void AssertionFail(const char* aAssertion, const char* aFile, TInt aLine) { __DEBUGGER(); TBuf8<256> buf; TSilentOverflow o; buf.AppendFormat(_L8("Assertion failed: \"%s\" in %s:%i\n"), &o, aAssertion, aFile, aLine); if (buf.Length()*2>buf.MaxLength()) buf.SetLength(buf.MaxLength()/2); console->Write(buf.Expand()); User::Panic(_L("Fed"), aLine); }
TInt CSuspendTest::ZeroFillBlock( TInt aBlockNumber ) // // Zero-fills and entire block // The requires that writing works // { test.Printf( _L("Zero-filling block %d\n"), aBlockNumber ); // // Create a buffer full of zeros // const TInt KZeroBufSize = 512; TBuf8<KZeroBufSize> buf; buf.FillZ( buf.MaxLength() ); // // Write the data out to the Flash // TInt writeCount = iBlockSize / KZeroBufSize; TInt r = KErrNone; TUint blockBaseOffset = aBlockNumber * iBlockSize; TInt pos = blockBaseOffset; for( ; (writeCount > 0) && (KErrNone == r); writeCount-- ) { r = iDrive.Write( pos, buf ); if( r != KErrNone ) { test.Printf( _L("... FAIL: write failed (%d) at offset 0x%x\n"), pos ); } pos += KZeroBufSize; } return r; }
TVerdict CDumpDrmArchive::doTestStepL() { // SetTestStepResult(EInconclusive) is a bad idea. // It makes the TEST macroes unusable. TPtrC fileName; TPtrC outputPath; GetStringFromConfig(ConfigSection(),_L("Filename"),fileName); GetStringFromConfig(ConfigSection(),_L("outputpath"),outputPath); __UHEAP_MARK; INFO_PRINTF2(_L("Reading DRM archive: %S "), &fileName); RFs fs; User::LeaveIfError(fs.Connect()); CleanupClosePushL(fs); #ifdef SYMBIAN_ENABLE_64_BIT_FILE_SERVER_API RFile64 file; #else RFile file; #endif // SYMBIAN_ENABLE_64_BIT_FILE_SERVER_API User::LeaveIfError(file.Open(fs, fileName, EFileRead | EFileStream | EFileShareReadersOnly)); CleanupClosePushL(file); CRefTestAgentArchive* archive = CRefTestAgentArchive::NewL(file); CleanupStack::PushL(archive); TBuf <256> mimeType; mimeType.Copy(archive->DefaultMimeType()); INFO_PRINTF2(_L("Default Mime Type : %S "), &mimeType); CDrmFiles& drmFiles = archive->DrmFilesL(); // enhance this later // just dump out the default content object CDrmFileContent& defaultContent = drmFiles.FindL(KDefaultContentObject()); TBuf8 <1024> buffer; TInt length = 1024; TFileName outputFileName; outputFileName.Copy(outputPath); outputFileName.Append(_L("output.txt")); RFile outputFile; User::LeaveIfError(outputFile.Create(fs, outputFileName, EFileWrite | EFileStream | EFileShareAny)); CleanupClosePushL(outputFile); while(length > 0) { User::LeaveIfError(defaultContent.Read(buffer, buffer.MaxLength())); length = buffer.Length(); User::LeaveIfError(outputFile.Write(buffer)); } CleanupStack::PopAndDestroy(4, &fs); // fs, file, archive, outputFile __UHEAP_MARKEND; return TestStepResult(); }
void CDrmFilesParser::ConstructL(CVirtualFile& aVirtualFile) { iDrmFiles = CDrmFiles::NewL(); CParser* xmlParser = CParser::NewLC(KXmlMimeType(), *this); xmlParser->ParseBeginL(); // Parse the file in chunks TBuf8 <1024> buffer; TInt length = buffer.MaxLength(); while(length > 0) { User::LeaveIfError(aVirtualFile.Read(buffer,length)); length = buffer.Length(); xmlParser->ParseL(buffer); } // Finished parsing xmlParser->ParseEndL(); CleanupStack::PopAndDestroy(xmlParser); if(!iParseComplete) { LogL(_L("Incomplete XML file")); User::Leave(KErrCorrupt); } }
TInt CVtConsoleOutputController::Write(const TDesC& aDes) { TInt err = KErrNone; if (iMode == ConsoleMode::EBinary) { // staight collapse to 8 bit, no cleverness TBuf8<256> buf; TInt offset = 0; while ((offset < aDes.Length()) && (err == KErrNone)) { buf.Copy(aDes.Mid(offset, Min(aDes.Length() - offset, buf.MaxLength()))); offset += buf.Length(); err = iOutput.Output(buf); } } else { // In text mode we do a UTF-16 -> UTF-8 conversion TRAP(err, iOutputBuf.CopyAsUtf8L(aDes)); if (err == KErrNone) { err = iOutput.Output(iOutputBuf); if (err == KErrNone) { iCursorTracker->Write(aDes); } } } return err; }
TBool SubConnActivities::CEventNotification::FillInEvent(const CSubConNotificationEvent& aEvent) { TBool sendEvent(iEventUidFilterListLength == 0); for (TUint i = 0; i < iEventUidFilterListLength; ++i) { if (iEventUidFilterList[i].iEventGroupUid == aEvent.GroupId() && iEventUidFilterList[i].iEventMask & aEvent.Id()) { sendEvent = ETrue; break; } } if (sendEvent) { TBuf8<KMaxSubConnectionEventSize> eventBuffer; TPtr8 ptr((TUint8*)eventBuffer.Ptr(),eventBuffer.MaxLength()); if (aEvent.Store(ptr) == KErrNone) { LOG(ESockLog::Printf(_L("ESock: CSubConnection[%x]: Notification Sent. Event Type %d"), this, aEvent.Id())); eventBuffer.SetLength(ptr.Length()); TInt err = iMessage.Write(0, eventBuffer); } } return sendEvent; }
EXPORT_C TMTPResponseCode MMTPServiceHandler::SaveServicePropValue( CRepository& aRepository, TUint aColumnNum, TMTPTypeGuid& aNewData) { TInt ret; TMTPResponseCode responseCode = EMTPRespCodeOK; TBuf8<KMTPTypeINT128Size> data; data.FillZ(data.MaxLength()); TUint64 upperValue = aNewData.UpperValue(); TUint64 lowerValue = aNewData.LowerValue(); /** Least significant 64-bit buffer offset. */ const TInt KMTPTypeUint128OffsetLS = 0; /** Most significant 64-bit buffer offset. */ const TInt KMTPTypeUint128OffsetMS = 8; memcpy(&data[KMTPTypeUint128OffsetMS], &upperValue, sizeof(upperValue)); memcpy(&data[KMTPTypeUint128OffsetLS], &lowerValue, sizeof(lowerValue)); ret = aRepository.Set(aColumnNum, data); if (KErrNone != ret) { responseCode = EMTPRespCodeGeneralError; } return responseCode; }
enum TVerdict CTestErrGetTsyVersionNumberSmallBuffer::doTestStepL() /** Check that RTelServer::SendReceive( EEtelServerGetTsyVersionNo, ... ) returns an error when a descriptor is too small for the version info. @return EPass or EFail */ { RTelServer1 server; TInt ret = server.Connect(); TESTCHECK(ret, KErrNone); ret=server.LoadPhoneModule(DSTD_MODULE_NAME); TESTCHECK(ret, KErrNone); // Now lets pass in a small data buffer // This is possible if a programmer derives from RTelServer // and makes a mistake, or does it on purpose for some perverse reason. TInt indexOfPhone=0; TName tsyName; ret = server.GetTsyName(indexOfPhone, tsyName); // Get a name for us to use. TESTCHECK(ret, KErrNone); TBuf8<1> version; TPtr8 ptr(REINTERPRET_CAST(TText8*,&version),version.Length(),version.MaxLength() ); TIpcArgs args(&tsyName, &ptr); ret = server.SendReceive(EEtelServerGetTsyVersionNo,args); // Note only possible of error if we inherit and mess around with calls. // Otherwise goes through API, which is more safe, but even then we can // do some casting. TESTCHECK(ret, KErrOverflow); ret=server.UnloadPhoneModule(DSTD_MODULE_NAME); TESTCHECK(ret, KErrNone); ServerClose(server); return TestStepResult(); }
TBool CSuspendTest::ValidateBlock( TInt aBlockNumber, TUint32 aFillWord ) // // Checks that every word in block aBlockNumber has the value aFillWord // { TUint offset = aBlockNumber * iBlockSize; test.Printf( _L("Validating block %d (offs=0x%x)\n"), aBlockNumber, offset ); TBool failed = EFalse; const TInt readBufLen = iReadBuffer.MaxLength(); for( TInt len = iBlockSize; len > 0 && !failed ;) { TInt r = iDrive.Read( offset, readBufLen, iReadBuffer ); if( r != KErrNone ) { test.Printf( _L("... FAIL: read failed (%d) at offset 0x%x\n"), r, offset ); test( KErrNone == r ); } test( iReadBuffer.Length() == readBufLen ); TUint32* p = (TUint32*)iReadBuffer.Ptr(); for( TInt i = 0; i < readBufLen; i += 4 ) { if( aFillWord != *p ) { failed = ETrue; test.Printf( _L("... FAILED: word @ offs=0x%x, read=0x%x, expected=0x%x\n"), offset+i, p[0], aFillWord ); break; } ++p; } offset += readBufLen; len -= readBufLen; } return !failed; }
void CMessageQueueWriter::WriteBufL(const TDesC8& aBuf) { TBuf8<128> buf; TPtrC8 lineFrag(aBuf); while (lineFrag.Length()) { TInt spaceFree = buf.MaxLength() - buf.Length(); buf.Append(lineFrag.Left(spaceFree)); TInt err = iQ.Send(buf); if (err == KErrOverflow) { // Drop a frame TBuf8<128> buf2; iQ.Receive(buf2); // And resend err = iQ.Send(buf); } lineFrag.Set(lineFrag.Mid(Min(spaceFree, lineFrag.Length()))); buf.Zero(); } }
/** * TotalConvertedLengthL() determines the total length in User Data Elements when the input buffer is converted. * Depending on the conversion properties returned from the alphabet converter, a complete conversion may need * to be performed, i.e. this call can be quite expensive. * * @return Total converted length * * @capability None */ EXPORT_C TInt CSmsBufferSegmenter::TotalConvertedLengthL(TSmsEncoding aEncoding) { OstTraceDef1(OST_TRACE_CATEGORY_DEBUG, TRACE_BORDER, CSMSBUFFERSEGMENTER_TOTALCONVERTEDLENGTHL_1, "CSmsBufferSegmenter::TotalConvertedLengthL(): aEncoding=%d", aEncoding); // Check for shortcut CSmsAlphabetConverter::TSmsAlphabetConversionProperties conversionProperties; iAlphabetConverter.ConversionPropertiesL(conversionProperties); if (conversionProperties.iWidthConversion==CSmsAlphabetConverter::ESmsAlphabetWidthConversionFixed) return iSmsBuffer.Length()*conversionProperties.iUDElementsPerNativeCharacter; // No shortcut, have to do piecewise conversion Reset(); // // Find the best encoding method to use... // TSmsEncoding aEncodingToUse = FindBestAlternativeEncodingL(aEncoding, iSmsBuffer.Length()); // // Segment and count the converted length... // TBool complete=EFalse; TInt totalConvertedLength=0; TInt unconvertedChars=0; TInt downgradedChars=0; TBuf8<CSmsBufferBase::EMaxBufLength> convertedChars; while (!complete) { complete=DoSegmentNextL(convertedChars,convertedChars.MaxLength(), unconvertedChars, downgradedChars, aEncodingToUse); totalConvertedLength+=convertedChars.Length(); } Reset(); return totalConvertedLength; } // CSmsBufferSegmenter::TotalConvertedLengthL
void CSuspendTest::DoRandomWriteSoak() // // For each block issues an erase and then // starts issuing write requests. The intervals // between write requests are derived from the // pseudo-random number generator. // Each block is checked after is has been erased // // The same data is written each time. This data is // also generated from the random number generator. After // each erase the data is read back to check that it is // correct. // { test.Next( _L("Erase suspend soak test using random writes") ); TRandomGenerator random; random.SetSeed( 0x13E00103 ); test.Printf( _L("Preparing buffer") ); TBuf8<20> writeBuf; writeBuf.SetLength( writeBuf.MaxLength() ); for( TInt i = writeBuf.Length(); i > 0;) { --i; writeBuf[i] = static_cast<TUint8>( random.Next() ); } test.Printf( _L("Starting test") ); random.SetSeed( MAKE_TINT64( 0xA05BE111,0x00101111 ) ); iStartTime.HomeTime(); // // We repeat the test for each block, erasing block n and reading from // block (n+1) modulo iBlockCount // // // Writes are always done to the block that we just erased. This // TBool prevents us starting writes until we have erased a block. // TBool firstErase = ETrue; for(;;) { TimeSinceStart(); for( TInt eraseBlock = 0; eraseBlock < iBlockCount; eraseBlock++ ) { TUint32 writeBlock = eraseBlock - 1; if( 0 == eraseBlock ) { writeBlock = iBlockCount - 1; } TUint32 erasePos = eraseBlock * iBlockSize; TInt writePos = writeBlock * iBlockSize; test.Printf( _L("Erasing block %d, writing to block %d"), eraseBlock, writeBlock ); // // Zero the block we are about to erase // test( KErrNone == ZeroFillBlock( eraseBlock ) ); test( ValidateBlock( eraseBlock, 0 ) ); // // Start the erase // _LIT( KEraseNotify, "Main thread starting erase\n" ); test.Printf( KEraseNotify ); iEraser->EraseBlock( erasePos, iBlockSize ); // // Now we loop, waiting for random intervals, issuing // writes, until the erase completes // TBool didWrite = EFalse; while( !iEraser->CheckDone() ) { // // Get a pseudo-random interval between 0 and 524.288 milliseconds // TInt delayInMicroseconds = random.Next() % 0x80000; User::After( delayInMicroseconds ); if( !firstErase ) { test( KErrNone == iDrive.Write( writePos, writeBuf ) ); _LIT( KWriteNotify, "Done write" ); test.Printf( KWriteNotify ); didWrite = ETrue; } } // // Now check that the block was erased // test( ValidateBlock( eraseBlock, 0xFFFFFFFF ) ); firstErase = EFalse; // // Also check that the data written to the Flash is correct. // if( didWrite ) { TBuf8<20> readBuf; test( KErrNone == iDrive.Read( writePos, writeBuf.Length(), readBuf ) ); test( readBuf == writeBuf ); test.Printf( _L("Write data is ok") ); } } } }
LOCAL_C void CreateUidTestFiles() // // Create files with uids for testing // { // Create \\gSessionPath\\UIDCHKNO.SHT - no uid, zero length RFile file; TInt r=file.Replace(TheFs,_L("UIDCHKNO.SHT"),EFileRead|EFileWrite); test_KErrNone(r); file.Close(); // Create \\gSessionPath\\UIDCHKNO.LNG - no uid, long length r=file.Replace(TheFs,_L("UIDCHKNO.LNG"),EFileRead|EFileWrite); test_KErrNone(r); r=file.Write(_L8("Hello World needs to be over 16 bytes")); file.Close(); // Create \\gSessionPath\\UIDCHK.BLG - with uid no data r=file.Replace(TheFs,_L("UIDCHK.BLG"),EFileRead|EFileWrite); test_KErrNone(r); TUidType uidType(TUid::Uid('U'),TUid::Uid('I'),TUid::Uid('D')); TCheckedUid checkedUid(uidType); TPtrC8 buf((TUint8*)&checkedUid,sizeof(TCheckedUid)); r=file.Write(buf); test_KErrNone(r); file.Close(); // Create \\gSessionPath\\UIDCHK.MSG - with uid and data r=file.Replace(TheFs,_L("UIDCHK.MSG"),EFileRead|EFileWrite); test_KErrNone(r); TUidType uidType2(TUid::Uid('X'),TUid::Uid('Y'),TUid::Uid('Z')); checkedUid.Set(uidType2); buf.Set((TUint8*)&checkedUid,sizeof(TCheckedUid)); r=file.Write(buf); test_KErrNone(r); r=file.Write(_L8("More file data")); test_KErrNone(r); file.Close(); // Create \\gSessionPath\\UIDCHK.DAT - uid stored only in the file r=file.Replace(TheFs,_L("UIDCHK.DAT"),EFileRead|EFileWrite); test_KErrNone(r); TUidType uidType3(TUid::Uid('D'),TUid::Uid('A'),TUid::Uid('T')); checkedUid.Set(uidType3); buf.Set((TUint8*)&checkedUid,sizeof(TCheckedUid)); r=file.Write(buf); test_KErrNone(r); r=file.Write(_L8("More file data")); test_KErrNone(r); file.Close(); // Create \\gSessionPath\\UIDCHK.PE - uid stored in WINS PE file header r=file.Replace(TheFs,_L("UIDWINS.PE"),EFileRead|EFileWrite); test_KErrNone(r); #if defined(__WINS__) if (!IsTestingLFFS()) { RFile fileSource; r=fileSource.Open(TheFs,_L("Z:\\TEST\\T_CHKUID.EXE"),EFileShareReadersOnly|EFileRead); test_KErrNone(r); TBuf8<0x100> buffer; do { r=fileSource.Read(buffer); test_KErrNone(r); r=file.Write(buffer); test_KErrNone(r); } while (buffer.Length()==buffer.MaxLength()); fileSource.Close(); } else { r=file.Write(_L8("Some zany stuff here!")); test_KErrNone(r); } #else r=file.Write(_L8("Some zany stuff here!")); test_KErrNone(r); #endif file.Close(); }
LOCAL_C void mainL() // initialize and call example code under cleanup stack { test.Title(); CTestConsole *con = CTestConsole::NewL(test.Console()); RFs fs; User::LeaveIfError(fs.Connect()); CleanupClosePushL(fs); TDriveUnit sysDrive (fs.GetSystemDrive()); TBuf<24> logFile (sysDrive.Name()); logFile.Append(_L("\\temblog.txt")); RFile file; User::LeaveIfError(file.Replace(fs, logFile, EFileShareAny|EFileWrite)); CleanupClosePushL(file); con->SetLogFile(file); test.SetConsole(con); TInt r; RDebug::Printf("Hello from user side\n"); test.Start(_L(" @SYMTestCaseID:SEC-CRYPTOSPI-TEMB-0001 Load driver ")); test.Next(_L("Loading Physical Device")); r=User::LoadPhysicalDevice(KPddFileName); test(r==KErrNone || r==KErrAlreadyExists); test.Next(_L("Loading Logical Device")); r=User::LoadLogicalDevice(KLddFileName); test(r==KErrNone || r==KErrAlreadyExists); // // Generate key and IV // test.Start(_L("Random - Generating key & IV for AES tests")); test.Printf(_L("\tGenerating random key\n")); // Generate random 16 byte key TBuf8<KEYLEN> key; key.SetLength(key.MaxLength()); TRandom::RandomL(key); key[0] = 'K'; key[1] = 'E'; key[2] = 'Y'; key[3] = '*'; for(int z=4; z<KEYLEN; ++z) key[z] = z; test.Printf(_L("\tGenerating random IV\n")); // Generate random 16 byte IV TBuf8<16> iv; iv.SetLength(iv.MaxLength()); TRandom::RandomL(iv); iv[0] = 'I'; iv[1] = 'V'; iv[2] = '*'; iv[3] = '*'; TBuf8<BUFLEN> plaintext; plaintext.FillZ(); plaintext.SetLength(BUFLEN); plaintext[0] = 'P'; plaintext[1] = 'L'; plaintext[2] = 'A'; plaintext[3] = 'I'; plaintext[4] = 'N'; for(int i=0; i<BUFLEN; ++i) { plaintext[i] = i; } // // KMS tests // test.Next(_L("KMS - Store key")); TBuf8<BUFLEN+16> kmsData; kmsData.FillZ(); kmsData.SetLength(0); do { RKeyMgmtSession kms; User::LeaveIfError(kms.Connect()); CleanupClosePushL(kms); TKeyHandle keyHandle; User::LeaveIfError(kms.StoreKey(key, keyHandle)); _LIT_SECURITY_POLICY_PASS(KAlwaysPass); User::LeaveIfError(kms.AddUsage(keyHandle, 0 /* operation */, KAlwaysPass)); test.Next(_L("KMS - Attempt to use key via embedded key handle")); TPckgBuf<TKeyHandle> keyHandlePkg; keyHandlePkg() = keyHandle; TKeyProperty keyProperty = {KAesUid, KNullUid, KSymmetricKeyUid, KNonExtractableKey}; CCryptoParams* keyParam =CCryptoParams::NewLC(); keyParam->AddL(keyHandlePkg, KSymmetricKeyParameterUid); CKey *ckey=CKey::NewL(keyProperty, *keyParam); CleanupStack::PopAndDestroy(keyParam); CleanupStack::PushL(ckey); CryptoSpi::CSymmetricCipher *aes = 0; CSymmetricCipherFactory::CreateSymmetricCipherL(aes, KAesUid, *ckey, KCryptoModeEncryptUid, KOperationModeCBCUid, KPaddingModePKCS7Uid, NULL); CleanupStack::PopAndDestroy(ckey); CleanupStack::PushL(aes); aes->SetOperationModeL(CryptoSpi::KOperationModeCBCUid); aes->SetIvL(iv); aes->ProcessFinalL(plaintext, kmsData); CleanupStack::PopAndDestroy(aes); CleanupStack::PopAndDestroy(&kms); } while(false); // // Encrypt using legacy API // TBuf8<BUFLEN+16> sw; sw.FillZ(); sw.SetLength(0); do { test.Next(_L("Encrypt using key directly (non-KMS)")); // ECB test.Printf(_L(" CBC\n")); CAESEncryptor *rawaes = CAESEncryptor::NewLC(key); // rawaes CModeCBCEncryptor *cbc = CModeCBCEncryptor::NewL(rawaes, iv); CleanupStack::Pop(rawaes); // CleanupStack::PushL(cbc); // cbc #ifdef PKCS7PAD CPadding *pad = CPaddingPKCS7::NewLC(16); // cbc, pad #else CPadding *pad = CPaddingNone::NewLC(16); // cbc, pad #endif CBufferedEncryptor *aes = CBufferedEncryptor::NewL(cbc, pad); CleanupStack::Pop(pad); // cbc CleanupStack::Pop(cbc); CleanupStack::PushL(aes); // aes test.Printf(_L("About to s/w encrypt (old api)\n")); aes->ProcessFinalL(plaintext, sw); CleanupStack::PopAndDestroy(aes); } while(false); test.Printf(_L("Checking KMS encrypt and direct encrypt had the same result\n")); test(kmsData == sw); test.End(); test.Printf(_L("\r\n0 tests failed out of 1\r\n")); // test.Printf(KTxtPressAnyKey); // test.Getch(); // get and ignore character test.Close(); CleanupStack::PopAndDestroy(&file); CleanupStack::PopAndDestroy(&fs); }
// do the example LOCAL_C void doExampleL() { TInt counter; TInt index; // For general binary data, construct an 8 bit // variant descriptor. Binary data is always // treated as 8 bit data regardless of the // build. // // This example constructs a TBuf8 using the // default constructor. TBuf8<32> buffer; // Look at: // 1. Descriptor content // 2. Length of descriptor // 3. Size of descriptor // 4. Maximum length of descriptor // // Length is zero. Maximum length is 32. // Size is zero. _LIT(KFormat1,"\"%S\"; Length()=%d; "); console->Printf(KFormat1,&buffer,buffer.Length()); console->Printf(KCommonFormat2,buffer.Size(),buffer.MaxLength()); // Set up an area in memory initialised // with binary data. TUint8 data[6] = {0x00,0x01,0x02,0xAD,0xAE,0xAF}; // Put data into descriptor buffer.Append(&data[0],sizeof(data)); // Append the following byte values buffer.Append(0xFD); buffer.Append(0xFE); buffer.Append(0xFF); // Length is now 9; maxlength is still 32; // Size is always 9 regardless of build. counter = buffer.Length(); console->Printf(KTxtNewLine); for (index = 0; index < counter; index++) console->Printf(KCommonFormat3,buffer[index]); console->Printf(KCommonFormat4,buffer.Length() ); console->Printf(KCommonFormat2,buffer.Size(),buffer.MaxLength()); // We can also mix text characters and // general binary data. buffer.Append('A'); buffer.Append('B'); buffer.Append(0x11); // Show it counter = buffer.Length(); console->Printf(KTxtNewLine); for (index = 0; index < counter; index++) console->Printf(KCommonFormat3,buffer[index]); console->Printf(KCommonFormat4,buffer.Length()); console->Printf(KCommonFormat2,buffer.Size(),buffer.MaxLength()); }
TVerdict CImportDrmArchive::doTestStepL() { // SetTestStepResult(EInconclusive) is a bad idea. // It makes the TEST macroes unusable. TPtrC source; TPtrC target; TPtrC importerMode; GetStringFromConfig(ConfigSection(),_L("source"),source); GetStringFromConfig(ConfigSection(),_L("target"),target); // importerMode is optional in ini file. If the token exist and its // value == ClientCreateFiles, then RTAUtils will hide the output // filename from CImportFile and handle opening the output file // and receipt files itself. GetStringFromConfig(ConfigSection(),_L("importerMode"),importerMode); _LIT(KClientCreateFiles, "ClientCreateFiles"); TBool doFileCreate = (importerMode.CompareF(KClientCreateFiles) == 0); INFO_PRINTF2(_L("Importing DRM archive : %S "), &source); INFO_PRINTF2(_L("Writing output archive: %S "), &target); TPtrC outputPath; TPtrC suggestedOutFileName; TParsePtrC parser(target); outputPath.Set( parser.DriveAndPath() ); suggestedOutFileName.Set( parser.NameAndExt() ); __UHEAP_MARK; TInt numpushed(0); // create a supplier session CSupplier *mySupplier = CSupplier::NewLC(); numpushed++; mySupplier->SetOutputDirectoryL(outputPath); // fill in a metadata array with just the mime type CMetaDataArray *metaDataArray = CMetaDataArray::NewL(); CleanupStack::PushL(metaDataArray); numpushed++; _LIT8(KContentType,"content-type"); metaDataArray->AddL(KContentType(), KRtaMimeRights); metaDataArray->AddL(KContentType(), KRtaMimeContentRights); CImportFile* import = NULL; if (doFileCreate) { import = mySupplier->ImportFileL(KRtaMimeContentRights, *metaDataArray); } else { import = mySupplier->ImportFileL(KRtaMimeContentRights, *metaDataArray, suggestedOutFileName); } CleanupStack::PopAndDestroy(metaDataArray); // numpushed-- CleanupStack::PushL(import); // numpushed++, so cancel with line above RFs fs; User::LeaveIfError(fs.Connect()); CleanupClosePushL(fs); numpushed++; #ifdef SYMBIAN_ENABLE_64_BIT_FILE_SERVER_API RFile64 sourcefile; #else RFile sourcefile; #endif // SYMBIAN_ENABLE_64_BIT_FILE_SERVER_API User::LeaveIfError(sourcefile.Open(fs, source, EFileRead | EFileStream | EFileShareReadersOnly)); CleanupClosePushL(sourcefile); numpushed++; #ifdef SYMBIAN_ENABLE_64_BIT_FILE_SERVER_API RFile64 targetfile; #else RFile targetfile; #endif // SYMBIAN_ENABLE_64_BIT_FILE_SERVER_API TBool targetFileOpen = EFalse; TInt err(KErrNone); TFileName fn; const TInt KMyBufSize = 1024; TBuf8 <KMyBufSize> buffer; TInt length = KMyBufSize; while(length > 0) { User::LeaveIfError(sourcefile.Read(buffer, buffer.MaxLength())); length = buffer.Length(); err = import->WriteData(buffer); if(err != KErrNone) { if(err == KErrCANewFileHandleRequired) { TESTL(doFileCreate); TESTL(!targetFileOpen); import->GetSuggestedOutputFileName(fn); fn.Insert(0, outputPath); INFO_PRINTF3(_L("Agent suggested name is %S, target is %S."), &fn, &target); User::LeaveIfError(targetfile.Create(fs, target, EFileStream | EFileWrite | EFileShareAny)); CleanupClosePushL(targetfile); numpushed++; targetFileOpen = ETrue; User::LeaveIfError(import->ContinueWithNewOutputFile(targetfile, fn)); } else { INFO_PRINTF2(_L("Error writing data, Error code is: %d"),err); User::LeaveIfError(err); } } } if(targetFileOpen) { CleanupStack::PopAndDestroy(&targetfile); numpushed--; } // process the rights that were received alongside the content err = import->WriteDataComplete(); while(err == KErrCANewFileHandleRequired) { TEST(doFileCreate); import->GetSuggestedOutputFileName(fn); fn.Insert(0, outputPath); INFO_PRINTF2(_L("Creating Receipt File: %S "), &fn); RFile receiptFile; User::LeaveIfError(receiptFile.Replace(fs, fn, EFileStream | EFileWrite | EFileShareAny)); CleanupClosePushL(receiptFile); err = import->ContinueWithNewOutputFile(receiptFile, fn); CleanupStack::PopAndDestroy(&receiptFile); } User::LeaveIfError(err); TPtrC importOutFileName; TPtrC contentOutputName(KNullDesC); for (TInt i = 0; i < import->OutputFileCountL(); i++) { importOutFileName.Set( import->OutputFileL(i).FileName() ); if (import->OutputFileL(i).OutputType() == EContent) { contentOutputName.Set(importOutFileName); } else { // delete the receipt we just created // they only get in the way when importing files using the utility INFO_PRINTF2(_L("Receipt files %S deleted (not important) when using ImportDrmArchive step"), &importOutFileName); fs.Delete(importOutFileName); // ignore return code } } /** * Added doFileCreate check while fixing DEF132876. On using * importerMode=ClientCreateFiles if target is not set as * "RTATest001.content" in the ini file, the comparison below * succeeds and "fs.Rename(contentOutputName, target)" fails, * causing test case to fail. * In all other case, contentOutputName and target are always * same and the if condition is not entered. */ if (!doFileCreate && contentOutputName.CompareF(target) != 0) { // This must be the case that RTA automatically create // output file. See the line targetfile.Create(fs, target, ...). // Before DEF088475, users of RTAUtils test harness can // specify whatever extension for the output file. The // defect fix changed the importer from CRefTestAgentImport // (unit test) to CImportFile (end-to-end test). CImportFile // converts non-standard ext to .content. To maintain backward // compatibility, we need to rename the generated output. fs.Delete(target); // ignore return code TEST(fs.Rename(contentOutputName, target) == 0); } CleanupStack::PopAndDestroy(numpushed); __UHEAP_MARKEND; return TestStepResult(); }
TBool DMemSpyDriverLogChanChunks::IsHeapChunk( DChunk& aChunk, const TName& aName ) { (void) aName; // UREL warning const TUint rHeapVTable = MemSpyDevice().RHeapVTable(); TRACE( Kern::Printf("DMemSpyDriverLogChanChunks::IsHeapChunk() - START - this: 0x%08x, aChunk: 0x%08x, RHeapVTable: 0x%08x, aName: %S, [%O]", this, &aChunk, rHeapVTable, &aName, &aChunk ) ); DMemSpyDriverOSAdaptionDChunk& chunkAdaption = OSAdaption().DChunk(); DMemSpyDriverOSAdaptionDProcess& processAdaption = OSAdaption().DProcess(); // The first 4 bytes of every chunk correspond to the allocator VTable (For heap chunks). // If it matches RHeap's vtable, we'll treat it as a heap. TBool isHeap = EFalse; // There must be an owning process or else it's definitely not a heap chunk. DProcess* process = chunkAdaption.GetOwningProcess( aChunk ); TUint8* base = chunkAdaption.GetBase( aChunk ); const TInt size = chunkAdaption.GetSize( aChunk ); TRACE( Kern::Printf("DMemSpyDriverLogChanChunks::IsHeapChunk() - base: 0x%08x, size: %d, process: 0x%08x (%O)", base, size, process, process ) ); if ( process && size >= 4 ) { NKern::ThreadEnterCS(); // Chunks are mapped into entire process so any thread within the process is enough... DThread* firstThread = processAdaption.OpenFirstThread( *process ); TRACE( Kern::Printf("DMemSpyDriverLogChanChunks::IsHeapChunk() - firstThread: 0x%08x (%O)", firstThread, firstThread ) ); if ( firstThread != NULL ) { TBuf8<4> allocatorVTableBuffer; TInt err = Kern::ThreadRawRead( firstThread, base, (TUint8*) allocatorVTableBuffer.Ptr(), allocatorVTableBuffer.MaxLength() ); TRACE( Kern::Printf("DMemSpyDriverLogChanChunks::IsHeapChunk - read result of vtable data from requested thread is: %d", err )); // if ( err == KErrNone ) { TRACE( MemSpyDriverUtils::DataDump("possible chunk vtable data - %lS", allocatorVTableBuffer.Ptr(), allocatorVTableBuffer.MaxLength(), allocatorVTableBuffer.MaxLength() ) ); allocatorVTableBuffer.SetLength( allocatorVTableBuffer.MaxLength() ); const TUint32 vtable = allocatorVTableBuffer[0] + (allocatorVTableBuffer[1] << 8) + (allocatorVTableBuffer[2] << 16) + (allocatorVTableBuffer[3] << 24); TRACE( Kern::Printf("DMemSpyDriverLogChanChunks::IsHeapChunk - [possible] vTable within chunk is: 0x%08x", vtable) ); // Check the v-table to work out if it really is an RHeap isHeap = ( vtable == rHeapVTable ); TRACE( Kern::Printf("DMemSpyDriverLogChanChunks::IsHeapChunk() - isHeap: %d", isHeap ) ); } TRACE( Kern::Printf("DMemSpyDriverLogChanChunks::IsHeapChunk() - closing first thread..." ) ); Kern::SafeClose( (DObject*&) firstThread, NULL ); } NKern::ThreadLeaveCS(); } /* We only want RHeap's at the moment if ( !isHeap && aName == KMemSpyLitDollarHeap ) { TRACE( Kern::Printf("DMemSpyDriverLogChanChunks::IsHeapChunk() - its called $HEAP, but its not an RHeap... we\'ll let it through though..." ) ); isHeap = ETrue; } */ TRACE( Kern::Printf("DMemSpyDriverLogChanChunks::IsHeapChunk() - END - this: 0x%08x, isHeap: %d", this, isHeap ) ); return isHeap; }