// ----------------------------------------------------------------------------------------
// CTerminalControlServer::StopProcessByFullNameL
// ----------------------------------------------------------------------------------------
void CTerminalControlServer::StopProcessByFullNameL(const TDesC8& aName) {
    RDEBUG("[CTerminalControlServer]-> StopProcessByFullNameL() >>>");


    TInt rounds = 5;
    TFileName lMatchStr;
    lMatchStr.Copy(aName);
    lMatchStr.LowerCase();

    TBool lIsAbsolute = EFalse;
    if(lMatchStr.LocateReverse(TChar('\\')) != KErrNotFound) {
        lIsAbsolute = ETrue;
    }
    while(rounds--) {
        TInt ret = KErrNone;
        TFullName processName;
        TFindProcess findProcess;

        while(KErrNone == (ret = findProcess.Next(processName))) {
            RProcess process;

            if(KErrNone == (ret = process.Open(findProcess))) {
                RDEBUG("[CTerminalControlServer]-> Process.Open() returned");

                TFileName lStrSource(process.FileName());
                lStrSource.LowerCase();
                if(lIsAbsolute) {
                    RDEBUG("[CTerminalControlServer]-> INFO: The input was specified as an absolute path...");
                    if(lStrSource.Compare(lMatchStr) == 0) {
                        RDEBUG("[CTerminalControlServer]-> Process with correct Filename found => Kill(0) ");
                        process.Kill(0);
                    }
                }
                else {
                    RDEBUG("[CTerminalControlServer]-> INFO: The input was specified as an application name...");
                    TInt lLastDirSepIndex = lStrSource.LocateReverse('\\');
                    TInt lExeIndex = lStrSource.Find(_L(".exe"));
                    if(lLastDirSepIndex < lExeIndex) {
                        TInt lAppNameIndex = lStrSource.Find(lMatchStr);

                        /*
                         * The logic works like this, if the value of lStrSource was 'z:\sys\bin\calendar.exe', lMatchStr would contain calendar
                         * the values of the variables will be as follows
                         * lLastDirSepIndex = 10
                         * lAppNameIndex = 11
                         * lExeIndex = 19
                         *
                         * The below logic would make sure that the right process is killed
                         */
                        if((lAppNameIndex == (lLastDirSepIndex + 1)) && ((lAppNameIndex + lMatchStr.Length()) == lExeIndex)) {
                            RDEBUG("[CTerminalControlServer]-> Process with correct Filename found => Kill(0)");
                            process.Kill(0);
                        }
                    }
                }
            }
            else {
                RDEBUG_2("[CTerminalControlServer]-> Process.Open() returned %d", ret);
            }
        }
        if(KErrNone != ret) {
            RDEBUG_2("[CTerminalControlServer]-> findProcess.Next() returned %d", ret);
        }
    }
    RDEBUG("[CTerminalControlServer]-> StopProcessByFullNameL() <<<");
}
예제 #2
0
//Terminate process when user press "Esc key"
void CSMPSoakThread::TerminateChildProcess()
    {
    iProcess.Kill(KErrNone);
    }
