void NDInstanceBase::EndStaticsMem() { _CrtMemState s2, s3; _CrtMemCheckpoint( &s2 ); if ( _CrtMemDifference( &s3, &m_s1, &s2 ) ) { _CrtSetReportHook( NDReportHook ) ; _CrtMemDumpStatistics( &s3 ); _CrtSetReportHook( NULL ) ; } }
void setFilterDebugHook(void) { //change the report function to only report memory leaks from program code #ifdef _MSC_VER prevHook = _CrtSetReportHook(reportingHook); #endif }
void EnableCRTReportHook(BOOL fEnable) { #ifdef _DEBUG if(fEnable) { if(!g_fpPrevCRTReportHook) g_fpPrevCRTReportHook = _CrtSetReportHook(&CRTReportHook); } else { if(g_fpPrevCRTReportHook) _CrtSetReportHook(g_fpPrevCRTReportHook); g_fpPrevCRTReportHook = NULL; } #endif //_DEBUG }
MONGO_INITIALIZER(Behaviors_Win32)(InitializerContext*) { // do not display dialog on abort() _set_abort_behavior(0, _CALL_REPORTFAULT | _WRITE_ABORT_MSG); // hook the C runtime's error display _CrtSetReportHook(crtDebugCallback); if (_setmaxstdio(2048) == -1) { warning() << "Failed to increase max open files limit from default of 512 to 2048"; } // Let's try to set minimum Windows Kernel quantum length to smallest viable timer resolution in // order to allow sleepmillis() to support waiting periods below Windows default quantum length // (which can vary per Windows version) // See https://msdn.microsoft.com/en-us/library/windows/desktop/dd743626(v=vs.85).aspx TIMECAPS tc; int targetResolution = 1; int timerResolution; if (timeGetDevCaps(&tc, sizeof(TIMECAPS)) != TIMERR_NOERROR) { warning() << "Failed to read timer resolution range."; if (timeBeginPeriod(1) != TIMERR_NOERROR) { warning() << "Failed to set minimum timer resolution to 1 millisecond."; } } else { timerResolution = std::min(std::max(int(tc.wPeriodMin), targetResolution), int(tc.wPeriodMax)); invariant(timeBeginPeriod(timerResolution) == TIMERR_NOERROR); } return Status::OK(); }
void CDebugMgr::EnableAssertHandler() { if ( m_prevAssertHandler ) return; #ifdef _DEBUG m_prevAssertHandler = _CrtSetReportHook(CDebugMgr::AssertHandler); #endif }
_MRTIMP _CRT_REPORT_HOOK __cdecl _CrtSetReportHook( int pfnNewHook ) { _VALIDATE_RETURN(pfnNewHook == 0, EINVAL, NULL); return _CrtSetReportHook((_CRT_REPORT_HOOK)NULL); }
void* CDbgMemAlloc::CrtSetReportHook( void* pfnNewHook ) { #ifdef WIN32 return (void*)_CrtSetReportHook( (_CRT_REPORT_HOOK)pfnNewHook ); #else printf("XXX: CDbgMemAlloc::CrtSetReportHook() not portd to FreeBSD in file %s\n", __FILE__); return NULL; #endif }
static void __clrcall _CrtReportHook_managed_cleanup(void) { _CRT_REPORT_HOOK pfnReportHook=_CrtGetReportHook(); _CRT_REPORT_HOOK_M enull = (_CRT_REPORT_HOOK_M) EncodePointer(NULL)(); if(pfnReportHook==_CrtReportHook_managed_thunk && __pfnReportHookManaged!=enull) { _CrtSetReportHook((_CRT_REPORT_HOOK)NULL); } __pfnReportHookManaged=enull; }
void CDebugMgr::DisableAssertHandler() { if ( !m_prevAssertHandler ) return; #ifdef _DEBUG _CrtSetReportHook(m_prevAssertHandler); m_prevAssertHandler = NULL; #endif }
_AFX_DEBUG_STATE::~_AFX_DEBUG_STATE() { #ifndef _AFX_NO_DEBUG_CRT _CrtDumpMemoryLeaks(); int nOldState = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); _CrtSetDbgFlag(nOldState & ~_CRTDBG_LEAK_CHECK_DF); _CrtSetReportHook(pfnOldCrtReportHook); _CrtSetDumpClient(pfnOldCrtDumpClient); #endif // _AFX_NO_DEBUG_CRT }
ArgParser::ArgParser(Environment* env, int argc, char** argv) : env_(env), argindex_(0), argc_(argc), argv_(argv) { env->program_path(next().value()); #ifdef WINDOWS _CrtSetReportHook(report_hook); #endif }
/*** *_CRT_REPORT_HOOK_M _CrtSetReportHook() - set client report hook * *Purpose: * set client report hook * *Entry: * _CRT_REPORT_HOOK_M pfnNewHook - new report hook * *Exit: * return previous hook * *Exceptions: * *******************************************************************************/ _MRTIMP _CRT_REPORT_HOOK_M __cdecl _CrtSetReportHook( _CRT_REPORT_HOOK_M pfnNewHook ) { if(_atexit_m_appdomain(_CrtReportHook_managed_cleanup)!=0) { return NULL; } _CRT_REPORT_HOOK_M pfnOldHook = (_CRT_REPORT_HOOK_M) DecodePointer(__pfnReportHookManaged); if (pfnNewHook) { __pfnReportHookManaged = (_CRT_REPORT_HOOK_M) EncodePointer(pfnNewHook); _CrtSetReportHook((_CRT_REPORT_HOOK)_CrtReportHook_managed_thunk); } else { _CRT_REPORT_HOOK_M enull = (_CRT_REPORT_HOOK_M) EncodePointer(NULL)(); __pfnReportHookManaged = enull; _CrtSetReportHook((_CRT_REPORT_HOOK)NULL); } return pfnOldHook; }
_AFX_DEBUG_STATE::_AFX_DEBUG_STATE() { afxTraceEnabled = ::GetPrivateProfileInt(szDiagSection, szTraceEnabled, TRUE, szIniFile); afxTraceFlags = ::GetPrivateProfileInt(szDiagSection, szTraceFlags, 0, szIniFile); #ifndef _AFX_NO_DEBUG_CRT ASSERT(pfnOldCrtDumpClient == NULL); pfnOldCrtDumpClient = _CrtSetDumpClient(_AfxCrtDumpClient); ASSERT(pfnOldCrtReportHook == NULL); pfnOldCrtReportHook = _CrtSetReportHook(_AfxCrtReportHook); _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_WNDW); #endif // _AFX_NO_DEBUG_CRT }
int reportingHook(int reportType, char* userMessage, int* retVal) { // This function is called several times for each memory leak. // Each time a part of the error message is supplied. // This holds number of subsequent detail messages after // a leak was reported const int numFollowupDebugMsgParts = 2; static bool ignoreMessage = false; static int debugMsgPartsCount = numFollowupDebugMsgParts; static bool firstMessage = true; if( strncmp(userMessage,"Detected memory leaks!\n", 10)==0) { ignoreMessage = true; return TRUE; } else if(strncmp(userMessage,"Dumping objects ->\n", 10)==0) { return TRUE; } else if (ignoreMessage) { // check if the memory leak reporting ends if (strncmp(userMessage,"Object dump complete.\n", 10) == 0) { _CrtSetReportHook(prevHook); ignoreMessage = false; } if(debugMsgPartsCount++ < numFollowupDebugMsgParts) // give it back to _CrtDbgReport() to be printed to the console return FALSE; // something from our own code? if(strstr(userMessage, ".cpp") || strstr(userMessage, ".h") || strstr(userMessage, ".c")) { if(firstMessage) { OutputDebugStringA("Detected memory leaks!\nDumping objects ->\n"); firstMessage = false; } debugMsgPartsCount = 0; // give it back to _CrtDbgReport() to be printed to the console return FALSE; } else return TRUE; } else // give it back to _CrtDbgReport() to be printed to the console return FALSE; };
static void uv_init(void) { /* Tell Windows that we will handle critical errors. */ SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); /* Tell the CRT to not exit the application when an invalid parameter is * passed. The main issue is that invalid FDs will trigger this behavior. */ #if !defined(__MINGW32__) || __MSVCRT_VERSION__ >= 0x800 _set_invalid_parameter_handler(uv__crt_invalid_parameter_handler); #endif /* We also need to setup our debug report handler because some CRT * functions (eg _get_osfhandle) raise an assert when called with invalid * FDs even though they return the proper error code in the release build. */ #if defined(_DEBUG) && (defined(_MSC_VER) || defined(__MINGW64_VERSION_MAJOR)) _CrtSetReportHook(uv__crt_dbg_report_handler); #endif /* Initialize tracking of all uv loops */ uv__loops_init(); /* Fetch winapi function pointers. This must be done first because other * initialization code might need these function pointers to be loaded. */ uv_winapi_init(); /* Initialize winsock */ uv_winsock_init(); /* Initialize FS */ uv_fs_init(); /* Initialize signal stuff */ uv_signals_init(); /* Initialize console */ uv_console_init(); /* Initialize utilities */ uv__util_init(); /* Initialize system wakeup detection */ uv__init_detect_system_wakeup(); }
int utxShutdownMemory() { #if defined(CRTDBG_MAP_ALLOC) _CrtSetReportHook(crtMemoryReporter); _CrtDumpMemoryLeaks(); #endif if (my_allocCount != my_freeCount) { char buffer[512]; sprintf(buffer, "Memory allocation mismatch: %d allocs, %d frees\n", my_allocCount, my_freeCount); utLog(buffer); return false; } return true; }
void Runner::preventDialogOnCrash() { #if defined(_MSC_VER) && defined(_DEBUG) // Install a hook to prevent MSVCRT error and assertion from // popping a dialog // This function a NO-OP in release configuration // (which cause warning since msvcrtSilentReportHook is not referenced) _CrtSetReportHook(&msvcrtSilentReportHook); #endif // if defined(_MSC_VER) // @todo investiguate this handler (for buffer overflow) // _set_security_error_handler #if defined(_WIN32) // Prevents the system from popping a dialog for debugging if the // application fails due to invalid memory access. SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); #endif // if defined(_WIN32) }
int reportingHook(int reportType, char* userMessage, int* retVal) { // This function is called several times for each memory leak. // Each time a part of the error message is supplied. // This holds number of subsequent detail messages after // a leak was reported const int numFollowupDebugMsgParts = 2; static bool ignoreMessage = false; static int debugMsgPartsCount = 0; // check if the memory leak reporting starts if ((strncmp(userMessage,"Detected memory leaks!\n", 10) == 0) || ignoreMessage) { // check if the memory leak reporting ends if (strncmp(userMessage,"Object dump complete.\n", 10) == 0) { #ifdef _MSC_VER _CrtSetReportHook(prevHook); #endif ignoreMessage = false; } else ignoreMessage = true; // something from our own code? if(strstr(userMessage, ".cpp") == NULL) { if(debugMsgPartsCount++ < numFollowupDebugMsgParts) // give it back to _CrtDbgReport() to be printed to the console return FALSE; else return TRUE; // ignore it } else { debugMsgPartsCount = 0; // give it back to _CrtDbgReport() to be printed to the console return FALSE; } } else // give it back to _CrtDbgReport() to be printed to the console return FALSE; };
// initialize the diagnostics environment. // int diagnostics_init( int _flags, const char* stdout_prefix, const char* stderr_prefix ) { // Check to see if we have already been called // if (diagnostics_initialized) { return ERR_INVALID_PARAM; } diagnostics_initialized = true; // Setup initial values // flags = _flags; strcpy(stdout_log, ""); strcpy(stdout_archive, ""); strcpy(stderr_log, ""); strcpy(stderr_archive, ""); strcpy(boinc_dir, ""); strcpy(boinc_install_dir, ""); boinc_proxy_enabled = 0; strcpy(boinc_proxy, ""); strcpy(symstore, ""); // Check for invalid parameter combinations // if ((flags & BOINC_DIAG_REDIRECTSTDERR) && (flags & BOINC_DIAG_REDIRECTSTDERROVERWRITE)) { return ERR_INVALID_PARAM; } if ((flags & BOINC_DIAG_REDIRECTSTDOUT) && (flags & BOINC_DIAG_REDIRECTSTDOUTOVERWRITE)) { return ERR_INVALID_PARAM; } // Determine where the log files are to be stored // if (flags & BOINC_DIAG_PERUSERLOGFILES) { char user_dir[MAXPATHLEN]; #if defined(_WIN32) snprintf(user_dir, sizeof(user_dir), "%s", getenv("APPDATA")); strncat(user_dir, "/BOINC", sizeof(user_dir) - strlen(user_dir)-1); #elif defined(__APPLE__) snprintf(user_dir, sizeof(user_dir), "%s", getenv("HOME")); strncat(user_dir, "/Library/Application Support/BOINC", sizeof(user_dir) - strlen(user_dir)-1); #else snprintf(user_dir, sizeof(user_dir), "%s", getenv("HOME")); strncat(user_dir, "/.BOINC", sizeof(user_dir) - strlen(user_dir)-1); #endif // Check to see if the directory exists if (!is_dir(user_dir)) { boinc_mkdir(user_dir); } snprintf(stdout_log, sizeof(stdout_log), "%s/%s.txt", user_dir, stdout_prefix); snprintf(stdout_archive, sizeof(stdout_archive), "%s/%s.old", user_dir, stdout_prefix); snprintf(stderr_log, sizeof(stderr_log), "%s/%s.txt", user_dir, stderr_prefix); snprintf(stderr_archive, sizeof(stderr_archive), "%s/%s.old", user_dir, stderr_prefix); } else { snprintf(stdout_log, sizeof(stdout_log), "%s.txt", stdout_prefix); snprintf(stdout_archive, sizeof(stdout_archive), "%s.old", stdout_prefix); snprintf(stderr_log, sizeof(stderr_log), "%s.txt", stderr_prefix); snprintf(stderr_archive, sizeof(stderr_archive), "%s.old", stderr_prefix); } // Archive any old stderr.txt and stdout.txt files, if requested // if (flags & BOINC_DIAG_ARCHIVESTDERR) { boinc_copy(stderr_log, stderr_archive); } if (flags & BOINC_DIAG_ARCHIVESTDOUT) { boinc_copy(stdout_log, stdout_archive); } // Redirect stderr and/or stdout, if requested // if (flags & BOINC_DIAG_REDIRECTSTDERR) { file_size(stderr_log, stderr_file_size); stderr_file = freopen(stderr_log, "a", stderr); if (!stderr_file) { return ERR_FOPEN; } setbuf(stderr_file, 0); } if (flags & BOINC_DIAG_REDIRECTSTDERROVERWRITE) { stderr_file = freopen(stderr_log, "w", stderr); if (!stderr_file) { return ERR_FOPEN; } setbuf(stderr_file, 0); } if (flags & BOINC_DIAG_REDIRECTSTDOUT) { file_size(stdout_log, stdout_file_size); stdout_file = freopen(stdout_log, "a", stdout); if (!stdout_file) { return ERR_FOPEN; } } if (flags & BOINC_DIAG_REDIRECTSTDOUTOVERWRITE) { stdout_file = freopen(stdout_log, "w", stdout); if (!stdout_file) { return ERR_FOPEN; } } #if defined(_WIN32) #if defined(_DEBUG) _CrtSetReportHook(boinc_message_reporting); if (flags & BOINC_DIAG_MEMORYLEAKCHECKENABLED) { SET_CRT_DEBUG_FIELD(_CRTDBG_LEAK_CHECK_DF); } if (flags & BOINC_DIAG_HEAPCHECKENABLED) { if (flags & BOINC_DIAG_HEAPCHECKEVERYALLOC) { SET_CRT_DEBUG_FIELD(_CRTDBG_CHECK_ALWAYS_DF); } else { SET_CRT_DEBUG_FIELD(_CRTDBG_CHECK_EVERY_1024_DF); } } if (flags & BOINC_DIAG_BOINCAPPLICATION) { if (flags & BOINC_DIAG_MEMORYLEAKCHECKENABLED) { _CrtMemCheckpoint(&start_snapshot); } } #endif // defined(_DEBUG) // Initialize the thread list structure // The data for this structure should be set by // boinc_init or boinc_init_graphics. diagnostics_init_thread_list(); diagnostics_init_unhandled_exception_monitor(); diagnostics_init_message_monitor(); #endif // defined(_WIN32) #ifdef ANDROID #define resolve_func(l,x) \ x=(x##_t)dlsym(l,#x); \ if (!x) {\ fprintf(stderr,"Unable to resolve function %s\n",#x); \ unwind_backtrace_signal_arch=NULL; \ } if ((libhandle=dlopen("libcorkscrew.so",RTLD_NOW|RTLD_GLOBAL))) { resolve_func(libhandle,unwind_backtrace_signal_arch); resolve_func(libhandle,acquire_my_map_info_list); resolve_func(libhandle,release_my_map_info_list); resolve_func(libhandle,get_backtrace_symbols); resolve_func(libhandle,free_backtrace_symbols); resolve_func(libhandle,format_backtrace_line); resolve_func(libhandle,load_symbol_table); resolve_func(libhandle,free_symbol_table); resolve_func(libhandle,find_symbol); } else { fprintf(stderr,"stackdumps unavailable\n"); } #endif // ANDROID // Install unhandled exception filters and signal traps. if (BOINC_SUCCESS != boinc_install_signal_handlers()) { return ERR_SIGNAL_OP; } // Store various pieces of inforation for future use. if (flags & BOINC_DIAG_BOINCAPPLICATION) { char buf[256]; char proxy_address[256]; int proxy_port; MIOFILE mf; FILE* p; #ifdef _WIN32 LONG lReturnValue; HKEY hkSetupHive; DWORD dwSize = 0; #endif strcpy(buf, ""); strcpy(proxy_address, ""); proxy_port = 0; #ifndef _USING_FCGI_ p = fopen(INIT_DATA_FILE, "r"); #else p = FCGI::fopen(INIT_DATA_FILE, "r"); #endif if (p) { mf.init_file(p); while(mf.fgets(buf, sizeof(buf))) { if (match_tag(buf, "</app_init_data>")) break; else if (parse_str(buf, "<boinc_dir>", boinc_dir, sizeof(boinc_dir))) continue; else if (parse_str(buf, "<symstore>", symstore, sizeof(symstore))) ; else if (match_tag(buf, "<use_http_proxy/>")) { boinc_proxy_enabled = true; continue; } else if (parse_str(buf, "<http_server_name>", proxy_address, sizeof(proxy_address))) continue; else if (parse_int(buf, "<http_server_port>", proxy_port)) continue; } fclose(p); } if (boinc_proxy_enabled) { int buffer_used = snprintf(boinc_proxy, sizeof(boinc_proxy), "%s:%d", proxy_address, proxy_port); if ((sizeof(boinc_proxy) == buffer_used) || (-1 == buffer_used)) { boinc_proxy[sizeof(boinc_proxy)-1] = '\0'; } } #ifdef _WIN32 // Lookup the location of where BOINC was installed to and store // that for future use. lReturnValue = RegOpenKeyEx( HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Space Sciences Laboratory, U.C. Berkeley\\BOINC Setup"), 0, KEY_READ, &hkSetupHive ); if (lReturnValue == ERROR_SUCCESS) { // How large does our buffer need to be? dwSize = sizeof(boinc_install_dir); lReturnValue = RegQueryValueEx( hkSetupHive, _T("INSTALLDIR"), NULL, NULL, (LPBYTE)&boinc_install_dir, &dwSize ); } if (hkSetupHive) RegCloseKey(hkSetupHive); #endif } return BOINC_SUCCESS; }
int __cdecl _CrtSetReportHook2( int mode, _CRT_REPORT_HOOK pfnNewHook ) { _CrtSetReportHook( pfnNewHook ); return 0; }
// from crm_vector_tokenize.c int main(void) { char input[1024]; char arg[8192]; char opts[1024]; int i, j; int ret; int k; crmhash_t feavec[2048]; uint32_t feamult[2048]; uint32_t feaord[2048]; ARGPARSE_BLOCK apb = { 0 }; VT_USERDEF_TOKENIZER tokenizer = { 0 }; VT_USERDEF_COEFF_MATRIX our_coeff = { 0 }; int use_default_re_and_coeff = USE_DEFAULT_RE_AND_COEFF; char my_regex[256]; static const int coeff[] = { 1, 3, 0, 0, 0, 1, 0, 5, 0, 0, 1, 0, 0, 11, 0, 1, 0, 0, 0, 23 }; init_stdin_out_err_as_os_handles(); #if 0 setvbuf(stdout, stdout_buf, _IOFBF, sizeof(stdout_buf)); setvbuf(stderr, stderr_buf, _IOFBF, sizeof(stderr_buf)); #endif #if (defined(WIN32) || defined(_WIN32) || defined(_WIN64) || defined(WIN64)) && defined(_DEBUG) /* * Hook in our client-defined reporting function. * Every time a _CrtDbgReport is called to generate * a debug report, our function will get called first. */ _CrtSetReportHook(crm_dbg_report_function); /* * Define the report destination(s) for each type of report * we are going to generate. In this case, we are going to * generate a report for every report type: _CRT_WARN, * _CRT_ERROR, and _CRT_ASSERT. * The destination(s) is defined by specifying the report mode(s) * and report file for each report type. */ _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG); _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG); _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR); _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG); _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); // Store a memory checkpoint in the s1 memory-state structure _CrtMemCheckpoint(&crm_memdbg_state_snapshot1); atexit(crm_report_mem_analysis); // Get the current bits i = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); // Set the debug-heap flag so that freed blocks are kept on the // linked list, to catch any inadvertent use of freed memory #if 0 i |= _CRTDBG_DELAY_FREE_MEM_DF; #endif // Set the debug-heap flag so that memory leaks are reported when // the process terminates. Then, exit. //i |= _CRTDBG_LEAK_CHECK_DF; // Clear the upper 16 bits and OR in the desired freqency //i = (i & 0x0000FFFF) | _CRTDBG_CHECK_EVERY_16_DF; i |= _CRTDBG_CHECK_ALWAYS_DF; // Set the new bits _CrtSetDbgFlag(i); // // set a malloc marker we can use it in the leak dump at the end of the program: // (void)_calloc_dbg(1, 1, _CLIENT_BLOCK, __FILE__, __LINE__); #endif // fprintf(stderr, " args: %d \n", argc); // for (i = 0; i < argc; i++) // fprintf(stderr, " argi: %d, argv: %s \n", i, argv[i]); atexit(crm_final_cleanup); #if defined(HAVE__SET_OUTPUT_FORMAT) _set_output_format(_TWO_DIGIT_EXPONENT); // force MSVC (& others?) to produce floating point %f with 2 digits for power component instead of 3 for easier comparison with 'knowngood'. #endif // force MSwin/Win32 console I/O into binary mode: treat \r\n and \n as completely different - like it is on *NIX boxes! #if defined(HAVE__SETMODE) && defined(HAVE__FILENO) && defined(O_BINARY) (void)_setmode(_fileno(crm_stdin), O_BINARY); (void)_setmode(_fileno(crm_stdout), O_BINARY); (void)_setmode(_fileno(crm_stderr), O_BINARY); #endif user_trace = 1; internal_trace = 1; do { strcpy(my_regex, "[[:alpha:]]+"); memset(&tokenizer, 0, sizeof(tokenizer)); memset(&our_coeff, 0, sizeof(our_coeff)); fprintf(stdout, "Enter a test string: "); fgets(input, sizeof(input), stdin); input[sizeof(input) - 1] = 0; fprintf(stdout, "Input = '%s'\n", input); // fscanf(stdin, "%1023s", input); // fprintf(stdout, "Input = '%s'\n", input); fprintf(stdout, "Enter optional 'vector: ...' arg (don't forget the 'vector: prefix in there!): "); fgets(arg, sizeof(arg), stdin); arg[sizeof(arg) - 1] = 0; fprintf(stdout, "Args = '%s'\n", arg); apb.s1start = my_regex; apb.s1len = (int)strlen(my_regex); apb.s2start = arg; apb.s2len = (int)strlen(arg); apb.sflags = CRM_MARKOVIAN | CRM_UNIQUE; fprintf(stdout, "Optional OSBF style token globbing: type integer values for max_token_size and count (must specify both!): "); fgets(opts, sizeof(opts), stdin); opts[sizeof(opts) - 1] = 0; k = sscanf(opts, "%d %d", &i, &j); if (k == 2) { fprintf(stdout, "using max_token_size %d and count %d.\n", i, j); tokenizer.max_token_length = i; tokenizer.max_big_token_count = j; } tokenizer.regex = my_regex; tokenizer.regexlen = (int)strlen(my_regex); if (strlen(arg) < 3) { CRM_VERIFY(transfer_matrix_to_VT(&our_coeff, coeff, 5, 4, 1)); } memset(feavec, 0, sizeof(feavec)); memset(feamult, 0, sizeof(feamult)); memset(feaord, 0, sizeof(feaord)); tokenizer.input_next_offset = 0; ret = crm_vector_tokenize_selector(&apb, vht, tdw, input, (int)strlen(input), 0, (use_default_re_and_coeff ? NULL : &tokenizer), (use_default_re_and_coeff ? NULL : &our_coeff), feavec, WIDTHOF(feavec), feamult, feaord, &j); for (k = 0; k < j; k++) { fprintf(stdout, "feature[%4d] = %12lu (%08lX) / mul: %d, order: %d\n", k, (unsigned long int)feavec[k], (unsigned long int)feavec[k], feamult[k], feaord[k]); } fprintf(stdout, "... and next_offset is %d\n", tokenizer.input_next_offset); tokenizer.input_next_offset = 0; memset(feavec, 0, sizeof(feavec)); ret = crm_vector_tokenize_selector_old(&apb, input, 0, (int)strlen(input), (use_default_re_and_coeff ? NULL : my_regex), (use_default_re_and_coeff ? 0 : (int)strlen(my_regex)), (use_default_re_and_coeff ? NULL : coeff), (use_default_re_and_coeff ? 0 : 5), (use_default_re_and_coeff ? 0 : 4), feavec, WIDTHOF(feavec), &j, &tokenizer.input_next_offset); for (k = 0; k < j; k++) { fprintf(stdout, "feature[%4d] = %12lu (%08lX)\n", k, (unsigned long int)feavec[k], (unsigned long int)feavec[k]); } fprintf(stdout, "... and next_offset is %d\n", tokenizer.input_next_offset); fprintf(stdout, "Another round? (enter 'y' for yes): "); fgets(input, sizeof(input), stdin); input[sizeof(input) - 1] = 0; } while (input[0] == 'y'); return ret >= 0 ? EXIT_SUCCESS : EXIT_FAILURE; }
int main(int argc, char** argv) { #if defined(_MSC_VER) _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); prevHook = _CrtSetReportHook(customReportHook); // _CrtSetBreakAlloc(157); // Use this line to break at the nth memory allocation #endif QApplication app(argc, argv); app.setAttribute(Qt::AA_DontShowIconsInMenus); // Icons are *no longer shown* in menus app.setAttribute(Qt::AA_UseHighDpiPixmaps); // HiDPI support QDir dir(QApplication::applicationDirPath()); #ifdef QT_DEBUG QApplication::addLibraryPath(dir.absolutePath()); #else QStringList l; l<<dir.absolutePath(); QApplication::setLibraryPaths(l); #endif #ifdef Q_OS_WIN dir.cd("platforms"); QApplication::addLibraryPath(dir.absolutePath()); #endif #ifdef Q_OS_MAC dir.cdUp(); dir.cd("plugins"); QApplication::addLibraryPath(dir.absolutePath()); dir.cdUp(); dir.cd("Frameworks"); QApplication::addLibraryPath(dir.absolutePath()); #endif app.setWindowIcon(QIcon(":/images/chessx.png")); app.setApplicationName("chessx"); app.setOrganizationName("chessx"); app.setOrganizationDomain("chessx.sourceforge.net"); AppSettings = new Settings; app.setStyle("plastique"); #ifdef Q_OS_MAC signal(SIGPIPE, SIG_IGN); #endif QString shortSystemLang = QString("chessx_%1.qm").arg(QLocale::system().name().left(2)); QString fullSystemLang = QString("chessx_%1.qm").arg(QLocale::system().name().left(5)); // Language may have two forms: "pt_BR" or "pl" QString lang = QString("chessx_%1.qm").arg(AppSettings->getValue("/General/language").toString()); QDir().mkpath(AppSettings->dataPath() + "/lang/"); QTranslator translator; if (lang != "chessx_en.qm") { QString filePath = AppSettings->dataPath() + QDir::separator() + "lang" + QDir::separator(); if(translator.load(QString(":/i18n/") + lang) || translator.load(filePath + lang) || translator.load(QString(":/i18n/") + fullSystemLang) || translator.load(filePath + fullSystemLang) || translator.load(QString(":/i18n/") + shortSystemLang) || translator.load(filePath + shortSystemLang)) { app.installTranslator(&translator); } } MainWindow* mainWindow = new MainWindow; mainWindow->show(); // Destroy main window and close application app.connect(&app, SIGNAL(lastWindowClosed()), &app, SLOT(quit())); startFileLog(); int result = app.exec(); stopFileLog(); delete AppSettings; #if defined(_MSC_VER) // Once the app has finished running and has been deleted, // we run this command to view the memory leaks: _CrtDumpMemoryLeaks(); #endif return result; }
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; }
// initialize the diagnostics environment. // int diagnostics_init( int _flags, const char* stdout_prefix, const char* stderr_prefix ) { // Check to see if we have already been called if (diagnostics_initialized) { return ERR_INVALID_PARAM; } diagnostics_initialized = true; // Setup initial values flags = _flags; snprintf(stdout_log, sizeof(stdout_log), "%s.txt", stdout_prefix); snprintf(stdout_archive, sizeof(stdout_archive), "%s.old", stdout_prefix); snprintf(stderr_log, sizeof(stderr_log), "%s.txt", stderr_prefix); snprintf(stderr_archive, sizeof(stderr_archive), "%s.old", stderr_prefix); strcpy(boinc_dir, ""); strcpy(boinc_install_dir, ""); boinc_proxy_enabled = 0; strcpy(boinc_proxy, ""); strcpy(symstore, ""); // Check for invalid parameter combinations if ((flags & BOINC_DIAG_REDIRECTSTDERR) && (flags & BOINC_DIAG_REDIRECTSTDERROVERWRITE)) { return ERR_INVALID_PARAM; } if ((flags & BOINC_DIAG_REDIRECTSTDOUT) && (flags & BOINC_DIAG_REDIRECTSTDOUTOVERWRITE)) { return ERR_INVALID_PARAM; } // Archive any old stderr.txt and stdout.txt files, if requested if (flags & BOINC_DIAG_ARCHIVESTDERR) { boinc_copy(stderr_log, stderr_archive); } if (flags & BOINC_DIAG_ARCHIVESTDOUT) { boinc_copy(stdout_log, stdout_archive); } // Redirect stderr and/or stdout, if requested // if (flags & BOINC_DIAG_REDIRECTSTDERR) { file_size(stderr_log, stderr_file_size); stderr_file = freopen(stderr_log, "a", stderr); if (!stderr_file) { return ERR_FOPEN; } setbuf(stderr_file, 0); } if (flags & BOINC_DIAG_REDIRECTSTDERROVERWRITE) { stderr_file = freopen(stderr_log, "w", stderr); if (!stderr_file) { return ERR_FOPEN; } setbuf(stderr_file, 0); } if (flags & BOINC_DIAG_REDIRECTSTDOUT) { file_size(stdout_log, stdout_file_size); stdout_file = freopen(stdout_log, "a", stdout); if (!stdout_file) { return ERR_FOPEN; } } if (flags & BOINC_DIAG_REDIRECTSTDOUTOVERWRITE) { stdout_file = freopen(stdout_log, "w", stdout); if (!stdout_file) { return ERR_FOPEN; } } #if defined(_WIN32) #if defined(_DEBUG) _CrtSetReportHook(boinc_message_reporting); if (flags & BOINC_DIAG_MEMORYLEAKCHECKENABLED) { SET_CRT_DEBUG_FIELD(_CRTDBG_LEAK_CHECK_DF); } if (flags & BOINC_DIAG_HEAPCHECKENABLED) { if (flags & BOINC_DIAG_HEAPCHECKEVERYALLOC) { SET_CRT_DEBUG_FIELD(_CRTDBG_CHECK_ALWAYS_DF); } else { SET_CRT_DEBUG_FIELD(_CRTDBG_CHECK_EVERY_1024_DF); } } if (flags & BOINC_DIAG_BOINCAPPLICATION) { if (flags & BOINC_DIAG_MEMORYLEAKCHECKENABLED) { _CrtMemCheckpoint(&start_snapshot); } } #endif // defined(_DEBUG) // Initialize the thread list structure // The data for this structure should be set by // boinc_init or boinc_init_graphics. diagnostics_init_thread_list(); diagnostics_init_unhandled_exception_monitor(); diagnostics_init_message_monitor(); #endif // defined(_WIN32) // Install unhandled exception filters and signal traps. if (BOINC_SUCCESS != boinc_install_signal_handlers()) { return ERR_SIGNAL_OP; } // Store various pieces of inforation for future use. if (flags & BOINC_DIAG_BOINCAPPLICATION) { char buf[256]; char proxy_address[256]; int proxy_port; MIOFILE mf; FILE* p; #ifdef _WIN32 LONG lReturnValue; HKEY hkSetupHive; DWORD dwSize = 0; #endif strcpy(buf, ""); strcpy(proxy_address, ""); proxy_port = 0; #ifndef _USING_FCGI_ p = fopen(INIT_DATA_FILE, "r"); #else p = FCGI::fopen(INIT_DATA_FILE, "r"); #endif if (p) { mf.init_file(p); while(mf.fgets(buf, sizeof(buf))) { if (match_tag(buf, "</app_init_data>")) break; else if (parse_str(buf, "<boinc_dir>", boinc_dir, 256)) continue; else if (parse_str(buf, "<symstore>", symstore, 256)) continue; else if (match_tag(buf, "<use_http_proxy/>")) { boinc_proxy_enabled = true; continue; } else if (parse_str(buf, "<http_server_name>", proxy_address, 256)) continue; else if (parse_int(buf, "<http_server_port>", proxy_port)) continue; } fclose(p); } if (boinc_proxy_enabled) { int buffer_used = snprintf(boinc_proxy, sizeof(boinc_proxy), "%s:%d", proxy_address, proxy_port); if ((sizeof(boinc_proxy) == buffer_used) || (-1 == buffer_used)) { boinc_proxy[sizeof(boinc_proxy)-1] = '\0'; } } #ifdef _WIN32 // Lookup the location of where BOINC was installed to and store // that for future use. lReturnValue = RegOpenKeyEx( HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Space Sciences Laboratory, U.C. Berkeley\\BOINC Setup"), 0, KEY_READ, &hkSetupHive ); if (lReturnValue == ERROR_SUCCESS) { // How large does our buffer need to be? dwSize = sizeof(boinc_install_dir); lReturnValue = RegQueryValueEx( hkSetupHive, _T("INSTALLDIR"), NULL, NULL, (LPBYTE)&boinc_install_dir, &dwSize ); } if (hkSetupHive) RegCloseKey(hkSetupHive); #endif } return BOINC_SUCCESS; }
~_CrtHooksRAII() { _CrtSetReportHook(oldHook); signal(SIGABRT, oldAbrtHandler); }
int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPTSTR lpCmdLine, _In_ int nCmdShow) { UNREFERENCED_PARAMETER(hInstance); UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); UNREFERENCED_PARAMETER(nCmdShow); debug_log("starting process"); // Prevent error dialogs. _set_error_mode(_OUT_TO_STDERR); _CrtSetReportHook(CrtDbgHook); SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); // The Visual Studio debugger starts us in the build\ subdirectory by // default, which will prevent us from finding the test files in the html\ // directory. This workaround will locate the html\ directory even if it's // in the parent directory so we will work in the debugger out of the box. WIN32_FIND_DATA find_data; HANDLE h = FindFirstFile("html", &find_data); if (h == INVALID_HANDLE_VALUE) { h = FindFirstFile("..\\html", &find_data); if (h != INVALID_HANDLE_VALUE) { SetCurrentDirectory(".."); } } if (h != INVALID_HANDLE_VALUE) { FindClose(h); } // Prevent automatic DPI scaling. SetProcessDPIAware(); if (__argc == 1) { debug_log("running server"); HDC desktop = GetDC(NULL); assert(desktop); if (GetDeviceCaps(desktop, LOGPIXELSX) != 96) { MessageBox(NULL, "Warning: DPI scaling is enabled. Non-DPI-aware browsers will not be able to run the test.", "Warning", MB_ICONWARNING | MB_OK); } ReleaseDC(NULL, desktop); run_server(); } debug_log("opening native reference window"); if (__argc != 3) { debug_log("Unrecognized number of arguments"); return 1; } // The first argument is the magic pattern to draw on the window, encoded as hex. memset(pattern, 0, sizeof(pattern)); if (!parse_hex_magic_pattern(__argv[1], pattern)) { debug_log("Failed to parse pattern"); return 1; } // The second argument is the handle of the parent process. HANDLE parent_process = (HANDLE)_strtoui64(__argv[2], NULL, 16); message_loop(parent_process); return 0; }
void DetectMemoryLeak() { _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); //change the report function to only report memory leaks from program code prevHook = _CrtSetReportHook(reportingHook); }
_CrtHooksRAII() { oldAbrtHandler = signal(SIGABRT, &AbrtHandler); _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG); _set_abort_behavior(0, _WRITE_ABORT_MSG); oldHook = _CrtSetReportHook(&CrtReportHook); }
MprApp *mprAllocInit(MprAllocCback cback) { MprAllocStats *stats; MprApp *app; MprSlab *slab; MprBlk *bp, *sp; int i; bp = malloc(sizeof(MprApp) + HDR_SIZE); mprAssert(bp); if (bp == 0) { if (cback) { (*cback)(0, sizeof(MprApp), 0, 0); } return 0; } memset(bp, 0, sizeof(MprApp) + HDR_SIZE); bp->parent = bp; bp->size = sizeof(MprApp); bp->flags = ALLOC_MAGIC; bp->next = bp->prev = bp; #if BLD_FEATURE_ALLOC_LEAK_TRACK bp->location = MPR_LOC; #endif app = (MprApp*) GET_PTR(bp); app->magic = APP_MAGIC; app->alloc.cback = cback; app->stackStart = (void*) &app; bp->app = app; app->alloc.slabs = mprAllocZeroedBlock(MPR_LOC_PASS(app, MPR_LOC), sizeof(MprSlab) * MPR_MAX_SLAB); if (app->alloc.slabs == 0) { mprFree(app); return 0; } /* * The slab control structures must not be freed. Set keep to safeguard * against accidents. */ sp = GET_HDR(app->alloc.slabs); sp->flags |= ALLOC_FLAGS_KEEP; for (i = 0; i < MPR_MAX_SLAB; i++) { /* * This is overriden by requestors calling slabAlloc */ slab = &app->alloc.slabs[i]; slab->preAllocateIncr = MPR_SLAB_DEFAULT_INC; } /* * Keep aggregated stats even in production code */ stats = &app->alloc.stats; stats->bytesAllocated += sizeof(MprApp); if (stats->bytesAllocated > stats->peakAllocated) { stats->peakAllocated = stats->bytesAllocated; } stats->allocCount++; #if !BREW rootCtx = app; #endif #if (WIN || BREW_SIMULATOR) && BLD_DEBUG _CrtSetReportHook(crtReportHook); #endif return app; }