コード例 #1
0
ファイル: remote-unwind.cpp プロジェクト: chunseoklee/coreclr
static bool 
ReadEncodedPointer(const libunwindInfo* info, unw_word_t* addr, unsigned char encoding, unw_word_t funcRel, unw_word_t* valp)
{
    unw_word_t initialAddr = *addr;
    uint16_t value16;
    uint32_t value32;
    uint64_t value64;
    unw_word_t value;

    if (encoding == DW_EH_PE_omit)
    {
        *valp = 0;
        return true;
    }
    else if (encoding == DW_EH_PE_aligned)
    {
        int size = sizeof(unw_word_t);
        *addr = (initialAddr + size - 1) & -size;
        return ReadPointer(info, addr, valp);
    }

    switch (encoding & DW_EH_PE_FORMAT_MASK)
    {
    case DW_EH_PE_ptr:
        if (!ReadPointer(info, addr, &value)) {
            return false;
        }
        break;

    case DW_EH_PE_uleb128:
        if (!ReadULEB128(info, addr, &value)) {
            return false;
        }
        break;

    case DW_EH_PE_sleb128:
        if (!ReadSLEB128(info, addr, &value)) {
            return false;
        }
        break;

    case DW_EH_PE_udata2:
        if (!ReadValue16(info, addr, &value16)) {
            return false;
        }
        value = value16;
        break;

    case DW_EH_PE_udata4:
        if (!ReadValue32(info, addr, &value32)) {
            return false;
        }
        value = value32;
        break;

    case DW_EH_PE_udata8:
        if (!ReadValue64(info, addr, &value64)) {
            return false;
        }
        value = value64;
        break;

    case DW_EH_PE_sdata2:
        if (!ReadValue16(info, addr, &value16)) {
            return false;
        }
        value = (int16_t)value16;
        break;

    case DW_EH_PE_sdata4:
        if (!ReadValue32(info, addr, &value32)) {
            return false;
        }
        value = (int32_t)value32;
        break;

    case DW_EH_PE_sdata8:
        if (!ReadValue64(info, addr, &value64)) {
            return false;
        }
        value = (int64_t)value64;
        break;

    default:
        ASSERT("ReadEncodedPointer: invalid encoding format %x\n", encoding);
        return false;
    }

    // 0 is a special value and always absolute
    if (value == 0) {
        *valp = 0;
        return true;
    }

    switch (encoding & DW_EH_PE_APPL_MASK)
    {
    case DW_EH_PE_absptr:
        break;

    case DW_EH_PE_pcrel:
        value += initialAddr;
        break;

    case DW_EH_PE_funcrel:
        _ASSERTE(funcRel != UINTPTR_MAX);
        value += funcRel;
        break;

    case DW_EH_PE_textrel:
    case DW_EH_PE_datarel:
    default:
        ASSERT("ReadEncodedPointer: invalid application type %x\n", encoding);
        return false;
    }

    if (encoding & DW_EH_PE_indirect)
    {
        unw_word_t indirect_addr = value;
        if (!ReadPointer(info, &indirect_addr, &value)) {
            return false;
        }
    }

    *valp = value;
    return true;
}
コード例 #2
0
ファイル: ConEmuCmd.cpp プロジェクト: AshWilliams/ConEmu
bool GetAliases(wchar_t* asExeName, wchar_t** rsAliases, LPDWORD rnAliasesSize)
{
	bool lbRc = false;
	DWORD nAliasRC, nAliasErr, nAliasAErr = 0, nSizeA = 0;
	_ASSERTE(asExeName && rsAliases && rnAliasesSize);
	_ASSERTE(*rsAliases == NULL);
	*rnAliasesSize = GetConsoleAliasesLength(asExeName);

	if (*rnAliasesSize == 0)
	{
		lbRc = true;
	}
	else
	{
		*rsAliases = (wchar_t*)calloc(*rnAliasesSize+2,1);
		nAliasRC = GetConsoleAliases(*rsAliases,*rnAliasesSize,asExeName);

		if (nAliasRC)
		{
			lbRc = true;
		}
		else
		{
			nAliasErr = GetLastError();

			if (nAliasErr == ERROR_NOT_ENOUGH_MEMORY)
			{
				// Попробовать ANSI функции
				UINT nCP = CP_OEMCP;
				char szExeName[MAX_PATH+1];
				char *pszAliases = NULL;
				WideCharToMultiByte(nCP,0,asExeName,-1,szExeName,MAX_PATH+1,0,0);
				nSizeA = GetConsoleAliasesLengthA(szExeName);

				if (nSizeA)
				{
					pszAliases = (char*)calloc(nSizeA+1,1);
					nAliasRC = GetConsoleAliasesA(pszAliases,nSizeA,szExeName);

					if (nAliasRC)
					{
						lbRc = true;
						MultiByteToWideChar(nCP,0,pszAliases,nSizeA,*rsAliases,((*rnAliasesSize)/2)+1);
					}
					else
					{
						nAliasAErr = GetLastError();
					}

					free(pszAliases);
				}
			}

			if (!nAliasRC)
			{
				if ((*rnAliasesSize) < 255) { free(*rsAliases); *rsAliases = (wchar_t*)calloc(128,2); }

				_wsprintf(*rsAliases, SKIPLEN(127) L"\nConEmuC: GetConsoleAliases failed, ErrCode=0x%08X(0x%08X), AliasesLength=%i(%i)\n\n", nAliasErr, nAliasAErr, *rnAliasesSize, nSizeA);
			}
		}
	}

	return lbRc;
}
コード例 #3
0
ファイル: plugcmn3.cpp プロジェクト: IDA-RE-things/idaplugs
bool has_meaningful_name(ea_t ea) {
	_ASSERTE(isEnabled(ea));
	char tmp[MAXNAMESIZE];
	return has_name(get_flags_novalue(ea)) && get_true_name(BADADDR, ea, CPY(tmp)) != 0
		&& !pcre_match("^unknown_libname_\\d+$", tmp);
}
コード例 #4
0
ファイル: test5.cpp プロジェクト: Hurleyworks/newton-dynamics
bool test5::Parce(lextest1& scanner)
{
	dList<dStackPair> stack;
	static short actionsCount[] = {2, 3, 3, 3, 2, 2, 3, 3, 2, 3};
	static short actionsStart[] = {0, 2, 5, 8, 0, 0, 11, 14, 0, 14};
	static dActionEntry actionTable[] = {
					dActionEntry (258, 0, 2, 0, 0), dActionEntry (266, 0, 3, 0, 0), 
					dActionEntry (0, 2, 0, 0, 0), dActionEntry (256, 0, 4, 0, 0), dActionEntry (257, 0, 5, 0, 0), 
					dActionEntry (0, 1, 0, 1, 5), dActionEntry (256, 1, 0, 1, 5), dActionEntry (257, 1, 0, 1, 5), 
					dActionEntry (0, 1, 0, 1, 4), dActionEntry (256, 1, 0, 1, 4), dActionEntry (257, 1, 0, 1, 4), 
					dActionEntry (0, 1, 0, 3, 2), dActionEntry (256, 0, 4, 0, 0), dActionEntry (257, 0, 8, 0, 0), 
					dActionEntry (0, 1, 0, 3, 3), dActionEntry (256, 0, 4, 0, 0), dActionEntry (257, 0, 5, 0, 0), 
			};

	static short gotoCount[] = {1, 0, 0, 0, 1, 1, 0, 0, 1, 0};
	static short gotoStart[] = {0, 1, 1, 1, 1, 2, 3, 3, 3, 4};
	static dGotoEntry gotoTable[] = {
					dGotoEntry (259, 1), dGotoEntry (259, 6), dGotoEntry (259, 7), dGotoEntry (259, 9), 
			};

	const int lastToken = 259;

	stack.Append ();
	dToken token = dToken (scanner.NextToken());
	for (;;) {
		const dStackPair& stackTop = stack.GetLast()->GetInfo();
		int start = actionsStart[stackTop.m_state];
		int count = actionsCount[stackTop.m_state];
		const dActionEntry* const action (FindAction (&actionTable[start], count, token));
		_ASSERTE (action);

		switch (action->m_stateType) 
		{
			case dSHIFT: 
			{
				dStackPair& entry = stack.Append()->GetInfo();
				entry.m_token = dToken (action->m_token);
				entry.m_state = action->m_nextState;
				entry.m_value = dStackPair::dUserVariable (entry.m_token, scanner.GetTokenString());
				token = dToken (scanner.NextToken());
				if (token == -1) {
					token = dToken (0);
				}

				break;
			}

			case dREDUCE: 
			{
				dStackPair parameter[MAX_USER_PARAM];

				int reduceCount = action->m_ruleSymbols;
				_ASSERTE (reduceCount < sizeof (parameter) / sizeof (parameter[0]));

				for (int i = 0; i < reduceCount; i ++) {
					parameter[reduceCount - i - 1] = stack.GetLast()->GetInfo();
					stack.Remove (stack.GetLast());
				}

				const dStackPair& stackTop = stack.GetLast()->GetInfo();
				int start = gotoStart[stackTop.m_state];
				int count = gotoCount[stackTop.m_state];
				const dGotoEntry* const gotoEntry = FindGoto (&gotoTable[start], count, dToken (action->m_nextState + lastToken));

				dStackPair& entry = stack.Append()->GetInfo();
				entry.m_state = gotoEntry->m_nextState;
				entry.m_token = dToken (gotoEntry->m_token);
				
				switch (action->m_ruleIndex) 
				{
					//do user semantic Actions
					case 5:// rule E : c 
						{}
						break;
					case 4:// rule E : { E } 
						{}
						break;
					case 2:// rule E : E sub E 
						{}
						break;
					case 3:// rule E : E sup E 
						{}
						break;

					default:;
				}

				break;

			}
	
			case dACCEPT: // 2 = accept
			{
				// program parced successfully, exit with successful code
				return true;
			}
			
			default:  
			{
				_ASSERTE (0);
				// syntact error parciing program
				//if (!ErrorHandler ("error")) {
				//}
				break;
			}
		}
	}
	return false;
}
コード例 #5
0
DWORD
CNdasEventMonitor::
OnTaskStart()
{
	
	BOOL bTerminateThread(FALSE);

	// 15 sec = 10,000,000 nanosec
	// negative value means relative time
	LARGE_INTEGER liDueTime;
	liDueTime.QuadPart = - 10 * 1000 * 1000;

	BOOL fSuccess = ::SetWaitableTimer(
		m_hHeartbeatMonitorTimer, 
		&liDueTime, 
		HEARTBEAT_MONITOR_INTERVAL, 
		NULL, 
		NULL, 
		FALSE);

	if (!fSuccess) {
		DPErrorEx(_FT("Setting waitable timer failed: "));
	}

	do {

		//
		// Lock against m_vLogDevice set change
		//
		this->Lock();

		DWORD dwLogDevices = m_vLogDevices.size();
		DWORD dwHandles = 3 + 2 * dwLogDevices;
		HANDLE* hWaitingHandles = new HANDLE[dwHandles];

		hWaitingHandles[0] = m_hTaskTerminateEvent;
		hWaitingHandles[1] = m_hLogDeviceSetChangeEvent;
		hWaitingHandles[2] = m_hHeartbeatMonitorTimer;

		PCNdasLogicalDeviceVector::const_iterator itr = m_vLogDevices.begin();
		for (DWORD i = 3; itr != m_vLogDevices.end(); ++itr, ++i) {
			PCNdasLogicalDevice pLogDevice = *itr;
			hWaitingHandles[i] = pLogDevice->GetDisconnectEvent();
			hWaitingHandles[dwLogDevices + i] = pLogDevice->GetAlarmEvent();
		}
		this->Unlock();

		BOOL fSuccess = ::ResetEvent(m_hLogDeviceSetChangeEvent);
		_ASSERTE(fSuccess);

		BOOL bResetLogDeviceSet(FALSE);

		do {

			DWORD dwWaitResult = ::WaitForMultipleObjects(
				dwHandles, 
				hWaitingHandles, 
				FALSE, 
				INFINITE);

			if (WAIT_OBJECT_0 == dwWaitResult) {
				//
				// Terminate Thread Event
				//
				bTerminateThread = TRUE;
			} else if (WAIT_OBJECT_0 + 1 == dwWaitResult) {
				//
				// LogicalDeviceSetChange Event
				//
				bResetLogDeviceSet = TRUE;
			} else if (WAIT_OBJECT_0 + 2 == dwWaitResult) {
				//
				// Heartbeat Monitor Timer Event
				//
				ximeta::CAutoLock autolock(this);
				PCNdasDeviceSet::const_iterator itr = m_hbMonDevices.begin();
				m_bIterating = TRUE;
				for (; itr != m_hbMonDevices.end();) {
					PCNdasDevice pDevice = *itr;
					BOOL bDetach = pDevice->OnStatusCheck();
					if (bDetach) {
						DPInfo(_FT("Detaching device %s from the monitor\n"),
							CNdasDeviceId(pDevice->GetDeviceId()).ToString());
						itr = m_hbMonDevices.erase(itr);
					} else {
						++itr;
					}
				}
				m_bIterating = FALSE;

			} else if (WAIT_OBJECT_0 + 3 <= dwWaitResult &&
				dwWaitResult < WAIT_OBJECT_0 + 3 + dwLogDevices)
			{
				//
				// Disconnect Event
				//
				DWORD n = dwWaitResult - (WAIT_OBJECT_0 + 3);
				PCNdasLogicalDevice pLogDevice = m_vLogDevices[n];

				DPInfo(_FT("Disconnect Event from slot %d: %s\n"),
					pLogDevice->GetSlot(), 
					pLogDevice->ToString());

				//
				// Publish event here
				//
				// TODO: Publish event here
				//
				CNdasInstanceManager* pInstMan = CNdasInstanceManager::Instance();
				_ASSERTE(NULL != pInstMan);

				CNdasEventPublisher* pEventPublisher = pInstMan->GetEventPublisher();
				_ASSERTE(NULL != pEventPublisher);

				NDAS_LOGICALDEVICE_ID logicalDeviceId = {0};
				logicalDeviceId.SlotNo = pLogDevice->GetSlot();
				logicalDeviceId.TargetId = 0;
				logicalDeviceId.LUN = 0;
				(void) pEventPublisher->LogicalDeviceDisconnected(logicalDeviceId);

				BOOL fSuccess = ::ResetEvent(pLogDevice->GetDisconnectEvent());
				_ASSERTE(fSuccess);

				//
				// Eject device
				//
				DPInfo(_FT("Ejecting disconnected logical device\n"));

				fSuccess = pLogDevice->Eject();
				if (!fSuccess) {
					DPErrorEx(_FT("Eject failed: "));
					DPError(_FT("Trying to unplug...\n"));
					fSuccess = pLogDevice->Unplug();
					if (!fSuccess) {
						DPErrorEx(_FT("Unplugging failed: "));
					}
				}

			} else if (WAIT_OBJECT_0 + 3 + dwLogDevices <= dwWaitResult &&
				dwWaitResult < WAIT_OBJECT_0 + 3 + 2 * dwLogDevices)
			{
				//
				// Alarm Event
				//
				DWORD n = dwWaitResult - (WAIT_OBJECT_0 + 3 + dwLogDevices);
				PCNdasLogicalDevice pLogDevice = m_vLogDevices[n];
				ULONG ulStatus;

				DPInfo(_FT("Alarm Event from slot %d: %s\n"),
					pLogDevice->GetSlot(),
					pLogDevice->ToString());

				LsBusCtlQueryAlarmStatus(pLogDevice->GetSlot(), &ulStatus);
				
				CNdasInstanceManager* pInstMan = CNdasInstanceManager::Instance();
				_ASSERTE(NULL != pInstMan);

				CNdasEventPublisher* pEventPublisher = pInstMan->GetEventPublisher();
				_ASSERTE(NULL != pEventPublisher);

				switch (ulStatus) {
				case ALARM_STATUS_NORMAL:
					{
						DPInfo(_FT("Alarm Normal\n"));
						NDAS_LOGICALDEVICE_ID logicalDeviceId = {0};
						logicalDeviceId.SlotNo = pLogDevice->GetSlot();
						logicalDeviceId.TargetId = 0;
						logicalDeviceId.LUN = 0;
						(void) pEventPublisher->
							LogicalDeviceReconnected(logicalDeviceId);
					}

					break;
				case ALARM_STATUS_START_RECONNECT:
					{
						DPInfo(_FT("Alarm Start Reconnect\n"));
						NDAS_LOGICALDEVICE_ID logicalDeviceId = {0};
						logicalDeviceId.SlotNo = pLogDevice->GetSlot();
						logicalDeviceId.TargetId = 0;
						logicalDeviceId.LUN = 0;
						(void) pEventPublisher->
							LogicalDeviceReconnecting(logicalDeviceId);
					}
					break;
				case ALARM_STATUS_FAIL_RECONNECT: // obsolete
					DPInfo(_FT("Alarm Failed Reconnecting\n"));
					break;
				default:
					DPWarning(_FT("Unknown alarm status: %d\n"), ulStatus);
				}

				//
				// TODO: Publish event here
				//

				BOOL fSuccess = ::ResetEvent(pLogDevice->GetAlarmEvent());
				_ASSERTE(fSuccess);

			} else {
				_ASSERTE(FALSE);
				DPErrorEx(_FT("Wait failed: "));
			}

		} while (!bResetLogDeviceSet && !bTerminateThread);

		delete [] hWaitingHandles;

	} while (!bTerminateThread);

	fSuccess = ::CancelWaitableTimer(m_hHeartbeatMonitorTimer);
	if (!fSuccess) {
		DPErrorEx(_FT("Canceling waitable timer failed: "));
	}

	return 0;
}
コード例 #6
0
ファイル: EditWrap.cpp プロジェクト: Maximus5/FarPlugins
void DoWrap(BOOL abWordWrap, EditorInfo &ei, int iMaxWidth)
{
	INT_PTR iRc = 0;
	INT_PTR cchMax = 0;
	TCHAR* pszCopy = NULL;
	TCHAR szEOL[4];
	INT_PTR iFrom, iTo, iEnd, iFind;
	bool bWasModifed = (ei.CurState & ECSTATE_MODIFIED) && !(ei.CurState & ECSTATE_SAVED);

	gbLastWrap = TRUE;
	
	for (INT_PTR i = 0; i < ei.TotalLines; i++)
	{
		//bool lbCurLine = (i == ei.CurLine);
		
		EditorGetString egs = {FARSTRUCTSIZE(egs)};
		egs.StringNumber = i;
		iRc = EditCtrl(ECTL_GETSTRING, &egs);
		if (!iRc)
		{
			_ASSERTE(iRc!=0);
			goto wrap;
		}
		_ASSERTE(egs.StringText!=NULL);
		
		if ((egs.StringLength <= iMaxWidth)
			&& ((egs.StringLength <= 0) || !(egs.StringText && wcschr(egs.StringText, L'\t'))))
		{
			// Эту строку резать не нужно
			continue;
		}
		
		lstrcpyn(szEOL, egs.StringEOL?egs.StringEOL:_T(""), ARRAYSIZE(szEOL));
		
		if (egs.StringLength >= cchMax || !pszCopy)
		{
			if (pszCopy)
				free(pszCopy);
			cchMax = egs.StringLength + 255;
			pszCopy = (TCHAR*)malloc(cchMax*sizeof(*pszCopy));
			if (!pszCopy)
			{
				_ASSERTE(pszCopy!=NULL);
				goto wrap;
			}
		}
		// Делаем копию, над которой можем издеваться
		memmove(pszCopy, egs.StringText, egs.StringLength*sizeof(*pszCopy));
		pszCopy[egs.StringLength] = 0; // на всякий случай, хотя вроде должен быть ASCIIZ
		
		bool lbFirst = 0;
		iFrom = 0; iEnd = egs.StringLength;
		while (iFrom < iEnd)
		{
			//iTo = min(iEnd,(iFrom+iMaxWidth));
			iTo = FindExceed(pszCopy, i, iFrom, min(iEnd/*+1*/,(iFrom+iMaxWidth)), iMaxWidth, ei.TabSize);
			iFind = iTo;
			if (iFind >= iEnd)
			{
				iFind = iTo = iEnd;
			}
			else if (abWordWrap
				/*&& (((egs.StringLength - iFrom) > iMaxWidth) || IsExceed(pszCopy, i, iFrom, iFind, iMaxWidth, ei.TabSize))*/
				)
			{
				while (iFind > iFrom)
				{
					if (IsSpaceOrNull(pszCopy[iFind-1]))
						break;
					//{
					//	// Если есть табы - нужно учитывать их ширину
					//	//TODO: Optimize, по хорошему, если есть табы, нужно оптимизировать расчет экранной позиции
					//	bool bExceed = IsExceed(pszCopy, i, iFrom, iFind, iMaxWidth, ei.TabSize);

					//	if (!bExceed)
					//		break;
					//}
					iFind--;
				}
				// Если по пробелам порезать не удалось, попробуем по другим знакам?
				if (iFind == iFrom)
				{
					iFind = iTo;
					while (iFind > iFrom)
					{
						if (_tcschr(gsPuctuators, pszCopy[iFind]) && !_tcschr(gsWordDiv, pszCopy[iFind-1]))
							break;
						//{
						//	// Если есть табы - нужно учитывать их ширину
						//	//TODO: Optimize, по хорошему, если есть табы, нужно оптимизировать расчет экранной позиции
						//	bool bExceed = IsExceed(pszCopy, i, iFrom, iFind, iMaxWidth, ei.TabSize);

						//	if (!bExceed)
						//		break;
						//}
						iFind--;
					}
					if (iFind == iFrom)
					{
						iFind = iTo;
						while (iFind > iFrom)
						{
							if (_tcschr(gsWordDiv, pszCopy[iFind]) && !_tcschr(gsWordDiv, pszCopy[iFind-1]))
								break;
							//{
							//	// Если есть табы - нужно учитывать их ширину
							//	//TODO: Optimize, по хорошему, если есть табы, нужно оптимизировать расчет экранной позиции
							//	bool bExceed = IsExceed(pszCopy, i, iFrom, iFind, iMaxWidth, ei.TabSize);

							//	if (!bExceed)
							//		break;
							//}
							iFind--;
						}
					}
				}
			}
			if (iFind == iFrom)
				iFind = iTo;

			if (iFind < iEnd)
			{
				// Для ECTL_INSERTSTRING нужно установить курсор
				EditorSetPosition eset = {FARSTRUCTSIZE(eset)};
				eset.CurLine = i;
				eset.TopScreenLine = -1;
				EditCtrl(ECTL_SETPOSITION, &eset);
				// Теперь можно разорвать строку
				EditCtrl(ECTL_INSERTSTRING, NULL);
				// Чтобы вернуть курсор на исходную строку
				if (i < ei.CurLine)
					ei.CurLine++;
			}
			// И менять ее данные
			EditorSetString esset = {FARSTRUCTSIZE(esset)};
			esset.StringNumber = i;
			esset.StringText = pszCopy+iFrom;
			esset.StringEOL = (iFind == iEnd) ? szEOL : _T("");
			esset.StringLength = (iFind - iFrom);
			EditCtrl(ECTL_SETSTRING, &esset);

			// Накрутить счетчики
			if (iFind < iEnd)
			{
				i++; ei.TotalLines++; // т.к. вставили строку
			}
			
			// Следующая часть строки
			iFrom = iFind;
		}
	}

	// Обновить позицию курсора
	{
		EditorSetPosition eset = {FARSTRUCTSIZE(eset)};
		eset.CurLine = ei.CurLine;
		eset.TopScreenLine = -1;
		EditCtrl(ECTL_SETPOSITION, &eset);
	}
	
wrap:
	if (pszCopy)
		free(pszCopy);

#ifdef _UNICODE
	// Сброс флага "редактирован"
	//TODO: bis-сборка?
	if (!bWasModifed)
		EditCtrl(ECTL_DROPMODIFEDFLAG, NULL);
#endif
}
コード例 #7
0
ファイル: trnsctrl.cpp プロジェクト: chunhualiu/OpenNT
void *CallCatchBlock(
    EHExceptionRecord  *pExcept,
    EHRegistrationNode *pRN,            // Dynamic info of function with catch
    void 			   *pContext,                     // ignored
    DispatcherContext  *pDC,        // Context within subject frame
	FuncInfo           *pFuncInfo,      // Static info of function with catch
    void               *handlerAddress, // Code address of handler
    int                 CatchDepth,     // How deeply nested in catch blocks are we?
	unsigned int       *pSp 
)
{
	FRAMEINFO frameinfo;
	PFRAMEINFO pframeinfo;
    EHExceptionRecord  *pExceptTmp;
	unsigned char *pRetAddr;
										   
	_CreateFrameInfo(&frameinfo, pDC, pContext);

	frameinfo.pExitContext = (void *)GetSP();
	if (pDC->pftinfo == _pftinfo)
		{
		// okay we are throw and catch in the same code fragment
		_pftinfo->pFrameInfo = _pFrameInfoChain;
		}
	else
		{
		// we are not throw and catch in the same code fragment
		// we need to chain the _pFrameInfoChain after the pDC->pftinof->pFrameInfo
		// we should have got all the Frames saved so far, no matter how many code fragments we have been through
		if (pDC->pftinfo->pFrameInfo != NULL)
			{
			// not chain if the case where CRT Is a DLL for everyone
			if ( pDC->pftinfo->pFrameInfo != _pFrameInfoChain->pNext)
				{
				_pFrameInfoChain->pNext = (PFRAMEINFO)(pDC->pftinfo->pFrameInfo); 
				}
			}
		}

	//call the handler
	pRetAddr = (unsigned char *)_CallSettingFrame(handlerAddress, pRN);

	*pSp = (unsigned int)GetR4();

	//destructing the object
	if (pExcept && (*(unsigned int *)pExcept != 0xffffffff))
		{
		DestructExceptionObject(pExcept, TRUE, pContext); 
		}

	if (_pFrameInfoChain)
		{

        // don't forget to clear out the frame info the handler we are about 
        // to remove since most if not all off them are stack elements

        _ASSERTE(_pFrameInfoChain->pftinfo != NULL);
        _ASSERTE(_pFrameInfoChain->pftinfo->pFrameInfo != NULL);
        pframeinfo = (PFRAMEINFO)_pFrameInfoChain->pftinfo->pFrameInfo;
        if (pframeinfo)
            _pFrameInfoChain->pftinfo->pFrameInfo = pframeinfo->pNext;

		_pFrameInfoChain = _pFrameInfoChain->pNext;        //remove current handler from the chain
		cNested--;
		_pftinfo->pFrameInfo = _pFrameInfoChain;
		}

	pframeinfo = _pFrameInfoChain;
	pExceptTmp = pExcept;
	while (pframeinfo && (pframeinfo->pSp <= (PPMSTACK)pRN))
		{
		// we should destruct any exception objects before this handler's frame
        if ((EHExceptionRecord *)(pframeinfo->pExcept) != pExceptTmp)
            {
            // this is not a re-throw, do destroy
            DestructExceptionObject((EHExceptionRecord *)pframeinfo->pExcept, TRUE, (void *)pframeinfo->dwRTOC);
			pExceptTmp = (EHExceptionRecord *)(pframeinfo->pExcept);
			*(unsigned int *)(pframeinfo->pExcept) = 0xffffffff;     
			pframeinfo->pExcept = NULL;     //???
            }
		pframeinfo = pframeinfo->pNext;
        _pFrameInfoChain = pframeinfo;   //remove handler frame from the list
		cNested--;
		_pftinfo->pFrameInfo = _pFrameInfoChain;
		}

	return (void *)pRetAddr;
}
コード例 #8
0
ファイル: context.cpp プロジェクト: nietras/coreclr
/*++
Function:
  SetThreadContextOnPort

  Helper for CONTEXT_SetThreadContext
--*/
kern_return_t
CONTEXT_SetThreadContextOnPort(
           mach_port_t Port,
           IN CONST CONTEXT *lpContext)
{
    kern_return_t MachRet = KERN_SUCCESS;
    mach_msg_type_number_t StateCount;
    thread_state_flavor_t StateFlavor;

    if (lpContext->ContextFlags & (CONTEXT_CONTROL|CONTEXT_INTEGER)) 
    {
#ifdef _X86_
        x86_thread_state32_t State;
        StateFlavor = x86_THREAD_STATE32;
        
        State.eax = lpContext->Eax;
        State.ebx = lpContext->Ebx;
        State.ecx = lpContext->Ecx;
        State.edx = lpContext->Edx;
        State.edi = lpContext->Edi;
        State.esi = lpContext->Esi;
        State.ebp = lpContext->Ebp;
        State.esp = lpContext->Esp;
        State.ss = lpContext->SegSs;
        State.eflags = lpContext->EFlags;
        State.eip = lpContext->Eip;
        State.cs = lpContext->SegCs;
        State.ds = lpContext->SegDs_PAL_Undefined;
        State.es = lpContext->SegEs_PAL_Undefined;
        State.fs = lpContext->SegFs_PAL_Undefined;
        State.gs = lpContext->SegGs_PAL_Undefined;
#elif defined(_AMD64_)
        x86_thread_state64_t State;
        StateFlavor = x86_THREAD_STATE64;

        State.__rax = lpContext->Rax;
        State.__rbx = lpContext->Rbx;
        State.__rcx = lpContext->Rcx;
        State.__rdx = lpContext->Rdx;
        State.__rdi = lpContext->Rdi;
        State.__rsi = lpContext->Rsi;
        State.__rbp = lpContext->Rbp;
        State.__rsp = lpContext->Rsp;
        State.__r8 = lpContext->R8;
        State.__r9 = lpContext->R9;
        State.__r10 = lpContext->R10;
        State.__r11 = lpContext->R11;
        State.__r12 = lpContext->R12;
        State.__r13 = lpContext->R13;
        State.__r14 = lpContext->R14;
        State.__r15 = lpContext->R15;
//        State.ss = lpContext->SegSs;
        State.__rflags = lpContext->EFlags;
        State.__rip = lpContext->Rip;
        State.__cs = lpContext->SegCs;
//        State.ds = lpContext->SegDs_PAL_Undefined;
//        State.es = lpContext->SegEs_PAL_Undefined;
        State.__fs = lpContext->SegFs;
        State.__gs = lpContext->SegGs;
#else
#error Unexpected architecture.
#endif

        StateCount = sizeof(State) / sizeof(natural_t);

        MachRet = thread_set_state(Port,
                                   StateFlavor,
                                   (thread_state_t)&State,
                                   StateCount);
        if (MachRet != KERN_SUCCESS)
        {
            ASSERT("thread_set_state(THREAD_STATE) failed: %d\n", MachRet);
            goto EXIT;
        }
    }

    if (lpContext->ContextFlags & CONTEXT_ALL_FLOATING)
    {
        
#ifdef _X86_
        x86_float_state32_t State;
        StateFlavor = x86_FLOAT_STATE32;
#elif defined(_AMD64_)
        x86_float_state64_t State;
        StateFlavor = x86_FLOAT_STATE64;
#else
#error Unexpected architecture.
#endif

        StateCount = sizeof(State) / sizeof(natural_t);

        // If we're setting only one of the floating point or extended registers (of which Mach supports only
        // the xmm values) then we don't have values for the other set. This is a problem since Mach only
        // supports setting both groups as a single unit. So in this case we'll need to fetch the current
        // values first.
        if ((lpContext->ContextFlags & CONTEXT_ALL_FLOATING) !=
            CONTEXT_ALL_FLOATING)
        {
            mach_msg_type_number_t StateCountGet = StateCount;
            MachRet = thread_get_state(Port,
                                       StateFlavor,
                                       (thread_state_t)&State,
                                       &StateCountGet);
            if (MachRet != KERN_SUCCESS)
            {
                ASSERT("thread_get_state(FLOAT_STATE) failed: %d\n", MachRet);
                goto EXIT;
            }
            _ASSERTE(StateCountGet == StateCount);
        }

        if (lpContext->ContextFlags & CONTEXT_FLOATING_POINT)
        {
#ifdef _X86_
            *(DWORD*)&State.fpu_fcw = lpContext->FloatSave.ControlWord;
            *(DWORD*)&State.fpu_fsw = lpContext->FloatSave.StatusWord;
            State.fpu_ftw = lpContext->FloatSave.TagWord;
            State.fpu_ip = lpContext->FloatSave.ErrorOffset;
            State.fpu_cs = lpContext->FloatSave.ErrorSelector;
            State.fpu_dp = lpContext->FloatSave.DataOffset;
            State.fpu_ds = lpContext->FloatSave.DataSelector;
            State.fpu_mxcsr = lpContext->FloatSave.Cr0NpxState;

            // Windows stores the floating point registers in a packed layout (each 10-byte register end to
            // end for a total of 80 bytes). But Mach returns each register in an 16-bit structure (presumably
            // for alignment purposes). So we can't just memcpy the registers over in a single block, we need
            // to copy them individually.
            for (int i = 0; i < 8; i++)
                memcpy((&State.fpu_stmm0)[i].mmst_reg, &lpContext->FloatSave.RegisterArea[i * 10], 10);
#elif defined(_AMD64_)
            *(DWORD*)&State.__fpu_fcw = lpContext->FltSave.ControlWord;
            *(DWORD*)&State.__fpu_fsw = lpContext->FltSave.StatusWord;
            State.__fpu_ftw = lpContext->FltSave.TagWord;
            State.__fpu_ip = lpContext->FltSave.ErrorOffset;
            State.__fpu_cs = lpContext->FltSave.ErrorSelector;
            State.__fpu_dp = lpContext->FltSave.DataOffset;
            State.__fpu_ds = lpContext->FltSave.DataSelector;
            State.__fpu_mxcsr = lpContext->FltSave.MxCsr;
            State.__fpu_mxcsrmask = lpContext->FltSave.MxCsr_Mask; // note: we don't save the mask for x86

            // Windows stores the floating point registers in a packed layout (each 10-byte register end to
            // end for a total of 80 bytes). But Mach returns each register in an 16-bit structure (presumably
            // for alignment purposes). So we can't just memcpy the registers over in a single block, we need
            // to copy them individually.
            for (int i = 0; i < 8; i++)
                memcpy((&State.__fpu_stmm0)[i].__mmst_reg, &lpContext->FltSave.FloatRegisters[i], 10);

            memcpy(&State.__fpu_xmm0, &lpContext->Xmm0, 8 * 16);
#else
#error Unexpected architecture.
#endif
        }

#ifdef _X86_
        if (lpContext->ContextFlags & CONTEXT_EXTENDED_REGISTERS)
        {
            // The only extended register information that Mach will tell us about are the xmm register
            // values. Both Windows and Mach store the registers in a packed layout (each of the 8 registers
            // is 16 bytes) so we can simply memcpy them across.
            memcpy(&State.fpu_xmm0, lpContext->ExtendedRegisters + CONTEXT_EXREG_XMM_OFFSET, 8 * 16);
        }
#endif // _X86_

        MachRet = thread_set_state(Port,
                                   StateFlavor,
                                   (thread_state_t)&State,
                                   StateCount);
        if (MachRet != KERN_SUCCESS)
        {
            ASSERT("thread_set_state(FLOAT_STATE) failed: %d\n", MachRet);
            goto EXIT;
        }
    }    

EXIT:
    return MachRet;
}
コード例 #9
0
ファイル: context.cpp プロジェクト: nietras/coreclr
/*++
Function :
    CONTEXTToNativeContext
    
    Converts a CONTEXT record to a native context.

Parameters :
    CONST CONTEXT *lpContext : CONTEXT to convert
    native_context_t *native : native context to fill in

Return value :
    None

--*/
void CONTEXTToNativeContext(CONST CONTEXT *lpContext, native_context_t *native)
{
#define ASSIGN_REG(reg) MCREG_##reg(native->uc_mcontext) = lpContext->reg;
    if ((lpContext->ContextFlags & CONTEXT_CONTROL) == CONTEXT_CONTROL)
    {
        ASSIGN_CONTROL_REGS
    }

    if ((lpContext->ContextFlags & CONTEXT_INTEGER) == CONTEXT_INTEGER)
    {
        ASSIGN_INTEGER_REGS
    }
#undef ASSIGN_REG

#if HAVE_GREGSET_T || HAVE_GREGSET_T
#if HAVE_GREGSET_T
    if (native->uc_mcontext.fpregs == nullptr)
#elif HAVE___GREGSET_T
    if (native->uc_mcontext.__fpregs == nullptr)
#endif
    {
        // If the pointer to the floating point state in the native context
        // is not valid, we can't copy floating point registers regardless of
        // whether CONTEXT_FLOATING_POINT is set in the CONTEXT's flags.
        return;
    }
#endif

    if ((lpContext->ContextFlags & CONTEXT_FLOATING_POINT) == CONTEXT_FLOATING_POINT)
    {
#ifdef _AMD64_
        FPREG_ControlWord(native) = lpContext->FltSave.ControlWord;
        FPREG_StatusWord(native) = lpContext->FltSave.StatusWord;
        FPREG_TagWord(native) = lpContext->FltSave.TagWord;
        FPREG_ErrorOffset(native) = lpContext->FltSave.ErrorOffset;
        FPREG_ErrorSelector(native) = lpContext->FltSave.ErrorSelector;
        FPREG_DataOffset(native) = lpContext->FltSave.DataOffset;
        FPREG_DataSelector(native) = lpContext->FltSave.DataSelector;
        FPREG_MxCsr(native) = lpContext->FltSave.MxCsr;
        FPREG_MxCsr_Mask(native) = lpContext->FltSave.MxCsr_Mask;

        for (int i = 0; i < 8; i++)
        {
            FPREG_St(native, i) = lpContext->FltSave.FloatRegisters[i];
        }

        for (int i = 0; i < 16; i++)
        {
            FPREG_Xmm(native, i) = lpContext->FltSave.XmmRegisters[i];
        }
#endif
    }

    // TODO: Enable for all Unix systems
#if defined(_AMD64_) && defined(XSTATE_SUPPORTED)
    if ((lpContext->ContextFlags & CONTEXT_XSTATE) == CONTEXT_XSTATE)
    {
        _ASSERTE(FPREG_HasExtendedState(native));
        memcpy_s(FPREG_Xstate_Ymmh(native), sizeof(M128A) * 16, lpContext->VectorRegister, sizeof(M128A) * 16);
    }
#endif //_AMD64_ && XSTATE_SUPPORTED
}
コード例 #10
0
ファイル: bob_dbg.cpp プロジェクト: somma/bob_dbg
/// @brief
int main()
{
    // create process with /dbg
    STARTUPINFO			si = {0};
	PROCESS_INFORMATION pi = {0};
    wchar_t* target = L".\\debuggee.exe";

	if (TRUE != CreateProcessW(
					target, 
					NULL, 
					NULL, 
					NULL, 
					FALSE, 
					CREATE_NEW_CONSOLE | DEBUG_PROCESS,
					NULL, 
					NULL, 
					&si, 
					&pi))
	{
        log("CreateProcess() failed. gle = %u", GetLastError());
		return -1;
	}

    log("process created. pid = %u", pi.dwProcessId);

	CloseHandle(pi.hThread);
	CloseHandle(pi.hProcess);

    DEBUG_EVENT debug_event = {0};	
	while (true)
	{
		if (TRUE != WaitForDebugEvent(&debug_event, 100)) continue;
        
        DWORD continue_status = DBG_CONTINUE;

		switch (debug_event.dwDebugEventCode)
        {
        case EXCEPTION_DEBUG_EVENT:
            {
                PDEBUGGEE dbge = NULL;
                for (int i = 0; i < sizeof(_debuggees) / sizeof(DEBUGGEE); ++i)
                {
                    if (_debuggees[i]._pid == debug_event.dwProcessId)
                    {
                        dbge = &_debuggees[i];
                    }
                }
                if (NULL == dbge) break;
                
                LPEXCEPTION_DEBUG_INFO edi = &debug_event.u.Exception;
                switch (edi->ExceptionRecord.ExceptionCode)
                {
                case EXCEPTION_BREAKPOINT:
                    if (true != dbge->_initial_bp_hit)
                    {
                        dbge->_initial_bp_hit = true;
                        log(
                            "\n"
                            "[EXCEPTION_DEBUG_EVENT] \n"\
                            "   img = %ws \n"\
                            "   pid = %u, tid = %u \n"\
                            "   + initial bp triggered at 0x%llx",
                            dbge->_image_name.c_str(),
                            debug_event.dwProcessId,
                            debug_event.dwThreadId,
                            edi->ExceptionRecord.ExceptionAddress);

                        // 
                        // install breakpoint at ep.
                        //

                        dbge->_bp_param = { 0 };
                        HANDLE thread_handle = OpenThread(THREAD_ALL_ACCESS, FALSE, debug_event.dwThreadId);
                        if (NULL == thread_handle)
                        {
                            _ASSERTE(!"oops");
                            break;
                        }

                        dbge->_bp_param.hthread = thread_handle;
                        dbge->_bp_param.hproc = dbge->_proc_handle;
                        dbge->_bp_addr = dbge->_start_address;
                        bool bp_ret = set_break_point(
                            &dbge->_bp_param,
                            (DWORD_PTR)dbge->_bp_addr,
                            &dbge->_opcode);
                        if (true != bp_ret)
                        {
                            _ASSERTE(true == bp_ret);
                            break;
                        }

                        continue_status = DBG_EXCEPTION_HANDLED;
                        log("   + break point installed at 0x%llx", dbge->_bp_addr);
                        _pause;
                    }
                    else
                    {
                        log(
                            "\n"
                            "[EXCEPTION_DEBUG_EVENT] \n"\
                            "   img = %ws \n"\
                            "   pid = %u, tid = %u \n"\
                            "   + break point at 0x%llx",
                            dbge->_image_name.c_str(),
                            debug_event.dwProcessId,
                            debug_event.dwThreadId,
                            edi->ExceptionRecord.ExceptionAddress);

                        // 
                        // restore opcode and resume
                        //
                        if (edi->ExceptionRecord.ExceptionAddress != dbge->_bp_addr)
                        {
                            _ASSERTE(!"oops");
                            break;
                        }

                        dbge->_bp_param.context.ContextFlags = CONTEXT_ALL;
                        if (TRUE != GetThreadContext(
                            dbge->_bp_param.hthread,
                            &dbge->_bp_param.context))
                        {
                            _ASSERTE(!"oops!");
                            break;
                        }
                        if (true != clear_break_point(
                            &dbge->_bp_param,
                            (DWORD_PTR)dbge->_bp_addr,
                            dbge->_opcode, true))
                        {
                            _ASSERTE(!"oops");
                            break;
                        }

                        continue_status = DBG_EXCEPTION_HANDLED;
                        log("   + breakpoint un-installed at 0x%llx", dbge->_bp_addr);

                        // single step enable
                        ch_param param = { 0 };
                        param.hthread = OpenThread(THREAD_ALL_ACCESS, FALSE, debug_event.dwThreadId);
                        if (NULL != param.hthread)
                        {
                            param.context.ContextFlags = CONTEXT_ALL;
                            if (TRUE != GetThreadContext(param.hthread, &param.context))
                            {
                                _ASSERTE(!"oops!");
                                break;
                            }
                            set_single_step(&param);
                        }
                        _pause;
                    }
                    break;

                case EXCEPTION_SINGLE_STEP:
                    {
                    //log(
                    //    "\n"
                    //    "[EXCEPTION_DEBUG_EVENT] \n"\
                    //    "   pid = %u, tid = %u\n"\
                    //    "   + handle single step at 0x%llx", 
                    //    debug_event.dwProcessId,
                    //    debug_event.dwThreadId, 
                    //    edi->ExceptionRecord.ExceptionAddress);

                    
                    // call 명령이라면 log
                    log_branch(edi->ExceptionRecord.ExceptionAddress,
                               debug_event.dwProcessId,
                               debug_event.dwThreadId);

                    //continue_status = DBG_EXCEPTION_NOT_HANDLED;
                    continue_status = DBG_EXCEPTION_HANDLED;
                    break;
                    }
                default:
                    if (0 != edi->dwFirstChance)
                    {   
                        log("\n"
                            "[EXCEPTION_DEBUG_EVENT]\n"\
                            "   pid = %u, tid = %u\n"\
                            "   + %s (first chance) at 0x%llx",
                            debug_event.dwProcessId,
                            debug_event.dwThreadId, 
                            exception_code_str(edi->ExceptionRecord.ExceptionCode),
                            edi->ExceptionRecord.ExceptionAddress
                            );
                    }
                    else
                    {
                        log("\n"
                            "[EXCEPTION_DEBUG_EVENT]\n"\
                            "   + %s (second chance) at 0x%llx, can't handle anymore.",
                            exception_code_str(edi->ExceptionRecord.ExceptionCode),
                            edi->ExceptionRecord.ExceptionAddress
                            );
                    }

                    continue_status = DBG_EXCEPTION_NOT_HANDLED;
                    break;
                }
                break;
            }
        case CREATE_THREAD_DEBUG_EVENT:
            {
                //str = "CREATE_THREAD_DEBUG_EVENT";
                break;
            }
        case CREATE_PROCESS_DEBUG_EVENT:
            {
                LPCREATE_PROCESS_DEBUG_INFO cpi = &debug_event.u.CreateProcessInfo;
                std::wstring image;
                if (true != get_filepath_by_handle(cpi->hFile, image))
                {
                    image = L"unknown image path";
                }
                
                log("\n"\
                    "[CREATE_PROCESS_DEBUG_EVENT]\n"\
                    "   img = %ws\n"\
                    "   pid = %u, tid = %u, ep = 0x%llx",
                    image.c_str(), 
                    debug_event.dwProcessId,
                    debug_event.dwThreadId,
                    cpi->lpStartAddress
                    );
                
                for (int i = 0; i < sizeof(_debuggees) / sizeof(DEBUGGEE); ++i)
                {
                    if (_debuggees[i]._pid == 0)
                    {
                        _debuggees[i]._initial_bp_hit = 0;
                        _debuggees[i]._pid = debug_event.dwProcessId;

                        _debuggees[i]._file_handle = debug_event.u.CreateProcessInfo.hFile;
                        _debuggees[i]._proc_handle = debug_event.u.CreateProcessInfo.hProcess;
                        _debuggees[i]._thread_handle = debug_event.u.CreateProcessInfo.hThread;
                        _debuggees[i]._base_of_image = debug_event.u.CreateProcessInfo.lpBaseOfImage;
                        _debuggees[i]._thread_local_base = debug_event.u.CreateProcessInfo.lpThreadLocalBase;
                        _debuggees[i]._start_address = debug_event.u.CreateProcessInfo.lpStartAddress;
                        _debuggees[i]._image_name = image;

                        break;
                    }
                }
                break;
            }
        case EXIT_THREAD_DEBUG_EVENT:
            {
                //str = "EXIT_THREAD_DEBUG_EVENT";
                break;
            }
        //case EXIT_PROCESS_DEBUG_EVENT:
        //    {
        //        str = "EXIT_PROCESS_DEBUG_EVENT";
        //        break;
        //    }
        case LOAD_DLL_DEBUG_EVENT:
            {
                LPLOAD_DLL_DEBUG_INFO lddi = &debug_event.u.LoadDll;
                std::wstring dll_path;
                if (true != get_filepath_by_handle(lddi->hFile, dll_path))
                {
                    dll_path = L"Unknown dll path";
                }

                // get dll file size
                if (0 != k32_base)  break;

                HANDLE hFile = CreateFileW(dll_path.c_str(),
                                           GENERIC_READ,
                                           FILE_SHARE_READ,
                                           NULL,
                                           OPEN_ALWAYS,
                                           FILE_ATTRIBUTE_NORMAL,
                                           NULL);
                if (NULL == hFile) break;


                LARGE_INTEGER file_size = { 0 };
                if (TRUE != GetFileSizeEx(lddi->hFile, &file_size))
                {
                    return false;
                }

                if (std::wstring::npos != dll_path.rfind(L"ntdll.dll"))
                {
                    log("\n"
                        "gotcha!\n"\
                        "   pid = %u, tid = %u, img = %ws, addr ragne = 0x%08x ~ 0x%08x",
                        debug_event.dwProcessId,
                        debug_event.dwThreadId,
                        dll_path.c_str(),
                        lddi->lpBaseOfDll,
                        (DWORD_PTR)lddi->lpBaseOfDll + file_size.LowPart
                        );

                    k32_base = (DWORD_PTR)lddi->lpBaseOfDll;
                    k32_max = (DWORD_PTR)lddi->lpBaseOfDll + file_size.LowPart;

                }
                
                //log("\n"
                //    "[LOAD_DLL_DEBUG_EVENT]\n"\
                //    "   pid = %u, tid = %u, img = %ws",
                //    debug_event.dwProcessId,
                //    debug_event.dwThreadId,
                //    dll_path.c_str()
                //    );
                break;
            }
        case UNLOAD_DLL_DEBUG_EVENT:
            {
                LPUNLOAD_DLL_DEBUG_INFO uddi = &debug_event.u.UnloadDll;
                // todo 3
                break;
            }
        case OUTPUT_DEBUG_STRING_EVENT:
            {
                
                break;
            }
        case RIP_EVENT:
            {
                //str = "RIP_EVENT";
                break;
            }
        default:
            //str = "unknown";
            break;
        }

        


		//> continue_status 값이
		//>
		//>	DBG_CONTINUE
		//>		EXCEPTION_DEBUG_EVENT 인 경우
		//>			모든 exception processing 을 멈추고 스레드를 계속 실행
		//>		EXCEPTION_DEBUG_EVENT 이 아닌 경우 
		//>			스레드 계속 실행 
		//>
		//>	DBG_EXCEPTION_NOT_HANDLED
		//>		EXCEPTION_DEBUG_EVENT 인 경우
		//>			exception processing 을 계속 진행.
		//>			first-chance exception 인 경우 seh 핸들러의 search, dispatch 로직이 실행
		//>			first-chance exception 이 아니라면 프로세스는 종료 됨
		//>		EXCEPTION_DEBUG_EVENT 이 아닌 경우 
		//>			스레드 계속 실행 
        ContinueDebugEvent(debug_event.dwProcessId,debug_event.dwThreadId,continue_status);

		//> debuggee is terminating
		if (EXIT_PROCESS_DEBUG_EVENT == debug_event.dwDebugEventCode)
		{
            int i = 0;
            for (; i < sizeof(_debuggees) / sizeof(DEBUGGEE); ++i)
            {
                if (_debuggees[i]._pid == debug_event.dwProcessId)
                {
                    _debuggees[i]._initial_bp_hit = 0;
                    _debuggees[i]._pid = 0;
                    break;
                }
            }

            if (i == 0)
            {
                log("\n"\
                    "[EXIT_PROCESS_DEBUG_EVENT] \n"\
                    "   img = %ws\n"\
                    "   pid = %u, tid = %u\n"\
                    "   + debuggee is terminated.",
                    _debuggees[i]._image_name.c_str(),
                    debug_event.dwProcessId, debug_event.dwThreadId);
                _pause;
                break;
            }
            // do nothing...
		}
	}

    //log("press any key to terminate...");
    //getchar();

}
コード例 #11
0
ファイル: bob_dbg.cpp プロジェクト: somma/bob_dbg
/**
 * @brief	file_handle 로 file path 를 구하는 함수
 * @param	
 * @see		http://msdn.microsoft.com/en-us/library/windows/desktop/aa366789(v=vs.85).aspx
 * @remarks	NtQueryObject() 를 사용하는게 더 좋을 것 같기도 함, 권한 문제가 발생 할 수도 있을것 같으나
 * @remarks 확인해본적 없음
 * @code		
 * @endcode	
 * @return	
**/
bool
get_filepath_by_handle(
	_In_ HANDLE file_handle, 
	_Out_ std::wstring& file_path
	)
{
	_ASSERTE(NULL != file_handle);
	_ASSERTE(INVALID_HANDLE_VALUE != file_handle);	
	if (NULL == file_handle || INVALID_HANDLE_VALUE == file_handle) return false;
	
	LARGE_INTEGER file_size = {0};
	if (TRUE != GetFileSizeEx(file_handle, &file_size))
	{
		return false;
	}

	if (0 == file_size.QuadPart)
	{
		return false;
	}
	
    bool succeeded = false;
    HANDLE hcfm = NULL;
    LPVOID mvo = NULL;

    do
    {
        hcfm = CreateFileMapping(file_handle, NULL, PAGE_READONLY, 0, 1, NULL);
	    if (NULL == hcfm)
	    {
            break;
	    }

        mvo = MapViewOfFile(hcfm, FILE_MAP_READ, 0, 0, 1);
	    if (NULL == mvo)
	    {   
            break;
	    }

	    std::wstring nt_device_name;
	    if (true != get_mapped_file_name(
					    GetCurrentProcess(), 
					    mvo, 
					    nt_device_name))
	    {
            break;
	    }

	    /*if (true != nt_name_to_dos_name(nt_device_name.c_str(), file_path))
	    {
		    log_err "nt_name_to_dos_name( nt name = %s )", nt_device_name.c_str() log_end
		    return false;
	    }*/
        file_path = nt_device_name.c_str();
        succeeded = true;
    } while (false);
    
    if (NULL != hcfm) CloseHandle(hcfm);
    if (NULL != mvo) UnmapViewOfFile(mvo);
    return succeeded;
}
コード例 #12
0
void* QCALLTYPE SynchronizationContextNative::GetWinRTDispatcherForCurrentThread()
{
    QCALL_CONTRACT;
    void* result = NULL;
    BEGIN_QCALL;

    _ASSERTE(WinRTSupported());

    //
    // Get access to ICoreWindow's statics.  We grab just one ICoreWindowStatic for the whole process.
    //
    ABI::Windows::UI::Core::ICoreWindowStatic* pICoreWindowStatic = g_pICoreWindowStatic;
    if (pICoreWindowStatic == NULL)
    {
        SafeComHolderPreemp<ABI::Windows::UI::Core::ICoreWindowStatic> pNewICoreWindowStatic;
        {
            HRESULT hr = clr::winrt::GetActivationFactory(RuntimeClass_Windows_UI_Core_CoreWindow, (ABI::Windows::UI::Core::ICoreWindowStatic**)pNewICoreWindowStatic.GetAddr());

            //
            // Older Windows builds don't support ICoreWindowStatic.  We should just return a null CoreDispatcher 
            // in that case, rather than throwing.
            //
            if (hr != E_NOTIMPL)
                IfFailThrow(hr);
        }

        if (pNewICoreWindowStatic != NULL)
        {
            ABI::Windows::UI::Core::ICoreWindowStatic* old = InterlockedCompareExchangeT<ABI::Windows::UI::Core::ICoreWindowStatic*>(&g_pICoreWindowStatic, pNewICoreWindowStatic, NULL);
            if (old == NULL)
            {
                pNewICoreWindowStatic.SuppressRelease();
                pICoreWindowStatic = pNewICoreWindowStatic;
            }
            else
            {
                pICoreWindowStatic = old;
            }
        }
    }


    if (pICoreWindowStatic != NULL)
    {
        //
        // Get the current ICoreWindow
        //
        SafeComHolderPreemp<ABI::Windows::UI::Core::ICoreWindow> pCoreWindow;

        //
        // workaround: we're currently ignoring the HRESULT from get_Current, because Windows is returning errors for threads that have no CoreWindow.
        // A better behavior would be to return S_OK, with a NULL CoreWindow.  If/when Windows does the right thing here, we can change this
        // back to checking the HRESULT.
        //
        pICoreWindowStatic->GetForCurrentThread(&pCoreWindow);

        if (pCoreWindow != NULL)
        {
            //
            // Get the ICoreDispatcher for this window
            //
            SafeComHolderPreemp<ABI::Windows::UI::Core::ICoreDispatcher> pCoreDispatcher;
            IfFailThrow(pCoreWindow->get_Dispatcher(&pCoreDispatcher));

            if (pCoreDispatcher != NULL)
            {
                //
                // Does the dispatcher belong to the current thread?
                //
                boolean hasThreadAccess = FALSE;
                IfFailThrow(pCoreDispatcher->get_HasThreadAccess(&hasThreadAccess));
                if (hasThreadAccess)
                {
                    //
                    // This is the dispatcher for the current thread.  Return it.
                    //
                    pCoreDispatcher.SuppressRelease();
                    result = (void*)pCoreDispatcher;
                }
            }
        }
    }

    END_QCALL;
    return result;
}
コード例 #13
0
ファイル: ConEmuTh2800.cpp プロジェクト: alexlav/conemu
BOOL LoadPanelInfoW2800(BOOL abActive)
{
	if (!InfoW2800) return FALSE;

	CeFullPanelInfo* pcefpi = NULL;
	PanelInfo pi = {sizeof(pi)};
	HANDLE hPanel = abActive ? PANEL_ACTIVE : PANEL_PASSIVE;
	INT_PTR nRc = InfoW2800->PanelControl(hPanel, FCTL_GETPANELINFO, 0, &pi);

	if (!nRc)
	{
		TODO("Показать информацию об ошибке");
		return FALSE;
	}

	// Даже если невидима - обновить информацию!
	//// Проверим, что панель видима. Иначе - сразу выходим.
	//if (!pi.Visible) {
	//	TODO("Показать информацию об ошибке");
	//	return NULL;
	//}

	if (pi.Flags & PFLAGS_PANELLEFT)
		pcefpi = &pviLeft;
	else
		pcefpi = &pviRight;

	pcefpi->cbSize = sizeof(*pcefpi);
	//pcefpi->hPanel = hPanel;

	// Если элементов на панели стало больше, чем выделено в (pviLeft/pviRight)
	if (pcefpi->ItemsNumber < (INT_PTR)pi.ItemsNumber)
	{
		if (!pcefpi->ReallocItems(pi.ItemsNumber))
			return FALSE;
	}

	// Копируем что нужно
	pcefpi->bLeftPanel = (pi.Flags & PFLAGS_PANELLEFT) == PFLAGS_PANELLEFT;
	pcefpi->bPlugin = (pi.Flags & PFLAGS_PLUGIN) == PFLAGS_PLUGIN;
	pcefpi->PanelRect = pi.PanelRect;
	pcefpi->ItemsNumber = pi.ItemsNumber;
	pcefpi->CurrentItem = pi.CurrentItem;
	pcefpi->TopPanelItem = pi.TopPanelItem;
	pcefpi->Visible = (pi.PanelType == PTYPE_FILEPANEL) && ((pi.Flags & PFLAGS_VISIBLE) == PFLAGS_VISIBLE);
	pcefpi->ShortNames = (pi.Flags & PFLAGS_ALTERNATIVENAMES) == PFLAGS_ALTERNATIVENAMES;
	pcefpi->Focus = (pi.Flags & PFLAGS_FOCUS) == PFLAGS_FOCUS;
	pcefpi->Flags = pi.Flags; // CEPANELINFOFLAGS
	pcefpi->PanelMode = pi.ViewMode;
	pcefpi->IsFilePanel = (pi.PanelType == PTYPE_FILEPANEL);
	// Настройки интерфейса
	LoadFarSettingsW2800(&pcefpi->FarInterfaceSettings, &pcefpi->FarPanelSettings);

	// Цвета фара
	INT_PTR nColorSize = InfoW2800->AdvControl(&guid_ConEmuTh, ACTL_GETARRAYCOLOR, 0, NULL);
#ifdef _DEBUG
	INT_PTR nDefColorSize = COL_LASTPALETTECOLOR;
	_ASSERTE(nColorSize==nDefColorSize);
#endif
	FarColor* pColors = (FarColor*)calloc(nColorSize, sizeof(*pColors));
	if (pColors)
		nColorSize = InfoW2800->AdvControl(&guid_ConEmuTh, ACTL_GETARRAYCOLOR, (int)nColorSize, pColors);
	WARNING("Поддержка более 4бит цветов");
	if (pColors && nColorSize > 0)
	{
		pcefpi->nFarColors[col_PanelText] = FarColor_3_2(pColors[COL_PANELTEXT]);
		pcefpi->nFarColors[col_PanelSelectedCursor] = FarColor_3_2(pColors[COL_PANELSELECTEDCURSOR]);
		pcefpi->nFarColors[col_PanelSelectedText] = FarColor_3_2(pColors[COL_PANELSELECTEDTEXT]);
		pcefpi->nFarColors[col_PanelCursor] = FarColor_3_2(pColors[COL_PANELCURSOR]);
		pcefpi->nFarColors[col_PanelColumnTitle] = FarColor_3_2(pColors[COL_PANELCOLUMNTITLE]);
		pcefpi->nFarColors[col_PanelBox] = FarColor_3_2(pColors[COL_PANELBOX]);
		pcefpi->nFarColors[col_HMenuText] = FarColor_3_2(pColors[COL_HMENUTEXT]);
		pcefpi->nFarColors[col_WarnDialogBox] = FarColor_3_2(pColors[COL_WARNDIALOGBOX]);
		pcefpi->nFarColors[col_DialogBox] = FarColor_3_2(pColors[COL_DIALOGBOX]);
		pcefpi->nFarColors[col_CommandLineUserScreen] = FarColor_3_2(pColors[COL_COMMANDLINEUSERSCREEN]);
		pcefpi->nFarColors[col_PanelScreensNumber] = FarColor_3_2(pColors[COL_PANELSCREENSNUMBER]);
		pcefpi->nFarColors[col_KeyBarNum] = FarColor_3_2(pColors[COL_KEYBARNUM]);
	}
	else
	{
		_ASSERTE(pColors!=NULL && nColorSize>0);
		memset(pcefpi->nFarColors, 7, countof(pcefpi->nFarColors)*sizeof(*pcefpi->nFarColors));
	}
	SafeFree(pColors);
	//int nColorSize = InfoW2800->AdvControl(&guid_ConEmuTh, ACTL_GETARRAYCOLOR, 0, NULL);
	//if ((pcefpi->nFarColors == NULL) || (nColorSize > pcefpi->nMaxFarColors))
	//{
	//	if (pcefpi->nFarColors) free(pcefpi->nFarColors);
	//	pcefpi->nFarColors = (BYTE*)calloc(nColorSize,1);
	//	pcefpi->nMaxFarColors = nColorSize;
	//}
	////nColorSize = InfoW2800->AdvControl(&guid_ConEmuTh, ACTL_GETARRAYCOLOR, 0, pcefpi->nFarColors);
	//FarColor* pColors = (FarColor*)calloc(nColorSize, sizeof(*pColors));
	//
	//if (pColors)
	//	nColorSize = InfoW2800->AdvControl(&guid_ConEmuTh, ACTL_GETARRAYCOLOR, nColorSize, pColors);
	//
	//WARNING("Поддержка более 4бит цветов");
	//if (pColors && nColorSize > 0)
	//{
	//	for (int i = 0; i < nColorSize; i++)
	//		pcefpi->nFarColors[i] = FarColor_3_2(pColors[i]);
	//}
	//else
	//{
	//	memset(pcefpi->nFarColors, 7, pcefpi->nMaxFarColors*sizeof(*pcefpi->nFarColors));
	//}
	//SafeFree(pColors);
	
	// Текущая папка панели
	size_t nSize = InfoW2800->PanelControl(hPanel, FCTL_GETPANELDIRECTORY, 0, 0);

	if (nSize)
	{
		if ((pcefpi->pFarPanelDirectory == NULL) || (nSize > pcefpi->nMaxPanelGetDir))
		{
			pcefpi->nMaxPanelGetDir = nSize + 1024; // + выделим немножко заранее
			pcefpi->pFarPanelDirectory = calloc(pcefpi->nMaxPanelGetDir,1);
		}
		((FarPanelDirectory*)pcefpi->pFarPanelDirectory)->StructSize = sizeof(FarPanelDirectory);
		nSize = InfoW2800->PanelControl(hPanel, FCTL_GETPANELDIRECTORY, nSize, pcefpi->pFarPanelDirectory);

		if ((pcefpi->pszPanelDir == NULL) || (nSize > pcefpi->nMaxPanelDir))
		{
			pcefpi->nMaxPanelDir = nSize + MAX_PATH; // + выделим немножко заранее
			SafeFree(pcefpi->pszPanelDir);
			pcefpi->pszPanelDir = (wchar_t*)calloc(pcefpi->nMaxPanelDir,2);
		}
		lstrcpyn(pcefpi->pszPanelDir, ((FarPanelDirectory*)pcefpi->pFarPanelDirectory)->Name, pcefpi->nMaxPanelDir);

		if (!nSize)
		{
			SafeFree(pcefpi->pszPanelDir);
			pcefpi->nMaxPanelDir = 0;
		}
	}
	else
	{
		SafeFree(pcefpi->pszPanelDir);
	}

	// Готовим буфер для информации об элементах
	pcefpi->ReallocItems(pcefpi->ItemsNumber);

	// и буфер для загрузки элемента из FAR
	nSize = sizeof(PluginPanelItem)+6*MAX_PATH;

	if ((pcefpi->pFarTmpBuf == NULL) || (pcefpi->nFarTmpBuf < nSize))
	{
		if (pcefpi->pFarTmpBuf) free(pcefpi->pFarTmpBuf);

		pcefpi->nFarTmpBuf = nSize;
		pcefpi->pFarTmpBuf = malloc(pcefpi->nFarTmpBuf);
	}

	return TRUE;
}
コード例 #14
0
ファイル: remote-unwind.cpp プロジェクト: chunseoklee/coreclr
static int 
find_proc_info(unw_addr_space_t as, unw_word_t ip, unw_proc_info_t *pip, int need_unwind_info, void *arg)
{
    const auto *info = (libunwindInfo*)arg;
    memset(pip, 0, sizeof(*pip));

    Ehdr ehdr;
    if (!info->ReadMemory((void*)info->BaseAddress, &ehdr, sizeof(ehdr))) {
        ERROR("ELF: reading ehdr %p\n", info->BaseAddress);
        return -UNW_EINVAL;
    }
    Phdr* phdrAddr = reinterpret_cast<Phdr*>(info->BaseAddress + ehdr.e_phoff);
    int phnum = ehdr.e_phnum;
    TRACE("ELF: base %p ip %p e_type %d e_phnum %d e_phoff %p\n", info->BaseAddress, ip, ehdr.e_type, ehdr.e_phnum, ehdr.e_phoff);

    // The eh_frame header
    Phdr ehPhdr;
    memset(&ehPhdr, 0, sizeof(ehPhdr));

    // Search for the module's dynamic header and unwind frames
    Dyn* dynamicAddr = nullptr;

    for (int i = 0; i < phnum; i++, phdrAddr++)
    {
        Phdr ph;
        if (!info->ReadMemory(phdrAddr, &ph, sizeof(ph))) {
            ERROR("ELF: reading phdrAddr %p\n", phdrAddr);
            return -UNW_EINVAL;
        }
        TRACE("ELF: phdr %p type %d (%x) vaddr %p memsz %016llx paddr %p filesz %016llx offset %p align %016llx\n",
            phdrAddr, ph.p_type, ph.p_type, ph.p_vaddr, ph.p_memsz, ph.p_paddr, ph.p_filesz, ph.p_offset, ph.p_align);

        switch (ph.p_type)
        {
        case PT_DYNAMIC:
            if (ehdr.e_type == ET_EXEC) {
                dynamicAddr = reinterpret_cast<Dyn*>(ph.p_vaddr);
            }
            if (ehdr.e_type == ET_DYN) {
                dynamicAddr = reinterpret_cast<Dyn*>(ph.p_vaddr + info->BaseAddress);
            }
            break;

        case PT_GNU_EH_FRAME:
            ehPhdr = ph;
            break;
        }
    }

    if (dynamicAddr != nullptr)
    {
        for (;;)
        {
            Dyn dyn;
            if (!info->ReadMemory(dynamicAddr, &dyn, sizeof(dyn))) {
                ERROR("ELF: reading dynamicAddr %p\n", dynamicAddr);
                return -UNW_EINVAL;
            }
            if (dyn.d_tag == DT_PLTGOT) {
                TRACE("ELF: dyn %p tag %d (%x) d_ptr %p\n", dynamicAddr, dyn.d_tag, dyn.d_tag, dyn.d_un.d_ptr);
                pip->gp = dyn.d_un.d_ptr;
                break;
            }
            else if (dyn.d_tag == DT_NULL) {
                break;
            }
            dynamicAddr++;
        }
    }
    unw_word_t ehFrameHdrAddr = ehPhdr.p_offset + info->BaseAddress;
    eh_frame_hdr ehFrameHdr;

    if (!info->ReadMemory((PVOID)ehFrameHdrAddr, &ehFrameHdr, sizeof(eh_frame_hdr))) {
        ERROR("ELF: reading ehFrameHdrAddr %p\n", ehFrameHdrAddr);
        return -UNW_EINVAL;
    }
    TRACE("ehFrameHdrAddr %p version %d eh_frame_ptr_enc %d fde_count_enc %d table_enc %d\n", 
        ehFrameHdrAddr, ehFrameHdr.version, ehFrameHdr.eh_frame_ptr_enc, ehFrameHdr.fde_count_enc, ehFrameHdr.table_enc);

    if (ehFrameHdr.version != DW_EH_VERSION) {
        ASSERT("ehFrameHdr version %x not supported\n", ehFrameHdr.version);
        return -UNW_EBADVERSION;
    }
    unw_word_t addr = ehFrameHdrAddr + sizeof(eh_frame_hdr);
    unw_word_t ehFrameStart;
    unw_word_t fdeCount;

    // Decode the eh_frame_hdr info
    if (!ReadEncodedPointer(info, &addr, ehFrameHdr.eh_frame_ptr_enc, UINTPTR_MAX, &ehFrameStart)) {
        ERROR("decoding eh_frame_ptr\n");
        return -UNW_EINVAL;
    }
    if (!ReadEncodedPointer(info, &addr, ehFrameHdr.fde_count_enc, UINTPTR_MAX, &fdeCount)) {
        ERROR("decoding fde_count_enc\n");
        return -UNW_EINVAL;
    }
    TRACE("ehFrameStart %p fdeCount %p ip offset %08x\n", ehFrameStart, fdeCount, (int32_t)(ip - ehFrameHdrAddr));

    // LookupTableEntry assumes this encoding
    if (ehFrameHdr.table_enc != (DW_EH_PE_datarel | DW_EH_PE_sdata4)) {
        ASSERT("Table encoding not supported %x\n", ehFrameHdr.table_enc);
        return -UNW_EINVAL;
    }
    // Find the fde using a binary search on the frame table
    table_entry entry;
    bool found;
    if (!LookupTableEntry(info, ip - ehFrameHdrAddr, addr, fdeCount, &entry, &found)) {
        ERROR("LookupTableEntry\n");
        return -UNW_EINVAL;
    }
    unw_word_t fdeAddr = entry.fde_offset + ehFrameHdrAddr;
    TRACE("start_ip %08x fde_offset %08x fdeAddr %p found %d\n", entry.start_ip, entry.fde_offset, fdeAddr, found);

    // Unwind info not found
    if (!found) {
        return -UNW_ENOINFO;
    }

    // Now get the unwind info
    if (!ExtractProcInfoFromFde(info, &fdeAddr, pip, need_unwind_info)) {
        ERROR("ExtractProcInfoFromFde\n");
        return -UNW_EINVAL;
    }

    _ASSERTE(ip >= pip->start_ip && ip <= pip->end_ip);
    return UNW_ESUCCESS;
}
コード例 #15
0
void dgCollisionScene::ImproveNodeFitness (dgNode* const node)
{
	_ASSERTE (node->m_left);
	_ASSERTE (node->m_right);

	if (node->m_parent)	{
		if (node->m_parent->m_left == node) {
			dgFloat32 cost0 = node->m_surfaceArea;

			dgVector cost1P0;
			dgVector cost1P1;		
			dgFloat32 cost1 = CalculateSurfaceArea (node->m_right, node->m_parent->m_right, cost1P0, cost1P1);

			dgVector cost2P0;
			dgVector cost2P1;		
			dgFloat32 cost2 = CalculateSurfaceArea (node->m_left, node->m_parent->m_right, cost2P0, cost2P1);

			if ((cost1 <= cost0) && (cost1 <= cost2)) {
				dgNode* const parent = node->m_parent;
				node->m_minBox = parent->m_minBox;
				node->m_maxBox = parent->m_maxBox;
				node->m_surfaceArea = parent->m_surfaceArea; 
				if (parent->m_parent) {
					if (parent->m_parent->m_left == parent) {
						parent->m_parent->m_left = node;
					} else {
						_ASSERTE (parent->m_parent->m_right == parent);
						parent->m_parent->m_right = node;
					}
				} else {
					m_rootNode = node;
				}
				node->m_parent = parent->m_parent;
				parent->m_parent = node;
				node->m_right->m_parent = parent;
				parent->m_left = node->m_right;
				node->m_right = parent;
				parent->m_minBox = cost1P0;
				parent->m_maxBox = cost1P1;		
				parent->m_surfaceArea = cost1;


			} else if ((cost2 <= cost0) && (cost2 <= cost1)) {
				dgNode* const parent = node->m_parent;
				node->m_minBox = parent->m_minBox;
				node->m_maxBox = parent->m_maxBox;
				node->m_surfaceArea = parent->m_surfaceArea; 

				if (parent->m_parent) {
					if (parent->m_parent->m_left == parent) {
						parent->m_parent->m_left = node;
					} else {
						_ASSERTE (parent->m_parent->m_right == parent);
						parent->m_parent->m_right = node;
					}
				} else {
					m_rootNode = node;
				}
				node->m_parent = parent->m_parent;
				parent->m_parent = node;
				node->m_left->m_parent = parent;
				parent->m_left = node->m_left;
				node->m_left = parent;

				parent->m_minBox = cost2P0;
				parent->m_maxBox = cost2P1;		
				parent->m_surfaceArea = cost2;
			}
		} else {
			dgFloat32 cost0 = node->m_surfaceArea;

			dgVector cost1P0;
			dgVector cost1P1;		
			dgFloat32 cost1 = CalculateSurfaceArea (node->m_left, node->m_parent->m_left, cost1P0, cost1P1);

			dgVector cost2P0;
			dgVector cost2P1;		
			dgFloat32 cost2 = CalculateSurfaceArea (node->m_right, node->m_parent->m_left, cost2P0, cost2P1);


			if ((cost1 <= cost0) && (cost1 <= cost2)) {

				dgNode* const parent = node->m_parent;
				node->m_minBox = parent->m_minBox;
				node->m_maxBox = parent->m_maxBox;
				node->m_surfaceArea = parent->m_surfaceArea; 
				if (parent->m_parent) {
					if (parent->m_parent->m_left == parent) {
						parent->m_parent->m_left = node;
					} else {
						_ASSERTE (parent->m_parent->m_right == parent);
						parent->m_parent->m_right = node;
					}
				} else {
					m_rootNode = node;
				}
				node->m_parent = parent->m_parent;
				parent->m_parent = node;
				node->m_left->m_parent = parent;
				parent->m_right = node->m_left;
				node->m_left = parent;

				parent->m_minBox = cost1P0;
				parent->m_maxBox = cost1P1;		
				parent->m_surfaceArea = cost1;

			} else if ((cost2 <= cost0) && (cost2 <= cost1)) {
				dgNode* const parent = node->m_parent;
				node->m_minBox = parent->m_minBox;
				node->m_maxBox = parent->m_maxBox;
				node->m_surfaceArea = parent->m_surfaceArea; 
				if (parent->m_parent) {
					if (parent->m_parent->m_left == parent) {
						parent->m_parent->m_left = node;
					} else {
						_ASSERTE (parent->m_parent->m_right == parent);
						parent->m_parent->m_right = node;
					}
				} else {
					m_rootNode = node;
				}
				node->m_parent = parent->m_parent;
				parent->m_parent = node;
				node->m_right->m_parent = parent;
				parent->m_right = node->m_right;
				node->m_right = parent;

				parent->m_minBox = cost2P0;
				parent->m_maxBox = cost2P1;		
				parent->m_surfaceArea = cost2;
			}
		}
	}

	_ASSERTE (!m_rootNode->m_parent);
}
コード例 #16
0
HRESULT CLR_RT_XmlState_InValue::ProcessOthersInvalidChar( CLR_RT_XmlState* st, CLR_UINT8*& buffer, bool& isDone )
{
    _ASSERTE(isDone == true);
    
    return XML_E_INVALID_CHARACTER;
}
コード例 #17
0
//*****************************************************************************
//* Function Name: LookupErrorCode
//*   Description: Call ::FormatMessage() to lookup an error code in each DLL
//*                in the given array of DLL names. ::FormatMessage() looks up
//*                the error code in the MESSAGETABLE resource that is bound
//*                into each DLL.
//*****************************************************************************
static bool LookupErrorCode (
	DWORD	p_dwErrorCode,
	LPCTSTR	p_rglpszDLLs[],
	UINT	p_uNumDLLs,
	LPTSTR	p_lpszBuffer,
	UINT	p_cchBuffer)
{
	_ASSERTE (p_lpszBuffer != NULL);
	_ASSERTE (p_cchBuffer > 0);

	bool l_bResult = false;

	p_lpszBuffer[0] = _T('\0');

	for (UINT l_uIndex = 0; l_uIndex < p_uNumDLLs; ++l_uIndex) {

		bool l_bNeedToUnloadModule = false;

		LPCTSTR l_lpszDLL = p_rglpszDLLs[l_uIndex];
		HMODULE l_hModule = ::GetModuleHandle (l_lpszDLL);

		if (l_hModule == NULL) {
			l_hModule = ::LoadLibraryEx (l_lpszDLL, NULL, LOAD_LIBRARY_AS_DATAFILE);
			if (l_hModule == NULL) {
				continue;
			}
			l_bNeedToUnloadModule = true;
		}

		DWORD l_dwFlags = FORMAT_MESSAGE_FROM_HMODULE |
						  FORMAT_MESSAGE_IGNORE_INSERTS;

		DWORD l_dwLanguageId = MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT);

		int l_cch = ::FormatMessage (	l_dwFlags,		// dwFlags
										l_hModule,		// lpSource
										p_dwErrorCode,	// dwMessageId
										l_dwLanguageId,	// dwLanguageId
										p_lpszBuffer,	// lpBuffer
										p_cchBuffer,	// nSize,
										NULL);			// Arguments

		if (l_cch > 0) {

			// Remove any trailing linebreak (\r\n) that may be present.
			if (l_cch >= 2) {
				if (p_lpszBuffer[l_cch - 2] == _T('\r') &&
					p_lpszBuffer[l_cch - 1] == _T('\n'))
				{
					p_lpszBuffer[l_cch - 2] = _T('\0');
				}
			}

			l_bResult = true;
		}

		if (l_bNeedToUnloadModule) {
			::FreeLibrary (l_hModule);
			l_hModule = NULL;
		}

		if (l_bResult) {
			break;
		}
	}

	return l_bResult;
}
コード例 #18
0
ファイル: KG3DSelector.cpp プロジェクト: 1suming/pap2
HRESULT KG3DSelector::OnRender()
{
	HRESULT hRetCode = E_FAIL;
	HRESULT hResult = E_FAIL;
	D3DLOCKED_RECT Rect;
	LPDIRECT3DSURFACE9 pResultColor = NULL;
	LPDIRECT3DSURFACE9 pStencilRT = NULL;
	D3DVIEWPORT9 vp;
	D3DVIEWPORT9 vpNew;
	KG3DRenderState RenderState;
	DWORD dwSelectIndex = 0xff;
	g_pd3dDevice->GetViewport(&vp);
		
	vpNew = vp;
	vpNew.X /= m_nScale;
	vpNew.Y /= m_nScale;
	vpNew.Width /= m_nScale;
	vpNew.Height /= m_nScale;
	
	m_dwIndex = 0;//Stencil Index清零
	KG_PROCESS_SUCCESS(!m_vecModels.size());
		
	hResult = g_pd3dDevice->GetRenderTarget(0, &m_pRTSave);
	KG_COM_PROCESS_ERROR(hResult);

	hResult = g_pd3dDevice->GetDepthStencilSurface(&m_pDepthSave);
	KG_COM_PROCESS_ERROR(hResult);

	hResult = m_pStencilRT->GetSurfaceLevel(0, &pStencilRT);
	KG_COM_PROCESS_ERROR(hResult);

	hResult = g_pd3dDevice->SetRenderTarget(0, pStencilRT);
	KG_COM_PROCESS_ERROR(hResult);

	hResult = g_pd3dDevice->SetDepthStencilSurface(m_pStencilDepth);
	KG_COM_PROCESS_ERROR(hResult);

	hResult = g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0xffffffff, 1.0f, 1L);
	KG_COM_PROCESS_ERROR(hResult);
	
	g_pd3dDevice->SetViewport(&vpNew);

	RenderModelList();
	
	if (0)
	{
		D3DXSaveTextureToFile("d:\\test.tga", D3DXIFF_TGA, m_pStencilRT, NULL);
	}

	hResult = g_pd3dDevice->SetTexture(0, m_pStencilRT);
	KG_COM_PROCESS_ERROR(hResult);

	g_pd3dDevice->SetTexture(1, NULL);

	hResult = g_pd3dDevice->SetDepthStencilSurface(NULL);
	KG_COM_PROCESS_ERROR(hResult);

	hResult = g_pd3dDevice->SetRenderTarget(0, m_pRT);
	KG_COM_PROCESS_ERROR(hResult);
	
	RenderState.SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);

	float fU = float(m_MousePoint.x) / m_nWidth ;
	float fV = float(m_MousePoint.y) / m_nHeight;

	ScreenRect[0].vec2UV = D3DXVECTOR2(fU, fV);
	ScreenRect[1].vec2UV = D3DXVECTOR2(fU, fV);
	ScreenRect[2].vec2UV = D3DXVECTOR2(fU, fV);
	ScreenRect[3].vec2UV = D3DXVECTOR2(fU, fV);

	hResult = g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET, 0xffffffff, 1.0f, 1L);
	KG_COM_PROCESS_ERROR(hResult);

	hResult = g_pd3dDevice->SetFVF(SelectorVertex::dwFVF);
	KG_COM_PROCESS_ERROR(hResult);

	RenderState.SetRenderState(D3DRS_FOGENABLE, FALSE);
	RenderState.SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_POINT);
	RenderState.SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_POINT);
	RenderState.SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
	RenderState.SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);

	hResult = g_pd3dDevice->DrawPrimitiveUP(D3DPT_TRIANGLEFAN, 2, ScreenRect, sizeof(SelectorVertex));
	KG_COM_PROCESS_ERROR(hResult);

	hResult = m_pResult->GetSurfaceLevel(0, &pResultColor);
	KG_COM_PROCESS_ERROR(hResult);

	hResult = g_pd3dDevice->GetRenderTargetData(m_pRT, pResultColor);
	KG_COM_PROCESS_ERROR(hResult);

	hResult = pResultColor->LockRect(&Rect, NULL, 0);
	KG_COM_PROCESS_ERROR(hResult);

	BYTE *pBit = (BYTE*)Rect.pBits;
	dwSelectIndex = *(pBit + 2);

	pResultColor->UnlockRect();
	KG_COM_PROCESS_ERROR(hResult);

	if (dwSelectIndex != 0xff)
	{
		_ASSERTE(dwSelectIndex < m_vecModels.size());
		m_pSelectedModel = m_vecModels[dwSelectIndex];
	}
	else
	{
		//模糊选择, 在所有的模型都没有精确选中的时候, 选中离镜头最近的那一个
		D3DXVECTOR3 vec3CamPos;
		float fNear = 9999999999.f;
		DWORD dwNear = 0xffffffff;
		g_cGraphicsTool.GetCamera()->GetPosition(&vec3CamPos);
		for (size_t i = 0; i < m_vecModels.size(); i++)
		{
			D3DXVECTOR3 vec3Length = vec3CamPos - D3DXVECTOR3(m_vecModels[i]->m_matWorld._41, 
				m_vecModels[i]->m_matWorld._42, 
				m_vecModels[i]->m_matWorld._43);
			
			float fLength = vec3Length.x * vec3Length.x + vec3Length.y * vec3Length.y + vec3Length.z * vec3Length.z;
			if (fLength < fNear)
			{
				fNear = fLength;
				dwNear = static_cast<DWORD>(i);
			}
		}
		m_pSelectedModel = m_vecModels[dwNear];
	}

	m_bSelected = TRUE;