/*
Bonus-test APPFWK-SYSMON-0001C 
Testing consistency of assertions in RSysMonSession::MonitorL
*/
void CStepProcMonInit::DoTestErrArgumentL()
	{
	INFO_PRINTF1(_L("TEST APPFWK-SYSMON-0001C -  validade that sysmon refuse invalid requests"));

	RProcess process;
	CleanupClosePushL(process);
	User::LeaveIfError(process.Create(KTestProcGood, KNullDesC));
	ResumeL(process);
	
	RSysMonSession sess;
	sess.OpenL();
	CleanupClosePushL(sess);
	CStartupProperties* prop = CStartupProperties::NewLC(KTestProcGood, KNullDesC);
	CSsmStartupProperties* ssmProp = CSsmStartupProperties::NewLC(KTestProcGood, KNullDesC);
	
	INFO_PRINTF1(_L("Going to check if RSysMonSession::MonitorL correctly refuse monitor with CStartupProperties::Monitor()==EFalse using startupproperties"));
	TRAPD(err, sess.MonitorL(*prop, process)); 
	TESTE(err == KErrArgument, err);

	INFO_PRINTF1(_L("Going to check if RSysMonSession::MonitorL correctly refuse monitor with CStartupProperties::Monitor()==EFalse using ssmstartupproperties"));
	TRAP(err, sess.MonitorL(*ssmProp, process)); 
	TESTE(err == KErrArgument, err);
	
	INFO_PRINTF1(_L("Going to check if RSysMonSession::MonitorL correctly refuse monitor with CStartupProperties::StartMethod==EDeferredWaitForStart using startupproperties"));
	prop->SetStartMethod(EDeferredWaitForStart);
	prop->SetNoOfRetries(0);
	TRAP(err, sess.MonitorL(*prop, process)); 
	TESTE(err == KErrArgument, err);

	INFO_PRINTF1(_L("Going to check if RSysMonSession::MonitorL correctly refuse monitor with CStartupProperties::StartMethod==ESsmDeferredWaitForSignal using ssmstartupproperties"));
	ssmProp->SetExecutionBehaviour(ESsmDeferredWaitForSignal);	
	TSsmMonitorInfo monitorInfo;
	monitorInfo.iRestartPolicy = ESsmIgnoreOnFailure;
	monitorInfo.iRestartMode = 0;
	monitorInfo.iTimeout = 0;
	monitorInfo.iRetries = 0;
	ssmProp->SetMonitorInfoL(monitorInfo);
	TRAP(err, sess.MonitorL(*ssmProp, process)); 
	TESTE(err == KErrArgument, err);
	
	INFO_PRINTF1(_L("Going to check if RSysMonSession::MonitorL correctly refuse to restart another exe image than the one it monitors using startupproperties."));
	prop->SetStartMethod(EWaitForStart);
	prop->SetNoOfRetries(1);
	prop->SetFileParamsL(_L("sdkjfhsdk"), KNullDesC);
	TRAP(err, sess.MonitorL(*prop, process)); 
	TESTE(err == KErrArgument, err);

	INFO_PRINTF1(_L("Going to check if RSysMonSession::MonitorL correctly refuse to restart another exe image than the one it monitors using ssmsstartupproperties."));
	ssmProp->SetExecutionBehaviour(ESsmWaitForSignal);	
	monitorInfo.iRestartPolicy = ESsmIgnoreOnFailure;
	monitorInfo.iRestartMode = 0;
	monitorInfo.iTimeout = 0;
	monitorInfo.iRetries = 1;
	ssmProp->SetMonitorInfoL(monitorInfo);
	ssmProp->SetFileParamsL(_L("sdkjfhsdk"), KNullDesC);
	TRAP(err, sess.MonitorL(*ssmProp, process)); 
	TESTE(err == KErrArgument, err);

	INFO_PRINTF1(_L("Going to check if RSysMonSession::MonitorL correctly refuse to monitor a dead process using startupproperties."));
	prop->SetFileParamsL(KTestProcGood, KNullDesC);
	prop->SetStartMethod(EWaitForStart);
	prop->SetMonitored(ETrue);
	prop->SetNoOfRetries(1);
	process.Kill(KErrNone);
	TRAP(err, sess.MonitorL(*prop, process)); 
	TESTE(err == KErrDied, err);

	INFO_PRINTF1(_L("Going to check if RSysMonSession::MonitorL correctly refuse to monitor a dead process using ssmstartupproperties."));
	ssmProp->SetFileParamsL(KTestProcGood, KNullDesC);
	TRAP(err, sess.MonitorL(*ssmProp, process)); 
	TESTE(err == KErrDied, err);

	CleanupStack::PopAndDestroy(ssmProp);
	CleanupStack::PopAndDestroy(prop);
	CleanupStack::PopAndDestroy(&sess);
	CleanupStack::PopAndDestroy(&process);
	}
TVerdict CProcessLaunchTest0Step::doTestStepL()
/**
 * @return - TVerdict code
 * Override of base class pure virtual
 * Our implementation only gets called if the base class doTestStepPreambleL() did
 * not leave. That being the case, the current test result value will be EPass.
 */
	{
	_LIT(KThreadName, "*lbsgpslocmanager*");
	TProcessStartParams processParams;
	_LIT(KDummyFileName, "\\sys\\bin\\lbsgpslocmanager.exe");
	_LIT(KDummyProcessName, "DummyAgpsManager");
	processParams.SetProcessFileName(KDummyFileName);
	processParams.SetProcessName(KDummyProcessName);
	processParams.SetRendezvousRequired(EFalse);

	if (TestStepResult()==EPass)
		{
		CProcessLaunch::ProcessLaunch(processParams);
		// now we have to look for this thread. 
		TFindThread threadFinder(KThreadName);
		TFullName matchedThreadName;
		// see how many instances we have of the thread
		TInt matchCount = 0;
		while(threadFinder.Next(matchedThreadName) == KErrNone)
			{
			++matchCount;
			}
		// match count must be one at this point
		if(matchCount!=1)
			{
			// fail the test, its all gone very wrong - there are 2 processes
			SetTestStepResult(EFail);
			}
		// now we want to grab the ThreadID (we can just use thead id's, don't need handles)
		RThread processThread;
		User::LeaveIfError(processThread.Open(matchedThreadName));
		TThreadId tid = processThread.Id();
		// now try and break things, by starting a 2nd copy of the process.

		CProcessLaunch::ProcessLaunch(processParams); // NB we use the same process params
		matchCount = 0;
		threadFinder.Find(KThreadName);
		while(threadFinder.Next(matchedThreadName)==KErrNone)
			{
			++matchCount;
			}
		// match count must be one at this point
		if(matchCount!=1)
			{
			// fail the test, its all gone very wrong - there are 2 processes
			// this is were we will fail with the current code.
			SetTestStepResult(EFail);
			}
		// check the thread ID's
		RThread newProcessThread;
		User::LeaveIfError(newProcessThread.Open(matchedThreadName));
		TThreadId newTid = newProcessThread.Id();
		if(newTid.Id() != tid.Id())
			{
			// fail the test these are different thread id's
			// This is to be expected in the current code base
			SetTestStepResult(EFail);
			}
		else
			{
			// test passes - there is only one instance of the process
			SetTestStepResult(EPass);
			}
		}
		// now kill the process we started
		_LIT(KStar, "*");
		TFullName wildCardPattern;
		wildCardPattern.Append(KStar);
		wildCardPattern.Append(KThreadName);
		wildCardPattern.Append(KStar);
		TFindProcess pf(wildCardPattern);
		TFullName name;
		TInt findError = pf.Next(name);
		RProcess p;
		TInt pErr = 0;
		pErr = p.Open(name);
		User::LeaveIfError(pErr);
		// nuke it
		p.Kill(0);
		p.Close();
		return TestStepResult();
	}
