Ejemplo n.º 1
0
/* NON_NULL points to the loaded object */
OBJECT *
ObjectContextLoad(
		  ANY_OBJECT_BUFFER   *object,        // IN: pointer to object structure in saved
		  //     context
		  TPMI_DH_OBJECT      *handle         // OUT: object handle
		  )
{
    OBJECT      *newObject = ObjectAllocateSlot(handle);
    // Try to allocate a slot for new object
    if(newObject != NULL)
	{
	    // Copy the first part of the object
	    MemoryCopy(newObject, object, offsetof(HASH_OBJECT, state));
	    // See if this is a sequence object
	    if(ObjectIsSequence(newObject))
		{
		    // If this is a sequence object, import the data
		    SequenceDataImport((HASH_OBJECT *)newObject,
				       (HASH_OBJECT_BUFFER *)object);
		}
	    else
		{
		    // Copy input object data to internal structure
		    MemoryCopy(newObject, object, sizeof(OBJECT));
		}
	}
    return newObject;
}
Ejemplo n.º 2
0
void BURGER_API Burger::OkAlertMessage(const char *pMessage,const char *pTitle)
{
	Word8 *TitleStr;		/* Pointer to the window title */
	DialogPtr MyDialog;	/* My dialog pointer */
	Handle ItemList;	/* Handle to the item list */
	Rect DialogRect;	/* Rect of the dialog window */
	Word TitleLen;		/* Length of the title */
	Word MessLen;		/* Length of the caption */
	short ItemHit;		/* Junk */
	Rect WorkRect;
	GrafPtr MyPort;	/* My grafport */
	//Word Foo;
	
	//Foo = InputSetState(FALSE);
		
	GetPort(&MyPort);	/* Save the current port */
	
	/* Center my dialog to the screen */
#if ACCESSOR_CALLS_ARE_FUNCTIONS
	GetPortBounds(MyPort,&WorkRect);
#else
	WorkRect = MyPort->portRect;
#endif
	DialogRect.top = static_cast<short>((((WorkRect.bottom-WorkRect.top)-190)/2)+WorkRect.top);
	DialogRect.left = static_cast<short>((((WorkRect.right-WorkRect.left)-350)/2)+WorkRect.left);
	DialogRect.bottom = static_cast<short>(DialogRect.top+190);
	DialogRect.right = static_cast<short>(DialogRect.left+350);

	TitleLen = 0;			/* Assume no length */
	if (pTitle) {
		TitleLen = Burger::StringLength(pTitle);		/* Get the length of the title string */
	}
	TitleStr = (Word8 *)Burger::Alloc(TitleLen+1);	/* Get memory of pascal string */
	if (TitleStr) {			/* Did I get the memory? */
		MemoryCopy(TitleStr+1,pTitle,TitleLen);
		TitleStr[0] = static_cast<Word8>(TitleLen);		/* Set the pascal length */
		
		MessLen = Burger::StringLength(pMessage);	/* Size of the message */
		ItemList = NewHandle(static_cast<Size>(sizeof(Template)+MessLen));
		if (ItemList) {				/* Ok? */
			Template[sizeof(Template)-1]=static_cast<Word8>(MessLen);	/* Save the message length */
			MemoryCopy(ItemList[0],Template,sizeof(Template));	/* Copy the template */
			MemoryCopy((ItemList[0])+sizeof(Template),pMessage,MessLen);	/* Copy the message */
			MyDialog = NewDialog(0,&DialogRect,(Word8 *)TitleStr,TRUE,5,(WindowPtr)-1,FALSE,0,ItemList);
			if (MyDialog) {
				SetDialogDefaultItem(MyDialog,1);	/* Default for OK button */
				ModalDialog(0,&ItemHit);			/* Handle the event */
				DisposeDialog(MyDialog);			/* Kill the dialog */
			} else {
				DisposeHandle(ItemList);			/* I must kill this myself! */
			}
		}
		Burger::Free(TitleStr);				/* Kill the title */
	}
	SetPort(MyPort);			/* Restore my grafport */
	//InputSetState(Foo);
}
Ejemplo n.º 3
0
void Pxf::ReplaceString(char *str, const char *find, const char *replace)
{
	int len_find = StringLength(find);
	int len_replace = StringLength(replace);

	const char *p, *s;
	char *t;

	if (len_find - len_replace < 0) return;

	p = StringFind(str, find);
	if (!p) return;
	
	s = t = (char*)p;
	while(*s)
	{
		MemoryCopy(t, replace, len_replace);
		p += len_find;
		t += len_replace;
		s = StringFind(p, find);
		if(!s) s = p + StringLength(p);
		MemoryMove(t, p, (unsigned)(s-p));
		t += s-p;
		p = s;
	}
	*t = 0;
}
Ejemplo n.º 4
0
Archivo: mad.c Proyecto: 01org/opa-ff
static FSTATUS recv_mad(MADT_HANDLE umadtHandle, MAD* mad, int timeout)
{
	FSTATUS status;
	MadtStruct *Mad;
	MadWorkCompletion *Wc;

	status = iba_umadt_wait_any_compl(umadtHandle, RECV_COMPLETION, timeout);
	if (status == FTIMEOUT) {
		DBGPRINT("Timeout waiting for MAD Recv. timeout= %d ms\n", timeout);
		return status;
	}
	// cleanup any send completions while here
	do {
		status = iba_umadt_poll_send_compl(umadtHandle, &Mad, &Wc);
		if (status == FSUCCESS) {
			(void)iba_umadt_release_sendmad(umadtHandle, Mad);
		}
	} while (status == FSUCCESS);
	// get next recv from the Q
	status = iba_umadt_poll_recv_compl(umadtHandle, &Mad, &Wc);
	if (status != FSUCCESS) {
		DBGPRINT("Poll Recv failed: %s\n", iba_fstatus_msg(status));
		return status;
	}
	MemoryCopy(mad, &Mad->IBMad, sizeof(*mad));	// caller must byte swap
	// for now ignore Work completion, only handling responses
	DBGPRINT("Received a MAD\n");
	status = iba_umadt_release_recvmad(umadtHandle, Mad);
	if (status != FSUCCESS) {
		fprintf(stderr, "%s: ReleaseRecvMad: (status=0x%x): %s\n",
						g_Top_cmdname, status, FSTATUS_MSG(status));
	}
	return status;
}
Ejemplo n.º 5
0
Burger::String16::String16(const Burger::String16 &rInput,WordPtr uStart,WordPtr uEnd)
{
	WordPtr uInputLength = rInput.m_uLength;	// Get the source length
	if (uEnd>uInputLength) {					// Clamp the end of the string
		uEnd = uInputLength;					// Make sure it fits
	}
	const Word16 *pInput = rInput.m_pData;
	if (uStart>=uEnd) {							// Valid range?
		uInputLength = 0;						// The result will be empty
	} else {
		uInputLength = uEnd-uStart;				// Length of the new string
		pInput += uStart;
	}
	Word16 *pWork = m_Raw;
	if (uInputLength>=BUFFERSIZE) {				// Buffer big enough?
		pWork = static_cast<Word16 *>(Alloc((uInputLength+1)*sizeof(Word16)));
		if (!pWork) {				// Oh oh...
			pWork = m_Raw;
			uInputLength = 0;		// Don't copy anything
		}
	}
	// Since I can't assume the string being created ends with a zero, I'll
	// manually place one in the new string
	pWork[uInputLength] = 0;
	m_uLength = uInputLength;			// Save the new length
	m_pData = pWork;					// Set the pointer
	MemoryCopy(pWork,pInput,uInputLength*sizeof(Word16));	// Copy the string
}
Ejemplo n.º 6
0
Burger::Decompress::eError Burger::DecompressUnsigned8BitAudio::Process(void *pOutput,WordPtr uOutputChunkLength,const void *pInput,WordPtr uInputChunkLength)
{
	// Which is smaller? Input or output?
	WordPtr uCount = Min(uInputChunkLength,uOutputChunkLength);

	// Copy the data
	MemoryCopy(pOutput,pInput,uCount);

	// Store the amount of data that was processed

	m_uInputLength = uCount;
	m_uOutputLength = uCount;

	// Add the decompressed data to the totals
	m_uTotalInput += uCount;
	m_uTotalOutput += uCount;

	// Output buffer not big enough?
	if (uOutputChunkLength!=uCount) {
		return DECOMPRESS_OUTPUTUNDERRUN;
	}

	// Input data remaining?
	if (uInputChunkLength!=uCount) {
		return DECOMPRESS_OUTPUTOVERRUN;
	}
	// Decompression is complete
	return DECOMPRESS_OKAY;
}
Ejemplo n.º 7
0
DataBuffer::DataBuffer(const void * data, YETI_Size size, bool copy)
: m_buffer_is_local_(copy)
, m_buffer_(copy ? (size ? new YETI_Byte[size] : NULL) : reinterpret_cast<YETI_Byte *>(const_cast<void *>(data)))
, m_buffer_size_(size)
, m_data_size_(size)
{
    if (copy && size) MemoryCopy(m_buffer_, data, size);
}
Ejemplo n.º 8
0
DataBuffer::DataBuffer(const DataBuffer & other)
: m_buffer_is_local_(true)
, m_buffer_(NULL)
, m_buffer_size_(other.m_data_size_)
{
    if (m_buffer_size_) {
        m_buffer_ = new YETI_Byte[m_buffer_size_];
        MemoryCopy(m_buffer_, other.m_buffer_, m_buffer_size_);
    }
}
Ejemplo n.º 9
0
void AirMemory::AddBackupMemory(DWORD Address, void *Memory, DWORD Size) {
	BackupMemory *p = (BackupMemory *)malloc(sizeof(BackupMemory));

	p->Address = Address;
	p->Size = Size;
	p->Memory = malloc(Size);
	MemoryCopy((DWORD)p->Memory, (void *)p->Address, p->Size);//Backup Memory
	if (Memory) {
		MemoryCopy(p->Address, Memory, p->Size);//Write Memory
	}

	if (!MemoryList.Next) {
		p->Next = NULL;
		MemoryList.Next = p;
	}
	else {
		p->Next = MemoryList.Next;
		MemoryList.Next = p;
	}
}
Ejemplo n.º 10
0
/* This function is used to update a value in the PERSISTENT_DATA structure and commits the value to
   NV. */
