os/kernelhwsrv/userlibandfileserver/fileserver/sfile/sf_ldr.cpp
changeset 0 bde4ae8d615e
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/os/kernelhwsrv/userlibandfileserver/fileserver/sfile/sf_ldr.cpp	Fri Jun 15 03:10:57 2012 +0200
     1.3 @@ -0,0 +1,2297 @@
     1.4 +// Copyright (c) 1995-2009 Nokia Corporation and/or its subsidiary(-ies).
     1.5 +// All rights reserved.
     1.6 +// This component and the accompanying materials are made available
     1.7 +// under the terms of the License "Eclipse Public License v1.0"
     1.8 +// which accompanies this distribution, and is available
     1.9 +// at the URL "http://www.eclipse.org/legal/epl-v10.html".
    1.10 +//
    1.11 +// Initial Contributors:
    1.12 +// Nokia Corporation - initial contribution.
    1.13 +//
    1.14 +// Contributors:
    1.15 +//
    1.16 +// Description:
    1.17 +// f32\sfile\sf_ldr.cpp
    1.18 +// 
    1.19 +//
    1.20 +
    1.21 +#include "sf_std.h"
    1.22 +#include <f32image.h>
    1.23 +#include "sf_image.h"
    1.24 +#include "sf_cache.h"
    1.25 +#include "sf_ldr.h"
    1.26 +#include <e32uid.h>
    1.27 +#include <hal.h>
    1.28 +
    1.29 +
    1.30 +#ifdef _DEBUG
    1.31 +#define IF_DEBUG(x)	x
    1.32 +TInt KernHeapFailCount=0;
    1.33 +TInt LdrHeapFailCount=0;
    1.34 +TInt HeapFailActive=0;
    1.35 +void SetupHeapFail(const RMessage2& aMsg);
    1.36 +void EndHeapFailCheck(TInt);
    1.37 +TInt RFsFailCount=0;
    1.38 +TInt RFsErrorCode=0;
    1.39 +TBool RFsFailActive=0;
    1.40 +void SetupRFsFail(const RMessage2& aMsg);
    1.41 +void EndRFsFailCheck(TInt);
    1.42 +TRequestStatus ProcessDestructStat;
    1.43 +TRequestStatus* ProcessDestructStatPtr=0;
    1.44 +TBool ProcessCreated=EFalse;
    1.45 +#else
    1.46 +#define IF_DEBUG(x)
    1.47 +#endif
    1.48 +TInt DoLoaderDebugFunction(const RMessage2& aMsg);
    1.49 +
    1.50 +
    1.51 +//#define __TRACE_LOADER_HEAP__
    1.52 +
    1.53 +class RLoaderFs : public RFs
    1.54 +	{
    1.55 +public:
    1.56 +	inline TInt SendReceive(TInt aFunction, const TIpcArgs& aArgs) const
    1.57 +		{ return RSessionBase::SendReceive(aFunction, aArgs); }
    1.58 +	};
    1.59 +
    1.60 +static TInt CheckLibraryHash(RLdrReq& aReq);
    1.61 +const TInt KPriorityVeryHigh=14641;
    1.62 +
    1.63 +GLDEF_D RFs gTheLoaderFs;
    1.64 +GLDEF_D TAny* gExeCodeSeg;
    1.65 +GLDEF_D TUint32 gExeAttr;
    1.66 +GLDEF_D TAny* gKernelCodeSeg;
    1.67 +GLDEF_D TUint32 gKernelAttr;
    1.68 +GLDEF_D SSecurityInfo gKernelSecInfo;
    1.69 +GLDEF_D TBool gExecutesInSupervisorMode;
    1.70 +GLDEF_D TAny* gFileServerCodeSeg;
    1.71 +GLDEF_D TUint32 gFileServerAttr;
    1.72 +GLDEF_D SSecurityInfo gFileServerSecInfo;
    1.73 +GLDEF_D CActiveReaper* gActiveReaper=NULL;
    1.74 +
    1.75 +CSlottedChunkAllocator gFileDataAllocator;
    1.76 +
    1.77 +
    1.78 +GLREF_D TCodePageUtils TheCodePage;
    1.79 +
    1.80 +
    1.81 +_LIT(KDriveSystemRoot, "?:\\");
    1.82 +_LIT(KLoaderThreadName, "LoaderThread");
    1.83 +_LIT8(KFileExtensionExe,".EXE");
    1.84 +_LIT8(KFileExtensionDll,".DLL");
    1.85 +_LIT8(KFileExtensionLdd,".LDD");
    1.86 +_LIT8(KFileExtensionPdd,".PDD");
    1.87 +_LIT8(KFileExtensionFsy,".FSY");
    1.88 +_LIT8(KFileExtensionFxt,".FXT");
    1.89 +_LIT8(KFileExtensionPxt,".PXT");
    1.90 +_LIT8(KFileExtensionPxy,".PXY");
    1.91 +_LIT(KPathDel,"?:\\sys\\del\\");
    1.92 +const TInt KPathDelLength = 11; 
    1.93 +const TInt KExtensionLength=4;
    1.94 +
    1.95 +#if defined(__EPOC32__) && defined(__X86__)
    1.96 +TInt UseFloppy;
    1.97 +#endif
    1.98 +
    1.99 +/******************************************************************************
   1.100 + * Loader top level stuff
   1.101 + ******************************************************************************/
   1.102 +
   1.103 +TUint32 GetCodeSegAttr(TAny* aCodeSeg, SSecurityInfo* aS, TUint32* aVer)
   1.104 +	{
   1.105 +	TCodeSegCreateInfo info;
   1.106 +	E32Loader::CodeSegInfo(aCodeSeg, info);
   1.107 +	if (aS)
   1.108 +		*aS = info.iS;
   1.109 +	if (aVer)
   1.110 +		*aVer = info.iModuleVersion;
   1.111 +	return info.iAttr;
   1.112 +	}
   1.113 +
   1.114 +#ifdef __EPOC32__
   1.115 +extern void InitExecuteInSupervisorMode();
   1.116 +#endif
   1.117 +
   1.118 +_LIT(KNullThreadName,"EKern*Null");
   1.119 +void GetKernelInfo()
   1.120 +	{
   1.121 +	TFindThread ft(KNullThreadName);
   1.122 +	TFullName fn;
   1.123 +	TInt r = ft.Next(fn);
   1.124 +	if (r==KErrNone)
   1.125 +		{
   1.126 +		RThread null;
   1.127 +		r = null.Open(ft);
   1.128 +		if (r==KErrNone)
   1.129 +			{
   1.130 +			gKernelCodeSeg = E32Loader::ThreadProcessCodeSeg(null.Handle());
   1.131 +			if (gKernelCodeSeg)
   1.132 +				{
   1.133 +				gKernelAttr = GetCodeSegAttr(gKernelCodeSeg, &gKernelSecInfo, NULL);
   1.134 +				__IF_DEBUG(Printf("gKernelCodeSeg=%08x", gKernelCodeSeg));
   1.135 +				__IF_DEBUG(Printf("gKernelAttr=%08x", gKernelAttr));
   1.136 +				}
   1.137 +			else
   1.138 +				r=KErrGeneral;
   1.139 +			null.Close();
   1.140 +			}
   1.141 +		}
   1.142 +	if (r==KErrNone)
   1.143 +		{
   1.144 +		gFileServerCodeSeg = E32Loader::ThreadProcessCodeSeg(KCurrentThreadHandle);
   1.145 +		if (gFileServerCodeSeg)
   1.146 +			{
   1.147 +			gFileServerAttr = GetCodeSegAttr(gFileServerCodeSeg, &gFileServerSecInfo, NULL);
   1.148 +			__IF_DEBUG(Printf("gFileServerCodeSeg=%08x", gFileServerCodeSeg));
   1.149 +			__IF_DEBUG(Printf("gFileServerAttr=%08x", gFileServerAttr));
   1.150 +			}
   1.151 +		else
   1.152 +			r=KErrGeneral;
   1.153 +		}
   1.154 +
   1.155 +#ifdef __EPOC32__
   1.156 +	InitExecuteInSupervisorMode();
   1.157 +#else
   1.158 +	// When running on the emulator the loader can access all memory so effectively it is
   1.159 +	// running in supervisor mode.
   1.160 +	gExecutesInSupervisorMode = ETrue;
   1.161 +#endif
   1.162 +
   1.163 +	__ASSERT_ALWAYS(r==KErrNone, Fault(ELdrGetKernelInfoFailed));
   1.164 +	}
   1.165 +
   1.166 +
   1.167 +#ifdef __TRACE_LOADER_HEAP__
   1.168 +void InstallHeapTracer();
   1.169 +#endif
   1.170 +
   1.171 +
   1.172 +#ifdef __LAZY_DLL_UNLOAD
   1.173 +const TInt KLoaderLazyDllDurationDefault=120;      // 120 seconds default
   1.174 +TInt KLoaderLazyDllDuration=KLoaderLazyDllDurationDefault;
   1.175 +CLazyUnloadTimer* LazyUnloadTimer=NULL;
   1.176 +
   1.177 +void CLazyUnloadTimer::New()
   1.178 +//
   1.179 +// Create a new CLazyUnloadTimer.
   1.180 +//
   1.181 +	{
   1.182 +
   1.183 +	CLazyUnloadTimer* lazyUnloadTimer=new CLazyUnloadTimer;
   1.184 +	if(lazyUnloadTimer)
   1.185 +		{
   1.186 +		TRAPD(err,lazyUnloadTimer->ConstructL());
   1.187 +		if(err==KErrNone)
   1.188 +			{
   1.189 +			lazyUnloadTimer->Start();
   1.190 +			}
   1.191 +		else
   1.192 +			{
   1.193 +			delete lazyUnloadTimer;
   1.194 +			}
   1.195 +		}
   1.196 +	}
   1.197 +
   1.198 +CLazyUnloadTimer::CLazyUnloadTimer()
   1.199 +//
   1.200 +// Constructor
   1.201 +//
   1.202 +	: CTimer(EPriorityIdle)
   1.203 +	{
   1.204 +	Finish();
   1.205 +	LazyUnloadTimer = this;
   1.206 +	if (KLoaderLazyDllDuration < 0) 
   1.207 +		KLoaderLazyDllDuration = KLoaderLazyDllDurationDefault;
   1.208 +	}
   1.209 +
   1.210 +CLazyUnloadTimer::~CLazyUnloadTimer()
   1.211 +	{
   1.212 +	LazyUnloadTimer = NULL;
   1.213 +	}
   1.214 +
   1.215 +void CLazyUnloadTimer::Start()
   1.216 +	{
   1.217 +	E32Loader::CodeSegDeferDeletes();
   1.218 +	CActiveScheduler::Add(this);
   1.219 +	TTimeIntervalMicroSeconds32 timeout=KLoaderLazyDllDuration*1000000;
   1.220 +	After(timeout);
   1.221 +	}
   1.222 +
   1.223 +void CLazyUnloadTimer::RunL()
   1.224 +//
   1.225 +// The timer has completed.
   1.226 +//
   1.227 +	{
   1.228 +	E32Loader::CodeSegEndDeferDeletes();
   1.229 +	delete this;
   1.230 +	}
   1.231 +
   1.232 +void CLazyUnloadTimer::Finish()
   1.233 +	{
   1.234 +	if(LazyUnloadTimer)
   1.235 +		{
   1.236 +		LazyUnloadTimer->Cancel();
   1.237 +		LazyUnloadTimer->RunL();
   1.238 +		}
   1.239 +	}
   1.240 +
   1.241 +#endif
   1.242 +
   1.243 +/* ReaperCleanupTimer - Used to clear /sys/del/ shortly after boot. */
   1.244 +
   1.245 +const TInt KLoaderReaperCleanupTimeDefault=60;      // 60 seconds default
   1.246 +TInt KLoaderReaperCleanupTime=KLoaderReaperCleanupTimeDefault;
   1.247 +CReaperCleanupTimer* CReaperCleanupTimer::Timer=NULL;
   1.248 +
   1.249 +TInt CReaperCleanupTimer::New()
   1.250 +//
   1.251 +// Create a new CReaperCleanupTimer.
   1.252 +//
   1.253 +	{
   1.254 +	if (Timer)
   1.255 +		return KErrInUse;
   1.256 +	
   1.257 +	CReaperCleanupTimer* timer=new CReaperCleanupTimer;
   1.258 +	if(timer)
   1.259 +		{
   1.260 +		TRAPD(err,Timer->ConstructL());
   1.261 +		if(err==KErrNone)
   1.262 +			{
   1.263 +			Timer->Start();
   1.264 +			return KErrNone;
   1.265 +			}
   1.266 +		else
   1.267 +			{
   1.268 +			delete Timer;
   1.269 +			return err;
   1.270 +			}
   1.271 +		}
   1.272 +	return KErrNoMemory;
   1.273 +	}
   1.274 +
   1.275 +CReaperCleanupTimer::CReaperCleanupTimer()
   1.276 +	: CTimer(EPriorityIdle)
   1.277 +	{
   1.278 +	Timer=this;
   1.279 +	}
   1.280 +	
   1.281 +CReaperCleanupTimer::~CReaperCleanupTimer()
   1.282 +	{
   1.283 +	Timer = NULL;
   1.284 +	}
   1.285 +
   1.286 +void CReaperCleanupTimer::Start()
   1.287 +	{
   1.288 +	CActiveScheduler::Add(this);
   1.289 +	TTimeIntervalMicroSeconds32 timeout=KLoaderReaperCleanupTime*1000000;
   1.290 +	After(timeout);
   1.291 +	}
   1.292 +
   1.293 +void CReaperCleanupTimer::RunL()
   1.294 +	{
   1.295 +	if (gActiveReaper)
   1.296 +		gActiveReaper->InitDelDir();
   1.297 +	delete this;
   1.298 +	}
   1.299 +	
   1.300 +void CReaperCleanupTimer::Complete()
   1.301 +	{
   1.302 +	if(Timer)
   1.303 +		{
   1.304 +		Timer->Cancel();
   1.305 +		Timer->RunL();
   1.306 +		}
   1.307 +	}	
   1.308 +
   1.309 +GLDEF_C TInt LoaderThread(TAny*)
   1.310 +//
   1.311 +// The loader thread.
   1.312 +//
   1.313 +	{
   1.314 +#ifdef __TRACE_LOADER_HEAP__
   1.315 +	InstallHeapTracer();
   1.316 +#endif
   1.317 +
   1.318 +	TInt r;
   1.319 +    __IF_DEBUG(Printf("LoaderThread"));
   1.320 +	User::SetCritical(User::ESystemCritical);
   1.321 +	GetKernelInfo();
   1.322 +
   1.323 +	CServerLoader* serverLoader;
   1.324 +	CActiveSchedulerLoader* scheduler;
   1.325 +
   1.326 +	CTrapCleanup* cleanup=CTrapCleanup::New();
   1.327 +	__ASSERT_ALWAYS(cleanup!=NULL, Fault(ELdrCleanupCreate));
   1.328 +	scheduler=CActiveSchedulerLoader::New();
   1.329 +	__ASSERT_ALWAYS(scheduler!=NULL, Fault(ELdrSchedulerCreate));
   1.330 +	serverLoader=CServerLoader::New();
   1.331 +	__ASSERT_ALWAYS(serverLoader!=NULL, Fault(ELdrServerCreate));
   1.332 +
   1.333 +	RThread::Rendezvous(KErrNone);
   1.334 +	r=gTheLoaderFs.Connect();
   1.335 +	__ASSERT_ALWAYS(r==KErrNone, Fault(ELdrFsConnect));
   1.336 +	TBuf<sizeof(KDriveSystemRoot)> driveSystemRoot(KDriveSystemRoot);
   1.337 +	driveSystemRoot[0] = (TUint8) RFs::GetSystemDriveChar();
   1.338 +	r=gTheLoaderFs.SetSessionPath(driveSystemRoot);
   1.339 +	__ASSERT_ALWAYS(r==KErrNone, Fault(ELdrFsSetPath));
   1.340 +
   1.341 +#ifdef __EPOC32__
   1.342 +	InitializeFileNameCache();
   1.343 +
   1.344 +	r=gFileDataAllocator.Construct();
   1.345 +	__ASSERT_ALWAYS(r==KErrNone, Fault(ELdrFileDataAllocInit));
   1.346 +#endif
   1.347 +
   1.348 +#ifdef __LAZY_DLL_UNLOAD
   1.349 +	CLazyUnloadTimer::New();
   1.350 +#endif
   1.351 +	
   1.352 +	gActiveReaper = CActiveReaper::New();
   1.353 +	__ASSERT_ALWAYS(gActiveReaper!=NULL, Fault(ELdrReaperCreate));
   1.354 +
   1.355 +	r=CReaperCleanupTimer::New();
   1.356 +	__ASSERT_ALWAYS(r==KErrNone, Fault(ELdrReaperCleanupTimerCreate));
   1.357 +	
   1.358 +	CActiveSchedulerLoader::Start();
   1.359 +	Fault(ELdrSchedulerStopped);
   1.360 +	return 0;
   1.361 +	}
   1.362 +
   1.363 +TInt InitLoader()
   1.364 +	{
   1.365 +
   1.366 +	TRequestStatus lts;
   1.367 +	RThread loaderThread; 
   1.368 +	RHeap* h = (RHeap*)&User::Allocator();
   1.369 +	TInt maxsize = h->MaxLength();	// loader heap max size = file server heap max size
   1.370 +	TInt r=loaderThread.Create(KLoaderThreadName,LoaderThread,KLoaderStackSize,KHeapMinSize,maxsize,NULL);
   1.371 +	if (r!=KErrNone)
   1.372 +		{
   1.373 +		return r;
   1.374 +		}
   1.375 +	loaderThread.Rendezvous(lts);
   1.376 +	loaderThread.Resume();
   1.377 +	User::WaitForRequest(lts);
   1.378 +	loaderThread.Close();
   1.379 +	return lts.Int();
   1.380 +	}
   1.381 +
   1.382 +TInt CompareVersions(TUint32 aL, TUint32 aR)
   1.383 +	{
   1.384 +	if (aL>aR)
   1.385 +		return 1;
   1.386 +	if (aL<aR)
   1.387 +		return -1;
   1.388 +	return 0;
   1.389 +	}
   1.390 +
   1.391 +TInt DetailedCompareVersions(TUint32 aCandidate, TUint32 aRequest)
   1.392 +	{
   1.393 +	if (aRequest == KModuleVersionNull)
   1.394 +		return EVersion_MinorBigger;
   1.395 +	if (aCandidate == KModuleVersionNull)
   1.396 +		return EVersion_MajorSmaller;
   1.397 +	TUint32 C = aCandidate >> 16;
   1.398 +	TUint32 c = aCandidate & 0x0000ffffu;
   1.399 +	TUint32 R = aRequest >> 16;
   1.400 +	TUint32 r = aRequest & 0x0000ffffu;
   1.401 +	if (C==R)
   1.402 +		{
   1.403 +		if (c>r)
   1.404 +			return EVersion_MinorBigger;
   1.405 +		if (c==r)
   1.406 +			return EVersion_Exact;
   1.407 +		return EVersion_MinorSmaller;
   1.408 +		}
   1.409 +	if (C>R)
   1.410 +		return EVersion_MajorBigger;
   1.411 +	return EVersion_MajorSmaller;
   1.412 +	}
   1.413 +
   1.414 +TInt DetailedCompareVersions(TUint32 aCandidate, TUint32 aRequest, TUint32 aCurrent, TBool aStrict)
   1.415 +	{
   1.416 +	TInt cvc = DetailedCompareVersions(aCandidate, aCurrent);
   1.417 +	if (aRequest == KModuleVersionWild)
   1.418 +		{
   1.419 +		return (cvc == EVersion_MinorBigger || cvc == EVersion_MajorBigger) ? EAction_Replace : EAction_Skip;
   1.420 +		}
   1.421 +	TInt candidate_state = DetailedCompareVersions(aCandidate, aRequest);
   1.422 +	if (aStrict)
   1.423 +		{
   1.424 +		if (candidate_state > EVersion_Exact)
   1.425 +			return EAction_Skip;	// no match
   1.426 +		if (cvc == EVersion_MinorBigger)
   1.427 +			return EAction_Replace;	// later minor version so take it
   1.428 +		return EAction_Skip;	// same or earlier minor version
   1.429 +		}
   1.430 +	TInt current_state = DetailedCompareVersions(aCurrent, aRequest);
   1.431 +	if (candidate_state < current_state)
   1.432 +		{
   1.433 +		// better match
   1.434 +		if (candidate_state <= EVersion_Exact)
   1.435 +			return EAction_Replace;
   1.436 +		return (candidate_state == EVersion_MajorBigger) ? EAction_CheckImports : EAction_CheckLastImport;
   1.437 +		}
   1.438 +	if (candidate_state > current_state)
   1.439 +		return EAction_Skip;	// worse match
   1.440 +	// match state same
   1.441 +	// skip if		(i) state=exact
   1.442 +	//				(ii) state=major smaller
   1.443 +	// replace if	(i) state=minor bigger and candidate minor > current minor
   1.444 +	//				(ii) state=minor smaller and candidate minor > current minor
   1.445 +	//				(iii) state=major bigger, candidate major=current major and candidate minor > current minor
   1.446 +	// check if		(i) state=major bigger and candidate major < current major
   1.447 +	switch (candidate_state)
   1.448 +		{
   1.449 +		case EVersion_MinorBigger:
   1.450 +		case EVersion_MinorSmaller:
   1.451 +			return (cvc == EVersion_MinorBigger) ? EAction_Replace : EAction_Skip;
   1.452 +		case EVersion_MajorBigger:
   1.453 +			if (cvc == EVersion_MinorBigger)
   1.454 +				return EAction_Replace;
   1.455 +			return (cvc == EVersion_MajorSmaller) ? EAction_CheckImports : EAction_Skip;
   1.456 +		default:
   1.457 +			return EAction_Skip;
   1.458 +		}
   1.459 +	}
   1.460 +
   1.461 +TFileNameInfo::TFileNameInfo()
   1.462 +	{
   1.463 +	memclr(this, sizeof(TFileNameInfo));
   1.464 +	}
   1.465 +
   1.466 +TInt TFileNameInfo::Set(const TDesC8& aFileName, TUint aFlags)
   1.467 +	{
   1.468 +	__IF_DEBUG(Printf(">TFileNameInfo::Set %S %08x", &aFileName, aFlags));
   1.469 +	iUid = 0;
   1.470 +	iVersion = 0;
   1.471 +	iPathPos = 0;
   1.472 +	iName = aFileName.Ptr();
   1.473 +	iLen = aFileName.Length();
   1.474 +	iExtPos = aFileName.LocateReverse('.');
   1.475 +	if (iExtPos<0)
   1.476 +		iExtPos = iLen;
   1.477 +	TInt osq = aFileName.LocateReverse('[');
   1.478 +	TInt csq = aFileName.LocateReverse(']');
   1.479 +	if (!(aFlags & EAllowUid) && (osq>=0 || csq>=0))
   1.480 +		{
   1.481 +		__IF_DEBUG(Printf("<TFileNameInfo::Set BadName1"));
   1.482 +		return KErrBadName;
   1.483 +		}
   1.484 +	if (osq>=iExtPos || csq>=iExtPos)
   1.485 +		{
   1.486 +		__IF_DEBUG(Printf("<TFileNameInfo::Set BadName2"));
   1.487 +		return KErrBadName;
   1.488 +		}
   1.489 +	TInt p = iExtPos;
   1.490 +	if ((aFlags & EAllowUid) && p>=10 && iName[p-1]==']' && iName[p-10]=='[')
   1.491 +		{
   1.492 +		TPtrC8 uidstr(iName + p - 9, 8);
   1.493 +		TLex8 uidlex(uidstr);
   1.494 +		TUint32 uid = 0;
   1.495 +		TInt r = uidlex.Val(uid, EHex);
   1.496 +		if (r==KErrNone && uidlex.Eos())
   1.497 +			iUid = uid, p -= 10;
   1.498 +		}
   1.499 +	iUidPos = p;
   1.500 +	TInt ob = aFileName.LocateReverse('{');
   1.501 +	TInt cb = aFileName.LocateReverse('}');
   1.502 +	if (ob>=iUidPos || cb>=iUidPos)
   1.503 +		{
   1.504 +		__IF_DEBUG(Printf("<TFileNameInfo::Set BadName3"));
   1.505 +		return KErrBadName;
   1.506 +		}
   1.507 +	if (ob>=0 && cb>=0 && p-1==cb)
   1.508 +		{
   1.509 +		TPtrC8 p8(iName, p);
   1.510 +		TInt d = p8.LocateReverse('.');
   1.511 +		TPtrC8 verstr(iName+ob+1, p-ob-2);
   1.512 +		TLex8 verlex(verstr);
   1.513 +		if (ob==p-10 && d<ob)
   1.514 +			{
   1.515 +			TUint32 ver = 0;
   1.516 +			TInt r = verlex.Val(ver, EHex);
   1.517 +			if (r==KErrNone && verlex.Eos())
   1.518 +				iVersion = ver, p = ob;
   1.519 +			}
   1.520 +		else if (d>ob && p-1>d && (aFlags & EAllowDecimalVersion))
   1.521 +			{
   1.522 +			TUint32 maj = 0;
   1.523 +			TUint32 min = 0;
   1.524 +			TInt r = verlex.Val(maj, EDecimal);
   1.525 +			TUint c = (TUint)verlex.Get();
   1.526 +			TInt r2 = verlex.Val(min, EDecimal);
   1.527 +			if (r==KErrNone && c=='.' && r2==KErrNone && verlex.Eos() && maj<32768 && min<32768)
   1.528 +				iVersion = (maj << 16) | min, p = ob;
   1.529 +			}
   1.530 +		}
   1.531 +	iVerPos = p;
   1.532 +	if (iLen>=2 && iName[1]==':')
   1.533 +		{
   1.534 +		TUint c = iName[0];
   1.535 +		if (c!='?' || !(aFlags & EAllowPlaceholder))
   1.536 +			{
   1.537 +			c |= 0x20;
   1.538 +			if (c<'a' || c>'z')
   1.539 +				{
   1.540 +				__IF_DEBUG(Printf("<TFileNameInfo::Set BadName4"));
   1.541 +				return KErrBadName;
   1.542 +				}
   1.543 +			}
   1.544 +		iPathPos = 2;
   1.545 +		}
   1.546 +	TPtrC8 pathp(iName+iPathPos, iVerPos-iPathPos);
   1.547 +	if (pathp.Locate('[')>=0 || pathp.Locate(']')>=0 || pathp.Locate('{')>=0 || pathp.Locate('}')>=0 || pathp.Locate(':')>=0)
   1.548 +		{
   1.549 +		__IF_DEBUG(Printf("<TFileNameInfo::Set BadName5"));
   1.550 +		return KErrBadName;
   1.551 +		}
   1.552 +	iBasePos = pathp.LocateReverse('\\') + 1 + iPathPos;
   1.553 +	__IF_DEBUG(Printf("<TFileNameInfo::Set OK"));
   1.554 +	__LDRTRACE(Dump());
   1.555 +	return KErrNone;
   1.556 +	}
   1.557 +
   1.558 +void TFileNameInfo::GetName(TDes8& aName, TUint aFlags) const
   1.559 +	{
   1.560 +	if (aFlags & EIncludeDrive)
   1.561 +		aName.Append(Drive());
   1.562 +	if (aFlags & EIncludePath)
   1.563 +		{
   1.564 +		if (PathLen() && iName[iPathPos]!='\\')
   1.565 +			aName.Append('\\');
   1.566 +		aName.Append(Path());
   1.567 +		}
   1.568 +	if (aFlags & EIncludeBase)
   1.569 +		aName.Append(Base());
   1.570 +	if ((aFlags & EForceVer) || ((aFlags & EIncludeVer) && VerLen()) )
   1.571 +		{
   1.572 +		aName.Append('{');
   1.573 +		aName.AppendNumFixedWidth(iVersion, EHex, 8);
   1.574 +		aName.Append('}');		
   1.575 +		}
   1.576 +	if ((aFlags & EForceUid) || ((aFlags & EIncludeUid) && UidLen()) )
   1.577 +		{
   1.578 +		aName.Append('[');
   1.579 +		aName.AppendNumFixedWidth(iUid, EHex, 8);
   1.580 +		aName.Append(']');
   1.581 +		}
   1.582 +	if (aFlags & EIncludeExt)
   1.583 +		aName.Append(Ext());
   1.584 +	}
   1.585 +
   1.586 +TInt OpenFile8(RFile& aFile, const TDesC8& aName)
   1.587 +	{
   1.588 +	TFileName fn;
   1.589 +	fn.Copy(aName);
   1.590 +	TInt r = aFile.Open(gTheLoaderFs, fn, EFileStream|EFileRead|EFileShareReadersOnly|EFileReadDirectIO);
   1.591 +	return r;
   1.592 +	}
   1.593 +
   1.594 +RLdrReq::RLdrReq()
   1.595 +	{
   1.596 +	memclr(&iFileName, sizeof(RLdrReq) - sizeof(TLdrInfo));
   1.597 +	}
   1.598 +
   1.599 +void RLdrReq::Close()
   1.600 +	{
   1.601 +	delete iFileName;
   1.602 +	delete iCmd;
   1.603 +	delete iPath;
   1.604 +	iClientThread.Close();
   1.605 +	iClientProcess.Close();
   1.606 +	}
   1.607 +
   1.608 +void RLdrReq::Panic(TInt aPanic)
   1.609 +	{
   1.610 +	iMsg->Panic(KLitLoader,aPanic);
   1.611 +	}
   1.612 +
   1.613 +TInt CheckedCollapse(TDes8& aDest, const TDesC16& aSrc)
   1.614 +	{
   1.615 +	TInt rl = aSrc.Length();
   1.616 +	aDest.SetLength(rl);
   1.617 +	TText8* d = (TText8*)aDest.Ptr();
   1.618 +	const TText16* s = aSrc.Ptr();
   1.619 +	const TText16* sE = s + rl;
   1.620 +	while (s<sE && *s>=0x20u && *s<0x7fu)
   1.621 +		*d++ = (TText8)*s++;
   1.622 +	return (s<sE) ? KErrBadName : KErrNone;
   1.623 +	}
   1.624 +
   1.625 +TInt RLoaderMsg::GetString(HBufC8*& aBuf, TInt aParam, TInt aMaxLen, TInt aHeadroom, TBool aReduce) const
   1.626 +	{
   1.627 +	aBuf=NULL;
   1.628 +	TInt l=GetDesLength(aParam);
   1.629 +	if (l<0)
   1.630 +		return l;
   1.631 +	if (l>aMaxLen)
   1.632 +		return KErrOverflow;
   1.633 +	aBuf=HBufC8::New((l+aHeadroom)*sizeof(TText));
   1.634 +	if (!aBuf)
   1.635 +		return KErrNoMemory;
   1.636 +	TPtr8 bp8(aBuf->Des());
   1.637 +	TPtr16 bp16((TText*)bp8.Ptr(), 0, bp8.MaxLength()/sizeof(TText));
   1.638 +	TInt r = Read(aParam, bp16);
   1.639 +	if (r == KErrNone)
   1.640 +		{
   1.641 +		TInt rl = bp16.Length();
   1.642 +		if (aReduce)
   1.643 +			r = CheckedCollapse(bp8, bp16);
   1.644 +		else
   1.645 +			bp8.SetLength(rl*sizeof(TText));
   1.646 +		}
   1.647 +	if (r!=KErrNone)
   1.648 +		{
   1.649 +		delete aBuf;
   1.650 +		aBuf=NULL;
   1.651 +		}
   1.652 +	return r;
   1.653 +	}
   1.654 +
   1.655 +TInt RLoaderMsg::GetLdrInfo(TLdrInfo& aInfo) const
   1.656 +	{
   1.657 +	TPckg<TLdrInfo> infoPckg(aInfo);
   1.658 +	return Read(0, infoPckg);
   1.659 +	}
   1.660 +
   1.661 +TInt RLoaderMsg::UpdateLdrInfo(const TLdrInfo& aInfo) const
   1.662 +	{
   1.663 +	TPckgC<TLdrInfo> infoPckg(aInfo);
   1.664 +	return Write(0, infoPckg);
   1.665 +	}
   1.666 +
   1.667 +TInt RLdrReq::AddFileExtension(const TDesC8& aExt)
   1.668 +	{
   1.669 +	if (iFileName->LocateReverse('.')==KErrNotFound)
   1.670 +		{
   1.671 +		if (iFileName->Length()+aExt.Length()>KMaxFileName)
   1.672 +			return KErrBadName;
   1.673 +		iFileName->Des().Append(aExt);
   1.674 +		}
   1.675 +	TInt r = iFileNameInfo.Set(*iFileName, TFileNameInfo::EAllowDecimalVersion);
   1.676 +	if (r == KErrNone)
   1.677 +		{
   1.678 +		TInt l = iFileNameInfo.BaseLen() + iFileNameInfo.ExtLen();
   1.679 +		if (l > KMaxProcessName)
   1.680 +			r = KErrBadName;
   1.681 +		}
   1.682 +	return r;
   1.683 +	}
   1.684 +
   1.685 +TInt CheckSubstDrive(TDes8& aDest, const TDesC8& aSrc, TBool aIsPathOnly)
   1.686 +	{
   1.687 +	TInt r = KErrNone;
   1.688 +	TInt l = aSrc.Length();
   1.689 +	TInt mdl = aDest.MaxLength();
   1.690 +	TInt pathStart = 0;
   1.691 +	if (l>=3 && aSrc[1]==':')
   1.692 +		{
   1.693 +		// drive letter specified...
   1.694 +		pathStart = 2;
   1.695 +		TInt drive;
   1.696 +		TDriveInfo dI;
   1.697 +		r = RFs::CharToDrive((TChar)aSrc[0], drive);
   1.698 +		if (r!=KErrNone)
   1.699 +			{
   1.700 +			return r;
   1.701 +			}
   1.702 +		r = gTheLoaderFs.Drive(dI, drive);
   1.703 +		if (r!=KErrNone)
   1.704 +			{
   1.705 +			return r;
   1.706 +			}
   1.707 +		if (dI.iDriveAtt & KDriveAttSubsted)
   1.708 +			{
   1.709 +			TPtr16 ptr16(aDest.Expand());
   1.710 +			r = gTheLoaderFs.Subst(ptr16, drive);
   1.711 +			if (r!=KErrNone)
   1.712 +				{
   1.713 +				return r;
   1.714 +				}
   1.715 +			aDest.SetLength(ptr16.Length()*sizeof(TText));
   1.716 +			aDest.Collapse();
   1.717 +			TInt srcm = (aSrc[2]=='\\') ? 3 : 2;
   1.718 +			TPtrC8 rest(aSrc.Mid(srcm));
   1.719 +			if (rest.Length() + aDest.Length() > mdl)
   1.720 +				return KErrBadName;
   1.721 +			aDest.Append(rest);
   1.722 +			r=1;
   1.723 +			}
   1.724 +		}
   1.725 +
   1.726 +	if(!PlatSec::ConfigSetting(PlatSec::EPlatSecEnforceSysBin))
   1.727 +		return r;
   1.728 +
   1.729 +	// make sure path starts with "\sys\bin\"...
   1.730 +
   1.731 +	// get filename/path...
   1.732 +	TPtrC8 ptr;
   1.733 +	if(!r)
   1.734 +		ptr.Set(aSrc);
   1.735 +	else
   1.736 +		ptr.Set(aDest);
   1.737 +
   1.738 +	// set pathStart to first character of path (after any initial '\')
   1.739 +	if(ptr.Length() && ptr[pathStart]=='\\')
   1.740 +		++pathStart; // drop initial '\'
   1.741 +
   1.742 +	// set pathEnd to first character after path (the final '\' if present)
   1.743 +	TInt pathEnd;
   1.744 +	if(aIsPathOnly)
   1.745 +		{
   1.746 +		pathEnd = ptr.Length();
   1.747 +		if(pathEnd && ptr[pathEnd-1]==';')
   1.748 +			--pathEnd; // drop trailing ';'
   1.749 +		if(pathEnd && ptr[pathEnd-1]=='\\')
   1.750 +			--pathEnd; // drop trailing '\'
   1.751 +		}
   1.752 +	else
   1.753 +		{
   1.754 +		pathEnd = ptr.LocateReverse('\\');
   1.755 +		if(pathEnd<0)
   1.756 +			return r;	// no path, so end
   1.757 +		}
   1.758 +
   1.759 +	// check if path starts with "sys\bin"...
   1.760 +	const TUint8* fn = ptr.Ptr();
   1.761 +	_LIT8(KSysBin,"sys\\bin");
   1.762 +	const TInt KSysBinLength = 7;
   1.763 +	if(pathStart+KSysBinLength <= pathEnd)
   1.764 +		if(KSysBin().CompareF(TPtrC8(fn+pathStart,KSysBinLength))==0)
   1.765 +			return r;	// path already starts with "sys\bin", so end
   1.766 +
   1.767 +	// replace path with "sys\bin"...
   1.768 +	TBuf8<KMaxFileName*sizeof(TText)> temp;
   1.769 +	temp.Append(TPtrC8(fn,pathStart));		// add bits before path
   1.770 +	temp.Append(KSysBin);					// add "sys\bin"
   1.771 +	TInt rootLen = ptr.Length()-pathEnd;
   1.772 +	if(temp.Length()+rootLen>temp.MaxLength())
   1.773 +		return KErrBadName;	// would overflow
   1.774 +	temp.Append(TPtrC8(fn+pathEnd,rootLen));	// add bits after path
   1.775 +
   1.776 +	// return modified string...
   1.777 +	aDest = temp;
   1.778 +	return 1;
   1.779 +	}
   1.780 +
   1.781 +
   1.782 +TInt RLdrReq::CheckForSubstDriveInName()
   1.783 +	{
   1.784 +	TBuf8<KMaxFileName*sizeof(TText)> temp;
   1.785 +	TInt r = CheckSubstDrive(temp, *iFileName, EFalse);
   1.786 +	if (r<0)
   1.787 +		{
   1.788 +		return r;
   1.789 +		}
   1.790 +	if (r>0)
   1.791 +		{
   1.792 +		TInt l=temp.Length();
   1.793 +		HBufC8* p = HBufC8::New(l+KExtensionLength);
   1.794 +		if (!p)
   1.795 +			return KErrNoMemory;
   1.796 +		TPtr8 bp8(p->Des());
   1.797 +		bp8 = temp;		
   1.798 +		delete iFileName;
   1.799 +		iFileName = p;
   1.800 +		r = KErrNone;
   1.801 +		}
   1.802 +	return r;
   1.803 +	}
   1.804 +
   1.805 +
   1.806 +TInt RLdrReq::CheckForSubstDrivesInPath()
   1.807 +	{
   1.808 +	if (!iPath)
   1.809 +		return KErrNone;
   1.810 +	TBuf8<(KMaxFileName+1)*sizeof(TText)> temp;
   1.811 +	TInt ppos = 0;
   1.812 +	TInt plen = iPath->Length();
   1.813 +	HBufC8* newpath = NULL;
   1.814 +	while (ppos < plen)
   1.815 +		{
   1.816 +		TPtrC8 rmn(iPath->Mid(ppos));
   1.817 +		TInt term = rmn.Locate(';');
   1.818 +		TInt pel = (term<0) ? rmn.Length() : term+1;
   1.819 +		TPtrC8 path_element(iPath->Mid(ppos, pel));
   1.820 +		ppos += pel;
   1.821 +		temp.Zero();
   1.822 +		TInt r = CheckSubstDrive(temp, path_element, ETrue);
   1.823 +		if (r<0)
   1.824 +			{
   1.825 +			delete newpath;
   1.826 +			return r;
   1.827 +			}
   1.828 +		else if (r>0 || newpath)
   1.829 +			{
   1.830 +			if(!newpath)
   1.831 +				{
   1.832 +				// initialise 'newpath' to contain everything in path before the element just processed...
   1.833 +				newpath = iPath->Left(ppos-pel).Alloc();
   1.834 +				if(!newpath)
   1.835 +					return KErrNoMemory;
   1.836 +				}
   1.837 +			// grow 'newpath'...
   1.838 +			TInt xl = (r>0) ? temp.Length() : pel;
   1.839 +			HBufC8* np = newpath->ReAlloc(newpath->Length() + xl);
   1.840 +			if(!np)
   1.841 +				{
   1.842 +				delete newpath;
   1.843 +				return KErrNoMemory;
   1.844 +				}
   1.845 +			newpath = np;
   1.846 +			// append modified path element to the 'newpath'...
   1.847 +			newpath->Des().Append( (r>0) ? (const TDesC8&)temp : (const TDesC8&)path_element);
   1.848 +			}
   1.849 +		}
   1.850 +	if(newpath)
   1.851 +		{
   1.852 +		delete iPath;
   1.853 +		iPath = newpath;
   1.854 +		}
   1.855 +	return KErrNone;
   1.856 +	}
   1.857 +
   1.858 +#ifdef __VC32__
   1.859 +#pragma warning( disable : 4701 )   // disable warning C4701: local variable 'missingCaps' may be used without having been initialized
   1.860 +#endif
   1.861 +
   1.862 +TInt RLdrReq::CheckSecInfo(const SSecurityInfo& aCandidate) const
   1.863 +//
   1.864 +//	Check that the security info of a candidate loadee is sufficient
   1.865 +//
   1.866 +	{
   1.867 +	if (iSecureId && iSecureId != aCandidate.iSecureId)
   1.868 +		return KErrPermissionDenied;
   1.869 +
   1.870 +	SCapabilitySet missingCaps;
   1.871 +	TUint32 checkFail = 0;
   1.872 +	for (TInt i=0; i<SCapabilitySet::ENCapW; ++i)
   1.873 +		{
   1.874 +		TUint32 missing = iPlatSecCaps[i] & ~aCandidate.iCaps[i];
   1.875 +		missingCaps[i] = missing;
   1.876 +		checkFail |= missing;
   1.877 +		}
   1.878 +	if(!checkFail)
   1.879 +		return KErrNone;
   1.880 +	// Failed check...
   1.881 +	if(iImporter)
   1.882 +		{
   1.883 +#ifndef __REMOVE_PLATSEC_DIAGNOSTICS__
   1.884 +		return PlatSec::LoaderCapabilityViolation(iImporter->iFileName,*iFileName,missingCaps);
   1.885 +#else //__REMOVE_PLATSEC_DIAGNOSTICS__
   1.886 +		return PlatSec::EmitDiagnostic();
   1.887 +#endif //!__REMOVE_PLATSEC_DIAGNOSTICS__
   1.888 +		}
   1.889 +
   1.890 +#ifndef __REMOVE_PLATSEC_DIAGNOSTICS__
   1.891 +	return PlatSec::LoaderCapabilityViolation(iClientProcess,*iFileName,missingCaps);
   1.892 +#else //__REMOVE_PLATSEC_DIAGNOSTICS__
   1.893 +	return PlatSec::EmitDiagnostic();
   1.894 +#endif //!__REMOVE_PLATSEC_DIAGNOSTICS__
   1.895 +	}
   1.896 +
   1.897 +#ifdef __VC32__
   1.898 +#pragma warning( default : 4701 )   // enable warning C4701: local variable 'missingCaps' may be used without having been initialized
   1.899 +#endif
   1.900 +
   1.901 +void CSessionLoader::ServiceL(const RMessage2& aMessage)
   1.902 +//
   1.903 +// Handle messages for this server.
   1.904 +//
   1.905 +	{
   1.906 +	const RLoaderMsg& msg = (const RLoaderMsg&)aMessage;
   1.907 +	TLoaderMsg mid=(TLoaderMsg)msg.Function();
   1.908 +	__IF_DEBUG(Printf("Loader: RX msg %d", mid));
   1.909 +	if (mid<1 || mid>=EMaxLoaderMsg)
   1.910 +		{
   1.911 +		aMessage.Complete(KErrNotSupported);
   1.912 +		return;
   1.913 +		}
   1.914 +#ifdef __EPOC32__
   1.915 +#ifdef __X86__
   1.916 +	UseFloppy = -1;
   1.917 +#endif
   1.918 +	TInt r=CheckLoaderCacheInit();
   1.919 +	if (r!=KErrNone)
   1.920 +		{
   1.921 +		aMessage.Complete(r);
   1.922 +		return;
   1.923 +		}
   1.924 +#else
   1.925 +	TInt r = KErrNone;
   1.926 +#endif
   1.927 +#ifdef _DEBUG
   1.928 +	if(mid==ELoaderDebugFunction)
   1.929 +		{
   1.930 +		msg.Complete(DoLoaderDebugFunction(msg));
   1.931 +		return;
   1.932 +		}
   1.933 +#endif
   1.934 +	if(mid==ELoaderCancelLazyDllUnload)
   1.935 +		{
   1.936 +#ifdef __LAZY_DLL_UNLOAD
   1.937 +		CLazyUnloadTimer::Finish();
   1.938 +#endif
   1.939 +		msg.Complete(KErrNone);
   1.940 +		return;
   1.941 +		}
   1.942 +#ifdef _DEBUG
   1.943 +	gTheLoaderFs.ResourceCountMarkStart();
   1.944 +#endif
   1.945 +	if(mid==EGetInfoFromHeader)
   1.946 +		{
   1.947 +		r=GetInfoFromHeader(msg);
   1.948 +#ifdef _DEBUG
   1.949 +		gTheLoaderFs.ResourceCountMarkEnd();
   1.950 +#endif
   1.951 +		msg.Complete(r);
   1.952 +		return;
   1.953 +		}
   1.954 +
   1.955 +	if (mid == ELdrDelete)
   1.956 +		{
   1.957 +		// TCB and AllFiles are sufficient to ensure that write
   1.958 +		// access to any part of the file system without having to
   1.959 +		// check substitutions and access rights here.
   1.960 +		if (! aMessage.HasCapability(ECapabilityTCB, ECapabilityAllFiles, __PLATSEC_DIAGNOSTIC_STRING("ELdrDelete,TCB+AllFiles")))
   1.961 +			{
   1.962 +			r = KErrPermissionDenied;
   1.963 +			}
   1.964 +		// because this function is a general-purpose replacement for RFs::Delete,
   1.965 +		// it doesn't use the transformed filename which would be put into ldrReq.iFileName,
   1.966 +		// but the literal filename which was supplied, provided it is absolute.
   1.967 +		else
   1.968 +			{
   1.969 +			TInt filenameLength = msg.GetDesLength(1);			
   1.970 +			if(filenameLength<0)
   1.971 +				r = filenameLength;
   1.972 +			else 
   1.973 +				{
   1.974 +				HBufC* fnSupply = HBufC::New(filenameLength);
   1.975 +				if(!fnSupply)
   1.976 +					r = KErrNoMemory;
   1.977 +				else
   1.978 +					{
   1.979 +					TPtr buf = fnSupply->Des();
   1.980 +					if ((r=msg.Read( 1, buf)) == KErrNone)
   1.981 +						{		
   1.982 +						_LIT(KAbsolutePathPattern,"?:\\*");
   1.983 +						if (fnSupply->MatchF(KAbsolutePathPattern) != 0)
   1.984 +							r = KErrBadName;
   1.985 +						else
   1.986 +							{
   1.987 +							_LIT(KSysBin,"?:\\sys\\bin\\*");
   1.988 +							if (fnSupply->MatchF(KSysBin) == 0)
   1.989 +								r = DeleteExecutable(*fnSupply);
   1.990 +							else
   1.991 +								r = gTheLoaderFs.Delete(*fnSupply);
   1.992 +							}	
   1.993 +						}
   1.994 +					delete fnSupply;
   1.995 +					}
   1.996 +				}
   1.997 +			} // endif !aMessage.HasCapability
   1.998 +		
   1.999 +#ifdef _DEBUG
  1.1000 +		gTheLoaderFs.ResourceCountMarkEnd();
  1.1001 +#endif
  1.1002 +		msg.Complete(r);
  1.1003 +		return;
  1.1004 +		}
  1.1005 +	
  1.1006 +	RLdrReq ldrReq;
  1.1007 +	ldrReq.iMsg=&msg;
  1.1008 +	r=msg.GetString(ldrReq.iFileName, 1, KMaxFileName, KExtensionLength, ETrue);
  1.1009 +	__IF_DEBUG(Printf("Filename: %S", ldrReq.iFileName));
  1.1010 +	if (r==KErrNone)
  1.1011 +		r = ldrReq.CheckForSubstDriveInName();
  1.1012 +	__IF_DEBUG(Printf("Post-subst filename: %S", ldrReq.iFileName));
  1.1013 +	if (r!=KErrNone)
  1.1014 +		goto error;
  1.1015 +
  1.1016 +	ldrReq.iPlatSecCaps = AllCapabilities; // secure default, require loaded executable to have all capabilities
  1.1017 +
  1.1018 +#ifndef __EPOC32__
  1.1019 +	// On the emulator, temporarily disable CPU speed restrictions whilst loading executables...
  1.1020 +	TInt cpu;
  1.1021 +	HAL::Get(HALData::ECPUSpeed, cpu);
  1.1022 +	HAL::Set(HALData::ECPUSpeed, 0);
  1.1023 +#endif
  1.1024 +	IF_DEBUG(SetupRFsFail(msg));
  1.1025 +	IF_DEBUG(SetupHeapFail(msg));
  1.1026 +	switch (mid)
  1.1027 +		{
  1.1028 +		//__DATA_CAGING__
  1.1029 +		case EGetInfo:
  1.1030 +			{
  1.1031 +			r=ldrReq.AddFileExtension(KFileExtensionDll);
  1.1032 +			if (r==KErrNone)
  1.1033 +				r=msg.GetLdrInfo(ldrReq);
  1.1034 +			if (r==KErrNone)
  1.1035 +				r=GetModuleInfo(ldrReq);
  1.1036 +			break;
  1.1037 +			}
  1.1038 +		//__DATA_CAGING__
  1.1039 +		case ELoadProcess:
  1.1040 +			{
  1.1041 +			r=ldrReq.AddFileExtension(KFileExtensionExe);
  1.1042 +			if (r==KErrNone)
  1.1043 +				r=msg.GetString(ldrReq.iCmd, 2, KMaxTInt, 0, EFalse);
  1.1044 +			if (r==KErrNone)
  1.1045 +				r=msg.GetLdrInfo(ldrReq);
  1.1046 +			if (r==KErrNone)
  1.1047 +				{
  1.1048 +				static const SCapabilitySet NoCapabilities={{0}};
  1.1049 +				ldrReq.iPlatSecCaps=NoCapabilities; // We don't care what EXEs capabilities are
  1.1050 +				r=LoadProcess(ldrReq);
  1.1051 +				}
  1.1052 +			break;
  1.1053 +			}
  1.1054 +		case ELoadLibrary:
  1.1055 +			{
  1.1056 +			r=E32Loader::CheckClientState(msg.Handle());
  1.1057 +			if (r!=KErrNone)
  1.1058 +				ldrReq.Panic(ELoadLibraryWithoutDllLock);
  1.1059 +			else
  1.1060 +				r=ldrReq.AddFileExtension(KFileExtensionDll);
  1.1061 +			if (r==KErrNone)
  1.1062 +				r=msg.GetString(ldrReq.iPath, 2, KMaxPath, 0, ETrue);
  1.1063 +			if (ldrReq.iPath)
  1.1064 +				{
  1.1065 +				__IF_DEBUG(Printf("Path: %S", ldrReq.iPath));
  1.1066 +				}
  1.1067 +			if (r==KErrNone)
  1.1068 +				r = ldrReq.CheckForSubstDrivesInPath();
  1.1069 +			if (ldrReq.iPath)
  1.1070 +				{
  1.1071 +				__IF_DEBUG(Printf("Post-subst Path: %S", ldrReq.iPath));
  1.1072 +				}
  1.1073 +			if (r==KErrNone)
  1.1074 +				r=msg.GetLdrInfo(ldrReq);
  1.1075 +			if (r==KErrNone)
  1.1076 +				r=LoadLibrary(ldrReq);
  1.1077 +			break;
  1.1078 +			}
  1.1079 +
  1.1080 +        case ECheckLibraryHash:
  1.1081 +
  1.1082 +           r = ldrReq.AddFileExtension(KFileExtensionDll);
  1.1083 +           if (r==KErrNone)
  1.1084 +            {
  1.1085 +            r = CheckLibraryHash(ldrReq);
  1.1086 +            }
  1.1087 +        break;
  1.1088 +
  1.1089 +		case ELoadLogicalDevice:
  1.1090 +			{
  1.1091 +			r=ldrReq.AddFileExtension(KFileExtensionLdd);
  1.1092 +			if (r==KErrNone)
  1.1093 +				r=LoadDeviceDriver(ldrReq, 0);
  1.1094 +			break;
  1.1095 +			}
  1.1096 +		case ELoadPhysicalDevice:
  1.1097 +			{
  1.1098 +			r=ldrReq.AddFileExtension(KFileExtensionPdd);
  1.1099 +			if (r==KErrNone)
  1.1100 +				r=LoadDeviceDriver(ldrReq, 1);
  1.1101 +			break;
  1.1102 +			}
  1.1103 +		case ELoadLocale:
  1.1104 +			{
  1.1105 +			r=ldrReq.AddFileExtension(KFileExtensionDll);
  1.1106 +			if (r==KErrNone)
  1.1107 +				{
  1.1108 +				ldrReq.iRequestedUids=TUidType(TUid::Uid(KDynamicLibraryUidValue),TUid::Uid(KLocaleDllUidValue));
  1.1109 +				ldrReq.iOwnerType=EOwnerProcess;
  1.1110 +				ldrReq.iHandle=0;
  1.1111 +				ldrReq.iPlatSecCaps=AllCapabilities;
  1.1112 +				ldrReq.iMsg=NULL;	// null msg -> client is self
  1.1113 +				TLibraryFunction functionList[KNumLocaleExports];
  1.1114 +				r=LoadLocale(ldrReq, functionList);
  1.1115 +				if(r==KErrNone)
  1.1116 +					{
  1.1117 +					TInt size = KNumLocaleExports * sizeof(TLibraryFunction);
  1.1118 +					TPtr8 functionListBuf((TUint8*)&functionList[0], size, size);
  1.1119 +					TRAP(r, aMessage.WriteL(2, functionListBuf, 0));
  1.1120 +					}
  1.1121 +				}
  1.1122 +			break;
  1.1123 +			}
  1.1124 +		case ELoadCodePage:
  1.1125 +			{
  1.1126 +            if (!KCapDiskAdmin.CheckPolicy(aMessage, __PLATSEC_DIAGNOSTIC_STRING("Loader : ELoadCodePage")))
  1.1127 +                {
  1.1128 +                r = KErrPermissionDenied;
  1.1129 +                break;
  1.1130 +                }
  1.1131 +			r=ldrReq.AddFileExtension(KFileExtensionDll);
  1.1132 +			if (r==KErrNone)
  1.1133 +				{
  1.1134 +				ldrReq.iRequestedUids=TUidType(TUid::Uid(KDynamicLibraryUidValue),TUid::Uid(KLocaleDllUidValue));
  1.1135 +				ldrReq.iOwnerType=EOwnerProcess;
  1.1136 +				ldrReq.iHandle=0;
  1.1137 +				ldrReq.iPlatSecCaps=gFileServerSecInfo.iCaps;
  1.1138 +				ldrReq.iMsg=NULL;	// null msg -> client is self
  1.1139 +				r=LoadLibrary(ldrReq);
  1.1140 +				if (r==KErrNone)
  1.1141 +					{
  1.1142 +					// call file server to install code page dll
  1.1143 +					r = ((RLoaderFs*)&gTheLoaderFs)->SendReceive(EFsLoadCodePage, TIpcArgs(ldrReq.iHandle));
  1.1144 +					}
  1.1145 +				}
  1.1146 +			if (r!=KErrNone)
  1.1147 +				{
  1.1148 +				RLibrary lib;
  1.1149 +				lib.SetHandle(ldrReq.iHandle);
  1.1150 +				lib.Close();
  1.1151 +				}
  1.1152 +			break;
  1.1153 +			}
  1.1154 +		case ELoadFileSystem:
  1.1155 +			{
  1.1156 +            if (!KCapFsAddFileSystem.CheckPolicy(aMessage, __PLATSEC_DIAGNOSTIC_STRING("Add File System")))
  1.1157 +                {
  1.1158 +                r = KErrPermissionDenied;
  1.1159 +                break;
  1.1160 +                }
  1.1161 +			r=ldrReq.AddFileExtension(KFileExtensionFsy);
  1.1162 +			if (r==KErrNone)
  1.1163 +				{
  1.1164 +				ldrReq.iRequestedUids=TUidType(TUid::Uid(KDynamicLibraryUidValue),TUid::Uid(KFileSystemUidValue));
  1.1165 +				ldrReq.iOwnerType=EOwnerProcess;
  1.1166 +				ldrReq.iHandle=0;
  1.1167 +				ldrReq.iPlatSecCaps=gFileServerSecInfo.iCaps;
  1.1168 +				ldrReq.iMsg=NULL;	// null msg -> client is self
  1.1169 +				r=LoadLibrary(ldrReq);
  1.1170 +				if (r==KErrNone)
  1.1171 +					{
  1.1172 +					// call file server to install file system
  1.1173 +					r = ((RLoaderFs*)&gTheLoaderFs)->SendReceive(EFsAddFileSystem, TIpcArgs(ldrReq.iHandle));
  1.1174 +					}
  1.1175 +				}
  1.1176 +			if (r!=KErrNone)
  1.1177 +				{
  1.1178 +				RLibrary lib;
  1.1179 +				lib.SetHandle(ldrReq.iHandle);
  1.1180 +				lib.Close();
  1.1181 +				}
  1.1182 +			break;
  1.1183 +			}
  1.1184 +		case ELoadFSExtension:
  1.1185 +			{
  1.1186 +            if (!KCapFsAddExtension.CheckPolicy(aMessage, __PLATSEC_DIAGNOSTIC_STRING("Add File Extension")))
  1.1187 +                {
  1.1188 +                r = KErrPermissionDenied;
  1.1189 +                break;
  1.1190 +                }
  1.1191 +			r=ldrReq.AddFileExtension(KFileExtensionFxt);
  1.1192 +			if (r==KErrNone)
  1.1193 +				{
  1.1194 +				ldrReq.iRequestedUids=TUidType(TUid::Uid(KDynamicLibraryUidValue),TUid::Uid(KFileSystemUidValue));
  1.1195 +				ldrReq.iOwnerType=EOwnerProcess;
  1.1196 +				ldrReq.iHandle=0;
  1.1197 +				ldrReq.iPlatSecCaps=gFileServerSecInfo.iCaps;
  1.1198 +				ldrReq.iMsg=NULL;	// null msg -> client is self
  1.1199 +				r=LoadLibrary(ldrReq);
  1.1200 +				if (r==KErrNone)
  1.1201 +					{
  1.1202 +					// call file server to install file system
  1.1203 +					r = ((RLoaderFs*)&gTheLoaderFs)->SendReceive(EFsAddExtension, TIpcArgs(ldrReq.iHandle));
  1.1204 +					}
  1.1205 +				}
  1.1206 +			if (r!=KErrNone)
  1.1207 +				{
  1.1208 +				RLibrary lib;
  1.1209 +				lib.SetHandle(ldrReq.iHandle);
  1.1210 +				lib.Close();
  1.1211 +				}
  1.1212 +			break;
  1.1213 +			}
  1.1214 +		case ELoadFSProxyDrive:
  1.1215 +			{
  1.1216 +            if (!KCapFsAddProxyDrive.CheckPolicy(aMessage, __PLATSEC_DIAGNOSTIC_STRING("Add Proxy Drive")))
  1.1217 +                {
  1.1218 +                r = KErrPermissionDenied;
  1.1219 +                break;
  1.1220 +                }
  1.1221 +			r=ldrReq.AddFileExtension(KFileExtensionPxy);
  1.1222 +			if (r==KErrNone)
  1.1223 +				{
  1.1224 +				ldrReq.iRequestedUids=TUidType(TUid::Uid(KDynamicLibraryUidValue),TUid::Uid(KFileSystemUidValue));
  1.1225 +				ldrReq.iOwnerType=EOwnerProcess;
  1.1226 +				ldrReq.iHandle=0;
  1.1227 +				ldrReq.iPlatSecCaps=gFileServerSecInfo.iCaps;
  1.1228 +				ldrReq.iMsg=NULL;	// null msg -> client is self
  1.1229 +				r=LoadLibrary(ldrReq);
  1.1230 +				if (r==KErrNone)
  1.1231 +					{
  1.1232 +					// call file server to install file system
  1.1233 +					r = ((RLoaderFs*)&gTheLoaderFs)->SendReceive(EFsAddProxyDrive, TIpcArgs(ldrReq.iHandle));
  1.1234 +					}
  1.1235 +				}
  1.1236 +			if (r!=KErrNone)
  1.1237 +				{
  1.1238 +				RLibrary lib;
  1.1239 +				lib.SetHandle(ldrReq.iHandle);
  1.1240 +				lib.Close();
  1.1241 +				}
  1.1242 +			break;
  1.1243 +			}
  1.1244 +		case ELoadFSPlugin:
  1.1245 +			{
  1.1246 +			r=ldrReq.AddFileExtension(KFileExtensionPxt);
  1.1247 +			if (r==KErrNone)
  1.1248 +				{
  1.1249 +				ldrReq.iRequestedUids=TUidType(TUid::Uid(KDynamicLibraryUidValue),TUid::Uid(KFileSystemUidValue));
  1.1250 +				ldrReq.iOwnerType=EOwnerProcess;
  1.1251 +				ldrReq.iHandle=0;
  1.1252 +				ldrReq.iPlatSecCaps=gFileServerSecInfo.iCaps;
  1.1253 +				ldrReq.iMsg=NULL;	// null msg -> client is self
  1.1254 +				r=LoadLibrary(ldrReq);
  1.1255 +				if (r==KErrNone)
  1.1256 +					{
  1.1257 +					// call file server to install file system
  1.1258 +					r = ((RLoaderFs*)&gTheLoaderFs)->SendReceive(EFsAddPlugin, TIpcArgs(ldrReq.iHandle));
  1.1259 +					}
  1.1260 +				}
  1.1261 +			if (r!=KErrNone)
  1.1262 +				{
  1.1263 +				RLibrary lib;
  1.1264 +				lib.SetHandle(ldrReq.iHandle);
  1.1265 +				lib.Close();
  1.1266 +				}
  1.1267 +			break;
  1.1268 +			}
  1.1269 +		
  1.1270 +		default:
  1.1271 +			r=KErrNotSupported;
  1.1272 +			break;
  1.1273 +		}
  1.1274 +	
  1.1275 +	ldrReq.Close();
  1.1276 +	IF_DEBUG(EndRFsFailCheck(r));
  1.1277 +	IF_DEBUG(EndHeapFailCheck(r));
  1.1278 +#ifndef __EPOC32__
  1.1279 +	HAL::Set(HALData::ECPUSpeed, cpu);
  1.1280 +#endif
  1.1281 +error:
  1.1282 +#ifdef _DEBUG
  1.1283 +	gTheLoaderFs.ResourceCountMarkEnd();
  1.1284 +#endif
  1.1285 +	if (!aMessage.IsNull())
  1.1286 +		{
  1.1287 +		__IF_DEBUG(Printf("Loader: msg complete %d", r));
  1.1288 +		aMessage.Complete(r);
  1.1289 +		}
  1.1290 +	}
  1.1291 +
  1.1292 +//-----------------------------------------------------------------------------------
  1.1293 +#ifndef __WINS__
  1.1294 +/**
  1.1295 +    Helper function that reads a hash file from c:\\sys\\hash and compares it with the givem dll hash.
  1.1296 +
  1.1297 +    @param  aHashFile     represents opened hash file in c:\\sys\\hash directory
  1.1298 +    @param  aDllFileName  full path to the dll file, which hash will be calculated and compared with aHashFile contents.
  1.1299 +    @leave  on file operation error or if hashes differ.
  1.1300 +*/
  1.1301 +static void DoCheckHashL(RFile& aHashFile, const TDesC& aDllFileName)
  1.1302 +    {
  1.1303 +	TBuf8<SHA1_HASH> hashInstalled; //-- installed dll hash, from c:\\sys\\hash
  1.1304 +	User::LeaveIfError(aHashFile.Read(hashInstalled));
  1.1305 +
  1.1306 +	CSHA1* hasher=CSHA1::NewL();
  1.1307 +	CleanupStack::PushL(hasher);
  1.1308 +
  1.1309 +    RFile fileDll;
  1.1310 +    CleanupClosePushL(fileDll);
  1.1311 +
  1.1312 +    //-- open dll file
  1.1313 +    User::LeaveIfError(fileDll.Open(gTheLoaderFs, aDllFileName, EFileRead|EFileReadDirectIO));
  1.1314 +
  1.1315 +    TInt fileSz;
  1.1316 +	User::LeaveIfError(fileDll.Size(fileSz));
  1.1317 +
  1.1318 +    //-- check if the file is on removable media
  1.1319 +    TInt drvNum;
  1.1320 +    TDriveInfo drvInfo;
  1.1321 +    User::LeaveIfError(fileDll.Drive(drvNum, drvInfo));
  1.1322 +    if(!(drvInfo.iDriveAtt & KDriveAttRemovable))
  1.1323 +        User::Leave(KErrNotSupported);
  1.1324 +
  1.1325 +    TInt    offset=0;
  1.1326 +    TInt    readSize = KHashFileReadSize;
  1.1327 +    RBuf8   readBuf;
  1.1328 +
  1.1329 +    CleanupClosePushL(readBuf);
  1.1330 +    readBuf.CreateMaxL(readSize);
  1.1331 +
  1.1332 +    //-- calculate dll hash
  1.1333 +    do	{
  1.1334 +		if((fileSz - offset) < readSize)
  1.1335 +			readSize = (fileSz - offset);
  1.1336 +
  1.1337 +		User::LeaveIfError(fileDll.Read(offset, readBuf, readSize));
  1.1338 +		hasher->Update(readBuf);
  1.1339 +		offset+=readSize;
  1.1340 +		}
  1.1341 +	while(offset < fileSz);
  1.1342 +
  1.1343 +    TBuf8<SHA1_HASH> hashCalculated; //-- calculated dll hash
  1.1344 +	hashCalculated=hasher->Final();
  1.1345 +
  1.1346 +    //-- compare hashes
  1.1347 +    if(hashCalculated.Compare(hashInstalled) !=0)
  1.1348 +        User::Leave(KErrCorrupt);
  1.1349 +
  1.1350 +    CleanupStack::PopAndDestroy(3); //hasher, fileDll, readBuf
  1.1351 +    }
  1.1352 +#endif //__WINS__
  1.1353 +
  1.1354 +//-----------------------------------------------------------------------------------
  1.1355 +
  1.1356 +/**
  1.1357 +    Check if specified dll hash exists in \\sys\\hash on system drive and optionally validate it.
  1.1358 +
  1.1359 +
  1.1360 +    @param  aReq loader request parameters
  1.1361 +
  1.1362 +    @return System-wide error code, see RLoader::CheckLibraryHash() description
  1.1363 +    @return KErrNotSupported for the emulator version, because loading dlls from the emulated removable media is not supported
  1.1364 +*/
  1.1365 +static TInt CheckLibraryHash(RLdrReq& aReq)
  1.1366 +    {
  1.1367 +#ifdef __WINS__
  1.1368 +    (void)aReq;
  1.1369 +    return KErrNotSupported; //-- loading dlls from removable media and dll hashing isn't supported for WINS
  1.1370 +#else
  1.1371 +
  1.1372 +    const TInt fNameLen=aReq.iFileName->Length();
  1.1373 +    if(fNameLen <= 0 || fNameLen > KMaxFileName)
  1.1374 +        return KErrArgument;
  1.1375 +
  1.1376 +    const TBool bValidateHash=aReq.iMsg->Int2();
  1.1377 +
  1.1378 +    //-- extract pure dll name
  1.1379 +    TInt posNameStart=aReq.iFileName->LocateReverse('\\');
  1.1380 +    if(posNameStart <0)
  1.1381 +        posNameStart = 0;
  1.1382 +    else
  1.1383 +        posNameStart++;
  1.1384 +
  1.1385 +    //-- compose hash file name \\sys\\hash\\xxx on system drive
  1.1386 +    TFileName hashFName;
  1.1387 +    hashFName.Copy(aReq.iFileName->Right(fNameLen-posNameStart));
  1.1388 +    hashFName.Insert(0, KSysHash);
  1.1389 +    hashFName[0] = (TUint8) RFs::GetSystemDriveChar();
  1.1390 +
  1.1391 +    //-- try to locate hash file
  1.1392 +    TInt nRes=KErrNone;
  1.1393 +    RFile fileHash;
  1.1394 +	nRes = fileHash.Open(gTheLoaderFs, hashFName, EFileRead|EFileReadDirectIO);
  1.1395 +
  1.1396 +    if(nRes != KErrNone)
  1.1397 +        {
  1.1398 +        nRes = KErrNotFound; //-- hash file couldn't be found
  1.1399 +        }
  1.1400 +    else if(bValidateHash)
  1.1401 +        {//-- request to validate the hash.
  1.1402 +        hashFName.Copy(aReq.iFileName->Left(fNameLen)); //-- expand file name to unicode
  1.1403 +        TRAP(nRes, DoCheckHashL(fileHash, hashFName));
  1.1404 +
  1.1405 +        if(nRes != KErrNone)
  1.1406 +            nRes=KErrCorrupt;
  1.1407 +        }
  1.1408 +
  1.1409 +    fileHash.Close();
  1.1410 +
  1.1411 +    return nRes;
  1.1412 +
  1.1413 +#endif //__WINS__
  1.1414 +    }
  1.1415 +
  1.1416 +// This safely deletes something that could be an executable (ie in /sys/bin)
  1.1417 +// aName will be deleted either in, or sometime after this call
  1.1418 +// (The descriptor and the file it represents)
  1.1419 +TInt CSessionLoader::DeleteExecutable(const TDesC& aName)
  1.1420 +	{
  1.1421 +	__IF_DEBUG(Printf("DeleteExecutable %S", &aName));
  1.1422 +	TInt r;
  1.1423 +	r = gTheLoaderFs.Delete(aName);
  1.1424 +	if (r!=KErrInUse)
  1.1425 +		{
  1.1426 +		return r;
  1.1427 +		}
  1.1428 +	RFile toDelete;
  1.1429 +	CReaperCleanupTimer::Complete();
  1.1430 +
  1.1431 +	HBufC* newName=NULL;
  1.1432 +	r = toDelete.Open(gTheLoaderFs,aName,EFileShareExclusive|EFileReadDirectIO);
  1.1433 +	if (r==KErrNone)
  1.1434 +		{
  1.1435 +		TInt64 startPos=0;
  1.1436 +		SBlockMapInfo blockmapInfo;
  1.1437 +								
  1.1438 +		// find drive number, and starting block
  1.1439 +		r = toDelete.BlockMap(blockmapInfo,startPos, 1, ETrue);
  1.1440 +		if (r == KErrCompletion)
  1.1441 +			{
  1.1442 +			TInt64 startBlock = blockmapInfo.iStartBlockAddress +
  1.1443 +								((TBlockMapEntry *)(&(blockmapInfo.iMap[0])))->iStartBlock *
  1.1444 +								blockmapInfo.iBlockGranularity +
  1.1445 +								blockmapInfo.iBlockStartOffset;
  1.1446 +			TInt driveNumber = blockmapInfo.iLocalDriveNumber;
  1.1447 +
  1.1448 +			newName = HBufC::New(KPathDelLength+2+16); // + 2 digits for drive and 16 for start block block
  1.1449 +			if(!newName)
  1.1450 +				r = KErrNoMemory;
  1.1451 +			else
  1.1452 +				{
  1.1453 +				// make unique name for file...
  1.1454 +				TPtr name = newName->Des();
  1.1455 +				name.Copy(KPathDel);
  1.1456 +				name[0] = aName[0]; // copy drive letter
  1.1457 +				name.AppendNumFixedWidth(driveNumber, EHex, 2);
  1.1458 +				name.AppendNumFixedWidth(TUint32(startBlock>>32), EHex, 8);
  1.1459 +				name.AppendNumFixedWidth(TUint32(startBlock), EHex, 8);
  1.1460 +
  1.1461 +				TLoaderDeletedList* tmpLink = new TLoaderDeletedList();
  1.1462 +				if(tmpLink==NULL)
  1.1463 +					r = KErrNoMemory;
  1.1464 +				else
  1.1465 +					{
  1.1466 +					toDelete.Close();
  1.1467 +					gTheLoaderFs.MkDirAll(*newName); // ignore error and let rename fail if path doesn't exists
  1.1468 +					r = gTheLoaderFs.Rename(aName, *newName);
  1.1469 +					__IF_DEBUG(Printf("DeleteExecutable rename to %S returns %d", &newName, r));
  1.1470 +					if(r==KErrNone)
  1.1471 +						{
  1.1472 +						// add to pending deletion list		
  1.1473 +						tmpLink->iStartBlock = startBlock;
  1.1474 +						tmpLink->iDriveNumber = driveNumber;
  1.1475 +						tmpLink->iFileName = newName;
  1.1476 +						gActiveReaper->AddDeleted(tmpLink);
  1.1477 +						return r;					
  1.1478 +						} //endif rename
  1.1479 +					delete tmpLink;
  1.1480 +					} // alloc
  1.1481 +				delete newName;
  1.1482 +				} // alloc name
  1.1483 +			} //endif blockmap
  1.1484 +		else if (r == KErrNotSupported)	
  1.1485 +			r = KErrInUse;
  1.1486 +		else if (r == KErrNone)
  1.1487 +			r = KErrGeneral; 
  1.1488 +		toDelete.Close();	
  1.1489 +		} // endif open						
  1.1490 +	return r;
  1.1491 +	}
  1.1492 +
  1.1493 +
  1.1494 +GLDEF_C TInt LoadProcess(RLdrReq& aReq)
  1.1495 +	{
  1.1496 +	__LDRTRACE(aReq.Dump("LoadProcess:"));
  1.1497 +	TInt32* uid=(TInt32*)&aReq.iRequestedUids;
  1.1498 +	if (uid[0] && uid[0]!=KExecutableImageUidValue)
  1.1499 +		return KErrNotSupported;
  1.1500 +	uid[0]=KExecutableImageUidValue;
  1.1501 +	gExeCodeSeg=NULL;	// new process doesn't load into another process
  1.1502 +	gExeAttr=0;
  1.1503 +	E32Image* e=new E32Image;
  1.1504 +	if (!e)
  1.1505 +		return KErrNoMemory;
  1.1506 +	e->iMain=e;
  1.1507 +	TInt r=e->LoadProcess(aReq);
  1.1508 +	if (r==KErrNone)
  1.1509 +		{
  1.1510 +		aReq.iHandle=e->iFinalHandle;
  1.1511 +		r=aReq.iMsg->UpdateLdrInfo(aReq);
  1.1512 +		if (r!=KErrNone)
  1.1513 +			aReq.Panic(KErrBadDescriptor);
  1.1514 +		}
  1.1515 +	if (r!=KErrNone && e->iProcessHandle)
  1.1516 +		{
  1.1517 +		RProcess p;
  1.1518 +		p.SetHandle(e->iProcessHandle);
  1.1519 +		p.Kill(0);
  1.1520 +		}
  1.1521 +	delete e;
  1.1522 +	return r;
  1.1523 +	}
  1.1524 +
  1.1525 +
  1.1526 +
  1.1527 +TInt LoadLibrary(RLdrReq& aReq)
  1.1528 +	{
  1.1529 +	__LDRTRACE(aReq.Dump("LoadLibrary:"));
  1.1530 +	TInt32* uid=(TInt32*)&aReq.iRequestedUids;
  1.1531 +	if (uid[0] && uid[0]!=KDynamicLibraryUidValue)
  1.1532 +		return KErrNotSupported;
  1.1533 +	uid[0]=KDynamicLibraryUidValue;
  1.1534 +	TInt r=KErrNone;
  1.1535 +	if (aReq.iMsg)
  1.1536 +		{
  1.1537 +		r = aReq.iMsg->Client(aReq.iClientThread);
  1.1538 +		if (r==KErrNone)
  1.1539 +			r = aReq.iClientThread.Process(aReq.iClientProcess);
  1.1540 +		if (r!=KErrNone)
  1.1541 +			{
  1.1542 +			return r;
  1.1543 +			}
  1.1544 +		}
  1.1545 +	else
  1.1546 +		{
  1.1547 +		aReq.iClientThread.SetHandle(KCurrentThreadHandle);
  1.1548 +		aReq.iClientProcess.SetHandle(KCurrentProcessHandle);
  1.1549 +		}
  1.1550 +	E32Loader::CodeSegDeferDeletes();
  1.1551 +	gExeCodeSeg=E32Loader::ThreadProcessCodeSeg(aReq.iClientThread.Handle());
  1.1552 +	SSecurityInfo si;
  1.1553 +	gExeAttr=GetCodeSegAttr(gExeCodeSeg, &si, NULL);
  1.1554 +	aReq.iPlatSecCaps=si.iCaps;
  1.1555 +	E32Loader::CodeSegEndDeferDeletes();
  1.1556 +	E32Image* e=new E32Image;
  1.1557 +	if (!e)
  1.1558 +		return KErrNoMemory;
  1.1559 +	e->iMain=e;
  1.1560 +	e->iClientProcessHandle=aReq.iClientProcess.Handle();
  1.1561 +	__IF_DEBUG(Printf("e->iClientProcessHandle = %08x", e->iClientProcessHandle));
  1.1562 +	if (r==KErrNone)
  1.1563 +		r=e->LoadCodeSeg(aReq);
  1.1564 +	if (r==KErrNone)
  1.1565 +		{
  1.1566 +		TLibraryCreateInfo libInfo;
  1.1567 +		libInfo.iCodeSegHandle=e->iHandle;
  1.1568 +		libInfo.iClientHandle=aReq.iClientThread.Handle();
  1.1569 +		libInfo.iLibraryHandle=0;
  1.1570 +		libInfo.iOwnerType=aReq.iOwnerType;
  1.1571 +		r=E32Loader::LibraryCreate(libInfo);
  1.1572 +		if (r==KErrNone)
  1.1573 +			{
  1.1574 +			aReq.iHandle=libInfo.iLibraryHandle;
  1.1575 +			if (aReq.iMsg)
  1.1576 +				{
  1.1577 +				r=aReq.iMsg->UpdateLdrInfo(aReq);
  1.1578 +				if (r!=KErrNone)
  1.1579 +					aReq.Panic(KErrBadDescriptor);
  1.1580 +				}
  1.1581 +			}
  1.1582 +		}
  1.1583 +	delete e;
  1.1584 +	return r;
  1.1585 +	}
  1.1586 +	
  1.1587 +struct TFatUtilityFunctions;
  1.1588 +
  1.1589 +GLDEF_C TInt LoadLocale(RLdrReq& aReq, TLibraryFunction* aExportsList)
  1.1590 +	{
  1.1591 +	__LDRTRACE(aReq.Dump("LoadLocale:"));
  1.1592 +	TUint32* uid=(TUint32*)&aReq.iRequestedUids;
  1.1593 +	uid[2]=0;
  1.1594 +	gExeCodeSeg=NULL;
  1.1595 +	gExeAttr = gFileServerAttr;
  1.1596 +	E32Image* e=new E32Image;
  1.1597 +	if (!e)
  1.1598 +		return KErrNoMemory;
  1.1599 +	e->iMain=e;
  1.1600 +	e->iAttr=ECodeSegAttGlobal;
  1.1601 +	TInt r=e->LoadCodeSeg(aReq);
  1.1602 +	if (r==KErrNone)
  1.1603 +		{
  1.1604 +		r = E32Loader::LocaleExports(e->iHandle, aExportsList);
  1.1605 +#ifdef SYMBIAN_DISTINCT_LOCALE_MODEL
  1.1606 +		_LIT8(KLocLan, "elocl_lan");
  1.1607 +		_LIT8(KLoc, "elocl.");
  1.1608 +        if(aReq.iFileName->Find(KLocLan) != KErrNotFound)
  1.1609 +            {
  1.1610 +			TheCodePage.SetLocaleCodePage((TFatUtilityFunctions*)aExportsList[FnFatUtilityFunctionsV2]());
  1.1611 +            }		
  1.1612 +        if(aReq.iFileName->Find(KLoc) != KErrNotFound)
  1.1613 +            {
  1.1614 +			TheCodePage.SetLocaleCodePage((TFatUtilityFunctions*)aExportsList[FnFatUtilityFunctions]());
  1.1615 +            }				
  1.1616 +#else
  1.1617 +		// The 'old' version of the locale DLL contained a set of code page conversion exports.
  1.1618 +		// This has now been superceeded by the use of a seperate code page DLL.
  1.1619 +		//  - To ease migration both are currently supported.
  1.1620 +		//  - If both locale and CP DLL functions are present, CP DLL's will take precedence
  1.1621 +		//  - This functionality will eventually be deprecated.
  1.1622 +		TheCodePage.SetLocaleCodePage((TFatUtilityFunctions*)aExportsList[FnFatUtilityFunctions]());
  1.1623 +#endif
  1.1624 +		}
  1.1625 +	delete e;
  1.1626 +	return r;
  1.1627 +	}
  1.1628 +
  1.1629 +TInt LoadDeviceDriver(RLdrReq& aReq, TInt aDeviceType)
  1.1630 +	{
  1.1631 +	__IF_DEBUG(Printf("LoadDeviceDriver type %d", aDeviceType));
  1.1632 +	__LDRTRACE(aReq.Dump(""));
  1.1633 +	TUint32* uid=(TUint32*)&aReq.iRequestedUids;
  1.1634 +	uid[0]=KDynamicLibraryUidValue;
  1.1635 +	uid[1]=aDeviceType ? KPhysicalDeviceDriverUidValue : KLogicalDeviceDriverUidValue;
  1.1636 +	uid[2]=0;
  1.1637 +	gExeCodeSeg=gKernelCodeSeg;
  1.1638 +	gExeAttr=gKernelAttr;
  1.1639 +	E32Image* e=new E32Image;
  1.1640 +	if (!e)
  1.1641 +		return KErrNoMemory;
  1.1642 +	e->iMain=e;
  1.1643 +	e->iAttr=ECodeSegAttKernel;
  1.1644 +	aReq.iOwnerType=EOwnerProcess;
  1.1645 +	aReq.iHandle=0;
  1.1646 +	aReq.iPlatSecCaps=gKernelSecInfo.iCaps;
  1.1647 +	TInt r=e->LoadCodeSeg(aReq);
  1.1648 +	if (r==KErrNone)
  1.1649 +		r=E32Loader::DeviceLoad(e->iHandle, aDeviceType);
  1.1650 +	delete e;
  1.1651 +	return r;
  1.1652 +	}
  1.1653 +
  1.1654 +CServerLoader* CServerLoader::New()
  1.1655 +//
  1.1656 +// Create a new CServerLoader.
  1.1657 +//
  1.1658 +	{
  1.1659 +	CServerLoader* pS=new CServerLoader(EPriorityNormal);
  1.1660 +	if (pS==NULL)
  1.1661 +		return(NULL);
  1.1662 +	_LIT(KLoaderServerName,"!Loader");
  1.1663 +	TInt r=pS->Start(KLoaderServerName);
  1.1664 +	if (r!=KErrNone)
  1.1665 +		return(NULL);
  1.1666 +	return(pS);
  1.1667 +	}
  1.1668 +
  1.1669 +CServerLoader::CServerLoader(TInt aPriority)
  1.1670 +//
  1.1671 +// Constructor.
  1.1672 +//
  1.1673 +	: CServer2(aPriority)
  1.1674 +	{
  1.1675 +	}
  1.1676 +
  1.1677 +CSession2* CServerLoader::NewSessionL(const TVersion& aVersion, const RMessage2&) const
  1.1678 +//
  1.1679 +// Create a new client for this server.
  1.1680 +//
  1.1681 +	{
  1.1682 +
  1.1683 +	TVersion v(KLoaderMajorVersionNumber,KLoaderMinorVersionNumber,KF32BuildVersionNumber);
  1.1684 +	TBool r=User::QueryVersionSupported(v,aVersion);
  1.1685 +	if (!r)
  1.1686 +		User::Leave(KErrNotSupported);
  1.1687 +	return new (ELeave) CSessionLoader;
  1.1688 +	}
  1.1689 +
  1.1690 +TInt CServerLoader::RunError(TInt aError)
  1.1691 +//
  1.1692 +// Complete the request with the error code
  1.1693 +//
  1.1694 +	{
  1.1695 +	Message().Complete(aError);
  1.1696 +	ReStart();
  1.1697 +	return KErrNone;
  1.1698 +	}
  1.1699 +
  1.1700 +CActiveSchedulerLoader* CActiveSchedulerLoader::New()
  1.1701 +//
  1.1702 +// Create and install the active scheduler.
  1.1703 +//
  1.1704 +	{
  1.1705 +
  1.1706 +	CActiveSchedulerLoader* pA=new CActiveSchedulerLoader;
  1.1707 +	if (pA==NULL)
  1.1708 +		return(NULL);
  1.1709 +	CActiveScheduler::Install(pA);
  1.1710 +	return(pA);
  1.1711 +	}
  1.1712 +
  1.1713 +void CActiveSchedulerLoader::Error(TInt anError) const
  1.1714 +//
  1.1715 +// Called if any Run() method leaves.
  1.1716 +//
  1.1717 +	{
  1.1718 +	_LIT(KPanicLoaderErr, "LOADER-ERR");
  1.1719 +	User::Panic(KPanicLoaderErr,anError);
  1.1720 +	}
  1.1721 +
  1.1722 +/******************************************************************************
  1.1723 + * E32Image functions common to WINS and EPOC
  1.1724 + ******************************************************************************/
  1.1725 +
  1.1726 +TInt CheckUids(const TUidType& aUids, const TUidType& aRequestedUids)
  1.1727 +	{
  1.1728 +	const TUint32* uid=(const TUint32*)&aUids;
  1.1729 +	const TUint32* req=(const TUint32*)&aRequestedUids;
  1.1730 +	__IF_DEBUG(Printf("CheckUids %08x,%08x,%08x req %08x,%08x,%08x",	uid[0],uid[1],uid[2],
  1.1731 +																		req[0],req[1],req[2]));
  1.1732 +	return (CheckUid(uid[0],req[0]) && CheckUid(uid[1],req[1]) && CheckUid(uid[2],req[2]))
  1.1733 +			? KErrNone : KErrNotSupported;
  1.1734 +	}
  1.1735 +
  1.1736 +E32Image::E32Image()
  1.1737 +	{
  1.1738 +	__IF_DEBUG(Printf("E32Image Constructor"));
  1.1739 +	Mem::FillZ(&iUids, sizeof(E32Image)-sizeof(iFileName));
  1.1740 +	}
  1.1741 +
  1.1742 +E32Image::~E32Image()
  1.1743 +	{
  1.1744 +
  1.1745 +	__IF_DEBUG(Printf("E32Image Destructor"));
  1.1746 +	Reset();
  1.1747 +	}
  1.1748 +
  1.1749 +void E32Image::Reset()
  1.1750 +	{
  1.1751 +	__IF_DEBUG(Printf("E32Image::Reset"));
  1.1752 +	delete iHeader;
  1.1753 +	__IF_DEBUG(Printf("iHeader"));
  1.1754 +
  1.1755 +	// demand paging fixup data
  1.1756 +	User::Free(iImportFixupTable);
  1.1757 +	__IF_DEBUG(Printf("iImportFixupTable"));
  1.1758 +
  1.1759 +	// demand paging file data
  1.1760 +	__IF_DEBUG(Printf("iCodePageOffsets"));
  1.1761 +	delete[] iCodePageOffsets;
  1.1762 +	__IF_DEBUG(Printf("iCodeBlockMapEntries"));
  1.1763 +	User::Free(iCodeBlockMapEntries);
  1.1764 +
  1.1765 +	__IF_DEBUG(Printf("iCodeRelocSection"));
  1.1766 +	User::Free(iCodeRelocTable);
  1.1767 +	__IF_DEBUG(Printf("iDataRelocSection"));
  1.1768 +	User::Free(iRestOfFileData);
  1.1769 +	__IF_DEBUG(Printf("iRestOfFileData"));
  1.1770 +	User::Free(iCurrentImportList);
  1.1771 +	__IF_DEBUG(Printf("iCurrentImportList"));
  1.1772 +	User::Free(iFixups);
  1.1773 +	__IF_DEBUG(Printf("iFixups"));
  1.1774 +	gFileDataAllocator.Free(iFileData);
  1.1775 +	iFileData = NULL;
  1.1776 +	__IF_DEBUG(Printf("iFileData"));
  1.1777 +	iFile.Close();
  1.1778 +	__IF_DEBUG(Printf("iFile"));
  1.1779 +	User::Free(iCopyOfExportDir);
  1.1780 +	if (iProcessHandle)
  1.1781 +		{
  1.1782 +		RProcess p;
  1.1783 +		p.SetHandle(iProcessHandle);
  1.1784 +		p.Close();
  1.1785 +		__IF_DEBUG(Printf("iProcessHandle"));
  1.1786 +		}
  1.1787 +	if (iCloseCodeSeg)
  1.1788 +		E32Loader::CodeSegClose(iCloseCodeSeg);
  1.1789 +	if (iMain==this)
  1.1790 +		E32Loader::CodeSegClose(NULL);
  1.1791 +
  1.1792 +	// Unclamp file if load failed.  Cannot handle error from RFs here.
  1.1793 +	__IF_DEBUG(Printf("iFileClamp,%ld,%ld", iFileClamp.iCookie[0], iFileClamp.iCookie[1]));
  1.1794 +	iFileClamp.Close(gTheLoaderFs);
  1.1795 +
  1.1796 +	__IF_DEBUG(Printf("Reset done"));
  1.1797 +	}
  1.1798 +
  1.1799 +
  1.1800 +TInt E32Image::OpenFile()
  1.1801 +	{
  1.1802 +	TBuf8<KMaxFileName*sizeof(TText)> fnb;
  1.1803 +	if (iAttr & ECodeSegAttExpVer)
  1.1804 +		{
  1.1805 +		TFileNameInfo fi;
  1.1806 +		fi.Set(iFileName, 0);
  1.1807 +		fi.iVersion = iModuleVersion;
  1.1808 +		fi.GetName(fnb, TFileNameInfo::EIncludeDrivePathBaseExt|TFileNameInfo::EForceVer);
  1.1809 +		}
  1.1810 +	else
  1.1811 +		fnb = iFileName;
  1.1812 +	TPtr16 fn(fnb.Expand());
  1.1813 +	__IF_DEBUG(Print(_L(">E32Image::OpenFile %S"),&fn));
  1.1814 +	TInt r = iFile.Open(gTheLoaderFs, fn, EFileStream|EFileRead|EFileShareReadersOnly|EFileReadDirectIO);
  1.1815 +	__IF_DEBUG(Printf("<E32Image::OpenFile %d", r));
  1.1816 +	return r;
  1.1817 +	}
  1.1818 +
  1.1819 +
  1.1820 +/**
  1.1821 +Check if this executable is already loaded. If it is, set iAlreadyLoaded true and
  1.1822 +iHandle to an newly opened reference on the CodeSeg. Also set iExportDirLoad if the
  1.1823 +export directory of the executable is directly visible to the Loader.
  1.1824 +*/
  1.1825 +TInt E32Image::CheckAlreadyLoaded()
  1.1826 +	{
  1.1827 +	__IF_DEBUG(Printf(">E32Image::CheckAlreadyLoaded %S", &iFileName));
  1.1828 +	__IF_DEBUG(Printf("UIDs %08x,%08x,%08x",iUids[0],iUids[1],iUids[2]));
  1.1829 +	__IF_DEBUG(Printf("VER %08x",iModuleVersion));
  1.1830 +	__IF_DEBUG(Printf("CAPS %08x %08x SID %08x", iS.iSecureId, iS.iCaps[1], iS.iCaps[0]));
  1.1831 +	__IF_DEBUG(Printf("Client process handle %08x",iClientProcessHandle));
  1.1832 +
  1.1833 +	TFindCodeSeg find;
  1.1834 +	find.iUids = iUids;
  1.1835 +	find.iRomImgHdr = NULL;
  1.1836 +#ifndef __WINS__
  1.1837 +	// Make sure we check the code segment attributes (kernel or global)
  1.1838 +	// as part of the decision as to whether we are loaded or not.
  1.1839 +	find.iAttrMask = (ECodeSegAttKernel|ECodeSegAttGlobal);
  1.1840 +	find.iAttrVal = iAttr&(ECodeSegAttKernel|ECodeSegAttGlobal);
  1.1841 +#else	
  1.1842 +	// On the emulator, all DLLs are loaded into the same process, so we
  1.1843 +	// don't distinguish between instances of the same DLL loaded with
  1.1844 +	// different code segment attributes.
  1.1845 +	find.iAttrMask = 0;
  1.1846 +	find.iAttrVal = 0;
  1.1847 +#endif
  1.1848 +	find.iProcess = iClientProcessHandle;
  1.1849 +	find.iS = iS;
  1.1850 +	find.iModuleVersion = iModuleVersion;
  1.1851 +	find.iName = RootName();
  1.1852 +	__IF_DEBUG(Printf("Required root name %S", &find.iName));
  1.1853 +
  1.1854 +	E32Loader::CodeSegDeferDeletes();
  1.1855 +	iHandle = NULL;
  1.1856 +	TAny* h = NULL;
  1.1857 +	TInt r = KErrNone;
  1.1858 +	E32Loader::CodeSegNext(h, find);
  1.1859 +	if(h)
  1.1860 +		{
  1.1861 +		// found...
  1.1862 +		iHandle = h;
  1.1863 +		__IF_DEBUG(Printf("Client process handle %08x",iClientProcessHandle));
  1.1864 +		E32Loader::CodeSegInfo(h, *this);
  1.1865 +		__IF_DEBUG(Printf("Client process handle %08x",iClientProcessHandle));
  1.1866 +		r = E32Loader::CodeSegOpen(h, iClientProcessHandle);
  1.1867 +		}
  1.1868 +	E32Loader::CodeSegEndDeferDeletes();
  1.1869 +
  1.1870 +	if(iHandle && r==KErrNone)
  1.1871 +		{
  1.1872 +		iAlreadyLoaded = ETrue;
  1.1873 +		TUint32 attrMask = (gExecutesInSupervisorMode)?
  1.1874 +			// The loader reads export directories in kernel mode so it can access 
  1.1875 +			// kernel code export directories and global export directories.
  1.1876 +			ECodeSegAttKernel | ECodeSegAttGlobal :
  1.1877 +			// The loader reads export directories in user mode so it can't access 
  1.1878 +			// kernel code export directories but can access global export directories.
  1.1879 +			ECodeSegAttGlobal;
  1.1880 +			
  1.1881 +		if(iAttr & attrMask)
  1.1882 +			{// The export directory is visible to loader so set iExportDirLoad to prevent
  1.1883 +			// the loader from invoking E32Loader::ReadExportDir() to copy the kernel's copy
  1.1884 +			// of the export directory to the loader's heap.
  1.1885 +			iExportDirLoad = iExportDir;
  1.1886 +			}
  1.1887 +		}
  1.1888 +
  1.1889 +	__IF_DEBUG(Printf("<E32Image::CheckAlreadyLoaded %08x, %d",iHandle,r));
  1.1890 +	return r;
  1.1891 +	}
  1.1892 +
  1.1893 +TInt E32Image::Order(const E32Image& aL, const E32Image& aR)
  1.1894 +	{
  1.1895 +	return aL.RootName().CompareF(aR.RootName());
  1.1896 +	}
  1.1897 +
  1.1898 +/******************************************************************************
  1.1899 + * Loader debug code
  1.1900 + ******************************************************************************/
  1.1901 +
  1.1902 +#ifdef _DEBUG
  1.1903 +TInt DoLoaderDebugFunction(const RMessage2& aMsg)
  1.1904 +	{
  1.1905 +	TInt f=aMsg.Int0();
  1.1906 +	__IF_DEBUG(Printf("LdrDbg: %d,%d,%d,%d",f,aMsg.Int1(),aMsg.Int2(),aMsg.Int3()));
  1.1907 +	switch(f)
  1.1908 +		{
  1.1909 +	case ELoaderDebug_SetHeapFail:
  1.1910 +		KernHeapFailCount=aMsg.Int2();
  1.1911 +		LdrHeapFailCount=aMsg.Int1();
  1.1912 +		return KErrNone;
  1.1913 +	case ELoaderDebug_SetRFsFail:
  1.1914 +		RFsErrorCode = aMsg.Int1();
  1.1915 +		RFsFailCount = aMsg.Int2();
  1.1916 +		return KErrNone;
  1.1917 +	default:
  1.1918 +		return KErrNotSupported;
  1.1919 +		}
  1.1920 +	}
  1.1921 +#endif
  1.1922 +
  1.1923 +#ifdef _DEBUG
  1.1924 +void SetupHeapFail(const RMessage2& /*aMsg*/)
  1.1925 +	{
  1.1926 +	__IF_DEBUG(Printf("SetupHeapFail: %d,%d",LdrHeapFailCount,KernHeapFailCount));
  1.1927 +	if (KernHeapFailCount>0)
  1.1928 +		{
  1.1929 +		__KHEAP_SETFAIL(RHeap::EFailNext, KernHeapFailCount);
  1.1930 +		__KHEAP_MARK;
  1.1931 +		HeapFailActive|=1;
  1.1932 +		}
  1.1933 +	if (LdrHeapFailCount>0)
  1.1934 +		{
  1.1935 +		__UHEAP_SETFAIL(RHeap::EFailNext, LdrHeapFailCount);
  1.1936 +		__UHEAP_MARK;
  1.1937 +		HeapFailActive|=2;
  1.1938 +		}
  1.1939 +	ProcessCreated = EFalse;
  1.1940 +	ProcessDestructStat = KRequestPending;
  1.1941 +	ProcessDestructStatPtr = &ProcessDestructStat;
  1.1942 +	}
  1.1943 +
  1.1944 +void EndHeapFailCheck(TInt aError)
  1.1945 +	{
  1.1946 +	__IF_DEBUG(Printf("EndHeapFail: %d",aError));
  1.1947 +	if (aError==KErrNone && ProcessCreated)
  1.1948 +		{
  1.1949 +		User::CancelMiscNotifier(ProcessDestructStat);
  1.1950 +		User::WaitForRequest(ProcessDestructStat);
  1.1951 +		}
  1.1952 +	if (aError!=KErrNone)
  1.1953 +		{
  1.1954 +		if (ProcessCreated)
  1.1955 +			// wait for any partially created process to die
  1.1956 +			User::WaitForRequest(ProcessDestructStat);
  1.1957 +
  1.1958 +		// wait for reaper to run
  1.1959 +		TInt rr;
  1.1960 +		if (CActiveScheduler::RunIfReady(rr,KPriorityVeryHigh))
  1.1961 +			User::WaitForAnyRequest();
  1.1962 +
  1.1963 +		// wait for any async cleanup in the supervisor to finish
  1.1964 +		UserSvr::HalFunction(EHalGroupKernel, EKernelHalSupervisorBarrier, 0, 0);
  1.1965 +
  1.1966 +		if (HeapFailActive&1)
  1.1967 +			{
  1.1968 +			__KHEAP_MARKEND;
  1.1969 +			}
  1.1970 +		if (HeapFailActive&2)
  1.1971 +			{
  1.1972 +			__UHEAP_MARKEND;
  1.1973 +			}
  1.1974 +		}
  1.1975 +	if (HeapFailActive & 3)
  1.1976 +		{
  1.1977 +		__KHEAP_TOTAL_RESET;
  1.1978 +		__UHEAP_TOTAL_RESET;
  1.1979 +		}
  1.1980 +	HeapFailActive=0;
  1.1981 +	ProcessDestructStatPtr = 0;
  1.1982 +	ProcessCreated = EFalse;
  1.1983 +	}
  1.1984 +
  1.1985 +void SetupRFsFail(const RMessage2& /*aMsg*/)
  1.1986 +	{
  1.1987 +	__IF_DEBUG(Printf("SetupRFsFail: %d,%d", RFsErrorCode, RFsFailCount));
  1.1988 +	if (RFsErrorCode!=KErrNone && RFsFailCount>0)
  1.1989 +		{
  1.1990 +		gTheLoaderFs.SetErrorCondition(RFsErrorCode, RFsFailCount);
  1.1991 +		RFsFailActive = ETrue;
  1.1992 +		}
  1.1993 +	}
  1.1994 +
  1.1995 +void EndRFsFailCheck(TInt /*aError*/)
  1.1996 +	{
  1.1997 +	if (RFsFailActive)
  1.1998 +		{
  1.1999 +		gTheLoaderFs.SetErrorCondition(KErrNone);
  1.2000 +		RFsFailActive = EFalse;
  1.2001 +		}
  1.2002 +	}
  1.2003 +
  1.2004 +#endif
  1.2005 +
  1.2006 +#if defined(_DEBUG) || defined(_DEBUG_RELEASE)
  1.2007 +void RLdrReq::Dump(const char* aTitle) const
  1.2008 +	{
  1.2009 +	RDebug::Printf(aTitle);
  1.2010 +	if (iFileName)
  1.2011 +		RDebug::Printf("iFileName=%S", iFileName);
  1.2012 +	if (iPath)
  1.2013 +		RDebug::Printf("iPath=%S", iPath);
  1.2014 +	RDebug::Printf("SID %08x Caps %08x %08x", iSecureId, iPlatSecCaps[1], iPlatSecCaps[0]);
  1.2015 +	const TUint32* uid = (const TUint32*)&iRequestedUids;
  1.2016 +	RDebug::Printf("REQ UIDs %08x %08x %08x REQ VER %08x", uid[0], uid[1], uid[2], iRequestedVersion);
  1.2017 +	iFileNameInfo.Dump();
  1.2018 +	}
  1.2019 +
  1.2020 +void TFileNameInfo::Dump() const
  1.2021 +	{
  1.2022 +	const TDesC8& d = Drive();
  1.2023 +	const TDesC8& p = Path();
  1.2024 +	const TDesC8& b = Base();
  1.2025 +	const TDesC8& v = VerStr();
  1.2026 +	const TDesC8& u = UidStr();
  1.2027 +	const TDesC8& e = Ext();
  1.2028 +	RDebug::Printf("D=%S P=%S B=%S V=%S U=%S E=%S", &d, &p, &b, &v, &u, &e);
  1.2029 +	}
  1.2030 +#endif
  1.2031 +
  1.2032 +#ifdef __TRACE_LOADER_HEAP__
  1.2033 +
  1.2034 +class RTraceHeap : public RAllocator
  1.2035 +	{
  1.2036 +public:
  1.2037 +	virtual TAny* Alloc(TInt aSize);
  1.2038 +	virtual void Free(TAny* aPtr);
  1.2039 +	virtual TAny* ReAlloc(TAny* aPtr, TInt aSize, TInt aMode=0);
  1.2040 +	virtual TInt AllocLen(const TAny* aCell) const;
  1.2041 +	virtual TInt Compress();
  1.2042 +	virtual void Reset();
  1.2043 +	virtual TInt AllocSize(TInt& aTotalAllocSize) const;
  1.2044 +	virtual TInt Available(TInt& aBiggestBlock) const;
  1.2045 +	virtual TInt DebugFunction(TInt aFunc, TAny* a1=NULL, TAny* a2=NULL);
  1.2046 +public:
  1.2047 +	RAllocator* iA;
  1.2048 +	};
  1.2049 +
  1.2050 +void InstallHeapTracer()
  1.2051 +	{
  1.2052 +	RTraceHeap* p = new RTraceHeap;
  1.2053 +	__ASSERT_ALWAYS(p!=NULL, User::Invariant());
  1.2054 +	p->iA = &User::Heap();
  1.2055 +	User::SwitchHeap(p);
  1.2056 +	}
  1.2057 +
  1.2058 +TAny* RTraceHeap::Alloc(TInt aSize)
  1.2059 +	{
  1.2060 +	RDebug::Printf("TH:Alloc(%08x)", aSize);
  1.2061 +	TAny* p = iA->Alloc(aSize);
  1.2062 +	RDebug::Printf("TH:returns %08x", p);
  1.2063 +	return p;
  1.2064 +	}
  1.2065 +
  1.2066 +void RTraceHeap::Free(TAny* aPtr)
  1.2067 +	{
  1.2068 +	RDebug::Printf("TH:Free(%08x)", aPtr);
  1.2069 +	iA->Free(aPtr);
  1.2070 +	}
  1.2071 +
  1.2072 +TAny* RTraceHeap::ReAlloc(TAny* aPtr, TInt aSize, TInt aMode=0)
  1.2073 +	{
  1.2074 +	RDebug::Printf("TH:ReAlloc(%08x,%08x,%x)", aPtr, aSize, aMode);
  1.2075 +	TAny* p = iA->ReAlloc(aPtr,aSize,aMode);
  1.2076 +	RDebug::Printf("TH:returns %08x", p);
  1.2077 +	return p;
  1.2078 +	}
  1.2079 +
  1.2080 +TInt RTraceHeap::AllocLen(const TAny* aCell) const
  1.2081 +	{
  1.2082 +	RDebug::Printf("TH:AllocLen(%08x)", aCell);
  1.2083 +	TInt l = iA->AllocLen(aCell);
  1.2084 +	RDebug::Printf("TH:returns %08x", l);
  1.2085 +	return l;
  1.2086 +	}
  1.2087 +
  1.2088 +TInt RTraceHeap::Compress()
  1.2089 +	{
  1.2090 +	RDebug::Printf("TH:Compress()");
  1.2091 +	TInt l = iA->Compress();
  1.2092 +	RDebug::Printf("TH:returns %08x", l);
  1.2093 +	return l;
  1.2094 +	}
  1.2095 +
  1.2096 +void RTraceHeap::Reset()
  1.2097 +	{
  1.2098 +	RDebug::Printf("TH:Reset()");
  1.2099 +	iA->Reset();
  1.2100 +	}
  1.2101 +
  1.2102 +TInt RTraceHeap::AllocSize(TInt& aTotalAllocSize) const
  1.2103 +	{
  1.2104 +	RDebug::Printf("TH:AllocSize()");
  1.2105 +	TInt s;
  1.2106 +	TInt r = iA->AllocSize(s);
  1.2107 +	RDebug::Printf("TH:returns %08x(%08x)", r, s);
  1.2108 +	aTotalAllocSize = s;
  1.2109 +	return r;
  1.2110 +	}
  1.2111 +
  1.2112 +TInt RTraceHeap::Available(TInt& aBiggestBlock) const
  1.2113 +	{
  1.2114 +	RDebug::Printf("TH:Available()");
  1.2115 +	TInt s;
  1.2116 +	TInt r = iA->Available(s);
  1.2117 +	RDebug::Printf("TH:returns %08x(%08x)", r, s);
  1.2118 +	aBiggestBlock = s;
  1.2119 +	return r;
  1.2120 +	}
  1.2121 +
  1.2122 +TInt RTraceHeap::DebugFunction(TInt aFunc, TAny* a1=NULL, TAny* a2=NULL)
  1.2123 +	{
  1.2124 +	RDebug::Printf("TH:DebugFunction(%d,%08x,%08x)", aFunc, a1, a2);
  1.2125 +	TInt r = iA->DebugFunction(aFunc, a1, a2);
  1.2126 +	RDebug::Printf("TH:returns %08x", r);
  1.2127 +	return r;
  1.2128 +	}
  1.2129 +
  1.2130 +#endif
  1.2131 +
  1.2132 +/* The Reaper - Used to delete binarys in /sys/del/ after they are no longer needed by demand paging */ 
  1.2133 +
  1.2134 +CActiveReaper::CActiveReaper()
  1.2135 +	: CActive(KPriorityVeryHigh)
  1.2136 +	{
  1.2137 +	iLoaderDeletedList=NULL;
  1.2138 +	}
  1.2139 +
  1.2140 +CActiveReaper* CActiveReaper::New()
  1.2141 +	{
  1.2142 +	CActiveReaper *self = new CActiveReaper();
  1.2143 +	if (self!=NULL)
  1.2144 +		self->Construct();
  1.2145 +	return self;
  1.2146 +	}
  1.2147 +
  1.2148 +void CActiveReaper::Construct()
  1.2149 +	{
  1.2150 +	iStatus=KRequestPending;
  1.2151 +	CActiveScheduler::Add(this);
  1.2152 +	E32Loader::NotifyIfCodeSegDestroyed(iStatus);
  1.2153 +	SetActive();
  1.2154 +	}
  1.2155 +
  1.2156 +/*
  1.2157 +Initialises the \sys\del\ directory, where files can be moved too, on deletion.
  1.2158 +If the directory exists, then it is emptied.
  1.2159 +*/
  1.2160 +
  1.2161 +void CActiveReaper::InitDelDir()
  1.2162 +	{
  1.2163 +	TDriveList driveList;
  1.2164 +	TDriveInfo driveInfo;
  1.2165 +	CDir* dir=NULL;
  1.2166 +	TFileName fileName;
  1.2167 +	TInt i;
  1.2168 +	TBuf<KPathDelLength> drivePath(KPathDel);
  1.2169 +	TInt r = gTheLoaderFs.DriveList(driveList);
  1.2170 +	if (r!=KErrNone)
  1.2171 +		return;
  1.2172 +	TChar ch;
  1.2173 +	for (TInt drvNum=0; drvNum<KMaxDrives; ++drvNum)
  1.2174 +		{
  1.2175 +	    if(!driveList[drvNum])
  1.2176 +	        continue;   //-- skip nonexistent drive
  1.2177 +	    r = gTheLoaderFs.Drive(driveInfo, drvNum);
  1.2178 +	    if ((r==KErrNone) && (driveInfo.iDriveAtt & KDriveAttPageable) && !(driveInfo.iMediaAtt & KMediaAttWriteProtected))
  1.2179 +			{
  1.2180 +			gTheLoaderFs.DriveToChar(drvNum, ch);
  1.2181 +			drivePath[0]=(TText)ch;
  1.2182 +			r = gTheLoaderFs.GetDir(drivePath,KEntryAttMatchExclude | KEntryAttDir ,ESortNone,dir);
  1.2183 +			if (r==KErrNone)
  1.2184 +				{
  1.2185 +				for (i=dir->Count()-1;i>=0;i--)
  1.2186 +					{
  1.2187 +					fileName = drivePath;
  1.2188 +					fileName.Append((*dir)[i].iName);
  1.2189 +					r = gTheLoaderFs.SetAtt(fileName,0,KEntryAttReadOnly|KEntryAttSystem);
  1.2190 +					r = gTheLoaderFs.Delete(fileName);
  1.2191 +					}						
  1.2192 +				delete dir;
  1.2193 +				}
  1.2194 +			}
  1.2195 +		}
  1.2196 +	}
  1.2197 +
  1.2198 +
  1.2199 +void CActiveReaper::RunL()
  1.2200 +	{   
  1.2201 +	
  1.2202 +	TCodeSegLoaderCookie cookie;
  1.2203 +	TInt r;
  1.2204 +
  1.2205 +	TLoaderDeletedList* link;
  1.2206 +	TLoaderDeletedList* prev;
  1.2207 +
  1.2208 +	iStatus=KRequestPending;
  1.2209 +	E32Loader::NotifyIfCodeSegDestroyed(iStatus);
  1.2210 +	SetActive();
  1.2211 +	FOREVER
  1.2212 +		{
  1.2213 +		r=E32Loader::GetDestroyedCodeSegInfo(cookie);
  1.2214 +		if (r!=KErrNone)
  1.2215 +			break;
  1.2216 +		r = cookie.iFileClamp.Close(gTheLoaderFs);
  1.2217 +		// See if its on our list.
  1.2218 +		if (r==KErrNone) 
  1.2219 +			{
  1.2220 +			link = iLoaderDeletedList;
  1.2221 +			prev= (TLoaderDeletedList*) &iLoaderDeletedList;
  1.2222 +
  1.2223 +			while (link!=NULL)
  1.2224 +				{
  1.2225 +				if ((link->iStartBlock==cookie.iStartAddress) && (link->iDriveNumber==cookie.iDriveNumber))
  1.2226 +					{
  1.2227 +					gTheLoaderFs.Delete(*link->iFileName);
  1.2228 +					// Ignore error from file delete operation. If it does fail then the
  1.2229 +					// file will just have to sit around until it is cleaned up on the next reboot.
  1.2230 +
  1.2231 +					// Remove from our list.
  1.2232 +					prev->iNext=link->iNext;
  1.2233 +					delete link;
  1.2234 +					link = prev->iNext;
  1.2235 +					}
  1.2236 +				else
  1.2237 +					{
  1.2238 +					prev = link;
  1.2239 +					link = link->iNext;
  1.2240 +					}
  1.2241 +				}// while
  1.2242 +			} // if unclamp ok
  1.2243 +		} //Forever
  1.2244 +	}
  1.2245 +
  1.2246 +void CActiveReaper::DoCancel(){};
  1.2247 +
  1.2248 +CActiveReaper::~CActiveReaper() {}
  1.2249 +
  1.2250 +void CActiveReaper::AddDeleted(TLoaderDeletedList* aLink)
  1.2251 +	{
  1.2252 +	aLink->iNext=iLoaderDeletedList;
  1.2253 +	iLoaderDeletedList = aLink;
  1.2254 +	}
  1.2255 +
  1.2256 +/* Slotted allocator - used to store iFileData from hashchecked images */
  1.2257 +
  1.2258 +TInt CSlottedChunkAllocator::Construct()
  1.2259 +	{
  1.2260 +	TInt r = iChunk.CreateDisconnectedLocal(0, 0, KSlotSize * KSlots);
  1.2261 +	if (r == KErrNone)
  1.2262 +		iBase = iChunk.Base();
  1.2263 +	return r;
  1.2264 +	}
  1.2265 +
  1.2266 +TAny* CSlottedChunkAllocator::Alloc(TUint aSize)
  1.2267 +	{
  1.2268 +	if (aSize == 0 || aSize > KSlotSize)
  1.2269 +		return NULL;
  1.2270 +
  1.2271 +	for (TInt i=0; i<KSlots; ++i)
  1.2272 +		if (!iUsed[i])
  1.2273 +			{
  1.2274 +			if (iChunk.Commit(i * KSlotSize, aSize) == KErrNone)
  1.2275 +				{
  1.2276 +				iUsed[i] = aSize;
  1.2277 +				return iBase + i * KSlotSize;
  1.2278 +				}
  1.2279 +			else
  1.2280 +				return NULL;
  1.2281 +			}
  1.2282 +
  1.2283 +	return NULL;
  1.2284 +	}
  1.2285 +
  1.2286 +void CSlottedChunkAllocator::Free(TAny* aPtr)
  1.2287 +	{
  1.2288 +	if (!aPtr)
  1.2289 +		return;
  1.2290 +
  1.2291 +	TInt offset = ((TUint8*)aPtr) - iBase;
  1.2292 +	TInt slot = offset / KSlotSize;
  1.2293 +	__ASSERT_DEBUG(offset % KSlotSize == 0 && slot >= 0 && slot < KSlots, Fault(ELdrFileDataAllocError));
  1.2294 +#ifdef _DEBUG
  1.2295 +	TInt r = 
  1.2296 +#endif
  1.2297 +	iChunk.Decommit(offset, iUsed[slot]);
  1.2298 +	__ASSERT_DEBUG(r==KErrNone, Fault(ELdrFileDataAllocError));
  1.2299 +	iUsed[slot] = 0;
  1.2300 +	}