void CDomainNameCodec::DecodeL(TPtr8& aInDes)
	{
	TDomainName domainName;

	TUint8* pChar = const_cast<TUint8*>(aInDes.Ptr());
	TUint listLength = aInDes.Length();
	TUint8 labelLength = 0;
	
	// Walk the list of domain names
	while(pChar < aInDes.Ptr() + listLength)
		{
		domainName.Zero();
		
		while(*pChar++ != NULL)
			{
			if(domainName.Length() > 0)
				{
				domainName.Append('.');
				}
				
			labelLength = *(pChar - 1);
			
			// The two highest order bits must be clear
			User::LeaveIfError(labelLength & 0xC0 ? KErrArgument : KErrNone);
					
			// Add in the label data
			domainName.Append(pChar, labelLength);
			
			// Advance the pointer to the next length value
			pChar += labelLength;
			}
			
		iDomainList.Append(domainName);
		}
	}
Пример #2
0
// ---------------------------------------------------------------------------
// CFepUiLayout::SendEditorTextAndCursorPosL
// handle layout command
// ---------------------------------------------------------------------------
//
void CFepUiLayout::SendEditorTextAndCursorPosL(TUint8* aData)
    {
    RDesReadStream readStream;
    
    TPtr8 countPtr( aData, 2*sizeof(TInt), 2*sizeof(TInt) );            
	readStream.Open(countPtr);
	CleanupClosePushL(readStream);
    const TInt dataCount = readStream.ReadInt32L();
	const TInt textCount = readStream.ReadInt32L();
    CleanupStack::PopAndDestroy(&readStream);
    
    TPtr8 ptr( aData+2*sizeof(TInt), dataCount+textCount, dataCount+textCount );            
	readStream.Open(ptr);
	CleanupClosePushL(readStream);
	
	HBufC8* dataBuf = HBufC8::NewLC(dataCount);
	TPtr8 dataBufPtr = dataBuf->Des();
	readStream.ReadL(dataBufPtr, dataCount);

    TFepInputContextFieldData* pIcfData = 
        reinterpret_cast<TFepInputContextFieldData*>(const_cast<TUint8*>(dataBufPtr.Ptr()));

    HBufC8* textBuf = HBufC8::NewLC(textCount);
	TPtr8 textBufPtr = textBuf->Des();
	readStream.ReadL(textBufPtr, textCount);
    pIcfData->iText.Set( reinterpret_cast<const TUint16*>(textBufPtr.Ptr()),
                         textCount/2);
                         
    OnAppEditorTextComing(*pIcfData);
    
    CleanupStack::PopAndDestroy(textBuf);
    CleanupStack::PopAndDestroy(dataBuf);
	CleanupStack::PopAndDestroy(&readStream);
    }
Пример #3
0
EXPORT_C TInt CDosExtensionBase::ExecuteMessageL(const RMessage2& aMessage)
{
    
    API_TRACE_( "[DOSSERVER] CDosExtensionBase::ExecuteMessageL(...)" );
	__ASSERT_DEBUG(aMessage.Function() == ECallFunction, 
		PanicClient(aMessage,EPanicIllegalFunction));

	TInt retVal(KErrNone);
	TBool parameterModifiedByDSY(EFalse);

	// Get data from RMessage
	TExtensionParPckg extPars;
	aMessage.ReadL(0, extPars);
	
	TInt dataLength(extPars().iParLength);
	if (dataLength >= 0)
	{
		HBufC8* dataBuffer = HBufC8::NewMaxLC( dataLength );
		TPtr8 dataPtr = dataBuffer->Des();
		aMessage.ReadL( 1, dataPtr );

		// Check autocomplete flag
		TUint autoCompl(aMessage.Int2());
		if (autoCompl == KAutoComplete)
		{
            COM_TRACE_4( "[DOSSERVER] MDosExtensionBaseDSY::CallFunctionL(0x%x,0x%x,0x%x,0x%x)"
                ,extPars().iFunc
                ,dataPtr.Ptr()
                ,dataPtr.Length()
                ,autoCompl );

			retVal = CallFunctionL(extPars().iFunc, const_cast<TUint8*>(dataPtr.Ptr()), dataPtr.Length(), parameterModifiedByDSY);

			if((retVal == KErrNone) && parameterModifiedByDSY)
			{
				// Write over client's parameters
				retVal = aMessage.Write(1, dataPtr);
			}
		}
		else
		{
			COM_TRACE_3( "[DOSSERVER] MDosExtensionBaseDSY::CallFunctionAndCompleteL(0x%x,0x%x,0x%x)"
                ,extPars().iFunc
                ,dataPtr.Ptr()
                ,dataPtr.Length() );
        
            CallFunctionAndCompleteL(extPars().iFunc, const_cast<TUint8*>(dataPtr.Ptr()), dataPtr.Length(), aMessage);
		}

		CleanupStack::PopAndDestroy(); // dataBuffer
	}
	else
	{
		// Client passed negative parameter length
		retVal = KErrGeneral;
	}

	return retVal;
}
Пример #4
0
void CProtocolExadump::DoPacket(const RMBufPacketBase &aPacket, const RMBufPktInfo &aInfo)
	/**
	* Dump the packet.
	*
	* This is called for both incoming and outgoing packets, from the
	* respective ApplyL methods.
	*
	* @param aPacket	The packet data
	* @param aInfo		The packet inforrmation
	*/
	{
/** @code */
	// Open the dump file, if not already opened (or attempted).
	if (iOpen == 0)
		DoOpen(1500);
	if (iOpen < 0)
		return;	// cannot open output file.

	//
	// Build PCAP frame into iBuffer (pcap_pkthdr + snapped portion of the packet)
	//
	TPtr8 buf = iBuffer->Des();
	struct pcap_pkthdr *const hdr = (struct pcap_pkthdr *)buf.Ptr();
	TPtr8 ptr((TUint8 *)buf.Ptr() + sizeof(*hdr), buf.MaxLength() - sizeof(*hdr));

	const TInt snap = aInfo.iLength > ptr.MaxLength() ? ptr.MaxLength() : aInfo.iLength;
	ptr.SetLength(snap);
	aPacket.CopyOut(ptr);

	hdr->caplen = snap;
	hdr->len = aInfo.iLength;

	TTime stamp;
	stamp.UniversalTime();
	const TTimeIntervalMicroSeconds elapsed = stamp.MicroSecondsFrom(iBase);
#ifdef I64INT
	hdr->ts.tv_usec = I64INT(elapsed.Int64() % 1000000);
	hdr->ts.tv_sec = I64INT(elapsed.Int64() / 1000000);
#else
	hdr->ts.tv_usec = (elapsed.Int64() % 1000000).GetTInt();
	hdr->ts.tv_sec = (elapsed.Int64() / 1000000).GetTInt();
#endif
	//
	// Write frame out.
	//
	iDumpFile.Write(buf, snap+sizeof(*hdr));
/** @endcode */
	}