void
NvUpdatePersistent(
		   UINT32           offset,        // IN: location in PERMANENT_DATA to be updated
		   UINT32           size,          // IN: size of the value
		   void            *buffer         // IN: the new data
		   )
{
    pAssert(offset + size <= sizeof(gp));
    MemoryCopy(&gp + offset, buffer, size);
    NvWrite(offset, size, buffer);
}
Ejemplo n.º 11
0
static void AddCh(CJcScanner* scanner){
	char *newBuf;
	if (scanner->tlen >= scanner->tvalLength){
		scanner->tvalLength *= 2;
		newBuf = (char*)g_oInterface.Malloc(scanner->tvalLength);
		MemoryCopy(newBuf, scanner->tval, scanner->tlen*sizeof(char));
		g_oInterface.Free(scanner->tval);
		scanner->tval = newBuf;
	}
	scanner->tval[scanner->tlen++] = scanner->ch;
	NextCh(scanner);
}
Ejemplo n.º 12
0
int GetMACAddress(unsigned char Buffer[6])
{
	PropertyTagMACAddress MACAddress;
	if (!PropertyTagsGetTag(PROPTAG_GET_MAC_ADDRESS, &MACAddress, sizeof(MACAddress), 0))
	{
		return 0;
	}

	MemoryCopy(MACAddress.Address, Buffer, 6);

	return 1;
}
Ejemplo n.º 13
0
char *Pxf::StringPadRight(char *dest, const char *src, int width, char pad_char)
{
	int len = StringLength(src);
	int dst_off = width-len;
	int src_off = len-width;
	src_off = (src_off < 0) ? 0 : src_off;
	dst_off = (dst_off < 0) ? 0 : dst_off;
	MemorySet(dest, pad_char, width);
	MemoryCopy(dest + dst_off, src + src_off, Min(len, width));
	/*dest[width] = 0x0; */
	return dest;
}
Ejemplo n.º 14
0
char *Pxf::DuplicateReplaceString(const char *str, const char *find, const char *replace)
{
	int len_find = StringLength(find);
	int len_replace = StringLength(replace);
	int count = 0, newlen = 0;

	/*char *src = (char*)str; */

	char *ret, *q;
	const char *p = str;
	p = StringFind(str, find);
	if (!p)
		return strdup(str);

	/* count occurrences of find */
	do { count++; } while ((p = StringFind(p+len_find, find)));

	newlen = (StringLength(str) + count * (len_replace - len_find) + 1) * sizeof(char);
	ret = (char*)MemoryAllocate( newlen );
	if (!ret) return 0;

	p = (char*)str;
	q = ret;
	while(1)
	{
		const char *tmp = StringFind(p, find);
		if (!tmp)
		{
			StringCopy(q, p, StringLength(str)-(unsigned)(p-str)+1);
			ret[newlen-1] = 0;
			return ret;
		}
		MemoryCopy(q, p, (unsigned)(tmp-p));
		q += tmp-p;
		MemoryCopy(q, replace, len_replace);
		q += len_replace;
		p = tmp+len_find;
	}
	return 0;
}
Ejemplo n.º 15
0
internal_function dod_tag*
DODGetDODTag(char* line) {
	char* tag = (char*)calloc(DOD_TAG_SIZE, sizeof(char));
	char* value = (char*)calloc(DOD_VALUE_SIZE, sizeof(char));

	char* tagAddress = tag;
	char* valueAddress = value;

	bool foundEqual = false;

	while(*line != '#') {
		if(!foundEqual && *line == '=') {
			foundEqual = true;
			line++;
			continue;
		}

		if(foundEqual) {
			*value = *line;
			value++;
		}
		else {
			*tag = *line;
			tag++;
		}

		line++;
	}

	dod_tag* result = DODAllocateDODTag();

	MemoryCopy(result->tag, tagAddress, DOD_TAG_SIZE);
	MemoryCopy(result->value, valueAddress, DOD_VALUE_SIZE);

	free(tagAddress);
	free(valueAddress);

	return(result);
}
Ejemplo n.º 16
0
YETI_Result DataBuffer::set_data(const YETI_Byte * data, YETI_Size data_size)
{
    if (data_size > m_buffer_size_) {
        if (m_buffer_is_local_) {
            YETI_CHECK(_reallocate_buffer(data_size));
        } else {
            return YETI_ERROR_NOT_SUPPORTED;
        }
    }

    if (data) MemoryCopy(m_buffer_, data, data_size);
    m_data_size_ = data_size;

    return YETI_SUCCESS;
}
Ejemplo n.º 17
0
YETI_Result DataBuffer::_reallocate_buffer(YETI_Size size)
{
    if (m_data_size_ > size) return YETI_ERROR_INVALID_PARAMETERS;

    YETI_Byte * new_buffer = new YETI_Byte[size];

    if (m_buffer_ && m_data_size_) {
        MemoryCopy(new_buffer, m_buffer_, m_data_size_);
    }

    delete[] m_buffer_;
    m_buffer_ = new_buffer;
    m_buffer_size_ = size;

    return YETI_SUCCESS;
}
Ejemplo n.º 18
0
bool AirMemory::DeleteBackupMemory(DWORD Address) {
	BackupMemory *p, *d, *pp;
	pp = &MemoryList;
	for (p = MemoryList.Next; p; p = p->Next) {
		if (p->Address == Address) {
			d = p;
			MemoryCopy(d->Address, d->Memory, d->Size);//Restore Memory
			pp->Next = p->Next;
			free(d->Memory);
			free(d);
			return true;
		}
		pp = p;
	}
	return false;
}
Ejemplo n.º 19
0
DataBuffer & DataBuffer::operator =(const DataBuffer & copy)
{
    if (this != &copy) {
        clear();

        m_buffer_is_local_ = true;
        m_buffer_size_ = copy.m_buffer_size_;
        m_data_size_ = copy.m_data_size_;

        if (m_buffer_size_) {
            m_buffer_ = new YETI_Byte[m_buffer_size_];
            MemoryCopy(m_buffer_, copy.m_buffer_, m_buffer_size_);
        }
    }

    return *this;
}
Ejemplo n.º 20
0
Burger::String16::String16(const Burger::String16 &rInput)
{
	WordPtr uInputLength = rInput.m_uLength;	// Get the source length
	Word16 *pWork = m_Raw;
	const Word16 *pInput = rInput.m_pData;
	if (uInputLength>=BUFFERSIZE) {				// Buffer big enough?
		pWork = static_cast<Word16 *>(Alloc((uInputLength+1)*sizeof(Word16)));
		if (!pWork) {				// Oh oh...
			pWork = m_Raw;
			pInput = g_EmptyString16;
			uInputLength = 0;
		}
	}
	m_uLength = uInputLength;			// Save the new length
	m_pData = pWork;					// Set the pointer
	MemoryCopy(pWork,pInput,(uInputLength+1)*sizeof(Word16));	// Copy the string and the ending NULL
}
Ejemplo n.º 21
0
char*
ToString(char* text, ...) {
	va_list ap;
	char* buffer = (char*)calloc(256, sizeof(char));

	va_start(ap, text);
	vsprintf_s(buffer, 256, text, ap);
	va_end(ap);

	int resultSize = CharPointerLength(buffer);
	char* result = (char*)calloc(resultSize, sizeof(char));

	MemoryCopy(result, buffer, resultSize);

	free(buffer);

	return(result);
}
Ejemplo n.º 22
0
Burger::String16::String16(const Word16 *pInput)
{
	if (!pInput) {
		pInput = g_EmptyString16;
	}
	WordPtr uInputLength = StringLength(pInput);
	Word16 *pWork = m_Raw;
	if (uInputLength>=BUFFERSIZE) {				// Buffer big enough?
		pWork = static_cast<Word16 *>(Alloc((uInputLength+1)*sizeof(Word16)));
		if (!pWork) {				// Oh oh...
			pWork = m_Raw;
			pInput = g_EmptyString16;
			uInputLength = 0;		// Don't copy anything
		}
	}
	m_uLength = uInputLength;			// Save the new length
	m_pData = pWork;					// Set the pointer
	MemoryCopy(pWork,pInput,(uInputLength+1)*sizeof(Word16));	// Copy the string
}
Ejemplo n.º 23
0
internal_function char*
DODSearchThroughNextTags(dod_tag* dodTag, char* tag, char* value, char* subTag = 0, char* subValue = 0) {
	if(subTag && subValue) {
		dod_tag* nextDODTag = dodTag;

		while(nextDODTag) {
			if(CompareCharPointers(nextDODTag->tag, tag)) {
				if(CompareCharPointers(nextDODTag->value, value)) {
					char* result = DODSearchThroughNextTags(nextDODTag->subTag, subTag, subValue);

					if(result) {
						return(result);
					}
				}
			}

			nextDODTag = nextDODTag->nextTag;
		}
	}

	while(dodTag) {
		if(CompareCharPointers(dodTag->tag, tag)) {
			if(CompareCharPointers(dodTag->value, value)) {
				if(dodTag->content) {
					//NOTE: Getting the contentSize by subtracting 2, we lose the \n and final \0
					int randomIndex = RandomNumberInRange(0, dodTag->amountOfContent - 1);
					int contentSize = CharPointerLength(dodTag->content[randomIndex]) - 2;

					//NOTE: Copying the content with 1 less of size removes the #.
					char* result = (char*)calloc(contentSize, sizeof(char));
					MemoryCopy(result, dodTag->content[randomIndex], contentSize - 1);

					return(result);
				}
			}
		}

		dodTag = dodTag->nextTag;
	}

	return("");
}
Ejemplo n.º 24
0
Archivo: mad.c Proyecto: 01org/opa-ff
static FSTATUS send_mad(MADT_HANDLE umadtHandle, IB_PATH_RECORD *pathp,
				uint32 qpn, uint32 qkey, MAD* mad)
{
	FSTATUS status;
	MadtStruct *Mad;
	MadAddrStruct Addr;
	uint32 count = 1;
	MadWorkCompletion *Wc;

	DBGPRINT("getting buffer to send Mad\n");
	status = iba_umadt_get_sendmad(umadtHandle, &count, &Mad);
	if (status != FSUCCESS) {
		return status;
	}

	DBGPRINT("sending Mad\n");
	Mad->Context = 0;	// TBD - for async in future
	MemoryClear(&Mad->Grh, sizeof(Mad->Grh));	/* only in recv */
	MemoryCopy(&Mad->IBMad, mad, sizeof(*mad));
	GetGsiAddrFromPath(pathp, qpn, qkey, &Addr);

	status = iba_umadt_post_send(umadtHandle, Mad, &Addr);
	if (status != FSUCCESS) {
		fprintf(stderr, "%s: Failed to send mad: (status=0x%x): %s\n",
						g_Top_cmdname, status, FSTATUS_MSG(status));
		(void)iba_umadt_release_sendmad(umadtHandle, Mad);
		return status;
	}
	status = iba_umadt_wait_any_compl(umadtHandle, SEND_COMPLETION, SEND_WAIT_TIME);
	if (status == FSUCCESS) {
		status = iba_umadt_poll_send_compl(umadtHandle, &Mad, &Wc);
		if (status == FSUCCESS) {
			DBGPRINT("MAD Sent\n");
			(void)iba_umadt_release_sendmad(umadtHandle, Mad);
		}
	}
	return status;
}
Ejemplo n.º 25
0
void BURGER_API Burger::String16::SetBufferSize(WordPtr uSize)
{
	if (uSize!=m_uLength) {
		// If no space is requested, clear the buffer
		if (!uSize) {
			Clear();
		} else {
			// Hold the old buffer
			Word16 *pWork = m_pData;
			// Get the new buffer
			Word16 *pDest = m_Raw;
			// Allocate a new buffer if needed
			if (uSize>=BUFFERSIZE) {	// Buffer big enough?
				pDest = static_cast<Word16 *>(Alloc((uSize+1)*2));
				if (!pDest) {			// Oh oh...
					pDest = m_Raw;
					uSize = 0;			// Don't copy anything
				}
			}
			// Get the size of the string
			WordPtr uDestSize = m_uLength;
			if (uDestSize>=uSize) {
				// Truncate the string
				uDestSize = uSize;
			}
			MemoryCopy(pDest,pWork,uDestSize*2);
			pDest[uDestSize] = 0;		// Ensure the buffer is zero terminated
			if (pWork!=m_Raw) {			// Discard previous memory
				Free(pWork);
			}
			m_pData = pDest;			// Set the pointer
			m_uLength = uSize;			// Save the new length
			pDest[uSize] = 0;			// Ensure the terminating zero is present
		}
	}
}
Ejemplo n.º 26
0
Burger::Decompress::eError Burger::Decompress32BitBEAudio::Process(void *pOutput,WordPtr uOutputChunkLength,const void *pInput,WordPtr uInputChunkLength)
{
#if defined(BURGER_BIGENDIAN)

	// Which is smaller? Input or output?
	WordPtr uCount = Min(uInputChunkLength,uOutputChunkLength);

	//
	// If there is no conversion, just upload the data as is.
	//

	MemoryCopy(pOutput,pInput,uCount);
	WordPtr uInputConsumed = uCount;
	WordPtr uOutputConsumed = uCount;
#else

	//
	// Handle data "decompression"
	//

	// Save the pointers to determine consumption
	void *pOldOutput = pOutput;
	const void *pOldInput = pInput;

	//
	// Process based on state
	//

	eState uState = m_eState;
	Word bAbort = FALSE;
	do {
		switch (uState) {

		//
		// Cache has not been used, just copy
		//

		case STATE_INIT:
			{
				// Copy the data while converting the endian
				WordPtr uCount = Min(uInputChunkLength,uOutputChunkLength);
				WordPtr uLength = uCount&(~(3));
				if (uLength) {

					uInputChunkLength -= uLength;
					uOutputChunkLength -= uLength;
					// Is it aligned?
					if (!((reinterpret_cast<WordPtr>(pInput)|reinterpret_cast<WordPtr>(pOutput))&3)) {
						ConvertEndian(static_cast<Word32 *>(pOutput),static_cast<const Word32 *>(pInput),uLength>>2U);
						pInput = static_cast<const Word32 *>(pInput)+uLength;
						pOutput = static_cast<Word32 *>(pOutput)+uLength;
					} else {

						// You monster.
						uLength = uLength>>2U;
						do {
							// Convert to endian with unaligned data
							static_cast<Word8 *>(pOutput)[0] = static_cast<const Word8 *>(pInput)[3];
							static_cast<Word8 *>(pOutput)[1] = static_cast<const Word8 *>(pInput)[2];
							static_cast<Word8 *>(pOutput)[2] = static_cast<const Word8 *>(pInput)[1];
							static_cast<Word8 *>(pOutput)[3] = static_cast<const Word8 *>(pInput)[0];
							pInput = static_cast<const Word32 *>(pInput)+1;
							pOutput = static_cast<Word32 *>(pOutput)+1;
						} while (--uLength);
					}
				}

				//
				// All done with the input?
				//

				if (!uInputChunkLength) {
					bAbort = TRUE;
				} else {
					m_uCacheCount = 0;
					uState = STATE_FILLINGCACHE;
				}
			}
			break;

		//
		// Fill up the cache
		//
		case STATE_FILLINGCACHE:
			bAbort = TRUE;			// Assume data starved
			if (uInputChunkLength) {

				// Get the number of bytes already obtained
				WordPtr uCacheSize = m_uCacheCount;

				// How many is needed to fill
				WordPtr uRemaining = sizeof(m_Cache)-uCacheSize;

				// Number of bytes to process
				WordPtr uChunk = Min(uRemaining,uInputChunkLength);

				// Fill in the cache
				MemoryCopy(&m_Cache[uCacheSize],pInput,uChunk);

				// Consume the input bytes

				pInput = static_cast<const Word8 *>(pInput)+uChunk;
				uInputChunkLength-=uChunk;

				// Did the cache fill up?
				uCacheSize += uChunk;
				m_uCacheCount = static_cast<Word>(uCacheSize);
				if (uCacheSize==sizeof(m_Cache)) {
					// Perform the endian swap on the cache
					SwapEndian::Fixup(static_cast<Word32 *>(static_cast<void *>(m_Cache)));
					// Cache is full, send to processing
					bAbort = FALSE;
					uState = STATE_CACHEFULL;
				}
			}
			break;
			
		//
		// Cache is full, output the data
		//

		case STATE_CACHEFULL:
			bAbort = TRUE;			// Assume output buffer is full
			if (uOutputChunkLength) {

				// Output data from the cache

				WordPtr uCacheCount = m_uCacheCount;
				WordPtr uSteps = Min(uOutputChunkLength,static_cast<WordPtr>(uCacheCount));

				// Mark the byte(s) as consumed
				uOutputChunkLength -= uSteps;

				// Start copying where it left off
				const Word8 *pInputChunk = &m_Cache[sizeof(m_Cache)-uCacheCount];

				// Update the cache size
				uCacheCount = static_cast<Word>(uCacheCount-uSteps);

				//
				// Copy out the cache data
				//
				do {
					static_cast<Word8 *>(pOutput)[0] = pInputChunk[0];
					++pInputChunk;
					pOutput = static_cast<Word8 *>(pOutput)+1;
				} while (--uSteps);

				// Data still in the cache?
				if (uCacheCount) {
					// Update and exit
					m_uCacheCount = static_cast<Word>(uCacheCount);
				} else {
					// Cache is empty, so switch to the next state
					uState = STATE_INIT;
					bAbort = FALSE;
				}
			}
			break;

		}
Ejemplo n.º 27
0
Burger::Decompress::eError Burger::Decompress16BitLEAudio::Process(void *pOutput,WordPtr uOutputChunkLength,const void *pInput,WordPtr uInputChunkLength)
{
#if !defined(BURGER_BIGENDIAN)

	// Which is smaller? Input or output?
	WordPtr uCount = Min(uInputChunkLength,uOutputChunkLength);

	//
	// If there is no conversion, just upload the data as is.
	//

	MemoryCopy(pOutput,pInput,uCount);
	WordPtr uInputConsumed = uCount;
	WordPtr uOutputConsumed = uCount;
#else

	//
	// Handle data "decompression"
	//

	// Save the pointers to determine consumption
	void *pOldOutput = pOutput;
	const void *pOldInput = pInput;

	//
	// Process based on state
	//

	eState uState = m_eState;
	Word bAbort = FALSE;
	do {
		switch (uState) {

		//
		// Cache has not been used, just copy
		//

		case STATE_INIT:
			{
				// Copy the data while converting the endian
				WordPtr uCount = Min(uInputChunkLength,uOutputChunkLength);
				uInputChunkLength -= uCount;
				uOutputChunkLength -= uCount&(~static_cast<WordPtr>(1));

				WordPtr uLength = uCount>>1;
				if (uLength) {
					// Is it aligned?
					if (!((reinterpret_cast<WordPtr>(pInput)|reinterpret_cast<WordPtr>(pOutput))&1)) {
						// Convert to native endian quickly
						ConvertEndian(static_cast<Word16 *>(pOutput),static_cast<const Word16 *>(pInput),uLength);
						pInput = static_cast<const Word16 *>(pInput)+uLength;
						pOutput = static_cast<Word16 *>(pOutput)+uLength;

					} else {

						// You monster.

						do {
							// Convert to endian with unaligned data
							static_cast<Word8 *>(pOutput)[0] = static_cast<const Word8 *>(pInput)[1];
							static_cast<Word8 *>(pOutput)[1] = static_cast<const Word8 *>(pInput)[0];
							pInput = static_cast<const Word16 *>(pInput)+1;
							pOutput = static_cast<Word16 *>(pOutput)+1;
						} while (--uLength);

					}
				}

				//
				// One extra byte?
				//
				if (uCount&1) {
					// Put it in the cache and go into cache mode
					m_Cache[1] = static_cast<const Word8 *>(pInput)[0];
					pInput = static_cast<const Word8 *>(pInput)+1;
					uState = STATE_FILLINGCACHE;
				}
			}
			bAbort = TRUE;
			break;

		//
		// Cache is full, output the data
		//

		case STATE_CACHEFULL:
			if (uOutputChunkLength) {

				// Output 1 or 2 bytes

				WordPtr uCacheSize = m_uCacheSize;
				WordPtr uSteps = Min(uOutputChunkLength,static_cast<WordPtr>(uCacheSize));

				// Mark the byte(s) as consumed
				uOutputChunkLength -= uSteps;

				// Start copying where it left off
				const Word8 *pSrc = &m_Cache[sizeof(m_Cache)-uCacheSize];

				// Update the cache size
				uCacheSize = static_cast<Word>(uCacheSize-uSteps);
				if (uCacheSize) {
					// Number of bytes remaining in cache
					m_uCacheSize = static_cast<Word>(uCacheSize);
				} else {
					// Cache will be empty, so switch to normal mode
					uState = STATE_INIT;
				}

				//
				// Copy out the cache data
				//
				do {
					static_cast<Word8 *>(pOutput)[0] = pSrc[0];
					++pSrc;
					pOutput = static_cast<Word8 *>(pOutput)+1;
				} while (--uSteps);
			} else {
				bAbort = TRUE;
			}
			break;

		//
		// Fill up the cache
		//
		case STATE_FILLINGCACHE:
			if (uInputChunkLength) {
				// Fill in the missing byte (Endian swapped)
				m_Cache[0] = static_cast<const Word8 *>(pInput)[0];

				// Consume the input byte

				pInput = static_cast<const Word8 *>(pInput)+1;
				--uInputChunkLength;

				// Change the state to empty the cache
				uState = STATE_CACHEFULL;
				m_uCacheSize = 2;
			} else {
				bAbort = TRUE;
			}
			break;
		}
	} while (!bAbort);

	// Save the state
	m_eState = uState;

	// Return the number of bytes actually consumed
	WordPtr uInputConsumed = static_cast<WordPtr>(static_cast<const Word8 *>(pInput)-static_cast<const Word8 *>(pOldInput));
	WordPtr uOutputConsumed = static_cast<WordPtr>(static_cast<const Word8 *>(pOutput)-static_cast<const Word8 *>(pOldOutput));
#endif

	// Store the amount of data that was processed

	m_uInputLength = uInputConsumed;
	m_uOutputLength = uOutputConsumed;

	// Add the decompressed data to the totals
	m_uTotalInput += uInputConsumed;
	m_uTotalOutput += uOutputConsumed;

	// Output buffer not big enough?
	if (uOutputChunkLength!=uOutputConsumed) {
		return DECOMPRESS_OUTPUTUNDERRUN;
	}

	// Input data remaining?
	if (uInputChunkLength!=uInputConsumed) {
		return DECOMPRESS_OUTPUTOVERRUN;
	}
	// Decompression is complete
	return DECOMPRESS_OKAY;
}
Ejemplo n.º 28
0
Result HcdSumbitControlMessage(struct UsbDevice *device, 
	struct UsbPipeAddress pipe, void* buffer, u32 bufferLength,
	struct UsbDeviceRequest *request) {
	Result result;
	struct UsbPipeAddress tempPipe;
	if (pipe.Device == RootHubDeviceNumber) {
		return HcdProcessRootHubMessage(device, pipe, buffer, bufferLength, request);
	}

	device->Error = Processing;
	device->LastTransfer = 0;
			
	// Setup
	tempPipe.Speed = pipe.Speed;
	tempPipe.Device = pipe.Device;
	tempPipe.EndPoint = pipe.EndPoint;
	tempPipe.MaxSize = pipe.MaxSize;
	tempPipe.Type = Control;
	tempPipe.Direction = Out;
	
	if ((result = HcdChannelSendWait(device, &tempPipe, 0, request, 8, request, Setup)) != OK) {		
		LOGF("HCD: Could not send SETUP to %s.\n", UsbGetDescription(device));
		return OK;
	}

	// Data
	if (buffer != NULL) {
		if (pipe.Direction == Out) {
			MemoryCopy(databuffer, buffer, bufferLength);
		}
		tempPipe.Speed = pipe.Speed;
		tempPipe.Device = pipe.Device;
		tempPipe.EndPoint = pipe.EndPoint;
		tempPipe.MaxSize = pipe.MaxSize;
		tempPipe.Type = Control;
		tempPipe.Direction = pipe.Direction;
		
		if ((result = HcdChannelSendWait(device, &tempPipe, 0, databuffer, bufferLength, request, Data1)) != OK) {		
			LOGF("HCD: Could not send DATA to %s.\n", UsbGetDescription(device));
			return OK;
		}
						
		ReadBackReg(&Host->Channel[0].TransferSize);
		if (pipe.Direction == In) {
			if (Host->Channel[0].TransferSize.TransferSize <= bufferLength)
				device->LastTransfer = bufferLength - Host->Channel[0].TransferSize.TransferSize;
			else{
				LOG_DEBUGF("HCD: Weird transfer.. %d/%d bytes received.\n", Host->Channel[0].TransferSize.TransferSize, bufferLength);
				LOG_DEBUGF("HCD: Message %02x%02x%02x%02x %02x%02x%02x%02x %02x%02x%02x%02x %02x%02x%02x%02x ...\n", 
					((u8*)databuffer)[0x0],((u8*)databuffer)[0x1],((u8*)databuffer)[0x2],((u8*)databuffer)[0x3],
					((u8*)databuffer)[0x4],((u8*)databuffer)[0x5],((u8*)databuffer)[0x6],((u8*)databuffer)[0x7],
					((u8*)databuffer)[0x8],((u8*)databuffer)[0x9],((u8*)databuffer)[0xa],((u8*)databuffer)[0xb],
					((u8*)databuffer)[0xc],((u8*)databuffer)[0xd],((u8*)databuffer)[0xe],((u8*)databuffer)[0xf]);
				device->LastTransfer = bufferLength;
			}
			MemoryCopy(buffer, databuffer, device->LastTransfer);
		}
		else {
			device->LastTransfer = bufferLength;
		}
	}

	// Status
	tempPipe.Speed = pipe.Speed;
	tempPipe.Device = pipe.Device;
	tempPipe.EndPoint = pipe.EndPoint;
	tempPipe.MaxSize = pipe.MaxSize;
	tempPipe.Type = Control;
	tempPipe.Direction = ((bufferLength == 0) || pipe.Direction == Out) ? In : Out;
	
	if ((result = HcdChannelSendWait(device, &tempPipe, 0, databuffer, 0, request, Data1)) != OK) {		
		LOGF("HCD: Could not send STATUS to %s.\n", UsbGetDescription(device));
		return OK;
	}

	ReadBackReg(&Host->Channel[0].TransferSize);
	if (Host->Channel[0].TransferSize.TransferSize != 0)
		LOG_DEBUGF("HCD: Warning non zero status transfer! %d.\n", Host->Channel[0].TransferSize.TransferSize);

	device->Error = NoError;

	return OK;
}
Ejemplo n.º 29
0
uint32									
iba_gsi_coalesce_dgrm2(
	IN IBT_DGRM_ELEMENT			*DgrmElement,
	IN uint8					**ppBuffer,
	IN uint32					ClassHeaderSize,
	IN uint32					MemAllocFlags
	)
{
	uint32						messageSize = 0;
	uint32						byteCount, totalBytesToCopy;
	IBT_ELEMENT					*pElement;
	IBT_BUFFER					*pBufferHdr;
	uint8						*pBuffer;
	MAD_RMPP					*pMadRmpp;
#ifdef TEST_DUMP
	static int counter;
#endif

	_DBG_ENTER_LVL(_DBG_LVL_POOL, iba_gsi_coalesce_dgrm);

	pElement	= &DgrmElement->Element;
	pBufferHdr	= pElement->pBufferList;
	pMadRmpp	= (MAD_RMPP*)pBufferHdr->pNextBuffer->pData;// 2nd buffer is MAD
	
	// Calculate total bytes to copy. 
	// Each buffer has a GRH+Mad Common Header+RMPP Header+ClassHeader+RMPP Data
	//
	// We copy only one copy of the headers and coalesce the data
	messageSize = totalBytesToCopy = iba_gsi_dgrm_len(DgrmElement, ClassHeaderSize);
	if (! messageSize)
		goto fail;
	_DBG_PRINT(_DBG_LVL_POOL,("Total bytes to copy: %d\n", totalBytesToCopy));

	if (*ppBuffer == NULL)
	{
		*ppBuffer = (uint8*)MemoryAllocate2(totalBytesToCopy, MemAllocFlags, GSA_MEM_TAG);
		if (*ppBuffer == NULL)
			goto fail;
	}
	pBuffer		= *ppBuffer;

	// Copy GRH
	if (pBufferHdr->ByteCount != sizeof(IB_GRH)) {
		_DBG_ERROR(("Bad buffer header size: %u expected %u\n", pBufferHdr->ByteCount, (unsigned)sizeof(IB_GRH)));
		messageSize = 0;	// indicate invalid packets
		goto fail;
	}
	byteCount = pBufferHdr->ByteCount;
	MemoryCopy( pBuffer, pBufferHdr->pData, byteCount ); 
	pBuffer += byteCount;
	totalBytesToCopy -= byteCount; // keep count
	pBufferHdr = pBufferHdr->pNextBuffer;
	
	// Copy Mad Common + RMPP Header + class header + first data area
	byteCount = (totalBytesToCopy > pBufferHdr->ByteCount) ? \
					pBufferHdr->ByteCount:totalBytesToCopy;
	MemoryCopy( pBuffer, pBufferHdr->pData, byteCount );
	pBuffer += byteCount;
	totalBytesToCopy -= byteCount; // keep count
	
	// Walk all elements of RMPP list
	while ( totalBytesToCopy )
	{
		pElement = pElement->pNextElement;

		if ( NULL == pElement )
		{
			_DBG_ERROR(("LIST ERROR DgrmElement %p ClassHeaderSize %d messageSize %d BytesLeft %d\n", 
					_DBG_PTR(DgrmElement), ClassHeaderSize, messageSize, totalBytesToCopy));
			DumpDgrmElement(DgrmElement);
			messageSize = 0;	// indicate invalid packets/buffers
			goto fail;
		}
		else
		{
#ifdef TEST_DUMP
			if ((++counter%50) == 0)
			{
				_DBG_ERROR(("LIST ERROR DgrmElement %p ClassHeaderSize %d messageSize %d BytesLeft %d\n", 
					_DBG_PTR(DgrmElement), ClassHeaderSize, messageSize, totalBytesToCopy));
				DumpDgrmElement(DgrmElement);
				messageSize = 0;	// indicate invalid packets/buffers
				goto fail;
			}
#endif
		}

		// skip GRH
		pBufferHdr = pElement->pBufferList->pNextBuffer;
		
		pMadRmpp = (MAD_RMPP *)pBufferHdr->pData;

		// copy as much class data as is left in packet
		// subtract common headers, if packet too small, don't copy anything
		byteCount = (sizeof(MAD_COMMON) + sizeof(RMPP_HEADER) + ClassHeaderSize);
		byteCount = (byteCount > pBufferHdr->ByteCount)? \
								0:(pBufferHdr->ByteCount - byteCount);

		byteCount = (totalBytesToCopy > byteCount)?byteCount:totalBytesToCopy;
		if (byteCount)
		{
			MemoryCopy( pBuffer, &pMadRmpp->Data[ClassHeaderSize], byteCount); 
			pBuffer += byteCount;
			totalBytesToCopy -= byteCount; // keep count
		}
	}
	_DBG_LEAVE_LVL(_DBG_LVL_POOL);
	return messageSize;

fail:
	if (*ppBuffer)
	{
		MemoryDeallocate(*ppBuffer);
		*ppBuffer = NULL;
	}
	_DBG_LEAVE_LVL(_DBG_LVL_POOL);
	return messageSize;
}
Ejemplo n.º 30
0
static uint32_t
TpmUtilWriteBootPolicy(
    TPM2B_MAX_NV_BUFFER* policy,
    TPM2B_PUBLIC* platformAuthority,
    TPMT_SIGNATURE* authorizationSignature
    )
{
    DEFINE_CALL_BUFFERS;
    UINT32 result = TPM_RC_SUCCESS;
    union
    {
        LoadExternal_In loadExternal;
        NV_ReadPublic_In nv_ReadPublic;
        NV_UndefineSpace_In nv_UndefineSpace;
        PolicyAuthorize_In policyAuthorize;
        PolicyCpHash_In policyCpHash;
        NV_DefineSpace_In nv_DefineSpace;
        StartAuthSession_In startAuthSession;
        VerifySignature_In verifySignature;
        NV_Write_In nv_Write;
        PolicyGetDigest_In policyGetDigest;
    } in;
    union
    {
        LoadExternal_Out loadExternal;
        NV_ReadPublic_Out nv_ReadPublic;
        NV_UndefineSpace_Out nv_UndefineSpace;
        PolicyAuthorize_Out policyAuthorize;
        PolicyCpHash_Out policyCpHash;
        NV_DefineSpace_Out nv_DefineSpace;
        StartAuthSession_Out startAuthSession;
        VerifySignature_Out verifySignature;
        NV_Write_Out nv_Write;
        PolicyGetDigest_Out policyGetDigest;
    } out;
    ANY_OBJECT platformAuthorityKey = {0};
    ANY_OBJECT nvIndex = {0};
    TPM2B_DIGEST authPolicy = {0};
    TPM2B_DIGEST cpHash = {0};
    TPM2B_DIGEST approvedPolicy = {0};
    TPM2B_DIGEST authorization = {0};
    HASH_STATE hash = {0};
    SESSION policySession = {0};
    TPMT_TK_VERIFIED ticket = {0};
    const TPM_CC commandCode = TPM_CC_NV_Write;
    const UINT16 offset = 0;

    // First we want to see if we have already a policyAuthority installed and
    // if yes if this is the same one
    INITIALIZE_CALL_BUFFERS(TPM2_LoadExternal, &in.loadExternal, &out.loadExternal);
    in.loadExternal.inPublic = *platformAuthority;
    in.loadExternal.hierarchy = TPM_RH_PLATFORM;
    EXECUTE_TPM_CALL(FALSE, TPM2_LoadExternal);
    platformAuthorityKey = parms.objectTableOut[TPM2_LoadExternal_HdlOut_ObjectHandle];
    if((persistedData.platformAuthorityName.t.size != 0) &&
       (!Memory2BEqual((TPM2B*)&persistedData.platformAuthorityName, (TPM2B*)&platformAuthorityKey.obj.name)))
    {
        result = TPM_RC_FAILURE;
        goto Cleanup;
    }

    // Next we want to see if there is already a policy in NV and remove it if yes
    INITIALIZE_CALL_BUFFERS(TPM2_NV_ReadPublic, &in.nv_ReadPublic, &out.nv_ReadPublic);
    parms.objectTableIn[TPM2_NV_ReadPublic_HdlIn_NvIndex].nv.handle = TPM_PLATFORM_LOCKDOWN_POLICY_NV_INDEX;
    TRY_TPM_CALL(FALSE, TPM2_NV_ReadPublic);
    if(result == TPM_RC_SUCCESS)
    {
        // Get the old NV index object
        nvIndex = parms.objectTableIn[TPM2_NV_ReadPublic_HdlIn_NvIndex];

        INITIALIZE_CALL_BUFFERS(TPM2_NV_UndefineSpace, &in.nv_UndefineSpace, &out.nv_UndefineSpace);
        parms.objectTableIn[TPM2_NV_UndefineSpace_HdlIn_AuthHandle].entity.handle = TPM_RH_PLATFORM;
        parms.objectTableIn[TPM2_NV_UndefineSpace_HdlIn_NvIndex] = nvIndex;
        EXECUTE_TPM_CALL(FALSE, TPM2_NV_UndefineSpace);
    }

    // Lets start by building the index policy digest from the policy authority key above
    // Calculate the authPolicy for the index
    MemorySet(&in.policyAuthorize, 0x00, sizeof(in.policyAuthorize));
    in.policyAuthorize.approvedPolicy.t.size = SHA256_DIGEST_SIZE;
    in.policyAuthorize.policyRef.t.size = SHA256_DIGEST_SIZE;
    MemoryCopy(in.policyAuthorize.policyRef.t.buffer, &persistedData.ekName.t.name[sizeof(UINT16)], in.policyAuthorize.policyRef.t.size, sizeof(in.policyAuthorize.policyRef.t.buffer));
    in.policyAuthorize.keySign = platformAuthorityKey.obj.name;
    in.policyAuthorize.checkTicket.tag = TPM_ST_VERIFIED;
    in.policyAuthorize.checkTicket.hierarchy = TPM_RH_NULL;
    authPolicy.t.size = SHA256_DIGEST_SIZE;
    TPM2_PolicyAuthorize_CalculateUpdate(TPM_ALG_SHA256, &authPolicy, &in.policyAuthorize);

    // Now we create the Index in the TPM
    INITIALIZE_CALL_BUFFERS(TPM2_NV_DefineSpace, &in.nv_DefineSpace, &out.nv_DefineSpace);
    parms.objectTableIn[TPM2_NV_DefineSpace_HdlIn_AuthHandle].entity.handle = TPM_RH_PLATFORM;
    in.nv_DefineSpace.publicInfo.t.nvPublic.dataSize = policy->t.size;
    in.nv_DefineSpace.publicInfo.t.nvPublic.nameAlg = TPM_ALG_SHA256;
    in.nv_DefineSpace.publicInfo.t.nvPublic.nvIndex = TPM_PLATFORM_LOCKDOWN_POLICY_NV_INDEX;
    in.nv_DefineSpace.publicInfo.t.nvPublic.attributes.TPMA_NV_AUTHREAD = SET;
    in.nv_DefineSpace.publicInfo.t.nvPublic.attributes.TPMA_NV_OWNERREAD = SET;
    in.nv_DefineSpace.publicInfo.t.nvPublic.attributes.TPMA_NV_NO_DA = SET;
    in.nv_DefineSpace.publicInfo.t.nvPublic.attributes.TPMA_NV_PLATFORMCREATE = SET;
    in.nv_DefineSpace.publicInfo.t.nvPublic.attributes.TPMA_NV_POLICYWRITE = SET;
    in.nv_DefineSpace.publicInfo.t.nvPublic.authPolicy = authPolicy;
    EXECUTE_TPM_CALL(FALSE, TPM2_NV_DefineSpace);

    // Read the name from the new index back
    INITIALIZE_CALL_BUFFERS(TPM2_NV_ReadPublic, &in.nv_ReadPublic, &out.nv_ReadPublic);
    parms.objectTableIn[TPM2_NV_ReadPublic_HdlIn_NvIndex].nv.handle = TPM_PLATFORM_LOCKDOWN_POLICY_NV_INDEX;
    EXECUTE_TPM_CALL(FALSE, TPM2_NV_ReadPublic);
    nvIndex = parms.objectTableIn[TPM2_NV_ReadPublic_HdlIn_NvIndex];  // Careful this name will change after writing

    // Start a policy session in preparation of the initial write
    INITIALIZE_CALL_BUFFERS(TPM2_StartAuthSession, &in.startAuthSession, &out.startAuthSession);
    parms.objectTableIn[TPM2_StartAuthSession_HdlIn_TpmKey].obj.handle = TPM_RH_NULL;
    parms.objectTableIn[TPM2_StartAuthSession_HdlIn_Bind].obj.handle = TPM_RH_NULL;
    in.startAuthSession.nonceCaller.t.size = CryptGenerateRandom(SHA256_DIGEST_SIZE, in.startAuthSession.nonceCaller.t.buffer);
    in.startAuthSession.sessionType = TPM_SE_POLICY;
    in.startAuthSession.symmetric.algorithm = TPM_ALG_NULL;
    in.startAuthSession.authHash = TPM_ALG_SHA256;
    EXECUTE_TPM_CALL(FALSE, TPM2_StartAuthSession);
    policySession = parms.objectTableOut[TPM2_StartAuthSession_HdlOut_SessionHandle].session;

    // Next we are calculating cpHash for the write command that we want to execute later
    cpHash.t.size = CryptStartHash(TPM_ALG_SHA256, &hash);
    CryptUpdateDigestInt(&hash, sizeof(commandCode), (void*)&commandCode);
    CryptUpdateDigest2B(&hash, &nvIndex.nv.name.b);
    CryptUpdateDigest2B(&hash, &nvIndex.nv.name.b);
    CryptUpdateDigestInt(&hash, sizeof(UINT16), &policy->t.size);
    CryptUpdateDigest2B(&hash, (TPM2B*)policy);
    CryptUpdateDigestInt(&hash, sizeof(UINT16), (void*)&offset);
    CryptCompleteHash2B(&hash, &cpHash.b);

    // We execute PolicyCpHash(cpHash) on the policy session to prepare the session for the
    // NV_Write() command. No other command can be executed through this session after that
    INITIALIZE_CALL_BUFFERS(TPM2_PolicyCpHash, &in.policyCpHash, &out.policyCpHash);
    parms.objectTableIn[TPM2_PolicyCpHash_HdlIn_PolicySession].session = policySession;
    in.policyCpHash.cpHashA = cpHash;
    EXECUTE_TPM_CALL(FALSE, TPM2_PolicyCpHash);

    // Now we read back the current policy digest. We are assuming everything is correct.
    // If not things will start to blow up later.
    INITIALIZE_CALL_BUFFERS(TPM2_PolicyGetDigest, &in.policyGetDigest, &out.policyGetDigest);
    parms.objectTableIn[TPM2_PolicyGetDigest_HdlIn_PolicySession].session = policySession;
    EXECUTE_TPM_CALL(FALSE, TPM2_PolicyGetDigest);
    approvedPolicy = out.policyGetDigest.policyDigest;

    // Calculate the authorization with the policy digest. If this authorization does not match
    // what was signed by the platform authority the signature verification is going to fail
    authorization.t.size = CryptStartHash(TPM_ALG_SHA256, &hash);
    CryptUpdateDigest2B(&hash, (TPM2B*)&approvedPolicy);
    CryptUpdateDigest(&hash, SHA256_DIGEST_SIZE, &persistedData.ekName.t.name[sizeof(UINT16)]);
    CryptCompleteHash2B(&hash, &authorization.b);

    // Verify the signature with the authorization - Moment of truth!
    INITIALIZE_CALL_BUFFERS(TPM2_VerifySignature, &in.verifySignature, &out.verifySignature);
    parms.objectTableIn[TPM2_VerifySignature_HdlIn_KeyHandle] = platformAuthorityKey;
    in.verifySignature.digest = authorization;
    in.verifySignature.signature = *authorizationSignature;
    EXECUTE_TPM_CALL(FALSE, TPM2_VerifySignature);
    ticket = out.verifySignature.validation;

    // Now authorize the current write specific policy digest by executing policyAuthorize().
    // If this matches the policy session will have the generic policy digest in it afterwards
    INITIALIZE_CALL_BUFFERS(TPM2_PolicyAuthorize, &in.policyAuthorize, &out.policyAuthorize);
    parms.objectTableIn[TPM2_PolicyCpHash_HdlIn_PolicySession].session = policySession;
    in.policyAuthorize.checkTicket = ticket;
    in.policyAuthorize.keySign = platformAuthorityKey.obj.name;
    in.policyAuthorize.policyRef.t.size = SHA256_DIGEST_SIZE;
    MemoryCopy(in.policyAuthorize.policyRef.t.buffer, &persistedData.ekName.t.name[sizeof(UINT16)], in.policyAuthorize.policyRef.t.size, sizeof(in.policyAuthorize.policyRef.t.buffer));
    in.policyAuthorize.approvedPolicy = approvedPolicy;
    EXECUTE_TPM_CALL(FALSE, TPM2_PolicyAuthorize);

    // The policy session is now primed for the NV_Write() command and nothing else
    // Because the session in the TPM has the cpHash for the pending command, while the
    // policy digest in the session has the generic policy digest that the NV Index requires
    policySession.attributes.continueSession = NO; // Kill the policy session with this command
    sessionTable[0] = policySession;
    INITIALIZE_CALL_BUFFERS(TPM2_NV_Write, &in.nv_Write, &out.nv_Write);
    parms.objectTableIn[TPM2_NV_Write_HdlIn_AuthHandle] = nvIndex;
    parms.objectTableIn[TPM2_NV_Write_HdlIn_NvIndex] = nvIndex;
    in.nv_Write.data = *policy;
    in.nv_Write.offset = 0;
    EXECUTE_TPM_CALL(FALSE, TPM2_NV_Write);

    if(persistedData.platformAuthorityName.t.size == 0)
    {
        // Finally if we wrote a policy make sure that we remember the policy
        // authority in the MCU if it was not set already
        persistedData.platformAuthorityName = platformAuthorityKey.obj.name;
    }

Cleanup:
    if(platformAuthorityKey.obj.handle != 0)
    {
        FlushContext(&platformAuthorityKey);
    }
    return result;
}