Command Context Allocation Functions
These functions are used to allocate a SAPI command context data structure, an opaque structure that is used by the implementation to maintain any state data required to execute the TPM 2.0 command.
The Tss2_Sys_GetContextSize function is used to determine how much memory is needed for the SAPI context data structure. The command can return the amount of memory required to support any TPM 2.0 Part 3 command, or the caller can provide a maximum command or response size and the function calculates the context size required to support that.
Tss2_Sys_Initialize is used to initialize a SAPI context. It takes as inputs a pointer to a memory block of sufficient size for the context, the context size returned by Tss2_Sys_GetContextSize, a pointer to a TCTI context (described in the later “TCTI” section) used to define the methods for transmitting commands and receiving responses, and the calling application's required SAPI version information.
one note about the following code: rval is shorthand for return value and is a 32- bit unsigned integer. this is used repeatedly in upcoming code examples.
Here's a code example for a function that creates and initializes a system context structure.
the function that follows is declared to return a pointer to a TSS2_SYS_CONTEXT structure. this structure is defined as follows:
typedef struct _TSS2_SYS_OPAQUE_CONTEXT_BLOB TSS2_SYS_CONTEXT;
But the opaque structure is never defined anywhere. this works because TSS2_SYS_CONTEXT structures are always referenced by a pointer. Basically, this is a compiler trick that provides an advantage over using void pointers: it performs some compile time type checking.
// Allocates space for and initializes system
// context structure.
// ptr to system context, if successful
// NULL pointer, if not successful.
TSS2_SYS_CONTEXT *InitSysContext( UINT16 maxCommandSize, TSS2_TCTI_CONTEXT *tctiContext, TSS2_ABI_VERSION *abiVersion
UINT32 contextSize; TSS2_RC rval;
// Get the size needed for system context structure. contextSize = Tss2_Sys_GetContextSize( maxCommandSize );
// Allocate the space for the system context structure. sysContext = malloc( contextSize );
if( sysContext != 0 )
// Initialize the system context structure. rval = Tss2_Sys_Initialize( sysContext,
contextSize, tctiContext, abiVersion );
if( rval == TSS2_RC_SUCCESS ) return sysContext;
The last function in this group is Tss2_Sys_Finalize, which is a placeholder for any functionality that may be required to retire a SAPI context data structure before its allocated memory is freed. Here's an example of how this might be used:
void TeardownSysContext( TSS2_SYS_CONTEXT *sysContext )
if( sysContext != 0 )
In this case, Tss2_Sys_Finalize is a dummy function that does nothing, because
the SapI library code doesn't need it to do anything. Note that the system context memory is freed after the Finalize call.