Exit1:
	hRetCode = S_OK;
Exit0:
	
	if (!m_bSelected)
	{
		m_pSelectedModel = NULL;
	}
		
	m_vecModels.clear();
	SAFE_RELEASE(pStencilRT);
	SAFE_RELEASE(pResultColor);
	if (m_pRTSave)
	{
		g_pd3dDevice->SetRenderTarget(0, m_pRTSave);
	}
	if (m_pDepthSave)
	{
		g_pd3dDevice->SetDepthStencilSurface(m_pDepthSave);
		g_pd3dDevice->SetViewport(&vp);
	}
	
	SAFE_RELEASE(pResultColor);
	SAFE_RELEASE(m_pRTSave);
	SAFE_RELEASE(m_pDepthSave);
	return hRetCode;
}
コード例 #19
0
ファイル: EditWrap.cpp プロジェクト: Maximus5/FarPlugins
void DoUnwrap(EditorInfo &ei)
{
	INT_PTR iRc = 0;
	INT_PTR cchMax = 0, cchPos = 0;
	TCHAR* pszCopy = NULL;
	TCHAR szEOL[4];
	bool bWasModifed = (ei.CurState & ECSTATE_MODIFIED) && !(ei.CurState & ECSTATE_SAVED);

	gbLastWrap = FALSE;
	
	for (INT_PTR i = 0; i < ei.TotalLines; i++)
	{
		EditorGetString egs = {FARSTRUCTSIZE(egs)};
		egs.StringNumber = i;
		iRc = EditCtrl(ECTL_GETSTRING, &egs);
		if (!iRc)
		{
			_ASSERTE(iRc!=0);
			goto wrap;
		}
		_ASSERTE(egs.StringText!=NULL);
		
		if (egs.StringEOL && *egs.StringEOL)
		{
			// В этой строке есть EOL, ее не сворачивали
			continue;
		}
		
		cchPos = 0;
		szEOL[0] = 0;
		INT_PTR j = i;
		while (j < ei.TotalLines)
		{
			if (!pszCopy || ((egs.StringLength + cchPos + 65536) > cchMax))
			{
				cchMax = egs.StringLength + cchPos + 65536;
				TCHAR* pszNew = (TCHAR*)malloc(cchMax*sizeof(*pszCopy));
				if (!pszNew)
				{
					_ASSERTE(pszNew!=NULL);
					goto wrap;
				}
				if (pszCopy)
				{
					if (cchPos > 0)
						memmove(pszNew, pszCopy, cchPos*sizeof(*pszCopy));
					free(pszCopy);
				}
				pszCopy = pszNew;
			}
			
			if (egs.StringLength > 0)
			{
				memmove(pszCopy+cchPos, egs.StringText, egs.StringLength*sizeof(*pszCopy));
				cchPos += egs.StringLength;
			}

			bool lbApplyAndBreak = false;

			if (*szEOL)
			{
				lbApplyAndBreak = true;
			}

			// Получить следующую строку
			if ((j+1) >= ei.TotalLines)
			{
				lbApplyAndBreak = true;
			}
			else if (!lbApplyAndBreak)
			{
				egs.StringNumber = ++j;
				iRc = EditCtrl(ECTL_GETSTRING, &egs);
				if (!iRc)
				{
					_ASSERTE(iRc!=0);
					goto wrap;
				}
				_ASSERTE(egs.StringText!=NULL);
				if (egs.StringEOL && *egs.StringEOL)
				{
					// В этой строке есть EOL, ее не сворачивали
					lstrcpyn(szEOL, egs.StringEOL?egs.StringEOL:_T(""), ARRAYSIZE(szEOL));
				}
			}
			
			if (lbApplyAndBreak)
			{
				EditorSetString esset = {FARSTRUCTSIZE(esset)};
				esset.StringNumber = i;
				esset.StringText = pszCopy;
				esset.StringEOL = szEOL;
				esset.StringLength = cchPos;
				EditCtrl(ECTL_SETSTRING, &esset);
				
				for (INT_PTR k = i+1; k <= j; k++)
				{
					// Для ECTL_DELETESTRING нужно установить курсор
					EditorSetPosition eset = {FARSTRUCTSIZE(eset)};
					eset.CurLine = i+1;
					eset.TopScreenLine = -1;
					iRc = EditCtrl(ECTL_SETPOSITION, &eset);
					_ASSERTE(iRc);
					// Удаляем "свернутое"
					iRc = EditCtrl(ECTL_DELETESTRING, NULL);
					_ASSERTE(iRc);
					ei.TotalLines--;
					if (ei.CurLine > i)
						ei.CurLine--;
				}
				
				// Выход из while
				break;
			}
		}
	}
	
	// Обновить позицию курсора
	{
		EditorSetPosition eset = {FARSTRUCTSIZE(eset)};
		eset.CurLine = ei.CurLine;
		eset.TopScreenLine = -1;
		EditCtrl(ECTL_SETPOSITION, &eset);
	}
	
wrap:
	if (pszCopy)
		free(pszCopy);

#ifdef _UNICODE
	// Сброс флага "редактирован"
	//TODO: bis-сборка?
	if (!bWasModifed)
		EditCtrl(ECTL_DROPMODIFEDFLAG, NULL);
#endif
}
コード例 #20
0
dgFloat32 dgCollisionScene::GetVolume () const
{
	_ASSERTE (0);
	return dgFloat32 (0.0f);
}
コード例 #21
0
ファイル: trnsctrl.cpp プロジェクト: chunhualiu/OpenNT
//PowerMac version of stack walking to find a C++ exception handler
//Assume:
//		_pftinfo
//
void MacExceptionDispatch(PEXCEPTION_RECORD pExceptionRecord)
{
	PPMSTACK spCur;				    
	PPMSTACK spCurCatch;				    
	DispatcherContext curDC;
	PRUNTIME_FUNCTION pFunctionEntry;
	PRUNTIME_FUNCTION pFunctionEntryCatch = NULL;
	PFTINFO pftinfoTOC;
	PPMSTACK pFrame;
	unsigned long cNestedTmp;
	PFRAMEINFO pframeinfo;
	
 	spCur = (PMSTACK *)GetSP();

	//Loop through the frames backwards on the stack to find a frame which has an EH handler
	//Assume:
	//      End of Stack: when the save area link register is NULL
	//      .pdata has Exception Handler points to CxxFrameHandler if an EH Frame
	//				   Exception Data points to FuncInfo
	spCur = spCur->pSpBackChain; //this should be in CxxThrowException frame
	spCur = spCur->pSpBackChain; //this should be in caller of CxxThrowException frame

	//Is this a cross TOC call? Do we need to switch RTOC???!!!
	if ( (spCur->dwLNKreg >= _pftinfo->dwEntryCF) && (spCur->dwLNKreg <= ((unsigned long)((char *)_pftinfo->dwEntryCF+ _pftinfo->dwSizeCF))) || spCur->dwTOCreg == (unsigned long)GetRTOC())
		{
		// okay, we are throw in the same code fragment as CRT, CRT being statically linked in, or the same as last throw
		}
	else if ( (spCur->dwLNKreg >= _pftinfoCRT->dwEntryCF) && (spCur->dwLNKreg <= ((unsigned long)((char *)_pftinfoCRT->dwEntryCF+ _pftinfoCRT->dwSizeCF))) || spCur->dwTOCreg == (unsigned long)GetRTOC())
		{
		_pftinfo = _pftinfoCRT;
		}
	else
		{
		// make _pftinfo point to the code fragment which has thrown the exception, CRT must be a DLL now
		_ASSERTE(spCur->dwTOCreg);
		_pftinfo = (PFTINFO)(*(unsigned long *)((char *)spCur->dwTOCreg + OFSFTINFO));
		dwRTOC = spCur->dwTOCreg;
		}


	while (spCur->dwLNKreg)
		{
		if (_pFrameInfoChain)
			{
			// we should only look the outer nested scope for handlers and we should skip catch handler frame
			// because the actual frame called the catch handler is way down
			if ( (spCur > _pFrameInfoChain->pExitContext) && (spCur < _pFrameInfoChain->pSp) )
				{
				spCur = spCur->pSpBackChain;
				continue;
				}

			if (cNested > 0)
				{
				cNestedTmp = cNested;
				pframeinfo = _pFrameInfoChain;
				while (cNestedTmp-- && pframeinfo)
					{
					// This means we are throw in the catch
					if ( (spCur->pSpBackChain == pframeinfo->pExitContext) )
						{
						pFunctionEntryCatch = GetFunctionEntry(spCur, &pftinfoTOC);
						spCurCatch = spCur;
						break;
						}
					pframeinfo = pframeinfo->pNext;
					}
				if (pframeinfo)
					{
					spCur = spCur->pSpBackChain;
					continue;
					}
				}
			}

		pFunctionEntry = GetFunctionEntry(spCur, &pftinfoTOC);

		if (pFunctionEntry && (pFunctionEntry->ExceptionHandler != NULL))
			{
			//stack point, old PC(in linker register, execution point==state), Registers in Context
			pFrame = spCur;
			curDC.ControlPc = spCur->dwLNKreg;
			curDC.FunctionEntry = pFunctionEntry;  
			curDC.EstablisherFrame = spCur;   
            curDC.pExcept = pExceptionRecord;   
			if (_pftinfo != pftinfoTOC)
				{
				// we are calling catch which is in different code fragment
				curDC.pftinfo = pftinfoTOC;   
				curDC.pftinfo->pFrameInfo = _pFrameInfoChain;
				_pftinfo->pFrameInfo = _pFrameInfoChain;
				_pFrameInfoChain = 0;      //reset
				cNested = 0;
				}
			else
				{
				curDC.pftinfo = _pftinfo;
   				curDC.pftinfo->pFrameInfo = _pFrameInfoChain;
				}
			if (dwRTOC == 0)
					{
					dwRTOC = (unsigned long)GetRTOC();  //not CRT as DLL case
					}
			//dwRTOC has throw object RTOC
			//curDC has handler's info
			if (pFunctionEntryCatch == pFunctionEntry)
				{
				// we have to  update the return address in original catch frame
				if (spCurCatch->dwLNKreg > curDC.ControlPc)
					{
					curDC.ControlPc = spCurCatch->dwLNKreg;
					}
				//we have to remeber the current return from catch's throw, so we can unwinding properly.
				//the return in the frame is adjusted to next state, so it can be off for unwinding
				//Note: we only need all the trouble for statically nested case
				curDC.ControlPcOld = spCurCatch->dwLNKreg;
				fStaticNested = 1;
				}
			(*pFunctionEntry->ExceptionHandler)(pExceptionRecord, pFrame, (void *)dwRTOC, &curDC);
			if (_pftinfo != pftinfoTOC)
				{
				_pFrameInfoChain = (PFRAMEINFO)_pftinfo->pFrameInfo; //reset our globals if we come back;STILL problem!!!
				pframeinfo = _pFrameInfoChain;	
				while (pframeinfo)
					{
					// This means we are throw in the catch
					cNested++;
					pframeinfo = pframeinfo->pNext;
					}
				}
			fStaticNested = 0;
			pFuncEntryLast = pFunctionEntry;
			}
		spCur = spCur->pSpBackChain;
		if (dwSPStartup)
			{
			if (spCur->dwLNKreg && (spCur > (PPMSTACK)dwSPStartup))
				{
				//we are at second to last of stack frame, break out the loop
				break;
				}
			}
		else
			{
			// we don't know our bottom of stack, didn't go through this instance of mainCRTStartup
			// let's break out the loop if we encounter 68k frame
			if ((unsigned int)spCur & 0x01)
				{
				break;
				}
			}
		}

	//We don't have a handler, we should just exit out of the program
    terminate();
}
コード例 #22
0
dgInt32 dgCollisionScene::CalculateSignature () const
{
	_ASSERTE (0);
	return 0;
}
コード例 #23
0
/**----------------------------------------------------------------------------
\brief
\param
\return
\code
\endcode
-----------------------------------------------------------------------------*/
DTSTATUS
FileIoHelper::FIOReference(
IN BOOL ReadOnly,
IN LARGE_INTEGER Offset,
IN DWORD Size,
IN OUT PUCHAR& ReferencedPointer
)
{
	if (TRUE != Initialized()) return DTS_INVALID_OBJECT_STATUS;
	if (TRUE == IsReadOnly())
	{
		if (TRUE != ReadOnly)
		{
			printf("file handle is read-only!");
			return DTS_INVALID_PARAMETER;
		}
	}

	_ASSERTE(NULL == mFileView);
	FIOUnreference();

	if (Offset.QuadPart + Size > mFileSize.QuadPart)
	{
		printf("invalid offset. file size=%I64d, req offset=%I64d", mFileSize.QuadPart, Offset.QuadPart);
		return DTS_INVALID_PARAMETER;
	}

	//
	// MapViewOfFile() 함수의 dwFileOffsetLow 파라미터는 
	// SYSTEM_INFO::dwAllocationGranularity 값의 배수이어야 한다.
	// 
	static DWORD AllocationGranularity = 0;
	if (0 == AllocationGranularity)
	{
		SYSTEM_INFO si = { 0 };
		GetSystemInfo(&si);
		AllocationGranularity = si.dwAllocationGranularity;
	}

	DWORD AdjustMask = AllocationGranularity - 1;
	LARGE_INTEGER AdjustOffset = { 0 };
	AdjustOffset.HighPart = Offset.HighPart;

	// AllocationGranularity 이하의 값을 버림
	// 
	AdjustOffset.LowPart = (Offset.LowPart & ~AdjustMask);

	// 버려진 값만큼 매핑할 사이즈를 증가
	// 
	DWORD BytesToMap = (Offset.LowPart & AdjustMask) + Size;

	mFileView = (PUCHAR)MapViewOfFile(
		mFileMap,
		(TRUE == ReadOnly) ? FILE_MAP_READ : FILE_MAP_READ | FILE_MAP_WRITE,
		AdjustOffset.HighPart,
		AdjustOffset.LowPart,
		BytesToMap
		);
	if (NULL == mFileView)
	{
		printf("MapViewOfFile(high=0x%08x, log=0x%08x, bytes to map=%u) failed, gle=0x%08x", AdjustOffset.HighPart, AdjustOffset.LowPart, BytesToMap, GetLastError());
		return DTS_WINAPI_FAILED;
	}

	ReferencedPointer = &mFileView[Offset.LowPart & AdjustMask];
	return DTS_SUCCESS;
}
コード例 #24
0
dgVector dgCollisionScene::CalculateVolumeIntegral (const dgMatrix& globalMatrix, GetBuoyancyPlane bouyancyPlane, void* const context) const
{
	_ASSERTE (0);
	return dgVector (dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (0.0f));
}
コード例 #25
0
ファイル: ConEmuCmd.cpp プロジェクト: AshWilliams/ConEmu
void ComspecDone(int aiRc)
{
#ifdef _DEBUG
	xf_dump_chk();
	xf_validate(NULL);
#endif
	//WARNING("Послать в GUI CONEMUCMDSTOPPED");
	LogSize(NULL, "ComspecDone");

	// Это необходимо делать, т.к. при смене буфера (SetConsoleActiveScreenBuffer) приложением,
	// дескриптор нужно закрыть, иначе conhost может не вернуть предыдущий буфер
	//ConOutCloseHandle()

	// Поддержка алиасов
	if (gpSrv->szComSpecName[0] && gpSrv->szSelfName[0])
	{
		// Скопировать алиасы из cmd.exe в conemuc.exe
		wchar_t *pszPostAliases = NULL;
		DWORD nPostAliasSize;
		BOOL lbChanged = (gpSrv->pszPreAliases == NULL);

		if (!GetAliases(gpSrv->szComSpecName, &pszPostAliases, &nPostAliasSize))
		{
			if (pszPostAliases)
				_wprintf(pszPostAliases);
		}
		else
		{
			if (!lbChanged)
			{
				lbChanged = (gpSrv->nPreAliasSize!=nPostAliasSize);
			}

			if (!lbChanged && gpSrv->nPreAliasSize && gpSrv->pszPreAliases && pszPostAliases)
			{
				lbChanged = memcmp(gpSrv->pszPreAliases,pszPostAliases,gpSrv->nPreAliasSize)!=0;
			}

			if (lbChanged)
			{
				xf_dump_chk();

				if (gnMainServerPID)
				{
					MCHKHEAP;
					CESERVER_REQ* pIn = ExecuteNewCmd(CECMD_SAVEALIASES,sizeof(CESERVER_REQ_HDR)+nPostAliasSize);

					if (pIn)
					{
						MCHKHEAP;
						memmove(pIn->Data, pszPostAliases, nPostAliasSize);
						MCHKHEAP;
						CESERVER_REQ* pOut = ExecuteSrvCmd(gnMainServerPID, pIn, GetConEmuHWND(2));
						MCHKHEAP;

						if (pOut) ExecuteFreeResult(pOut);

						ExecuteFreeResult(pIn);
						MCHKHEAP;
					}
				}

				xf_dump_chk();
				wchar_t *pszNewName = pszPostAliases, *pszNewTarget, *pszNewLine;

				while (pszNewName && *pszNewName)
				{
					pszNewLine = pszNewName + lstrlen(pszNewName);
					pszNewTarget = wcschr(pszNewName, L'=');

					if (pszNewTarget)
					{
						*pszNewTarget = 0;
						pszNewTarget++;
					}

					if (*pszNewTarget == 0) pszNewTarget = NULL;

					AddConsoleAlias(pszNewName, pszNewTarget, gpSrv->szSelfName);
					pszNewName = pszNewLine+1;
				}

				xf_dump_chk();
			}
		}

		if (pszPostAliases)
		{
			free(pszPostAliases); pszPostAliases = NULL;
		}
	}

	xf_dump_chk();
	//TODO("Уведомить плагин через пайп (если родитель - FAR) что процесс завершен. Плагин должен считать и запомнить содержимое консоли и только потом вернуть управление в ConEmuC!");
	DWORD dwErr1 = 0; //, dwErr2 = 0;
	HANDLE hOut1 = NULL, hOut2 = NULL;
	BOOL lbRc1 = FALSE, lbRc2 = FALSE;
	CONSOLE_SCREEN_BUFFER_INFO sbi1 = {{0,0}}, sbi2 = {{0,0}};

	#ifdef _DEBUG
	HWND hWndCon = GetConEmuHWND(2);
	#endif

	// Тут нужна реальная, а не скорректированная информация!
	if (!gbNonGuiMode)
	{
		// Если GUI не сможет через сервер вернуть высоту буфера - это нужно сделать нам!
		lbRc1 = GetConsoleScreenBufferInfo(hOut1 = GetStdHandle(STD_OUTPUT_HANDLE), &sbi1);

		if (!lbRc1)
			dwErr1 = GetLastError();

		xf_dump_chk();
	}

	//PRAGMA_ERROR("Размер должен возвращать сам GUI, через серверный ConEmuC!");
	#ifdef SHOW_STARTED_MSGBOX
	MessageBox(GetConEmuHWND(2), L"ConEmuC (comspec mode) is about to TERMINATE", L"ConEmuC.ComSpec", 0);
	#endif

	#ifdef _DEBUG
	xf_dump_chk();
	xf_validate(NULL);
	#endif

	if (!gbNonGuiMode && (gpSrv->dwParentFarPID != 0))
	{
		//// Вернуть размер буфера (высота И ширина)
		//if (gpSrv->sbi.dwSize.X && gpSrv->sbi.dwSize.Y) {
		//	SMALL_RECT rc = {0};
		//	SetConsoleSize(0, gpSrv->sbi.dwSize, rc, "ComspecDone");
		//}
		//ConOutCloseHandle()
		CONSOLE_SCREEN_BUFFER_INFO l_csbi = {{0}};
		lbRc2 = GetConsoleScreenBufferInfo(hOut2 = GetStdHandle(STD_OUTPUT_HANDLE), &l_csbi);

		CESERVER_REQ *pOut = SendStopped(&l_csbi);

		if (pOut)
		{
			if (!pOut->StartStopRet.bWasBufferHeight)
			{
				//gpSrv->sbi.dwSize = pIn->StartStop.sbi.dwSize;
				lbRc1 = FALSE; // Консольное приложение самостоятельно сбросило буферный режим. Не дергаться...
			}
			else
			{
				lbRc1 = TRUE;
			}

			ExecuteFreeResult(pOut); pOut = NULL;
		}

		if (!gbWasBufferHeight)
		{
			lbRc2 = GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &sbi2);

			#ifdef _DEBUG
			if (sbi2.dwSize.Y > 200)
			{
				wchar_t szTitle[128]; _wsprintf(szTitle, SKIPLEN(countof(szTitle)) L"ConEmuC (PID=%i)", GetCurrentProcessId());
				MessageBox(NULL, L"BufferHeight was not turned OFF", szTitle, MB_SETFOREGROUND|MB_SYSTEMMODAL);
			}
			#endif

			if (lbRc1 && lbRc2 && sbi2.dwSize.Y == sbi1.dwSize.Y)
			{
				// GUI не смог вернуть высоту буфера...
				// Это плохо, т.к. фар высоту буфера не меняет и будет сильно глючить на N сотнях строк...
				int nNeedHeight = gpSrv->sbi.dwSize.Y;

				if (nNeedHeight < 10)
				{
					nNeedHeight = (sbi2.srWindow.Bottom-sbi2.srWindow.Top+1);
				}

				if (sbi2.dwSize.Y != nNeedHeight)
				{
					_ASSERTE(sbi2.dwSize.Y == nNeedHeight);
					PRINT_COMSPEC(L"Error: BufferHeight was not changed from %i\n", sbi2.dwSize.Y);
					SMALL_RECT rc = {0};
					sbi2.dwSize.Y = nNeedHeight;

					if (gpLogSize) LogSize(&sbi2.dwSize, ":ComspecDone.RetSize.before");

					SetConsoleSize(0, sbi2.dwSize, rc, "ComspecDone.Force");

					if (gpLogSize) LogSize(NULL, ":ComspecDone.RetSize.after");
				}
			}
		}
	}

	if (gpSrv->pszPreAliases) { free(gpSrv->pszPreAliases); gpSrv->pszPreAliases = NULL; }

	//SafeCloseHandle(ghCtrlCEvent);
	//SafeCloseHandle(ghCtrlBreakEvent);
}
コード例 #26
0
bool dgCollisionScene::OOBBTest (const dgMatrix& matrix, const dgCollisionConvex* const shape, void* const cacheOrder) const
{
	_ASSERTE (0);
	return true;
}
コード例 #27
0
ファイル: ConEmuCmd.cpp プロジェクト: AshWilliams/ConEmu
int ComspecInit()
{
	TODO("Определить код родительского процесса, и если это FAR - запомнить его (для подключения к пайпу плагина)");
	TODO("Размер получить из GUI, если оно есть, иначе - по умолчанию");
	TODO("GUI может скорректировать размер с учетом полосы прокрутки");
	WARNING("CreateFile(CONOUT$) по идее возвращает текущий ScreenBuffer. Можно его самим возвращать в ComspecDone");

	// Правда нужно проверить, что там происходит с ghConOut.Close(),...
	// Размер должен менять сам GUI, через серверный ConEmuC!
#ifdef SHOW_STARTED_MSGBOX
	MessageBox(GetConEmuHWND(2), L"ConEmuC (comspec mode) is about to START", L"ConEmuC.ComSpec", 0);
#endif
	//int nNewBufferHeight = 0;
	//COORD crNewSize = {0,0};
	//SMALL_RECT rNewWindow = gpSrv->sbi.srWindow;
	BOOL lbSbiRc = FALSE;
	gbRootWasFoundInCon = 2; // не добавлять к "Press Enter to close console" - "or wait"
	gbComspecInitCalled = TRUE; // Нельзя вызывать ComspecDone, если не было вызова ComspecInit
	// в режиме ComSpec - запрещено!
	gbAlwaysConfirmExit = FALSE; gbAutoDisableConfirmExit = FALSE;
#ifdef _DEBUG
	xf_validate();
	xf_dump_chk();
#endif
	// Это наверное и не нужно, просто для информации...
	lbSbiRc = GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &gpSrv->sbi);
	#ifdef _DEBUG
	DWORD nErrCode = lbSbiRc ? 0 : GetLastError();
	// Процесс запущен с редиректом вывода?
	_ASSERTE(lbSbiRc || (nErrCode == ERROR_INVALID_HANDLE));
	#endif

