示例#1
0
static void DoTestFileWriteCPU(TInt aBlockSize)
//
// Benchmark CPU utilisation for Write method
//
// Write operations are performed for 10 seconds whilst a second thread executes floating point calculations
// The higher the number of calculations the less amount of CPU time has been used by the Write method.
//
{
    DataBuf.SetLength(aBlockSize);

    TFileName testDir(_L("?:\\F32-TST\\"));
    testDir[0] = (TText) gDriveToTest;
    TInt r = TheFs.MkDir(testDir);
    test_Value(r, r == KErrNone || r == KErrAlreadyExists);

    TFileName fileName;
    r = File.Temp(TheFs, testDir, fileName, EFileWrite | (gFileSequentialModeOn ? EFileSequential : 0)
                  | (gWriteCachingOn ? EFileWriteBuffered : EFileWriteDirectIO));
    test_KErrNone(r);

    TUint functionCalls = 0;
    TUint fltPntCalls = 0;
    RThread fltPntThrd;

    TBuf<6> buf = _L("Floaty");
    fltPntThrd.Create(buf, FloatingPointLoop, KDefaultStackSize, KHeapSize, KHeapSize, (TAny*) &fltPntCalls);

    TUint initTicks = 0;
    TUint finalTicks = 0;

    // up the priority of this thread so that we only run the floating point thread when this thread is idle
    RThread				thisThread;
    thisThread.SetPriority(EPriorityMuchMore);

    TRequestStatus req;
    fltPntThrd.Logon(req);

    RTimer timer;
    timer.CreateLocal();
    TRequestStatus reqStat;

    TInt pos = 0;
    File.Seek(ESeekStart, pos);

    timer.After(reqStat, KFloatingPointTestTime);
    initTicks = User::FastCounter();

    fltPntThrd.Resume();

    for (TInt i = 0 ; reqStat==KRequestPending; i++)
    {
        File.Write(DataBuf, aBlockSize);
        functionCalls++;
    }
    TUint fltPntCallsFinal = fltPntCalls;

    fltPntThrd.Kill(KErrNone);

    finalTicks = User::FastCounter();

    fltPntThrd.Close();
    User::WaitForRequest(req);

    TTimeIntervalMicroSeconds duration = TInt64(finalTicks - initTicks) * TInt64(1000000) / TInt64(gFastCounterFreq) ;

    TInt dataTransferred = functionCalls * aBlockSize;
    TReal transferRate =  TReal32(dataTransferred) /
                          TReal(duration.Int64()) * TReal(1000000) / TReal(K1K); // KB/s

    test.Printf(_L("Write %7d bytes in %7d byte blocks:\t%11.3f KBytes/s; %d Flt Calcs\n"),
                dataTransferred, aBlockSize, transferRate, fltPntCallsFinal);

    timer.Close();

    File.Close();
    r = TheFs.Delete(fileName);
    test_KErrNone(r)

    return;
}
// start run a test case
void CTestExecutor::RunTestCaseL()
	{
	RSemaphore smphF;
	smphF.CreateLocal(0);
	RSemaphore smphN;
	smphN.CreateLocal(0);
		
	RArray<RThread> notiThreads; // list of handles of notification threads
	RPointerArray<CTimerLogger> loggerList;
	
	TUint16 count = 0;
	TUint16 option = iTestSetting.iOption;
	while (count < iTestSetting.iNumCli)
		{
		test(count < 16);
		iTestSetting.iOption = (TUint16)(option + count); // Put Thread ID in option
		
		TThreadParam param;
		param.iSetting = iTestSetting;
		param.iSmphFT = &smphF;
		param.iSmphNT = &smphN;
			
		TFileName logName;
		logName.FillZ();
		
		if (gPerfMeasure)
		    {
            logName.Append(gLogFilePath);
            if (iTestSetting.iNumCli == 1)
                logName.Append(_L("SingleClient"));
            else
                logName.AppendFormat(_L("MultiClient%02d"), count);
            
            logName.Append(gLogPostFix);
		    }
		
		CTimerLogger* logger = CTimerLogger::NewL(logName);
		CleanupStack::PushL(logger);
		
		param.iLogger = logger;
		param.iLoggerArray = NULL;
		
		TUint operation = *iTestSetting.iOperationList;
		TBool numFilesVaries = EFalse; 
		
		if (operation == EOpManyFiles || operation == EOpManyChanges || operation == EOpMixed)
			{
			numFilesVaries = ETrue;
			}
		logger->LogSettingDescription(iTestSetting.iNumFiles, iTestSetting.iNumCli, iTestSetting.iOption, numFilesVaries);
		
		loggerList.AppendL(logger);
		
		TBuf<20> threadName;
		threadName.AppendFormat(_L("NotificationThread%02d"), count);

		RThread notifyOp;
		notifyOp.Create(threadName, NotificationOperationThread, KDefaultStackSize, KMinHeapSize, KMaxHeapSize, &param);
		
		notiThreads.AppendL(notifyOp);
		
		notifyOp.Resume();
		
		smphF.Wait();	// Wait for the parameters being properly passed
		
		CleanupStack::Pop(logger);
		count++;
		}
	
	gNotiThreads = notiThreads;
	
	if (iTestSetting.iNumCli == 0)	// no notification
		{
		TFileName logName;
		logName.Append(gLogFilePath);
		logName.Append(_L("SingleClient"));
		logName.Append(gLogPostFix);
	
		CTimerLogger* logger = CTimerLogger::NewL(logName);
		CleanupStack::PushL(logger);
		
		logger->LogSettingDescription(iTestSetting.iNumFiles, iTestSetting.iNumCli, iTestSetting.iOption);
		
		loggerList.AppendL(logger);
		CleanupStack::Pop(logger);
		}
	
	TThreadParam paramFileOp;
	paramFileOp.iSetting = iTestSetting;
	paramFileOp.iSmphFT = &smphF;
	paramFileOp.iSmphNT = &smphN;
	paramFileOp.iLogger = NULL;
	paramFileOp.iLoggerArray = &loggerList;
	
	RThread fileOp;
	fileOp.Create(_L("FileOperationThread"), FileOperationThread, KDefaultStackSize, KMinHeapSize, KMaxHeapSize, &paramFileOp);	
	gFileThread = fileOp;
	
	fileOp.Resume();
	
	TInt err;
	
	TRequestStatus status;
	fileOp.Logon(status);
	User::WaitForRequest(status);
	err = fileOp.ExitReason();
	test(err == KErrNone);
		
	count = 0;
	while(count < notiThreads.Count())
		{
		notiThreads[count].Logon(status);
		User::WaitForRequest(status);
		err = notiThreads[count].ExitReason();
		test(err == KErrNone);
		count++;
		}
	
	CLOSE_AND_WAIT(fileOp);
	
	count = 0;
	while(count < notiThreads.Count())
		{
		RThread thread = notiThreads[count];
		CLOSE_AND_WAIT(thread);
		count++;
		}
	
	for (TInt i = 0; i < loggerList.Count(); i++)
		{
		loggerList[i]->LogAndPrint(_L("===================================================="));
		}
	
	smphN.Close();
	smphF.Close();
	loggerList.ResetAndDestroy();
	loggerList.Close();
	notiThreads.Reset();
	notiThreads.Close();
	}
示例#3
0
GLDEF_C TInt E32Main()
	{
	RTest test(_L("T_SVRPINNING...main"));
	test.Title();


	if (DPTest::Attributes() & DPTest::ERomPaging)
		test.Printf(_L("Rom paging supported\n"));
	if (DPTest::Attributes() & DPTest::ECodePaging)
		test.Printf(_L("Code paging supported\n"));
	if (DPTest::Attributes() & DPTest::EDataPaging)
		{
		test.Printf(_L("Data paging supported\n"));
		gDataPagingSupport = ETrue;
		}

	// Determine the data paging attribute.
	RProcess process;	// Default to point to current process.
	gProcessPaged = process.DefaultDataPaged();
	test.Printf(_L("Process data paged %x\n"), gProcessPaged);

	test.Start(_L("Test IPC message arguments pinning"));
	test_KErrNone(HAL::Get(HAL::EMemoryPageSize, gPageSize));
	gPageMask = gPageSize - 1;
	test_Equal(KPageSize, gPageSize);
	// Disable JIT as we are testing panics and don't want the emulator to hang.
	TBool justInTime = User::JustInTime();
	User::SetJustInTime(EFalse);

	TBool exitFailure = EFalse;
	for (	gServerPinningState = EServerDefault; 
			gServerPinningState < EServerSetPinningTooLate && !exitFailure; 
			gServerPinningState++)
		{
		// Create the server with the specified pinning mode.
		switch (gServerPinningState)
			{
			case EServerDefault : 
				test.Next(_L("Test server with default pinning policy"));
				break;
			case EServerPinning : 
				test.Next(_L("Test server with pinning policy"));
				break;
			case EServerNotPinning : 
				test.Next(_L("Test server with not pinning policy"));
				break;
			}
		test_KErrNone(gSem.CreateLocal(0));
		test_KErrNone(gSem1.CreateLocal(0));
		// Create the server thread it needs to have a unpaged stack and heap.
		TThreadCreateInfo serverInfo(_L("Server Thread"), ServerThread, KDefaultStackSize, (TAny*)gServerPinningState);
		serverInfo.SetPaging(TThreadCreateInfo::EUnpaged);
		serverInfo.SetCreateHeap(KHeapMinSize, KHeapMaxSize);
		RThread serverThread;
		test_KErrNone(serverThread.Create(serverInfo));
		TRequestStatus serverStat;
		serverThread.Logon(serverStat);
		serverThread.Resume();

		// Wait for the server to start and then create a session to it.
		gSem.Wait();
		RSession session;
		test_KErrNone(session.PublicCreateSession(_L("CTestServer"),5));
		
		for (	TUint clientTest = CTestSession::ETestRdPinAll; 
				clientTest <= CTestSession::ETestPinDefault && !exitFailure;
				clientTest++)
			{
			// Create the client thread it needs to have a paged stack and heap.
			TThreadCreateInfo clientInfo(_L("Client Thread"), ClientThread, 10 * gPageSize, (TAny*)clientTest);
			clientInfo.SetPaging(TThreadCreateInfo::EPaged);
			clientInfo.SetCreateHeap(KHeapMinSize, KHeapMaxSize);
			RThread clientThread;
			test_KErrNone(clientThread.Create(clientInfo));

			TRequestStatus clientStat;
			clientThread.Logon(clientStat);
			clientThread.Resume();

			// Wait for the client thread to end.
			User::WaitForRequest(clientStat);

			// If all the descriptor arguments were not pinned then the client 
			// thread should have been panicked.
			TBool expectPanic = (clientTest == CTestSession::ETestRdPinAll || 
								clientTest == CTestSession::ETestWrPinAll ||
								clientTest == CTestSession::ETestPinOOM )? 0 : 1;
			expectPanic = !UpdateExpected(!expectPanic);

			TInt exitReason = clientThread.ExitReason();
			TInt exitType = clientThread.ExitType();
			if (expectPanic)
				{
				if (exitType != EExitPanic || 
					exitReason != EIllegalFunctionForRealtimeThread ||
					clientThread.ExitCategory() != _L("KERN-EXEC"))
					{
					test.Printf(_L("Thread didn't panic as expected\n"));
					exitFailure = ETrue;
					}
				}
			else
				{
				if (exitType != EExitKill || exitReason != KErrNone)
					{
					test.Printf(_L("Thread didn't exit gracefully as expected\n"));
					exitFailure = ETrue;
					}
				}
			test(!exitFailure);
			CLOSE_AND_WAIT(clientThread);
			}

		test.Next(_L("Test client sending message to closed server"));
		TThreadCreateInfo clientInfo(_L("Client Thread"), ClientThread, 10 * gPageSize, (TAny*)CTestSession::ETestDeadServer);
		clientInfo.SetPaging(TThreadCreateInfo::EPaged);
		clientInfo.SetCreateHeap(KHeapMinSize, KHeapMaxSize);
		RThread clientThread;
		test_KErrNone(clientThread.Create(clientInfo));
		TRequestStatus clientStat;
		clientThread.Logon(clientStat);
		clientThread.Resume();
		gSem.Wait();
		
		// Signal to stop ActiveScheduler and wait for server to stop.
		session.PublicSendReceive(CTestSession::EStop, TIpcArgs());
		session.Close();
		User::WaitForRequest(serverStat);
		if (serverThread.ExitType() != EExitKill)
			{
			test.Printf(_L("!!Server thread did something bizarre %d\n"), serverThread.ExitReason());
			}

		gSem1.Signal();
		User::WaitForRequest(clientStat);
		test_Equal(EExitKill, clientThread.ExitType());
		test_Equal(KErrServerTerminated, clientThread.ExitReason());

		CLOSE_AND_WAIT(clientThread);
		CLOSE_AND_WAIT(serverThread);
		CLOSE_AND_WAIT(gSem);
		CLOSE_AND_WAIT(gSem1);
		}

	test.Next(_L("Test server setting pinning policy after server started"));
	RThread serverThread;
	test_KErrNone(serverThread.Create(_L("Server Thread"),ServerThread,KDefaultStackSize,KHeapMinSize,KHeapMaxSize, (TAny*)gServerPinningState));
	TRequestStatus serverStat;
	serverThread.Logon(serverStat);
	serverThread.Resume();
	// The server should have panicked with E32USER-CBase 106.
	User::WaitForRequest(serverStat);
	TInt exitReason = serverThread.ExitReason();
	TInt exitType = serverThread.ExitType();
	test_Equal(EExitPanic, exitType);
	test_Equal(ECServer2InvalidSetPin, exitReason);
	if (_L("E32USER-CBase") != serverThread.ExitCategory())
		test(0);
	CLOSE_AND_WAIT(serverThread);

	test.End();

	// Set JIT back to original state.
	User::SetJustInTime(justInTime);

	return (KErrNone);
	}