TVerdict CAppFwkStartSafeTestStepProcMonSysRestart::doTestStepL()
	{
	
#ifdef __WINSCW__
	ASSERT(0);
#endif	

	CActiveScheduler* sched = new(ELeave) CActiveScheduler;
	CleanupStack::PushL(sched);
	CActiveScheduler::Install(sched);	
	
	iNotifier = CSaveNotifier::NewL(*this);

	CStartSafe* startSafe = CStartSafe::NewL();	
	CleanupStack::PushL( startSafe );

	CStartupProperties* prop = CStartupProperties::NewLC();
	prop->SetFileParamsL(KTestProcGood, KNullDesC);	
	prop->SetStartMethod(EWaitForStart);
	prop->SetMonitored(ETrue);
	prop->SetRecoveryParams(ERestartOS, 0);
	
	TInt tried;
	RProcess proc;
	CleanupClosePushL(proc);
	TRAPD(err, startSafe->StartAndMonitorL(*prop, proc, tried));
	TEST(KErrNone == err);
	CleanupStack::Pop(&proc);
	CleanupStack::PopAndDestroy(prop);
	CleanupStack::PopAndDestroy(startSafe);
	INFO_PRINTF1(_L("Process monitoring setup with TRecoveryMethod=ERestartOS"));

	proc.Kill(KErrNone);
	proc.Close();
	
	TTime init;
	init.UniversalTime();
	INFO_PRINTF4( _L("Process killed at time %d:%d.%d"), init.DateTime().Minute(), init.DateTime().Second(), init.DateTime().MicroSecond());
	INFO_PRINTF1(_L("Starting scheduler (expecting an OS restart)"));
	CActiveScheduler::Start(); //Wait for MSaveObserver callback
	
	//resume here after callback has stopped the scheduler
	TESTE(iCallbackReceived, iCallbackReceived);
	if(iCallbackReceived)
		{
		const TTimeIntervalMicroSeconds elapsedTime = iShutdownPerformed.MicroSecondsFrom(init);
		const TDateTime dt = iShutdownPerformed.DateTime();
		const TInt64 value = elapsedTime.Int64();
		INFO_PRINTF5(_L("Shutdown callback received at time %d:%d.%d (after %d microseconds)"), dt.Minute(), dt.Second(), dt.MicroSecond(), value);
		TESTE((value >= 0) && (value < 1000000), value); // within 1 second	
		}
	else
		{
		INFO_PRINTF1( _L("Restart didn't take place :-("));
		TEST(EFalse);	
		}
	
	// Now call CPowerdownClient::QueryServerPowerState() which will in turn call the method 'ServerPowerState()'
	// to stop the shutdown. This function call will cause the shutdown server in syslibs/pwrcli to cancel power off.
	INFO_PRINTF1(_L("Aborting shutdown."));
	TBool powerOff = EFalse;
	CPowerdownClient* powerdownclient = CPowerdownClient::NewL();
	CleanupStack::PushL(powerdownclient);
	TEST(KErrNone == powerdownclient->QueryServerPowerState(iNotifier,powerOff));
	TEST(powerOff);
	CleanupStack::PopAndDestroy(powerdownclient);
	
	CleanupStack::PopAndDestroy(sched);
	return TestStepResult();	
	}