#if 0
	// 111211 - "-new_console" теперь передается в GUI и исполняется в нем
	// Сюда мы попадаем если был ключик -new_console
	// А этом случае нужно завершить ЭТОТ экземпляр и запустить в ConEmu новую вкладку
	if (gpSrv->bNewConsole)
	{
#ifdef _DEBUG
		xf_validate();
		xf_dump_chk();
#endif
		PROCESS_INFORMATION pi; memset(&pi, 0, sizeof(pi));
		STARTUPINFOW si; memset(&si, 0, sizeof(si)); si.cb = sizeof(si);
		si.dwFlags = STARTF_USESHOWWINDOW|STARTF_USECOUNTCHARS;
		si.dwXCountChars = gpSrv->sbi.dwSize.X;
		si.dwYCountChars = gpSrv->sbi.dwSize.Y;
		si.wShowWindow = SW_HIDE;
		PRINT_COMSPEC(L"Creating new console for:\n%s\n", gpszRunCmd);
#ifdef _DEBUG
		xf_validate();
		xf_dump_chk();
#endif
		// CREATE_NEW_PROCESS_GROUP - низя, перестает работать Ctrl-C
		// Запускается новый сервер (новая консоль), сюда хуки ставить не надо.
		BOOL lbRc = createProcess(TRUE, NULL, gpszRunCmd, NULL,NULL, TRUE,
		                           NORMAL_PRIORITY_CLASS|CREATE_NEW_CONSOLE,
		                           NULL, NULL, &si, &pi);
		DWORD dwErr = GetLastError();

		if (!lbRc)
		{
			PrintExecuteError(gpszRunCmd, dwErr);
			return CERR_CREATEPROCESS;
		}

#ifdef _DEBUG
		xf_validate();
		xf_dump_chk();
#endif
		//delete psNewCmd; psNewCmd = NULL;
		AllowSetForegroundWindow(pi.dwProcessId);
		PRINT_COMSPEC(L"New console created. PID=%i. Exiting...\n", pi.dwProcessId);
		SafeCloseHandle(pi.hProcess); SafeCloseHandle(pi.hThread);
		DisableAutoConfirmExit();
		//gpSrv->nProcessStartTick = GetTickCount() - 2*CHECK_ROOTSTART_TIMEOUT; // менять nProcessStartTick не нужно. проверка только по флажкам
#ifdef _DEBUG
		xf_validate();
		xf_dump_chk();
#endif
		return CERR_RUNNEWCONSOLE;
	}
