void SEO( int stream ) { _CrtSetReportMode( stream, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG ); _CrtSetReportFile( stream, _CRTDBG_FILE_STDOUT ); }
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_end */
BOOL WINAPI DllMain(HINSTANCE instance, DWORD reason, LPVOID lpReserved) { static bool bDllInited = false; BOOL IsUnload = false, bEnableDW = true; switch(reason) { case DLL_PROCESS_ATTACH: #ifdef DEBUG //MessageBox(0, L"Load", NULL, MB_OK); #endif if (bDllInited) return true; bDllInited = true; g_dllInstance = instance; { LPWSTR dllPath = new WCHAR[MAX_PATH + 1]; int nSize = GetModuleFileName(g_dllInstance, dllPath, MAX_PATH + 1); WCHAR* p = &dllPath[nSize]; while (*--p != L'\\'); *p = L'\0'; #ifdef _WIN64 wcscat(dllPath, L"\\EasyHk64.dll"); #else wcscat(dllPath, L"\\EasyHk32.dll"); #endif HMODULE hEasyhk = LoadLibrary(dllPath); delete[]dllPath; if (!hEasyhk) return false; } //弶婜壔弴彉 //DLL_PROCESS_DETACH偱偼偙傟偺媡弴偵偡傞 //1. CRT娭悢偺弶婜壔 //2. 僋儕僥傿僇儖僙僋僔儑儞偺弶婜壔 //3. TLS偺弨旛 //4. CGdippSettings偺僀儞僗僞儞僗惗惉丄INI撉傒崬傒 //5. ExcludeModule僠僃僢僋 // 6. FreeType儔僀僽儔儕偺弶婜壔 // 7. FreeTypeFontEngine偺僀儞僗僞儞僗惗惉 // 8. API傪僼僢僋 // 9. Manager偺GetProcAddress傪僼僢僋 //1 _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF); _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_WNDW); //_CrtSetBreakAlloc(100); //Opera傛巭傑傟乣 //Assert(GetModuleHandleA("opera.exe") == NULL); setlocale(LC_ALL, ""); g_hinstDLL = instance; //APITracer::Start(instance, APITracer::OutputFile); //2, 3 CCriticalSectionLock::Init(); COwnedCriticalSectionLock::Init(); CThreadCounter::Init(); if (!g_TLInfo.ProcessInit()) { return FALSE; } //4 { CGdippSettings* pSettings = CGdippSettings::CreateInstance(); if (!pSettings || !pSettings->LoadSettings(instance)) { CGdippSettings::DestroyInstance(); return FALSE; } IsUnload = IsProcessUnload(); bEnableDW = pSettings->DirectWrite(); } if (!IsUnload) hook_initinternal(); //不加载的模块就不做任何事情 //5 if (!IsProcessExcluded() && !IsUnload) { #ifndef _WIN64 InitWow64ext(); #endif if (!FontLInit()) { return FALSE; } g_pFTEngine = new FreeTypeFontEngine; if (!g_pFTEngine) { return FALSE; } //if (!AddEasyHookEnv()) return FALSE; //fail to load easyhook InterlockedExchange(&g_bHookEnabled, TRUE); if (hook_init()!=NOERROR) return FALSE; //hook d2d if already loaded /* DWORD dwSessionID = 0; if (ProcessIdToSessionIdProc) ProcessIdToSessionIdProc(GetCurrentThreadId(), &dwSessionID); else dwSessionID = 1;*/ if (IsRunAsUser() && bEnableDW && IsWindowsVistaOrGreater()) //vista or later { //ORIG_LdrLoadDll = LdrLoadDll; //MessageBox(0, L"Test", NULL, MB_OK); HookD2DDll(); //hook_demand_LdrLoadDll(); } /*if (IsWindows8OrGreater()) { *(DWORD_PTR*)&(ORIG_MySetProcessMitigationPolicy) = *(DWORD_PTR*)&(MySetProcessMitigationPolicy); //hook_demand_MySetProcessMitigationPolicy(); }*/ // InstallManagerHook(); } //获得当前加载模式 if (IsUnload) { HANDLE mutex_offical = OpenMutex(MUTEX_ALL_ACCESS, false, _T("{46AD3688-30D0-411e-B2AA-CB177818F428}")); HANDLE mutex_gditray2 = OpenMutex(MUTEX_ALL_ACCESS, false, _T("Global\\MacType")); if (!mutex_gditray2) mutex_gditray2 = OpenMutex(MUTEX_ALL_ACCESS, false, _T("MacType")); HANDLE mutex_CompMode = OpenMutex(MUTEX_ALL_ACCESS, false, _T("Global\\MacTypeCompMode")); if (!mutex_CompMode) mutex_CompMode = OpenMutex(MUTEX_ALL_ACCESS, false, _T("MacTypeCompMode")); BOOL HookMode = (mutex_offical || (mutex_gditray2 && mutex_CompMode)) || (!mutex_offical && !mutex_gditray2); //是否在兼容模式下 CloseHandle(mutex_CompMode); CloseHandle(mutex_gditray2); CloseHandle(mutex_offical); if (!HookMode) //非兼容模式下,拒绝加载 return false; } //APITracer::Finish(); break; case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: g_TLInfo.ThreadTerm(); break; case DLL_PROCESS_DETACH: // RemoveManagerHook(); if (!bDllInited) return true; bDllInited = false; if (InterlockedExchange(&g_bHookEnabled, FALSE) && lpReserved == NULL) { //如果是进程终止,则不需要释放 hook_term(); //delete AACacheFull; //delete AACache; // for (int i=0;i<CACHE_SIZE;i++) // delete g_AACache2[i]; //清除缓存 //free(g_charmapCache); } #ifndef DEBUG if (lpReserved != NULL) return true; #endif if (g_pFTEngine) { delete g_pFTEngine; } //if (g_alterGUIFont) // DeleteObject(g_alterGUIFont); FontLFree(); /* #ifndef _WIN64 __FUnloadDelayLoadedDLL2("easyhk32.dll"); #else __FUnloadDelayLoadedDLL2("easyhk64.dll"); #endif*/ CGdippSettings::DestroyInstance(); g_TLInfo.ProcessTerm(); CCriticalSectionLock::Term(); COwnedCriticalSectionLock::Term(); break; } return TRUE; }
void my_end(int infoflag) { FILE *info_file; if (!(info_file=DBUG_FILE)) info_file=stderr; if (infoflag & MY_CHECK_ERROR || info_file != stderr) { /* Test if some file is left open */ if (my_file_opened | my_stream_opened) { sprintf(errbuff[0],EE(EE_OPEN_WARNING),my_file_opened,my_stream_opened); (void) my_message_no_curses(EE_OPEN_WARNING,errbuff[0],ME_BELL); DBUG_PRINT("error",("%s",errbuff[0])); } } free_charsets(); if (infoflag & MY_GIVE_INFO || info_file != stderr) { #ifdef HAVE_GETRUSAGE struct rusage rus; 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(MSDOS) || defined(__NETWARE__) ) && !defined(__WIN__) fprintf(info_file,"\nRun time: %.1f\n",(double) clock()/CLOCKS_PER_SEC); #endif #if defined(SAFEMALLOC) TERMINATE(stderr); /* Give statistic on screen */ #elif 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 } #ifdef THREAD DBUG_POP(); /* Must be done before my_thread_end */ my_once_free(); 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 ? stderr : (FILE *) 0); #endif /* defined(SAFE_MUTEX) */ #endif /* THREAD */ #ifdef __WIN__ if (have_tcpip) WSACleanup(); #endif /* __WIN__ */ my_init_done=0; } /* my_end */
int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { #ifdef _CRTDBG_MAP_ALLOC _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); #endif UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); // TODO: Place code here. MSG msg; HACCEL hAccelTable; INITCOMMONCONTROLSEX InitCtrlEx; InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX); InitCtrlEx.dwICC = 0x00004000; //ICC_STANDARD_CLASSES; InitCommonControlsEx(&InitCtrlEx); // Initialize global strings LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_WINLAUNCHER, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // Perform application initialization: if (!InitInstance (hInstance, nCmdShow)) return FALSE; // Init COM OleInitialize(NULL); hURLBarWnd = CreateWindow(L"EDIT", 0, WS_CHILD | WS_VISIBLE | WS_BORDER | ES_LEFT | ES_AUTOVSCROLL, 0, 0, 0, 0, hMainWnd, 0, hInstance, 0); DefEditProc = GetWindowLong(hURLBarWnd, GWL_WNDPROC); SetWindowLong(hURLBarWnd, GWL_WNDPROC,(long)MyEditProc); SetFocus(hURLBarWnd); HRESULT hr = CoCreateInstance(CLSID_WebView, 0, CLSCTX_ALL, IID_IWebView, (void**)&gWebView); if (FAILED(hr)) goto exit; gWebHost = new WinLauncherWebHost(); gWebHost->AddRef(); hr = gWebView->setFrameLoadDelegate(gWebHost); if (FAILED(hr)) goto exit; hr = gWebView->setHostWindow((OLE_HANDLE) hMainWnd); if (FAILED(hr)) goto exit; RECT clientRect; GetClientRect(hMainWnd, &clientRect); hr = gWebView->initWithFrame(clientRect, 0, 0); if (FAILED(hr)) goto exit; IWebFrame* frame; hr = gWebView->mainFrame(&frame); if (FAILED(hr)) goto exit; static BSTR defaultHTML = 0; if (!defaultHTML) defaultHTML = SysAllocString(TEXT("<p style=\"background-color: #00FF00\">Testing</p><img src=\"http://webkit.org/images/icon-gold.png\" alt=\"Face\"><div style=\"border: solid blue\" contenteditable=\"true\">div with blue border</div><ul><li>foo<li>bar<li>baz</ul>")); frame->loadHTMLString(defaultHTML, 0); frame->Release(); IWebViewPrivate* viewExt; hr = gWebView->QueryInterface(IID_IWebViewPrivate, (void**)&viewExt); if (FAILED(hr)) goto exit; hr = viewExt->viewWindow((OLE_HANDLE*) &gViewWindow); viewExt->Release(); if (FAILED(hr) || !gViewWindow) goto exit; resizeSubViews(); ShowWindow(gViewWindow, nCmdShow); UpdateWindow(gViewWindow); hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_WINLAUNCHER)); // Main message loop: while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } exit: delete gWebView; #ifdef _CRTDBG_MAP_ALLOC _CrtDumpMemoryLeaks(); #endif // Shut down COM. OleUninitialize(); return (int) msg.wParam; }
int main(int argc, char* argv[]) { int err = 0; XML_Parser expat = XML_ParserCreate(NULL); main_args args; dae_COLLADA* collada = NULL; FILE* fp = NULL; void* data = NULL; size_t size = 0; taa_scene scene; err = main_parse_args(argc, argv, &args); if(err != 0) { puts(MAIN_USAGE); } taa_scene_create(&scene, taa_SCENE_Y_UP); if(err == 0) { // open input file fp = fopen(args.dae, "rb"); if(fp == NULL) { printf("could not open input file %s\n", args.dae); err = -1; } } if(err == 0) { // get allocate file buffer fseek(fp, 0, SEEK_END); size = ftell(fp); fseek(fp, 0, SEEK_SET); data = XML_GetBuffer(expat, size); if(data == NULL) { printf("could not allocate memory of size %u", (unsigned) size); err = -1; } } if(err == 0) { // read file if(fread(data, 1, size, fp) != size) { printf("error reading file\n"); err = -1; } } if(fp != NULL) { fclose(fp); } if(err == 0) { // parse the dae data daeu_xml_parser parser; collada = dae_create(); daeu_xml_create(collada, &parser); XML_SetElementHandler( expat, daeu_xml_startelement, daeu_xml_endelement); XML_SetCharacterDataHandler(expat, daeu_xml_chardata); XML_SetUserData(expat, parser); if(XML_ParseBuffer(expat, size, 1) != XML_STATUS_OK) { printf("error parsing xml\n"); err = -1; } daeu_xml_destroy(parser); } XML_ParserFree(expat); if(err == 0) { // convert to taa_scene convert_collada(args.dae, collada, &scene); } if(collada != NULL) { dae_destroy(collada); } if(err == 0) { // convert up axis taa_scene_convert_upaxis(&scene, args.upaxis); } if(err == 0) { // open output file fp = fopen(args.out, "wb"); if(fp == NULL) { printf("could not open output file %s\n", args.out); err = -1; } } if(err == 0) { // export taa_filestream outfs; taa_filestream_create(fp, 1024 * 1024, taa_FILESTREAM_WRITE, &outfs); taa_scenefile_serialize(&scene, &outfs); taa_filestream_destroy(&outfs); fclose(fp); } taa_scene_destroy(&scene); #if defined(_DEBUG) && defined(_MSC_FULL_VER) _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDOUT); _CrtCheckMemory(); _CrtDumpMemoryLeaks(); #endif return err; }
int main(int argc, char *argv[]) #endif { #ifdef PHP_CLI_WIN32_NO_CONSOLE int argc = __argc; char **argv = __argv; #endif int c; int exit_status = SUCCESS; int module_started = 0, sapi_started = 0; char *php_optarg = NULL; int php_optind = 1, use_extended_info = 0; char *ini_path_override = NULL; char *ini_entries = NULL; int ini_entries_len = 0; int ini_ignore = 0; sapi_module_struct *sapi_module = &cli_sapi_module; /* * Do not move this initialization. It needs to happen before argv is used * in any way. */ argv = save_ps_args(argc, argv); cli_sapi_module.additional_functions = additional_functions; #if defined(PHP_WIN32) && defined(_DEBUG) && defined(PHP_WIN32_DEBUG_HEAP) { int tmp_flag; _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); tmp_flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); tmp_flag |= _CRTDBG_DELAY_FREE_MEM_DF; tmp_flag |= _CRTDBG_LEAK_CHECK_DF; _CrtSetDbgFlag(tmp_flag); } #endif #ifdef HAVE_SIGNAL_H #if defined(SIGPIPE) && defined(SIG_IGN) signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE in standalone mode so that sockets created via fsockopen() don't kill PHP if the remote site closes it. in apache|apxs mode apache does that for us! [email protected] 20000419 */ #endif #endif #ifdef ZTS tsrm_startup(1, 1, 0, NULL); (void)ts_resource(0); ZEND_TSRMLS_CACHE_UPDATE(); #endif #ifdef ZEND_SIGNALS zend_signal_startup(); #endif #ifdef PHP_WIN32 _fmode = _O_BINARY; /*sets default for file streams to binary */ setmode(_fileno(stdin), O_BINARY); /* make the stdio mode be binary */ setmode(_fileno(stdout), O_BINARY); /* make the stdio mode be binary */ setmode(_fileno(stderr), O_BINARY); /* make the stdio mode be binary */ #endif while ((c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2))!=-1) { switch (c) { case 'c': if (ini_path_override) { free(ini_path_override); } ini_path_override = strdup(php_optarg); break; case 'n': ini_ignore = 1; break; case 'd': { /* define ini entries on command line */ int len = (int)strlen(php_optarg); char *val; if ((val = strchr(php_optarg, '='))) { val++; if (!isalnum(*val) && *val != '"' && *val != '\'' && *val != '\0') { ini_entries = realloc(ini_entries, ini_entries_len + len + sizeof("\"\"\n\0")); memcpy(ini_entries + ini_entries_len, php_optarg, (val - php_optarg)); ini_entries_len += (int)(val - php_optarg); memcpy(ini_entries + ini_entries_len, "\"", 1); ini_entries_len++; memcpy(ini_entries + ini_entries_len, val, len - (val - php_optarg)); ini_entries_len += len - (int)(val - php_optarg); memcpy(ini_entries + ini_entries_len, "\"\n\0", sizeof("\"\n\0")); ini_entries_len += sizeof("\n\0\"") - 2; } else { ini_entries = realloc(ini_entries, ini_entries_len + len + sizeof("\n\0")); memcpy(ini_entries + ini_entries_len, php_optarg, len); memcpy(ini_entries + ini_entries_len + len, "\n\0", sizeof("\n\0")); ini_entries_len += len + sizeof("\n\0") - 2; } } else { ini_entries = realloc(ini_entries, ini_entries_len + len + sizeof("=1\n\0")); memcpy(ini_entries + ini_entries_len, php_optarg, len); memcpy(ini_entries + ini_entries_len + len, "=1\n\0", sizeof("=1\n\0")); ini_entries_len += len + sizeof("=1\n\0") - 2; } break; } #ifndef PHP_CLI_WIN32_NO_CONSOLE case 'S': sapi_module = &cli_server_sapi_module; cli_server_sapi_module.additional_functions = server_additional_functions; break; #endif case 'h': /* help & quit */ case '?': php_cli_usage(argv[0]); goto out; case 'i': case 'v': case 'm': sapi_module = &cli_sapi_module; goto exit_loop; case 'e': /* enable extended info output */ use_extended_info = 1; break; } } exit_loop: sapi_module->ini_defaults = sapi_cli_ini_defaults; sapi_module->php_ini_path_override = ini_path_override; sapi_module->phpinfo_as_text = 1; sapi_module->php_ini_ignore_cwd = 1; sapi_startup(sapi_module); sapi_started = 1; sapi_module->php_ini_ignore = ini_ignore; sapi_module->executable_location = argv[0]; if (sapi_module == &cli_sapi_module) { if (ini_entries) { ini_entries = realloc(ini_entries, ini_entries_len + sizeof(HARDCODED_INI)); memmove(ini_entries + sizeof(HARDCODED_INI) - 2, ini_entries, ini_entries_len + 1); memcpy(ini_entries, HARDCODED_INI, sizeof(HARDCODED_INI) - 2); } else { ini_entries = malloc(sizeof(HARDCODED_INI)); memcpy(ini_entries, HARDCODED_INI, sizeof(HARDCODED_INI)); } ini_entries_len += sizeof(HARDCODED_INI) - 2; } sapi_module->ini_entries = ini_entries; /* startup after we get the above ini override se we get things right */ if (sapi_module->startup(sapi_module) == FAILURE) { /* there is no way to see if we must call zend_ini_deactivate() * since we cannot check if EG(ini_directives) has been initialised * because the executor's constructor does not set initialize it. * Apart from that there seems no need for zend_ini_deactivate() yet. * So we goto out_err.*/ exit_status = 1; goto out; } module_started = 1; /* -e option */ if (use_extended_info) { CG(compiler_options) |= ZEND_COMPILE_EXTENDED_INFO; } zend_first_try { #ifndef PHP_CLI_WIN32_NO_CONSOLE if (sapi_module == &cli_sapi_module) { #endif exit_status = do_cli(argc, argv); #ifndef PHP_CLI_WIN32_NO_CONSOLE } else { exit_status = do_cli_server(argc, argv); } #endif } zend_end_try(); out: if (ini_path_override) { free(ini_path_override); } if (ini_entries) { free(ini_entries); } if (module_started) { php_module_shutdown(); } if (sapi_started) { sapi_shutdown(); } #ifdef ZTS tsrm_shutdown(); #endif /* * Do not move this de-initialization. It needs to happen right before * exiting. */ cleanup_ps_args(argv); exit(exit_status); }
int AP_Win32App::WinMain(const char * szAppName, HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow) { if (!g_thread_supported ()) g_thread_init (NULL); bool bShowApp = true; BOOL bInitialized = FALSE; // this is a static function and doesn't have a 'this' pointer. MSG msg; #ifdef _MSC_VER _CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_DEBUG ); _CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_DEBUG ); _CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_WNDW); #endif // HACK: load least-common-denominator Rich Edit control // TODO: fix Spell dlg so we don't rely on this // ALT: make it a Preview widget instead HINSTANCE hinstRich = LoadLibrary("riched32.dll"); if (!hinstRich) hinstRich = LoadLibrary("riched20.dll"); UT_return_val_if_fail (hinstRich, 1); AP_Win32App * pMyWin32App; // OLE Stuff if (SUCCEEDED(OleInitialize(NULL))) bInitialized = TRUE; // We put this in a block to force the destruction of Args in the stack { // Load the command line into an XAP_Args class #ifdef _MSC_VER // when using MSVC use already split arguments XAP_Args XArgs = XAP_Args(__argc, __argv); #else // but for other compiles may not be available so use szCmdLine UT_String szNewCmdLine = UT_String_sprintf ( "%s %s", "AbiWord.exe", szCmdLine ) ; XAP_Args XArgs = XAP_Args(szNewCmdLine.c_str()); #endif // Step 1: Initialize our application. pMyWin32App = new AP_Win32App(hInstance, szAppName); AP_Args Args = AP_Args(&XArgs, szAppName, pMyWin32App); Args.parseOptions(); pMyWin32App->initialize(); // Step 2: Handle all non-window args. // process args (calls common arg handler, which then calls platform specific) // As best I understand, it returns true to continue and show window, or // false if no window should be shown (and thus we should simply exit). bool windowlessArgsWereSuccessful = true; if (!Args.doWindowlessArgs(windowlessArgsWereSuccessful)) { pMyWin32App->shutdown(); // properly shutdown the app 1st delete pMyWin32App; return (windowlessArgsWereSuccessful ? 0 : -1); } // Step 3: Create windows as appropriate. // if some args are botched, it returns false and we should // continue out the door. // We used to check for bShowApp here. It shouldn't be needed // anymore, because doWindowlessArgs was supposed to bail already. -PL if (!pMyWin32App->openCmdLineFiles(&Args)) { pMyWin32App->shutdown(); // properly shutdown the app 1st delete pMyWin32App; return 0; } } // // This block is controlled by the Structured Exception Handle // if any crash happens here we will recover it and save the file (cross fingers) // try { UT_uint32 iHeight = 0, iWidth = 0, t_flag =0; UT_sint32 iPosX = 0, iPosY = 0; if (!((XAP_App::getApp()->getGeometry(&iPosX,&iPosY,&iWidth,&iHeight,&t_flag)) && ((iWidth > 0) && (iHeight > 0))) ) XAP_App::getApp()->getDefaultGeometry(iWidth,iHeight,t_flag); if ((t_flag & PREF_FLAG_GEOMETRY_MAXIMIZED)==PREF_FLAG_GEOMETRY_MAXIMIZED) iCmdShow = SW_SHOWMAXIMIZED; if (bShowApp) { // display the windows for(UT_sint32 i = 0; i < pMyWin32App->m_vecFrames.getItemCount(); i++) { AP_Win32Frame * curFrame = (AP_Win32Frame*)pMyWin32App->m_vecFrames[i]; UT_continue_if_fail(curFrame); HWND hwnd = curFrame->getTopLevelWindow(); ShowWindow(hwnd, iCmdShow); UpdateWindow(hwnd); } // do dispatch loop while(UT_GetMessage(&msg, NULL, 0, 0, m_bForceAnsi)) { // TranslateMessage is not called because AbiWord // has its own way of decoding keyboard accelerators if (pMyWin32App->handleModelessDialogMessage(&msg)) continue; TranslateMessage(&msg); UT_DispatchMessage(&msg); // Check for idle condition while( !UT_Win32Idle::_isEmpty() && !PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE) ) { // Fire idle functions when no pending messages UT_Win32Idle::_fireall(); } } } // Un-init OLE if (bInitialized) OleUninitialize(); FreeLibrary(hinstRich); // unload all loaded plugins (remove some of the memory leaks shown at shutdown :-) XAP_ModuleManager::instance().unloadAllPlugins(); // Step 4: Destroy the App. It should take care of deleting all frames. pMyWin32App->shutdown(); delete pMyWin32App; }// end of thes block is controlled by the Exception Handler // // If an exception happens, with "catch" the block // and then the save it into disk // catch (...) { #ifdef DEBUG throw; #endif AP_Win32App *pApp = (AP_Win32App *) XAP_App::getApp(); UT_return_val_if_fail (pApp,1); // first of all, try to save the current prefs (so that any log entries are dumped // onto disk -- this allows us to save useful info for dbg purposes) we will enclose // this inside of a try/catch block, so that in the (unlikely) case something goes // badly wrong when writing the prefs file, we still get chance to save the open // documents try { if(pApp->getPrefs()) { pApp->getPrefs()->savePrefsFile(); } } catch(...) { // do nothing } IEFileType abiType = IE_Imp::fileTypeForSuffix(".abw"); for (UT_sint32 i = 0; i < pApp->m_vecFrames.getItemCount(); i++) { AP_Win32Frame * curFrame = (AP_Win32Frame*)pApp->m_vecFrames[i]; UT_continue_if_fail(curFrame); // again, we want to catch any exception thrown while saving individual documents, // in order to run through the whole loop try { if (NULL == curFrame->getFilename()) curFrame->backup(".abw.saved", abiType); else curFrame->backup(".saved", abiType); } catch(...) { // do nothing } } // Tell the user was has just happened AP_Win32Frame * curFrame = (AP_Win32Frame*)pApp->m_vecFrames[0]; if (curFrame) { curFrame->showMessageBox(AP_STRING_ID_MSG_Exception,XAP_Dialog_MessageBox::b_O, XAP_Dialog_MessageBox::a_OK); } }// end of except SET_CRT_DEBUG_FIELD( _CRTDBG_LEAK_CHECK_DF ); return msg.wParam; }
bool AppInit2(int argc, char* argv[]) { #ifdef _MSC_VER // Turn off microsoft heap dump noise _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0)); #endif #if _MSC_VER >= 1400 // Disable confusing "helpful" text message on abort, ctrl-c _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); #endif #ifndef __WXMSW__ umask(077); #endif // // Parameters // ParseParameters(argc, argv); if (mapArgs.count("-datadir")) strlcpy(pszSetDataDir, mapArgs["-datadir"].c_str(), sizeof(pszSetDataDir)); ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir if (mapArgs.count("-?") || mapArgs.count("--help")) { string strUsage = string() + _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" + " bitcoin [options] \t " + "\n" + " bitcoin [options] <command> [params]\t " + _("Send command to -server or bitcoind\n") + " bitcoin [options] <command> -? \t\t " + _("Get help for a command\n") + " bitcoin help \t\t\t " + _("List commands\n") + _("Options:\n") + " -conf=<file> \t " + _("Specify configuration file (default: bitcoin.conf)\n") + " -gen \t " + _("Generate coins\n") + " -gen=0 \t " + _("Don't generate coins\n") + " -min \t " + _("Start minimized\n") + " -datadir=<dir> \t " + _("Specify data directory\n") + " -proxy=<ip:port>\t " + _("Connect through socks4 proxy\n") + " -addnode=<ip> \t " + _("Add a node to connect to\n") + " -connect=<ip> \t " + _("Connect only to the specified node\n") + " -server \t " + _("Accept command line and JSON-RPC commands\n") + " -daemon \t " + _("Run in the background as a daemon and accept commands\n") + " -? \t " + _("This help message\n"); #if defined(__WXMSW__) && defined(GUI) // Tabs make the columns line up in the message box wxMessageBox(strUsage, "Bitcoin", wxOK); #else // Remove tabs strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end()); fprintf(stderr, "%s", strUsage.c_str()); #endif return false; } if (mapArgs.count("-debug")) fDebug = true; if (mapArgs.count("-printtodebugger")) fPrintToDebugger = true; if (fCommandLine) { int ret = CommandLineRPC(argc, argv); exit(ret); } if (!fDebug && !pszSetDataDir[0]) ShrinkDebugFile(); printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); printf("BitcoinTEST version %d.%d.%d%s beta\n", VERSION/10000, (VERSION/100)%100, VERSION%100, pszSubVer); #ifdef GUI printf("OS version %s\n", ((string)wxGetOsDescription()).c_str()); printf("System default language is %d %s\n", g_locale.GetSystemLanguage(), ((string)g_locale.GetSysName()).c_str()); printf("Language file %s (%s)\n", (string("locale/") + (string)g_locale.GetCanonicalName() + "/LC_MESSAGES/bitcoin.mo").c_str(), ((string)g_locale.GetLocale()).c_str()); #endif printf("Default data directory %s\n", GetDefaultDataDir().c_str()); if (mapArgs.count("-loadblockindextest")) { CTxDB txdb("r"); txdb.LoadBlockIndex(); PrintBlockTree(); return false; } // // Limit to single instance per user // Required to protect the database files if we're going to keep deleting log.* // #if defined(__WXMSW__) && defined(GUI) // todo: wxSingleInstanceChecker wasn't working on Linux, never deleted its lock file // maybe should go by whether successfully bind port 18333 instead wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH"); for (int i = 0; i < strMutexName.size(); i++) if (!isalnum(strMutexName[i])) strMutexName[i] = '.'; wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName); if (psingleinstancechecker->IsAnotherRunning()) { printf("Existing instance found\n"); unsigned int nStart = GetTime(); loop { // TODO: find out how to do this in Linux, or replace with wxWidgets commands // Show the previous instance and exit HWND hwndPrev = FindWindowA("wxWindowClassNR", "BitcoinTEST"); if (hwndPrev) { if (IsIconic(hwndPrev)) ShowWindow(hwndPrev, SW_RESTORE); SetForegroundWindow(hwndPrev); return false; } if (GetTime() > nStart + 60) return false; // Resume this instance if the other exits delete psingleinstancechecker; Sleep(1000); psingleinstancechecker = new wxSingleInstanceChecker(strMutexName); if (!psingleinstancechecker->IsAnotherRunning()) break; } }
/** Initialize bitcoin. * @pre Parameters should be parsed and config file should be read. */ bool AppInit2(boost::thread_group& threadGroup) { // ********************************************************* Step 1: setup #ifdef _MSC_VER // Turn off Microsoft heap dump noise _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0)); #endif #if _MSC_VER >= 1400 // Disable confusing "helpful" text message on abort, Ctrl-C _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); #endif #ifdef WIN32 // Enable Data Execution Prevention (DEP) // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008 // A failure is non-critical and needs no further attention! #ifndef PROCESS_DEP_ENABLE // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7), // which is not correct. Can be removed, when GCCs winbase.h is fixed! #define PROCESS_DEP_ENABLE 0x00000001 #endif typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD); PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy"); if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE); #endif #ifndef WIN32 umask(077); // Clean shutdown on SIGTERM struct sigaction sa; sa.sa_handler = HandleSIGTERM; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(SIGTERM, &sa, NULL); sigaction(SIGINT, &sa, NULL); // Reopen debug.log on SIGHUP struct sigaction sa_hup; sa_hup.sa_handler = HandleSIGHUP; sigemptyset(&sa_hup.sa_mask); sa_hup.sa_flags = 0; sigaction(SIGHUP, &sa_hup, NULL); #endif if (!CheckDiskSpace()) return false; // ********************************************************* Step 2: parameter interactions nNodeLifespan = GetArg("-addrlifespan", 7); nMinStakeInterval = GetArg("-minstakeinterval", 0); nMinerSleep = GetArg("-minersleep", 500); // Largest block you're willing to create. // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity: nBlockMaxSize = GetArg("-blockmaxsize", MAX_BLOCK_SIZE_GEN/2); nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize)); // How much of the block should be dedicated to high-priority transactions, // included regardless of the fees they pay nBlockPrioritySize = GetArg("-blockprioritysize", 27000); nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize); // Minimum block size you want to create; block will be filled with free transactions // until there are no more or the block reaches this size: nBlockMinSize = GetArg("-blockminsize", 0); nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize); // Fee-per-kilobyte amount considered the same as "free" // Be careful setting this: if you set it to zero then // a transaction spammer can cheaply fill blocks using // 1-satoshi-fee transactions. It should be set above the real // cost to you of processing a transaction. if (mapArgs.count("-mintxfee")) ParseMoney(mapArgs["-mintxfee"], nMinTxFee); if (fDebug) LogPrintf("nMinerSleep %u\n", nMinerSleep); CheckpointsMode = Checkpoints::STRICT; std::string strCpMode = GetArg("-cppolicy", "strict"); if (strCpMode == "strict") CheckpointsMode = Checkpoints::STRICT; if (strCpMode == "advisory") CheckpointsMode = Checkpoints::ADVISORY; if (strCpMode == "permissive") CheckpointsMode = Checkpoints::PERMISSIVE; nDerivationMethodIndex = 0; fTestNet = GetBoolArg("-testnet"); if (!SelectParamsFromCommandLine()) return InitError("Invalid combination of -testnet and -regtest."); if (GetBoolArg("-thinmode")) nNodeMode = NT_THIN; if (fTestNet) { SoftSetBoolArg("-irc", true); } if (mapArgs.count("-bind")) { // when specifying an explicit binding address, you want to listen on it // even when -connect or -proxy is specified SoftSetBoolArg("-listen", true); } if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) { // when only connecting to trusted nodes, do not seed via DNS, or listen by default SoftSetBoolArg("-dnsseed", false); SoftSetBoolArg("-listen", false); } if (mapArgs.count("-proxy")) { // to protect privacy, do not listen by default if a proxy server is specified SoftSetBoolArg("-listen", false); } if (!GetBoolArg("-listen", true)) { // do not map ports or try to retrieve public IP when not listening (pointless) SoftSetBoolArg("-upnp", false); SoftSetBoolArg("-discover", false); } if (mapArgs.count("-externalip")) { // if an explicit public IP is specified, do not try to find others SoftSetBoolArg("-discover", false); } if (GetBoolArg("-salvagewallet")) { // Rewrite just private keys: rescan to find transactions SoftSetBoolArg("-rescan", true); } if (fTestNet) { nStakeMinAge = 1 * 60 * 60; // test net min age is 1 hour nCoinbaseMaturity = 10; // test maturity is 10 blocks }; // ********************************************************* Step 3: parameter-to-internal-flags fDebug = !mapMultiArgs["-debug"].empty(); // Special-case: if -debug=0/-nodebug is set, turn off debugging messages const std::vector<std::string>& categories = mapMultiArgs["-debug"]; if (GetBoolArg("-nodebug", false) || std::find(categories.begin(), categories.end(), std::string("0")) != categories.end()) fDebug = false; // -debug implies fDebug*, unless otherwise specified if (fDebug) { SoftSetBoolArg("-debugnet", true); SoftSetBoolArg("-debugsmsg", true); SoftSetBoolArg("-debugchain", true); SoftSetBoolArg("-debugringsig", true); }; fDebugNet = GetBoolArg("-debugnet"); fDebugSmsg = GetBoolArg("-debugsmsg"); fDebugChain = GetBoolArg("-debugchain"); fDebugRingSig = GetBoolArg("-debugringsig"); fDebugPoS = GetBoolArg("-debugpos"); fNoSmsg = GetBoolArg("-nosmsg"); // Check for -socks - as this is a privacy risk to continue, exit here if (mapArgs.count("-socks")) return InitError(_("Error: Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported.")); bitdb.SetDetach(GetBoolArg("-detachdb", false)); if (fDaemon) fServer = true; else fServer = GetBoolArg("-server", false); /* force fServer when running without GUI */ if (!fHaveGUI) fServer = true; fPrintToConsole = GetBoolArg("-printtoconsole"); fPrintToDebugLog = SoftSetBoolArg("-printtodebuglog", true); fLogTimestamps = GetBoolArg("-logtimestamps"); if (mapArgs.count("-timeout")) { int nNewTimeout = GetArg("-timeout", 5000); if (nNewTimeout > 0 && nNewTimeout < 600000) nConnectTimeout = nNewTimeout; }; if (mapArgs.count("-paytxfee")) { if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee)) return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str())); if (nTransactionFee > 0.25 * COIN) InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.")); }; fConfChange = GetBoolArg("-confchange", false); fEnforceCanonical = GetBoolArg("-enforcecanonical", true); if (mapArgs.count("-mininput")) { if (!ParseMoney(mapArgs["-mininput"], nMinimumInputValue)) return InitError(strprintf(_("Invalid amount for -mininput=<amount>: '%s'"), mapArgs["-mininput"].c_str())); }; // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log // Sanity check if (!InitSanityCheck()) return InitError(_("Initialization sanity check failed. PerfectCoin is shutting down.")); std::string strDataDir = GetDataDir().string(); std::string strWalletFileName = GetArg("-wallet", "wallet.dat"); // strWalletFileName must be a plain filename without a directory if (strWalletFileName != fs::basename(strWalletFileName) + fs::extension(strWalletFileName)) return InitError(strprintf(_("Wallet %s resides outside data directory %s."), strWalletFileName.c_str(), strDataDir.c_str())); // Make sure only a single Bitcoin process is using the data directory. fs::path pathLockFile = GetDataDir() / ".lock"; FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist. if (file) fclose(file); static boost::interprocess::file_lock lock(pathLockFile.string().c_str()); if (!lock.try_lock()) return InitError(strprintf(_("Cannot obtain a lock on data directory %s. PerfectCoin is probably already running."), strDataDir.c_str())); if (GetBoolArg("-shrinkdebugfile", !fDebug)) ShrinkDebugFile(); LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); LogPrintf("PerfectCoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str()); LogPrintf("Operating in %s mode.\n", GetNodeModeName(nNodeMode)); LogPrintf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION)); if (!fLogTimestamps) LogPrintf("Startup time: %s\n", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str()); LogPrintf("Default data directory %s\n", GetDefaultDataDir().string().c_str()); LogPrintf("Used data directory %s\n", strDataDir.c_str()); std::ostringstream strErrors; if (fDaemon) { fprintf(stdout, "PerfectCoin server starting\n"); fflush(stdout); }; int64_t nStart; /* ********************************************************* Step 4.5: adjust parameters for nNodeMode ********************************************************* */ switch (nNodeMode) { case NT_FULL: if (GetBoolArg("-nothinssupport")) { LogPrintf("Thin support disabled.\n"); nLocalServices &= ~(THIN_SUPPORT); }; if (GetBoolArg("-nothinstealth")) { LogPrintf("Thin stealth support disabled.\n"); nLocalServices &= ~(THIN_STEALTH); }; break; case NT_THIN: SetBoolArg("-staking", false); // -- clear services nLocalServices &= ~(NODE_NETWORK); nLocalServices &= ~(THIN_SUPPORT); nLocalServices &= ~(THIN_STAKE); nLocalServices &= ~(THIN_STEALTH); nLocalRequirements |= (THIN_SUPPORT); if (GetBoolArg("-thinfullindex")) { LogPrintf("Thin full index enabled.\n"); fThinFullIndex = true; } else { nThinIndexWindow = GetArg("-thinindexmax", 4096); if (nThinIndexWindow < 4096) { LogPrintf("Thin index window minimum size is %d.\n", 4096); nThinIndexWindow = 4096; }; LogPrintf("Thin index window size %d.\n", nThinIndexWindow); }; if (GetBoolArg("-nothinstealth")) { LogPrintf("Thin stealth disabled.\n"); } else { nLocalRequirements |= (THIN_STEALTH); }; break; default: break; }; // -- thin and full if (fNoSmsg) nLocalServices &= ~(SMSG_RELAY); if (initialiseRingSigs() != 0) return InitError("initialiseRingSigs() failed."); // ********************************************************* Step 5: verify database integrity uiInterface.InitMessage(_("Verifying database integrity...")); if (!bitdb.Open(GetDataDir())) { std::string msg = strprintf(_("Error initializing database environment %s!" " To recover, BACKUP THAT DIRECTORY, then remove" " everything from it except for wallet.dat."), strDataDir.c_str()); return InitError(msg); }; if (GetBoolArg("-salvagewallet")) { // Recover readable keypairs: if (!CWalletDB::Recover(bitdb, strWalletFileName, true)) return false; }; if (fs::exists(GetDataDir() / strWalletFileName)) { CDBEnv::VerifyResult r = bitdb.Verify(strWalletFileName, CWalletDB::Recover); if (r == CDBEnv::RECOVER_OK) { std::string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!" " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if" " your balance or transactions are incorrect you should" " restore from a backup."), strDataDir.c_str()); uiInterface.ThreadSafeMessageBox(msg, _("PerfectCoin"), CClientUIInterface::BTN_OK | CClientUIInterface::ICON_WARNING | CClientUIInterface::MODAL); }; if (r == CDBEnv::RECOVER_FAIL) return InitError(_("wallet.dat corrupt, salvage failed")); }; // ********************************************************* Step 6: network initialization nMaxThinPeers = GetArg("-maxthinpeers", 8); nBloomFilterElements = GetArg("-bloomfilterelements", 1536); if (mapArgs.count("-onlynet")) { std::set<enum Network> nets; BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) { enum Network net = ParseNetwork(snet); if (net == NET_UNROUTABLE) return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str())); nets.insert(net); }; for (int n = 0; n < NET_MAX; n++) { enum Network net = (enum Network)n; if (!nets.count(net)) SetLimited(net); }; };
void CrudeMemoryLeakDetection() { _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); _CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_DEBUG ); }
int main(int argc, char *argv[]) { #ifdef _MSC_VER // just for the MS compiler #define WIN_CHECK_LEAKS #endif #ifdef Q_OS_WIN #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) originalMsgHandler = qInstallMsgHandler(fMessageHandler); #else originalMsgHandler = qInstallMessageHandler(fMessageHandler); #endif #ifndef QT_NO_DEBUG #ifdef WIN_CHECK_LEAKS HANDLE hLogFile; QString path = FolderUtils::getUserDataStorePath("") + "/fritzing_leak_log.txt"; std::wstring wstr = path.toStdWString(); LPCWSTR ptr = wstr.c_str(); hLogFile = CreateFile(ptr, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ERROR, hLogFile); _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, hLogFile); _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ASSERT, hLogFile); _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); //_CrtSetBreakAlloc(323809); // sets a break when this memory id is allocated #endif #endif #endif int result = 0; try { //QApplication::setGraphicsSystem("raster"); FApplication * app = new FApplication(argc, argv); if (app->init()) { //DebugDialog::setDebugLevel(DebugDialog::Error); if (app->runAsService()) { // for example: -g C:\Users\jonathan\fritzing2\fz\Test_multiple.fz -go C:\Users\jonathan\fritzing2\fz\gerber result = app->serviceStartup(); if (result == 1) { result = app->exec(); } } else { result = app->startup(); if (result == 0) { result = app->exec(); } } app->finish(); } else { qDebug() << "\n" "Fritzing version " << Version::versionString() << " , Qt version " << QT_VERSION_STR << "\n" "\n" "usage: fritzing [-d] [-f path] filename\n" " fritzing [-f path] -geda folder\n" " fritzing [-f path] -gerber folder\n" " fritzing [-f path] -kicad folder\n" " fritzing [-f path] -kicadschematic folder\n" " fritzing [-f path] -svg folder\n" " fritzing [-f path] -port number\n" "\n" "user options:\n" " d,debug : runs Fritzing in debug mode, providing additional debug information\n" //" drc filename : runs a design rule check on the given sketch file\n" " f,folder : path to folder containing Fritzing parts, sketches, bins, & translations folders}]\n" " geda path : converts all gEDA footprint (.fp) files in folder <path> to Fritzing SVGs}]\n" " g,gerber path : exports all sketches in folder <path> to Gerber, in the same folder\n" " h,help : print this help message\n" " kicad path : converts all Kicad footprint (.mod) files in folder <path> to Fritzing SVGs}]\n" " kicadschematic path: converts all Kicad schematic (.lib) files in folder <path> to Fritzing SVGs}]\n" " port : runs Fritzing as a server process under <port>\n" " svg path : exports all sketches in folder <path> to SVGs of all views, in the same folder\n" "\n" "developer options:\n" " db path : rebuilds the internal parts database at the given path\n" " e,examples path : prepares all sketches in the folder to be included as examples\n" " ep path : external process at <path>\n" " eparg args : external process arguments\n" " epname name : external process menu item name\n" "\n" "The -geda/-kicad/-kicadschematic/-gerber/svg options all exit Fritzing after the conversion process is complete;\n" "these options are mutually exclusive.\n" "\n" "Usually, the Fritzing executable is stored in the same folder that contains the parts/bins/sketches/translations folders,\n" "or the executable is in a child folder of the p/b/s/t folder.\n" "If this is not the case, use the -f option to point to the p/b/s/t folder.\n" "\n" "The -ep option creates a menu item to launch an external process,\n" "and puts the standard output of that process into a dialog window in Fritzing.\n" "The process path follows the -ep argument; the name of the menu item follows the -epname argument;\n" "and any arguments to pass to the external process are provided in the -eparg argments.\n" "\n"; } delete app; } catch (char const *str) { writeCrashMessage(str); } catch (...) { result = -1; } return result; }
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 main(int argc, char **argv) { int ds, dms, ret; double mb; struct timeval t1, t2; #ifndef C_WINDOWS struct timezone tz; sigset_t sigset; #endif struct optstruct *opt; const char *pt; #if defined(C_WINDOWS) && defined(CL_THREAD_SAFE) if(!pthread_win32_process_attach_np()) { mprintf("!Can't start the win32 pthreads layer\n"); return 72; } #endif #if !defined(C_WINDOWS) && !defined(C_BEOS) sigemptyset(&sigset); sigaddset(&sigset, SIGXFSZ); sigprocmask(SIG_SETMASK, &sigset, NULL); #endif opt = opt_parse(argc, argv, clamscan_shortopt, clamscan_longopt, NULL, clamscan_deprecated); if(!opt) { mprintf("!Can't parse the command line\n"); return 40; } if(opt_check(opt, "verbose")) { mprintf_verbose = 1; logg_verbose = 1; } if(opt_check(opt, "quiet")) mprintf_quiet = 1; if(opt_check(opt, "stdout")) mprintf_stdout = 1; if(opt_check(opt, "debug")) { #if defined(C_LINUX) /* [email protected]: create a dump if needed */ struct rlimit rlim; rlim.rlim_cur = rlim.rlim_max = RLIM_INFINITY; if(setrlimit(RLIMIT_CORE, &rlim) < 0) perror("setrlimit"); #endif cl_debug(); /* enable debug messages */ } if(opt_check(opt, "version")) { print_version(opt_arg(opt, "database")); opt_free(opt); return 0; } if(opt_check(opt, "help")) { opt_free(opt); help(); return 0; } if(opt_check(opt, "recursive")) recursion = 1; if(opt_check(opt, "infected")) printinfected = 1; if(opt_check(opt, "bell")) bell = 1; if(opt_check(opt, "tempdir")) cl_settempdir(opt_arg(opt, "tempdir"), 0); if(opt_check(opt, "leave-temps")) cl_settempdir(NULL, 1); /* initialize logger */ if(opt_check(opt, "log")) { logg_file = opt_arg(opt, "log"); if(logg("#\n-------------------------------------------------------------------------------\n\n")) { mprintf("!Problem with internal logger.\n"); opt_free(opt); return 62; } } else logg_file = NULL; /* validate some numerical options */ if(opt_check(opt, "max-scansize")) { pt = opt_arg(opt, "max-scansize"); if(!strchr(pt, 'M') && !strchr(pt, 'm')) { if(!cli_isnumber(pt)) { logg("!--max-scansize requires a natural number\n"); opt_free(opt); return 40; } } } if(opt_check(opt, "max-filesize")) { pt = opt_arg(opt, "max-filesize"); if(!strchr(pt, 'M') && !strchr(pt, 'm')) { if(!cli_isnumber(pt)) { logg("!--max-filesize requires a natural number\n"); opt_free(opt); return 40; } } } if(opt_check(opt, "max-files")) { if(!cli_isnumber(opt_arg(opt, "max-files"))) { logg("!--max-files requires a natural number\n"); opt_free(opt); return 40; } } if(opt_check(opt, "max-recursion")) { if(!cli_isnumber(opt_arg(opt, "max-recursion"))) { logg("!--max-recursion requires a natural number\n"); opt_free(opt); return 40; } } if(opt_check(opt, "max-mail-recursion")) { if(!cli_isnumber(opt_arg(opt, "max-mail-recursion"))) { logg("!--max-mail-recursion requires a natural number\n"); opt_free(opt); return 40; } } if(opt_check(opt, "max-dir-recursion")) { if(!cli_isnumber(opt_arg(opt, "max-dir-recursion"))) { logg("!--max-dir-recursion requires a natural number\n"); opt_free(opt); return 40; } } if(opt_check(opt, "max-ratio")) { if(!cli_isnumber(opt_arg(opt, "max-ratio"))) { logg("!--max-ratio requires a natural number\n"); opt_free(opt); return 40; } } memset(&info, 0, sizeof(struct s_info)); #ifdef _WIN32 SetConsoleCtrlHandler((PHANDLER_ROUTINE) clamscan_ctrl_handler, TRUE); #endif #ifdef C_WINDOWS _set_fmode(_O_BINARY); #ifdef CL_DEBUG { _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR); } #endif gettimeofday(&t1, NULL); #else gettimeofday(&t1, &tz); #endif ret = scanmanager(opt); if(!opt_check(opt, "disable-summary") && !opt_check(opt, "no-summary")) { #ifdef C_WINDOWS gettimeofday(&t2, NULL); #else gettimeofday(&t2, &tz); #endif ds = t2.tv_sec - t1.tv_sec; dms = t2.tv_usec - t1.tv_usec; ds -= (dms < 0) ? (1):(0); dms += (dms < 0) ? (1000000):(0); logg("\n----------- SCAN SUMMARY -----------\n"); logg("Known viruses: %u\n", info.sigs); logg("Engine version: %s\n", get_version()); logg("Scanned directories: %u\n", info.dirs); logg("Scanned files: %u\n", info.files); logg("Infected files: %u\n", info.ifiles); if(info.notremoved) { logg("Not removed: %u\n", info.notremoved); } if(info.notmoved) { logg("Not %s: %u\n", opt_check(opt, "copy") ? "moved" : "copied", info.notmoved); } mb = info.blocks * (CL_COUNT_PRECISION / 1024) / 1024.0; logg("Data scanned: %2.2lf MB\n", mb); logg("Time: %u.%3.3u sec (%u m %u s)\n", ds, dms/1000, ds/60, ds%60); } opt_free(opt); #if defined(C_WINDOWS) && defined(CL_THREAD_SAFE) if(!pthread_win32_process_detach_np()) { logg("!Can't stop the win32 pthreads layer\n"); return 72; } #endif return ret; }
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); DBUG_ENTER("my_end"); if (!info_file) { info_file= stderr; print_info= 0; } DBUG_PRINT("info",("Shutting down: print_info: %d", print_info)); if ((infoflag & MY_CHECK_ERROR) || print_info) { /* Test if some file is left open */ if (my_file_opened | my_stream_opened) { sprintf(errbuff[0],EE(EE_OPEN_WARNING),my_file_opened,my_stream_opened); (void) my_message_no_curses(EE_OPEN_WARNING,errbuff[0],ME_BELL); DBUG_PRINT("error",("%s",errbuff[0])); } } free_charsets(); 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(MSDOS) || defined(__NETWARE__) ) && !defined(__WIN__) fprintf(info_file,"\nRun time: %.1f\n",(double) clock()/CLOCKS_PER_SEC); #endif #if defined(SAFEMALLOC) TERMINATE(stderr); /* Give statistic on screen */ #elif 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 } #ifdef THREAD DBUG_POP(); /* 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 ? stderr : (FILE *) 0); #endif /* defined(SAFE_MUTEX) */ #endif /* THREAD */ #ifdef __WIN__ if (have_tcpip) WSACleanup(); #endif /* __WIN__ */ my_init_done=0; } /* my_end */
bool AppInit2(int argc, char* argv[]) { #ifdef _MSC_VER // Turn off microsoft heap dump noise _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0)); #endif #if _MSC_VER >= 1400 // Disable confusing "helpful" text message on abort, ctrl-c _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); #endif #ifndef __WXMSW__ umask(077); #endif #ifndef __WXMSW__ // Clean shutdown on SIGTERM struct sigaction sa; sa.sa_handler = HandleSIGTERM; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(SIGTERM, &sa, NULL); #endif // // Parameters // ParseParameters(argc, argv); if (mapArgs.count("-datadir")) { filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]); strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir)); } ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir if (mapArgs.count("-?") || mapArgs.count("--help")) { string strUsage = string() + _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" + " bitcoin [options] \t " + "\n" + " bitcoin [options] <command> [params]\t " + _("Send command to -server or bitcoind\n") + " bitcoin [options] help \t\t " + _("List commands\n") + " bitcoin [options] help <command> \t\t " + _("Get help for a command\n") + _("Options:\n") + " -conf=<file> \t\t " + _("Specify configuration file (default: bitcoin.conf)\n") + " -gen \t\t " + _("Generate coins\n") + " -gen=0 \t\t " + _("Don't generate coins\n") + " -min \t\t " + _("Start minimized\n") + " -datadir=<dir> \t\t " + _("Specify data directory\n") + " -proxy=<ip:port> \t " + _("Connect through socks4 proxy\n") + " -addnode=<ip> \t " + _("Add a node to connect to\n") + " -connect=<ip> \t\t " + _("Connect only to the specified node\n") + " -paytxfee=<amt> \t " + _("Fee per KB to add to transactions you send\n") + " -server \t\t " + _("Accept command line and JSON-RPC commands\n") + " -daemon \t\t " + _("Run in the background as a daemon and accept commands\n") + " -testnet \t\t " + _("Use the test network\n") + " -rpcuser=<user> \t " + _("Username for JSON-RPC connections\n") + " -rpcpassword=<pw>\t " + _("Password for JSON-RPC connections\n") + " -rpcport=<port> \t\t " + _("Listen for JSON-RPC connections on <port>\n") + " -rpcallowip=<ip> \t\t " + _("Allow JSON-RPC connections from specified IP address\n") + " -rpcconnect=<ip> \t " + _("Send commands to node running on <ip>\n"); #ifdef USE_SSL strUsage += string() + _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)\n") + " -rpcssl=1 \t " + _("Use OpenSSL (https) for JSON-RPC connections\n") + " -rpcsslcertificatchainfile=<file.cert>\t " + _("Server certificate file (default: server.cert)\n") + " -rpcsslprivatekeyfile=<file.pem> \t " + _("Server private key (default: server.pem)\n") + " -rpcsslciphers=<ciphers> \t " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)\n"); #endif strUsage += string() + " -? \t\t " + _("This help message\n"); #if defined(__WXMSW__) && defined(GUI) // Tabs make the columns line up in the message box wxMessageBox(strUsage, "Bitcoin", wxOK); #else // Remove tabs strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end()); fprintf(stderr, "%s", strUsage.c_str()); #endif return false; } fDebug = GetBoolArg("-debug"); fPrintToDebugger = GetBoolArg("-printtodebugger"); fTestNet = GetBoolArg("-testnet"); if (fCommandLine) { int ret = CommandLineRPC(argc, argv); exit(ret); } if (!fDebug && !pszSetDataDir[0]) ShrinkDebugFile(); printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); printf("Bitcoin version %s%s beta\n", FormatVersion(VERSION).c_str(), pszSubVer); #ifdef GUI printf("OS version %s\n", ((string)wxGetOsDescription()).c_str()); printf("System default language is %d %s\n", g_locale.GetSystemLanguage(), ((string)g_locale.GetSysName()).c_str()); printf("Language file %s (%s)\n", (string("locale/") + (string)g_locale.GetCanonicalName() + "/LC_MESSAGES/bitcoin.mo").c_str(), ((string)g_locale.GetLocale()).c_str()); #endif printf("Default data directory %s\n", GetDefaultDataDir().c_str()); if (GetBoolArg("-loadblockindextest")) { CTxDB txdb("r"); txdb.LoadBlockIndex(); PrintBlockTree(); return false; } // // Limit to single instance per user // Required to protect the database files if we're going to keep deleting log.* // #if defined(__WXMSW__) && defined(GUI) // wxSingleInstanceChecker doesn't work on Linux wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH"); for (int i = 0; i < strMutexName.size(); i++) if (!isalnum(strMutexName[i])) strMutexName[i] = '.'; wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName); if (psingleinstancechecker->IsAnotherRunning()) { printf("Existing instance found\n"); unsigned int nStart = GetTime(); loop { // Show the previous instance and exit HWND hwndPrev = FindWindowA("wxWindowClassNR", "Bitcoin"); if (hwndPrev) { if (IsIconic(hwndPrev)) ShowWindow(hwndPrev, SW_RESTORE); SetForegroundWindow(hwndPrev); return false; } if (GetTime() > nStart + 60) return false; // Resume this instance if the other exits delete psingleinstancechecker; Sleep(1000); psingleinstancechecker = new wxSingleInstanceChecker(strMutexName); if (!psingleinstancechecker->IsAnotherRunning()) break; } }
/* Format a time value into a buffer. Same semantics as strftime() */ size_t PRMJ_FormatTime(char *buf, int buflen, const char *fmt, PRMJTime *prtm) { size_t result = 0; #if defined(XP_UNIX) || defined(XP_WIN) || defined(XP_OS2) struct tm a; int fake_tm_year = 0; #ifdef NS_HAVE_INVALID_PARAMETER_HANDLER _invalid_parameter_handler oldHandler; int oldReportMode; #endif memset(&a, 0, sizeof(struct tm)); a.tm_sec = prtm->tm_sec; a.tm_min = prtm->tm_min; a.tm_hour = prtm->tm_hour; a.tm_mday = prtm->tm_mday; a.tm_mon = prtm->tm_mon; a.tm_wday = prtm->tm_wday; /* * On systems where |struct tm| has members tm_gmtoff and tm_zone, we * must fill in those values, or else strftime will return wrong results * (e.g., bug 511726, bug 554338). */ #if defined(HAVE_LOCALTIME_R) && defined(HAVE_TM_ZONE_TM_GMTOFF) { /* * Fill out |td| to the time represented by |prtm|, leaving the * timezone fields zeroed out. localtime_r will then fill in the * timezone fields for that local time according to the system's * timezone parameters. */ struct tm td; memset(&td, 0, sizeof(td)); td.tm_sec = prtm->tm_sec; td.tm_min = prtm->tm_min; td.tm_hour = prtm->tm_hour; td.tm_mday = prtm->tm_mday; td.tm_mon = prtm->tm_mon; td.tm_wday = prtm->tm_wday; td.tm_year = prtm->tm_year - 1900; td.tm_yday = prtm->tm_yday; td.tm_isdst = prtm->tm_isdst; time_t t = mktime(&td); localtime_r(&t, &td); a.tm_gmtoff = td.tm_gmtoff; a.tm_zone = td.tm_zone; } #endif /* * Years before 1900 and after 9999 cause strftime() to abort on Windows. * To avoid that we replace it with FAKE_YEAR_BASE + year % 100 and then * replace matching substrings in the strftime() result with the real year. * Note that FAKE_YEAR_BASE should be a multiple of 100 to make 2-digit * year formats (%y) work correctly (since we won't find the fake year * in that case). * e.g. new Date(1873, 0).toLocaleFormat('%Y %y') => "1873 73" * See bug 327869. */ #define FAKE_YEAR_BASE 9900 if (prtm->tm_year < 1900 || prtm->tm_year > 9999) { fake_tm_year = FAKE_YEAR_BASE + prtm->tm_year % 100; a.tm_year = fake_tm_year - 1900; } else { a.tm_year = prtm->tm_year - 1900; } a.tm_yday = prtm->tm_yday; a.tm_isdst = prtm->tm_isdst; /* * Even with the above, SunOS 4 seems to detonate if tm_zone and tm_gmtoff * are null. This doesn't quite work, though - the timezone is off by * tzoff + dst. (And mktime seems to return -1 for the exact dst * changeover time.) */ #ifdef NS_HAVE_INVALID_PARAMETER_HANDLER oldHandler = _set_invalid_parameter_handler(PRMJ_InvalidParameterHandler); oldReportMode = _CrtSetReportMode(_CRT_ASSERT, 0); #endif result = strftime(buf, buflen, fmt, &a); #ifdef NS_HAVE_INVALID_PARAMETER_HANDLER _set_invalid_parameter_handler(oldHandler); _CrtSetReportMode(_CRT_ASSERT, oldReportMode); #endif if (fake_tm_year && result) { char real_year[16]; char fake_year[16]; size_t real_year_len; size_t fake_year_len; char* p; sprintf(real_year, "%d", prtm->tm_year); real_year_len = strlen(real_year); sprintf(fake_year, "%d", fake_tm_year); fake_year_len = strlen(fake_year); /* Replace the fake year in the result with the real year. */ for (p = buf; (p = strstr(p, fake_year)); p += real_year_len) { size_t new_result = result + real_year_len - fake_year_len; if ((int)new_result >= buflen) { return 0; } memmove(p + real_year_len, p + fake_year_len, strlen(p + fake_year_len)); memcpy(p, real_year, real_year_len); result = new_result; *(buf + result) = '\0'; } } #endif return result; }
int main(int ac, char *av[]) { int errorn; long total_output_spks; double input_traject_vars[NUM_JOINTS*3]; // Desired trajectory position, velocity and acceletarion double robot_state_vars[NUM_JOINTS*3]; // Actual robot position, velocity and acceleration double cerebellar_output_vars[NUM_OUTPUT_VARS]={0.0}; // Corrective cerebellar output torque double robot_inv_dyn_torque[NUM_JOINTS]; // Robot's inverse dynamics torque double total_torque[NUM_JOINTS]; // Total torque applied to the robot double *delayed_error_vars; double robot_error_vars[NUM_JOINTS]; // Joint error (PD correction) double cerebellar_learning_vars[NUM_OUTPUT_VARS]; // Error-related learning signals // Robot's dynamics variables mxArray *robot_inv_dyn_object=NULL, *robot_dir_dyn_object=NULL; struct integrator_buffers num_integration_buffers; // Integration buffers used to simulate the robot Simulation *neural_sim; int n_robot_joints; // Time variables double sim_time,cur_traject_time; float slot_elapsed_time,sim_elapsed_time; int n_traj_exec; // Delay line struct delay error_delay; // Variable for logging the simulation state variables struct log var_log; #if defined(REAL_TIME_WINNT) // Variables for consumed-CPU-time measurement LARGE_INTEGER startt,endt,freq; #elif defined(REAL_TIME_OSX) uint64_t startt, endt, elapsed; static mach_timebase_info_data_t freq; #elif defined(REAL_TIME_LINUX) // Calculate time taken by a request - Link with real-time library -lrt struct timespec startt, endt, freq; #endif #if defined(_DEBUG) && (defined(_WIN32) || defined(_WIN64)) // _CrtMemState state0; _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); #endif #if defined(REAL_TIME_WINNT) if(!QueryPerformanceFrequency(&freq)) puts("QueryPerformanceFrequency failed"); #elif defined (REAL_TIME_LINUX) if(clock_getres(CLOCK_REALTIME, &freq)) puts("clock_getres failed"); #elif defined (REAL_TIME_OSX) // If this is the first time we've run, get the timebase. // We can use denom == 0 to indicate that sTimebaseInfo is // uninitialised because it makes no sense to have a zero // denominator is a fraction. if (freq.denom == 0 ) { (void) mach_timebase_info(&freq); } #endif // Load Matlab robot objects from Matlab files if(!(errorn=load_robot(ROBOT_VAR_FILE_NAME,ROBOT_BASE_VAR_NAME,&n_robot_joints,&robot_inv_dyn_object)) && \ !(errorn=load_robot(ROBOT_VAR_FILE_NAME,ROBOT_SIMUL_VAR_NAME,NULL,&robot_dir_dyn_object))) { if(!(errorn=allocate_integration_buffers(&num_integration_buffers,n_robot_joints))) // Initialize the buffers for numerical integration using the initial desired robot's state { // Initialize variable log if(!(errorn=create_log(&var_log, MAX_TRAJ_EXECUTIONS, TRAJECTORY_TIME))) { // Initialize EDLUT and load neural network files neural_sim=create_neural_simulation(NET_FILE, INPUT_WEIGHT_FILE, INPUT_ACTIVITY_FILE, OUTPUT_WEIGHT_FILE, OUTPUT_ACTIVITY_FILE, WEIGHT_SAVE_PERIOD, REAL_TIME_NEURAL_SIM); if(neural_sim) { double min_traj_amplitude[3], max_traj_amplitude[3]; // Position, velocity and acceleration calculate_input_trajectory_max_amplitude(TRAJECTORY_TIME,TRAJ_POS_AMP, min_traj_amplitude, max_traj_amplitude); // Calcula the maximum and minimum values of the desired trajectory total_output_spks=0L; puts("Simulating..."); sim_elapsed_time=0.0; errorn=0; // _CrtMemCheckpoint(&state0); for(n_traj_exec=0;n_traj_exec<MAX_TRAJ_EXECUTIONS && !errorn;n_traj_exec++) { calculate_input_trajectory(robot_state_vars, TRAJ_POS_AMP, 0.0); // Initialize simulated robot's actual state from the desired state (input trajectory) (position, velocity and acceleration) initialize_integration_buffers(robot_state_vars,&num_integration_buffers,n_robot_joints); // For the robot's direct reset_neural_simulation(neural_sim); // after each trajectory execution the network simulation state must be reset (pending activity events are discarded) init_delay(&error_delay, ERROR_DELAY_TIME); // Clear the delay line cur_traject_time=0.0; do { int n_joint; #if defined(REAL_TIME_WINNT) QueryPerformanceCounter(&startt); #elif defined(REAL_TIME_LINUX) clock_gettime(CLOCK_REALTIME, &startt); #elif defined(REAL_TIME_OSX) startt = mach_absolute_time(); #endif // control loop iteration starts sim_time=(double)n_traj_exec*TRAJECTORY_TIME + cur_traject_time; // Calculate absolute simulation time calculate_input_trajectory(input_traject_vars, TRAJ_POS_AMP, cur_traject_time); // Calculate desired input trajectory //ECEA generate_input_traj_activity(neural_sim, sim_time, input_traject_vars, min_traj_amplitude, max_traj_amplitude); // Translates desired trajectory (position and velocity) into spikes generate_robot_state_activity(neural_sim, sim_time, input_traject_vars, min_traj_amplitude, max_traj_amplitude); // Translates desired trajectory into spikes again to improve the input codification (using the robot's state input neurons) //ICEA // generate_robot_state_activity(neural_sim, sim_time, robot_state_vars, min_traj_amplitude, max_traj_amplitude); // Translates robot's current state (position and velocity) into spikes compute_robot_inv_dynamics(robot_inv_dyn_object,input_traject_vars,ROBOT_EXTERNAL_FORCE,ROBOT_GRAVITY,robot_inv_dyn_torque); // Calculate crude inverse dynamics of the base robot. They constitude the base robot's input torque for(n_joint=0;n_joint<NUM_JOINTS;n_joint++) // Calculate total torque from forward controller (cerebellum) torque plus base controller torque total_torque[n_joint]=robot_inv_dyn_torque[n_joint]+cerebellar_output_vars[n_joint*2]-cerebellar_output_vars[n_joint*2+1]; compute_robot_dir_dynamics(robot_dir_dyn_object,robot_state_vars,total_torque,robot_state_vars,&num_integration_buffers,ROBOT_EXTERNAL_FORCE,ROBOT_GRAVITY,SIM_SLOT_LENGTH); // Simulate the robot (direct dynamics). calculate_error_signals(input_traject_vars, robot_state_vars, robot_error_vars); // Calculated robot's performed error //delayed_error_vars=delay_line(&error_delay,robot_error_vars); // Delay in the error bars delayed_error_vars=robot_error_vars; // No delay in the error bars calculate_learning_signals(delayed_error_vars, cerebellar_output_vars, cerebellar_learning_vars); // Calculate learning signal from the calculated error generate_learning_activity(neural_sim, sim_time, cerebellar_learning_vars); // Translates the learning activity into spikes and injects this activity in the network errorn=run_neural_simulation_slot(neural_sim, sim_time+SIM_SLOT_LENGTH); // Simulation the neural network during a time slot total_output_spks+=(long)compute_output_activity(neural_sim, cerebellar_output_vars); // Translates cerebellum output activity into analog output variables (corrective torques) // control loop iteration ends #if defined(REAL_TIME_WINNT) QueryPerformanceCounter(&endt); // measures time slot_elapsed_time=(endt.QuadPart-startt.QuadPart)/(float)freq.QuadPart; // to be logged #elif defined(REAL_TIME_LINUX) clock_gettime(CLOCK_REALTIME, &endt); // Calculate time it took slot_elapsed_time = (endt.tv_sec-startt.tv_sec ) + (endt.tv_nsec-endt.tv_nsec )/((float)(1e9)); #elif defined(REAL_TIME_OSX) // Stop the clock. endt = mach_absolute_time(); // Calculate the duration. elapsed = endt - startt; slot_elapsed_time = 1e-9 * elapsed * freq.numer / freq.denom; #endif sim_elapsed_time+=slot_elapsed_time; log_vars(&var_log, sim_time, input_traject_vars, robot_state_vars, robot_inv_dyn_torque, cerebellar_output_vars, cerebellar_learning_vars, delayed_error_vars, slot_elapsed_time,get_neural_simulation_spike_counter(neural_sim)); // Store vars into RAM cur_traject_time+=SIM_SLOT_LENGTH; } while(cur_traject_time<TRAJECTORY_TIME-(SIM_SLOT_LENGTH/2.0) && !errorn); // we add -(SIM_SLOT_LENGTH/2.0) because of floating-point-type codification problems } // reset_neural_simulation(neural_sim); // _CrtMemDumpAllObjectsSince(&state0); if(errorn) printf("Error %i performing neural network simulation\n",errorn); printf("Total neural-network output spikes: %li\n",total_output_spks); printf("Total number of neural updates: %Ld\n",get_neural_simulation_event_counter(neural_sim)); printf("Mean number of neural-network spikes in heap: %f\n",get_accumulated_heap_occupancy_counter(neural_sim)/(double)get_neural_simulation_event_counter(neural_sim)); #if defined(REAL_TIME_WINNT) printf("Total elapsed time: %fs (time resolution: %fus)\n",sim_elapsed_time,1.0e6/freq.QuadPart); #elif defined(REAL_TIME_LINUX) printf("Total elapsed time: %fs (time resolution: %fus)\n",sim_elapsed_time,freq.tv_sec*1.0e6+freq.tv_nsec/((float)(1e3))); #elif defined(REAL_TIME_OSX) printf("Total elapsed time: %fs (time resolution: %fus)\n",sim_elapsed_time,1e-3*freq.numer/freq.denom); #endif save_neural_weights(neural_sim); finish_neural_simulation(neural_sim); } else { errorn=10000; printf("Error initializing neural network simulation\n"); } puts("Saving log file"); errorn=save_and_finish_log(&var_log, LOG_FILE); // Store logged vars in disk if(errorn) printf("Error %i while saving log file\n",errorn); } else { errorn*=1000; printf("Error allocating memory for the log of the simulation variables\n"); } free_integration_buffers(&num_integration_buffers); } else { errorn*=100; printf("Error allocating memory for the numerical integration\n"); } free_robot(robot_inv_dyn_object); free_robot(robot_dir_dyn_object); } else { errorn*=10; printf("Error loading the robot object from file: %s\n",ROBOT_VAR_FILE_NAME); } if(!errorn) puts("OK"); else printf("Error: %i\n",errorn); #if defined(_DEBUG) && (defined(_WIN32) || defined(_WIN64)) _CrtDumpMemoryLeaks(); #endif return(errorn); }
int main(int argc, char **argv) { #ifdef WIN32 // Send all reports to STDOUT _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 ); // enable the options SET_CRT_DEBUG_FIELD( _CRTDBG_DELAY_FREE_MEM_DF ); SET_CRT_DEBUG_FIELD( _CRTDBG_LEAK_CHECK_DF ); #endif printf("int %d, short int %d, char %d, double %d, float %d, node %d\n",sizeof(int),sizeof(short int), sizeof(char), sizeof(double), sizeof(float), sizeof(svm_node)); char input_file_name[FILENAME_LEN]; char model_file_name[FILENAME_LEN]; const char *error_msg; parse_command_line(argc, argv, input_file_name, model_file_name); read_problem(input_file_name); param.modelFile = model_file_name; printf ("Finish reading input files!\n"); error_msg = svm_check_parameter(&prob,¶m); #ifdef WIN32 assert(_CrtCheckMemory()); #endif if(error_msg) { fprintf(stderr,"Error: %s\n",error_msg); exit(1); } double duration; double start = getRunTime(); if(cross_validation) { do_cross_validation(); } else { printf("kernel: %d\n",param.kernel_type); model = svm_train(&prob,¶m); double finish = getRunTime(); duration = (double)(finish - start); #ifdef WIN32 assert(_CrtCheckMemory()); #endif svm_save_model(model_file_name,model); svm_destroy_model(model); } printf("CPU Time = %f second\n", duration); FILE* fModel = fopen(model_file_name, "a+t"); // append mode fprintf(fModel, "CPU Time = %f second\n", duration); fclose(fModel); svm_destroy_param(¶m); free(prob.y); free(prob.x); free(x_space); #ifdef WIN32 assert(_CrtCheckMemory()); #endif return 0; }
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) { #if defined _DEBUG _CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF | _CRTDBG_ALLOC_MEM_DF); _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); #endif MSG msg = {0}; WNDCLASSEX wcl = {0}; wcl.cbSize = sizeof(wcl); wcl.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW; wcl.lpfnWndProc = WindowProc; wcl.cbClsExtra = 0; wcl.cbWndExtra = 0; wcl.hInstance = g_hInstance = hInstance; wcl.hIcon = LoadIcon(0, IDI_APPLICATION); wcl.hCursor = LoadCursor(0, IDC_ARROW); wcl.hbrBackground = 0; wcl.lpszMenuName = 0; wcl.lpszClassName = "GLWindowClass"; wcl.hIconSm = 0; if (!RegisterClassEx(&wcl)) return 0; g_hWnd = CreateAppWindow(wcl, 0); if (g_hWnd) { InitGL(); ToggleFullScreen(); glDisable(GL_MULTISAMPLE_ARB); ShowWindow(g_hWnd, nShowCmd); UpdateWindow(g_hWnd); while (true) { while (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) { if (msg.message == WM_QUIT) break; TranslateMessage(&msg); DispatchMessage(&msg); } if (msg.message == WM_QUIT) break; if (keys[VK_ESCAPE]) { msg.message = WM_QUIT ; } if (g_hasFocus) { RenderGL(); SwapBuffers(g_hDC); ProcessKeyboard(); } else { WaitMessage(); } } Cleanup(); UnregisterClass(wcl.lpszClassName, hInstance); } return static_cast<int>(msg.wParam); }
int main() { _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_CHECK_ALWAYS_DF | _CRTDBG_CHECK_CRT_DF | _CRTDBG_LEAK_CHECK_DF | _CRTDBG_CHECK_EVERY_16_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); _CrtMemState s1, s2, s3; _CrtMemCheckpoint(&s1); ExePath(); //////////// most common way to use licensing module //// { time_t LicenseRemainingTime; time_t GracePeriodRemainingTime; int GraceStatusCode; int LicenseCheckRes = GetRemainingTime(&LicenseRemainingTime, &GracePeriodRemainingTime, &GraceStatusCode); if (LicenseCheckRes != 0 || (LicenseRemainingTime == 0 && GracePeriodRemainingTime == 0)) { printf("LicenseCheckRes %d", LicenseCheckRes); printf("LicenseRemainingTime %d", (int)LicenseRemainingTime); printf("GracePeriodRemainingTime %d", (int)GracePeriodRemainingTime); } char ActivationKeyBuffer[200]; int GetKeyRes = GetActivationKey(ALMA, ALMA_KPI, ActivationKeyBuffer, sizeof(ActivationKeyBuffer)); if (GetKeyRes == 0) printf("For project ALMA and Feature KPI we obtained activation key '%s'\n", ActivationKeyBuffer); else printf("License did not contain a valid activation key\n"); } //////////// most common way to use licensing module //// ///////////////////////////////////////// get the key using class //////////////////////////////////// //create a license License *TestLicense = new License; //TestLicense->SaveToFile("t.t", "LicenseSeed.dat"); if (TestLicense == NULL) { printf("Unexpected error: feature list object is NULL\n"); return 1; } //for testing, load up the saved license and check if we can extract feature keys printf("Load license into temp buffer\n"); int er = TestLicense->LoadFromFile("../License.dat"); if (er != 0) { printf("Error %d while loading license. Please solve it to continue\n",er); delete TestLicense; _getch(); return 1; } printf("Seach for activation key inside license\n"); //find the key we need to activate a feature char ActivationKeyBuffer[200]; int GetKeyRes = TestLicense->GetActivationKey(ALMA, ALMA_KPI, ActivationKeyBuffer, sizeof(ActivationKeyBuffer)); //this is for debugging only, you should not need to check for return value inside siemens projects. Hacker might be able to intercept the event and track the variable used for the activation key if (GetKeyRes == 0) printf("For project ALMA and Feature KPI we obtained activation key '%s'\n", ActivationKeyBuffer); else printf("License did not contain a valid activation key\n"); //cleanup delete TestLicense; ///////////////////////////////////////// get the key using class //////////////////////////////////// ///////////////////////////////////////// get the key in an async way //////////////////////////////////// /* GetActivationKeyAsync(ALMA, ALMA_KPI, &HandleAsyncKeyAssignCallback); while (ReceivedCallback==0) Sleep(10); printf("For project ALMA and Feature KPI we obtained activation key '%s'\n", GlobalKeyStoreTestCallback); printf("\n\nAll done. Push a key to exit."); _getch();*/ ///////////////////////////////////////// get the key in an async way //////////////////////////////////// ///////////////////////////////////////// simulate HW failure. Test Grace period //////////////////////////////////// // !! in previous tests we made a successfull query for an activation key. // Grace period should be initialized at this point and even if fingerprint is no longer valid, it should trigger grace period and allow us to gte the key TestLicense = new License; er = TestLicense->LoadFromFile("../License.dat", "../License.dat"); // !! we are loading a bad file as fingerprint !! if (er == 0) { // int GracePeriodTriggered; // int erGraceCall = IsLicenseInGracePeriod(&GracePeriodTriggered); char ActivationKeyBuffer[200]; int GetKeyRes = TestLicense->GetActivationKey(ALMA, ALMA_KPI, ActivationKeyBuffer, sizeof(ActivationKeyBuffer)); //this is for debugging only, you should not need to check for return value inside siemens projects. Hacker might be able to intercept the event and track the variable used for the activation key if (GetKeyRes == 0) printf("Tested bad hardware configuration license check. Got key '%s'\n", ActivationKeyBuffer); } else printf("!!Load error\n"); delete TestLicense; TestLicense = NULL; ///////////////////////////////////////// simulate HW failure. Test Grace period //////////////////////////////////// ///////////////////////////////////////// simulate license expire. Test Grace period //////////////////////////////////// TestLicense = new License; er = TestLicense->LoadFromFile("../License.dat"); //set license expiration to a very short interval TestLicense->SetDuration(time(NULL), 1, 5 * 60); //wait for the license to expire Sleep(1000); //check if we can query an activation key. It should succeed as we are in grace period time_t GracePeriodTriggered; char IsGraceTriggered; GetKeyRes = TestLicense->IsGracePeriodTriggered(&GracePeriodTriggered, &IsGraceTriggered); GetKeyRes = TestLicense->GetActivationKey(ALMA, ALMA_KPI, ActivationKeyBuffer, sizeof(ActivationKeyBuffer)); //this is for debugging only, you should not need to check for return value inside siemens projects. Hacker might be able to intercept the event and track the variable used for the activation key if (GetKeyRes == 0) printf("Got key '%s'. Grace period is triggered %d\n", ActivationKeyBuffer, GracePeriodTriggered); //make the license be valid again TestLicense->SetDuration(time(NULL), 10000, 5 * 60); //query an activation key to force grace period to get disabled GetKeyRes = TestLicense->GetActivationKey(ALMA, ALMA_KPI, ActivationKeyBuffer, sizeof(ActivationKeyBuffer)); //make license expire more than max grace period TestLicense->SetDuration(time(NULL) - MAX_GRACE_PERIOD_SECONDS, 1, 1); //wait for the license to expire Sleep(1000); //query an activation key. It should fail as grace period ended GetKeyRes = TestLicense->IsGracePeriodTriggered(&GracePeriodTriggered, &IsGraceTriggered); if (GetKeyRes != 0) printf("Error obtaining grace data %d\n", GetKeyRes); GetKeyRes = TestLicense->GetActivationKey(ALMA, ALMA_KPI, ActivationKeyBuffer, sizeof(ActivationKeyBuffer)); //this is for debugging only, you should not need to check for return value inside siemens projects. Hacker might be able to intercept the event and track the variable used for the activation key if (GetKeyRes == WARNING_NO_LICENSE_FOUND) printf("Could not obtain license. Expected behavior as grace period expired. Status %d\n", GracePeriodTriggered); delete TestLicense; TestLicense = NULL; ///////////////////////////////////////// simulate license expire. Test Grace period //////////////////////////////////// ///////////////////////////////////////// simulate bad license file content and check error proofness //////////////////////////////////// #ifdef _DEBUG EnableErrorTests(); for (int i = 0; i < 201; i++) // the 500 is a fictional number, should know the sizeo of the license file { GetKeyRes = GetActivationKey(ALMA, ALMA_KPI, ActivationKeyBuffer, sizeof(ActivationKeyBuffer)); printf("Corrupting byte %d from license file. Got result '%s'\n", i, ActivationKeyBuffer); } #endif ///////////////////////////////////////// simulate bad license file content and check error proofness //////////////////////////////////// printf("\n\nAll done. Push a key to continue.\n"); _getch(); _CrtMemCheckpoint(&s2); if (_CrtMemDifference(&s3, &s1, &s2) && (s3.lCounts[0]>0 || s3.lCounts[1] > 0 || s3.lCounts[3] > 0 || s3.lCounts[3] > 0)) //ignore CRT block allocs, can't do much about them. Some come from printf... { _CrtMemDumpStatistics(&s3); printf("!!Memory issues detected. Investigate !\n"); _getch(); } _CrtCheckMemory(); _CrtDumpMemoryLeaks(); return 0; }
int main(int argc, wchar_t* argv[]) { static_assert(sizeof(void*) == 4, "64-bit code generation is not supported."); SetUnhandledExceptionFilter(UserUnhandledExceptionFilter); std::wcout << L"Type \"q\" to close application." << std::endl; // Set debug mode. #ifdef _DEBUG _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF | _CRTDBG_CHECK_ALWAYS_DF ); _CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_DEBUG ); _CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_DEBUG ); _CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_DEBUG ); #endif // Increase process priotity. SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS); // Install structured exception handler. caspar::win32_exception::install_handler(); caspar::log::set_log_level(L"debug"); // Increase time precision. This will increase accuracy of function like Sleep(1) from 10 ms to 1 ms. struct inc_prec { inc_prec(){timeBeginPeriod(1);} ~inc_prec(){timeEndPeriod(1);} } inc_prec; // Install unstructured exception handlers into all tbb threads. struct tbb_thread_installer : public tbb::task_scheduler_observer { tbb_thread_installer(){observe(true);} void on_scheduler_entry(bool is_worker) { //caspar::detail::SetThreadName(GetCurrentThreadId(), "tbb-worker-thread"); caspar::win32_exception::install_handler(); } } tbb_thread_installer; tbb::task_scheduler_init init; try { { // Configure environment properties from configuration. caspar::env::configure("casparcg.config"); #ifdef _DEBUG if(caspar::env::properties().get("configuration.debugging.remote", false)) MessageBox(nullptr, TEXT("Now is the time to connect for remote debugging..."), TEXT("Debug"), MB_OK | MB_TOPMOST); #endif // Start logging to file. caspar::log::add_file_sink(caspar::env::log_folder()); std::wcout << L"Logging [info] or higher severity to " << caspar::env::log_folder() << std::endl << std::endl; // Setup console window. setup_console_window(); // Print environment information. print_info(); // Create server object which initializes channels, protocols and controllers. caspar::server caspar_server; // Create a amcp parser for console commands. caspar::protocol::amcp::AMCPProtocolStrategy amcp(caspar_server.get_channels()); // Create a dummy client which prints amcp responses to console. auto console_client = std::make_shared<caspar::IO::ConsoleClientInfo>(); boost::thread input_thread([&] { while(shutdown_event == application_state::running) { std::wstring wcmd; std::getline(std::wcin, wcmd); // TODO: It's blocking... try { if(wcmd == L"exit" || wcmd == L"q") { shutdown_event = application_state::pause_and_shutdown; shutdown_cond.notify_all(); return; } // This is just dummy code for testing. if(wcmd.substr(0, 1) == L"1") wcmd = L"LOADBG 1-1 " + wcmd.substr(1, wcmd.length()-1) + L" SLIDE 100 LOOP \r\nPLAY 1-1"; else if(wcmd.substr(0, 1) == L"2") wcmd = L"MIXER 1-0 VIDEO IS_KEY 1"; else if(wcmd.substr(0, 1) == L"3") wcmd = L"CG 1-2 ADD 1 BBTELEFONARE 1"; else if(wcmd.substr(0, 1) == L"4") wcmd = L"PLAY 1-1 DV FILTER yadif=1:-1 LOOP"; else if(wcmd.substr(0, 1) == L"5") { auto file = wcmd.substr(2, wcmd.length()-1); wcmd = L"PLAY 1-1 " + file + L" LOOP\r\n" L"PLAY 1-2 " + file + L" LOOP\r\n" L"PLAY 1-3 " + file + L" LOOP\r\n" L"PLAY 2-1 " + file + L" LOOP\r\n" L"PLAY 2-2 " + file + L" LOOP\r\n" L"PLAY 2-3 " + file + L" LOOP\r\n"; } else if(wcmd.substr(0, 1) == L"X") { int num = 0; std::wstring file; try { num = boost::lexical_cast<int>(wcmd.substr(1, 2)); file = wcmd.substr(4, wcmd.length()-1); } catch(...) { num = boost::lexical_cast<int>(wcmd.substr(1, 1)); file = wcmd.substr(3, wcmd.length()-1); } int n = 0; int num2 = num; while(num2 > 0) { num2 >>= 1; n++; } wcmd = L"MIXER 1 GRID " + boost::lexical_cast<std::wstring>(n); for(int i = 1; i <= num; ++i) wcmd += L"\r\nPLAY 1-" + boost::lexical_cast<std::wstring>(i) + L" " + file + L" LOOP";// + L" SLIDE 100 LOOP"; } wcmd += L"\r\n"; amcp.Parse(wcmd.c_str(), wcmd.length(), console_client); } catch(...) { CASPAR_LOG_CURRENT_EXCEPTION(); } } });
// //! [UtilLoadFiles] void WorkbenchUtil::LoadFiles(const QStringList &fileNames, berry::IWorkbenchWindow::Pointer window, bool openEditor) // //! [UtilLoadFiles] { if (fileNames.empty()) return; mitk::IDataStorageReference::Pointer dataStorageRef; { ctkPluginContext* context = mitk::PluginActivator::GetContext(); mitk::IDataStorageService* dss = 0; ctkServiceReference dsRef = context->getServiceReference<mitk::IDataStorageService>(); if (dsRef) { dss = context->getService<mitk::IDataStorageService>(dsRef); } if (!dss) { QString msg = "IDataStorageService service not available. Unable to open files."; MITK_WARN << msg.toStdString(); QMessageBox::warning(QApplication::activeWindow(), "Unable to open files", msg); return; } // Get the active data storage (or the default one, if none is active) dataStorageRef = dss->GetDataStorage(); context->ungetService(dsRef); } mitk::DataStorage::Pointer dataStorage = dataStorageRef->GetDataStorage(); // Do the actual work of loading the data into the data storage std::vector<std::string> fileNames2; // Correct conversion for File names.(BUG 12252) fileNames2.resize(fileNames.size()); for (int i = 0; i< fileNames.size(); i++) fileNames2[i] = std::string(QFile::encodeName(fileNames[i]).data()); // Old conversion which returns wrong encoded Non-Latin-Characters. //ctk::qListToSTLVector(fileNames, fileNames2); // Turn off ASSERT #if defined(_MSC_VER) && !defined(NDEBUG) && defined(_DEBUG) && defined(_CRT_ERROR) int lastCrtReportType = _CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_DEBUG ); #endif const bool dsmodified = mitk::IOUtil::LoadFiles(fileNames2, *dataStorage); // Set ASSERT status back to previous status. #if defined(_MSC_VER) && !defined(NDEBUG) && defined(_DEBUG) && defined(_CRT_ERROR) if (lastCrtReportType) _CrtSetReportMode( _CRT_ASSERT, lastCrtReportType ); #endif // Check if there is an open perspective. If not, open the default perspective. if (window->GetActivePage().IsNull()) { std::string defaultPerspId = window->GetWorkbench()->GetPerspectiveRegistry()->GetDefaultPerspective(); window->GetWorkbench()->ShowPerspective(defaultPerspId, window); } bool globalReinitOnNodeAdded = true; berry::IPreferencesService::Pointer prefService = berry::Platform::GetServiceRegistry().GetServiceById<berry::IPreferencesService>(berry::IPreferencesService::ID); if (prefService.IsNotNull()) { berry::IBerryPreferences::Pointer prefs = (prefService->GetSystemPreferences()->Node("org.mitk.views.datamanager")).Cast<berry::IBerryPreferences>(); if(prefs.IsNotNull()) globalReinitOnNodeAdded = prefs->GetBool("Call global reinit if node is added", true); } if (openEditor && globalReinitOnNodeAdded) { try { // Activate the editor using the same data storage or open the default editor mitk::DataStorageEditorInput::Pointer input(new mitk::DataStorageEditorInput(dataStorageRef)); berry::IEditorPart::Pointer editor = mitk::WorkbenchUtil::OpenEditor(window->GetActivePage(), input, true); mitk::IRenderWindowPart* renderEditor = dynamic_cast<mitk::IRenderWindowPart*>(editor.GetPointer()); mitk::IRenderingManager* renderingManager = renderEditor == 0 ? 0 : renderEditor->GetRenderingManager(); if(dsmodified && renderingManager) { // get all nodes that have not set "includeInBoundingBox" to false mitk::NodePredicateNot::Pointer pred = mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("includeInBoundingBox" , mitk::BoolProperty::New(false))); mitk::DataStorage::SetOfObjects::ConstPointer rs = dataStorage->GetSubset(pred); // calculate bounding geometry of these nodes mitk::TimeGeometry::Pointer bounds = dataStorage->ComputeBoundingGeometry3D(rs); // initialize the views to the bounding geometry renderingManager->InitializeViews(bounds); } } catch (const berry::PartInitException& e) { QString msg = "An error occurred when displaying the file(s): %1"; QMessageBox::warning(QApplication::activeWindow(), "Error displaying file", msg.arg(QString::fromStdString(e.message()))); } } }
MSICA_IMP ReplaceEula(MSIHANDLE hInstall) { // ::DebugBreak(); _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG); _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG); // // EULA File Content is MBCS (RTF) not Unicode // XTL::AutoProcessHeapPtr<CHAR> lpEula = pReadEulaFromFile(hInstall); if (NULL == (LPSTR) lpEula) { pMsiLogMessage( hInstall, _T("EULACA: ReadEulaFromFile failed, error=0x%X"), GetLastError()); return ERROR_INSTALL_FAILURE; } // // Replacing EULA text control in the database // PMSIHANDLE hDatabase = MsiGetActiveDatabase(hInstall); if (0 == hDatabase) { pMsiLogMessage( hInstall, _T("EULACA: MsiGetActiveDatabase failed, error=0x%X"), GetLastError()); return ERROR_INSTALL_FAILURE; } PMSIHANDLE hView; LPCTSTR query = _T("SELECT * FROM `Control` ") _T(" WHERE `Dialog_` = 'LicenseAgreement' AND `Control` = 'Memo' "); UINT ret = MsiDatabaseOpenView(hDatabase, query, &hView); if (ERROR_SUCCESS != ret) { pMsiLogMessage( hInstall, _T("EULACA: MsiDatabaseOpenView failed, error=0x%X"), ret); return ERROR_INSTALL_FAILURE; } ret = MsiViewExecute(hView, 0); if (ERROR_SUCCESS != ret) { pMsiLogMessage( hInstall, _T("EULACA: MsiViewExecute failed, error=0x%X"), ret); return ERROR_INSTALL_FAILURE; } PMSIHANDLE hRecord; ret = MsiViewFetch(hView, &hRecord); if (ERROR_SUCCESS != ret) { pMsiLogMessage( hInstall, _T("EULACA: MsiViewFetch failed, error=0x%X"), ret); return ERROR_INSTALL_FAILURE; } ret = MsiViewModify(hView, MSIMODIFY_DELETE, hRecord); if (ERROR_SUCCESS != ret) { pMsiLogMessage( hInstall, _T("EULACA: MsiViewModify failed, error=0x%X"), ret); return ERROR_INSTALL_FAILURE; } // // 10th field is the Text column // // Dialog_, Control, Type, X, Y, // Width, Height, Attributes, Property, Text // Control_Next, Help // ret = MsiRecordSetStringA(hRecord, 10, lpEula); if (ERROR_SUCCESS != ret) { pMsiLogMessage( hInstall, _T("EULACA: MsiRecordSetString failed, error=0x%X"), ret); return ERROR_INSTALL_FAILURE; } // // Commit the changes temporarily // ret = MsiViewModify(hView, MSIMODIFY_INSERT_TEMPORARY, hRecord); if (ERROR_SUCCESS != ret) { pMsiLogMessage( hInstall, _T("EULACA: MsiViewModify failed, error=0x%X"), ret); return ERROR_INSTALL_FAILURE; } pMsiLogMessage( hInstall, _T("EULACA: EULA is replaced successfully.")); return ERROR_SUCCESS; }
int main(int argc, char **argv) { char *name; #ifdef _MSC_VER // Send all reports to STDOUT _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 #ifdef __DJGPP__ if (--argc <= 0) return 1; if ((name = strrchr(argv[0], '/'))) strcpy(name + 1, argv[1]); name = argv[1]; argv[1] = argv[0]; argv++; #else if (!argv[0]) name = "john"; else if ((name = strrchr(argv[0], '/'))) name++; #if defined(__CYGWIN32__) || defined (__MINGW32__) || defined (_MSC_VER) else if ((name = strrchr(argv[0], '\\'))) name++; #endif else name = argv[0]; #endif #if defined(__CYGWIN32__) || defined (__MINGW32__) || defined (_MSC_VER) strlwr(name); if (strlen(name) > 4 && !strcmp(name + strlen(name) - 4, ".exe")) name[strlen(name) - 4] = 0; #endif if (!strcmp(name, "unshadow")) { CPU_detect_or_fallback(argv, 0); return unshadow(argc, argv); } if (!strcmp(name, "unafs")) { CPU_detect_or_fallback(argv, 0); return unafs(argc, argv); } if (!strcmp(name, "undrop")) { CPU_detect_or_fallback(argv, 0); return undrop(argc, argv); } if (!strcmp(name, "unique")) { CPU_detect_or_fallback(argv, 0); return unique(argc, argv); } #ifndef _MSC_VER if (!strcmp(name, "ssh2john")) { CPU_detect_or_fallback(argv, 0); return ssh2john(argc, argv); } if (!strcmp(name, "keepass2john")) { CPU_detect_or_fallback(argv, 0); return keepass2john(argc, argv); } if (!strcmp(name, "keychain2john")) { CPU_detect_or_fallback(argv, 0); return keychain2john(argc, argv); } if (!strcmp(name, "rar2john")) { CPU_detect_or_fallback(argv, 0); return rar2john(argc, argv); } if (!strcmp(name, "racf2john")) { CPU_detect_or_fallback(argv, 0); return racf2john(argc, argv); } if (!strcmp(name, "pwsafe2john")) { CPU_detect_or_fallback(argv, 0); return pwsafe2john(argc, argv); } #endif #ifdef HAVE_NSS if (!strcmp(name, "mozilla2john")) { CPU_detect_or_fallback(argv, 0); return mozilla2john(argc, argv); } #endif if (!strcmp(name, "pdf2john")) { CPU_detect_or_fallback(argv, 0); return pdf2john(argc, argv); } if (!strcmp(name, "zip2john")) { CPU_detect_or_fallback(argv, 0); return zip2john(argc, argv); } if (!strcmp(name, "hccap2john")) { CPU_detect_or_fallback(argv, 0); return hccap2john(argc, argv); } #ifdef HAVE_MPI mpi_setup(argc, argv); #endif john_init(name, argc, argv); /* --max-run-time disregards load times */ timer_abort = options.max_run_time + 1; john_run(); john_done(); #ifdef _MSC_VER _CrtDumpMemoryLeaks(); #endif return exit_status; }
int main() { _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG); PWSTR sUserSid = L""; HANDLE hToken = NULL; if (OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, FALSE, &hToken) || OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) { if (!GetUserSidToken(hToken, &sUserSid)) { printf("GetUserSid error: %d\n", GetLastError()); return 1; } CloseHandle(hToken); } PWSTR sKeyHandle = L""; PWSTR sPublicKey = L""; PWSTR sChallenge = L""; PWSTR sHost = L""; PWSTR sPort = L""; PWSTR sUrl = L""; PWSTR sAppId = CRYSIL_APP_ID; std::cout << "Saved values in registry for current user" << std::endl; printf("UserSid: %ls\n", sUserSid); if (!Helper::Registry::GetRegValue(L"KeyHandle", &sKeyHandle, sUserSid)) { printf("GetKeyHandle error"); return false; } printf("KeyHandle: %ls\n", sKeyHandle); if (!Helper::Registry::GetRegValue(L"PublicKey", &sPublicKey, sUserSid)) { printf("GetPublicKey error"); return false; } if (!Helper::String::HexEncode(&sPublicKey)) { printf("GetPublicKey error"); return false; } printf("PublicKey: %ls\n", sPublicKey); if (!Helper::Registry::GetRegValue(L"Host", &sHost, sUserSid)) { printf("GetHost error"); return false; } printf("Host: %ls\n", sHost); if (!Helper::Registry::GetRegValue(L"Port", &sPort, sUserSid)) { printf("GetPort error"); return false; } printf("Port: %ls\n", sPort); if (!Helper::Registry::GetRegValue(L"URL", &sUrl, sUserSid)) { printf("GetUrl error"); return false; } printf("Url: %ls\n", sUrl); if (!Helper::Crypto::CreateRandomChallenge(&sChallenge)) { printf("CreateRandomChallenge error"); return false; } printf("Random challenge: %ls\n", sChallenge); ConsolePinHandler pinHandler{}; //WindowsPinHandler pinHandler{}; //HWND hwndC = GetConsoleWindow(); //g_hinst = GetModuleHandle(0); //pinHandler.setHwndOwner(hwndC); if (Helper::CrySIL::PerformU2FRequest(sUserSid, &pinHandler)) printf("PerformU2FRequest: Success\n"); else printf("PerformU2FRequest: Error\n"); printf("Press any key to continue ..."); _CrtDumpMemoryLeaks(); getchar(); return 0; }
int main( int argc, char *argv[ ] ) { #define nStrLen 256 int bReleaseVersion = bRELEASE_VERSION; char szSdfDataValue[MAX_SDF_VALUE+1]; char szInchiCmdLine[512]; char pStrInchiId[nStrLen], pStrLogId[nStrLen]; const char *p1, *p2; int retcode= 0, retcode1 = 0, i, k, tot_len; int inp_index, out_index; int nStructNo; long lSdfId; long num_inp, num_err, num_output; INPUT_PARMS inp_parms, *ip = &inp_parms; STRUCT_DATA struct_data, *sd = &struct_data; INCHI_IOSTREAM outputstr, logstr, prbstr, instr; INCHI_IOSTREAM *out_stream=&outputstr, *log_stream=&logstr, *prb_stream=&prbstr, *inp_stream=&instr; inchi_Input inchi_inp, *pInp = &inchi_inp; inchi_Output genout, *pResults = &genout; INCHIGEN_DATA inchi_gendata, *pGenData = &inchi_gendata; INCHIGEN_HANDLE HGen = NULL; char *pinfo; int len_mess=0, len_mess1, mshift=0, was_print = 0; char ik_string[256]; /*^^^ Resulting InChIKey string */ int ik_ret=0; /*^^^ InChIKey-calc result code */ int xhash1, xhash2; char szXtra1[256], szXtra2[256]; unsigned long ulDisplTime = 0; /* infinite, milliseconds */ time_t elapsed; /*^^^ Post-1.02b - moved from below */ int bTabbed=0; /*^^^ Set debug output */ #if (TRACE_MEMORY_LEAKS == 1) _CrtSetDbgFlag(_CRTDBG_CHECK_ALWAYS_DF | _CRTDBG_LEAK_CHECK_DF | _CRTDBG_ALLOC_MEM_DF); /* for execution outside of the VC++ debugger uncomment one of the following two */ /*#define MY_REPORT_FILE _CRTDBG_FILE_STDERR */ /*#define MY_REPORT_FILE _CRTDBG_FILE_STDOUT */ #ifdef MY_REPORT_FILE _CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE ); _CrtSetReportFile( _CRT_WARN, MY_REPORT_FILE ); _CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE ); _CrtSetReportFile( _CRT_ERROR, MY_REPORT_FILE ); _CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_FILE ); _CrtSetReportFile( _CRT_ASSERT, MY_REPORT_FILE ); #else _CrtSetReportMode(_CRT_WARN | _CRT_ERROR, _CRTDBG_MODE_DEBUG); #endif /* turn on floating point exceptions */ #if ( !defined(__STDC__) || __STDC__ != 1 ) { /* Get the default control word. */ int cw = _controlfp( 0,0 ); /* Set the exception masks OFF, turn exceptions on. */ /*cw &=~(EM_OVERFLOW|EM_UNDERFLOW|EM_INEXACT|EM_ZERODIVIDE|EM_DENORMAL);*/ cw &=~(EM_OVERFLOW|EM_UNDERFLOW|EM_ZERODIVIDE|EM_DENORMAL); /* Set the control word. */ _controlfp( cw, MCW_EM ); } #endif #endif /* #if (TRACE_MEMORY_LEAKS == 1) */ /*^^^ Set Ctrl+C trap under Win32 + MS VC++ */ #if( defined( _WIN32 ) && defined( _CONSOLE ) && defined(_MSC_VER) && _MSC_VER >= 800 && defined(ADD_WIN_CTLC) && !(defined(__STDC__) && __STDC__ == 1)) if ( SetConsoleCtrlHandler( MyHandlerRoutine, 1 ) ) { ; /*ConsoleQuit = WasInterrupted*/; } #endif num_inp = 0; num_err = 0; num_output = 0; elapsed = time(NULL); /*^^^ Set original input structure */ memset(pInp, 0, sizeof(*pInp)); memset(pResults, 0, sizeof(*pResults)); memset(pGenData, 0, sizeof(*pGenData)); memset(szSdfDataValue, 0, sizeof(szSdfDataValue)); /*^^^ Initialize I/O streams as string buffers so that they may be filled within dll; also associate files with the streams and use inchi_ios_flush to flush buffer content */ inchi_ios_init(log_stream, INCHI_IOSTREAM_TYPE_STRING, NULL); inchi_ios_init(inp_stream, INCHI_IOSTREAM_TYPE_STRING, NULL); inchi_ios_init(out_stream, INCHI_IOSTREAM_TYPE_STRING, NULL); inchi_ios_init(prb_stream, INCHI_IOSTREAM_TYPE_STRING, NULL); /*^^^ Check command line */ if ( argc < 2 || argc==2 && ( argv[1][0]==INCHI_OPTION_PREFX ) && (!strcmp(argv[1]+1, "?") || !e_inchi_stricmp(argv[1]+1, "help") ) ) { /* e_HelpCommandLineParms(stdout); */ e_HelpCommandLineParmsReduced(log_stream); log_stream->f = stderr; inchi_ios_flush(log_stream); return 0; } if ( 0 > e_ReadCommandLineParms( argc, (const char **)argv, ip, szSdfDataValue, &ulDisplTime, bReleaseVersion, log_stream ) ) /*^^^ Explicitly cast to (const char **) to avoid a warning about "incompatible pointer type":*/ { goto exit_function; } /*^^^ Open files associated with I/O streams. */ if ( !e_OpenFiles( &(inp_stream->f), &(out_stream->f), &(log_stream->f), &(prb_stream->f), ip ) ) goto exit_function; /*^^^ Create InChI generator object. */ #ifndef USE_STDINCHI_API HGen = INCHIGEN_Create(); #else HGen = STDINCHIGEN_Create(); #endif if (NULL==HGen) { /*^^^ Probably, out of RAM. Could do nothing. */ inchi_fprintf( stderr, "Could not create InChI generator (out of RAM?)\n" ); goto exit_function; } /*^^^ Set input labelling opts */ if ( ip->bNoStructLabels ) { ip->pSdfLabel = NULL; ip->pSdfValue = NULL; } else if ( ip->nInputType == INPUT_INCHI_PLAIN || ip->nInputType == INPUT_INCHI_XML || ip->nInputType == INPUT_CMLFILE ) { /* the input may contain both the header and the label of the structure */ if ( !ip->pSdfLabel ) ip->pSdfLabel = ip->szSdfDataHeader; if ( !ip->pSdfValue ) ip->pSdfValue = szSdfDataValue; } e_PrintInputParms( log_stream, ip ); inchi_ios_flush2(log_stream,stdout); pStrInchiId[0] = '\0'; /*^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Main cycle: read input structures and create their InChI ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/ out_index = 0; while (!e_bInterrupted) { int bHasTimeout = 0; if ( ip->last_struct_number && num_inp >= ip->last_struct_number ) { retcode = _IS_EOF; /* simulate end of file */ goto exit_function; } /*^^^ Create command line */ szInchiCmdLine[0] = '\0'; for ( i = 1; i < argc; i ++ ) { if ( argv[i] && INCHI_OPTION_PREFX == argv[i][0] && argv[i][1] ) { /*^^^ Omit certain options */ if ( !e_inchi_memicmp( argv[i]+1, "start:", 6) || !e_inchi_memicmp( argv[i]+1, "end:", 4) || !e_inchi_stricmp( argv[i]+1, "Tabbed" ) ) { continue; } if ( !e_inchi_stricmp( argv[i]+1, "Inchi2Inchi" ) ) { inchi_ios_eprint( log_stream, "\nOption Inchi2Inchi is not supported (use classic interface). \n" ); goto exit_function; } else if ( !e_inchi_stricmp( argv[i]+1, "Inchi2Struct" ) ) { inchi_ios_eprint( log_stream, "\nOption Inchi2Struct is not supported (use classic interface). \n" ); goto exit_function; } if ( !e_inchi_memicmp( argv[i]+1, "w", 1 ) && isdigit( UCINT argv[i][2] ) ) { bHasTimeout = 1; } /*^^^ Add option to szInchiCmdLine */ if ( strlen(szInchiCmdLine)+strlen(argv[i]) + 4 < sizeof(szInchiCmdLine) ) { if ( szInchiCmdLine[0] ) strcat( szInchiCmdLine, " " ); k = ( !(k=strcspn( argv[i], " \t" )) || argv[i][k] ); /* k means enclose in "" */ if (k) strcat( szInchiCmdLine, "\"" ); strcat( szInchiCmdLine, argv[i] ); if (k) strcat( szInchiCmdLine, "\"" ); } else { inchi_fprintf( stderr, "Too many options. Option \"%s\" ignored\n", argv[i] ); } } } if ( !bHasTimeout ) { /*^^^ Add default timeout option -W60: 60 seconds */ char szW60[] = " ?W60"; szW60[1] = INCHI_OPTION_PREFX; if ( strlen(szInchiCmdLine) + strlen( szW60 ) < sizeof(szInchiCmdLine) ) strcat( szInchiCmdLine, szW60 ); else inchi_fprintf( stderr, "Too many options. Option \"%s\" ignored\n", szW60 ); } /*^^^ End of command line deal */ if ( ip->nInputType==INPUT_INCHI_PLAIN ) { inchi_ios_eprint( log_stream, "\nRestoring InChI from AuxInfo is not supported (use classic interface). \n" ); goto exit_function; } /*^^^ Skip input cycle */ while(!e_bInterrupted) { inp_index = out_index; /*^^^ Read one structure from input */ e_FreeInchi_Input( pInp ); retcode = e_ReadStructure( sd, ip, inp_stream, log_stream, out_stream, prb_stream, pInp, num_inp+1, /* for CML:*/ inp_index, &out_index ); inchi_ios_flush2(log_stream,stdout); if ( _IS_SKIP != retcode) { lSdfId = ( ip->bGetSdfileId )? ip->lSdfId : 0; /* if requested then CAS r.n. otherwise struct. number*/ nStructNo = ( ip->lMolfileNumber > 0 )? ip->lMolfileNumber : num_inp+1; e_MakeOutputHeader( ip->pSdfLabel, ip->pSdfValue, lSdfId, nStructNo, pStrInchiId, pStrLogId ); } /* e_ReadStructure() outputs the error/warning messages, so we do not need to re-output them here */ switch (retcode) { case _IS_FATAL: num_inp ++; num_err ++; goto exit_function; case _IS_EOF: inchi_ios_eprint( log_stream, "\rStructure %d could not be read: Detected end of file. \r", num_inp+1 ); goto exit_function; case _IS_ERROR: num_inp ++; num_err ++; continue; case _IS_SKIP: num_inp ++; continue; } break; } if ( e_bInterrupted ) { inchi_ios_eprint( log_stream, "\nStructure %d could not be read: User Quit.\n", num_inp+1 ); inchi_ios_flush2(log_stream,stdout); num_err ++; goto exit_function; } /*^^^ Analyze the chiral flag */ p1 = NULL; #ifndef USE_STDINCHI_API if ( (ip->nMode & REQ_MODE_CHIR_FLG_STEREO) && (ip->nMode & REQ_MODE_STEREO) && ( ip->bChiralFlag & (FLAG_SET_INP_AT_CHIRAL | FLAG_SET_INP_AT_NONCHIRAL) ) ) ; /* cmd line has priority over the chiral flag in Molfile */ else if ( sd->bChiralFlag & FLAG_INP_AT_CHIRAL ) p1 = e_GetChiralFlagString( 1 ); /* input file has chiral flag */ else if ( (ip->nMode & REQ_MODE_CHIR_FLG_STEREO) && (ip->nMode & REQ_MODE_STEREO) || (sd->bChiralFlag & FLAG_INP_AT_NONCHIRAL) ) /* fix 04/05/2005 D.T.*/ /* chiral flag requested (/SUCF) or input has non-chiral flag */ p1 = e_GetChiralFlagString( 0 ); if (p1) { if ( strlen(szInchiCmdLine) + strlen( p1 ) < sizeof(szInchiCmdLine) ) strcat( szInchiCmdLine, p1 ); else inchi_fprintf( stderr, "Too many options. Option \"%s\" ignored\n", p1 ); } #endif pInp->szOptions = szInchiCmdLine; /*^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ create INChI for each connected component of the structure and optionally display them; output INChI for the whole structure. Use compartmentalized library interface. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/ #ifdef CREATE_0D_PARITIES if ( !pInp->stereo0D && !pInp->num_stereo0D ) { int bPointedEdgeStereo = (0 != (TG_FLAG_POINTED_EDGE_STEREO & ip->bTautFlags)); set_0D_stereo_parities( pInp, bPointedEdgeStereo ); Clear3D2Dstereo(pInp); } #endif #ifdef NEIGH_ONLY_ONCE e_RemoveRedundantNeighbors(pInp); #endif len_mess = len_mess1 = 0; pinfo = (char*) &(pGenData->pStrErrStruct); was_print = 0; /*^^^ Set up */ #ifndef USE_STDINCHI_API retcode = INCHIGEN_Setup( HGen, pGenData, pInp ); #else retcode = STDINCHIGEN_Setup( HGen, pGenData, pInp ); #endif len_mess1 = strlen(pinfo); if (len_mess1 > len_mess) { mshift = len_mess?1:0; inchi_ios_eprint(log_stream, "*** %-s [Initialization] %-s\n", pStrLogId, pinfo+len_mess+mshift); inchi_ios_flush2(log_stream,stdout); len_mess = len_mess1; was_print = 1; } /*^^^ Normalization step */ if ( (retcode == inchi_Ret_OKAY) || (retcode == inchi_Ret_WARNING) ) { #ifndef USE_STDINCHI_API retcode = INCHIGEN_DoNormalization(HGen, pGenData); #else retcode = STDINCHIGEN_DoNormalization(HGen, pGenData); #endif len_mess1 = strlen(pinfo); if (len_mess1 > len_mess) { mshift = len_mess?1:0; inchi_ios_eprint(log_stream, "*** %-s [Normalization] %-s\n", pStrLogId, pinfo+len_mess+mshift); inchi_ios_flush2(log_stream,stdout); len_mess = len_mess1; was_print = 1; } #ifdef OUTPUT_NORMALIZATION_DATA { int ic, istruct, itaut, ia, ib, nc[2]; NORM_ATOMS *inp_norm_data[TAUT_NUM]; /* = { &NormAtomsNontaut, &NormAtomsTaut}; */ NORM_ATOM *atom; nc[0] = pGenData->num_components[0]; nc[1] = pGenData->num_components[1]; inchi_ios_eprint(log_stream, "=== %-s Intermediate normalization data follow", pStrLogId); for (istruct=0; istruct<2; istruct++) { /*^^^ Print results for 1) original/disconnected structure and 2)reconnected structure */ if (nc[istruct]>0) { if (istruct==0) inchi_ios_eprint(log_stream, "\n\tOriginal/disconnected structure: "); else inchi_ios_eprint(log_stream, "\n\tReconnected structure: "); inchi_ios_eprint(log_stream, "%-d component(s)\n", nc[istruct]); inchi_ios_eprint(log_stream, "\t===============================================\n"); for (ic=0; ic < nc[istruct]; ic++) { /* Print results for each component of the structure */ inp_norm_data[0] = &(pGenData->NormAtomsNontaut[istruct][ic]); inp_norm_data[1] = &(pGenData->NormAtomsTaut[istruct][ic]); for (itaut=0;itaut<2;itaut++) { /* Print results for 1) non-tautomeric and 2) tautomeric version (if present) of the component */ if (NULL!=inp_norm_data[itaut]) { if (inp_norm_data[itaut]->num_at>0) { if (itaut==0) inchi_ios_eprint(log_stream, "\tComponent %-d, non-tautomeric:", ic+1); else inchi_ios_eprint(log_stream, "\tComponent %-d, tautomeric:", ic+1); inchi_ios_eprint(log_stream, "\t%-d atom(s)\n", inp_norm_data[itaut]->num_at); for (ia=0; ia< inp_norm_data[itaut]->num_at; ia++) { /*^^^ Print data for each atom */ if (inp_norm_data[itaut]->at != NULL) { atom = &( inp_norm_data[itaut]->at[ia] ); if (NULL!=atom) { /*^^^ Print: element, number, original number, no. of Hs, charge, coordination number, valence */ inchi_ios_eprint(log_stream, "\t\tatom %-s%-d (orig.%-s%-d) [H%-d] charge=%-+d CN=%-d val=%-d ", atom->elname, ia+1, atom->elname, atom->orig_at_number, atom->num_H, atom->charge, atom->valence, atom->chem_bonds_valence); if (atom->valence > 0) { /*^^^ Neighbors */ inchi_ios_eprint(log_stream, "nbrs { "); for (ib=0; ib <atom->valence; ib++) { inchi_ios_eprint(log_stream, "%-d ", atom->neighbor[ib]+1); } inchi_ios_eprint(log_stream, "}"); } /* Indicate if atom shares Hs with others */ if (atom->endpoint > 0) { inchi_ios_eprint(log_stream, "\n\t\t(in taut. group: %-d)", atom->endpoint); } inchi_ios_eprint(log_stream, "\n"); } } } } } } } } } } inchi_ios_flush(log_stream); #endif } /*^^^ Canonicalization step */ if ( (retcode == inchi_Ret_OKAY) || (retcode == inchi_Ret_WARNING) ) { #ifndef USE_STDINCHI_API retcode = INCHIGEN_DoCanonicalization( HGen, pGenData ); #else retcode = STDINCHIGEN_DoCanonicalization( HGen, pGenData ); #endif len_mess1 = strlen(pinfo); if (len_mess1 > len_mess) { mshift = len_mess?1:0; inchi_ios_eprint(log_stream, "*** %-s [Canonicalization] %-s\n", pStrLogId, pinfo+len_mess+mshift); inchi_ios_flush2(log_stream,stdout); len_mess = len_mess1; was_print = 1; } } /*^^^ Serialization (final) step */ if ( (retcode == inchi_Ret_OKAY) || (retcode == inchi_Ret_WARNING) ) { #ifndef USE_STDINCHI_API retcode1 = INCHIGEN_DoSerialization(HGen, pGenData, pResults); #else retcode1 = STDINCHIGEN_DoSerialization(HGen, pGenData, pResults); #endif retcode = inchi_max(retcode , retcode1); len_mess1 = strlen(pinfo); if (len_mess1 > len_mess) { mshift = len_mess?1:0; inchi_ios_eprint(log_stream, "*** %-s [Serialization] %-s\n", pStrLogId, pinfo+len_mess+mshift); inchi_ios_flush2(log_stream,stdout); was_print = 1; } } /* if (!was_print) inchi_ios_eprint(log_stream, "*** %-s \r", pStrLogId); */ /*^^^ Output err/warn */ if ( pResults->szMessage && pResults->szMessage[0] ) { p1 = "; "; p2 = pResults->szMessage; } else p1 = p2 = ""; switch (retcode) { case inchi_Ret_UNKNOWN: case inchi_Ret_FATAL: /* fatal processing error -- typically, memory allocation error */ num_inp ++; num_err ++; inchi_ios_eprint( log_stream, "Fatal Error (No INChI%s%s) %s\n", p1, p2, pStrLogId ); inchi_ios_eprint( log_stream, "Log start:---------------------\n%s\nLog end--------------------\n", pResults->szLog? pResults->szLog : "Log is missing" ); /*^^^ Free InChI library memories */ #ifndef USE_STDINCHI_API INCHIGEN_Reset(HGen, pGenData, pResults); #else STDINCHIGEN_Reset(HGen, pGenData, pResults); #endif goto exit_function; case inchi_Ret_EOF: /* typically, no input structure provided or help requested */ /* output previous structure number and message */ inchi_ios_eprint( log_stream, "End of file detected after structure %d\n", num_inp ); goto exit_function; case inchi_Ret_ERROR: num_inp ++; num_err ++; inchi_ios_eprint( log_stream, "Error (No INChI%s%s) %s\n", p1, p2, pStrLogId ); inchi_ios_flush2(log_stream,stdout); /*^^^ Free InChI library memories */ #ifndef USE_STDINCHI_API INCHIGEN_Reset(HGen, pGenData, pResults); #else STDINCHIGEN_Reset(HGen, pGenData, pResults); #endif continue; case inchi_Ret_SKIP: num_inp ++; inchi_ios_eprint( log_stream, "Skipped %s\n", pStrLogId ); goto exit_function; case inchi_Ret_OKAY: break; case inchi_Ret_WARNING: /*^^^ Suppress warnings, we display them step by steps */ /*^^^ if ( p2 && p2[0] ) inchi_ios_eprint( log_stream, "Warning (%s) %s\n", p2, pStrLogId ); */ break; /* ok */ } num_inp ++; tot_len = 0; /*^^^ Post-1.02b - here from below */ bTabbed = 0 != ( ip->bINChIOutputOptions & INCHI_OUT_TABBED_OUTPUT ); if ( pResults->szInChI && pResults->szInChI[0] ) { if (ip->bINChIOutputOptions & INCHI_OUT_SDFILE_ONLY ) { /*^^^ output SDfile */ char *start; unsigned len; int bAddLabel = 0; /*^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ output a SDfile. pResults->szInChI contains Molfile ending with "$$$$\n" line. Replace the 1st line with the structure number Replace the last line with the SDfile header, label, and new "$$$$\n" line ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/ start = pResults->szInChI; /*^^^ 2. SDfile header and data: write zero to the 1st byte of the last line "$$$$\n" to remove this line with purpose to relpace it */ if ( ip->pSdfLabel && ip->pSdfLabel[0] && ip->pSdfValue && ip->pSdfValue[0] && (len = strlen(start)) && len > 5 && '$' == start[len-5] && '\n' == start[len-6] ) { start[len-5] = '\0'; bAddLabel = 1; } /*^^^ 3. Output the whole Molfile */ inchi_ios_print( out_stream, "%s", start ); if ( bAddLabel ) { inchi_ios_print( out_stream, "> <%s>\n%s\n\n$$$$\n", ip->pSdfLabel, ip->pSdfValue ); } inchi_ios_flush(out_stream); } /* if (ip->bINChIOutputOptions & INCHI_OUT_SDFILE_ONLY ) */ else { /*^^^ Print InChI */ int bAuxInfo = !( ip->bINChIOutputOptions & INCHI_OUT_ONLY_AUX_INFO ) && pResults->szAuxInfo && pResults->szAuxInfo[0]; /*^^^ Post-1.02b - correctly treat tabbed output with InChIKey */ int bAuxOrKey = bAuxInfo || ( ip->bCalcInChIHash != INCHIHASH_NONE ); const char *pLF = "\n"; const char *pTAB = bTabbed? "\t" : pLF; if ( !ip->bNoStructLabels ) { /* Print a previously created label string */ inchi_ios_print(out_stream, "%s%s", pStrInchiId, pTAB); } /*^^^ Print INChI Identifier */ /*^^^ Post-1.02b */ inchi_ios_print(out_stream, "%s%s", pResults->szInChI, bAuxOrKey? pTAB : pLF); /*^^^ Print INChI Aux Info */ if ( bAuxInfo ) inchi_ios_print(out_stream, "%s%s",pResults->szAuxInfo, ip->bCalcInChIHash? pTAB : pLF); inchi_ios_flush(out_stream); } } /* if ( pResults->szInChI && pResults->szInChI[0] ) */ /*^^^ Calculate InChIKey */ if ( ip->bCalcInChIHash != INCHIHASH_NONE ) { xhash1 = xhash2 = 0; if ( ( ip->bCalcInChIHash == INCHIHASH_KEY_XTRA1 ) || ( ip->bCalcInChIHash == INCHIHASH_KEY_XTRA1_XTRA2 ) ) xhash1 = 1; if ( ( ip->bCalcInChIHash == INCHIHASH_KEY_XTRA2 ) || ( ip->bCalcInChIHash == INCHIHASH_KEY_XTRA1_XTRA2 ) ) xhash2 = 1; ik_ret = GetINCHIKeyFromINCHI(pResults->szInChI, xhash1, xhash2, ik_string, szXtra1, szXtra2); if (ik_ret==INCHIKEY_OK) { /* NB: correctly treat tabbed output with InChIKey & hash extensions */ char csep = '\n'; if ( ip->bINChIOutputOptions & INCHI_OUT_TABBED_OUTPUT ) csep = '\t'; inchi_ios_print(out_stream, "InChIKey=%-s",ik_string); if ( xhash1 ) inchi_ios_print(out_stream, "%cXHash1=%-s",csep,szXtra1); if ( xhash2 ) inchi_ios_print(out_stream, "%cXHash2=%-s",csep,szXtra2); inchi_ios_print(out_stream, "\n"); } else { /*^^^ Post-1.02b - add LF if output is tabbed and key generation failed */ if (bTabbed) inchi_ios_print(out_stream, "\n"); inchi_ios_eprint(log_stream, "Warning: could not compute InChIKey for #%-d ", num_inp); switch(ik_ret) { case INCHIKEY_UNKNOWN_ERROR: inchi_ios_eprint(log_stream, "(invalid key length requested)\n"); break; case INCHIKEY_EMPTY_INPUT: inchi_ios_eprint(log_stream, "(got an empty string)\n"); break; case INCHIKEY_INVALID_INCHI_PREFIX: case INCHIKEY_INVALID_INCHI: case INCHIKEY_INVALID_STD_INCHI: inchi_ios_eprint(log_stream, "(got non-InChI string)\n"); break; case INCHIKEY_NOT_ENOUGH_MEMORY: inchi_ios_eprint(log_stream, "(not enough memory to treat the string)\n"); break; default:inchi_ios_eprint(log_stream, "(internal program error)\n"); break; } } inchi_ios_flush(out_stream); inchi_ios_flush2(log_stream,stdout); } /*^^^ Free InChI library memories */ #ifndef USE_STDINCHI_API INCHIGEN_Reset(HGen, pGenData, pResults); #else STDINCHIGEN_Reset(HGen, pGenData, pResults); #endif } /* while ( !e_bInterrupted ) */ if (e_bInterrupted) { inchi_ios_eprint( log_stream, "\nStructure %d could not be processed: User Quit.\n", num_inp+1 ); num_err ++; goto exit_function; } /*^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/ exit_function: inchi_ios_eprint( log_stream, "\nProcessed %ld structure%s, %ld error%s.\n", num_inp, (num_inp==1)?"":"s", num_err, (num_err==1)?"":"s" ); elapsed-= time(NULL); inchi_ios_eprint( log_stream,"\nElapsed time: %ld\"\n", -elapsed); inchi_ios_flush2(log_stream,stdout); /*^^^ Freeing/closing */ e_FreeInchi_Input( pInp ); #ifndef USE_STDINCHI_API INCHIGEN_Destroy(HGen); #else STDINCHIGEN_Destroy(HGen); #endif for (i = 0; i<MAX_NUM_PATHS; i++) { if ( ip->path[i] ) { e_inchi_free( (char*) ip->path[i] ); /* cast deliberately discards 'const' qualifier */ ip->path[i] = NULL; } } inchi_ios_close(inp_stream); inchi_ios_close(log_stream); inchi_ios_close(out_stream); inchi_ios_close(prb_stream); return 0; }
int main(int argc, char *argv[]) { // For detecting memory leaks #ifdef _MSVC _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); _CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_DEBUG ); #endif //// Seed the random number generator //srand( (unsigned int)time( 0 ) ); // Display license std::cout << "RayWatch - A simple cross-platform RayTracer." << std::endl << "Copyright (C) 2008" << std::endl << " Angelo Rohit Joseph Pulikotil," << std::endl << " Francis Xavier Joseph Pulikotil" << std::endl << "This program comes with ABSOLUTELY NO WARRANTY." << std::endl << "This is free software, and you are welcome to redistribute it" << std::endl << "under certain conditions; see <http://www.gnu.org/licenses/>." << std::endl << std::endl; if( argc < 3 ) { std::cout << "Insufficient arguments" << std::endl << std::endl; std::cout << "Syntax (to render a Scene file):" << std::endl << argv[0] << " <input scene filename> <output bitmap filename> [width] [height]" << std::endl << std::endl; std::cout << "Syntax (to generate a sample file): " << std::endl << argv[0] << " --gen:<sample name> <output scene filename>" << std::endl << std::endl; std::cout << "Currently supported samples are CornellBox, Example1, Example2" << std::endl; return -1; } // If we're supposed to generate a sample file if( Utility::String::CaseInsensitiveCompare( std::string( argv[1] ).substr(0, 6), "--gen:" ) == 0 ) { const std::string sampleName = std::string( argv[1] ).substr( 6 ); bool bResult = false; if( Utility::String::CaseInsensitiveCompare( sampleName, "CornellBox" ) == 0 ) { bResult = Examples::CornellBox( argv[2] ); } else if( Utility::String::CaseInsensitiveCompare( sampleName, "Example1" ) == 0 ) { bResult = Examples::Example1( argv[2] ); } else if( Utility::String::CaseInsensitiveCompare( sampleName, "Example2" ) == 0 ) { bResult = Examples::Example2( argv[2] ); } else // We don't have this sample std::cout << "Error: Unknown sample name: " << sampleName << std::endl; if( !bResult ) return -1; std::cout << "Sample '" << sampleName << "' written to file: " << argv[2] << std::endl; return 0; } // Get the required width int width = 500; if( argc > 3 ) { if( !Utility::String::FromString(width, argv[3]) || (width < 1) ) { std::cout << "Error: Invalid integer specified for width: " << argv[3] << std::endl; return -1; } } // Get the required height int height = 500; if( argc > 4 ) { if( !Utility::String::FromString(height, argv[4]) || (height < 1) ) { std::cout << "Error: Invalid integer specified for height: " << argv[4] << std::endl; return -1; } } // Create a Camera Camera camera; camera._position .Set( 0, 0, 0 ); camera._hFov = 45 * (width / (float)height); camera._vFov = 45; // Create an Image Image image; if( !image.Create( width, height ) ) { std::cout << "Error: Failed to create Image of size " << width << "x" << height << std::endl; return -1; } // Open the input scene file std::fstream stream; stream.open( argv[1], std::ios_base::in ); if( !stream.is_open() ) { std::cout << "Error: Failed to open input scene file: " << argv[1] << std::endl; return -1; } // Create a Deserializer for the stream Deserializer d; if( !d.Open( stream ) ) { std::cout << "Error: Failed to read file: " << argv[1] << std::endl; return -1; } // Load the scene from the stream Scene *pScene = d.Deserialize<Scene>( 0 ); if( !pScene ) { std::cout << "Error: Failed to load Scene from file: " << argv[1] << std::endl; return -1; } // Create a RayTracer and ray trace the scene RayTracer rayTracer; std::cout << "RayTracing"; const bool bRTResult = rayTracer.Render( camera, *pScene, image ); std::cout << "Done" << std::endl; // We're done with the scene, delete it SafeDeleteScalar( pScene ); if( !bRTResult ) { std::cout << "Error: Failed while RayTracing the Scene." << std::endl; return -1; } // Save the image to the required output file if( !image.Save( argv[2] ) ) { std::cout << "Error: Failed while saving image to file: " << argv[2] << std::endl; return -1; } return 0; }
void InitGame (void) { int i; #ifdef _DEBUG _CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_DEBUG ); _CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_DEBUG ); // _CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_DEBUG ); _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF |_CRTDBG_CHECK_ALWAYS_DF // |_CRTDBG_CHECK_CRT_DF |_CRTDBG_LEAK_CHECK_DF); gi.dprintf ("!!!! DEBUGGING !!!! \n"); #endif gi.dprintf ("==== InitGame ====\n"); srand( (unsigned)time( NULL ) ); gun_x = gi.cvar ("gun_x", "0", 0); gun_y = gi.cvar ("gun_y", "0", 0); gun_z = gi.cvar ("gun_z", "0", 0); //FIXME: sv_ prefix is wrong for these sv_rollspeed = gi.cvar ("sv_rollspeed", "200", 0); sv_rollangle = gi.cvar ("sv_rollangle", "0", 0); sv_maxvelocity = gi.cvar ("sv_maxvelocity", "2000", 0); sv_gravity = gi.cvar ("sv_gravity", "800", 0); // noset vars dedicated = gi.cvar ("dedicated", "0", CVAR_NOSET); // latched vars sv_cheats = gi.cvar ("cheats", "0", CVAR_LATCH); gi.cvar ("gamename", GAMEVERSION , CVAR_SERVERINFO | CVAR_LATCH); gi.cvar ("gamedate", __DATE__ , CVAR_SERVERINFO | CVAR_LATCH); no_spec = gi.cvar ("no_spec", "0", 0); no_shadows = gi.cvar ("no_shadows", "0", 0); no_zoom = gi.cvar ("no_zoom", "0", 0); maxclients = gi.cvar ("maxclients", "4", CVAR_SERVERINFO | CVAR_LATCH); // deathmatch = gi.cvar ("deathmatch", "0", CVAR_LATCH); // coop = gi.cvar ("coop", "0", CVAR_LATCH); // JOSEPH 16-OCT-98 maxentities = gi.cvar ("maxentities", /*"1024"*/"2048", CVAR_LATCH); // change anytime vars dmflags = gi.cvar ("dmflags", "0", CVAR_SERVERINFO|CVAR_ARCHIVE); fraglimit = gi.cvar ("fraglimit", "0", CVAR_SERVERINFO); timelimit = gi.cvar ("timelimit", "0", CVAR_SERVERINFO); password = gi.cvar ("password", "", CVAR_USERINFO); filterban = gi.cvar ("filterban", "1", 0); antilag = gi.cvar("antilag", "1", CVAR_SERVERINFO); props = gi.cvar("props", "0", 0); bonus = gi.cvar("bonus", "0", 0); if (kpded2 && (int)gi.cvar("sv_uptime", "0", 0)->value) { // kpded2's uptime status is enabled, so disable ours starttime = 0; } else { char buf[20]; Com_sprintf(buf, sizeof(buf), "%d", time(NULL)); starttime = atoi(gi.cvar("starttime", buf, 0)->string); gi.cvar("uptime", "", CVAR_SERVERINFO); } g_select_empty = gi.cvar ("g_select_empty", "0", CVAR_ARCHIVE); run_pitch = gi.cvar ("run_pitch", "0.002", 0); run_roll = gi.cvar ("run_roll", "0.005", 0); bob_up = gi.cvar ("bob_up", "0.005", 0); bob_pitch = gi.cvar ("bob_pitch", "0.002", 0); bob_roll = gi.cvar ("bob_roll", "0.002", 0); // flood control flood_msgs = gi.cvar ("flood_msgs", "4", 0); flood_persecond = gi.cvar ("flood_persecond", "4", 0); flood_waitdelay = gi.cvar ("flood_waitdelay", "10", 0); kick_flamehack = gi.cvar ("kick_flamehack", "1", CVAR_SERVERINFO); anti_spawncamp = gi.cvar ("anti_spawncamp", "1", 0); idle_client = gi.cvar("idle_client", "120", 0); // Ridah, new cvar's developer = gi.cvar ("developer", "0", 0); g_vehicle_test = gi.cvar ("g_vehicle_test", "0", CVAR_LATCH); // Enables Hovercars for all players dm_locational_damage = gi.cvar ("dm_locational_damage", "0", 0); showlights = gi.cvar ("showlights", "0", 0); timescale = gi.cvar("timescale", "1.0", 0); // speed hack fix gi.cvar_set("sv_enforcetime", "1"); teamplay = gi.cvar("teamplay", "0", CVAR_LATCH|CVAR_SERVERINFO); if (teamplay->value != 0 && teamplay->value != 1 && teamplay->value != 4) gi.cvar_set("teamplay", "1"); cashlimit = gi.cvar ("cashlimit", "0", teamplay->value == 1 ? CVAR_SERVERINFO : 0); g_cashspawndelay = gi.cvar("g_cashspawndelay", "5", CVAR_ARCHIVE|CVAR_LATCH); dm_realmode = gi.cvar( "dm_realmode", "0", CVAR_LATCH|CVAR_SERVERINFO); g_mapcycle_file = gi.cvar( "g_mapcycle_file", "", 0); // Ridah, done. // snap - team tags gi.cvar(TEAMNAME, "", CVAR_SERVERINFO); gi.cvar_set(TEAMNAME, ""); gi.cvar(SCORENAME, "", CVAR_SERVERINFO); gi.cvar_set(SCORENAME, ""); // the "rconx serverinfo" command needs this to be the final serverinfo cvar gi.cvar(TIMENAME, "", CVAR_SERVERINFO); gi.cvar_set(TIMENAME, ""); // items InitItems (); // initialize all entities for this game game.maxentities = maxentities->value; g_edicts = gi.TagMalloc (game.maxentities * sizeof(g_edicts[0]), TAG_GAME); globals.edicts = g_edicts; globals.max_edicts = game.maxentities; // initialize all clients for this game game.maxclients = maxclients->value; game.clients = gi.TagMalloc (game.maxclients * sizeof(game.clients[0]), TAG_GAME); globals.num_edicts = game.maxclients+1; // disable single player and co-op modes gi.cvar_set("deathmatch", "1"); gi.cvar_set("coop", "0"); i = proccess_ini_file(); if (i != OK) gi.dprintf("Error opening comp ini file\n"); else gi.dprintf("Processed comp.ini file\n"); if (!map_list_filename[0]) strcpy(map_list_filename, g_mapcycle_file->string); if (map_list_filename[0]) { i = read_map_file(); if (i != OK) gi.dprintf("Error opening map list file (%s)\n", map_list_filename); else gi.dprintf("Processed map list file (%s)\n", map_list_filename); } if (!num_maps) allow_map_voting = false; cmd_check[0] = '\176'; for (i=1; i<7; i++) cmd_check[i] = 'A'+(rand()%26)+(rand()&32); cmd_check[i] = 0; // load & initialize GeoIP library if (!disable_geoip) { #ifdef _WIN32 HINSTANCE libgeoip = LoadLibrary("GeoIP"); #else void *libgeoip = dlopen("libGeoIP.so.1", RTLD_LAZY|RTLD_LOCAL); #endif if (libgeoip) { void* (*_GeoIP_new)(int flags); #ifdef _WIN32 *(void**)&_GeoIP_new = GetProcAddress(libgeoip, "GeoIP_new"); *(void**)&_GeoIP_delete = GetProcAddress(libgeoip, "GeoIP_delete"); *(void**)&_GeoIP_country_name_by_addr = GetProcAddress(libgeoip, "GeoIP_country_name_by_addr"); #else _GeoIP_new = dlsym(libgeoip, "GeoIP_new"); _GeoIP_delete = dlsym(libgeoip, "GeoIP_delete"); _GeoIP_country_name_by_addr = dlsym(libgeoip, "GeoIP_country_name_by_addr"); #endif geoip = _GeoIP_new(0); if (!geoip) { #ifdef _WIN32 FreeLibrary(libgeoip); #else dlclose(libgeoip); #endif gi.dprintf("Failed to load GeoIP database\n"); } else gi.dprintf("Loaded GeoIP database\n"); } } if (kpded2) { /* enable kpded2 features: GMF_CLIENTPOV - improved eyecam chase mode GMF_CLIENTTEAM - team info in server browsers GMF_CLIENTNOENTS - removes everything when spectating is disabled GMF_WANT_ALL_DISCONNECTS - cancelled connection notifications */ char buf[10]; sprintf(buf, "%d", GMF_CLIENTPOV | GMF_CLIENTNOENTS | GMF_WANT_ALL_DISCONNECTS | (teamplay->value ? GMF_CLIENTTEAM : 0)); gi.cvar_forceset("g_features", buf); } }
int main(int argc, char* argv[]) #endif { #if defined(_DEBUG) && defined(__WINDOWS__) int tmpDbgFlag; _CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE ); _CrtSetReportFile( _CRT_ERROR, _CRTDBG_FILE_STDERR ); tmpDbgFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); tmpDbgFlag |= _CRTDBG_DELAY_FREE_MEM_DF; tmpDbgFlag |= _CRTDBG_LEAK_CHECK_DF; _CrtSetDbgFlag(tmpDbgFlag); #endif #if defined(__LINUX__) signal(SIGPIPE,SIG_IGN); #endif g_pSharedMessageQueueT2M=new SharedMessageQueue(); g_pMap=new SharedStringMap(); g_pMap->InitMap(1024); int runFlag=TRUE; int onlyOnce=FALSE; InterpreterOptions options; options.SetExpressionPoolSize(4*1024); options.SetMaxPredefinedValueNum(256); options.SetMaxFunctionDimensionNum(8); options.SetMaxInnerFunctionApiNum(256); options.SetMaxInnerStatementApiNum(32); options.SetMaxLocalNum(256); options.SetMaxProgramSize(4*1024); options.SetMaxStatementApiNum(4); options.SetMaxStatementNum(1024); options.SetStackValuePoolSize(4*1024); options.SetStringBufferSize(32*1024); options.SetValuePoolSize(4*1024); SourceCodeScript script(options); Interpreter& interpreter=script.GetInterpreter(); interpreter.SetExternRunFlagRef(runFlag); ConsoleScriptSource source(runFlag); char tempBuf[64]; tsnprintf(tempBuf,64,"%d",argc-1); g_pMap->Set("argc",tempBuf); for(int argIx=1;argIx<argc;++argIx) { tsnprintf(tempBuf,64,"argv%d",argIx-1); g_pMap->Set(tempBuf,argv[argIx]); } g_Argc = argc-1; g_Argv = (argc>1 ? &argv[1] : NULL); if(argc>=2) { runFlag=FALSE; const char* pFile=argv[1]; FILE* fp=fopen(pFile,"r"); if(NULL!=fp) { int size=(int)fread(g_FileBuffer,1,g_c_MaxFileBuffer,fp); if(size>=0) { g_FileBuffer[size]=0; int outSize=0; char* pOutMemory=NULL; int haveOutMemory=FALSE; int isContinue=DecryptMemoryWithCyclone(g_FileBuffer,size,pOutMemory,outSize,haveOutMemory); if(TRUE==isContinue) { if(TRUE==haveOutMemory && NULL!=pOutMemory && outSize>0) { tsnprintf(g_FileBuffer,g_c_MaxFileBuffer,"%s",pOutMemory); size=outSize; g_FileBuffer[size]=0; delete[] pOutMemory; } source.SetBuffer(g_FileBuffer); runFlag=TRUE; onlyOnce=TRUE; } } fclose(fp); } else { printf("Can't open %s !!!\n",pFile); } } else { printf("[usage]:\n"); printf("\tadmintool\n"); printf("\tadmintool file.scp [arg1 arg2 ...]\n"); printf("Start interaction script ...\n"); } for(int ix=0;ix<g_c_MaxScriptThread;++ix) { g_pScriptThread[ix]=NULL; } g_ScriptThreadNum=0; SharedStringMapObj mapObj(interpreter); interpreter.RegisterPredefinedValue("stringMap",FunctionScript::Value(&mapObj)); SleepApi sleepApi(interpreter); interpreter.RegisterPredefinedValue("sleep", FunctionScript::Value(&sleepApi)); TestPrintfApi testPrintfApi(interpreter); interpreter.RegisterPredefinedValue("sprintf",FunctionScript::Value(&testPrintfApi)); ArgvApi argvApi(interpreter); interpreter.RegisterPredefinedValue("argv",FunctionScript::Value(&argvApi)); interpreter.RegisterPredefinedValue("argc",FunctionScript::Value(g_Argc)); WriteConsoleApi writeConsoleApi(interpreter); interpreter.RegisterPredefinedValue("writeConsole",FunctionScript::Value(&writeConsoleApi)); GetLogFileIdApi getLogFileIdApi(interpreter); interpreter.RegisterPredefinedValue("getLogFileId",FunctionScript::Value(&getLogFileIdApi)); GetTimeStringApi getTimeStringApi(interpreter); interpreter.RegisterPredefinedValue("getTimeString",FunctionScript::Value(&getTimeStringApi)); GetMillisecondsApi getMillisecondsApi(interpreter); interpreter.RegisterPredefinedValue("getMilliseconds",FunctionScript::Value(&getMillisecondsApi)); ReadStringApi readStringApi(interpreter); interpreter.RegisterPredefinedValue("readString",FunctionScript::Value(&readStringApi)); WriteStringApi writeStringApi(interpreter); interpreter.RegisterPredefinedValue("writeString",FunctionScript::Value(&writeStringApi)); CreateIniReaderApi createIniReaderApi(interpreter); interpreter.RegisterPredefinedValue("createIniReader",FunctionScript::Value(&createIniReaderApi)); CreateTxtTableApi createTxtTableApi(interpreter); interpreter.RegisterPredefinedValue("createTxtTable",FunctionScript::Value(&createTxtTableApi)); CreateConfigTableApi createConfigTableApi(interpreter); interpreter.RegisterPredefinedValue("createConfigTable",FunctionScript::Value(&createConfigTableApi)); CreateXmlVisitorApi createXmlVisitorApi(interpreter); interpreter.RegisterPredefinedValue("createXmlVisitor",FunctionScript::Value(&createXmlVisitorApi)); SimpleClientObj clientObj(interpreter); RunFileApi runfileApi(interpreter,source); RunScriptApi runscriptApi(interpreter,source); QuitApi quitApi(interpreter,runFlag); GetScriptThreadNumApi getScriptThreadNumApi(interpreter); StartScriptThreadApi startScriptThreadApi(interpreter); MarkWaitingQuitApi markWaitingQuitApi(interpreter); StopScriptThreadApi stopScriptThreadApi(interpreter); IsScriptThreadRunningApi isScriptThreadRunningApi(interpreter); SendMessageM2TApi sendMessageApi(interpreter); PushMessageMT2MApi pushMessageApi(interpreter); PopMessageMT2MApi popMessageApi(interpreter); interpreter.RegisterPredefinedValue("client", FunctionScript::Value(&clientObj)); interpreter.RegisterPredefinedValue("runfile",FunctionScript::Value(&runfileApi)); interpreter.RegisterPredefinedValue("runscript",FunctionScript::Value(&runscriptApi)); interpreter.RegisterPredefinedValue("quit",FunctionScript::Value(&quitApi)); interpreter.RegisterPredefinedValue("getScriptThreadNum",FunctionScript::Value(&getScriptThreadNumApi)); interpreter.RegisterPredefinedValue("startScriptThread",FunctionScript::Value(&startScriptThreadApi)); interpreter.RegisterPredefinedValue("markWaitingQuit",FunctionScript::Value(&markWaitingQuitApi)); interpreter.RegisterPredefinedValue("stopScriptThread",FunctionScript::Value(&stopScriptThreadApi)); interpreter.RegisterPredefinedValue("isScriptThreadRunning", FunctionScript::Value(&isScriptThreadRunningApi)); interpreter.RegisterPredefinedValue("sendMessage", FunctionScript::Value(&sendMessageApi)); interpreter.RegisterPredefinedValue("pushMessage",FunctionScript::Value(&pushMessageApi)); interpreter.RegisterPredefinedValue("popMessage",FunctionScript::Value(&popMessageApi)); int lastValue=0; for(;TRUE==runFlag;) { source.ClearBuffer(); source.ResetTime(); unsigned int t1=MyTimeGetTime(); script.Parse(source); t1+=source.GetTime(); unsigned int t2=MyTimeGetTime(); if(interpreter.HasError()) { for(int ix=0;ix<interpreter.GetErrorNum();++ix) { printf("%s\n",interpreter.GetErrorInfo(ix)); } interpreter.Reset(); printf("Interpreter has already reset !\n"); } else { if(interpreter.GetStatementNum()>=options.GetMaxProgramSize()-10 || interpreter.GetValueNum()>=options.GetValuePoolSize()-10 || interpreter.GetStackValueNum()!=options.GetStackValuePoolSize() && interpreter.GetStackValueNum()>=options.GetStackValuePoolSize()-10 || interpreter.GetSyntaxComponentNum()>=options.GetExpressionPoolSize()-10 || int(interpreter.GetUnusedStringPtrRef()-interpreter.GetStringBuffer())>=options.GetStringBufferSize()-1024) { printf("[Statistic] statements:%u value:%u stack:%u syntax:%u string:%u\n",interpreter.GetStatementNum(),interpreter.GetValueNum(),interpreter.GetStackValueNum(),interpreter.GetSyntaxComponentNum(),(unsigned int)(interpreter.GetUnusedStringPtrRef()-interpreter.GetStringBuffer())); } Value val; interpreter.Execute(&val); if(argc==1) { if(!val.IsInvalid()) { if(val.IsString()) { printf("%s\n",val.GetString()); } else { char temp[MAX_NUMBER_STRING_SIZE]; const char* p=val.ToString(temp,MAX_NUMBER_STRING_SIZE); if(p && p[0]!='\0') { printf("Command Result:%s\n",p); } } } } else { if (val.IsInt()){ lastValue = val.GetInt(); } else { lastValue = 0; } } } unsigned int t3=MyTimeGetTime(); //printf("[Time] parse:%u interpret:%u\n",t2-t1,t3-t2); const char* line=source.GetBackBuffer(); if(NULL!=line) { if(strcmp(line,".")==0) { interpreter.Reset(); runFlag=TRUE; if(argc==1) { printf("Process command: reset\n"); } } else if(strcmp(line,"quit")==0 || strcmp(line,"exit")==0) { runFlag=FALSE; } else if(strcmp(line,"enabledebuginfo")==0) { interpreter.EnableDebugInfo(); } else if(strcmp(line,"disabledebuginfo")==0) { interpreter.DisableDebugInfo(); } } MySleep(100); if(TRUE==onlyOnce) break; } for(int ix=0;ix<g_ScriptThreadNum;++ix) { if(g_pScriptThread[ix] && g_pScriptThread[ix]->getStatus()==Thread::RUNNING) { g_pScriptThread[ix]->stop(); } } if(argc==1) { printf("Wait script thread exiting ...\n"); } while(g_CreateThreadCount!=g_QuitThreadCount) { MySleep(100); } if(argc==1) { printf("Now quit ...\n"); } for(int ix=0;ix<g_ScriptThreadNum;++ix) { if(g_pScriptThread[ix]) { delete g_pScriptThread[ix]; g_pScriptThread[ix]=NULL; } } if(g_pSharedMessageQueueT2M) { delete g_pSharedMessageQueueT2M; g_pSharedMessageQueueT2M=NULL; } return lastValue; }