예제 #6
0
EXPORT_C void CMsvTestUtils::CleanMessageFolderL()
	{

	//Kill the message server if its running
	_LIT(KMsvServerPattern, "!MsvServer*");
	TFindProcess findprocess(KMsvServerPattern);
	TFullName name;
	if(findprocess.Next(name)==KErrNone)
		{
		RProcess process;
    	User::LeaveIfError(process.Open(findprocess));
     	process.Kill(KErrCancel) ;
		process.Close() ;
		}
	
	// Wait for the server to close before trying to remove
	// the message folder
	
	TInt loopCount = 0;
	FOREVER
		{
		TFindServer find(KMsvServerPattern);
		if (find.Next(name) != KErrNone)
			break;
		User::After(1000000);
		++loopCount;
		if(loopCount > 5)
			{
			User::Invariant();
			}
		}
	
	// remove the drive from the system ini 
	CDictionaryFileStore* store = CDictionaryFileStore::SystemLC(iFs);
	if (store->IsPresentL(KUidMsvMessageDriveStream))
		{
		store->RemoveL(KUidMsvMessageDriveStream); 
		store->CommitL();
		}
	CleanupStack::PopAndDestroy(); // store

	CFileMan* fileMan = CFileMan::NewL(iFs); 
	CleanupStack::PushL(fileMan);
	TParse parse;
	TInt error;
	TFileName fileName(KMsvDefaultFolder2); 
	
	TChar driveChar=FileSession().GetSystemDriveChar();
 	TBuf<2> systemDrive = iDriveName;

	parse.Set(fileName, &systemDrive, NULL);
	error = fileMan->RmDir(parse.DriveAndPath()); 
	error = iFs.RmDir(parse.DriveAndPath()); 
	if (!(error==KErrNotFound||error==KErrNone || error == KErrPathNotFound))
		{
        TPtrC driveAndPath = parse.DriveAndPath();
		Printf(_L("Directory %S cannot be removed. "), &driveAndPath);
		Printf(_L("Please ensure directory is not in use.\n"));
		User::Leave(KErrAccessDenied);
		}
	
	//delete DBs in C:, D: and E:.
	TPath pathNameTemp(iDriveName);
	pathNameTemp.Append(KDbFileName);
	RSqlDatabase::Delete(pathNameTemp);
	pathNameTemp = _L("D:");
	pathNameTemp.Append(KDbFileName);
	RSqlDatabase::Delete(pathNameTemp);
	pathNameTemp = _L("E:");
	pathNameTemp.Append(KDbFileName);	
	RSqlDatabase::Delete(pathNameTemp);

	// delete "StoreInit.tmp"
 	TPath pathName(iDriveName);
	pathName.Append(KStoreInitFileName);  	
	iFs.Delete(pathName); 
	CleanupStack::PopAndDestroy(fileMan);
	}
TVerdict CAppFwkStartSafeTestStepAppStartAppArcInit::doTestStepL( void )
	{
	
	CStartSafe* startSafe = CStartSafe::NewL();	
	CleanupStack::PushL( startSafe );
	
	CStartupProperties* prop = CStartupProperties::NewL();
	CleanupStack::PushL( prop );
	
	RProcess proc;
	CleanupClosePushL( proc );
	
	prop->SetFileParamsL( KTestAppGood, KNullDesC );
	prop->SetStartupType( EStartApp );
	prop->SetStartMethod( EDeferredWaitForStart );
	

	TRequestStatus startupTRS;
	TRequestStatus apparcSessionTRS;
	
	INFO_PRINTF1(_L("Starting the Test-App process asynchronously"));
	
	startSafe->StartL( *prop, proc, startupTRS );	

	User::WaitForRequest( startupTRS );
	INFO_PRINTF2( _L("Rendezvous completed with %d"), startupTRS.Int() );	
	
	// StartL should have left if it was unsuccessful, 
	// but ensure that the process's name is that of the test-app.
	TPtrC procNamePtr = proc.FileName().Right( KTestAppGood().Length() );
	TInt nameComparison = procNamePtr.Compare( KTestAppGood() );
	
	if( 0 == nameComparison )
		{
		INFO_PRINTF2( _L("Application \"%S\" started correctly"), &procNamePtr );	
		}
	else
		{
		ERR_PRINTF1( _L("Application-start unsuccessful. Test not completed") );
		
		SetTestStepResult( EFail );
		return TestStepResult();
		}
	
	startSafe->InitAppArcServer( apparcSessionTRS ); // try to initiate apparc, to see if that causes any problems
	User::WaitForRequest( apparcSessionTRS );
	

	if ( ( startupTRS == KErrNone) && ( apparcSessionTRS == KErrNone) )
		{
		SetTestStepResult( EPass );
		INFO_PRINTF1( _L("Test passed") );
		// Dispose of the test-app
		proc.Kill( KErrNone );		
		}
	else
		{
		SetTestStepResult( EFail );
		ERR_PRINTF3( _L("Test failed.startupTRS = %d apparcSessionTRS = %d "), startupTRS.Int(), apparcSessionTRS.Int() );				
		}
	
		
	CleanupStack::PopAndDestroy( 3, startSafe );

	return TestStepResult();	
	}