#endif

	// Если определена ComSpecC - значит ConEmuC переопределил стандартный ComSpec
	// Вернем его
	wchar_t szComSpec[MAX_PATH+1];
	const wchar_t* pszComSpecName;

	//110202 - comspec более не переопределяется
	//if (GetEnvironmentVariable(L"ComSpecC", szComSpec, MAX_PATH) && szComSpec[0] != 0)
	WARNING("TCC/ComSpec");
	if (GetEnvironmentVariable(L"ComSpec", szComSpec, MAX_PATH) && szComSpec[0] != 0)
	{
		//// Только если это (случайно) не conemuc.exe
		//wchar_t* pwszCopy = (wchar_t*)PointToName(szComSpec); //wcsrchr(szComSpec, L'\\');
		////if (!pwszCopy) pwszCopy = szComSpec;

		//#pragma warning( push )
		//#pragma warning(disable : 6400)
		//if (lstrcmpiW(pwszCopy, L"ConEmuC")==0 || lstrcmpiW(pwszCopy, L"ConEmuC.exe")==0
		//        /*|| lstrcmpiW(pwszCopy, L"ConEmuC64")==0 || lstrcmpiW(pwszCopy, L"ConEmuC64.exe")==0*/)
		//	szComSpec[0] = 0;
		//#pragma warning( pop )

		//if (szComSpec[0])
		//{
		//	SetEnvironmentVariable(L"ComSpec", szComSpec);
		//	SetEnvironmentVariable(L"ComSpecC", NULL);
		//}

		pszComSpecName = (wchar_t*)PointToName(szComSpec);
	}
	else
	{
		WARNING("TCC/ComSpec");
		pszComSpecName = L"cmd.exe";
	}

	lstrcpyn(gpSrv->szComSpecName, pszComSpecName, countof(gpSrv->szComSpecName));

	if (pszComSpecName)
	{
		wchar_t szSelf[MAX_PATH+1];

		if (GetModuleFileName(NULL, szSelf, MAX_PATH))
		{
			lstrcpyn(gpSrv->szSelfName, (wchar_t*)PointToName(szSelf), countof(gpSrv->szSelfName));

			if (!GetAliases(gpSrv->szSelfName, &gpSrv->pszPreAliases, &gpSrv->nPreAliasSize))
			{
				if (gpSrv->pszPreAliases)
				{
					_wprintf(gpSrv->pszPreAliases);
					free(gpSrv->pszPreAliases);
					gpSrv->pszPreAliases = NULL;
				}
			}
		}
	}

	SendStarted();
	//ConOutCloseHandle()
	return 0;
}
コード例 #28
0
dgVector dgCollisionScene::SupportVertex (const dgVector& dir) const
{
	_ASSERTE (0);
	return dgVector (0, 0, 0, 0);
}
コード例 #29
0
ファイル: TermX.cpp プロジェクト: chengyil/ConEmu
bool TermX::GetSubstitute(const KEY_EVENT_RECORD& k, wchar_t (&szSubst)[16])
{
	_ASSERTE(szSubst[0] == 0);

	static UINT F1Codes[24] = {
		11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 23, 24,
		25, 26, 28, 29, 31, 32, 33, 34, 42, 43, 44, 45
	};
	static wchar_t F1F4Codes[] = {L'P', L'Q', L'R', L'S'};

	typedef DWORD XTermCtrls;
	const XTermCtrls
		xtc_Shift = 1,
		xtc_Alt   = 2,
		xtc_Ctrl  = 4,
		xtc_None  = 0;
	struct processor
	{
		XTermCtrls Mods;

		void SetKey(wchar_t (&szSubst)[16], wchar_t c, wchar_t prefix=L'O')
		{
			if (!Mods)
			{
				//wcscpy_c(szSubst, L"\033O*A");
				msprintf(szSubst, countof(szSubst), L"\033%c%c", prefix, c);
			}
			else
			{
				msprintf(szSubst, countof(szSubst), L"\033[1;%c%c", Mods+L'1', c);
			}
		}

		void SetFKey(wchar_t (&szSubst)[16], UINT fn)
		{
			if (!Mods)
			{
				msprintf(szSubst, countof(szSubst), L"\033[%u~", fn);
			}
			else
			{
				msprintf(szSubst, countof(szSubst), L"\033[%u;%c~", fn, Mods+L'1');
			}
		}

		void SetTilde(wchar_t (&szSubst)[16], wchar_t c)
		{
			if (!Mods)
			{
				msprintf(szSubst, countof(szSubst), L"\033[%c~", c);
			}
			else
			{
				msprintf(szSubst, countof(szSubst), L"\033[%c;%c~", c, Mods+L'1');
			}
		}
	} Processor = {xtc_None};

	if (k.dwControlKeyState & (SHIFT_PRESSED))
		Processor.Mods |= xtc_Shift;
	if (k.dwControlKeyState & (LEFT_ALT_PRESSED|RIGHT_ALT_PRESSED))
		Processor.Mods |= xtc_Alt;
	if (k.dwControlKeyState & (LEFT_CTRL_PRESSED|RIGHT_CTRL_PRESSED))
		Processor.Mods |= xtc_Ctrl;

	switch (k.wVirtualKeyCode)
	{
	case VK_UP:
		Processor.SetKey(szSubst, L'A', L'[');
		return true;
	case VK_DOWN:
		Processor.SetKey(szSubst, L'B', L'[');
		return true;
	case VK_RIGHT:
		Processor.SetKey(szSubst, L'C', L'[');
		return true;
	case VK_LEFT:
		Processor.SetKey(szSubst, L'D', L'[');
		return true;
	case VK_HOME:
		Processor.SetKey(szSubst, L'H', L'[');
		return true;
	case VK_END:
		Processor.SetKey(szSubst, L'F', L'[');
		return true;

	case VK_F1: case VK_F2: case VK_F3: case VK_F4:
		Processor.SetKey(szSubst, F1F4Codes[(k.wVirtualKeyCode-VK_F1)]);
		return true;
	case VK_F5: case VK_F6: case VK_F7: case VK_F8:
	case VK_F9: case VK_F10: case VK_F11: case VK_F12: case VK_F13: case VK_F14: case VK_F15: case VK_F16:
	case VK_F17: case VK_F18: case VK_F19: case VK_F20: case VK_F21: case VK_F22: case VK_F23: case VK_F24:
		// "\033[11;*~" .. L"\033[15;*~", and so on: F1Codes[]
		Processor.SetFKey(szSubst, F1Codes[(k.wVirtualKeyCode-VK_F1)]);
		return true;

	case VK_INSERT:
		Processor.SetTilde(szSubst, L'2');
		return true;
	case VK_PRIOR:
		Processor.SetTilde(szSubst, L'5');
		return true;
	case VK_NEXT:
		Processor.SetTilde(szSubst, L'6');
		return true;
	case VK_DELETE:
		Processor.SetTilde(szSubst, L'3');
		return true;
	case VK_BACK:
		if ((Processor.Mods & xtc_Alt)) szSubst[0] = 0x1B;
		szSubst[(Processor.Mods == xtc_Alt) ? 1 : 0] = ((Processor.Mods & (xtc_Ctrl|xtc_Alt)) == (xtc_Ctrl|xtc_Alt)) ? 0x9F
			: (Processor.Mods & xtc_Ctrl) ? 0x1F : 0x7F;
		szSubst[(Processor.Mods == xtc_Alt) ? 2 : 1] = 0;
		return true;

	case VK_TAB:
		if (!(k.dwControlKeyState & (LEFT_CTRL_PRESSED|RIGHT_CTRL_PRESSED|LEFT_ALT_PRESSED|RIGHT_ALT_PRESSED)))
		{
			wcscpy_c(szSubst, (k.dwControlKeyState & SHIFT_PRESSED) ? L"\033[Z" : L"\t");
		}
		return true;

	/* NumPad with NumLock ON */
	case VK_NUMPAD0:
	case VK_NUMPAD1:
	case VK_NUMPAD2:
	case VK_NUMPAD3:
	case VK_NUMPAD4:
	case VK_NUMPAD5:
	case VK_NUMPAD6:
	case VK_NUMPAD7:
	case VK_NUMPAD8:
	case VK_NUMPAD9:
	case VK_DECIMAL: // VK_OEM_PERIOD}, // Actually, this may be comma
	case VK_DIVIDE:
	case VK_MULTIPLY:
	case VK_SUBTRACT:
	case VK_ADD:
		if (k.uChar.UnicodeChar)
		{
			// Just a digits '0'..'9' and symbols +-/*.
			szSubst[0] = k.uChar.UnicodeChar; szSubst[1] = 0;
		}
		return true;
	}

	// Alt+Char
	if ((Processor.Mods & xtc_Alt) && k.uChar.UnicodeChar
		// connector/gh#4: AltGr+Char
		&& ((k.dwControlKeyState & (LEFT_CTRL_PRESSED|RIGHT_CTRL_PRESSED|LEFT_ALT_PRESSED|RIGHT_ALT_PRESSED))
				!= (LEFT_CTRL_PRESSED|RIGHT_ALT_PRESSED))
		)
	{
		szSubst[0] = L'\033'; szSubst[1] = k.uChar.UnicodeChar; szSubst[2] = 0;
		return true;
	}

	// Ctrl+Char? A-->1, ..., J-->10, ...

	return false;
}
コード例 #30
0
ファイル: detours.cpp プロジェクト: nkoep/advancedfx
/*++
  Routine Description:
    Replace the function pointer in a module's IAT.

  Parameters:
    Module              - Module to use IAT from.
    ImportedModuleName  - Name of imported DLL from which 
                          function is imported.
    ImportedProcName    - Name of imported function.
    AlternateProc       - Function to be written to IAT.
    OldProc             - Original function.

  Return Value:
    S_OK on success.
    (any HRESULT) on failure.
--*/
HRESULT PatchIat(
  __in HMODULE Module,
  __in PSTR ImportedModuleName,
  __in PSTR ImportedProcName,
  __in PVOID AlternateProc,
  __out_opt PVOID *OldProc
  )
{
  PIMAGE_DOS_HEADER DosHeader = ( PIMAGE_DOS_HEADER ) Module;
  PIMAGE_NT_HEADERS NtHeader; 
  PIMAGE_IMPORT_DESCRIPTOR ImportDescriptor;
  UINT Index;

  _ASSERTE( Module );
  _ASSERTE( ImportedModuleName );
  _ASSERTE( ImportedProcName );
  _ASSERTE( AlternateProc );

  NtHeader = ( PIMAGE_NT_HEADERS ) 
    PtrFromRva( DosHeader, DosHeader->e_lfanew );
  if( IMAGE_NT_SIGNATURE != NtHeader->Signature )
  {
    return HRESULT_FROM_WIN32( ERROR_BAD_EXE_FORMAT );
  }

  ImportDescriptor = ( PIMAGE_IMPORT_DESCRIPTOR ) 
    PtrFromRva( DosHeader, 
      NtHeader->OptionalHeader.DataDirectory
        [ IMAGE_DIRECTORY_ENTRY_IMPORT ].VirtualAddress );

  //
  // Iterate over import descriptors/DLLs.
  //
  for ( Index = 0; 
        ImportDescriptor[ Index ].Characteristics != 0; 
        Index++ )
  {
    PSTR dllName = ( PSTR ) 
      PtrFromRva( DosHeader, ImportDescriptor[ Index ].Name );

    if ( 0 == _strcmpi( dllName, ImportedModuleName ) )
    {
      //
      // This the DLL we are after.
      //
      PIMAGE_THUNK_DATA Thunk;
      PIMAGE_THUNK_DATA OrigThunk;

      if ( ! ImportDescriptor[ Index ].FirstThunk ||
         ! ImportDescriptor[ Index ].OriginalFirstThunk )
      {
        return E_INVALIDARG;
      }

      Thunk = ( PIMAGE_THUNK_DATA )
        PtrFromRva( DosHeader, 
          ImportDescriptor[ Index ].FirstThunk );
      OrigThunk = ( PIMAGE_THUNK_DATA )
        PtrFromRva( DosHeader, 
          ImportDescriptor[ Index ].OriginalFirstThunk );

      for ( ; OrigThunk->u1.Function != NULL; 
              OrigThunk++, Thunk++ )
      {
        if ( OrigThunk->u1.Ordinal & IMAGE_ORDINAL_FLAG )
        {
          //
          // Ordinal import - we can handle named imports
          // ony, so skip it.
          //
          continue;
        }

        PIMAGE_IMPORT_BY_NAME import = ( PIMAGE_IMPORT_BY_NAME )
          PtrFromRva( DosHeader, OrigThunk->u1.AddressOfData );

        if ( 0 == strcmp( ImportedProcName, 
                              ( char* ) import->Name ) )
        {
          //
          // Proc found, patch it.
          //
          DWORD junk;
          MEMORY_BASIC_INFORMATION thunkMemInfo;

          //
          // Make page writable.
          //
          VirtualQuery(
            Thunk,
            &thunkMemInfo,
            sizeof( MEMORY_BASIC_INFORMATION ) );
          if ( ! VirtualProtect(
            thunkMemInfo.BaseAddress,
            thunkMemInfo.RegionSize,
            PAGE_EXECUTE_READWRITE,
            &thunkMemInfo.Protect ) )
          {
            return HRESULT_FROM_WIN32( GetLastError() );
          }

          //
          // Replace function pointers (non-atomically).
          //
          if ( OldProc )
          {
            *OldProc = ( PVOID ) ( DWORD_PTR ) 
                Thunk->u1.Function;
          }
#ifdef _WIN64
          Thunk->u1.Function = ( ULONGLONG ) ( DWORD_PTR ) 
              AlternateProc;
#else
          Thunk->u1.Function = ( DWORD ) ( DWORD_PTR ) 
              AlternateProc;
#endif
          //
          // Restore page protection.
          //
          if ( ! VirtualProtect(
            thunkMemInfo.BaseAddress,
            thunkMemInfo.RegionSize,
            thunkMemInfo.Protect,
            &junk ) )
          {
            return HRESULT_FROM_WIN32( GetLastError() );
          }

          return S_OK;
        }
      }
      
      //
      // Import not found.
      //
      return HRESULT_FROM_WIN32( ERROR_PROC_NOT_FOUND );    
    }
  }

  //
  // DLL not found.
  //
  return HRESULT_FROM_WIN32( ERROR_MOD_NOT_FOUND );
}