Update contrib.
1 // Copyright (c) 1998-2009 Nokia Corporation and/or its subsidiary(-ies).
2 // All rights reserved.
3 // This component and the accompanying materials are made available
4 // under the terms of the License "Eclipse Public License v1.0"
5 // which accompanies this distribution, and is available
6 // at the URL "http://www.eclipse.org/legal/epl-v10.html".
8 // Initial Contributors:
9 // Nokia Corporation - initial contribution.
14 // f32\runtests\runtests.cpp
19 #include <e32std_private.h>
20 #include <e32def_private.h>
29 #define __PANIC(r) Panic(__LINE__,r)
31 //#define _RUN_FOREVER_
32 //#define _PANIC_ON_FAILURE_
34 const TInt KDefaultTimeout=1200; // 20 minutes
35 const TInt KBackgroundTimeout=3000000; // 3 seconds
36 const TInt KDestroyTimeout=1000000; // 1 second
38 _LIT(KLitBackslash,"\\");
39 _LIT(KDebugMessage, "Testing finished, and the system will be panicked");
41 _LIT(KLitDefaultTestPath,"Z:\\TEST");
43 _LIT(KLitDefaultTestPath,"");
47 _LIT(KBuildType, "UDEB");
49 _LIT(KBuildType, "UREL");
52 typedef RArray<TUint> RProcIdList;
54 GLDEF_D TPath TheTestPath = KLitDefaultTestPath();
56 GLDEF_D RLoader TheLoaderSession;
57 GLDEF_D TDesC8* TheTestList;
58 GLDEF_D RTimer TheTimer;
59 GLDEF_D TBuf<256> TheProcessCommand=KNullDesC();
60 GLDEF_D TInt TheTimeOut = KDefaultTimeout;
61 GLDEF_D TInt TheCurrentProcessList;
62 GLDEF_D RProcIdList ProcLists[2];
63 GLDEF_D RTimer IdleWaitTimer;
64 GLDEF_D RTimer DestructionTimer;
65 GLDEF_D RProperty CurrTest;
66 TBool ShowTimings = 0;
67 TInt TickPeriod = 15625;
68 TBool CleanUpProcesses = EFalse;
70 #ifdef _ENABLE_BTRACE_ANALYSIS_
72 // BTrace analysis forward declarations
73 const TInt KDefaultBTraceLevel = 0;
74 TBool BtraceAnalysis = EFalse;
75 TInt BTraceAnalysisLevel;
76 TInt BTraceAnalyseSetup();
77 void BTraceAnalyseEnd();
78 void BTraceAnalyse(TInt aAnalysisLevel);
80 #endif //_ENABLE_BTRACE_ANALYSIS_
82 _LIT(KLitPanicCategory,"RUNTESTS-");
83 _LIT(KLitLogPreamble,"RUNTESTS: ");
85 void LogMsg(TRefByValue<const TDesC> aFmt,...);
87 void DisableSimulatedFailure()
89 // Turn off simulated failure mechanisms for all base servers
90 TheFs.SetAllocFailure(KAllocFailureOff); // F32 heap failure
91 TheFs.SetErrorCondition(KErrNone, 0); // F32 other failure
92 TheLoaderSession.DebugFunction(ELoaderDebug_SetHeapFail, 0, 0, 0); // Loader heap failure
93 TheLoaderSession.DebugFunction(ELoaderDebug_SetRFsFail, KErrNone, 0, 0); // Loader RFs failure
95 // make sure kernel heap debug is off
99 GLDEF_C void Panic(TInt aLine, TInt aReason)
101 TBuf<16> cat=KLitPanicCategory();
102 cat.AppendNum(aLine);
103 User::Panic(cat,aReason);
106 TInt CloseAndWait(RHandleBase aH, TRequestStatus *aN = NULL)
108 TRequestStatus tempS;
111 // Create a destruction notifier if none was supplied.
112 aH.NotifyDestruction(tempS);
115 if (*aN!=KRequestPending)
117 User::WaitForRequest(*aN);
122 DestructionTimer.After(t, KDestroyTimeout);
124 User::WaitForRequest(*aN, t);
125 if (*aN != KRequestPending)
127 DestructionTimer.Cancel();
128 User::WaitForRequest(t);
131 User::CancelMiscNotifier(*aN);
132 User::WaitForRequest(*aN);
136 void CloseWaitAndWarn(RHandleBase aH, TRequestStatus *aN = NULL)
138 TFullName fn(aH.FullName());
139 TInt r = CloseAndWait(aH, aN);
140 if (r == KErrNoMemory)
141 LogMsg(_L("WARNING OOM checking destruction of %S"), &fn);
142 else if (r == KErrTimedOut)
143 LogMsg(_L("ERROR Destruction of %S timed out"), &fn);
148 TInt r = IdleWaitTimer.CreateLocal();
156 TRequestStatus idle_req;
157 TRequestStatus timer_req;
158 IdleWaitTimer.After(timer_req, KBackgroundTimeout);
159 User::NotifyOnIdle(idle_req);
160 User::WaitForRequest(idle_req, timer_req);
161 if (idle_req != KRequestPending)
163 IdleWaitTimer.Cancel();
164 User::WaitForRequest(timer_req);
168 User::CancelMiscNotifier(idle_req);
169 User::WaitForRequest(idle_req);
170 LogMsg(_L("WARNING Excessive Background Activity Detected"));
174 TBool IntentionallyPersistent(RProcess aProcess)
177 TInt r = RProperty::Get(aProcess.SecureId(), KRuntestsIntentionalPersistenceKey, v);
178 if (r==KErrNone && TUint(v)==KRuntestsIntentionalPersistenceValue)
183 TInt GetProcessListThread(TAny* a)
185 RProcIdList& pl = *(RProcIdList*)a;
186 TFindProcess fp(_L("*"));
189 while (r==KErrNone && fp.Next(fn)==KErrNone)
192 r = p.Open(fp, EOwnerThread);
195 TUint id = (TUint)p.Id();
203 TInt GetProcessList(RProcIdList& aList)
208 TInt r = t.Create(KNullDesC, &GetProcessListThread, 0x1000, NULL, &aList);
212 t.SetPriority(EPriorityAbsoluteHigh);
213 if (s==KRequestPending)
215 User::WaitForRequest(s);
217 if (t.ExitType()==EExitPending)
222 else if (t.ExitType()!=EExitKill)
232 TBool ParseNumber(TLex& aLex, TUint& aNumber, TBool isTime)
234 TPtrC numberDes = aLex.NextToken();
235 TInt len = numberDes.Length();
243 TChar c = numberDes[len-1];
270 for (TInt i = len-1; i >= 0; --i)
273 if (c < '0' || c > '9')
274 __PANIC(KErrArgument);
275 aNumber += ((TInt)c-'0')*magnitude;
282 void GetTimeOut(TLex& aLex)
287 TheTimeOut = KDefaultTimeout;
289 if (ParseNumber(aLex, timeOut, ETrue))
291 TheTimeOut = timeOut;
295 #ifdef _ENABLE_BTRACE_ANALYSIS_
297 void GetAnalysisLevel(TLex& aLex)
299 BTraceAnalysisLevel = KDefaultBTraceLevel;
301 if (ParseNumber(aLex, level, EFalse))
303 BTraceAnalysisLevel = level;
306 #endif //_ENABLE_BTRACE_ANALYSIS_
308 void LogMsg(TRefByValue<const TDesC> aFmt,...)
312 TBuf<0x100> buf=KLitLogPreamble();
313 buf.AppendFormatList(aFmt,list);
314 RDebug::Print(_L("%S"),&buf);
317 _LIT(KLitError, "Error ");
318 TBool LogProcess(TUint aId, TBool aInit)
323 TBool killed = EFalse;
324 TInt r = p.Open(TProcessId(aId));
327 if (IntentionallyPersistent(p))
334 if (!aInit && CleanUpProcesses && p.ExitType()==EExitPending)
335 {// p is a left over process so terminate it.
337 TRequestStatus status;
339 p.Kill(KErrNone); // Kill with KErrNone to suppress extra debug output from kernel.
340 User::WaitForRequest(status);
354 LogMsg(_L("Running process id=%d: %S (%S)"),aId,&pn,&fn);
358 LogMsg(_L("ERROR Leftover process was killed id=%d: %S (%S)"),aId,&pn,&fn);
360 LogMsg(_L("ERROR Leftover process id=%d: %S (%S)"),aId,&pn,&fn);
367 RProcIdList& cur_list = ProcLists[TheCurrentProcessList];
368 TInt cc = cur_list.Count();
370 for (ci=0; ci<cc; ++ci)
372 LogProcess(cur_list[ci], ETrue);
376 void CheckProcesses()
378 RProcIdList& cur_list = ProcLists[TheCurrentProcessList];
379 RProcIdList& new_list = ProcLists[1-TheCurrentProcessList];
380 TInt r = GetProcessList(new_list);
383 LogMsg(_L("WARNING Problem getting process list, error %d"),r);
387 TInt cc = cur_list.Count();
388 TInt nc = new_list.Count();
391 while (ci<cc || ni<nc)
401 // extra process has appeared so kill it and output an error message.
402 if (LogProcess(id2, EFalse))
403 {// Remove from list as we don't want it to be considered as vanished when the next test completes.
408 {// Extra process was left running so just move onto the next one.
412 else if (ni<nc && id1==id2)
419 // process has disappeared
420 LogMsg(_L("WARNING Vanished process, id=%d"),id1);
425 // current list = new list
426 TheCurrentProcessList = 1 - TheCurrentProcessList;
428 // throw away the old list
432 _LIT8 (KLitRemark,"REM");
433 _LIT8 (KLitAtRemark,"@REM");
435 void ProcessLine(const TDesC8& aLine)
438 TPtrC8 testname=lex.NextToken();
439 if (testname.Length()>=2 && testname[0]=='/' && testname[1]=='/')
441 // ignore this line if it begins with rem or @rem
442 if (testname.CompareF(KLitRemark) == 0 || testname.CompareF(KLitAtRemark) == 0)
445 testnameU.Copy(testname);
446 TFileName fullpathname;
447 if (testnameU.Locate(TChar('\\'))==KErrNotFound)
448 fullpathname=TheTestPath;
449 fullpathname+=testnameU;
450 if (testname.Locate(TChar('.'))==KErrNotFound)
451 fullpathname+=_L(".EXE");
455 r=file.Open(TheFs,fullpathname,EFileRead);
458 // Remove path to let loader locate exe
459 fullpathname = fullpathname.Mid(fullpathname.LocateReverse('\\')+1);
465 if(TheProcessCommand==KNullDesC)
467 TheProcessCommand.Copy(lex.Remainder());
468 r=p.Create(fullpathname, TheProcessCommand);
469 TheProcessCommand=KNullDesC();
472 r=p.Create(fullpathname, TheProcessCommand);
475 LogMsg(_L("Test %S ERROR Could not load file, error %d"),&fullpathname,r);
480 LogMsg(_L("Started test %S"),&fullpathname);
483 p.NotifyDestruction(ds); // allocate the destruction notifier early so that it doesn't get flagged as a leak by kernel heap checking in e.g., efile (DEF133800)
484 CurrTest.Set(p.FileName());
485 User::After(100000); // allow latency measurements to be output
486 p.SetJustInTime(EFalse); // we don't want the automatic test run to be halted by the debugger
489 TInt time_remain = TheTimeOut;
491 TUint start = User::TickCount();
493 TBool persist = EFalse;
494 TBool timer_running = EFalse;
497 TInt nsec = Min(time_remain, 1800);
499 TheTimer.After(ts, nsec*1000000);
500 timer_running = ETrue;
501 User::WaitForRequest(ps,ts);
502 if (ps!=KRequestPending)
504 if (p.ExitType()==EExitPending)
506 // rendezvous completed but process not terminated
507 if (!IntentionallyPersistent(p))
509 // not persistent - wait for process to terminate
517 timer_running = EFalse;
521 LogMsg(_L("Going to kill test %S: it's taken %u seconds, which is too long"),&fullpathname,TheTimeOut);
523 User::WaitForRequest(ps);
525 User::WaitForRequest(ps);
527 CloseWaitAndWarn(p, &ds);
528 RDebug::Print(_L("\n"));
529 LogMsg(_L("Test %S TIMEOUT"),&fullpathname);
534 LogMsg(_L("Taken %u seconds so far"),TheTimeOut-time_remain);
537 TUint end = User::TickCount();
541 User::WaitForRequest(ts);
544 #ifdef _ENABLE_BTRACE_ANALYSIS_
549 {// Analyse BTrace buffer
550 BTraceAnalyse(BTraceAnalysisLevel);
552 #endif //_ENABLE_BTRACE_ANALYSIS_
554 TBuf<32> exitCat=p.ExitCategory();
555 TExitType exitType=p.ExitType();
556 TInt exitReason=p.ExitReason();
557 if (persist || (exitType==EExitKill && exitReason==KErrNone))
559 TUint time = TUint((TUint64)(end-start)*(TUint64)TickPeriod/(TUint64)1000000);
562 LogMsg(_L("Test %S OK - Seconds Taken: %u"),&fullpathname, time);
566 LogMsg(_L("Test %S OK"),&fullpathname);
570 // We do not need this destruction notifier so cancel it.
571 User::CancelMiscNotifier(ds);
572 User::WaitForRequest(ds);
578 CloseWaitAndWarn(p, &ds);
582 LogMsg(_L("Test %S FAIL - Exit code %d,%d,%S"),&fullpathname,exitType,exitReason,&exitCat);
583 CloseWaitAndWarn(p, &ds);
584 #if defined(_PANIC_ON_FAILURE_)
585 __PANIC(KErrGeneral);
589 void ProcessTestList()
591 TUint start = User::TickCount();
593 TLex8 llex(*TheTestList);
598 while(!llex.Eos() && llex.Peek()!='\n' && llex.Peek()!='\r')
600 TPtrC8 line=llex.MarkedToken();
601 if (line.Length()!=0)
604 // allow cleanup to complete before starting the next test
607 // make sure simulated failure is off
608 DisableSimulatedFailure();
610 // check for leftover processes
613 // Reset the demand paging cache to its default size.
614 UserSvr::HalFunction(EHalGroupVM,EVMHalSetCacheSize, 0, 0);
617 TUint end = User::TickCount();
618 TUint time = TUint((TUint64)(end-start)*(TUint64)TickPeriod/(TUint64)1000000);
619 LogMsg(_L("Elapsed Seconds: %u"), time);
624 RDebug::Print(_L("Runtests test list [-x where tests are] [-d drive letter to test] [-t timeout] [-p] [-st] [-c]"));
625 RDebug::Print(_L("where -p sets runtests to be system permanent, -st enables timing information,"));
626 RDebug::Print(_L("-c enables left over processes to be cleaned up"));
629 GLDEF_C TInt E32Main()
631 HAL::Get(HAL::ESystemTickPeriod, TickPeriod);
632 RThread().SetPriority(EPriorityAbsoluteHigh);
634 User::CommandLine(cmd);
635 TFileName thisfile=RProcess().FileName();
637 TPtrC token=lex.NextToken();
638 if (token.MatchF(thisfile)==0)
640 token.Set(lex.NextToken());
642 if (token.Length()==0)
647 TFileName listfilename=token;
650 token.Set(lex.NextToken());
651 if (token.Length()==0)
652 break; // ignore trailing whitespace
653 else if (token==_L("-x"))
655 token.Set(lex.NextToken());
658 else if (token==_L("-d"))
660 token.Set(lex.NextToken());
661 TheProcessCommand = token;
663 else if (token==_L("-t"))
667 else if (token==_L("-p"))
669 User::SetCritical(User::ESystemPermanent);
671 else if (token==_L("-st"))
674 #ifdef _ENABLE_BTRACE_ANALYSIS_
675 else if (token == _L("-a"))
677 BtraceAnalysis = ETrue;
678 GetAnalysisLevel(lex);
679 TInt r = BTraceAnalyseSetup();
682 RDebug::Print(_L("ERROR - Couldn't open BTrace driver (Code %d)"), r);
686 #endif //_ENABLE_BTRACE_ANALYSIS_
688 else if (token == _L("-c"))
689 CleanUpProcesses = ETrue;
692 RDebug::Print(_L("Unknown option %S"), &token);
698 RDebug::Print(_L("TPTT= %S \n"), &TheProcessCommand);
699 RDebug::Print(_L("TTL= %S \n"), &listfilename);
700 RDebug::Print(_L("TTP= %S \n"), &TheTestPath);
701 RDebug::Print(_L("TO= %d seconds\n"), TheTimeOut);
703 TInt l=TheTestPath.Length();
704 if (l > 0 && TheTestPath[l-1]!='\\')
705 TheTestPath+=KLitBackslash;
706 if (listfilename.Locate(TChar('\\'))==KErrNotFound)
707 listfilename.Insert(0,TheTestPath);
708 TInt r=TheFs.Connect();
711 r = TheLoaderSession.Connect();
714 DisableSimulatedFailure();
715 r=TheFs.SetSessionPath(_L("Z:\\test\\"));
718 r=TheTimer.CreateLocal();
722 r=listfile.Open(TheFs,listfilename,EFileRead|EFileShareAny);
726 r=listfile.Size(listfilesize);
729 HBufC8* pL=HBufC8::New(listfilesize);
731 __PANIC(KErrNoMemory);
734 r=listfile.Read(ptr);
738 LogMsg(_L("Running test script %S"),&listfilename);
739 LogMsg(_L("Build %S"),&KBuildType);
740 LogMsg(_L("Path to test %S"),&TheProcessCommand);
742 r = RProperty::Define( KRuntestsCurrentTestKey,
744 TSecurityPolicy(TSecurityPolicy::EAlwaysPass),
745 TSecurityPolicy(RProcess().SecureId()),
748 if (r!=KErrNone && r!=KErrAlreadyExists)
750 r = CurrTest.Attach(RProcess().SecureId(), KRuntestsCurrentTestKey);
753 r = CurrTest.Set(KNullDesC);
757 r = DestructionTimer.CreateLocal();
760 TheCurrentProcessList = 0;
761 r = GetProcessList(ProcLists[0]);
768 #if defined(_RUN_FOREVER_)
772 r = CurrTest.Set(KNullDesC);
776 User::After(1000000); // allow latency measurements to be output before exiting
777 LogMsg(_L("Completed test script %S"),&listfilename);
778 TheLoaderSession.Close();
781 IdleWaitTimer.Close();
782 DestructionTimer.Close();
784 #ifdef _ENABLE_BTRACE_ANALYSIS_
786 #endif //_ENABLE_BTRACE_ANALYSIS_
787 if(User::Critical()==User::ESystemPermanent)
788 RDebug::Print(KDebugMessage);