예제 #8
0
// -----------------------------------------------------------------------------
// RPhCltServer::StartServer
// 
// Launches the phone server, which is assumed to be not
// already running.
// -----------------------------------------------------------------------------
//
TInt RPhCltServer::StartServer()
    {
    // The uid of the DLL/EXE - used to identify the correct target
    const TUidType KPhServerUidType( 
        KExecutableImageUid, 
        KSharedLibraryUid, 
        KPhCltServerUid );
    

    //////////////////////////////////////////////////////////////////////////
    // On MARM, the server is an exe, so it is run inside its own process. 
    // The server itself takes care of creating a thread and finalizing the 
    // construction of the server. We pass the signalling object via the 
    // command line.
    //////////////////////////////////////////////////////////////////////////

    RProcess serverUnitOfExecution;

    TFileName pathName( KPhCltServerZDrive );
    pathName.Append( KDC_PROGRAMS_DIR );
    pathName.Append( KPhServerPathAndNameMARM );
    pathName.ZeroTerminate();

    TInt err = serverUnitOfExecution.Create( 
        pathName,
        KNullDesC, 
        KPhServerUidType );

    if ( err != KErrNone )
        {
        User::Panic( PH_SRV_SU_FAILURE, err );
        }
    serverUnitOfExecution.SetPriority( EPriorityHigh );


    // Now wait for the server to start up, and also observe if the server
    // thread dies for any reason.


	TRequestStatus stat;
	serverUnitOfExecution.Rendezvous( stat );
 	if ( stat != KRequestPending )
        {
        User::Panic( PH_SRV_SU_FAILURE, EPhSrvStartupFailurePhase1 );

 		serverUnitOfExecution.Kill( KErrAbort );	// abort startup
        }
 	else
        {
 		serverUnitOfExecution.Resume();	// logon ok
        }

    // wait for start or death
 	User::WaitForRequest( stat ); 
 	// we can't use the 'exit reason' if the server panicked as this
 	// is the panic 'reason' and may be '0' which cannot be distinguished
 	// from KErrNone
 	err = ( serverUnitOfExecution.ExitType() == EExitPanic ) 
        ? KErrGeneral : stat.Int();

    serverUnitOfExecution.Close();


    return err;
    }
예제 #9
0
void CSsTestStepProcStart::DoTestForMonitorAlreadyMonProcL()
	{
	INFO_PRINTF1( _L("\n\nPerforming Process-monitor test for already started and monitored process") );
	
	RProcess process;
	CleanupClosePushL(process);
	
	CSsmStartupProperties* startupProperties = CSsmStartupProperties::NewL();
	CleanupStack::PushL( startupProperties );
	
	// Need to start testprocess as a server so that we can tell it to stop being monitored.
	startupProperties->SetFileParamsL(KTestProcGood, KLaunchServerCommandLineOption);
	startupProperties->SetCommandTypeL(ESsmCmdStartProcess);
	startupProperties->SetExecutionBehaviour(ESsmWaitForSignal);
	
	const TInt KMonitorTimeout = 3000; // milliseconds I presume
	TSsmMonitorInfo monitorInfo;
	monitorInfo.iRestartPolicy = ESsmIgnoreOnFailure;
	monitorInfo.iRestartMode = 0;
	monitorInfo.iTimeout = KMonitorTimeout;
	monitorInfo.iRetries = 1;
	startupProperties->SetMonitorInfoL(monitorInfo);

	CSsmStartSafe* ss  = CSsmStartSafe::NewLC();

	// Try to start and monitor the process
	TRAPD(err, ss->StartAndMonitorL(*startupProperties, process));
	TEST(err == KErrNone);
	INFO_PRINTF3( _L("StartAndMonitorL() completed with %d. anticipated value %d"),err, KErrNone );
	
	RTestProcGoodSession testProcServerSession;
	err = testProcServerSession.Connect();
	TEST(KErrNone == err);
	INFO_PRINTF1( _L("Asserted that server is running"));

	// Try to start and monitor an already started and monitored process
	TRAP(err, ss->StartAndMonitorL(*startupProperties, process));

	// sysmon returns KErrAlreadyExists, if we try to monitor an already monitored process
	TEST(err == KErrAlreadyExists);
	INFO_PRINTF3( _L("StartAndMonitorL() completed with %d. anticipated value %d"),err, KErrAlreadyExists);
	
	process.Kill(KErrNone);
	
	err = testProcServerSession.Connect();
	//Connecting to the test proc server session should fail here with error value as either KErrNotFound(in case session object is cleaned up) or KErrServerTerminated(session object is there but session terminated) 
	TEST(KErrNotFound == err || KErrServerTerminated == err);
	INFO_PRINTF3( _L("Connect to test proc server session failed with %d. anticipated value %d"),err, KErrNotFound);

	RSemaphore sem;
	err = sem.CreateGlobal(KStartProcSignalSemaphore, 0);
	INFO_PRINTF2(_L("Created semaphore with err %d"),err);
	TEST(err == KErrNone);
	CleanupClosePushL(sem);
	
	INFO_PRINTF1(_L("Waiting for Start of the test application"));
	sem.Wait();
	//Waiting for 5 seconds as in the ssmtestprocgood application the active scheduler
	// will be started after signalling the semaphore.  And we can connect to the
	// application only after the active scheduler is started.
	User::After(KWaitForActiveSchedStart);
	
	// Check that the killed process is restarted by SysMon
	err = testProcServerSession.Connect();
	TEST(KErrNone == err);
	INFO_PRINTF3( _L("process re-started by sysmon with %d, anticipate value %d"),err,KErrNone);
	
	// Stop monitoring to stop restarts.
	if(KErrNone == testProcServerSession.Connect())
		{
		testProcServerSession.CancelMonitor();
		testProcServerSession.Close();
		}
	TEST(1 == FindAndKill(KTestProcGood));
	CleanupStack::PopAndDestroy(4, &process);
	}