int main()
{
    __UHEAP_MARK;
    int retval =ESuccess;
    wchar_t* mywcharstring = L"Hello Widechar String";
    int wchar_length= wcslen(mywcharstring);
    TBufC8<30> buf;
    TPtr8 myTptr = buf.Des();
    char* temp=new char[30];
    retval = WcharpToTptr8(mywcharstring,temp, myTptr);

    int buf_len = myTptr.Length();
    if (retval ==ESuccess &&\
    wchar_length == buf_len &&\
    strncmp("Hello Widechar String",(char*)myTptr.Ptr() , 21) ==0 )
    {
    printf("wcharptotptr8 content check Passed\n");
    }
    else
    {
    assert_failed = true;
    printf("wcharptotptr8 content check Failed\n");
    }      
    delete []temp;
    __UHEAP_MARKEND;
    testResultXml("test_wcharptotptr8_content_check");
	
	return 0;
}
EXPORT_C int Tptr8ToWcharp(const TPtr8& aSrc, wchar_t* aDes, int& n_size)
{
   
    int retval = ESuccess;
    unsigned int ilen = aSrc.Length();
    int minusone = -1;
    
    if (0 == ilen)
    {
    	return EDescriptorNoData;
    }
    else if(!aDes)
    {
    	return EInvalidPointer;
    } 
	else if(n_size < ilen+1)
    {
        n_size = ilen+1 ;
    	return EInvalidSize;
    }
	
	if(minusone != mbstowcs(aDes, (const char*)aSrc.Ptr(), ilen))
	{
	    aDes[ilen] = L'\0';
	}
	else 
	{
		retval = EInvalidMBSSequence;
	}
	
	return retval;
}
Пример #7
0
TReal CGpsDataHandler::ParseCoordinateData() {
	TPtr8 pBuffer = iBuffer->Des();
	TReal aAngle;
	TReal aResult = 0.0;
	TInt aFindResult;

	aFindResult = pBuffer.Find(_L8(","));
	if(aFindResult != KErrNotFound) {
		HBufC8* aField = HBufC8::NewL(aFindResult);
		CleanupStack::PushL(aField);
		TPtr8 pField = aField->Des();

		pField.Copy(pBuffer.Ptr(), aFindResult);
		pBuffer.Delete(0, aFindResult+1);

		TLex8 aFieldLex(pField.Ptr());
		if(aFieldLex.Val(aAngle, '.') == KErrNone) {
			TInt32 aDegrees;
			Math::Int(aDegrees, aAngle / 100.0);

			TInt32 aMinutes;
			Math::Int(aMinutes, aAngle - aDegrees * 100);

			TReal aDecimal;
			Math::Frac(aDecimal, aAngle);

			aResult = aDegrees + (aMinutes + aDecimal) / 60.0;

			if(pBuffer[0] == TUint('S') || pBuffer[0] == TUint('W')) {
				aResult = -aResult;
			}

			aFindResult = pBuffer.Find(_L8(","));

			if(aFindResult != KErrNotFound) {
				pBuffer.Delete(0, aFindResult+1);
			}
		}

		CleanupStack::PopAndDestroy();
	}

	return aResult;
}
Пример #8
0
/**
@SYMTestCaseID			PDS-STORE-UT-4055
@SYMTestCaseDesc		Test for DEF141471 - STORE, new stream performance tests.
						PREQ2505 Insturmentation of PDS.
						RMemWriteStream & RMemReadStream performance tests.
@SYMTestPriority		High
@SYMTestActions			Test for DEF141471 - STORE, new stream performance tests.
@SYMTestExpectedResults Test must not fail
@SYMDEF					DEF141471
*/
void MemStreamTestL()
	{
	HBufC8* buf = HBufC8::NewLC(KBufSize);
	TPtr8 bufPtr = buf->Des();

	//RMemWriteStream::Open()	
	RMemWriteStream strm1;
	TUint32 fc = User::FastCounter();
	strm1.Open(const_cast <TUint8*> (bufPtr.Ptr()), KBufSize);
	TUint32 openFc = CalcTickDiff(fc, User::FastCounter());
	PrintFcDiffAsUs(_L("###  RMemWriteStream::Open(), Time=%d us\r\n"), openFc);
	strm1.Close();
	
	//RMemWriteStream::RMemWriteStream(TAny*,...)	
	fc = User::FastCounter();
	RMemWriteStream strm2(const_cast <TUint8*> (bufPtr.Ptr()), KBufSize);
	TUint32 constrFc = CalcTickDiff(fc, User::FastCounter());
	PrintFcDiffAsUs(_L("###  RMemWriteStream::RMemWriteStream(TAny*,...), Time=%d us\r\n"), constrFc);
	CleanupClosePushL(strm2);
	DoStreamWriteTestL(strm2);
	CleanupStack::PopAndDestroy(&strm2);
	
	//RMemReadStream::Open()
	RMemReadStream strm3;
	fc = User::FastCounter();
	strm3.Open(bufPtr.Ptr(), KBufSize);
	openFc = CalcTickDiff(fc, User::FastCounter());
	PrintFcDiffAsUs(_L("###  RMemReadStream::Open(), Time=%d us\r\n"), openFc);
	strm3.Close();

	//RMemReadStream::RMemReadStream(TAny*,...)	
	fc = User::FastCounter();
	RMemReadStream strm4(bufPtr.Ptr(), KBufSize);
	constrFc = CalcTickDiff(fc, User::FastCounter());
	PrintFcDiffAsUs(_L("###  RMemReadStream::RMemReadStream(TAny*,...), Time=%d us\r\n"), openFc);
	CleanupClosePushL(strm4);
	DoStreamReadTestL(strm4);
	CleanupStack::PopAndDestroy(&strm4);
	
	CleanupStack::PopAndDestroy(buf);
	}
Пример #9
0
void CRFC3984Encode::AddSnaluPacketL( TPtr8 aStart, TInt aSize )
    {
    HBufC8* pBuffer = HBufC8::NewLC( aSize );
	
	TPtr8 pPtr = pBuffer->Des();
	pPtr.Copy( aStart.Ptr(), aSize );
	
	// inserting into the payloadized NAL unit buffer for retreival
	iPayloadizedBuffers.InsertL( pBuffer, iNalCount );
	iNalCount++;
	CleanupStack::Pop( pBuffer );
    }
Пример #10
0
void CSecureSocketReader::IssueRead()
	{
	SUPLLOG(ELogP1, "CSecureSocketReader::IssueRead() Begin\n");
	if (!IsActive())
		{
		TPtr8 ptr = iBuffer.MidTPtr(iReadSoFar);
		iPtr.Set(const_cast<TUint8*>(ptr.Ptr()), 0, ptr.MaxLength());
		iSocket.RecvOneOrMore(iPtr, iStatus, iBufferRead);
		SetActive();
		}
	SUPLLOG(ELogP1, "CSecureSocketReader::IssueRead() End\n");
	}
Пример #11
0
//------------------------------------------------------------
// CNsmlObexClient::ReceiveDataL( TDes8& aStartPtr, TRequestStatus &aStatus )
//------------------------------------------------------------
void CNsmlObexClient::ReceiveDataL( TPtr8& aStartPtr, TRequestStatus &aStatus )
    {
	iAgentStatus = &aStatus;
	// agent
	*iAgentStatus = KRequestPending;
	
	iDataPtr.Set( aStartPtr );

    if ( iState != EWaitingToReceive )
        {
        User::Leave( KErrDisconnected );
        }
    else if ( IsActive() ) 
        {
        User::Leave( KErrInUse );
        }
	iDataBuf->Reset();
	iCurrObject->Reset();

	TBuf8<KNameLen> str;
	str.Copy( this->iMimeType->Des() );
	iCurrObject->SetTypeL( str );

	iClient->Get( *iCurrObject, iStatus );
	
	DBG_DUMP((void*)aStartPtr.Ptr(), aStartPtr.Length(), 
	_S8("ReceiveDataL (WBXML)"));
#ifdef __NSML_DEBUG__
	_DBG_FILE("CNsmlObexClient::ReceiveDataL: CWbxml2XmlConverter::ConvertL()\
	 begin");
	CWbxml2XmlConverter* c = CWbxml2XmlConverter::NewLC();
	c->ConvertL(aStartPtr.Ptr(), aStartPtr.Length());
	DBG_DUMP((void*)c->Document().Ptr(), c->Document().Length(), 
	_S8("ReceiveDataL (XML)") );
	CleanupStack::PopAndDestroy(); // c
	_DBG_FILE("CNsmlObexClient::ReceiveDataL: CWbxml2XmlConverter::ConvertL() end");
#endif // __NSML_DEBUG__

	SetActive ();
    }
Пример #12
0
/*
** Read data from a file into a buffer.  Return SQLITE_OK if all
** bytes were read successfully and SQLITE_IOERR if anything goes
** wrong.
*/
int winRead(
  sqlite3_file *id,          /* File to read from */
  void *pBuf,                /* Write content into this buffer */
  int amt,                   /* Number of bytes to read */
  sqlite3_int64 offset       /* Begin reading at this offset */
){
  int rc;
  size_t got;
  symbianFile *pFile = (symbianFile*)id;
  assert( id!=0 );
  SimulateIOError(return SQLITE_IOERR_READ);
  TInt tOffset = (TInt)offset;
  rc = pFile->file.Seek(ESeekStart, tOffset);
  if( rc!= KErrNone){
    return SQLITE_FULL;
  }

  HBufC8* buf = HBufC8::NewL(amt) ;
  TPtr8 ptr = buf->Des();

  if (pFile->file.Read(ptr, amt) != KErrNone)
	  {
	    delete buf;
	    return SQLITE_IOERR_READ;
	  }

  got = buf->Length();

  if( got == 0 ){
	  delete buf;
	  TInt size = 0;
	  if (pFile->file.Size(size) != KErrNone) 
	  {
		  return SQLITE_IOERR_READ;
	  }
	  if (size == 0)
	  {
		  return SQLITE_IOERR_SHORT_READ;
	  }
    return SQLITE_IOERR_READ;
 }
  memcpy(pBuf, ptr.Ptr(), got);
  delete buf;
 if( got == amt ){
    return SQLITE_OK;
  }else{
    memset(&((char*)pBuf)[got], 0, amt-got);
    return SQLITE_IOERR_SHORT_READ;
  }
}
Пример #13
0
///////////////////////////////////////////////////////////////////
//  CopyPackedFileHeaderToUnpackedObject
//  This function copies the packet format log file element to an
//  unpacked object.
///////////////////////////////////////////////////////////////////
void CEventViewer::CopyPackedLogElemToUnpackedObject(TUint32 aPositionOfCurrLogElem)
    {
    // Build the log element pointer

    TPtr8 logFileBuf (iLogFileBuf->Des()); // Log file in memory
    TPtr8 logElem (const_cast<TUint8*>(logFileBuf.Ptr())+ aPositionOfCurrLogElem, // Data ptr
                   iUnpackedLogElem.iEventLength,   // Data length
                   iUnpackedLogElem.iEventLength);  // Max length

    // Convert the TPtr8 parameter to TUint8* format

    TLogElem* logElemPtr = (TLogElem*) logElem.Ptr(); 


    // Copy the packet format header parameters to unpacked object

    iUnpackedLogElem.iMsgId                = logElemPtr->GetMsgId();
    iUnpackedLogElem.iTimeStamp            = logElemPtr->GetTimeStamp();
    iUnpackedLogElem.iSourceComponent      = logElemPtr->GetSourceComponent();
    iUnpackedLogElem.iCategory             = logElemPtr->GetCategory();
    iUnpackedLogElem.iDescrCount           = logElemPtr->GetDescrCount();

    }