示例#4
0
static void init_symbian_thread_handle(RThread &thread)
{
    thread = RThread();
    TThreadId threadId = thread.Id();
    qt_symbian_throwIfError(thread.Open(threadId, EOwnerProcess));
}
示例#5
0
Uint32 SDL_ThreadID(void)
{
    RThread current;
    TThreadId id = current.Id();
	return id;
}
/**
Second phase constructor
@internalComponent
*/
void CVideoRenderer::ConstructL()
	{
	User::LeaveIfError(iSurfaceManager.Open());

	User::LeaveIfError(iWsSession.Connect());
	
	CResourceFileReader* reader = CResourceFileReader::NewLC(KResourceFileName);
	reader->ReadSupportedFormatL(iSupportedFormat);

	if (iTimed)
		{
		// Create a high priority thread for timed mode

		// get timer info for timed mode
		TInt64 defaultDelay;
		TInt64 maxDelay;
		reader->ReadTimerInfoL(defaultDelay, maxDelay);

		//Get a reference to this thread's heap
		RHeap& thisHeap = User::Heap();

		//Parameters to send to the sub thread
		TThreadRelayParam param;
		param.iObserver = &iObserver;
		param.iThreadRelay = &iRendererRelay; // return pointer to allow direct calls

		//Get the id of this thread
		RThread thisThread;
		TThreadId thisThreadId = thisThread.Id();
		param.iMainThreadId = thisThreadId;

		//Get a request to signal for setup completion
		TRequestStatus setupComplete = KRequestPending;
		param.iSetupComplete = &setupComplete;
		
		//current time and the "this" pointer for a unique key
		_LIT(KFormatString,"%S.%020Lu.%08X");
	   	TName threadName;
		TTime now;
		now.UniversalTime();
		threadName.Format(KFormatString, &KVideoRendererThreadName, now.Int64(), reinterpret_cast<TUint>(this));

		//Create a new thread using the same heap as this thread
		TInt result = iRendererThread.Create(threadName,
										ThreadCreateFunction,
										KSubThreadStackSize,
										&thisHeap,
										&param);
		User::LeaveIfError(result);

		//Run the thread under high priority
		iRendererThread.SetPriority(KSubThreadPriority); 

		//Wait for thread startup to complete
		TRequestStatus threadStatus = KRequestPending;
		iRendererThread.Logon(threadStatus);

		//Start the thread
		iRendererThread.Resume();
		User::WaitForRequest(threadStatus, setupComplete);
		if(threadStatus != KRequestPending)
			{
			//Thread creation failed
			TInt reason = iRendererThread.ExitReason();
			DEBUGPRINT3(_L("Renderer thread died with type=%d, reason=%d"), iRendererThread.ExitType(), reason);
			User::Leave(reason);
			}

		// Thread creation was successfull
		TInt error = iRendererThread.LogonCancel(threadStatus);
		User::LeaveIfError(error); // There is no outstanding request
		User::WaitForRequest(threadStatus); // Consume the signal

		__ASSERT_DEBUG(iRendererRelay != NULL, User::Panic(_L("CVR::ConstructL"), KErrCorrupt));
		iRendererRelay->SetRendererThread(&iRendererThread);
		iRendererRelay->SetTimerInfo(defaultDelay, maxDelay);
		
		iThreadCreated = ETrue;
		User::LeaveIfError(setupComplete.Int());

		//Create a listener that will monitor the thread
		iRendererThreadUndertaker = CThreadUndertaker::NewL(iRendererThread);
		}
	else
		{
		iRendererRelay = CRendererRelay::NewL(iObserver);
		}

	CleanupStack::PopAndDestroy(reader);
	}
TInt CTe_locsrvSuiteStepBase::DoPanicTestL(TThreadFunction aThreadFunction, TExitCategoryName aExpectedExitCat,
                  TInt aExpectedExitReason, TTimeIntervalMicroSeconds32 aTimeoutValue)

{
#ifdef __WINS__
    User::SetJustInTime(EFalse);
    CleanupStack::PushL(TCleanupItem(TurnJITBackOn));
#endif
    RThread panickingThread;

    SPanicThreadFunctionData threadData;
    threadData.iPanicFunction = aThreadFunction;
    threadData.iPtr = NULL;

    // check that thread does not already exist
    TInt result = KErrNone;
    TBuf<24> threadName(KPanicThreadName);
    
    result = panickingThread.Create(
                threadName,
                PanicThreadFunction,
                KDefaultStackSize,
                KTestHeapMinSize,
                KTestHeapMaxSize,
                &threadData,
                EOwnerProcess);

    CheckExpectedResult(result, KErrNone, KUnexpectedErrorCreatingPanicThread);
    User::LeaveIfError(result);

    CleanupClosePushL(panickingThread);

    RTimer timeoutTimer;
    User::LeaveIfError(timeoutTimer.CreateLocal());
    CleanupClosePushL(timeoutTimer);

    TRequestStatus timerStatus;
    timeoutTimer.After(timerStatus, aTimeoutValue);

    TRequestStatus threadStatus;

    panickingThread.Rendezvous(threadStatus);
    if (threadStatus != KRequestPending)
        {
        // logon failed - thread is not yet running, so cannot have terminated
        User::WaitForRequest(threadStatus);              // eat signal
        panickingThread.Kill(threadStatus.Int());        // abort startup
        }
    else
        {
        panickingThread.Resume();
        User::WaitForRequest(threadStatus, timerStatus);
        }

    TInt exitReason = KErrNone;
    if (threadStatus == KRequestPending)
    {
        ERR_PRINTF1(KThreadDidntDieKillIt);
        panickingThread.Kill(KErrTimedOut);
        User::WaitForRequest(threadStatus);
    }
    else // (timerStatus == KRequestPending)
    {
        // stop timer
        timeoutTimer.Cancel();
        User::WaitForRequest(timerStatus);
    }

    exitReason = panickingThread.ExitReason();
    TExitCategoryName exitCat = panickingThread.ExitCategory();
    
    switch(panickingThread.ExitType()) 
    {
        case EExitKill:
            INFO_PRINTF2(KThreadWasKilled, exitReason);
            break;
        case EExitTerminate:
            INFO_PRINTF2(KThreadWasTerminated, exitReason);
            break;
        case EExitPanic:
            // check exit reasons
            if (exitCat.Compare(aExpectedExitCat) != 0)
                {
                INFO_PRINTF3(KUnexpectedPanicCategory, &exitCat, &aExpectedExitCat);
                }
            CheckExpectedResult(exitReason, aExpectedExitReason, KUnexpectedPanicReason);
            break;
        default:
            CheckExpectedResult((TInt)EExitPanic, threadStatus.Int(), KUnexpectedThreadExitType);
            break;
    }

    CleanupStack::PopAndDestroy(&timeoutTimer);
    CleanupStack::PopAndDestroy(&panickingThread);
#ifdef __WINS__
    CleanupStack::PopAndDestroy();  //TurnJITBackOn
#endif
    // wait a bit to make sure this thread is over
    const TTimeIntervalMicroSeconds32 KThreadDelay = 1000 * 1000; // 1 s
    User::After(KThreadDelay);

    return exitReason;
}
LOCAL_C void ResetL()
	{
	CRepository* repository;
	User::LeaveIfNull(repository = CRepository::NewLC(KUidPlatsecTestRepository));

	TInt x;
	TInt r = repository->Get(KInt1, x);
	TEST2(r, KErrNone);
	TEST(x!=KInt1_InitialValue);

	r = repository->Reset(KInt1);
	TEST2(r, KErrNone);

	r = repository->Get(KInt1, x);
	TEST2(r, KErrNone);
	TEST(x==KInt1_InitialValue);

	CleanupStack::PopAndDestroy(repository);

	// Repository D
	User::LeaveIfNull(repository = CRepository::NewLC(KUidResetTestRepository));
	// Remember that this repository need to be reset
	::AddRepositoryToReset(KUidResetTestRepository);


	const TInt KNewSetting1 = 5;
	const TInt KNewSetting2 = 6;
	r = repository->Create(KNewSetting1, 0);
	TEST2(r, KErrNone);
	r = repository->Create(KNewSetting2, 0);
	TEST2(r, KErrNone);

	r = repository->Create(65, 1);
	TEST2(r, KErrNone);

	r = repository->Set(70, 1);
	TEST2(r, KErrNone);

	r = repository->Create(80, 1);
	TEST2(r, KErrNone);

	r = repository->Create(90, 1);
	TEST2(r, KErrNone);

	TRequestStatus status = -1;
	r = repository->NotifyRequest(0, 0, status);
	TEST2(r, KErrNone);

	r = repository->Reset();
	TEST2(r, KErrNone);
	TEST(status==KUnspecifiedKey);
	RThread thisThread;
	TEST(thisThread.RequestCount()==1);

	r = repository->Get(10, x);
	TEST2(r, KErrNone);
	TEST(x==10);

	r = repository->Get(40, x);
	TEST2(r, KErrNone);
	TEST(x==0);

	r = repository->Get(50, x);
	TEST2(r, KErrNone);
	TEST(x==0);

	r = repository->Get(60, x);
	TEST2(r, KErrNone);
	TEST(x==0);

	r = repository->Get(70, x);
	TEST2(r, KErrNone);
	TEST(x==0);

	TBuf<10> z;
	r = repository->Get(20, z);
	TEST2(r, KErrNone);
	TEST(z==_L("string"));

	TReal y;
	r = repository->Get(30, y);
	TEST2(r, KErrNone);
	TEST(y==1);

	r = repository->Get(5, x);
	TEST2(r, KErrNotFound);
	r = repository->Get(6, x);
	TEST2(r, KErrNotFound);
	r = repository->Get(65, x);
	TEST2(r, KErrNotFound);
	r = repository->Get(80, x);
	TEST2(r, KErrNotFound);
	r = repository->Get(90, x);
	TEST2(r, KErrNotFound);

	CleanupStack::PopAndDestroy(repository);
	}