/**
 * Start the server process/thread which lives in an EPOCEXE object.
 *
 * \internal
 * @return KErrNone if successful, any other error code otherwise
 */
TInt RSuplNetworkServer::StartServer()
    {
    TRequestStatus started;
    TInt ret;

    RSemaphore startupSemaphore;
    ret = startupSemaphore.CreateGlobal( KSuplServerStartupSemaphoreName, 0 );

    if ( ret == KErrAlreadyExists )
        {
        // The server is starting up, but has not yet started 
        startupSemaphore.OpenGlobal( KSuplServerStartupSemaphoreName );
        // wait until the server has started up, Max 5 secs.
        TInt err = startupSemaphore.Wait(5000000); 
        startupSemaphore.Close();
        if (err != KErrNone)
        	return err;
        else
        	return ret;
        }

#ifdef _DEBUG
    RDebug::Print(_L("SuplNetworkApi: Starting SUPL Server..."));
#endif
    const TUidType serverUid(KNullUid, KNullUid, KSuplServerUid3);

    // Simultaneous launching of two such processes should be detected 
    // when the second one attempts to create the server object, 
    // failing with KErrAlreadyExists.
    //
    RProcess server;
    ret = server.Create(KSuplServerImg, KNullDesC, serverUid);

    if (ret != KErrNone)
        {
#ifdef _DEBUG
        RDebug::Print(_L("SuplApi: server start failed %d"), ret);
#endif
        startupSemaphore.Close();
        return ret;
        }

    TRequestStatus died;
    server.Rendezvous(died);

    if (died != KRequestPending)
        {
        // logon failed - server is not yet running, so cannot have terminated
        User::WaitForRequest(died); // eat signal
        server.Kill(0);                         // abort startup
        }
    else
        {
        server.Resume();
        }
    User::WaitForRequest(died);                // wait for start or death

    // we can't use the 'exit reason' if the server panicked as this
    // is the panic 'reason' and may be '0' which cannot be distinguished
    // from KErrNone
    ret = (server.ExitType() == EExitPanic) ? KErrGeneral : died.Int();
    server.Close();
    startupSemaphore.Wait();
    startupSemaphore.Close();
    return ret;
    }
