CMemAlloc::~CMemAlloc(void) { if(m_hHeap != NULL) HeapDestroy(m_hHeap); }
INT _tmain(DWORD argc, LPCTSTR argv[]) { FileInformation fCurrent = {0, 0, 0, 0, NULL}; HANDLE hConfig = NULL, hParserHeap = NULL; ServiceSpecArray sEntries = NULL; LPTSTR lpFileData = NULL; DWORD dwRet = 0; if(argc == 2) { __try { hParserHeap = HeapCreate((HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY | HEAP_GENERATE_EXCEPTIONS), 0, 0); sEntries = (ServiceSpecArray)HeapAlloc(hParserHeap, (HEAP_NO_SERIALIZE | HEAP_GENERATE_EXCEPTIONS), sizeof(ServSpec)); } __except(ExceptionFilter(GetExceptionCode(), NULL)) { ReportSysError(GetLastError()); return 2; } hConfig = OpenServiceFile(argv[1]); if(hConfig) { INT32 fileSize = GetValidFileSize(hConfig); if(fileSize > 0) { lpFileData = (LPTSTR)HeapAlloc(hParserHeap, (HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY), (fileSize * sizeof(TCHAR))); if(ReadFileData(hConfig, lpFileData, fileSize) == 0) { dwRet = ParseData(lpFileData, &fCurrent, sEntries, hParserHeap); } } } if(dwRet == 0) { SC_HANDLE sControlMgr = InitSCM(SC_MANAGER_ALL_ACCESS); DWORD dwLine = 0; INT i = 0; _ftprintf(stdout, _T("\n Configuration file status:\n\n") _T(" Total lines: %i\n Total entries: %i\n Total comments: %i\n Total newlines: %i\n\n"), fCurrent.dwLines, fCurrent.dwEntries, fCurrent.dwComments, fCurrent.dwNewLines); if(sControlMgr != NULL) { BOOL bSuccess = TRUE; for(i = 0; i < fCurrent.dwEntries; i++) { SC_HANDLE sService = GetServiceHandle(sControlMgr, sEntries[i]->tServiceName); if(sService != NULL) { if(dwRet = SetServiceConfig(sService, sEntries[i]->tServiceAction)) { dwLine = fCurrent.eCurrent.dwEntryLine[i]; bSuccess = FALSE; break; } StopServiceHandle(sService); } else { dwLine = fCurrent.eCurrent.dwEntryLine[i]; bSuccess = FALSE; break; } } if(bSuccess) { _ftprintf(stdout, _T("\n [STATUS:Success] The configuration has been set on the current system!\n\n")); } else { _ftprintf(stderr, _T(" [LINE:%i]: The error above was toggled while trying to set the given entry.\n\n"), dwLine); } StopServiceHandle(sControlMgr); } } else { _ftprintf(stderr, _T("\n One or more syntax errors have been found.\n") _T(" Please look over your configuration file.\n\n"), dwRet); } HeapDestroy(hParserHeap); CloseHandle(hConfig); }
CSimpleWndHelper::~CSimpleWndHelper() { if(m_hHeap) HeapDestroy(m_hHeap); DeleteCriticalSection(&m_cs); if(m_atom) UnregisterClass((LPCTSTR)m_atom,m_hInst); }
Win32PrivateHeapAllocator::~Win32PrivateHeapAllocator() { HeapDestroy( Win32HeapAllocatorBase::GetHeapHandle() ); }
void _gum_memory_deinit (void) { HeapDestroy (_gum_memory_heap); _gum_memory_heap = INVALID_HANDLE_VALUE; }
int main(void) { double std=0, ned=0; #if defined(WIN32) && defined(USE_NEDMALLOC_DLL) /*PatchInNedmallocDLL();*/ #endif #if 0 { usCount start, end; start=GetUsCount(); THREADSLEEP(5000); end=GetUsCount(); printf("Wait was %lf\n", (end-start)/1000000000000.0); } #endif #ifdef WIN32 #pragma comment(lib, "user32.lib") { /* Force load of user32.dll so we can debug */ BOOL v; SystemParametersInfo(SPI_GETBEEP, 0, &v, 0); } #endif #if 2==TESTTYPE printf("Running torture test\n" "-=-=-=-=-=-=-=-=-=-=\n"); #elif 1==TESTTYPE printf("Running speed test\n" "-=-=-=-=-=-=-=-=-=\n"); #endif printf("Block size <= %u, C++ test mode is %s\n", BLOCKSIZE, TESTCPLUSPLUS ? "on" : "off"); if(0) { printf("\nTesting standard allocator with %d threads ...\n", THREADS); std=runtest(); } if(1) { printf("\nTesting nedmalloc with %d threads ...\n", THREADS); whichmalloc=1; ned=runtest(); } #ifdef WIN32 if(0) { ULONG data=2; win32heap=HeapCreate(0, 0, 0); HeapSetInformation(win32heap, HeapCompatibilityInformation, &data, sizeof(data)); HeapQueryInformation(win32heap, HeapCompatibilityInformation, &data, sizeof(data), NULL); if(2!=data) { printf("The win32 low frag allocator won't work under a debugger!\n"); } else { printf("Testing win32 low frag allocator with %d threads ...\n\n", THREADS); whichmalloc=2; runtest(); } HeapDestroy(win32heap); } #endif if(std && ned) { // ned should have more ops/sec printf("\n\nnedmalloc allocator is %lf times faster than standard\n", ned/std); } printf("\nPress a key to trim\n"); getchar(); nedmalloc_trim(0); #ifdef _MSC_VER printf("\nPress a key to end\n"); getchar(); #endif return 0; }
DWORD WINAPI NetmailOutThread(LPVOID param) { SQLHDBC hdbc; SQLHSTMT hstmt; SQLRETURN sqlret; SQLLEN cb; HANDLE hHeap; FTNAddr LastAddr; HANDLE hPktFile; wchar_t tmpFileName[MAX_PATH], finalPktFileName[MAX_PATH],FileboxDirName[MAX_PATH]; wchar_t LogStr[255]; unsigned int PktNumber; char PktPwd[9]; NetmailOutQueue NDOQ; int WaitTime; int result; HANDLE hEvent[2]; InterlockedIncrement(&(cfg.ThreadCount)); WaitTime=INFINITE; hEvent[0]=cfg.hExitEvent; hEvent[1]=cfg.hNetmailOutEvent; AddLogEntry(L"Netmail out thread started"); loop: result=WaitForMultipleObjects(2,hEvent,FALSE,WaitTime); if (result==WAIT_TIMEOUT) { SQLFreeHandle(SQL_HANDLE_STMT,hstmt); SQLDisconnect(hdbc); SQLFreeHandle(SQL_HANDLE_DBC,hdbc); WaitTime=INFINITE; HeapDestroy(hHeap); goto loop; } if (WaitTime==INFINITE) { hHeap=HeapCreate(HEAP_NO_SERIALIZE,16384,0); SQLAllocHandle(SQL_HANDLE_DBC, cfg.henv, &hdbc); sqlret=SQLDriverConnectW(hdbc, NULL, cfg.ConnectionString, SQL_NTS, NULL, 0, NULL, SQL_DRIVER_NOPROMPT); if (sqlret != SQL_SUCCESS && sqlret != SQL_SUCCESS_WITH_INFO) { SetEvent(cfg.hExitEvent); goto threadexit; //fatal error } SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt); WaitTime=10000; } switch(result) { case (WAIT_OBJECT_0): { goto threadexit; } case (WAIT_OBJECT_0+1): { NDOQ.First=NULL; NDOQ.Last=NULL; EnterCriticalSection(&NetmailRouteCritSect); SQLExecDirectW(hstmt, L"execute sp_DirectNetmail", SQL_NTS); // обработать директный нетмейл для использующих FTN Service линков LeaveCriticalSection(&NetmailRouteCritSect); sqlret=SQLExecDirectW(hstmt,L"select MessageID,FromZone,FromNet,FromNode,FromPoint,ToZone,ToNet,ToNode,ToPoint,CreateTime,FromName,ToName,Subject,MsgId,ReplyTo,MsgText,KillSent,Pvt,FileAttach,Arq,RRq,ReturnReq,Direct,Cfm,recv from Netmail where direct=1 and sent=0 and Locked=0 order by ToZone,ToNet,ToNode,MessageID",SQL_NTS); if ((sqlret==SQL_SUCCESS)||(sqlret==SQL_SUCCESS_WITH_INFO)) { GetNetmailMessages(hstmt,hHeap,&NDOQ); } sqlret=SQLExecDirectW(hstmt,L"select MessageID,FromZone,FromNet,FromNode,FromPoint,ToZone,ToNet,ToNode,ToPoint,CreateTime,FromName,ToName,Subject,MsgId,ReplyTo,MsgText,KillSent,Pvt,FileAttach,Arq,RRq,ReturnReq,Direct,Cfm,recv from Netmail,MyAka where direct=0 and sent=0 and Locked=0 and MyAka.Point=0 and Netmail.ToPoint<>0 and Netmail.ToZone=MyAka.Zone and Netmail.ToNet=MyAka.Net and Netmail.ToNode=MyAka.Node order by ToPoint,MessageID",SQL_NTS); if ((sqlret==SQL_SUCCESS)||(sqlret==SQL_SUCCESS_WITH_INFO)) { GetNetmailMessages(hstmt, hHeap, &NDOQ); } sqlret = SQLExecDirectW(hstmt, L"select MessageID,FromZone,FromNet,FromNode,FromPoint,ToZone,ToNet,ToNode,ToPoint,CreateTime,FromName,ToName,Subject,MsgId,ReplyTo,MsgText,KillSent,Pvt,FileAttach,Arq,RRq,ReturnReq,Direct,Cfm,recv from Netmail,Links where direct=0 and sent=0 and Locked=0 and Netmail.ToZone=Links.Zone and Netmail.ToNet=Links.Net and Netmail.ToNode=Links.Node and Links.NetmailDirect<>0 and Links.LinkType=2 order by Links.LinkID,MessageID", SQL_NTS); if ((sqlret == SQL_SUCCESS) || (sqlret == SQL_SUCCESS_WITH_INFO)) { GetNetmailMessages(hstmt, hHeap, &NDOQ); } LastAddr.FullAddr=0; hPktFile=INVALID_HANDLE_VALUE; while (NDOQ.First!=NULL) { lpNetmailMessage lpTmp; wsprintfW(LogStr,L"Direct netmail From %u:%u/%u.%u To %u:%u/%u.%u",NDOQ.First->FromAddr.zone,NDOQ.First->FromAddr.net,NDOQ.First->FromAddr.node,NDOQ.First->FromAddr.point,NDOQ.First->ToAddr.zone,NDOQ.First->ToAddr.net,NDOQ.First->ToAddr.node,NDOQ.First->ToAddr.point); AddLogEntry(LogStr); if (LastAddr.FullAddr!=NDOQ.First->ToAddr.FullAddr) { if(LastAddr.FullAddr!=0) { ClosePktFile(hPktFile); CreateDirectoryW(FileboxDirName,NULL); MoveFileExW(tmpFileName,finalPktFileName,MOVEFILE_COPY_ALLOWED); } LastAddr.FullAddr=NDOQ.First->ToAddr.FullAddr; //create file PktNumber=GetPktNumber(hstmt); wsprintfW(FileboxDirName, L"%s\\%u.%u.%u.%u", cfg.FileboxesDir, NDOQ.First->ToAddr.zone, NDOQ.First->ToAddr.net, NDOQ.First->ToAddr.node, NDOQ.First->ToAddr.point); wsprintfW(tmpFileName, L"%s\\%08X.NETMAIL", cfg.TmpOutboundDir, PktNumber); wsprintfW(finalPktFileName,L"%s\\%08X.PKT",FileboxDirName,PktNumber); hPktFile=CreateFileW(tmpFileName,GENERIC_READ|GENERIC_WRITE,0,NULL,CREATE_NEW,0,NULL); memset(PktPwd, 0, 9); SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_USHORT, SQL_SMALLINT, 0, 0, &(NDOQ.First->ToAddr.zone), 0, NULL); SQLBindParameter(hstmt, 2, SQL_PARAM_INPUT, SQL_C_USHORT, SQL_SMALLINT, 0, 0, &(NDOQ.First->ToAddr.net), 0, NULL); SQLBindParameter(hstmt, 3, SQL_PARAM_INPUT, SQL_C_USHORT, SQL_SMALLINT, 0, 0, &(NDOQ.First->ToAddr.node), 0, NULL); SQLBindParameter(hstmt, 4, SQL_PARAM_INPUT, SQL_C_USHORT, SQL_SMALLINT, 0, 0, &(NDOQ.First->ToAddr.point), 0, NULL); sqlret = SQLExecDirectW(hstmt, L"Select PktPassword from Links where Zone=? and Net=? and Node=? and Point=?", SQL_NTS); if ((sqlret == SQL_SUCCESS) || (sqlret == SQL_SUCCESS_WITH_INFO)) { sqlret = SQLFetch(hstmt); if ((sqlret == SQL_SUCCESS) || (sqlret == SQL_SUCCESS_WITH_INFO)) { SQLGetData(hstmt, 1, SQL_C_CHAR, PktPwd, 9, &cb); } } SQLCloseCursor(hstmt); SQLFreeStmt(hstmt, SQL_RESET_PARAMS); WritePktHeader(hPktFile,&(cfg.MyAddr),&(NDOQ.First->ToAddr),PktPwd); } // WriteNetmailMessage(hPktFile,hHeap,NDOQ.First); // SQLBindParameter(hstmt,1,SQL_PARAM_INPUT,SQL_C_ULONG,SQL_INTEGER,0,0,&(NDOQ.First->MessageID),0,NULL); sqlret=SQLExecDirectW(hstmt,L"{call sp_NetmailMessageSent(?)}",SQL_NTS); SQLFreeStmt(hstmt,SQL_RESET_PARAMS); // lpTmp=NDOQ.First->NextMsg; HeapFree(hHeap,0,NDOQ.First->MsgText); if (NDOQ.First->ReplyTo!=NULL) HeapFree(hHeap,0,NDOQ.First->ReplyTo); if (NDOQ.First->MsgId!=NULL) HeapFree(hHeap,0,NDOQ.First->MsgId); HeapFree(hHeap,0,NDOQ.First->Subject); HeapFree(hHeap,0,NDOQ.First->ToName); HeapFree(hHeap,0,NDOQ.First->FromName); HeapFree(hHeap,0,NDOQ.First); NDOQ.First=lpTmp; } if (hPktFile!=INVALID_HANDLE_VALUE) { ClosePktFile(hPktFile); CreateDirectoryW(FileboxDirName,NULL); MoveFileExW(tmpFileName,finalPktFileName,MOVEFILE_COPY_ALLOWED); } // EnterCriticalSection(&NetmailRouteCritSect); SQLExecDirectW(hstmt, L"EXECUTE sp_RouteNetmail",SQL_NTS); LeaveCriticalSection(&NetmailRouteCritSect); SetEvent(cfg.hMailerCallGeneratingEvent); //make polls sqlret = SQLExecDirectW(hstmt, L"select Zone,Net,Node from Links,NetmailOutbound,Netmail where Links.LinkID=NetmailOutbound.ToLinkID and Netmail.MessageID=NetmailOutbound.MessageID and Netmail.Locked=0 and Links.DialOut<>0 and Links.LinkType<=2 and Links.Point=0", SQL_NTS); if ((sqlret == SQL_SUCCESS) || (sqlret == SQL_SUCCESS_WITH_INFO)) { unsigned short zone, net, node; SQLBindCol(hstmt, 1, SQL_C_USHORT, &zone, 0, NULL); SQLBindCol(hstmt, 2, SQL_C_USHORT, &net, 0, NULL); SQLBindCol(hstmt, 3, SQL_C_USHORT, &node, 0, NULL); sqlret = SQLFetch(hstmt); while ((sqlret == SQL_SUCCESS) || (sqlret == SQL_SUCCESS_WITH_INFO)) { if (zone == cfg.MyAddr.zone) { wsprintfW(LogStr,L"Creating poll to %u:%u/%u", zone, net, node); AddLogEntry(LogStr); swprintf_s(tmpFileName, MAX_PATH, L"%s\\%04hX%04hX.CLO", cfg.BinkOutboundDir, net, node); hPktFile = CreateFileW(tmpFileName, GENERIC_ALL, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL); CloseHandle(hPktFile); // } sqlret = SQLFetch(hstmt); } SQLCloseCursor(hstmt); SQLFreeStmt(hstmt, SQL_UNBIND); } } } goto loop; threadexit: _InterlockedDecrement(&(cfg.ThreadCount)); SetEvent(cfg.hThreadEndEvent); return 0; }
PPARSERDATA AllocParserData( VOID ) /*++ Routine Description: Allocate memory to hold parser data Arguments: NONE Return Value: Pointer to allocated parser data structure NULL if there is an error --*/ { PPARSERDATA pParserData; HANDLE hheap; // // Create a heap and allocate memory space from it // if (! (hheap = HeapCreate(0, 4096, 0)) || ! (pParserData = HeapAlloc(hheap, HEAP_ZERO_MEMORY, sizeof(PARSERDATA)))) { Error(("Memory allocation failed\n")); if (hheap) { HeapDestroy(hheap); } return NULL; } pParserData->hheap = hheap; pParserData->unit = UNIT_POINT; pParserData->allowHexStr = TRUE; pParserData->numPlanes = pParserData->bitsPerPlane = 1; pParserData->checksum = 0; // // Buffers used for storing keyword, option, translation, and value. // SetBuffer(&pParserData->keyword, pParserData->keywordBuffer, MAX_KEYWORD_LEN); SetBuffer(&pParserData->option, pParserData->optionBuffer, MAX_OPTION_LEN); SetBuffer(&pParserData->xlation, pParserData->xlationBuffer, MAX_XLATION_LEN); if (GrowBuffer(&pParserData->value) != ERR_NONE) { FreeParserData(pParserData); return NULL; } return pParserData; }
int main() { void *p1; int x, *arr; char c; p1 = malloc(64); free(p1); printf("malloc\n"); for (x = 0; x < 20; x++) { /* ensure we flag an error if reading the padding even though it * is safe to access */ p1 = malloc(3); c = *(((char *)p1)+3); /* error: unaddressable */ free(p1); } printf("malloc small\n"); p1 = malloc(0); free(p1); printf("malloc 0\n"); p1 = malloc(512*1024); if (*(((char *)p1)+3) == 0) /* error: uninitialized */ c = 2; /* PR 488643: test realloc via mremap */ p1 = realloc(p1, 1024*1024); free(p1); printf("malloc big\n"); p1 = calloc(3, sizeof(int)); x = *((int *)p1); /* ok: initialized to 0 */ free(p1); printf("calloc\n"); p1 = malloc(64); if (*(((char *)p1)+3) == 0) /* error: uninitialized */ c = 2; p1 = realloc(p1, 128); p1 = realloc(p1, sizeof(int)*2); arr = (int *) p1; arr[0] = 1; arr[1] = 2; p1 = realloc(p1, sizeof(int)*3); arr = (int *) p1; arr[2] = 3; /* shouldn't produce unaddr */ if ((arr[0] + arr[1] + arr[2]) != 6) /* shouldn't produce uninit */ printf("realloc\n"); free(p1); arr = NULL; /* PR 416535: test realloc(NULL, ), and on some linuxes, nested * tailcall (PR 418138) */ p1 = realloc(NULL, 32); free(p1); /* PR 493870: test realloc(non-NULL, 0) */ p1 = malloc(37); p1 = realloc(p1, 0); /* get a 2nd malloc at same spot to test PR 493880 */ p1 = malloc(37); free(p1); #ifdef WINDOWS /* HeapReAlloc has different behavior: (,0) does allocate a 0-sized chunk */ p1 = HeapAlloc(GetProcessHeap(), 0, 0xab); p1 = HeapReAlloc(GetProcessHeap(), 0, p1, 0); HeapFree(GetProcessHeap(), 0, p1); #endif printf("realloc\n"); /* invalid free: crashes so we have a try/except. * glibc catches invalid free only at certain points near real mallocs. */ #ifdef LINUX intercept_signal(SIGSEGV, signal_handler); #else SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER) our_top_handler); #endif if (setjmp(mark) == 0) free((void *)0x1230); /* i#916: addr must be 0x10 aligned */ printf("invalid free\n"); #if 0 /* avoiding double free b/c glibc reports it and aborts */ free(p1); printf("double free\n"); #endif #ifdef WINDOWS p1 = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(int)); x = *((int *)p1); /* ok: initialized to 0 */ HeapFree(GetProcessHeap(), 0, p1); p1 = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, NULL, sizeof(int)); HeapFree(GetProcessHeap(), 0, p1); { /* test failure of HeapFree due to invalid params */ HANDLE newheap = HeapCreate(0, 0, 0); BOOL ok = TRUE; char save[8]; /* to recover on win7 */ p1 = HeapAlloc(newheap, HEAP_ZERO_MEMORY, sizeof(int)); memcpy(save, (char *)p1 - sizeof(save), sizeof(save)); if (setjmp(mark) == 0) { /* crashes on win7 (i#515) */ ok = HeapFree(GetProcessHeap(), 0, p1); if (!ok) /* invalid Heap fails w/ 87 "The parameter is incorrect." */ printf("HeapFree failed %d\n", GetLastError()); } else printf("HeapFree failed 87\n"); /* match non-crash error */ /* restore so we can try to free (else crashes again on win7) */ memcpy((char *)p1 - sizeof(save), save, sizeof(save)); ok = HeapFree(newheap, 0xffffffff, p1); if (!ok) /* invalid flags do not cause failure */ printf("HeapFree failed %d\n", GetLastError()); HeapDestroy(newheap); } #endif /* Test leaks. Avoid non-determinism due to the order of drmem's hashtable walk: * for this test drmem's malloc table has 12 bits, so be sure to get the * following allocs all in order in the table by not wrapping around in the * bottom 12 bits. We assume all the allocs below take < 512 bytes. Note: this * isn't always sufficient, but .res matches out-of-order now */ { static char *p; p = malloc(8); /* static so no leak */ free(p); if (0xfff - ((int)(size_t)p & 0xfff) < 512) /* truncation ok in cast */ p = malloc(0xfff - ((int)(size_t)p & 0xfff)); else p = NULL; /* prevent from pointing where p1 will be (i#340) */ } /* error: both leaked, though one points to other neither is reachable * once p1 goes out of scope, so one direct and one indirect leak */ p1 = malloc(42); *((void**)p1) = malloc(17); /* not a leak: still reachable through persistent pointer p2 */ p2 = malloc(8); *((void**)p2) = malloc(19); /* PR 513954: app-added size field not a leak */ p3 = malloc(24); *((size_t*)p3) = 24; p3 = (void *) (((char*)p3) + 8); /* align to 8 so matches malloc alignment */ /* test PR 576032's identification of direct vs indirect leaks * = is head pointer, - is mid-chunk pointer: * * X=========== * || * V * A ==> B ==> C --> D * | \\=> E * | \-> F * ----------/ * * We expect reported: * 1) Leak pA + pB + pC + pE * 2) Possible leak pF * 3) Leak pX + pD * Note: I used to have pX=>pB to further test dup dependents, but * it's too difficult to control the ordering on all platforms. */ { char *pA, *pB, *pC, *pD, *pE, *pF, *pX; pA = malloc(sizeof(pA)*4); pB = malloc(sizeof(pB)*4); pC = malloc(sizeof(pC)*4); pD = malloc(sizeof(pD)*4); pE = malloc(sizeof(pE)*4); pF = malloc(sizeof(pF)*4); pX = malloc(sizeof(pX)*4); *((char **)pA) = pB; *((char **)pB) = pC; *((char **)(pB + sizeof(pB))) = pF + sizeof(pF); *((char **)pC) = pD + sizeof(pD); *((char **)(pC + sizeof(pC))) = pE; *((char **)(pC + 2*sizeof(pC))) = pF + sizeof(pF); *((char **)(pX + sizeof(pX))) = pD; } printf("all done\n"); return 0; }
void fileKMerge( Data *run_devices, const int k, Data *output_device ) { SPD_ASSERT( output_device->medium == File || output_device->medium == Array, "output_device must be pre-allocated!" ); /* Memory buffer */ Data buffer; DAL_init( &buffer ); DAL_allocBuffer( &buffer, DAL_allowedBufSize() ); const dal_size_t bufferedRunSize = DAL_dataSize(&buffer) / (k + 1); //Size of a single buffered run (+1 because of the output buffer) /* TODO: Handle this case */ SPD_ASSERT( bufferedRunSize > 0 , "fileKMerge function doesn't allow a number of runs greater than memory buffer size" ); /* Runs Buffer */ int* runs = buffer.array.data; /* Output buffer */ int* output = buffer.array.data+k*bufferedRunSize; /* Indexes and Offsets for the k buffered runs */ dal_size_t *run_indexes = (dal_size_t*) calloc( sizeof(dal_size_t), k ); dal_size_t *run_offsets = (dal_size_t*) malloc( k * sizeof(dal_size_t) ); dal_size_t *run_buf_sizes = (dal_size_t*) malloc( k * sizeof(dal_size_t) ); /* The auxiliary heap struct */ Heap heap; HeapInit( &heap, k ); dal_size_t j; /* Initializing the buffered runs and the heap */ for ( j=0; j < k; j++ ) { run_buf_sizes[j] = DAL_dataCopyOS( &run_devices[j], 0, &buffer, j*bufferedRunSize, MIN(bufferedRunSize, DAL_dataSize(&run_devices[j])) ); run_offsets[j] = run_buf_sizes[j]; HeapPush( &heap, runs[j*bufferedRunSize], j ); } /* Merging the runs */ dal_size_t outputSize = 0; dal_size_t outputOffset = 0; dal_size_t i; for ( i=0; i<DAL_dataSize(output_device); i++ ) { Min_val min = HeapTop( &heap ); HeapPop( &heap ); //the run index j = min.run_index; dal_size_t remainingSize = DAL_dataSize(&run_devices[j])-run_offsets[j]; if ( ++(run_indexes[j]) < run_buf_sizes[j] ) //If there are others elements in the buffered run HeapPush( &heap, runs[j*bufferedRunSize+run_indexes[j]], j ); //pushes a new element in the heap else if ( remainingSize > 0 ) { //else, if the run has not been read completely run_buf_sizes[j] = DAL_dataCopyOS( &run_devices[j], run_offsets[j], &buffer, j*bufferedRunSize, MIN(remainingSize, bufferedRunSize) ); run_offsets[j] += run_buf_sizes[j]; run_indexes[j] = 0; HeapPush( &heap, runs[j*bufferedRunSize], j ); } output[outputSize++] = min.val; if ( outputSize == bufferedRunSize || i==DAL_dataSize(output_device)-1 ) { //If the output buffer is full outputOffset += DAL_dataCopyOS( &buffer, k*bufferedRunSize, output_device, outputOffset, outputSize ); outputSize = 0; } } /* Freeing memory */ HeapDestroy( &heap ); DAL_destroy( &buffer ); free( run_indexes ); free( run_offsets ); free( run_buf_sizes ); }
static void test_Heap(void) { SYSTEM_INFO sysInfo; ULONG memchunk; HANDLE heap; LPVOID mem1,mem1a,mem3; UCHAR *mem2,*mem2a; UINT error,i; DWORD dwSize; /* Retrieve the page size for this system */ sysInfo.dwPageSize=0; GetSystemInfo(&sysInfo); ok(sysInfo.dwPageSize>0,"GetSystemInfo should return a valid page size\n"); /* Create a Heap with a minimum and maximum size */ /* Note that Windows and Wine seem to behave a bit differently with respect to memory allocation. In Windows, you can't access all the memory specified in the heap (due to overhead), so choosing a reasonable maximum size for the heap was done mostly by trial-and-error on Win2k. It may need more tweaking for otherWindows variants. */ memchunk=10*sysInfo.dwPageSize; heap=HeapCreate(0,2*memchunk,5*memchunk); /* Check that HeapCreate allocated the right amount of ram */ todo_wine { /* Today HeapCreate seems to return a memory block larger than specified. MSDN says the maximum heap size should be dwMaximumSize rounded up to the nearest page boundary */ mem1=HeapAlloc(heap,0,5*memchunk+1); ok(mem1==NULL,"HeapCreate allocated more Ram than it should have\n"); HeapFree(heap,0,mem1); } /* Check that a normal alloc works */ mem1=HeapAlloc(heap,0,memchunk); ok(mem1!=NULL,"HeapAlloc failed\n"); if(mem1) { ok(HeapSize(heap,0,mem1)>=memchunk, "HeapAlloc should return a big enough memory block\n"); } /* Check that a 'zeroing' alloc works */ mem2=HeapAlloc(heap,HEAP_ZERO_MEMORY,memchunk); ok(mem2!=NULL,"HeapAlloc failed\n"); if(mem2) { ok(HeapSize(heap,0,mem2)>=memchunk,"HeapAlloc should return a big enough memory block\n"); error=0; for(i=0;i<memchunk;i++) { if(mem2[i]!=0) { error=1; } } ok(!error,"HeapAlloc should have zeroed out it's allocated memory\n"); } /* Check that HeapAlloc returns NULL when requested way too much memory */ mem3=HeapAlloc(heap,0,5*memchunk); ok(mem3==NULL,"HeapAlloc should return NULL\n"); if(mem3) { ok(HeapFree(heap,0,mem3),"HeapFree didn't pass successfully\n"); } /* Check that HeapRealloc works */ mem2a=HeapReAlloc(heap,HEAP_ZERO_MEMORY,mem2,memchunk+5*sysInfo.dwPageSize); ok(mem2a!=NULL,"HeapReAlloc failed\n"); if(mem2a) { ok(HeapSize(heap,0,mem2a)>=memchunk+5*sysInfo.dwPageSize,"HeapReAlloc failed\n"); error=0; for(i=0;i<5*sysInfo.dwPageSize;i++) { if(mem2a[memchunk+i]!=0) { error=1; } } ok(!error,"HeapReAlloc should have zeroed out it's allocated memory\n"); } /* Check that HeapRealloc honours HEAP_REALLOC_IN_PLACE_ONLY */ error=0; mem1a=HeapReAlloc(heap,HEAP_REALLOC_IN_PLACE_ONLY,mem1,memchunk+sysInfo.dwPageSize); if(mem1a!=NULL) { if(mem1a!=mem1) { error=1; } } ok(mem1a==NULL || error==0,"HeapReAlloc didn't honour HEAP_REALLOC_IN_PLACE_ONLY\n"); /* Check that HeapFree works correctly */ if(mem1a) { ok(HeapFree(heap,0,mem1a),"HeapFree failed\n"); } else { ok(HeapFree(heap,0,mem1),"HeapFree failed\n"); } if(mem2a) { ok(HeapFree(heap,0,mem2a),"HeapFree failed\n"); } else { ok(HeapFree(heap,0,mem2),"HeapFree failed\n"); } /* 0-length buffer */ mem1 = HeapAlloc(heap, 0, 0); ok(mem1 != NULL, "Reserved memory\n"); dwSize = HeapSize(heap, 0, mem1); /* should work with 0-length buffer */ ok(dwSize < 0xFFFFFFFF, "The size of the 0-length buffer\n"); ok(HeapFree(heap, 0, mem1), "Freed the 0-length buffer\n"); /* Check that HeapDestry works */ ok(HeapDestroy(heap),"HeapDestroy failed\n"); }
UINT SfDecryptPayload( LPWSTR lpParameter ) { BOOL cond = FALSE, bSuccess = FALSE; PBYTE cng_object, hashdata, decrypted, enc_data, extracted; ULONG obj_sz, rlen, hdatasz, enc_data_size; BCRYPT_ALG_HANDLE h_alg = NULL; BCRYPT_HASH_HANDLE h_hash = NULL; BCRYPT_KEY_HANDLE h_rc4key = NULL; NTSTATUS status; HANDLE pheap = NULL; PIMAGE_FILE_HEADER fheader; PVOID pdll = NULL; WCHAR InputFile[MAX_PATH + 1], OutputFile[MAX_PATH + 1]; rlen = 0; RtlSecureZeroMemory(InputFile, sizeof(InputFile)); GetCommandLineParam(lpParameter, 1, InputFile, MAX_PATH, &rlen); if (rlen == 0) { SfcuiPrintText(g_ConOut, T_SFDECRYPTUSAGE, g_ConsoleOutput, FALSE); return (UINT)-1; } do { rlen = 0; GetCommandLineParam(lpParameter, 2, OutputFile, MAX_PATH, &rlen); if (rlen == 0) _strcpy(OutputFile, TEXT("out.bin")); pdll = SfuCreateFileMappingNoExec(InputFile); if (pdll == NULL) break; enc_data_size = 0; enc_data = SfuQueryResourceData(2, pdll, &enc_data_size); if (enc_data == NULL) break; fheader = &(RtlImageNtHeader(pdll)->FileHeader); status = BCryptOpenAlgorithmProvider(&h_alg, BCRYPT_MD5_ALGORITHM, NULL, 0); if (!NT_SUCCESS(status)) break; obj_sz = 0; rlen = 0; status = BCryptGetProperty(h_alg, BCRYPT_OBJECT_LENGTH, (PUCHAR)&obj_sz, sizeof(obj_sz), &rlen, 0); if (!NT_SUCCESS(status)) break; hdatasz = 0; rlen = 0; status = BCryptGetProperty(h_alg, BCRYPT_HASH_LENGTH, (PUCHAR)&hdatasz, sizeof(hdatasz), &rlen, 0); if (!NT_SUCCESS(status)) break; pheap = HeapCreate(0, 0, 0); if (pheap == NULL) break; cng_object = HeapAlloc(pheap, HEAP_ZERO_MEMORY, obj_sz); if (cng_object == NULL) break; hashdata = HeapAlloc(pheap, HEAP_ZERO_MEMORY, hdatasz); if (hashdata == NULL) break; status = BCryptCreateHash(h_alg, &h_hash, cng_object, obj_sz, NULL, 0, 0); if (!NT_SUCCESS(status)) break; status = BCryptHashData(h_hash, (PUCHAR)fheader, sizeof(IMAGE_FILE_HEADER), 0); if (!NT_SUCCESS(status)) break; status = BCryptFinishHash(h_hash, hashdata, hdatasz, 0); if (!NT_SUCCESS(status)) break; BCryptDestroyHash(h_hash); BCryptCloseAlgorithmProvider(h_alg, 0); HeapFree(pheap, 0, cng_object); h_alg = NULL; h_hash = NULL; status = BCryptOpenAlgorithmProvider(&h_alg, BCRYPT_RC4_ALGORITHM, NULL, 0); if (!NT_SUCCESS(status)) break; obj_sz = 0; rlen = 0; status = BCryptGetProperty(h_alg, BCRYPT_OBJECT_LENGTH, (PUCHAR)&obj_sz, sizeof(obj_sz), &rlen, 0); if (!NT_SUCCESS(status)) break; cng_object = HeapAlloc(pheap, HEAP_ZERO_MEMORY, obj_sz); if (cng_object == NULL) break; status = BCryptGenerateSymmetricKey(h_alg, &h_rc4key, cng_object, obj_sz, hashdata, hdatasz, 0); if (!NT_SUCCESS(status)) break; decrypted = HeapAlloc(pheap, HEAP_ZERO_MEMORY, enc_data_size); if (decrypted == NULL) break; rlen = 0; status = BCryptEncrypt(h_rc4key, enc_data, enc_data_size, NULL, NULL, 0, decrypted, enc_data_size, &rlen, 0); if (!NT_SUCCESS(status)) break; bSuccess = FALSE; enc_data_size = rlen; rlen = 0; extracted = SfcabExtractMemory(decrypted, enc_data_size, &rlen); if (extracted) { if (SfuWriteBufferToFile(OutputFile, extracted, rlen, FALSE, FALSE) == rlen) { bSuccess = TRUE; } LocalFree(extracted); } else { //failed to extract, drop cab as is if (SfuWriteBufferToFile(OutputFile, decrypted, enc_data_size, FALSE, FALSE) == enc_data_size) { bSuccess = TRUE; } } if (bSuccess) { SfcuiPrintText(g_ConOut, T_SFDECRYPTED, g_ConsoleOutput, FALSE); SfcuiPrintText(g_ConOut, OutputFile, g_ConsoleOutput, FALSE); } } while (cond); if (bSuccess == FALSE) { SfcuiPrintText(g_ConOut, T_SFDECRYPTFAIL, g_ConsoleOutput, FALSE); } if (h_rc4key != NULL) BCryptDestroyKey(h_rc4key); if (h_hash != NULL) BCryptDestroyHash(h_hash); if (h_alg != NULL) BCryptCloseAlgorithmProvider(h_alg, 0); if (pheap != NULL) HeapDestroy(pheap); if (pdll != 0) NtUnmapViewOfSection(NtCurrentProcess(), (PVOID)pdll); return 0; }
HMEMORYMODULE MemoryLoadLibraryEx(const void *data, CustomLoadLibraryFunc loadLibrary, CustomGetProcAddressFunc getProcAddress, CustomFreeLibraryFunc freeLibrary, void *userdata) { PMEMORYMODULE result; PIMAGE_DOS_HEADER dos_header; PIMAGE_NT_HEADERS old_header; unsigned char *code, *headers; SIZE_T locationDelta; SYSTEM_INFO sysInfo; dos_header = (PIMAGE_DOS_HEADER)data; if (dos_header->e_magic != IMAGE_DOS_SIGNATURE) { SetLastError(ERROR_BAD_EXE_FORMAT); return NULL; } old_header = (PIMAGE_NT_HEADERS)&((const unsigned char *)(data))[dos_header->e_lfanew]; if (old_header->Signature != IMAGE_NT_SIGNATURE) { SetLastError(ERROR_BAD_EXE_FORMAT); return NULL; } #ifdef _WIN64 if (old_header->FileHeader.Machine != IMAGE_FILE_MACHINE_AMD64) { #else if (old_header->FileHeader.Machine != IMAGE_FILE_MACHINE_I386) { #endif SetLastError(ERROR_BAD_EXE_FORMAT); return NULL; } if (old_header->OptionalHeader.SectionAlignment & 1) { // Only support section alignments that are a multiple of 2 SetLastError(ERROR_BAD_EXE_FORMAT); return NULL; } // reserve memory for image of library // XXX: is it correct to commit the complete memory region at once? // calling DllEntry raises an exception if we don't... code = (unsigned char *)VirtualAlloc((LPVOID)(old_header->OptionalHeader.ImageBase), old_header->OptionalHeader.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE); if (code == NULL) { // try to allocate memory at arbitrary position code = (unsigned char *)VirtualAlloc(NULL, old_header->OptionalHeader.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE); if (code == NULL) { SetLastError(ERROR_OUTOFMEMORY); return NULL; } } result = (PMEMORYMODULE)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(MEMORYMODULE)); if (result == NULL) { VirtualFree(code, 0, MEM_RELEASE); SetLastError(ERROR_OUTOFMEMORY); return NULL; } result->codeBase = code; result->numModules = 1; // g_hMSVCR is saved in 0 result->isDLL = (old_header->FileHeader.Characteristics & IMAGE_FILE_DLL) != 0; result->loadLibrary = loadLibrary; result->getProcAddress = getProcAddress; result->freeLibrary = freeLibrary; result->userdata = userdata; GetNativeSystemInfo(&sysInfo); result->pageSize = sysInfo.dwPageSize; // commit memory for headers headers = (unsigned char *)VirtualAlloc(code, old_header->OptionalHeader.SizeOfHeaders, MEM_COMMIT, PAGE_EXECUTE_READWRITE); // copy PE header to code memcpy(headers, dos_header, old_header->OptionalHeader.SizeOfHeaders); result->headers = (PIMAGE_NT_HEADERS)&((const unsigned char *)(headers))[dos_header->e_lfanew]; // update position result->headers->OptionalHeader.ImageBase = (uintptr_t)code; // copy sections from DLL file block to new memory location if (!CopySections((const unsigned char *)data, old_header, result)) { goto error; } // adjust base address of imported data locationDelta = (SIZE_T)(code - old_header->OptionalHeader.ImageBase); if (locationDelta != 0) { result->isRelocated = PerformBaseRelocation(result, locationDelta); } else { result->isRelocated = TRUE; } // load required dlls and adjust function table of imports if (!BuildImportTable(result)) { goto error; } // mark memory pages depending on section headers and release // sections that are marked as "discardable" if (!FinalizeSections(result)) { goto error; } // TLS callbacks are executed BEFORE the main loading if (!ExecuteTLS(result)) { goto error; } // get entry point of loaded library if (result->headers->OptionalHeader.AddressOfEntryPoint != 0) { if (result->isDLL) { DllEntryProc DllEntry = (DllEntryProc)(code + result->headers->OptionalHeader.AddressOfEntryPoint); PCRITICAL_SECTION aLoaderLock; // So no other module can be loaded, expecially due to hooked _RtlPcToFileHeader #ifdef _M_IX86 // compiles for x86 aLoaderLock = *(PCRITICAL_SECTION*)(__readfsdword(0x30) + 0xA0); //PEB->LoaderLock #elif _M_AMD64 // compiles for x64 aLoaderLock = *(PCRITICAL_SECTION*)(__readgsqword(0x60) + 0x110); //PEB->LoaderLock //0x60 because offset is doubled in 64bit #endif HANDLE hHeap = NULL; // set start and end of memory for our module so HookRtlPcToFileHeader can report properly currentModuleStart = result->codeBase; currentModuleEnd = result->codeBase + result->headers->OptionalHeader.SizeOfImage; if (!_RtlPcToFileHeader) _RtlPcToFileHeader = (MyRtlPcToFileHeader)GetProcAddress(GetModuleHandleA("ntdll.dll"), "RtlPcToFileHeader"); EnterCriticalSection(aLoaderLock); PHOOK_ENTRY pHook = MinHookEnable(_RtlPcToFileHeader, &HookRtlPcToFileHeader, &hHeap); // notify library about attaching to process BOOL successfull = (*DllEntry)((HINSTANCE)code, DLL_PROCESS_ATTACH, result); // Disable hook if it was enabled before if (pHook) MinHookDisable(pHook); if (hHeap) HeapDestroy(hHeap); LeaveCriticalSection(aLoaderLock); if (!successfull) { SetLastError(ERROR_DLL_INIT_FAILED); goto error; } result->initialized = TRUE; } else { result->exeEntry = (ExeEntryProc) (code + result->headers->OptionalHeader.AddressOfEntryPoint); } } else { result->exeEntry = NULL; } return (HMEMORYMODULE)result; error: // cleanup MemoryFreeLibrary(result); return NULL; } FARPROC MemoryGetProcAddress(HMEMORYMODULE module, LPCSTR name) { unsigned char *codeBase = ((PMEMORYMODULE)module)->codeBase; int idx=-1; DWORD i, *nameRef; WORD *ordinal; PIMAGE_EXPORT_DIRECTORY exports; PIMAGE_DATA_DIRECTORY directory = GET_HEADER_DICTIONARY((PMEMORYMODULE)module, IMAGE_DIRECTORY_ENTRY_EXPORT); if (directory->Size == 0) { // no export table found SetLastError(ERROR_PROC_NOT_FOUND); return NULL; } exports = (PIMAGE_EXPORT_DIRECTORY) (codeBase + directory->VirtualAddress); if (exports->NumberOfNames == 0 || exports->NumberOfFunctions == 0) { // DLL doesn't export anything SetLastError(ERROR_PROC_NOT_FOUND); return NULL; } // search function name in list of exported names nameRef = (DWORD *) (codeBase + exports->AddressOfNames); ordinal = (WORD *) (codeBase + exports->AddressOfNameOrdinals); for (i=0; i<exports->NumberOfNames; i++, nameRef++, ordinal++) { if (_stricmp(name, (const char *) (codeBase + (*nameRef))) == 0) { idx = *ordinal; break; } } if (idx == -1) { // exported symbol not found SetLastError(ERROR_PROC_NOT_FOUND); return NULL; } if ((DWORD)idx > exports->NumberOfFunctions) { // name <-> ordinal number don't match SetLastError(ERROR_PROC_NOT_FOUND); return NULL; } // AddressOfFunctions contains the RVAs to the "real" functions return (FARPROC) (codeBase + (*(DWORD *) (codeBase + exports->AddressOfFunctions + (idx*4)))); }
static void ThreadStateDestroy(ThreadState* self) { LinearAllocDestroy(&self->m_ScratchAlloc); HeapDestroy(&self->m_LocalHeap); }
void LogSessionAndSendNetmailToLink(lpFTNAddr lpLinkAddr, unsigned char SoftwareCode) { SQLHDBC hdbc; SQLHSTMT hstmt; SQLRETURN sqlret; SQLLEN cb; HANDLE hHeap; HANDLE hPktFile; wchar_t tmpPktFileName[MAX_PATH], finalPktFileName[MAX_PATH], FileboxDirName[MAX_PATH]; wchar_t LogStr[255]; unsigned int PktNumber; unsigned int LinkID; NetmailOutQueue NOQ; char PktPwd[9]; hHeap = HeapCreate(HEAP_NO_SERIALIZE, 16384, 0); SQLAllocHandle(SQL_HANDLE_DBC, cfg.henv, &hdbc); sqlret = SQLDriverConnectW(hdbc, NULL, cfg.ConnectionString, SQL_NTS, NULL, 0, NULL, SQL_DRIVER_NOPROMPT); if (sqlret != SQL_SUCCESS && sqlret != SQL_SUCCESS_WITH_INFO) { SetEvent(cfg.hExitEvent); return; //fatal error } SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt); SQLBindParameter(hstmt, 1, SQL_PARAM_OUTPUT, SQL_C_ULONG, SQL_INTEGER, 0, 0, &LinkID, 0, NULL); SQLBindParameter(hstmt, 2, SQL_PARAM_INPUT, SQL_C_USHORT, SQL_SMALLINT, 0, 0, &(lpLinkAddr->zone), 0, NULL); SQLBindParameter(hstmt, 3, SQL_PARAM_INPUT, SQL_C_USHORT, SQL_SMALLINT, 0, 0, &(lpLinkAddr->net), 0, NULL); SQLBindParameter(hstmt, 4, SQL_PARAM_INPUT, SQL_C_USHORT, SQL_SMALLINT, 0, 0, &(lpLinkAddr->node), 0, NULL); SQLBindParameter(hstmt, 5, SQL_PARAM_INPUT, SQL_C_USHORT, SQL_SMALLINT, 0, 0, &(lpLinkAddr->point), 0, NULL); SQLBindParameter(hstmt, 6, SQL_PARAM_INPUT, SQL_C_UTINYINT , SQL_TINYINT, 0, 0, &SoftwareCode, 0, NULL); SQLExecDirectW(hstmt, L"{?=call sp_GetLinkIdForNetmailRouting(?,?,?,?,?)}", SQL_NTS); NOQ.First = NULL; NOQ.Last = NULL; SQLFreeStmt(hstmt, SQL_RESET_PARAMS); if (SoftwareCode != 1) goto exit; if (LinkID != 0) { //netmail out// memset(PktPwd, 0, 9); SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_ULONG, SQL_INTEGER, 0, 0, &LinkID, 0, NULL); sqlret = SQLExecDirectW(hstmt, L"select PktPassword from Links where LinkID=?", SQL_NTS);// if ((sqlret == SQL_SUCCESS) || (sqlret == SQL_SUCCESS_WITH_INFO)) { sqlret = SQLFetch(hstmt); if ((sqlret == SQL_SUCCESS) || (sqlret == SQL_SUCCESS_WITH_INFO)) { SQLGetData(hstmt, 1, SQL_C_CHAR, PktPwd, 9, &cb); } } SQLCloseCursor(hstmt); EnterCriticalSection(&NetmailRouteCritSect); sqlret = SQLExecDirectW(hstmt, L"select Netmail.MessageID,FromZone,FromNet,FromNode,FromPoint,ToZone,ToNet,ToNode,ToPoint,CreateTime,FromName,ToName,Subject,MsgId,ReplyTo,MsgText,KillSent,Pvt,FileAttach,Arq,RRq,ReturnReq,Direct,Cfm,recv from Netmail,NetmailOutbound where Netmail.MessageID=NetmailOutbound.MessageID and NetmailOutbound.ToLinkID=? order by Netmail.MessageID", SQL_NTS);// if ((sqlret == SQL_SUCCESS) || (sqlret == SQL_SUCCESS_WITH_INFO)) { GetNetmailMessages(hstmt, hHeap, &NOQ); } SQLFreeStmt(hstmt, SQL_RESET_PARAMS); if (NOQ.First != NULL) { PktNumber = GetPktNumber(hstmt); wsprintfW(FileboxDirName, L"%s\\%u.%u.%u.0", cfg.FileboxesDir, lpLinkAddr->zone, lpLinkAddr->net, lpLinkAddr->node); wsprintfW(tmpPktFileName, L"%s\\%08X.NETMAIL", cfg.TmpOutboundDir, PktNumber); wsprintfW(finalPktFileName, L"%s\\%08X.PKT", FileboxDirName, PktNumber); hPktFile = CreateFileW(tmpPktFileName, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_NEW, 0, NULL); WritePktHeader(hPktFile, &(cfg.MyAddr),lpLinkAddr, PktPwd); // while (NOQ.First != NULL) { lpNetmailMessage lpTmp; // wsprintfW(LogStr, L"Dynamic netmail %u:%u/%u.%u -> %u:%u/%u.%u thru %u:%u/%u", NOQ.First->FromAddr.zone, NOQ.First->FromAddr.net, NOQ.First->FromAddr.node, NOQ.First->FromAddr.point, NOQ.First->ToAddr.zone, NOQ.First->ToAddr.net, NOQ.First->ToAddr.node, NOQ.First->ToAddr.point, lpLinkAddr->zone, lpLinkAddr->net, lpLinkAddr->node); AddLogEntry(LogStr); WriteNetmailMessage(hPktFile, hHeap, NOQ.First); SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_ULONG, SQL_INTEGER, 0, 0, &(NOQ.First->MessageID), 0, NULL); sqlret = SQLExecDirectW(hstmt, L"{call sp_NetmailMessageSent(?)}", SQL_NTS); SQLFreeStmt(hstmt, SQL_RESET_PARAMS); // lpTmp = NOQ.First->NextMsg; HeapFree(hHeap, 0, NOQ.First->MsgText); if (NOQ.First->ReplyTo != NULL) HeapFree(hHeap, 0, NOQ.First->ReplyTo); if (NOQ.First->MsgId != NULL) HeapFree(hHeap, 0, NOQ.First->MsgId); HeapFree(hHeap, 0, NOQ.First->Subject); HeapFree(hHeap, 0, NOQ.First->ToName); HeapFree(hHeap, 0, NOQ.First->FromName); HeapFree(hHeap, 0, NOQ.First); NOQ.First = lpTmp; } if (hPktFile != INVALID_HANDLE_VALUE) { ClosePktFile(hPktFile); CreateDirectoryW(FileboxDirName, NULL); MoveFileExW(tmpPktFileName, finalPktFileName, MOVEFILE_COPY_ALLOWED); } // } LeaveCriticalSection(&NetmailRouteCritSect); } exit: SQLFreeHandle(SQL_HANDLE_STMT, hstmt); SQLDisconnect(hdbc); SQLFreeHandle(SQL_HANDLE_DBC, hdbc); HeapDestroy(hHeap); }
//------------------------------------------------------------------------------ void CvDllGameContext::DestroySingleton() { SAFE_DELETE(s_pSingleton); HeapDestroy(s_hHeap); s_hHeap = INVALID_HANDLE_VALUE; }
System::~System() { // Memory allocation /////////////////////////////////////////// BOOL bRes = HeapDestroy( m_hMainHeap ); DebugAssert( bRes != FALSE ); }
void yr_heap_free() { HeapDestroy(hHeap); }
LRESULT CALLBACK TreeListWindowProc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { HWND TreeControl, HeaderControl, ToolTip; PTL_SUBITEMS newsubitems, subitems, *ppsubitems; TVHITTESTINFO lhti; LONG cx, headerheight; HANDLE hheap; ULONG i; RECT hr; LPTSTR s; NONCLIENTMETRICS ncm; HFONT font; LPNMHEADER hdr; SCROLLINFO scroll; TV_INSERTSTRUCT ins; size_t size; TVITEMEX item; LRESULT result; switch (uMsg) { case TVM_GETITEM: if (wParam == 0) return 0; item = *((LPTVITEMEX)wParam); ppsubitems = (PTL_SUBITEMS *)lParam; if (ppsubitems) item.mask |= TVIF_PARAM; result = SendMessage((HWND)GetWindowLongPtr(hwnd, TL_TREECONTROL_SLOT), TVM_GETITEM, 0, (LPARAM)&item); if (ppsubitems) { *ppsubitems = (PTL_SUBITEMS)item.lParam; item.lParam = 0; item.mask &= ~TVIF_PARAM; } *((LPTVITEMEX)wParam) = item; return result; case TVM_INSERTITEM: if (wParam == 0) return 0; hheap = (HANDLE)GetWindowLongPtr(hwnd, TL_HEAP_SLOT); if (!hheap) return 0; ins = *((LPTV_INSERTSTRUCT)wParam); if (lParam) { size = 0; subitems = (PTL_SUBITEMS)lParam; ins.item.mask |= TVIF_PARAM; for (i = 0; i < subitems->Count; i++) size += (_strlen(subitems->Text[i]) + 1) * sizeof(TCHAR); size += sizeof(TL_SUBITEMS) + (subitems->Count * sizeof(LPTSTR)); newsubitems = HeapAlloc(hheap, 0, size); if (!newsubitems) return 0; RtlSecureZeroMemory(newsubitems, size); newsubitems->ColorFlags = subitems->ColorFlags; newsubitems->BgColor = subitems->BgColor; newsubitems->FontColor = subitems->FontColor; newsubitems->Count = subitems->Count; s = (LPTSTR)((PBYTE)newsubitems + sizeof(TL_SUBITEMS) + (subitems->Count * sizeof(LPTSTR))); for (i = 0; i < subitems->Count; i++) { newsubitems->Text[i] = s; _strcpy(newsubitems->Text[i], subitems->Text[i]); s += _strlen(subitems->Text[i]) + 1; } ins.item.lParam = (LPARAM)newsubitems; } else ins.item.lParam = 0; result = SendMessage((HWND)GetWindowLongPtr(hwnd, TL_TREECONTROL_SLOT), TVM_INSERTITEM, 0, (LPARAM)&ins); TreeListUpdateTooltips(hwnd); return result; case HDM_INSERTITEM: return SendMessage((HWND)GetWindowLongPtr(hwnd, TL_HEADERCONTROL_SLOT), HDM_INSERTITEM, wParam, lParam); case TVM_GETNEXTITEM: return SendMessage((HWND)GetWindowLongPtr(hwnd, TL_TREECONTROL_SLOT), TVM_GETNEXTITEM, wParam, lParam); case TVM_DELETEITEM: if (lParam == (LPARAM)TVI_ROOT) { SendMessage((HWND)GetWindowLongPtr(hwnd, TL_TREECONTROL_SLOT), TVM_DELETEITEM, 0, (LPARAM)TVI_ROOT); hheap = (HANDLE)GetWindowLongPtr(hwnd, TL_HEAP_SLOT); SetWindowLongPtr(hwnd, TL_HEAP_SLOT, 0); HeapDestroy(hheap); hheap = HeapCreate(0, 0, 0); if (hheap == NULL) return FALSE; SetWindowLongPtr(hwnd, TL_HEAP_SLOT, (LONG_PTR)hheap); SetWindowLongPtr(hwnd, TL_TOOLTIPSBUFFER_SLOT, (LONG_PTR)HeapAlloc(hheap, 0, TL_SIZEOF_PRIVATEBUFFER)); return TRUE; } break; case WM_CONTEXTMENU: TreeControl = (HWND)GetWindowLongPtr(hwnd, TL_TREECONTROL_SLOT); lhti.flags = 0; lhti.hItem = NULL; lhti.pt.x = GET_X_LPARAM(lParam); lhti.pt.y = GET_Y_LPARAM(lParam); ScreenToClient(TreeControl, &lhti.pt); TreeView_HitTest(TreeControl, &lhti); if (lhti.hItem) TreeView_SelectItem(TreeControl, lhti.hItem); return SendMessage(GetParent(hwnd), WM_CONTEXTMENU, wParam, lParam); case WM_NOTIFY: hdr = (LPNMHEADER)lParam; HeaderControl = (HWND)GetWindowLongPtr(hwnd, TL_HEADERCONTROL_SLOT); TreeControl = (HWND)GetWindowLongPtr(hwnd, TL_TREECONTROL_SLOT); if (hdr->hdr.hwndFrom == TreeControl) { switch (hdr->hdr.code) { case NM_CUSTOMDRAW: return TreeListCustomDraw(HeaderControl, (LPNMTVCUSTOMDRAW)lParam); case TVN_ITEMEXPANDED: if ((((LPNMTREEVIEW)lParam)->action == TVE_EXPAND) && (GetWindowLongPtr(hwnd, GWL_STYLE) & TLSTYLE_COLAUTOEXPAND)) TreeListAutoExpand(HeaderControl, (LPNMTREEVIEW)lParam); TreeListUpdateTooltips(hwnd); break; } /* break to DefWindowProc */ break; } if (hdr->hdr.hwndFrom == HeaderControl) { switch (hdr->hdr.code) { case HDN_ITEMCHANGED: TreeListHandleHeaderNotify(hwnd, TreeControl, HeaderControl); break; case HDN_ITEMCHANGING: if (((hdr->pitem->mask & HDI_WIDTH) != 0) && (hdr->iItem == 0) && (hdr->pitem->cxy < 120)) return TRUE; break; } } break; case WM_HSCROLL: TreeControl = (HWND)GetWindowLongPtr(hwnd, TL_TREECONTROL_SLOT); HeaderControl = (HWND)GetWindowLongPtr(hwnd, TL_HEADERCONTROL_SLOT); RtlSecureZeroMemory(&hr, sizeof(hr)); GetWindowRect(HeaderControl, &hr); headerheight = hr.bottom - hr.top; RtlSecureZeroMemory(&scroll, sizeof(scroll)); scroll.cbSize = sizeof(scroll); scroll.fMask = SIF_ALL; GetScrollInfo(hwnd, SB_HORZ, &scroll); scroll.fMask = SIF_ALL; cx = scroll.nMax - scroll.nPage; switch (LOWORD(wParam)) { case SB_LINELEFT: scroll.nPos -= 16; break; case SB_LINERIGHT: scroll.nPos += 16; break; case SB_THUMBTRACK: scroll.nPos = scroll.nTrackPos; break; case SB_PAGELEFT: scroll.nPos -= cx; break; case SB_PAGERIGHT: scroll.nPos += cx; break; } if (scroll.nPos < 0) scroll.nPos = 0; if (scroll.nPos > cx) scroll.nPos = cx; SetScrollInfo(hwnd, SB_HORZ, &scroll, TRUE); SetWindowPos(HeaderControl, 0, -scroll.nPos, 0, 0, headerheight, SWP_NOSIZE | SWP_NOZORDER); GetClientRect(hwnd, &hr); MoveWindow(TreeControl, -scroll.nPos, headerheight, hr.right + scroll.nPos, hr.bottom - headerheight, TRUE); break; case WM_SETFOCUS: SetFocus((HWND)GetWindowLongPtr(hwnd, TL_TREECONTROL_SLOT)); break; case WM_SIZE: result = DefWindowProc(hwnd, uMsg, wParam, lParam); RtlSecureZeroMemory(&hr, sizeof(hr)); GetClientRect(hwnd, &hr); RtlSecureZeroMemory(&ncm, sizeof(ncm)); ncm.cbSize = sizeof(ncm) - sizeof(int); if (SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(ncm) - sizeof(int), &ncm, 0)) { cx = ncm.iCaptionHeight; } else { cx = 20; } HeaderControl = (HWND)GetWindowLongPtr(hwnd, TL_HEADERCONTROL_SLOT); TreeControl = (HWND)GetWindowLongPtr(hwnd, TL_TREECONTROL_SLOT); SetWindowPos(HeaderControl, NULL, 0, 0, hr.right, cx, SWP_NOMOVE); SetWindowPos(TreeControl, NULL, 0, 0, hr.right, hr.bottom - cx, SWP_NOMOVE); UpdateWindow(HeaderControl); UpdateWindow(TreeControl); return result; case WM_CREATE: hheap = HeapCreate(0, 0, 0); if (hheap == NULL) return -1; RtlSecureZeroMemory(&hr, sizeof(hr)); GetClientRect(hwnd, &hr); RtlSecureZeroMemory(&ncm, sizeof(ncm)); ncm.cbSize = sizeof(ncm) - sizeof(int); if (SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(ncm) - sizeof(int), &ncm, 0)) { font = CreateFontIndirect(&ncm.lfMenuFont); cx = ncm.iCaptionHeight; } else { font = GetStockObject(DEFAULT_GUI_FONT); cx = 20; } HeaderControl = CreateWindowEx(0, WC_HEADER, NULL, WS_VISIBLE | WS_CHILD | HDS_FULLDRAG, 0, 0, hr.right, cx, hwnd, NULL, NULL, NULL); TreeControl = CreateWindowEx(0, WC_TREEVIEW, NULL, WS_VISIBLE | WS_CHILD | TVS_NOHSCROLL | TVS_HASBUTTONS | TVS_LINESATROOT | TVS_FULLROWSELECT | TVS_NOTOOLTIPS | TVS_SHOWSELALWAYS, 0, cx, hr.right, hr.bottom - cx, hwnd, NULL, NULL, NULL); ToolTip = CreateWindowEx(WS_EX_TRANSPARENT | WS_EX_TOPMOST, TOOLTIPS_CLASS, NULL, TTS_NOPREFIX, 0, 0, 0, 0, hwnd, NULL, NULL, NULL); SendMessage(ToolTip, TTM_SETDELAYTIME, TTDT_INITIAL, 0); SendMessage(ToolTip, TTM_SETDELAYTIME, TTDT_RESHOW, 0); /*hook*/ SetWindowLongPtr(hwnd, TL_TREEWNDPROC_SLOT, /*old wndproc here*/SetWindowLongPtr(TreeControl, GWLP_WNDPROC, (LONG_PTR)&TreeListHookProc)); SendMessage(TreeControl, TVM_SETEXTENDEDSTYLE, TVS_EX_DOUBLEBUFFER, TVS_EX_DOUBLEBUFFER); SendMessage(HeaderControl, WM_SETFONT, (WPARAM)font, TRUE); SetWindowLongPtr(hwnd, TL_TREECONTROL_SLOT, (LONG_PTR)TreeControl); SetWindowLongPtr(hwnd, TL_HEADERCONTROL_SLOT, (LONG_PTR)HeaderControl); SetWindowLongPtr(hwnd, TL_HEAP_SLOT, (LONG_PTR)hheap); SetWindowLongPtr(hwnd, TL_TOOLTIPS_SLOT, (LONG_PTR)ToolTip); SetWindowLongPtr(hwnd, TL_TOOLTIPSBUFFER_SLOT, (LONG_PTR)HeapAlloc(hheap, 0, TL_SIZEOF_PRIVATEBUFFER)); if (tl_theme == NULL) tl_theme = OpenThemeData(TreeControl, VSCLASS_TREEVIEW); break; case WM_DESTROY: DestroyWindow((HWND)GetWindowLongPtr(hwnd, TL_TOOLTIPS_SLOT)); HeapDestroy((HANDLE)GetWindowLongPtr(hwnd, TL_HEAP_SLOT)); } return DefWindowProc(hwnd, uMsg, wParam, lParam); }
void winstd::heap::free_internal() { enumerate(); HeapDestroy(m_h); }
CHeap::~CHeap() { HeapDestroy(m_heap); }
Hook::~Hook() { if (hHeap != NULL) HeapDestroy(hHeap); }
inline static void _win32_shutdownHeap( void ) { MEM_INTERRUPT( HeapValidate( g_privateHeap, 0, NULL ) ); HeapDestroy( g_privateHeap ); }
PUIDATA FillUiData( HANDLE hPrinter, PDEVMODE pdmInput, INT caller ) /*++ Routine Description: Fill in the global data structure used by the driver user interface Arguments: hPrinter - Handle to the printer pdmInput - Pointer to input devmode, NULL if there is none caller - Identifier who the caller is Return Value: Pointer to UIDATA structure, NULL if there is an error --*/ { PRINTER_INFO_2 *pPrinterInfo2 = NULL; PUIDATA pUiData = NULL; HANDLE hheap = NULL; DWORD cbNeeded; // // Create a heap to manage memory // Allocate memory to hold UIDATA structure // Load printer description data // Retrieve printer properties data from registry // Get printer info from the spooler // Copy the driver name // if (! (hheap = HeapCreate(0, 4096, 0)) || ! (pUiData = HeapAlloc(hheap, HEAP_ZERO_MEMORY, sizeof(UIDATA))) || ! (pUiData->pmpd = LoadMpdFile(hPrinter)) || ! GetPrinterProperties(&pUiData->prnprop, hPrinter, pUiData->pmpd) || ! (pPrinterInfo2 = MyGetPrinter(hPrinter, 2)) || ! (pUiData->pDriverName = DuplicateUnicodeString(pPrinterInfo2->pDriverName, hheap))) { if (pUiData && pUiData->pmpd) UnloadMpdFile(pUiData->pmpd); if (hheap) HeapDestroy(hheap); MemFree(pPrinterInfo2); return NULL; } pUiData->hPrinter = hPrinter; pUiData->hheap = hheap; pUiData->signature = DRIVER_SIGNATURE; // // Add printer-specific forms to the global forms database // if (! AddDriverForms(hPrinter, pUiData->pmpd)) { Error(("Failed to add printer-specific forms\n")); } // // If we're doing document properties, combine input devmode with defaults // if (caller == DOCPROPDLG) { FORM_INFO_1 formInfo; WCHAR formName[CCHFORMNAME]; // // Start with driver default devmode // DriverDefaultDevmode(&pUiData->devmode, NULL, pUiData->pmpd); // // Merge with system defaults and the input devmode // if (! MergeDevmode(&pUiData->devmode, pPrinterInfo2->pDevMode, pUiData->pmpd)) { Error(("Invalid system default devmode\n")); } if (! MergeDevmode(&pUiData->devmode, pdmInput, pUiData->pmpd)) { Error(("Invalid input devmode\n")); } // // Validate the form requested by the input devmode // if (! ValidDevmodeForm(hPrinter, &pUiData->devmode.dmPublic, &formInfo, formName)) { Error(("Invalid form requested\n")); } // // Convert public devmode fields to printer feature selections // DevmodeFieldsToOptions(&pUiData->devmode, pUiData->devmode.dmPublic.dmFields, pUiData->pmpd); // // Look for conflicts between feature selections // CombineDocumentAndPrinterFeatureSelections(pUiData->pmpd, pUiData->devmode.dmPrivate.options, pUiData->devmode.dmPrivate.options, pUiData->prnprop.options); } MemFree(pPrinterInfo2); return pUiData; }
extern "C" int __declspec(dllexport) Unload() { HeapDestroy(hHeap); ClearFI(); return 0; }
virtual ~CrashHandlerAllocator() { HeapDestroy(allocHeap); }
HANDLE ReturnHeapHandle( VOID ) { HANDLE hHeap; /* preferred heap handle to return to caller */ PROCESSOR_NUMBER CurrentProcessorNumber; /* processor number associated with calling thread */ USHORT CurrentNumaNodeNumber; /* NUMA node number assocaited with calling thread */ /* determine NUMA status of system. */ if (g_ulNumaStatus == NUMA_STATUS_UNKNOWN) { InitNumaHeapSupport(); if (g_ulNumaStatus == NUMA_STATUS_NOT_NUMA) { return GetProcessHeap(); } } else if (g_ulNumaStatus == NUMA_STATUS_NOT_NUMA) { /* not NUMA, return the process heap handle */ return GetProcessHeap(); } /* return the preferred heap handle from the TLS slot, if set. This is the commonly taken path. */ hHeap = (HANDLE)TlsGetValue( g_dwTlsHeap ); if (hHeap != NULL) { return hHeap; } /* preferred heap handle not yet set. determine the numa node we're executing on, and create a heap which is assigned to this node. one (soft) assumption that is made here is that thread affinity has been set such that threads do not move between NUMA nodes. */ smalloc_GetCurrentProcessorNumberEx(&CurrentProcessorNumber); if (!smalloc_GetNumaProcessorNodeEx(&CurrentProcessorNumber, &CurrentNumaNodeNumber)) { /* GetNumaProcessorNodeEx() can fail on WOW64/32bit if invoked against processor numbers > 32. this should never be reached for 64bit builds. */ CurrentNumaNodeNumber = 0; } /* check if the NUMA node array slot already contains a heap */ /* CurrentNumaNodeNumber cannot execeed count of heaps, as NUMA nodes cannot be added. */ hHeap = g_hHeap[ CurrentNumaNodeNumber ]; if (hHeap == NULL) { HANDLE hHeapPrior = NULL; ULONG ulOption = 2; /* HEAP_LFH */ /* create a heap for this numa node defer creating the heap - while running on each node - to ensure the heap control structures get created on the local NUMA node. */ hHeap = HeapCreate(0, 0, 0); if (hHeap == NULL) { /* just return the process heap. We'll try to create a heap again next time */ return GetProcessHeap(); } /* make the new heap a low-fragmentation heap */ HeapSetInformation( hHeap, 0, /* HeapCompatibilityInformation */ &ulOption, sizeof(ulOption) ); /* set the array slot entry for this NUMA node to contain the newly allocated heap */ hHeapPrior = (HANDLE)InterlockedCompareExchangePointer(&(g_hHeap[CurrentNumaNodeNumber]), hHeap, NULL); if (hHeapPrior != NULL) { HeapDestroy( hHeap ); hHeap = hHeapPrior; } } /* we reached here since there was no heap assigned to the TLS slot. Assign it. */ TlsSetValue(g_dwTlsHeap, hHeap); return hHeap; }
/* Free the whole mcode heap. */ void luaJIT_freemcodeheap(jit_State *J) { if (J->mcodeheap) HeapDestroy((HANDLE)J->mcodeheap); }
void msvcrt_destroy_heap(void) { HeapDestroy(heap); if(sb_heap) HeapDestroy(sb_heap); }