示例#9
0
/**
 * This function unlocks the mutex, making it available again. If other
 * threads are waiting for the lock, the first thread in the FIFO queue
 * will be given the lock.
 */
void SHVMutexBase::Unlock()
{
#ifdef __SHIVA_WIN32
	SHVVERIFY(WaitForSingleObject(Locker, INFINITE) == WAIT_OBJECT_0);
	if (Queue.GetCount()) // somebody is waiting
	{
	SHVListPos pos;
	LONG prevCount;
		NewOwner = Queue.GetFirst(pos);
		ReleaseSemaphore(NewOwner,1,&prevCount);
	}
	else
	{
		Mutex = 0;
	}
	ReleaseMutex(Locker);
#elif defined(__SHIVA_EPOC)
	Locker.Wait();
	if (Queue.GetCount()) // somebody is waiting
	{
	SHVListPos pos;
	SHVQueuedThread queue = Queue.GetFirst(pos);

		if (queue.Timer)
		{
		RTimer timer( *queue.Timer );
		RThread thread;

			thread.Open(queue.Owner);

			timer.Duplicate(thread);
			timer.Cancel();

			timer.Close();
			thread.Close();
			NewOwner = queue.Timer;
		}
		if (queue.Mutex)
		{
			queue.Mutex->Signal();
			NewOwner = queue.Mutex;
		}
	}
	else
	{
		Mutex = 0;
	}
	Locker.Signal();
#else
	pthread_mutex_lock(&Locker);
	if (Queue.GetCount()) // somebody is waiting
	{
	SHVListPos pos;
		NewOwner = Queue.GetFirst(pos);
        pthread_cond_signal(NewOwner);
	}
	else
	{
		Mutex = 0;
	}
	pthread_mutex_unlock(&Locker);
#endif
}
示例#10
0
void CLocalChild::Kill()
	{
	iChild.Kill(KErrCancel);
	}
/**
Unfound TStringTable in Bafl StringPool not treated correctly.
Check that the function panics when the specified table is not present.

@SYMTestCaseID          SYSLIB-BAFL-CT-0492
@SYMTestCaseDesc        Tests for the functionality of RStringPool
@SYMTestPriority        High
@SYMTestActions         Tests for panic when the specified table is not present
@SYMTestExpectedResults Tests must not fail
@SYMREQ                 REQ0000
*/
void RStringPoolPanicTest::DEF043985L()
	{
	test.Next(_L("DEF043985L"));
	
#ifdef _DEBUG
	__UHEAP_MARK;

	TRequestStatus threadStatus;
	RThread thread;
	TInt rc;
	TBool jit;
	jit = User::JustInTime();
	User::SetJustInTime(EFalse);
	
	// Test the Panics for this defect
	
	// RString Test
	rc = thread.Create(_L("DEF043985_StringTest_Thread Panic Test"), 
					   RStringPoolPanicTest::DEF043985_StringTest_ThreadL,
					   KDefaultStackSize, KMinHeapSize, KMinHeapSize<<2, this);
	test(KErrNone == rc);
	thread.Logon(threadStatus);
	thread.Resume();
	User::WaitForRequest(threadStatus);
	test (thread.ExitType() == EExitPanic);
	test (thread.ExitReason() == StringPoolPanic::EStringTableNotFound);
	thread.Close();

	// RStringF Test
	rc = thread.Create(_L("DEF043985_StringFTest_Thread Panic Test"), 
					   RStringPoolPanicTest::DEF043985_StringFTest_ThreadL,
					   KDefaultStackSize, KMinHeapSize, KMinHeapSize<<2, this);
	test(KErrNone == rc);
	thread.Logon(threadStatus);
	thread.Resume();
	User::WaitForRequest(threadStatus);
	test (thread.ExitType() == EExitPanic);
	test (thread.ExitReason() == StringPoolPanic::EStringTableNotFound);
	thread.Close();

	// Index Test
	rc = thread.Create(_L("DEF043985_IndexTest_Thread Panic Test"), 
					   RStringPoolPanicTest::DEF043985_IndexTest_Thread,
					   KDefaultStackSize, KMinHeapSize, KMinHeapSize<<2, this);
	test(KErrNone == rc);
	thread.Logon(threadStatus);
	thread.Resume();
	User::WaitForRequest(threadStatus);
	test (thread.ExitType() == EExitPanic);
	test (thread.ExitReason() == StringPoolPanic::EStringTableNotFound);
	thread.Close();


	User::SetJustInTime(jit);

	__UHEAP_MARKEND;
	
#else
	test.Printf(_L("This test is valid for debug builds only, behaviour for release builds is undefined (DEF050908)\n"));
#endif
	}
void CMemoryMonitorSession::ServiceL(const RMessage2& aMessage)
    {
    FUNC_LOG;
    
    iFunction = aMessage.Function();
    RThread t;
    aMessage.Client(t);
    
    iClientId = t.SecureId();
    t.Close();
    
    TRACES1("NEW REQUEST from client %x", iClientId);
    switch (aMessage.Function())
        {
        case EGOomMonitorRequestFreeMemory:

            //Do not take any more requests from the same client if previous request being served
            if (!iRequestFreeRam.IsNull() && !Server().Monitor().IsSafeToProcessNewRequest(iClientId))
                {
                TRACES1("CANNOT PROCESS NEW REQUEST from %x", iClientId);
                aMessage.Complete(KErrInUse);
                return;
                }
            
            Server().Monitor().SetActiveClient(iClientId);
            // message will be completed when CloseAppsFinished() is called.
            if (aMessage.Int1() == 0)
                {
                iRequestFreeRam = aMessage;

                Server().Monitor().SessionInCriticalAllocation(1, iClientId);
                
                TRAPD(err, Monitor().RequestFreeMemoryL(aMessage.Int0()));
                if(err == KErrCompletion) 
                    {
                    TRACES("There is already enough memory - nothing to do");
                    Server().Monitor().SessionInCriticalAllocation(0, iClientId);
                    }
                else if (err != KErrNone )
                    {
                    // completes the message if that was left to pending
                    TRACES1("Error in RequestFreeMemory %d", err);
                    CloseAppsFinished(0, EFalse);
                    }
                }
            else
                {
                TInt appUid = aMessage.Int1();
                // if no new memory was needed, the message is completed synchronously
                iRequestFreeRam = aMessage;
                TRAP_IGNORE(Monitor().HandleFocusedWgChangeL(appUid));
                }
            break;
            
        case EGOomMonitorMemoryAllocationsComplete:
            TRACES1("ServiceL : Memory Allocations complete from %x", iClientId);
            Server().Monitor().SessionInCriticalAllocation(0, iClientId);
            aMessage.Complete(KErrNone);
            break;

        case EGOomMonitorCancelRequestFreeMemory:
            if (!iRequestFreeRam.IsNull())
                {
                iRequestFreeRam.Complete(KErrCancel);
                }
            Server().Monitor().SessionInCriticalAllocation(0, iClientId);
            aMessage.Complete(KErrNone);
            break;

        case EGOomMonitorThisAppIsNotExiting:
            Monitor().AppNotExiting(aMessage.Int0());
            aMessage.Complete(KErrNone);
            break;

        case EGOomMonitorRequestOptionalRam:
            if (!iRequestFreeRam.IsNull() && !Server().Monitor().IsSafeToProcessNewRequest(iClientId))
                {
                aMessage.Complete(KErrInUse);
                }
            Server().Monitor().SetActiveClient(iClientId);
            // message will be completed when CloseAppsFinished() is called.
            iRequestFreeRam = aMessage;
            iMinimumMemoryRequested = aMessage.Int1();
            Monitor().FreeOptionalRamL(aMessage.Int0(), aMessage.Int2());
            break;
            
        case EGOomMonitorSetPriorityBusy:
            Monitor().SetPriorityBusy(aMessage.Int0());
            aMessage.Complete(KErrNone);
            break;
            
        case EGOomMonitorSetPriorityNormal:
            Monitor().SetPriorityNormal(aMessage.Int0());
            aMessage.Complete(KErrNone);
            break;

        case EGOomMonitorSetPriorityHigh:
            Monitor().SetPriorityHigh(aMessage.Int0());
            aMessage.Complete(KErrNone);
            break;

        case EGoomMonitorAppAboutToStart:
            {
            TInt appUid = aMessage.Int0();
            aMessage.Complete(KErrNone);  
            TRAP_IGNORE(Monitor().HandleFocusedWgChangeL(appUid))
            break;
            }
           
        case EGoomMonitorAppUsesAbsoluteMemTargets:
            {
            iUseAbsoluteTargets = aMessage.Int0();
/*            TRACES2("EGoomMonitorAppUsesAbsoluteMemTargets this: 0x%x, use abs targets %d", this, iUseAbsoluteTargets);
            Server().Monitor().SessionInCriticalAllocation(iUseAbsoluteTargets);
*/          aMessage.Complete(KErrNone);     
            break;
            }    
        case EGOomMonitorRequestHWRendering:
            {
            RDebug::Printf("RAN_DEBUG : GOOM EGOomMonitorRequestHWRendering");
            if(Server().Monitor().SwitchRenderingToHW())
                aMessage.Complete(KErrNone);
            else
                aMessage.Complete(KErrNoMemory);
            
            break;
            }
        default:
            PanicClient(aMessage, EPanicIllegalFunction);
            break;
        }
    }
