Exemple #1
0
/* Test each page.  */
static bool
TestPage(const char *pagelabel, uintptr_t pageaddr, int should_succeed)
{
    const char *oplabel;
    uintptr_t opaddr;

    bool failed = false;
    for (unsigned int test = 0; test < 3; test++) {
        switch (test) {
        // The execute test must be done before the write test, because the
        // write test will clobber memory at the target address.
        case 0:
            oplabel = "reading";
            opaddr = pageaddr + PAGESIZE/2 - 1;
            break;
        case 1:
            oplabel = "executing";
            opaddr = pageaddr + PAGESIZE/2;
            break;
        case 2:
            oplabel = "writing";
            opaddr = pageaddr + PAGESIZE/2 - 1;
            break;
        default:
            abort();
        }

#ifdef _WIN32
        BOOL badptr;

        switch (test) {
        case 0:
            badptr = IsBadReadPtr((const void*)opaddr, 1);
            break;
        case 1:
            badptr = IsBadExecPtr(opaddr);
            break;
        case 2:
            badptr = IsBadWritePtr((void*)opaddr, 1);
            break;
        default:
            abort();
        }

        if (badptr) {
            if (should_succeed) {
                printf("TEST-UNEXPECTED-FAIL | %s %s\n", oplabel, pagelabel);
                failed = true;
            } else {
                printf("TEST-PASS | %s %s\n", oplabel, pagelabel);
            }
        } else {
            // if control reaches this point the probe succeeded
            if (should_succeed) {
                printf("TEST-PASS | %s %s\n", oplabel, pagelabel);
            } else {
                printf("TEST-UNEXPECTED-FAIL | %s %s\n", oplabel, pagelabel);
                failed = true;
            }
        }
#elif defined(__OS2__)
        XCPT xcpt;
        volatile int code = setjmp(xcpt.jmpbuf);

        if (!code) {
            xcpt.regrec.prev_structure = 0;
            xcpt.regrec.ExceptionHandler = ExceptionHandler;
            DosSetExceptionHandler(&xcpt.regrec);
            unsigned char scratch;
            switch (test) {
            case 0:
                scratch = *(volatile unsigned char *)opaddr;
                break;
            case 1:
                ((void (*)())opaddr)();
                break;
            case 2:
                *(volatile unsigned char *)opaddr = 0;
                break;
            default:
                abort();
            }
        }

        if (code) {
            if (should_succeed) {
                printf("TEST-UNEXPECTED-FAIL | %s %s | exception code %x\n",
                       oplabel, pagelabel, code);
                failed = true;
            } else {
                printf("TEST-PASS | %s %s | exception code %x\n",
                       oplabel, pagelabel, code);
            }
        } else {
            if (should_succeed) {
                printf("TEST-PASS | %s %s\n", oplabel, pagelabel);
            } else {
                printf("TEST-UNEXPECTED-FAIL | %s %s\n", oplabel, pagelabel);
                failed = true;
            }
            DosUnsetExceptionHandler(&xcpt.regrec);
        }
#else
        pid_t pid = fork();
        if (pid == -1) {
            printf("ERROR | %s %s | fork=%s\n", oplabel, pagelabel,
                   LastErrMsg());
            exit(2);
        } else if (pid == 0) {
            volatile unsigned char scratch;
            switch (test) {
            case 0:
                scratch = *(volatile unsigned char *)opaddr;
                break;
            case 1:
                JumpTo(opaddr);
                break;
            case 2:
                *(volatile unsigned char *)opaddr = 0;
                break;
            default:
                abort();
            }
            (void)scratch;
            _exit(0);
        } else {
            int status;
            if (waitpid(pid, &status, 0) != pid) {
                printf("ERROR | %s %s | wait=%s\n", oplabel, pagelabel,
                       LastErrMsg());
                exit(2);
            }

            if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
                if (should_succeed) {
                    printf("TEST-PASS | %s %s\n", oplabel, pagelabel);
                } else {
                    printf("TEST-UNEXPECTED-FAIL | %s %s | unexpected successful exit\n",
                           oplabel, pagelabel);
                    failed = true;
                }
            } else if (WIFEXITED(status)) {
                printf("ERROR | %s %s | unexpected exit code %d\n",
                       oplabel, pagelabel, WEXITSTATUS(status));
                exit(2);
            } else if (WIFSIGNALED(status)) {
                if (should_succeed) {
                    printf("TEST-UNEXPECTED-FAIL | %s %s | unexpected signal %d\n",
                           oplabel, pagelabel, WTERMSIG(status));
                    failed = true;
                } else {
                    printf("TEST-PASS | %s %s | signal %d (as expected)\n",
                           oplabel, pagelabel, WTERMSIG(status));
                }
            } else {
                printf("ERROR | %s %s | unexpected exit status %d\n",
                       oplabel, pagelabel, status);
                exit(2);
            }
        }
#endif
    }
    return failed;
}
Exemple #2
0
// thanks to Eugene Khodakovsky (I've just modified his code to make more lazy script call)
BOOL CHtmlViewer::ExecScript(TCHAR* ScriptContent,VARIANT* pScriptResult,EXCEPINFO* pExcepInfo)
{
    HRESULT hr = S_OK;

    IDispatch* pHtmlDocDispatch = NULL;
    IHTMLDocument2* pHtmlDoc = NULL;
    DISPID dispid = NULL;
    BSTR bstrMember;
    IDispatch* spScript;

    if (IsBadWritePtr(pExcepInfo,sizeof(EXCEPINFO)))
        return FALSE;

    memset(pExcepInfo, 0, sizeof(EXCEPINFO));
    pScriptResult->vt=VT_EMPTY;

    // Retrieve the document object.

    hr = pIWebBrowser->get_Document(&pHtmlDocDispatch);
    if (SUCCEEDED (hr) && (pHtmlDocDispatch != NULL))
    {
        hr = pHtmlDocDispatch->QueryInterface(IID_IHTMLDocument2,(void**)&pHtmlDoc);
        if (SUCCEEDED (hr) && (pHtmlDoc != NULL))
        {
            //Getting IDispatch for Java Script objects
            hr = pHtmlDoc->get_Script(&spScript);

            if (SUCCEEDED (hr) && (spScript != NULL))
            {
                bstrMember=SysAllocString(L"eval");// THE trick is here
                if (bstrMember)
                {
                    hr = spScript->GetIDsOfNames(IID_NULL,&bstrMember,1,LOCALE_SYSTEM_DEFAULT,&dispid);

                    if (SUCCEEDED (hr))
                    {
                        //Putting parameters
                        DISPPARAMS dispparams;
                        memset(&dispparams, 0, sizeof (DISPPARAMS));
                        dispparams.cArgs      = 1;
                        dispparams.rgvarg     = new VARIANT[dispparams.cArgs];
                        dispparams.cNamedArgs = 0;

                        dispparams.rgvarg[0].vt = VT_BSTR;

                        WCHAR* wScriptContent;
#if (defined(UNICODE)||defined(_UNICODE))
                        wScriptContent=ScriptContent;
#else
                        CAnsiUnicodeConvert::AnsiToUnicode(ScriptContent,&wScriptContent);
#endif
                        dispparams.rgvarg[0].bstrVal = SysAllocString(wScriptContent);

#if ((!defined(UNICODE))&& (!defined(_UNICODE)))
                        free(wScriptContent);
#endif
                        /*
                        // code for those who want to do the same thing
                        // using an array of string "const CStringArray& paramArray" as parameter
                        // instead of eval tips
                        
                        const int arraySize = paramArray.GetSize();
                        //Putting parameters
                        DISPPARAMS dispparams;
                        memset(&dispparams, 0, sizeof dispparams);
                        dispparams.cArgs      = arraySize;
                        dispparams.rgvarg     = new VARIANT[dispparams.cArgs];
                        dispparams.cNamedArgs = 0;

                        for( int i = 0; i < arraySize; i++)
                        {
                            CComBSTR> bstr = paramArray.GetAt(arraySize - 1 - i);
                            // back reading
                            bstr.CopyTo(&dispparams.rgvarg[i].bstrVal);
                            dispparams.rgvarg[i].vt = VT_BSTR;
                        }
                        */

                        if (dispparams.rgvarg[0].bstrVal)
                        {
                            UINT nArgErr = (UINT)-1;// initialize to invalid arg
                            //Call JavaScript function
                            hr = spScript->Invoke(dispid,
                                                    IID_NULL,
                                                    0,
                                                    DISPATCH_METHOD,
                                                    &dispparams,
                                                    pScriptResult,
                                                    pExcepInfo,
                                                    &nArgErr);

                            SysFreeString(dispparams.rgvarg[0].bstrVal);
                        }

                        delete [] dispparams.rgvarg;
                    }

                    SysFreeString(bstrMember);
                }
                
            }
            pHtmlDoc->Release();
        }
        pHtmlDocDispatch->Release();
    }

    return SUCCEEDED (hr);
}
Exemple #3
0
DWORD 
HW_Read(
    PI2C_CONTEXT pI2C,
    DWORD  SlaveAddr,   // slave address
    UCHAR  WordAddr,    // starting word address
    PUCHAR pData,       // pdata
    DWORD  Count        // bytes to read
    )
{
    DWORD  dwErr;

    if ( !VALID_CONTEXT(pI2C) )
        return ERROR_INVALID_PARAMETER;
        
    DEBUGMSG(ZONE_READ|ZONE_TRACE,(TEXT("+I2C_Read[%u]: 0x%X, 0x%X, 0x%X, %u\r\n"), 
        pI2C->State, SlaveAddr, WordAddr, pData, Count));
    
    if ( !pData || !Count || IsBadWritePtr(pData, Count) ) {
        DEBUGMSG(ZONE_ERR,(TEXT("I2C_Read ERROR: invalid parameter \r\n")));
        return ERROR_INVALID_PARAMETER;
    }

    EnterCriticalSection(&pI2C->RegCS);
    
    if ( pI2C->State != IDLE) {
        DEBUGMSG(ZONE_ERR,(TEXT("I2C_Read ERROR: i2cState: %u \r\n"), pI2C->State));
        LeaveCriticalSection(&pI2C->RegCS);
        return ERROR_BUSY;
    }

    pI2C->LastError = ERROR_SUCCESS;
    
    ResetEvent(pI2C->DoneEvent);

    rIICSTAT = M_ACTIVE;
    
    // pre-setup word address
    pI2C->Data = NULL;
    pI2C->State = SET_READ_ADDR;
    pI2C->WordAddr = WordAddr;
    pI2C->Flags.WordAddr = TRUE;
    pI2C->DataCount = 1;
    
    // enable the slave address drop
    pI2C->Flags.DropRxAddr = TRUE;

    // write slave address
    rIICDS = (UCHAR)SlaveAddr;
    rIICSTAT = MTX_START;

    // Wait for IST to write the word address
    if (WAIT_OBJECT_0 != SyncIst(pI2C, RX_TIMEOUT)) {
        
        DEBUGMSG(ZONE_READ|ZONE_ERR,(TEXT("RX_TIMEOUT.1\r\n")));

        goto _done;
    }

    ResetEvent(pI2C->DoneEvent);

    // get read data
    pI2C->State = READ_DATA;
    pI2C->Data = pData;
    pI2C->DataCount = Count;
    rIICDS = (UCHAR)SlaveAddr;
    rIICSTAT = MRX_START;
    rIICCON  = RESUME_ACK;  // Resume IIC operation (clear bit 4)

    // Wait for IST to get data
    if (WAIT_OBJECT_0 != SyncIst(pI2C, RX_TIMEOUT)) {
        
        DEBUGMSG(ZONE_READ|ZONE_ERR,(TEXT("RX_TIMEOUT.2\r\n")));

        goto _done;
    }



_done:    
    rIICSTAT  = M_IDLE;    // disable Rx/Tx
    pI2C->State = IDLE;
    pI2C->Data  = NULL;
    pI2C->DataCount = INVALID_DATA_COUNT;

    if ( !pI2C->LastError && (SlaveAddr != pI2C->RxRetAddr) ) {

        DEBUGMSG(ZONE_READ|ZONE_ERR,(TEXT("I2C_Read Invalid Return Address: 0x%X != 0x%X \r\n"), 
            pI2C->RxRetAddr, SlaveAddr ));

        pI2C->LastError = ERROR_INCORRECT_ADDRESS;

        TEST_TRAP;
    }
    
    pI2C->RxRetAddr = 0;

    dwErr = pI2C->LastError;
    
    LeaveCriticalSection(&pI2C->RegCS);
    
    DEBUGMSG(ZONE_READ|ZONE_TRACE,(TEXT("-I2C_Read:%u \r\n"), dwErr ));
	//RETAILMSG(1,(_T("data = 0x%X\r\n", *pData)));

    return dwErr;
}
Exemple #4
0
void Test()
{
	  //////////////////////////////////
	 //  MEMORY ALLOCATION TEST CODE //
	//////////////////////////////////

	int* test = MemoryManager::AllocateMemory<int>();
	assert(!IsBadWritePtr(test, sizeof(int)), "Memory allocation test failed: allocate");

	MemoryManager::FreeMemory(test);
	assert(IsBadWritePtr(test, sizeof(int)), "Memory free test failed: free");

	  ////////////////////////////////////
	 //  DOUBLY LINKED LIST TEST CODE  //
	////////////////////////////////////

	int* testint = MemoryManager::AllocateMemory<int>(10);
	testint[0] = 5;
	testint[1] = 12;
	testint[2] = 32;
	testint[3] = -2;
	testint[4] = 124125;

	DoubleLinkedList<int> TestList;
	DoubleLinkedList<int>::Node* testnode = TestList.Insert(&testint[0]);
	TestList.Insert(&testint[1]);
	TestList.Insert(&testint[2]);
	TestList.Insert(&testint[3]);
	TestList.Insert(&testint[4]);

	assert(*testnode->Item == 5, "Doubly linked list test failed: set");
	assert(*testnode->Next->Item == 12, "Doubly linked list test failed: next");

	TestList.Remove(testnode);


	///////////////////////////////
	//  POOL ALLOCATOR TEST CODE //
	///////////////////////////////

	//Create a pool of floats with length 10
	Pool<float>* TestPool = new Pool<float>(10);
	assert(TestPool != nullptr, "P ool allocator fails");

	//Get three values from the pool
	float* first = TestPool->Get();
	float* second = TestPool->Get();
	float* third = TestPool->Get();

	//Set their values
	*second = 2.f;
	*third = 123.4f;

	//Delete the pool
	delete TestPool;

	//////////////////////
	// LOGING TEST CODE //
	//////////////////////
	
	Log TestLog("TestLog.txt");
	TestLog.Write("Hello!");
	TestLog.Write("I am a cheese");



}
Exemple #5
0
BOOL 
WINAPI
NdasDmGetNdasLogDevSlotNoOfVolume(
	HANDLE hVolume, 
	LPDWORD lpdwSlotNo, 
	DWORD nBuffer, 
	LPDWORD lpdwBufferUsed)
{
	_ASSERTE(INVALID_HANDLE_VALUE != hVolume);
	_ASSERTE(NULL != hVolume);
	_ASSERTE(!IsBadWritePtr(lpdwSlotNo, sizeof(DWORD) * nBuffer));
	_ASSERTE(!IsBadWritePtr(lpdwBufferUsed, sizeof(DWORD)));

	BOOL fSuccess(FALSE);
	//
	// Get the physical disk numbers of the volume
	//
	DWORD pDiskNumbers[256];
	DWORD nDiskNumbers;

	fSuccess = NdasDmGetDiskNumbersOfVolume(hVolume, pDiskNumbers, 256, &nDiskNumbers);
	if (!fSuccess) {
		DBGPRT_ERR(_FT("NdasDmGetDiskNumbersOfVolume failed.\n"));
		return FALSE;
	}

	//
	// Get SCSI port number for each disks
	//
	// TODO: Resolve this problem!
	// What if the volume is spanned through NDAS Logical Disks and 
	// OS's regular Disks?
	//
	
	*lpdwBufferUsed = 0;
	for (DWORD i = 0; i < nDiskNumbers; ++i) {

		if (*lpdwBufferUsed >= nBuffer) {
			DBGPRT_ERR(_FT("Insufficient Slot Buffer.\n"));
			::SetLastError(ERROR_INSUFFICIENT_BUFFER);
			return FALSE;
		}
		
		DWORD dwDiskNumber = pDiskNumbers[i];
		DWORD dwScsiPortNumber;

		fSuccess = NdasDmGetScsiPortNumberOfDisk(dwDiskNumber, &dwScsiPortNumber);
		if (!fSuccess) {
			DBGPRT_ERR_EX(_FT("NdasDmGetScsiPortNumberOfDisk(%d) failed: "), dwDiskNumber);
			return FALSE;
		}

		DWORD dwSlotNo;
		fSuccess = NdasDmGetNdasLogDevSlotNoOfScsiPort(dwScsiPortNumber, &dwSlotNo);
		if (!fSuccess) {
			DBGPRT_ERR_EX(_FT("NdasDmGetNdasLogDevSlotNoOfScsiPort(%d) failed: "), dwScsiPortNumber);
			return FALSE;
		}

		BOOL bDuplicate(FALSE);
		for (DWORD j = 0; j < *lpdwBufferUsed; ++j) {
			if (lpdwSlotNo[j] == dwSlotNo) {
				bDuplicate = TRUE;
				break;
			}
		}

		if (!bDuplicate) {
			lpdwSlotNo[*lpdwBufferUsed] = dwSlotNo;
			(*lpdwBufferUsed)++;
		}

	}

	return TRUE;
}
Exemple #6
0
/**************************************************************************
 * DPA_Merge [COMCTL32.11]
 *
 * Merge two dynamic pointers arrays.
 *
 * PARAMS
 *     hdpa1       [I] handle to a dynamic pointer array
 *     hdpa2       [I] handle to a dynamic pointer array
 *     dwFlags     [I] flags
 *     pfnCompare  [I] pointer to sort function
 *     pfnMerge    [I] pointer to merge function
 *     lParam      [I] application specific value
 *
 * RETURNS
 *     Success: TRUE
 *     Failure: FALSE 
 *
 * NOTES
 *     No more information available yet!
 */
