os/kernelhwsrv/userlibandfileserver/fileserver/sfat/sl_mnt.cpp
changeset 0 bde4ae8d615e
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/os/kernelhwsrv/userlibandfileserver/fileserver/sfat/sl_mnt.cpp	Fri Jun 15 03:10:57 2012 +0200
     1.3 @@ -0,0 +1,4575 @@
     1.4 +// Copyright (c) 1996-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 +// Common CFatMountCB code for both EFAT.FSY and EFAT32.fsy
    1.18 +//
    1.19 +//
    1.20 +
    1.21 +/**
    1.22 + @file
    1.23 + @internalTechnology
    1.24 +*/
    1.25 +
    1.26 +//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    1.27 +//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    1.28 +//!!
    1.29 +//!! WARNING!! DO NOT edit this file !! '\sfat' component is obsolete and is not being used. '\sfat32'replaces it
    1.30 +//!!
    1.31 +//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    1.32 +//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    1.33 +
    1.34 +
    1.35 +#include "sl_std.h"
    1.36 +#include "sl_cache.h"
    1.37 +#include "sl_leafdir_cache.h"
    1.38 +#include "sl_dir_cache.h"
    1.39 +#include "sl_scandrv.h"
    1.40 +#include <hal.h>
    1.41 +
    1.42 +TShortName DoGenerateShortNameL(const TDesC& aLongName,TInt& aNum,TBool aUseTildeSelectively);
    1.43 +
    1.44 +static void  MarkClusterVisited(RBitVector& aFatBitVec, TUint32 aCluster);
    1.45 +static TBool IsClusterVisited(const RBitVector& aFatBitVec, TUint32 aCluster);
    1.46 +static TInt  NextUnvisitedCluster(const RBitVector& aFatBitVec, TUint32 aCluster);
    1.47 +
    1.48 +//-----------------------------------------------------------------------------------------
    1.49 +
    1.50 +TFatVolParam::TFatVolParam()
    1.51 +    {
    1.52 +    Mem::FillZ(this, sizeof(TFatVolParam));
    1.53 +    }
    1.54 +
    1.55 +/**
    1.56 +    populate the object with the values from the boot sector.
    1.57 +    @param aBootSector a reference to the valid boots sector
    1.58 +*/
    1.59 +void TFatVolParam::Populate(const TFatBootSector& aBootSector)
    1.60 +    {
    1.61 +    ASSERT(aBootSector.IsValid());
    1.62 +
    1.63 +    iSectorsPerCluster = aBootSector.SectorsPerCluster();
    1.64 +    iSectorSizeLog2    = Log2(aBootSector.BytesPerSector());
    1.65 +    iClusterSizeLog2   = iSectorSizeLog2+Log2(iSectorsPerCluster);
    1.66 +    iFirstFatSector    = aBootSector.FirstFatSector();
    1.67 +    iNumberOfFats      = aBootSector.NumberOfFats();
    1.68 +    iFatSizeInBytes    = aBootSector.TotalFatSectors()*aBootSector.BytesPerSector();
    1.69 +    iTotalSectors      = aBootSector.VolumeTotalSectorNumber();
    1.70 +    iRootClusterNum    = aBootSector.RootClusterNum(); //-- will be 0 for FAT12/16
    1.71 +
    1.72 +    iRootDirectorySector = aBootSector.RootDirStartSector();
    1.73 +    iRootDirEnd = (iRootDirectorySector + aBootSector.RootDirSectors()) << SectorSizeLog2(); //-- doesn't matter for FAT32
    1.74 +
    1.75 +    //-- get main and backup FSInfo sectors position, these fields will be 0 for FAT12/16
    1.76 +    iFSInfoSectorNum   = aBootSector.FSInfoSectorNum();
    1.77 +    iBkFSInfoSectorNum = (TUint16)(aBootSector.BkBootRecSector()+iFSInfoSectorNum); //-- Bk FSInfo sector must follow the Bk boot sector
    1.78 +    }
    1.79 +
    1.80 +TBool TFatVolParam::operator==(const TFatVolParam& aRhs) const
    1.81 +    {
    1.82 +    ASSERT(&aRhs != this);
    1.83 +    if(&aRhs == this)
    1.84 +        return ETrue; //-- comparing with itself
    1.85 +
    1.86 +    return (Mem::Compare((TUint8*)this, sizeof(TFatVolParam), (TUint8*)&aRhs, sizeof(TFatVolParam)) == 0);
    1.87 +    }
    1.88 +
    1.89 +
    1.90 +//-----------------------------------------------------------------------------------------
    1.91 +
    1.92 +
    1.93 +CFatMountCB::CFatMountCB()
    1.94 +    {
    1.95 +    __PRINT2(_L("CFatMountCB::CFatMountCB() 0x%x, %S"), this, &KThisFsyName);
    1.96 +    iFatType = EInvalid;
    1.97 +    iState   = ENotMounted;
    1.98 +    DBG_STATEMENT(iCBRecFlag = 0); //-- debug flag only
    1.99 +    }
   1.100 +
   1.101 +CFatMountCB::~CFatMountCB()
   1.102 +    {
   1.103 +    __PRINT1(_L("#-CFatMountCB::~CFatMountCB() 0x%x"), this);
   1.104 +
   1.105 +    DoDismount();
   1.106 +
   1.107 +    delete iNotifier;
   1.108 +    delete iFatTable;
   1.109 +    delete iRawDisk;
   1.110 +    delete iLeafDirCache;
   1.111 +
   1.112 +    }
   1.113 +
   1.114 +//-----------------------------------------------------------------------------------------
   1.115 +
   1.116 +CFatMountCB* CFatMountCB::NewL()
   1.117 +    {
   1.118 +    CFatMountCB* pSelf = new(ELeave) CFatMountCB;
   1.119 +
   1.120 +    CleanupStack::PushL(pSelf);
   1.121 +    pSelf->ConstructL();
   1.122 +    CleanupStack::Pop(pSelf);
   1.123 +
   1.124 +    return pSelf;
   1.125 +    }
   1.126 +
   1.127 +// second-stage constructor
   1.128 +void CFatMountCB::ConstructL()
   1.129 +{
   1.130 +    //-- create Notifier
   1.131 +    iNotifier = CAsyncNotifier::New();
   1.132 +    if( !iNotifier )
   1.133 +        {
   1.134 +        Close();
   1.135 +        User::Leave(KErrNoMemory);
   1.136 +        }
   1.137 +
   1.138 +    iNotifier->SetMount(this);
   1.139 +    }
   1.140 +
   1.141 +//-------------------------------------------------------------------------------------------------------------------
   1.142 +
   1.143 +/**
   1.144 +Implementation of CMountCB::FileSystemClusterSize(). Returns cluster size of this mount.
   1.145 +@return Cluster size value if successful; otherwise KErrNotReady if the mount is not ready.
   1.146 +@see CMountCB::FileSystemClusterSize()
   1.147 +*/
   1.148 +TInt CFatMountCB::ClusterSize() const
   1.149 +    {
   1.150 +    if (ClusterSizeLog2())
   1.151 +        return (1 << ClusterSizeLog2());
   1.152 +
   1.153 +    return KErrNotReady;
   1.154 +    }
   1.155 +
   1.156 +//-------------------------------------------------------------------------------------------------------------------
   1.157 +
   1.158 +/**
   1.159 +    @leave KErrAccessDenied if the mount is read-only
   1.160 +*/
   1.161 +void CFatMountCB::CheckWritableL() const
   1.162 +    {
   1.163 +    if(ReadOnly())
   1.164 +        {
   1.165 +        __PRINT(_L("CFatMountCB is RO!"));
   1.166 +        User::Leave(KErrAccessDenied);
   1.167 +        }
   1.168 +    }
   1.169 +
   1.170 +/**
   1.171 +    @leave KErrCorrupt if the mount is in inconsistent state i.e high-level file and directory  operations can not be performed
   1.172 +*/
   1.173 +void CFatMountCB::CheckStateConsistentL() const
   1.174 +    {
   1.175 +    if(!ConsistentState())
   1.176 +        {
   1.177 +        __PRINT(_L("CFatMountCB state is inconsistent !"));
   1.178 +        User::Leave(KErrCorrupt);
   1.179 +        }
   1.180 +    }
   1.181 +
   1.182 +
   1.183 +//-------------------------------------------------------------------------------------------------------------------
   1.184 +/**
   1.185 +    Helper Method. Check if the parameters of the volume being remounted are the same as current ones.
   1.186 +    @return ETrue if volume parameters remained same.
   1.187 +*/
   1.188 +TBool CFatMountCB::CheckVolumeTheSame()
   1.189 +{
   1.190 +    //-- initialise local drive
   1.191 +    TInt nRes =InitLocalDrive();
   1.192 +    if(nRes != KErrNone)
   1.193 +        return EFalse;
   1.194 +
   1.195 +    //-- read the boot sector or its backup copy if the main is damaged. It will aslo validate it.
   1.196 +    TFatBootSector bootSector;
   1.197 +    nRes = ReadBootSector(bootSector, iRamDrive);
   1.198 +    if(nRes != KErrNone)
   1.199 +        return EFalse;
   1.200 +
   1.201 +    //-- 1. check volume Uid
   1.202 +    if(iUniqueID != bootSector.UniqueID())
   1.203 +        return EFalse;
   1.204 +
   1.205 +    //-- check volume parameters, they must remain the same
   1.206 +    TFatVolParam volParam;
   1.207 +    volParam.Populate(bootSector);
   1.208 +
   1.209 +    if(!(volParam == iVolParam))
   1.210 +        return EFalse;
   1.211 +
   1.212 +
   1.213 +    return ETrue;
   1.214 +
   1.215 +}
   1.216 +//-------------------------------------------------------------------------------------------------------------------
   1.217 +
   1.218 +/**
   1.219 +    Helper Method. Check if the parameters of the volume being remounted are the same as current ones.
   1.220 +    If they are, re-initialises the mount.
   1.221 +*/
   1.222 +void CFatMountCB::DoReMountL()
   1.223 +    {
   1.224 +
   1.225 +    if(!CheckVolumeTheSame())
   1.226 +        User::Leave(KErrGeneral);
   1.227 +
   1.228 +    //-- get drive capabilities
   1.229 +    TLocalDriveCapsV2Buf capsBuf;
   1.230 +    User::LeaveIfError(LocalDrive()->Caps(capsBuf));
   1.231 +
   1.232 +    //-- the volume is the same as it was on original MountL()
   1.233 +    //-- we need to re-initialize for the case when the media was removed, FAT or directory structure changed on other device and the media returned back.
   1.234 +    DoDismount();
   1.235 +
   1.236 +    SetState(EMounting);
   1.237 +
   1.238 +    InitializeL(capsBuf(), ETrue); //-- forcedly disable FSInfo usage. This will lead to FAT free clusters re-counting.
   1.239 +
   1.240 +    }
   1.241 +
   1.242 +//-------------------------------------------------------------------------------------------------------------------
   1.243 +
   1.244 +/**
   1.245 +    Try remount this Fat volume. Checks if the volume parameters remained the same as on original MountL() call, and
   1.246 +    if they are, re-initialises the mount. This includes resetting all caches.
   1.247 +    ! Do not call this method from TFatDriveInterface methods, like citical and non-critical notifiers ! This can lead to the
   1.248 +    recursive loops and undefined behaviour.
   1.249 +
   1.250 +    @return KErrNone if the remount was OK
   1.251 +            system-wide error code otherwise
   1.252 +*/
   1.253 +TInt CFatMountCB::ReMount()
   1.254 +    {
   1.255 +    __PRINT2(_L("CFatMountCB::ReMount(), drv:%d, curr state:%d"), DriveNumber(), State());
   1.256 +
   1.257 +    const TFatMntState currState = State();
   1.258 +
   1.259 +    //-- analyse the mount state and find out if we can remount at all.
   1.260 +    switch(currState)
   1.261 +        {
   1.262 +        case ENotMounted:
   1.263 +        __PRINT(_L("CFatMountCB::ReMount() Invalid mount state!"));
   1.264 +
   1.265 +        ASSERT(0);
   1.266 +        return KErrGeneral;
   1.267 +
   1.268 +        //-- correct state, proceed to remount
   1.269 +        default:
   1.270 +        break;
   1.271 +    }
   1.272 +
   1.273 +    //-- there are 2 options here:
   1.274 +    //-- 1. normally initialised mount had been forcedly dismounted (it can optionally have objects opened on it)
   1.275 +    //--    in this case the DoReMountL() will succeed and everything will be fine, the objects will be accessible afterwards
   1.276 +    //-- 2. the mount hasn't been initialised at all (it does not have for example, FAT table created etc.)
   1.277 +    //--    in this case we may need to fake the success. This can only happen on forced mount by CFormatCB
   1.278 +    TInt nRes;
   1.279 +    TRAP(nRes, DoReMountL());
   1.280 +
   1.281 +    if(nRes != KErrNone)
   1.282 +        {
   1.283 +        //-- note that the mount may be here left in inconsistent state (EMounting)
   1.284 +        //-- if DoReMountL() fails. This is OK, because we can not make any valid read/write operations in such a state and
   1.285 +        //-- the drive must be dismounted and mounted again. File Server's TDrive shall do this.
   1.286 +        __PRINT1(_L("CFatMountCB::ReMount() failed! code:%d"), nRes);
   1.287 +
   1.288 +        //-- If we are in the EInit_Forced state, it means that we are trying to remount the volume that has been formatted.
   1.289 +        //-- scenario: On formatting, if we can't read a bootsector, new _empty_ object of the CFatMountCB is created and
   1.290 +        //-- it is used for performing a format. If the format has finished, but RFormat isn't closed yet and we try to access the volume,
   1.291 +        //-- we will get here, because all members of the constructed mount will be zeroes.
   1.292 +        if(currState == EInit_Forced)
   1.293 +            {
   1.294 +            __PRINT(_L("CFatMountCB::ReMount() simulating normal remount!"));
   1.295 +            SetState(currState);
   1.296 +            return KErrNone;
   1.297 +            }
   1.298 +
   1.299 +        return nRes;
   1.300 +        }
   1.301 +
   1.302 +    __PRINT1(_L("CFatMountCB::ReMount() Completed drv:%d"), DriveNumber());
   1.303 +    SetState(EInit_R);
   1.304 +    return nRes;
   1.305 +    }
   1.306 +
   1.307 +//-------------------------------------------------------------------------------------------------------------------
   1.308 +
   1.309 +/**
   1.310 +    Reset the last leaf dir or invalidate leaf dir cache if leaf dir cache is
   1.311 +    instantiated.
   1.312 +*/
   1.313 +
   1.314 +void CFatMountCB::InvalidateLeafDirCache()
   1.315 +    {
   1.316 +    if (iLeafDirCache)
   1.317 +        {
   1.318 +        iLeafDirCache->Reset();
   1.319 +        }
   1.320 +    else
   1.321 +        {
   1.322 +        User::Free(iLastLeafDir);
   1.323 +        iLastLeafDir=NULL;
   1.324 +        }
   1.325 +    }
   1.326 +
   1.327 +//-------------------------------------------------------------------------------------------------------------------
   1.328 +
   1.329 +/**
   1.330 +    Delete mount's caches
   1.331 +    Moves CFatMountCB into ENotMounted state immediately.
   1.332 +*/
   1.333 +void CFatMountCB::DoDismount()
   1.334 +    {
   1.335 +    __PRINT1(_L("CFatMountCB::DoDismount() drv:%d"), DriveNumber());
   1.336 +
   1.337 +    //-- try to flush and destroy FAT cache
   1.338 +    if (iFatTable)
   1.339 +        {
   1.340 +        if(!ConsistentState() || ReadOnly())
   1.341 +            {//-- the mount state is inconsistent, so the data can't be flushed. Ignore dirty cache either.
   1.342 +            iFatTable->Dismount(ETrue);
   1.343 +            }
   1.344 +        else
   1.345 +            {//-- Try to flush the FAT - if this fails there's not much we can do
   1.346 +            TRAPD(r, iFatTable->FlushL());
   1.347 +            iFatTable->Dismount(r != KErrNone); //-- ignore dirty data if we failed to flush the cache
   1.348 +            }
   1.349 +        }
   1.350 +
   1.351 +    //-- destroy leafdir name cache, this cache will be re-created while mounting or re-mounting
   1.352 +    //-- see CFatMountCB::InitializeL()
   1.353 +    delete iLeafDirCache;
   1.354 +    iLeafDirCache = NULL;
   1.355 +
   1.356 +    //-- destroy directory cache, this cache will be re-created while mounting or re-mounting
   1.357 +    //-- see CFatMountCB::InitializeL()
   1.358 +    delete iRawDisk;
   1.359 +    iRawDisk = NULL;
   1.360 +
   1.361 +    //-- Set mount state to "Dismounted". Which means that there might be no caches, but the mount is alive,
   1.362 +    //-- i.e. iFatTable & iRawDisk are valid
   1.363 +    SetState(EDismounted);
   1.364 +    }
   1.365 +
   1.366 +//-----------------------------------------------------------------------------------------
   1.367 +
   1.368 +/** old implementation */
   1.369 +void CFatMountCB::FinaliseMountL()
   1.370 +    {
   1.371 +    FinaliseMountL(RFs::EFinal_RW);
   1.372 +    }
   1.373 +
   1.374 +//-----------------------------------------------------------------------------------------
   1.375 +/**
   1.376 +    Dismount the CFatMountCB and the drive.
   1.377 +    called from TDrive::Dismount().
   1.378 +*/
   1.379 +void CFatMountCB::Dismounted()
   1.380 +    {
   1.381 +    __PRINT1(_L("CFatMountCB::Dismounted() drv:%d"), DriveNumber());
   1.382 +
   1.383 +    //-- n.b. it is no safe to do a kind of filnalisatin work here that implies accessing the media.
   1.384 +    //-- this method may be called after the media change occured from the TDrive::Dismount(). It means
   1.385 +    //-- that if we try to write some data here, they could be written into a different medium, if it had been
   1.386 +    //-- physically changed.
   1.387 +
   1.388 +    const TFatMntState prevState = State();
   1.389 +
   1.390 +    DoDismount(); //-- it will change mount state to EDismounted
   1.391 +    DismountedLocalDrive();
   1.392 +
   1.393 +    //-- check if the previous state was EInit_Forced, which means that this method was called
   1.394 +    //-- on the mount that might not be alive (no valid iFatTable & iRawDisk).
   1.395 +    //-- This can happen only during format operation on non-mounted previously volume.
   1.396 +    //-- this EInit_Forced state must be processed separately, see ::Remount()
   1.397 +    if(prevState == EInit_Forced)
   1.398 +        SetState(EInit_Forced);
   1.399 +
   1.400 +    }
   1.401 +
   1.402 +
   1.403 +//-------------------------------------------------------------------------------------------------------------------
   1.404 +
   1.405 +/**
   1.406 +    Find out if the mount is finalised.
   1.407 +    @param  aFinalised on exit will be ETrue if the maunt is finalised, EFalse otherwise.
   1.408 +    @return standard error codes.
   1.409 +*/
   1.410 +TInt CFatMountCB::IsFinalised(TBool& aFinalised)
   1.411 +    {
   1.412 +    switch(State())
   1.413 +        {
   1.414 +        case EFinalised: //-- already explicitly finalised
   1.415 +            aFinalised = ETrue;
   1.416 +        return KErrNone;
   1.417 +
   1.418 +        case EInit_W: //-- the volume had been written
   1.419 +            aFinalised = EFalse;
   1.420 +        return KErrNone;
   1.421 +
   1.422 +        default: //-- it depends on the state
   1.423 +        break;
   1.424 +        }
   1.425 +
   1.426 +    //-- find out if the volume is _physically_ finalised.
   1.427 +    //-- It can be in the state EInit_R, but finalised before mounting
   1.428 +    if(!VolCleanFlagSupported())
   1.429 +        return KErrNotSupported;
   1.430 +
   1.431 +    TInt nRes = KErrNone;
   1.432 +    TRAP(nRes, aFinalised = VolumeCleanL());
   1.433 +
   1.434 +    return nRes;
   1.435 +    }
   1.436 +
   1.437 +//-------------------------------------------------------------------------------------------------------------------
   1.438 +
   1.439 +/**
   1.440 +    @return ETrue if the mount is in consistent state i.e. normally mounted.
   1.441 +    See TFatMntState enum for more detail.
   1.442 +*/
   1.443 +TBool CFatMountCB::ConsistentState() const
   1.444 +    {
   1.445 +    return (iState==EInit_R) || (iState==EInit_W) || (iState == EFinalised);
   1.446 +    }
   1.447 +
   1.448 +//-------------------------------------------------------------------------------------------------------------------
   1.449 +
   1.450 +/**
   1.451 +    Open CFatMountCB for write. I.e. perform some actions on the first write attempt.
   1.452 +    This is a callback from TFatDriveInterface.
   1.453 +    @return System wide error code.
   1.454 +*/
   1.455 +TInt CFatMountCB::OpenMountForWrite()
   1.456 +    {
   1.457 +    if(State() == EInit_W)
   1.458 +        return KErrNone; //-- nothing to do, the mount is already opened for write
   1.459 +
   1.460 +    __PRINT1(_L("#- CFatMountCB::OpenMountForWrite() drv:%d\n"),DriveNumber());
   1.461 +
   1.462 +    ASSERT(State() == EInit_R || State() == EFinalised);
   1.463 +
   1.464 +    //-- Check possible recursion. This method must not be called recursively. SetVolumeCleanL() works through direct disc access and
   1.465 +    //-- can not call TFatDriveInterface methods that call this method etc.
   1.466 +    ASSERT(iCBRecFlag == 0);
   1.467 +    DBG_STATEMENT(iCBRecFlag = 1); //-- set recursion check flag
   1.468 +
   1.469 +    //-- do here some "opening" work, like marking volme as dirty
   1.470 +    //-- be careful here, as soon as this is a callback from TFatDriveInterface, writing via TFatDriveInterface may cause some unwanted recursion.
   1.471 +
   1.472 +    //-- mark the volume as dirty
   1.473 +    TInt nRes=KErrNone;
   1.474 +    TRAP(nRes, SetVolumeCleanL(EFalse));
   1.475 +    if(nRes == KErrNone)
   1.476 +        {
   1.477 +        SetState(EInit_W);
   1.478 +        }
   1.479 +
   1.480 +    DBG_STATEMENT(iCBRecFlag = 0); //-- reset recursion check flag
   1.481 +
   1.482 +    return nRes;
   1.483 +
   1.484 +    }
   1.485 +
   1.486 +//-------------------------------------------------------------------------------------------------------------------
   1.487 +
   1.488 +/**
   1.489 +    Unfinalise the mount, reset "VolumeCleanShutDown" flag and change the state if necessarily.
   1.490 +*/
   1.491 +void CFatMountCB::UnFinaliseMountL()
   1.492 +    {
   1.493 +    switch(State())
   1.494 +        {
   1.495 +        case EFinalised:
   1.496 +        case EInit_R:
   1.497 +            SetVolumeCleanL(EFalse); //-- the mount, mark volume "dirty"
   1.498 +            SetState(EInit_R);
   1.499 +        return;
   1.500 +
   1.501 +        case EInit_W:
   1.502 +        return; //-- nothing to do
   1.503 +
   1.504 +        default:
   1.505 +        //-- other mount states are inconsistent; can't perform this operation
   1.506 +        User::Leave(KErrAbort);
   1.507 +        break;
   1.508 +
   1.509 +        }
   1.510 +
   1.511 +    }
   1.512 +
   1.513 +//-------------------------------------------------------------------------------------------------------------------
   1.514 +
   1.515 +/**
   1.516 +    Finalise the mount.
   1.517 +
   1.518 +    @param  aOperation  describes finalisation operation ,see RFs::TFinaliseDrvMode
   1.519 +    @param  aParam1     not used, for future expansion
   1.520 +    @param  aParam2     not used, for future expansion
   1.521 +
   1.522 +    @leave  System wide error code. particular cases:
   1.523 +            KErrArgument invalid arguments
   1.524 +            KErrInUse    if the volume has opened objects (files, directories etc)
   1.525 +            KErrCorrupt  if the volume is corrupt
   1.526 +
   1.527 +*/
   1.528 +void CFatMountCB::FinaliseMountL(TInt aOperation, TAny* /*aParam1*/, TAny* /*aParam2*/)
   1.529 +    {
   1.530 +    __PRINT2(_L("#- CFatMountCB::FinaliseMountL() op:%d, drv:%d"), aOperation, DriveNumber());
   1.531 +
   1.532 +    switch(aOperation)
   1.533 +        {
   1.534 +        case RFs::EFinal_RW:
   1.535 +        case RFs::EFinal_RO:
   1.536 +        break;
   1.537 +
   1.538 +        case RFs::EForceUnfinalise:
   1.539 +            UnFinaliseMountL();
   1.540 +        return;
   1.541 +
   1.542 +        default:
   1.543 +            __PRINT1(_L("#- CFatMountCB::FinaliseMountL() unexpected operation!:%d"), aOperation);
   1.544 +            ASSERT(0);
   1.545 +            User::Leave(KErrArgument);
   1.546 +        return;
   1.547 +        }
   1.548 +
   1.549 +    //-- mount finalisation work
   1.550 +
   1.551 +    ASSERT(aOperation == RFs::EFinal_RW || aOperation == RFs::EFinal_RO);
   1.552 +
   1.553 +    if(State() == EFinalised)
   1.554 +        {//-- the mount is already finalised. All we can do is to set it to RO mode
   1.555 +        if(ReadOnly() && aOperation == RFs::EFinal_RW)
   1.556 +            {
   1.557 +            User::Leave(KErrAccessDenied); //-- can't override RO flag
   1.558 +            }
   1.559 +
   1.560 +        (void)LocalDrive()->Finalise(ETrue);
   1.561 +
   1.562 +        if(aOperation == RFs::EFinal_RO)
   1.563 +            {
   1.564 +            SetReadOnly(ETrue);
   1.565 +            return;
   1.566 +            }
   1.567 +
   1.568 +        return;
   1.569 +        }
   1.570 +
   1.571 +    if(LockStatus() != 0)
   1.572 +        {//-- can't finalise the volume if it has opened objects and not in the consistent state.
   1.573 +         //-- Theoretically, we can finalise the mount if we have files opened only for read, but at present,
   1.574 +         //-- it's impossible to detect such situation.
   1.575 +        User::Leave(KErrInUse);
   1.576 +        }
   1.577 +
   1.578 +    if(State() != EInit_R && State() != EInit_W)
   1.579 +        {//-- can't finalise the mount because it can be in an inconsistent state; e.g. corrupt.
   1.580 +        __PRINT1(_L("#- CFatMountCB::FinaliseMountL() Invalid mount State: %d"),State());
   1.581 +        User::Leave(KErrCorrupt);
   1.582 +        }
   1.583 +
   1.584 +    //-- flush FAT cache
   1.585 +    FAT().FlushL();
   1.586 +
   1.587 +    //-- for FAT32 we may need to update data in FSInfo sectors
   1.588 +    if(Is32BitFat())
   1.589 +        {
   1.590 +        if(FAT().ConsistentState())
   1.591 +            {//-- FAT table state is consistent and the number of free clusters is known.
   1.592 +             //-- Do it disregarding the mount state, it may help in the situation when 2 copies of the FSInfo are different for some reason.
   1.593 +            DoUpdateFSInfoSectorsL(EFalse);
   1.594 +            }
   1.595 +            else
   1.596 +            {//-- FAT table state is inconsistent, the most probable case here: background scan for free clusters is still working.
   1.597 +             //-- in this case we can't put corect values into the FSInfo.
   1.598 +            if(State() == EInit_W)
   1.599 +                {//-- bad situation: free clusters may be being counted and someone has already written something on the volume at the same time.
   1.600 +                 //-- we do not know the exact number of free clustes and can't wait until scan finishes. Invalidate FSInfo.
   1.601 +                __PRINT(_L("#- CFatMountCB::FinaliseMountL() invalidating FSInfo"));
   1.602 +                DoUpdateFSInfoSectorsL(ETrue);
   1.603 +                }
   1.604 +             else
   1.605 +                {//-- no changes on the volume, just do not update FSInfo
   1.606 +                __PRINT(_L("#- CFatMountCB::FinaliseMountL() FAT state inconsistent; FSInfo isn't updated"));
   1.607 +                }
   1.608 +
   1.609 +            }//if(FAT().ConsistentState())
   1.610 +
   1.611 +        }//if(Is32BitFat())
   1.612 +
   1.613 +
   1.614 +
   1.615 +    //-- mark the volume as clean
   1.616 +    SetVolumeCleanL(ETrue);
   1.617 +
   1.618 +    //-- finally, put the volume into RO mode if required
   1.619 +    if(aOperation == RFs::EFinal_RO)
   1.620 +        SetReadOnly(ETrue);
   1.621 +
   1.622 +    SetState(EFinalised);
   1.623 +    }
   1.624 +
   1.625 +
   1.626 +//-------------------------------------------------------------------------------------------------------------------
   1.627 +
   1.628 +/**
   1.629 +@return ETrue if "VolumeClean" flag is supported i.e. this is not FAT12
   1.630 +*/
   1.631 +TBool CFatMountCB::VolCleanFlagSupported() const
   1.632 +    {
   1.633 +        const TFatType fatType=FatType();
   1.634 +
   1.635 +        ASSERT(fatType == EFat12 || fatType == EFat16 || fatType == EFat32);
   1.636 +        return (fatType != EFat12);
   1.637 +    }
   1.638 +
   1.639 +//-----------------------------------------------------------------------------------------
   1.640 +
   1.641 +
   1.642 +/**
   1.643 +    Obtain the volume information.
   1.644 +    All information except iSize and iFree has been added by TDrive::Volume().
   1.645 +
   1.646 +    @param  aVolume on return will contain iSize & iFree fields filled with actual data.
   1.647 +*/
   1.648 +void CFatMountCB::VolumeL(TVolumeInfo& aVolume) const
   1.649 +    {
   1.650 +
   1.651 +    //-- if true, this operation will be synchronous, i.e the client will be suspended until FAT32 scanning thread finishes, if running.
   1.652 +    //-- the information if this operation is synchronous or not can be passed by client in TVolumeInfo::iFileCacheFlags field.
   1.653 +    //-- if the client sets aVolume.iVolSizeAsync flag there, RFs::Volume() will be asynchronous, i.e the _current_ number of free clusters
   1.654 +    //-- will be returned.
   1.655 +    const TBool bSyncOp = !aVolume.iVolSizeAsync;
   1.656 +    aVolume.iVolSizeAsync = EFalse; //-- reset this flag in order it not to be reused on the client side
   1.657 +
   1.658 +    __PRINT2(_L("CFatMountCB::VolumeL() drv:%d, synch:%d"), DriveNumber(), bSyncOp);
   1.659 +    const TDriveInfo& drvInfo=aVolume.iDrive;
   1.660 +
   1.661 +#if defined(__EPOC32__)
   1.662 +    // if RAM drive, cap size according to HAL.
   1.663 +    if (drvInfo.iType==EMediaRam)
   1.664 +        {
   1.665 +        TLocalDriveCapsV2Buf caps;
   1.666 +        LocalDrive()->Caps(caps);
   1.667 +
   1.668 +        const TInt max_drive_size=TInt(caps().iEraseBlockSize);
   1.669 +        const TInt cur_drive_size=I64INT(caps().iSize);
   1.670 +
   1.671 +        aVolume.iSize=max_drive_size;
   1.672 +        aVolume.iFree=max_drive_size-cur_drive_size;
   1.673 +
   1.674 +        aVolume.iSize=aVolume.iFree+iSize;
   1.675 +
   1.676 +        TInt maxSize;
   1.677 +        if (HAL::Get(HAL::EMaxRAMDriveSize, maxSize) == KErrNone)
   1.678 +            {
   1.679 +            // iSize will never grow beyond maxRam because of a check in medint.
   1.680 +            // d <= f; (s{f} + f) - m <= f; s{f} <= m
   1.681 +            __ASSERT_DEBUG(iSize <= maxSize, Fault(EFatRAMDriveSizeInvalid));
   1.682 +            if (aVolume.iSize > maxSize)
   1.683 +                {
   1.684 +                TInt64 d = aVolume.iSize - maxSize;
   1.685 +                __ASSERT_DEBUG(d <= aVolume.iFree, Fault(EFatRAMDriveFreeInvalid));
   1.686 +                aVolume.iSize -= d;
   1.687 +                aVolume.iFree -= d;
   1.688 +                }
   1.689 +            }
   1.690 +
   1.691 +        aVolume.iSize-=ClusterBasePosition(); // Allow for bytes used by FAT etc
   1.692 +        aVolume.iSize=(aVolume.iSize>>ClusterSizeLog2())<<ClusterSizeLog2();  //-- round down to cluster size
   1.693 +
   1.694 +        return;
   1.695 +        }//if (drvInfo.iType==EMediaRam)
   1.696 +
   1.697 +#endif
   1.698 +
   1.699 +
   1.700 +    const TUint32 freeClusters = FAT().NumberOfFreeClusters(bSyncOp);
   1.701 +
   1.702 +    __PRINT1(_L("CFatMountCB::VolumeL() free clusters:%d"), freeClusters);
   1.703 +
   1.704 +    aVolume.iFree = (TInt64)freeClusters << ClusterSizeLog2();
   1.705 +
   1.706 +    if (drvInfo.iType==EMediaRam)
   1.707 +        aVolume.iSize=aVolume.iFree+iSize;
   1.708 +
   1.709 +    aVolume.iSize-=ClusterBasePosition(); // Allow for bytes used by FAT etc
   1.710 +    aVolume.iSize=(aVolume.iSize >> ClusterSizeLog2()) << ClusterSizeLog2();  //-- round down to cluster size
   1.711 +
   1.712 +    }
   1.713 +
   1.714 +
   1.715 +//-----------------------------------------------------------------------------------------
   1.716 +
   1.717 +//
   1.718 +//  Set the volume label (write aVolume label into BPB & Volume Label File)
   1.719 +//  aName string may be zero length but is assumed to contain no illegal characters or NULLs.
   1.720 +//
   1.721 +void CFatMountCB::SetVolumeL(TDes& aName)
   1.722 +    {
   1.723 +
   1.724 +    __PRINT(_L("CFatMountCB::SetVolumeL"));
   1.725 +
   1.726 +    CheckStateConsistentL();
   1.727 +    CheckWritableL();
   1.728 +
   1.729 +    __ASSERT_ALWAYS(aName.Length()<=KVolumeLabelSize,User::Leave(KErrBadName));
   1.730 +
   1.731 +    TBuf8<KVolumeLabelSize> buf8(KVolumeLabelSize);
   1.732 +    buf8.Zero();
   1.733 +    LocaleUtils::ConvertFromUnicodeL(buf8, aName, TFatUtilityFunctions::EOverflowActionLeave);
   1.734 +    aName.Zero();
   1.735 +    LocaleUtils::ConvertToUnicodeL(aName, buf8); // adjust aName (which may contain more underscores after this line than before)
   1.736 +
   1.737 +    const TInt lengthOfBuf8=buf8.Length();
   1.738 +    // Pad to end with spaces if not empty.
   1.739 +    if (lengthOfBuf8>0 && lengthOfBuf8<KVolumeLabelSize)
   1.740 +        {
   1.741 +        buf8.SetLength(KVolumeLabelSize);
   1.742 +        Mem::Fill(&buf8[lengthOfBuf8],KVolumeLabelSize-lengthOfBuf8,' ');
   1.743 +        }
   1.744 +
   1.745 +    // Write a volume label file
   1.746 +    WriteVolumeLabelFileL( buf8 );
   1.747 +
   1.748 +    // Write the boot sector volume label
   1.749 +    // Always pad to full length with spaces
   1.750 +    if (lengthOfBuf8==0)
   1.751 +        {
   1.752 +        buf8.Fill(' ',KVolumeLabelSize);
   1.753 +        }
   1.754 +
   1.755 +    WriteVolumeLabelL(buf8);
   1.756 +    }
   1.757 +
   1.758 +//-----------------------------------------------------------------------------------------
   1.759 +
   1.760 +/**
   1.761 +    Make a directory.
   1.762 +    @param aName full path to the directory to create. Name validity is checked by file server.
   1.763 +    all trailing dots from the name will be removed
   1.764 +*/
   1.765 +void CFatMountCB::MkDirL(const TDesC& aName)
   1.766 +    {
   1.767 +    __PRINT2(_L("CFatMountCB::MkDirL, drv:%d, %S"), DriveNumber(), &aName);
   1.768 +
   1.769 +    CheckStateConsistentL();
   1.770 +    CheckWritableL();
   1.771 +
   1.772 +    TPtrC dirName = RemoveTrailingDots(aName); //-- remove trailing dots from the name
   1.773 +
   1.774 +    TInt namePos=dirName.LocateReverse(KPathDelimiter)+1; // There is always a path delimiter
   1.775 +    TPtrC name=dirName.Mid(namePos);
   1.776 +    TLeafDirData leafDir;
   1.777 +    const TEntryPos dirPos(FindLeafDirL(dirName.Left(namePos), leafDir),0);
   1.778 +    TEntryPos dumPos=dirPos;
   1.779 +    TFatDirEntry dumEntry;
   1.780 +
   1.781 +    TBool isOriginalNameLegal = IsLegalDosName(name,EFalse,EFalse,EFalse,EFalse,ETrue);
   1.782 +    iFileCreationHelper.InitialiseL(name);
   1.783 +    TFileName fileName;
   1.784 +    TEntryPos startPos;
   1.785 +    TFatDirEntry startEntry;
   1.786 +    
   1.787 +    TRAPD(ret,DoFindL(name,KEntryAttMaskSupported,
   1.788 +                        startPos,startEntry,dumPos,dumEntry,
   1.789 +                        fileName,KErrNotFound,
   1.790 +                        &iFileCreationHelper,
   1.791 +                        leafDir));
   1.792 +
   1.793 +    if (ret!=KErrNotFound && ret!=KErrNone)
   1.794 +        User::Leave(ret);
   1.795 +    if (ret!=KErrNotFound)
   1.796 +        {
   1.797 +        if (dumEntry.Attributes()&KEntryAttDir)
   1.798 +            User::Leave(KErrAlreadyExists);
   1.799 +        else
   1.800 +            User::Leave(KErrAccessDenied);
   1.801 +        }
   1.802 +    TShortName shortName;
   1.803 +
   1.804 +    if (iFileCreationHelper.GetValidatedShortName(shortName) == KErrNotFound)
   1.805 +        {
   1.806 +        GenerateShortNameL(dirPos.iCluster,name,shortName,ETrue);
   1.807 +        }
   1.808 +
   1.809 +    TInt numEntries=1;
   1.810 +    if (isOriginalNameLegal==EFalse)
   1.811 +        numEntries=NumberOfVFatEntries(name.Length());
   1.812 +    dumPos=dirPos;
   1.813 +
   1.814 +    if (iFileCreationHelper.IsNewEntryPosFound())
   1.815 +        {
   1.816 +        dumPos = iFileCreationHelper.EntryAddingPos();
   1.817 +        }
   1.818 +
   1.819 +    AddDirEntryL(dumPos,numEntries);    //  Directory entry in leaf directory
   1.820 +    TInt startCluster;
   1.821 +    FOREVER
   1.822 +        {
   1.823 +        //-- FAT().FreeClusterHint() will give us a hint of the last free cluster
   1.824 +        startCluster=FAT().AllocateSingleClusterL(dumPos.iCluster ? dumPos.iCluster : FAT().FreeClusterHint());
   1.825 +
   1.826 +        FAT().FlushL();
   1.827 +        TRAPD(r, InitializeFirstDirClusterL(startCluster,dirPos.iCluster));
   1.828 +        if(r == KErrNone)
   1.829 +            break;
   1.830 +        if(r != KErrCorrupt)
   1.831 +            User::Leave(r);
   1.832 +        FAT().MarkAsBadClusterL(startCluster);
   1.833 +        }
   1.834 +    TFatDirEntry fatDirEntry;
   1.835 +    fatDirEntry.SetName(shortName);
   1.836 +    fatDirEntry.SetAttributes(KEntryAttDir);
   1.837 +    TTime now;
   1.838 +    now.UniversalTime();
   1.839 +    fatDirEntry.SetTime(now, TimeOffset());
   1.840 +    fatDirEntry.SetCreateTime(now, TimeOffset());
   1.841 +    fatDirEntry.SetStartCluster(startCluster);
   1.842 +    fatDirEntry.SetSize(0);
   1.843 +    if (isOriginalNameLegal)
   1.844 +        WriteDirEntryL(dumPos,fatDirEntry);
   1.845 +    else
   1.846 +        WriteDirEntryL(dumPos,fatDirEntry,name);
   1.847 +
   1.848 +    iFileCreationHelper.Close();
   1.849 +    }
   1.850 +
   1.851 +//-----------------------------------------------------------------------------------------
   1.852 +
   1.853 +/**
   1.854 +    Setup 1st cluster of the new directory
   1.855 +
   1.856 +    @param  aStartCluster   this entry start cluster number
   1.857 +    @param  aParentCluster  parent entry start cluster number
   1.858 +*/
   1.859 +void CFatMountCB::InitializeFirstDirClusterL(TInt aStartCluster,TInt aParentCluster)
   1.860 +    {
   1.861 +    const TUint32 KClusterSz= 1<<ClusterSizeLog2();
   1.862 +    const TUint32 KMaxBufSz = KClusterSz;           //-- max. nuffer size is a cluster
   1.863 +    const TUint32 KMinBufSz = 1<<SectorSizeLog2();  //-- min. buffer size is 1 sector (for OOM case)
   1.864 +
   1.865 +    //-- allocate a buffer for directory file 1st cluster initialisation
   1.866 +    RBuf8 buf;
   1.867 +    CleanupClosePushL(buf);
   1.868 +
   1.869 +    if(buf.CreateMax(KMaxBufSz) != KErrNone)
   1.870 +        buf.CreateMaxL(KMinBufSz); //-- OOM, try to create smaller buffer
   1.871 +
   1.872 +    buf.FillZ();
   1.873 +
   1.874 +    //-- copy "." directory entry to the buffer
   1.875 +
   1.876 +    //-- "." directory entry
   1.877 +    TFatDirEntry entry;
   1.878 +    TTime now;
   1.879 +    now.UniversalTime();
   1.880 +    entry.SetTime(now, TimeOffset() );
   1.881 +    entry.SetAttributes(KEntryAttDir);
   1.882 +    entry.SetCurrentDirectory();
   1.883 +    entry.SetStartCluster(aStartCluster);
   1.884 +    Mem::Copy(&buf[0],&entry,KSizeOfFatDirEntry);
   1.885 +
   1.886 +    //-- append ".." directory entry
   1.887 +    entry.SetParentDirectory();
   1.888 +    entry.SetStartCluster(aParentCluster==RootIndicator() ? 0 : aParentCluster);
   1.889 +    Mem::Copy(&buf[0]+KSizeOfFatDirEntry,&entry,KSizeOfFatDirEntry);
   1.890 +
   1.891 +    TEntryPos entryPos(aStartCluster,0);
   1.892 +
   1.893 +    //-- write buffer to the beginning of the directory file.
   1.894 +    DirWriteL(entryPos, buf); //-- use special interface to access FAT directory file
   1.895 +
   1.896 +    //-- fill in the rest of the cluster if we used a small buffer
   1.897 +    if((TUint32)buf.Size() < KClusterSz) //-- use special interface to access FAT directory file
   1.898 +    {
   1.899 +        buf.FillZ();
   1.900 +        const TInt restCnt = SectorsPerCluster() - 1;
   1.901 +        ASSERT(restCnt >=1);
   1.902 +
   1.903 +        for(TInt i=0; i<restCnt; ++i)
   1.904 +        {
   1.905 +            entryPos.iPos += KMinBufSz;
   1.906 +            DirWriteL(entryPos, buf); //-- use directory cache when dealing with directories
   1.907 +        }
   1.908 +
   1.909 +    }
   1.910 +
   1.911 +    CleanupStack::PopAndDestroy(&buf);
   1.912 +
   1.913 +    }
   1.914 +
   1.915 +//-----------------------------------------------------------------------------------------
   1.916 +
   1.917 +/**
   1.918 +    Remove a directory.
   1.919 +    @param aName directory name
   1.920 +    all trailing dots from the name will be removed
   1.921 +*/
   1.922 +void CFatMountCB::RmDirL(const TDesC& aName)
   1.923 +    {
   1.924 +    __PRINT2(_L("CFatMountCB::RmDirL, drv:%d, %S"), DriveNumber(), &aName);
   1.925 +
   1.926 +    CheckStateConsistentL();
   1.927 +    CheckWritableL();
   1.928 +
   1.929 +    TPtrC dirName = RemoveTrailingDots(aName); //-- remove trailing dots from the name
   1.930 +
   1.931 +    TFatDirEntry dirEntry;
   1.932 +    TEntryPos dirEntryPos(RootIndicator(),0); // Already checked entry is a directory
   1.933 +    FindEntryStartL(dirName,KEntryAttMatchMask|KEntryAttMatchExclusive,dirEntry,dirEntryPos);
   1.934 +    TEntryPos dosEntryPos=dirEntryPos;
   1.935 +    TFatDirEntry dosEntry=dirEntry;
   1.936 +    MoveToDosEntryL(dosEntryPos,dosEntry);
   1.937 +    if (!IsDirectoryEmptyL(StartCluster(dosEntry)))
   1.938 +        User::Leave(KErrInUse);
   1.939 +    // Remove the directory from cache before erasing
   1.940 +    if(iLeafDirCache && iLeafDirCache->CacheCount() > 0)
   1.941 +        {
   1.942 +        iLeafDirCache->RemoveDirL(StartCluster(dosEntry));
   1.943 +        }
   1.944 +
   1.945 +    EraseDirEntryL(dirEntryPos,dirEntry);
   1.946 +    FAT().FreeClusterListL(StartCluster(dosEntry));
   1.947 +    FAT().FlushL();
   1.948 +    }
   1.949 +
   1.950 +//-----------------------------------------------------------------------------------------
   1.951 +
   1.952 +/**
   1.953 +    Delete a file
   1.954 +    @param aName file name
   1.955 +    all trailing dots from the name will be removed
   1.956 +*/
   1.957 +void CFatMountCB::DeleteL(const TDesC& aName)
   1.958 +    {
   1.959 +    __PRINT2(_L("CFatMountCB::DeleteL, drv:%d, %S"), DriveNumber(), &aName);
   1.960 +
   1.961 +    CheckStateConsistentL();
   1.962 +    CheckWritableL();
   1.963 +
   1.964 +    TPtrC fullName = RemoveTrailingDots(aName); //-- remove trailing dots from the name
   1.965 +
   1.966 +    TFatDirEntry firstEntry;
   1.967 +    TEntryPos firstEntryPos(RootIndicator(),0);
   1.968 +    FindEntryStartL(fullName,KEntryAttMaskSupported,firstEntry,firstEntryPos);
   1.969 +    TEntryPos dosEntryPos=firstEntryPos;
   1.970 +    TFatDirEntry dosEntry=firstEntry;
   1.971 +    MoveToDosEntryL(dosEntryPos,dosEntry);
   1.972 +    if ((dosEntry.Attributes()&KEntryAttReadOnly) || (dosEntry.Attributes()&KEntryAttDir))
   1.973 +        User::Leave(KErrAccessDenied);
   1.974 +    // Can not delete a file if it is clamped
   1.975 +    CMountCB* basePtr=(CMountCB*)this;
   1.976 +    TInt startCluster=StartCluster(dosEntry);
   1.977 +    if(basePtr->IsFileClamped(MAKE_TINT64(0,startCluster)) > 0)
   1.978 +        User::Leave(KErrInUse);
   1.979 +    EraseDirEntryL(firstEntryPos,firstEntry);
   1.980 +    FAT().FreeClusterListL(StartCluster(dosEntry));
   1.981 +    FAT().FlushL();
   1.982 +    }
   1.983 +
   1.984 +//-----------------------------------------------------------------------------------------
   1.985 +
   1.986 +/**
   1.987 +
   1.988 +    Rename or replace a directory entry.
   1.989 +    Assumes all files are closed and replace is only passed files.
   1.990 +    Assumes rename target does not exist or is the source file.
   1.991 +
   1.992 +    --------------- operating mode --------------------------------------------
   1.993 +
   1.994 +    * rename mode
   1.995 +
   1.996 +    aOldName exists  |  aNewName exists |   result
   1.997 +        N                    N              leave KErrNotFound
   1.998 +        N                    Y              leave KErrNotFound
   1.999 +        Y                    N              rename aOldName -> aNewName
  1.1000 +        Y                    Y              leave KErrAlreadyExists if(aOldName!=aNewName); otherwise do nothing
  1.1001 +
  1.1002 +    * replace mode
  1.1003 +
  1.1004 +        N                    N              leave KErrNotFound
  1.1005 +        N                    Y              leave KErrNotFound
  1.1006 +        Y                    N              rename aOldName -> aNewName
  1.1007 +        Y                    Y              contents and all file attributes of the "aNewName" are replaced with aOldName's. "aOldName" entries are deleted then.
  1.1008 +
  1.1009 +
  1.1010 +    @param   aOldName           entry name to be renamed or replaced
  1.1011 +    @param   aNewName           a new entry name
  1.1012 +    @param   aMode              specifies renaming / replacing
  1.1013 +    @param   aNewDosEntryPos    on exit contains new entry Pos.
  1.1014 +*/
  1.1015 +void CFatMountCB::DoRenameOrReplaceL(const TDesC& aOldName, const TDesC& aNewName, TRenMode aMode, TEntryPos& aNewName_DosEntryPos)
  1.1016 +    {
  1.1017 +    __PRINT3(_L("CFatMountCB::DoRenameOrReplaceL() mode:%d old:%S, new:%S"), aMode, &aOldName, &aNewName);
  1.1018 +
  1.1019 +    const TBool namesAreIdentical = FileNamesIdentical(aOldName, aNewName); //-- this is case-insensitive.
  1.1020 +    const TBool renameMode = (aMode == EModeRename);
  1.1021 +    const TBool replaceMode = !renameMode;
  1.1022 +    TInt  nRes;
  1.1023 +
  1.1024 +    if(namesAreIdentical && replaceMode)
  1.1025 +        return; //-- nothing to do, replacing file with itself
  1.1026 +
  1.1027 +    //---------------------------------------------------------------------------------------------------------------------------
  1.1028 +    //-- 1. find the entries of 'aOldName' file. It must always succeed, because FileServer firstly tries to locate 'aOldName'
  1.1029 +
  1.1030 +    TFatDirEntry oldName_FirstEntry; //-- first entry of the "aOldName" entryset
  1.1031 +    TEntryPos    oldName_FirstEntryPos(RootIndicator(), 0); //-- dir. pos of the start "aOldName" VFAT entry set
  1.1032 +
  1.1033 +    FindEntryStartL(aOldName, KEntryAttMaskSupported, oldName_FirstEntry, oldName_FirstEntryPos);
  1.1034 +
  1.1035 +    TFatDirEntry oldName_DosEntry    = oldName_FirstEntry;   //-- "aOldName" entry set DOS entry
  1.1036 +    TEntryPos    oldName_DosEntryPos = oldName_FirstEntryPos;//-- dir. pos of the "aOldName" DOS entry
  1.1037 +
  1.1038 +    MoveToDosEntryL(oldName_DosEntryPos, oldName_DosEntry);
  1.1039 +
  1.1040 +    const TBool bOldNameIsVFAT = !(oldName_DosEntryPos == oldName_FirstEntryPos); //-- ETrue if "aOldName" is VFAT name, i.e. consists of mode than 1 entry
  1.1041 +
  1.1042 +    //-- check if the file "aOldName" is clamped. In this case it can't be replaced.
  1.1043 +    if(replaceMode && (IsFileClamped(StartCluster(oldName_DosEntry)) > 0))
  1.1044 +        User::Leave(KErrInUse);
  1.1045 +
  1.1046 +    //---------------------------------------------------------------------------------------------------------------------------
  1.1047 +    //-- 2. find the entry of 'aNewName' file. Further behavior depends on rename/replace mode and if this file exists or not
  1.1048 +
  1.1049 +    //-- extract new file name from the full path
  1.1050 +    TPtrC ptrNewName;
  1.1051 +    TPtrC ptrNewNameParentDir;
  1.1052 +    const TInt delimPos = aNewName.LocateReverse(KPathDelimiter);
  1.1053 +    ptrNewName.Set(aNewName.Mid(delimPos+1));
  1.1054 +    ptrNewNameParentDir.Set(aNewName.Left(delimPos+1));
  1.1055 +
  1.1056 +    //-- find the parent directory of the "aNewName" and create iterator for it
  1.1057 +    TLeafDirData leafDir;
  1.1058 +    const TEntryPos aNewName_ParentDirPos = TEntryPos(FindLeafDirL(ptrNewNameParentDir, leafDir), 0); //-- 'aNewName' parent directory iterator
  1.1059 +    aNewName_DosEntryPos = aNewName_ParentDirPos;
  1.1060 +
  1.1061 +    TEntryPos    newName_VFatEntryPos; //-- dir. pos of the start "aNewName" VFAT entry set
  1.1062 +    TFatDirEntry newName_DosEntry;
  1.1063 +
  1.1064 +    TFileName fileName;
  1.1065 +    iFileCreationHelper.InitialiseL(ptrNewName);
  1.1066 +    TFatDirEntry startEntry;
  1.1067 +
  1.1068 +    TRAP(nRes, DoFindL(ptrNewName, KEntryAttMaskSupported,
  1.1069 +                newName_VFatEntryPos, startEntry, aNewName_DosEntryPos, newName_DosEntry,
  1.1070 +                fileName, KErrNotFound,
  1.1071 +                &iFileCreationHelper,
  1.1072 +                leafDir));
  1.1073 +
  1.1074 +    if (nRes!=KErrNone && nRes!=KErrNotFound)
  1.1075 +        User::Leave(nRes);
  1.1076 +
  1.1077 +    const TBool newFileExists = (nRes == KErrNone); //-- ETrue if 'aNewName' file exists.
  1.1078 +    const TBool bNewNameIsVFAT = !IsLegalDosName(ptrNewName, EFalse, EFalse, EFalse, EFalse, ETrue);
  1.1079 +
  1.1080 +    if(renameMode && newFileExists)
  1.1081 +        {
  1.1082 +        if(!namesAreIdentical)
  1.1083 +        {
  1.1084 +        if ((newName_DosEntry.Attributes()&KEntryAttDir) != (oldName_DosEntry.Attributes()&KEntryAttDir))
  1.1085 +            {
  1.1086 +            User::Leave(KErrAccessDenied);  //-- leave with KErrAccessDenied if it is trying to rename a file
  1.1087 +                                            //      to a dir or vice versa.
  1.1088 +            }
  1.1089 +        User::Leave(KErrAlreadyExists); //-- can't rename file if the file with 'aNewName' already exists
  1.1090 +        }
  1.1091 +        else
  1.1092 +            {
  1.1093 +            if(!bNewNameIsVFAT && !bOldNameIsVFAT)
  1.1094 +                return; //-- renaming DOS name to itself
  1.1095 +            }
  1.1096 +        //-- allow renaming entry to itself. "namesAreIdentical" is case-insensitive. use case: "FILE" -> "File"
  1.1097 +        }
  1.1098 +
  1.1099 +    //---------------------------------------------------------------------------------------------------------------------------
  1.1100 +
  1.1101 +    if(replaceMode && newFileExists)
  1.1102 +        {
  1.1103 +        //---------------------------------------------------------------------------------------------------------------------------
  1.1104 +        //-- replace contents of the 'aNewName' with 'aOldName' and remove 'aOldName' entries.
  1.1105 +
  1.1106 +        //-- check if we are still trying to replace the file with itself, probably using short name alias
  1.1107 +        if(aNewName_DosEntryPos == oldName_DosEntryPos)
  1.1108 +            return; //-- nothing to do, it's the same file
  1.1109 +
  1.1110 +        const TInt oldNameStartCluster = StartCluster(oldName_DosEntry);
  1.1111 +        const TInt newNameStartCluster = StartCluster(newName_DosEntry); //-- store starting cluster of the chain to be unlinked
  1.1112 +
  1.1113 +        newName_DosEntry.SetStartCluster(oldNameStartCluster);
  1.1114 +        newName_DosEntry.SetSize(oldName_DosEntry.Size());
  1.1115 +        newName_DosEntry.SetTime(oldName_DosEntry.Time(TTimeIntervalSeconds(0)), TTimeIntervalSeconds(0));
  1.1116 +        newName_DosEntry.SetAttributes(oldName_DosEntry.Attributes());
  1.1117 +
  1.1118 +            if(IsRuggedFSys())
  1.1119 +                {
  1.1120 +                //-- Note 1.
  1.1121 +                //-- set a special Id in reserved section for old and new entries.
  1.1122 +                //-- if write fails before the old entry gets erased, we will have 2 entries pointing to the same clusterchain.
  1.1123 +                //-- ScanDrive is responsible for fixing this situation by erasing entry with ID KReservedIdOldEntry.
  1.1124 +                //-- note that  SetRuggedFatEntryId() uses "LastAccessTime" DOS FAT entry field to store the ID.
  1.1125 +                //-- in normal situation this field isn't used, though Windows checkdisk can chack its validiy.
  1.1126 +                //-- KReservedIdNewEntry == 0x0000 that corresponds to year 1980.
  1.1127 +
  1.1128 +                newName_DosEntry.SetRuggedFatEntryId(KReservedIdNewEntry);
  1.1129 +                oldName_DosEntry.SetRuggedFatEntryId(KReservedIdOldEntry);
  1.1130 +                WriteDirEntryL(oldName_DosEntryPos, oldName_DosEntry);
  1.1131 +                }
  1.1132 +
  1.1133 +        //-- write 'aNewName' DOS dir. entry data back
  1.1134 +        WriteDirEntryL(aNewName_DosEntryPos, newName_DosEntry);
  1.1135 +
  1.1136 +        //-- erase "oldName" entryset.
  1.1137 +        EraseDirEntryL(oldName_FirstEntryPos, oldName_FirstEntry);
  1.1138 +
  1.1139 +        //-- free 'aNewName' cluster list
  1.1140 +        FAT().FreeClusterListL(newNameStartCluster);
  1.1141 +
  1.1142 +        if(IsRuggedFSys())
  1.1143 +            FAT().FlushL();
  1.1144 +
  1.1145 +        }
  1.1146 +    else //if(replaceMode && newFileExists)
  1.1147 +        {
  1.1148 +        //---------------------------------------------------------------------------------------------------------------------------
  1.1149 +        //-- Renaming 'aOldName' to 'aNewName': add 'aNewName' entry set and remove 'aOldName' entryset
  1.1150 +
  1.1151 +        TFatDirEntry newDosEntry = oldName_DosEntry;
  1.1152 +        //-- generate short name for the 'aNewName' entryset and make new DOS entry
  1.1153 +        if(bNewNameIsVFAT)
  1.1154 +            {//-- need to generate a short name for VFAT entryset DOS entry
  1.1155 +            TShortName shortName;
  1.1156 +
  1.1157 +            if (iFileCreationHelper.GetValidatedShortName(shortName) == KErrNotFound)
  1.1158 +                {
  1.1159 +                GenerateShortNameL(aNewName_DosEntryPos.Cluster(), ptrNewName, shortName, ETrue);
  1.1160 +                }
  1.1161 +
  1.1162 +            newDosEntry.SetName(shortName);
  1.1163 +            }
  1.1164 +        else
  1.1165 +            {//-- just use 'aNewName' as DOS name.
  1.1166 +            TBuf8<KFatDirNameSize+1> tmp; //-- the name may be "XXXXXXXX.YYY"
  1.1167 +            tmp.Copy(ptrNewName);
  1.1168 +            newDosEntry.SetName(DosNameToStdFormat(tmp));
  1.1169 +            }
  1.1170 +
  1.1171 +        if(IsRuggedFSys())
  1.1172 +            {//-- the the note(1) above
  1.1173 +            newDosEntry.SetRuggedFatEntryId(KReservedIdNewEntry);
  1.1174 +            oldName_DosEntry.SetRuggedFatEntryId(KReservedIdOldEntry);
  1.1175 +            WriteDirEntryL(oldName_DosEntryPos, oldName_DosEntry);
  1.1176 +            }
  1.1177 +
  1.1178 +        //-- add new entryset to the directory
  1.1179 +        aNewName_DosEntryPos.iPos = 0;
  1.1180 +        aNewName_DosEntryPos.iCluster = aNewName_ParentDirPos.Cluster();
  1.1181 +
  1.1182 +        if (iFileCreationHelper.IsNewEntryPosFound())
  1.1183 +            {
  1.1184 +            aNewName_DosEntryPos = iFileCreationHelper.EntryAddingPos();
  1.1185 +            }
  1.1186 +
  1.1187 +        if(bNewNameIsVFAT)
  1.1188 +            {
  1.1189 +            const TInt numEntries = NumberOfVFatEntries(ptrNewName.Length());
  1.1190 +            AddDirEntryL(aNewName_DosEntryPos, numEntries);
  1.1191 +            WriteDirEntryL(aNewName_DosEntryPos, newDosEntry, ptrNewName);
  1.1192 +            }
  1.1193 +        else
  1.1194 +            {//-- new name is one DOS entry only
  1.1195 +            AddDirEntryL(aNewName_DosEntryPos, 1);
  1.1196 +            WriteDirEntryL(aNewName_DosEntryPos, newDosEntry);
  1.1197 +            }
  1.1198 +
  1.1199 +        //-- erase old entryset.
  1.1200 +        EraseDirEntryL(oldName_FirstEntryPos, oldName_FirstEntry);
  1.1201 +
  1.1202 +        //-- if we have renamed (moved) a directory, need to update its pointer to parent directory ('..' entry)
  1.1203 +        if((newDosEntry.Attributes() & KEntryAttDir))
  1.1204 +            {
  1.1205 +            TEntryPos parentPtrEntPos(StartCluster(newDosEntry), 1*KSizeOfFatDirEntry);
  1.1206 +
  1.1207 +            TFatDirEntry chFatEnt;
  1.1208 +            ReadDirEntryL(parentPtrEntPos, chFatEnt);
  1.1209 +
  1.1210 +            const TUint parentDirStartCluster_Old = StartCluster(chFatEnt);
  1.1211 +                  TUint parentDirStartCluster_New = aNewName_ParentDirPos.Cluster();
  1.1212 +
  1.1213 +            if(parentDirStartCluster_New == RootClusterNum() && parentDirStartCluster_New != 0)
  1.1214 +                {//-- we are in the root directory. for some reason, '..' entries of the directories in the root dir.
  1.1215 +                //-- must have starting cluster 0
  1.1216 +                parentDirStartCluster_New = 0;
  1.1217 +                }
  1.1218 +
  1.1219 +            if(parentDirStartCluster_Old != parentDirStartCluster_New)
  1.1220 +                {
  1.1221 +                chFatEnt.SetStartCluster(parentDirStartCluster_New);
  1.1222 +                WriteDirEntryL(parentPtrEntPos, chFatEnt);
  1.1223 +                }
  1.1224 +            // Invalidate leaf dir cache as it is hard to track the dir structure changes now
  1.1225 +            if (iLeafDirCache)
  1.1226 +                {
  1.1227 +                iLeafDirCache->Reset();
  1.1228 +                }
  1.1229 +            }
  1.1230 +        }//else if(replaceMode && newFileExists)
  1.1231 +
  1.1232 +    iFileCreationHelper.Close();
  1.1233 +    }
  1.1234 +
  1.1235 +//-----------------------------------------------------------------------------------------
  1.1236 +
  1.1237 +/**
  1.1238 +    Rename 'aOldName' file/directory to 'aNewName'
  1.1239 +    all trailing dots from the names will be removed
  1.1240 +
  1.1241 +    @param  aOldName        existing object name
  1.1242 +    @param  aNewName        new object name
  1.1243 +*/
  1.1244 +void CFatMountCB::RenameL(const TDesC& aOldName, const TDesC& aNewName)
  1.1245 +    {
  1.1246 +    __PRINT3(_L("CFatMountCB::RenameL, drv:%d, %S %S"), DriveNumber(), &aOldName, &aNewName);
  1.1247 +
  1.1248 +    CheckStateConsistentL();
  1.1249 +    CheckWritableL();
  1.1250 +
  1.1251 +    TEntryPos newEntryPos;
  1.1252 +    DoRenameOrReplaceL(RemoveTrailingDots(aOldName), RemoveTrailingDots(aNewName) ,EModeRename, newEntryPos);
  1.1253 +
  1.1254 +    if(!IsRuggedFSys())
  1.1255 +        FAT().FlushL();
  1.1256 +    }
  1.1257 +
  1.1258 +//-----------------------------------------------------------------------------------------
  1.1259 +
  1.1260 +/**
  1.1261 +    Replace contents of the 'aNewName' with the contents of 'aOldName'
  1.1262 +    all trailing dots from the names will be removed
  1.1263 +
  1.1264 +    @param  aOldName        existing object name
  1.1265 +    @param  aNewName        new object name
  1.1266 +*/
  1.1267 +void CFatMountCB::ReplaceL(const TDesC& aOldName,const TDesC& aNewName)
  1.1268 +    {
  1.1269 +
  1.1270 +    __PRINT3(_L("CFatMountCB::ReplaceL, drv:%d, %S %S"), DriveNumber(), &aOldName, &aNewName);
  1.1271 +
  1.1272 +    CheckStateConsistentL();
  1.1273 +    CheckWritableL();
  1.1274 +
  1.1275 +    TEntryPos newEntryPos;
  1.1276 +    DoRenameOrReplaceL(RemoveTrailingDots(aOldName), RemoveTrailingDots(aNewName), EModeReplace, newEntryPos);
  1.1277 +    if(!IsRuggedFSys())
  1.1278 +        FAT().FlushL();
  1.1279 +    }
  1.1280 +
  1.1281 +//-----------------------------------------------------------------------------------------
  1.1282 +
  1.1283 +
  1.1284 +/**
  1.1285 +    Try to find a directory entry by the given name and path.
  1.1286 +    This method _must_ leave if the entry is not found. See the caller.
  1.1287 +
  1.1288 +    @param  aName   path to the directory object. all trailing dots from the name will be removed.
  1.1289 +    @param  anEntry on return will contain the entry data
  1.1290 +
  1.1291 +    @leave  KErrPathNotFound if there is no path to the aName
  1.1292 +            KErrNotFound     if the entry corresponding to the aName is not found
  1.1293 +            system-wide erorr code of media read failure.
  1.1294 +*/
  1.1295 +void CFatMountCB::EntryL(const TDesC& aName,TEntry& anEntry) const
  1.1296 +    {
  1.1297 +    __PRINT2(_L("CFatMountCB::EntryL, drv:%d, %S"), DriveNumber(), &aName);
  1.1298 +
  1.1299 +    CheckStateConsistentL();
  1.1300 +
  1.1301 +    TEntryPos entryPos(RootIndicator(),0);
  1.1302 +    TFatDirEntry entry;
  1.1303 +    TPtr fileName(anEntry.iName.Des());
  1.1304 +
  1.1305 +    TPtrC fullName = RemoveTrailingDots(aName);
  1.1306 +    TInt namePos=fullName.LocateReverse(KPathDelimiter)+1; // There is always a path delimiter
  1.1307 +    TLeafDirData leafDir;
  1.1308 +    entryPos.iCluster=FindLeafDirL(fullName.Left(namePos), leafDir);
  1.1309 +    entryPos.iPos=0;
  1.1310 +    TEntryPos startPos;
  1.1311 +    TFatDirEntry startEntry;
  1.1312 +
  1.1313 +    DoFindL(fullName.Mid(namePos),KEntryAttMaskSupported,
  1.1314 +            startPos,startEntry,entryPos,entry,
  1.1315 +            fileName,KErrNotFound,
  1.1316 +            NULL,
  1.1317 +            leafDir);
  1.1318 +
  1.1319 +
  1.1320 +    anEntry.iAtt=entry.Attributes();
  1.1321 +    anEntry.iSize=entry.Size();
  1.1322 +    anEntry.iModified=entry.Time(TimeOffset());
  1.1323 +
  1.1324 +    if (fileName.Length()==0)
  1.1325 +        {
  1.1326 +        TBuf8<0x20> dosName(DosNameFromStdFormat(entry.Name()));
  1.1327 +        LocaleUtils::ConvertToUnicodeL(fileName,dosName);
  1.1328 +        }
  1.1329 +    if ((TUint)anEntry.iSize>=sizeof(TCheckedUid))
  1.1330 +        ReadUidL(StartCluster(entry),anEntry);
  1.1331 +    }
  1.1332 +
  1.1333 +//-----------------------------------------------------------------------------------------
  1.1334 +
  1.1335 +/**
  1.1336 +    Set directory entry details.
  1.1337 +    @param  aName           entry name; all trailing dots from the name will be removed
  1.1338 +    @param  aTime           entry modification time (and last access as well)
  1.1339 +    @param  aSetAttMask     entry attributes OR mask
  1.1340 +    @param  aClearAttMask   entry attributes AND mask
  1.1341 +
  1.1342 +*/
  1.1343 +void CFatMountCB::SetEntryL(const TDesC& aName,const TTime& aTime,TUint aSetAttMask,TUint aClearAttMask)
  1.1344 +    {
  1.1345 +    __PRINT2(_L("CFatMountCB::SetEntryL, drv:%d, %S"), DriveNumber(), &aName);
  1.1346 +
  1.1347 +    CheckStateConsistentL();
  1.1348 +    CheckWritableL();
  1.1349 +
  1.1350 +    TEntryPos firstEntryPos(RootIndicator(),0);
  1.1351 +    TFatDirEntry firstEntry;
  1.1352 +    FindEntryStartL(RemoveTrailingDots(aName),KEntryAttMaskSupported,firstEntry,firstEntryPos);
  1.1353 +    MoveToDosEntryL(firstEntryPos,firstEntry);
  1.1354 +    TUint setAttMask=aSetAttMask&KEntryAttMaskSupported;
  1.1355 +    if (setAttMask|aClearAttMask)
  1.1356 +        {
  1.1357 +        TInt att=firstEntry.Attributes();
  1.1358 +        att|=setAttMask;
  1.1359 +        att&=(~aClearAttMask);
  1.1360 +        firstEntry.SetAttributes(att);
  1.1361 +        }
  1.1362 +    if (aSetAttMask&KEntryAttModified)
  1.1363 +        {
  1.1364 +        firstEntry.SetTime(aTime,TimeOffset());
  1.1365 +        }
  1.1366 +    WriteDirEntryL(firstEntryPos,firstEntry);
  1.1367 +    }
  1.1368 +
  1.1369 +//-----------------------------------------------------------------------------------------
  1.1370 +
  1.1371 +void CFatMountCB::DoCheckFatForLoopsL(TInt aCluster, TInt& aPreviousCluster, TInt& aChangePreviousCluster, TInt& aCount) const
  1.1372 +//
  1.1373 +// Check one fat cluster for loops.
  1.1374 +//
  1.1375 +    {
  1.1376 +
  1.1377 +    if (aCluster==aPreviousCluster)
  1.1378 +        User::Leave(KErrCorrupt); // Found loop
  1.1379 +
  1.1380 +    aCount++;
  1.1381 +    if (aCount==aChangePreviousCluster)
  1.1382 +        {
  1.1383 +        aCount=0;
  1.1384 +        aChangePreviousCluster<<=1;
  1.1385 +        aPreviousCluster=aCluster;
  1.1386 +        }
  1.1387 +    }
  1.1388 +
  1.1389 +//-----------------------------------------------------------------------------------------
  1.1390 +
  1.1391 +void CFatMountCB::CheckFatForLoopsL(const TFatDirEntry& anEntry) const
  1.1392 +//
  1.1393 +// Check for loops
  1.1394 +//
  1.1395 +    {
  1.1396 +
  1.1397 +    TInt cluster=StartCluster(anEntry);
  1.1398 +    if (cluster==0 && anEntry.Size()==0)
  1.1399 +        return;
  1.1400 +
  1.1401 +    TInt previousCluster=cluster;
  1.1402 +    TInt changePreviousCluster=1;
  1.1403 +    TInt count=0;
  1.1404 +
  1.1405 +
  1.1406 +    for(;;)
  1.1407 +        {
  1.1408 +        if ((TUint)cluster < KFatFirstSearchCluster || (!IsEndOfClusterCh(cluster) && (TUint)cluster>MaxClusterNumber()))
  1.1409 +            User::Leave(KErrCorrupt);
  1.1410 +
  1.1411 +         if(!FAT().GetNextClusterL(cluster))
  1.1412 +            break;
  1.1413 +
  1.1414 +         DoCheckFatForLoopsL(cluster, previousCluster, changePreviousCluster, count);
  1.1415 +        }
  1.1416 +
  1.1417 +    }
  1.1418 +
  1.1419 +//-----------------------------------------------------------------------------------------
  1.1420 +
  1.1421 +/**
  1.1422 +    Open/Create/Replace a file on the current mount.
  1.1423 +
  1.1424 +    @param  aName   file name; all trailing dots from the name will be removed
  1.1425 +    @param  aMode   File open mode, See TFileMode
  1.1426 +    @param  anOpen  specifies action: open, create or replace the file
  1.1427 +    @param  aFile   pointer to the CFileCB object to populate
  1.1428 +
  1.1429 +*/
  1.1430 +void CFatMountCB::FileOpenL(const TDesC& aName,TUint aMode,TFileOpen anOpen,CFileCB* aFile)
  1.1431 +    {
  1.1432 +    __PRINT3(_L("CFatMountCB::FileOpenL, drv:%d, mode:%d, name:%S"), DriveNumber(), anOpen, &aName);
  1.1433 +
  1.1434 +    CheckStateConsistentL();
  1.1435 +
  1.1436 +    TPtrC fullName = RemoveTrailingDots(aName); //-- remove trailing dots from the name
  1.1437 +
  1.1438 +    TFatDirEntry firstEntry;
  1.1439 +    TEntryPos firstEntryPos(RootIndicator(),0);
  1.1440 +    TInt nPos=fullName.LocateReverse(KPathDelimiter)+1; // There is always a path delimiter
  1.1441 +    TPtrC name(fullName.Mid(nPos));
  1.1442 +    TInt ret = KErrNone;
  1.1443 +
  1.1444 +    iFileCreationHelper.Close();
  1.1445 +    if (anOpen == EFileCreate || anOpen == EFileReplace)
  1.1446 +        {
  1.1447 +        iFileCreationHelper.InitialiseL(name);
  1.1448 +        TRAP(ret,FindEntryStartL(fullName,KEntryAttMaskSupported,firstEntry,firstEntryPos,&iFileCreationHelper));
  1.1449 +        }
  1.1450 +    else
  1.1451 +        {
  1.1452 +        TRAP(ret,FindEntryStartL(fullName,KEntryAttMaskSupported,firstEntry,firstEntryPos));
  1.1453 +        }
  1.1454 +
  1.1455 +    if (ret!=KErrNone && ret!=KErrNotFound)
  1.1456 +        User::Leave(ret);
  1.1457 +
  1.1458 +    if (ret==KErrNone)
  1.1459 +        {
  1.1460 +        MoveToDosEntryL(firstEntryPos,firstEntry);
  1.1461 +        if ((firstEntry.Attributes()&KEntryAttDir) || (firstEntry.Attributes()&KEntryAttVolume))
  1.1462 +            User::Leave(KErrAccessDenied);
  1.1463 +        if (anOpen==EFileCreate)
  1.1464 +            User::Leave(KErrAlreadyExists);
  1.1465 +        if ((firstEntry.Attributes()&KEntryAttReadOnly) && aMode&EFileWrite)
  1.1466 +            User::Leave(KErrAccessDenied);
  1.1467 +        if((aMode & EFileWrite) && (IsFileClamped(StartCluster(firstEntry))>0))
  1.1468 +            User::Leave(KErrInUse);
  1.1469 +        CheckFatForLoopsL(firstEntry);
  1.1470 +        }
  1.1471 +    else
  1.1472 +        {
  1.1473 +        if (anOpen==EFileOpen)
  1.1474 +            User::Leave(KErrNotFound);
  1.1475 +
  1.1476 +        //-- here we try to either create or replace file
  1.1477 +        CheckWritableL();
  1.1478 +
  1.1479 +        TLeafDirData leafDir;
  1.1480 +
  1.1481 +        TInt numEntries = iFileCreationHelper.NumOfAddingEntries();
  1.1482 +        TShortName shortName;
  1.1483 +        if (iFileCreationHelper.GetValidatedShortName(shortName) == KErrNotFound)
  1.1484 +            {
  1.1485 +            firstEntryPos.iCluster=FindLeafDirL(fullName.Left(nPos), leafDir);
  1.1486 +            GenerateShortNameL(firstEntryPos.iCluster,name,shortName,ETrue);
  1.1487 +            }
  1.1488 +
  1.1489 +        if (iFileCreationHelper.IsNewEntryPosFound())
  1.1490 +            {
  1.1491 +            firstEntryPos = iFileCreationHelper.EntryAddingPos();
  1.1492 +            }
  1.1493 +        else
  1.1494 +            {
  1.1495 +            firstEntryPos.iCluster=FindLeafDirL(fullName.Left(nPos), leafDir);
  1.1496 +            firstEntryPos.iPos=0;
  1.1497 +            }
  1.1498 +
  1.1499 +        AddDirEntryL(firstEntryPos,numEntries);
  1.1500 +        firstEntry.InitZ();
  1.1501 +        firstEntry.SetName(shortName);
  1.1502 +        firstEntry.SetStartCluster(0);
  1.1503 +
  1.1504 +        TTime now;
  1.1505 +        now.UniversalTime();
  1.1506 +        firstEntry.SetCreateTime(now, TimeOffset() );
  1.1507 +
  1.1508 +        if (iFileCreationHelper.IsTrgNameLegalDosName())
  1.1509 +            WriteDirEntryL(firstEntryPos,firstEntry);
  1.1510 +        else
  1.1511 +            WriteDirEntryL(firstEntryPos,firstEntry,name);
  1.1512 +        }
  1.1513 +
  1.1514 +    CFatFileCB& file=(*((CFatFileCB*)aFile));
  1.1515 +    file.SetL(firstEntry,(TShare)(aMode&KFileShareMask),firstEntryPos);
  1.1516 +    if (anOpen==EFileReplace && file.Size())
  1.1517 +        {
  1.1518 +        file.SetSizeL(0);
  1.1519 +        file.SetSize(0);
  1.1520 +        }
  1.1521 +    if (file.IsSeekIndex()==EFalse)
  1.1522 +        file.CreateSeekIndex();
  1.1523 +    if (anOpen==EFileReplace || anOpen==EFileCreate)
  1.1524 +        file.SetArchiveAttribute();
  1.1525 +
  1.1526 +    if(!IsRuggedFSys())
  1.1527 +        FAT().FlushL();
  1.1528 +
  1.1529 +    iFileCreationHelper.Close();
  1.1530 +    }
  1.1531 +
  1.1532 +//-----------------------------------------------------------------------------------------
  1.1533 +
  1.1534 +
  1.1535 +/**
  1.1536 +    Open a directory on the current mount.
  1.1537 +
  1.1538 +    @param  aName   path to the object in the directory we want to open; all trailing dots from the name will be removed
  1.1539 +    @param  aDir    dir. CB to be filled in.
  1.1540 +
  1.1541 +    If there is no such a path, this method must leave with KErrPathNotFound
  1.1542 +
  1.1543 +    @leave  KErrPathNotFound if thereis no such path
  1.1544 +    @leave  error code on media read fault
  1.1545 +*/
  1.1546 +void CFatMountCB::DirOpenL(const TDesC& aName,CDirCB* aDir)
  1.1547 +    {
  1.1548 +    __PRINT2(_L("CFatMountCB::DirOpenL, drv:%d, %S"), DriveNumber(), &aName);
  1.1549 +
  1.1550 +    CheckStateConsistentL();
  1.1551 +
  1.1552 +    const TPtrC dirName = RemoveTrailingDots(aName); //-- remove trailing dots from the name
  1.1553 +
  1.1554 +    TInt namePos=dirName.LocateReverse(KPathDelimiter);
  1.1555 +
  1.1556 +    TFatDirEntry dosEntry;
  1.1557 +    TEntryPos dosEntryPos(RootIndicator(),0);
  1.1558 +    if (namePos==0)
  1.1559 +        InitializeRootEntry(dosEntry);
  1.1560 +    else
  1.1561 +        {
  1.1562 +        TPtrC dirPath=dirName.Left(namePos);
  1.1563 +        TInt dirPos=dirPath.LocateReverse(KPathDelimiter)+1;
  1.1564 +        TLeafDirData leafDir;
  1.1565 +        dosEntryPos.iCluster=FindLeafDirL(dirPath.Left(dirPos), leafDir); // Find directory before leaf
  1.1566 +        dosEntryPos.iPos=0;
  1.1567 +
  1.1568 +        TFileName fileName;
  1.1569 +        TEntryPos startPos;
  1.1570 +        TFatDirEntry startEntry;
  1.1571 +        DoFindL(dirPath.Mid(dirPos),
  1.1572 +                KEntryAttMatchMask|KEntryAttMatchExclusive,
  1.1573 +                startPos, startEntry, dosEntryPos, dosEntry,
  1.1574 +                fileName, KErrPathNotFound,
  1.1575 +                NULL,
  1.1576 +                leafDir);
  1.1577 +
  1.1578 +
  1.1579 +        }
  1.1580 +
  1.1581 +    TPtrC matchName(dirName.Mid(namePos+1));
  1.1582 +    if (matchName.Length()==0)
  1.1583 +        matchName.Set(_L("*"));
  1.1584 +
  1.1585 +    ((CFatDirCB*)aDir)->SetDirL(dosEntry,matchName);
  1.1586 +
  1.1587 +    }
  1.1588 +
  1.1589 +//-----------------------------------------------------------------------------------------
  1.1590 +
  1.1591 +TBool CFatMountCB::IsDirectoryEmptyL(TInt aCluster)
  1.1592 +//
  1.1593 +// Check aCluster contains no directory entries other than . and ..
  1.1594 +//
  1.1595 +    {
  1.1596 +
  1.1597 +    __PRINT(_L("CFatMountCB::IsDirectoryEmptyL"));
  1.1598 +    TEntryPos dirEntryPos(aCluster,0);
  1.1599 +    TFatDirEntry dirEntry;
  1.1600 +    FOREVER
  1.1601 +        {
  1.1602 +        ReadDirEntryL(dirEntryPos,dirEntry);
  1.1603 +        MoveToDosEntryL(dirEntryPos,dirEntry);
  1.1604 +        if (dirEntry.IsParentDirectory() || dirEntry.IsCurrentDirectory())
  1.1605 +            goto LoopEnd;
  1.1606 +        if (dirEntry.IsEndOfDirectory())
  1.1607 +            return ETrue;
  1.1608 +        if (IsRootDir(dirEntryPos)&&(dirEntryPos.iPos+StartOfRootDirInBytes()==RootDirEnd()))
  1.1609 +            return ETrue;   //  Root Directory has no end of directory marker
  1.1610 +        if (!dirEntry.IsErased())
  1.1611 +            return EFalse;
  1.1612 +LoopEnd:
  1.1613 +        MoveToNextEntryL(dirEntryPos);
  1.1614 +        }
  1.1615 +    }
  1.1616 +
  1.1617 +//-----------------------------------------------------------------------------------------
  1.1618 +
  1.1619 +/**
  1.1620 +    Overwrite as many contiguous file clusters as possible.
  1.1621 +*/
  1.1622 +void CFatMountCB::DoWriteToClusterListL(TEntryPos& aPos,TInt aLength,const TAny* aSrc,const RMessagePtr2& aMessage,TInt anOffset, TInt aLastcluster, TInt &aBadcluster, TInt &aGoodcluster)
  1.1623 +    {
  1.1624 +
  1.1625 +    __PRINT(_L("CFatMountCB::DoWriteToClusterListL"));
  1.1626 +    __ASSERT_ALWAYS(aPos.Cluster()>=KFatFirstSearchCluster,User::Leave(KErrCorrupt));
  1.1627 +
  1.1628 +    TInt endCluster=0;
  1.1629 +
  1.1630 +    const TInt clusterRelativePos=ClusterRelativePos(aPos.iPos);
  1.1631 +    const TInt maxClusters=((aLength+clusterRelativePos-1)>>ClusterSizeLog2())+1;
  1.1632 +    const TInt clusterListLen=FAT().CountContiguousClustersL(aPos.iCluster,endCluster,maxClusters);
  1.1633 +    const TInt writeLength=Min(aLength,(clusterListLen<<ClusterSizeLog2())-clusterRelativePos);
  1.1634 +    TInt64 dataStart=FAT().DataPositionInBytes(aPos.iCluster)+clusterRelativePos;
  1.1635 +
  1.1636 +    TRAPD(r, iRawDisk->WriteL(dataStart,writeLength,aSrc,aMessage,anOffset));
  1.1637 +
  1.1638 +    if(r == KErrNone) // Write succeded
  1.1639 +        {
  1.1640 +        aPos.iPos+=writeLength;
  1.1641 +        aPos.iCluster=endCluster;
  1.1642 +        return;
  1.1643 +        }
  1.1644 +
  1.1645 +    if(r != KErrCorrupt) // failure not due to corruption so propogate up
  1.1646 +        User::Leave(r);
  1.1647 +
  1.1648 +    TErrorInfoBuf errinf;
  1.1649 +    r = iRawDisk->GetLastErrorInfo(errinf);
  1.1650 +
  1.1651 +    if(r == KErrNone && errinf().iReasonCode == TErrorInfo::EBadSector) // GetLastErrorInfo succeded and Last Error was caused by bad sector
  1.1652 +        {
  1.1653 +
  1.1654 +        const TInt badcluster = (TInt)(((dataStart + errinf().iErrorPos) - ClusterBasePosition())>>ClusterSizeLog2())+KFatFirstSearchCluster;
  1.1655 +              TInt goodcluster = FAT().AllocateSingleClusterL(badcluster);
  1.1656 +
  1.1657 +        //Calculate cluster number to check whether this write started at the beginning of new cluster or middle of previous cluster.
  1.1658 +        TInt cluster = aPos.iCluster;
  1.1659 +        if ( (aPos.iPos) && ((aPos.iPos)==((aPos.iPos >> ClusterSizeLog2())<<ClusterSizeLog2())))
  1.1660 +            cluster--;
  1.1661 +
  1.1662 +        if((aPos.iPos != 0) && (badcluster == aPos.iCluster) && (aLastcluster == 0) && (aPos.iCluster == cluster))
  1.1663 +            { //Copy the contents already present in this cluster to new cluster allocated.
  1.1664 +            const TInt sizeToRead = aPos.iPos - ((aPos.iPos >> ClusterSizeLog2()) << ClusterSizeLog2());
  1.1665 +            dataStart = FAT().DataPositionInBytes(aPos.iCluster) + ClusterRelativePos((aPos.iPos - sizeToRead));
  1.1666 +
  1.1667 +
  1.1668 +            //-- Allocate the buffer required to copy the contents from bad cluster
  1.1669 +            RBuf8 clustBuf;
  1.1670 +            CleanupClosePushL(clustBuf);
  1.1671 +            if(clustBuf.CreateMax(sizeToRead) != KErrNone)
  1.1672 +                {
  1.1673 +                FAT().FreeClusterListL(goodcluster);
  1.1674 +                User::Leave(KErrNoMemory);
  1.1675 +                }
  1.1676 +
  1.1677 +            r = LocalDrive()->Read(dataStart, sizeToRead, clustBuf); //Read the contents into buffer
  1.1678 +            if(r != KErrNone) //If read fails dont do anything not even marking bad cluster.
  1.1679 +                {
  1.1680 +                FAT().FreeClusterListL(goodcluster);
  1.1681 +                User::Leave(r);
  1.1682 +                }
  1.1683 +
  1.1684 +            //Copy the bad and good cluster,required to adjust the start cluster number.
  1.1685 +            if(aBadcluster == 0)
  1.1686 +                aBadcluster = badcluster;
  1.1687 +
  1.1688 +            aGoodcluster = goodcluster;
  1.1689 +
  1.1690 +            FOREVER
  1.1691 +                {
  1.1692 +                //Calculate and copy the contents to new cluster.
  1.1693 +                aPos.iCluster = goodcluster;
  1.1694 +                dataStart = FAT().DataPositionInBytes(aPos.iCluster) + ClusterRelativePos(aPos.iPos - sizeToRead);
  1.1695 +
  1.1696 +                r = LocalDrive()->Write(dataStart, clustBuf);
  1.1697 +                if(r == KErrNone)
  1.1698 +                    { // Copied contents to new cluster so fix up the chain and mark the cluster as bad.
  1.1699 +                    FAT().WriteL(goodcluster, FAT().ReadL(badcluster));
  1.1700 +                    FAT().MarkAsBadClusterL(badcluster);
  1.1701 +                    aGoodcluster = goodcluster;
  1.1702 +                    CleanupStack::PopAndDestroy(&clustBuf); //-- deallocate a cluster buffer
  1.1703 +                    return;
  1.1704 +                    }
  1.1705 +                else if(r == KErrCorrupt)
  1.1706 +                    {
  1.1707 +                    r = LocalDrive()->GetLastErrorInfo(errinf);
  1.1708 +                    if(r == KErrNone && errinf().iReasonCode == TErrorInfo::EBadSector)
  1.1709 +                        { //Allocate new cluster and adjust the cluster list.
  1.1710 +                        goodcluster = FAT().AllocateSingleClusterL(aPos.iCluster);
  1.1711 +                        FAT().MarkAsBadClusterL(aPos.iCluster);
  1.1712 +                        continue;
  1.1713 +                        }
  1.1714 +                        r = KErrCorrupt;
  1.1715 +                    }
  1.1716 +                    //Not able to write successfully so dont alter the original list.
  1.1717 +                    aBadcluster = aGoodcluster = 0;
  1.1718 +                    FAT().FreeClusterListL(goodcluster);
  1.1719 +                    User::Leave(r);
  1.1720 +                }
  1.1721 +
  1.1722 +        }//if((aPos.iPos != 0) && (badcluster == aPos.iCluster) && (aLastcluster == 0) && (aPos.iCluster == cluster))
  1.1723 +
  1.1724 +        if((badcluster == aPos.iCluster) && (aLastcluster == 0)) //bad cluster at beginning of original clusterlist
  1.1725 +            {
  1.1726 +            // return bad and good clusters for CFatFileCB to fix up
  1.1727 +            FAT().WriteL(goodcluster, FAT().ReadL(badcluster));
  1.1728 +            aBadcluster = badcluster;
  1.1729 +            aGoodcluster = goodcluster;
  1.1730 +            aPos.iCluster = goodcluster;
  1.1731 +            }
  1.1732 +        else    //fix up chain
  1.1733 +            {
  1.1734 +            FAT().WriteL(goodcluster, FAT().ReadL(badcluster));
  1.1735 +            if(badcluster > aPos.iCluster)  //bad cluster not first in this contiguous list
  1.1736 +                FAT().WriteL(badcluster-1, goodcluster);
  1.1737 +            else    //first cluster of this contigous list bad so update last cluster of previous contiguous list
  1.1738 +                FAT().WriteL(aLastcluster, goodcluster);
  1.1739 +            }
  1.1740 +
  1.1741 +        FAT().MarkAsBadClusterL(badcluster);
  1.1742 +
  1.1743 +
  1.1744 +        return;
  1.1745 +        }
  1.1746 +    User::Leave(KErrCorrupt);
  1.1747 +    }
  1.1748 +
  1.1749 +//-----------------------------------------------------------------------------------------
  1.1750 +
  1.1751 +void CFatMountCB::WriteToClusterListL(TEntryPos& aPos,TInt aLength,const TAny* aSrc,const RMessagePtr2& aMessage,TInt anOffset, TInt &aBadcluster, TInt& aGoodcluster)
  1.1752 +//
  1.1753 +// Overwrite cluster list.
  1.1754 +//
  1.1755 +    {
  1.1756 +
  1.1757 +    __PRINT(_L("CFatMountCB::WriteToClusterListL"));
  1.1758 +    __ASSERT_ALWAYS(aPos.Cluster()>=KFatFirstSearchCluster,User::Leave(KErrCorrupt));
  1.1759 +
  1.1760 +    const TUint startPos=aPos.iPos;
  1.1761 +    const TUint temp=startPos>>ClusterSizeLog2();
  1.1762 +    const TUint length = (TUint)aLength;
  1.1763 +
  1.1764 +    if ( (startPos) && ((startPos)==(temp<<ClusterSizeLog2())) )
  1.1765 +        {
  1.1766 +        __ASSERT_ALWAYS(FAT().GetNextClusterL(aPos.iCluster),User::Leave(KErrCorrupt));
  1.1767 +        }
  1.1768 +
  1.1769 +    TUint offset=0;
  1.1770 +    TInt previouscluster=0;
  1.1771 +    FOREVER
  1.1772 +        {
  1.1773 +        DoWriteToClusterListL(aPos,length-offset,aSrc,aMessage,anOffset+offset, previouscluster, aBadcluster, aGoodcluster);
  1.1774 +        if (offset == (aPos.iPos-startPos))
  1.1775 +            continue;
  1.1776 +        offset=aPos.iPos-startPos;
  1.1777 +        __ASSERT_ALWAYS(aPos.iPos>startPos,User::Leave(KErrCorrupt));
  1.1778 +        previouscluster=aPos.iCluster;
  1.1779 +        if (offset<length)
  1.1780 +            {__ASSERT_ALWAYS(FAT().GetNextClusterL(aPos.iCluster),User::Leave(KErrCorrupt));}
  1.1781 +        if (offset>=length)
  1.1782 +            return;
  1.1783 +        }
  1.1784 +    }
  1.1785 +
  1.1786 +//-----------------------------------------------------------------------------------------
  1.1787 +
  1.1788 +void CFatMountCB::DoReadFromClusterListL(TEntryPos& aPos,TInt aLength,const TAny* aTrg,const RMessagePtr2& aMessage,TInt anOffset) const
  1.1789 +//
  1.1790 +// Read from as many contiguous file clusters as possible
  1.1791 +//
  1.1792 +    {
  1.1793 +
  1.1794 +    __PRINT(_L("CFatMountCB::DoReadFromClusterListL"));
  1.1795 +
  1.1796 +    TInt endCluster=0;
  1.1797 +
  1.1798 +    const TInt clusterRelativePos=ClusterRelativePos(aPos.iPos);
  1.1799 +    const TInt maxClusters=((aLength+clusterRelativePos-1)>>ClusterSizeLog2())+1;
  1.1800 +    const TInt clusterListLen=FAT().CountContiguousClustersL(aPos.iCluster,endCluster,maxClusters);
  1.1801 +    const TInt readLength=Min(aLength,(clusterListLen<<ClusterSizeLog2())-clusterRelativePos);
  1.1802 +    const TInt64 dataStart=FAT().DataPositionInBytes(aPos.iCluster)+clusterRelativePos;
  1.1803 +
  1.1804 +    TRAPD(r, iRawDisk->ReadL(dataStart,readLength,aTrg,aMessage,anOffset));
  1.1805 +
  1.1806 +    if(r == KErrNone) // Read succeded
  1.1807 +        {
  1.1808 +        aPos.iPos+=readLength;
  1.1809 +        aPos.iCluster=endCluster;
  1.1810 +        return;
  1.1811 +        }
  1.1812 +    if(r != KErrCorrupt) // failure not due to corruption so propogate up
  1.1813 +        User::Leave(r);
  1.1814 +
  1.1815 +    TErrorInfoBuf errinf;
  1.1816 +    r = iRawDisk->GetLastErrorInfo(errinf);
  1.1817 +
  1.1818 +    if(r == KErrNone && errinf().iReasonCode == TErrorInfo::EBadSector) // GetLastErrorInfo succeded and Last Error was caused by bad sector
  1.1819 +        {
  1.1820 +        TInt badcluster = (TInt)(((dataStart + errinf().iErrorPos) - ClusterBasePosition())>>ClusterSizeLog2())+KFatFirstSearchCluster;
  1.1821 +        FAT().MarkAsBadClusterL(badcluster);
  1.1822 +        }
  1.1823 +
  1.1824 +    User::Leave(KErrCorrupt);
  1.1825 +    }
  1.1826 +
  1.1827 +//-----------------------------------------------------------------------------------------
  1.1828 +
  1.1829 +void CFatMountCB::ReadFromClusterListL(TEntryPos& aPos,TInt aLength,const TAny* aTrg,const RMessagePtr2& aMessage,TInt anOffset) const
  1.1830 +//
  1.1831 +// Read from cluster list
  1.1832 +//
  1.1833 +    {
  1.1834 +
  1.1835 +    __PRINT(_L("CFatMountCB::ReadFromClusterListL"));
  1.1836 +    __ASSERT_ALWAYS(aPos.Cluster()>=KFatFirstSearchCluster,User::Leave(KErrCorrupt));
  1.1837 +
  1.1838 +    const TInt startPos=aPos.iPos;
  1.1839 +    const TInt temp=startPos>>ClusterSizeLog2();
  1.1840 +
  1.1841 +    if ( (startPos) && ((startPos)==(temp<<ClusterSizeLog2())) )
  1.1842 +        {
  1.1843 +        __ASSERT_ALWAYS(FAT().GetNextClusterL(aPos.iCluster),User::Leave(KErrCorrupt));
  1.1844 +        }
  1.1845 +
  1.1846 +    TInt offset=0;
  1.1847 +    FOREVER
  1.1848 +        {
  1.1849 +        DoReadFromClusterListL(aPos,aLength-offset,aTrg,aMessage,anOffset+offset);
  1.1850 +        offset=aPos.iPos-startPos;
  1.1851 +        if ((offset<aLength))
  1.1852 +            {
  1.1853 +            __ASSERT_ALWAYS(FAT().GetNextClusterL(aPos.iCluster),User::Leave(KErrCorrupt));
  1.1854 +            }
  1.1855 +        if (offset>=aLength)
  1.1856 +            return;
  1.1857 +        }
  1.1858 +    }
  1.1859 +
  1.1860 +//-----------------------------------------------------------------------------------------
  1.1861 +
  1.1862 +TInt CFatMountCB::FindLeafDirL(const TDesC& aName, TLeafDirData& aLeafDir) const
  1.1863 +//
  1.1864 +// Navigate the path to find the leaf directory.
  1.1865 +// Returns the startcluster of data for the directory found.
  1.1866 +//
  1.1867 +    {
  1.1868 +
  1.1869 +    __PRINT(_L("CFatMountCB::FindLeafDirL"));
  1.1870 +
  1.1871 +    TLex lex(aName);
  1.1872 +    TInt r;
  1.1873 +    TEntryPos entryPos(RootIndicator(),0);
  1.1874 +
  1.1875 +    if (iLeafDirCache == NULL)
  1.1876 +        {
  1.1877 +        TInt leaflen=(iLastLeafDir) ? iLastLeafDir->Length() : 0;
  1.1878 +        TInt namelen=aName.Length();
  1.1879 +        if (leaflen>1 && namelen>=leaflen && *iLastLeafDir==aName.Left(leaflen))
  1.1880 +            {
  1.1881 +            if (leaflen==namelen)
  1.1882 +                return(iLastLeafDirCluster);
  1.1883 +            lex.Inc(leaflen-1);
  1.1884 +            entryPos.iCluster=iLastLeafDirCluster;
  1.1885 +            }
  1.1886 +        }
  1.1887 +    else
  1.1888 +        {
  1.1889 +        // Skip root directory
  1.1890 +        if (iLeafDirCache->CacheCount() > 0 && aName.Length() > 1)
  1.1891 +            {
  1.1892 +            TInt err = iLeafDirCache->FindInCache(aName, aLeafDir);
  1.1893 +            if (err == KErrNone)
  1.1894 +                {
  1.1895 +                ASSERT(aLeafDir.iClusterNum > 0);
  1.1896 +                return aLeafDir.iClusterNum;
  1.1897 +                }
  1.1898 +            else if (err != KErrNotFound)
  1.1899 +                {
  1.1900 +                User::LeaveIfError(err);
  1.1901 +                }
  1.1902 +            }
  1.1903 +        }
  1.1904 +
  1.1905 +    FOREVER
  1.1906 +        {
  1.1907 +        lex.Inc(); // Skip path delimiter
  1.1908 +        lex.Mark();
  1.1909 +        r=lex.Remainder().Locate(KPathDelimiter);
  1.1910 +        if (r==KErrNotFound)
  1.1911 +            r=lex.Remainder().Length();
  1.1912 +        if (r==0) // End of the path
  1.1913 +            break;
  1.1914 +        lex.Inc(r); // Set the token length
  1.1915 +        TFatDirEntry entry;
  1.1916 +
  1.1917 +        TFileName fileName;
  1.1918 +        TEntryPos startPos;
  1.1919 +        TFatDirEntry startEntry;
  1.1920 +        DoFindL(lex.MarkedToken(),
  1.1921 +                KEntryAttMatchMask|KEntryAttMatchExclusive,
  1.1922 +                startPos, startEntry, entryPos, entry,
  1.1923 +                fileName, KErrPathNotFound,
  1.1924 +                NULL,
  1.1925 +                aLeafDir);
  1.1926 +
  1.1927 +
  1.1928 +        entryPos.iCluster=StartCluster(entry);
  1.1929 +        entryPos.iPos=0;
  1.1930 +        }
  1.1931 +
  1.1932 +    if (iLeafDirCache == NULL)
  1.1933 +        {
  1.1934 +        AllocBufferL(((CFatMountCB*)this)->iLastLeafDir,aName);
  1.1935 +        ((CFatMountCB*)this)->iLastLeafDirCluster=entryPos.iCluster;
  1.1936 +        }
  1.1937 +    else
  1.1938 +        {
  1.1939 +        if (aName.Length() > 1)
  1.1940 +            {
  1.1941 +            aLeafDir = TLeafDirData(entryPos.iCluster);
  1.1942 +            iLeafDirCache->AddToCacheL(aName, aLeafDir);
  1.1943 +            }
  1.1944 +        }
  1.1945 +
  1.1946 +    return entryPos.iCluster;
  1.1947 +    }
  1.1948 +
  1.1949 +//-----------------------------------------------------------------------------------------
  1.1950 +
  1.1951 +/**
  1.1952 +    Search for a specified name winthin directory cache
  1.1953 +    Works similary to TBool CFatMountCB::DoFindL()
  1.1954 +
  1.1955 +    @param  anAtt           attributes of the object to find
  1.1956 +    @param  aStartEntryPos  on return in case of VFAT entry will contain start position of the VFAT dir. entry
  1.1957 +    @param  aStartEntry     on return will contain first VFAT dir entry
  1.1958 +    @param  aDosEntryPos    the search will start from this position of dir entry, on return it will contain result DOS entry position, last one for VFAT case
  1.1959 +    @param  aDosEntry       on return will contain DOS dir entry (the last one for VFAT case)
  1.1960 +    @param  aFileName       in the case of VFAT entry and on success here will be returned a long filename
  1.1961 +    @param  aAuxParam       some parameters package
  1.1962 +    @param  aFileCreationHelper       a helper package for file creations
  1.1963 +
  1.1964 +    @return ETrue if the specified name is found in the cache. In this case aStartEntryPos, aStartEntry, aDosEntryPos, aDosEntry, aFileName will contain valid values
  1.1965 +*/
  1.1966 +TBool CFatMountCB::DoRummageDirCacheL(const TUint anAtt, TEntryPos& aStartEntryPos,  
  1.1967 +                                        TFatDirEntry& aStartEntry,  TEntryPos& aDosEntryPos,
  1.1968 +                                        TFatDirEntry& aDosEntry,    TDes& aFileName,
  1.1969 +                                        const TFindHelper& aAuxParam,
  1.1970 +                                        XFileCreationHelper* aFileCreationHelper,
  1.1971 +                                        const TLeafDirData& aLeafDir) const
  1.1972 +    {
  1.1973 +    TBool bCacheMatchFound = EFalse;
  1.1974 +
  1.1975 +    //-- get an interface to the Dir. cache
  1.1976 +    MWTCacheInterface* pDirCache = iRawDisk->DirCacheInterface();
  1.1977 +    ASSERT(pDirCache);
  1.1978 +    if(!pDirCache)
  1.1979 +        return EFalse;
  1.1980 +
  1.1981 +    //-- save original values in order to restore them in the case of negative search results
  1.1982 +    TEntryPos       StartEntryPos1(aStartEntryPos);
  1.1983 +    TEntryPos       DosEntryPos1(aDosEntryPos);
  1.1984 +    TFatDirEntry    StartEntry1(aStartEntry);
  1.1985 +    TFatDirEntry    DosEntry1(aDosEntry);
  1.1986 +
  1.1987 +    TInt64          nCachedLinPos;
  1.1988 +
  1.1989 +    const TUint32 clSize = 1 << ClusterSizeLog2(); //-- media cluster size
  1.1990 +    const TUint32 cacheSz = pDirCache->CacheSizeInBytes(); //-- cache size in bytes
  1.1991 +    const TUint32 maxDirEntries = cacheSz >> KSizeOfFatDirEntryLog2;  //-- maximal number of dir entries that can be in the cache
  1.1992 +
  1.1993 +    const TUint   pageSzLog2 = pDirCache->PageSizeInBytesLog2();
  1.1994 +    TBool ScanMRUPageFirst  = EFalse;
  1.1995 +    TBool MRUPageScanned    = EFalse;
  1.1996 +
  1.1997 +    // if MRU pos is availale, start with MRU page
  1.1998 +    if (aLeafDir.iMRUPos.Cluster())
  1.1999 +        {
  1.2000 +        ScanMRUPageFirst = ETrue;
  1.2001 +        DosEntryPos1 = aLeafDir.iMRUPos;
  1.2002 +        }
  1.2003 +
  1.2004 +    TInt numFound = 0;
  1.2005 +    TEntryPos startPos = DosEntryPos1;
  1.2006 +    TInt clusterNum = DosEntryPos1.iCluster;
  1.2007 +
  1.2008 +    for(TUint32 entryCnt=0; entryCnt < maxDirEntries; ++entryCnt)
  1.2009 +        {//-- walk through directory cluster list. The loop is limited by maximal number of dir entries
  1.2010 +         //-- that can be cached. Helps to avoid problems with infinite (looped) directories
  1.2011 +
  1.2012 +        if (IsEndOfClusterCh(DosEntryPos1.iCluster))
  1.2013 +            {
  1.2014 +            // refer back to the last stored cluster position
  1.2015 +            //  note aFileCreationHelper may not be initialised for file opening operations
  1.2016 +            if (aFileCreationHelper && aFileCreationHelper->IsInitialised() && clusterNum != DosEntryPos1.iCluster)
  1.2017 +                {
  1.2018 +                TEntryPos dummyPos(clusterNum, clSize - KSizeOfFatDirEntry);
  1.2019 +                aFileCreationHelper->SetEntryAddingPos(dummyPos);
  1.2020 +                aFileCreationHelper->SetIsNewEntryPosFound(ETrue);
  1.2021 +                }
  1.2022 +
  1.2023 +            if (ScanMRUPageFirst && !MRUPageScanned)
  1.2024 +                {
  1.2025 +                DosEntryPos1 = aDosEntryPos;
  1.2026 +                MRUPageScanned = ETrue;
  1.2027 +                continue;
  1.2028 +                }
  1.2029 +            break; //-- this was the last cluster in this directory
  1.2030 +            }
  1.2031 +
  1.2032 +        const TUint32 pageStartPos = CalculatePageOffsetInCluster(DosEntryPos1.iPos, pageSzLog2);
  1.2033 +        DosEntryPos1.iPos = pageStartPos;
  1.2034 +        TBool   PassedPageBoundary = EFalse;
  1.2035 +
  1.2036 +        const TInt64  entryLinPos = MakeLinAddrL(DosEntryPos1); //-- linear media position of the cluster for this directory
  1.2037 +        const TUint32 cachePageSz = pDirCache->PosCached(entryLinPos, nCachedLinPos); //-- indicates if entryLinPos is cached
  1.2038 +        if(cachePageSz)
  1.2039 +            {//-- current page is in the directory cache
  1.2040 +             //__PRINT2(_L("#-!! CFatMountCB::DoRummageDirCacheL() Searching cl:%d, lin Pos:%X"),DosEntryPos1.iCluster,(TUint32)entryLinPos);
  1.2041 +
  1.2042 +            //-- search to the end of the cached page.
  1.2043 +            // Note GetDirEntry() will read data beyond cache page boundary
  1.2044 +            const TUint32 nEntries = (1 << pageSzLog2) >> KSizeOfFatDirEntryLog2;
  1.2045 +
  1.2046 +            TInt nErr;
  1.2047 +            //-- extract dir entries from the cached page and see if they match given name (aName)
  1.2048 +            /// until it reaches the next page
  1.2049 +            for(;;)
  1.2050 +                {
  1.2051 +                StartEntryPos1 = DosEntryPos1;
  1.2052 +                TInt clSave = DosEntryPos1.iCluster; //-- need to save current cluster number because GetDirEntry() & MoveToNextEntryL() can change it
  1.2053 +
  1.2054 +                //-- get directory entry from the cache. We know that the DosEntryPos1 is cached.
  1.2055 +                nErr = GetDirEntry(DosEntryPos1, DosEntry1, StartEntry1, aFileName);
  1.2056 +                if(nErr != KErrNone)
  1.2057 +                    break;
  1.2058 +
  1.2059 +                if(DosEntry1.IsEndOfDirectory())
  1.2060 +                    {
  1.2061 +                    if (aFileCreationHelper && aFileCreationHelper->IsInitialised() && !aFileCreationHelper->IsNewEntryPosFound())
  1.2062 +                        {
  1.2063 +                        // note it is impossible to be at the end of the cluster chain here.
  1.2064 +                        aFileCreationHelper->SetEntryAddingPos(DosEntryPos1);
  1.2065 +                        aFileCreationHelper->SetIsNewEntryPosFound(ETrue);
  1.2066 +                        }
  1.2067 +
  1.2068 +                    if (ScanMRUPageFirst && !MRUPageScanned)
  1.2069 +                        {
  1.2070 +                        break;
  1.2071 +                        }
  1.2072 +
  1.2073 +                    // if (!ScanMRUPageFirst || ScanMRUPageFirst && MRUPageScanned)
  1.2074 +                    goto Exit; //-- this was the last entry in this directory, no reason to look further
  1.2075 +                    }
  1.2076 +
  1.2077 +                if (aFileCreationHelper && aFileCreationHelper->IsInitialised() && !aFileCreationHelper->IsNewEntryPosFound())
  1.2078 +                    {
  1.2079 +                    if (!DosEntry1.IsErased() && !DosEntry1.IsGarbage())
  1.2080 +                        {
  1.2081 +                        numFound = 0;
  1.2082 +                        }
  1.2083 +                    else
  1.2084 +                        {
  1.2085 +                        if (numFound == 0)
  1.2086 +                            {
  1.2087 +                            startPos = DosEntryPos1;
  1.2088 +                            }
  1.2089 +                        numFound++;
  1.2090 +                        if (numFound == aFileCreationHelper->NumOfAddingEntries())
  1.2091 +                            {
  1.2092 +                            aFileCreationHelper->SetEntryAddingPos(startPos);
  1.2093 +                            aFileCreationHelper->SetIsNewEntryPosFound(ETrue);
  1.2094 +                            }
  1.2095 +                        }
  1.2096 +                    }
  1.2097 +                if(MatchEntryAtt(DosEntry1.Attributes(),anAtt))
  1.2098 +                    {//-- FAT or VFAT dir entry is extracted and attributes match. Compare names then.
  1.2099 +
  1.2100 +                    if(StartEntry1.IsVFatEntry())
  1.2101 +                        {//-- extracted entry is VFAT one, name can be in UNICODE
  1.2102 +
  1.2103 +                        // we only check short name candidates for long file names with VFAT entries,
  1.2104 +                        //  if it is a valid dos name, it will be checked by default
  1.2105 +                        // note here target name is always fully specified
  1.2106 +                        if (aFileCreationHelper && aFileCreationHelper->IsInitialised())
  1.2107 +                            {
  1.2108 +                            aFileCreationHelper->CheckShortNameCandidates(DosEntry1.Name().Ptr());
  1.2109 +                            }
  1.2110 +
  1.2111 +                        TPtrC ptrAssembledName = RemoveTrailingDots(aFileName);
  1.2112 +
  1.2113 +                        if(ptrAssembledName.MatchF(aAuxParam.iTargetName) != KErrNotFound)
  1.2114 +                            {//-- found match in cache
  1.2115 +                            bCacheMatchFound = ETrue;
  1.2116 +                            goto Exit;
  1.2117 +                            }
  1.2118 +                        else if(aAuxParam.TrgtNameIsLegalDos())
  1.2119 +                            {
  1.2120 +                            if(aAuxParam.MatchDosEntryName(DosEntry1.Name().Ptr()))
  1.2121 +                                {
  1.2122 +                                bCacheMatchFound = ETrue;
  1.2123 +                                goto Exit;
  1.2124 +                                }
  1.2125 +                            }
  1.2126 +                        }//if(StartEntry1.IsVFatEntry())
  1.2127 +                    else if(aAuxParam.TrgtNameIsLegalDos())
  1.2128 +                        {//-- this is an old DOS FAT entry
  1.2129 +
  1.2130 +                          if(aAuxParam.MatchDosEntryName(DosEntry1.Name().Ptr()))
  1.2131 +                            {
  1.2132 +                            //-- Here is the trick that helps with the situation when VFAT entry is split into 2 halves
  1.2133 +                            //-- between 2 clusters (or/and cache pages). I.e. 1st part of this long entry belongs to one cluster and even more might not be cached,
  1.2134 +                            //-- While the rest of the entry, DOS part of it is the 1st entry in the cluster and cached.
  1.2135 +                            //-- In this case if we search for short file name, we find it, but the aStartEntryPos will be incorrect, which leads to the directory corruption.
  1.2136 +                            //-- The simple and quick solution - discard 1st DOS entry and return to old search. It shall be quite rare.
  1.2137 +                            if(StartEntryPos1.iPos == 0)
  1.2138 +                                {//-- this is the 1st FAT entry in the cluster. Discard it, see comments above.
  1.2139 +                                __PRINT(_L("#------ CFatMountCB::DoRummageDirCacheL() discarding FAT Entry!!"));
  1.2140 +                                goto Exit;
  1.2141 +                                }
  1.2142 +
  1.2143 +                            bCacheMatchFound = ETrue;
  1.2144 +                            goto Exit;
  1.2145 +                            }
  1.2146 +                        }
  1.2147 +
  1.2148 +                    }//if(bGotEntry && MatchEntryAtt(DosEntry1.Attributes(),anAtt))
  1.2149 +
  1.2150 +                // check boundaries after GetDirEntry()
  1.2151 +                // if we have cross the cluster boundary, break the for loop
  1.2152 +                if(DosEntryPos1.iCluster != clSave)
  1.2153 +                    {//-- GetDirEntry() has decided to move to the next cluster.
  1.2154 +                    DosEntryPos1.iCluster = clSave;
  1.2155 +                    break;
  1.2156 +                    }
  1.2157 +
  1.2158 +                // if we are still in the same cluster, check the page boundary by
  1.2159 +                /// exam how many entries we have scanned within the cluster
  1.2160 +                const TUint entriesLooked =  ((DosEntryPos1.iPos + KSizeOfFatDirEntry)- pageStartPos) >> KSizeOfFatDirEntryLog2;
  1.2161 +                if(entriesLooked > nEntries)
  1.2162 +                    {
  1.2163 +                    PassedPageBoundary = ETrue;
  1.2164 +                    break;
  1.2165 +                    }
  1.2166 +
  1.2167 +
  1.2168 +                // move to next entry before scanning next file
  1.2169 +                TRAP(nErr,MoveToNextEntryL(DosEntryPos1));
  1.2170 +                if(nErr != KErrNone)
  1.2171 +                    goto Exit;
  1.2172 +
  1.2173 +                // check boundaries after MoveToNextEntryL()
  1.2174 +                if(DosEntryPos1.iCluster != clSave)
  1.2175 +                    {
  1.2176 +                    DosEntryPos1.iCluster = clSave;
  1.2177 +                    break;
  1.2178 +                    }
  1.2179 +
  1.2180 +                if (entriesLooked + 1 > nEntries)
  1.2181 +                    {
  1.2182 +                    PassedPageBoundary = ETrue;
  1.2183 +                    break;
  1.2184 +                    }
  1.2185 +
  1.2186 +                } //for(;;)
  1.2187 +
  1.2188 +            } //if(iRawDisk->PosCached(...))
  1.2189 +
  1.2190 +        // scanning did not happen because the page is not cached,
  1.2191 +        // or
  1.2192 +        // scanning finished in last page and file is not found
  1.2193 +
  1.2194 +        // if MRU page is not cached or
  1.2195 +        // we scan MRU page first and it is not scanned yet, then this must be the MRU page,
  1.2196 +        //  we now start to scan from the beginning
  1.2197 +        if (ScanMRUPageFirst && !MRUPageScanned)
  1.2198 +            {
  1.2199 +            MRUPageScanned = ETrue;
  1.2200 +            DosEntryPos1 = aDosEntryPos;
  1.2201 +            DosEntryPos1.iPos = 0;
  1.2202 +            continue;
  1.2203 +            }
  1.2204 +
  1.2205 +        // if we just finished scanning a page and still in the same cluster, then we crossed page
  1.2206 +        //  boundary, continue with next page.
  1.2207 +        // note: although we are in the 'next page' already, this page might not be cached, so we need to
  1.2208 +        //  check it via pDirCache->PosCached(entryLinPos, nCachedLinPos) and scan it properly.
  1.2209 +        if (PassedPageBoundary)
  1.2210 +            {
  1.2211 +            DosEntryPos1.iPos = CalculatePageOffsetInCluster(DosEntryPos1.iPos, pageSzLog2);
  1.2212 +            PassedPageBoundary = EFalse;
  1.2213 +            continue;
  1.2214 +            }
  1.2215 +
  1.2216 +        //-- try to move to the next cluster of the directory file
  1.2217 +
  1.2218 +        if(DosEntryPos1.Cluster() < KFatFirstSearchCluster)  //-- small trick to get rid of TRAPping GetNextClusterL()
  1.2219 +            break;
  1.2220 +
  1.2221 +        // record previous cluster number before move on
  1.2222 +        clusterNum = DosEntryPos1.iCluster;
  1.2223 +
  1.2224 +        if(! FAT().GetNextClusterL(DosEntryPos1.iCluster))
  1.2225 +            break;
  1.2226 +
  1.2227 +
  1.2228 +    } //for(TUint32 entryCnt=0; entryCnt< maxDirEntries; ++entryCnt)
  1.2229 +
  1.2230 +    //---------------------------------
  1.2231 +    Exit:
  1.2232 +
  1.2233 +    if(bCacheMatchFound)
  1.2234 +        {
  1.2235 +        //-- if the position of the found in cache object is less than given, pretend that we haven't found anything
  1.2236 +        //-- Return to the old search, because it can be the case of the end of directory, which is quite difficult to
  1.2237 +        //-- detect in this situation. Note that the old part of DoFindL() leaves when the search reaches the end of dir.
  1.2238 +        TBool bFallBack=EFalse;
  1.2239 +
  1.2240 +        if(DosEntryPos1.iCluster == aDosEntryPos.iCluster)
  1.2241 +            {
  1.2242 +            if(DosEntryPos1.iPos < aDosEntryPos.iPos)
  1.2243 +                bFallBack = ETrue;
  1.2244 +            }
  1.2245 +        else
  1.2246 +            {
  1.2247 +            if(MakeLinAddrL(DosEntryPos1) < MakeLinAddrL(aDosEntryPos))
  1.2248 +                bFallBack = ETrue;
  1.2249 +            }
  1.2250 +
  1.2251 +        if(bFallBack)
  1.2252 +            {
  1.2253 +            return EFalse;
  1.2254 +            }
  1.2255 +
  1.2256 +        //-- Update parameters with new values
  1.2257 +        aStartEntryPos= StartEntryPos1;
  1.2258 +        aDosEntryPos  = DosEntryPos1;
  1.2259 +        aStartEntry   = StartEntry1;
  1.2260 +        aDosEntry     = DosEntry1;
  1.2261 +
  1.2262 +        const TInt64  mruPos = MakeLinAddrL(aDosEntryPos);
  1.2263 +        
  1.2264 +        pDirCache->MakePageMRU(mruPos);
  1.2265 +
  1.2266 +        // only update the leaf dir cache when the original cache index is provided
  1.2267 +        if (aLeafDir.iClusterNum)
  1.2268 +            {
  1.2269 +            iLeafDirCache->UpdateMRUPos(TLeafDirData(aLeafDir.iClusterNum, aStartEntryPos));
  1.2270 +            }
  1.2271 +        }
  1.2272 +    return bCacheMatchFound;
  1.2273 +    }
  1.2274 +
  1.2275 +//-----------------------------------------------------------------------------------------
  1.2276 +
  1.2277 +/**
  1.2278 +    initialise find helper with the target file name.
  1.2279 +    This is a quite expensive operation and initialisation is done only once. After this we know if the name is a legal dos one
  1.2280 +    and also have the corresponding generated DOS name for it.
  1.2281 +
  1.2282 +    @param aTargetName target file name we are looking for in ::DoFindL()
  1.2283 +*/
  1.2284 +void CFatMountCB::TFindHelper::InitialiseL(const TDesC& aTargetName)
  1.2285 +    {
  1.2286 +    if(isInitialised)
  1.2287 +        return;
  1.2288 +
  1.2289 +     TInt count = 1;
  1.2290 +
  1.2291 +     iTargetName.Set(aTargetName);
  1.2292 +     isLegalDosName = IsLegalDosName(aTargetName, ETrue, EFalse, EFalse, ETrue, EFalse);
  1.2293 +
  1.2294 +     if(isLegalDosName)
  1.2295 +        {//-- iShortName will contain generated short DOS name by long filename
  1.2296 +        iShortName = DoGenerateShortNameL(aTargetName, count, ETrue);
  1.2297 +        }
  1.2298 +
  1.2299 +     isInitialised = ETrue;
  1.2300 +    }
  1.2301 +
  1.2302 +/**
  1.2303 +    Perform binary comparison between a given the DOS entry name and the DOS name we generated in TFindHelper::Initialise().
  1.2304 +    @param  apDosEntryName pointer to the DOS entry name in XXXXXXXXYYY format
  1.2305 +    @return ETrue if the apDosEntryName is the same as generated iShortName
  1.2306 +*/
  1.2307 +TBool CFatMountCB::TFindHelper::MatchDosEntryName(const TUint8* apDosEntryName) const
  1.2308 +    {
  1.2309 +    ASSERT(isInitialised);
  1.2310 +
  1.2311 +    if(!isLegalDosName)
  1.2312 +        return EFalse;
  1.2313 +
  1.2314 +    return (Mem::Compare(iShortName.Ptr(), KFatDirNameSize, apDosEntryName, KFatDirNameSize) == 0);
  1.2315 +    }
  1.2316 +
  1.2317 +//-----------------------------------------------------------------------------------------
  1.2318 +const TInt KShortNameCandidatesNum = 4;
  1.2319 +/**
  1.2320 +Constructor of XFileCreationHelper class
  1.2321 +*/
  1.2322 +CFatMountCB::XFileCreationHelper::XFileCreationHelper()
  1.2323 +    {
  1.2324 +    isInitialised = EFalse;
  1.2325 +    }
  1.2326 +
  1.2327 +/**
  1.2328 +Destructor of XFileCreationHelper class
  1.2329 +*/
  1.2330 +CFatMountCB::XFileCreationHelper::~XFileCreationHelper()
  1.2331 +    {
  1.2332 +    Close();
  1.2333 +    }
  1.2334 +
  1.2335 +/**
  1.2336 +Initialises a TFileCreationHelper object, generate a short name candidate pool.
  1.2337 +
  1.2338 +@param  aTargetName Target file name for the potential new file.
  1.2339 +@post   TFileCreationHelper is fully initialised.
  1.2340 +*/
  1.2341 +void CFatMountCB::XFileCreationHelper::InitialiseL(const TDesC& aTargetName)
  1.2342 +    {
  1.2343 +    // close before use, to avoid memory leak
  1.2344 +    Close();
  1.2345 +
  1.2346 +    iTargetName.Set(aTargetName);
  1.2347 +    // generates short name candidate(s)
  1.2348 +    TInt count = 1;
  1.2349 +    while (count <= KShortNameCandidatesNum)
  1.2350 +        {
  1.2351 +        TShortName shortNameCandidate = DoGenerateShortNameL(aTargetName, count, ETrue);
  1.2352 +        TInt err = iShortNameCandidates.Append(shortNameCandidate);
  1.2353 +        User::LeaveIfError(err);
  1.2354 +
  1.2355 +        if (count == -1)    // No tilde and number is needed
  1.2356 +            {
  1.2357 +            break;
  1.2358 +            }
  1.2359 +        else
  1.2360 +            count++;
  1.2361 +        }
  1.2362 +
  1.2363 +    // calculate number of new entries needed
  1.2364 +    iNumOfAddingEntries = 1;
  1.2365 +    isTrgNameLegalDosName = IsLegalDosName(aTargetName, EFalse, EFalse, EFalse, EFalse, ETrue);
  1.2366 +    if (!isTrgNameLegalDosName)
  1.2367 +        iNumOfAddingEntries = (TUint16) NumberOfVFatEntries(iTargetName.Length());
  1.2368 +
  1.2369 +    isNewEntryPosFound = EFalse;
  1.2370 +    isInitialised = ETrue;
  1.2371 +    }
  1.2372 +
  1.2373 +/**
  1.2374 +Close function of XFileCreationHelper class
  1.2375 +*/
  1.2376 +void CFatMountCB::XFileCreationHelper::Close()
  1.2377 +    {
  1.2378 +    iShortNameCandidates.Close();
  1.2379 +    isInitialised = EFalse;
  1.2380 +    }
  1.2381 +
  1.2382 +/**
  1.2383 +Validates short name candidates. If the input dos entry name is found in the short name
  1.2384 + candidate pool, the corresponding short name candidate will be removed from the pool.
  1.2385 +
  1.2386 +@param  apDosEntryName  An existing short name, to compare with the candidates.
  1.2387 +@pre    Object should be initialised
  1.2388 +*/
  1.2389 +void CFatMountCB::XFileCreationHelper::CheckShortNameCandidates(const TUint8* apDosEntryName)
  1.2390 +    {
  1.2391 +    ASSERT(isInitialised);
  1.2392 +    if (!isInitialised)
  1.2393 +        return;
  1.2394 +
  1.2395 +    if (iShortNameCandidates.Count() > 0)
  1.2396 +        {
  1.2397 +        for (TInt i = 0; i < iShortNameCandidates.Count(); i++)
  1.2398 +            {
  1.2399 +            if (Mem::Compare(iShortNameCandidates[i].Ptr(), KFatDirNameSize, apDosEntryName, KFatDirNameSize) == 0)
  1.2400 +                {
  1.2401 +                iShortNameCandidates.Remove(i);
  1.2402 +                break;
  1.2403 +                }
  1.2404 +            }
  1.2405 +        }
  1.2406 +    }
  1.2407 +
  1.2408 +/**
  1.2409 +Gets a validated short name from the short name candidate pool.
  1.2410 +
  1.2411 +@param  aShortName  On return, contains a validated short name if found, otherwise zeroed.
  1.2412 +@return TInt        Returns KErrNone if a validated short name found successfully,
  1.2413 +                     else KErrNotFound is returned.
  1.2414 +                    Returns KErrNotReady if object is not initialised.
  1.2415 +@pre    Object should be initialised
  1.2416 +*/
  1.2417 +TInt CFatMountCB::XFileCreationHelper::GetValidatedShortName(TShortName& aShortName) const
  1.2418 +    {
  1.2419 +    aShortName.Zero();
  1.2420 +
  1.2421 +    ASSERT(isInitialised);
  1.2422 +    if (!isInitialised)
  1.2423 +        return KErrNotReady;
  1.2424 +
  1.2425 +    if (iShortNameCandidates.Count() > 0)
  1.2426 +        {
  1.2427 +        aShortName.Copy(iShortNameCandidates[0]);
  1.2428 +        return KErrNone;
  1.2429 +        }
  1.2430 +
  1.2431 +    return KErrNotFound;
  1.2432 +    }
  1.2433 +
  1.2434 +//-----------------------------------------------------------------------------------------
  1.2435 +
  1.2436 +
  1.2437 +/**
  1.2438 +    Scan a directory looking for aName.
  1.2439 +
  1.2440 +    @param  aTrgtName       a name of an object we are looking up in directory
  1.2441 +    @param  anAtt           attributes of this object
  1.2442 +    @param  aStartEntryPos  on return in case of VFAT entry will contain start position of the VFAT dir. entry
  1.2443 +    @param  aStartEntry     on return will contain first VFAT dir entry
  1.2444 +    @param  aDosEntryPos    the search will start from this position of dir entry, on return it will contain result DOS entry position, last one for VFAT case
  1.2445 +    @param  aDosEntry       on return will contain DOS dir entry (the last one for VFAT case)
  1.2446 +    @param  aFileName       in the case of VFAT entry and on success here will be returned a long filename
  1.2447 +    @param  anError         This function might leave with this given error code
  1.2448 +    @param  aFileCreationHelper       a helper package for file creations
  1.2449 +
  1.2450 +    @return ETrue if extracted entry is VFAT one, EFalse, if it's old DOS-style one
  1.2451 +    @leave  can leave with anError code on error or if the search has reached the end of directory (!)
  1.2452 +*/
  1.2453 +TBool CFatMountCB::DoFindL(const TDesC& aTrgtName,TUint anAtt,
  1.2454 +                        TEntryPos& aStartEntryPos,TFatDirEntry& aStartEntry,
  1.2455 +                        TEntryPos& aDosEntryPos,TFatDirEntry& aDosEntry,
  1.2456 +                        TDes& aFileName,TInt anError,
  1.2457 +                        XFileCreationHelper* aFileCreationHelper,
  1.2458 +                        const TLeafDirData& aLeafDirData) const
  1.2459 +    {
  1.2460 +    // check that the entry position to be read next is not past the end of the
  1.2461 +    // root directory. If this is the case then when GetDirEntryL(..) is called
  1.2462 +    // this will lead to MakeLinAddr(..) leaving with KErrDirFull.
  1.2463 +
  1.2464 +    if (IsRootDir(aDosEntryPos)&&(aDosEntryPos.iPos+StartOfRootDirInBytes()>=RootDirEnd()))
  1.2465 +        User::Leave(anError);//Allows maximum number of entries in root directory
  1.2466 +
  1.2467 +    __PRINT2(_L("CFatMountCB::DoFindL() drv:%d, %S"),Drive().DriveNumber(),&aTrgtName);
  1.2468 +
  1.2469 +    TInt previousCluster=aDosEntryPos.iCluster;
  1.2470 +    TUint previousPosition=aDosEntryPos.iPos;
  1.2471 +    TInt changePreviousCluster=1;
  1.2472 +    TInt count=0;
  1.2473 +
  1.2474 +    TBool trgNameIsWildCard     = EFalse; //-- ETrue if the name we are looking for is a wildcard
  1.2475 +    TBool trgNameFullySpecified = ETrue;  //-- ETrue if the name we are looking for doesn't contain wildcards
  1.2476 +
  1.2477 +
  1.2478 +    {
  1.2479 +    //-- find out if the name we are looking for is a wildcard ("*" or "*.*")
  1.2480 +    const TInt len = aTrgtName.Length();
  1.2481 +
  1.2482 +    if(len == 1)
  1.2483 +        trgNameIsWildCard = (aTrgtName[0] == '*');
  1.2484 +    else if(len == 3)
  1.2485 +        {
  1.2486 +        _LIT(KAllFiles, "*.*");
  1.2487 +        trgNameIsWildCard = (aTrgtName==KAllFiles);
  1.2488 +        }
  1.2489 +
  1.2490 +    //-- find out if the name we are looking for contains wildcharacters: "*" or "?"
  1.2491 +    if(trgNameIsWildCard)
  1.2492 +        trgNameFullySpecified = EFalse;
  1.2493 +    else
  1.2494 +        {
  1.2495 +        for(TInt i=0; i<len; ++i)
  1.2496 +            {
  1.2497 +            const TChar ch = aTrgtName[i];
  1.2498 +            if(ch == (TChar)'*' || ch == (TChar)'?')
  1.2499 +                {
  1.2500 +                trgNameFullySpecified = EFalse;
  1.2501 +                break;
  1.2502 +                }
  1.2503 +            }
  1.2504 +        }
  1.2505 +    }
  1.2506 +
  1.2507 +
  1.2508 +    TPtrC trgtNameNoDot(aTrgtName);
  1.2509 +
  1.2510 +    TFindHelper findHelper;
  1.2511 +    //---------------------------------------------------
  1.2512 +    //-- if we have fully specified name and directory cache is present, try to
  1.2513 +    //-- locate the name in the cache first to avoid reading from media
  1.2514 +    //-- if the entry belongs to the root directory (for FAT12,16) skip the lookup, because root directory isn't aligned by cluster size boundary,
  1.2515 +    //-- while directory cache pages are. For FAT32 it doesn't matter, because root dir is a usual file.
  1.2516 +    if(iRawDisk->DirCacheInterface() && trgNameFullySpecified && !IsRootDir(aDosEntryPos) && !aFileCreationHelper)
  1.2517 +        {//-- aName is fully specified, i.e doesn't contain wildcards
  1.2518 +
  1.2519 +        findHelper.InitialiseL(trgtNameNoDot);
  1.2520 +
  1.2521 +        const TBool bMatchFound = DoRummageDirCacheL(anAtt, aStartEntryPos, aStartEntry, aDosEntryPos, aDosEntry, aFileName, findHelper, aFileCreationHelper, aLeafDirData);
  1.2522 +        if(bMatchFound)
  1.2523 +            {
  1.2524 +            return(aStartEntry.IsVFatEntry());
  1.2525 +            }
  1.2526 +        }
  1.2527 +    //---------------------------------------------------
  1.2528 +
  1.2529 +    // we need to scan ahead from the mru pos then come back to beginning, if startcluster is provided
  1.2530 +    TBool scanAhead = EFalse;
  1.2531 +    // if we have a starting cluster number (and it's not root directory in FAT16/12 case)&&
  1.2532 +    //  we found a lastScanned entry's cluster (and it's not root directory in FAT16/12 case)&&
  1.2533 +    // if we don't have a starting cluster number, we draw back to original scanning algorithm
  1.2534 +    if (!IsRootDir(aDosEntryPos)            // we don't do forward scanning for root dir &
  1.2535 +            && aLeafDirData.iClusterNum != 0    // if we have a starting cluster number &
  1.2536 +            && aLeafDirData.iMRUPos.Cluster() != 0)     // if we have a starting cluster number &
  1.2537 +        {
  1.2538 +        scanAhead = ETrue;
  1.2539 +        aDosEntryPos = aLeafDirData.iMRUPos;
  1.2540 +        }
  1.2541 +
  1.2542 +    TInt numFound = 0;
  1.2543 +    TEntryPos startPos = aDosEntryPos;
  1.2544 +    TInt clustNum = aDosEntryPos.Cluster();
  1.2545 +
  1.2546 +    for (TInt scanCnt = 1; scanCnt <= 2; ++scanCnt)
  1.2547 +        {
  1.2548 +        // if we are not scanning ahead, we don't need this outer for loop
  1.2549 +        if (!scanAhead)
  1.2550 +            scanCnt++;
  1.2551 +
  1.2552 +        TBool found = EFalse;
  1.2553 +
  1.2554 +        FOREVER //FOREVER2 -- walk through all directory entries in the current directory until find a match or directory end
  1.2555 +            {
  1.2556 +            //-- read full directory entry starting from aDosEntryPos. On return aFileName may contain assembled long filename (if the entry is VFAT)
  1.2557 +            //-- aDosEntry will contain a DOS entry of the directory entry we have read.
  1.2558 +            aStartEntryPos=aDosEntryPos;
  1.2559 +            User::LeaveIfError(GetDirEntry(aDosEntryPos, aDosEntry, aStartEntry, aFileName));
  1.2560 +
  1.2561 +            if (aDosEntry.IsEndOfDirectory())
  1.2562 +                {//-- the end of directory reached.
  1.2563 +
  1.2564 +                // if new entry position for adding has not been found yet.
  1.2565 +                // note aFileCreationHelper may not be initialised for pure file opening operations
  1.2566 +                if (aFileCreationHelper && aFileCreationHelper->IsInitialised() && !aFileCreationHelper->IsNewEntryPosFound())
  1.2567 +                    {
  1.2568 +                    // if MoveToNextEntryL have gone to the next cluster which is the end of cluster chain,
  1.2569 +                    //  we pass the last scanned entry position to AddDirEntryL
  1.2570 +                    if (IsEndOfClusterCh(aDosEntryPos.iCluster))
  1.2571 +                        {
  1.2572 +                        TInt clusterSize=1<<ClusterSizeLog2();
  1.2573 +                        TEntryPos dummyPos(clustNum, clusterSize - KSizeOfFatDirEntry);
  1.2574 +                        aFileCreationHelper->SetEntryAddingPos(dummyPos);
  1.2575 +                        aFileCreationHelper->SetIsNewEntryPosFound(ETrue);
  1.2576 +                        }
  1.2577 +                    // or we reached the end of the directory.
  1.2578 +                    else
  1.2579 +                        {
  1.2580 +                        aFileCreationHelper->SetEntryAddingPos(aDosEntryPos);
  1.2581 +                        aFileCreationHelper->SetIsNewEntryPosFound(ETrue);
  1.2582 +                        }
  1.2583 +                    }
  1.2584 +
  1.2585 +                // if we are scanning ahead and this is the first scanning, we break out to restart scanning
  1.2586 +                if (scanAhead && scanCnt == 1)
  1.2587 +                    {
  1.2588 +                    break; // from FOREVER, restart scanning
  1.2589 +                    }
  1.2590 +
  1.2591 +                // if (!scanAhead || scanAhead && scanCnt == 2)
  1.2592 +                User::Leave(anError);
  1.2593 +                }
  1.2594 +
  1.2595 +
  1.2596 +            // entry space searching for potential new file/directory creation
  1.2597 +            if (aFileCreationHelper && aFileCreationHelper->IsInitialised() && !aFileCreationHelper->IsNewEntryPosFound())
  1.2598 +                {
  1.2599 +                if (!aDosEntry.IsErased() && !aDosEntry.IsGarbage())
  1.2600 +                    {
  1.2601 +                    numFound = 0;
  1.2602 +                    }
  1.2603 +                else
  1.2604 +                    {
  1.2605 +                    if (numFound == 0)
  1.2606 +                        {
  1.2607 +                        startPos = aDosEntryPos;
  1.2608 +                        }
  1.2609 +                    numFound++;
  1.2610 +                    if (numFound == aFileCreationHelper->NumOfAddingEntries())
  1.2611 +                        {
  1.2612 +                        aFileCreationHelper->SetEntryAddingPos(startPos);
  1.2613 +                        aFileCreationHelper->SetIsNewEntryPosFound(ETrue);
  1.2614 +                        }
  1.2615 +                    }
  1.2616 +                }
  1.2617 +
  1.2618 +
  1.2619 +            if (IsRootDir(aDosEntryPos)&&(aDosEntryPos.iPos+StartOfRootDirInBytes()==(RootDirEnd()-KSizeOfFatDirEntry)))
  1.2620 +                if (aDosEntry.IsErased())
  1.2621 +                    {
  1.2622 +                    User::Leave(anError);//Allows maximum number of entries in root directory
  1.2623 +                    }
  1.2624 +
  1.2625 +
  1.2626 +            const TBool bFileNameEntry = !aDosEntry.IsCurrentDirectory() && !aDosEntry.IsParentDirectory() && !aDosEntry.IsErased() && !aDosEntry.IsGarbage();
  1.2627 +
  1.2628 +            if (bFileNameEntry && MatchEntryAtt(aDosEntry.Attributes(), anAtt))
  1.2629 +                {//-- we have read a filename entry and entry's attributes match required; compare names then.
  1.2630 +
  1.2631 +                if (trgNameIsWildCard)
  1.2632 +                    {
  1.2633 +                    found = ETrue;
  1.2634 +                    break; //-- we were looking for '*' or '*.*', so will be satisfied with any current file name.
  1.2635 +                    }
  1.2636 +
  1.2637 +
  1.2638 +                if (aStartEntry.IsVFatEntry())
  1.2639 +                    {//-- we've read a VFAT entry, aFileName is supposed to contain long filename, aDosEntry - DOS entry for this name.
  1.2640 +                     //-- note: aFileName.Length() may be 0, while DOS entry (short name is OK) in the case of orphaned VFAT entries
  1.2641 +
  1.2642 +
  1.2643 +                    // we only check short name candidates for long file names with VFAT entries,
  1.2644 +                    //  if it is a valid dos name, it will be checked by default
  1.2645 +                    // note, for file creation cases, target name will be always fully specified
  1.2646 +                    if (aFileCreationHelper && aFileCreationHelper->IsInitialised() && trgNameFullySpecified)
  1.2647 +                         {
  1.2648 +                         aFileCreationHelper->CheckShortNameCandidates(aDosEntry.Name().Ptr());
  1.2649 +                         }
  1.2650 +
  1.2651 +                    //-- discard trailing dots from aFileName if present
  1.2652 +                     TPtrC ptrAssembledName = RemoveTrailingDots(aFileName);
  1.2653 +
  1.2654 +                     if(ptrAssembledName.MatchF(trgtNameNoDot) != KErrNotFound)
  1.2655 +                         {
  1.2656 +                         found = ETrue;
  1.2657 +                         break; //-- OK, found a match.
  1.2658 +                         }
  1.2659 +                     else if (trgNameFullySpecified)
  1.2660 +                         {
  1.2661 +                         //-- long name assembled by GetDirEntry() doesn't match the target. But if he target name is fully specified,
  1.2662 +                         //-- we need to compare corresponding DOS entries, because VFAT entries may be damaged, while DOS ones are OK.
  1.2663 +                         findHelper.InitialiseL(trgtNameNoDot);
  1.2664 +
  1.2665 +                         if(findHelper.MatchDosEntryName(aDosEntry.Name().Ptr()))
  1.2666 +                             {
  1.2667 +                             found = ETrue;
  1.2668 +                             break; //-- DOS entries match, success.
  1.2669 +                             }
  1.2670 +                         }
  1.2671 +                     else if (!trgNameFullySpecified)
  1.2672 +                         {//-- target name contains wildcards, we need to use MatchF with dos name
  1.2673 +                         TBuf8<0x20> dosName8(DosNameFromStdFormat(aDosEntry.Name()));
  1.2674 +                         TBuf<0x20>  dosName;
  1.2675 +                         LocaleUtils::ConvertToUnicodeL(dosName, dosName8); //-- convert DOS name to unicode (implies locale settings)
  1.2676 +                         if (dosName.MatchF(trgtNameNoDot)!=KErrNotFound)
  1.2677 +                             {
  1.2678 +                             found = ETrue;
  1.2679 +                             break;
  1.2680 +                             }
  1.2681 +                         }
  1.2682 +
  1.2683 +
  1.2684 +                    }
  1.2685 +                else //if (aStartEntry.IsVFatEntry())
  1.2686 +                    {//-- we've read a legacy FAT entry, so compare DOS entries
  1.2687 +                    findHelper.InitialiseL(trgtNameNoDot);
  1.2688 +
  1.2689 +                    if(findHelper.TrgtNameIsLegalDos())
  1.2690 +                        {//-- we are looking for a legal DOS name
  1.2691 +                        if(trgNameFullySpecified)
  1.2692 +                            {//-- if the target name is fully specified, we can yse binary comparison of the DOS entries
  1.2693 +                            if(findHelper.MatchDosEntryName(aDosEntry.Name().Ptr()))
  1.2694 +                                {
  1.2695 +                                found = ETrue;
  1.2696 +                                break;
  1.2697 +                                }
  1.2698 +                            }
  1.2699 +                        else
  1.2700 +                            {//-- target name contains wildcards, we neeed to use MatchF
  1.2701 +                            TBuf8<0x20> dosName8(DosNameFromStdFormat(aDosEntry.Name()));
  1.2702 +                            TBuf<0x20>  dosName;
  1.2703 +                            LocaleUtils::ConvertToUnicodeL(dosName, dosName8); //-- convert DOS name to unicode (implies locale settings)
  1.2704 +                            if (dosName.MatchF(trgtNameNoDot)!=KErrNotFound)
  1.2705 +                                {
  1.2706 +                                found = ETrue;
  1.2707 +                                break;
  1.2708 +                                }
  1.2709 +
  1.2710 +                            }
  1.2711 +                        } //if(findHelper.TrgtNameIsLegalDos())
  1.2712 +
  1.2713 +                    } //else if (aStartEntry.IsVFatEntry())
  1.2714 +
  1.2715 +                } //if (bFileNameEntry && MatchEntryAtt(aDosEntry.Attributes(),anAtt))
  1.2716 +
  1.2717 +
  1.2718 +            // record previous cluster number
  1.2719 +            clustNum = aDosEntryPos.iCluster;
  1.2720 +
  1.2721 +            // this is the 2nd scanning and we have just passed the pos we started.
  1.2722 +            if (scanAhead && scanCnt == 2)
  1.2723 +                {
  1.2724 +                if (aDosEntryPos.Cluster() == aLeafDirData.iMRUPos.Cluster()
  1.2725 +                        && aDosEntryPos.Pos() >= aLeafDirData.iMRUPos.Pos())
  1.2726 +                    {
  1.2727 +                    User::Leave(anError);
  1.2728 +                    }
  1.2729 +                }
  1.2730 +
  1.2731 +
  1.2732 +            MoveToNextEntryL(aDosEntryPos); //-- goto the next entry in the directory
  1.2733 +
  1.2734 +            if (IsRootDir(aDosEntryPos)&&(aDosEntryPos.iPos+StartOfRootDirInBytes()>=RootDirEnd()))
  1.2735 +                {
  1.2736 +                User::Leave(anError);//Allows maximum number of entries in root directory
  1.2737 +                }
  1.2738 +
  1.2739 +
  1.2740 +            if (!scanAhead || scanCnt == 2)
  1.2741 +                {
  1.2742 +                if (aDosEntryPos.iCluster && (aDosEntryPos.iPos <= previousPosition))
  1.2743 +                    DoCheckFatForLoopsL(aDosEntryPos.iCluster,previousCluster,changePreviousCluster,count);
  1.2744 +
  1.2745 +                previousPosition=aDosEntryPos.iPos;
  1.2746 +                }
  1.2747 +            }   // FOREVER -- the actual scanning is done inside this loop
  1.2748 +
  1.2749 +
  1.2750 +        if (found)
  1.2751 +            {
  1.2752 +            break;
  1.2753 +            }
  1.2754 +
  1.2755 +        // if not found:
  1.2756 +        // if we have not found in the first scanning and we are doing scanning ahead,
  1.2757 +        //  we need to go back to the starting pos of this dir and scan from start until
  1.2758 +        //  we reach lastscannedPos
  1.2759 +        if (scanAhead && scanCnt == 1)
  1.2760 +            {
  1.2761 +            aDosEntryPos = TEntryPos(aLeafDirData.iClusterNum, 0);
  1.2762 +            continue;
  1.2763 +            }
  1.2764 +        else
  1.2765 +            {
  1.2766 +            // there are only two exits: either found or reached end of dir in the 1st scanning
  1.2767 +            ASSERT(0);
  1.2768 +            break;
  1.2769 +            }
  1.2770 +        } // for (TInt scanCnt = 1; scanCnt <= 2; ++scanCnt)
  1.2771 +
  1.2772 +    //---------------------------------------------------
  1.2773 +    if (iRawDisk->DirCacheInterface() && aDosEntryPos.Cluster())
  1.2774 +        {
  1.2775 +        TInt64 mruPos = MakeLinAddrL(aDosEntryPos);
  1.2776 +        iRawDisk->DirCacheInterface()->MakePageMRU(mruPos);
  1.2777 +
  1.2778 +        // only update the leaf dir cache when the original cache index is provided
  1.2779 +        if (aLeafDirData.iClusterNum)
  1.2780 +            {
  1.2781 +            iLeafDirCache->UpdateMRUPos(TLeafDirData(aLeafDirData.iClusterNum, aDosEntryPos));
  1.2782 +            }
  1.2783 +        }
  1.2784 +
  1.2785 +    return (aStartEntry.IsVFatEntry());
  1.2786 +    }
  1.2787 +
  1.2788 +//-----------------------------------------------------------------------------------------
  1.2789 +/**
  1.2790 +    Locate an directory entry entry from its full path name.
  1.2791 +
  1.2792 +    @param  aName           a name of an object we are looking for
  1.2793 +    @param  anAtt           attributes of this object
  1.2794 +    @param  anEntry         on return will contain first VFAT dir entry
  1.2795 +    @param  anEntryPos      on return in case of VFAT entry will contain start position of the VFAT dir. entry
  1.2796 +
  1.2797 +    @leave  can leave with KErrNotFound if the search has reached the end of directory
  1.2798 +*/
  1.2799 +void CFatMountCB::FindEntryStartL(const TDesC& aName,TUint anAtt,TFatDirEntry& anEntry,TEntryPos& anEntryPos) const
  1.2800 +    {
  1.2801 +    __PRINT(_L("CFatMountCB::FindEntryStartL()"));
  1.2802 +    TInt namePos=aName.LocateReverse(KPathDelimiter)+1; // There is always a path delimiter
  1.2803 +    TFileName fileName;
  1.2804 +    TLeafDirData leafDir;
  1.2805 +    TEntryPos dosEntryPos(FindLeafDirL(aName.Left(namePos),leafDir),0);
  1.2806 +    TFatDirEntry dosEntry;
  1.2807 +
  1.2808 +    DoFindL(aName.Mid(namePos),anAtt,anEntryPos,anEntry,dosEntryPos,dosEntry,fileName,KErrNotFound,NULL,leafDir);
  1.2809 +    }
  1.2810 +
  1.2811 +
  1.2812 +//-----------------------------------------------------------------------------------------
  1.2813 +
  1.2814 +/**
  1.2815 +    Locate an directory entry entry from its full path name.
  1.2816 +
  1.2817 +    @param  aName           a name of an object we are looking for
  1.2818 +    @param  anAtt           attributes of this object
  1.2819 +    @param  anEntry         on return will contain first VFAT dir entry
  1.2820 +    @param  anEntryPos      on return in case of VFAT entry will contain start position of the VFAT dir. entry
  1.2821 +
  1.2822 +    @leave  can leave with KErrNotFound if the search has reached the end of directory
  1.2823 +*/
  1.2824 +void CFatMountCB::FindEntryStartL(const TDesC& aName,TUint anAtt,TFatDirEntry& anEntry,TEntryPos& anEntryPos,XFileCreationHelper* aFileCreationHelper) const
  1.2825 +    {
  1.2826 +    __PRINT(_L("CFatMountCB::FindEntryStartL()"));
  1.2827 +    TInt namePos=aName.LocateReverse(KPathDelimiter)+1; // There is always a path delimiter
  1.2828 +    TFileName fileName;
  1.2829 +    TLeafDirData leafDir;
  1.2830 +    TEntryPos dosEntryPos(FindLeafDirL(aName.Left(namePos),leafDir),0);
  1.2831 +    TFatDirEntry dosEntry;
  1.2832 +    DoFindL(aName.Mid(namePos),anAtt,anEntryPos,anEntry,dosEntryPos,dosEntry,fileName,KErrNotFound,aFileCreationHelper,leafDir);
  1.2833 +    }
  1.2834 +
  1.2835 +//-----------------------------------------------------------------------------------------
  1.2836 +void CFatMountCB::FindDosNameL(const TDesC& aName,TUint anAtt,TEntryPos& aDosEntryPos,TFatDirEntry& aDosEntry,TDes& aFileName,TInt anError) const
  1.2837 +//
  1.2838 +// Scan a directory looking for aName.
  1.2839 +// aCluster and anEntryAddr give the location of the entry.
  1.2840 +//
  1.2841 +    {
  1.2842 +
  1.2843 +    __PRINT(_L("CFatMountCB::FindDosNameL()"));
  1.2844 +    TEntryPos startPos;
  1.2845 +    TFatDirEntry startEntry;
  1.2846 +
  1.2847 +    TLeafDirData leafDir;           // leaf dir data is zero initialized, no scannig ahead
  1.2848 +    DoFindL(aName,anAtt,startPos,startEntry,aDosEntryPos,aDosEntry,aFileName,anError,NULL,leafDir);
  1.2849 +    }
  1.2850 +//-----------------------------------------------------------------------------------------
  1.2851 +
  1.2852 +void CFatMountCB::AddDirEntryL(TEntryPos& aPos,TInt aNumOfEntries)
  1.2853 +//
  1.2854 +// Find space for a new directory entry. Leave KErrEof if no space
  1.2855 +//
  1.2856 +    {
  1.2857 +
  1.2858 +    __PRINT(_L("CFatMountCB::AddDirEntryL"));
  1.2859 +    TInt numFound=0;
  1.2860 +    TFatDirEntry entry;
  1.2861 +    TEntryPos startPos(RootIndicator(),0);
  1.2862 +    TInt clusterNum=aPos.iCluster;
  1.2863 +    FOREVER
  1.2864 +        {
  1.2865 +        ReadDirEntryL(aPos,entry);
  1.2866 +        if (entry.IsEndOfDirectory())
  1.2867 +            break;
  1.2868 +        if (!entry.IsErased() && !entry.IsGarbage())
  1.2869 +            numFound=0;
  1.2870 +        else
  1.2871 +            {
  1.2872 +            if (numFound==0)
  1.2873 +                startPos=aPos;
  1.2874 +            numFound++;
  1.2875 +            if (numFound==aNumOfEntries)
  1.2876 +                {
  1.2877 +                aPos=startPos;
  1.2878 +                return;
  1.2879 +                }
  1.2880 +            }
  1.2881 +        clusterNum=aPos.iCluster;
  1.2882 +        MoveToNextEntryL(aPos);
  1.2883 +        if (IsRootDir(aPos)&&(StartOfRootDirInBytes()+aPos.iPos==RootDirEnd()))
  1.2884 +    //  No end of directory marker at end of root directory
  1.2885 +            User::Leave(KErrDirFull);
  1.2886 +        }
  1.2887 +
  1.2888 +    TUint clusterSize=1<<ClusterSizeLog2();
  1.2889 +    if (IsEndOfClusterCh(aPos.iCluster))
  1.2890 +        { // End of last cluster in directory
  1.2891 +        aPos.iCluster=clusterNum;
  1.2892 +        aPos.iPos=clusterSize;
  1.2893 +        }
  1.2894 +
  1.2895 +    TEntryPos eofPos(aPos.iCluster,aPos.iPos+KSizeOfFatDirEntry*aNumOfEntries);
  1.2896 +
  1.2897 +    if (IsRootDir(aPos))
  1.2898 +        { // Special case of root directory
  1.2899 +        if (eofPos.iPos+StartOfRootDirInBytes()>RootDirEnd())
  1.2900 +            User::Leave(KErrDirFull);
  1.2901 +        else
  1.2902 +            return;
  1.2903 +        }
  1.2904 +
  1.2905 +    if (eofPos.iPos==clusterSize)
  1.2906 +        return; // No need to allocate
  1.2907 +    if (eofPos.iPos>clusterSize)
  1.2908 +        {
  1.2909 +        TInt numNeeded=eofPos.iPos>>ClusterSizeLog2();
  1.2910 +        if(IsRuggedFSys())
  1.2911 +            {
  1.2912 +            ExtendClusterListZeroedL(numNeeded,eofPos.iCluster);
  1.2913 +            }
  1.2914 +        else
  1.2915 +            {
  1.2916 +            FAT().ExtendClusterListL(numNeeded,eofPos.iCluster);
  1.2917 +            ZeroDirClusterL(eofPos.iCluster);
  1.2918 +            }
  1.2919 +
  1.2920 +        eofPos.iPos-=numNeeded<<ClusterSizeLog2();
  1.2921 +        if(aPos.iPos==clusterSize)
  1.2922 +            {
  1.2923 +            if (!FAT().GetNextClusterL(aPos.iCluster))
  1.2924 +                {
  1.2925 +                __PRINT(_L("CFatMountCB::AddDirEntryL corrupt#1"))
  1.2926 +                User::Leave(KErrCorrupt);
  1.2927 +                }
  1.2928 +            aPos.iPos=0;
  1.2929 +            }
  1.2930 +        }
  1.2931 +    else if(Drive().IsRemovable())
  1.2932 +        {
  1.2933 +        // check if entry is already zeroed
  1.2934 +        ReadDirEntryL(eofPos,entry);
  1.2935 +        if(!entry.IsEndOfDirectory())
  1.2936 +            {
  1.2937 +            // some removable media may not have directory zeroed
  1.2938 +            entry.SetEndOfDirectory();
  1.2939 +            WriteDirEntryL(eofPos,entry);
  1.2940 +            }
  1.2941 +        }
  1.2942 +    }
  1.2943 +
  1.2944 +/**
  1.2945 +    Zero fill a cluster
  1.2946 +    @param  aCluster cluster number to zero-fill
  1.2947 +*/
  1.2948 +void CFatMountCB::ZeroDirClusterL(TInt aCluster)
  1.2949 +    {
  1.2950 +
  1.2951 +    __PRINT1(_L("CFatMountCB::ZeroDirClusterL %d"),aCluster);
  1.2952 +
  1.2953 +    const TUint32 KClusterSz= 1<<ClusterSizeLog2();
  1.2954 +    const TUint32 KMaxBufSz = KClusterSz;           //-- max. nuffer size is a cluster
  1.2955 +    const TUint32 KMinBufSz = 1<<SectorSizeLog2();  //-- min. buffer size is 1 sector (for OOM case)
  1.2956 +
  1.2957 +    //-- allocate a buffer for zero-filling a cluster
  1.2958 +    RBuf8 buf;
  1.2959 +    CleanupClosePushL(buf);
  1.2960 +
  1.2961 +    if(buf.CreateMax(KMaxBufSz) != KErrNone)
  1.2962 +        buf.CreateMaxL(KMinBufSz); //-- OOM, try to create smaller buffer
  1.2963 +
  1.2964 +    buf.FillZ();
  1.2965 +
  1.2966 +    TEntryPos entryPos(aCluster,0);
  1.2967 +
  1.2968 +    //-- write buffer to the beginning of the directory file.
  1.2969 +    DirWriteL(entryPos, buf); //-- use special interface to access FAT directory file
  1.2970 +
  1.2971 +    //-- fill in the rest of the cluster if we used a small buffer
  1.2972 +    if((TUint32)buf.Size() < KClusterSz) //--  KMaxBufSz may == KMinBufSz if we have 1 sector per cluster
  1.2973 +    {
  1.2974 +        const TInt restCnt = SectorsPerCluster() - 1;
  1.2975 +        ASSERT(restCnt >=1);
  1.2976 +
  1.2977 +        for(TInt i=0; i<restCnt; ++i)
  1.2978 +        {
  1.2979 +            entryPos.iPos += KMinBufSz;
  1.2980 +            DirWriteL(entryPos, buf); //-- use special interface to access FAT directory file
  1.2981 +        }
  1.2982 +
  1.2983 +    }
  1.2984 +
  1.2985 +    CleanupStack::PopAndDestroy(&buf);
  1.2986 +    }
  1.2987 +
  1.2988 +
  1.2989 +/**
  1.2990 +    Internal method. Retrieves directory entry from given position.
  1.2991 +
  1.2992 +    @param  aPos            on enter shall contain start position, from where the entry will be read. On return contains position of the DOS entry (the last one for object name for the VFAT case)
  1.2993 +    @param  aDosEntry       On return contains DOS entry for the VFAT case
  1.2994 +    @param  aStartEntry     On return contains start entry of the directory object for the VFAT case
  1.2995 +    @param  aLongFileName   On return contains VFAT or long filename
  1.2996 +
  1.2997 +    @return  ETrue  if whole FAT entry is OK: only 1 entry for DOS name or _ALL_ entries for a long name
  1.2998 +             EFalse if there was an error in assembling entries to the long file name. In this case this entry shall be ignored by upper level.
  1.2999 +
  1.3000 +    can leave because of ReadDirEntryL() and MoveToNextEntryL() [end of dir].
  1.3001 +*/
  1.3002 +TBool CFatMountCB::DoGetDirEntryL(TEntryPos& aPos, TFatDirEntry& aDosEntry, TFatDirEntry& aStartEntry, TDes& aLongFileName) const
  1.3003 +    {
  1.3004 +
  1.3005 +//    __PRINT3(_L("CFatMountCB::GetDirEntryL() drv:%d, pos:%d:%d"), Drive().DriveNumber(), aPos.iCluster, aPos.iPos);
  1.3006 +
  1.3007 +    ReadDirEntryL(aPos,aStartEntry);
  1.3008 +    aDosEntry=aStartEntry;
  1.3009 +    if (!aDosEntry.IsVFatEntry() || aDosEntry.IsErased() || aDosEntry.IsGarbage())
  1.3010 +        {//-- This is either a 8.3 FAT entry or garbage
  1.3011 +        aLongFileName.SetLength(0);
  1.3012 +        return ETrue;
  1.3013 +        }
  1.3014 +
  1.3015 +    //-- process VFAT entries
  1.3016 +
  1.3017 +    if(!aDosEntry.IsLongNameStart())
  1.3018 +        return EFalse; //-- wrong counter in the 1st VFat entry, consider it as orphaned
  1.3019 +
  1.3020 +
  1.3021 +    TInt count = aDosEntry.NumFollowing(); //-- count of the following VFat entries
  1.3022 +
  1.3023 +    TBuf16<KMaxVFatEntryName> vBuf(KMaxVFatEntryName);
  1.3024 +    aDosEntry.ReadVFatEntry(vBuf);
  1.3025 +
  1.3026 +    TInt vLength=vBuf.Locate('\0');
  1.3027 +    if (vLength==KErrNotFound)
  1.3028 +        vLength=KMaxVFatEntryName;
  1.3029 +
  1.3030 +    vBuf.SetLength(vLength);
  1.3031 +
  1.3032 +    const TInt nameLen = vLength+KMaxVFatEntryName*(count-1);
  1.3033 +    if(nameLen <= 0 || nameLen > KMaxFileName)
  1.3034 +        return EFalse; //--  wrong long file name length, consider VFAT entry as orphaned
  1.3035 +
  1.3036 +    aLongFileName.SetLength(nameLen);
  1.3037 +
  1.3038 +    const TUint8 entryCheckSum = aDosEntry.CheckSum(); //-- check sum from the 1st VFat entry
  1.3039 +
  1.3040 +    while (count--)
  1.3041 +        {
  1.3042 +        TPtr fileNamePtr(&aLongFileName[0]+KMaxVFatEntryName*count,aLongFileName.Length()-KMaxVFatEntryName*count);
  1.3043 +        fileNamePtr.Copy(vBuf);
  1.3044 +        if (count==0)
  1.3045 +            break; //-- all VFat entries read, only DOS entry remained
  1.3046 +
  1.3047 +        MoveToNextEntryL(aPos);
  1.3048 +        ReadDirEntryL(aPos,aDosEntry);
  1.3049 +
  1.3050 +        //-- check if it is correct VFat entry.
  1.3051 +        //-- if not, this is the "orphaned" entry and will be ignored
  1.3052 +        if(!aDosEntry.IsVFatEntry() || aDosEntry.IsErased() || entryCheckSum != aDosEntry.CheckSum() || aDosEntry.NumFollowing() != count)
  1.3053 +            return EFalse;  //-- bad VFAT entry
  1.3054 +
  1.3055 +        aDosEntry.ReadVFatEntry(vBuf);
  1.3056 +        }
  1.3057 +
  1.3058 +    if (IsRootDir(aPos)&&(aPos.iPos+StartOfRootDirInBytes()==(RootDirEnd()-KSizeOfFatDirEntry)))
  1.3059 +        return ETrue;//Allows maximum number of entries in root directory
  1.3060 +
  1.3061 +    //-- read the last, DOS FAT entry
  1.3062 +    MoveToNextEntryL(aPos);
  1.3063 +    ReadDirEntryL(aPos,aDosEntry);
  1.3064 +
  1.3065 +    //-- check if it is corect
  1.3066 +    if(aDosEntry.IsEndOfDirectory() || aDosEntry.IsErased() || aDosEntry.IsVFatEntry())
  1.3067 +        return EFalse; //-- Bad DOS entry
  1.3068 +
  1.3069 +    //-- verify ChechSum here if it is incorrect, use DOS name only
  1.3070 +    const TUint8 calcNameChkSum = CalculateShortNameCheckSum(aDosEntry.Name());
  1.3071 +    if(calcNameChkSum != entryCheckSum)
  1.3072 +        {
  1.3073 +        aLongFileName.SetLength(0);//-- don't use long filename
  1.3074 +        __PRINT2(_L("CFatMountCB::GetDirEntryL() CheckSum mismatch: VFat:0x%x, DOS:0x%d"),entryCheckSum, calcNameChkSum);
  1.3075 +        }
  1.3076 +
  1.3077 +    return ETrue;
  1.3078 +    }
  1.3079 +
  1.3080 +
  1.3081 +/**
  1.3082 +    Read a number of VFAT entries from the directory file.
  1.3083 +    for parameters see DoGetDirEntryL()
  1.3084 +
  1.3085 +    @return KErrNone if everything is OK, system wide error code otherwise
  1.3086 +
  1.3087 +*/
  1.3088 +TInt CFatMountCB::GetDirEntry(TEntryPos& aPos,TFatDirEntry& aDosEntry,TFatDirEntry& aStartEntry,TDes& aLongFileName) const
  1.3089 +    {
  1.3090 +
  1.3091 +    TBool bEntryOK=ETrue;
  1.3092 +    TRAPD(nErr, bEntryOK = DoGetDirEntryL(aPos, aDosEntry, aStartEntry, aLongFileName));
  1.3093 +
  1.3094 +    if(nErr !=KErrNone)
  1.3095 +        return nErr;
  1.3096 +
  1.3097 +    if(!bEntryOK)
  1.3098 +        {//-- DoGetDirEntryL could not assemble whole VFat entry, probably some parts of it are damaged.
  1.3099 +         //-- consider it as an "orphaned" entry and skip
  1.3100 +        aDosEntry.iData[0] = 0xFF;      // Mark entry as garbage
  1.3101 +        aLongFileName.SetLength(0);     // No long filename
  1.3102 +        }
  1.3103 +
  1.3104 +    return KErrNone;
  1.3105 +    }
  1.3106 +
  1.3107 +void CFatMountCB::MoveToNextEntryL(TEntryPos& aPos) const
  1.3108 +//
  1.3109 +// If anEntry is at the end of the cluster, and we are not the root dir,
  1.3110 +// move it to the next in the list.
  1.3111 +//
  1.3112 +    {
  1.3113 +
  1.3114 +//  __PRINT(_L("CFatMountCB::MoveToNextEntryL"));
  1.3115 +    if (IsEndOfClusterCh(aPos.iCluster))
  1.3116 +        return;
  1.3117 +    const TUint temp = 1<<ClusterSizeLog2();
  1.3118 +    if (aPos.iPos+KSizeOfFatDirEntry!=temp || IsRootDir(aPos))
  1.3119 +        {
  1.3120 +        aPos.iPos+=KSizeOfFatDirEntry;
  1.3121 +        }
  1.3122 +    else
  1.3123 +        {
  1.3124 +        if (FAT().GetNextClusterL(aPos.iCluster)==EFalse)
  1.3125 +            {
  1.3126 +            SetEndOfClusterCh(aPos.iCluster);
  1.3127 +            }
  1.3128 +        aPos.iPos=0;
  1.3129 +        }
  1.3130 +    }
  1.3131 +
  1.3132 +//-----------------------------------------------------------------------------------------
  1.3133 +
  1.3134 +/**
  1.3135 +    Starting from a VFat entry walk down the directory until the associated dos entry is found
  1.3136 +
  1.3137 +    @param aPos     in: VFAT entry position. out: if this is a VFAT entry set, it will be DOS entry position. otherwise not changed
  1.3138 +    @param anEntry  on return will contain DOS dir. entry contents (if aPos points to the VFAT entry)
  1.3139 +*/
  1.3140 +void CFatMountCB::MoveToDosEntryL(TEntryPos& aPos,TFatDirEntry& anEntry) const
  1.3141 +    {
  1.3142 +
  1.3143 +    //__PRINT(_L("CFatMountCB::MoveToDosEntryL"));
  1.3144 +    if (anEntry.IsVFatEntry()==EFalse)
  1.3145 +        return;
  1.3146 +    FOREVER
  1.3147 +        {
  1.3148 +        MoveToNextEntryL(aPos);
  1.3149 +        ReadDirEntryL(aPos,anEntry);
  1.3150 +        if (anEntry.IsVFatEntry()==EFalse)
  1.3151 +            break;
  1.3152 +        if (IsRootDir(aPos)&&(aPos.iPos+StartOfRootDirInBytes()==(RootDirEnd()-KSizeOfFatDirEntry)))
  1.3153 +            break;  //  Allows maximum number of entries in root directory
  1.3154 +        }
  1.3155 +    }
  1.3156 +
  1.3157 +//-----------------------------------------------------------------------------------------
  1.3158 +
  1.3159 +/** Read the Uid of the entry starting at aCluster */
  1.3160 +void CFatMountCB::ReadUidL(TInt aCluster,TEntry& anEntry) const
  1.3161 +    {
  1.3162 +
  1.3163 +    __PRINT1(_L("CFatMountCB::ReadUidL(%d)"), aCluster);
  1.3164 +
  1.3165 +    if((TUint)aCluster < KFatFirstSearchCluster || (TUint)aCluster >= UsableClusters()+KFatFirstSearchCluster)
  1.3166 +        User::Leave(KErrCorrupt);
  1.3167 +
  1.3168 +    TBuf8<sizeof(TCheckedUid)> uidBuf;
  1.3169 +    iRawDisk->ReadCachedL(FAT().DataPositionInBytes(aCluster),sizeof(TCheckedUid),uidBuf);
  1.3170 +    __ASSERT_DEBUG(uidBuf.Length()==sizeof(TCheckedUid),Fault(EFatReadUidFailed));
  1.3171 +    TCheckedUid uid(uidBuf);
  1.3172 +    anEntry.iType=uid.UidType();
  1.3173 +    }
  1.3174 +
  1.3175 +//-----------------------------------------------------------------------------------------
  1.3176 +
  1.3177 +/**
  1.3178 +    Read file section without opening this file on a file server side.
  1.3179 +
  1.3180 +    @param  aName       file name; all trailing dots from the name will be removed
  1.3181 +    @param  aFilePos    start read position within a file
  1.3182 +    @param  aLength     how many bytes to read; on return will be how many bytes actually read
  1.3183 +    @param  aDes        local buffer desctriptor
  1.3184 +    @param  aMessage    from file server, used to write data to the buffer in different address space.
  1.3185 +
  1.3186 +    @leave on media read error
  1.3187 +*/
  1.3188 +void CFatMountCB::ReadSectionL(const TDesC& aName,TInt aPos,TAny* aTrg,TInt aLength,const RMessagePtr2& aMessage)
  1.3189 +    {
  1.3190 +    __PRINT4(_L("CFatMountCB::ReadSectionL, drv:%d, pos:%d, len:%d, FN:%S"), DriveNumber(), aPos, aLength, &aName);
  1.3191 +
  1.3192 +    CheckStateConsistentL();
  1.3193 +
  1.3194 +    TEntryPos dosEntryPos(RootIndicator(),0);
  1.3195 +    TFatDirEntry dosEntry;
  1.3196 +    TFileName fileName;
  1.3197 +
  1.3198 +
  1.3199 +    TInt namePos=RemoveTrailingDots(aName).LocateReverse(KPathDelimiter)+1; // There is always a path delimiter
  1.3200 +    TLeafDirData leafDir;
  1.3201 +    dosEntryPos.iCluster=FindLeafDirL(RemoveTrailingDots(aName).Left(namePos), leafDir);
  1.3202 +    dosEntryPos.iPos=0;
  1.3203 +    TEntryPos startPos;
  1.3204 +    TFatDirEntry startEntry;
  1.3205 +    DoFindL(RemoveTrailingDots(aName).Mid(namePos),KEntryAttMaskSupported,
  1.3206 +            startPos,startEntry,dosEntryPos,dosEntry,
  1.3207 +            fileName,KErrNotFound,
  1.3208 +            NULL,
  1.3209 +            leafDir);
  1.3210 +
  1.3211 +//  Check that reading from aPos for aLength lies within the file
  1.3212 +//  if aPos is within the file, and aLength is too long, read up to EOF
  1.3213 +//  If aPos is beyond the end of the file, return a zero length descriptor
  1.3214 +
  1.3215 +    TUint32 fileSize = dosEntry.Size();
  1.3216 +    if ((TUint)aPos>=fileSize)
  1.3217 +        User::Leave(KErrEof);
  1.3218 +
  1.3219 +    if ((TUint)(aPos+aLength)>fileSize)
  1.3220 +        aLength=fileSize-aPos;
  1.3221 +
  1.3222 +    TInt cluster=StartCluster(dosEntry);
  1.3223 +    TInt pos = aPos;
  1.3224 +
  1.3225 +    TInt endCluster;
  1.3226 +    TInt clusterSize=1<<ClusterSizeLog2();      //  Size of file clusters
  1.3227 +    TInt readTotal = 0;
  1.3228 +
  1.3229 +    // Total number of clusters in file
  1.3230 +    TInt maxClusters=((fileSize+clusterSize-1)>>ClusterSizeLog2());
  1.3231 +
  1.3232 +    // Read data
  1.3233 +    FOREVER
  1.3234 +        {
  1.3235 +        //  Get the maximum number of clusters that can be read contiguously
  1.3236 +        TInt clusterListLen=FAT().CountContiguousClustersL(cluster,endCluster,maxClusters);
  1.3237 +        __ASSERT_DEBUG(clusterListLen>0,Fault(EReadFileSectionFailed));
  1.3238 +
  1.3239 +        //  If start position within this block, then read some data
  1.3240 +        if (pos<(clusterListLen<<ClusterSizeLog2()))
  1.3241 +            {
  1.3242 +            //  Read the remaining length or the entire cluster block whichever is smaller
  1.3243 +            TInt readLength = Min(aLength-readTotal,(clusterListLen<<ClusterSizeLog2())-pos);
  1.3244 +            __ASSERT_DEBUG(readLength>0,Fault(EReadFileSectionFailed));
  1.3245 +            TInt64 dataAddress=(FAT().DataPositionInBytes(cluster))+pos;
  1.3246 +            iRawDisk->ReadL(dataAddress,readLength,aTrg,aMessage,readTotal);
  1.3247 +            readTotal += readLength;
  1.3248 +
  1.3249 +            if (readTotal == aLength)
  1.3250 +                return;
  1.3251 +
  1.3252 +            pos += readLength;
  1.3253 +            }
  1.3254 +
  1.3255 +        // Get the next cluster in file
  1.3256 +        pos-=(clusterListLen<<ClusterSizeLog2());
  1.3257 +#if defined(_DEBUG)
  1.3258 +        TBool remainingClusters=
  1.3259 +#endif
  1.3260 +            ((CFatMountCB*)this)->FAT().GetNextClusterL(endCluster);
  1.3261 +        __ASSERT_DEBUG(remainingClusters,Fault(EReadFileSectionFailed));
  1.3262 +        cluster=endCluster;
  1.3263 +        }
  1.3264 +    }
  1.3265 +
  1.3266 +
  1.3267 +//-----------------------------------------------------------------------------------------
  1.3268 +
  1.3269 +void CFatMountCB::RawReadL(TInt64 aPos,TInt aLength,const TAny* aTrg,TInt anOffset,const RMessagePtr2& aMessage) const
  1.3270 +//
  1.3271 +// Read aLength of data from disk directly to thread relative descriptor
  1.3272 +//
  1.3273 +    {
  1.3274 +    iRawDisk->ReadL(aPos,aLength,aTrg,aMessage,anOffset);
  1.3275 +    }
  1.3276 +
  1.3277 +//-----------------------------------------------------------------------------------------
  1.3278 +
  1.3279 +void CFatMountCB::RawWriteL(TInt64 aPos,TInt aLength,const TAny* aSrc,TInt anOffset,const RMessagePtr2& aMessage)
  1.3280 +//
  1.3281 +// Write aLength of data from thread relative descriptor to disk
  1.3282 +//
  1.3283 +    {
  1.3284 +    CheckWritableL();
  1.3285 +
  1.3286 +    //-- check if we are trying to write to the FAT directly and wait until FAT scan thread finishes in this case.
  1.3287 +    FAT().RequestRawWriteAccess(aPos, aLength);
  1.3288 +
  1.3289 +    iRawDisk->WriteL(aPos,aLength,aSrc,aMessage,anOffset);
  1.3290 +    //-- Note: FAT directory cache will be invalidated in MountL()
  1.3291 +    }
  1.3292 +
  1.3293 +//-----------------------------------------------------------------------------------------
  1.3294 +/**
  1.3295 +    This method must be used when writing to the FAT directory file.
  1.3296 +    If FAT directory cache is present on this drive, it will be used.
  1.3297 +    @param  aPos    entry media position
  1.3298 +    @param  aDes    data descriptor
  1.3299 +*/
  1.3300 +void CFatMountCB::DirWriteL(const TEntryPos& aPos,const TDesC8& aDes)
  1.3301 +    {
  1.3302 +        CheckWritableL();
  1.3303 +        const TInt64 posAddr=MakeLinAddrL(aPos);
  1.3304 +
  1.3305 +        if(!iRawDisk->DirCacheInterface())
  1.3306 +            {
  1.3307 +            iRawDisk->WriteCachedL(posAddr,aDes);
  1.3308 +            }
  1.3309 +        else
  1.3310 +            {//-- if there is an interface to the FAT directory cache, use it
  1.3311 +            iRawDisk->DirCacheInterface()->WriteL(posAddr, aDes);
  1.3312 +            }
  1.3313 +    }
  1.3314 +
  1.3315 +//-----------------------------------------------------------------------------------------
  1.3316 +
  1.3317 +/**
  1.3318 +    This method must be used when reading from the FAT directory file.
  1.3319 +    If FAT directory cache is present on this drive, it will be used.
  1.3320 +
  1.3321 +    @param  aPos    entry media position
  1.3322 +    @param  aLength how many bytes to read
  1.3323 +    @param  aDes    input data descriptor
  1.3324 +*/
  1.3325 +void CFatMountCB::DirReadL(const TEntryPos& aPos, TInt aLength, TDes8& aDes) const
  1.3326 +    {
  1.3327 +        const TInt64 posAddr=MakeLinAddrL(aPos);
  1.3328 +
  1.3329 +        if(!iRawDisk->DirCacheInterface())
  1.3330 +            {
  1.3331 +            iRawDisk->ReadCachedL(posAddr,aLength,aDes);
  1.3332 +            }
  1.3333 +        else
  1.3334 +            {//-- if there is an interface to the FAT directory cache, use it
  1.3335 +            iRawDisk->DirCacheInterface()->ReadL(posAddr, aLength, aDes);
  1.3336 +            }
  1.3337 +    }
  1.3338 +
  1.3339 +//-----------------------------------------------------------------------------------------
  1.3340 +
  1.3341 +void CFatMountCB::WriteDirEntryL(const TEntryPos& aPos,const TFatDirEntry& aDirEntry)
  1.3342 +//
  1.3343 +// Write a FAT directory entry to disk.
  1.3344 +// Assumes sufficient space has been created for it by AddDirEntry.
  1.3345 +//
  1.3346 +    {
  1.3347 +
  1.3348 +    __PRINT(_L("CFatMountCB::WriteDirEntryL"));
  1.3349 +
  1.3350 +    //-- use special interface to access FAT directory file
  1.3351 +    DirWriteL(aPos,TPtrC8((TUint8*)&aDirEntry,KSizeOfFatDirEntry));
  1.3352 +    }
  1.3353 +
  1.3354 +//-----------------------------------------------------------------------------------------
  1.3355 +
  1.3356 +void CFatMountCB::EraseDirEntryL(const TEntryPos& aPos)
  1.3357 +//
  1.3358 +// Mark a dir entry as erased
  1.3359 +//
  1.3360 +    {
  1.3361 +
  1.3362 +    __PRINT(_L("CFatMountCB::EraseDirEntryL"));
  1.3363 +    if(!iLeafDirCache && iLastLeafDir)
  1.3364 +        iLastLeafDir->Des().SetLength(0);
  1.3365 +
  1.3366 +    //-- use special interface to access FAT directory file
  1.3367 +    DirWriteL(aPos,TPtrC8((TUint8*)&KEntryErasedMarker,sizeof(TUint8)));
  1.3368 +    }
  1.3369 +
  1.3370 +//-----------------------------------------------------------------------------------------
  1.3371 +
  1.3372 +void CFatMountCB::ReadDirEntryL(const TEntryPos& aPos,TFatDirEntry& aDirEntry) const
  1.3373 +//
  1.3374 +// Read a FAT directory entry to disk
  1.3375 +//
  1.3376 +    {
  1.3377 +
  1.3378 +//  __PRINT(_L("CFatMountCB::ReadDirEntryL"));
  1.3379 +    if (IsEndOfClusterCh(aPos.iCluster))
  1.3380 +        {
  1.3381 +        aDirEntry.InitZ();
  1.3382 +        return;
  1.3383 +        }
  1.3384 +    TPtr8 buf=TPtr8((TUint8*)&aDirEntry,KSizeOfFatDirEntry);
  1.3385 +
  1.3386 +    //-- use special interface to access FAT directory file
  1.3387 +    DirReadL(aPos,KSizeOfFatDirEntry,buf);
  1.3388 +    }
  1.3389 +
  1.3390 +//-----------------------------------------------------------------------------------------
  1.3391 +
  1.3392 +/**
  1.3393 +    Enlarge the disk's size.
  1.3394 +    This method can be called only for variable size media, i.e. RAM drive
  1.3395 +
  1.3396 +    @param aSize size increment (bytes)
  1.3397 +*/
  1.3398 +void CFatMountCB::EnlargeL(TInt aSize)
  1.3399 +    {
  1.3400 +    __PRINT2(_L("CFatMountCB::EnlargeL by 0x%x currentsize=0x%x"),aSize,iSize);
  1.3401 +
  1.3402 +    ASSERT(iRamDrive);
  1.3403 +
  1.3404 +    TInt maxSize;
  1.3405 +    if (HAL::Get(HAL::EMaxRAMDriveSize, maxSize) == KErrNone && iSize + aSize > maxSize)
  1.3406 +        User::Leave(KErrDiskFull);
  1.3407 +    User::LeaveIfError(LocalDrive()->Enlarge(aSize));
  1.3408 +    iSize+=aSize;
  1.3409 +
  1.3410 +    if (&FAT())
  1.3411 +        {
  1.3412 +        FAT().InitializeL();
  1.3413 +        }
  1.3414 +
  1.3415 +    if (&RawDisk())
  1.3416 +        {
  1.3417 +        RawDisk().InitializeL();
  1.3418 +        }
  1.3419 +
  1.3420 +    }
  1.3421 +
  1.3422 +//-----------------------------------------------------------------------------------------
  1.3423 +
  1.3424 +void CFatMountCB::ReduceSizeL(TInt aPos,TInt aLength)
  1.3425 +//
  1.3426 +// Reduce the disk's size
  1.3427 +//
  1.3428 +    {
  1.3429 +
  1.3430 +    __PRINT2(_L("CFatMountCB::ReduceSizeL aPos=0x%x aLength=0x%x"),aPos,aLength);
  1.3431 +    User::LeaveIfError(LocalDrive()->ReduceSize(aPos,aLength));
  1.3432 +    iSize-=aLength;
  1.3433 +    }
  1.3434 +
  1.3435 +//-----------------------------------------------------------------------------------------
  1.3436 +
  1.3437 +TInt64 CFatMountCB::MakeLinAddrL(const TEntryPos& aPos) const
  1.3438 +//
  1.3439 +// Convert cluster/position into linear address
  1.3440 +//
  1.3441 +    {
  1.3442 +
  1.3443 +    //__PRINT2(_L("CFatMountCB::MakeLinAddrL, cl:%d, pos:%d"), aPos.iCluster, aPos.iPos);
  1.3444 +    if (!IsRootDir(aPos))
  1.3445 +        {
  1.3446 +        TInt relPos=ClusterRelativePos(aPos.iPos);
  1.3447 +        return FAT().DataPositionInBytes(aPos.iCluster)+relPos;
  1.3448 +        }
  1.3449 +    if (aPos.iPos+StartOfRootDirInBytes()>=RootDirEnd())
  1.3450 +        User::Leave(KErrDirFull); // Past last root dir entry
  1.3451 +    return StartOfRootDirInBytes()+aPos.iPos;
  1.3452 +    }
  1.3453 +
  1.3454 +//-----------------------------------------------------------------------------------------
  1.3455 +
  1.3456 +void CFatMountCB::GetShortNameL(const TDesC& aLongName,TDes& aShortName)
  1.3457 +//
  1.3458 +// Get the short name associated with a long file name
  1.3459 +//
  1.3460 +    {
  1.3461 +    __PRINT(_L("CFatMountCB::GetShortNameL"));
  1.3462 +    TEntryPos firstEntryPos(RootIndicator(),0);
  1.3463 +    TFatDirEntry firstEntry;
  1.3464 +    FindEntryStartL(aLongName,KEntryAttMaskSupported,firstEntry,firstEntryPos);
  1.3465 +    MoveToDosEntryL(firstEntryPos,firstEntry);
  1.3466 +    TBuf8<0x20> dosName(DosNameFromStdFormat(firstEntry.Name()));
  1.3467 +    LocaleUtils::ConvertToUnicodeL(aShortName, dosName);
  1.3468 +    }
  1.3469 +
  1.3470 +//-----------------------------------------------------------------------------------------
  1.3471 +
  1.3472 +void CFatMountCB::GetLongNameL(const TDesC& aShortName,TDes& aLongName)
  1.3473 +//
  1.3474 +// Get the long name associated with a short file name
  1.3475 +//
  1.3476 +    {
  1.3477 +    __PRINT(_L("CFatMountCB::GetLongNameL"));
  1.3478 +    TEntryPos pos(RootIndicator(),0);
  1.3479 +    TFatDirEntry entry;
  1.3480 +    const TInt namePos=aShortName.LocateReverse(KPathDelimiter)+1; // There is always a path delimiter
  1.3481 +    const TPtrC shortNameWithoutPathDelimiter(aShortName.Mid(namePos));
  1.3482 +    __ASSERT_ALWAYS(shortNameWithoutPathDelimiter.Length()<=12,User::Leave(KErrBadName));
  1.3483 +
  1.3484 +    TLeafDirData leafDir;
  1.3485 +    pos.iCluster=FindLeafDirL(aShortName.Left(namePos), leafDir);
  1.3486 +    FOREVER
  1.3487 +        {
  1.3488 +        TFatDirEntry startEntry;
  1.3489 +        User::LeaveIfError(GetDirEntry(pos,entry,startEntry,aLongName));
  1.3490 +        if (entry.IsEndOfDirectory())
  1.3491 +            User::Leave(KErrNotFound);
  1.3492 +        TBool entryIsVFat=EFalse;
  1.3493 +        if (startEntry.IsVFatEntry())
  1.3494 +            entryIsVFat=ETrue;
  1.3495 +        if (!entry.IsParentDirectory() && !entry.IsCurrentDirectory() && !entry.IsGarbage() && !entry.IsErased())
  1.3496 +            {
  1.3497 +            TBuf8<0x20> entryName8(DosNameFromStdFormat(entry.Name()));
  1.3498 +            TBuf<0x20> entryName;
  1.3499 +            LocaleUtils::ConvertToUnicodeL(entryName, entryName8);
  1.3500 +            if (shortNameWithoutPathDelimiter.MatchF(entryName)!=KErrNotFound)
  1.3501 +                {
  1.3502 +                if (entryIsVFat==EFalse)
  1.3503 +                    aLongName=shortNameWithoutPathDelimiter;
  1.3504 +                return;
  1.3505 +                }
  1.3506 +            }
  1.3507 +        MoveToNextEntryL(pos);
  1.3508 +        }
  1.3509 +    }
  1.3510 +
  1.3511 +
  1.3512 +
  1.3513 +//-----------------------------------------------------------------------------------------
  1.3514 +
  1.3515 +/**
  1.3516 +    Extend a file or directory, zeroing cluster chain and flushing after every write to FAT.
  1.3517 +    This method is called for rugged FAT only.
  1.3518 +    for parameters see CFatTable::ExtendClusterListL
  1.3519 +*/
  1.3520 +void CFatMountCB::ExtendClusterListZeroedL(TInt aNumber,TInt& aCluster)
  1.3521 +    {
  1.3522 +    __PRINT(_L("CFatMountCB::ExtendClusterListZeroedL"));
  1.3523 +    __ASSERT_DEBUG(aNumber>0,Fault(EFatBadParameter));
  1.3524 +
  1.3525 +    while(aNumber && FAT().GetNextClusterL(aCluster))
  1.3526 +        aNumber--;
  1.3527 +
  1.3528 +    //-- request aNumber free clusters from the FAT, this request may wait until FAT scan thread counted enough free clusters if it is running.
  1.3529 +    if(!FAT().RequestFreeClusters(aNumber))
  1.3530 +        {
  1.3531 +        __PRINT(_L("CFatMountCB::ExtendClusterListL - leaving KErrDirFull"));
  1.3532 +        User::Leave(KErrDiskFull);
  1.3533 +        }
  1.3534 +    while (aNumber--)
  1.3535 +        {
  1.3536 +        TInt freeCluster=FAT().AllocateSingleClusterL(aCluster);
  1.3537 +        FAT().FlushL();
  1.3538 +        ZeroDirClusterL(freeCluster);
  1.3539 +        FAT().WriteL(aCluster,freeCluster);
  1.3540 +        FAT().FlushL();
  1.3541 +        aCluster=freeCluster;
  1.3542 +        }
  1.3543 +    }
  1.3544 +
  1.3545 +//-----------------------------------------------------------------------------------------
  1.3546 +
  1.3547 +#if defined(_DEBUG)
  1.3548 +TInt CFatMountCB::ControlIO(const RMessagePtr2& aMessage,TInt aCommand,TAny* aParam1,TAny* aParam2)
  1.3549 +//
  1.3550 +// Debug function
  1.3551 +//
  1.3552 +    {
  1.3553 +    if(aCommand>=EExtCustom)
  1.3554 +        {
  1.3555 +        if(LocalDrive())
  1.3556 +            return LocalDrive()->ControlIO(aMessage,aCommand-EExtCustom,aParam1,aParam2);
  1.3557 +        else
  1.3558 +            return KErrNotSupported;
  1.3559 +        }
  1.3560 +    switch(aCommand)
  1.3561 +        {
  1.3562 +        case ECriticalWriteFailOn:
  1.3563 +            {
  1.3564 +            TInt r;
  1.3565 +            TInt16 args[2];
  1.3566 +            TPtr8 des((TUint8*)args,4,4);
  1.3567 +            TRAP(r,aMessage.ReadL(2,des,0));
  1.3568 +            if(r!=KErrNone)
  1.3569 +                return(r);
  1.3570 +            SetWriteFail(ETrue);
  1.3571 +            SetWriteFailCount(args[0]);
  1.3572 +            SetWriteFailError(args[1]);
  1.3573 +            break;
  1.3574 +            }
  1.3575 +        case ECriticalWriteFailOff:SetWriteFail(EFalse);break;
  1.3576 +        case ERuggedFSysOn: SetRuggedFSys(ETrue);break;
  1.3577 +        case ERuggedFSysOff: SetRuggedFSys(EFalse);break;
  1.3578 +        case EIsRuggedFSys:
  1.3579 +            {
  1.3580 +            TInt r;
  1.3581 +            TUint8 val = (IsRuggedFSys()!=0); // val = 0 or 1 for false/true
  1.3582 +            TPtr8 pVal(&val,1,1);
  1.3583 +            TRAP(r,aMessage.WriteL(2,pVal,0));
  1.3584 +            if(r!=KErrNone)
  1.3585 +                return(r);
  1.3586 +            break;
  1.3587 +            }
  1.3588 +        case ELocalTimeForRemovableMediaOn:
  1.3589 +            {
  1.3590 +            FatFileSystem().SetUseLocalTime(ETrue);
  1.3591 +            break;
  1.3592 +            }
  1.3593 +        case ELocalTimeForRemovableMediaOff:
  1.3594 +            {
  1.3595 +            FatFileSystem().SetUseLocalTime(EFalse);
  1.3596 +            break;
  1.3597 +            }
  1.3598 +        case ELocalTimeUsedOnRemovableMedia:
  1.3599 +            {
  1.3600 +            TBool flag = FatFileSystem().GetUseLocalTime();
  1.3601 +            TPckgC<TBool> flagPckg(flag);
  1.3602 +            TInt r = aMessage.Write(2, flagPckg);
  1.3603 +            if(r!=KErrNone)
  1.3604 +                return r;
  1.3605 +            break;
  1.3606 +            }
  1.3607 +        case ECreationTime:
  1.3608 +            {
  1.3609 +            CheckStateConsistentL();
  1.3610 +
  1.3611 +            TEntryPos firstEntryPos(RootIndicator(),0);
  1.3612 +            TFatDirEntry firstEntry;
  1.3613 +            //RFs::ControlIO restricts you to use narrow descriptors
  1.3614 +            //so convert narrow back to wide.
  1.3615 +            TBuf8<KMaxPath> fileNameNarrow;
  1.3616 +            aMessage.Read(2, fileNameNarrow);
  1.3617 +
  1.3618 +            TFileName fileNameWide;
  1.3619 +            fileNameWide.Copy(fileNameNarrow);
  1.3620 +
  1.3621 +            //find the long file name entry
  1.3622 +            TRAPD(r, FindEntryStartL(fileNameWide,KEntryAttMaskSupported,firstEntry,firstEntryPos) );
  1.3623 +            if(r!=KErrNone)
  1.3624 +              return(r);
  1.3625 +            //Find the corresponding 8.3 short name entry, for metadata
  1.3626 +            MoveToDosEntryL(firstEntryPos,firstEntry);
  1.3627 +            TTime creationTime=0;
  1.3628 +            TPckg<TTime> timePckg(creationTime);
  1.3629 +            SFatDirEntry* sEntry = reinterpret_cast<SFatDirEntry*>(firstEntry.iData);
  1.3630 +            creationTime = DosTimeToTTime(sEntry->iTimeC, sEntry->iDateC);
  1.3631 +            r = aMessage.Write(3, timePckg);
  1.3632 +            if(r!=KErrNone)
  1.3633 +                return r;
  1.3634 +            break;
  1.3635 +            }
  1.3636 +        case EDisableFATDirCache:
  1.3637 +            {
  1.3638 +            MWTCacheInterface* pDirCache = iRawDisk->DirCacheInterface();
  1.3639 +            TUint32 KEDisableFATDirCache = CDynamicDirCache::EDisableCache;
  1.3640 +            pDirCache->Control(KEDisableFATDirCache, (TUint32) aParam1, NULL);
  1.3641 +            break;
  1.3642 +            }
  1.3643 +        case EDumpFATDirCache:
  1.3644 +            {
  1.3645 +            MWTCacheInterface* pDirCache = iRawDisk->DirCacheInterface();
  1.3646 +            TUint32 KEDumpFATDirCache = CDynamicDirCache::EDumpCache;
  1.3647 +            pDirCache->Control(KEDumpFATDirCache, 0, NULL);
  1.3648 +            break;
  1.3649 +            }
  1.3650 +        case EFATDirCacheInfo:
  1.3651 +            {
  1.3652 +            MWTCacheInterface* pDirCache = iRawDisk->DirCacheInterface();
  1.3653 +            TUint32 KEFATDirCacheInfo = CDynamicDirCache::ECacheInfo;
  1.3654 +            pDirCache->Control(KEFATDirCacheInfo, 0, NULL);
  1.3655 +            break;
  1.3656 +            }
  1.3657 +
  1.3658 +
  1.3659 +        default: return(KErrNotSupported);
  1.3660 +        }
  1.3661 +    return(KErrNone);
  1.3662 +    }
  1.3663 +#else
  1.3664 +TInt CFatMountCB::ControlIO(const RMessagePtr2& /*aMessage*/,TInt /*aCommand*/,TAny* /*aParam1*/,TAny* /*aParam2*/)
  1.3665 +    {return(KErrNotSupported);}
  1.3666 +#endif
  1.3667 +
  1.3668 +
  1.3669 +//-----------------------------------------------------------------------------------------
  1.3670 +
  1.3671 +TInt CFatMountCB::Lock(TMediaPassword& aOld,TMediaPassword& aNew,TBool aStore)
  1.3672 +//
  1.3673 +// lock media device
  1.3674 +//
  1.3675 +    {
  1.3676 +    __PRINT(_L("CFatMountCB::Lock"));
  1.3677 +    TInt r=CreateDrive(Drive().DriveNumber());
  1.3678 +    if (r!=KErrNone)
  1.3679 +        return r;
  1.3680 +
  1.3681 +    TBusLocalDrive* local;
  1.3682 +    r=LocalDrive()->GetLocalDrive(local);
  1.3683 +    if (r!=KErrNone)
  1.3684 +        return r;
  1.3685 +
  1.3686 +#ifdef _LOCKABLE_MEDIA
  1.3687 +    if(local->Status()==KErrLocked)
  1.3688 +        local->Status() = KErrNotReady;
  1.3689 +#endif
  1.3690 +    r=local->SetPassword(aOld,aNew,aStore);
  1.3691 +    if(r==KErrNone&&aStore)
  1.3692 +        WritePasswordData();
  1.3693 +    return(r);
  1.3694 +    }
  1.3695 +
  1.3696 +//-----------------------------------------------------------------------------------------
  1.3697 +
  1.3698 +TInt CFatMountCB::Unlock(TMediaPassword& aPassword,TBool aStore)
  1.3699 +//
  1.3700 +// Unlock media device
  1.3701 +//
  1.3702 +    {
  1.3703 +    __PRINT(_L("CFatMountCB::Unlock"));
  1.3704 +    TInt r=CreateDrive(Drive().DriveNumber());
  1.3705 +    if (r!=KErrNone)
  1.3706 +        return r;
  1.3707 +
  1.3708 +    TBusLocalDrive* local;
  1.3709 +    r=LocalDrive()->GetLocalDrive(local);
  1.3710 +    if (r!=KErrNone)
  1.3711 +        return r;
  1.3712 +
  1.3713 +#ifdef _LOCKABLE_MEDIA
  1.3714 +    if(local->Status()==KErrLocked)
  1.3715 +        local->Status() = KErrNotReady;
  1.3716 +#endif
  1.3717 +    r=local->Unlock(aPassword,aStore);
  1.3718 +    if(r==KErrNone&&aStore)
  1.3719 +        WritePasswordData();
  1.3720 +    return(r);
  1.3721 +    }
  1.3722 +
  1.3723 +//-----------------------------------------------------------------------------------------
  1.3724 +
  1.3725 +TInt CFatMountCB::ClearPassword(TMediaPassword& aPassword)
  1.3726 +//
  1.3727 +// Clear password from media device
  1.3728 +//
  1.3729 +    {
  1.3730 +    __PRINT(_L("CFatMountCB::ClearPassword"));
  1.3731 +    TInt r=CreateDrive(Drive().DriveNumber());
  1.3732 +    if (r!=KErrNone)
  1.3733 +        return r;
  1.3734 +
  1.3735 +    TBusLocalDrive* local;
  1.3736 +    r=LocalDrive()->GetLocalDrive(local);
  1.3737 +    if (r!=KErrNone)
  1.3738 +        return r;
  1.3739 +
  1.3740 +#ifdef _LOCKABLE_MEDIA
  1.3741 +    if(local->Status()==KErrLocked)
  1.3742 +        local->Status() = KErrNotReady;
  1.3743 +#endif
  1.3744 +    r=local->Clear(aPassword);
  1.3745 +    if(r==KErrNone)
  1.3746 +        WritePasswordData();
  1.3747 +    return(r);
  1.3748 +    }
  1.3749 +
  1.3750 +//-----------------------------------------------------------------------------------------
  1.3751 +
  1.3752 +TInt CFatMountCB::ErasePassword()
  1.3753 +//
  1.3754 +// Forcibly erase the password from a media device
  1.3755 +//
  1.3756 +    {
  1.3757 +    __PRINT(_L("CFatMountCB::ErasePassword"));
  1.3758 +
  1.3759 +    TInt r=CreateDrive(Drive().DriveNumber());
  1.3760 +    if (r!=KErrNone)
  1.3761 +        return r;
  1.3762 +
  1.3763 +    TBusLocalDrive* local;
  1.3764 +    r=LocalDrive()->GetLocalDrive(local);
  1.3765 +    if (r!=KErrNone)
  1.3766 +        return r;
  1.3767 +
  1.3768 +#ifdef _LOCKABLE_MEDIA
  1.3769 +    if(local->Status()==KErrLocked)
  1.3770 +        local->Status() = KErrNotReady;
  1.3771 +#endif
  1.3772 +    r=local->ErasePassword();
  1.3773 +    if(r==KErrNone)
  1.3774 +        {
  1.3775 +        // ...media change to ensure a fresh remount the drive
  1.3776 +        r = local->ForceRemount(0);
  1.3777 +        local->Status() = KErrNotReady;
  1.3778 +        WritePasswordData();
  1.3779 +        }
  1.3780 +    return(r);
  1.3781 +    }
  1.3782 +
  1.3783 +//-----------------------------------------------------------------------------------------
  1.3784 +
  1.3785 +TInt CFatMountCB::ForceRemountDrive(const TDesC8* aMountInfo,TInt aMountInfoMessageHandle,TUint aFlags)
  1.3786 +//
  1.3787 +// Force a remount of the drive
  1.3788 +//
  1.3789 +    {
  1.3790 +    __PRINT(_L("CFatMountCB::ForceRemountDrive"));
  1.3791 +    TInt r=CreateDrive(Drive().DriveNumber());
  1.3792 +    if (r==KErrNone)
  1.3793 +        r=LocalDrive()->SetMountInfo(aMountInfo,aMountInfoMessageHandle);
  1.3794 +    if (r==KErrNone)
  1.3795 +        r=LocalDrive()->ForceRemount(aFlags);
  1.3796 +    return(r);
  1.3797 +    }
  1.3798 +
  1.3799 +//-----------------------------------------------------------------------------------------
  1.3800 +
  1.3801 +void CFatMountCB::WritePasswordData()
  1.3802 +//
  1.3803 +// Write store password data to disk
  1.3804 +//
  1.3805 +    {
  1.3806 +    __PRINT(_L("CFatMountCB::WritePasswordData"));
  1.3807 +    TBuf<sizeof(KMediaPWrdFile)> mediaPWrdFile(KMediaPWrdFile);
  1.3808 +    mediaPWrdFile[0] = (TUint8) RFs::GetSystemDriveChar();
  1.3809 +    __PRINT1TEMP(_L("disk file = %S"),mediaPWrdFile);
  1.3810 +    TBusLocalDrive& local=GetLocalDrive(Drive().DriveNumber());
  1.3811 +    TInt length=local.PasswordStoreLengthInBytes();
  1.3812 +    if(length==0)
  1.3813 +        {
  1.3814 +        WriteToDisk(mediaPWrdFile,_L8(""));
  1.3815 +        return;
  1.3816 +        }
  1.3817 +    HBufC8* hDes=HBufC8::New(length);
  1.3818 +    if(hDes==NULL)
  1.3819 +        return;
  1.3820 +    TPtr8 pDes=hDes->Des();
  1.3821 +    TInt r=local.ReadPasswordData(pDes);
  1.3822 +    if(r==KErrNone)
  1.3823 +        WriteToDisk(mediaPWrdFile,pDes);
  1.3824 +    delete hDes;
  1.3825 +    }
  1.3826 +
  1.3827 +//-----------------------------------------------------------------------------------------
  1.3828 +
  1.3829 +/**
  1.3830 +Trim trailing spaces of volume label descriptor and adjust its length
  1.3831 +*/
  1.3832 +void CFatMountCB::TrimVolumeLabel(TDes8& aLabel) const
  1.3833 +    {
  1.3834 +    // Locate first '\0'
  1.3835 +    TInt nullPos = aLabel.Locate('\0');
  1.3836 +    if (nullPos == KErrNotFound)
  1.3837 +        nullPos = KVolumeLabelSize;
  1.3838 +
  1.3839 +    // Trim trailing spaces
  1.3840 +    TInt i;
  1.3841 +    for (i=nullPos-1; i>=0; --i)
  1.3842 +        if (aLabel[i] != 0x20)
  1.3843 +            break;
  1.3844 +    aLabel.SetLength(i+1);
  1.3845 +    }
  1.3846 +
  1.3847 +//-----------------------------------------------------------------------------------------
  1.3848 +
  1.3849 +/**
  1.3850 +Searches for the volume label file
  1.3851 +
  1.3852 +@param aLabel The name of the volume label file returned upon successful search
  1.3853 +@return KErrNone if it finds the volume label file, otherwise KErrNotFound
  1.3854 +*/
  1.3855 +TInt CFatMountCB::ReadVolumeLabelFile(TDes8& aLabel)
  1.3856 +    {
  1.3857 +    __PRINT(_L("+CFatMountCB::ReadVolumeLabelFile"));
  1.3858 +    TEntryPos pos(RootIndicator(),0);
  1.3859 +    TFatDirEntry entry;
  1.3860 +    TRAPD(r, FindVolumeLabelFileL(aLabel, pos, entry));
  1.3861 +    __PRINT1(_L("-CFatMountCB::ReadVolumeLabelFile: %d"),r);
  1.3862 +    return r;
  1.3863 +    }
  1.3864 +
  1.3865 +//-----------------------------------------------------------------------------------------
  1.3866 +
  1.3867 +/**
  1.3868 +Creates or updates the volume label file with name aNewName
  1.3869 +
  1.3870 +@param aNewName The new name for the volume label file
  1.3871 +*/
  1.3872 +void CFatMountCB::WriteVolumeLabelFileL(const TDesC8& aNewName)
  1.3873 +    {
  1.3874 +    __PRINT1(_L("+CFatMountCB::WriteVolumeLabelFileL: [%S]"), &aNewName);
  1.3875 +    TEntryPos pos(RootIndicator(),0);
  1.3876 +    TFatDirEntry entry;
  1.3877 +
  1.3878 +    TBuf8<KVolumeLabelSize> oldName;
  1.3879 +    TRAPD(r, FindVolumeLabelFileL(oldName, pos, entry));
  1.3880 +
  1.3881 +    if( KErrNone == r )
  1.3882 +        {
  1.3883 +        // Found existing volume label file, rename or delete
  1.3884 +        if(oldName == aNewName)
  1.3885 +            {
  1.3886 +            __PRINT(_L("-CFatMountCB::WriteVolumeLabelFileL: found: names match"));
  1.3887 +            return;
  1.3888 +            }
  1.3889 +        else
  1.3890 +            {
  1.3891 +            if(aNewName.Length() == 0)
  1.3892 +                {
  1.3893 +                // delete the volume label file
  1.3894 +                __PRINT(_L("CFatMountCB::WriteVolumeLabelFileL: found: delete"));
  1.3895 +                EraseDirEntryL(pos, entry);
  1.3896 +                }
  1.3897 +            else
  1.3898 +                {
  1.3899 +                __PRINT(_L("CFatMountCB::WriteVolumeLabelFileL: found: replace"));
  1.3900 +                entry.SetName(aNewName);
  1.3901 +                WriteDirEntryL(pos, entry);
  1.3902 +                }
  1.3903 +            FAT().FlushL();
  1.3904 +            }
  1.3905 +        }
  1.3906 +    else if( KErrNotFound == r )
  1.3907 +        {
  1.3908 +        // Not found, need to create if aNewName is not empty
  1.3909 +        // Windows allows a volume label file to have the same name as
  1.3910 +        // an existing file or directory
  1.3911 +        if(aNewName.Length() > 0)
  1.3912 +            {
  1.3913 +            __PRINT(_L("CFatMountCB::WriteVolumeLabelFileL: not found: create"));
  1.3914 +            TEntryPos dirPos(RootIndicator(),0);
  1.3915 +            AddDirEntryL(dirPos,1);
  1.3916 +            TFatDirEntry fatDirEntry;
  1.3917 +            fatDirEntry.SetName(aNewName);
  1.3918 +            fatDirEntry.SetAttributes(KEntryAttVolume);
  1.3919 +
  1.3920 +            TTime now;
  1.3921 +            now.UniversalTime();
  1.3922 +            fatDirEntry.SetTime(now, TimeOffset() );
  1.3923 +            fatDirEntry.SetStartCluster(0);
  1.3924 +            fatDirEntry.SetSize(0);
  1.3925 +            WriteDirEntryL(dirPos, fatDirEntry);
  1.3926 +            FAT().FlushL();
  1.3927 +            }
  1.3928 +        }
  1.3929 +    else
  1.3930 +        {
  1.3931 +        // Some other error
  1.3932 +        User::Leave(r);
  1.3933 +        }
  1.3934 +    }
  1.3935 +
  1.3936 +
  1.3937 +//-----------------------------------------------------------------------------------------
  1.3938 +
  1.3939 +/**
  1.3940 +Scans the root directory for a volume label file. Leaves with an error if not found
  1.3941 +
  1.3942 +@param aLabel Name of the volume label file upon successful search
  1.3943 +@param aDosEntryPos Pointer to position of the volume label file upon successful search
  1.3944 +@param aDosEntry Contains the entry for the volume label file upon successful search
  1.3945 +*/
  1.3946 +void CFatMountCB::FindVolumeLabelFileL(TDes8& aLabel, TEntryPos& aDosEntryPos, TFatDirEntry& aDosEntry)
  1.3947 +    {
  1.3948 +    __PRINT(_L("+CFatMountCB::FindVolumeLabelFileL"));
  1.3949 +
  1.3950 +    if(IsRootDir(aDosEntryPos) && (aDosEntryPos.iPos+StartOfRootDirInBytes()>=RootDirEnd()))
  1.3951 +        {
  1.3952 +        __PRINT(_L("-CFatMountCB::FindVolumeLabelFileL: abort, exceeds root"));
  1.3953 +        User::Leave(KErrNotFound); // Allows maximum number of entries in root directory
  1.3954 +        }
  1.3955 +
  1.3956 +    TInt previousCluster= aDosEntryPos.iCluster;
  1.3957 +    TUint previousPosition= aDosEntryPos.iPos;
  1.3958 +    TInt changePreviousCluster=1;
  1.3959 +    TInt count=0;
  1.3960 +
  1.3961 +    TFatDirEntry startEntry;
  1.3962 +    TFileName dummyLongName;
  1.3963 +
  1.3964 +    FOREVER
  1.3965 +        {
  1.3966 +#ifdef _DEBUG
  1.3967 +        const TInt e= GetDirEntry(aDosEntryPos, aDosEntry, startEntry, dummyLongName);
  1.3968 +        __PRINT1(_L("CFatMountCB::FindVolumeLabelFileL: GetDir %d"), e);
  1.3969 +        User::LeaveIfError(e);
  1.3970 +#else
  1.3971 +        User::LeaveIfError(GetDirEntry(aDosEntryPos, aDosEntry, startEntry, dummyLongName));
  1.3972 +#endif
  1.3973 +        if(aDosEntry.IsEndOfDirectory())
  1.3974 +            {
  1.3975 +            __PRINT(_L("-CFatMountCB::FindVolumeLabelFileL: end of dir"));
  1.3976 +            User::Leave(KErrNotFound);
  1.3977 +            }
  1.3978 +        if(IsRootDir(aDosEntryPos) && (aDosEntryPos.iPos+StartOfRootDirInBytes()==(RootDirEnd()-KSizeOfFatDirEntry)))
  1.3979 +            {
  1.3980 +            if(aDosEntry.IsErased())
  1.3981 +                {
  1.3982 +                __PRINT(_L("-CFatMountCB::FindVolumeLabelFileL: erased end of root"));
  1.3983 +                User::Leave(KErrNotFound); //Allows maximum number of entries in root directory
  1.3984 +                }
  1.3985 +            }
  1.3986 +        if(!aDosEntry.IsCurrentDirectory() && !aDosEntry.IsParentDirectory() && !aDosEntry.IsErased() && !aDosEntry.IsGarbage())
  1.3987 +            {
  1.3988 +            if(aDosEntry.Attributes() & KEntryAttVolume)
  1.3989 +                {
  1.3990 +                aLabel = aDosEntry.Name();
  1.3991 +#ifdef _DEBUG
  1.3992 +                dummyLongName.Copy(aLabel);
  1.3993 +                __PRINT1(_L("-CFatMountCB::FindVolumeLabelFileL: found [%S]"), &dummyLongName);
  1.3994 +#endif
  1.3995 +                break;
  1.3996 +                }
  1.3997 +            }
  1.3998 +        MoveToNextEntryL(aDosEntryPos);
  1.3999 +        if(IsRootDir(aDosEntryPos) && (aDosEntryPos.iPos+StartOfRootDirInBytes()>=RootDirEnd()))
  1.4000 +            {
  1.4001 +            __PRINT(_L("-CFatMountCB::FindVolumeLabelFileL: passed end of root"));
  1.4002 +            User::Leave(KErrNotFound); //Allows maximum number of entries in root directory
  1.4003 +            }
  1.4004 +        if(aDosEntryPos.iCluster && (aDosEntryPos.iPos <= previousPosition))
  1.4005 +            {
  1.4006 +            DoCheckFatForLoopsL(aDosEntryPos.iCluster, previousCluster, changePreviousCluster, count);
  1.4007 +            }
  1.4008 +        previousPosition=aDosEntryPos.iPos;
  1.4009 +        }
  1.4010 +    }
  1.4011 +
  1.4012 +//-----------------------------------------------------------------------------------------
  1.4013 +
  1.4014 +/**
  1.4015 +Read volume label from disk and trim trailing 0x20 & 0x00 characters
  1.4016 +*/
  1.4017 +void CFatMountCB::GetVolumeLabelFromDiskL(const TFatBootSector& aBootSector)
  1.4018 +    {
  1.4019 +    // Read volume label as 8 bit descriptor
  1.4020 +    TBuf8<KVolumeLabelSize> volName8;
  1.4021 +    TInt r = ReadVolumeLabelFile(volName8);
  1.4022 +    if(r != KErrNone)   // No volume label file in root directory
  1.4023 +        volName8 = aBootSector.VolumeLabel();
  1.4024 +    TrimVolumeLabel(volName8);
  1.4025 +
  1.4026 +    TBuf16<KVolumeLabelSize> volName16;
  1.4027 +    LocaleUtils::ConvertToUnicodeL(volName16, volName8);
  1.4028 +    SetVolumeName(volName16.AllocL());
  1.4029 +    }
  1.4030 +
  1.4031 +
  1.4032 +//-----------------------------------------------------------------------------------------
  1.4033 +
  1.4034 +/**
  1.4035 +Populates iMap member of aInfo with contiguous block group maps.
  1.4036 +
  1.4037 +@param aPos     Start position for a desired section of the file.
  1.4038 +@param sLength  Length of the desired data to produce the block map for.
  1.4039 +@param aInfo    A structure describing a group of block maps.
  1.4040 +*/
  1.4041 +void CFatMountCB::BlockMapReadFromClusterListL(TEntryPos& aPos, TInt aLength, SBlockMapInfo& aInfo)
  1.4042 +    {
  1.4043 +    __PRINT(_L("CFatMountCB::BlockMapReadFromClusterListL"));
  1.4044 +    __ASSERT_ALWAYS(aPos.Cluster()>=KFatFirstSearchCluster,User::Leave(KErrCorrupt));
  1.4045 +    TBlockMapEntry blockMapEntry;
  1.4046 +
  1.4047 +    TUint i = 0;
  1.4048 +    TInt clusterRelativePos;
  1.4049 +    TInt maxClusters;
  1.4050 +    TInt endCluster;
  1.4051 +    TInt clusterListLen;
  1.4052 +    TInt readLength;
  1.4053 +    TInt temp;
  1.4054 +    TInt currentPos;
  1.4055 +    TLocalDriveCapsBuf caps;
  1.4056 +    TInt r;
  1.4057 +    TInt64 realPosition = 0;
  1.4058 +
  1.4059 +    do
  1.4060 +        {
  1.4061 +        currentPos = aPos.iPos;
  1.4062 +        temp = currentPos>>ClusterSizeLog2();
  1.4063 +        if ( (currentPos) && ( (currentPos) == (temp<<ClusterSizeLog2()) ) )
  1.4064 +            {
  1.4065 +            if (!FAT().GetNextClusterL(aPos.iCluster))
  1.4066 +                {
  1.4067 +                __PRINT(_L("CFatMountCB::BlockMapReadFromClusterListL corrupt#1"))
  1.4068 +                User::Leave(KErrCorrupt);
  1.4069 +                }
  1.4070 +            }
  1.4071 +        clusterRelativePos = ClusterRelativePos( aPos.iPos );
  1.4072 +        maxClusters = ((aLength + clusterRelativePos - 1)>>ClusterSizeLog2())+1;
  1.4073 +        clusterListLen = FAT().CountContiguousClustersL(aPos.iCluster, endCluster, maxClusters);
  1.4074 +        readLength = Min( aLength, (clusterListLen<<ClusterSizeLog2()) - clusterRelativePos);
  1.4075 +
  1.4076 +        blockMapEntry.SetNumberOfBlocks( clusterListLen );
  1.4077 +        if (aPos.iCluster < 2)
  1.4078 +            User::Leave(KErrCorrupt);
  1.4079 +        r = LocalDrive()->Caps(caps);
  1.4080 +        if ( r != KErrNone )
  1.4081 +            User::LeaveIfError(r);
  1.4082 +        if ( caps().iType&EMediaRam )
  1.4083 +            {
  1.4084 +            realPosition = FAT().DataPositionInBytes( aPos.iCluster );
  1.4085 +            aPos.iCluster = I64LOW((realPosition - aInfo.iStartBlockAddress)>>ClusterSizeLog2());
  1.4086 +            blockMapEntry.SetStartBlock( aPos.iCluster );
  1.4087 +            }
  1.4088 +        else
  1.4089 +            blockMapEntry.SetStartBlock( aPos.iCluster - 2);
  1.4090 +        aInfo.iMap.Append(TPckgC<TBlockMapEntry>(blockMapEntry));
  1.4091 +        aPos.iPos += readLength;
  1.4092 +        aPos.iCluster = endCluster;
  1.4093 +        aLength -= readLength;
  1.4094 +        }
  1.4095 +    while( ( aLength > 0 ) && ( ++i < KMaxMapsPerCall ) );
  1.4096 +    }
  1.4097 +
  1.4098 +
  1.4099 +//-----------------------------------------------------------------------------------------
  1.4100 +
  1.4101 +TInt CFatMountCB::GetDosEntryFromNameL(const TDesC& aName, TEntryPos& aDosEntryPos, TFatDirEntry& aDosEntry)
  1.4102 +    {
  1.4103 +    TFatDirEntry firstEntry;
  1.4104 +    TEntryPos firstEntryPos(RootIndicator(),0); // Already checked entry is a directory
  1.4105 +    FindEntryStartL(aName,KEntryAttMaskSupported,firstEntry,firstEntryPos);
  1.4106 +
  1.4107 +    aDosEntryPos=firstEntryPos;
  1.4108 +    aDosEntry=firstEntry;
  1.4109 +    MoveToDosEntryL(aDosEntryPos,aDosEntry);
  1.4110 +
  1.4111 +    return KErrNone;
  1.4112 +    }
  1.4113 +
  1.4114 +//-----------------------------------------------------------------------------------------
  1.4115 +
  1.4116 +TInt CFatMountCB::GetFileUniqueId(const TDesC& aName, TInt64& aUniqueId)
  1.4117 +    {
  1.4118 +    // Get first cluster of file
  1.4119 +    TEntryPos dosEntryPos(RootIndicator(),0);
  1.4120 +    TFatDirEntry dosEntry;
  1.4121 +    InitializeRootEntry(dosEntry);  // Nugatory initialisation to placate warnings
  1.4122 +    TRAPD(err,GetDosEntryFromNameL(aName,dosEntryPos,dosEntry));
  1.4123 +    if(err!=KErrNone)
  1.4124 +        return err;
  1.4125 +    TInt startCluster=StartCluster(dosEntry);
  1.4126 +    // Empty files will return a cluster of zero
  1.4127 +    if(startCluster==0)
  1.4128 +        return KErrEof;
  1.4129 +    aUniqueId=MAKE_TINT64(0,startCluster);
  1.4130 +    return KErrNone;
  1.4131 +    }
  1.4132 +//-----------------------------------------------------------------------------------------
  1.4133 +
  1.4134 +
  1.4135 +TInt CFatMountCB::Spare3(TInt /*aVal*/, TAny* /*aPtr1*/, TAny* /*aPtr2*/)
  1.4136 +    {
  1.4137 +    return KErrNotSupported;
  1.4138 +    }
  1.4139 +
  1.4140 +TInt CFatMountCB::Spare2(TInt /*aVal*/, TAny* /*aPtr1*/, TAny* /*aPtr2*/)
  1.4141 +    {
  1.4142 +    return KErrNotSupported;
  1.4143 +    }
  1.4144 +
  1.4145 +TInt CFatMountCB::Spare1(TInt /*aVal*/, TAny* /*aPtr1*/, TAny* /*aPtr2*/)
  1.4146 +    {
  1.4147 +    return KErrNotSupported;
  1.4148 +    }
  1.4149 +
  1.4150 +//-----------------------------------------------------------------------------------------
  1.4151 +
  1.4152 +//-- maximal level of recursion for the CheckDisk. i.e. the max. number of folded directories to check.
  1.4153 +const TInt KCheckDskMaxRecursionLevel = 50;
  1.4154 +
  1.4155 +//
  1.4156 +// Walks a directory cluster list then checks all the entries.
  1.4157 +//
  1.4158 +void  CFatMountCB::ChkDirL(RBitVector& aFatBitVec, TInt aDirCluster)
  1.4159 +    {
  1.4160 +    //__PRINT1(_L("### CFatMountCB::ChkDirL() level:%d"),iChkDiscRecLevel);
  1.4161 +
  1.4162 +    //-- check if we have reached the recursion limit. on hardware the stack is very limited
  1.4163 +    //-- and its overflow will lead to crash.
  1.4164 +    if(iChkDiscRecLevel++ >= KCheckDskMaxRecursionLevel)
  1.4165 +        {
  1.4166 +         __PRINT1(_L("CFatMountCB::ChkDirL() max recursion level(%d) reached. Leaving!"),iChkDiscRecLevel);
  1.4167 +         User::Leave(KErrTooBig);
  1.4168 +        }
  1.4169 +
  1.4170 +    if(/*Is32BitFat() &&*/aDirCluster != 0 && (aDirCluster == RootIndicator()))//the bit in comments maybe required
  1.4171 +        WalkClusterListL(aFatBitVec, RootIndicator());
  1.4172 +
  1.4173 +    TEntryPos entryPos(aDirCluster,0);
  1.4174 +    FOREVER
  1.4175 +        {
  1.4176 +        TFatDirEntry entry;
  1.4177 +        ReadDirEntryL(entryPos,entry);
  1.4178 +        MoveToDosEntryL(entryPos,entry);
  1.4179 +        if (entry.IsEndOfDirectory())
  1.4180 +            break;
  1.4181 +        if (IsRootDir(entryPos)&&(StartOfRootDirInBytes()+entryPos.iPos==(RootDirEnd()-KSizeOfFatDirEntry)))
  1.4182 +            {
  1.4183 +            if(!entry.IsErased())
  1.4184 +                ChkEntryL(aFatBitVec, entry);
  1.4185 +            break;  //  Allows maximum number of entries in root directory
  1.4186 +            }
  1.4187 +        MoveToNextEntryL(entryPos);
  1.4188 +        if (entry.IsParentDirectory() || entry.IsCurrentDirectory() || entry.IsErased())
  1.4189 +            continue;
  1.4190 +        ChkEntryL(aFatBitVec, entry);
  1.4191 +        }
  1.4192 +
  1.4193 +    iChkDiscRecLevel--;
  1.4194 +    }
  1.4195 +
  1.4196 +//-----------------------------------------------------------------------------------------
  1.4197 +
  1.4198 +//
  1.4199 +// Check FAT is valid for anEntry
  1.4200 +//
  1.4201 +void  CFatMountCB::ChkEntryL(RBitVector& aFatBitVec, const TFatDirEntry& anEntry)
  1.4202 +    {
  1.4203 +    TInt listLength=0;
  1.4204 +
  1.4205 +    if ((anEntry.Attributes()&(KEntryAttDir)) || anEntry.Size())
  1.4206 +        listLength=WalkClusterListL(aFatBitVec, StartCluster(anEntry));
  1.4207 +    else if (anEntry.StartCluster() != 0)        // zero length file
  1.4208 +        User::Leave(EFatChkDskInvalidEntrySize); // shouldn't have clusters
  1.4209 +
  1.4210 +    if (anEntry.Attributes()&KEntryAttDir)
  1.4211 +        ChkDirL(aFatBitVec, StartCluster(anEntry));
  1.4212 +
  1.4213 +    //  Check that the correct number of clusters have been allocated for the size of the file.
  1.4214 +
  1.4215 +    else if ((anEntry.Attributes()&KEntryAttVolume)==0)
  1.4216 +        {
  1.4217 +        TInt clustersForFileSize;
  1.4218 +        TInt clusterSize=1<<ClusterSizeLog2();
  1.4219 +        clustersForFileSize = (TInt) ( (TInt64(anEntry.Size()) + TInt64(clusterSize-1)) >> ClusterSizeLog2() );
  1.4220 +
  1.4221 +        if (listLength!=clustersForFileSize)
  1.4222 +            User::Leave(EFatChkDskInvalidEntrySize);
  1.4223 +        }
  1.4224 +    }
  1.4225 +
  1.4226 +//-----------------------------------------------------------------------------------------
  1.4227 +
  1.4228 +//
  1.4229 +// Walks cluster list from aCluster to EOF
  1.4230 +// Reports an error if an invalid cluster is found before EOF or
  1.4231 +// a cluster has been visited before.
  1.4232 +//
  1.4233 +TInt  CFatMountCB::WalkClusterListL(RBitVector& aFatBitVec, TInt aCluster)
  1.4234 +    {
  1.4235 +
  1.4236 +    TInt i=0;
  1.4237 +    do  {
  1.4238 +        i++;
  1.4239 +        if (!ValidClusterNumber(aCluster))
  1.4240 +            {
  1.4241 +            __PRINT1(_L("Bad Cluster number %d"),aCluster);
  1.4242 +            User::Leave(EFatChkDskIllegalClusterNumber);
  1.4243 +            }
  1.4244 +
  1.4245 +        if (IsClusterVisited(aFatBitVec, aCluster))
  1.4246 +            {
  1.4247 +            __PRINT1(_L("Cluster already in use %d"),aCluster);
  1.4248 +            User::Leave(EFatChkDskClusterAlreadyInUse);
  1.4249 +            }
  1.4250 +
  1.4251 +        MarkClusterVisited(aFatBitVec, aCluster);
  1.4252 +
  1.4253 +        } while (FAT().GetNextClusterL(aCluster));
  1.4254 +
  1.4255 +    return(i);
  1.4256 +    }
  1.4257 +
  1.4258 +//-----------------------------------------------------------------------------------------
  1.4259 +
  1.4260 +//
  1.4261 +// Checks that all unvisited clusters are marked as free in the FAT
  1.4262 +//
  1.4263 +void  CFatMountCB::CheckUnvisitedClustersL(const RBitVector& aFatBitVec) const
  1.4264 +    {
  1.4265 +
  1.4266 +    TInt cluster=2;
  1.4267 +    TInt maxCluster=cluster + UsableClusters();
  1.4268 +    while (cluster<maxCluster)
  1.4269 +        {
  1.4270 +        cluster=NextUnvisitedCluster(aFatBitVec, cluster); //-- move to the next unvisited cluster
  1.4271 +        if(cluster < 0 || cluster >= maxCluster)
  1.4272 +            break;
  1.4273 +
  1.4274 +        TInt clusterVal=FAT().ReadL(cluster);
  1.4275 +        if (clusterVal!=0 && IsEndOfClusterCh(clusterVal)==EFalse && !IsBadCluster(clusterVal))
  1.4276 +            {
  1.4277 +            __PRINT1(_L("\n*****Bad cluster Num = %d"),cluster);
  1.4278 +            User::Leave(EFatChkDskBadCluster);
  1.4279 +            }
  1.4280 +        }
  1.4281 +    }
  1.4282 +
  1.4283 +//-----------------------------------------------------------------------------------------
  1.4284 +
  1.4285 +/**
  1.4286 +@param  aCluster cluster number to check for validity
  1.4287 +@returns ETrue if aCluster is a valid cluster number
  1.4288 +*/
  1.4289 +TBool CFatMountCB::ValidClusterNumber(TUint32 aCluster) const
  1.4290 +    {
  1.4291 +    return (aCluster>=KFatFirstSearchCluster && aCluster<=MaxClusterNumber());
  1.4292 +    }
  1.4293 +
  1.4294 +//-----------------------------------------------------------------------------------------
  1.4295 +
  1.4296 +//
  1.4297 +// Walk the FAT, returns error if find an unterminated list or
  1.4298 +// lists that merge.
  1.4299 +//
  1.4300 +TInt CFatMountCB::CheckDisk()
  1.4301 +    {
  1.4302 +
  1.4303 +    __PRINT1(_L("CFatMountCB::CheckDisk() drv:%d"), DriveNumber());
  1.4304 +
  1.4305 +    if(!ConsistentState())
  1.4306 +        return KErrCorrupt;
  1.4307 +
  1.4308 +    //-- create a bit representation of the FAT
  1.4309 +    const TUint32 MaxClusters = UsableClusters()+KFatFirstSearchCluster; //-- UsableClusters() doesn't count first 2 unused clusers
  1.4310 +
  1.4311 +
  1.4312 +    // cluster count may be zero if boot sector failed to be read (e.g. if the media is locked)
  1.4313 +    // or if TDrive::MountMedia(ETrue) has been called (in which case the boot sector may
  1.4314 +    if (MaxClusters == 0)
  1.4315 +        return KErrCorrupt;
  1.4316 +
  1.4317 +    RBitVector bitVec; //-- each bit in this vector represents a FAT cluster
  1.4318 +
  1.4319 +    TInt nRes = bitVec.Create(MaxClusters);
  1.4320 +    if(nRes != KErrNone)
  1.4321 +        {
  1.4322 +        ASSERT(nRes == KErrNoMemory); //-- the only one possible reason.
  1.4323 +        return KErrNoMemory;
  1.4324 +        }
  1.4325 +
  1.4326 +    iChkDiscRecLevel = 0; //-- reset CheckDisk recursion counter
  1.4327 +    TRAPD(r,ChkDirL(bitVec, RootIndicator())); // Check from root directory
  1.4328 +    if (r==KErrNone)
  1.4329 +        {
  1.4330 +        TRAP(r,CheckUnvisitedClustersL(bitVec));
  1.4331 +        }
  1.4332 +
  1.4333 +
  1.4334 +    bitVec.Close();
  1.4335 +
  1.4336 +    switch(r)
  1.4337 +        {
  1.4338 +
  1.4339 +    case KErrNone:
  1.4340 +        return KErrNone;
  1.4341 +
  1.4342 +    case EFatChkDskIllegalClusterNumber:
  1.4343 +        return(1);
  1.4344 +
  1.4345 +    case EFatChkDskClusterAlreadyInUse:
  1.4346 +        return(2);
  1.4347 +
  1.4348 +    case EFatChkDskBadCluster:
  1.4349 +        return(3);
  1.4350 +
  1.4351 +    case EFatChkDskInvalidEntrySize:
  1.4352 +        return(4);
  1.4353 +
  1.4354 +    default:
  1.4355 +        break;
  1.4356 +        }
  1.4357 +
  1.4358 +    return(r);
  1.4359 +    }
  1.4360 +
  1.4361 +
  1.4362 +//-----------------------------------------------------------------------------------------
  1.4363 +//  Helper functions for Check Disk functionality
  1.4364 +//-----------------------------------------------------------------------------------------
  1.4365 +
  1.4366 +/**
  1.4367 +    Find the next unvisited cluster number in the bit array.
  1.4368 +
  1.4369 +    @param  aBitList    bit array, where '0' bits represent unvisited clusters.
  1.4370 +    @param  aCluster    cluster number to start search with.
  1.4371 +
  1.4372 +    @return positive integer indicating next unvisited cluster number
  1.4373 +            KErrNotFound (-1) if there are no unvisited clusters
  1.4374 +
  1.4375 +*/
  1.4376 +static TInt  NextUnvisitedCluster(const RBitVector& aFatBitVec, TUint32 aCluster)
  1.4377 +{
  1.4378 +    __ASSERT_DEBUG(aCluster >= KFatFirstSearchCluster, Fault(EFatChkDskIllegalClusterNumber)); //-- 1st 2 FAT entries are reserved
  1.4379 +
  1.4380 +    TUint32 searchPos = aCluster; //-- bit number to start search with
  1.4381 +
  1.4382 +    //-- look for the unvisited cluster (bit '0') in the bit array from the searchPos to the right
  1.4383 +    if(aFatBitVec.Find(searchPos, 0, RBitVector::ERight))
  1.4384 +        return searchPos;
  1.4385 +
  1.4386 +    return KErrNotFound;
  1.4387 +}
  1.4388 +
  1.4389 +
  1.4390 +/**
  1.4391 +    Check if we have visited cluster aCluster
  1.4392 +
  1.4393 +    @param  aFatBitVec  bit array, where '0' bits represent unvisited clusters.
  1.4394 +    @param  aCluster    cluster number to check
  1.4395 +    @return ETrue if aCluster has been visited.
  1.4396 +*/
  1.4397 +static TBool IsClusterVisited(const RBitVector& aFatBitVec, TUint32 aCluster)
  1.4398 +{
  1.4399 +    __ASSERT_DEBUG(aCluster >= KFatFirstSearchCluster, Fault(EFatChkDskIllegalClusterNumber)); //-- 1st 2 FAT entries are reserved
  1.4400 +
  1.4401 +    return aFatBitVec[aCluster];
  1.4402 +}
  1.4403 +
  1.4404 +/**
  1.4405 +    Mark aCluster as visited
  1.4406 +    @param  aFatBitVec  bit array, where '0' bits represent unvisited clusters.
  1.4407 +    @param  aCluster    cluster number to mark
  1.4408 +*/
  1.4409 +static void MarkClusterVisited(RBitVector& aFatBitVec, TUint32 aCluster)
  1.4410 +{
  1.4411 +    __ASSERT_DEBUG(aCluster >= KFatFirstSearchCluster, Fault(EFatChkDskIllegalClusterNumber)); //-- 1st 2 FAT entries are reserved
  1.4412 +
  1.4413 +    aFatBitVec.SetBit(aCluster); //-- '1' bit in a bit array means that the corresponding cluster is visited
  1.4414 +}
  1.4415 +
  1.4416 +
  1.4417 +
  1.4418 +//-------------------------------------------------------------------------------------------------------------------
  1.4419 +
  1.4420 +/**
  1.4421 +    Creates a scan drive object and starts the scan.
  1.4422 +*/
  1.4423 +TInt CFatMountCB::DoRunScanDrive()
  1.4424 +{
  1.4425 +    TInt nRes;
  1.4426 +
  1.4427 +    CScanDrive* pScnDrv = NULL;
  1.4428 +    TRAP(nRes, pScnDrv=CScanDrive::NewL(this));
  1.4429 +    if(nRes != KErrNone)
  1.4430 +        return nRes;
  1.4431 +
  1.4432 +    TRAPD(nScnDrvRes, pScnDrv->StartL());
  1.4433 +
  1.4434 +    const TBool bNeedFatRemount = (nScnDrvRes!=KErrNone) || pScnDrv->ProblemsDiscovered();
  1.4435 +    delete pScnDrv;
  1.4436 +
  1.4437 +
  1.4438 +    if(bNeedFatRemount)
  1.4439 +        {//-- ScanDrive found and probably fixed some errors.
  1.4440 +        // ensure cached fat and free cluster count are updated
  1.4441 +        DoDismount(); //-- dismount
  1.4442 +        TRAP(nRes, MountL(EFalse)); //-- mount again
  1.4443 +        }
  1.4444 +
  1.4445 +    if(nScnDrvRes != KErrNone)
  1.4446 +        return nScnDrvRes;
  1.4447 +
  1.4448 +
  1.4449 +    //-- if ScanDrive hasn't found anything wrong or has fixed recoverable erros, mark the volume clean
  1.4450 +    if(VolCleanFlagSupported())
  1.4451 +        {
  1.4452 +        //-- if there is a background FAT scanning thread, we need to wait until it finishes its work.
  1.4453 +        //-- otherwise it's possible to have incorrect amount of free space on the volume until next remounting.
  1.4454 +        (void)FAT().NumberOfFreeClusters(ETrue);
  1.4455 +        TRAP(nRes, FinaliseMountL());
  1.4456 +        ASSERT(nRes == KErrNone);
  1.4457 +        }
  1.4458 +
  1.4459 +    return KErrNone;
  1.4460 +}
  1.4461 +
  1.4462 +//-------------------------------------------------------------------------------------------------------------------
  1.4463 +
  1.4464 +/**
  1.4465 +    Run scan drive on the given volume.
  1.4466 +    The ScanDrive may be skipped on the finalised volumes, i.e. those, that had been shut down properly.
  1.4467 +
  1.4468 +
  1.4469 +    @return Either  KErrCorrupt if an error was found that is not caused by write failure due to power removal.
  1.4470 +                    KErrNone if no error was found. One of four positive codes explaining what type of error was rectified
  1.4471 +*/
  1.4472 +TInt CFatMountCB::ScanDrive()
  1.4473 +{
  1.4474 +    __PRINT1(_L("CFatMountCB::ScanDrive() starting on drive %d"), DriveNumber());
  1.4475 +
  1.4476 +    if(!ConsistentState())
  1.4477 +        return KErrCorrupt;
  1.4478 +
  1.4479 +    TInt nRes;
  1.4480 +
  1.4481 +    if(LockStatus()!=0)
  1.4482 +        {
  1.4483 +        __PRINT(_L("CFatMountCB::ScanDrive() locked!\n"));
  1.4484 +        return KErrInUse;
  1.4485 +        }
  1.4486 +
  1.4487 +    if(iRamDrive)
  1.4488 +        {//-- Do not check internal RAM drive
  1.4489 +        __PRINT(_L("CFatMountCB::ScanDrive() Skipping Internal RAM drive."));
  1.4490 +        return KErrNone;
  1.4491 +        }
  1.4492 +
  1.4493 +    //-- check if the volume is finalised and skip running ScanDrive if this option is enabled in estart.txt
  1.4494 +    if(VolCleanFlagSupported() && FatConfig().ScanDrvSkipFinalisedVolume())
  1.4495 +        {
  1.4496 +        TBool bVolClean = EFalse;
  1.4497 +        TRAP(nRes, bVolClean = VolumeCleanL());
  1.4498 +
  1.4499 +        if(nRes == KErrNone && bVolClean)
  1.4500 +            {
  1.4501 +            __PRINT(_L("Skipping ScanDrive on finalised volume!"));
  1.4502 +            return KErrNone; //-- skip ScanDrive on a clean volume
  1.4503 +            }
  1.4504 +        }
  1.4505 +
  1.4506 +    //-- run ScanDrive
  1.4507 +    nRes = Open();
  1.4508 +    if(nRes != KErrNone)
  1.4509 +        return nRes;
  1.4510 +
  1.4511 +    nRes = DoRunScanDrive();
  1.4512 +
  1.4513 +    Close();
  1.4514 +
  1.4515 +    __PRINT2(_L("~ CFatMountCB::ScanDrive() finished for drive %d with the code %d"),DriveNumber(), nRes);
  1.4516 +
  1.4517 +    return nRes;
  1.4518 +
  1.4519 +}
  1.4520 +
  1.4521 +//-----------------------------------------------------------------------------------------
  1.4522 +/**
  1.4523 +Returns the offset between UTC time and timestamps on the filesystem. This will return User::UTCOffset
  1.4524 +if the flag iUseLocalTime has been set in CFatFileSystem and this mount is on a removable drive. If not
  1.4525 +a null offset is returned.
  1.4526 +
  1.4527 +@return The offset in seconds that timestamps on the filesystem have, relative to UTC.
  1.4528 +*/
  1.4529 +TTimeIntervalSeconds CFatMountCB::TimeOffset() const
  1.4530 +    {
  1.4531 +    if((Drive().Att() & KDriveAttRemovable) && FatFileSystem().GetUseLocalTime() )
  1.4532 +        {
  1.4533 +        return User::UTCOffset();
  1.4534 +        }
  1.4535 +    else
  1.4536 +        {
  1.4537 +        return TTimeIntervalSeconds(0);
  1.4538 +        }
  1.4539 +    }
  1.4540 +
  1.4541 +
  1.4542 +
  1.4543 +
  1.4544 +//-----------------------------------------------------------------------------------------
  1.4545 +/** 
  1.4546 +    Check is this file system can be mounted on the drive at all.
  1.4547 +    Just read and validate boot region, no real mounting overhead. 
  1.4548 +    
  1.4549 +    @return KErrNone    boot region is OK, the file system can be mounted.
  1.4550 +            KErrLocked  the media is locked on a physical level.
  1.4551 +            other error codes depending on the implementation
  1.4552 +
  1.4553 +*/
  1.4554 +TInt CFatMountCB::MntCtl_DoCheckFileSystemMountable()
  1.4555 +    {
  1.4556 +    TInt nRes;
  1.4557 +    
  1.4558 +    const TInt driveNo = Drive().DriveNumber();
  1.4559 +    __PRINT1(_L("CFatMountCB::MntCtl_DoCheckFileSystemMountable() drv:%d"),driveNo);
  1.4560 +
  1.4561 +    nRes = CreateDrive(driveNo);
  1.4562 +    if(nRes != KErrNone)
  1.4563 +        {
  1.4564 +        __PRINT1(_L(" ..CreateDrive() err:%d \n"), nRes);    
  1.4565 +        return nRes;
  1.4566 +        }
  1.4567 +
  1.4568 +    //-- try reading boot sector. This doesn't require iDriverInterface setup, it uses LocalDrive()
  1.4569 +    TFatBootSector bootSector;
  1.4570 +    nRes = ReadBootSector(bootSector);
  1.4571 +
  1.4572 +    DismountedLocalDrive();
  1.4573 +
  1.4574 +    return nRes;
  1.4575 +    }
  1.4576 +
  1.4577 +
  1.4578 +