示例#13
0
TInt CMultiTargetAgent::LaunchTargetsInOrderL()
{
    RDebug::Printf( "CMultiTargetAgent::LaunchTargetsInOrderL" );

    RBuf launcher;
    CleanupClosePushL( launcher );
    launcher.CreateL( KLauncherExe() );

    RBuf launcherOptions;
    CleanupClosePushL( launcherOptions );
    launcherOptions.CreateL( KTargetOptions().Length() + 2 );
    launcherOptions.Format( KTargetOptions(), (TUint)ENormalExit );

    RDebug::Printf( ">LaunchProcess()" );
    RProcess launcherProc;
    CleanupClosePushL( launcherProc );

    TInt ret = LaunchProcess( launcherProc, launcher, launcherOptions );
    RDebug::Printf( "<LaunchProcess() ret %d", ret );

    CleanupStack::PopAndDestroy( &launcherProc ); // launcherProc
    CleanupStack::PopAndDestroy( &launcherOptions ); // launcherOptions
    CleanupStack::PopAndDestroy( &launcher ); //launcher

    test( ret == KErrNone );

    RSemaphore launchSemaphore;
    CleanupClosePushL( launchSemaphore );

    TFindSemaphore launchSemFinder( KLaunchSemaphoreNameSearchString );
    TFullName semaphoreResult;
    ret = launchSemFinder.Next(semaphoreResult);
    RDebug::Printf( ">  Find Launch Semaphote.Next ret=%d, %lS", ret, &semaphoreResult );
    test( ret == KErrNone );

    ret = launchSemaphore.OpenGlobal( semaphoreResult );
    RDebug::Printf( "> OpenGlobal semaphore ret=%d", ret );
    test( ret == KErrNone );

    TBool thisLaunchCompleted;

    test.Next(_L("LaunchTargetsInOrderL\n"));
    for( TInt numLaunches = KNumLaunches; numLaunches > 0; numLaunches-- )
    {
        for( TInt numApps = KNumApps; numApps > 0; numApps-- )
        {
            thisLaunchCompleted = EFalse;
            // This will trigger the launcher app to launch the next target
            RDebug::Printf( " >Semaphore.Signal app=%d, launch=%d", numApps, numLaunches);
            launchSemaphore.Signal();

            RBuf8 tgt8Name;
            CleanupClosePushL( tgt8Name );

            RBuf tgtCollapseName;
            CleanupClosePushL( tgtCollapseName );

            tgtCollapseName.CreateL( iTargets[numApps-1] );
            tgt8Name.CreateL( tgtCollapseName.Collapse() );


            while( ! thisLaunchCompleted )
            {
                RDebug::Printf( ">GetEvent app %d for %S", numApps, &tgt8Name );
                iServSession.GetEvent( iTargets[numApps-1], iStatus, iEventPtr );

                // Wait for the target to get started.
                RDebug::Printf( " >Wait for event from target app=%d, launch=%d\n", numApps, numLaunches);
                User::WaitForRequest( iStatus );
                RDebug::Printf( " <Wait for request returned with status %d", iStatus.Int() );
                test( iStatus==KErrNone );

                RDebug::Printf( " > Got iEventType =%d, app=%d", iEventInfo.iEventType, numApps );
                switch( iEventInfo.iEventType )
                {
                case EEventsAddProcess:
                {
                    RDebug::Printf( "Got EEventsAddProcess" );
                    TPtrC8 exeNamePtr8( iEventInfo.iAddProcessInfo.iFileName, iEventInfo.iAddProcessInfo.iFileNameLength );

                    RBuf8 exeName8;
                    CleanupClosePushL( exeName8 );
                    exeName8.CreateL( exeNamePtr8 );
                    RDebug::Printf( " from event: exeName8=%S", &exeName8 );
                    CleanupStack::PopAndDestroy( &exeName8 );

                    RBuf8 compareName8;
                    CleanupClosePushL( compareName8 );
                    compareName8.CreateL( KTargetExeName().Length() + 10 );
                    compareName8.Format( KTargetExeName(), numApps );
                    RDebug::Printf( " comparing to: compareName8=%S", &compareName8 );

                    test( compareName8.CompareC( exeNamePtr8 ) == 0 );
                    CleanupStack::PopAndDestroy( &compareName8 );

                    RDebug::Printf( "Testing if event process id is valid" );
                    test( iEventInfo.iProcessIdValid );
                    RDebug::Printf( "Got iEventInfo.iProcessId=%d", I64LOW( iEventInfo.iProcessId ) );

                    RProcess targetProc;
                    ret = targetProc.Open( TProcessId( iEventInfo.iProcessId ) );
                    RDebug::Printf( "RProcess open ret=%d",ret );
                    targetProc.Close();
                    test( ret == KErrNone );

                    break;
                }//EEventsAddProcess

                case EEventsStartThread:
                {
                    RDebug::Printf( "Got EEventsStartThread" );

                    TPtrC8 exeNamePtr8( iEventInfo.iStartThreadInfo.iFileName, iEventInfo.iStartThreadInfo.iFileNameLength );
                    RBuf8 exe8Name;
                    CleanupClosePushL( exe8Name );
                    exe8Name.CreateL( exeNamePtr8 );
                    RDebug::Printf( " from event: exeName8=%S", &exe8Name );
                    CleanupStack::PopAndDestroy( &exe8Name );

                    test( tgt8Name.CompareC( exeNamePtr8 ) == 0 );

                    RDebug::Printf( "Testing if event process id is valid" );
                    test( iEventInfo.iProcessIdValid );
                    RDebug::Printf( "Got iEventInfo.iProcessId=%d", I64LOW( iEventInfo.iProcessId ) );

                    RDebug::Printf( "Testing if event thread id is valid" );
                    test( iEventInfo.iThreadIdValid );
                    RDebug::Printf( "Got iEventInfo.iThreadId=%d", I64LOW( iEventInfo.iThreadId ) );

                    RThread targetThread;
                    CleanupClosePushL( targetThread );

                    ret = targetThread.Open( TThreadId( iEventInfo.iThreadId ) );
                    RDebug::Printf( "RThread open ret=%d", ret );
                    test( ret == KErrNone );

                    test( iEventInfo.iThreadId == targetThread.Id() );

                    RDebug::Printf( "Resuming thread for app=%d, id=%d", numApps, I64LOW( targetThread.Id() ));
                    ret = iServSession.ResumeThread( iEventInfo.iThreadId );
                    CleanupStack::PopAndDestroy( &targetThread );

                    test( ret == KErrNone );

                    ret = iServSession.ResumeThread( iEventInfo.iThreadId );
                    break;
                }//case EEventsStartThread

                case ( EEventsRemoveProcess ):
                {
                    RDebug::Printf( "*** Got EEventsRemoveProcess. app%d has exited. Moving on to next app", numApps );
                    thisLaunchCompleted = ETrue;
                    break;
                }

                default :
                    RDebug::Printf( "Got unknown event" );
                    test( EFalse );
                    break;
                }
            }//while

            CleanupStack::PopAndDestroy( &tgtCollapseName ); // tgtCollapseName
            CleanupStack::PopAndDestroy( &tgt8Name ); // tgt8Name
        }
    }

    launchSemaphore.Signal();

    CleanupStack::PopAndDestroy( &launchSemaphore ); // launchSemaphore

    for( TInt i = iTargets.Count()-1; i>=0; i-- )
    {
        RDebug::Printf( "Closing target %d", i );
        iTargets[ i ].Close();
    }

    iTargets.Close();

    return KErrNone;
}
示例#14
0
void CTestConductor::RunL()
	{
	User::After(1000);
	switch (iCurrentTestNumber)
		{
		// Test One - Async Open of a Named Database
		case EAsyncOpenNamed:
	    	test.Next(_L("=== Async Open of Named Db"));

			SetActive();
			iContactOpenOperation = CContactDatabase::Open(KDbFileName,iStatus);
			++iCurrentTestNumber;
			
			break;
			
		// Check Test One Results
		case EAsyncOpenedNamed:
			test(iStatus.Int() == KErrNone);
			test.Printf(_L("=== Opened Async\n"));
			iDb = iContactOpenOperation->TakeDatabase();
			
			test(iDb != NULL);
			delete iContactOpenOperation;
			delete iDb;
			
			NextTest();
			break;

        // Test Two - Async Open of the Default Database
		case EAsyncOpenDefault:
		    test.Next(_L("=== Async Open Default"));

			SetActive();
			iContactOpenOperation = CContactDatabase::Open(iStatus);
			++iCurrentTestNumber;

			break;
		
		// Check Test Two Results	
		case EAsyncOpenedDefault:
			test(iStatus.Int() == KErrNone);
	     	test.Printf(_L("=== Opened Async Default \n"));
			iDb = iContactOpenOperation->TakeDatabase();
            test(iDb != NULL);
            delete iContactOpenOperation;
            delete iDb;            
			
			NextTest();
			break;			
		
		// Test Three - Attempted Async Open of a Non-Existent File
		case EAsyncOpenNonExistent:		
			test.Next(_L("=== Attempted Open of Non-Existent File"));

			SetActive();
			iContactOpenOperation = CContactDatabase::Open(KDbFileNameNotExist,iStatus);
			++iCurrentTestNumber;
			
			break;
			
		// Check Test Three Results	
		case EAsyncOpenedNonExistent:
		    test.Printf(_L("=== Opened Non Existent Response\n"));		
			test(iStatus.Int() == KErrNotFound);
			
			delete iContactOpenOperation;
			NextTest();
			break;	
			
		// Test Four - Cancel the Async Open
		case EAsyncCancelOpenDefault:
			test.Next(_L("=== Cancel Async Open"));


			SetActive();
			iContactOpenOperation = CContactDatabase::Open(iStatus);
			++iCurrentTestNumber;
			
			// Cancel the request
			delete iContactOpenOperation;
						
			break;	
			
		// Check Test Four Results	
		case EAsyncCanceledOpenedDefault:
			test.Printf(_L("=== Cancelled Async Open\n"));
			test(iStatus.Int() == KErrCancel);
			NextTest();
			break;	
			
		// Test Five - Async Open of a damaged Database
		case EAsyncOpenDamaged:					
			test.Next(_L("Open a damaged database"));

            
            SetActive();
			iContactOpenOperation = CContactDatabase::Open(KDbDamaged,iStatus);
			++iCurrentTestNumber;
			
			break;	
		
		// Check Test Five Results
		case EAsyncOpenedDamaged:	
			test(iStatus.Int() == KErrNone);
	     	test.Printf(_L("=== Opened Damaged Db \n"));
			iDb = iContactOpenOperation->TakeDatabase();
            test(iDb != NULL);
            delete iContactOpenOperation;
            delete iDb;
            
			NextTest();
				
			break;
							
		// Test Six - Async Open of a Previous version of the Database	
		case EAsyncOpenPreviousVersion:					
			test.Next(_L("Open an old version database"));

    
			SetActive();
			iContactOpenOperation = CContactDatabase::Open(KDbOldVersionFileName,iStatus);
			++iCurrentTestNumber;
			
			break;	
		
		// Check Test Six Results
		case EAsyncOpenedPreviousVersion:	
   			test(iStatus.Int() == KErrNone);
	     	test.Printf(_L("=== Opened Previoius Version Db \n"));
	     	
			iDb = iContactOpenOperation->TakeDatabase();
            test(iDb != NULL);
            delete iContactOpenOperation;
            delete iDb;			
            
			NextTest();
			break;
			
		// Test Seven - Async Open of a Previous version of the Database, and an Async
		// call open of the same database in a different thread.	
		case EOpenAsyncAndAsync:
		    test.Next(_L("Open Async Then Sync"));

		    
		    // Copy Version 4 Db
		    CopyCdbFileL(KDatabaseV4,KDbOldVersionFilePath);
		
		    // Open Async
		    SetActive();
			iContactOpenOperation = CContactDatabase::Open(KDbOldVersionFileName,iStatus);
			++iCurrentTestNumber;
		    
		    // Lauch Thread to Open Db Asynchronously
		    CDbOpenLauncher::Create(KThreadOpenAsync, KThreadOpenAsync);		
		    break;
		
		// Check Test Seven Results 
		case EOpenedAsyncAndAsync:
			test(iStatus.Int() == KErrNone);
	     	test.Printf(_L("=== Opened After Async Open Db \n"));
	     	
			iDb = iContactOpenOperation->TakeDatabase();
            test(iDb != NULL);
			delete iContactOpenOperation;
            delete iDb;
             
			NextTest();
			break;	
			
			
		// Iterate through these states (allowing other thread to open asynchronously)
		case EWaitState:
			test.Printf(_L("=== Waiting in first thread \n"));
			iCurrentTestNumber = EWaitedState;
			SetActive();
			iContactOpenOperation = CContactDatabase::Open(KDbOldVersionFileName,iStatus);

		    break;
		    
		case EWaitedState:
		
		    test(iStatus.Int() == KErrNone);
	     	test.Printf(_L("=== Opened After Wait Db \n"));
	     	
			iDb = iContactOpenOperation->TakeDatabase();
            test(iDb != NULL);
			delete iContactOpenOperation;
            delete iDb;
            
            if (iWaitCounter < KNumWaitLoops) 
            	{
            	iCurrentTestNumber = EWaitState - 1;  
            	iWaitCounter++; 	
            	}
            else
            	{
            	// move onto next test
                iCurrentTestNumber = EWaitedState;
            	}
            
			NextTest();
			
			break;	
		
		// Test Eight - Async Open of a Previous version of the Database, and a Sync
		// open of the same database in a different thread.	
		case EOpenAsyncAndSync:		
			test.Next(_L("Open Async Then Sync"));

		    
		    // Copy Version 4 Db
		    CopyCdbFileL(KDatabaseV4,KDbOldVersionFilePath);
		
		    // Open Async
		    SetActive();
			iContactOpenOperation = CContactDatabase::Open(KDbOldVersionFileName,iStatus);
		    ++iCurrentTestNumber;
		    
		    // Lauch Thread to Open Db Synchronously
		    CDbOpenLauncher::Create(KThreadOpenSync, KThreadOpenSync);
	        break;
	
		// Check Test Eight Results
		case EOpenedAsyncAndSync:
		  	test(iStatus.Int() == KErrNone);
	     	test.Printf(_L("=== Opened After Sync Open Db \n"));
	     	
			iDb = iContactOpenOperation->TakeDatabase();
            test(iDb != NULL);
			delete iContactOpenOperation;
            delete iDb;
             
			NextTest();
			break;				

		// End of Tests	
		case ENumTests:
			{
			test.Printf(_L("=== Main Tests Complete\n"));
			RThread thread;
			test(thread.RequestCount()==0);

			// tidy up files
			CContactDatabase::DeleteDatabaseL(KDbDamaged);
			CContactDatabase::DeleteDatabaseL(KDefaultDb);			
			CContactDatabase::DeleteDatabaseL(KDbOldVersionFileName);
			 			

			CContactDatabase::DeleteDatabaseL(KDbFileName);
			
			CActiveScheduler::Stop();
			}
			break;
		
		
		default:
			ASSERT(EFalse);
			break;
		}
	}