BOOL WINAPI DPA_Merge (HDPA hdpa1, HDPA hdpa2, DWORD dwFlags,
                       PFNDPACOMPARE pfnCompare, PFNDPAMERGE pfnMerge,
                       LPARAM lParam)
{
    INT nCount;
    LPVOID *pWork1, *pWork2;
    INT nResult, i;
    INT nIndex;

    TRACE("%p %p %08x %p %p %08lx)\n",
           hdpa1, hdpa2, dwFlags, pfnCompare, pfnMerge, lParam);

    if (IsBadWritePtr (hdpa1, sizeof(*hdpa1)))
        return FALSE;

    if (IsBadWritePtr (hdpa2, sizeof(*hdpa2)))
        return FALSE;

    if (IsBadCodePtr ((FARPROC)pfnCompare))
        return FALSE;

    if (IsBadCodePtr ((FARPROC)pfnMerge))
        return FALSE;

    if (!(dwFlags & DPAM_SORTED)) {
        TRACE("sorting dpa's!\n");
        if (hdpa1->nItemCount > 0)
        DPA_Sort (hdpa1, pfnCompare, lParam);
        TRACE ("dpa 1 sorted!\n");
        if (hdpa2->nItemCount > 0)
        DPA_Sort (hdpa2, pfnCompare, lParam);
        TRACE ("dpa 2 sorted!\n");
    }

    if (hdpa2->nItemCount < 1)
        return TRUE;

    TRACE("hdpa1->nItemCount=%d hdpa2->nItemCount=%d\n",
           hdpa1->nItemCount, hdpa2->nItemCount);


    /* working but untrusted implementation */

    pWork1 = &(hdpa1->ptrs[hdpa1->nItemCount - 1]);
    pWork2 = &(hdpa2->ptrs[hdpa2->nItemCount - 1]);

    nIndex = hdpa1->nItemCount - 1;
    nCount = hdpa2->nItemCount - 1;

    do
    {
        if (nIndex < 0) {
            if ((nCount >= 0) && (dwFlags & DPAM_UNION)) {
                /* Now insert the remaining new items into DPA 1 */
                TRACE("%d items to be inserted at start of DPA 1\n",
                      nCount+1);
                for (i=nCount; i>=0; i--) {
                    PVOID ptr;

                    ptr = (pfnMerge)(DPAMM_INSERT, *pWork2, NULL, lParam);
                    if (!ptr)
                        return FALSE;
                    DPA_InsertPtr (hdpa1, 0, ptr);
                    pWork2--;
                }
            }
            break;
        }
        nResult = (pfnCompare)(*pWork1, *pWork2, lParam);
        TRACE("compare result=%d, dpa1.cnt=%d, dpa2.cnt=%d\n",
              nResult, nIndex, nCount);

        if (nResult == 0)
        {
            PVOID ptr;

            ptr = (pfnMerge)(DPAMM_MERGE, *pWork1, *pWork2, lParam);
            if (!ptr)
                return FALSE;

            nCount--;
            pWork2--;
            *pWork1 = ptr;
            nIndex--;
            pWork1--;
        }
        else if (nResult > 0)
        {
            /* item in DPA 1 missing from DPA 2 */
            if (dwFlags & DPAM_INTERSECT)
            {
                /* Now delete the extra item in DPA1 */
                PVOID ptr;

                ptr = DPA_DeletePtr (hdpa1, nIndex);

                (pfnMerge)(DPAMM_DELETE, ptr, NULL, lParam);
            }
            nIndex--;
            pWork1--;
        }
        else
        {
            /* new item in DPA 2 */
            if (dwFlags & DPAM_UNION)
            {
                /* Now insert the new item in DPA 1 */
                PVOID ptr;

                ptr = (pfnMerge)(DPAMM_INSERT, *pWork2, NULL, lParam);
                if (!ptr)
                    return FALSE;
                DPA_InsertPtr (hdpa1, nIndex+1, ptr);
            }
            nCount--;
            pWork2--;
        }

    }
    while (nCount >= 0);

    return TRUE;
}
Exemple #7
0
BOOL AwtPrintControl::CreateDevModeAndDevNames(PRINTDLG *ppd,
					       LPTSTR pPrinterName,
					       LPTSTR pPortName)
{
    DWORD cbNeeded = 0;
    LPBYTE pPrinter = NULL;
    BOOL retval = FALSE;
    HANDLE hPrinter;

    try {
        if (!::OpenPrinter(pPrinterName, &hPrinter, NULL)) {
	    goto done;
	}
	VERIFY(::GetPrinter(hPrinter, 2, NULL, 0, &cbNeeded) == 0);
	if (::GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
	    goto done;
	}
	pPrinter = new BYTE[cbNeeded];
	if (!::GetPrinter(hPrinter, 2, pPrinter, cbNeeded, &cbNeeded)) {
	    goto done;
	}
	PRINTER_INFO_2 *info2 = (PRINTER_INFO_2 *)pPrinter;

	// Create DEVMODE, if it exists.
	if (info2->pDevMode != NULL) {
	    size_t devmodeSize =
	        sizeof(DEVMODE) + info2->pDevMode->dmDriverExtra;
	    ppd->hDevMode = ::GlobalAlloc(GHND, devmodeSize);
	    if (ppd->hDevMode == NULL) {
	        throw std::bad_alloc();
	    }
	    DEVMODE *devmode = (DEVMODE *)::GlobalLock(ppd->hDevMode);
	    DASSERT(!::IsBadWritePtr(devmode, devmodeSize));
	    memcpy(devmode, info2->pDevMode, devmodeSize);
	    VERIFY(::GlobalUnlock(ppd->hDevMode) == 0);
	    DASSERT(::GetLastError() == NO_ERROR);
	}

	// Create DEVNAMES.
	if (IS_NT) {
	    if (pPortName != NULL) {
	        info2->pPortName = pPortName;
	    } else if (info2->pPortName != NULL) {
	        // pPortName may specify multiple ports. We only want one.
	        info2->pPortName = _tcstok(info2->pPortName, TEXT(","));
	    }
	}

	size_t lenDriverName = ((info2->pDriverName != NULL)
				    ? _tcslen(info2->pDriverName)
				    : 0) + 1;
	size_t lenPrinterName = ((pPrinterName != NULL)
				     ? _tcslen(pPrinterName)
				     : 0) + 1;
	size_t lenOutputName = ((info2->pPortName != NULL)
				    ? _tcslen(info2->pPortName)
				    : 0) + 1;
	size_t devnameSize= sizeof(DEVNAMES) +
			lenDriverName*sizeof(TCHAR) +
			lenPrinterName*sizeof(TCHAR) +
			lenOutputName*sizeof(TCHAR);
	
	ppd->hDevNames = ::GlobalAlloc(GHND, devnameSize);
	if (ppd->hDevNames == NULL) {
	    throw std::bad_alloc();
	}

	DEVNAMES *devnames =
	    (DEVNAMES *)::GlobalLock(ppd->hDevNames);
	DASSERT(!IsBadWritePtr(devnames, devnameSize));
	LPTSTR lpcDevnames = (LPTSTR)devnames;

	// note: all sizes are in characters, not in bytes
	devnames->wDriverOffset = sizeof(DEVNAMES)/sizeof(TCHAR);
	devnames->wDeviceOffset = 
	    static_cast<WORD>(sizeof(DEVNAMES)/sizeof(TCHAR) + lenDriverName);
	devnames->wOutputOffset =
	    static_cast<WORD>(sizeof(DEVNAMES)/sizeof(TCHAR) + lenDriverName + lenPrinterName);
	if (info2->pDriverName != NULL) {
	    _tcscpy(lpcDevnames + devnames->wDriverOffset, info2->pDriverName);
	} else {
	    *(lpcDevnames + devnames->wDriverOffset) = _T('\0');
	}
	if (pPrinterName != NULL) {
	    _tcscpy(lpcDevnames + devnames->wDeviceOffset, pPrinterName);
	} else {
	    *(lpcDevnames + devnames->wDeviceOffset) = _T('\0');
	}
	if (info2->pPortName != NULL) {
	    _tcscpy(lpcDevnames + devnames->wOutputOffset, info2->pPortName);
	} else {
	    *(lpcDevnames + devnames->wOutputOffset) = _T('\0');
	}
	VERIFY(::GlobalUnlock(ppd->hDevNames) == 0);
	DASSERT(::GetLastError() == NO_ERROR);
    } catch (std::bad_alloc&) {
        if (ppd->hDevNames != NULL) {
	    VERIFY(::GlobalFree(ppd->hDevNames) == NULL);
	    ppd->hDevNames = NULL;
	}
	if (ppd->hDevMode != NULL) {
	    VERIFY(::GlobalFree(ppd->hDevMode) == NULL);
	    ppd->hDevMode = NULL;
	}
	delete [] pPrinter;
	VERIFY(::ClosePrinter(hPrinter));
	hPrinter = NULL;
	throw;
    }

    retval = TRUE;

done:
    delete [] pPrinter;
    if (hPrinter) {
        VERIFY(::ClosePrinter(hPrinter));
	hPrinter = NULL;
    }

    return retval;
}
Exemple #8
0
BOOL CNamedPipeTransport::Receive(
	LPVOID lpBuffer, DWORD cbToReceive, LPDWORD lpcbReceived,
	LPOVERLAPPED lpOverlapped, LPDWORD lpdwFlags)
{
	// AUTOFUNCTRACE();

	_ASSERTE(!IsBadWritePtr(lpBuffer, cbToReceive));
	_ASSERTE(!IsBadWritePtr(lpcbReceived, sizeof(DWORD)));
	_ASSERTE(NULL == lpOverlapped ||
		!IsBadWritePtr(lpOverlapped, sizeof(OVERLAPPED)) &&
		NULL != lpOverlapped->hEvent &&
		INVALID_HANDLE_VALUE != lpOverlapped->hEvent);
		
	UNREFERENCED_PARAMETER(lpdwFlags);

	// handling sending zero-byte packet
	if (cbToReceive == 0) {
		*lpcbReceived = 0;
		if (lpOverlapped) {
			BOOL fSuccess = ::SetEvent(lpOverlapped->hEvent);
			_ASSERT(fSuccess);
		}
		return TRUE;
	}

	// we have to receive by the request size

	DPInfo(_FT("Reading %d bytes.\n"), cbToReceive);

	BOOL fSuccess(FALSE);
	DWORD cbCurReceived(0), cbCurToReceive(cbToReceive);
	LPBYTE lpCurBuffer = reinterpret_cast<LPBYTE>(lpBuffer);
	*lpcbReceived = 0;

	while (cbCurToReceive > 0) {

		fSuccess = ::ReadFile(m_hPipe, lpBuffer, cbCurToReceive, &cbCurReceived, lpOverlapped);
		if (!fSuccess && NULL != lpOverlapped && ::GetLastError() != ERROR_IO_PENDING) {
			break;
		}

		if (lpOverlapped) {
			// wait until timeout (to prevent indefinite waiting...)
			DWORD dwWaitResult = ::WaitForSingleObject(lpOverlapped->hEvent, TRANSMIT_TIMEOUT);
			if (dwWaitResult != WAIT_OBJECT_0) {
				switch (dwWaitResult) {
				case WAIT_TIMEOUT:		::SetLastError(WAIT_TIMEOUT);
				case WAIT_ABANDONED:	::SetLastError(WAIT_ABANDONED);
				default:	break;
				}
				return FALSE;
			}
			fSuccess = ::GetOverlappedResult(m_hPipe, lpOverlapped, &cbCurReceived, TRUE);
			if (!fSuccess && ::GetLastError() != ERROR_IO_PENDING) {
				break;
			}
		}

		cbCurToReceive -= cbCurReceived;
		*lpcbReceived += cbCurReceived;
		lpCurBuffer += cbCurReceived;

	}

	DPInfo(_FT("Read %d bytes.\n"), *lpcbReceived);

	return fSuccess;
}
Exemple #9
0
BOOL CNamedPipeTransport::Send(
	LPCVOID lpBuffer, DWORD cbToSend, LPDWORD lpcbSent, 
	LPOVERLAPPED lpOverlapped, DWORD dwFlags)
{
//	AUTOFUNCTRACE();

	_ASSERTE(!IsBadReadPtr(lpBuffer, cbToSend));
	_ASSERTE(!IsBadWritePtr(lpcbSent, sizeof(DWORD)));
	_ASSERTE(
		(NULL == lpOverlapped) || 
		(!IsBadReadPtr(lpOverlapped, sizeof(OVERLAPPED)) &&
		NULL != lpOverlapped->hEvent &&
		INVALID_HANDLE_VALUE != lpOverlapped->hEvent));

	UNREFERENCED_PARAMETER(dwFlags);

	// handling sending zero-byte packet
	if (cbToSend == 0) {
		*lpcbSent = 0;
		if (lpOverlapped) {
			BOOL fSuccess = ::SetEvent(lpOverlapped->hEvent);
			_ASSERT(fSuccess);
		}
		DPInfo(_FT("Sending 0 byte ignored\n"));
		return TRUE;
	}

	DPInfo(_FT("Sending %d bytes.\n"), cbToSend);

	BOOL fSuccess(FALSE);
	DWORD cbCurSent(0), cbCurToSend(cbToSend);
	const BYTE* lpCurBuffer = reinterpret_cast<const BYTE*>(lpBuffer);
	*lpcbSent = 0;

	while (cbCurToSend > 0) {

		fSuccess = ::WriteFile(m_hPipe, lpBuffer, cbCurToSend, &cbCurSent, lpOverlapped);
		if (!fSuccess && NULL != lpOverlapped && ::GetLastError() != ERROR_IO_PENDING) {
			break;
		}

		if (lpOverlapped) {
			// wait until timeout (to prevent indefinite waiting...)
			DWORD dwWaitResult = ::WaitForSingleObject(lpOverlapped->hEvent, TRANSMIT_TIMEOUT);
			if (dwWaitResult != WAIT_OBJECT_0) {
				switch (dwWaitResult) {
				case WAIT_TIMEOUT:		::SetLastError(WAIT_TIMEOUT);
				case WAIT_ABANDONED:	::SetLastError(WAIT_ABANDONED);
				default:	break;
				}
				return FALSE;
			}
			fSuccess = ::GetOverlappedResult(m_hPipe, lpOverlapped, &cbCurSent, TRUE);
			if (!fSuccess && ::GetLastError() != ERROR_IO_PENDING) {
				break;
			}
		}

		cbCurToSend -= cbCurSent;
		*lpcbSent += cbCurSent;
		lpCurBuffer += cbCurSent;

	}

	DPInfo(_FT("Sent %d bytes.\n"), *lpcbSent);

	return fSuccess;
}
Exemple #10
0
NDUPDATE_API
BOOL
WINAPI
NdasUpdateGetUpdateInfo(
	IN IBindStatusCallback* pBSC,
	IN LPCTSTR szBaseURL,
	IN PNDUPDATE_SYSTEM_INFO pSystemInformation,
	OUT PNDUPDATE_UPDATE_INFO_V2 pUpdateInformation)
{
	BOOL  fSuccess = FALSE;
	HRESULT hr = E_FAIL;

	DBGPRT_INFO(_FT("BaseURL: %s\n"), szBaseURL);

	TCHAR szUpdateURL[NDUPDATE_MAX_URL];

	if (IsBadReadPtr(pSystemInformation, sizeof(NDUPDATE_SYSTEM_INFO)) ||
		IsBadWritePtr(pUpdateInformation, sizeof(NDUPDATE_UPDATE_INFO_V2)))
	{
		SetLastError(ERROR_INVALID_PARAMETER);
		return FALSE;
	}

	// create URL
	hr = StringCchPrintf(
		szUpdateURL,
		NDUPDATE_MAX_URL,
		_T("%s?REV=%d&PLATFORM=%d&MAJOR=%d&MINOR=%d&BUILD=%d&PRIV=%d&VENDOR=%d&LANGUAGESET=%d&CT=%08X"),
		szBaseURL,
		NDAS_UPDATE_REV,
		pSystemInformation->dwPlatform,
		pSystemInformation->ProductVersion.wMajor,
		pSystemInformation->ProductVersion.wMinor,
		pSystemInformation->ProductVersion.wBuild,
		pSystemInformation->ProductVersion.wPrivate,
		pSystemInformation->dwVendor,
		pSystemInformation->dwLanguageSet,
		GetTickCount());

	if (FAILED(hr)) {
		DBGPRT_ERR_EX(_FT("Making URL failed, too long?, hr=%08X: "), hr);
		return FALSE;
	}

	DBGPRT_INFO(_FT("UpdateURL: %s\n"), szUpdateURL);

	TCHAR szDownloadedFileName[MAX_PATH] = {0};
	hr = ::URLDownloadToCacheFile(
		NULL,
		szUpdateURL,
		szDownloadedFileName,
		sizeof(szDownloadedFileName),
		0,
		pBSC);

	if (FAILED(hr)) {
		DBGPRT_ERR_EX(_FT("Downloading a file failed.\n"));
		::SetLastError(hr);
		return FALSE;
	}

	DBGPRT_INFO(_FT("Downloaded to %s.\n"), szDownloadedFileName);

	TCHAR szINIFileName[MAX_PATH];
	TCHAR szINIString[NDUPDATE_STRING_SIZE] = {0};  
	UINT uiINIValue;

	GetPrivateProfileString(
		UPDATER_SECTION, 
		_T("CLASS"), 
		_T(""), 
		szINIString, 
		NDUPDATE_STRING_SIZE, 
		szDownloadedFileName);

	DBGPRT_INFO(_T("UPDATER CLASS: %s\n"), szINIString);

	if (0 != lstrcmpi(szINIString, UPDATE_CLASS_STRING)) {
		SetLastError(NDUPDATE_ERROR_INVALID_SERVER_RESPONSE);
		return FALSE;
	}

	uiINIValue = ::GetPrivateProfileInt(
		UPDATER_SECTION, 
		_T("REVISION"), 
		0, 
		szDownloadedFileName);

	DBGPRT_INFO(_T("UPDATER REVISION: %d\n"), uiINIValue);

	if (NDAS_UPDATE_REV != uiINIValue) {
		SetLastError(NDUPDATE_ERROR_INVALID_UPDATE_VERSION_FROM_SERVER);
		return FALSE;
	}

	// read patch information
	uiINIValue = ::GetPrivateProfileInt(
		UPDATE_SECTION, 
		_T("NEED_UPDATE"), 
		0xFFFFFFFF,
		szDownloadedFileName);

	DBGPRT_INFO(_T("UPDATE NEED_UPDATE: %d\n"), uiINIValue);

	if (0xFFFFFFFF == uiINIValue) {
		SetLastError(NDUPDATE_ERROR_INVALID_SERVER_RESPONSE);
		return FALSE;
	}

	//
	// we should return TRUE even if update is not required!
	//
	if (0 == uiINIValue) {
		pUpdateInformation->fNeedUpdate = FALSE;
		return TRUE;
	}

	//
	// Update!
	//

	pUpdateInformation->fNeedUpdate = TRUE;

	uiINIValue = GetPrivateProfileInt(
		UPDATE_SECTION, 
		_T("PRODUCT_VERSION_MAJOR"),
		0xFFFFFFFF, 
		szDownloadedFileName);

	if (0xFFFFFFFF == uiINIValue) {
		SetLastError(NDUPDATE_ERROR_INVALID_SERVER_RESPONSE);
		return FALSE;
	}

	pUpdateInformation->ProductVersion.wMajor = (WORD) uiINIValue;

	uiINIValue = GetPrivateProfileInt(
		UPDATE_SECTION, 
		_T("PRODUCT_VERSION_MINOR"), 
		0xFFFFFFFF, 
		szDownloadedFileName);

	if (0xFFFFFFFF == uiINIValue) {
		SetLastError(NDUPDATE_ERROR_INVALID_SERVER_RESPONSE);
		return FALSE;
	}

	pUpdateInformation->ProductVersion.wMinor = (WORD) uiINIValue;

	uiINIValue = GetPrivateProfileInt(
		UPDATE_SECTION, 
		_T("PRODUCT_VERSION_BUILD"), 
		0xFFFFFFFF, 
		szDownloadedFileName);

	if (0xFFFFFFFF == uiINIValue) {
		SetLastError(NDUPDATE_ERROR_INVALID_SERVER_RESPONSE);
		return FALSE;
	}

	pUpdateInformation->ProductVersion.wBuild = (WORD) uiINIValue;

	uiINIValue = GetPrivateProfileInt(
		UPDATE_SECTION, 
		_T("PRODUCT_VERSION_PRIVATE"), 
		0xFFFFFFFF, 
		szDownloadedFileName);

	if (0xFFFFFFFF == uiINIValue) {
		SetLastError(NDUPDATE_ERROR_INVALID_SERVER_RESPONSE);
		return FALSE;
	}

	pUpdateInformation->ProductVersion.wPrivate = (WORD) uiINIValue;

	//
	// Update File URL
	//

	uiINIValue = GetPrivateProfileInt(
		UPDATE_SECTION, _T("FILESIZE"), 
		0xFFFFFFFF, szDownloadedFileName);

	if (0xFFFFFFFF == uiINIValue) {
		SetLastError(NDUPDATE_ERROR_INVALID_SERVER_RESPONSE);
		return FALSE;
	}

	pUpdateInformation->dwFullSetupFileSize = (DWORD) uiINIValue;

	pUpdateInformation->szFullSetupFileURL[0] = _T('\0');

	(VOID) GetPrivateProfileString(
		UPDATE_SECTION, _T("FILE_URL"), _T(""), 
		pUpdateInformation->szFullSetupFileURL, 
		NDUPDATE_MAX_URL, szDownloadedFileName);

	if (_T('\0') == pUpdateInformation->szFullSetupFileURL[0]) {
		SetLastError(NDUPDATE_ERROR_INVALID_SERVER_RESPONSE);
		return FALSE;
	}

	(VOID) GetPrivateProfileString(
		UPDATE_SECTION,	_T("FILENAME"),	_T(""),
		pUpdateInformation->szFullSetupFileName, 
		MAX_PATH, szDownloadedFileName);

	if (_T('\0') == pUpdateInformation->szFullSetupFileName[0]) {
		SetLastError(NDUPDATE_ERROR_INVALID_SERVER_RESPONSE);
		return FALSE;
	}

	//
	// Update Reference File URL
	//
	pUpdateInformation->szRefURL[0] = _T('\0');

	GetPrivateProfileString(
		UPDATE_SECTION, 
		_T("REF_URL"), 
		_T(""), 
		pUpdateInformation->szRefURL, 
		NDUPDATE_MAX_URL, 
		szDownloadedFileName);

	if (_T('\0') == pUpdateInformation->szRefURL[0]) {
		SetLastError(NDUPDATE_ERROR_INVALID_SERVER_RESPONSE);
		return FALSE;
	}

	//
	// Patch File URL if available
	//

	GetPrivateProfileString(
		UPDATE_SECTION, _T("PATCH_FILE_URL"), _T(""), 
		pUpdateInformation->szPatchFileURL, 
		NDUPDATE_MAX_URL, szDownloadedFileName);

	GetPrivateProfileString(
		UPDATE_SECTION, _T("PATCH_FILE_NAME"), _T(""),
		pUpdateInformation->szPatchFileName,
		MAX_PATH, szDownloadedFileName);

	pUpdateInformation->dwPatchFileSize = GetPrivateProfileInt(
		UPDATE_SECTION, _T("PATCH_FILE_SIZE"), 
		0, szDownloadedFileName);

	if (0 == pUpdateInformation->dwPatchFileSize) 
	{
		// ignorable error
		pUpdateInformation->szPatchFileURL[0] = _T('\0');
		pUpdateInformation->szPatchFileName[0] = _T('\0');
		pUpdateInformation->dwPatchFileSize = 0;
	}

	//
	// SmallSetup File URL
	//

	// URL
	GetPrivateProfileString(
		UPDATE_SECTION, _T("SMALL_SETUP_FILE_URL"), _T(""), 
		pUpdateInformation->szSmallSetupFileURL, 
		NDUPDATE_MAX_URL, szDownloadedFileName);

	// FileName
	GetPrivateProfileString(
		UPDATE_SECTION, _T("SMALL_SETUP_FILE_NAME"), _T(""),
		pUpdateInformation->szSmallSetupFileName,
		MAX_PATH, szDownloadedFileName);

	// FileSize
	pUpdateInformation->dwPatchFileSize = (DWORD) GetPrivateProfileInt(
		UPDATE_SECTION, _T("SMALL_SETUP_FILE_SIZE"), 
		0, szDownloadedFileName);

	if (0 == pUpdateInformation->dwPatchFileSize) {
		// ignorable error
		pUpdateInformation->szSmallSetupFileURL[0] = _T('\0');
		pUpdateInformation->szSmallSetupFileName[0] = _T('\0');
	}

	// Failure will retain the downloaded file to check error!
	// Ignore error on delete

	(VOID) DeleteUrlCacheEntry(szDownloadedFileName);

	return TRUE;
}
Exemple #11
0
HRESULT WINAPI
Main_DirectDraw_GetDeviceIdentifier7(LPDDRAWI_DIRECTDRAW_INT This,
                                     LPDDDEVICEIDENTIFIER2 pDDDI, DWORD dwFlags)
{
    HRESULT retVal = DDERR_INVALIDPARAMS;

    BOOL found = FALSE;
    DWORD iDevNum = 0;
    DISPLAY_DEVICEA DisplayDeviceA;
    HKEY hKey;
    DWORD lpType = 0;
    DWORD strSize = MAX_DDDEVICEID_STRING;
    char *pdest;
    char* pcCnvEnd;
    long *lpdata;

    DX_WINDBG_trace();

    EnterCriticalSection( &ddcs );

    _SEH2_TRY
    {
        if ( (IsBadWritePtr( pDDDI, sizeof(DDDEVICEIDENTIFIER2) ) ) ||
             (dwFlags & ~DDGDI_GETHOSTIDENTIFIER))
        {
            retVal = DDERR_INVALIDPARAMS;
            _SEH2_LEAVE;
        }

        /* now we can start getting the driver data */

        while (1)
        {
            ZeroMemory(&DisplayDeviceA,sizeof(DISPLAY_DEVICEA));

            DisplayDeviceA.cb = sizeof(DISPLAY_DEVICEA);

            if ( EnumDisplayDevicesA( NULL, iDevNum, &DisplayDeviceA, 0) == 0)
            {
                retVal = DDERR_INVALIDPARAMS;
                break;
            }

            if (_stricmp(DisplayDeviceA.DeviceName, This->lpLcl->lpGbl->cDriverName) != 0)
            {
                /* if we got another device like hardware mpeg decoder or video card or another drv */
                found = TRUE;
            }
            else if (DisplayDeviceA.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE)
            {
                /* double check if it primary driver we just found */
                if (!_stricmp( This->lpLcl->lpGbl->cDriverName, "DISPLAY"))
                {
                    /* yeah we found it */
                    found = TRUE;
                }
            }

            if (found == TRUE)
            {
                /* we found our driver now we start setup it */
                if (!_strnicmp(DisplayDeviceA.DeviceKey,"\\REGISTRY\\Machine\\",18))
                {
                    if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, &DisplayDeviceA.DeviceKey[18], 0, KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS )
                    {

                        if (RegQueryValueExA(hKey, "InstalledDisplayDrivers",0, &lpType, (LPBYTE)pDDDI->szDriver, &strSize) != ERROR_SUCCESS)
                        {
                            ZeroMemory(pDDDI->szDriver,MAX_DDDEVICEID_STRING);
                        }
                        else
                        {
                            strcat(pDDDI->szDriver,".dll");
                        }
                        RegCloseKey(hKey);
                    }

                    strcpy( pDDDI->szDescription, DisplayDeviceA.DeviceString);
                    pDDDI->liDriverVersion.HighPart = 0;
                    pDDDI->liDriverVersion.LowPart = 0;

                    pdest = strstr(DisplayDeviceA.DeviceID,"REV_");
                    pDDDI->dwRevision =  strtol ( &pdest[4], &pcCnvEnd, 16);

                    pdest = strstr(DisplayDeviceA.DeviceID,"SUBSYS_");
                    pDDDI->dwSubSysId =  strtol ( &pdest[7], &pcCnvEnd, 16);

                    pdest = strstr(DisplayDeviceA.DeviceID,"DEV_");
                    pDDDI->dwDeviceId = strtol ( &pdest[4], &pcCnvEnd, 16);

                    pdest = strstr(DisplayDeviceA.DeviceID,"VEN_");
                    pDDDI->dwVendorId =strtol ( &pdest[4], &pcCnvEnd, 16);

                    /* Count out the guidDeviceIdentifier */
                    memcpy(&pDDDI->guidDeviceIdentifier, &CLSID_DirectDraw,sizeof(GUID));

                    pDDDI->guidDeviceIdentifier.Data1 ^= pDDDI->dwVendorId;

                    lpdata = (long *)&pDDDI->guidDeviceIdentifier.Data2;
                    *lpdata ^= pDDDI->dwDeviceId;

                    lpdata = (long *)&pDDDI->guidDeviceIdentifier.Data4;
                    *lpdata = (*lpdata ^ pDDDI->dwSubSysId) ^ pDDDI->liDriverVersion.LowPart;

                    lpdata = (long *)&pDDDI->guidDeviceIdentifier.Data4[4];
                    *lpdata = (*lpdata ^ pDDDI->dwRevision) ^ pDDDI->liDriverVersion.HighPart;

                    /* FIXME pDDDI->dwWHQLLevel
                     * we leave this with no informations, I do not known
                     * if program care for it, I mark this api done, and
                     * tested, no bugs was found in it
                     */
                    pDDDI->dwWHQLLevel = 0;
                    retVal = DD_OK;
                }

                break;
            }

            iDevNum++;
         }

    }
    _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
    {
        retVal = DD_FALSE;
    }
    _SEH2_END;

    LeaveCriticalSection( &ddcs );
    return retVal;
}
Exemple #12
0
/***********************************************************************
 *             IsBadHugeWritePtr   (KERNEL32.@)
 *
 * Check for write access on a memory block.
 *
 * PARAMS
 *  ptr  [I] Address of memory block.
 *  size [I] Size of block.
 *
 * RETURNS
 *  Success: TRUE.
 *	Failure: FALSE. Process has write access to entire block.
 */