// -----------------------------------------------------------------------------
// RUsbPnClient::ConnectL
// (other items were commented in a header).
// -----------------------------------------------------------------------------
//
EXPORT_C void RUsbPnClient::ConnectL()
    {
    OstTrace0( TRACE_BORDER, RUSBPNCLIENT_CONNECTL_ENTRY, "RUsbPnClient::ConnectL" );
    A_TRACE( ( _T( "RUsbPnClient::ConnectL()" ) ) );

    TInt err( KErrNone );

    // Create USB Phonet Link Server session
    err = CreateSession( KUsbPnServerName, TVersion(1,0,0));

    if ( err == KErrNotFound )
        {
        // Session not created

        // Find lock semaphore for server process creation
        TFindSemaphore lock( KUsbPnServerName );
        TFullName semaphoreName;
        err = lock.Next( semaphoreName );

        if ( err == KErrNotFound )
            {
            // Lock is not enabled
            OstTrace0( TRACE_INTERNALS, RUSBPNCLIENT_CONNECTL, "RUsbPnClient::ConnectL() - semaphore not found, start server" );
            E_TRACE( ( _L( "RUsbPnClient::ConnectL() - semaphore not found, start server" ) ) );

            RSemaphore startLock;

            // Create lock
            User::LeaveIfError( startLock.CreateGlobal( KUsbPnServerName, 0, EOwnerProcess ) );


            /********************************************/
            /* Start the USB Phonet Link process process */
            TRequestStatus status;
            RProcess server;

            User::LeaveIfError( server.Create( KUsbPnServerName, TPtrC( NULL, 0),
                         EOwnerThread ) );

            server.Rendezvous( status );

            if( status != KRequestPending )
              {
              server.Kill(0);  // Abort startup
              }
            else
              {
              server.Resume();  // Logon OK -> start the server
              }

            OstTrace0( TRACE_INTERNALS, RUSBPNCLIENT_CONNECTL_DUP1, "RUsbPnClient::ConnectL() - waiting server response" );
            E_TRACE( ( _T( "RUsbPnClient::ConnectL() - waiting server response" ) ) );
            User::WaitForRequest( status );  // Wait for start or death

            // we can't use the 'exit reason' if the server panicked as this
            // is the panic 'reason' and may be '0' which cannot be distinguished
            // from KErrNone
            TInt err = status.Int();
            if (err == KErrNone && (server.ExitType() == EExitPanic || server.ExitType() == EExitKill))
              {
              err = KErrServerTerminated;
              }

            server.Close();

            if( err )
                {
                OstTrace1( TRACE_INTERNALS, RUSBPNCLIENT_CONNECTL_DUP2, "RUsbPnClient::ConnectL() - waiting server response status; err=%d", err );
                E_TRACE( ( _T( "RUsbPnClient::ConnectL() - waiting server response status: %d" ), err ) );
                TRACE_ASSERT_ALWAYS;
                User::LeaveIfError( err );
                }
            /* End of starting process */
            /********************************************/

            OstTrace0( TRACE_INTERNALS, RUSBPNCLIENT_CONNECTL_DUP3, "RUsbPnClient::ConnectL() - server is started, signal other clients" );
            E_TRACE( ( _L( "RUsbPnClient::ConnectL() - server is started, signal other clients" ) ) );
            // Signal other clients
            startLock.Signal( KMaxTInt );

            // Close semaphore
            startLock.Close();
            }
        else
            {
            // Lock is enabled

            RSemaphore startLock;

            // Open lock semaphore
            User::LeaveIfError( startLock.Open( lock ) );

            OstTrace0( TRACE_INTERNALS, RUSBPNCLIENT_CONNECTL_DUP4, "RUsbPnClient::ConnectL() - server is starting, wait for signal" );
            E_TRACE( ( _L( "RUsbPnClient::ConnectL() - server is starting, wait for signal" ) ) );
            // Wait for signal
            startLock.Wait();
            OstTrace0( TRACE_INTERNALS, RUSBPNCLIENT_CONNECTL_DUP5, "RUsbPnClient::ConnectL() - signal received" );
            E_TRACE( ( _L( "RUsbPnClient::ConnectL() - signal received" ) ) );

            // Close semaphore
            startLock.Close();

            }

        // Create USB Phonet Link server session
        OstTrace0( TRACE_INTERNALS, RUSBPNCLIENT_CONNECTL_DUP6, "RUsbPnClient::ConnectL() - Create session" );
        E_TRACE( ( _L( "RUsbPnClient::ConnectL() - Create session" ) ) );

        User::LeaveIfError( CreateSession( KUsbPnServerName, TVersion(1,0,0) ) );

        OstTrace0( TRACE_INTERNALS, RUSBPNCLIENT_CONNECTL_DUP7, "RUsbPnClient::ConnectL() - session created1" );
        E_TRACE( ( _L( "RUsbPnClient::ConnectL() - session created1" ) ) );
        }
    else if ( err )
        {
        OstTrace0( TRACE_INTERNALS, RUSBPNCLIENT_CONNECTL_DUP8, "RUsbPnClient::ConnectL() - session not created, reason uknown" );
        E_TRACE( ( _L( "RUsbPnClient::ConnectL() - session not created, reason uknown" ) ) );            
        TRACE_ASSERT_ALWAYS;
        User::Leave( err );
        }
    else
        {
        OstTrace0( TRACE_INTERNALS, RUSBPNCLIENT_CONNECTL_DUP9, "RUsbPnClient::ConnectL() - session created2" );
        E_TRACE( ( _T( "RUsbPnClient::ConnectL() - session created2" ) ) );
        }
    OstTrace0( TRACE_BORDER, RUSBPNCLIENT_CONNECTL_EXIT, "RUsbPnClient::ConnectL() - return void" );
    A_TRACE( ( _T( "RUsbPnClient::ConnectL() - return void" ) ) );
    }
예제 #12
0
void CRemoteChild::Kill()
	{
	iChild.Kill(KErrCancel);
	}