示例#15
0
GLDEF_C TInt E32Main()
//
// Test server & session cleanup.
//
    {
	RSemaphore svrSem;
	RSemaphore svrSem2;
	RSemaphore clientSem;
	RTest test(_L("T_SVR2"));
	test.Title();

	__KHEAP_MARK;

	test.Start(_L("Creating server semaphore"));
	TInt r=svrSem.CreateGlobal(KSvrSemName, 0);
	test(r==KErrNone);
	test.Next(_L("Creating server semaphore 2"));
	r=svrSem2.CreateGlobal(KSvrSem2Name, 0);
	test(r==KErrNone);
	test.Next(_L("Creating client semaphore"));
	r=clientSem.CreateGlobal(KClientSemName, 0);
	test(r==KErrNone);

	test.Next(_L("Creating server"));
	RThread server;
	r=server.Create(_L("MyServer"),serverThreadEntryPoint,KDefaultStackSize,KHeapSize,KHeapSize,(TAny*)1);
	test(r==KErrNone);
	server.Resume();
	svrSem2.Wait(); // server up & running

	test.Next(_L("Forcing granularity expansion"));
	const TInt KNumberOfSessions=10;
	TInt i;
	RMySessionBase ts[KNumberOfSessions];
	for (i=0; i<KNumberOfSessions; i++)
		ts[i].Open();
	for (i=0; i<KNumberOfSessions; i++)
		ts[i].Close(); 

	test.Next(_L("Opening a session and closing it"));
	RMySessionBase t;
	r=t.Open();
	test(r==KErrNone);
	t.Close();
	RThread clientx;
	r=clientx.Create(_L("MyClientx"),clientThreadEntryPoint,KDefaultStackSize,KHeapSize,KHeapSize,(TAny*)1);
	test(r==KErrNone);
	clientx.Resume();
	clientSem.Wait(); // client connected

	test.Next(_L("Creating client & killing it"));

	RThread client;
	r=client.Create(_L("MyClient"),clientThreadEntryPoint,KDefaultStackSize,KHeapSize,KHeapSize,(TAny*)1);
	test(r==KErrNone);
	client.Resume();
	clientSem.Wait(); // client connected
	User::After(1000000);
	client.Kill(666); // kill the client

	clientx.Kill(666); // kill the client
	CLOSE_AND_WAIT(clientx);
	CLOSE_AND_WAIT(client);

	test.Next(_L("Creating client and killing server"));
	server.Kill(0);	// first kill the existing server 
	CLOSE_AND_WAIT(server);
	RThread client2;	// and create the client so the heap is in a good state for the mark
	r=client2.Create(_L("MyClient"),clientThreadEntryPoint,KDefaultStackSize,KHeapSize,KHeapSize,(TAny*)2);
	test(r==KErrNone);
	client2.Resume();
	clientSem.Wait(); // client running but not connected

	RThread server2;
	r=server2.Create(_L("MyServer"),serverThreadEntryPoint,KDefaultStackSize,KHeapSize,KHeapSize,(TAny*)2);
	test(r==KErrNone);
	server2.Resume();
	svrSem.Wait(); // client has request outstanding to server
	server2.Kill(666); // kill the server
	clientSem.Wait(); // client's request has completed & client has closed session
	User::After(1000000);
	client2.Kill(666);
	CLOSE_AND_WAIT(client2);
	CLOSE_AND_WAIT(server2);

	svrSem.Close();
	svrSem2.Close();
	clientSem.Close();

	__KHEAP_MARKEND; // and check the kernel's heap is OK

	test.End();
 	return(KErrNone);
    }
示例#16
0
// -----------------------------------------------------------------------------
// RDRMHelper::StartServer
// -----------------------------------------------------------------------------
//
TInt RDRMHelper::StartServer()
{
    RThread currentThread;
    const TUint32 secureIdAsTuint32( currentThread.SecureId() );
    TRACE2( "RDRMHelper::StartServer(): currentThread: 0x%08x",
            secureIdAsTuint32 );
    if ( currentThread.SecureId() == KServerSecureId )
    {
        // HelperServer cannot connect to itself.
        return KErrCouldNotConnect;
    }

    TInt result( 0 );

    TFindServer findHelperServer( KDRMHelperServerName );
    TFullName name;

    result = findHelperServer.Next( name );
    TRACE2( "RDRMHelper::StartServer(): result: %d", result );
    if ( result == KErrNone )
    {
        // Server already running
        return KErrNone;
    }

    RSemaphore semaphoreStarting;
    TInt semaphoreExist( semaphoreStarting.CreateGlobal(
                             KDRMHelperServerSemaphoreStartingName, 0 ) );
    TRACE2( "RDRMHelper::StartServer(): semaphoreExist: %d", semaphoreExist );

    if( semaphoreExist != KErrAlreadyExists && semaphoreExist != KErrNone )
    {
        return semaphoreExist;
    }

    // Semaphore exists, wait until server is finished with it's tasks
    if ( semaphoreExist == KErrAlreadyExists )
    {
        TInt openErr( semaphoreStarting.OpenGlobal(
                          KDRMHelperServerSemaphoreStartingName) );
        TRACE2( "RDRMHelper::StartServer(): openErr: %d", openErr );
        if ( openErr != KErrNone )
        {
            return openErr;
        }

        TRACE( "RDRMHelper::StartServer(): semaphoreStarting.Wait()" );
        semaphoreStarting.Wait();
        TRACE( "RDRMHelper::StartServer(): semaphoreStarting.Wait() - returning" );
    }
    else
    {
        RSemaphore semaphoreStartServer;
        TInt result( semaphoreStartServer.CreateGlobal(
                         KDRMHelperServerSemaphoreName, 0 ) );
        TRACE2( "RDRMHelper::StartServer(): 2 result: %d", result );
        if ( result != KErrNone )
        {
            semaphoreStarting.Close();
            return result;
        }

        result = CreateServerProcess();
        TRACE2( "RDRMHelper::StartServer(): 3 result: %d", result );
        if ( result != KErrNone )
        {
            return  result;
        }

        semaphoreStartServer.Wait();
        semaphoreStartServer.Close();

        TRACE( "RDRMHelper::StartServer(): semaphoreStarting.Signal()" );

        semaphoreStarting.Signal();
        semaphoreStarting.Close();
    }

    TRACE( "RDRMHelper::StartServer(): return KErrNone" );
    return  KErrNone;
}
TInt E32Main()
	{
	StaticMain();
	
	RBuf cmd;
	test_KErrNone(cmd.Create(User::CommandLineLength()));
	User::CommandLine(cmd);

	TLex lex(cmd);
	TTestType type;
	test_KErrNone(lex.Val((TInt&)type));
	GlobalObjectWithDestructor.iTestType = type;

	RMsgQueue<TMessage> messageQueue;
	test_KErrNone(messageQueue.OpenGlobal(KMessageQueueName));

	// Dynamically load DLL with global data
	RLibrary library;
	test_KErrNone(library.Load(KDynamicDll));
	
	switch(type)
		{
		case ETestMainThreadReturn:
			test_KErrNone(messageQueue.Send(EMessagePreDestruct));
			return type;

		case ETestMainThreadExit:
			test_KErrNone(messageQueue.Send(EMessagePreDestruct));
			User::Exit(type);
			break;

		case ETestChildThreadReturn:
			{
			// Start child thread passing this thread's id
			MainThreadId = RThread().Id();
			RThread childThread;
			test_KErrNone(childThread.Create(_L("ChildThread"), ChildThread, 4096, NULL, (TAny*)type));
			TRequestStatus status;
			childThread.Rendezvous(status);
			childThread.Resume();

			User::After(1);

			// Wait for child to open handle on this thread
			User::WaitForRequest(status);
			test_KErrNone(status.Int());
			childThread.Close();

			// Set this thread non-critical and exit
			User::SetCritical(User::ENotCritical);
			}
			break;

		case ETestOtherThreadExit:
			{
			RThread childThread;
			test_KErrNone(childThread.Create(_L("ChildThread"), ExitThread, 4096, NULL, (TAny*)type));
			childThread.Resume();
			TRequestStatus status;
			childThread.Logon(status);
			User::WaitForRequest(status);
			test_KErrNone(status.Int());
			childThread.Close();
			test_KErrNone(messageQueue.Send(EMessagePreDestruct));
			}
			return type;

		case ETestOtherThreadPanic:
			{
			RThread childThread;
			test_KErrNone(childThread.Create(_L("ChildThread"), PanicThread, 4096, NULL, (TAny*)type));
			childThread.Resume();
			TRequestStatus status;
			childThread.Logon(status);
			User::WaitForRequest(status);
			test_KErrNone(status.Int());
			childThread.Close();
			test_KErrNone(messageQueue.Send(EMessagePreDestruct));
			}
			return type;
			
		case ETestOtherThreadRunning:
			{
			RThread childThread;
			test_KErrNone(childThread.Create(_L("ChildThread"), LoopThread, 4096, NULL, (TAny*)type));
			childThread.Resume();
			childThread.Close();
			test_KErrNone(messageQueue.Send(EMessagePreDestruct));
			}
			return type;
			
		case ETestPermanentThreadExit:
			{
			RThread childThread;
			test_KErrNone(childThread.Create(_L("ChildThread"), PermanentThread, 4096, NULL, (TAny*)type));
			childThread.Resume();
			TRequestStatus status;
			childThread.Logon(status);
			User::WaitForRequest(status);
			test_KErrNone(status.Int());
			childThread.Close();
			}
			break;
			
		case ETestRecursive:
			test_KErrNone(messageQueue.Send(EMessagePreDestruct));
			break;

		case ETestDestructorExits:
			test_KErrNone(messageQueue.Send(EMessagePreDestruct));
			break;

		case ETestLastThreadPanic:
			test_KErrNone(messageQueue.Send(EMessagePreDestruct));
			Panic(type);
			break;
			
		default:
			test(EFalse);
		}
	return KErrNone;
	}