Пример #14
0
/** 
EncodeToL()

Encode a populated outgoing message to the specified buffer.

@param  aBuf buffer pointer 
@return error indication, KErrNone otherwise
*/
EXPORT_C TInt CSuplMessageBase::EncodeToL(TPtr8& aBuf)
	{
	SUPLLOG(ELogP1, "CSuplMessageBase::EncodeToL() Begin\n");
	__ASSERT_DEBUG(iIsOutgoingMessage, User::Invariant());

	TInt retval = KErrNone;
	
	// buffer pointer, fixed max length
	TUint8* msgBuf = (TUint8*)aBuf.Ptr();
	TInt maxLength = aBuf.MaxLength();
	
	// Log the un-encoded SUPL values
	SUPLLOG(ELogP9, "-> ENCODING SUPL MESSAGE FOR SENDING\n");
	//LogMessageContent();
	
	// if the message is a SUPL POS, encode the payload
	if (iData->message.t == T_UlpMessage_msSUPLPOS)
		{
		CSuplPos* suplPos = reinterpret_cast <CSuplPos*>(this);
		retval = suplPos->EncodePosPayloadL();
		if (retval != KErrNone)
			{
			SUPLLOG(ELogP1, "CSuplMessageBase::EncodeToL() Error encoding Positioning Payload\n");
			return retval;
			}
		}
		
	// construct the encode buffer control object
	iEncodeBuffer = new (ELeave) ASN1PEREncodeBuffer (msgBuf, (unsigned int)maxLength, FALSE, (OSRTContext*)iControl->getContext());
	
	// Encode the message to the buffer
	TInt stat = iControl->EncodeTo(*iEncodeBuffer);

	if (stat == 0)
		{
		// Set the length according to reported buffer length
		TInt len = iEncodeBuffer->getMsgLen ();
		iData->length = len;
		aBuf.SetLength(len);
		
		// clear the encoded length field
		msgBuf[0] = 0;
		msgBuf[1] = 0;

		// set the encoded length field
      	msgBuf[0] |= (TUint8)( len >> 8 );
		msgBuf[1] |= (TUint8)( len );
		}
//
// Get interface number
//
TInt CNcmCommunicationInterface::GetInterfaceNumber()
{
    OstTraceFunctionEntry1( CNCMCOMMUNICATIONINTERFACE_GETINTERFACENUMBER_ENTRY, this );

    TInt interfaceSize = 0;
    // 2 is where the interface number is, according to the LDD API
    const TInt intNumOffsetInDes = 2;

    // 0 means the main interface in the LDD API
    TInt res = iPort.GetInterfaceDescriptorSize(0, interfaceSize);

    if ( res )
    {
        OstTraceFunctionExit1( CNCMCOMMUNICATIONINTERFACE_GETINTERFACENUMBER_EXIT, this );
        return res;
    }

    HBufC8* interfaceBuf = HBufC8::New(interfaceSize);
    if ( !interfaceBuf )
    {
        OstTraceFunctionExit1( CNCMCOMMUNICATIONINTERFACE_GETINTERFACENUMBER_EXIT_DUP1, this );
        return KErrNoMemory;
    }

    TPtr8 interfacePtr = interfaceBuf->Des();
    interfacePtr.SetLength(0);
    // 0 means the main interface in the LDD API
    res = iPort.GetInterfaceDescriptor(0, interfacePtr);

    if ( res )
    {
        delete interfaceBuf;
        OstTraceFunctionExit1( CNCMCOMMUNICATIONINTERFACE_GETINTERFACENUMBER_EXIT_DUP2, this );
        return res;
    }

    const TUint8* buffer = reinterpret_cast<const TUint8*>(interfacePtr.Ptr());
    iInterfaceNumber = buffer[intNumOffsetInDes];

    delete interfaceBuf;
    OstTraceFunctionExit1( CNCMCOMMUNICATIONINTERFACE_GETINTERFACENUMBER_EXIT_DUP3, this );
    return KErrNone;
}
/**
Encode CBW into the supplied buffer. The command is also encoded using the
supplied encoding method of MClientCommandServiceReq.

@param aBuffer The buffer to copy the encoded stream in to
@param aCommand The command to be encoded into the Command Block field
*/
void TBotCbw::EncodeL(TPtr8 &aBuffer, const MClientCommandServiceReq* aCommand) const
{
    __MSFNSLOG
    aBuffer.SetLength(KCbwLength);

    TPtr8 commandBlock = aBuffer.MidTPtr(TBotCbw::KCbwCbOffset);

    aBuffer.FillZ();

    TInt cbLength = aCommand->EncodeRequestL(commandBlock);

    TUint8* ptr = (TUint8 *) aBuffer.Ptr();
    LittleEndian::Put32(&ptr[KCbwSignatureOffset], 0x43425355);
    LittleEndian::Put32(&ptr[KCbwTagOffset], iTag);
    LittleEndian::Put32(&ptr[KCbwDataTransferLengthOffset], iDataTransferLength);
    aBuffer[KCbwFlagOffset] = (iDirection == EDataOut) ? 0x00 : 0x80;
    aBuffer[KCbwLunOffset] = iLun;
    aBuffer[KCbwCbLengthOffset] = cbLength;
    __BOTPRINT1(_L("BOT TBotCbw::Encode Lun=%d"), iLun);
}
Пример #17
0
void COptionList::ParseL(TPtr8& aDes8)
/**
  * Parse message to set pointers into descriptor buffer
  * at locations of each option supplied in a response msg
  *
  * @internalTechnology
  */
	{
	ASSERT(!iRecord.iFirst);
	
    COptionNode** ppNode = reinterpret_cast<COptionNode**>(&iRecord.iFirst);
	
	while(aDes8.Length())
        {
        User::LeaveIfError(aDes8.Length() < KOptionHeaderLength ? KErrBadDescriptor : KErrNone);

        TUint nOptCode = TBigEndian::GetValue(aDes8.Ptr(), KOptionLengthOffset);

		*ppNode = CreateNodeL(nOptCode);
		(*ppNode)->ParseL(aDes8);
		
		ppNode = reinterpret_cast<COptionNode**>(&(*ppNode)->iNext);
		}
	}
/**
Draws a VerticalGradient onto a CFbsBitmap from top/color aLo to bottom/aHi
*/
void CTe_graphicsperformanceSuiteStepBase::VerticalGradientAlphaL(CFbsBitmap* aBitmap, TRgb aLo, TRgb aHi)
	{
	const TSize size = aBitmap->SizeInPixels();
	const TDisplayMode mode = aBitmap->DisplayMode();
	const TInt scanLineLength = CFbsBitmap::ScanLineLength(size.iWidth, mode);
	HBufC8* buffer = HBufC8::NewL(scanLineLength);
	CleanupStack::PushL(buffer);
	TPtr8 des = buffer->Des();
	des.SetLength(scanLineLength);
	for(TInt i=0; i<size.iHeight; i++)
		{
		TRgb color = InterpolateColour(aLo, aHi, i, size.iHeight);
		switch(mode)
			{
			case EGray256:
				{
				TUint8  g = color.Gray256();
				TUint8* p = (TUint8*)des.Ptr();
				for(TInt j=0; j<size.iWidth; j++)
					{						
					p[j] = g;
					}
				}
				break;
			case EColor64K:
				{
				TUint16  g = color._Color64K();
				TUint16* p = (TUint16*)des.Ptr();
				for(TInt j=0; j<size.iWidth/2; j++)
					{						
					p[j] = g;
					}
				}
				break;
			case EColor16MU:
				{
				TUint32 rgba = color._Color16MU();
				TUint32* p = (TUint32*)des.Ptr();
				for(TInt j=0; j<(size.iWidth/4); j++)
					{						
					p[j] = rgba;
					}
				}
				break;
			case EColor16MA:
				{
				TUint32 rgba = color._Color16MA();
				TUint32* p = (TUint32*)des.Ptr();
				for(TInt j=0; j<(size.iWidth/4); j++)
					{						
					p[j] = rgba;
					}
				}
				break;
			case EColor16MAP:
				{
				TUint32 rgba = color._Color16MAP();
				TUint32* p = (TUint32*)des.Ptr();
				for(TInt j=0; j<(size.iWidth/4); j++)
					{						
					p[j] = rgba;
					}
				}
				break;
			default:
				ASSERT(EFalse);
				break;
			}
		aBitmap->SetScanLine(des, i);
		}
	CleanupStack::PopAndDestroy(buffer);
	}
Пример #19
0
void CIkev1Dialog::StoreUserNameL(TPtr8 aUserName)
{
/*--------------------------------------------------------------------
 *
 *  Store specified user name into cache file (used as init value in
 *  the next user name specific dialog).
 *  User name shall be encrypted (DES) before stored into cache file. 
 *
 *---------------------------------------------------------------------*/

 
	if (aUserName.Length() == 0)
	    {
	    User::Leave(KErrArgument);
	    }
		
	//
	// Allocate buffer for file header and encrypted key
	//

	HBufC8* HeaderBfr = HBufC8::NewLC(aUserName.Length() + sizeof(TUserNameFileHdr) + 32);
    
	TUserNameFileHdr* FileHeader = (TUserNameFileHdr*)HeaderBfr->Ptr();
	//
	// Get random data values for salt and IV. 
	//
	TPtr8 ptr((TUint8*)FileHeader, sizeof(TUserNameFileHdr));
	ptr.SetLength(sizeof(TUserNameFileHdr));
	TRandom::RandomL(ptr);

	FileHeader->iFileId = USER_NAME_FILE_ID;	
	//
	// Build encryption key from just created salt data and fixed
	// secret passphrase using MD5 hash
	//
	TBuf8<16>  EncryptionKey;
	TPtr8 SaltPtr((TUint8*)FileHeader->iSalt, 8, 8);
	User::LeaveIfError(CIkev1Dialog::BuildEncryptionKey(SaltPtr, EncryptionKey));
	   //
	   // Encrypt user name data with just created key. 
	   // Because DES is used as encryption algorithm, the eight first
	   // octets of created encryption octets is used as encryption key.
	   //
	    TInt EncrLth = 0;
    EncrLth = SymmetricCipherL((TUint8*)aUserName.Ptr(),
					          ((TUint8*)FileHeader + sizeof(TUserNameFileHdr)),
           					    aUserName.Length(), FileHeader->iIV, (TUint8*)EncryptionKey.Ptr(), ETrue);
	if ( EncrLth ) 
	    {
        //
        // Write encrypted data into user name file
        //
		RFile NameFile;		  

		TBuf<128> Ppath;	
		User::LeaveIfError(iFs.PrivatePath(Ppath));

	    Ppath.Append(USER_NAME_CACHE_FILE);
	    TInt err = iFs.CreatePrivatePath(EDriveC);
	    if (err != KErrNone &&
	        err != KErrAlreadyExists)
	        {
	        User::Leave(err);
	        }
	    User::LeaveIfError(NameFile.Replace(iFs, Ppath, EFileShareAny|EFileWrite));

		TPtrC8 EncryptedData((TUint8*)FileHeader, sizeof(TUserNameFileHdr) + EncrLth); 

		NameFile.Write(EncryptedData);
		NameFile.Close();
	    }

    CleanupStack::PopAndDestroy(); // Delete encryption buffer
}
Пример #20
0
/**
@SYMTestCaseID			PDS-SQL-UT-4151
@SYMTestCaseDesc		Measures the performance of inserting multiple records
						into the Music Player MPX database.  This test is based on 
						a real Music Player Harvesting use case
@SYMTestPriority		Medium
@SYMTestActions			Reads SQL transactions from a file and executes them.  
						Records the time for executing each statement
@SYMTestExpectedResults All statements should be executed without error and 
						performance measurements logged
@SYMDEF					DEF142306
*/
void RunTest()
	{
	//Open the file with the sql statements 
	_LIT(KSqlFileName,"z:\\test\\t_sqlperformance4.sql");
	RFile sqlFile;
	TInt err = sqlFile.Open(TheFs, KSqlFileName, EFileRead); 
	TEST2(err, KErrNone);
	
	TInt fileLen = 0;
	err = sqlFile.Size(fileLen); 
	TEST2(err, KErrNone);
	
	HBufC8* sqlBuf = HBufC8::New(fileLen); 
	TEST(sqlBuf != NULL);
	TPtr8 sql = sqlBuf->Des();
	err = sqlFile.Read(sql);
	
	sqlFile.Close();
	TEST2(err, KErrNone);
	TEST2(sql.Length(), fileLen);
	
	//Open main database
	err = TheDbC.Open(TheDbFileName, &TheSqlConfigString);
	TEST2(err, KErrNone);
	
	TheTest.Printf(_L("Beginning INSERTS...\n"));
	
	const TInt KRecordCount = 6544;
	TInt recordCount = 0;
	TInt insertCnt = 0;
	TInt updateCnt = 0;
	TInt selectCnt = 0;
	TInt trnCnt = 0;
	TInt totalTime = 0;

	TInt insertTrnCnt = 0;
	TInt updateTrnCnt = 0;
	TInt selectTrnCnt = 0;
	
	for(;sql.Length()>0;)
		{
		TInt eolPos = sql.Locate(TChar('\n'));
		if(eolPos < 0)
			{
			break;//No more SQL statements
			}
		TInt stmtLength = eolPos;
		while (stmtLength > 0 && (sql[stmtLength-1] == '\r'))
			{
			--stmtLength; //Reduce length to remove carriage return characters from the end of the statement string
			}
		TPtrC8 sqlStmt8(sql.Ptr(), stmtLength);
		TPtrC8 ptr = sql.Mid(eolPos + 1);//"eolPos + 1" - first character after '\n'
		sql.Set(const_cast <TUint8*> (ptr.Ptr()), ptr.Length(), ptr.Length());
		++recordCount;
		
		//Convert to 16 bit query string
		TBuf<1024> query;
		query.Copy(sqlStmt8);
		
		//Execute the statement
		TInt start = User::FastCounter();
		err = TheDbC.Exec(query);
		TInt end = User::FastCounter();
		
		TEST(err >= 0);
		
		//Get the execution time for that statement
		TInt duration = GetDuration(start, end);
		totalTime += duration;
		
		if(query == KBeginTransaction)
			{		
			TheTest.Printf(_L("Execute Statement - BEGIN: %d us\n"), duration);
			}
		
		else if(query == KCommitTransaction)
			{
			++trnCnt;
			TheTest.Printf(_L("Execute Statement - COMMIT: %d us, Trn#%d, \"INSERT\" count: %d, \"UPDATE\" count: %d, \"SELECT\" count: %d\n"), 
					duration, trnCnt, insertTrnCnt, updateTrnCnt, selectTrnCnt);
			insertTrnCnt = updateTrnCnt = selectTrnCnt = 0;
			}

		else
			{	
			TPtrC queryType(query.Ptr(), 6);
			TheTest.Printf(_L("Execute Statement - %S: %d us\n"),&queryType, duration);
			if(queryType.FindF(_L("INSERT")) >= 0)
				{
				++insertCnt;
				++insertTrnCnt;
				}
			else if(queryType.FindF(_L("UPDATE")) >= 0)
				{
				++updateCnt;
				++updateTrnCnt;
				}
			else if(queryType.FindF(_L("SELECT")) >= 0)
				{
				++selectCnt;
				++selectTrnCnt;
				}
			}
		}
	delete sqlBuf;
	
	TheDbC.Close();
	
	TheTest.Printf(_L("Total time to process Songs: %d us\n"), totalTime);
	TheTest.Printf(_L("Transactions count: %d, \"INSERT\" count: %d, \"UPDATE\" count: %d, \"SELECT\" count: %d\n"), 
			               trnCnt, insertCnt, updateCnt, selectCnt);
	TEST2(recordCount, KRecordCount);
	}
void eapol_am_wlan_authentication_symbian_c::read_configureL(
	const TDesC& aDbName,
	const TDesC& aTableName,
	eap_config_string field,
	const u32_t /*field_length*/,
	eap_variable_data_c * const data)
{	
	EAP_TRACE_BEGIN(m_am_tools, TRACE_FLAGS_DEFAULT);
	EAP_TRACE_DEBUG(
		m_am_tools, 
		TRACE_FLAGS_DEFAULT, 
		(EAPL("eapol_am_wlan_authentication_symbian_c::read_configureL(): %s, this = 0x%08x => 0x%08x\n"),
		 (m_is_client == true) ? "client": "server",
		 this,
		 dynamic_cast<abs_eap_base_timer_c *>(this)));
	EAP_TRACE_RETURN_STRING_FLAGS(m_am_tools, TRACE_FLAGS_DEFAULT, "returns: eapol_am_wlan_authentication_symbian_c::read_configureL()");

	// Open database
	RDbNamedDatabase db;

	TInt error = db.Open(m_session, aDbName);

	EAP_TRACE_DEBUG(
		m_am_tools, 
		TRACE_FLAGS_DEFAULT, 
		(EAPL("eapol_am_wlan_authentication_symbian_c::read_configureL(): db.Open(), error = %d\n"),
		 error));

	User::LeaveIfError(error);
	
	CleanupClosePushL(db);


	// Create a buffer for the ascii strings - initialised with the argument
	HBufC8* asciibuf = HBufC8::NewLC(128);
	TPtr8 asciiString = asciibuf->Des();
	asciiString.Copy(reinterpret_cast<const unsigned char *>(field));
		
	// Buffer for unicode parameter
	HBufC* unicodebuf = HBufC::NewLC(128);
	TPtr unicodeString = unicodebuf->Des();
	
	// Convert to unicode 
	unicodeString.Copy(asciiString);

	// Now do the database query
	HBufC* buf = HBufC::NewLC(KMaxSqlQueryLength);
	TPtr sqlStatement = buf->Des();
	_LIT(KSQLQueryRow, "SELECT %S FROM %S");
	sqlStatement.Format( KSQLQueryRow, &unicodeString, &aTableName );
	
	RDbView view;
	User::LeaveIfError(view.Prepare(db, TDbQuery(sqlStatement), TDbWindow::EUnlimited));
	CleanupClosePushL(view);
	User::LeaveIfError(view.EvaluateAll());	
	if (view.FirstL())
	{
		eap_status_e status(eap_status_process_general_error);
		view.GetL();		
		switch (view.ColType(1))
		{
		case EDbColText:				
			{
				unicodeString = view.ColDes(1);
				// Convert to 8-bit
				asciiString.Copy(unicodeString);
				if (asciiString.Size() > 0)
				{
					status = data->set_copy_of_buffer(asciiString.Ptr(), asciiString.Size());
					if (status != eap_status_ok)
					{
						User::Leave(m_am_tools->convert_eapol_error_to_am_error(
							EAP_STATUS_RETURN(m_am_tools, status)));
					}
				} 
				else 
				{
					// Empty field. Do nothing...data remains invalid and the stack knows what to do hopefully.
					break;
				}
			}
			break;
		case EDbColUint32:
			{
				TUint value;
				value = view.ColUint32(1);
				status = data->set_copy_of_buffer((const unsigned char *) &value, sizeof(value));
				if (status != eap_status_ok)
				{
					User::Leave(m_am_tools->convert_eapol_error_to_am_error(
						EAP_STATUS_RETURN(m_am_tools, status)));
				}
			}
			break;
		default:
			EAP_TRACE_DEBUG(
				m_am_tools,
				TRACE_FLAGS_DEFAULT,
				(EAPL("ERROR: read_configureL: Unexpected column type.\n")));
			User::Panic(_L("EAPOL"), 1);			
		}
	} 
	else 
	{
		// Could not find parameter
		EAP_TRACE_DEBUG(
			m_am_tools,
			TRACE_FLAGS_DEFAULT,
			(EAPL("ERROR: read_configureL: Could not find configuration parameter.\n")));
		User::Leave(m_am_tools->convert_eapol_error_to_am_error(
							EAP_STATUS_RETURN(m_am_tools, eap_status_not_found)));
	}		
	
	// Close database
	CleanupStack::PopAndDestroy(&view);
	CleanupStack::PopAndDestroy(buf);
	CleanupStack::PopAndDestroy(unicodebuf);
	CleanupStack::PopAndDestroy(asciibuf);
	CleanupStack::PopAndDestroy(&db);


	EAP_TRACE_END(m_am_tools, TRACE_FLAGS_DEFAULT);
}
Пример #22
0
/*
-------------------------------------------------------------------------------

    Class: CStifParser

    Method: NextSectionMemoryL

    Description: Parses sections from configuration files.

    Open and read configuration source and parses a required section.
    If start tag is empty the parsing starts beginning of the configuration
    file. If end tag is empty the parsing goes end of configuration file.
    This method will parse next section after the earlier section if aSeeked
    parameter is not given.
    If configuration file includes several sections with both start and end
    tags so aSeeked parameter seeks the required section. The aSeeked
    parameters indicates section that will be parsed.

    Parameters: const TDesC& aStartTag: in: Indicates a start tag for parsing
                const TDesC& aEndTag: in: Indicates an end tag for parsing
                TInt aSeeked: in: a seeked section which will be parsed

    Return Values:  CStifSectionParser* : pointer to CStifSectionParser object
                    NULL will return if file size or aSeeked is not positive
                    NULL will return if start tag is not found
                    NULL will return if end tag is not found
                    NULL will return if parsed section length is not positive

    Errors/Exceptions:  Leaves if called Size method fails
                        Leaves if HBufC::NewLC method leaves
                        Leaves if called Read method fails
                        Leaves if CStifSectionParser::NewL methods leaves

    Status: Proposal

-------------------------------------------------------------------------------
*/
CStifSectionParser* CStifParser::NextSectionMemoryL( const TDesC& aStartTag,
                                                 	 const TDesC& aEndTag,
                                                     TInt aSeeked )
    {
    TInt size( 0 );
    // Parser is created straight with data
    if( iParsingMode == EBufferParsing )
        {
        size = iBuffer.Length();
        }
    // Parser is created with path and file informations
    else
        {
        User::LeaveIfError( iFile.Size( size ) );
        }

    // size or aSeeked cannot be 0 or negetive
    if( size <= 0 || aSeeked <= 0)
        {
        __TRACE(
            KInfo, ( _L( "STIFPARSER: NextSectionL method returns a NULL" ) ) );
        return NULL;
        }

    const TInt tmpSize = 128;//--UNICODE-- KMaxName; // 128 - set to even value, because KMaxName may change in the future
    TInt offset( 0 ); // Offset value to parts reading

    // Construct modifiable heap-based descriptor. tmp to CleanupStack
    HBufC* tmp = HBufC::NewLC( size );
    TPtr wholeSection = tmp->Des();

    // Construct modifiable heap-based descriptor. tmp2 to CleanupStack
    HBufC8* tmp2 = HBufC8::NewLC( tmpSize );    // 128
    TPtr8 buf = tmp2->Des();

    // Construct modifiable heap-based descriptor. tmp3 to CleanupStack
    HBufC* tmp3 = HBufC::NewLC( tmpSize );      // 128
    TPtr currentSection = tmp3->Des();

    // Parser is created straight with data
    if( iParsingMode == EBufferParsing )
        {
        // If 8 bit copy changes to 16
        wholeSection.Copy( iBuffer );
        }
    // Parser is created with path and file informations
    else
        {
        TPtrC16 currentSectionUnicode;
        do // Read data in parts(Maximum part size is KMaxName)
            {
            // Read data
            User::LeaveIfError( iFile.Read( offset, buf, tmpSize ) );

            // If file is unicode convert differently
            if(iIsUnicode)
                {
                // 8 bit to 16 with unicode conversion - simply point to byte array as to double-byte array
                currentSectionUnicode.Set((TUint16 *)(buf.Ptr()), buf.Length() / 2);
                // Appends current section to whole section
                wholeSection.Append( currentSectionUnicode );
                }
            else
                {
                // 8 bit to 16
                currentSection.Copy( buf );
                // Appends current section to whole section
                wholeSection.Append( currentSection );
                }

            offset += tmpSize;

            } while( offset < size );
        }

    CleanupStack::PopAndDestroy( tmp3 );
    CleanupStack::PopAndDestroy( tmp2 );

    // User wants section without c-style comments
    if( iCommentType == ECStyleComments )
        {
        ParseCommentsOff( wholeSection );
        }

    TLex lex( wholeSection );
    lex.SkipAndMark( iOffset );

    // For the required section length and positions
    TInt length( 0 );
    TInt lengthStartPos( 0 );
    TInt lengthEndPos( 0 );
    TBool eos( EFalse );
    TInt tagCount( 1 );

    // Check is aStartTag given
    if ( aStartTag.Length() == 0 )
        {
        // Skip line break, tabs, spaces etc.
        lex.SkipSpace();
        lengthStartPos = lex.Offset();
        }
    else
        {
        // While end of section
        while ( !lex.Eos() )
            {
            TPtrC ptr = lex.NextToken();
            // Start of the section is found and correct section
            if ( ptr == aStartTag && tagCount == aSeeked )
                {
                lengthStartPos = lex.Offset();
                break;
                }
            // Start tag is found but not correct section
            else if ( ptr == aStartTag )
                {
                tagCount++;
                }
            }
        }

    // If we are end of section lex.Eos() and eos will be ETrue
    eos = lex.Eos();

    // Seeked section is not found
    if ( tagCount != aSeeked )
        {
        __TRACE( KInfo, ( _L(
            "STIFPARSER: NextSectionL method: Seeked section is not found" ) ) );
        CleanupStack::PopAndDestroy( tmp );
        User::Leave( KErrNotFound );
        }

    // Check is aEndTag given
    if ( aEndTag.Length() == 0 )
        {
        lengthEndPos = wholeSection.Length();
        }
    else
        {
        // While end of section
        while ( !lex.Eos() )
            {
            TPtrC ptr = lex.NextToken();
            // End tag of the section is found
            if ( ptr == aEndTag )
                {
                lengthEndPos = lex.Offset();
                // Because Offset() position is after the aEndTag
                lengthEndPos -= aEndTag.Length();
                break;
                }
            }
        }

    // If we are end of section and lengthEndPos is 0
    if ( lengthEndPos == 0 )
        {
        // lex.Eos() and eos will be ETrue
        eos = lex.Eos();
        }

    // The length includes spaces and end of lines
    length = ( lengthEndPos - lengthStartPos );

    CStifSectionParser* section = NULL;

    // If eos is true or length is negative
    if ( eos || length <= 0  )
        {
        __TRACE(
            KInfo, ( _L( "STIFPARSER: NextSectionL method returns a NULL" ) ) );
        }
    else
        {
        // Make CStifSectionParser object and alloc required length
        section = CStifSectionParser::NewL( length );
        CleanupStack::PushL( section );

        // Copy required data to the section object
        section->SetData( wholeSection, lengthStartPos, length );

        //iOffset += lengthEndPos + aEndTag.Length();
        iOffset = lex.Offset();

        CleanupStack::Pop( section );
        }
    CleanupStack::PopAndDestroy( tmp );

    return section;

    }
Пример #23
0
void CRFC3984Encode::PayloadizeNaluL(
    TDes8 & aBuffer, 
    TUint32 /*aTimeStamp*/, 
    TUint32& /*aMarkerBit*/, 
    TInt & aNalCount )
    {
	TInt startIndex = 0;
	TInt size = 0;
	
	__ASSERT_ALWAYS( iToPayloadizeCount > 0, User::Leave( KErrArgument ) );
	
	__ASSERT_ALWAYS( iToPayloadizeBuffer.Count() == iToPayloadizeSizeBuffer.Count(), 
	                 User::Leave( KErrArgument ) );
		
	if ( iToPayloadizeCount == 1 ) // SNALU packet
	    {
		startIndex = iToPayloadizeBuffer[0];
		size = iToPayloadizeSizeBuffer[0];	
		TPtr8 start = aBuffer.MidTPtr( startIndex );
		AddSnaluPacketL( start, size );
    	}
	else // payloadize STAP-A packet
	    {
		TInt count = 0;
		TInt totalSize = 0;
		TUint8 headerByte = 0;
		
		for ( count = 0; count < iToPayloadizeCount; count++ )
		    {
		    // finding total size of all the NALU's to aggregate
			totalSize += iToPayloadizeSizeBuffer[count]; 
		    }
		
		// addding the total size fields and STAP-A header size	
		totalSize += ( iToPayloadizeCount*2 + 1 ); 
		
		count = 0;
		
		// allocating memory for the total buffer size		
		HBufC8* pBuffer = HBufC8::NewLC( totalSize );
		
		TUint16 value = 0;
		TPtr8 pDes1 = pBuffer->Des();
		
		headerByte = PACKET_STAP_A | ( aBuffer[iToPayloadizeBuffer[count]] & ( 0x7 << 5 ) ); 
		pDes1.Append( &headerByte, 1 );
		
		 // Pps and sps are handled as SNALUs, 
		 // if there's nothing else to packetize, stap-a packet is not created
		TBool stapPacketCreated( EFalse );
		for( count = 0; count < iToPayloadizeCount; count++ )
		    {
			startIndex = iToPayloadizeBuffer[count];
			size = iToPayloadizeSizeBuffer[count];
			TPtr8 pStart = aBuffer.MidTPtr( startIndex ); // getting start index
			
			if ( TMccCodecInfo::IsAvcPpsOrSpsData( pStart, ETrue ) )
			    {
			    AddSnaluPacketL( pStart, size );
			    }
			else
			    {
    			// convert to network byte order
    			value = ByteOrder::Swap16( static_cast<TUint16>( size ) ); 
    			TUint8* ptrByte = reinterpret_cast<TUint8*>( &value );
    			pDes1.Append( ptrByte, 2 );
    			pDes1.Append( pStart.Ptr(), size );
    			stapPacketCreated = ETrue;
			    }
		    }
		
		if ( stapPacketCreated )
		    {
    		// inserting stap-a packet into the payloadized NAL unit buffer for retrieval
        	iPayloadizedBuffers.InsertL( pBuffer, iNalCount );
        	iNalCount++;
        	CleanupStack::Pop(pBuffer);
		    }
		else
		    {
		    // stap-a packet not created
		    CleanupStack::PopAndDestroy(pBuffer);
		    }
	    }
	
    //Now cleaning up the buffer
    iToPayloadizeBuffer.Reset();
    iToPayloadizeSizeBuffer.Reset();
    iToPayloadizeCount = 0;
    	
	aNalCount = iNalCount;
    }
Пример #24
0
void CRFC3984Encode::FragmentNaluL(
    TDes8 & aBuffer, 
    TUint32 /*aTimeStamp*/, 
    TUint32 & aMarkerBit, 
    TInt & aNalCount, 
    TInt aStartIndex, 
    TInt aSize, 
    TUint16 aDON )
    {
	TInt index = 0;
	TInt fragsPacketized = 0;
	TUint8 headerByte = 0; // FU-A packet header byte (contains F, NRI, Type Fields) 
	TUint8 fragHeaderByte = 0;
	TInt length = 0;
	// maximum size of fragment, 4 is to cater for DON field in FU-B
	TInt fragMaxSize = iMaxPacketSize - 4; 
	TInt fragSize = 0; // size of fragment
	HBufC8 * pBuffer = NULL;
	
	// index keeps track of indexes in the buffer
	index = aStartIndex; 
	// length of data packetized, the code decrements this after each fragment is made
	length = aSize;	
	
	while ( length > 0 )
	    {
	     // Actually should be based on (PacketizationMode == INTERLEAVED && fragsPacketized == 0)
		TBool fuB = EFalse;
		
		headerByte = aBuffer[aStartIndex]  & ( 0x07 << 5 ); // Extracting F and NRI bits
		
		// taking lower 5 type bits and putting into fragHeader
		fragHeaderByte = aBuffer[aStartIndex] & 0x1f; 
			
		if ( fragsPacketized == 0 )
		    {
		    fragHeaderByte |= (0x1 << 7); // setting start bit
		    }
		    
		if ( length <= fragMaxSize )
		    {
			fragHeaderByte |= ( 0x1 << 6 );	// setting end byte
			aMarkerBit = 1;	
		    }
		else
		    {
			aMarkerBit = 0;
		    }
		
		if ( fragsPacketized == 0 )	// skipping payload header byte for FU packets 
		    {	
		    index += 1;
			length -= 1;	
		    }
	    
	    fragSize = ( length > fragMaxSize ) ? fragMaxSize+2 : length+2; // 2 bytes for headers
		
		if( !fuB )
		    {
			headerByte |= PACKET_FU_A;	
		    }
		else
		    {
			fragSize += 2; // for additional DON field
			headerByte |= PACKET_FU_B;
		    }
		
		// allocating memory for fragmented NAL unit
	    pBuffer = HBufC8::NewLC(fragSize);
	     	
 		TPtr8 pDes = pBuffer->Des(); //new (ELeave) TBuf8<size>;
		pDes.Append( &headerByte, 1 ); // appending FU-A packet header byte
		pDes.Append( &fragHeaderByte, 1 ); // appending Fragment header
		
		if ( fuB )
		    {  
		    // writing DON in network byte order
			TUint16 val = ByteOrder::Swap16( aDON );
			TUint8* ptrByte = reinterpret_cast<TUint8*>( &val );
			pDes.Append( ptrByte, 2 );
		    }
		
		TPtr8 pStart = aBuffer.MidTPtr( index ); // pStart contains the data pointer    		
    	
    	if ( !fuB )
    	    {
    		pDes.Append( pStart.Ptr(), fragSize-2 ); // copying data	
    		index += Min( length, fragMaxSize );    	
    		length -= ( fragSize-2 );
        	}
    	else
    	    {
    	    // copying data, subtracting DON and header size from total size to copy
    		pDes.Append( pStart.Ptr( ), fragSize-4 );
			index += Min( length, fragMaxSize );
			length -= ( fragSize-4 );    		
    	    }
    
    	
    	// inserting into the payloadized NAL unit buffer for retreival
    	iPayloadizedBuffers.InsertL( pBuffer, iNalCount );
    	iNalCount++;
    	CleanupStack::Pop( pBuffer );
    	pBuffer = NULL; // ownership transferred
    	
    	fragsPacketized++; // to count the number of fragments
	
	    } // end while()
	
	aNalCount = iNalCount;
    }
/*!
    \internal
    RunL from CActive.
*/
void CHbDeviceDialogSymbianPrivate::RunL()
{
    TInt completionCode = iStatus.Int();
    int errorCode = SymToDeviceDialogError(completionCode);

    if (completionCode < KErrNone) {
        // Any Symbian error, stop requesting, sycnhoronous requests are stopped
        // in the end of the RunL
        iRequesting = EFalse;
        SetError(errorCode);
        if (CallDialogClosedObserver(errorCode)) {
            return; // observed deleted this object, do not touch it
        }
    }
    else {
        // Check that event is for latest device dialog. iDeviceDialogId was updated by server
        // during show()
        THbDeviceDialogSrvUpdateInfo &updateInfo = iUpdateInfo();
        if (updateInfo.iDeviceDialogId == iDeviceDialogId()) {
            switch(updateInfo.iUpdateType) {
            case EHbDeviceDialogUpdateData: {
                if (completionCode == KErrNone &&
                    updateInfo.iInfo.iDataInfo.iDataSize > 0) {
                    // Resize buffer and get new data synchronously
                    delete iBuffer;
                    iBuffer = NULL;
                    iBuffer = HBufC8::NewL(updateInfo.iInfo.iDataInfo.iDataSize);
                    iDataPtr.Set(iBuffer->Des());
                    completionCode = iHbSession.SendSyncRequest(EHbSrvUpdateData, iDataPtr);
                    errorCode = SymToDeviceDialogError(completionCode);

                    // data request failed
                    if (completionCode < KErrNone) {
                        iRequesting = EFalse;
                        SetError(errorCode);
                        if (CallDialogClosedObserver(errorCode)) {
                            return; // observed deleted this object, do not touch it
                        }
                    }
                }
                if (completionCode == KErrNone) {
                    // Signal data if there are connections. Otherwise keep a copy.
                    QByteArray resArray((const char*)iDataPtr.Ptr(), iDataPtr.Size());
                    QDataStream stream(&resArray, QIODevice::ReadOnly);

                    iDataReceived.clear();

                    QVariant var;
                    stream >> var;
                    QVariantMap varMap = var.toMap();

                    if (iObserver) {
                        CHbSymbianVariantMap* symbianMap =
                            HbSymbianVariantConverter::fromQVariantMapL(varMap);
                        bool thisIsDeleted = CallDataReceivedObserver(*symbianMap);
                        delete symbianMap;
                        symbianMap = 0;
                        if (thisIsDeleted) { // observer deleted this, do not touch anymore
                            return;
                        }
                    }
                    else {
                        iDataReceived = varMap;
                    }
                }
                break;
            }
            case EHbDeviceDialogUpdateClosed:
                // Signal possible cancelled error
                if (completionCode != KErrNone) {
                    SetError(errorCode);
                }
                iRequesting = EFalse;
                if (CallDialogClosedObserver(errorCode)) {
                    return; // observed deleted this object, do not touch it
                }
                break;
            default:
                break;
            }
        }
    }
Пример #26
0
/*
-----------------------------------------------------------------------------

  ProcessL

  Process image referenced by aImage (modify aImage).
  May leave with KErrNoMemory if no memory available

  Return Values:  none

-----------------------------------------------------------------------------
*/
void CDCDithering::ProcessL(CFbsBitmap& aImage)
{
    TUint	r, g, b;	// Color components
    TUint8*	dataPtr;	// Pointer to data

    //Dithering variables, init to 0
    TInt	count=0;
    TInt16	dither=0;

    //EColor16M image is needed
    if (aImage.DisplayMode() != EColor16M || aImage.DisplayMode() != EColor16M)
        return;

    // Line Buffer and pointer to the data
    TUint imageWidth = aImage.SizeInPixels().iWidth;
    TUint scanLineLengthInBytes = aImage.ScanLineLength(imageWidth, aImage.DisplayMode());

    //Allocate buffer for scanline
    iScanLineBuffer = HBufC8::NewMaxL(scanLineLengthInBytes);
    //Pointer to scanline
    TPtr8 linePtr = iScanLineBuffer->Des();

    //Step through image lines
    for (TInt lineNo=0; lineNo<aImage.SizeInPixels().iHeight; ++lineNo)
    {
        //Get line
        aImage.GetScanLine(linePtr, TPoint(0, lineNo), imageWidth, aImage.DisplayMode());
        //CHECK! CONST_CAST not used in every algorithm which way is better?
        dataPtr = CONST_CAST(TUint8*, linePtr.Ptr());

        //Step through image pixels
        for (TUint x=0; x < imageWidth; ++x)
        {
            // Get original values
            b = *dataPtr++;
            g = *dataPtr++;
            r = *dataPtr++;

            //Compute DCDithering factor from base count
            switch (count&1)
            {
            case 0:
                dither = (TInt16)(dither*0x7ffd);
                break;
            case 1:
                dither = (TInt16)(dither+0x7f21);
                break;
            }

            //Add DCDithering factor, adjust gain according to quantization factors.
            r = Limit255((TInt)r + (dither>>13));
            g = Limit255((TInt)g - (dither>>14));
            b = Limit255((TInt)b + (dither>>13));

            //Move to the previous pixel
            dataPtr -= 3;

            /* Set the result */
            *dataPtr++ = (TUint8)b;
            *dataPtr++ = (TUint8)g;
            *dataPtr++ = (TUint8)r;

            //Increase bae count
            count++;
        }

        //Set scan line
        aImage.SetScanLine(linePtr, lineNo);
    }

    //Free allocated memory
    delete(iScanLineBuffer);
    iScanLineBuffer = 0;
}
Пример #27
0
void COptionList::ParseL(TPtr8& aDes8)
/**
  * Parse message to set pointers into descriptor buffer
  * at locations of each option supplied in a response msg
  *
  * @internalTechnology
  */
	{
	__CFLOG_VAR((KLogSubSysDHCP, KLogCode, _L8("COptionList::ParseL")));
	ASSERT(!iRecord.iFirst);

	COptionNode** ppNode = reinterpret_cast<COptionNode**>(&iRecord.iFirst);
	TUint8 nCode = *aDes8.Ptr();
	COptionNode* pNode;
	TInt i, nItemLen, nHeaderLength;
	while (nCode != EDHCPEnd && aDes8.Length() > 0)
		{
		for (i = 0; KOptions[i].iCode != nCode && ++i < KNumberOfSupportedOptions;) {}
		nHeaderLength = (nCode == EDHCPPad) ? KEDHCPPadLength : KOptionHeaderLength; 
		pNode = new(ELeave) COptionNode(nHeaderLength);
		
		/* ppNode is a pointer to a pointer. It has not got assigned any dynamically allocated memory. But coverity has misinterpreted it an issue.*/
		// coverity [SYMBIAN.CLEANUP STACK]
		// coverity [leave_without_push]
		CleanupStack::PushL(pNode);
		
		/* pNode can not be Null here as the memmory assignment is done using new(ELeave). Thus, there is no need of checking for Null, explicitly .*/
		// coverity[deref_ptr_in_call]	
		pNode->ParseL(aDes8);
		nItemLen = pNode->GetItemLength();
		
		if (aDes8.Length() > 0)
			{
			nCode = *aDes8.Ptr();
			}
		else
			{
			__CFLOG_VAR((KLogSubSysDHCP, KLogCode, _L8("COptionList::ParseL Option list ended without EDHCPEnd flag")));
			}

		if (i < KNumberOfSupportedOptions)
			{
			// now do some sanity checks and leave if bad results
			TInt nPayloadLength = nItemLen - nHeaderLength;
			*ppNode = pNode;

			if (nItemLen < KOptions[i].iMinLength)	// min length check
				{
				__CFLOG_VAR((KLogSubSysDHCP, KLogCode, _L8("COptionList::ParseL BadDescriptor 2")));
				*ppNode = NULL;
				User::Leave(KErrBadDescriptor);
				}

			if (nPayloadLength % KOptions[i].iAlignment != 0)	// alignment check
				{
				__CFLOG_VAR((KLogSubSysDHCP, KLogCode, _L8("COptionList::ParseL BadDescriptor 3")));
				*ppNode = NULL;
				User::Leave(KErrBadDescriptor);
				}

			if (KOptions[i].iExpLength > 0 && nPayloadLength != KOptions[i].iExpLength)	//expected length check
				{
				__CFLOG_VAR((KLogSubSysDHCP, KLogCode, _L8("COptionList::ParseL BadDescriptor 4")));
				*ppNode = NULL;
				User::Leave(KErrBadDescriptor);
				}

			ppNode = reinterpret_cast<COptionNode**>(&(pNode->iNext));
			CleanupStack::Pop(pNode);
			}
		else
			{
#ifdef SYMBIAN_NETWORKING_DHCP_MSG_HEADERS
			//make sure we parse everything becz we support every option now
			if (pNode)
				{
				*ppNode = pNode;
				ppNode = reinterpret_cast<COptionNode**>(&(pNode->iNext));
				CleanupStack::Pop(pNode);
				}
			else
				{
#endif // SYMBIAN_NETWORKING_DHCP_MSG_HEADERS
 			__CFLOG_VAR((KLogSubSysDHCP, KLogCode, _L8("COptionList::ParseL Code Not Found")));

			/* ppNode is a pointer to a pointer. It has not got assigned any dynamically allocated memory. But coverity has misinterpreted it an issue.*/
			// coverity [SYMBIAN.CLEANUP STACK]
			// coverity [memory_leak]
 			CleanupStack::PopAndDestroy(pNode);
 			pNode=NULL;
#ifdef SYMBIAN_NETWORKING_DHCP_MSG_HEADERS
				}
#endif // SYMBIAN_NETWORKING_DHCP_MSG_HEADERS
			}
		}


	}
Пример #28
0
TInt CMP4Demux::ReadAndSendFrames()
    {    

    DASSERT( iGotFrame );

    // Find the correct channel. If there is no channel open for this
    // type of frames, we'll simply ignore it
    TOutputChannel *chan = 0;
    TUint i;
    for ( i = 0; i < iNumOutputChannels; i++ )
        {
        if ( iOutputChannels[i].iDataType == iFrameType )
            chan = &iOutputChannels[i];
        }    
    
    if ( chan )
        {
        // OK, we have a target channel. Get a block from its queue
        
        TPtr8 *block = 0;                       
        
        // NOTE: if output block does not need to be saved in any case, make it a local variable

        //PRINT((_L("framelen = %d, bytesdemuxed = %d\n"), iFrameLen, iBytesDemuxed));

        TUint blockLen = iFrameLen;
        TPtr8 readDes(0,0);        
        TInt error;

        if ( iFrameType == EDataVideo ) 
        {
            // make room for timestamp
            blockLen += 4;
        }              
        


        TRAP( error, (block = chan->iTargetQueue->GetFreeBlockL(blockLen)) );
        if ( error != KErrNone )
            return error;        

        if ( iFrameType == EDataVideo ) 
        {
            TUint8 *p = (TUint8 *)(block->Ptr()) + 4;
            readDes.Set( p, 0, TInt(iFrameLen) );
        }
        else
        {
            readDes.Set( *block );
        }
                
        TUint32 numReadFrames = 0;
        TUint32 timeStamp;

        // read frame(s) from parser
        error = iParser->ReadFrames(readDes, CMP4Parser::TFrameType(iFrameType), 
            numReadFrames, timeStamp);
   
        if ( error != KErrNone )
            return error;

        DASSERT( numReadFrames > 0 );   
        
        if ( iFrameType == EDataAudio )
        {
            block->SetLength(readDes.Length());            
        }
        else
        {            
            block->SetLength(readDes.Length() + 4);

            // put timestamp in the output block before the actual frame data                       
            TUint* d = (TUint *)(block->Ptr());            
            Mem::Copy(d, &timeStamp, 4);
        }

        iBytesDemuxed += TUint( readDes.Length() );
        
        // Send the block
        chan->iTargetQueue->WriteBlock(block);        
        iFrameLen = 0;
        iFrameType = EDataNone;
        iGotFrame = EFalse;
        }
    else
        {     
        PRINT((_L("Unknown channel\n")));
        }    
    
    return KErrNone;
    }
Пример #29
0
///////////////////////////////////////////////////////////////////
//  GetStartPositionOfLogElem
//  This function calculates the start position of a log element.
//  As input parameter it has the position of the first byte
//  after the element.
///////////////////////////////////////////////////////////////////
TInt CEventViewer::GetStartPositionOfLogElem(TUint32 aPositionOfLogElemEnd,       
                                             TUint32* aPositionOfLogElem)
    {

    // Set base for the most recent log element trailer

    TPtr8 logFileBuf (iLogFileBuf->Des()); // Log file in memory
    TUint32  logElemTrailerPos = aPositionOfLogElemEnd - LOG_ELEM_TRAILER_LTH;

    if (iWrappingOccured && logElemTrailerPos <= iCurrFileHeader.iPositionOfNextFree)
        {

        return KErrNotFound;
        }

    TPtr8 elemTrailer (const_cast<TUint8*>(logFileBuf.Ptr())+ logElemTrailerPos, // Data ptr
                       LOG_ELEM_TRAILER_LTH,    // Data length
                       LOG_ELEM_TRAILER_LTH);   // Max length
    // Convert the TPtr8 parameter to TUint8* format

    TLogElemTrailer* elemTrailerPtr = (TLogElemTrailer*) elemTrailer.Ptr(); 

    // Copy the packet format trailer parameters to unpacked object

    iLogElemTrailer.iEndMark1             = elemTrailerPtr->GetEndMark1();
    iLogElemTrailer.iEndMark2             = elemTrailerPtr->GetEndMark2();
    iLogElemTrailer.iEventLength          = elemTrailerPtr->GetEventLength();

    // Check the validity of trailer

    if (iLogElemTrailer.iEndMark1 != END_MARK_1
        ||
        iLogElemTrailer.iEndMark2 != END_MARK_2
        ||
        iLogElemTrailer.iEventLength > aPositionOfLogElemEnd +
        EVENTLOG_FILE_HEADER_LTH)
        {

        return KErrGeneral;
        }

    // Set position for the current log element

    TUint32  logElemPos = aPositionOfLogElemEnd - iLogElemTrailer.iEventLength;

    if (iWrappingOccured && logElemPos < iCurrFileHeader.iPositionOfNextFree)
        {

        return KErrNotFound;
        }

    TPtr8 logElem (const_cast<TUint8*>(logFileBuf.Ptr())+ logElemPos, // Data ptr
                   iLogElemTrailer.iEventLength,   // Data length
                   iLogElemTrailer.iEventLength);

    // Convert the TPtr8 parameter to TUint8* format

    TLogElem* logElemPtr = (TLogElem*) logElem.Ptr(); 

    // Copy the event number and event length parameters
    // from packed format log element to unpacked object

    iUnpackedLogElem.iEventLength                 = logElemPtr->GetEventLength();
    iUnpackedLogElem.iEventNumber                 = logElemPtr->GetEventNumber();

    // Verify the extracted data

    if (iUnpackedLogElem.iEventNumber > iCurrFileHeader.iCurrEventNumber
        ||
        iUnpackedLogElem.iEventLength  != iLogElemTrailer.iEventLength)
        {

        return KErrGeneral;
        }

    *aPositionOfLogElem = logElemPos;

    return KErrNone;

    }