/****************************************************************************** * Synopsis: * * AeDemo2 [-o owner] [-s] [-g] [{-ph|-ps} proxy-host [-pp proxy-port] * [-pu proxy-user] [-pw proxy-password]] [-o owner] url * * url: * Use the following syntax: * http://<server-name>:<port>/eMessage (non-secure communications) or * https://<server-name>:<port>/eMessage (secure communications) * where <server-name> is replaced with the Enterprise server name. * and <port> is replaced with the port number. (Use 443 for SSL). * For example, http://drm.axeda.com/eMessage. * * Options: * * -o owner * Use specified owner (database name). * -s * Use secure communication (SSL). * -g * Enable debug messages. * -ph proxy-host * Use HTTP proxy at proxy-host. Default port is 80. * -ps proxy-host * Use SOCKS proxy at proxy-host. Default port is 1080. * -pp proxy-port * Override default port for proxy. * -pu proxy-user * Use proxy-user as user name for proxy authentication. * -pw proxy-password * Use proxy-password as password for proxy authentication. * * Description: * * The program defines a device, configures the primary Enterprise server * (using url argument) and installs command callbacks. After that it loops * and waits for callback invocation. ******************************************************************************/ int main(int argc, char *argv[]) { AeDemoConfig config; AeInt32 iDeviceId, iServerId; AeTimeValue pingRate, timeLimit; AeError rc; /* process options */ if (!AeDemoProcessOptions(&config, &argc, argv, 1)) { AeDemoUsage(argv[0], "url"); return 1; } /* initialize Axeda Agent Embedded */ AeInitialize(); /* apply options */ AeDemoApplyConfig(&config); /* configure master device */ rc = AeDRMAddDevice(AeDRMDeviceMaster, MODEL_NUMBER, SERIAL_NUMBER, &iDeviceId); if (rc != AeEOK) { fprintf(stderr, "Failed to add device (%s)\n", AeGetErrorString(rc)); return 1; } /* configure primary DRM server */ pingRate.iSec = PING_RATE; pingRate.iMicroSec = 0; rc = AeDRMAddServer(AeDRMServerConfigPrimary, argv[argc], config.pOwner, &pingRate, &iServerId); if (rc != AeEOK) { fprintf(stderr, "Failed to add server (%s)\n", AeGetErrorString(rc)); return 1; } AeWebSetPersistent(iServerId, AeTrue); /* install command callbacks */ AeDRMSetOnCommandSetTag(AeDemoOnSetTag); AeDRMSetOnCommandSetTime(AeDemoOnSetTime); AeDRMSetOnCommandRestart(AeDemoOnRestart); timeLimit.iSec = 1; timeLimit.iMicroSec = 0; /* execute demo until keystroke */ #ifdef WIN32 while (!_kbhit()) #else while (1) #endif { /* do DRM processing */ AeDRMExecute(&timeLimit); } /* shutdown Axeda Agent Embedded */ AeShutdown(); #if defined(WIN32) && defined(_DEBUG)&& (_MSC_VER < 1300) _CrtDumpMemoryLeaks(); #endif return 0; }
DWORD OnPreprocHeaders( HTTP_FILTER_CONTEXT * pfc, HTTP_FILTER_PREPROC_HEADERS * pPPH) { int rc = SF_STATUS_REQ_NEXT_NOTIFICATION; InitializeCriticalSection( &g_AgentLock ); if (!ssoAgent->isStarted()) { ssoAgent->start(); } LeaveCriticalSection(&g_AgentLock); if (!ssoAgent->isStarted()) { syslog(JK_LOG_ERROR_LEVEL, "JOSSO Agent is not running ..."); return SF_STATUS_REQ_ERROR; } // Create request / response objects SSOAgentRequest *req = ssoAgent->initIsapiFilterRequest(pfc, SF_NOTIFY_PREPROC_HEADERS, pPPH); if (req == NULL) { jk_log(ssoAgent->logger, JK_LOG_ERROR, "Cannot initialize SSO Agent Request"); syslog(JK_LOG_ERROR_LEVEL, "Cannot initialize SSO Agent Request"); return SF_STATUS_REQ_ERROR; } SSOAgentResponse *res = ssoAgent->initIsapiFilterResponse(pfc, SF_NOTIFY_PREPROC_HEADERS, pPPH); if (res == NULL) { jk_log(ssoAgent->logger, JK_LOG_ERROR, "Cannot initialize SSO Agent Response"); syslog(JK_LOG_ERROR_LEVEL, "Cannot initialize SSO Agent Response"); return SF_STATUS_REQ_ERROR; } jk_log(ssoAgent->logger, JK_LOG_TRACE, "Request / Response initialized ..."); string pJossoNode = req->getParameter("josso_node"); if (!pJossoNode.empty()) { res->setCookie("JOSSO_NODE", pJossoNode, "/", false); } string &path = req->getPath(); jk_log(ssoAgent->logger, JK_LOG_DEBUG, "Processing request for URI %s", path.c_str()); // Verify that this URI is a partner application PartnerAppConfig *appCfg = ssoAgent->getPartnerAppConfig(path); if (appCfg == NULL) { jk_log(ssoAgent->logger, JK_LOG_DEBUG, "[%s] is not associated to a partner application, ignoring", path.c_str()); } else { jk_log(ssoAgent->logger, JK_LOG_DEBUG, "[%s] is associated to %s partner application", path.c_str(), appCfg->getId()); //string appKey (appCfg->getKey()); if (!ssoAgent->isIgnored(appCfg, req)) { jk_log(ssoAgent->logger, JK_LOG_TRACE, "[%s] is associated to %s partner application and will be processed", path.c_str(), appCfg->getId()); // We found the application config, check if the resource must be ignored // Send P3P Header (TODO : Make it optional) res->addHeader("P3P", "CP=\"CAO PSA OUR\""); // Create security context if (!ssoAgent->createSecurityContext(req, appCfg)) { // Clean up SSO Cookie jk_log(ssoAgent->logger, JK_LOG_DEBUG, "Cleaning SSO Cookie"); res->setCookie("JOSSO_SESSIONID", "-", "/"); } bool isAuthenticated = req->isAuthenticated(); bool isAuthorized = ssoAgent->isAuthorized(req); // Check for automatic Login if (!isAuthenticated) { // Only trigger automatic login if resource is public, otherwise a full login will be triggered later. if (isAuthorized) { jk_log(ssoAgent->logger, JK_LOG_DEBUG, "Request is authorized, but not authenticated, check automatic login [%s]", path.c_str()); if (ssoAgent->isAutomaticLoginRequired(req, res)) { jk_log(ssoAgent->logger, JK_LOG_DEBUG, "Automatic login started[%s]", path.c_str()); ssoAgent->requestLogin(req, res, appCfg, true); rc = SF_STATUS_REQ_FINISHED; } } } else { // This is an authenticated request, clean up any autologin state if present. string autoLoginExecuted = req->getCookie("JOSSO_AUTOMATIC_LOGIN_EXECUTED"); if (!autoLoginExecuted.empty() && autoLoginExecuted.compare("-") != 0) { res->setCookie("JOSSO_AUTOMATIC_LOGIN_EXECUTED", "-", "/", false); } string autoLoginReferer = req->getCookie("JOSSO_AUTOLOGIN_REFERER"); if (!autoLoginReferer.empty() && autoLoginReferer.compare("-") != 0) { res->setCookie("JOSSO_AUTOLOGIN_REFERER", "-", "/", false); } } // Check for security constraints if (!isAuthorized) { if (req->getRemoteUser().empty()) { // User is not authorized to access this resource, but was not authenticated yet -> ask for login jk_log(ssoAgent->logger, JK_LOG_DEBUG, "annonymous accesss to [%s] requires authentication, redirecting to login page", path.c_str()); ssoAgent->requestLogin(req, res, appCfg, false); rc = SF_STATUS_REQ_FINISHED; } else { // User is not authorized to access this, but was authenticated, -> return HTTP 403 status. jk_log(ssoAgent->logger, JK_LOG_DEBUG, "[%s] user cannot access [%s], returning HTTP 403 status", req->getRemoteUser().c_str(), path.c_str()); res->sendStatus(HTTP_STATUS_FORBIDDEN, "Forbidden"); // Send a HTTP STATUS 403, Forbidden! rc = SF_STATUS_REQ_FINISHED; } } } else { // Configured as ignored! jk_log(ssoAgent->logger, JK_LOG_TRACE, "[%s] is associated to %s partner application, but ignored", path.c_str(), appCfg->getId()); } } if (rc == SF_STATUS_REQ_NEXT_NOTIFICATION) { // We did not handled this request, but some headers might have been set, so flush them! if (!res->flushHeaders()) { jk_log(ssoAgent->logger, JK_LOG_ERROR, "Cannot flush headers!"); } } // ----------------------------------------------- // !!! IMPORTAT : CLEAN UP AFTER EACH REQUEST !!!! // ----------------------------------------------- jk_log(ssoAgent->logger, JK_LOG_DEBUG, "Processed request for URI %s", path.c_str()); delete req; delete res; _CrtDumpMemoryLeaks(); return rc; } /* HttpFilterProc */
void my_end(int infoflag) { /* this code is suboptimal to workaround a bug in Sun CC: Sun C++ 5.6 2004/06/02 for x86, and should not be optimized until this compiler is not in use anymore */ FILE *info_file= DBUG_FILE; my_bool print_info= (info_file != stderr); if (!my_init_done) return; /* We do not use DBUG_ENTER here, as after cleanup DBUG is no longer operational, so we cannot use DBUG_RETURN. */ DBUG_PRINT("info",("Shutting down: infoflag: %d print_info: %d", infoflag, print_info)); if (!info_file) { info_file= stderr; print_info= 0; } if ((infoflag & MY_CHECK_ERROR) || print_info) { /* Test if some file is left open */ if (my_file_opened | my_stream_opened) { char ebuff[512]; my_snprintf(ebuff, sizeof(ebuff), EE(EE_OPEN_WARNING), my_file_opened, my_stream_opened); my_message_stderr(EE_OPEN_WARNING, ebuff, ME_BELL); DBUG_PRINT("error", ("%s", ebuff)); my_print_open_files(); } } free_charsets(); my_error_unregister_all(); my_once_free(); if ((infoflag & MY_GIVE_INFO) || print_info) { #ifdef HAVE_GETRUSAGE struct rusage rus; #ifdef HAVE_purify /* Purify assumes that rus is uninitialized after getrusage call */ bzero((char*) &rus, sizeof(rus)); #endif if (!getrusage(RUSAGE_SELF, &rus)) fprintf(info_file,"\n\ User time %.2f, System time %.2f\n\ Maximum resident set size %ld, Integral resident set size %ld\n\ Non-physical pagefaults %ld, Physical pagefaults %ld, Swaps %ld\n\ Blocks in %ld out %ld, Messages in %ld out %ld, Signals %ld\n\ Voluntary context switches %ld, Involuntary context switches %ld\n", (rus.ru_utime.tv_sec * SCALE_SEC + rus.ru_utime.tv_usec / SCALE_USEC) / 100.0, (rus.ru_stime.tv_sec * SCALE_SEC + rus.ru_stime.tv_usec / SCALE_USEC) / 100.0, rus.ru_maxrss, rus.ru_idrss, rus.ru_minflt, rus.ru_majflt, rus.ru_nswap, rus.ru_inblock, rus.ru_oublock, rus.ru_msgsnd, rus.ru_msgrcv, rus.ru_nsignals, rus.ru_nvcsw, rus.ru_nivcsw); #endif #if defined(__WIN__) && defined(_MSC_VER) _CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE ); _CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDERR ); _CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE ); _CrtSetReportFile( _CRT_ERROR, _CRTDBG_FILE_STDERR ); _CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_FILE ); _CrtSetReportFile( _CRT_ASSERT, _CRTDBG_FILE_STDERR ); _CrtCheckMemory(); _CrtDumpMemoryLeaks(); #endif } if (!(infoflag & MY_DONT_FREE_DBUG)) { DBUG_END(); /* Must be done before my_thread_end */ } my_thread_end(); my_thread_global_end(); #if defined(SAFE_MUTEX) /* Check on destroying of mutexes. A few may be left that will get cleaned up by C++ destructors */ safe_mutex_end((infoflag & (MY_GIVE_INFO | MY_CHECK_ERROR)) ? stderr : (FILE *) 0); #endif /* defined(SAFE_MUTEX) */ #ifdef __WIN__ if (have_tcpip) WSACleanup(); #endif /* __WIN__ */ my_init_done=0; my_basic_init_done= 0; } /* my_end */
int main(int argc, char *argv[], char *envp[]) { int RValue = false; int CaptureModeHex = 0; int NewChar=0; int nResult = 0; int arraySize = 2000; printf ("main - start\n"); const char* ClassFileNaMe = "allegro.log"; // signal(SIGSEGV, posix_death_signal); // printHex(ClassFileNaMe); // segfault(); throw_error t_err; //Exp _exp; // _exp.run(); /* try { // func( 10 ); fall_in_file(); } catch ( const std::exception& msg ) // catch ( const char* msg) { std::cout << "Application had exception handling with message: "; // std::cout << msg; printf ("%s\n", msg.what()); std::cout << "-------------------" << strerror(errno); //return 1; } catch (...) { cout << "Unknown Error!!!!" << std::endl; std::cout << "-------------------" << strerror(errno); }*/ //std::stringstream ss; std::auto_ptr <Auto> bakery(new Auto()); char* pleak = new char[1024]; // might be lost => memory leak __try { //fault_simple(); //fall(); //t_err.Run(); // open_my_file(); // fall_in_file(); // call an exception delete [] pleak; // will only get here if x == 0. if x!=0, throw exception } __except (EXCEPTION_EXECUTE_HANDLER) { std::cout << "-------------------" << strerror(errno); // memento(); } /* */ #ifdef YS_TEST213413_B try { //my_exceptions m_ex; //m_ex.run(); //fault_simple(); // t_err->Run(); // open_my_file(); } catch (std::runtime_error _str_error) { std::cout << _str_error.what(); throw; } catch (DivideByZeroError err) { cout << "ERROR: "; err.printMesage(); cout << endl; return 1; } catch (...) { cout << "Unknown Error!!!!" << std::endl; } #endif //*************MAIN LOOP*****************// cout << "\n$ > Press any key to exit." << std::endl; do { //This is simple Windows way: Sleep(55); // control of endless loop (may be also in monitor.cpp) if (_kbhit()) // has anything been pressed from keyboard ? { NewChar=(unsigned char)_getch(); RValue = true; if ((NewChar & 0xff) == 24) // CTRL-X pressed { RValue = true; // END mark } if (NewChar == 'd') // pressed { if (1 == CaptureModeHex) CaptureModeHex = 1; else CaptureModeHex = 0; } } } while (!RValue); printf ("Application complete.\n"); _CrtDumpMemoryLeaks(); return 0; }
void DumpMemoryInfo() { DebugOut("\n Dump Info:\n"); _CrtDumpMemoryLeaks(); }
void main(int argc,char *argv[]) { bool CreateNewDBFromIDA=TRUE; TCHAR *optstring=TEXT("f:i:I:L:ld:s:t:y"); int optind=0; TCHAR *optarg; int c; char *SourceFilename=NULL; char *TargetFilename=NULL; char *LogFilename=NULL; BOOL bListFiles=FALSE; char *IDAPath=NULL; BOOL UseIDASync=FALSE; DWORD SourceFunctionAddress=0; DWORD TargetFunctionAddress = 0; int SourceFileID; int TargetFileID; int DebugLevel = 0; bool is_64 = false; //TODO: #ifdef DEBUG_MEMORY _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDOUT); _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDOUT); _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDOUT); #endif while((c=getopt(argc,argv,optstring,&optind,&optarg))!=EOF) { switch(c) { case 'f': SourceFilename=optarg; TargetFilename=argv[optind]; optind++; break; case 'i': SourceFileID=strtoul10(optarg); TargetFileID=strtoul10(argv[optind]); optind++; break; case 'd': DebugLevel=strtoul10(optarg); break; case 's': SourceFunctionAddress = strtoul(optarg, NULL, 16); break; case 't': TargetFunctionAddress = strtoul(optarg, NULL, 16); break; case 'I': IDAPath=optarg; break; case 'L': LogFilename=optarg; break; case 'l': bListFiles=TRUE; break; case 'y': UseIDASync=TRUE; break; } } if(argc<=optind) { printf("Usage: %s [-f <original filename> <patched filename>]|[-i <original file id> <patched file id>]|-l -L <Log Filename> [-y] <database filename>\r\n" " - f <original filename> <patched filename>\r\n" " Original filename and patched filename\r\n" " Retrieve data from IDA using DarunGrim IDA plugin\r\n" "-i <original file id> <patched file id>\r\n" " Original files ID in the database and patched files ID in the database\r\n" " Retrieve data from database file created using DarunGrim IDA plugin\r\n" "-I IDA Program path.\r\n" //Debugging related parameters "-L Debug Log Filename\r\n" "-d <level> Debug Level\r\n" "-s <function address> Function address to analyze for the original binary\r\n" "-t <function address> Function address to analyze for the patched binary\r\n" "-y Use IDA synchorinzation mode\r\n" "-l: \r\n" " List file informations in the <database filename>\r\n" "<database filename>\r\n" " Database filename to use\r\n\r\n", argv[0]); return; } DarunGrim *pDarunGrim = new DarunGrim(); if (IDAPath) pDarunGrim->SetIDAPath(IDAPath,is_64); pDarunGrim->SetLogParameters(LogToStdout, DebugLevel, ""); char *DiffDatabaseFilename=argv[optind]; if (bListFiles) { pDarunGrim->ListDiffDatabase(DiffDatabaseFilename); } else if (SourceFilename && TargetFilename && DiffDatabaseFilename) { pDarunGrim->PerformDiff( SourceFilename, SourceFunctionAddress, TargetFilename, TargetFunctionAddress, DiffDatabaseFilename); } else { pDarunGrim->AcceptIDAClientsFromSocket(); pDarunGrim->PerformDiff(); } if(UseIDASync) { pDarunGrim->ShowOnIDA(); } #ifdef DEBUG_MEMORY _CrtDumpMemoryLeaks(); #endif }
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPreviousInst, LPSTR lpCmdLine, int nCmdShow) { WNDCLASS wndClass; wndClass.style = CS_HREDRAW | CS_VREDRAW; wndClass.lpfnWndProc = WndProc; wndClass.cbClsExtra = 0; wndClass.cbWndExtra = 0; wndClass.hInstance = hInstance; wndClass.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON)); wndClass.hCursor = LoadCursor(NULL, IDC_ARROW); wndClass.hbrBackground = (HBRUSH) GetStockObject(LTGRAY_BRUSH); wndClass.lpszMenuName = NULL; wndClass.lpszClassName = "FOnline"; if (!RegisterClass(&wndClass)) { char* msg = FormatLastWin32Error(); ReportErrorMessage("Win32 error.", "Could not register window class: %s", msg); free(msg); return -1; } if (!OpenLogFile("FOnlineClient.log")) { ReportErrorMessage("IO error.", "Could not open log file."); return -1; } LoadSettings(); size_t modeWidth = screen_width[opt_screen_mode]; size_t modeHeight = screen_height[opt_screen_mode]; HWND hWnd = CreateWindow( "FOnline", "Fallout Online", WS_OVERLAPPEDWINDOW & (~WS_MAXIMIZEBOX) & (~WS_SIZEBOX) & (~WS_SYSMENU), 0,0,modeWidth + 5, modeHeight + 25, NULL, NULL, hInstance, NULL ); if (hWnd == NULL) { char* msg = FormatLastWin32Error(); ReportErrorMessage("Win32 error.", "Could not create window: %s", msg); free(msg); return -1; } ShowWindow(hWnd, SW_SHOWNORMAL); UpdateWindow(hWnd); FONLINE_LOG("Starting FOnline...\n"); srand(GetTickCount()); engine = new FOnlineEngine; if (!engine->Init(hWnd)) { FONLINE_LOG("Could not initialize the engine.\n"); DestroyWindow(hWnd); return 0; } MSG msg; while(!cmn_Quit) { if(!cmn_lost) { if(PeekMessage(&msg, NULL, NULL, NULL, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } else { engine->Render(); if (opt_sleep) Sleep(opt_sleep); } } else { GetMessage(&msg, NULL, NULL, NULL); TranslateMessage(&msg); DispatchMessage(&msg); } } FONLINE_LOG("\nFOnline Closed\n"); CloseLogFile(); delete engine; //SimpleLeakDetector::PrintAllLeaks(); _CrtDumpMemoryLeaks(); return 0; }
BOOL AFXAPI AfxDumpMemoryLeaks() { return _CrtDumpMemoryLeaks(); }
int _tmain(int argc, _TCHAR* argv[]) { HANDLE hVolume; LPWSTR lpDrive = L"\\\\.\\c:"; NTFS_VOLUME_DATA_BUFFER ntfsVolData = {0}; BOOL bDioControl = FALSE; DWORD dwWritten = 0; LARGE_INTEGER num; LONGLONG total_file_count, i; NTFS_FILE_RECORD_INPUT_BUFFER mftRecordInput; PNTFS_FILE_RECORD_OUTPUT_BUFFER output_buffer; hVolume = CreateFile(lpDrive, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); if(hVolume == INVALID_HANDLE_VALUE) { wprintf(L"CreateFile() failed!\n"); ErrorMessage(GetLastError()); if(CloseHandle(hVolume) != 0) wprintf(L"hVolume handle was closed successfully!\n"); else { wprintf(L"Failed to close hVolume handle!\n"); ErrorMessage(GetLastError()); } exit(1); } else wprintf(L"CreateFile() is pretty fine!\n"); // a call to FSCTL_GET_NTFS_VOLUME_DATA returns the structure NTFS_VOLUME_DATA_BUFFER bDioControl = DeviceIoControl(hVolume, FSCTL_GET_NTFS_VOLUME_DATA, NULL, 0, &ntfsVolData, sizeof(NTFS_VOLUME_DATA_BUFFER), &dwWritten, NULL); if(bDioControl == 0) { wprintf(L"DeviceIoControl() failed!\n"); ErrorMessage(GetLastError()); if(CloseHandle(hVolume) != 0) wprintf(L"hVolume handle was closed successfully!\n"); else { wprintf(L"Failed to close hVolume handle!\n"); ErrorMessage(GetLastError()); } exit(1); } else wprintf(L"DeviceIoControl(...,FSCTL_GET_NTFS_VOLUME_DATA,...) is working...\n\n"); wprintf(L"Volume Serial Number: 0X%.8X%.8X\n",ntfsVolData.VolumeSerialNumber.HighPart,ntfsVolData.VolumeSerialNumber.LowPart); wprintf(L"The number of bytes in a cluster: %u\n",ntfsVolData.BytesPerCluster); wprintf(L"The number of bytes in a file record segment: %u\n",ntfsVolData.BytesPerFileRecordSegment); wprintf(L"The number of bytes in a sector: %u\n",ntfsVolData.BytesPerSector); wprintf(L"The number of clusters in a file record segment: %u\n",ntfsVolData.ClustersPerFileRecordSegment); wprintf(L"The number of free clusters in the specified volume: %u\n",ntfsVolData.FreeClusters); wprintf(L"The starting logical cluster number of the master file table mirror: 0X%.8X%.8X\n",ntfsVolData.Mft2StartLcn.HighPart, ntfsVolData.Mft2StartLcn.LowPart); wprintf(L"The starting logical cluster number of the master file table: 0X%.8X%.8X\n",ntfsVolData.MftStartLcn.HighPart, ntfsVolData.MftStartLcn.LowPart); wprintf(L"The length of the master file table, in bytes: %u\n",ntfsVolData.MftValidDataLength); wprintf(L"The ending logical cluster number of the master file table zone: 0X%.8X%.8X\n",ntfsVolData.MftZoneEnd.HighPart, ntfsVolData.MftZoneEnd.LowPart); wprintf(L"The starting logical cluster number of the master file table zone: 0X%.8X%.8X\n",ntfsVolData.MftZoneStart.HighPart, ntfsVolData.MftZoneStart.LowPart); wprintf(L"The number of sectors: %u\n",ntfsVolData.NumberSectors); wprintf(L"Total Clusters (used and free): %u\n",ntfsVolData.TotalClusters); wprintf(L"The number of reserved clusters: %u\n\n",ntfsVolData.TotalReserved); num.QuadPart = 1024; // 1024 or 2048 // We divide the MftValidDataLength (Master file table length) by 1024 to find // the total entry count for the MFT total_file_count = (ntfsVolData.MftValidDataLength.QuadPart/num.QuadPart); //total_file_count = 50; //test wprintf(L"Total file count = %u\n", total_file_count); MFT_FILE_INFO* pfile_info = (MFT_FILE_INFO*)malloc(sizeof(MFT_FILE_INFO)*total_file_count); for(i = 0; i < total_file_count;i++) { mftRecordInput.FileReferenceNumber.QuadPart = i; //int kkk = sizeof(mftRecordInput); // prior to calling the DeviceIoControl() we need to load // an input record with which entry number we want //int kk = sizeof(NTFS_FILE_RECORD_OUTPUT_BUFFER)+ntfsVolData.BytesPerFileRecordSegment-1; // setup outputbuffer - FSCTL_GET_NTFS_FILE_RECORD depends on this output_buffer = (PNTFS_FILE_RECORD_OUTPUT_BUFFER)malloc(sizeof(NTFS_FILE_RECORD_OUTPUT_BUFFER)+ntfsVolData.BytesPerFileRecordSegment-1); if(output_buffer == NULL) { wprintf(L"malloc() failed - insufficient memory!\n"); ErrorMessage(GetLastError()); exit(1); } DWORD ooo = FSCTL_GET_NTFS_FILE_RECORD; bDioControl = DeviceIoControl(hVolume, FSCTL_GET_NTFS_FILE_RECORD, &mftRecordInput, sizeof(mftRecordInput), output_buffer, sizeof(NTFS_FILE_RECORD_OUTPUT_BUFFER) + (ntfsVolData.BytesPerFileRecordSegment)- 1, &dwWritten, NULL); // More data will make DeviceIoControl() fails... /*if(bDioControl == 0) { wprintf(L"DeviceIoControl(...,FSCTL_GET_NTFS_FILE_RECORD,...) failed!\n"); ErrorMessage(GetLastError()); exit(1); }*/ // FSCTL_GET_NTFS_FILE_RECORD retrieves one MFT entry // FILE_RECORD_HEADER is the Base struct for the MFT entry // that we will work from PFILE_RECORD_HEADER p_file_record_header = (PFILE_RECORD_HEADER)output_buffer->FileRecordBuffer; PFILENAME_ATTRIBUTE fn; PSTANDARD_INFORMATION si; POBJECTID_ATTRIBUTE objid; PATTRIBUTE attr = (PATTRIBUTE)((LPBYTE)p_file_record_header + p_file_record_header->AttributesOffset); PRESIDENT_ATTRIBUTE preg; int stop = min(8,p_file_record_header->NextAttributeNumber); if(p_file_record_header->Ntfs.Type =='ELIF'){ while(true){ if (attr->AttributeType<0 || attr->AttributeType>0x100) break; switch(attr->AttributeType) { case AttributeFileName: preg = PRESIDENT_ATTRIBUTE(attr); fn = PFILENAME_ATTRIBUTE(PUCHAR(attr) + PRESIDENT_ATTRIBUTE(attr)->ValueOffset); if (fn->NameType & WIN32_NAME || fn->NameType == 0) { if(p_file_record_header->Flags & 0x1){ wprintf(L"FileName InUse\n") ; }else{ wprintf(L"FileName NOt In Use\n") ; } if(p_file_record_header->Flags & 0x2){ wprintf(L"FileName Directory\n") ; }else{ wprintf(L"FileName File\n") ; } wprintf(L"FileName i : %u\n", i ); wprintf(L"FileName DirectoryFileReferenceNumber : %u\n", fn->DirectoryFileReferenceNumber ); wprintf(L"FileName DataSize : %u\n", fn->DataSize ); fn->Name[fn->NameLength] = L'\0'; wprintf(L"FileName Name :%s\n", fn->Name) ; //pfile_info[i].Name = (LPWSTR)malloc((lstrlenW(fn->Name)+1)*sizeof(WCHAR)); pfile_info[i].Name = new WCHAR[lstrlenW(fn->Name)+1]; lstrcpyW(pfile_info[i].Name , fn->Name); pfile_info[i].Size = fn->DataSize; //LPWSTR lp = fn->Name; //wprintf(L"FileName Name :%s\n", lp) ; if (lstrcmpW(fn->Name, L"3-chmode1.raw")==0) { //if(i==28635){ int h=0; } } break; case AttributeStandardInformation: preg = PRESIDENT_ATTRIBUTE(attr); si = PSTANDARD_INFORMATION(PUCHAR(attr) + PRESIDENT_ATTRIBUTE(attr)->ValueOffset); wprintf(L"#####StandardInformation CreationTime : %u\n", si->CreationTime ); break; //case AttributeObjectId: // objid = POBJECTID_ATTRIBUTE(PUCHAR(attr) + PRESIDENT_ATTRIBUTE(attr)->ValueOffset); // wprintf(L"ObjectId Data1 : %u\n", objid->ObjectId.Data1 ); // wprintf(L"ObjectId Data2 : %u\n", objid->ObjectId.Data2 ); // wprintf(L"ObjectId Data3 : %u\n", objid->ObjectId.Data3 ); // wprintf(L"ObjectId Data4[0] : %u\n", objid->ObjectId.Data4[0] ); // wprintf(L"ObjectId Data4[1] : %u\n", objid->ObjectId.Data4[1] ); // wprintf(L"ObjectId Data4[2] : %u\n", objid->ObjectId.Data4[2] ); // wprintf(L"ObjectId Data4[3] : %u\n", objid->ObjectId.Data4[3] ); // wprintf(L"ObjectId Data4[3] : %u\n", objid->ObjectId.Data4[4] ); // wprintf(L"ObjectId Data4[3] : %u\n", objid->ObjectId.Data4[5] ); // wprintf(L"ObjectId Data4[3] : %u\n", objid->ObjectId.Data4[6] ); // wprintf(L"ObjectId Data4[3] : %u\n", objid->ObjectId.Data4[7] ); // break; default: break; }; if (attr->Length>0 && attr->Length < p_file_record_header->BytesInUse) attr = PATTRIBUTE(PUCHAR(attr) + attr->Length); else if (attr->Nonresident == TRUE) attr = PATTRIBUTE(PUCHAR(attr) + sizeof(NONRESIDENT_ATTRIBUTE)); } } wprintf(L"\n"); free(output_buffer); } // Let verify wprintf(L"i\'s count = %u\n", i); //====================== if(CloseHandle(hVolume) != 0) wprintf(L"hVolume handle was closed successfully!\n"); else { wprintf(L"Failed to close hVolume handle!\n"); ErrorMessage(GetLastError()); } // De-allocate the memory by malloc() //free(output_buffer); //free(pfile_info); _CrtDumpMemoryLeaks(); return 0; }
int main(int argc, char** argv) { int result; (void)argc, argv; amqpalloc_set_memory_tracing_enabled(true); if (platform_init() != 0) { result = -1; } else { size_t last_memory_used = 0; SOCKET_LISTENER_HANDLE socket_listener = socketlistener_create(5672); if (socketlistener_start(socket_listener, on_socket_accepted, NULL) != 0) { result = -1; } else { while (true) { size_t current_memory_used; size_t maximum_memory_used; socketlistener_dowork(socket_listener); current_memory_used = amqpalloc_get_current_memory_used(); maximum_memory_used = amqpalloc_get_maximum_memory_used(); if (current_memory_used != last_memory_used) { printf("Current memory usage:%lu (max:%lu)\r\n", (unsigned long)current_memory_used, (unsigned long)maximum_memory_used); last_memory_used = current_memory_used; } if (sent_messages == msg_count) { break; } if (connection != NULL) { connection_dowork(connection); } } result = 0; } socketlistener_destroy(socket_listener); platform_deinit(); printf("Max memory usage:%lu\r\n", (unsigned long)amqpalloc_get_maximum_memory_used()); printf("Current memory usage:%lu\r\n", (unsigned long)amqpalloc_get_current_memory_used()); } #ifdef _CRTDBG_MAP_ALLOC _CrtDumpMemoryLeaks(); #endif return result; }
int main( int argc, char *argv[] ) { // Set the debug heap to report memory leaks when the process terminates, // and to keep freed blocks in the linked list. #ifndef LINUX //_CrtSetDbgFlag( _CRTDBG_LEAK_CHECK_DF | _CRTDBG_DELAY_FREE_MEM_DF ); /* TEST FOR MEMORY LEAKS:*/ _CrtMemState memstate; _CrtMemState memstate2; _CrtMemState memstate3; _CrtMemCheckpoint(&memstate); #endif #ifndef LINUX _CrtMemCheckpoint(&memstate2); _CrtMemDifference(&memstate3, &memstate, &memstate2); _RPT0(_CRT_WARN, "Here's what we allocated some notes...\n"); _CrtMemDumpStatistics(&memstate3); _CrtMemDumpAllObjectsSince( &memstate ); #endif if( argc < 3 ) { printf("Two arguments expected.\n"); printf("Need to run with one MIDI file and a specified directory.\n"); return 0; } if( argc == 3 ){ fprintf(stderr, "MIDI file to read in: %s\n", argv[1]); fprintf(stderr, "Directory to store files: %s\n", argv[2]); } if( argc > 3 ) { printf("Too many arguments supplied.\n"); printf("Need to run with one MIDI file and a specified directory.\n"); return 0; } char * FILENAME = argv[1]; Alg_seq_ptr seq = read_file(FILENAME); char * slash = strrchr(FILENAME,'/'); if(slash != 0){ //printf("%s\n", slash+1); FILENAME = slash + 1; } char FILENAME_gro[1000]; char * DIRECTORY = argv[2]; int i = 0; for(; i < strlen(DIRECTORY); i++){ FILENAME_gro[i] = DIRECTORY[i]; } int j = 0; for(; j < strrchr(FILENAME, '.') - FILENAME && j < 1000-5; j++){ FILENAME_gro[i+j] = FILENAME[j]; } FILENAME_gro[i+j] = '.'; FILENAME_gro[i+j+1] = 'g'; FILENAME_gro[i+j+2] = 'r'; FILENAME_gro[i+j+3] = 'o'; FILENAME_gro[i+j+4] = '\0'; // Saving MIDI file as .gro text fprintf(stderr, "save as text in %s...\n", FILENAME_gro); FILE *outf = fopen(FILENAME_gro, "w"); alg_write(seq, outf); fclose(outf); /**/ /* DELETE THE DATA */ delete seq; #ifndef LINUX _CrtDumpMemoryLeaks( ); #endif /**/ return 0; }
//—————————————————————— //エントリーポイント //—————————————————————— int WINAPI WinMain(HINSTANCE hCurInst, HINSTANCE hPrevInst, LPSTR lpsCmdLine, int nCmdShow) { #if _DEBUG _CrtDumpMemoryLeaks(); _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); #endif MSG msg; //ウィンドウクラスの登録 if (!InitApp(hCurInst)) return FALSE; //ウィンドウ生成 if (!InitInstance(hCurInst, nCmdShow)) return FALSE; //ランダムの準備 srand((unsigned)time(NULL)); //ゲームオブジェクトを作成 game = new Game; //Direct3Dの初期化 if (FAILED(game->InitD3d(hWnd))) { return FALSE; } //入力処理の初期化 g_pInput = new Input(); g_pInput->Init(hWnd); //読み込み処理 if (FAILED(game->Load())) { return FALSE; } // メッセージを取得 ZeroMemory(&msg, sizeof(msg)); while (msg.message != WM_QUIT) { if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } else { if (isEnd) { break; } //ゲームの更新 if (FAILED(game->Update())) { return FALSE; } //衝突判定 if (FAILED(game->Hit())) { return FALSE; } //ゲーム画面の描画 if (FAILED(game->Render())) { return FALSE; } } } return (int)msg.wParam; }
int main( int argc, const char* argv[] ) { #ifdef WIN32 _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); #endif int ret=-1; time_t start_time=time(NULL); FILE *file=NULL; int writer_indent=0; pbool_t reader_mce=PTRUE; const char *fileName=NULL; for(int i=1;i<argc;i++) { if ((0==xmlStrcmp(_X("--understands"), _X(argv[i])) || 0==xmlStrcmp(_X("-u"), _X(argv[i]))) && i+1<argc) { i++; // skip namespace, registered later when parser was created. } else if ((0==xmlStrcmp(_X("--out"), _X(argv[i])) || 0==xmlStrcmp(_X("--out"), _X(argv[i]))) && i+1<argc && NULL==file) { const char *filename=argv[++i]; file=fopen(filename, "w"); } else if (0==xmlStrcmp(_X("--indent"), _X(argv[i]))) { writer_indent=1; } else if (0==xmlStrcmp(_X("--raw"), _X(argv[i]))) { reader_mce=PFALSE; } else if (NULL==fileName) { fileName=argv[i]; } else { fprintf(stderr, "IGNORED: %s\n", argv[i]); } } xmlTextWriter *writer=xmlNewTextWriterFile(file); if (NULL==fileName || NULL==writer) { printf("mcepp [--understands NAMESPACE] [--out FILENAME] [--indent] [--raw] [FILENAME | - ]\n\n"); printf("Sample: mcepp sample.xml\n"); } else { xmlInitParser(); xmlTextWriterSetIndent(writer, writer_indent); mceTextReader_t mceTextReader; mceTextReaderInit(&mceTextReader, ('-'==fileName[0] && 0==fileName[1]?xmlReaderForFd(0, NULL, NULL, 0):xmlReaderForFile(fileName, NULL, 0))); mceTextReaderDisableMCE(&mceTextReader, !reader_mce); for(int i=1;i<argc;i++) { if ((0==xmlStrcmp(_X("--understands"), _X(argv[i])) || 0==xmlStrcmp(_X("-u"), _X(argv[i]))) && i+1<argc) { const xmlChar *ns=_X(argv[++i]); mceTextReaderUnderstandsNamespace(&mceTextReader, ns); } } if (-1==mceTextReaderDump(&mceTextReader, writer, PFALSE)) { ret=mceTextReaderGetError(&mceTextReader); } else { ret=0; } mceTextReaderCleanup(&mceTextReader); xmlCleanupParser(); } if (NULL!=writer) xmlFreeTextWriter(writer); if (NULL!=file) fclose(file); time_t end_time=time(NULL); fprintf(stderr, "time %.2lfsec\n", difftime(end_time, start_time)); #ifdef WIN32 OPC_ASSERT(!_CrtDumpMemoryLeaks()); #endif return ret; }
void reportLeaks () { _CrtDumpMemoryLeaks (); }
int main() { int errorCode = 0; do { char buffer[150]; char* string1 = NULL; char* substring1 = NULL; // Make input string for user printf("Input some string:\n"); gets_s(buffer); if (0 == buffer) { errorCode = -1; break; } // Create dynamic string int stringLength1 = strlen(buffer); string1 = new char[stringLength1 + 1]; // +1 for '\0' strcpy(string1, buffer); #ifdef SHOW_MEMORY_ERRORS #define MEMORY_ERROR 2 #if 1 == MEMORY_ERROR // Wrong creation of dynamic string // Run app by CTRL-F5 in Debug version char* tempString = new char[stringLength1]; tempString[stringLength1] = 'f'; strcpy(tempString, buffer); delete[] tempString; tempString = NULL; // If you want use this variable later, you need clear pointer #else if 2 == MEMORY_ERROR // This is extansion of previous example // Start from here debuging and watch to variables char someString1[5] = "1234"; char someString2[5] = "abcd"; strcpy(someString2, "zxcv-------------"); int sizeOfStr1 = sizeof(someString1); int sizeOfStr2 = sizeof(someString2); #endif #endif printf("Input substring for search:\n"); gets_s(buffer); if (0 == buffer) { errorCode = -2; break; } int substringLength1 = strlen(buffer); substring1 = new char[substringLength1 + 1]; // +1 for '\0' strcpy(substring1, buffer); printf("Index of first entering for substring: %i\n", IndexOfSubstring(string1, substring1)); /////////////////////////////////////////////////////////////////////////// char* string2 = NULL; printf("Input string for palindrom check:\n"); gets_s(buffer); if (0 == buffer) { errorCode = -3; break; } // Create dynamic string int stringLength2 = strlen(buffer); string2 = new char[stringLength2 + 1]; strcpy(string2, buffer); printf("\nInput string %s palindrom\n", IsPalindrom(string2) ? "is" : "isn't"); ////it's the same as: //char* choiseStr; //if (IsPalindrom(string2)) //{ // choiseStr = "is"; //} //else //{ // choiseStr = "isn't"; //} //printf("Input string %s palindrom\n", choiseStr); /////////////////////////////////////////////////////////////////////////// // Some test strings: // aaabccba // aaabcba // aa // a char* string3 = NULL; printf("Input string for making palindrom:\n"); gets_s(buffer); if (0 == buffer) { errorCode = -4; break; } // Create dynamic string int stringLength3 = strlen(buffer); string3 = new char[stringLength3 + 1]; strcpy(string3, buffer); char* palindromString = MakePalindrom(string3); printf("Maded palindrom '%s'\n", palindromString); #ifndef SIMULATE_MEMORY_LEAKS delete[] string1; delete[] substring1; delete[] string2; delete[] string3; delete[] palindromString; #else //delete[] string1; //delete[] substring1; //delete[] string2; //delete[] string3; //delete[] palindromString; //MakePalindrom("aba"); #endif } while (false); #ifdef NEED_FIND_LEAKS if (0 == errorCode && _CrtDumpMemoryLeaks()) { printf("!!! There are some leaks. See 'Output' window in Visual Stusio.\n"); getchar(); } #endif return errorCode; }
void dumpLeaks() { _CrtDumpMemoryLeaks(); }
int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE h0, LPWSTR cmdLine, int cmdShow) { int ret = runDialog(hInst, cmdShow, DLG_MAIN, ICO_FROG, 0, Main_dialogProc, 0); _ASSERT(!_CrtDumpMemoryLeaks()); return ret; }
int main(int argc, char** argv) { SDL_Init(SDL_INIT_EVERYTHING); SDL_Window * window = SDL_CreateWindow("Tower Defense",100,50,872,588,SDL_WINDOW_SHOWN); SDL_Renderer * rend = SDL_CreateRenderer(window,-1,SDL_RENDERER_ACCELERATED); SDL_ShowCursor(0); TTF_Init(); IMG_Init(IMG_INIT_PNG); TextureLoader::getPtr()->setRenderer(rend); GlobalHeap::getPtr()->TextureObjects.Allocate(20); ScreenManager * mgr = ScreenManager::getPtr(); mgr->setRenderer(rend); mgr->setWindow(window); mgr->setActiveScreen(new StartScreen()); mgr->reevluate(); bool end = false; SDL_Event e; while(!end) { auto begin = std::chrono::high_resolution_clock::now(); mgr->reevluate(); if(mgr->screenRequestAppStop()) { break; } while(SDL_PollEvent(&e)) { if(e.type == SDL_QUIT) { end = true; break; } mgr->fireEventToActiveScreen(e); } mgr->updateActiveScreen(); SDL_SetRenderDrawColor(rend,0,0,0,255); mgr->drawActiveScreen(); SDL_RenderPresent(rend); auto end = std::chrono::high_resolution_clock::now(); int delta = std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count(); if(delta < 40) SDL_Delay(40 - delta); } ScreenManager::Destroy(); GlobalHeap::getPtr()->Destroy(); SDL_DestroyRenderer(rend); SDL_DestroyWindow(window); TTF_Quit(); SDL_Quit(); _CrtDumpMemoryLeaks(); return 0; }
/*---------------------------------------------------------------------- | main +---------------------------------------------------------------------*/ int main(int /*argc*/, char** /*argv*/) { // setup debugging #if defined(WIN32) && defined(_DEBUG) int flags = _crtDbgFlag | _CRTDBG_ALLOC_MEM_DF | _CRTDBG_DELAY_FREE_MEM_DF | _CRTDBG_CHECK_ALWAYS_DF; _CrtSetDbgFlag(flags); //AllocConsole(); //freopen("CONOUT$", "w", stdout); #endif NPT_Result result; TcpServerThread* server_thread = NULL; NPT_TcpClientSocket* tcp_client = NULL; NPT_TcpServerSocket* tcp_server = NULL; CancellerThread* canceller = NULL; NPT_SocketAddress address(NPT_IpAddress(127,0,0,1), 10000); #if 0 result = RemoteIpAddress.ResolveName("www.google.com"); CHECK(result == NPT_SUCCESS); NPT_Console::Output("--- test for immediate connection\n"); NPT_Console::Output("[01] starting write server thread\n"); server_thread = new TcpServerThread(); server_thread->Start(); NPT_Console::Output("[01] waiting for server to be ready...\n"); server_thread->m_Ready.WaitUntilEquals(1); NPT_Console::Output("[01] server thread ready\n"); NPT_Console::Output("[01] waiting a while...\n"); NPT_System::Sleep(3.0); tcp_client = new NPT_TcpClientSocket(); NPT_Console::Output("[01] connection to 127.0.0.1:10000\n"); result = tcp_client->Connect(address); NPT_Console::OutputF("[01] connect returns %d : %s\n", result, NPT_ResultText(result)); CHECK(result == NPT_SUCCESS); delete tcp_client; NPT_Console::Output("[01] terminating server\n"); server_thread->m_Interrupted = true; server_thread->Wait(); delete server_thread; NPT_Console::Output("\n--- test for refused local connection\n"); address.SetPort(89); tcp_client = new NPT_TcpClientSocket(); NPT_Console::Output("[01] connecting to 127.0.0.1:89\n"); result = tcp_client->Connect(address); NPT_Console::OutputF("[01] connect returns %d : %s\n", result, NPT_ResultText(result)); CHECK(result == NPT_ERROR_CONNECTION_REFUSED); delete tcp_client; /*NPT_Console::Output("\n--- test for refused remote connection\n"); address.SetIpAddress(RemoteIpAddress); address.SetPort(81); tcp_client = new NPT_TcpClientSocket(); NPT_Console::Output("[01] connecting to www.google.com:81\n"); result = tcp_client->Connect(address); NPT_Console::OutputF("[01] connect returns %d : %s\n", result, NPT_ResultText(result)); CHECK(result == NPT_ERROR_CONNECTION_REFUSED); delete tcp_client;*/ NPT_Console::Output("\n--- test for connection timeout\n"); address.SetIpAddress(NPT_IpAddress(1,1,1,1)); NPT_Console::Output("[01] connecting to 1.1.1.1:89\n"); tcp_client = new NPT_TcpClientSocket(); result = tcp_client->Connect(address, 3000); NPT_Console::OutputF("[01] connect returns %d : %s\n", result, NPT_ResultText(result)); CHECK(result == NPT_ERROR_TIMEOUT); delete tcp_client; NPT_Console::Output("\n--- test for remote connection\n"); address.SetIpAddress(RemoteIpAddress); address.SetPort(80); NPT_Console::Output("[01] connecting to www.google.com:80\n"); tcp_client = new NPT_TcpClientSocket(); result = tcp_client->Connect(address); NPT_Console::OutputF("[01] connect returns %d : %s\n", result, NPT_ResultText(result)); CHECK(result == NPT_SUCCESS); delete tcp_client; #endif for (int i=0; i<2; i++) { NPT_Console::OutputF("\n--- test for cancelled connection, shutdown=%d\n", i); address.SetIpAddress(NPT_IpAddress(1,1,1,1)); address.SetPort(89); NPT_Console::Output("[01] connecting to 1.1.1.1:89\n"); tcp_client = new NPT_TcpClientSocket(NPT_SOCKET_FLAG_CANCELLABLE); canceller = new CancellerThread(tcp_client, 3.0f, i==1); result = tcp_client->Connect(address); NPT_Console::OutputF("[01] connect returns %d : %s\n", result, NPT_ResultText(result)); CHECK(result == NPT_ERROR_CANCELLED); canceller->Wait(); delete canceller; delete tcp_client; } for (int i=0; i<2; i++) { NPT_Console::OutputF("\n--- testing read cancellation, shutdown=%d\n", i); address.SetIpAddress(RemoteIpAddress); address.SetPort(80); NPT_Console::Output("[01] connecting to www.google.com:80\n"); tcp_client = new NPT_TcpClientSocket(NPT_SOCKET_FLAG_CANCELLABLE); result = tcp_client->Connect(address); NPT_Console::OutputF("[01] connect returns %d : %s\n", result, NPT_ResultText(result)); CHECK(result == NPT_SUCCESS); canceller = new CancellerThread(tcp_client, 3.0f, i==1); NPT_InputStreamReference input; tcp_client->GetInputStream(input); unsigned char buffer[4096]; NPT_SetMemory(buffer, 0, sizeof(buffer)); result = input->Read(buffer, 4096); NPT_Console::OutputF("{00} read returned %d (%s)\n", result, NPT_ResultText(result)); CHECK(result == NPT_ERROR_CANCELLED); delete tcp_client; canceller->Wait(); delete canceller; } for (int i=0; i<2; i++) { NPT_Console::OutputF("\n--- testing write cancellation, shutdown=%d\n", i); server_thread = new TcpServerThread(); server_thread->Start(); NPT_Console::Output("[01] waiting for server to be ready...\n"); server_thread->m_Ready.WaitUntilEquals(1); NPT_Console::Output("[01] server thread ready\n"); NPT_Console::Output("[01] waiting a while...\n"); NPT_System::Sleep(3.0); address.SetIpAddress(NPT_IpAddress(127,0,0,1)); address.SetPort(10000); NPT_Console::Output("[01] connecting to localhost:10000\n"); tcp_client = new NPT_TcpClientSocket(NPT_SOCKET_FLAG_CANCELLABLE); result = tcp_client->Connect(address); NPT_Console::OutputF("[01] connect returns %d : %s\n", result, NPT_ResultText(result)); CHECK(result == NPT_SUCCESS); canceller = new CancellerThread(tcp_client, 3.0f, i==1); NPT_OutputStreamReference output; tcp_client->GetOutputStream(output); NPT_Size total_written = 0; unsigned char buffer[4096]; NPT_SetMemory(buffer, 0, sizeof(buffer)); do { NPT_Size bytes_written = 0; result = output->Write(buffer, 4096, &bytes_written); if (NPT_SUCCEEDED(result)) { total_written += bytes_written; } } while (NPT_SUCCEEDED(result)); output = NULL; NPT_Console::OutputF("{01} write returned %d (%s)\n", result, NPT_ResultText(result)); NPT_Console::OutputF("{01} wrote %d bytes total\n", total_written); CHECK(result == NPT_ERROR_CANCELLED); delete tcp_client; canceller->Wait(); delete canceller; server_thread->m_Interrupted = true; server_thread->Wait(); delete server_thread; } for (int i=0; i<2; i++) { NPT_Console::OutputF("\n--- testing accept cancellation, shutdown=%d\n", i); NPT_Console::Output("{03} waiting for connection on port 10000\n"); address.SetIpAddress(NPT_IpAddress(127,0,0,1)); address.SetPort(10000); tcp_server = new NPT_TcpServerSocket(NPT_SOCKET_FLAG_CANCELLABLE); result = tcp_server->Bind(address, true); CHECK(result == NPT_SUCCESS); canceller = new CancellerThread(tcp_server, 3.0f, i==1); NPT_Socket* new_client = NULL; result = tcp_server->WaitForNewClient(new_client); NPT_Console::OutputF("{03} WaitForNewClient returned %d (%s)\n", result, NPT_ResultText(result)); CHECK(result == NPT_ERROR_CANCELLED); canceller->Wait(); delete canceller; delete tcp_server; } NPT_Console::Output("------------\n"); NPT_Console::Output("bye bye\n"); #if defined(WIN32) && defined(_DEBUG) _CrtDumpMemoryLeaks(); #endif return 0; }
DWORD CfixrunMain( __in PCFIXRUN_OPTIONS Options ) { // // Initialize state. // CFIXRUN_STATE State; HRESULT Hr; DWORD ExitCode = CFIXRUN_EXIT_FAILURE; ZeroMemory( &State, sizeof( CFIXRUN_STATE ) ); State.Options = Options; ASSERT( Options->PrintConsole ); // // Resolver. // Hr = CdiagCreateMessageResolver( &State.Resolver ); if ( FAILED( Hr ) ) { goto Cleanup; } State.Resolver->RegisterMessageDll( State.Resolver, L"cdiag.dll", 0, 0 ); if ( FAILED( Hr ) ) { goto Cleanup; } State.Resolver->RegisterMessageDll( State.Resolver, L"cfix.dll", 0, 0 ); if ( FAILED( Hr ) ) { goto Cleanup; } State.Resolver->RegisterMessageDll( State.Resolver, L"cfixkl.dll", 0, 0 ); if ( FAILED( Hr ) ) { goto Cleanup; } if ( Options->PauseAtBeginning ) { Options->PrintConsole( L"Press any key to start testrun...\n" ); ( VOID ) _getch(); } // // Ready to run. // Hr = CfixrunsMainWorker( &State, &ExitCode ); if ( FAILED( Hr ) ) { WCHAR ErrMsg[ 256 ]; if ( FAILED( State.Resolver->ResolveMessage( State.Resolver, Hr, CDIAG_MSGRES_FALLBACK_TO_DEFAULT | CDIAG_MSGRES_RESOLVE_IGNORE_INSERTS, NULL, _countof( ErrMsg ), ErrMsg ) ) ) { VERIFY( SUCCEEDED( StringCchPrintf( ErrMsg, _countof( ErrMsg ), L"Error 0x%08X", Hr ) ) ); } Options->PrintConsole( L"%s\n", ErrMsg ); } Cleanup: if ( State.Resolver ) { State.Resolver->Dereference( State.Resolver ); } if ( Options->PauseAtEnd ) { Options->PrintConsole( L"Finished. Press any key to continue...\n" ); ( VOID ) _getch(); } _CrtDumpMemoryLeaks(); return ExitCode; }
int main(int argc, char* argv[]) { #ifdef _DEBUG _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); //_CrtSetBreakAlloc(1166); #endif char in_url[500]={0}; char out_url[500]={0}; int limit_num=0; int width=0; int height=0; bool limit_is=false; bool graphically_ti=false; bool graphically_si=false; bool isinterval=true; int intervalcnt=5; //接收参数------------------ extern char *optarg; int opt; //-------------------------- if(argc==1){ usage(); return 0; } while ((opt =getopt(argc, argv,"i:o:g:l:n:x:y:h")) != -1) { switch (opt) { case 'h':{ usage(); return 0; } case 'i':{ strcpy(in_url,optarg); break; } case 'o':{ strcpy(out_url,optarg); break; } case 'l':{ limit_num=atoi(optarg); limit_is=true; break; } case 'n':{ intervalcnt=atoi(optarg); break; } case 'g':{ if(strcmp(optarg,"ti")==0){ graphically_ti=true; }else if(strcmp(optarg,"si")==0){ graphically_si=true; } break; } case 'x':{ width=atoi(optarg); break; } case 'y':{ height=atoi(optarg); break; } default: printf("Unknown: %c\n", opt); usage(); return 0; } } if(strcmp(in_url,"")==0){ printf("Input Video's URL is not set. Exit.\n"); return 0; } if(strcmp(out_url,"")==0){ printf("Output .csv file is not set. Default is {Input Name}.csv\n"); char *suffix=strchr(in_url, '.'); *suffix='\0'; strcpy(out_url,in_url); *suffix='.'; sprintf(out_url,"%s.csv",out_url); } AVFormatContext *pFormatCtx; int i, video_stream,audio_stream; AVCodecContext *pCodecCtx,*pCodecCtx_au; AVCodec *pCodec,*pCodec_au; av_register_all(); pFormatCtx = avformat_alloc_context(); if(avformat_open_input(&pFormatCtx,in_url,NULL,NULL)!=0){ printf("Couldn't open file.\n"); return FALSE; } if(strcmp(pFormatCtx->iformat->name,"rawvideo")!=0) { if(av_find_stream_info(pFormatCtx)<0) { printf("Couldn't find stream information.\n"); return FALSE; } } video_stream=-1; audio_stream=-1; for(i=0; i<pFormatCtx->nb_streams; i++) { if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO){ video_stream=i; }if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_AUDIO){ audio_stream=i; } } if(video_stream==-1) { printf("Didn't find a video stream.\n"); return FALSE; } if(video_stream!=-1){ pCodecCtx=pFormatCtx->streams[video_stream]->codec; pCodecCtx->width=width; pCodecCtx->height=height; pCodec=avcodec_find_decoder(pCodecCtx->codec_id); if(pCodec==NULL) { printf("Codec not found.\n"); return FALSE; } if(avcodec_open2(pCodecCtx, pCodec,NULL)<0) { printf("Could not open codec.\n"); return FALSE; } //------------SDL---------------- SDLParam sdlparam={NULL,NULL,{0,0,0,0},graphically_ti,graphically_si,isinterval,NULL,NULL,0,0,0,0}; if(graphically_ti==true||graphically_si==true){ sdlparam.graphically_si=graphically_si; sdlparam.graphically_ti=graphically_ti; sdlparam.show_w=pCodecCtx->width-2*PADDING; sdlparam.show_h=pCodecCtx->height-2*PADDING; sdlparam.pixel_w=pCodecCtx->width-2*PADDING; sdlparam.pixel_h=pCodecCtx->height-2*PADDING; //FIX sdlparam.show_YBuffer=(char *)malloc(sdlparam.pixel_w*sdlparam.pixel_h); sdlparam.show_UVBuffer=(char *)malloc(sdlparam.pixel_w*sdlparam.pixel_h/2); memset(sdlparam.show_UVBuffer,0x80,sdlparam.pixel_w*sdlparam.pixel_h/2); SDL_Thread *video_tid = SDL_CreateThread(show_thread,&sdlparam); } //--------------- float* silist=(float*)malloc(FRAMENUM*sizeof(float)); float* tilist=(float*)malloc((FRAMENUM-1)*sizeof(float)); float* old_silist; float* old_tilist; AVFrame *pFrame,*pFrameYUV; pFrame=avcodec_alloc_frame(); pFrameYUV=avcodec_alloc_frame(); uint8_t *out_buffer; out_buffer=(uint8_t *)av_malloc(avpicture_get_size(PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height)); avpicture_fill((AVPicture *)pFrameYUV, out_buffer, PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height); int ret, got_picture; static struct SwsContext *img_convert_ctx; int y_size = pCodecCtx->width * pCodecCtx->height; AVPacket *packet=(AVPacket *)av_malloc(sizeof(AVPacket)); av_new_packet(packet, y_size); //计算TI的时候使用 int prev_has=0; uint8_t *prev_ydata=(uint8_t *)av_malloc(pCodecCtx->width*pCodecCtx->height); img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height, PIX_FMT_YUV420P, SWS_BILINEAR, NULL, NULL, NULL); //打开文件 FILE *fp=fopen(out_url,"wb+"); fprintf(fp,"TI,SI\n"); //记个数 int framecnt=0; int realloc_time=1; while(av_read_frame(pFormatCtx, packet)>=0&&(framecnt<limit_num||!limit_is)) { if(packet->stream_index==video_stream) { ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, packet); if(ret < 0) { printf("Decode Error.\n"); return -1; } if(got_picture) { sws_scale(img_convert_ctx, (const uint8_t* const*)pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pFrameYUV->data, pFrameYUV->linesize); //有前面的帧,才能计算TI if(prev_has==1){ if(framecnt%intervalcnt==0){ sdlparam.isinterval=false; }else{ sdlparam.isinterval=true; } float ti=0,si=0; int retval=tisi((char *)pFrameYUV->data[0],(char *)prev_ydata,pCodecCtx->width,pCodecCtx->height,sdlparam,ti,si); if(retval==-1) break; if(framecnt>=FRAMENUM*realloc_time) { realloc_time++; old_tilist=tilist; old_silist=silist; if( (tilist = (float*)realloc( tilist, (FRAMENUM*realloc_time-1)*sizeof(float)))==NULL) { free( old_tilist ); // free original block return -1; } if( (silist = (float*)realloc( silist, (FRAMENUM*realloc_time)*sizeof(float)))==NULL) { free( old_silist ); // free original block return -1; } } tilist[framecnt]=ti; silist[framecnt]=si; printf("%f,%f\n",ti,si); fprintf(fp,"%f,%f\n",ti,si); framecnt++; }else{ prev_has=1; } //拷贝亮度数据 memcpy(prev_ydata,pFrameYUV->data[0],pCodecCtx->width*pCodecCtx->height); } } av_free_packet(packet); } sws_freeContext(img_convert_ctx); //计算平均值和最大值 float sum=0; for (int i=0;i<framecnt;i++) sum +=silist[i]; float avg_si=sum/framecnt; qsort(silist,FRAMENUM*realloc_time,sizeof(float),comp); float max_si=silist[FRAMENUM*realloc_time-1]; sum=0; for (int i=0;i<framecnt-1;i++) sum +=tilist[i]; float avg_ti=sum/(framecnt-1); qsort(tilist,(FRAMENUM*realloc_time-1),sizeof(float),comp); float max_ti=tilist[FRAMENUM*realloc_time-2]; fprintf(fp,"TI_AVG,SI_AVG\n"); fprintf(fp,"%f,%f\n",avg_ti,avg_si); fprintf(fp,"TI_MAX,SI_MAX\n"); fprintf(fp,"%f,%f\n",max_ti,max_si); fclose(fp); av_free(out_buffer); av_free(pFrameYUV); avcodec_close(pCodecCtx); if(graphically_ti==true||graphically_si==true){ free(sdlparam.show_YBuffer); free(sdlparam.show_UVBuffer); SDL_Event event; event.type=SDL_QUIT; SDL_PushEvent(&event); } delete silist; delete tilist; } avformat_close_input(&pFormatCtx); #ifdef _DEBUG _CrtDumpMemoryLeaks();//调试运行到该步,输出检测信息 #endif return 0; }
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE /*prevInstance*/, PSTR /*cmdLine*/, int /*showCmd*/) { //notify user if heap is corrupt #if defined _DEBUG HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, NULL, 0); #endif #pragma region junk //*********************** //get command line params //LPCWSTR int numArgs=0; WCHAR **sArgList = CommandLineToArgvW(GetCommandLineW(), &numArgs); //print arguments if( NULL == sArgList ) { wprintf(L"CommandLineToArgvW failed\n"); return 0; } else { wstringstream strstr; for(int i=0; i < numArgs; i++) { strstr << i << sArgList[i] << _T("\n"); } OutputDebugStringW(strstr.str().c_str()); } LocalFree(sArgList);//free memory //end of parameters experiment //**************************** #pragma endregion //create game singleton object Engine* pEngine = new Engine(hInstance); MainGame* pGame = new MainGame(); #if defined DEBUG || _DEBUG cout << "-Engine & Game created\n"; #endif pEngine->SetGame(pGame); pEngine->Initialize(); #if defined DEBUG || _DEBUG cout << "------------------------\n:::Engine Initialized:::\n------------------------\n\n"; #endif int ret = pEngine->Run(); //destroy objects delete pGame; delete pEngine; cout << "\n\n"; cout << " Happy Engine wishes you a happy day! \n"; cout << "--------------\\Press any key/-------------\n"; cin.get(); #if defined _DEBUG _CrtDumpMemoryLeaks(); #endif return ret; }
int _tmain(int argc, _TCHAR* argv[]) { int i; char buf[MAX_PATH]; #ifdef _DEBUG _crtBreakAlloc = -1; // break on Nth memory allocation #endif #if defined(TRACE) System::Diagnostics::Trace::Listeners->Add( gcnew System::Diagnostics::TextWriterTraceListener( System::Console::Out ) ); System::Diagnostics::Trace::AutoFlush = true; #endif WSADATA wsaData; int iResult; // Initialize Winsock iResult = WSAStartup(MAKEWORD(2,2), &wsaData); if (iResult != 0) { printf_s( "WSAStartup failed: %d\n", iResult ); goto returnFail; } else { printf_s( "WSAStartup succeeded\n" ); } // -- select agent and playback file -- char *logPath = "..\\data\\"; WCHAR logDirName[TOP_LOG_DIRS][256]; int logDirCount; WCHAR logDirPath[MAX_PATH]; WCHAR logName[10][256]; int logCount; FILE *logF; FILE *settingsF; char AT_name[256]; char UUIDString[256]; int breakOnAlloc = -1; int optionNum; // get crt break val or use last settings printf( "0) Use last settings\n1) _crtBreakAlloc = -1 (disabled)\n2) Enter _crtBreakAlloc\n\nNOTE: To properly use _crtBreakAlloc you should:\n a) ensure the desired log file is selected (e.g. run once with option 2)\n b) run once with option 0 to determine the desired break value (because \n selecting things in this menu unfortunately changes the allocation\n count)\n c) use option 2 to set the _crtDebugAlloc value\n d) run with option 0 again so that the correct allocation count is used\n from step b)\n\n" ); do { printf( "Select an option: " ); *buf = getchar(); while( getchar() != '\n' ); // clear until return } while ( buf[0] - '0' < 0 || buf[0] - '0' >= 3 ); optionNum = buf[0] - '0'; if ( optionNum == 0 ) { // use last settings if ( fopen_s( &settingsF, "settings.txt", "r" ) ) { printf( "Couldn't open settings file\n" ); goto returnFail; } fscanf_s( settingsF, "%d\n", &breakOnAlloc ); #ifdef _DEBUG _crtBreakAlloc = breakOnAlloc; #endif fgetws( logDirPath, MAX_PATH, settingsF ); logDirPath[wcslen(logDirPath)-1] = '\0'; // strip \n fgets( AT_name, 256, settingsF ); AT_name[strlen(AT_name)-1] = '\0'; // strip \n fgets( UUIDString, 256, settingsF ); // no \n here fclose( settingsF ); } else { if ( optionNum == 2 ) { // get _crtBreakAlloc printf( "Enter value for _crtBreakAlloc: " ); while( 1 != scanf_s( "%d", &breakOnAlloc ) ) { while( getchar() != '\n' ); // clear until return } while( getchar() != '\n' ); // clear until return } #ifdef _DEBUG _crtBreakAlloc = breakOnAlloc; #endif // enumerate log directories enumerateLogDirectories( logPath, logDirName, &logDirCount ); printf( "0) Use last settings\n" ); for ( i=0; i<logDirCount; i++ ) { printf( "%d) %ls\n", i+1, logDirName[i] ); } do { printf( "Select a directory: " ); *buf = getchar(); while( getchar() != '\n' ); // clear until return } while ( buf[0] - '0' < 0 || buf[0] - '0' >= logDirCount+1 ); i = buf[0] - '0'; // use i to store selection if ( i == 0 ) { // use last settings if ( fopen_s( &settingsF, "settings.txt", "r" ) ) { printf( "Couldn't open settings file\n" ); goto returnFail; } fscanf_s( settingsF, "%d\n", &i ); // throw away fgetws( logDirPath, MAX_PATH, settingsF ); logDirPath[wcslen(logDirPath)-1] = '\0'; // strip \n fgets( AT_name, 256, settingsF ); AT_name[strlen(AT_name)-1] = '\0'; // strip \n fgets( UUIDString, 256, settingsF ); // no \n here fclose( settingsF ); } else { i--; // set i to the name index swprintf_s( logDirPath, MAX_PATH, L"%hs%s\\", logPath, logDirName[i] ); // enumerate logs int page = 0; int moreLogs; do { enumerateLogs( logDirPath, page, logName, &logCount, &moreLogs ); system("cls"); printf( "Page %d\n", page ); for ( i=0; i<logCount; i++ ) { printf( "%d) %.64ls\n", i, logName[i] ); } if ( page != 0 ) printf( "p) previous page\n" ); if ( moreLogs ) printf( "n) next page\n" ); do { printf( "Select a log: " ); *buf = getchar(); while( getchar() != '\n' ); // clear until return } while ( (buf[0] - '0' < 0 || buf[0] - '0' >= logCount) && (buf[0] != 'p' || page == 0) && (buf[0] != 'n' || !moreLogs) ); if ( buf[0] == 'p' ) { page--; } else if ( buf[0] == 'n' ) { page++; } else { break; } } while (1); i = buf[0] - '0'; // this is the log we want // open the log to parse the agent id sprintf_s( buf, MAX_PATH, "%ls%ls", logDirPath, logName[i] ); if ( fopen_s( &logF, buf, "r" ) ) { printf( "Failed to open log file! %s\n", buf ); goto returnFail; } // clear first line fgets( buf, MAX_PATH, logF ); // get agent type if ( 5 != fscanf_s( logF, "[%d:%d:%d.%d] %s\n", &i, &i, &i, &i, AT_name, 256 ) ) { printf( "Expected agent name\n" ); goto returnFail; } // finish line fgets( buf, MAX_PATH, logF ); // clear agent UUID line fgets( buf, MAX_PATH, logF ); // get playbackfile UUID if ( 5 != fscanf_s( logF, "[%d:%d:%d.%d] AgentPlayback UUID %s\n", &i, &i, &i, &i, UUIDString, 256 ) ) { printf( "Expected agentplayback UUID\n" ); goto returnFail; } fclose( logF ); } // save settings for next time if ( fopen_s( &settingsF, "settings.txt", "w" ) ) { printf( "Couldn't save settings file\n" ); goto returnFail; } fprintf_s( settingsF, "%d\n%ls\n%s\n%s", breakOnAlloc, logDirPath, AT_name, UUIDString ); fclose( settingsF ); } if ( optionNum == 2 ) { printf( "\nSettings saved, restart and run with option 0\n\n" ); goto returnFail; } // -- Startup info -- char *libraryPath = "library\\"; // library path sAddressPort ap; sprintf_s( ap.address, sizeof(ap.address), "127.0.0.1" ); sprintf_s( ap.port, sizeof(ap.port), "50000" ); UUID ticket; UuidCreateNil( &ticket ); int logLevel = 9; char logDirectory[MAX_PATH]; WCHAR baseDirectory[512]; GetCurrentDirectory( 512, baseDirectory ); sprintf_s( logDirectory, MAX_PATH, "%ls", baseDirectory ); // strip last directory to reach base path i = (int)wcslen(baseDirectory); while ( baseDirectory[i] != '\\' ) i--; baseDirectory[i] = '\0'; SetCurrentDirectory( baseDirectory ); char playbackFile[256]; sprintf_s( playbackFile, 256, "%lsx %s.apb", logDirPath+1, UUIDString ); // strip off the leading . of ..\\ if ( strcmp( AT_name, "AgentHost" ) != 0 ) { // regular agent WCHAR wbuf[512]; char AT_object[256]; // agent template object sprintf_s( AT_object, 256, "%s.dll", AT_name ); // -- Load agent DLL -- HINSTANCE library = NULL; // set the current directory to the library path in case they need their own dlls SetCurrentDirectory( baseDirectory ); wsprintf( wbuf, _T(".\\%hs%hs\\"), libraryPath, AT_name ); SetCurrentDirectory( wbuf ); // load the library wsprintf( wbuf, _T("%hs"), AT_object ); library = LoadLibrary( wbuf ); SetCurrentDirectory( baseDirectory ); // set the directory back if ( library == NULL ) { printf_s( "LoadLibrary failed for %ls\n", wbuf ); goto returnFail; } // -- Spawn Agent -- SpawnFuncPtr sfp; sfp = (SpawnFuncPtr)GetProcAddress( library, "Playback" ); if ( sfp( &ap, &ticket, logLevel, logDirectory, PLAYBACKMODE_PLAYBACK, playbackFile ) ) { printf_s( "Failed to spawn agent\n" ); goto returnFail; } // -- Clean up -- FreeLibrary( library ); } else { // host int steps = 0; AgentHost *pHOST; SetCurrentDirectory( baseDirectory ); pHOST = new AgentHost( ".\\library\\", LOG_LEVEL_ALL, logDirectory, PLAYBACKMODE_PLAYBACK, playbackFile ); pHOST->configure(); pHOST->start( NULL, NULL ); while ( !pHOST->step() ) steps++; pHOST->stop(); delete pHOST; } // Clean up Winsock WSACleanup(); #if defined(TRACE) System::Diagnostics::Trace::WriteLine( "--- Exit _tmain() for startup thread: AutonomicPlayback ---" ); _CrtDumpMemoryLeaks(); #endif printf( "Finished. Press ENTER to exit..." ); getchar(); return 0; returnFail: printf( "Finished. Press ENTER to exit..." ); getchar(); return 1; }
int git_win32__crtdbg_stacktrace__dump( git_win32__crtdbg_stacktrace_options opt, const char *label) { _CRT_REPORT_HOOK old; unsigned int k; int r = 0; #define IS_BIT_SET(o,b) (((o) & (b)) != 0) bool b_set_mark = IS_BIT_SET(opt, GIT_WIN32__CRTDBG_STACKTRACE__SET_MARK); bool b_leaks_since_mark = IS_BIT_SET(opt, GIT_WIN32__CRTDBG_STACKTRACE__LEAKS_SINCE_MARK); bool b_leaks_total = IS_BIT_SET(opt, GIT_WIN32__CRTDBG_STACKTRACE__LEAKS_TOTAL); bool b_quiet = IS_BIT_SET(opt, GIT_WIN32__CRTDBG_STACKTRACE__QUIET); if (b_leaks_since_mark && b_leaks_total) { giterr_set(GITERR_INVALID, "Cannot combine LEAKS_SINCE_MARK and LEAKS_TOTAL."); return GIT_ERROR; } if (!b_set_mark && !b_leaks_since_mark && !b_leaks_total) { giterr_set(GITERR_INVALID, "Nothing to do."); return GIT_ERROR; } EnterCriticalSection(&g_crtdbg_stacktrace_cs); if (b_leaks_since_mark || b_leaks_total) { /* All variables with "transient" in the name are per-dump counters * and reset before each dump. This lets us handle checkpoints. */ g_transient_count_total_leaks = 0; g_transient_count_dedup_leaks = 0; for (k = 0; k < g_cs_ins; k++) { g_cs_rows[k].transient_count_leaks = 0; } } g_transient_leaks_since_mark = b_leaks_since_mark; old = _CrtSetReportHook(report_hook); _CrtDumpMemoryLeaks(); _CrtSetReportHook(old); if (b_leaks_since_mark || b_leaks_total) { r = g_transient_count_dedup_leaks; if (!b_quiet) dump_summary(label); } if (b_set_mark) { for (k = 0; k < g_cs_ins; k++) { g_cs_rows[k].count_allocs_at_last_checkpoint = g_cs_rows[k].count_allocs; } g_checkpoint_id++; } LeaveCriticalSection(&g_crtdbg_stacktrace_cs); return r; }
extern "C" __declspec(dllexport) int WINAPI dllLauncherEntryPoint(HINSTANCE, HINSTANCE, LPTSTR, int nCmdShow) { #ifdef _CRTDBG_MAP_ALLOC _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); #endif // TODO: Place code here. MSG msg = {0}; HACCEL hAccelTable; INITCOMMONCONTROLSEX InitCtrlEx; InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX); InitCtrlEx.dwICC = 0x00004000; //ICC_STANDARD_CLASSES; InitCommonControlsEx(&InitCtrlEx); _bstr_t requestedURL; int argc = 0; WCHAR** argv = CommandLineToArgvW(GetCommandLineW(), &argc); for (int i = 1; i < argc; ++i) { if (!wcsicmp(argv[i], L"--transparent")) s_usesLayeredWebView = true; else if (!wcsicmp(argv[i], L"--desktop")) s_fullDesktop = true; else if (!requestedURL) requestedURL = argv[i]; } // Initialize global strings LoadString(hInst, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInst, IDC_WINLAUNCHER, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInst); if (shouldUseFullDesktop()) computeFullDesktopFrame(); // Init COM OleInitialize(NULL); if (usesLayeredWebView()) { hURLBarWnd = CreateWindow(L"EDIT", L"Type URL Here", WS_OVERLAPPEDWINDOW | WS_VISIBLE | WS_BORDER | ES_LEFT | ES_AUTOVSCROLL, s_windowPosition.x, s_windowPosition.y + s_windowSize.cy, s_windowSize.cx, URLBAR_HEIGHT, 0, 0, hInst, 0); } else { hMainWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, 0, 0, hInst, 0); if (!hMainWnd) return FALSE; hBackButtonWnd = CreateWindow(L"BUTTON", L"<", WS_CHILD | WS_VISIBLE | BS_TEXT, 0, 0, 0, 0, hMainWnd, 0, hInst, 0); hForwardButtonWnd = CreateWindow(L"BUTTON", L">", WS_CHILD | WS_VISIBLE | BS_TEXT, CONTROLBUTTON_WIDTH, 0, 0, 0, hMainWnd, 0, hInst, 0); hURLBarWnd = CreateWindow(L"EDIT", 0, WS_CHILD | WS_VISIBLE | WS_BORDER | ES_LEFT | ES_AUTOVSCROLL, CONTROLBUTTON_WIDTH * 2, 0, 0, 0, hMainWnd, 0, hInst, 0); ShowWindow(hMainWnd, nCmdShow); UpdateWindow(hMainWnd); } DefEditProc = reinterpret_cast<WNDPROC>(GetWindowLongPtr(hURLBarWnd, GWLP_WNDPROC)); DefButtonProc = reinterpret_cast<WNDPROC>(GetWindowLongPtr(hBackButtonWnd, GWLP_WNDPROC)); SetWindowLongPtr(hURLBarWnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(EditProc)); SetWindowLongPtr(hBackButtonWnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(BackButtonProc)); SetWindowLongPtr(hForwardButtonWnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(ForwardButtonProc)); SetFocus(hURLBarWnd); RECT clientRect = { s_windowPosition.x, s_windowPosition.y, s_windowPosition.x + s_windowSize.cx, s_windowPosition.y + s_windowSize.cy }; IWebPreferencesPtr tmpPreferences; if (FAILED(WebKitCreateInstance(CLSID_WebPreferences, 0, IID_IWebPreferences, reinterpret_cast<void**>(&tmpPreferences.GetInterfacePtr())))) goto exit; if (FAILED(tmpPreferences->standardPreferences(&gStandardPreferences.GetInterfacePtr()))) goto exit; if (!setToDefaultPreferences()) goto exit; HRESULT hr = WebKitCreateInstance(CLSID_WebView, 0, IID_IWebView, reinterpret_cast<void**>(&gWebView.GetInterfacePtr())); if (FAILED(hr)) goto exit; hr = gWebView->QueryInterface(IID_IWebViewPrivate, reinterpret_cast<void**>(&gWebViewPrivate.GetInterfacePtr())); if (FAILED(hr)) goto exit; hr = WebKitCreateInstance(CLSID_WebHistory, 0, __uuidof(gWebHistory), reinterpret_cast<void**>(&gWebHistory.GetInterfacePtr())); if (FAILED(hr)) goto exit; gWebHost = new WinLauncherWebHost(); gWebHost->AddRef(); hr = gWebView->setFrameLoadDelegate(gWebHost); if (FAILED(hr)) goto exit; gPrintDelegate = new PrintWebUIDelegate; gPrintDelegate->AddRef(); hr = gWebView->setUIDelegate(gPrintDelegate); if (FAILED (hr)) goto exit; gAccessibilityDelegate = new AccessibilityDelegate; gAccessibilityDelegate->AddRef(); hr = gWebView->setAccessibilityDelegate(gAccessibilityDelegate); if (FAILED (hr)) goto exit; hr = gWebView->setHostWindow(reinterpret_cast<OLE_HANDLE>(hMainWnd)); if (FAILED(hr)) goto exit; hr = gWebView->initWithFrame(clientRect, 0, 0); if (FAILED(hr)) goto exit; if (!requestedURL) { IWebFramePtr frame; hr = gWebView->mainFrame(&frame.GetInterfacePtr()); if (FAILED(hr)) goto exit; _bstr_t defaultHTML(L"<p style=\"background-color: #00FF00\">Testing</p><img id=\"webkit logo\" src=\"http://webkit.org/images/icon-gold.png\" alt=\"Face\"><div style=\"border: solid blue; background: white;\" contenteditable=\"true\">div with blue border</div><ul><li>foo<li>bar<li>baz</ul>"); frame->loadHTMLString(defaultHTML.GetBSTR(), 0); } hr = gWebViewPrivate->setTransparent(usesLayeredWebView()); if (FAILED(hr)) goto exit; hr = gWebViewPrivate->setUsesLayeredWindow(usesLayeredWebView()); if (FAILED(hr)) goto exit; hr = gWebViewPrivate->viewWindow(reinterpret_cast<OLE_HANDLE*>(&gViewWindow)); if (FAILED(hr) || !gViewWindow) goto exit; if (usesLayeredWebView()) subclassForLayeredWindow(); resizeSubViews(); ShowWindow(gViewWindow, nCmdShow); UpdateWindow(gViewWindow); hAccelTable = LoadAccelerators(hInst, MAKEINTRESOURCE(IDC_WINLAUNCHER)); if (requestedURL.length()) loadURL(requestedURL.GetBSTR()); // Main message loop: #if USE(CF) _CFRunLoopSetWindowsMessageQueueMask(CFRunLoopGetMain(), QS_ALLINPUT | QS_ALLPOSTMESSAGE, kCFRunLoopDefaultMode); CFRunLoopRun(); #else while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } #endif exit: gPrintDelegate->Release(); shutDownWebKit(); #ifdef _CRTDBG_MAP_ALLOC _CrtDumpMemoryLeaks(); #endif // Shut down COM. OleUninitialize(); return static_cast<int>(msg.wParam); }