LOCAL_C void NotifyL()
	{
	CRepository* repository;
	User::LeaveIfNull(repository = CRepository::NewLC(KUidPlatsecTestRepository));
	// Remember that this repository need to be reset
	::AddRepositoryToReset(KUidPlatsecTestRepository);

	PlatSec platsec;

	//
	// Notification on non-existent setting
	//
	TRequestStatus intStatus;
	TInt r = repository->NotifyRequest(KNonExisitent, intStatus);
	TEST2(r, KErrNotFound);


	//
	// Basic notification
	//
	r = repository->NotifyRequest(KInt1, intStatus);
	TEST2(r, KErrNone);

	TRequestStatus realStatus;
	r = repository->NotifyRequest(KReal1, realStatus);
	TEST2(r, KErrNone);

	TRequestStatus stringStatus;
	r = repository->NotifyRequest(KString1, stringStatus);
	if(!platsec.ConfigSetting(PlatSec::EPlatSecEnforcement))
		{
		TEST2(r, KErrNone);
		}
	else
		{
		TEST2(r, KErrPermissionDenied);
		}


	// Setting to the same value should not cause a notification
	TInt intval;
	r = repository->Get(KInt1, intval);
	TEST2(r, KErrNone);
	r = repository->Set(KInt1, intval);
	TEST2(r, KErrNone);
	TEST(intStatus==KRequestPending);
	TEST(realStatus==KRequestPending);
	if(!platsec.ConfigSetting(PlatSec::EPlatSecEnforcement))
		TEST(stringStatus==KRequestPending);
	RThread thisThread;
	TEST(thisThread.RequestCount()==0);

	// First change to setting should cause notification
	r = repository->Set(KInt1, 0);
	TEST2(r, KErrNone);
	User::WaitForAnyRequest();
	TEST(intStatus==KInt1);
	TEST(realStatus==KRequestPending);
	if(!platsec.ConfigSetting(PlatSec::EPlatSecEnforcement))
		TEST(stringStatus==KRequestPending);

	// Second change to setting should not cause notification
	intStatus = 7777;
	r = repository->Set(KInt1, 0);
	TEST2(r, KErrNone);
	TEST(intStatus==7777);
	TEST(realStatus==KRequestPending);
	if(!platsec.ConfigSetting(PlatSec::EPlatSecEnforcement))
		TEST(stringStatus==KRequestPending);
	TEST(thisThread.RequestCount()==0);


	// Setting to the same value should not cause a notification
	TReal realval;
	r = repository->Get(KReal1, realval);
	TEST2(r, KErrNone);
	r = repository->Set(KReal1, realval);
	TEST2(r, KErrNone);
	TEST(intStatus==7777);
	TEST(realStatus==KRequestPending);
	if(!platsec.ConfigSetting(PlatSec::EPlatSecEnforcement))
		TEST(stringStatus==KRequestPending);
	TEST(thisThread.RequestCount()==0);

	r = repository->Set(KReal1, 0.0);
	TEST2(r, KErrNone);
	User::WaitForAnyRequest();
	TEST(intStatus==7777);
	TEST(realStatus==KReal1);
	if(!platsec.ConfigSetting(PlatSec::EPlatSecEnforcement))
		TEST(stringStatus==KRequestPending);


	// Setting to the same value should not cause a notification
	realStatus = 8888;
	TBuf<20> stringval;
	r = repository->Get(KString1, stringval);
	if(!platsec.ConfigSetting(PlatSec::EPlatSecEnforcement))
		TEST2(r, KErrNone);
	else
		TEST2(r, KErrPermissionDenied);
	r = repository->Set(KString1, stringval);
	if(!platsec.ConfigSetting(PlatSec::EPlatSecEnforcement))
		TEST2(r, KErrNone);
	else
		TEST2(r, KErrPermissionDenied);
	TEST(intStatus==7777);
	TEST(realStatus==8888);
	if(!platsec.ConfigSetting(PlatSec::EPlatSecEnforcement))
		TEST(stringStatus==KRequestPending);
	TEST(thisThread.RequestCount()==0);

	_LIT(KStringValue2, "string2");
	r = repository->Set(KString1, KStringValue2);
	if(!platsec.ConfigSetting(PlatSec::EPlatSecEnforcement))
		{
		TEST2(r, KErrNone);
		User::WaitForAnyRequest();
		}
	else
		TEST2(r, KErrPermissionDenied);

	TEST(intStatus==7777);
	TEST(realStatus==8888);
	if(!platsec.ConfigSetting(PlatSec::EPlatSecEnforcement))
		TEST(stringStatus==KString1);


	//
	// Cancelling single notifications
	//
	r = repository->NotifyRequest(KInt1, intStatus);
	TEST2(r, KErrNone);
	r = repository->NotifyCancel(KInt1);
	TEST2(r, KErrNone);
	User::WaitForAnyRequest();
	TEST(intStatus==KUnspecifiedKey);

	intStatus = 7777;
	r = repository->NotifyRequest(KReal1, realStatus);
	TEST2(r, KErrNone);
	r = repository->Set(KInt1, 1);
	TEST2(r, KErrNone);
	r = repository->Set(KReal1, 1.1);
	TEST2(r, KErrNone);
	User::WaitForAnyRequest();
	TEST(intStatus==7777);
	TEST(realStatus==KReal1);
	TEST(thisThread.RequestCount()==0);


	//
	// Cancelling all notifications
	//
	realStatus = 8888;
	r = repository->NotifyRequest(KInt1, intStatus);
	TEST2(r, KErrNone);
	r = repository->NotifyRequest(KReal1, realStatus);
	TEST2(r, KErrNone);

	r = repository->NotifyCancelAll();
	TEST2(r, KErrNone);
	User::WaitForAnyRequest();
	User::WaitForAnyRequest();
	TEST(intStatus==KUnspecifiedKey);
	TEST(realStatus==KUnspecifiedKey);

	intStatus = 7777;
	realStatus = 8888;
	r = repository->Set(KInt1, 2);
	TEST2(r, KErrNone);
	r = repository->Set(KReal1, 2.2);
	TEST2(r, KErrNone);
	TEST(intStatus==7777);
	TEST(realStatus==8888);
	TEST(thisThread.RequestCount()==0);

	//
	// Group notifications
	//
	r = repository->NotifyRequest(0, 0, intStatus);
	TEST2(r, KErrNone);
	User::WaitForAnyRequest();
	// we do not have capabilities for all settings
	TEST(intStatus==KErrPermissionDenied);

	CleanupStack::PopAndDestroy(repository);
	}
示例#19
0
// --------------------------------------------------------------------------
// Set thread priority to normal
// --------------------------------------------------------------------------
void CAknCompaServer::SetThreadPriorityNormal(TAny* /*aUnused*/)
    {
    RThread thread;
    thread.SetPriority(EPriorityNormal);
    }
示例#20
0
    {   // File based DataSource (making a CMMFFile object)
        TMMFFileParams fileParams ;
        fileParams.iPath = TFileName(aFilename) ;
        TMMFFileConfig fileConfig( fileParams ) ;

        // Create the iDataSource object.
        iDataSource = STATIC_CAST(CMMFFile*, MDataSource::NewSourceL( KUidMmfFileSource,
                                  *STATIC_CAST(TDesC8*,&fileConfig)));
    }
    else
    {   // Descriptor based DataSource
        // Reads first 4k buffer from file + puts in iData.
        ReadFileToDescriptorL(aFilename, aOffset, KFormatDefaultFrameSize);

        // Create parameters for the DataSource
        RThread thread;
        TMMFDescriptorParams descParams;
        descParams.iDes  = &iData;
        descParams.iDesThreadId = thread.Id(); // This thread
        TMMFDescriptorConfig descConfig(descParams);

        // Create the MDataSource object.
        iDataSource = STATIC_CAST(CMMFDescriptor*, MDataSource::NewSourceL(
                                      KUidMmfDescriptorSource,
                                      *STATIC_CAST(TDesC8*,&descConfig)
                                  ));
    }
}


示例#21
0
// --------------------------------------------------------------------------
// Set thread priority higher than any non-signed application threads
// --------------------------------------------------------------------------
void CAknCompaServer::SetThreadPriorityHigh()
    {
    RThread thread;
    thread.SetPriority(EPriorityAbsoluteRealTime1);
    }
示例#22
0
TInt CTestSession::CheckDesPresent(const RMessage2& aMessage, TUint aArgIndex, TBool aExpected, TBool aWrite)
	{
	TRequestStatus clientStat;
	
	if (aExpected)
		{
		RDebug::Printf("  Checking message argument at %d is present", aArgIndex);
		}
	else
		{
		RDebug::Printf("  Checking message argument at %d is not present", aArgIndex);
		// Start watching for client thread death
		RThread clientThread;
		aMessage.Client(clientThread);
		clientThread.Logon(clientStat);
		clientThread.Close();
		}
		
	// Get the length of the descriptor and verify it is as expected.
	TInt length = aMessage.GetDesLength(aArgIndex);
	if (length < KErrNone)
		{
		RDebug::Printf("  Error getting descriptor length %d", length);
		return length;
		}
	if (length < 3)
		{// The incorrect descriptor length.
		RDebug::Printf("  Error - Descriptor length too small %d", length);
		return KErrArgument;
		}
	if (!aWrite)
		{// Now read the descriptor and verify that it is present or not.
		TBuf8<5> des;
		TInt r = aMessage.Read(aArgIndex, des);
		if (r != (aExpected ? KErrNone : KErrBadDescriptor))
			{
			RDebug::Printf("  Unexpected value returned from aMessage.Read:%d", r);
			return KErrGeneral;
			}
		if (r==KErrNone && (des[0] != 'a' || des[1] != 'r' || des[2] != 'g'))
			{// The incorrect descriptor data has been passed.
			RDebug::Printf("  Error in descriptor data is corrupt r %d", r);
			return KErrArgument;
			}
		}
	else
		{// Now write to the maximum length of the descriptor.
		TInt max = aMessage.GetDesMaxLength(aArgIndex);
		if (max < 0)
			{
			RDebug::Printf("  Error getting descriptor max. length %d", max);
			return length;
			}
		HBufC8* argTmp = HBufC8::New(max);
		TPtr8 argPtr = argTmp->Des();
		argPtr.SetLength(max);
		for (TInt i = 0; i < max; i++)
			argPtr[i] = (TUint8)aArgIndex;
		TInt r = aMessage.Write(aArgIndex, argPtr);
		if (r != (aExpected ? KErrNone : KErrBadDescriptor))
			{
			RDebug::Printf("  Unexpected value returned from aMessage.Write:%d", r);
			return KErrGeneral;
			}
		}

	if (!aExpected)
		{// The client should have been killed as the data wasn't present.
		RDebug::Printf("  CheckDesPresent: Waiting for client to die");
		User::WaitForRequest(clientStat);
		iClientDied = ETrue;
		RDebug::Printf("  CheckDesPresent: Client dead");
		}
	return KErrNone;
	}
