bool Test::PerformTest() { printf("\nTEST: %s ...\n", test_name); bool result; _CrtMemState s1, s2, s3; _CrtMemCheckpoint(&s1); result = DoTest(); _CrtMemCheckpoint(&s2); if (_CrtMemDifference(&s3, &s1, &s2)) { result = false; printf("leak detected\n"); _CrtMemDumpStatistics(&s3); } if (result) { printf("RESULT: passed\n"); } else { printf("RESULT: error\n"); } return result; }
void debug_check() { _CrtMemState *temp; OutputHeading("Checking memory..."); if (ss1 == NULL) { debug_init(); ss1 = &s1; ss2 = &s2; } _CrtCheckMemory(); /* _CrtMemDumpAllObjectsSince( NULL ); */ _CrtMemCheckpoint( &s2 ); if ( _CrtMemDifference( &s3, &s1, &s2 ) ) _CrtMemDumpStatistics( &s3 ); /* _CrtDumpMemoryLeaks(); */ /* * swap the snapshots around */ temp = ss1; ss1 = ss2; ss2 = temp; }
int main() { char buf[50]; char buf1[50]; struct sockaddr_in sin; SafeSock ssock; IpVerify* userverify; set_mySubSystem( "COLLECTOR", SUBSYSTEM_TYPE_COLLECTOR ); config(); #ifdef WIN32 _CrtMemCheckpoint( &s1 ); #endif userverify = new IpVerify(); userverify->Init(); buf[0] = '\0'; while( 1 ) { printf("Enter test:\n"); scanf("%s",buf); if ( strncmp(buf,"exit",4) == 0 ) break; if ( strncmp(buf,"reinit",6) == 0 ) { config(); userverify->Init(); continue; } printf("Verifying %s ... ",buf); sprintf(buf1,"<%s:1970>",buf); string_to_sin(buf1,&sin); if ( userverify->Verify(WRITE,&sin) == TRUE ) printf("ALLOW\n"); else printf("DENY\n"); } delete userverify; #ifdef WIN32 _CrtMemCheckpoint( &s2 ); // _CrtMemDumpAllObjectsSince( &s1 ); _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); if ( _CrtMemDifference( &s3, &s1, &s2 ) ) _CrtMemDumpStatistics( &s3 ); // _CrtDumpMemoryLeaks(); // report any memory leaks on Win32 #endif return TRUE; }
HANDEL_EXPORT void xiaMemCheckpoint(int pass) { switch (pass) { case XIA_BEFORE: _CrtMemCheckpoint(&before); break; case XIA_AFTER: _CrtMemCheckpoint(&after); #pragma warning(disable : 4127) _RPT0(_CRT_WARN, "****Dumping Memory Changes Between Checkpoints****\n"); #pragma warning(default : 4127) #pragma warning(disable : 4127) if (!_CrtMemDifference(&difference, &before, &after)) { #pragma warning(default : 4127) _CrtMemDumpStatistics(&difference); } break; } return; }
int main(int argc, char* argv[]) { _CrtMemState s1,s2,s3; int r; if(argc == 2) { return RUN_TEST_BY_CATALOG(argv[1], &out); } else if(argc >= 3 ) { char name[512]; strcpy(name, argv[1]); strcat(name, "_"); strcat(name, argv[2]); return RUN_TEST_BY_NAME(name, &out); } RUN_ALL_TESTS(&out); _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDOUT); _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE ); _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDOUT ); _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE ); _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDOUT ); _CrtMemCheckpoint( &s1 ); malloc(3); r = RUN_ALL_TESTS(&out); _CrtMemCheckpoint( &s2 ); if ( _CrtMemDifference( &s3, &s1, &s2) ) { _CrtMemDumpStatistics( &s3 ); } return r; }
void EndCrtCheck() { _CrtMemState state_end; _CrtMemState state_diff; _CrtMemCheckpoint(&state_end); if (_CrtMemDifference(&state_diff, &g_state_begin, &state_end)) _CrtMemDumpStatistics(&state_diff); }
void NDInstanceBase::EndStaticsMem() { _CrtMemState s2, s3; _CrtMemCheckpoint( &s2 ); if ( _CrtMemDifference( &s3, &m_s1, &s2 ) ) { _CrtSetReportHook( NDReportHook ) ; _CrtMemDumpStatistics( &s3 ); _CrtSetReportHook( NULL ) ; } }
void DebugMemCheckEndPoint(void) { #ifdef FORTIFY Fortify_LeaveScope(); #else _CrtMemCheckpoint(&newState); _CrtMemDifference(&stateDiff, &oldState, &newState); _CrtMemDumpStatistics(&stateDiff); #endif }
void memStats() { #if (defined(WIN32) && defined(CHECK_LEAKS)) _CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE ); _CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDERR ); _CrtMemState memsnap; _CrtMemCheckpoint(&memsnap); _CrtMemDumpStatistics(&memsnap); #endif }
int main() { int i = 0; _CrtMemState memory; // C/C++ runtime memory management state storage while (i < 1000) { f(i++); // dump memory management state _CrtMemCheckpoint(&memory); _CrtMemDumpStatistics(&memory); } _CrtDumpMemoryLeaks(); // check if there were memory leaks return 0; }
~MemoryLeaks() { _CrtMemState checkpoint; _CrtMemCheckpoint(&checkpoint); _CrtMemState diff; _CrtMemDifference(&diff, &m_checkpoint, &checkpoint); _CrtMemDumpStatistics(&diff); _CrtMemDumpAllObjectsSince(&diff); }
// Cleanup the diagnostic framework before dumping any memory leaks. // int diagnostics_finish() { #ifdef _WIN32 // Shutdown the message monitor thread and handles diagnostics_finish_message_monitor(); // Shutdown the unhandled exception filter thread and handles diagnostics_finish_unhandled_exception_monitor(); // Cleanup internal thread list structures and free up any // used memory. diagnostics_finish_thread_list(); #ifdef _DEBUG // Only perform the memory leak dump if it is a boinc application // and not the BOINC Manager, BOINC Core Client, or BOINC // Screen saver since they'll check on close. if (flags & BOINC_DIAG_BOINCAPPLICATION) { if (flags & BOINC_DIAG_MEMORYLEAKCHECKENABLED) { _CrtMemCheckpoint(&finish_snapshot); if (_CrtMemDifference(&difference_snapshot, &start_snapshot, &finish_snapshot)) { fprintf(stdout, "\n\n"); fprintf(stdout, "**********\n"); fprintf(stdout, "**********\n"); fprintf(stdout, "\n"); fprintf(stdout, "Memory Leaks Detected!!!\n"); fprintf(stdout, "\n"); fprintf(stdout, "Memory Statistics:\n"); _CrtMemDumpStatistics(&difference_snapshot); fprintf(stdout, "\n"); _CrtMemDumpAllObjectsSince(&difference_snapshot); fprintf(stdout, "\n"); } } } #endif // defined(_DEBUG) #endif // defined(_WIN32) #ifdef ANDROID if (libhandle) { dlclose(libhandle); } #endif // Set initalization flag to false. diagnostics_initialized = false; return BOINC_SUCCESS; }
~CAAFInitialize() { AAFUnload(); #if defined(CHECKLEAKS) //_CrtMemDumpAllObjectsSince( &_memoryState ); //Cleaning up debug output: _CrtMemState memNow; _CrtMemCheckpoint(&memNow); _CrtMemState memDiff; std::string leakMsg = (_CrtMemDifference(&memDiff, &_memoryState, &memNow)==0)?"No leak.":"Leak!"; std::wcout << "_CrtMemDifference says " << leakMsg.c_str() << std::endl; _CrtMemDumpStatistics( &memDiff ); #endif }
void MemLeakCheck() { #if (WINDOWSPC>0) #if _DEBUG _CrtMemState memstate_s2, memstate_s3; // Store a 2nd memory checkpoint in s2 _CrtMemCheckpoint( &memstate_s2 ); if ( _CrtMemDifference( &memstate_s3, &memstate_s1, &memstate_s2 ) ) { _CrtMemDumpStatistics( &memstate_s3 ); _CrtMemDumpAllObjectsSince(&memstate_s1); } _CrtCheckMemory(); #endif #endif }
EWXWEXPORT(void,ELJApp_InitializeC)(wxClosure* closure,int _argc,char** _argv) { wxHANDLE wxhInstance = GetModuleHandle(NULL); /* check memory leaks with visual C++ */ #if (defined(__WXDEBUG__) && defined(_MSC_VER)) _CrtMemState memStart,memEnd,memDif; _CrtMemCheckpoint( &memStart ); _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 initClosure = closure; APPTerminating = 0; wxEntry(wxhInstance, NULL, (_argc > 0 ? _argv[0] : NULL), SW_SHOWNORMAL); APPTerminating = 1; /* wxPendingEvents is deleted but not set to NULL -> disaster when restarted from an interpreter */ #if !defined(WXMAKINGDLL) && !defined(WXUSINGDLL) wxPendingEvents = NULL; #endif #if defined(wxUSE_ODBC) && (wxUSE_ODBC != 0) wxDbCloseConnections(); #endif /* check memory leaks with visual C++ */ #if (defined(__WXDEBUG__) && defined(_MSC_VER)) _CrtMemCheckpoint( &memEnd ); if (_CrtMemDifference( &memDif, &memStart, &memEnd) && (memDif.lCounts[_NORMAL_BLOCK]>=-2 && memDif.lCounts[_NORMAL_BLOCK] <= 0)) { _RPT0(_CRT_WARN,"\n** memory leak detected (**\n" ); _CrtMemDumpStatistics(&memDif); /* _CrtMemDumpAllObjectsSince(&memStart); */ _RPT0(_CRT_WARN,"** memory leak report done **\n\n" ); } #endif }
void HeapChecker::Report() { #ifdef _DEBUG _CrtMemState m_stateNow; _CrtMemCheckpoint( &m_stateNow ); _CrtMemState m_stateDiff; if (_CrtMemDifference(&m_stateDiff, &m_stateStart, &m_stateNow)) { // Memory leaks was found. Report them now. _CrtMemDumpAllObjectsSince(&m_stateStart); _CrtMemDumpStatistics(&m_stateDiff); throw 0; // memory leak } #endif }
void t_f() { auto test = std::make_shared<rpc>(io); test->Run(); // _CrtSetBreakAlloc(1300); for (auto i = 0; i < 2; i++) { std::this_thread::sleep_for(1s); io.run(); } test->Stop(); // memory allocations take place here _CrtMemDumpAllObjectsSince(&s1); _CrtMemCheckpoint(&s2); if (_CrtMemDifference(&s3, &s1, &s2)) { _CrtMemDumpStatistics(&s3); } }
int main() { #if MG_PLATFORM_WINDOWS && MUGGLE_DEBUG _CrtMemState s1, s2, s3; _CrtMemCheckpoint(&s1); #endif TestFunction(); TestPerformance(); #if MG_PLATFORM_WINDOWS && MUGGLE_DEBUG _CrtMemCheckpoint(&s2); if (_CrtMemDifference(&s3, &s1, &s2)) { _CrtMemDumpStatistics(&s3); } _CrtDumpMemoryLeaks(); #endif return 0; }
void CMemoryState::DumpStatistics() const { _CrtMemDumpStatistics(&m_memState); }
void RefineW(const MSA &msaIn, MSA &msaOut) { const unsigned uSeqCount = msaIn.GetSeqCount(); const unsigned uColCount = msaIn.GetColCount(); // Reserve same nr seqs, 20% more cols const unsigned uReserveColCount = (uColCount*120)/100; msaOut.SetSize(uSeqCount, uReserveColCount); for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex) { msaOut.SetSeqName(uSeqIndex, msaIn.GetSeqName(uSeqIndex)); msaOut.SetSeqId(uSeqIndex, msaIn.GetSeqId(uSeqIndex)); } const unsigned uWindowCount = (uColCount + g_uRefineWindow - 1)/g_uRefineWindow; if (0 == g_uWindowTo) g_uWindowTo = uWindowCount - 1; #if MEMDEBUG _CrtSetBreakAlloc(1560); #endif if (g_uWindowOffset > 0) { MSA msaTmp; MSAFromColRange(msaIn, 0, g_uWindowOffset, msaOut); } fprintf(stderr, "\n"); for (unsigned uWindowIndex = g_uWindowFrom; uWindowIndex <= g_uWindowTo; ++uWindowIndex) { fprintf(stderr, "Window %d of %d \r", uWindowIndex, uWindowCount); const unsigned uColFrom = g_uWindowOffset + uWindowIndex*g_uRefineWindow; unsigned uColTo = uColFrom + g_uRefineWindow - 1; if (uColTo >= uColCount) uColTo = uColCount - 1; assert(uColTo >= uColFrom); SeqVect v; SeqVectFromMSACols(msaIn, uColFrom, uColTo, v); #if MEMDEBUG _CrtMemState s1; _CrtMemCheckpoint(&s1); #endif MSA msaTmp; MUSCLE(v, msaTmp); AppendMSA(msaOut, msaTmp); if (uWindowIndex == g_uSaveWindow) { MSA msaInTmp; unsigned uOutCols = msaOut.GetColCount(); unsigned un = uColTo - uColFrom + 1; MSAFromColRange(msaIn, uColFrom, un, msaInTmp); char fn[256]; sprintf(fn, "win%d_inaln.tmp", uWindowIndex); TextFile fIn(fn, true); msaInTmp.ToFile(fIn); sprintf(fn, "win%d_inseqs.tmp", uWindowIndex); TextFile fv(fn, true); v.ToFile(fv); sprintf(fn, "win%d_outaln.tmp", uWindowIndex); TextFile fOut(fn, true); msaTmp.ToFile(fOut); } #if MEMDEBUG void FreeDPMemSPN(); FreeDPMemSPN(); _CrtMemState s2; _CrtMemCheckpoint(&s2); _CrtMemState s; _CrtMemDifference(&s, &s1, &s2); _CrtMemDumpStatistics(&s); _CrtMemDumpAllObjectsSince(&s1); exit(1); #endif //#if DEBUG // AssertMSAEqIgnoreCaseAndGaps(msaInTmp, msaTmp); //#endif } fprintf(stderr, "\n"); // AssertMSAEqIgnoreCaseAndGaps(msaIn, msaOut);//@@uncomment! }
void testSimpleTeardown() { KNOWN_FATAL_BUG("XECS-259", "fails in mutex calls"); #ifdef _WIN32 _CrtMemCheckpoint(&MemStateBegin); #endif for (int i=0; i<NUM_OF_RUNS; ++i) { CallManager *pCallManager = new CallManager(FALSE, NULL, //LineMgr TRUE, // early media in 180 ringing NULL, // CodecFactory 9000, // rtp start 9002, // rtp end "sip:[email protected]", "sip:[email protected]", NULL, //SipUserAgent 0, // sipSessionReinviteTimer NULL, // mgcpStackTask NULL, // defaultCallExtension Connection::RING, // availableBehavior NULL, // unconditionalForwardUrl -1, // forwardOnNoAnswerSeconds NULL, // forwardOnNoAnswerUrl Connection::BUSY, // busyBehavior NULL, // sipForwardOnBusyUrl NULL, // speedNums CallManager::SIP_CALL, // phonesetOutgoingCallProtocol 4, // numDialPlanDigits CallManager::NEAR_END_HOLD, // holdType 5000, // offeringDelay "", // pLocal CP_MAXIMUM_RINGING_EXPIRE_SECONDS, //inviteExpireSeconds QOS_LAYER3_LOW_DELAY_IP_TOS, // expeditedIpTos 10, //maxCalls sipXmediaFactoryFactory(NULL)); //pMediaFactory #if 0 printf("Starting CallManager\n"); #endif pCallManager->start(); pCallManager->requestShutdown(); #if 0 printf("Deleting CallManager\n"); #endif delete pCallManager; } for (int i=0; i<NUM_OF_RUNS; ++i) { sipxDestroyMediaFactoryFactory() ; } #ifdef _WIN32 _CrtMemCheckpoint(&MemStateEnd); if (_CrtMemDifference(&MemStateDiff, &MemStateBegin, &MemStateEnd)) { _CrtMemDumpStatistics(&MemStateDiff); } #endif }
void debug_MEMSTATS(void) { _CrtMemState state; _CrtMemCheckpoint(&state); _CrtMemDumpStatistics(&state); }
void sipXtapiTestSuite::tearDown() { printf("sipXtapiTestSuite::tearDown line: %d\n", __LINE__); #ifdef _WIN32 #ifdef SIPX_TEST_FOR_MEMORY_LEAKS static bool bFirstRun = true ; #endif #endif SIPX_RESULT rc ; suiteLock.acquire(); #ifdef PURIFY Sleep(250000); PurifyNewLeaks(); #endif if (g_hInst != NULL) { rc = sipxUnInitialize(g_hInst); if (rc != SIPX_RESULT_SUCCESS) { printf("\nERROR: sipxTapiTest -- Forcing shutdown of g_hInst (0x%08X)\n", g_hInst) ; rc = sipxUnInitialize(g_hInst, true); } g_hInst = NULL; } if (g_hInst2 != NULL) { rc = sipxUnInitialize(g_hInst2); if (rc != SIPX_RESULT_SUCCESS) { printf("\nERROR: sipxTapiTest -- Forcing shutdown of g_hInst2 (0x%08X)\n", g_hInst2) ; rc = sipxUnInitialize(g_hInst2, true); } g_hInst2 = NULL; } if (g_hInst3 != NULL) { rc = sipxUnInitialize(g_hInst3); if (rc != SIPX_RESULT_SUCCESS) { printf("\nERROR: sipxTapiTest -- Forcing shutdown of g_hInst3 (0x%08X)\n", g_hInst3) ; rc = sipxUnInitialize(g_hInst3, true); } g_hInst3 = NULL; } if (g_hInst4 != NULL) { rc = sipxUnInitialize(g_hInst4); if (rc != SIPX_RESULT_SUCCESS) { printf("\nERROR: sipxTapiTest -- Forcing shutdown of g_hInst4 (0x%08X)\n", g_hInst4) ; rc = sipxUnInitialize(g_hInst4, true); } g_hInst4 = NULL; } if (g_hInst5 != NULL) { rc = sipxUnInitialize(g_hInst5); if (rc != SIPX_RESULT_SUCCESS) { printf("\nERROR: sipxTapiTest -- Forcing shutdown of g_hInst5 (0x%08X)\n", g_hInst5) ; rc = sipxUnInitialize(g_hInst5, true); } g_hInst5 = NULL; } sipxFlushHandles() ; suiteLock.release(); #ifdef _WIN32 #ifdef SIPX_TEST_FOR_MEMORY_LEAKS if (bFirstRun == false) { _CrtMemCheckpoint( &msAfterTest ); _CrtMemState diff ; if (_CrtMemDifference( &diff, &msBeforeTest, &msAfterTest)) { _CrtMemDumpStatistics( &diff ); _CrtMemDumpAllObjectsSince(&msBeforeTest) ; } } else { bFirstRun = false ; } #endif #endif printf("sipXtapiTestSuite::tearDown line: %d\n", __LINE__); }
int main(int argc, char *argv[]) { int iRet = 0; //susiaccess_agent_conf_body_t config; susiaccess_agent_profile_body_t profile; char *buffer = NULL; #ifdef MEM_LEAK_CHECK _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); //_CrtSetBreakAlloc(3719); _CrtMemCheckpoint( &memStateStart); #endif /* memset(&config, 0 , sizeof(susiaccess_agent_conf_body_t)); strcpy(config.runMode,"remote"); strcpy(config.autoStart,"True"); strcpy(config.serverIP,"172.22.12.12"); strcpy(config.serverPort,"1883"); strcpy(config.serverAuth,"F0PE1/aaU8o="); config.tlstype = tls_type_none; switch(config.tlstype) { case tls_type_none: break; case tls_type_tls: { strcpy(config.cafile, "ca.crt"); strcpy(config.capath, ""); strcpy(config.certfile, "server.crt"); strcpy(config.keyfile, "server.key"); strcpy(config.cerpasswd, "123456"); } break; case tls_type_psk: { strcpy(config.psk, ""); strcpy(config.identity, "SAClientSample"); strcpy(config.ciphers, ""); } break; } */ memset(&profile, 0 , sizeof(susiaccess_agent_profile_body_t)); sprintf_s(profile.version, DEF_VERSION_LENGTH, "%d.%d.%d.%d", 3, 1, 0, 0); strcpy(profile.hostname,"SAClientSample"); strcpy(profile.devId,"000014DAE996BE04"); strcpy(profile.sn,"14DAE996BE04"); strcpy(profile.mac,"14DAE996BE04"); strcpy(profile.type,"IPC"); strcpy(profile.product,"Sample Agent"); strcpy(profile.manufacture,"test"); strcpy(profile.osversion,"NA"); strcpy(profile.biosversion,"NA"); strcpy(profile.platformname,"NA"); strcpy(profile.processorname,"NA"); strcpy(profile.osarchitect,"NA"); profile.totalmemsize = 40832; strcpy(profile.maclist,"14DAE996BE04"); strcpy(profile.localip,"172.22.12.21"); strcpy(profile.account,"anonymous"); strcpy(profile.passwd,""); strcpy(profile.workdir, ""); /*GPS Test*/ { MSG_CLASSIFY_T *dev = NULL; MSG_CLASSIFY_T *gps = NULL; gps = GPS_CreateGPS(); dev = GPS_AddDevice(gps, "/dev/0", "1.0"); GPS_SetLatitudeAttribute(dev, 0, 180, -180, NULL); GPS_SetLongitudeAttribute(dev, 0, 90, -90, NULL); GPS_SetCustomFloatAttribute(dev, "Skey", "xdop", "r", 2.53, NULL); buffer = GPS_PrintUnformatted(gps); printf("GPS Format:\r\n%s\r\n", buffer); free(buffer); GPS_ReleaseGPS(gps); } printf("Click enter to next"); fgetc(stdin); /*AgentInfo Test*/ { MSG_CLASSIFY_T *myDev = NULL; myDev = DEV_CreateAgentInfo(&profile); buffer = DEV_PrintUnformatted(myDev); printf("AgentInfo Format:\r\n%s\r\n", buffer); free(buffer); DEV_ReleaseDevice(myDev); buffer = DEV_GetAgentInfoTopic(profile.devId); printf("AgentInfo topic:\r\n%s\r\n", buffer); free(buffer); } printf("Click enter to next"); fgetc(stdin); /*WillMessage Test*/ { MSG_CLASSIFY_T *myDev = NULL; myDev = DEV_CreateWillMessage(&profile); buffer = DEV_PrintUnformatted(myDev); printf("Will Message Format:\r\n%s\r\n", buffer); free(buffer); DEV_ReleaseDevice(myDev); buffer = DEV_GetWillMessageTopic(profile.devId); printf("Will Message topic:\r\n%s\r\n", buffer); free(buffer); } printf("Click enter to next"); fgetc(stdin); /*OSInfo Test*/ { MSG_CLASSIFY_T *myDev = NULL; myDev = DEV_CreateOSInfo(&profile); buffer = DEV_PrintUnformatted(myDev); printf("OSInfo Format:\r\n%s\r\n", buffer); free(buffer); DEV_ReleaseDevice(myDev); buffer = DEV_GetOSInfoTopic(profile.devId); printf("OSInfo topic:\r\n%s\r\n", buffer); free(buffer); } printf("Click enter to next"); fgetc(stdin); /*HandlerList Test*/ { MSG_CLASSIFY_T *myDev = NULL; char* list[] = {"handler1","handler2","handler3"}; myDev = DEV_CreateHandlerList(profile.devId, list, 3); buffer = DEV_PrintUnformatted(myDev); printf("HandlerList Format:\r\n%s\r\n", buffer); free(buffer); DEV_ReleaseDevice(myDev); buffer = DEV_GetHandlerListTopic(profile.devId); printf("HandlerList topic:\r\n%s\r\n", buffer); free(buffer); } printf("Click enter to next"); fgetc(stdin); /*IoT Test*/ { MSG_CLASSIFY_T *myCapability = IoT_CreateRoot("Test"); MSG_CLASSIFY_T *myVoltGroup = IoT_AddGroup(myCapability, "Voltage"); MSG_CLASSIFY_T *myTempGroup = IoT_AddGroup(myCapability, "Temperature"); MSG_ATTRIBUTE_T *attrVolt1 = NULL, *attrVolt2 = NULL, *attrTemp1 = NULL, *attrTemp2 = NULL; MSG_ATTRIBUTE_T* attr = IoT_AddGroupAttribute(myVoltGroup, "bu"); if(attr) IoT_SetStringValue(attr, "V", IoT_READONLY); attr = IoT_AddGroupAttribute(myTempGroup, "bu"); if(attr) IoT_SetStringValue(attr, "Celsius", IoT_READONLY); attrVolt1 = IoT_AddSensorNode(myVoltGroup, "5V"); if(attrVolt1) IoT_SetFloatValueWithMaxMin(attrVolt1, 4.9, IoT_READONLY, 5.5, 4.5, "V"); attrVolt2 = IoT_AddSensorNode(myVoltGroup, "12V"); if(attrVolt2) IoT_SetFloatValueWithMaxMin(attrVolt2, 11, IoT_READONLY, 10, 14, "V"); attrTemp1 = IoT_AddSensorNode(myTempGroup, "CPU"); if(attrTemp1) IoT_SetFloatValue(attrTemp1, 65, IoT_READONLY, "Celsius"); attrTemp2 = IoT_AddSensorNode(myTempGroup, "SYS"); if(attrTemp2) IoT_SetFloatValue(attrTemp2, 50, IoT_READONLY, "Celsius"); buffer = IoT_PrintCapability(myCapability); printf("IoT Format:\r\n%s\r\n", buffer); free(buffer); printf("Click enter to next"); fgetc(stdin); if(attrVolt2) IoT_SetFloatValue(attrVolt2, 12, IoT_READONLY, "V"); if(attrTemp1) IoT_SetFloatValueWithMaxMin(attrTemp1, 80, IoT_READONLY, 100, 40, "Celsius"); buffer = IoT_PrintCapability(myCapability); printf("IoT Format2:\r\n%s\r\n", buffer); free(buffer); printf("Click enter to next"); fgetc(stdin); if(myVoltGroup) IoT_DelSensorNode(myVoltGroup, "SYS"); if(myTempGroup) IoT_DelSensorNode(myTempGroup, "SYS"); buffer = IoT_PrintCapability(myCapability); printf("IoT Format3:\r\n%s\r\n", buffer); free(buffer); printf("Click enter to next"); fgetc(stdin); buffer = IoT_PrintData(myCapability); printf("IoT Data:\r\n%s\r\n", buffer); free(buffer); IoT_ReleaseAll(myCapability); } printf("Click enter to next"); fgetc(stdin); /*EventNotify Test*/ { MSG_CLASSIFY_T *myEvent = NULL; myEvent = DEV_CreateEventNotify("MsgGen", "My MsgGenTest"); buffer = DEV_PrintUnformatted(myEvent); printf("EventNotify Format:\r\n%s\r\n", buffer); free(buffer); DEV_ReleaseDevice(myEvent); } printf("Click enter to next"); fgetc(stdin); /*Full EventNotify Test*/ { MSG_CLASSIFY_T *myEvent = NULL; myEvent = DEV_CreateFullEventNotify(profile.devId, 2, "MsgGen", "MsgGen", "My MsgGenTest"); buffer = DEV_PrintUnformatted(myEvent); printf("EventNotify Format2:\r\n%s\r\n", buffer); free(buffer); DEV_ReleaseDevice(myEvent); buffer = DEV_GetEventNotifyTopic(profile.devId); printf("EventNotify topic:\r\n%s\r\n", buffer); free(buffer); } printf("Click enter to next"); fgetc(stdin); /*Get/Set Sensor Data Test*/ { MSG_ATTRIBUTE_T *attr = NULL; MSG_CLASSIFY_T *pInfoList = NULL, *pEArray = NULL, *pSensor = NULL; MSG_CLASSIFY_T *pRoot = MSG_CreateRoot(); if(pRoot) { attr = MSG_AddJSONAttribute(pRoot, "sessionID"); if(attr) MSG_SetStringValue(attr, "1234", NULL); pInfoList = MSG_AddJSONClassify(pRoot, "sensorInfoList", NULL, false); if(pInfoList) pEArray = MSG_AddJSONClassify(pInfoList, "e", NULL, true); pSensor = MSG_AddJSONClassify(pEArray, "sensor", NULL, false); if(pSensor) { attr = MSG_AddJSONAttribute(pSensor, "n"); if(attr) MSG_SetStringValue(attr, "SUSIControl/Hardware Monitor/Voltage/CPU", NULL); attr = MSG_AddJSONAttribute(pSensor, "v"); if(attr) MSG_SetDoubleValue(attr, 10, NULL, NULL); attr = MSG_AddJSONAttribute(pSensor, "statusCode"); if(attr) MSG_SetDoubleValue(attr, 220, NULL, NULL); } pSensor = MSG_AddJSONClassify(pEArray, "sensor", NULL, false); if(pSensor) { attr = MSG_AddJSONAttribute(pSensor, "n"); if(attr) MSG_SetStringValue(attr, "SUSIControl/Hardware Monitor/Temperature/CPU", NULL); attr = MSG_AddJSONAttribute(pSensor, "v"); if(attr) MSG_SetDoubleValue(attr, 10, NULL, NULL); attr = MSG_AddJSONAttribute(pSensor, "statusCode"); if(attr) MSG_SetDoubleValue(attr, 220, NULL, NULL); } } buffer = MSG_PrintUnformatted(pRoot); printf("Get/Set Sensor Data:\r\n%s\r\n", buffer); free(buffer); MSG_ReleaseRoot(pRoot); } printf("Click enter to exit"); fgetc(stdin); #ifdef MEM_LEAK_CHECK _CrtMemCheckpoint( &memStateEnd ); if ( _CrtMemDifference( &memStateDiff, &memStateStart, &memStateEnd) ) _CrtMemDumpStatistics( &memStateDiff ); #endif return iRet; }
void RefineW(const MSA &msaIn, MSA &msaOut) { const unsigned uSeqCount = msaIn.GetSeqCount(); const unsigned uColCount = msaIn.GetColCount(); // Reserve same nr seqs, 20% more cols const unsigned uReserveColCount = (uColCount*120)/100; msaOut.SetSize(uSeqCount, uReserveColCount); for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex) { msaOut.SetSeqName(uSeqIndex, msaIn.GetSeqName(uSeqIndex)); msaOut.SetSeqId(uSeqIndex, msaIn.GetSeqId(uSeqIndex)); } const unsigned uWindowCount = (uColCount + g_uRefineWindow.get() - 1)/g_uRefineWindow.get(); if (0 == g_uWindowTo.get()) g_uWindowTo.get() = uWindowCount - 1; #if MEMDEBUG _CrtSetBreakAlloc(1560); #endif if (g_uWindowOffset.get() > 0) { MSA msaTmp; MSAFromColRange(msaIn, 0, g_uWindowOffset.get(), msaOut); } if (!g_bQuiet.get()) fprintf(stderr, "\n"); for (unsigned uWindowIndex = g_uWindowFrom.get(); uWindowIndex <= g_uWindowTo.get(); ++uWindowIndex) { if (!g_bQuiet.get()) fprintf(stderr, "Window %d of %d \r", uWindowIndex, uWindowCount); const unsigned uColFrom = g_uWindowOffset.get() + uWindowIndex*g_uRefineWindow.get(); unsigned uColTo = uColFrom + g_uRefineWindow.get() - 1; if (uColTo >= uColCount) uColTo = uColCount - 1; assert(uColTo >= uColFrom); SeqVect v; SeqVectFromMSACols(msaIn, uColFrom, uColTo, v); #if MEMDEBUG _CrtMemState s1; _CrtMemCheckpoint(&s1); #endif // Begin AED 5/20/06 // remove any empty seqs in this window std::vector< size_t > empty_seqs; SeqVect vr; for( size_t seqI = 0; seqI < v.size(); ++seqI ) { if( v[seqI]->size() == 0 ) empty_seqs.push_back(seqI); else vr.push_back(v[seqI]); } std::vector< unsigned > seqid_map( vr.size() ); for( size_t seqI = 0; seqI < vr.size(); ++seqI ) { seqid_map[seqI] = vr[seqI]->GetId(); vr[seqI]->SetId(seqI); } MSA msaTmp; if( vr.size() > 1 ) MUSCLE(vr, msaTmp); // remap the seqids to their original state for( size_t seqI = 0; seqI < vr.size(); ++seqI ) vr[seqI]->SetId(seqid_map[seqI]); // merge empty seqs back in { const unsigned uSeqCount = msaOut.GetSeqCount(); const unsigned uColCount1 = msaOut.GetColCount(); const unsigned uColCount2 = vr.size() > 1 ? msaTmp.GetColCount() : vr[0]->size(); const unsigned uColCountCat = uColCount1 + uColCount2; for( unsigned seqI = 0; seqI < vr.size(); ++seqI ) { unsigned uSeqIndex = msaOut.GetSeqIndex(seqid_map[seqI]); if( vr.size() > 1 ) { unsigned uSeqIndex2 = msaTmp.GetSeqIndex(seqI); for (unsigned uColIndex = 0; uColIndex < uColCount2; ++uColIndex) { const char c = msaTmp.GetChar(uSeqIndex2, uColIndex); msaOut.SetChar(uSeqIndex, uColCount1 + uColIndex, c); } }else{ for (unsigned uColIndex = 0; uColIndex < uColCount2; ++uColIndex) { const char c = vr[0]->GetChar(uColIndex); msaOut.SetChar(uSeqIndex, uColCount1 + uColIndex, c); } } } for( unsigned seqI = 0; seqI < empty_seqs.size(); ++seqI ) { unsigned uSeqId2 = v[empty_seqs[seqI]]->GetId(); unsigned uSeqIndex = msaOut.GetSeqIndex(uSeqId2); for (unsigned uColIndex = 0; uColIndex < uColCount2; ++uColIndex) { msaOut.SetChar(uSeqIndex, uColCount1 + uColIndex, '-'); } } vr.clear(); } // AppendMSA(msaOut, msaTmp); // end AED 5/20/06 if (uWindowIndex == g_uSaveWindow.get()) { MSA msaInTmp; unsigned uOutCols = msaOut.GetColCount(); unsigned un = uColTo - uColFrom + 1; MSAFromColRange(msaIn, uColFrom, un, msaInTmp); char fn[256]; sprintf(fn, "win%d_inaln.tmp", uWindowIndex); TextFile fIn(fn, true); msaInTmp.ToFile(fIn); sprintf(fn, "win%d_inseqs.tmp", uWindowIndex); TextFile fv(fn, true); v.ToFile(fv); sprintf(fn, "win%d_outaln.tmp", uWindowIndex); TextFile fOut(fn, true); msaTmp.ToFile(fOut); } #if MEMDEBUG void FreeDPMemSPN(); FreeDPMemSPN(); _CrtMemState s2; _CrtMemCheckpoint(&s2); _CrtMemState s; _CrtMemDifference(&s, &s1, &s2); _CrtMemDumpStatistics(&s); _CrtMemDumpAllObjectsSince(&s1); exit(1); #endif //#if DEBUG // AssertMSAEqIgnoreCaseAndGaps(msaInTmp, msaTmp); //#endif } if (!g_bQuiet.get()) fprintf(stderr, "\n"); // AssertMSAEqIgnoreCaseAndGaps(msaIn, msaOut);//@@uncomment! }
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; }
void memory_leak_test(behaviac::Workspace::EFileFormat format) { #if ENABLE_MEMORYDUMP _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); _CrtDumpMemoryLeaks(); static long s_breakalloc = -1; _CrtSetBreakAlloc(s_breakalloc); #endif behaviac::IMemAllocator& allocator = behaviac::GetMemoryAllocator(); size_t allocatedSize = allocator.GetAllocatedSize(); #if ENABLE_MEMORYDUMP _CrtMemState s1; _CrtMemCheckpoint(&s1); #endif EmployeeParTestAgent::clearAllStaticMemberVariables(); behaviac::Profiler::CreateInstance(); behaviac::Config::SetSocketing(false); behaviac::Config::SetLogging(false); registerAllTypes(); EmployeeParTestAgent* myTestAgent = EmployeeParTestAgent::DynamicCast(behaviac::Agent::Create<EmployeeParTestAgent>()); behaviac::Agent::SetIdMask(1); myTestAgent->SetIdFlag(1); //myTestAgent->btload("par_test/register_name_as_left_value_and_param"); myTestAgent->btsetcurrent("par_test/register_name_as_left_value_and_param"); ParTestRegNameAgent::clearAllStaticMemberVariables(); behaviac::Agent::Create<ParTestRegNameAgent>("ParTestRegNameAgent"); ParTestRegNameAgent* regNameAgent = behaviac::Agent::GetInstance<ParTestRegNameAgent>("ParTestRegNameAgent"); regNameAgent->resetProperties(); myTestAgent->resetProperties(); myTestAgent->btexec(); behaviac::Agent::Destroy(regNameAgent); behaviac::Agent::UnRegisterInstanceName<ParTestRegNameAgent>("ParTestRegNameAgent"); BEHAVIAC_DELETE(myTestAgent); behaviac::Workspace::GetInstance()->UnLoadAll(); EmployeeParTestAgent::clearAllStaticMemberVariables(); ParTestRegNameAgent::clearAllStaticMemberVariables(); unregisterAllTypes(); behaviac::Profiler::DestroyInstance(); size_t allocatedSize1 = allocator.GetAllocatedSize(); size_t allocateDiff = allocatedSize1 - allocatedSize; #if !ENABLE_MEMORYDUMP //if CStringID is used before this test, CStringID::Cleaup() will free more memory //allocateDiff would be negative //CHECK_EQUAL(true, allocateDiff <= 0); CHECK_EQUAL(true, allocateDiff == 0); #endif #if ENABLE_MEMORYDUMP _CrtMemState s2; _CrtMemState s3; BEHAVIAC_UNUSED_VAR(s1); BEHAVIAC_UNUSED_VAR(s2); BEHAVIAC_UNUSED_VAR(s3); _CrtMemCheckpoint(&s2); //CHECK_EQUAL(0, _CrtMemDifference(&s3, &s1, &s2)); if (_CrtMemDifference(&s3, &s1, &s2)) { _CrtMemDumpStatistics(&s3); _CrtDumpMemoryLeaks(); } #endif BEHAVIAC_ASSERT(true); }
int main( int argc, char *argv[] ) { // Set the debug heap to report memory leaks when the process terminates, // and to keep freed blocks in the linked list. #ifndef LINUX //_CrtSetDbgFlag( _CRTDBG_LEAK_CHECK_DF | _CRTDBG_DELAY_FREE_MEM_DF ); /* TEST FOR MEMORY LEAKS:*/ _CrtMemState memstate; _CrtMemState memstate2; _CrtMemState memstate3; _CrtMemCheckpoint(&memstate); #endif #ifndef LINUX _CrtMemCheckpoint(&memstate2); _CrtMemDifference(&memstate3, &memstate, &memstate2); _RPT0(_CRT_WARN, "Here's what we allocated some notes...\n"); _CrtMemDumpStatistics(&memstate3); _CrtMemDumpAllObjectsSince( &memstate ); #endif if( argc < 3 ) { printf("Two arguments expected.\n"); printf("Need to run with one MIDI file and a specified directory.\n"); return 0; } if( argc == 3 ){ fprintf(stderr, "MIDI file to read in: %s\n", argv[1]); fprintf(stderr, "Directory to store files: %s\n", argv[2]); } if( argc > 3 ) { printf("Too many arguments supplied.\n"); printf("Need to run with one MIDI file and a specified directory.\n"); return 0; } char * FILENAME = argv[1]; Alg_seq_ptr seq = read_file(FILENAME); char * slash = strrchr(FILENAME,'/'); if(slash != 0){ //printf("%s\n", slash+1); FILENAME = slash + 1; } char FILENAME_gro[1000]; char * DIRECTORY = argv[2]; int i = 0; for(; i < strlen(DIRECTORY); i++){ FILENAME_gro[i] = DIRECTORY[i]; } int j = 0; for(; j < strrchr(FILENAME, '.') - FILENAME && j < 1000-5; j++){ FILENAME_gro[i+j] = FILENAME[j]; } FILENAME_gro[i+j] = '.'; FILENAME_gro[i+j+1] = 'g'; FILENAME_gro[i+j+2] = 'r'; FILENAME_gro[i+j+3] = 'o'; FILENAME_gro[i+j+4] = '\0'; // Saving MIDI file as .gro text fprintf(stderr, "save as text in %s...\n", FILENAME_gro); FILE *outf = fopen(FILENAME_gro, "w"); alg_write(seq, outf); fclose(outf); /**/ /* DELETE THE DATA */ delete seq; #ifndef LINUX _CrtDumpMemoryLeaks( ); #endif /**/ return 0; }
int main() { // // We start with the 'demoStart' todo list. Process it. And // should hopefully end up with the todo list as illustrated. // const char* demoStart = "<?xml version=\"1.0\" standalone='no' >\n" "<!-- Our to do list data -->" "<ToDo>\n" "<!-- Do I need a secure PDA? -->\n" "<Item priority=\"1\" distance='close'> Go to the <bold>Toy store!</bold></Item>" "<Item priority=\"2\" distance='none'> Do bills </Item>" "<Item priority=\"2\" distance='far & back'> Look for Evil Dinosaurs! </Item>" "</ToDo>"; { #ifdef TIXML_USE_STL // What the todo list should look like after processing. // In stream (no formatting) representation. const char* demoEnd = "<?xml version=\"1.0\" standalone=\"no\" ?>" "<!-- Our to do list data -->" "<ToDo>" "<!-- Do I need a secure PDA? -->" "<Item priority=\"2\" distance=\"close\">Go to the" "<bold>Toy store!" "</bold>" "</Item>" "<Item priority=\"1\" distance=\"far\">Talk to:" "<Meeting where=\"School\">" "<Attendee name=\"Marple\" position=\"teacher\" />" "<Attendee name=\"Voel\" position=\"counselor\" />" "</Meeting>" "<Meeting where=\"Lunch\" />" "</Item>" "<Item priority=\"2\" distance=\"here\">Do bills" "</Item>" "</ToDo>"; #endif // The example parses from the character string (above): #if defined( WIN32 ) && defined( TUNE ) _CrtMemCheckpoint( &startMemState ); #endif { // Write to a file and read it back, to check file I/O. TiXmlDocument doc( "demotest.xml" ); doc.Parse( demoStart ); if ( doc.Error() ) { printf( "Error in %s: %s\n", doc.Value(), doc.ErrorDesc() ); exit( 1 ); } doc.SaveFile(); } TiXmlDocument doc( "demotest.xml" ); bool loadOkay = doc.LoadFile(); if ( !loadOkay ) { printf( "Could not load test file 'demotest.xml'. Error='%s'. Exiting.\n", doc.ErrorDesc() ); exit( 1 ); } printf( "** Demo doc read from disk: ** \n\n" ); printf( "** Printing via doc.Print **\n" ); doc.Print( stdout ); { printf( "** Printing via TiXmlPrinter **\n" ); TiXmlPrinter printer; doc.Accept( &printer ); fprintf( stdout, "%s", printer.CStr() ); } #ifdef TIXML_USE_STL { printf( "** Printing via operator<< **\n" ); std::cout << doc; } #endif TiXmlNode* node = 0; TiXmlElement* todoElement = 0; TiXmlElement* itemElement = 0; // -------------------------------------------------------- // An example of changing existing attributes, and removing // an element from the document. // -------------------------------------------------------- // Get the "ToDo" element. // It is a child of the document, and can be selected by name. node = doc.FirstChild( "ToDo" ); assert( node ); todoElement = node->ToElement(); assert( todoElement ); // Going to the toy store is now our second priority... // So set the "priority" attribute of the first item in the list. node = todoElement->FirstChildElement(); // This skips the "PDA" comment. assert( node ); itemElement = node->ToElement(); assert( itemElement ); itemElement->SetAttribute( "priority", 2 ); // Change the distance to "doing bills" from // "none" to "here". It's the next sibling element. itemElement = itemElement->NextSiblingElement(); assert( itemElement ); itemElement->SetAttribute( "distance", "here" ); // Remove the "Look for Evil Dinosaurs!" item. // It is 1 more sibling away. We ask the parent to remove // a particular child. itemElement = itemElement->NextSiblingElement(); todoElement->RemoveChild( itemElement ); itemElement = 0; // -------------------------------------------------------- // What follows is an example of created elements and text // nodes and adding them to the document. // -------------------------------------------------------- // Add some meetings. TiXmlElement item( "Item" ); item.SetAttribute( "priority", "1" ); item.SetAttribute( "distance", "far" ); TiXmlText text( "Talk to:" ); TiXmlElement meeting1( "Meeting" ); meeting1.SetAttribute( "where", "School" ); TiXmlElement meeting2( "Meeting" ); meeting2.SetAttribute( "where", "Lunch" ); TiXmlElement attendee1( "Attendee" ); attendee1.SetAttribute( "name", "Marple" ); attendee1.SetAttribute( "position", "teacher" ); TiXmlElement attendee2( "Attendee" ); attendee2.SetAttribute( "name", "Voel" ); attendee2.SetAttribute( "position", "counselor" ); // Assemble the nodes we've created: meeting1.InsertEndChild( attendee1 ); meeting1.InsertEndChild( attendee2 ); item.InsertEndChild( text ); item.InsertEndChild( meeting1 ); item.InsertEndChild( meeting2 ); // And add the node to the existing list after the first child. node = todoElement->FirstChild( "Item" ); assert( node ); itemElement = node->ToElement(); assert( itemElement ); todoElement->InsertAfterChild( itemElement, item ); printf( "\n** Demo doc processed: ** \n\n" ); doc.Print( stdout ); #ifdef TIXML_USE_STL printf( "** Demo doc processed to stream: ** \n\n" ); cout << doc << endl << endl; #endif // -------------------------------------------------------- // Different tests...do we have what we expect? // -------------------------------------------------------- int count = 0; TiXmlElement* element; ////////////////////////////////////////////////////// #ifdef TIXML_USE_STL cout << "** Basic structure. **\n"; ostringstream outputStream( ostringstream::out ); outputStream << doc; XmlTest( "Output stream correct.", string( demoEnd ).c_str(), outputStream.str().c_str(), true ); #endif node = doc.RootElement(); assert( node ); XmlTest( "Root element exists.", true, ( node != 0 && node->ToElement() ) ); XmlTest ( "Root element value is 'ToDo'.", "ToDo", node->Value()); node = node->FirstChild(); XmlTest( "First child exists & is a comment.", true, ( node != 0 && node->ToComment() ) ); node = node->NextSibling(); XmlTest( "Sibling element exists & is an element.", true, ( node != 0 && node->ToElement() ) ); XmlTest ( "Value is 'Item'.", "Item", node->Value() ); node = node->FirstChild(); XmlTest ( "First child exists.", true, ( node != 0 && node->ToText() ) ); XmlTest ( "Value is 'Go to the'.", "Go to the", node->Value() ); ////////////////////////////////////////////////////// printf ("\n** Iterators. **\n"); // Walk all the top level nodes of the document. count = 0; for( node = doc.FirstChild(); node; node = node->NextSibling() ) { count++; } XmlTest( "Top level nodes, using First / Next.", 3, count ); count = 0; for( node = doc.LastChild(); node; node = node->PreviousSibling() ) { count++; } XmlTest( "Top level nodes, using Last / Previous.", 3, count ); // Walk all the top level nodes of the document, // using a different syntax. count = 0; for( node = doc.IterateChildren( 0 ); node; node = doc.IterateChildren( node ) ) { count++; } XmlTest( "Top level nodes, using IterateChildren.", 3, count ); // Walk all the elements in a node. count = 0; for( element = todoElement->FirstChildElement(); element; element = element->NextSiblingElement() ) { count++; } XmlTest( "Children of the 'ToDo' element, using First / Next.", 3, count ); // Walk all the elements in a node by value. count = 0; for( node = todoElement->FirstChild( "Item" ); node; node = node->NextSibling( "Item" ) ) { count++; } XmlTest( "'Item' children of the 'ToDo' element, using First/Next.", 3, count ); count = 0; for( node = todoElement->LastChild( "Item" ); node; node = node->PreviousSibling( "Item" ) ) { count++; } XmlTest( "'Item' children of the 'ToDo' element, using Last/Previous.", 3, count ); #ifdef TIXML_USE_STL { cout << "\n** Parsing. **\n"; istringstream parse0( "<Element0 attribute0='foo0' attribute1= noquotes attribute2 = '>' />" ); TiXmlElement element0( "default" ); parse0 >> element0; XmlTest ( "Element parsed, value is 'Element0'.", "Element0", element0.Value() ); XmlTest ( "Reads attribute 'attribute0=\"foo0\"'.", "foo0", element0.Attribute( "attribute0" )); XmlTest ( "Reads incorrectly formatted 'attribute1=noquotes'.", "noquotes", element0.Attribute( "attribute1" ) ); XmlTest ( "Read attribute with entity value '>'.", ">", element0.Attribute( "attribute2" ) ); } #endif { const char* error = "<?xml version=\"1.0\" standalone=\"no\" ?>\n" "<passages count=\"006\" formatversion=\"20020620\">\n" " <wrong error>\n" "</passages>"; TiXmlDocument docTest; docTest.Parse( error ); XmlTest( "Error row", docTest.ErrorRow(), 3 ); XmlTest( "Error column", docTest.ErrorCol(), 17 ); //printf( "error=%d id='%s' row %d col%d\n", (int) doc.Error(), doc.ErrorDesc(), doc.ErrorRow()+1, doc.ErrorCol() + 1 ); } #ifdef TIXML_USE_STL { ////////////////////////////////////////////////////// cout << "\n** Streaming. **\n"; // Round trip check: stream in, then stream back out to verify. The stream // out has already been checked, above. We use the output istringstream inputStringStream( outputStream.str() ); TiXmlDocument document0; inputStringStream >> document0; ostringstream outputStream0( ostringstream::out ); outputStream0 << document0; XmlTest( "Stream round trip correct.", string( demoEnd ).c_str(), outputStream0.str().c_str(), true ); std::string str; str << document0; XmlTest( "String printing correct.", string( demoEnd ).c_str(), str.c_str(), true ); } #endif } { const char* str = "<doc attr0='1' attr1='2.0' attr2='foo' />"; TiXmlDocument doc; doc.Parse( str ); TiXmlElement* ele = doc.FirstChildElement(); int iVal, result; double dVal; result = ele->QueryDoubleAttribute( "attr0", &dVal ); XmlTest( "Query attribute: int as double", result, TIXML_SUCCESS ); XmlTest( "Query attribute: int as double", (int)dVal, 1 ); result = ele->QueryDoubleAttribute( "attr1", &dVal ); XmlTest( "Query attribute: double as double", (int)dVal, 2 ); result = ele->QueryIntAttribute( "attr1", &iVal ); XmlTest( "Query attribute: double as int", result, TIXML_SUCCESS ); XmlTest( "Query attribute: double as int", iVal, 2 ); result = ele->QueryIntAttribute( "attr2", &iVal ); XmlTest( "Query attribute: not a number", result, TIXML_WRONG_TYPE ); result = ele->QueryIntAttribute( "bar", &iVal ); XmlTest( "Query attribute: does not exist", result, TIXML_NO_ATTRIBUTE ); } { const char* str = "<doc/>"; TiXmlDocument doc; doc.Parse( str ); TiXmlElement* ele = doc.FirstChildElement(); int iVal; double dVal; ele->SetAttribute( "str", "strValue" ); ele->SetAttribute( "int", 1 ); ele->SetDoubleAttribute( "double", -1.0 ); const char* cStr = ele->Attribute( "str" ); ele->QueryIntAttribute( "int", &iVal ); ele->QueryDoubleAttribute( "double", &dVal ); XmlTest( "Attribute round trip. c-string.", "strValue", cStr ); XmlTest( "Attribute round trip. int.", 1, iVal ); XmlTest( "Attribute round trip. double.", -1, (int)dVal ); } { const char* str = "\t<?xml version=\"1.0\" standalone=\"no\" ?>\t<room doors='2'>\n" "</room>"; TiXmlDocument doc; doc.SetTabSize( 8 ); doc.Parse( str ); TiXmlHandle docHandle( &doc ); TiXmlHandle roomHandle = docHandle.FirstChildElement( "room" ); assert( docHandle.Node() ); assert( roomHandle.Element() ); TiXmlElement* room = roomHandle.Element(); assert( room ); TiXmlAttribute* doors = room->FirstAttribute(); assert( doors ); XmlTest( "Location tracking: Tab 8: room row", room->Row(), 1 ); XmlTest( "Location tracking: Tab 8: room col", room->Column(), 49 ); XmlTest( "Location tracking: Tab 8: doors row", doors->Row(), 1 ); XmlTest( "Location tracking: Tab 8: doors col", doors->Column(), 55 ); } { const char* str = "\t<?xml version=\"1.0\" standalone=\"no\" ?>\t<room doors='2'>\n" " <!-- Silly example -->\n" " <door wall='north'>A great door!</door>\n" "\t<door wall='east'/>" "</room>"; TiXmlDocument doc; doc.Parse( str ); TiXmlHandle docHandle( &doc ); TiXmlHandle roomHandle = docHandle.FirstChildElement( "room" ); TiXmlHandle commentHandle = docHandle.FirstChildElement( "room" ).FirstChild(); TiXmlHandle textHandle = docHandle.FirstChildElement( "room" ).ChildElement( "door", 0 ).FirstChild(); TiXmlHandle door0Handle = docHandle.FirstChildElement( "room" ).ChildElement( 0 ); TiXmlHandle door1Handle = docHandle.FirstChildElement( "room" ).ChildElement( 1 ); assert( docHandle.Node() ); assert( roomHandle.Element() ); assert( commentHandle.Node() ); assert( textHandle.Text() ); assert( door0Handle.Element() ); assert( door1Handle.Element() ); TiXmlDeclaration* declaration = doc.FirstChild()->ToDeclaration(); assert( declaration ); TiXmlElement* room = roomHandle.Element(); assert( room ); TiXmlAttribute* doors = room->FirstAttribute(); assert( doors ); TiXmlText* text = textHandle.Text(); TiXmlComment* comment = commentHandle.Node()->ToComment(); assert( comment ); TiXmlElement* door0 = door0Handle.Element(); TiXmlElement* door1 = door1Handle.Element(); XmlTest( "Location tracking: Declaration row", declaration->Row(), 1 ); XmlTest( "Location tracking: Declaration col", declaration->Column(), 5 ); XmlTest( "Location tracking: room row", room->Row(), 1 ); XmlTest( "Location tracking: room col", room->Column(), 45 ); XmlTest( "Location tracking: doors row", doors->Row(), 1 ); XmlTest( "Location tracking: doors col", doors->Column(), 51 ); XmlTest( "Location tracking: Comment row", comment->Row(), 2 ); XmlTest( "Location tracking: Comment col", comment->Column(), 3 ); XmlTest( "Location tracking: text row", text->Row(), 3 ); XmlTest( "Location tracking: text col", text->Column(), 24 ); XmlTest( "Location tracking: door0 row", door0->Row(), 3 ); XmlTest( "Location tracking: door0 col", door0->Column(), 5 ); XmlTest( "Location tracking: door1 row", door1->Row(), 4 ); XmlTest( "Location tracking: door1 col", door1->Column(), 5 ); } // -------------------------------------------------------- // UTF-8 testing. It is important to test: // 1. Making sure name, value, and text read correctly // 2. Row, Col functionality // 3. Correct output // -------------------------------------------------------- printf ("\n** UTF-8 **\n"); { TiXmlDocument doc( "utf8test.xml" ); doc.LoadFile(); if ( doc.Error() && doc.ErrorId() == TiXmlBase::TIXML_ERROR_OPENING_FILE ) { printf( "WARNING: File 'utf8test.xml' not found.\n" "(Are you running the test from the wrong directory?)\n" "Could not test UTF-8 functionality.\n" ); } else { TiXmlHandle docH( &doc ); // Get the attribute "value" from the "Russian" element and check it. TiXmlElement* element = docH.FirstChildElement( "document" ).FirstChildElement( "Russian" ).Element(); const unsigned char correctValue[] = { 0xd1U, 0x86U, 0xd0U, 0xb5U, 0xd0U, 0xbdU, 0xd0U, 0xbdU, 0xd0U, 0xbeU, 0xd1U, 0x81U, 0xd1U, 0x82U, 0xd1U, 0x8cU, 0 }; XmlTest( "UTF-8: Russian value.", (const char*)correctValue, element->Attribute( "value" ), true ); XmlTest( "UTF-8: Russian value row.", 4, element->Row() ); XmlTest( "UTF-8: Russian value column.", 5, element->Column() ); const unsigned char russianElementName[] = { 0xd0U, 0xa0U, 0xd1U, 0x83U, 0xd1U, 0x81U, 0xd1U, 0x81U, 0xd0U, 0xbaU, 0xd0U, 0xb8U, 0xd0U, 0xb9U, 0 }; const char russianText[] = "<\xD0\xB8\xD0\xBC\xD0\xB5\xD0\xB5\xD1\x82>"; TiXmlText* text = docH.FirstChildElement( "document" ).FirstChildElement( (const char*) russianElementName ).Child( 0 ).Text(); XmlTest( "UTF-8: Browsing russian element name.", russianText, text->Value(), true ); XmlTest( "UTF-8: Russian element name row.", 7, text->Row() ); XmlTest( "UTF-8: Russian element name column.", 47, text->Column() ); TiXmlDeclaration* dec = docH.Child( 0 ).Node()->ToDeclaration(); XmlTest( "UTF-8: Declaration column.", 1, dec->Column() ); XmlTest( "UTF-8: Document column.", 1, doc.Column() ); // Now try for a round trip. doc.SaveFile( "utf8testout.xml" ); // Check the round trip. char savedBuf[256]; char verifyBuf[256]; int okay = 1; FILE* saved = fopen( "data/utf8testout.xml", "r" ); FILE* verify = fopen( "data/utf8testverify.xml", "r" ); //bool firstLineBOM=true; if ( saved && verify ) { while ( fgets( verifyBuf, 256, verify ) ) { fgets( savedBuf, 256, saved ); NullLineEndings( verifyBuf ); NullLineEndings( savedBuf ); if ( /*!firstLineBOM && */ strcmp( verifyBuf, savedBuf ) ) { printf( "verify:%s<\n", verifyBuf ); printf( "saved :%s<\n", savedBuf ); okay = 0; break; } //firstLineBOM = false; } } if ( saved ) fclose( saved ); if ( verify ) fclose( verify ); XmlTest( "UTF-8: Verified multi-language round trip.", 1, okay ); // On most Western machines, this is an element that contains // the word "resume" with the correct accents, in a latin encoding. // It will be something else completely on non-wester machines, // which is why TinyXml is switching to UTF-8. const char latin[] = "<element>r\x82sum\x82</element>"; TiXmlDocument latinDoc; latinDoc.Parse( latin, 0, TIXML_ENCODING_LEGACY ); text = latinDoc.FirstChildElement()->FirstChild()->ToText(); XmlTest( "Legacy encoding: Verify text element.", "r\x82sum\x82", text->Value() ); } } ////////////////////// // Copy and assignment ////////////////////// printf ("\n** Copy and Assignment **\n"); { TiXmlElement element( "foo" ); element.Parse( "<element name='value' />", 0, TIXML_ENCODING_UNKNOWN ); TiXmlElement elementCopy( element ); TiXmlElement elementAssign( "foo" ); elementAssign.Parse( "<incorrect foo='bar'/>", 0, TIXML_ENCODING_UNKNOWN ); elementAssign = element; XmlTest( "Copy/Assign: element copy #1.", "element", elementCopy.Value() ); XmlTest( "Copy/Assign: element copy #2.", "value", elementCopy.Attribute( "name" ) ); XmlTest( "Copy/Assign: element assign #1.", "element", elementAssign.Value() ); XmlTest( "Copy/Assign: element assign #2.", "value", elementAssign.Attribute( "name" ) ); XmlTest( "Copy/Assign: element assign #3.", true, ( 0 == elementAssign.Attribute( "foo" )) ); TiXmlComment comment; comment.Parse( "<!--comment-->", 0, TIXML_ENCODING_UNKNOWN ); TiXmlComment commentCopy( comment ); TiXmlComment commentAssign; commentAssign = commentCopy; XmlTest( "Copy/Assign: comment copy.", "comment", commentCopy.Value() ); XmlTest( "Copy/Assign: comment assign.", "comment", commentAssign.Value() ); TiXmlUnknown unknown; unknown.Parse( "<[unknown]>", 0, TIXML_ENCODING_UNKNOWN ); TiXmlUnknown unknownCopy( unknown ); TiXmlUnknown unknownAssign; unknownAssign.Parse( "incorrect", 0, TIXML_ENCODING_UNKNOWN ); unknownAssign = unknownCopy; XmlTest( "Copy/Assign: unknown copy.", "[unknown]", unknownCopy.Value() ); XmlTest( "Copy/Assign: unknown assign.", "[unknown]", unknownAssign.Value() ); TiXmlText text( "TextNode" ); TiXmlText textCopy( text ); TiXmlText textAssign( "incorrect" ); textAssign = text; XmlTest( "Copy/Assign: text copy.", "TextNode", textCopy.Value() ); XmlTest( "Copy/Assign: text assign.", "TextNode", textAssign.Value() ); TiXmlDeclaration dec; dec.Parse( "<?xml version='1.0' encoding='UTF-8'?>", 0, TIXML_ENCODING_UNKNOWN ); TiXmlDeclaration decCopy( dec ); TiXmlDeclaration decAssign; decAssign = dec; XmlTest( "Copy/Assign: declaration copy.", "UTF-8", decCopy.Encoding() ); XmlTest( "Copy/Assign: text assign.", "UTF-8", decAssign.Encoding() ); TiXmlDocument doc; elementCopy.InsertEndChild( textCopy ); doc.InsertEndChild( decAssign ); doc.InsertEndChild( elementCopy ); doc.InsertEndChild( unknownAssign ); TiXmlDocument docCopy( doc ); TiXmlDocument docAssign; docAssign = docCopy; #ifdef TIXML_USE_STL std::string original, copy, assign; original << doc; copy << docCopy; assign << docAssign; XmlTest( "Copy/Assign: document copy.", original.c_str(), copy.c_str(), true ); XmlTest( "Copy/Assign: document assign.", original.c_str(), assign.c_str(), true ); #endif } ////////////////////////////////////////////////////// #ifdef TIXML_USE_STL printf ("\n** Parsing, no Condense Whitespace **\n"); TiXmlBase::SetCondenseWhiteSpace( false ); { istringstream parse1( "<start>This is \ntext</start>" ); TiXmlElement text1( "text" ); parse1 >> text1; XmlTest ( "Condense white space OFF.", "This is \ntext", text1.FirstChild()->Value(), true ); } TiXmlBase::SetCondenseWhiteSpace( true ); #endif ////////////////////////////////////////////////////// // GetText(); { const char* str = "<foo>This is text</foo>"; TiXmlDocument doc; doc.Parse( str ); const TiXmlElement* element = doc.RootElement(); XmlTest( "GetText() normal use.", "This is text", element->GetText() ); str = "<foo><b>This is text</b></foo>"; doc.Clear(); doc.Parse( str ); element = doc.RootElement(); XmlTest( "GetText() contained element.", element->GetText() == 0, true ); str = "<foo>This is <b>text</b></foo>"; doc.Clear(); TiXmlBase::SetCondenseWhiteSpace( false ); doc.Parse( str ); TiXmlBase::SetCondenseWhiteSpace( true ); element = doc.RootElement(); XmlTest( "GetText() partial.", "This is ", element->GetText() ); } ////////////////////////////////////////////////////// // CDATA { const char* str = "<xmlElement>" "<![CDATA[" "I am > the rules!\n" "...since I make symbolic puns" "]]>" "</xmlElement>"; TiXmlDocument doc; doc.Parse( str ); doc.Print(); XmlTest( "CDATA parse.", doc.FirstChildElement()->FirstChild()->Value(), "I am > the rules!\n...since I make symbolic puns", true ); #ifdef TIXML_USE_STL //cout << doc << '\n'; doc.Clear(); istringstream parse0( str ); parse0 >> doc; //cout << doc << '\n'; XmlTest( "CDATA stream.", doc.FirstChildElement()->FirstChild()->Value(), "I am > the rules!\n...since I make symbolic puns", true ); #endif TiXmlDocument doc1 = doc; //doc.Print(); XmlTest( "CDATA copy.", doc1.FirstChildElement()->FirstChild()->Value(), "I am > the rules!\n...since I make symbolic puns", true ); } { // [ 1482728 ] Wrong wide char parsing char buf[256]; buf[255] = 0; for( int i=0; i<255; ++i ) { buf[i] = (char)((i>=32) ? i : 32); } TIXML_STRING str( "<xmlElement><![CDATA[" ); str += buf; str += "]]></xmlElement>"; TiXmlDocument doc; doc.Parse( str.c_str() ); TiXmlPrinter printer; printer.SetStreamPrinting(); doc.Accept( &printer ); XmlTest( "CDATA with all bytes #1.", str.c_str(), printer.CStr(), true ); #ifdef TIXML_USE_STL doc.Clear(); istringstream iss( printer.Str() ); iss >> doc; std::string out; out << doc; XmlTest( "CDATA with all bytes #2.", out.c_str(), printer.CStr(), true ); #endif } { // [ 1480107 ] Bug-fix for STL-streaming of CDATA that contains tags // CDATA streaming had a couple of bugs, that this tests for. const char* str = "<xmlElement>" "<![CDATA[" "<b>I am > the rules!</b>\n" "...since I make symbolic puns" "]]>" "</xmlElement>"; TiXmlDocument doc; doc.Parse( str ); doc.Print(); XmlTest( "CDATA parse. [ 1480107 ]", doc.FirstChildElement()->FirstChild()->Value(), "<b>I am > the rules!</b>\n...since I make symbolic puns", true ); #ifdef TIXML_USE_STL doc.Clear(); istringstream parse0( str ); parse0 >> doc; XmlTest( "CDATA stream. [ 1480107 ]", doc.FirstChildElement()->FirstChild()->Value(), "<b>I am > the rules!</b>\n...since I make symbolic puns", true ); #endif TiXmlDocument doc1 = doc; //doc.Print(); XmlTest( "CDATA copy. [ 1480107 ]", doc1.FirstChildElement()->FirstChild()->Value(), "<b>I am > the rules!</b>\n...since I make symbolic puns", true ); } ////////////////////////////////////////////////////// // Visit() ////////////////////////////////////////////////////// printf( "\n** Fuzzing... **\n" ); const int FUZZ_ITERATION = 300; // The only goal is not to crash on bad input. int len = (int) strlen( demoStart ); for( int i=0; i<FUZZ_ITERATION; ++i ) { char* demoCopy = new char[ len+1 ]; strcpy( demoCopy, demoStart ); demoCopy[ i%len ] = (char)((i+1)*3); demoCopy[ (i*7)%len ] = '>'; demoCopy[ (i*11)%len ] = '<'; TiXmlDocument xml; xml.Parse( demoCopy ); delete [] demoCopy; } printf( "** Fuzzing Complete. **\n" ); ////////////////////////////////////////////////////// printf ("\n** Bug regression tests **\n"); // InsertBeforeChild and InsertAfterChild causes crash. { TiXmlElement parent( "Parent" ); TiXmlElement childText0( "childText0" ); TiXmlElement childText1( "childText1" ); TiXmlNode* childNode0 = parent.InsertEndChild( childText0 ); TiXmlNode* childNode1 = parent.InsertBeforeChild( childNode0, childText1 ); XmlTest( "Test InsertBeforeChild on empty node.", ( childNode1 == parent.FirstChild() ), true ); } { // InsertBeforeChild and InsertAfterChild causes crash. TiXmlElement parent( "Parent" ); TiXmlElement childText0( "childText0" ); TiXmlElement childText1( "childText1" ); TiXmlNode* childNode0 = parent.InsertEndChild( childText0 ); TiXmlNode* childNode1 = parent.InsertAfterChild( childNode0, childText1 ); XmlTest( "Test InsertAfterChild on empty node. ", ( childNode1 == parent.LastChild() ), true ); } // Reports of missing constructors, irregular string problems. { // Missing constructor implementation. No test -- just compiles. TiXmlText text( "Missing" ); #ifdef TIXML_USE_STL // Missing implementation: TiXmlDocument doc; string name = "missing"; doc.LoadFile( name ); TiXmlText textSTL( name ); #else // verifying some basic string functions: TiXmlString a; TiXmlString b( "Hello" ); TiXmlString c( "ooga" ); c = " World!"; a = b; a += c; a = a; XmlTest( "Basic TiXmlString test. ", "Hello World!", a.c_str() ); #endif } // Long filenames crashing STL version { TiXmlDocument doc( "midsummerNightsDreamWithAVeryLongFilenameToConfuseTheStringHandlingRoutines.xml" ); bool loadOkay = doc.LoadFile(); loadOkay = true; // get rid of compiler warning. // Won't pass on non-dev systems. Just a "no crash" check. //XmlTest( "Long filename. ", true, loadOkay ); } { // Entities not being written correctly. // From Lynn Allen const char* passages = "<?xml version=\"1.0\" standalone=\"no\" ?>" "<passages count=\"006\" formatversion=\"20020620\">" "<psg context=\"Line 5 has "quotation marks" and 'apostrophe marks'." " It also has <, >, and &, as well as a fake copyright ©.\"> </psg>" "</passages>"; TiXmlDocument doc( "passages.xml" ); doc.Parse( passages ); TiXmlElement* psg = doc.RootElement()->FirstChildElement(); const char* context = psg->Attribute( "context" ); const char* expected = "Line 5 has \"quotation marks\" and 'apostrophe marks'. It also has <, >, and &, as well as a fake copyright \xC2\xA9."; XmlTest( "Entity transformation: read. ", expected, context, true ); FILE* textfile = fopen( "textfile.txt", "w" ); if ( textfile ) { psg->Print( textfile, 0 ); fclose( textfile ); } textfile = fopen( "textfile.txt", "r" ); assert( textfile ); if ( textfile ) { char buf[ 1024 ]; fgets( buf, 1024, textfile ); XmlTest( "Entity transformation: write. ", "<psg context=\'Line 5 has "quotation marks" and 'apostrophe marks'." " It also has <, >, and &, as well as a fake copyright \xC2\xA9.' />", buf, true ); } fclose( textfile ); } { FILE* textfile = fopen( "test5.xml", "w" ); if ( textfile ) { fputs("<?xml version='1.0'?><a.elem xmi.version='2.0'/>", textfile); fclose(textfile); TiXmlDocument doc; doc.LoadFile( "test5.xml" ); XmlTest( "dot in element attributes and names", doc.Error(), 0); } } { FILE* textfile = fopen( "test6.xml", "w" ); if ( textfile ) { fputs("<element><Name>1.1 Start easy ignore fin thickness
</Name></element>", textfile ); fclose(textfile); TiXmlDocument doc; bool result = doc.LoadFile( "test6.xml" ); XmlTest( "Entity with one digit.", result, true ); TiXmlText* text = doc.FirstChildElement()->FirstChildElement()->FirstChild()->ToText(); XmlTest( "Entity with one digit.", text->Value(), "1.1 Start easy ignore fin thickness\n" ); } } { // DOCTYPE not preserved (950171) // const char* doctype = "<?xml version=\"1.0\" ?>" "<!DOCTYPE PLAY SYSTEM 'play.dtd'>" "<!ELEMENT title (#PCDATA)>" "<!ELEMENT books (title,authors)>" "<element />"; TiXmlDocument doc; doc.Parse( doctype ); doc.SaveFile( "test7.xml" ); doc.Clear(); doc.LoadFile( "test7.xml" ); TiXmlHandle docH( &doc ); TiXmlUnknown* unknown = docH.Child( 1 ).Unknown(); XmlTest( "Correct value of unknown.", "!DOCTYPE PLAY SYSTEM 'play.dtd'", unknown->Value() ); #ifdef TIXML_USE_STL TiXmlNode* node = docH.Child( 2 ).Node(); std::string str; str << (*node); XmlTest( "Correct streaming of unknown.", "<!ELEMENT title (#PCDATA)>", str.c_str() ); #endif } { // [ 791411 ] Formatting bug // Comments do not stream out correctly. const char* doctype = "<!-- Somewhat<evil> -->"; TiXmlDocument doc; doc.Parse( doctype ); TiXmlHandle docH( &doc ); TiXmlComment* comment = docH.Child( 0 ).Node()->ToComment(); XmlTest( "Comment formatting.", " Somewhat<evil> ", comment->Value() ); #ifdef TIXML_USE_STL std::string str; str << (*comment); XmlTest( "Comment streaming.", "<!-- Somewhat<evil> -->", str.c_str() ); #endif } { // [ 870502 ] White space issues TiXmlDocument doc; TiXmlText* text; TiXmlHandle docH( &doc ); const char* doctype0 = "<element> This has leading and trailing space </element>"; const char* doctype1 = "<element>This has internal space</element>"; const char* doctype2 = "<element> This has leading, trailing, and internal space </element>"; TiXmlBase::SetCondenseWhiteSpace( false ); doc.Clear(); doc.Parse( doctype0 ); text = docH.FirstChildElement( "element" ).Child( 0 ).Text(); XmlTest( "White space kept.", " This has leading and trailing space ", text->Value() ); doc.Clear(); doc.Parse( doctype1 ); text = docH.FirstChildElement( "element" ).Child( 0 ).Text(); XmlTest( "White space kept.", "This has internal space", text->Value() ); doc.Clear(); doc.Parse( doctype2 ); text = docH.FirstChildElement( "element" ).Child( 0 ).Text(); XmlTest( "White space kept.", " This has leading, trailing, and internal space ", text->Value() ); TiXmlBase::SetCondenseWhiteSpace( true ); doc.Clear(); doc.Parse( doctype0 ); text = docH.FirstChildElement( "element" ).Child( 0 ).Text(); XmlTest( "White space condensed.", "This has leading and trailing space", text->Value() ); doc.Clear(); doc.Parse( doctype1 ); text = docH.FirstChildElement( "element" ).Child( 0 ).Text(); XmlTest( "White space condensed.", "This has internal space", text->Value() ); doc.Clear(); doc.Parse( doctype2 ); text = docH.FirstChildElement( "element" ).Child( 0 ).Text(); XmlTest( "White space condensed.", "This has leading, trailing, and internal space", text->Value() ); } { // Double attributes const char* doctype = "<element attr='red' attr='blue' />"; TiXmlDocument doc; doc.Parse( doctype ); XmlTest( "Parsing repeated attributes.", true, doc.Error() ); // is an error to tinyxml (didn't use to be, but caused issues) //XmlTest( "Parsing repeated attributes.", "blue", doc.FirstChildElement( "element" )->Attribute( "attr" ) ); } { // Embedded null in stream. const char* doctype = "<element att\0r='red' attr='blue' />"; TiXmlDocument doc; doc.Parse( doctype ); XmlTest( "Embedded null throws error.", true, doc.Error() ); #ifdef TIXML_USE_STL istringstream strm( doctype ); doc.Clear(); doc.ClearError(); strm >> doc; XmlTest( "Embedded null throws error.", true, doc.Error() ); #endif } { /** // Legacy mode test. (This test may only pass on a western system) const char* str = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" "<?" "C鰊t鋘t咪鳇闹?" "</?"; TiXmlDocument doc; doc.Parse( str ); TiXmlHandle docHandle( &doc ); TiXmlHandle aHandle = docHandle.FirstChildElement( "?" ); TiXmlHandle tHandle = aHandle.Child( 0 ); assert( aHandle.Element() ); assert( tHandle.Text() ); XmlTest( "ISO-8859-1 Parsing.", "C鰊t鋘t咪鳇闹?, tHandle.Text()->Value() "); } { // Empty documents should return TIXML_ERROR_PARSING_EMPTY, bug 1070717 const char* str = " "; TiXmlDocument doc; doc.Parse( str ); XmlTest( "Empty document error TIXML_ERROR_DOCUMENT_EMPTY", TiXmlBase::TIXML_ERROR_DOCUMENT_EMPTY, doc.ErrorId() ); } #ifndef TIXML_USE_STL { // String equality. [ 1006409 ] string operator==/!= no worky in all cases TiXmlString temp; XmlTest( "Empty tinyxml string compare equal", ( temp == "" ), true ); TiXmlString foo; TiXmlString bar( "" ); XmlTest( "Empty tinyxml string compare equal", ( foo == bar ), true ); } #endif { // Bug [ 1195696 ] from marlonism TiXmlBase::SetCondenseWhiteSpace(false); TiXmlDocument xml; xml.Parse("<text><break/>This hangs</text>"); XmlTest( "Test safe error return.", xml.Error(), false ); } { // Bug [ 1243992 ] - another infinite loop TiXmlDocument doc; doc.SetCondenseWhiteSpace(false); doc.Parse("<p><pb></pb>test</p>"); } { // Low entities TiXmlDocument xml; xml.Parse( "<test></test>" ); const char result[] = { 0x0e, 0 }; XmlTest( "Low entities.", xml.FirstChildElement()->GetText(), result ); xml.Print(); } { // Bug [ 1451649 ] Attribute values with trailing quotes not handled correctly TiXmlDocument xml; xml.Parse( "<foo attribute=bar\" />" ); XmlTest( "Throw error with bad end quotes.", xml.Error(), true ); } #ifdef TIXML_USE_STL { // Bug [ 1449463 ] Consider generic query TiXmlDocument xml; xml.Parse( "<foo bar='3' barStr='a string'/>" ); TiXmlElement* ele = xml.FirstChildElement(); double d; int i; float f; bool b; std::string str; XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "bar", &d ), TIXML_SUCCESS ); XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "bar", &i ), TIXML_SUCCESS ); XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "bar", &f ), TIXML_SUCCESS ); XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "bar", &b ), TIXML_WRONG_TYPE ); XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "nobar", &b ), TIXML_NO_ATTRIBUTE ); XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "barStr", &str ), TIXML_SUCCESS ); XmlTest( "QueryValueAttribute", (d==3.0), true ); XmlTest( "QueryValueAttribute", (i==3), true ); XmlTest( "QueryValueAttribute", (f==3.0f), true ); XmlTest( "QueryValueAttribute", (str==std::string( "a string" )), true ); } #endif #ifdef TIXML_USE_STL { // [ 1505267 ] redundant malloc in TiXmlElement::Attribute TiXmlDocument xml; xml.Parse( "<foo bar='3' />" ); TiXmlElement* ele = xml.FirstChildElement(); double d; int i; std::string bar = "bar"; const std::string* atrrib = ele->Attribute( bar ); ele->Attribute( bar, &d ); ele->Attribute( bar, &i ); XmlTest( "Attribute", atrrib->empty(), false ); XmlTest( "Attribute", (d==3.0), true ); XmlTest( "Attribute", (i==3), true ); } #endif { // [ 1356059 ] Allow TiXMLDocument to only be at the top level TiXmlDocument xml, xml2; xml.InsertEndChild( xml2 ); XmlTest( "Document only at top level.", xml.Error(), true ); XmlTest( "Document only at top level.", xml.ErrorId(), TiXmlBase::TIXML_ERROR_DOCUMENT_TOP_ONLY ); } { // [ 1663758 ] Failure to report error on bad XML TiXmlDocument xml; xml.Parse("<x>"); XmlTest("Missing end tag at end of input", xml.Error(), true); xml.Parse("<x> "); XmlTest("Missing end tag with trailing whitespace", xml.Error(), true); } { // [ 1635701 ] fail to parse files with a tag separated into two lines // I'm not sure this is a bug. Marked 'pending' for feedback. TiXmlDocument xml; xml.Parse( "<title><p>text</p\n><title>" ); //xml.Print(); //XmlTest( "Tag split by newline", xml.Error(), false ); } #ifdef TIXML_USE_STL { // [ 1475201 ] TinyXML parses entities in comments TiXmlDocument xml; istringstream parse1( "<!-- declarations for <head> & <body> -->" "<!-- far & away -->" ); parse1 >> xml; TiXmlNode* e0 = xml.FirstChild(); TiXmlNode* e1 = e0->NextSibling(); TiXmlComment* c0 = e0->ToComment(); TiXmlComment* c1 = e1->ToComment(); XmlTest( "Comments ignore entities.", " declarations for <head> & <body> ", c0->Value(), true ); XmlTest( "Comments ignore entities.", " far & away ", c1->Value(), true ); } #endif { // [ 1475201 ] TinyXML parses entities in comments TiXmlDocument xml; xml.Parse("<!-- declarations for <head> & <body> -->" "<!-- far & away -->" ); TiXmlNode* e0 = xml.FirstChild(); TiXmlNode* e1 = e0->NextSibling(); TiXmlComment* c0 = e0->ToComment(); TiXmlComment* c1 = e1->ToComment(); XmlTest( "Comments ignore entities.", " declarations for <head> & <body> ", c0->Value(), true ); XmlTest( "Comments ignore entities.", " far & away ", c1->Value(), true ); } { TiXmlDocument xml; xml.Parse( "<Parent>" "<child1 att=''/>" "<!-- With this comment, child2 will not be parsed! -->" "<child2 att=''/>" "</Parent>" ); int count = 0; TiXmlNode* ele = 0; while ( (ele = xml.FirstChildElement( "Parent" )->IterateChildren( ele ) ) != 0 ) { ++count; } XmlTest( "Comments iterate correctly.", 3, count ); } { // trying to repro ]1874301]. If it doesn't go into an infinite loop, all is well. unsigned char buf[] = "<?xml version=\"1.0\" encoding=\"utf-8\"?><feed><![CDATA[Test XMLblablablalblbl"; buf[60] = 239; buf[61] = 0; TiXmlDocument doc; doc.Parse( (const char*)buf); } { // bug 1827248 Error while parsing a little bit malformed file // Actually not malformed - should work. TiXmlDocument xml; xml.Parse( "<attributelist> </attributelist >" ); XmlTest( "Handle end tag whitespace", false, xml.Error() ); } { // This one must not result in an infinite loop TiXmlDocument xml; xml.Parse( "<infinite>loop" ); XmlTest( "Infinite loop test.", true, true ); } { // 1709904 - can not repro the crash { TiXmlDocument xml; xml.Parse( "<tag>/</tag>" ); XmlTest( "Odd XML parsing.", xml.FirstChild()->Value(), "tag" ); } /* Could not repro. { TiXmlDocument xml; xml.LoadFile( "EQUI_Inventory.xml" ); //XmlTest( "Odd XML parsing.", xml.FirstChildElement()->Value(), "XML" ); TiXmlPrinter printer; xml.Accept( &printer ); fprintf( stdout, "%s", printer.CStr() ); }*/ } /* 1417717 experiment { TiXmlDocument xml; xml.Parse("<text>Dan & Tracie</text>"); xml.Print(stdout); } { TiXmlDocument xml; xml.Parse("<text>Dan &foo; Tracie</text>"); xml.Print(stdout); } */ #if defined( WIN32 ) && defined( TUNE ) _CrtMemCheckpoint( &endMemState ); //_CrtMemDumpStatistics( &endMemState ); _CrtMemState diffMemState; _CrtMemDifference( &diffMemState, &startMemState, &endMemState ); _CrtMemDumpStatistics( &diffMemState ); #endif printf ("\nPass %d, Fail %d\n", gPass, gFail); return gFail; }
void ObjectMemory::DumpStats() { tracelock lock(TRACESTREAM); TRACESTREAM << std::endl<< L"Object Memory Statistics:" << std::endl << L"------------------------------" << std::endl; CheckPoint(); _CrtMemDumpStatistics(&CRTMemState); #ifdef _DEBUG checkPools(); #endif TRACESTREAM << std::endl<< L"Pool Statistics:" << std::endl << L"------------------" << std::endl << std::dec << NumPools<< L" pools in the interval (" << m_pools[0].getSize()<< L" to: " << m_pools[NumPools-1].getSize()<< L" by: " << PoolGranularity << L')' << std::endl << std::endl; int pageWaste=0; int totalPages=0; int totalFreeBytes=0; int totalChunks=0; int totalFreeChunks=0; for (int i=0;i<NumPools;i++) { int nSize = m_pools[i].getSize(); int perPage = dwPageSize/nSize; int wastePerPage = dwPageSize - (perPage*nSize); int nPages = m_pools[i].getPages(); int nChunks = perPage*nPages; int waste = nPages*wastePerPage; int nFree = m_pools[i].getFree(); TRACE(L"%d: size %d, %d objects on %d pgs (%d per pg, %d free), waste %d (%d per page)\n", i, nSize, nChunks-nFree, nPages, perPage, nFree, waste, wastePerPage); totalChunks += nChunks; pageWaste += waste; totalPages += nPages; totalFreeBytes += nFree*nSize; totalFreeChunks += nFree; } int objectWaste = 0; int totalObjects = 0; const OTE* pEnd = m_pOT+m_nOTSize; for (OTE* ote=m_pOT; ote < pEnd; ote++) { if (!ote->isFree()) { totalObjects++; if (ote->heapSpace() == OTEFlags::PoolSpace) { int size = ote->sizeOf(); int chunkSize = _ROUND2(size, PoolGranularity); objectWaste += chunkSize - size; } } } int wastePercentage = (totalChunks - totalFreeChunks) == 0 ? 0 : int(double(objectWaste)/ double(totalChunks-totalFreeChunks)*100.0); TRACESTREAM<< L"===============================================" << std::endl; TRACE(L"Total objects = %d\n" "Total pool objs = %d\n" "Total chunks = %d\n" "Total Pages = %d\n" "Total Allocs = %d\n" "Total allocated = %d\n" "Page Waste = %d bytes\n" "Object Waste = %d bytes (avg 0.%d)\n" "Total Waste = %d\n" "Total free chks = %d\n" "Total Free = %d bytes\n", totalObjects, totalChunks-totalFreeChunks, totalChunks, totalPages, FixedSizePool::m_nAllocations, totalPages*dwPageSize, pageWaste, objectWaste, wastePercentage, pageWaste+objectWaste, totalFreeChunks, totalFreeBytes); }