TVerdict CAppFwkStartSafeTestStepAppStartRvError::doTestStepL()
	{
	TInt threadHandles_Before;
	TInt processHandles_Before;
	TInt threadHandles_After;
	TInt processHandles_After;
		
	RThread().HandleCount(processHandles_Before, threadHandles_Before);
	
	CStartSafe *startSafe = CStartSafe::NewL();	
	CleanupStack::PushL( startSafe );
	
	CStartupProperties *prop = CStartupProperties::NewL();
	CleanupStack::PushL( prop );
	
	RProcess proc;
	CleanupClosePushL( proc );
	
	prop->SetFileParamsL( KTestAppRvError, KNullDesC );
	prop->SetStartupType( EStartApp );
	prop->SetStartMethod( EWaitForStart );
	prop->SetNoOfRetries( KStartSafeAppStartRvErrorRetries );
	prop->SetTimeout( KStartSafeAppStartErrorNominalTimeout ); 

	TInt tried = 0;
	
	INFO_PRINTF1( _L("Start the Test Application") );
	TRAPD( err, startSafe->StartL(*prop, proc, tried) );

	// Ensure that the process-name of the test-app is not extant.
	TPtrC procNamePtr = proc.FileName().Right( KTestAppRvError().Length() );
	TInt nameComparison = procNamePtr.Compare( KTestAppRvError() );
		
	if ( (0 == nameComparison) )
		{
		ERR_PRINTF2( _L("Application whose process-name is\"%S\" was found, but should not have been"), &procNamePtr );
		
		// Dispose of the erroneously extant test-app.
		proc.Kill( KErrNone );
		SetTestStepResult( EFail );
		
		ERR_PRINTF1( _L("Test failed") );
		}
	else if( (KStartSafeAppStartRvErrorRetries +1) != tried )
		{
		ERR_PRINTF1( _L("Process-name (correctly) not found, but...") );
		ERR_PRINTF3( _L("Total tries = %d  should have been %d"), tried, (KStartSafeAppStartRvErrorRetries +1) );	
		
		SetTestStepResult( EFail );
		}
	else
		{
		INFO_PRINTF1( _L("Process was (correctly) not found") );
		INFO_PRINTF2( _L("Error code %d"), err );
		
		// The 'erroneous' rendezvous code
		TESTE( KErrGeneral, err );		
		}	


	CleanupStack::PopAndDestroy( 3, startSafe ); 
	
	RThread().HandleCount(processHandles_After, threadHandles_After);
	TEST(processHandles_After == processHandles_Before);
	TEST(threadHandles_After == threadHandles_Before);
	
	return TestStepResult();	
	}
EXPORT_C int pthread_getschedparam(pthread_t thr, int *policy,
                                   struct sched_param *param)
{
    _global_data_t *glbPtr;
    _pthread_node_t *tempPtr;
    _pthread_node_t *selfNodePtr;
    _pthread_node_t *thHandle;
        
    THR_PRINTF("[pthread] Begin pthread_getschedparam\n");
    
    //Get the TLS value (self node pointer)
    selfNodePtr = (_pthread_node_t*) _pthread_getTls();
	//coverity[var_compare_op]
    if (NULL == selfNodePtr)
    {
        THR_PRINTF("[pthread] FATAL :TLS is not initialized \n");
        THR_PRINTF("[pthread] Terminating the process\n");
        RProcess rp;
        rp.Kill(0);                // Terminate the process
    }
    
    thHandle = (_pthread_node_t *)thr;
    if (selfNodePtr == thHandle) // Self thread
    {
        glbPtr = selfNodePtr->glbDataPtr;  // point to global struct
        glbPtr->lockThreadTable.Wait();    // Acquire the thread table lock
        selfNodePtr->lockNode.Wait();
        
        param->sched_priority = selfNodePtr->priority;
        *policy = SCHED_RR;

        selfNodePtr->lockNode.Signal();
        glbPtr->lockThreadTable.Signal(); // Release thread table lock        

        THR_PRINTF("[pthread] End of pthread_getschedparam\n");
        return 0;
    }
	//coverity[var_deref_op]
    glbPtr = selfNodePtr->glbDataPtr;  // point to global struct
    
    glbPtr->lockThreadTable.Wait();    // Acquire the thread table lock
    
    // Traverse through the list, till destination node is reached
    for (tempPtr = glbPtr->start; 
         ((tempPtr != thHandle) && (tempPtr != NULL)); 
         tempPtr = tempPtr->next)
    {
        ;             //Empty loop 
    }
    
    if (NULL == tempPtr)              // Not found; 
    {
        THR_PRINTF("[pthread] End of pthread_getschedparam");
        glbPtr->lockThreadTable.Signal();  //release global lock
        return ESRCH;
    }
    
    thHandle->lockNode.Wait(); // Acquire the node lock 
                              
    param->sched_priority = thHandle->priority;
    *policy = SCHED_RR;    
    
    thHandle->lockNode.Signal();
    glbPtr->lockThreadTable.Signal();  // release thread table lock

    THR_PRINTF("[pthread] End pthread_getschedparam\n");
    
    return 0;
}