示例#23
0
uintptr_t ThreadId() 
{ 
    RThread current;
    return current.Id();
}
示例#24
0
void TestDateSuffix()
	{
	test.Next(_L("TDateSuffix"));
	
	test.Start(_L("Simple creation and assignment"));
	TDateSuffix suff1;
	test(suff1.Compare(_L("st"))==KErrNone);
	TDateSuffix suff2(1);
	test(suff2.Compare(_L("nd"))==KErrNone);
	suff1.Set(2);
	test(suff1.Compare(_L("rd"))==KErrNone);
	
	test.Next(_L("Constructor in a thread"));
	RThread thread;
	TRequestStatus stat;
	thread.Create(_L("Test Thread"),TestThread1,KDefaultStackSize,0x100,0x200,(TAny*)0);
	thread.Logon(stat);
	thread.Resume();
	User::WaitForRequest(stat);
	test(thread.ExitType()==EExitKill);
	CLOSE_AND_WAIT(thread);
	
	test.Next(_L("Constructor panics for -1"));
	thread.Create(_L("Test Thread"),TestThread1,KDefaultStackSize,0x100,0x200,(TAny*)-1);
	thread.Logon(stat);
	// don't want just in time debugging as we trap panics
	TBool justInTime=User::JustInTime(); 
	User::SetJustInTime(EFalse); 
	thread.Resume();
	User::WaitForRequest(stat);
	User::SetJustInTime(justInTime); 
	test(thread.ExitType()==EExitPanic);
	CLOSE_AND_WAIT(thread);

	test.Next(_L("Constructor panics for KMaxSuffices"));
	thread.Create(_L("Test Thread"),TestThread1,KDefaultStackSize,0x100,0x200,(TAny*)KMaxSuffixes);
	thread.Logon(stat);
	User::SetJustInTime(EFalse); 
	thread.Resume();
	User::WaitForRequest(stat);
	User::SetJustInTime(justInTime); 
	test(thread.ExitType()==EExitPanic);
	CLOSE_AND_WAIT(thread);
	
	test.Next(_L("Set in a thread"));
	thread.Create(_L("Test Thread"),TestThread2,KDefaultStackSize,0x100,0x200,(TAny*)0);
	thread.Logon(stat);
	thread.Resume();
	User::WaitForRequest(stat);
	test(thread.ExitType()==EExitKill);
	CLOSE_AND_WAIT(thread);
	
	test.Next(_L("Set panics for -1"));
	thread.Create(_L("Test Thread"),TestThread2,KDefaultStackSize,0x100,0x200,(TAny*)-1);
	thread.Logon(stat);
	User::SetJustInTime(EFalse); 
	thread.Resume();
	User::WaitForRequest(stat);
	User::SetJustInTime(justInTime); 
	test(thread.ExitType()==EExitPanic);
	CLOSE_AND_WAIT(thread);

	test.Next(_L("Set panics for KMaxSuffices"));
	thread.Create(_L("Test Thread"),TestThread2,KDefaultStackSize,0x100,0x200,(TAny*)KMaxSuffixes);
	thread.Logon(stat);						  
	User::SetJustInTime(EFalse); 
	thread.Resume();
	User::WaitForRequest(stat);
	User::SetJustInTime(justInTime); 
	test(thread.ExitType()==EExitPanic);
	CLOSE_AND_WAIT(thread);

	test.End();
	}
示例#25
0
void* ThreadSelf()
{
	RThread Thread;
	return (void *)Thread.Handle(); 
}
示例#26
0
static void DoTestFileReadCPU(TInt aBlockSize)
//
// Benchmark CPU utilisation for Read method
//
// Read operations are performed for 10 seconds whilst a second thread executes floating point calculations
// The higher the number of calculations the less amount of CPU time has been used by the Read method.
//
{
    enum {EFileReadBuffered = 0x00002000, EFileReadDirectIO = 0x00004000};
    TInt r = File.Open(TheFs, _L("READCPUTEST"), EFileStream | (gReadCachingOn ? EFileReadBuffered : EFileReadDirectIO));
    test_KErrNone(r);

    TInt pos = 0;

    TUint functionCalls = 0;
    TUint fltPntCalls = 0;
    RThread fltPntThrd;

    TBuf<6> buf = _L("Floaty");
    fltPntThrd.Create(buf, FloatingPointLoop, KDefaultStackSize, KHeapSize, KHeapSize, (TAny*) &fltPntCalls);

    RTimer timer;
    timer.CreateLocal();
    TRequestStatus reqStat;

    TUint initTicks = 0;
    TUint finalTicks = 0;

    timer.After(reqStat, KFloatingPointTestTime); // After 10 secs
    initTicks = User::FastCounter();

    // up the priority of this thread so that we only run the floating point thread when this thread is idle
    RThread				thisThread;
    thisThread.SetPriority(EPriorityMuchMore);

    TRequestStatus req;
    fltPntThrd.Logon(req);

    fltPntThrd.Resume();

    for (TInt i = 0; reqStat==KRequestPending; i++)
    {
        TInt r = File.Read(pos, DataBuf, aBlockSize);
        test_KErrNone(r);

        pos += aBlockSize;
        if (pos > KMaxFileSize-aBlockSize)
            pos = 0;

        functionCalls++;
    }

    TUint fltPntCallsFinal = fltPntCalls;
    fltPntThrd.Kill(KErrNone);

    finalTicks = User::FastCounter();

    fltPntThrd.Close();
    User::WaitForRequest(req);

    TInt dataTransferred = functionCalls * aBlockSize;

    TTimeIntervalMicroSeconds duration = TInt64(finalTicks - initTicks) * TInt64(1000000) / TInt64(gFastCounterFreq) ;

    TReal transferRate =  TReal32(dataTransferred) /
                          TReal(duration.Int64()) * TReal(1000000) / TReal(K1K); // KB/s

    test.Printf(_L("Read %7d bytes in %7d byte blocks:\t%11.3f KBytes/s; %d Flt Calcs\n"),
                dataTransferred, aBlockSize, transferRate, fltPntCallsFinal);

    timer.Close();

    File.Close();

    return;
}
TVerdict CUPSDbManagementStep::doTestStepPreambleL()
/**
 * @return - TVerdict code
 * Override of base class virtual
 */
	{
 	__UHEAP_MARK;
 	
 	INFO_PRINTF2(_L("START CELLS: %d"), User::CountAllocCells());
 	
 	// reads client name and SID
	TParse clientFullName;
	RThread client;
	clientFullName.Set(client.FullName(),NULL, NULL);
	iTEFServerName=clientFullName.Name();
	iExpectedClientSid = client.SecureId() ;
	client.Close();
 	
    // Read how many times the test step needs to be repeated.
    TName fStepRepeat(_L("StepRepeat"));
    TInt  repeats;
    
    if(GetIntFromConfig(ConfigSection(),fStepRepeat,repeats))
    	{
    	iStepRepeat=repeats;
    	}
	else
		{	
		iStepRepeat=1;		
		}
    
    // Read values for test sequence from INI file. (ARRAY of values)
	TInt index=0;
	TName fOperation;
	fOperation.Format(_L("Operation_%d"), index);
	TName fClientSid;
	fClientSid.Format(_L("ClientSid_%d"),index);
	TName fEvaluatorId;
	fEvaluatorId.Format(_L("EvaluatorId_%d"),index);
	TName fServiceId;
	fServiceId.Format(_L("ServiceId_%d"),index);
	TName fServerSid;
	fServerSid.Format(_L("ServerSid_%d"),index);
	TName fFingerprint;
	fFingerprint.Format(_L("Fingerprint_%d"),index);
	TName fClientEntity;
	fClientEntity.Format(_L("ClientEntity_%d"),index);
	TName fDescription;
	fDescription.Format(_L("Description_%d"),index);
	TName fDecisionResult;
	fDecisionResult.Format(_L("DecisionResult_%d"),index);
	TName fMajorPolicyVersion;
	fMajorPolicyVersion.Format(_L("MajorPolicyVersion_%d"),index);
	TName fRecordId;
	fRecordId.Format(_L("RecordId_%d"),index);
	TName fEvaluatorInfo;
	fEvaluatorInfo.Format(_L("EvaluatorInfo_%d"),index);
	TName fExpectedDecisionCount;
	fExpectedDecisionCount.Format(_L("ExpectedDecisionCount_%d"),index);
	
	TPtrC 	operation;
	TInt	clientSid;
	TInt	evaluatorId;
	TInt	serviceId;
	TInt	serverSid;
	TPtrC	fingerprint;
	TPtrC	clientEntity;
	TPtrC	description;
	TPtrC	decisionResult;
	TInt	majorPolicyVersion;
	TInt 	recordId;
	TInt	evaluatorInfo;
	TInt 	expectedDecisionCount;
	
	while (GetStringFromConfig(ConfigSection(),fOperation,operation))
		{
		
		// Create an instance of a new request
		CUpsDbRequest* newRequest = CUpsDbRequest::NewL();
		CleanupStack::PushL(newRequest);
		
		// Set the operation to be performed
	    newRequest->iOperation = operation;
	    
	    if(GetHexFromConfig(ConfigSection(),fClientSid,clientSid))
		    {
		    newRequest->iClientSid = clientSid;
		  	newRequest->iDecisionFilter->SetClientSid(TSecureId(clientSid),EEqual);
		    }
	    
		if(GetHexFromConfig(ConfigSection(),fEvaluatorId,evaluatorId))
			{
			newRequest->iEvaluatorId = evaluatorId;	
			newRequest->iDecisionFilter->SetEvaluatorId(TUid::Uid(evaluatorId),EEqual);
			}
		
		if(GetHexFromConfig(ConfigSection(),fServiceId,serviceId))
			{
			newRequest->iServiceId = serviceId;	
			newRequest->iDecisionFilter->SetServiceId(TUid::Uid(serviceId),EEqual);
			}
	
		if(GetHexFromConfig(ConfigSection(),fServerSid,serverSid))
			{
			newRequest->iServerSid = serverSid;	
			newRequest->iDecisionFilter->SetServerSid(TSecureId(serverSid),EEqual);
			}
			
		if(GetStringFromConfig(ConfigSection(),fFingerprint,fingerprint))
			{
			HBufC8* fingerprintConverter = HBufC8::NewLC(fingerprint.Length());
			TPtr8 fingerprintPtr = fingerprintConverter->Des();
			fingerprintPtr.Copy(fingerprint); 	
             
	       	newRequest->iFingerprint = fingerprintPtr;
	       	
	       	HBufC8* binaryFingerprint = StringToBinaryLC(fingerprintPtr);
	       	
	      	newRequest->iDecisionFilter->SetFingerprintL(*binaryFingerprint,EEqual);	
	       	CleanupStack::PopAndDestroy(binaryFingerprint);
	       	CleanupStack::PopAndDestroy(fingerprintConverter); 
			}

		if(GetStringFromConfig(ConfigSection(),fClientEntity,clientEntity))
			{
			HBufC8* clientEntityConverter = HBufC8::NewLC(clientEntity.Length());
			TPtr8 clientEntityPtr = clientEntityConverter->Des();
			clientEntityPtr.Copy(clientEntity); 	
             
	       	newRequest->iClientEntity = clientEntityPtr;
	       	newRequest->iDecisionFilter->SetClientEntityL(clientEntityPtr,EEqual);		
	       	CleanupStack::PopAndDestroy(clientEntityConverter); 
			}
			
		if(GetStringFromConfig(ConfigSection(),fDescription,description))
			{
		    newRequest->iDescription = description;
			}
			
		if(GetStringFromConfig(ConfigSection(),fDecisionResult,decisionResult))
			{
			if(decisionResult.CompareF(_L("Yes"))==0 || decisionResult.CompareF(_L("No"))==0 || decisionResult.CompareF(_L(""))==0 )
				{
				newRequest->iDecisionResult = decisionResult;	
				}
			else 
				{
				ERR_PRINTF3(_L("%S: Unexpected Decision Result - %S"),&iTEFServerName, &decisionResult);
				}
			}

		if(GetIntFromConfig(ConfigSection(),fMajorPolicyVersion,majorPolicyVersion)) 
			{
			newRequest->iMajorPolicyVersion = majorPolicyVersion;
			newRequest->iDecisionFilter->SetMajorPolicyVersion(majorPolicyVersion,EEqual);		
			}
		
		if(GetIntFromConfig(ConfigSection(),fRecordId,recordId))
			{
			newRequest->iRecordId = recordId;
			newRequest->iDecisionFilter->SetRecordId(recordId,EEqual);		
			}
			
		if(GetIntFromConfig(ConfigSection(),fEvaluatorInfo,evaluatorInfo))
			{
			newRequest->iEvaluatorInfo = evaluatorInfo;		
			}
			
		if(GetIntFromConfig(ConfigSection(),fExpectedDecisionCount,expectedDecisionCount))
			{
			newRequest->iExpectedDecisionCount = expectedDecisionCount;		
			}
	    
	    // Add the new service to be requested to array.
	    iArraySersToRequest.AppendL(newRequest);
	    
	    CleanupStack::Pop(newRequest);
	       
	    index++;
	    fOperation.Format(_L("Operation_%d"), index);
	    fClientSid.Format(_L("ClientSid_%d"),index);
		fEvaluatorId.Format(_L("EvaluatorId_%d"),index);
		fServiceId.Format(_L("ServiceId_%d"),index);
		fServerSid.Format(_L("ServerSid_%d"),index);
		fFingerprint.Format(_L("Fingerprint_%d"),index);
		fClientEntity.Format(_L("ClientEntity_%d"),index);
		fDescription.Format(_L("Description_%d"),index);
		fDecisionResult.Format(_L("DecisionResult_%d"),index);
		fMajorPolicyVersion.Format(_L("MajorPolicyVersion_%d"),index);
		fRecordId.Format(_L("RecordId_%d"),index);
		fEvaluatorInfo.Format(_L("EvaluatorInfo_%d"),index);
		fExpectedDecisionCount.Format(_L("ExpectedDecisionCount_%d"),index);
		}
	
	SetTestStepResult(EPass);
	return TestStepResult();
	}
