INT unit_useMenu(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) { CDebug cDbg("unit useMenu"); myUnit* lpUnit = (myUnit*)JS_GetPrivate(cx, obj); *rval = JSVAL_FALSE; if(argc < 1 || !JSVAL_IS_INT(argv[0])) return JS_TRUE; if(!lpUnit || IsBadReadPtr(lpUnit, sizeof(myUnit)) || lpUnit->_dwPrivateType != PRIVATE_UNIT) return JS_TRUE; UnitAny* pUnit = D2CLIENT_FindUnit(lpUnit->dwUnitId, lpUnit->dwType); if(!pUnit) return JS_TRUE; *rval = BOOLEAN_TO_JSVAL(ClickNPCMenu(pUnit->dwTxtFileNo, JSVAL_TO_INT(argv[0]))); return JS_TRUE; }
/* MAKE_EXPORT MessageBoxIndirectW_new=MessageBoxIndirectW */ int WINAPI MessageBoxIndirectW_new(const LPMSGBOXPARAMSW lpMsgBoxParams) { LPSTR lpszText = NULL; LPSTR lpszCaption = NULL; LPSTR lpszIcon = NULL; MSGBOXPARAMSA mbp; if(IsBadReadPtr(lpMsgBoxParams, sizeof(MSGBOXPARAMSW))) return 0; memcpy(&mbp, lpMsgBoxParams, sizeof(MSGBOXPARAMSA)); STACK_WtoA(lpMsgBoxParams->lpszText, lpszText); STACK_WtoA(lpMsgBoxParams->lpszCaption, lpszCaption); STACK_WtoA(lpMsgBoxParams->lpszIcon, lpszIcon); mbp.lpszText = lpszText; mbp.lpszCaption = lpszCaption; mbp.lpszIcon = lpszIcon; return MessageBoxIndirectA(&mbp); }
BOOL CNamedPipeTransport:: Accept( LPOVERLAPPED lpOverlapped) { _ASSERTE( (NULL == lpOverlapped) || (!IsBadReadPtr(lpOverlapped, sizeof(OVERLAPPED)) && NULL != lpOverlapped->hEvent && INVALID_HANDLE_VALUE != lpOverlapped->hEvent)); BOOL fConnected = ::ConnectNamedPipe(m_hPipe, lpOverlapped); if (fConnected) { XTLTRACE1(TRACE_LEVEL_VERBOSE, "Accepting a new connection.\n"); return TRUE; } if (lpOverlapped) { // if overlapped operation ConnectNamedPipe should return FALSE; DWORD dwError = ::GetLastError(); switch (dwError) { case ERROR_PIPE_CONNECTED: ::SetEvent(lpOverlapped->hEvent); // omitting break is intentional case ERROR_IO_PENDING: XTLTRACE1(TRACE_LEVEL_INFORMATION, "Accepting a new connection.\n"); return TRUE; default: // An error occurs during the connect operation XTLTRACE1(TRACE_LEVEL_ERROR, "ConnectNamedPipe failed, error=0x%X\n", GetLastError()); return FALSE; } } return FALSE; }
int CStockManager::GetStocksList(CArray<CodeInfo>* pArInfo, CArray<StockUserInfo>& stockInfo, BOOL bCompareOnlyMainMarket) { if ( m_ayStocks.GetCount() <= 0) { return 0; } if (pArInfo != NULL ) { CHSDSStockInfoIntact* pStock = NULL; CSingleLock lock(&m_mutexStock); if (lock.Lock()) { if (pArInfo->GetSize() > 0) for ( int i=0; i<pArInfo->GetCount(); i++ ) { CodeInfo* pCode = &pArInfo->GetAt(i); if ( pCode && !IsBadReadPtr(pCode, sizeof(CodeInfo))) { int nIndex = -1; m_mapIndex.Lookup(pCode->GetCode(), (CObject*&)nIndex); if ( nIndex >=0 && nIndex<m_ayStocks.GetCount() ) { CHSDSStockInfoIntact* pStock = m_ayStocks.GetAt(nIndex); if (pStock != NULL) { StockUserInfo stock; memset(&stock, 0, sizeof(StockUserInfo)); stock.Copy(&pStock->m_stockInfo); stockInfo.Add(stock); } } } } } lock.Unlock(); return stockInfo.GetSize(); } return 0; }
//请求返回后,调用回调函数 void BaseHTTPRequestHandler::invokeResponseCallback(char *buf,size_t len) { CALLBACK_DATA callback_data; if(buf == NULL || len == 0) return; if(IsBadReadPtr(buf,len)) return; memset(&callback_data, 0, sizeof(CALLBACK_DATA)); callback_data.buf=(char*)malloc(len); memset(callback_data.buf,0,len); memcpy_s(callback_data.buf,len,buf,len); m_pHttpService_Params->response_callback(&callback_data); //处理完之后,清理掉内存 if (callback_data.buf != NULL) { free(callback_data.buf); callback_data.buf = NULL; } }
BOOL CHSDownloadData::DownLoadData() { CriticalGuard guard(&m_critical); long lLen; StockUserInfo* pStock = NULL; short nPeriod; SetTaskMask(m_nCulType); m_nCulType ++; if ( m_nCulType >= 4) m_nCulType = 1; GetNextCode(&pStock, nPeriod); char* pBuffer = MakeReqPacket(&pStock->m_ciStockCode,nPeriod,lLen); if(pBuffer == NULL) { DownLoadData(); } else { HSMarketDataType market = pStock->m_ciStockCode.m_cCodeType & 0xF000; char cServerType = CEV_Connect_HQ; if(market == FUTURES_MARKET) { //cServerType = CEV_Connect_QH; //期货 } if (market == HK_MARKET) { //cServerType = CEV_Connect_GG; //港股 } if ( m_pDataSource && !IsBadReadPtr(m_pDataSource,1)) m_pDataSource->HSDataSource_RequestAsyncData(m_nDataSourceID,pBuffer,lLen,-1,e_DataSouceSend_Normal|e_DataSourceSend_HQDataDownLoad, m_lHandle); TRACE2("\r\n send packet code:%s, nPeriod:%d \r\n", pStock->GetName(),nPeriod); } return TRUE; }
void CGonryunPractice_Decoder:: recPaketProcces_BATTLE_PRACTICE_BATTINGTRADE_CANCEL(playerCharacter_t* pPlayer) { if((TRUE == IsBadWritePtr(pPlayer,sizeof(playerCharacter_t))) || (TRUE == IsBadReadPtr(pPlayer,sizeof(playerCharacter_t)))) { return; } if( (playerCharacter_t::tagGonryunBattlePractice::MEMBERSHIP_LEADER != pPlayer->GonryunBattlePractice.MemberShip) && (playerCharacter_t::tagGonryunBattlePractice::MEMBERSHIP_OPENENT != pPlayer->GonryunBattlePractice.MemberShip) ) { GTH_DisconnectPlayer(pPlayer,FALSE); return; } int Tagetidx = MSG_ReadShort(); playerCharacter_t* pTargetPlayer= gcpTools->GetPlayerRecordPointer(Tagetidx); if(NULL == pTargetPlayer){ GTH_DisconnectPlayer(pPlayer,FALSE); return; } if( (playerCharacter_t::tagGonryunBattlePractice::MEMBERSHIP_LEADER != pTargetPlayer->GonryunBattlePractice.MemberShip) && (playerCharacter_t::tagGonryunBattlePractice::MEMBERSHIP_OPENENT != pTargetPlayer->GonryunBattlePractice.MemberShip) ) { GTH_DisconnectPlayer(pPlayer,FALSE); return; } pPlayer->GonryunBattlePractice.bBattingOkSignal = FALSE; pPlayer->GonryunBattlePractice.bBattingAdmitSignal = FALSE; pTargetPlayer->GonryunBattlePractice.bBattingOkSignal = FALSE; pTargetPlayer->GonryunBattlePractice.bBattingAdmitSignal = FALSE; m_cpVirtualEncoder->SendMessage_BattingTrade_CancelBatting( pPlayer, TRUE ); m_cpVirtualEncoder->SendMessage_BattingTrade_CancelBatting( pTargetPlayer,FALSE ); }
int CStockManager::GetMarketStockList(HSMarketDataType* pMarket, int nMarketCount,CArray<StockUserInfo>& ayRef) { CSingleLock lock(&m_mutexStock); if (lock.Lock()) { int nCount = 0; for ( int i=0; i<m_ayStocks.GetCount(); i++ ) { CHSDSStockInfoIntact* pStockIntact = (CHSDSStockInfoIntact*)m_ayStocks.GetAt(i); HSMarketDataType hsMarketCur = pStockIntact->m_stockInfo.m_ciStockCode.m_cCodeType; BOOL bInMarket = FALSE; if ( pStockIntact && !IsBadReadPtr(pStockIntact,sizeof(CHSDSStockInfoIntact))) { HSMarketDataType hsMarketCur = pStockIntact->m_stockInfo.m_ciStockCode.m_cCodeType; BOOL bInMarket = FALSE; if (pStockIntact != NULL ) { for (int i = 0; i < nMarketCount; i ++) { if (hsMarketCur == pMarket[i]) { bInMarket = TRUE; break; } } } if (bInMarket ) { ayRef.Add(pStockIntact->m_stockInfo); } } } lock.Unlock(); } return ayRef.GetCount(); }
static int dll_intercept(register void* addr) { IMAGE_DOS_HEADER* dosp = (IMAGE_DOS_HEADER*)addr; IMAGE_NT_HEADERS* ntp; IMAGE_EXPORT_DIRECTORY* exp; register int i; register int j; register int base; DWORD* names; WORD* ordinals; DWORD* functions; char* name; void* fun; if (IsBadReadPtr(addr, sizeof(*dosp))) return 0; if (dosp->e_magic != IMAGE_DOS_SIGNATURE) return 0; ntp = ptr(IMAGE_NT_HEADERS, dosp, dosp->e_lfanew); exp = ptr(IMAGE_EXPORT_DIRECTORY, addr, ntp->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress); if ((void*)exp == (void*)ntp) return 1; base = exp->Base - 1; names = ptr(DWORD, addr, exp->AddressOfNames); ordinals = ptr(WORD, addr, exp->AddressOfNameOrdinals); functions = ptr(DWORD, addr, exp->AddressOfFunctions); for (i = j = 0; i < (int)exp->NumberOfNames; i++) { name = ptr(char, addr, names[i]); if (strcmp(name, sys_call[j].name) == 0) { fun = ptr(void, addr, functions[ordinals[i]-base]); sys_call[j].actual = (Syscall_f)fun; trace_error(-2, "%3d %3d %p %s", i, j, fun, name); if (++j >= elementsof(sys_call)) return 1; } }
// Get string file info. // Key name is something like "CompanyName". BOOL CVersion::GetValue(LPCTSTR lpKeyName,LPTSTR szValue) { TCHAR sz[MAX_PATH]; UINT iLenVal; LPVOID lpvi; if (!this->pVersionInfo) return FALSE; if (IsBadWritePtr(szValue,1)) return FALSE; if (IsBadReadPtr(lpKeyName,1)) return FALSE; *szValue=0; // To get a string value must pass query in the form // // "\StringFileInfo\<langID><codepage>\keyname" // // where <lang-codepage> is the languageID concatenated with the // code page, in hex. Wow. // _stprintf(sz,_TEXT("\\StringFileInfo\\%04x%04x\\%s"), this->LangAndCodePage.wLanguage, this->LangAndCodePage.wCodePage, lpKeyName); if(!VerQueryValue(this->pVersionInfo,sz,&lpvi,&iLenVal)) return FALSE; if (iLenVal>MAX_PATH) iLenVal=MAX_PATH; memcpy(szValue,lpvi,iLenVal*sizeof(TCHAR)); return TRUE; }
NEWAPI BOOL WINAPI VFindNextFileW( HANDLE hFindFile, LPWIN32_FIND_DATAW lpFindFileData ) { BOOL retValue = FALSE; //find a file RESTORE_API(FindNextFileW); OLDCALL(FindNextFileW, 2); REPLACE_API(FindNextFileW); if (retValue) { if (!IsBadReadPtr(lpFindFileData, sizeof(WIN32_FIND_DATAW))) { //while we are finding a hidden file RESTORE_API(FindNextFileW); while (posw0(lpFindFileData->cFileName) != MAXDWORD) { //get next file retValue = FindNextFileW(hFindFile, lpFindFileData); //if there is no file to get then fail if (!retValue) { //we keep the error from FindNextFileW, NO SetLastError(ERROR_NO_MORE_FILES); break; } } REPLACE_API(FindNextFileW); } } return retValue; }
//----------------------------------------------------------------------------- // Name: ReplaceText // Object: change text of a button // Parameters : // in : int ButtonID : button id // TCHAR* NewToolTipText : new text associated with tooltip // out : // return : TRUE on success, FALSE on error //----------------------------------------------------------------------------- BOOL CToolbar::ReplaceToolTipText(int ButtonID,TCHAR* NewToolTipText) { TBBUTTONINFO ButtonInfo={0}; // retrieve button param ButtonInfo.dwMask=TBIF_LPARAM; ButtonInfo.cbSize=sizeof(TBBUTTONINFO); // get button info if (SendMessage( this->hwndTB,(UINT) TB_GETBUTTONINFO,(WPARAM) ButtonID,(LPARAM) &ButtonInfo)==-1) return FALSE; if (IsBadReadPtr((PVOID)ButtonInfo.lParam,sizeof(CToolbarButtonUserData))) return FALSE; // change tooltip ((CToolbarButtonUserData*)ButtonInfo.lParam)->SetToolTip(NewToolTipText); // set button info if (SendMessage( this->hwndTB,(UINT) TB_SETBUTTONINFO,(WPARAM) ButtonID,(LPARAM) &ButtonInfo)==-1) return FALSE; return TRUE; }
static char * hexdump8(char * out,unsigned address,const char * msg,int from,int to) { unsigned max = (to-from)*16; if (!IsBadReadPtr((const void*)(address+(from*16)),max)) { out += sprintf(out,"%s (%08Xh):",msg,address); unsigned n; const unsigned char * src = (const unsigned char*)(address)+(from*16); for(n=0;n<max;n++) { if (n%16==0) { out += sprintf(out,"\n%08Xh: ",src); } out += sprintf(out," %02X",*(src++)); } *(out++) = '\n'; *out=0; } return out; }
void CGonryunPractice_Decoder:: recPaketProcces_BATTLE_PRACTICE_BATTINGTRADE_OK(playerCharacter_t* pPlayer) { if((TRUE == IsBadWritePtr(pPlayer,sizeof(playerCharacter_t))) || (TRUE == IsBadReadPtr(pPlayer,sizeof(playerCharacter_t)))) { return; } int TargetIdx = MSG_ReadShort(); playerCharacter_t* pTargetPlayer= gcpTools->GetPlayerRecordPointer(TargetIdx); if(NULL == pTargetPlayer) { GTH_DisconnectPlayer(pPlayer,FALSE); return; } pPlayer->GonryunBattlePractice.bBattingOkSignal = TRUE; m_cpVirtualEncoder->SendMessage_BattingTrade_OkBatting( pPlayer, TRUE ); m_cpVirtualEncoder->SendMessage_BattingTrade_OkBatting( pTargetPlayer, FALSE ); }
PBYTE get_valid_frame(PBYTE esp) { PDWORD cur_stack_loc = NULL; const int max_search = 400; WCHAR module_name[MAX_PATH]; PBYTE module_addr = 0; // round to highest multiple of four esp = (esp + (4 - ((int)esp % 4)) % 4); // scroll through stack a few hundred places. for (cur_stack_loc = (PDWORD) esp; cur_stack_loc < (PDWORD)esp + max_search; cur_stack_loc += 1) { // if you can read the pointer, if (IsBadReadPtr(cur_stack_loc, sizeof(PDWORD))) { continue; } // check if it's in a module if (!Get_Module_By_Ret_Addr((PBYTE)*cur_stack_loc, module_name, module_addr)) { continue; } // check if the code before the instruction ptr is a call if(!has_valid_call_before(cur_stack_loc)) { continue; } // if these all pass, return that ebp, otherwise continue till we're dead return (PBYTE)(cur_stack_loc - 1); } return NULL; }
bool dbgsymengine::stack_first (CONTEXT* pctx) { if (!pctx || IsBadReadPtr(pctx, sizeof(CONTEXT))) return false; if (!check()) return false; if (!m_pframe) { m_pframe = new STACKFRAME; if (!m_pframe) return false; } memset(m_pframe, 0, sizeof(STACKFRAME)); #ifdef _X86_ m_pframe->AddrPC.Offset = pctx->Eip; m_pframe->AddrPC.Mode = AddrModeFlat; m_pframe->AddrStack.Offset = pctx->Esp; m_pframe->AddrStack.Mode = AddrModeFlat; m_pframe->AddrFrame.Offset = pctx->Ebp; m_pframe->AddrFrame.Mode = AddrModeFlat; #else m_pframe->AddrPC.Offset = (DWORD)pctx->Fir; m_pframe->AddrPC.Mode = AddrModeFlat; m_pframe->AddrReturn.Offset = (DWORD)pctx->IntRa; m_pframe->AddrReturn.Mode = AddrModeFlat; m_pframe->AddrStack.Offset = (DWORD)pctx->IntSp; m_pframe->AddrStack.Mode = AddrModeFlat; m_pframe->AddrFrame.Offset = (DWORD)pctx->IntFp; m_pframe->AddrFrame.Mode = AddrModeFlat; #endif m_pctx = pctx; return stack_next(); }
BOOL FixThunk(LONG dwLong) { _WndProcThunk* pThunk = (_WndProcThunk*)dwLong; MEMORY_BASIC_INFORMATION mbi; DWORD dwOldProtect; if (IsBadReadPtr(pThunk, sizeof(_WndProcThunk)) || !CheckThunk(pThunk)) { return TRUE; } if (VirtualQuery((LPCVOID)pThunk, &mbi, sizeof(MEMORY_BASIC_INFORMATION)) == 0) { return FALSE; } // The memory is already PAGE_EXECUTE_READWRITE, so don't need fixing if (mbi.AllocationProtect == PAGE_EXECUTE_READWRITE) { return TRUE; } return VirtualProtect((LPVOID)pThunk, sizeof(_WndProcThunk), PAGE_EXECUTE_READWRITE, &dwOldProtect); }
static cell AMX_NATIVE_CALL get_pdata_string(AMX *amx, cell *params) { int index=params[1]; CHECK_ENTITY(index); int iOffset=params[2]; CHECK_OFFSET(iOffset); #if defined( __linux__ ) iOffset += params[6]; #elif defined( __APPLE__ ) // Use Linux offset in older plugins if (params[0] / sizeof(cell) == 6 || params[7] == CELL_MIN) iOffset += params[6]; else iOffset += params[7]; #endif edict_t *pEdict = TypeConversion.id_to_edict(index); char *szData; if (params[5]) { szData = get_pdata<char*>(pEdict, iOffset); } else { szData = get_pdata_direct<char*>(pEdict, iOffset); } if (IsBadReadPtr(szData, 1)) { return 0; } MF_SetAmxString(amx, params[3], szData, params[4]); return 1; }
void BuildStackTrace( char* buffer, int size ) { int i, j; DWORD* sp; DWORD stackTrace[MAX_STACK_TRACE_LINES]; sp = ( DWORD * )( m_exPointers->ContextRecord->Ebp ); for ( i = 0; i < MAX_STACK_TRACE_LINES; i++ ) { if ( !IsBadReadPtr( sp, sizeof( DWORD ) ) && *sp ) { DWORD* np = (DWORD*)*sp; stackTrace[i] = *( sp + 1 ); sp = np; } else { stackTrace[i] = 0; } } for ( i = 0; i < MAX_STACK_TRACE_LINES; i++ ) { if ( i == 0 ) { Q_strcat( buffer, size, "Stack Trace : " ); } else { Q_strcat( buffer, size, " : " ); } for ( j = 0; j < 4 && i < MAX_STACK_TRACE_LINES; i++, j++ ) { char minibuffer[16]; Com_sprintf( minibuffer, sizeof( minibuffer ), "%.8x ", stackTrace[i] ); Q_strcat( buffer, size, minibuffer ); } Q_strcat( buffer, size, "\r\n" ); } // MessageBox( g_hWnd, buffer, "Arf!", MB_OK ); }
/* MAKE_EXPORT SetMenuItemInfoW_new=SetMenuItemInfoW */ BOOL WINAPI SetMenuItemInfoW_new(HMENU hMenu, UINT uItem, BOOL fByPosition, LPCMENUITEMINFO lpmii) { MENUITEMINFOA mii; BOOL result; LPSTR lpTypeData; if(IsBadReadPtr(lpmii, sizeof(MENUITEMINFOW))) return FALSE; memcpy(&mii, lpmii, sizeof(MENUITEMINFOA)); lpTypeData = NULL; STACK_WtoA(lpmii->dwTypeData, lpTypeData); mii.dwTypeData = lpTypeData; result = SetMenuItemInfoA(hMenu, uItem, fByPosition, lpmii); if(!result) return FALSE; return TRUE; }
int KFuncTable::InterceptWin32(const char *ModuleName, const char * baseAddress) { int no = 0; PIMAGE_DOS_HEADER pDOSHeader = (PIMAGE_DOS_HEADER) baseAddress; if ( IsBadReadPtr(baseAddress, sizeof(PIMAGE_NT_HEADERS)) ) return 0; if ( pDOSHeader->e_magic != IMAGE_DOS_SIGNATURE ) return 0; PIMAGE_NT_HEADERS pNTHeader = (PIMAGE_NT_HEADERS) ( baseAddress + pDOSHeader->e_lfanew); if ( pNTHeader->Signature != IMAGE_NT_SIGNATURE ) return 0; PIMAGE_IMPORT_DESCRIPTOR pImportDesc = (PIMAGE_IMPORT_DESCRIPTOR) ( baseAddress + pNTHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress ); // Bail out if the RVA of the imports section is 0 (it doesn't exist) if ( pImportDesc == (PIMAGE_IMPORT_DESCRIPTOR) pNTHeader ) return 0; while ( pImportDesc->Name ) { no += InterceptWin32(ModuleName, (const char *) ( baseAddress + pImportDesc->Name ), (PIMAGE_THUNK_DATA) ( baseAddress + (unsigned) pImportDesc->OriginalFirstThunk), (PIMAGE_THUNK_DATA) ( baseAddress + (unsigned) pImportDesc->FirstThunk), baseAddress); pImportDesc++; } return no; }
void CrashLog_LogStacktrace(char *buffer) { uint32* b; int i, j; strcat(buffer, "Stack trace:\n"); #ifdef _M_AMD64 b = (uint32*)s_ep->ContextRecord->Rsp; #else b = (uint32*)s_ep->ContextRecord->Esp; #endif for (j = 0; j != 24; j++) { for (i = 0; i != 8; i++) { if (IsBadReadPtr(b, sizeof(uint32))) { strcat(buffer, " ????????"); } else { sprintf(buffer + strlen(buffer), " %.8X", *b); } b++; } strcat(buffer, "\n"); } strcat(buffer, "\n"); }
/*********************************************************************** * IsBadCodePtr (KERNEL32.@) * * Check for read access on a memory address. * * PARAMS * ptr [I] Address of function. * * RETURNS * Success: TRUE. * Failure: FALSE. Process has read access to specified memory. */ BOOL WINAPI IsBadCodePtr( FARPROC ptr ) { return IsBadReadPtr( ptr, 1 ); }
STDMETHODIMP CUUEngine::get_DFileDetail(short row, short itemno, short subscr, VARIANT *pVal) { MString cs; CComVariant lv; int *ip; struct _uufile *ufp; long lct; uulist *l = ue.GetUulp(row); if (l == NULL) return(CTL_E_INVALIDPROPERTYARRAYINDEX); switch (itemno) { case UUVBLD_STATE: lv = l->state; break; case UUVBLD_MODE: lv = l->mode; break; case UUVBLD_BEGIN: lv = (short) l->begin; break; case UUVBLD_END: lv = (short) l->end; break; case UUVBLD_UUDET: lv = l->uudet; break; case UUVBLD_FLAGS: lv = (short) l->flags; break; case UUVBLD_SIZE: lv = l->size; break; case UUVBLD_FILEN: cs = l->filename; break; case UUVBLD_SUBF: cs = l->subfname; break; case UUVBLD_MIMEID: cs = l->mimeid; break; case UUVBLD_MIMETYPE: cs = l->mimetype; break; case UUVBLD_BINFILE: cs = l->binfile; break; case UUVBLD_HAVEPART: case UUVBLD_MISSPART: if (subscr < 0 || subscr > 255) return(CTL_E_INVALIDPROPERTYARRAYINDEX); ip = ((itemno == UUVBLD_HAVEPART) ? l->haveparts : l->misparts) + subscr; if (IsBadReadPtr(ip, sizeof(int))) return(CTL_E_INVALIDPROPERTYARRAYINDEX); lv = (short) *ip; break; case UUVBLD_UFPART: if (subscr < 0 || subscr > 255) return(CTL_E_INVALIDPROPERTYARRAYINDEX); for (ufp=l->thisfile; ufp != NULL && subscr > 0; subscr--) ufp = ufp->NEXT; if (ufp == NULL) return(CTL_E_INVALIDPROPERTYARRAYINDEX); lv = ufp->partno; break; case UUVBLD_UFRSUBJ: case UUVBLD_UFRORG: case UUVBLD_UFRSFN: case UUVBLD_UFRSTART: // uulist.thisfile[subscr].data.start case UUVBLD_UFRLEN: // uulist.thisfile[subscr].data.length if (subscr < 0 || subscr > 255) return(CTL_E_INVALIDPROPERTYARRAYINDEX); for (ufp=l->thisfile; ufp != NULL && subscr > 0; subscr--) ufp = ufp->NEXT; if (ufp == NULL || ufp->data == NULL) return(CTL_E_INVALIDPROPERTYARRAYINDEX); switch (itemno) { case UUVBLD_UFRSUBJ: cs = ufp->data->subject; break; case UUVBLD_UFRORG: cs = ufp->data->origin; break; case UUVBLD_UFRSFN: cs = ufp->data->sfname; break; case UUVBLD_UFRSTART: // uulist.thisfile[subscr].data.start lv = ufp->data->startpos; break; case UUVBLD_UFRLEN: // uulist.thisfile[subscr].data.length lv = ufp->data->length; break; } break; case UUVBLD_UFRCOUNT: // Figure out the number of parts this subsection has lct = 0; ufp = l->thisfile; while (ufp != NULL) { ufp = ufp->NEXT; lct++; } lv = lct; break; } if (!cs.IsEmpty()) // This is a string return { lv.vt = VT_BSTR; cs.ToBSTR(&lv.bstrVal); } lv.Copy(pVal); return S_OK; }
/*********************************************************************** * IsBadHugeReadPtr (KERNEL32.@) * * Check for read access on a memory block. * * PARAMS * ptr [I] Address of memory block. * size [I] Size of block. * * RETURNS * Success: TRUE. * Failure: FALSE. Process has read access to entire block. */ BOOL WINAPI IsBadHugeReadPtr( LPCVOID ptr, UINT size ) { return IsBadReadPtr( ptr, size ); }
BOOL AwtPrintControl::UpdateAttributes(JNIEnv *env, jobject printCtrl, PRINTDLG &pd) { DEVNAMES *devnames = NULL; DEVMODE *devmode = NULL; unsigned int copies = 1; DWORD pdFlags = pd.Flags; DWORD dmFields = 0, dmValues = 0; bool newDC = false; // This call ensures that default PrintService gets updated for the // case where initially, there weren't any printers. env->CallObjectMethod(printCtrl, AwtPrintControl::getPrinterID); if (pd.hDevMode != NULL) { devmode = (DEVMODE *)::GlobalLock(pd.hDevMode); DASSERT(!IsBadReadPtr(devmode, sizeof(DEVMODE))); } if (devmode != NULL) { /* Query the settings we understand and are interested in. * For the flags that are set in dmFields, where the values * are a simple enumeration, set the same bits in a clean dmFields * variable, and set bits in a dmValues variable to indicate the * selected value. These can all be passed up to Java in one * call to sync up the Java view of this. */ if (devmode->dmFields & DM_COPIES) { dmFields |= DM_COPIES; copies = devmode->dmCopies; if (pd.nCopies == 1) { env->SetBooleanField(printCtrl, driverDoesMultipleCopiesID, JNI_TRUE); } else { copies = pd.nCopies; } } if (devmode->dmFields & DM_PAPERSIZE) { env->CallVoidMethod(printCtrl, AwtPrintControl::setWin32MediaID, devmode->dmPaperSize, devmode->dmPaperWidth, devmode->dmPaperLength); } if (devmode->dmFields & DM_DEFAULTSOURCE) { env->CallVoidMethod(printCtrl, AwtPrintControl::setWin32MediaTrayID, devmode->dmDefaultSource); } if (devmode->dmFields & DM_COLOR) { dmFields |= DM_COLOR; if (devmode->dmColor == DMCOLOR_COLOR) { dmValues |= SET_COLOR; } } if (devmode->dmFields & DM_ORIENTATION) { dmFields |= DM_ORIENTATION; if (devmode->dmOrientation == DMORIENT_LANDSCAPE) { dmValues |= SET_ORIENTATION; } } if (devmode->dmFields & DM_COLLATE) { dmFields |= DM_COLLATE; if (devmode->dmCollate == DMCOLLATE_TRUE) { pdFlags |= PD_COLLATE; env->SetBooleanField(printCtrl, driverDoesCollationID, JNI_TRUE); } else { pdFlags &= ~PD_COLLATE; } } if (devmode->dmFields & DM_PRINTQUALITY) { /* value < 0 indicates quality setting. * value > 0 indicates X resolution. In that case * hopefully we will also find y-resolution specified. * If its not, assume its the same as x-res. * Maybe Java code should try to reconcile this against * the printers claimed set of supported resolutions. */ if (devmode->dmPrintQuality < 0) { if (dmFields |= DM_PRINTQUALITY) { if (devmode->dmPrintQuality == DMRES_HIGH) { dmValues |= SET_RES_HIGH; } else if ((devmode->dmPrintQuality == DMRES_LOW) || (devmode->dmPrintQuality == DMRES_DRAFT)) { dmValues |= SET_RES_LOW; } else if (devmode->dmPrintQuality == DMRES_MEDIUM) { /* default */ } } } else { int xRes = devmode->dmPrintQuality; int yRes = (devmode->dmFields & DM_YRESOLUTION) ? devmode->dmYResolution : devmode->dmPrintQuality; env->CallVoidMethod(printCtrl, AwtPrintControl::setResID, xRes, yRes); } } if (devmode->dmFields & DM_DUPLEX) { dmFields |= DM_DUPLEX; if (devmode->dmDuplex == DMDUP_HORIZONTAL) { dmValues |= SET_DUP_HORIZONTAL; } else if (devmode->dmDuplex == DMDUP_VERTICAL) { dmValues |= SET_DUP_VERTICAL; } } ::GlobalUnlock(pd.hDevMode); devmode = NULL; } else { copies = pd.nCopies; } if (pd.hDevNames != NULL) { DEVNAMES *devnames = (DEVNAMES*)::GlobalLock(pd.hDevNames); DASSERT(!IsBadReadPtr(devnames, sizeof(DEVNAMES))); LPTSTR lpcNames = (LPTSTR)devnames; LPTSTR pbuf = (_tcslen(lpcNames + devnames->wDeviceOffset) == 0 ? TEXT("") : lpcNames + devnames->wDeviceOffset); if (pbuf != NULL) { jstring jstr = JNU_NewStringPlatform(env, pbuf); env->CallVoidMethod(printCtrl, AwtPrintControl::setPrinterID, jstr); env->DeleteLocalRef(jstr); } pbuf = (_tcslen(lpcNames + devnames->wOutputOffset) == 0 ? TEXT("") : lpcNames + devnames->wOutputOffset); if (pbuf != NULL) { if (wcscmp(pbuf, L"FILE:") == 0) { pdFlags |= PD_PRINTTOFILE; } } ::GlobalUnlock(pd.hDevNames); devnames = NULL; } env->CallVoidMethod(printCtrl, AwtPrintControl::setNativeAttID, pdFlags, dmFields, dmValues); // copies & range are always set so no need to check for any flags env->CallVoidMethod(printCtrl, AwtPrintControl::setRangeCopiesID, pd.nFromPage, pd.nToPage, (pdFlags & PD_PAGENUMS), copies); // repeated calls to printDialog should not leak handles HDC oldDC = AwtPrintControl::getPrintDC(env, printCtrl); if (pd.hDC != oldDC) { if (oldDC != NULL) { ::DeleteDC(oldDC); } AwtPrintControl::setPrintDC(env, printCtrl, pd.hDC); newDC = true; } // Need to update WPrinterJob with device resolution settings for // new or changed DC. setCapabilities(env, printCtrl, pd.hDC); HGLOBAL oldG = AwtPrintControl::getPrintHDMode(env, printCtrl); if (pd.hDevMode != oldG) { AwtPrintControl::setPrintHDMode(env, printCtrl, pd.hDevMode); } oldG = AwtPrintControl::getPrintHDName(env, printCtrl); if (pd.hDevNames != oldG) { AwtPrintControl::setPrintHDName(env, printCtrl, pd.hDevNames); } return newDC; }
/* 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; } } #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; }
/*---------------------------------------------------------------------- FUNCTION : GetNamedImportDescriptor DISCUSSION : Gets the import descriptor for the requested module. If the module is not imported in hModule, NULL is returned. This is a potential useful function in the future. PARAMETERS : hModule - The module to hook in. szImportMod - The module name to get the import descriptor for. RETURNS : NULL - The module was not imported or hModule is invalid. !NULL - The import descriptor. ----------------------------------------------------------------------*/ PIMAGE_IMPORT_DESCRIPTOR GetNamedImportDescriptor ( HMODULE hModule , LPCSTR szImportMod ) { // Always check parameters. ASSERT ( NULL != szImportMod ) ; ASSERT ( NULL != hModule ) ; if ( ( NULL == szImportMod ) || ( NULL == hModule ) ) { SetLastErrorEx ( ERROR_INVALID_PARAMETER , SLE_ERROR ) ; return ( NULL ) ; } PIMAGE_DOS_HEADER pDOSHeader = (PIMAGE_DOS_HEADER)hModule ; // Is this the MZ header? if ( ( TRUE == IsBadReadPtr ( pDOSHeader , sizeof ( IMAGE_DOS_HEADER ) ) ) || ( IMAGE_DOS_SIGNATURE != pDOSHeader->e_magic ) ) { ASSERT ( FALSE ) ; SetLastErrorEx ( ERROR_INVALID_PARAMETER , SLE_ERROR ) ; return ( NULL ) ; } // Get the PE header. PIMAGE_NT_HEADERS pNTHeader = MakePtr ( PIMAGE_NT_HEADERS , pDOSHeader , pDOSHeader->e_lfanew ) ; // Is this a real PE image? if ( ( TRUE == IsBadReadPtr ( pNTHeader , sizeof ( IMAGE_NT_HEADERS ) ) ) || ( IMAGE_NT_SIGNATURE != pNTHeader->Signature ) ) { ASSERT ( FALSE ) ; SetLastErrorEx ( ERROR_INVALID_PARAMETER , SLE_ERROR ) ; return ( NULL ) ; } // If there is no imports section, leave now. if ( 0 == pNTHeader->OptionalHeader. DataDirectory[ IMAGE_DIRECTORY_ENTRY_IMPORT ]. VirtualAddress ) { return ( NULL ) ; } // Get the pointer to the imports section. PIMAGE_IMPORT_DESCRIPTOR pImportDesc = MakePtr ( PIMAGE_IMPORT_DESCRIPTOR , pDOSHeader , pNTHeader->OptionalHeader. DataDirectory[ IMAGE_DIRECTORY_ENTRY_IMPORT ]. VirtualAddress ) ; // Loop through the import module descriptors looking for the // module whose name matches szImportMod. while ( NULL != pImportDesc->Name ) { PSTR szCurrMod = MakePtr ( PSTR , pDOSHeader , pImportDesc->Name ) ; if ( 0 == _stricmp ( szCurrMod , szImportMod ) ) { // Found it. break ; } // Look at the next one. pImportDesc++ ; } // If the name is NULL, then the module is not imported. if ( NULL == pImportDesc->Name ) { return ( NULL ) ; } // All OK, Jumpmaster! return ( pImportDesc ) ; }
BOOL BUGSUTIL_DLLINTERFACE __stdcall HookImportedFunctionsByName ( HMODULE hModule , LPCSTR szImportMod , UINT uiCount , LPHOOKFUNCDESCA paHookArray , PROC * paOrigFuncs , LPDWORD pdwHooked ) { // Double check the parameters. ASSERT ( NULL != szImportMod ) ; ASSERT ( 0 != uiCount ) ; ASSERT ( FALSE == IsBadReadPtr ( paHookArray , sizeof (HOOKFUNCDESC) * uiCount )); #ifdef _DEBUG if ( NULL != paOrigFuncs ) { ASSERT ( FALSE == IsBadWritePtr ( paOrigFuncs , sizeof ( PROC ) * uiCount ) ); } if ( NULL != pdwHooked ) { ASSERT ( FALSE == IsBadWritePtr ( pdwHooked , sizeof ( UINT ))); } // Check each function name in the hook array. { for ( UINT i = 0 ; i < uiCount ; i++ ) { ASSERT ( NULL != paHookArray[ i ].szFunc ) ; ASSERT ( '\0' != *paHookArray[ i ].szFunc ) ; // If the proc is not NULL, then it is checked. if ( NULL != paHookArray[ i ].pProc ) { ASSERT ( FALSE == IsBadCodePtr ( paHookArray[i].pProc)); } } } #endif // Do the parameter validation for real. if ( ( 0 == uiCount ) || ( NULL == szImportMod ) || ( TRUE == IsBadReadPtr ( paHookArray , sizeof (HOOKFUNCDESC) * uiCount ) ) ) { SetLastErrorEx ( ERROR_INVALID_PARAMETER , SLE_ERROR ) ; return ( FALSE ) ; } if ( ( NULL != paOrigFuncs ) && ( TRUE == IsBadWritePtr ( paOrigFuncs , sizeof ( PROC ) * uiCount ) ) ) { SetLastErrorEx ( ERROR_INVALID_PARAMETER , SLE_ERROR ) ; return ( FALSE ) ; } if ( ( NULL != pdwHooked ) && ( TRUE == IsBadWritePtr ( pdwHooked , sizeof ( UINT ) ) ) ) { SetLastErrorEx ( ERROR_INVALID_PARAMETER , SLE_ERROR ) ; return ( FALSE ) ; } // Is this a system DLL, which Windows95 will not let you patch // since it is above the 2GB line? if ( ( FALSE == IsNT ( ) ) && ( (DWORD)hModule >= 0x80000000 ) ) { SetLastErrorEx ( ERROR_INVALID_HANDLE , SLE_ERROR ) ; return ( FALSE ) ; } // TODO TODO // Should each item in the hook array be checked in release builds? if ( NULL != paOrigFuncs ) { // Set all the values in paOrigFuncs to NULL. memset ( paOrigFuncs , NULL , sizeof ( PROC ) * uiCount ) ; } if ( NULL != pdwHooked ) { // Set the number of functions hooked to zero. *pdwHooked = 0 ; } // Get the specific import descriptor. PIMAGE_IMPORT_DESCRIPTOR pImportDesc = GetNamedImportDescriptor ( hModule , szImportMod ); if ( NULL == pImportDesc ) { // The requested module was not imported. This is not an error. return ( TRUE ) ; } // Get the original thunk information for this DLL. I cannot use // the thunk information stored in the pImportDesc->FirstThunk // because the that is the array that the loader has already // bashed to fix up all the imports. This pointer gives us acess // to the function names. PIMAGE_THUNK_DATA pOrigThunk = MakePtr ( PIMAGE_THUNK_DATA , hModule , pImportDesc->OriginalFirstThunk ) ; // Get the array pointed to by the pImportDesc->FirstThunk. This is // where I will do the actual bash. PIMAGE_THUNK_DATA pRealThunk = MakePtr ( PIMAGE_THUNK_DATA , hModule , pImportDesc->FirstThunk ); // Loop through and look for the one that matches the name. while ( NULL != pOrigThunk->u1.Function ) { // Only look at those that are imported by name, not ordinal. if ( IMAGE_ORDINAL_FLAG != ( pOrigThunk->u1.Ordinal & IMAGE_ORDINAL_FLAG )) { // Look get the name of this imported function. PIMAGE_IMPORT_BY_NAME pByName ; pByName = MakePtr ( PIMAGE_IMPORT_BY_NAME , hModule , pOrigThunk->u1.AddressOfData ) ; // If the name starts with NULL, then just skip out now. if ( '\0' == pByName->Name[ 0 ] ) { continue ; } // Determines if we do the hook. BOOL bDoHook = FALSE ; // TODO TODO // Might want to consider bsearch here. // See if the particular function name is in the import // list. It might be good to consider requiring the // paHookArray to be in sorted order so bsearch could be // used so the lookup will be faster. However, the size of // uiCount coming into this function should be rather // small but it is called for each function imported by // szImportMod. for ( UINT i = 0 ; i < uiCount ; i++ ) { if ( ( paHookArray[i].szFunc[0] == pByName->Name[0] ) && ( 0 == _strcmpi ( paHookArray[i].szFunc , (char*)pByName->Name ) ) ) { // If the proc is NULL, kick out, otherwise go // ahead and hook it. if ( NULL != paHookArray[ i ].pProc ) { bDoHook = TRUE ; } break ; } } if ( TRUE == bDoHook ) { // I found it. Now I need to change the protection to // writable before I do the blast. Note that I am now // blasting into the real thunk area! MEMORY_BASIC_INFORMATION mbi_thunk ; VirtualQuery ( pRealThunk , &mbi_thunk , sizeof ( MEMORY_BASIC_INFORMATION ) ) ; VERIFY ( VirtualProtect ( mbi_thunk.BaseAddress , mbi_thunk.RegionSize , PAGE_READWRITE , &mbi_thunk.Protect ) ) ; // Save the original address if requested. if ( NULL != paOrigFuncs ) { paOrigFuncs[i] = (PROC)pRealThunk->u1.Function ; } // Do the actual hook. pRealThunk->u1.Function = (DWORD)paHookArray[i].pProc ; DWORD dwOldProtect ; // Change the protection back to what it was before I // blasted. VERIFY ( VirtualProtect ( mbi_thunk.BaseAddress , mbi_thunk.RegionSize , mbi_thunk.Protect , &dwOldProtect ) ) ; if ( NULL != pdwHooked ) { // Increment the total number hooked. *pdwHooked += 1 ; } } } // Increment both tables. pOrigThunk++ ; pRealThunk++ ; } // All OK, JumpMaster! SetLastError ( ERROR_SUCCESS ) ; return ( TRUE ) ; }
HRESULT WriteToBuffer(LPTSTR &lpszBuffer, //[in,out]Destination pointer where the buffer is located LPCTSTR lpszString, //[in]String to be copied to the buffer BOOL bRefresh) //[in]Initialize the buffer if it is TRUE, default is FALSE { DWORD dwSize = 0; try { if(NULL == lpszString) { return E_POINTER; } //Get the actual size of the string dwSize = _tcslen(lpszString); if(NULL == lpszBuffer) { //allocate the required initial memory DWORD dwMemoryReq = g_dwExtraBuffer + dwSize; lpszBuffer = new TCHAR [dwMemoryReq + 1]; if(NULL == lpszBuffer) { //allocation failed return ERROR_NOT_ENOUGH_MEMORY; } //allocation successful, set the memory //_tcsnset(lpszBuffer,_T('\0'),dwMemoryReq); memset(lpszBuffer,_T('\0'),dwMemoryReq); //copy the source string to the destination _tcscpy(lpszBuffer,lpszString); } else { //Check for the validity of the lpszBuffer pointer BOOL bRet1 = IsBadWritePtr(lpszBuffer,1); BOOL bRet2 = IsBadReadPtr(lpszBuffer,1); if(0 != bRet1 || 0 != bRet2) { //bad memory pointer, allocate a new memory DWORD dwMemoryReq = g_dwExtraBuffer + dwSize; lpszBuffer = new TCHAR [dwMemoryReq + 1]; if(NULL == lpszBuffer) { return ERROR_NOT_ENOUGH_MEMORY; } //allocation successful, set the memory //_tcsnset(lpszBuffer,_T('\0'),dwMemoryReq); memset(lpszBuffer,_T('\0'),dwMemoryReq); } //see whether the current memory is sufficient to add the string to the buffer DWORD dwActualSize = _msize(lpszBuffer); --dwActualSize; DWORD dwSizeUsed = _tcslen(lpszBuffer); //Initialize the buffer if set to TRUE if(TRUE == bRefresh) { //_tcsnset(lpszBuffer,_T('\0'),dwActualSize); memset(lpszBuffer,_T('\0'),dwActualSize); dwSizeUsed = 0; } //calculate the required size for the store string & the string to be stored DWORD dwReqSize = dwSizeUsed + dwSize + 1; if(dwReqSize > dwActualSize) { //Memory is insufficient allocate a new block DWORD dwMemoryReq = g_dwExtraBuffer + dwReqSize; LPTSTR lpszTemp = new TCHAR[dwMemoryReq + 1]; if(NULL == lpszTemp) { //allocation failed return ERROR_NOT_ENOUGH_MEMORY; } //allocation found successful, initialize the mem block //_tcsnset(lpszTemp,_T('\0'),dwMemoryReq); memset(lpszTemp,_T('\0'),dwMemoryReq); //copy the old string back to the newly allocated block _tcscpy(lpszTemp,lpszBuffer); //delete the old allocated block try { delete [] lpszBuffer; } catch(...) { //Something has gone wrong while deleting, it might be Corrupt Memory lpszBuffer = NULL; //Store the newly allocated memory lpszBuffer = lpszTemp; //copy the final string _tcscpy(lpszBuffer,lpszString); return S_OK; } lpszBuffer = NULL; lpszBuffer = lpszTemp; //copy the final string _tcscat(lpszBuffer,lpszString); } else { //Memory is sufficient copy the string _tcscat(lpszBuffer,lpszString); } } } catch(...) { //some thing has gone wrong ??????? return E_FAIL; } return S_OK; }