BOOL WINAPI IsBadHugeWritePtr( LPVOID ptr, UINT size )
{
    return IsBadWritePtr( ptr, size );
}
Exemple #13
0
BOOL 
WINAPI
NdasDmGetNdasLogDevSlotNoOfScsiPort(
	LPCWSTR wszDbccName, LPDWORD lpdwSlotNo)
{
	_ASSERTE(!IsBadWritePtr(lpdwSlotNo, sizeof(DWORD)));
	_ASSERTE(!IsBadStringPtr(wszDbccName, _MAX_PATH));

	DBGPRT_INFO(_FT("NdasDmGetNdasLogDevSlotNoOfScsiPort got %s.\n"), wszDbccName);

	//
	// extract the last string between '&' and '#', which has slot number and unitdisk numer
	//
	// example of dbcc_name at logical device slot no 10
	//
	// \\?\lanscsibus#netdisk_v0#1&1a590e2c&5&10#{2accfe60-c130-11d2-b082-00a0c91efb8b}
	//                                       ^^^^

	if (!NdasDmIsLANSCSIPortInterface(wszDbccName)) {
		DBGPRT_INFO(_FT("Non-LANSCSI Port Interface Name.\n"));
		return FALSE;
	}

	// skip LANSCSIIDDEV_IFDW
	LPCWSTR pwszLeftBound = &wszDbccName[LANSCSI_DEV_IFIDW_LEN];

	// pwszLeftBound now points to 
	// \\?\lanscsibus#netdisk_v0#1&1a590e2c&5&10#{2accfe60-c130-11d2-b082-00a0c91efb8b}
	//                ^
	//                left bound

	while (*pwszLeftBound != L'#') {
		if (*pwszLeftBound == L'\0') {
			DBGPRT_ERR(_FT("Slot Number Parse Error at left bound!\n"));
			return FALSE; // invalid!
		}
		++pwszLeftBound;
	}

	// pwszpwszLeftBound now points to 
	// \\?\lanscsibus#netdisk_v0#1&1a590e2c&5&10#{2accfe60-c130-11d2-b082-00a0c91efb8b}
	//                          ^          
	//                      left bound     

	LPCWSTR pwszRightBound = pwszLeftBound + 1;
	while (*pwszRightBound != L'#') {
		if (*pwszRightBound == L'\0') {
			DBGPRT_ERR(_FT("Slot Number Parse Error at right bound!\n"));
			return FALSE; // invalid!
		}
		++pwszRightBound;
	}

	// pwszRightBound now points to 
	// \\?\lanscsibus#netdisk_v0#1&1a590e2c&5&10#{2accfe60-c130-11d2-b082-00a0c91efb8b}
	//                          ^               ^
	//                      left bound     right bound
	
	LPCWSTR pwszSlotStart = pwszRightBound - 1;
	while (*pwszSlotStart != L'&') {
		if (pwszSlotStart <= pwszLeftBound) {
			DBGPRT_ERR(_FT("Slot Number Parse Error at slot start bound!\n"));
			return FALSE;
		}
		--pwszSlotStart;
	}

	// pwszRightBound now points to 
	// \\?\lanscsibus#netdisk_v0#1&1a590e2c&5&10#{2accfe60-c130-11d2-b082-00a0c91efb8b}
	//                          ^            ^  ^
	//                      left bound       |  right bound
    //                                      slot start

	if (pwszSlotStart + 1 == pwszRightBound) {
		// &# -> no slot number
		DBGPRT_ERR(_FT("Slot Number Parse Error at slot start bound!\n"));
		return FALSE;
	}

	WCHAR szSlotNo[10];
	LPCWSTR pch = pwszSlotStart + 1;
	DWORD i(0);
	for (; pch < pwszRightBound && i < 9; ++i, ++pch) {
		szSlotNo[i] = *pch;
	}
	szSlotNo[i] = L'\0';

	DWORD dwSlotNo = _wtoi(szSlotNo);
	if (dwSlotNo == 0) {
		DBGPRT_ERR(_FT("Invalid slot number (%s) -> (%d)\n"), szSlotNo, dwSlotNo);
		return FALSE;
	}

	*lpdwSlotNo = dwSlotNo;

	DBGPRT_INFO(_FT("Slot no is %d.\n"), dwSlotNo);
	return TRUE;

}
Exemple #14
0
BOOL 
WINAPI
NdasDmGetDriveNumberOfVolume(
	HANDLE hVolume,
	LPDWORD lpdwFirstDriverLetter)
{
	_ASSERTE(INVALID_HANDLE_VALUE != hVolume);
	_ASSERTE(NULL != hVolume);
	_ASSERTE(!IsBadWritePtr(lpdwFirstDriverLetter, sizeof(DWORD)));

	BOOL fSuccess(FALSE);

	VOLUME_NUMBER volumeNumber ;

	//
	// find a volume number for hFile
	//
	DWORD cbReturned;
	fSuccess = ::DeviceIoControl(
		hVolume,
		IOCTL_VOLUME_QUERY_VOLUME_NUMBER, 
		NULL,
		0,							
		(LPVOID) &volumeNumber,                   
		(DWORD) sizeof(VOLUME_NUMBER),             
		&cbReturned,
		NULL);

	if (!fSuccess) {
		DBGPRT_ERR_EX(_FT("DeviceIoControl(IOCTL_VOLUME_QUERY_VOLUME_NUMBER) failed: "));
		return FALSE;
	}

	DBGPRT_INFO(_FT("Volume Number: %d\n"), volumeNumber.VolumeNumber);

	// VolumeManagerName is 8 wide-chars without null
	DBGPRT_INFO(_FT("Volume Manager Name: %c%c%c%c%c%c%c%c\n"), 
		(TCHAR)volumeNumber.VolumeManagerName[0], (TCHAR)volumeNumber.VolumeManagerName[1],
		(TCHAR)volumeNumber.VolumeManagerName[2], (TCHAR)volumeNumber.VolumeManagerName[3],
		(TCHAR)volumeNumber.VolumeManagerName[4], (TCHAR)volumeNumber.VolumeManagerName[5],
		(TCHAR)volumeNumber.VolumeManagerName[6], (TCHAR)volumeNumber.VolumeManagerName[7]);

	DWORD dwLogicalDriveSet = ::GetLogicalDrives() ;
	if(dwLogicalDriveSet == 0) {
		DBGPRT_ERR_EX(_FT("GetLogicalDrivers() failed: "));
		return FALSE ;
	}

	//
	//	go through every drive letter from 1 (to skip drive A:)
	//
	for(DWORD i = 1 ; i < 26 ; ++i) {

		if( (dwLogicalDriveSet & ( 1 << i )) == 0 ) 
			continue ;

		ULONG vn;
		fSuccess = NdasDmGetVolumeNumberOfDriveLetter(i, &vn) ;
		if(!fSuccess) 
			continue ;

		if(volumeNumber.VolumeNumber == vn) {
			*lpdwFirstDriverLetter = i ;
			return TRUE ;
		}
	}

	return FALSE ;
	
}
Exemple #15
0
HRESULT PasswordUtil_Check(LPCWSTR password, LPCWSTR salt, LPCWSTR passwordHash, BOOL* pResult)
{
	if(IsBadStringPtrW(password,512))
		return E_INVALIDARG;
	if(IsBadStringPtrW(salt,512))
		return E_INVALIDARG;
	if(IsBadStringPtrW(passwordHash,512))
		return E_INVALIDARG;

	if(IsBadWritePtr(pResult,sizeof(BOOL*)))
		return E_INVALIDARG;

	*pResult = FALSE;

	HRESULT hr = S_OK;

	HCRYPTPROV hProv = NULL;
	HCRYPTHASH hHash = NULL;

	WCHAR saltAndPwd[1024] = L"";

	wcsncat_s(saltAndPwd, 1024, password, 512);
	wcsncat_s(saltAndPwd, 1024, L"$",1);
	wcsncat_s(saltAndPwd, 1024, salt, 511);

	DWORD dwFlags = CRYPT_SILENT|CRYPT_MACHINE_KEYSET;
	TCHAR szContainer[50] = _T("{BDECD56B-6D48-4add-9AEE-265D537408DF}");

	CString auditMessage;

	BOOL bCreated = FALSE;

	if(!CryptAcquireContext(&hProv, szContainer, MS_ENHANCED_PROV, PROV_RSA_FULL, dwFlags))
	{
		hr = HRESULT_FROM_WIN32(GetLastError());

		if(hr==0x80090016L) // Key Not Found
		{
			bCreated = TRUE;

			if(!CryptAcquireContext(&hProv, szContainer, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_NEWKEYSET|dwFlags))
			{
				hr = HRESULT_FROM_WIN32(GetLastError());

				if(hr == 0x8009000FL) // Key Exists
				{
					if(CryptAcquireContext(&hProv, szContainer, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_DELETEKEYSET|dwFlags))
					{
						hr = S_OK;

						if(!CryptAcquireContext(&hProv, szContainer, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_NEWKEYSET|dwFlags))
						{
							hr = HRESULT_FROM_WIN32(GetLastError());
						}
						else
						{
							hr = S_OK;
						}
					}
					else
					{
						hr = HRESULT_FROM_WIN32(GetLastError());
					}
				}
				else
				{
					hr = S_OK;
				}
			}
			else
			{
				hr = S_OK;
			}
		}
	}

	if(SUCCEEDED(hr))
	{
		if(bCreated)
		{
			// Set DACL for this container to allow full control for everyone and for local system.
			PSECURITY_DESCRIPTOR pSd = NULL;
			LPBYTE pbDacl = NULL;

			HRESULT hr2 = CreateSecurityDescriptor(&pSd, &pbDacl);
			if(SUCCEEDED(hr2))
			{
				CryptSetProvParam(hProv, PP_KEYSET_SEC_DESCR, reinterpret_cast<LPBYTE>(pSd), DACL_SECURITY_INFORMATION);
				delete pSd;
				delete[] pbDacl;
			}
		}

		if(CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash))
		{
			//auditMessage.Format(_T("Step 2-2. Error Code: 0x%X."), hr);
			//CEventLog::AddAppLog(auditMessage, FAILED_LOGIN, EVENTLOG_WARNING_TYPE);

			if(CryptHashData(hHash, (BYTE*)saltAndPwd, (DWORD)(wcslen(saltAndPwd))*2, 0))
			{
				//auditMessage.Format(_T("Step 2-3. Error Code: 0x%X."), hr);
				//CEventLog::AddAppLog(auditMessage, FAILED_LOGIN, EVENTLOG_WARNING_TYPE);

				BYTE szData[50] = {0};
				DWORD dwDataLen = 50;

				if(CryptGetHashParam(hHash, HP_HASHVAL, szData, &dwDataLen, 0))
				{
					/*auditMessage.Format(_T("Step 2-4. Error Code: 0x%X."), hr);
					CEventLog::AddAppLog(auditMessage, FAILED_LOGIN, EVENTLOG_WARNING_TYPE);*/

					CW2A ansiPasswordHash(passwordHash);

					int passwordHashLen = static_cast<int>(strlen(ansiPasswordHash));
					int nDestLen = Base64DecodeGetRequiredLength(passwordHashLen);

					CHeapPtr<BYTE> dataBuffer;
					if(dataBuffer.AllocateBytes(nDestLen))
					{
						//auditMessage.Format(_T("Step 2-5. Error Code: 0x%X."), hr);
						//CEventLog::AddAppLog(auditMessage, FAILED_LOGIN, EVENTLOG_WARNING_TYPE);

						if(Base64Decode(ansiPasswordHash, passwordHashLen, dataBuffer, &nDestLen))
						{
							size_t testHashLength = static_cast<size_t>(dwDataLen);
							size_t validHashLength = static_cast<size_t>(nDestLen);

							*pResult = (testHashLength == validHashLength && (memcmp(szData, dataBuffer, testHashLength) == 0));
						}
					}
					else
						hr = E_OUTOFMEMORY;
				}
				else
					hr = HRESULT_FROM_WIN32(GetLastError());
			}
			else
				hr = HRESULT_FROM_WIN32(GetLastError());

			CryptDestroyHash(hHash);
		}
		else
			hr = HRESULT_FROM_WIN32(GetLastError());

		CryptReleaseContext(hProv, 0);
	}
	//else
	//	hr = HRESULT_FROM_WIN32(GetLastError());

	//auditMessage.Format(_T("Step Final. Error Code: 0x%X."), hr);
	//CEventLog::AddAppLog(auditMessage, FAILED_LOGIN, EVENTLOG_WARNING_TYPE);

	return hr;
}
Exemple #16
0
void SlowVideo(char* Video,int BPP,int Width,int Height,int StrideX,int StrideY,int32_t* Result)
{
	if (BPP == 16)
	{
		int64_t t0,t1,t;
		int nv,ns;
		int Mul,Len;

		int SystemLength = 512*1024;
		char* System = (char*) malloc( SystemLength ); //hopefully cpu cache will be smaller

		if (System)
		{
			TRY_BEGIN

			if (StrideX < 0)
			{
				StrideX = -StrideX;
				Video -= StrideX * (Width - 1);
			}

			if (StrideY < 0)
			{
				StrideY = -StrideY;
				Video -= StrideY * (Height - 1);
			}

			if (StrideX > StrideY)
			{
				Swap(&Width,&Height);
				Swap(&StrideX,&StrideY);
			}		

			Len = (Width*BPP) >> 3;

			if (Len>32 && !IsBadWritePtr(Video,Len) && !IsBadReadPtr(Video,Len))
			{
				int i;
				int Rows = SystemLength / Len;

				memset(System,0,Rows*Len);
				memcpy(System,Video,Len);

				BeginCounter(&t);

				t >>= 1; // 0.5 sec

				SetThreadPriority(GetCurrentThread(),THREAD_PRIORITY_HIGHEST);

				nv=0;
				GetCounter(&t0);
				t0 += t;				
				do
				{
					for (i=0;i<Rows;++i)
						memcpy(Video,System,Len);
					nv++;
					GetCounter(&t1);
				} while (t1 < t0);

				ns=0;
				GetCounter(&t0);
				t0 += t;				
				do
				{
					for (i=0;i<Rows;i++)
						memcpy(System+i*Len,System,Len);
					ns++;
					GetCounter(&t1);
				} while (t1 < t0);

				Mul = 6;

				if (nv*Mul >= ns)
					*Result = 0; // fast
				else
					*Result = 1; // slow (video memory or in general)

				SetThreadPriority(GetCurrentThread(),THREAD_PRIORITY_NORMAL);
				EndCounter();

#ifdef BENCH
				{
					tchar_t Msg[256];
					stprintf_s(Msg,TSIZEOF(Msg),T("Video %d\nSystem %d\nResult %d"),nv,ns,*Result);
					MessageBox(NULL,Msg,T(""),MB_OK|MB_SETFOREGROUND);
				}
#endif
			}

			TRY_END

			free(System);
		}
Exemple #17
0
bool RedirectIAT( SDLLHook* DLLHook, PIMAGE_IMPORT_DESCRIPTOR pImportDesc, PVOID pBaseLoadAddr )
{
    PIMAGE_THUNK_DATA pIAT;     // Ptr to import address table
    PIMAGE_THUNK_DATA pINT;     // Ptr to import names table
    PIMAGE_THUNK_DATA pIteratingIAT;

    // Figure out which OS platform we're on
    OSVERSIONINFO osvi; 
    osvi.dwOSVersionInfoSize = sizeof(osvi);
    GetVersionEx( &osvi );

    // If no import names table, we can't redirect this, so bail
    if ( pImportDesc->OriginalFirstThunk == 0 )
        return false;

    pIAT = MakePtr( PIMAGE_THUNK_DATA, pBaseLoadAddr, pImportDesc->FirstThunk );
    pINT = MakePtr( PIMAGE_THUNK_DATA, pBaseLoadAddr, pImportDesc->OriginalFirstThunk );

    // Count how many entries there are in this IAT.  Array is 0 terminated
    pIteratingIAT = pIAT;
    unsigned cFuncs = 0;
    while ( pIteratingIAT->u1.Function )
    {
        cFuncs++;
        pIteratingIAT++;
    }

    if ( cFuncs == 0 )  // If no imported functions, we're done!
        return false;

    // These next few lines ensure that we'll be able to modify the IAT,
    // which is often in a read-only section in the EXE.
    DWORD flOldProtect, flNewProtect, flDontCare;
    MEMORY_BASIC_INFORMATION mbi;
    
    // Get the current protection attributes                            
    VirtualQuery( pIAT, &mbi, sizeof(mbi) );
    
    // remove ReadOnly and ExecuteRead attributes, add on ReadWrite flag
    flNewProtect = mbi.Protect;
    flNewProtect &= ~(PAGE_READONLY | PAGE_EXECUTE_READ);
    flNewProtect |= (PAGE_READWRITE);
    
    if ( !VirtualProtect(   pIAT, sizeof(PVOID) * cFuncs,
                            flNewProtect, &flOldProtect) )
    {
        return false;
    }

    // If the Default hook is enabled, build an array of redirection stubs in the processes memory.
    DLPD_IAT_STUB * pStubs = 0;
    if ( DLLHook->UseDefault )
    {
        // Allocate memory for the redirection stubs.  Make one extra stub at the
        // end to be a sentinel
        pStubs = new DLPD_IAT_STUB[ cFuncs + 1];
        if ( !pStubs )
            return false;
    }

    // Scan through the IAT, completing the stubs and redirecting the IAT
    // entries to point to the stubs
    pIteratingIAT = pIAT;

    while ( pIteratingIAT->u1.Function )
    {
        void* HookFn = 0;  // Set to either the SFunctionHook or pStubs.

        if ( !IMAGE_SNAP_BY_ORDINAL( pINT->u1.Ordinal ) )  // import by name
        {
            PIMAGE_IMPORT_BY_NAME pImportName = MakePtr( PIMAGE_IMPORT_BY_NAME, pBaseLoadAddr, pINT->u1.AddressOfData );

            // Iterate through the hook functions, searching for this import.
            SFunctionHook* FHook = DLLHook->Functions;
            while ( FHook->Name )
            {
                if ( lstrcmpi( FHook->Name, (char*)pImportName->Name ) == 0 )
                {
                    OutputDebugString( "Hooked function: " );
                    OutputDebugString( (char*)pImportName->Name );
                    OutputDebugString( "\n" );

                    // Save the old function in the SFunctionHook structure and get the new one.
                    FHook->OrigFn = (void*) pIteratingIAT->u1.Function;
                    HookFn = FHook->HookFn;
                    break;
                }

                FHook++;
            }

            // If the default function is enabled, store the name for the user.
            if ( DLLHook->UseDefault )
                pStubs->pszNameOrOrdinal = (DWORD)&pImportName->Name;
        }
        else
        {
            // If the default function is enabled, store the ordinal for the user.
            if ( DLLHook->UseDefault )
                pStubs->pszNameOrOrdinal = pINT->u1.Ordinal;
        }

        // If the default function is enabled, fill in the fields to the stub code.
        if ( DLLHook->UseDefault )
        {
            pStubs->data_call = (DWORD)(PDWORD)DLLHook->DefaultFn
                                - (DWORD)(PDWORD)&pStubs->instr_JMP;
            pStubs->data_JMP = *(PDWORD)pIteratingIAT - (DWORD)(PDWORD)&pStubs->count;

            // If it wasn't manually hooked, use the Stub function.
            if ( !HookFn )
                HookFn = (void*)pStubs;
        }

        // Replace the IAT function pointer if we have a hook.
        if ( HookFn )
        {
            // Cheez-o hack to see if what we're importing is code or data.
            // If it's code, we shouldn't be able to write to it
            if ( IsBadWritePtr( (PVOID)pIteratingIAT->u1.Function, 1 ) )
            {
                pIteratingIAT->u1.Function = (DWORD_PTR)HookFn;
            }
            else if ( osvi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS )
            {
                // Special hack for Win9X, which builds stubs for imported
                // functions in system DLLs (Loaded above 2GB).  These stubs are
                // writeable, so we have to explicitly check for this case
                if ( pIteratingIAT->u1.Function > (DWORD_PTR)0x80000000 )
                    pIteratingIAT->u1.Function = (DWORD_PTR)HookFn;
            }
        }

        if ( DLLHook->UseDefault )
            pStubs++;           // Advance to next stub

        pIteratingIAT++;    // Advance to next IAT entry
        pINT++;             // Advance to next INT entry
    }

    if ( DLLHook->UseDefault )
        pStubs->pszNameOrOrdinal = 0;   // Final stub is a sentinel

    // Put the page attributes back the way they were.
    VirtualProtect( pIAT, sizeof(PVOID) * cFuncs, flOldProtect, &flDontCare);
    
    return true;
}
Exemple #18
0
//-----------------------------------------------------------------------------
// Name: GetThreadContext
// Object: getting context of the given thread
//         Caller MUST call GetThreadContextFree() after having fully resumed hThread
//         DON'T WORK ON A DEBUGGED BREAKED THREAD
// Parameters :
//     in  : HANDLE hThread : handle of the thread (running or suspended thread)
//     out : LPCONTEXT lpContext : pointer to a context structure
//                                  eip,eax,ebx,ecx,edx,ebp,esp,edi,esi and efl are not
//                                  those returned by the M$ func
//     return : TRUE on success
//-----------------------------------------------------------------------------
BOOL CThreadContext::GetThreadContext(HANDLE hThread,LPCONTEXT lpContext)
{
    PBYTE Eip=0;
    PBYTE Ebp=0;
    DWORD SuspendedCount;
    DWORD dwCnt;
    BOOL bRet;
    CThreadContext::CONTEXT_LITE ContextLite={0};
    CProcessAndThreadID ProcessAndThreadID;

    // check parameters
    if (IsBadWritePtr(lpContext,sizeof(CONTEXT)))
        return FALSE;

    // assume user has free memory of previous GetThreadContext call
    if (!this->HasProcessMemoryBeenFree())
        return FALSE;

    // Dummy user prevention
    if (ProcessAndThreadID.GetThreadId(hThread)==GetCurrentThreadId())
    {
        // for current thread user have direct access to all registers
#ifndef TOOLS_NO_MESSAGEBOX
        // user asks it's one registers --> report an error
        MessageBox(NULL,_T("Can't get context of current thread"),_T("Information"),MB_OK|MB_ICONINFORMATION|MB_TOPMOST);
#endif
        return FALSE;
    }

    // MSDN You cannot get a valid context for a running thread. Use the SuspendThread function to suspend the thread before calling GetThreadContext
    SuspendedCount=SuspendThread(hThread);
    if (SuspendedCount==(DWORD)-1)
    {
        CAPIError::ShowLastError();
        return FALSE;
    }

    // get real eip
    if (!this->GetFirstHookableEipEbp(hThread,&Eip,&Ebp))
    {
        ResumeThread(hThread);
        return FALSE;
    }

    // assume SuspendedCount thread value is 1
    for(dwCnt=0;dwCnt<SuspendedCount;dwCnt++)
    {
        if (ResumeThread(hThread)==(DWORD)-1)
        {
            CAPIError::ShowLastError();
            return FALSE;
        }
    }

    // assume that all other threads of the process are suspended
    CThreadContext::SuspendAllOtherThreads(hThread);

    // get thread context (hoping that some registers are ok :D)
    lpContext->ContextFlags=CONTEXT_ALL;
    ::GetThreadContext(hThread,lpContext);

    if (ProcessAndThreadID.GetProcessIdOfThread(hThread)==GetCurrentProcessId())
    {
        this->bLastGetThreadContextIsForCurrentProcess=TRUE;
        bRet=this->GetThreadContextOfCurrentProcess(hThread,Eip,&ContextLite);
    }
    else
    {
        this->bLastGetThreadContextIsForCurrentProcess=FALSE;
        // put a hook in remote process to retrieve real values of eax,ebx,ecx,edx,ebp,esp,edi,esi and efl
        bRet=this->GetThreadContextOfDifferentProcess(hThread,Eip,&ContextLite);
    }

    // Resume all other threads of the process are suspended
    CThreadContext::ResumeAllOtherThreads(hThread);

    // restore SuspendedCount thread value
    for(dwCnt=0;dwCnt<SuspendedCount;dwCnt++)
    {
        if (SuspendThread(hThread)==(DWORD)-1)
        {
            CAPIError::ShowLastError();
            return FALSE;
        }
    }
    if (ResumeThread(hThread)==(DWORD)-1)
    {
        CAPIError::ShowLastError();
        return FALSE;
    }

    // set context values
    if (bRet)
    {
        lpContext->Eax=ContextLite.EAX;
        lpContext->Ebx=ContextLite.EBX;
        lpContext->Ecx=ContextLite.ECX;
        lpContext->Edx=ContextLite.EDX;
        lpContext->Esp=ContextLite.ESP;
        lpContext->Eip=ContextLite.EIP;
        lpContext->Ebp=ContextLite.EBP;
        lpContext->Esi=ContextLite.ESI;
        lpContext->Edi=ContextLite.EDI;
        lpContext->EFlags=ContextLite.EFL;
    }

    return bRet;
}
Exemple #19
0
void CDebugMgr::RecordStack(const CONTEXT* pContext)
{
    m_pchBuffer += wsprintf(m_pchBuffer,"\nCall stack:\n" );

    m_pchBuffer += wsprintf(m_pchBuffer,"Address   Frame     Logical addr  Module\n" );

    DWORD pc = pContext->Eip;
    PDWORD pFrame, pPrevFrame;
    
    pFrame = (PDWORD)pContext->Ebp;

    do
    {
        TCHAR szModule[MAX_PATH] = "";
        DWORD section = 0, offset = 0;

        FindLogicalAddress((PVOID)pc, szModule,sizeof(szModule),section,offset );

        m_pchBuffer += wsprintf(m_pchBuffer,"%08X  %08X  %04X:%08X %s",
                  pc, pFrame, section, offset, szModule );

		// See if we need to spit out symbol/source/line info

		if ( m_dwOptions & DEBUGMGR_RESOLVESYMBOLS )
		{
			// Generate the name of the map file

			TCHAR szMap[MAX_PATH] = "";
			wsprintf(szMap, szModule);
			wsprintf(&szMap[lstrlen(szMap)-3], "MAP");

			TCHAR szSymbol[256] = "<unknown>";
			TCHAR szUnmangledSymbol[1024] = "<unknown>";
			TCHAR szObject[128] = "<unknown>";

			if ( FindSymbol(szMap, section, offset, szSymbol, szObject) )
			{
				if ( m_dwOptions & DEBUGMGR_UNMANGLESYMBOLS && *szSymbol == '?' )
				{
					UnDecorateSymbolName(szSymbol, szUnmangledSymbol, 1024, UNDNAME_COMPLETE);
				}
				else
				{
					wsprintf(szUnmangledSymbol, szSymbol);
				}
			}

			m_pchBuffer += wsprintf(m_pchBuffer, " in function %s in object file %s", szUnmangledSymbol, szObject);

			if ( m_dwOptions & DEBUGMGR_RESOLVESOURCELINE )
			{
				TCHAR szSource[256];
				TCHAR szLine[256];

				if ( FindSourceLine(szMap, szObject, section, offset, szSource, szLine) )
				{
					m_pchBuffer += wsprintf(m_pchBuffer, " at Line %s of %s\n", szLine, szSource);
				}
				else
				{
					m_pchBuffer += wsprintf(m_pchBuffer, " at Line ??? of ???\n");
				}
			}
			else
			{
				m_pchBuffer += wsprintf(m_pchBuffer, "\n\n");
			}
		}
		else
		{
			m_pchBuffer += wsprintf(m_pchBuffer, "\n");
		}

		// Go on to the next stack frame

        pc = pFrame[1];

        pPrevFrame = pFrame;

        pFrame = (PDWORD)pFrame[0]; // proceed to next higher frame on stack

        if ( (DWORD)pFrame & 3 )    // Frame pointer must be aligned on a
            break;                  // DWORD boundary.  Bail if not so.

        if ( pFrame <= pPrevFrame )
            break;

        // Can two DWORDs be read from the supposed frame address?          
        if ( IsBadWritePtr(pFrame, sizeof(PVOID)*2) )
            break;

    } while ( 1 );
}
Exemple #20
0
BOOL CThreadContext::GetThreadContextOfCurrentProcess(HANDLE hThreadHandle,PVOID Address,PCONTEXT_LITE pContextLite)
{
    // check params
    if (IsBadWritePtr(pContextLite,sizeof(CONTEXT_LITE)))
        return FALSE;

    // hThreadHandle is suspended and it's eip is Address
    PBYTE TmpAddress;
    CTHREADCONTEXT_GETTHREADCONTEXTOFCURRENTPROCESS_ARGS Args={0};
    Args.pContextLite=pContextLite;
    Args.EipToRestore=Address;
    Args.hEvent=CreateEvent(NULL,FALSE,FALSE,NULL);
    pContextLite->EIP=(DWORD)Address;

    // for window app, you generally fall in the window message loop,which is entered only when receiving messages
    // so we can be lock by this stuff
    // To avoid such lock, we send a stupid message to force message loop entering (using PostMessage to don't wait for return)
    // Notice 1 : we could find the corresponding window and send it a message, but the easiest way is to send a broadcast message
    // Notice 2 : this tricks not always works as lock can result of WaitForMultipleObjects and other blocking calls
    this->UnlockWndProc();

    // save original bytes
    memcpy(Args.OriginalBytes,Address,CTHREADCONTEXT_GETTHREADCONTEXTOFCURRENTPROCESS_OPCODESIZE);

    DWORD OldProtectionFlag;
    // remove memory protection
    if (!VirtualProtectEx(GetCurrentProcess(),
                    Address,
                    CTHREADCONTEXT_GETTHREADCONTEXTOFCURRENTPROCESS_OPCODESIZE,
                    PAGE_EXECUTE_READWRITE,
                    &OldProtectionFlag))
        return FALSE;

    // replace opcodes by our own
    PBYTE pBuffer=(PBYTE)Address;
    int BufferIndex=0;
    // pushfd
    pBuffer[BufferIndex++]=0x9C;
    // push eax
    pBuffer[BufferIndex++]=0x50;

    // push &Args
    pBuffer[BufferIndex++]=0xB8; // mov eax,
    TmpAddress=(PBYTE)&Args;
    memcpy(&pBuffer[BufferIndex],&TmpAddress,sizeof(PBYTE));
    BufferIndex+=sizeof(PBYTE);
    pBuffer[BufferIndex++]=0x50;// push eax

    // call CThreadContext_GetThreadContextOfCurrentProcess
    pBuffer[BufferIndex++]=0xB8; // mov eax,
    TmpAddress=(PBYTE)CThreadContext::GetThreadContextInside;
    memcpy(&pBuffer[BufferIndex],&TmpAddress,sizeof(PBYTE));
    BufferIndex+=sizeof(PBYTE);
    // do a call not a jump, as func parameters must be at ebp-4
    // if no return address is pushed, parameters use won't work
    pBuffer[BufferIndex++]=0xFF;pBuffer[BufferIndex++]=0xD0; // call eax

    // resume hThreadHandle
    if (ResumeThread(hThreadHandle)==(DWORD)-1)
    {
        CAPIError::ShowLastError();
        // restore original opcodes
        memcpy((PBYTE)Args.EipToRestore,Args.OriginalBytes,CTHREADCONTEXT_GETTHREADCONTEXTOFCURRENTPROCESS_OPCODESIZE);
        return FALSE;
    }

    // wait for the end of context retrieval (10 sec max)
    DWORD dwRes=WaitForSingleObject(Args.hEvent,10000);

    if (dwRes!=WAIT_OBJECT_0)
    {
        // restore original opcodes
        memcpy((PBYTE)Args.EipToRestore,Args.OriginalBytes,CTHREADCONTEXT_GETTHREADCONTEXTOFCURRENTPROCESS_OPCODESIZE);
        return FALSE;
    }

    // restore memory protection
    VirtualProtectEx(GetCurrentProcess(),
                    Address,
                    CTHREADCONTEXT_GETTHREADCONTEXTOFCURRENTPROCESS_OPCODESIZE,
                    OldProtectionFlag,
                    &OldProtectionFlag);

    return TRUE;
}
Exemple #21
0
/*
 * Copy settings into a print dialog & any devmode
 */
BOOL AwtPrintControl::InitPrintDialog(JNIEnv *env,
				      jobject printCtrl, PRINTDLG &pd) {
    HWND hwndOwner = NULL;
    jobject dialogOwner =
        env->GetObjectField(printCtrl, AwtPrintControl::dialogOwnerPeerID);
    if (dialogOwner != NULL) {
        AwtComponent *dialogOwnerComp = 
	  (AwtComponent *)JNI_GET_PDATA(dialogOwner);

	hwndOwner = dialogOwnerComp->GetHWnd();
	env->DeleteLocalRef(dialogOwner);
	dialogOwner = NULL;
    }
    jobject mdh = NULL;
    jobject dest = NULL;
    jobject select = NULL;
    jobject dialog = NULL;
    LPTSTR printName = NULL;
    LPTSTR portName = NULL;

    // If the user didn't specify a printer, then this call returns the
    // name of the default printer.
    jstring printerName = (jstring)
      env->CallObjectMethod(printCtrl, AwtPrintControl::getPrinterID);

    if (printerName != NULL) {

	pd.hDevMode = AwtPrintControl::getPrintHDMode(env, printCtrl);
	pd.hDevNames = AwtPrintControl::getPrintHDName(env, printCtrl);
        
	LPTSTR getName = (LPTSTR)JNU_GetStringPlatformChars(env, 
						      printerName, NULL);

	BOOL samePrinter = FALSE;
      
	// check if given printername is same as the currently saved printer
	if (pd.hDevNames != NULL ) {

	    DEVNAMES *devnames = (DEVNAMES *)::GlobalLock(pd.hDevNames);
	    if (devnames != NULL) {
	        LPTSTR lpdevnames = (LPTSTR)devnames;
		printName = lpdevnames+devnames->wDeviceOffset;
		
		if (!_tcscmp(printName, getName)) {
	
		    samePrinter = TRUE;		
		    printName = _tcsdup(lpdevnames+devnames->wDeviceOffset);   
		    portName = _tcsdup(lpdevnames+devnames->wOutputOffset);
	
		}
	    }
	    ::GlobalUnlock(pd.hDevNames);
	}
   
	if (!samePrinter) {
 	    LPTSTR foundPrinter = NULL;
	    LPTSTR foundPort = NULL;
	    DWORD cbBuf = 0;
	    VERIFY(AwtPrintControl::FindPrinter(NULL, NULL, &cbBuf, 
						NULL, NULL));
	    LPBYTE buffer = new BYTE[cbBuf];
      
	    if (AwtPrintControl::FindPrinter(printerName, buffer, &cbBuf,
					     &foundPrinter, &foundPort) &&
		(foundPrinter != NULL) && (foundPort != NULL)) {

	        printName = _tcsdup(foundPrinter);   
		portName = _tcsdup(foundPort);
			
	        if (!AwtPrintControl::CreateDevModeAndDevNames(&pd,
						   foundPrinter, foundPort)) {
		    delete [] buffer;		    
		    if (printName != NULL) {
		      free(printName);
		    }
		    if (portName != NULL) {
		      free(portName);
		    }
		    return FALSE;
		}

		DASSERT(pd.hDevNames != NULL);
	    } else {
	        delete [] buffer;		
		if (printName != NULL) {
		  free(printName);
		}
		if (portName != NULL) {
		  free(portName);
		}
		JNU_ThrowIllegalArgumentException(env, 
		   "Invalid value for property printer or null printer port");
		return FALSE;
	    }    
      
	    delete [] buffer;
	}
        // PrintDlg may change the values of hDevMode and hDevNames so we
	// re-initialize our saved handles.
	AwtPrintControl::setPrintHDMode(env, printCtrl, NULL);
	AwtPrintControl::setPrintHDName(env, printCtrl, NULL);
    } else {
 
        // There is no default printer. This means that there are no
        // printers installed at all.

	if (printName != NULL) {
	  free(printName);
	}
	if (portName != NULL) {
	  free(portName);
	}
        // Returning TRUE means try to display the native print dialog
        // which will either display an error message or prompt the
	// user to install a printer.
	return TRUE;
    }

    // Now, set-up the struct for the real calls to ::PrintDlg and ::CreateDC

    pd.hwndOwner = hwndOwner;
    pd.Flags = PD_ENABLEPRINTHOOK | PD_RETURNDC |
               PD_USEDEVMODECOPIESANDCOLLATE;
    pd.lpfnPrintHook = (LPPRINTHOOKPROC)PrintDlgHook;

    if (env->CallBooleanMethod(printCtrl, AwtPrintControl::getMDHID)) {
        pd.Flags |= PD_COLLATE;
    }
	
    pd.nCopies = (WORD)env->CallIntMethod(printCtrl,
					  AwtPrintControl::getCopiesID);
    pd.nFromPage = (WORD)env->CallIntMethod(printCtrl, 
					    AwtPrintControl::getFromPageID);
    pd.nToPage = (WORD)env->CallIntMethod(printCtrl, 
					  AwtPrintControl::getToPageID);
    pd.nMinPage = (WORD)env->CallIntMethod(printCtrl,
					   AwtPrintControl::getMinPageID);
    jint maxPage = env->CallIntMethod(printCtrl, 
				      AwtPrintControl::getMaxPageID);
    pd.nMaxPage = (maxPage <= (jint)((WORD)-1)) ? (WORD)maxPage : (WORD)-1;
    
    if (env->CallBooleanMethod(printCtrl, 
			       AwtPrintControl::getDestID)) {
      pd.Flags |= PD_PRINTTOFILE;
    }

    jint selectType = env->CallIntMethod(printCtrl, 
					 AwtPrintControl::getSelectID);

    // selectType identifies whether No selection (2D) or 
    // SunPageSelection (AWT)
    if (selectType != 0) {
      pd.Flags |= selectType;
    }
  
    if (!env->CallBooleanMethod(printCtrl,
				AwtPrintControl::getPrintToFileEnabledID)) {
      pd.Flags |= PD_DISABLEPRINTTOFILE;
    }
    
    if (pd.hDevMode != NULL) {	
      DEVMODE *devmode = (DEVMODE *)::GlobalLock(pd.hDevMode);
      DASSERT(!IsBadWritePtr(devmode, sizeof(DEVMODE)));
      
      devmode->dmFields |= DM_COPIES | DM_COLLATE | DM_ORIENTATION |
	DM_PAPERSIZE | DM_PRINTQUALITY | DM_COLOR |
	DM_PRINTQUALITY | DM_COLOR |
	DM_DUPLEX;
      
      devmode->dmCopies = pd.nCopies;   
      
      jint orient = env->CallIntMethod(printCtrl,
				       AwtPrintControl::getOrientID);
      if (orient == 0) {
	devmode->dmOrientation = DMORIENT_LANDSCAPE;
      } else if (orient == 1) {
	devmode->dmOrientation = DMORIENT_PORTRAIT;
      }
      
      devmode->dmCollate = (pd.Flags & PD_COLLATE) ? DMCOLLATE_TRUE
	: DMCOLLATE_FALSE;
      
      int quality = env->CallIntMethod(printCtrl, 
				       AwtPrintControl::getQualityID);        
      if (quality) {
	devmode->dmPrintQuality = quality;
      }
      
      int color = env->CallIntMethod(printCtrl,
				     AwtPrintControl::getColorID);
      if (color) {
	devmode->dmColor = color;
      } 
      
      int sides = env->CallIntMethod(printCtrl,
				     AwtPrintControl::getSidesID);
      if (sides) {
	devmode->dmDuplex = (int)sides;
      }
      
      jintArray obj = (jintArray)env->CallObjectMethod(printCtrl, 
	       			       AwtPrintControl::getWin32MediaID);
      jboolean isCopy;
      jint *wid_ht = env->GetIntArrayElements(obj,
					      &isCopy);
      
      double newWid = 0.0, newHt = 0.0;
      if (wid_ht != NULL && wid_ht[0] != 0 && wid_ht[1] != 0) { 
	devmode->dmPaperSize = AwtPrintControl::getNearestMatchingPaper(
					     printName,
					     portName,
			    		     (double)wid_ht[0], 
					     (double)wid_ht[1],
					     &newWid, &newHt);

      }
      env->ReleaseIntArrayElements(obj, wid_ht, 0);
      ::GlobalUnlock(pd.hDevMode);
      devmode = NULL;
    }

    if (printName != NULL) {
      free(printName);
    }
    if (portName != NULL) {
      free(portName);
    }

    return TRUE;
}
Exemple #22
0
//-----------------------------------------------------------------------------
// Name: GetThreadContextOfDifferentProcess
// Object: inject code for the specified thread at the specified address
//          to retrieve eax,ebx,ecx,edx,ebp,esp,edi,esi and efl regiters values
// Parameters :
//     in  : HANDLE hThreadHandle : handle of suspended thread
//                                  FOR SECURITY ALL OTHER THREADS OF THE PROCESS MUST BE SUSPENDED
//           PVOID Address : address of thread's EIP
//     out : PCONTEXT_LITE pContextLite : pointer to CONTEXT_LITE struct
//     return : TRUE on success
//-----------------------------------------------------------------------------
BOOL CThreadContext::GetThreadContextOfDifferentProcess(HANDLE hThreadHandle,PVOID Address,PCONTEXT_LITE pContextLite)
{
    // check params
    if (IsBadWritePtr(pContextLite,sizeof(CONTEXT_LITE)))
        return FALSE;

    // for window app, you generally fall in the window message loop,which is entered only when receiving messages
    // so we can be lock by this stuff
    // To avoid such lock, we send a stupid message to force message loop entering (using PostMessage to don't wait for return)
    // Notice 1 : we could find the corresponding window and send it a message, but the easiest way is to send a broadcast message
    // Notice 2 : this tricks not always works as lock can result of WaitForMultipleObjects and other blocking calls
    this->UnlockWndProc();

    // retrieve process associated to thread
    CProcessAndThreadID ProcessAndThreadID;
    DWORD dwProcessId=ProcessAndThreadID.GetProcessIdOfThread(hThreadHandle);

    if(this->HookProcessMemoryAddress)// can appear if previous context query was done for a suspended thread
        delete this->HookProcessMemoryAddress;

    this->HookProcessMemoryAddress=new CProcessMemory(dwProcessId,FALSE);

    #define REGISTER_SIZE 4 // size of registers in byte (4 for 32bits)
    #define SIZEOF_HOOK_PROXY CTHREADCONTEXT_GETTHREADCONTEXTOFREMOTEPROCESS_OPCODESIZE // better to comput size for this 
    #define SIZEOF_HOOK 2000 // something enough (don't need to comput size)
    #define HOOK_END_POOLING_IN_MS 100
    #define HOOK_END_POOLING_MAX_IN_MS 5000
    DWORD dwHookEndFlag=0xBADCAFE;
    DWORD dwBeginTime;
    DWORD dwMaxWait;
    DWORD dw=0;

    // as kernel32 is always mapped at the same address, kernel32 func will get same addr in all processes
    FARPROC pGetCurrentThread=GetProcAddress(GetModuleHandle(_T("kernel32.dll")),"GetCurrentThread");
    FARPROC pSuspendThread=GetProcAddress(GetModuleHandle(_T("kernel32.dll")),"SuspendThread");

    SIZE_T dwTransferedSize=0;

    BYTE BufferIndex;

    BYTE LocalOriginalOpCode[SIZEOF_HOOK_PROXY];
    BYTE LocalProxy[SIZEOF_HOOK_PROXY];
    BYTE LocalHook[SIZEOF_HOOK];

    #define CONTEXT_SIZE (9*sizeof(PBYTE)) // size of this->HookRemoteContext in bytes

    PBYTE EntryPointAddress=(PBYTE)Address;

    // read original eip opcode
    if (!this->HookProcessMemoryAddress->Read(
                                            (LPVOID)EntryPointAddress,
                                            LocalOriginalOpCode,
                                            SIZEOF_HOOK_PROXY,
                                            &dwTransferedSize)
                                            )
        return FALSE;

    // allocate memory for the Hook
    this->HookRemoteHook=(PBYTE)this->HookProcessMemoryAddress->Alloc(SIZEOF_HOOK);
    if (!this->HookRemoteHook)
        return FALSE;

    // allocate memory in remote process to store context lite
    this->HookRemoteContext=(PBYTE)this->HookProcessMemoryAddress->Alloc(CONTEXT_SIZE);
    if (!this->HookRemoteContext)
        return FALSE;

    //// code for absolute jump if you don't want to make a relative one
    // #define SIZEOF_HOOK_PROXY 7
    // // jump Hook Address
    // LocalProxy[0]=0xB8;// mov eax,
    // memcpy(&LocalProxy[1],&RemoteHook,sizeof(DWORD));// Hook Address
    // LocalProxy[5]=0xFF;LocalProxy[6]=0xE0;//jmp eax absolute 

    // make a relative jump
    dw=(DWORD)(this->HookRemoteHook-EntryPointAddress-SIZEOF_HOOK_PROXY);
    // jump relative
    LocalProxy[0]=0xE9;
    memcpy(&LocalProxy[1],&dw,sizeof(DWORD));// Hook Address


    ///////////////////////
    // fill hook data
    // algorithm is the following :
    //
    //      ///////////////////////////////////////
    //      ///// specifics operations to do 
    //      ///////////////////////////////////////
    //
    //       // save context without affecting registers and flag registers
    //            push esp
    //            pushfd
    //            push ebx
    //            push eax
    //
    //            mov eax,RemoteContext
    //
    //            // get eax
    //            pop ebx
    //            mov dword ptr[eax],ebx
    //
    //            // get ebx
    //            pop ebx
    //            add eax,REGISTER_SIZE
    //            mov dword ptr[eax],ebx
    //
    //            // get ecx
    //            add eax,REGISTER_SIZE
    //            mov dword ptr[eax],ecx
    //
    //            // get edx
    //            add eax,REGISTER_SIZE
    //            mov dword ptr[eax],edx
    //
    //            // get esi
    //            add eax,REGISTER_SIZE
    //            mov dword ptr[eax],esi
    //
    //            // get edi
    //            add eax,REGISTER_SIZE
    //            mov dword ptr[eax],edi
    //
    //            // get efl
    //            pop ebx
    //            add eax,REGISTER_SIZE
    //            mov dword ptr[eax],ebx
    //
    //            // get ebp
    //            add eax,REGISTER_SIZE
    //            mov dword ptr[eax],ebp
    //
    //            // get esp
    //            pop ebx
    //            add eax,REGISTER_SIZE
    //            mov dword ptr[eax],ebx
    //
    //            // store efl again
    //            sub eax,2*REGISTER_SIZE
    //            push dword ptr[eax]
    //
    //            // push return address on stack
    //
    //            // restore ebx and eax using our local storage
    //
    //            // restore ebx
    //            mov eax,RemoteContext
    //            add eax,REGISTER_SIZE
    //            mov ebx,dword ptr[eax]
    //
    //            // restore eax
    //            sub eax,REGISTER_SIZE
    //            mov eax,dword ptr[eax]
    //
    //            // restore flags
    //            popfd
    //
    //      ///////////////////////////////////////
    //      ///// End of specifics operations to do 
    //      ///////////////////////////////////////
    //
    //      // save registers and flag registers
    //
    //
    //      // do some action that can tell the calling process that the hook is ending
    //      // so we can restore original opcode
    //      // and free memory
    //
    //      // suspend thread to allow user context use
    //
    //      // restore registers and flag registers
    //
    //      // jump to Entry point
    //
    ///////////////////////

    BufferIndex=0;

    ////////////////////////////////
    // 1) SaveContext
    ////////////////////////////////

    // push esp
    LocalHook[BufferIndex++]=0x54;
    //pushfd
    LocalHook[BufferIndex++]=0x9C;
    //push ebx
    LocalHook[BufferIndex++]=0x53;
    //push eax
    LocalHook[BufferIndex++]=0x50;

    // lea RemoteContext --> mov eax,&RemoteContext
    LocalHook[BufferIndex++]=0xB8; // mov eax,
    memcpy(&LocalHook[BufferIndex],&this->HookRemoteContext,sizeof(DWORD));
    BufferIndex+=sizeof(DWORD);

    ///////////
    // get eax
    ///////////

    // pop ebx
    LocalHook[BufferIndex++]=0x5B;
    // mov dword ptr[eax],ebx
    LocalHook[BufferIndex++]=0x89;LocalHook[BufferIndex++]=0x18;

    ///////////
    // get ebx
    ///////////

    // pop ebx
    LocalHook[BufferIndex++]=0x5B;
    //add eax,REGISTER_SIZE
    LocalHook[BufferIndex++]=0x83;LocalHook[BufferIndex++]=0xC0;LocalHook[BufferIndex++]=REGISTER_SIZE;
    // mov dword ptr[eax],ebx
    LocalHook[BufferIndex++]=0x89;LocalHook[BufferIndex++]=0x18;

    ///////////
    // get ecx
    ///////////

    //add eax,REGISTER_SIZE
    LocalHook[BufferIndex++]=0x83;LocalHook[BufferIndex++]=0xC0;LocalHook[BufferIndex++]=REGISTER_SIZE;
    // mov dword ptr[eax],ecx
    LocalHook[BufferIndex++]=0x89;LocalHook[BufferIndex++]=0x08;

    ///////////
    // get edx
    ///////////

    //add eax,REGISTER_SIZE
    LocalHook[BufferIndex++]=0x83;LocalHook[BufferIndex++]=0xC0;LocalHook[BufferIndex++]=REGISTER_SIZE;
    // mov dword ptr[eax],edx
    LocalHook[BufferIndex++]=0x89;LocalHook[BufferIndex++]=0x10;

    ///////////
    // get esi
    ///////////

    // add eax,REGISTER_SIZE
    LocalHook[BufferIndex++]=0x83;LocalHook[BufferIndex++]=0xC0;LocalHook[BufferIndex++]=REGISTER_SIZE;
    // mov dword ptr[eax],esi
    LocalHook[BufferIndex++]=0x89;LocalHook[BufferIndex++]=0x30;

    ///////////
    // get edi
    ///////////

    // add eax,REGISTER_SIZE
    LocalHook[BufferIndex++]=0x83;LocalHook[BufferIndex++]=0xC0;LocalHook[BufferIndex++]=REGISTER_SIZE;
    // mov dword ptr[eax],edi
    LocalHook[BufferIndex++]=0x89;LocalHook[BufferIndex++]=0x38;

    ///////////
    // get efl
    ///////////

    // pop ebx
    LocalHook[BufferIndex++]=0x5B;
    // add eax,REGISTER_SIZE
    LocalHook[BufferIndex++]=0x83;LocalHook[BufferIndex++]=0xC0;LocalHook[BufferIndex++]=REGISTER_SIZE;
    // mov dword ptr[eax],ebx
    LocalHook[BufferIndex++]=0x89;LocalHook[BufferIndex++]=0x18;

    ///////////
    // get ebp
    ///////////

    // add eax,REGISTER_SIZE
    LocalHook[BufferIndex++]=0x83;LocalHook[BufferIndex++]=0xC0;LocalHook[BufferIndex++]=REGISTER_SIZE;
    // mov dword ptr[eax],ebp
    LocalHook[BufferIndex++]=0x89;LocalHook[BufferIndex++]=0x28;

    ///////////
    // get esp
    ///////////

    // pop ebx
    LocalHook[BufferIndex++]=0x5B;
    // add eax,REGISTER_SIZE
    LocalHook[BufferIndex++]=0x83;LocalHook[BufferIndex++]=0xC0;LocalHook[BufferIndex++]=REGISTER_SIZE;
    // mov dword ptr[eax],ebx
    LocalHook[BufferIndex++]=0x89;LocalHook[BufferIndex++]=0x18;

    ////////////////////////////////////////////
    // push return address on stack
    ////////////////////////////////////////////
    LocalHook[BufferIndex++]=0xBB;//mov ebx, 
    memcpy(&LocalHook[BufferIndex],&EntryPointAddress,sizeof(DWORD));// dwEntryPointAddress
    BufferIndex+=sizeof(DWORD);
    // push eax
    LocalHook[BufferIndex++]=0x53;// push ebx

    ///////////////////
    // push saved efl on stack
    ///////////////////

    // sub eax,2*REGISTER_SIZE
    LocalHook[BufferIndex++]=0x83;LocalHook[BufferIndex++]=0xE8;LocalHook[BufferIndex++]=2*REGISTER_SIZE;
    // push dword ptr[eax]
    LocalHook[BufferIndex++]=0xFF;LocalHook[BufferIndex++]=0x30;

    ////////////////////////////////////////////
    // restore ebx and eax using our local storage
    /////////////////////////////////////////////

    ////////////////
    // restore ebx
    ////////////////

    // lea RemoteContext --> mov eax,&RemoteContext
    LocalHook[BufferIndex++]=0xB8; // mov eax,
    memcpy(&LocalHook[BufferIndex],&this->HookRemoteContext,sizeof(DWORD));
    BufferIndex+=sizeof(DWORD);


    // add eax,REGISTER_SIZE
    LocalHook[BufferIndex++]=0x83;LocalHook[BufferIndex++]=0xC0;LocalHook[BufferIndex++]=REGISTER_SIZE;
    // mov ebx,dword ptr[eax]
    LocalHook[BufferIndex++]=0x8B;LocalHook[BufferIndex++]=0x18;

    ///////////////
    // restore eax
    ///////////////

    // sub eax,REGISTER_SIZE
    LocalHook[BufferIndex++]=0x83;LocalHook[BufferIndex++]=0xE8;LocalHook[BufferIndex++]=REGISTER_SIZE;
    // mov eax,dword ptr[eax]
    LocalHook[BufferIndex++]=0x8B;LocalHook[BufferIndex++]=0x00;

    ////////////////
    // restore flags
    ////////////////

    // popfd
    LocalHook[BufferIndex++]=0x9D;

    // at this point all registers are in the same state
    // as the begin of hook

    ////////////////////////////////
    // 2) restoring context
    ////////////////////////////////

    // save registers and flag registers
    LocalHook[BufferIndex++]=0x60;//pushad
    LocalHook[BufferIndex++]=0x9c;//pushfd

    //////////////////////////////////////////////////////////////////////
    //do some action that can tell the calling process that the hook is ending
    //////////////////////////////////////////////////////////////////////

    //////////////////////////////////////////////////////////////////////
    // here we change some remotely allocated memory to signal end of hook
    // it's allow for remote process to do polling on this memory pointer
    // (Notice you can use Named event or whatever you want if you dislike
    // this way of doing)
    //
    //  so here we use the begin of RemoteHook and put first DWORD to dwHookEndFlag
    //////////////////////////////////////////////////////////////////////

    // mov eax,RemoteHook
    LocalHook[BufferIndex++]=0xB8;// mov eax,
    memcpy(&LocalHook[BufferIndex],&this->HookRemoteHook,sizeof(DWORD));
    BufferIndex+=sizeof(DWORD);

    // mov ebx,dwHookEndFlag
    LocalHook[BufferIndex++]=0xBB;// mov ebx,
    memcpy(&LocalHook[BufferIndex],&dwHookEndFlag,sizeof(DWORD));
    BufferIndex+=sizeof(DWORD);

    // *RemoteHook=dwHookEndFlag
    LocalHook[BufferIndex++]=0x89;LocalHook[BufferIndex++]=0x18;// mov dword ptr[eax],ebx


    //////////////////////////////////////////////////////////////////////
    // suspend thread 
    //////////////////////////////////////////////////////////////////////

    // mov eax,pGetCurrentThread
    LocalHook[BufferIndex++]=0xB8;// mov eax,
    memcpy(&LocalHook[BufferIndex],&pGetCurrentThread,sizeof(DWORD));
    BufferIndex+=sizeof(DWORD);

    // call GetCurrentThread
    LocalHook[BufferIndex++]=0xFF;LocalHook[BufferIndex++]=0xD0; // call eax

    // we are in stdcall --> parameters are removed from stack

    // push eax (contains the thread handle
    LocalHook[BufferIndex++]=0x50;// push eax

    // mov eax,pSuspendThread
    LocalHook[BufferIndex++]=0xB8;// mov eax,
    memcpy(&LocalHook[BufferIndex],&pSuspendThread,sizeof(DWORD));
    BufferIndex+=sizeof(DWORD);

    // call SuspendThread
    LocalHook[BufferIndex++]=0xFF;LocalHook[BufferIndex++]=0xD0; // call eax


    // we are in stdcall --> parameters are removed from stack


    //////////////////////////////////////////////////////////////////////
    // restore registers and flag registers
    //////////////////////////////////////////////////////////////////////
    LocalHook[BufferIndex++]=0x9D;//popfd
    LocalHook[BufferIndex++]=0x61;//popad

    //////////////////////////////////////////////////////////////////////
    // remember that return address is on stack
    // so jump to EntryPointAddress using  Ret
    //////////////////////////////////////////////////////////////////////
    LocalHook[BufferIndex++]=0xC3;//ret

    // copy hook data
    if (!this->HookProcessMemoryAddress->Write(
                                                (LPVOID)this->HookRemoteHook,
                                                LocalHook,
                                                SIZEOF_HOOK,
                                                &dwTransferedSize)
                                                )
    {
        return FALSE;
    }

    DWORD OldProtectionFlag;
    // mark allocated memory has executable
    if (!VirtualProtectEx(this->HookProcessMemoryAddress->GetProcessHandle(),
                    this->HookRemoteHook,
                    SIZEOF_HOOK,
                    PAGE_EXECUTE_READWRITE,
                    &OldProtectionFlag))
        return FALSE;



    if (!VirtualProtectEx(this->HookProcessMemoryAddress->GetProcessHandle(),
                    EntryPointAddress,
                    SIZEOF_HOOK_PROXY,
                    PAGE_EXECUTE_READWRITE,
                    &OldProtectionFlag))
        return FALSE;

    // copy proxy data (assume that our hook is in remote process before jumping to it)
    if (!this->HookProcessMemoryAddress->Write(
                                                (LPVOID)EntryPointAddress,
                                                LocalProxy,
                                                SIZEOF_HOOK_PROXY,
                                                &dwTransferedSize)
                                                )
    {
        return FALSE;
    }

    // resume thread a first time to run our hook
    if(ResumeThread(hThreadHandle)==((DWORD)-1))
        return FALSE;

    dwMaxWait=HOOK_END_POOLING_MAX_IN_MS;
    dwBeginTime=GetTickCount();

    // wait until hook has done it's job --> check the memory flags put at the begin of RemoteHook
    for(;;)
    {

        Sleep(HOOK_END_POOLING_IN_MS);
        // read remote process memory to check memory flags
        if (!this->HookProcessMemoryAddress->Read( this->HookRemoteHook,&dw,sizeof(DWORD),&dwTransferedSize))
            return FALSE;

        // if hooking as finished
        if (dw==dwHookEndFlag)
            break;

        // if process is crashed or stopped don't wait anymore
        if (!CProcessHelper::IsAlive(dwProcessId))
        {
#ifndef TOOLS_NO_MESSAGEBOX
            TCHAR pszMsg[2*MAX_PATH];
            _stprintf(pszMsg,_T("Error application seems to be closed"));
            MessageBox(NULL,pszMsg,_T("Error"),MB_OK|MB_ICONERROR|MB_TOPMOST);
#endif
            return FALSE;
        }

        // assume we are not in infinite loop
        if (GetTickCount()-dwBeginTime>HOOK_END_POOLING_MAX_IN_MS)
        {
#ifndef TOOLS_NO_MESSAGEBOX
            TCHAR pszMsg[2*MAX_PATH];
            _stprintf(pszMsg,_T("Thread is currently inside a system function.\r\n")
                             _T("The next EIP inside the application will be 0x%p.\r\n")
                             _T("Do you want to wait %us more for trying to retrieve other registers values ?"),
                             EntryPointAddress,
                             dwMaxWait*2/1000);
            if (MessageBox(NULL,pszMsg,_T("Question"),MB_YESNO|MB_ICONQUESTION|MB_TOPMOST)==IDYES)
            {
                // increase the wait time at each MsgBox
                dwMaxWait*=2;
                // reset begin time to wait dwMaxWait more time
                dwBeginTime=GetTickCount();
            }
            else
#endif
            {
                // restore originals opcode to avoid crash (in case of memory freeing) at the end of the lock state
                if (!this->HookProcessMemoryAddress->Write(
                                                            (LPVOID)EntryPointAddress,
                                                            LocalOriginalOpCode,
                                                            SIZEOF_HOOK_PROXY,
                                                            &dwTransferedSize)
                                                            )
                {
#ifndef TOOLS_NO_MESSAGEBOX
                    // better to terminate thread
                    if (MessageBox(NULL,_T("To avoid process crash it's better to terminate it now.\r\n")
                                        _T("Do you want to terminate it ?"),_T("Question"),MB_YESNO|MB_ICONQUESTION|MB_TOPMOST)==IDYES)
#endif
                    {
                        HANDLE hProcess=OpenProcess(PROCESS_ALL_ACCESS,FALSE,dwProcessId);
                        TerminateProcess(hProcess,(DWORD)-1);
                        CloseHandle(hProcess);
                    }
                    return FALSE;
                }
                return FALSE;
            }
        }
    }

    // restore original opcodes
    if (!this->HookProcessMemoryAddress->Write((LPVOID)EntryPointAddress,
                                                LocalOriginalOpCode,
                                                SIZEOF_HOOK_PROXY,
                                                &dwTransferedSize
                                               )
        )
        return FALSE;
    
    // restore memory protection
    if (!VirtualProtectEx(this->HookProcessMemoryAddress->GetProcessHandle(),
                            EntryPointAddress,
                            SIZEOF_HOOK_PROXY,
                            OldProtectionFlag,
                            &OldProtectionFlag)
        )
        return FALSE;

    // get context result
    if (!this->HookProcessMemoryAddress->Read( this->HookRemoteContext,pContextLite,sizeof(CONTEXT_LITE),&dwTransferedSize))
        return FALSE;

    pContextLite->EIP=(DWORD)Address;

    return TRUE;
}
Exemple #23
0
void CHelperManager::ProcessMessage_Invite_REQ_fromHELPER(playerCharacter_t* pHelper)
{
	
	if(TRUE == IsBadWritePtr(pHelper,sizeof(playerCharacter_t)) 
		|| TRUE == IsBadReadPtr(pHelper,sizeof(playerCharacter_t)))
	{
	
	
		
		return;
	}


	
	if( tagHelper::tagMemberList::HELPER != pHelper->tHelper.List.mode)
	{
		SendMessage_Invite_Respond_toHelper(
			pHelper,tagHelperPacket_SC_INVITE_RES_toHELPER::Fail_RegistrationRequest_invalidMode );
			g_logSystem->Write("Fail_RegistrationRequest_invalidMode" );
		return ;
	}



	char cz_tempTakerName[NAMESTRING+1];
	strncpy(cz_tempTakerName,MSG_ReadString(),NAMESTRING);
	cz_tempTakerName[NAMESTRING]=NULL;

	int idx = GTH_FindPCByName(cz_tempTakerName);
	
	playerCharacter_t * pTaker=gcpTools->GetPlayerRecordPointer(idx);

	if(NULL == pTaker){
		SendMessage_Invite_Respond_toHelper(
			pHelper,tagHelperPacket_SC_INVITE_RES_toHELPER::Fail_RegistrationRequest_invalidUser);
			g_logSystem->Write("Fail_RegistrationRequest_invalidUser" );
		return;
	}
	
	
	if( tagHelper::tagMemberList::TAKER != pTaker->tHelper.List.mode)
	{
		SendMessage_Invite_Respond_toHelper(
			pHelper,tagHelperPacket_SC_INVITE_RES_toHELPER::Fail_RegistrationRequest_invalidTakerMode );
			g_logSystem->Write("Fail_RegistrationRequest_invalidMode" );
		return ;
	}

	
	if(pTaker->idx == pHelper->idx)
	{
		SendMessage_Invite_Respond_toHelper( 
			pHelper,tagHelperPacket_SC_INVITE_RES_toHELPER::Fail_RegistrationRequest_invalidUser);
		g_logSystem->Write("Fail_RegistrationRequest_invalidUser" );
		return;
	}


	
	if ( pHelper->tHelper.List.count > tagHelper::MAX_MEMBER)
	{
		SendMessage_Invite_Respond_toHelper( 
			pHelper,tagHelperPacket_SC_INVITE_RES_toHELPER::Fail_RegistrationRequest_invalidTakersCount);
			g_logSystem->Write("Fail_RegistrationRequest_invalidTakersCount" );
		return;
	}

	
	if(pTaker->tHelper.List.count >= tagHelper::MAX_Accept_HELPERS)
	{
		SendMessage_Invite_Respond_toHelper( 
			pHelper,tagHelperPacket_SC_INVITE_RES_toHELPER::Fail_RegistrationRequest_invalidHelperCount);
		g_logSystem->Write("Fail_RegistrationRequest_invalidHelperCount" );
		return;
	}

	if ( pHelper->worldIdx != pTaker->worldIdx )
	{
		SendMessage_Invite_Respond_toHelper( 
			pHelper,tagHelperPacket_SC_INVITE_RES_toHELPER::Fail_RegistrationRequest_invalidWorldIndex);
			g_logSystem->Write("Fail_RegistrationRequest_invalidWorldIndex" );
		return ;
	}

	if(TRUE == isMyChild(pHelper,pTaker->name))
	{
		SendMessage_Invite_Respond_toHelper(
			pHelper,tagHelperPacket_SC_INVITE_RES_toHELPER::Fail_RegistrationRequest_invaliChild);
			g_logSystem->Write("Fail_RegistrationRequest_invaliChild" );
		return ;
	}



	strncpy(pTaker->HelperAdd.RequestPlayer.Name,pHelper->name,NAMESTRING);
	pTaker->HelperAdd.RequestPlayer.Name[NAMESTRING]=NULL;
	pTaker->HelperAdd.RequestPlayer.pcIdx=pHelper->idx;


	SendMessage_Invite_Respond_toHelper( 
		pHelper,tagHelperPacket_SC_INVITE_RES_toHELPER::Ready_Registration);
	
	ShowLogInfo("Helper_Invite_Suggest: name:%s,level:%d ",pHelper->name,pHelper->level);
	
	SendMessage_Invite_Request_toTaker( pTaker,pHelper->name);
	ShowLogInfo("Helper_Invite_Suggest: name:%s,level:%d ",pTaker->name,pTaker->level);
}
Exemple #24
0
BOOL 
WINAPI
NdasDmGetScsiPortNumberOfDisk(
	IN HANDLE hDisk,
	OUT LPDWORD lpdwScsiPortNumber)
{
	_ASSERTE(!IsBadWritePtr(lpdwScsiPortNumber, sizeof(DWORD)));

	BOOL fSuccess(FALSE);
	DWORD cbReturned(0);

	//
	// Query Storage Property
	//

	STORAGE_PROPERTY_QUERY	storPropQuery;
	STORAGE_ADAPTER_DESCRIPTOR	storAdptDesc;

	DWORD cbStorPropQuery = sizeof(STORAGE_PROPERTY_QUERY);
	DWORD cbStorAdptDesc = sizeof(STORAGE_ADAPTER_DESCRIPTOR);

	DBGPRT_TRACE(_FT("DeviceIoControl(IOCTL_STORAGE_QUERY_PROPERTY)\n"));

	::ZeroMemory(&storPropQuery, cbStorPropQuery);
	storPropQuery.PropertyId = StorageAdapterProperty;
	storPropQuery.QueryType = PropertyStandardQuery;

	fSuccess = ::DeviceIoControl(
		hDisk,
        IOCTL_STORAGE_QUERY_PROPERTY,
        &storPropQuery,
		cbStorPropQuery,
		&storAdptDesc,
		cbStorAdptDesc,
        &cbReturned,
		NULL);

	if (!fSuccess) {
		DBGPRT_ERR_EX(_FT("DeviceIoControl(IOCTL_STORAGE_QUERY_PROPERTY) failed: "));
		return FALSE;
	}

	//
	// Ignore non-SCSI device
	//

	if (BusTypeScsi != storAdptDesc.BusType) {
		DBGPRT_INFO(_FT("Ignoring non-scsi bus\n"));
		::SetLastError(NDASDM_ERROR_NON_SCSI_TYPE_DEVICE);
		return FALSE;
	}

	//
	// Query SCSI Address, given that the physical drive is a SCSI device
	//

	SCSI_ADDRESS scsiAddress;
	DWORD cbScsiAddress = sizeof(SCSI_ADDRESS);

	DBGPRT_TRACE(_FT("DeviceIoControl(IOCTL_SCSI_GET_ADDRESS)\n"));

	fSuccess = ::DeviceIoControl(
		hDisk,
		IOCTL_SCSI_GET_ADDRESS,
		NULL,
		0,
		&scsiAddress,
		cbScsiAddress,
		&cbReturned,
		NULL);

	if (!fSuccess) {
		DBGPRT_ERR_EX(_FT("DeviceIoControl(IOCTL_SCSI_GET_ADDRESS) failed: "));
		return FALSE;
	}

	DBGPRT_INFO(_FT("SCSIAddress: Len: %d, PortNumber: %d, PathId: %d, TargetId: %d, Lun: %d\n"),
		(DWORD) scsiAddress.Length,
		(DWORD) scsiAddress.PortNumber,
		(DWORD) scsiAddress.PathId,
		(DWORD) scsiAddress.TargetId,
		(DWORD) scsiAddress.Lun);

	//
	// Return the result
	//
	*lpdwScsiPortNumber = scsiAddress.PortNumber;

	return TRUE;
}