示例#28
0
/** Client dying uncleanly before the operation is finished

*/
void TestClientDies()
{
	TInt r = 0;


	TBuf<20> drive = _L("?:\\");
	TVolumeInfo volInfo;
	drive[0]=(TText)(gDrive+'A');
	
	r = TheFs.CheckDisk(drive);
	TEST(r == KErrNone || r == KErrNotSupported);

	// Sync test
	TBuf<20> buf = _L("Big Write V");
	r = gBig.Create(buf, WriteBigFile, KDefaultStackSize, KHeapSize, KMaxHeapSize, NULL);
	TEST(r == KErrNone);
	
	TRequestStatus status;
	gBig.Logon(status);
	gBig.Resume();
	gSync.Wait();

	// Kill the writing thread and wait for it to die.
	
    if(status.Int() == KRequestPending)
		{// the people who wrote this test did not consider the case when the file write finishes before they try to kill the thread.
		gBig.Kill(KErrGeneral);
		User::WaitForRequest(status);
		TEST(gBig.ExitReason() == KErrGeneral);
		TEST(gBig.ExitType() == EExitKill);
		}

    
    // Make sure the thread is destroyed and the handles it owned and IPCs
    // it executed are closed/cancelled.
    CLOSE_AND_WAIT(gBig);


	r = TheFs.Volume(volInfo, gDrive);
	TESTERROR(r);

	r = TheFs.CheckDisk(drive);
	TEST(r == KErrNone || r == KErrNotSupported);

	r = TheFs.ScanDrive(drive);
	TEST(r == KErrNone || r == KErrNotSupported);

	test.Printf(_L("Sync operation stopped\n"));
	
	// Async test 
	buf = _L("Big Write VI");
	r = gSmall.Create(buf, WriteBigFileAsync, KDefaultStackSize * 2, KHeapSize, KMaxHeapSize, NULL);
	TEST(r == KErrNone);
	
	gSmall.Logon(status);
	gSmall.Resume();
	gSync.Wait();
	
    
    if(status.Int() == KRequestPending)
		{
		// Kill the writing thread and wait for it to die.
		gSmall.Kill(KErrGeneral);
		User::WaitForRequest(status);
		TEST(gSmall.ExitReason() == KErrGeneral);
		TEST(gSmall.ExitType() == EExitKill);
		}


    // Make sure the thread is destroyed and the handles it owned and IPCs
    // it executed are closed/cancelled.
    CLOSE_AND_WAIT(gSmall);

	r = TheFs.CheckDisk(drive);
	TEST(r == KErrNone || r == KErrNotSupported);
	
	r=TheFs.ScanDrive(drive);
	TEST(r == KErrNone || r == KErrNotSupported);
	
	test.Printf(_L("Async operation stopped\n"));
}
示例#29
0
GLDEF_C TInt E32Main()
    {
	TBuf<64> b;
	TInt r;
	TInt i;

	test.Title();
	test.Start(_L("Check loader running"));

#if !defined (__WINS__)
    test.Next(_L("Read drive information"));
	TDriveInfoV1Buf dinfo;
	r=UserHal::DriveInfo(dinfo);
	test(r==KErrNone);
	if (dinfo().iTotalSockets==2)
        TheDriveNumber=3;
    else if (dinfo().iTotalSockets==1)
        TheDriveNumber=2;
    else
		{
		test.Printf(_L("Test not supported on this platform"));
		test.End();
		return(0);
		}
#else
    TheDriveNumber=3;
#endif

	test.Next(_L("Load 1st Media Driver"));
	r=User::LoadPhysicalDevice(MEDDRV_ATA_NAME);
	test(r==KErrNone||r==KErrAlreadyExists);
	r=User::LoadPhysicalDevice(MEDDRV_SINGLE_REQ_NAME);
	test(r==KErrNone||r==KErrAlreadyExists);
	test.Printf(_L("Media drivers installed:\n\r"));
	TFindPhysicalDevice findMediaDrv(_L("Media.*"));
	TFullName findResult;
	r=findMediaDrv.Next(findResult);
	while (r==KErrNone)
		{
		test.Printf(_L("   %S\n\r"),&findResult);
		r=findMediaDrv.Next(findResult);
		}

	b.Format(_L("Connect to local drive %d"),TheDriveNumber);
	test.Next(b);
	TBusLocalDrive theDrive;
	TBool changeFlag=EFalse;
	test(theDrive.Connect(TheDriveNumber,changeFlag)==KErrNone);

	test.Next(_L("Local drive: Capabilities"));
	// Generate a media change to open the profiler media driver rather than the standard one
//	UserSvr::ForceRemountMedia(ERemovableMedia0);
	User::After(300000); // Wait 0.3Sec
	TLocalDriveCapsV2Buf info;
	test(theDrive.Caps(info)==KErrNone);
	test(I64LOW(info().iSize)==(TUint)KTestDriverMediaSize);
	test(info().iType==EMediaRam);

	test.Next(_L("Local drive: Write/Read"));
	TInt len;
	TBuf8<KShortBufferSize> rdBuf,wrBuf;
	wrBuf.SetLength(KShortBufferSize);
	for (i=0;i<KShortBufferSize;i++)
		wrBuf[i]=(TUint8)i;
	for (i=0;i<KTestDriverMediaSize;i+=len)
		{
		len=Min(KShortBufferSize,(KTestDriverMediaSize-i));
		wrBuf.SetLength(len);
		test(theDrive.Write(i,wrBuf)==KErrNone);
		}
	for (i=0;i<KTestDriverMediaSize;i+=len)
		{
		len=Min(KShortBufferSize,(KTestDriverMediaSize-i));
		rdBuf.Fill(0,len);
 		test(theDrive.Read(i,len,rdBuf)==KErrNone);
		wrBuf.SetLength(len);
  	    test(rdBuf.Compare(wrBuf)==0);
		}

	test.Next(_L("Start 2nd thread to format drive"));
	RThread thread;
	TRequestStatus stat;
	test(thread.Create(_L("Thread"),formatThread,KDefaultStackSize,KHeapSize,KHeapSize,NULL)==KErrNone);
	thread.Logon(stat);
	thread.Resume();
  
	test.Next(_L("Drive read/write during format"));
	User::After(2000000); // Wait 2Secs for format to get going
    rdBuf.SetLength(KShortBufferSize);
 	test(theDrive.Read(0,KShortBufferSize,rdBuf)==KErrInUse);
	wrBuf.SetLength(KShortBufferSize);
	test(theDrive.Write(0,wrBuf)==KErrInUse);
    
    // Verify format unaffected
    User::WaitForRequest(stat);
	test(stat==KErrNone);
	CLOSE_AND_WAIT(thread);
	wrBuf.Fill(0xFF,KShortBufferSize);
	for (i=0;i<KTestDriverMediaSize;i+=len)
		{
		len=Min(KShortBufferSize,(KTestDriverMediaSize-i));
		rdBuf.Fill(0,len);
 		test(theDrive.Read(i,len,rdBuf)==KErrNone);
		wrBuf.SetLength(len);
  	    test(rdBuf.Compare(wrBuf)==0);
		}

	test.Next(_L("Load 2nd Media Driver"));
	r=User::FreePhysicalDevice(_L("Media.Tst1"));
	test(r==KErrNone);
	r=User::LoadPhysicalDevice(MEDDRV_SIMULTANEOUS_REQ_NAME);
	test(r==KErrNone||r==KErrAlreadyExists);
	test.Printf(_L("Media drivers installed:\n\r"));
	findMediaDrv.Find(_L("Media.*"));
	r=findMediaDrv.Next(findResult);
	while (r==KErrNone)
		{
		test.Printf(_L("   %S\n\r"),&findResult);
		r=findMediaDrv.Next(findResult);
		}

	test.Next(_L("Local drive: Capabilities"));
	// Generate a media change to open the profiler media driver rather than the standard one
//	UserSvr::ForceRemountMedia(ERemovableMedia0);
	User::After(300000); // Wait 0.3Sec
	test(theDrive.Caps(info)==KErrNone);
	test(I64LOW(info().iSize)==(TUint)KTestDriverMediaSize);
	test(info().iType==EMediaFlash);

	test.Next(_L("Local drive: Write/Read"));
	wrBuf.SetLength(KShortBufferSize);
	for (i=0;i<KShortBufferSize;i++)
		wrBuf[i]=(TUint8)i;
	for (i=0;i<KTestDriverMediaSize;i+=len)
		{
		len=Min(KShortBufferSize,(KTestDriverMediaSize-i));
		wrBuf.SetLength(len);
		test(theDrive.Write(i,wrBuf)==KErrNone);
		}
	for (i=0;i<KTestDriverMediaSize;i+=len)
		{
		len=Min(KShortBufferSize,(KTestDriverMediaSize-i));
		rdBuf.Fill(0,len);
 		test(theDrive.Read(i,len,rdBuf)==KErrNone);
		wrBuf.SetLength(len);
  	    test(rdBuf.Compare(wrBuf)==0);
		}

	test.Next(_L("Start 2nd thread again to format drive"));
	test(thread.Create(_L("Thread"),formatThread,KDefaultStackSize,KHeapSize,KHeapSize,NULL)==KErrNone);
	thread.Logon(stat);
	thread.Resume();
  
	test.Next(_L("Drive read/write during format"));
	User::After(2000000); // Wait 2Secs for format to get going
    rdBuf.SetLength(KShortBufferSize);
 	test(theDrive.Read(0,KShortBufferSize,rdBuf)==KErrNone);
	wrBuf.Fill(0xFF,KShortBufferSize);
  	test(rdBuf.Compare(wrBuf)==0);
	
    for (i=0;i<KShortBufferSize;i++)
		wrBuf[i]=(TUint8)i;
	test(theDrive.Write(0,wrBuf)==KErrNone);
 	test(theDrive.Read(0,KShortBufferSize,rdBuf)==KErrNone);
  	test(rdBuf.Compare(wrBuf)==0);
    
    // Verify remaining part of format
    User::WaitForRequest(stat);
	test(stat==KErrNone);
	CLOSE_AND_WAIT(thread);
	wrBuf.Fill(0xFF,KShortBufferSize);
	for (i=KShortBufferSize;i<KTestDriverMediaSize;i+=len)
		{
		len=Min(KShortBufferSize,(KTestDriverMediaSize-i));
		rdBuf.Fill(0,len);
 		test(theDrive.Read(i,len,rdBuf)==KErrNone);
		wrBuf.SetLength(len);
  	    test(rdBuf.Compare(wrBuf)==0);
		}

	test.Next(_L("Unload 2nd Media Driver"));
	User::FreePhysicalDevice(_L("Media.Tst2"));
	// Generate a media change to restore the standard one next mount
//	UserSvr::ForceRemountMedia(ERemovableMedia0);
	User::After(300000); // Wait 0.3Sec

	theDrive.Disconnect();
	test.End();
	return(0);
	}