/**
 * @file tee_internal_api.h
 * @brief GlobalPlatform Core internal API definitions
 * @author Iaroslav Makarchuk (i.makarchuk@samsung.com)
 * @date Created Oct 3, 2016
 * @par In Samsung Ukraine R&D Center (SURC) under a contract between
 * @par LLC "Samsung Electronics Ukraine Company" (Kiev, Ukraine) and
 * @par "Samsung Elecrtronics Co", Ltd (Seoul, Republic of Korea)
 * @par Copyright: (c) Samsung Electronics Co, Ltd 2015. All rights reserved.
 *
 * This software is proprietary of Samsung Electronics.
 * No part of this software, either material or conceptual may be copied
 * or distributed, transmitted, transcribed, stored in a retrieval system
 * or translated into any human or computer language in any form by any means,
 * electronic, mechanical, manual or otherwise, or disclosed to third parties
 * without the express written permission of Samsung Electronics.
 *
 * The file was taken from tzsl repo and modified for Multibuild project's
 * needs.
 */

#ifndef _TEE_INTERNAL_API_H
#define _TEE_INTERNAL_API_H

#ifndef ECC_IMPLEMENTATION
#define ECC_IMPLEMENTATION
#endif

#include <stdbool.h>
#include <stdint.h>
#include <stddef.h>

#define NON_GP_PADDING

#ifdef  __cplusplus
extern "C" {
#endif

#define S_VAR_NOT_USED(variable) do{(void)(variable);}while(0);

/******************************************************************************
* 3 Common Definitions
******************************************************************************/

/*
  All structures which travels across IW boundary must be packed
*/

#define IW_STRUCTURE __attribute__((packed))

//TEE_Result is the type used for return codes from the APIs.
typedef uint32_t TEE_Result;

//TEE_UUID is the Universally Unique Resource Identifier
//This type is used to identify Trusted Applications and clients.
typedef struct {
    uint32_t timeLow;
    uint16_t timeMid;
    uint16_t timeHiAndVersion;
    uint8_t clockSeqAndNode[8];
} IW_STRUCTURE TEE_UUID;

typedef enum {
    TEE_SUCCESS                       = 0x00000000,
    TEE_ERROR_CORRUPT_OBJECT          = 0xF0100001,
    TEE_ERROR_CORRUPT_OBJECT_2        = 0xF0100002,
    TEE_ERROR_STORAGE_NOT_AVAILABLE   = 0xF0100003,
    TEE_ERROR_STORAGE_NOT_AVAILABLE_2 = 0xF0100004,
    TEE_ERROR_GENERIC                 = 0xFFFF0000,
    TEE_ERROR_ACCESS_DENIED           = 0xFFFF0001,
    TEE_ERROR_CANCEL                  = 0xFFFF0002,
    TEE_ERROR_ACCESS_CONFLICT         = 0xFFFF0003,
    TEE_ERROR_EXCESS_DATA             = 0xFFFF0004,
    TEE_ERROR_BAD_FORMAT              = 0xFFFF0005,
    TEE_ERROR_BAD_PARAMETERS          = 0xFFFF0006,
    TEE_ERROR_BAD_STATE               = 0xFFFF0007,
    TEE_ERROR_ITEM_NOT_FOUND          = 0xFFFF0008,
    TEE_ERROR_NOT_IMPLEMENTED         = 0xFFFF0009,
    TEE_ERROR_NOT_SUPPORTED           = 0xFFFF000A,
    TEE_ERROR_NO_DATA                 = 0xFFFF000B,
    TEE_ERROR_OUT_OF_MEMORY           = 0xFFFF000C,
    TEE_ERROR_BUSY                    = 0xFFFF000D,
    TEE_ERROR_COMMUNICATION           = 0xFFFF000E,
    TEE_ERROR_SECURITY                = 0xFFFF000F,
    TEE_ERROR_SHORT_BUFFER            = 0xFFFF0010,
    TEE_ERROR_EXTERNAL_CANCEL         = 0xFFFF0011,
    TEE_PENDING                       = 0xFFFF2000,
    TEE_ERROR_TIMEOUT                 = 0xFFFF3001,
    TEE_ERROR_OVERFLOW                = 0xFFFF300F,
    TEE_ERROR_TARGET_DEAD             = 0xFFFF3024,
    TEE_ERROR_STORAGE_NO_SPACE        = 0xFFFF3041,
    TEE_ERROR_MAC_INVALID             = 0xFFFF3071,
    TEE_ERROR_SIGNATURE_INVALID       = 0xFFFF3072,
    TEE_ERROR_TIME_NOT_SET            = 0xFFFF5000,
    TEE_ERROR_TIME_NEEDS_RESET        = 0xFFFF5001,
    TEE_RESULT_NOT_READY              = 0xFFFF0FFF,

        /* Implementation defined error codes */
    TEE_ERROR_CERT_PARSING           = 0x80000000,
    TEE_ERROR_CRL_PARSING            = 0x80000001,
    TEE_ERROR_CERT_EXPIRED           = 0x80000002,
    TEE_ERROR_CERT_VERIFICATION      = 0x80000003,
    TEE_ERROR_BAD_FIPS_MODE          = 0x80000004,
    TEE_ERROR_TA_AUTHORITY_UNKNOWN   = 0x80000005,
    TEE_ERROR_NO_DEVICE_INFO         = 0x80000006,
    TEE_ERROR_DEVICE_ACCESS_DENIED   = 0x80000007,

} TEE_Error_Codes;

#define TEE_HANDLE_NULL 0

/******************************************************************************
*  4. Trusted Core Framework API */

/******************************************************************************
*  4.1 Data Types
******************************************************************************/

typedef struct {
    uint32_t login;
    TEE_UUID uuid;
} IW_STRUCTURE TEE_Identity;

typedef union {
    struct {
        void *buffer;
        uint32_t size;
    } IW_STRUCTURE memref;
    struct {
        uint32_t a, b;
    } IW_STRUCTURE value;
} IW_STRUCTURE TEE_Param;

#define TEE_PARAM_TYPES(t0,t1,t2,t3) \
    ((t0) | ((t1) << 4) | ((t2) << 8) | ((t3) << 12))

#define TEE_PARAM_TYPE_GET(t, i) (((t) >> (i*4)) & 0xF)

typedef struct __TEE_TASessionHandle* TEE_TASessionHandle;

typedef struct __TEE_PropSetHandle* TEE_PropSetHandle;


/******************************************************************************
*  4.2 Constants
******************************************************************************/

#define TEE_PARAM_TYPE_NONE                0x00000000
#define TEE_PARAM_TYPE_VALUE_INPUT         0x00000001
#define TEE_PARAM_TYPE_VALUE_OUTPUT        0x00000002
#define TEE_PARAM_TYPE_VALUE_INOUT         0x00000003
#define TEE_PARAM_TYPE_MEMREF_INPUT        0x00000005
#define TEE_PARAM_TYPE_MEMREF_OUTPUT       0x00000006
#define TEE_PARAM_TYPE_MEMREF_INOUT        0x00000007

#define TEE_MEM_INPUT                      0x00000001
#define TEE_MEM_OUTPUT                     0x00000002

#define TEE_LOGIN_PUBLIC                   0x00000000
#define TEE_LOGIN_USER                     0x00000001
#define TEE_LOGIN_GROUP                    0x00000002
#define TEE_LOGIN_APPLICATION              0x00000004
#define TEE_LOGIN_APPLICATION_USER         0x00000005
#define TEE_LOGIN_APPLICATION_GROUP        0x00000006
#define TEE_LOGIN_TRUSTED_APP              0xF0000000
#define TEE_LOGIN_IMP_MIN                  0x80000000
#define TEE_LOGIN_IMP_MAX                  0xEFFFFFFF

#define TEE_ORIGIN_API                     0x1
#define TEE_ORIGIN_COMMS                   0x2
#define TEE_ORIGIN_TEE                     0x3
#define TEE_ORIGIN_TRUSTED_APP             0x4
#define TEE_TIMEOUT_INFINITE               0xFFFFFFFF

#define TEE_PROPSET_CURRENT_TA            (TEE_PropSetHandle)0xFFFFFFFF
#define TEE_PROPSET_CURRENT_CLIENT        (TEE_PropSetHandle)0xFFFFFFFE
#define TEE_PROPSET_TEE_IMPLEMENTATION    (TEE_PropSetHandle)0xFFFFFFFD

#define TEE_CONFIG_MEM_ALLOC_MAX_SIZE (0x800000)
/******************************************************************************
*  4.3 TA Interface
******************************************************************************/

/* This is protection from already implemented GP interface: */
#define TA_CreateEntryPoint          MultibuildInternal_TA_CreateEntryPoint
#define TA_DestroyEntryPoint         MultibuildInternal_TA_DestroyEntryPoint
#define TA_OpenSessionEntryPoint     MultibuildInternal_TA_OpenSessionEntryPoint
#define TA_CloseSessionEntryPoint    MultibuildInternal_TA_CloseSessionEntryPoint
#define TA_InvokeCommandEntryPoint   MultibuildInternal_TA_InvokeCommandEntryPoint
#define TEE_CheckMemoryAccessRights  MultibuildInternal_TEE_CheckMemoryAccessRights
#define TEE_SetInstanceData          MultibuildInternal_TEE_SetInstanceData
#define TEE_GetInstanceData          MultibuildInternal_TEE_GetInstanceData
#define TEE_Malloc                   MultibuildInternal_TEE_Malloc
#define TEE_Realloc                  MultibuildInternal_TEE_Realloc
#define TEE_Free                     MultibuildInternal_TEE_Free
#define TEE_MemMove                  MultibuildInternal_TEE_MemMove
#define TEE_MemCompare               MultibuildInternal_TEE_MemCompare
#define TEE_MemFill                  MultibuildInternal_TEE_MemFill
#define TEE_GetObjectInfo            MultibuildInternal_TEE_GetObjectInfo
#define TEE_GetObjectInfo1           MultibuildInternal_TEE_GetObjectInfo1
#define TEE_RestrictObjectUsage      MultibuildInternal_TEE_RestrictObjectUsage
#define TEE_RestrictObjectUsage1     MultibuildInternal_TEE_RestrictObjectUsage1
#define TEE_GetObjectBufferAttribute MultibuildInternal_TEE_GetObjectBufferAttribute
#define TEE_GetObjectValueAttribute  MultibuildInternal_TEE_GetObjectValueAttribute
#define TEE_CloseObject              MultibuildInternal_TEE_CloseObject
#define TEE_AllocateTransientObject  MultibuildInternal_TEE_AllocateTransientObject
#define TEE_FreeTransientObject      MultibuildInternal_TEE_FreeTransientObject
#define TEE_ResetTransientObject     MultibuildInternal_TEE_ResetTransientObject
#define TEE_PopulateTransientObject  MultibuildInternal_TEE_PopulateTransientObject
#define TEE_InitRefAttribute         MultibuildInternal_TEE_InitRefAttribute
#define TEE_InitValueAttribute       MultibuildInternal_TEE_InitValueAttribute
#define TEE_CopyObjectAttributes     MultibuildInternal_TEE_CopyObjectAttributes
#define TEE_CopyObjectAttributes1    MultibuildInternal_TEE_CopyObjectAttributes1
#define TEE_GenerateKey              MultibuildInternal_TEE_GenerateKey
#define TEE_AllocateOperation        MultibuildInternal_TEE_AllocateOperation
#define TEE_FreeOperation            MultibuildInternal_TEE_FreeOperation
#define TEE_GetOperationInfo         MultibuildInternal_TEE_GetOperationInfo
#define TEE_GetOperationInfoMultiple MultibuildInternal_TEE_GetOperationInfoMultiple
#define TEE_ResetOperation           MultibuildInternal_TEE_ResetOperation
#define TEE_SetOperationKey          MultibuildInternal_TEE_SetOperationKey
#define TEE_SetOperationKey2         MultibuildInternal_TEE_SetOperationKey2
#define TEE_CopyOperation            MultibuildInternal_TEE_CopyOperation
#define TEE_DigestUpdate             MultibuildInternal_TEE_DigestUpdate
#define TEE_DigestDoFinal            MultibuildInternal_TEE_DigestDoFinal
#define TEE_CipherInit               MultibuildInternal_TEE_CipherInit
#define TEE_CipherUpdate             MultibuildInternal_TEE_CipherUpdate
#define TEE_CipherDoFinal            MultibuildInternal_TEE_CipherDoFinal
#define TEE_MACInit                  MultibuildInternal_TEE_MACInit
#define TEE_MACUpdate                MultibuildInternal_TEE_MACUpdate
#define TEE_MACComputeFinal          MultibuildInternal_TEE_MACComputeFinal
#define TEE_MACCompareFinal          MultibuildInternal_TEE_MACCompareFinal
#define TEE_AEInit                   MultibuildInternal_TEE_AEInit
#define TEE_AEUpdateAAD              MultibuildInternal_TEE_AEUpdateAAD
#define TEE_AEUpdate                 MultibuildInternal_TEE_AEUpdate
#define TEE_AEEncryptFinal           MultibuildInternal_TEE_AEEncryptFinal
#define TEE_AEDecryptFinal           MultibuildInternal_TEE_AEDecryptFinal
#define TEE_AsymmetricEncrypt        MultibuildInternal_TEE_AsymmetricEncrypt
#define TEE_AsymmetricDecrypt        MultibuildInternal_TEE_AsymmetricDecrypt
#define TEE_AsymmetricSignDigest     MultibuildInternal_TEE_AsymmetricSignDigest
#define TEE_AsymmetricVerifyDigest   MultibuildInternal_TEE_AsymmetricVerifyDigest
#define TEE_DeriveKey                MultibuildInternal_TEE_DeriveKey
#define TEE_GenerateRandom           MultibuildInternal_TEE_GenerateRandom
#define TEE_GetSystemTime            MultibuildInternal_TEE_GetSystemTime

#define TEE_BigIntAdd                     MultibuildInternal_TEE_BigIntAdd
#define TEE_BigIntAddMod                  MultibuildInternal_TEE_BigIntAddMod
#define TEE_BigIntCmp                     MultibuildInternal_TEE_BigIntCmp
#define TEE_BigIntCmpS32                  MultibuildInternal_TEE_BigIntCmpS32
#define TEE_BigIntComputeExtendedGcd      MultibuildInternal_TEE_BigIntComputeExtendedGcd
#define TEE_BigIntComputeFMM              MultibuildInternal_TEE_BigIntComputeFMM
#define TEE_BigIntConvertFromFMM          MultibuildInternal_TEE_BigIntConvertFromFMM
#define TEE_BigIntConvertFromOctetString  MultibuildInternal_TEE_BigIntConvertFromOctetString
#define TEE_BigIntConvertFromS32          MultibuildInternal_TEE_BigIntConvertFromS32
#define TEE_BigIntConvertToFMM            MultibuildInternal_TEE_BigIntConvertToFMM
#define TEE_BigIntConvertToOctetString    MultibuildInternal_TEE_BigIntConvertToOctetString
#define TEE_BigIntConvertToS32            MultibuildInternal_TEE_BigIntConvertToS32
#define TEE_BigIntDiv                     MultibuildInternal_TEE_BigIntDiv
#define TEE_BigIntFMMContextSizeInU32     MultibuildInternal_TEE_BigIntFMMContextSizeInU32
#define TEE_BigIntFMMSizeInU32            MultibuildInternal_TEE_BigIntFMMSizeInU32
#define TEE_BigIntGetBit                  MultibuildInternal_TEE_BigIntGetBit
#define TEE_BigIntGetBitCount             MultibuildInternal_TEE_BigIntGetBitCount
#define TEE_BigIntInit                    MultibuildInternal_TEE_BigIntInit
#define TEE_BigIntInitFMM                 MultibuildInternal_TEE_BigIntInitFMM
#define TEE_BigIntInitFMMContext          MultibuildInternal_TEE_BigIntInitFMMContext
#define TEE_BigIntInvMod                  MultibuildInternal_TEE_BigIntInvMod
#define TEE_BigIntMod                     MultibuildInternal_TEE_BigIntMod
#define TEE_BigIntMul                     MultibuildInternal_TEE_BigIntMul
#define TEE_BigIntMulMod                  MultibuildInternal_TEE_BigIntMulMod
#define TEE_BigIntNeg                     MultibuildInternal_TEE_BigIntNeg
#define TEE_BigIntRelativePrime           MultibuildInternal_TEE_BigIntRelativePrime
#define TEE_BigIntShiftRight              MultibuildInternal_TEE_BigIntShiftRight
#define TEE_BigIntSquare                  MultibuildInternal_TEE_BigIntSquare
#define TEE_BigIntSquareMod               MultibuildInternal_TEE_BigIntSquareMod
#define TEE_BigIntSub                     MultibuildInternal_TEE_BigIntSub
#define TEE_BigIntSubMod                  MultibuildInternal_TEE_BigIntSubMod
#define TEE_BigIntIsProbablePrime         MultibuildInternal_TEE_BigIntIsProbablePrime

#define TEE_GetPropertyAsString           MultibuildInternal_TEE_GetPropertyAsString
#define TEE_GetPropertyAsBool             MultibuildInternal_TEE_GetPropertyAsBool
#define TEE_GetPropertyAsU32              MultibuildInternal_TEE_GetPropertyAsU32
#define TEE_GetPropertyAsBinaryBlock      MultibuildInternal_TEE_GetPropertyAsBinaryBlock
#define TEE_GetPropertyAsUUID             MultibuildInternal_TEE_GetPropertyAsUUID
#define TEE_GetPropertyAsIdentity         MultibuildInternal_TEE_GetPropertyAsIdentity
#define TEE_AllocatePropertyEnumerator    MultibuildInternal_TEE_AllocatePropertyEnumerator
#define TEE_FreePropertyEnumerator        MultibuildInternal_TEE_FreePropertyEnumerator
#define TEE_StartPropertyEnumerator       MultibuildInternal_TEE_StartPropertyEnumerator
#define TEE_ResetPropertyEnumerator       MultibuildInternal_TEE_ResetPropertyEnumerator
#define TEE_GetPropertyName               MultibuildInternal_TEE_GetPropertyName
#define TEE_GetNextProperty               MultibuildInternal_TEE_GetNextProperty

#define TEE_OpenPersistentObject            MultibuildInternal_TEE_OpenPersistentObject
#define TEE_CreatePersistentObject          MultibuildInternal_TEE_CreatePersistentObject
#define TEE_RenamePersistentObject          MultibuildInternal_TEE_RenamePersistentObject
#define TEE_CloseAndDeletePersistentObject  MultibuildInternal_TEE_CloseAndDeletePersistentObject
#define TEE_CloseAndDeletePersistentObject1 MultibuildInternal_TEE_CloseAndDeletePersistentObject1

#define TEE_ReadObjectData     MultibuildInternal_TEE_ReadObjectData
#define TEE_WriteObjectData    MultibuildInternal_TEE_WriteObjectData
#define TEE_TruncateObjectData MultibuildInternal_TEE_TruncateObjectData
#define TEE_SeekObjectData     MultibuildInternal_TEE_SeekObjectData

#define TEE_AllocatePersistentObjectEnumerator MultibuildInternal_TEE_AllocatePersistentObjectEnumerator
#define TEE_FreePersistentObjectEnumerator MultibuildInternal_TEE_FreePersistentObjectEnumerator
#define TEE_ResetPersistentObjectEnumerator MultibuildInternal_TEE_ResetPersistentObjectEnumerator
#define TEE_StartPersistentObjectEnumerator MultibuildInternal_TEE_StartPersistentObjectEnumerator
#define TEE_GetNextPersistentObject MultibuildInternal_TEE_GetNextPersistentObject

#define TEE_GetREETime          MultibuildInternal_TEE_GetREETime
#define TEE_Wait                MultibuildInternal_TEE_Wait
#define TEE_GetTAPersistentTime MultibuildInternal_TEE_GetTAPersistentTime
#define TEE_SetTAPersistentTime MultibuildInternal_TEE_SetTAPersistentTime
#define TEE_GetCancellationFlag MultibuildInternal_TEE_GetCancellationFlag
#define TEE_MaskCancellation    MultibuildInternal_TEE_MaskCancellation
#define TEE_UnmaskCancellation  MultibuildInternal_TEE_UnmaskCancellation
/**
 * Trusted Application's constructor
 *
 * The function TA_CreateEntryPoint is the Trusted Application's constructor,
 * which the Framework calls when it creates a new instance of the Trusted
 * Application. To register instance data, the implementation of this
 * constructor can use either global variables or the function
 * @ref TEE_SetInstanceData.
 *
 * @return TEE_SUCCESS if the instance is successfully created. Any other value
 * if any other code is returned, then the instance is not created, and no other
 * entry points of this instance will be called. The Framework reclaims all
 * resources and dereference all objects related to the creation of the
 * instance. If this entry point was called as a result of a client opening a
 * session, the error code is returned to the client and the session is not
 * opened.
 */
TEE_Result TA_CreateEntryPoint(void);


/**
 * Trusted Application's destructor
 *
 * The function TA_DestroyEntryPoint is the Trusted Application's destructor,
 * which the Framework calls when the instance is being destroyed.
 * When the function TA_DestroyEntryPoint is called, the Framework guarantees
 * that no client session is currently open. Once the call to
 * TA_DestroyEntryPoint has been completed, no other entry point of this
 * instance will ever be called. Note that when this function is called, all
 * resources opened by the instance are still available. It is only after the
 * function returns that the Implementation MUST start automatically reclaiming
 * resources left opened.
 *
 * @return his function can return no success or error code. After this
 * unction returns the  mplementation Monsider sthe instance destroyed and
 *Meclaim sall resources left open by the instance.
 */
void TA_DestroyEntryPoint(void);


/**
 * Connects to the Trusted Application instance to open a new session
 *
 * This function is called whenever a client attempts to connect to the Trusted
 * Application instance to open a new session. If this function returns an
 * error, the connection is rejected and no new session is opened. In this
 * function, the Trusted Application can attach an opaque void* context to the
 * session. This context is recalled in all subsequent TA calls within the
 * session.
 *
 * @param[in] paramTypes The types of the four parameters.
 * @param[in,out] params A pointer to an array of four parameters.
 * @param[out] sessionContext A pointer to a variable that can be filled by the
 * Trusted Application instance with an opaque void* data pointer
 *
 * @return EE_SUCCESS:Ii the session is successfully opened , and any other
 * value if the session could not be opened. The error code may be one of the
 * pre-defined codes, or may be a new error code defined by the
 * Trusted Application implementation itself. In any case, the Implementation
 * reports the error code to the client with the origin
 * @ref TEEC_ORIGIN_TRUSTED_APP.
 */
TEE_Result TA_OpenSessionEntryPoint(
               uint32_t paramTypes,
               TEE_Param params[4],
               void** sessionContext);


/**
 * Closes a client session
 *
 * The Framework calls the function TA_CloseSessionEntryPoint to close a client
 * session. The Trusted Application implementation is responsible for freeing
 * any resources consumed by the session being closed. Note that the Trusted
 * Application cannot refuse to close a session, but can hold the closing until
 * it returns from TA_CloseSessionEntryPoint. This is why this function cannot
 * return an error code.
 *
 * @param[in] sessionContext The value of the void* opaque data pointer set by
 * the Trusted Application in the function @ref TA_OpenSessionEntryPoint for
 * this session.
 *
 * @return his function can return no success or error code.
 *
*/
void TA_CloseSessionEntryPoint(void* pSessionContext);

/**
 * Invokes a command within the given sessionContext
 *
 * The Framework calls the function TA_InvokeCommandEntryPoint when the client
 * invokes a command within the given session. The Trusted Application can
 * access the parameters sent by the client through the paramTypes and params
 * arguments. It can also use these arguments to transfer response data back to
 * the client. During the call to TA_InvokeCommandEntryPoint the client may
 * request to cancel the operation. A command is always invoked within the
 * context of a client session. Thus, any session function can be called by the
 * command implementation.
 *
 * @param[in] sessionContext The value of the void* opaque data pointer set by
 * the rusted Application in the function @ref TA_OpenSessionEntryPoint
 * @param[in] commandID A Trusted Application-specific code that identifies the
 * command to be invoked
 * @param[in] paramTypes The types of the four parameters.
 * @param[in,out] params A pointer to an array of four parameters.
 *
 * @return TEE_SUCCESS if the command is successfully executed, the function
 * must return this value, and any other value if the invocation of the command
 * fails for any reason. The error code may be one of the pre-defined codes, or
 * may be a new error code defined by the Trusted Application implementation
 * itself. In any case, the Implementation reports the error code to the client
 * with the origin @ref TEEC_ORIGIN_TRUSTED_APP.
 */
TEE_Result TA_InvokeCommandEntryPoint(
               void*       pSessionContext,
               uint32_t    nCommandID,
               uint32_t    nParamTypes,
               TEE_Param   pParams[4]);


/******************************************************************************
*  4.4 Property Access Functions
******************************************************************************/

/**
 * Retrieves an individual property
 *
 * The TEE_GetPropertyAsString function performs a lookup in a property set to
 * retrieve an individual property and convert its value into a printable
 * string. When the lookup succeeds, the implementation converts the property
 * into a printable string and copy the result into the buffer described by
 * valueBuffer and valueBufferLen.
 *
 * @param[in] name A pointer to the zero-terminated string containing the name
 * of the property to retrieve. Its content is case-sensitive and it must be
 * encoded in UTF-8.
 * @param[out] valueBuffer Output buffer for the property value
 * @param[in] valueBufferLen Size of output buffer for the property value
 *
 * @return EE_SUCCESS:In case of success , EE_ERROR_ITEM_NOT_FOUND: i the
 *property is not found or if name is not a valid UTF-8 encoding ,
 *TEE_ERROR_SHORT_BUFFER: i the value buffer is not large enough to hold the
 *whole property value .
 */

#ifndef __HIDE_INTERNAL_FUNCTIONS__
TEE_Result __TEE_SetProperty(
              // TEE_UUID *uuid,
              const char *name,
              void *valueBuffer,
              size_t valueBufferLen,
              int type);
#endif /* __HIDE_INTERNAL_FUNCTIONS__ */


/**
 * Retrieves property and convert its value into a string
 *
 * The TEE_GetPropertyAsString function performs a lookup in a property set to
 * retrieve an individual property and convert its value into a printable
 * string. When the lookup succeeds, the implementation converts the property
 * into a printable string and copy the result into the buffer described by
 * valueBuffer and valueBufferLen.
 *
 * @param[in] propsetOrEnumerator One of the TEE_PROPSET_XXX pseudo-handles or a
 * handle on a property enumerator
 * @param[in] name A pointer to the zero-terminated string containing the name
 * of the property to retrieve. Its content is case-sensitive and it must be
 * encoded in UTF-8.
 * @param[out] valueBuffer Output buffer for the property value
 * @param[in] valueBufferLen: Size of output buffer for the property value
 *
 * @return EE_SUCCESS:Ii case of success , TEE_ERROR_ITEM_NOT_FOUND if the
 * property is not found or if name is not a valid UTF-8 encoding,
 * TEE_ERROR_SHORT_BUFFER if the value buffer is not large enough to hold the
 * whole property value.
 */
extern TEE_Result TEE_GetPropertyAsString(
                      TEE_PropSetHandle propsetOrEnumerator,
                      const char* name,
                      char* valueBuffer,
                      uint32_t* valueBufferLen);


/**
 * Retrieves property and convert its value into a Boolean
 *
 * The TEE_GetPropertyAsBool function retrieves a single property in a property
 * set and converts its value to a Boolean. If a property cannot be viewed as a
 * Boolean, this function returns TEE_ERROR_BAD_FORMAT. Otherwise, if this
 * function succeeds, then calling the function @ref TEE_GetPropertyAsString on
 * the same name and with a sufficiently large output buffer also succeed and
 * return a string equal to true or false case-insensitive, depending on the
 * value of the Boolean.
 *
 * @param[in] propsetOrEnumerator One of the TEE_PROPSET_XXX pseudo-handles or a
 * handle on a property enumerator
 * @param[in] name A pointer to the zero-terminated string containing the name
 * of the property to retrieve. Its content is case-sensitive and must be
 * encoded in UTF-8.
 * @param[out] value A pointer to the variable that will contain the value of
 * the property on success or false on error.
 *
 * @return EE_SUCCESS:Ii case of success , TEE_ERROR_ITEM_NOT_FOUND  if the
 * property is not found or if name is not a valid UTF-8 encoding,
 * TEE_ERROR_BAD_FORMAT if the property value cannot be converted to a Boolean.
 */
TEE_Result TEE_GetPropertyAsBool(TEE_PropSetHandle propsetOrEnumerator,
                                 const char* name,
                                 bool* value ); // commented fix build error


/**
 * Retrieves property and convert its value to a 32-bit unsigned integer
 *
 *
 * The TEE_GetPropertyAsU32 function retrieves a single property in a property
 * set and converts its value to a 32-bit unsigned integer. If a property cannot
 * be viewed as a 32-bit unsigned integer, this function returns
 * TEE_ERROR_BAD_FORMAT. Otherwise, if this function succeeds, then calling the
 * function @ref TEE_GetPropertyAsString on the same name and with a
 * sufficiently large output buffer also succeed and return a string that is
 * consistent with the following syntax:
 * integer: decimal-integer | hexadecimal-integer | binary-integer
 * decimal-integer: [0-9,_]+{K,M}?
 * hexadecimal-integer: 0[x,X][0-9,a-f,A-F,_]+
 * binary-integer: 0[b,B][0,1,_]+
 * Note that the syntax allows returning the integer either in decimal,
 * hexadecimal, or binary format, that the representation can mix cases and can
 * include underscores to separate groups of digits, and finally that the
 * decimal representation may use 'K' or 'M' to denote multiplication by 1024 or
 * 1048576 respectively. For example, here are a few acceptable representations
 * of the number 1024: "1K", "0X400", "0b100_0000_0000".
 *
 * @param[in] propsetOrEnumerator One of the TEE_PROPSET_XXX pseudo-handles or a
 * handle on a property enumerator
 * @param[in] name A pointer to the zero-terminated string containing the name of
 * the property to retrieve. Its content is case-sensitive and must be encoded
 * in UTF-8.
 * @param[out] value: A pointer to the variable that will contain the value of
 * the property on success, or zero on error.
 *
 * @return EE_SUCCESS:Ii case of success ,TEE_ERROR_ITEM_NOT_FOUND:Ii the
 * roperty is not found or if name is not a valid UTF-8 encoding ,
 * EE_ERROR_BAD_FORMAT: i the property value cannot be converted to an unsigned
 *32-bit integer
 */
TEE_Result TEE_GetPropertyAsU32(
               TEE_PropSetHandle propsetOrEnumerator,
               const char* name,
               uint32_t* value );


/**
 * Retrieves property and convert its value into a binary block
 *
 * The function TEE_GetPropertyAsBinaryBlock retrieves an individual property
 * and converts its value into a binary block. If a property cannot be viewed as
 * a binary block, this function returns TEE_ERROR_BAD_FORMAT. Otherwise, if
 * this function succeeds, then calling the function
 * @ref TEE_GetPropertyAsString on the same name and with a sufficiently large
 * output buffer also succeed and return a string that is consistent with a
 * Base64 encoding of the binary block as defined in RFC 2045 [6], section 6.8
 * but with the following tolerance:
 * + An Implementation is allowed not to encode the final padding '='
 * characters.
 * + An Implementation is allowed to insert characters that are not in the
 * Base64 character set.
 *
 * @param[in] propsetOrEnumerator One of the TEE_PROPSET_XXX pseudo-handles or a
 * handle on a property enumerator
 * @param[in] name A pointer to the zero-terminated string containing the name
 * of the property to retrieve. Its content is case-sensitive and must be
 * encoded in UTF-8.
 * @param[out] valueBuffer Output buffer for the binary block
 * @param[in] valueBufferLen Size of output buffer for the binary block
 *
 * @return EE_SUCCESS:Ii case of success , TEE_ERROR_ITEM_NOT_FOUND if the
 * property is not found or if name is not a valid UTF-8 encoding,
 * TEE_ERROR_BAD_FORMAT if the property cannot be retrieved as a binary block,
 * TEE_ERROR_SHORT_BUFFER: If the value buffer is not large enough to hold the
 * whole property value
 */
TEE_Result TEE_GetPropertyAsBinaryBlock(
               TEE_PropSetHandle propsetOrEnumerator,
               const char* name,
               void* valueBuffer, uint32_t* valueBufferLen );


/**
 * Retrieves property and convert its value into a UUID
 *
 * The function TEE_GetPropertyAsUUID retrieves an individual property and
 * converts its value into a UUID. If a property cannot be viewed as a UUID,
 * this function returns TEE_ERROR_BAD_FORMAT. Otherwise, if this function
 * succeeds, then calling the function @ref TEE_GetPropertyAsString on the same
 * name and with a sufficiently large output buffer MUST also succeed and return
 * a string that is consistent with the concrete syntax of UUIDs defined in RFC
 * 4122. Note that this string may mix character cases.
 *
 * @param[in] propsetOrEnumerator One of the TEE_PROPSET_XXX pseudo-handles or
 * a handle on a property enumerator
 * @param[in] name A pointer to the zero-terminated string containing the name
 * of the property to retrieve. ts content is case-sensitive and must be
 *encoded in UTF-8.
 * @param[out] value A pointer filled with the UUID. Must not be NULL.
 *
 * @return EE_SUCCESS:Ii case of success, TEE_ERROR_ITEM_NOT_FOUND  if the
 * property is not found or if name is not a valid UTF-8 encoding,
 * TEE_ERROR_BAD_FORMAT  if the property cannot be converted into a UUID
 */
TEE_Result TEE_GetPropertyAsUUID(
               TEE_PropSetHandle propsetOrEnumerator,
               const char* name,
               TEE_UUID* value );


/**
 * Retrieves property and convert its value into a into a TEE_Identity
 *
 * The function TEE_GetPropertyAsIdentity retrieves an individual property and
 * converts its value into a TEE_Identity. If this function succeeds then
 * retrieving the property as a printable string using
 * @ref TEE_GetPropertyAsString must return a string consistent with the
 * following syntax: identity: integer (':' uuid)? where: The integer is
 * consistent with the integer syntax described in the specification of the
 * function @ref TEE_GetPropertyAsU32. If the identity UUID is Nil, then it can
 * be omitted from the string representation of the property.
 *
 * @param[in] propsetOrEnumerator One of the TEE_PROPSET_XXX pseudo-handles or a
 * handle on a property enumerator
 * @param[in] name A pointer to the zero-terminated string containing the name
 * of the property to retrieve. Its content is case-sensitive and must be
 * encoded in UTF-8.
 * @param[in] value A pointer filled with the identity. Must not be NULL.
 * @return EE_SUCCESS: i case of success , TEE_ERROR_ITEM_NOT_FOUND if the
 * property is not found or if name is not a valid UTF-8 encoding,
 * TEE_ERROR_BAD_FORMAT if the property value cannot be converted into an
 * Identity
 */
TEE_Result TEE_GetPropertyAsIdentity(
               TEE_PropSetHandle propsetOrEnumerator,
               const char* name,
               TEE_Identity* value );


/**
 * Allocates a property enumerator object
 *
 * The function TEE_AllocatePropertyEnumerator allocates a property enumerator
 * object. Once a handle on a property enumerator has been allocated, it can be
 * used to enumerate properties in a property set using the function
 * @ref TEE_StartPropertyEnumerator.
 *
 * @param[in] enumerator A pointer filled with an opaque handle on the property
 * enumerator on success and with TEE_HANDLE_NULL on error
 * @return EE_SUCCESS: In case of success ; TEE_ERROR_OUT_OF_MEMORY: If there
 * are not enough resources to allocate the property enumerator
 */
TEE_Result TEE_AllocatePropertyEnumerator(
               TEE_PropSetHandle* enumerator );


/**
 * Deallocates a property enumerator object
 *
 * The function TEE_FreePropertyEnumerator deallocates a property enumerator
 * object.
 * @param[in] enumerator A handle on the enumerator to free
 */
void TEE_FreePropertyEnumerator(TEE_PropSetHandle enumerator );

/**
 * Starts to enumerate the properties in an enumerator
 *
 * The function TEE_StartPropertyEnumerator starts to enumerate the properties
 * in an enumerator. Once an enumerator is attached to a property set:
 *
 * + Properties can be retrieved using one of the TEE_GetPropertyAsXXX
 * functions, passing the enumerator handle as the property set and NULL as the
 * name.
 *
 * + The function @ref TEE_GetPropertyName can be used to retrieve the name of
 * the current property in the enumerator.
 *
 * + The function @ref TEE_GetNextProperty can be used to advance the
 * enumeration to the next property in the property set.
 *
 * @param[in] enumerator A handle on the enumerator
 * @param[in] propSet A pseudo-handle on the property set to enumerate. Must be
 * one of the TEE_PROPSET_XXX pseudo-handles.
 */
void TEE_StartPropertyEnumerator(
         TEE_PropSetHandle enumerator,
         TEE_PropSetHandle propSet );


/**
 * Resets a property enumerate to its state
 *
 * The function TEE_ResetPropertyEnumerator resets a property enumerate to its
 * state immediately after allocation. If an enumeration is currently started,
 * it is abandoned.
 *
 * @param[in] enumerator A handle on the enumerator to reset
 */
void TEE_ResetPropertyEnumerator(
         TEE_PropSetHandle enumerator );

/**
 * Gets the name of the current property
 *
 * The function TEE_GetPropertyName gets the name of the current property in an
 * enumerator. The property name must the valid UTF-8 encoding of a Unicode
 * string containing no U+0000 code points.
 *
 * @param[in] enumerator A handle on the enumerator
 * @param[out] nameBufferThe The buffer filled with the name
 * @param[in] nameBufferLen: Lenth of the buffer filled with the name
 *
 * @return EE_SUCCESS: In case of success , TEE_ERROR_ITEM_NOT_FOUND: If there
 * is no current property either because the enumerator has not started or
 * because it has reached the end of the property set, TEE_ERROR_SHORT_BUFFER:
 * If the name buffer is not large enough to contain the property name
 */
TEE_Result TEE_GetPropertyName(
               TEE_PropSetHandle enumerator,
               void* nameBuffer, uint32_t* nameBufferLen );


/**
 * Advances the enumerator to the next property
 *
 * The function TEE_GetNextProperty advances the enumerator to the next
 * property.
 *
 * @param[in] enumerator A handle on the enumerator
 *
 * @return EE_SUCCESS: In case of success , TEE_ERROR_ITEM_NOT_FOUND: If the
 * enumerator has reached the end of the property set or if it has not started
 */
TEE_Result TEE_GetNextProperty(
               TEE_PropSetHandle enumerator);


/******************************************************************************
*  4.5 Trusted Application Configuration Properties
******************************************************************************/

/******************************************************************************
*  4.6 Client Properties
******************************************************************************/

/******************************************************************************
*  4.7 Implementation Properties
******************************************************************************/

/******************************************************************************
*  4.8 Panics
******************************************************************************/
/**
 * Raises a Panic in the Trusted Application instance
 *
 * The TEE_Panic function raises a Panic in the Trusted Application instance.
 * When a Trusted Application calls the TEE_Panic function, the current instance
 * is destroyed and all the resources opened by the instance are reclaimed. All
 * sessions opened from the panicking instance on another TA must be gracefully
 * closed and all cryptographic objects and operations must be closed properly.
 * When an instance panics, its clients receive the error code
 * TEE_ERROR_TARGET_DEAD of origin TEE_ORIGIN_TEE until they close their
 * session. This applies to Rich Execution Environment clients calling through
 * the TEE Client API and to Trusted Execution Environment clients calling
 * through the Internal Client API. Once an instance is panicked, no TA entry
 * point is ever called again for this instance, not even TA_DestroyEntryPoint.
 * The caller cannot expect that the TEE_Panic function will return.
 *
 * @param[in] panicCode An informative panic code defined by the TA. May be
 * displayed in traces if traces are available.
 */

void _TEE_Panic(TEE_Result panic_code, const char* szSrcFuncName, int nSrcFileLine ) __attribute__ ((noreturn));

#define TEE_Panic(panic_code) _TEE_Panic(panic_code, __func__, __LINE__)

/******************************************************************************
*  4.10 Cancellation Functions
******************************************************************************/
/**
 * Determines whether the current task's Cancellation Flag is set
 *
 * The TEE_GetCancellationFlag function determines whether the current task's
 * Cancellation Flag is set. If cancellations are masked, this function must
 * return false.
 *
 * @return 'false' if the cancellation flag is not set or if cancellations are
 * masked; 'true' if the cancellation flag is set and cancellations are not
 * masked
 */
bool TEE_GetCancellationFlag( void );


/**
 * Unmasks the effects of cancellation
 *
 * The TEE_UnmaskCancellation function unmasks the effects of cancellation for
 * the current task. When cancellation requests are unmasked, the Cancellation
 * Flag interrupts cancellable functions such as @ref TEE_Wait and requests the
 * cancellation of operations started with @ref TEE_OpenTASession or
 * @ref TEE_InvokeTACommand. By default, tasks created to handle a TA entry
 * point have cancellation masked, so that a TA does not have to cope with the
 * effects of cancellation requests.
 * @return 'true' if cancellations were masked prior to calling this function;
 * 'false' otherwise
 */
bool TEE_UnmaskCancellation( void );


/**
 * Masks the effects of cancellation
 *
 * The TEE_MaskCancellation function masks the effects of cancellation for the
 * current task. When cancellation requests are masked, the Cancellation Flag
 * does not have an effect on the cancellable functions and cannot be retrieved
 * using @ref TEE_GetCancellationFlag. By default, tasks created to handle a TA
 * entry point have cancellation masked, so that a TA does not have to cope with
 * the effects of cancellation requests.
 *
 * @return 'true' if cancellations were masked prior to calling this function;
 * 'false' otherwise
 */
bool TEE_MaskCancellation( void );
/******************************************************************************
*  4.11 Memory Management Functions
******************************************************************************/

/* Specification defined, default value. Returns zeroed memory */
#define HINT_FILL_WITH_ZEROS    0x0

/* same as HINT_FILL_WITH_ZEROS */
#define HINT_DEFAULT    0x0

/* Implementation defined values. It's possible to combine it with "|". */

/* Opposite for HINT_FILL_WITH_ZEROS, DO NOT zero memory. */
#define HINT_DONT_FILL_WITH_ZEROS    0x80000001

/* Fills memory with random generated values on freeing. */
#define HINT_RANDOMIZE_ON_FREE    0x80000002

enum {
    TEE_MEMORY_ACCESS_READ        = 1,
    TEE_MEMORY_ACCESS_WRITE       = 2,
    TEE_MEMORY_ACCESS_ANY_OWNER   = 4
};

/**
 * Checks specified buffer for access rights
 *
 * The TEE_CheckMemoryAccessRights function causes the Implementation to examine
 * a buffer of memory specified in the parameters buffer and size and to
 * determine whether the current Trusted Application instance has the access
 * rights requested in the parameter accessFlags. If the characteristics of the
 * buffer are compatible with accessFlags, then the function returns
 * TEE_SUCCESS. Otherwise, it returns TEE_ERROR_ACCESS_DENIED. Note that the
 * buffer should not be accessed by the function, but the Implementation should
 * check the access rights based on the address of the buffer and internal
 * memory management information.
 * This function MUST NOT panic for any reason.
 *
 * @param[in] buffer Pointer to the buffer to check
 * @param[in] size Size of the buffer to check
 * @param[in] accessFlags The access flags to check
 *
 * @return TEE_SUCCESS: If the entire buffer allows the requested accesses or
 * TEE_ERROR_ACCESS_DENIED: If at least one byte in the buffer is not accessible
 * with the requested accesses
 */
TEE_Result TEE_CheckMemoryAccessRights(
              uint32_t accessFlags,
              void* buffer, uint32_t size);


/**
 *  Provides an alternative to writable global data
 *
 * The TEE_SetInstanceData and TEE_GetInstanceData functions provide an
 * alternative to writable global data (writable variables with global scope and
 * writable static variables with global or function scope). While an
 * Implementation supports C global variables, using these functions may be
 * sometimes more efficient, especially if only a single instance data variable
 * is required.
 *
 * @param[in] instanceData A pointer to the global Trusted Application instance
 * data. This pointer may be NULL.
 */
void TEE_SetInstanceData(void* instanceData );


/**
 * Retrieves the instance data pointer
 *
 * The TEE_GetInstanceData function retrieves the instance data pointer set by
 * the Trusted Application using the @ref TEE_GetInstanceData function.
 *
 * @return The value returned is the previously set pointer to the Trusted
 * Application instance data, or NULL if no instance data pointer has yet been
 * set.
 */
void* TEE_GetInstanceData( void );


/**
 * Allocates space for an object
 *
 * The TEE_Malloc function allocates space for an object whose size in bytes is
 * specified in the parameter size.
 *
 * @param[in] size The size of the buffer to be allocated.
 * @param[in] hint A hint to the allocator. Currently defined values are as
 * follows:
 *
 * + The default value, 0, guarantees that the returned block of memory is
 * filled with zeros.
 *
 * + Values in the range [0x00000001, 0x7FFFFFFF] are reserved for future
 * version of this specification.
 *
 * + Values in the range [0x80000000, 0xFFFFFFFF] can be used for
 * implementation-defined hints.
 *
 * @return Upon successful completion, with size not equal to zero, the function
 * returns a pointer to the allocated space. If the space cannot be allocated, a
 * NULL pointer is returned.
 */
void* TEE_Malloc( uint32_t size, uint32_t hint );


/**
 * Changes the size of the memory object
 *
 * The TEE_Realloc function changes the size of the memory object pointed to by
 * buffer to the size specified by nNewSize.
 *
 * @param[in] buffer: The pointer to the object to be reallocated
 * @param[in] newSize: The new size required for the object
 *
 * @return Upon successful completion, TEE_Realloc returns a pointer to the
 * (possibly moved) allocated space. If there is not enough available memory,
 * TEE_Realloc returns a NULL pointer.
*/
void* TEE_Realloc(const void* buffer, uint32_t newSize );


/**
 * Causes the space pointed to by buffer to be deallocated
 *
 * The TEE_Free function causes the space pointed to by buffer to be
 * deallocated; that is, made available for further allocation. If buffer is a
 * NULL pointer, TEE_Free does nothing. Otherwise, it is a Programmer Error
 * if the argument does not match a pointer previously returned by the
 * @ref TEE_Malloc or @ref TEE_Realloc, or if the space has been deallocated by
 * a call to TEE_Free or @ref TEE_Realloc.
 *
 * @param[in] buffer The pointer to the memory block to be freed
 */
void TEE_Free(void *buffer);


/**
 * Copies size bytes from one object to another
 *
 * The TEE_MemMove function copies size bytes from the object pointed to by src
 * into the object pointed to by dest. Note that the buffers dest and src can
 * reside in any kinds of memory, including shared memory.
 *
 * @param[in] dest A pointer to the destination buffer
 * @param[in] src A pointer to the source buffer
 * @param[in] size The number of bytes to be copied
 */
void TEE_MemMove(void* dest, const void* src, uint32_t size );


/**
 * Compares bytes of one object to another
 *
 * The TEE_MemCompare function compares the first size bytes of the object
 * pointed to by buffer1 to the first size bytes of the object pointed to by
 * buffer2. Note that buffer1 and buffer2 can reside in any kinds of memory,
 * including shared memory.
 *
 * @param[in] buffer1 A pointer to the first buffer
 * @param[in] buffer2 A pointer to the second buffer
 * @param[in] size The number of bytes to be compared
 *
 * @return The sign of a non-zero return value is determined by the sign of the
 * difference between the values of the first pair of bytes (both interpreted as
 * type uint8_t) that differ in the objects being compared.
 *
 * + If the first byte that differs is higher in buffer1, then return an integer
 * greater than zero.
 *
 * + If the first size bytes of the two buffers are identical, then return zero.
 *
 * + If the first byte that differs is higher in buffer2, then return an integer
 * lower than zero.
 */
int32_t TEE_MemCompare(const void *buffer1, const void *buffer2, uint32_t size);

/**
 * Writes the byte x into the object
 *
 * The TEE_MemFill function writes the byte x (converted to a uint8_t) into the
 * first size bytes of the object pointed to by buffer. Note that buffer can
 * reside in any kinds of memory, including shared memory.
 *
 * @param[in] buffer A pointer to the destination buffer
 * @param[in] x The value to be set
 * @param[in] size The number of bytes to be set
 */
void TEE_MemFill(void* buffer, uint32_t x,uint32_t size);



/******************************************************************************
*  5 Trusted Storage API for Data and Keys
******************************************************************************/

/******************************************************************************
*  5.2 Data Types
******************************************************************************/

typedef struct {
    uint32_t attributeID;
    union {
        struct {
            const void* buffer;
            uint32_t length;
        } ref;
        struct {
            uint32_t a, b;
        } value;
    } content;
} TEE_Attribute;

typedef struct {
    uint32_t objectType;
    uint32_t keySize;
    uint32_t maxKeySize;
    uint32_t objectUsage;
    uint32_t dataSize;
    uint32_t dataPosition;
    uint32_t handleFlags;
} TEE_ObjectInfo;

typedef enum {
    TEE_DATA_SEEK_SET = 0,
    TEE_DATA_SEEK_CUR,
    TEE_DATA_SEEK_END
} TEE_Whence;

typedef struct __TEE_ObjectHandle* TEE_ObjectHandle;

typedef struct __TEE_ObjectEnumHandle* TEE_ObjectEnumHandle;


/******************************************************************************
*  5.3 Constants
******************************************************************************/

#define TEE_STORAGE_PRIVATE              0x00000001

// Data Flag Constants
#define TEE_DATA_FLAG_ACCESS_READ        0x00000001
#define TEE_DATA_FLAG_ACCESS_WRITE       0x00000002
#define TEE_DATA_FLAG_ACCESS_WRITE_META  0x00000004
#define TEE_DATA_FLAG_SHARE_READ         0x00000010
#define TEE_DATA_FLAG_SHARE_WRITE        0x00000020
#define TEE_DATA_FLAG_EXCLUSIVE          0x00000400
#define TEE_DATA_FLAG_OVERWRITE          0x00000400

// Usage Constants
#define TEE_USAGE_EXTRACTABLE            0x00000001
#define TEE_USAGE_ENCRYPT                0x00000002
#define TEE_USAGE_DECRYPT                0x00000004
#define TEE_USAGE_MAC                    0x00000008
#define TEE_USAGE_SIGN                   0x00000010
#define TEE_USAGE_VERIFY                 0x00000020
#define TEE_USAGE_DERIVE                 0x00000040

// Handle Flag Constants
#define TEE_HANDLE_FLAG_PERSISTENT       0x00010000
#define TEE_HANDLE_FLAG_INITIALIZED      0x00020000
#define TEE_HANDLE_FLAG_KEY_SET          0x00040000
#define TEE_HANDLE_FLAG_EXPECT_TWO_KEYS  0x00080000

// Operation Constants
#define TEE_OPERATION_CIPHER                  1
#define TEE_OPERATION_MAC                     3
#define TEE_OPERATION_AE                      4
#define TEE_OPERATION_DIGEST                  5
#define TEE_OPERATION_ASYMMETRIC_CIPHER       6
#define TEE_OPERATION_ASYMMETRIC_SIGNATURE    7
#define TEE_OPERATION_KEY_DERIVATION          8

/* Operation States */
#define TEE_OPERATION_STATE_INITIAL       0x00000000
#define TEE_OPERATION_STATE_ACTIVE        0x00000001

/* Miscellaneous Constants */
#define TEE_DATA_MAX_POSITION             0xFFFF
#define TEE_OBJECT_ID_MAX_LEN             64

/******************************************************************************
*  5.4 Generic Object Functions
******************************************************************************/

/**
 * Returns the characteristics of an object
 *
 * The TEE_GetObjectInfo function returns the characteristics of an object.
 *
 * @param[in] object Handle of the object
 * @param[in] objectInfo Pointer to a structure filled with the object
 * information
 */
void TEE_GetObjectInfo( TEE_ObjectHandle object, TEE_ObjectInfo* objectInfo );

TEE_Result TEE_GetObjectInfo1(TEE_ObjectHandle object, TEE_ObjectInfo* objectInfo);

/**
 * Restricts the object usage
 *
 * The TEE_RestrictObjectUsage function restricts the object usage flags of an
 * object handle to contain at most the flags passed in the objectUsage
 * parameter.
 *
 * @param[in] object: Handle on an object
 * @param[in] objectUsage: New object usage, an OR combination of one or more of
 * the TEE_USAGE_XXX constants
 */
void TEE_RestrictObjectUsage(TEE_ObjectHandle object, uint32_t objectUsage );

TEE_Result TEE_RestrictObjectUsage1(TEE_ObjectHandle object, uint32_t objectUsage);

/**
 * Extracts one buffer attribute from an object
 *
 * The TEE_GetObjectBufferAttribute function extracts one buffer attribute from
 * an object.
 *
 * Panic Reasons
 *
 * + object is not a valid opened object handle.
 *
 * + The object is not initialized.
 *
 * + Bit [29] of attributeID is not set to 0, so the attribute is not a buffer
 * attribute
 *
 * + Bit [28] of attributeID is set to 1, denoting a protected attribute, and
 * the object usage does not contain the TEE_USAGE_EXTRACTABLE flag.
 *
 * @param[in] object: Handle of the object
 * @param[in] attributeID: Identifier of the attribute to retrieve
 * @param[in] buffer, size: Output buffer to get the content of the attribute
 *
 * @return TEE_SUCCESS: In case of success; TEE_ERROR_ITEM_NOT_FOUND: If the
 * attribute is not found on this object or if the object is a transient
 * uninitialized object; TEE_ERROR_SHORT_BUFFER: If buffer is NULL or too small
 * to contain the key part
 */
TEE_Result TEE_GetObjectBufferAttribute(
               TEE_ObjectHandle object,
               uint32_t attributeID,
               void* buffer, uint32_t* size
               );

/**
 * Extracts a value attribute from an object
 *
 * The TEE_GetObjectValueAttribute function extracts a value attribute from an
 * object.
 *
 * Panic Reasons
 * + object is not a valid opened object handle.
 *
 * + The object is not initialized.
 *
 * + Bit [29] of attributeID is not set to 1, so the attribute is not a value
 * attribute.
 *
 * + Bit [28] of attributeID is set to 1, denoting a protected attribute, and
 * the object usage does not contain the TEE_USAGE_EXTRACTABLE flag.
 *
 * @param[in] object Handle of the object
 *
 * @param[in] attributeID Identifier of the attribute to retrieve
 *
 * @param[in] a, @param[in] b Pointers on the placeholders filled with the
 * attribute field a and b. Each can be NULL if the corresponding field is not
 * of interest to the caller.
 *
 * @return TEE_SUCCESS: In case of success; TEE_ERROR_ITEM_NOT_FOUND: If the
 * attribute is not found on this object or if the object is a transient
 * uninitialized object; TEE_ERROR_ACCESS_DENIED: For an attempt to extract a
 * secret part of a non-extractable container
 */
TEE_Result TEE_GetObjectValueAttribute(
               TEE_ObjectHandle object,
               uint32_t attributeID,
               uint32_t* a,
               uint32_t* b
               );

/**
 * closes an opened object handle
 *
 * The TEE_CloseObject function closes an opened object handle. The object can
 * be persistent or transient.
 * Panic Reasons object is not a valid opened object handle and is not equal to
 * TEE_HANDLE_NULL.
 *
 * @param[in] object Handle on the object to close. If set to TEE_HANDLE_NULL,
 * does nothing.
*/
void TEE_CloseObject( TEE_ObjectHandle object);




/******************************************************************************
*  5.5 Transient Object Functions
******************************************************************************/

/**
 * Allocates an uninitialized transient object
 *
 * The TEE_AllocateTransientObject function allocates an uninitialized transient
 * object, i.e., a container for attributes. Transient objects are used to hold
 * a cryptographic object (key or key-pair). The object type and the maximum
 * object characteristic size must be specified so that all the container
 * resources can be pre-allocated. Note that a compliant Implementation must
 * implement all the object types, algorithms, and object sizes
 *
 * @param[in] objectType: Type of uninitialized object container to be created
 * @param[in] maxObjectSize: Size of the object. The interpretation of this
 * parameter depends on the object type.
 * @param[out] object: Filled with a handle on the newly created key container
 *
 * @return TEE_SUCCESS: On success; TEE_ERROR_OUT_OF_MEMORY: If not enough
 * resources are available to allocate the object handle;
 * TEE_ERROR_NOT_SUPPORTED: If the object size is not supported.
 */TEE_Result TEE_AllocateTransientObject(
                  uint32_t objectType,
                  uint32_t maxObjectSize,
                  TEE_ObjectHandle* object
                  );

/*
 * Description
 * The TEE_FreeTransientObject function deallocates a transient object previously allocated with TEE_AllocateTransientObject.
 * After this function has been called, the object handle is no longer valid and all resources associated with the transient object
 * must have been reclaimed.
 * If the object is initialized, the object attributes are cleared before the object is deallocated.
 * This function cannot fail. It does nothing if object is TEE_HANDLE_NULL.
 * Parameters
 * + object: Handle on the object to free
 * Panic Reasons
 * + object is not a valid opened object handle and is not equal to TEE_HANDLE_NULL.
*/
void TEE_FreeTransientObject(TEE_ObjectHandle object );

/*
 * Description
 * The TEE_ResetTransientObject function resets a transient object to its initial state after allocation.
 * If the object is currently initialized, the function clears the object of all its material.
 * The object is then uninitialized again.
 * In any case, the function resets the key usage of the container to 0xFFFFFFFFF.
 * This function does nothing if object is set to TEE_HANDLE_NULL.
 * Parameters
 * + object: Handle on a transient object to reset
 * Panic Reasons
 * + object is not a valid opened object handle and is not equal to TEE_HANDLE_NULL.
*/
void TEE_ResetTransientObject(TEE_ObjectHandle object);

/*
 * Description
 * The TEE_PopulateTransientObject function populates an uninitialized object container
 * with object attributes passed by the TA in the attrs parameter.
 * Parameters
 * + object: Handle on an already created transient and uninitialized object
 * + attrs, attrCount: Array of object attributes
 * Return Value
 * + TEE_SUCCESS: In case of success. In this case, the content of the object MUST be initialized.
 * + TEE_ERROR_BAD_PARAMETERS: If an incorrect or inconsistent attribute value is detected.
 *     In this case, the content of the object container MUST remain uninitialized.
 * Panic Reasons
 * + object is not a valid opened object handle that is transient and uninitialized.
 * + Some mandatory attribute is missing.
*/
TEE_Result TEE_PopulateTransientObject(TEE_ObjectHandle object, const TEE_Attribute* attrs, uint32_t attrCount );

/*
 * Description
 * The TEE_InitRefAttribute and TEE_InitValueAttribute helper functions can be used to populate a single
 * attribute either with a reference to a buffer or with integer values.
 *
 */

void TEE_InitRefAttribute(
        TEE_Attribute* attr,
        uint32_t attributeID,
        const void* buffer, uint32_t length
        );

void TEE_InitValueAttribute(
        TEE_Attribute* attr,
        uint32_t attributeID,
        uint32_t a, uint32_t b
        );

/*
 * Description
 * The TEE_CopyObjectAttributes function populates an uninitialized object handle with the attributes of another object handle;
 * that is, it populates the attributes of destObject with the attributes of srcObject. It is most useful in the following situations:
 * Parameters
 * + destObject: Handle on an uninitialized transient object
 * + srcObject: Handle on an initialized object
 * Panic Reasons
 * + srcObject is not initialized.
 * + destObject is not uninitialized.
 * + The type and size of srcObject and destObject are not compatible.
 * */
void TEE_CopyObjectAttributes(
         TEE_ObjectHandle destObject,
         TEE_ObjectHandle srcObject
         );

TEE_Result TEE_CopyObjectAttributes1(
               TEE_ObjectHandle destObject,
               TEE_ObjectHandle srcObject
               );
/*
 * Description
 * The TEE_GenerateKey function generates a random key or a key-pair and populates a transient key object with the generated key material.
 * Parameters
 * + object: Handle on an uninitialized transient key to populate with the generated key
 * + keySize: Requested key size. Must be less than or equal to the maximum size of the object container.
 * + params, paramCount: Parameters for the key generation
 * Return Value
 * + TEE_SUCCESS: On success
 * + TEE_ERROR_BAD_PARAMETERS: If an incorrect or inconsistent attribute is detected
 * Panic Reasons
 * + object is not a valid opened object handle that is transient and uninitialized.
 * + keySize is too large.
+ A mandatory parameter is missing.
*/
TEE_Result TEE_GenerateKey(
               TEE_ObjectHandle object,
               uint32_t keySize,
               const TEE_Attribute* params, uint32_t paramCount
               );


/******************************************************************************
*  5.6 Persistent Object Functions
******************************************************************************/
/*
 * Description
 * The TEE_OpenPersistentObject function opens a handle on an existing persistent
 * object. It returns a handle that can be used to access the object’s attributes
 * and data stream.
 * Parameters
 * • storageID: The storage to use. Valid values are defined in Table 5-2 (see specification).
 * • objectID, objectIDLen: The object identifier. Note that this buffer cannot
 *                          reside in shared memory.
 * • flags: The flags which determine the settings under which the object is opened.
 * • object: A pointer to the handle, which contains the opened handle upon
 *           successful completion. If this function fails for any reason, the
 *           value pointed to by object is set to TEE_HANDLE_NULL. When the
 *           object handle is no longer required, it MUST be closed using a call
 *           to the TEE_CloseObject function.
 * Return Code
 * • TEE_SUCCESS: In case of success
 * • TEE_ERROR_ITEM_NOT_FOUND: If the storage denoted by storageID does not exist or
 *                             if the object identifier cannot be found in the storage
 * • TEE_ERROR_ACCESS_CONFLICT: If an access right conflict was detected while opening the object
 * • TEE_ERROR_OUT_OF_MEMORY: If there is not enough memory to complete the operation
 * • TEE_ERROR_CORRUPT_OBJECT: If the storage or object is corrupt
 * • TEE_ERROR_STORAGE_NOT_AVAILABLE: If the persistent object is stored in a storage
 *                                    area which is currently inaccessible.
 * Panic Reasons
 * • objectIDLen is greater than TEE_OBJECT_ID_MAX_LEN.
 * • If the Implementation detects any other error which is not explicitly
 *   associated with a defined return code for this function.
*/
TEE_Result TEE_OpenPersistentObject(uint32_t storageID, const void* objectID, uint32_t objectIDLen, uint32_t flags, TEE_ObjectHandle* object);

/*
 * Description
 * The TEE_CreatePersistentObject function creates a persistent object with
 * initial attributes and an initial data stream content, and optionally returns
 * either a handle on the created object, or TEE_HANDLE_NULL upon failure.
 * Parameters
 * • storageID: The storage to use. Valid values are defined in Table 5-2.
 * • objectID, objectIDLen: The object identifier. Note that this cannot reside
 *                          in shared memory.
 * • flags: The flags which determine the settings under which the object is opened
 * • attributes: A handle on a persistent object or an initialized transient object
 *               from which to take the persistent object attributes. Can be TEE_HANDLE_NULL
 *               if the persistent object contains no attribute; for example,
 *               if it is a pure data object.
 * • initialData, initialDataLen: The initial data content of the persistent object
 * • object: A pointer to the handle, which contains the opened handle upon successful
 *           completion. If this function fails for any reason, the value pointed to by
 *           object is set to TEE_HANDLE_NULL. When the object handle is no longer
 *           required, it MUST be closed using a call to the TEE_CloseObject function.
 * Return Code
 * • TEE_SUCCESS: In case of success
 * • TEE_ERROR_ITEM_NOT_FOUND: If the storage denoted by storageID does not exist
 * • TEE_ERROR_ACCESS_CONFLICT: If an access right conflict was detected while opening the object
 * • TEE_ERROR_OUT_OF_MEMORY: If there is not enough memory to complete the operation
 * • TEE_ERROR_STORAGE_NO_SPACE: If insufficient space is available to create the persistent object
 * • TEE_ERROR_CORRUPT_OBJECT: If the storage is corrupt
 * • TEE_ERROR_STORAGE_NOT_AVAILABLE: If the persistent object is stored in a storage
 *                                    area which is currently inaccessible.
 * Panic Reasons
 * • objectIDLen is greater than TEE_OBJECT_ID_MAX_LEN.
 * • attributes is not TEE_HANDLE_NULL and is not a valid handle on an initialized
 *   object containing the type and attributes of the persistent object to create.
 * • Specified storageID is invalid
 * • If the Implementation detects any other error which is not explicitly associated
 *   with a defined return code for this function.
*/
TEE_Result TEE_CreatePersistentObject(uint32_t storageID, const void* objectID, uint32_t objectIDLen, uint32_t flags, TEE_ObjectHandle attributes,
                     const void* initialData, uint32_t initialDataLen, TEE_ObjectHandle* object);

/*
 * Description
 * The function TEE_RenamePersistentObject changes the identifier of an object.
 * The object handle MUST have been opened with the write-meta access right, which
 * means access to the object is exclusive. Renaming an object is an atomic
 * operation; either the object is renamed or nothing happens.
 * Parameters
 * • object: The object handle
 * • newObjectID, newObjectIDLen: A buffer containing the new object identifier.
 *                                The identifier contains arbitrary bytes, including
 *                                the zero byte. The identifier length MUST be less
 *                                than or equal to TEE_OBJECT_ID_MAX_LEN and can be
 *                                zero. The buffer containing the new object identifier
 *                                cannot reside in shared memory.
 * Return Code
 * • TEE_SUCCESS: In case of success
 * • TEE_ERROR_ACCESS_CONFLICT: If an object with the same identifier already exists
 * • TEE_ERROR_CORRUPT_OBJECT: If the object is corrupt. The object handle is closed.
 * • TEE_ERROR_STORAGE_NOT_AVAILABLE: If the persistent object is stored in a storage
 *                                    area which is currently inaccessible.
 * Panic Reasons
 * • object is not a valid handle on a persistent object that has been opened with
 *   the write-meta access right.
 * • newObjectID resides in shared memory.
 * • newObjectIDLen is more than TEE_OBJECT_ID_MAX_LEN.
 * • If the Implementation detects any other error which is not explicitly
 *   associated with a defined return code for this function.
*/
TEE_Result TEE_RenamePersistentObject(TEE_ObjectHandle object, const void* newObjectID, uint32_t newObjectIDLen);

/*
 * Description
 * The TEE_CloseAndDeletePersistentObject (version 1.0) function marks an object
 * for deletion and closes the object handle.
 * Parameters
 * • object: The object handle
 * Panic Reasons
 * • object is not a valid handle on a persistent object opened with the write-
 *   meta access right.
*/
void TEE_CloseAndDeletePersistentObject(TEE_ObjectHandle object);

/*
 * Description
 * This function replaces the TEE_CloseAndDeletePersistentObject function, whose
 * use is deprecated.
 * The TEE_CloseAndDeletePersistentObject1 (version 1.1) function marks an object
 * for deletion and closes the object handle.
 * Parameters
 * • object: The object handle
 * Return Code
 * • TEE_SUCCESS: In case of success
 * • TEE_ERROR_STORAGE_NOT_AVAILABLE: If the persistent object is stored in a
 *                                    storage area which is currently inaccessible.
 * Panic Reasons
 * • object is not a valid handle on a persistent object opened with the write-
 *   meta access right.
 * • If the Implementation detects any other error which is not explicitly
 *   associated with a defined return code for this function.
*/
TEE_Result TEE_CloseAndDeletePersistentObject1(TEE_ObjectHandle object);

/******************************************************************************
* 5.7 Persistent Object Enumeration Functions
******************************************************************************/

/*
 * Description
 * The TEE_AllocatePersistentObjectEnumerator function allocates a handle on an
 * object enumerator. Once an object enumerator handle has been allocated, it
 * can be reused for multiple enumerations.
 * Parameters
 * • objectEnumerator: A pointer filled with the newly-allocated object enumerator
 *                     handle on success. Set to TEE_HANDLE_NULL in case of error.
 * Return Code
 * • TEE_SUCCESS: In case of success
 * • TEE_ERROR_OUT_OF_MEMORY: If there is not enough memory to allocate the
 *                            enumerator handle
 * Panic Reasons
 * • If the Implementation detects any error which is not explicitly associated
 *   with a defined return code for this function.
*/
TEE_Result TEE_AllocatePersistentObjectEnumerator(TEE_ObjectEnumHandle* objectEnumerator);

/*
 * Description
 * The TEE_FreePersistentObjectEnumerator function deallocates all resources
 * associated with an object enumerator handle. After this function is called,
 * the handle is no longer valid.
 * Parameters
 * • objectEnumerator: The handle to close. If objectEnumerator is TEE_HANDLE_NULL,
 * then this function does nothing.
 * Panic Reasons
 * • objectEnumerator is not a valid handle on an object enumerator.
 * • If the Implementation detects any other error.
*/
void TEE_FreePersistentObjectEnumerator(TEE_ObjectEnumHandle objectEnumerator);

/*
 * Description
 * The TEE_ResetPersistentObjectEnumerator function resets an object enumerator
 * handle to its initial state after allocation. If an enumeration has been
 * started, it is stopped.
 * This function does nothing if objectEnumerator is TEE_HANDLE_NULL.
 * Parameters
 * • objectEnumerator: The handle to reset
 * Panic Reasons
 * • objectEnumerator is not TEE_HANDLE_NULL and is not a valid handle on an
 *   object enumerator.
 * • If the Implementation detects any other error.
*/
void TEE_ResetPersistentObjectEnumerator(TEE_ObjectEnumHandle objectEnumerator);

/*
 * Description
 * The TEE_StartPersistentObjectEnumerator function starts the enumeration of all
 * the persistent objects in a given Trusted Storage. The object information can
 * be retrieved by calling the function TEE_GetNextPersistentObject repeatedly.
 * Parameters
 * • objectEnumerator: A valid handle on an object enumerator
 * • storageID: The identifier of the storage in which the objects MUST be enumerated.
 *              Possible values are defined in Table 5-2.
 * Return Code
 * • TEE_SUCCESS: In case of success
 * • TEE_ERROR_ITEM_NOT_FOUND: If the storage does not exist or if there is no
 *                             object in the specified storage
 * • TEE_ERROR_CORRUPT_OBJECT: If the storage is corrupt
 * • TEE_ERROR_STORAGE_NOT_AVAILABLE: If the persistent object is stored in a
 *                                    storage area which is currently inaccessible.
 * Panic Reasons
 * • objectEnumerator is not a valid handle on an object enumerator.
 * • If the Implementation detects any other error which is not explicitly
 *   associated with a defined return code for this function.
*/
TEE_Result TEE_StartPersistentObjectEnumerator(TEE_ObjectEnumHandle objectEnumerator, uint32_t storageID);

/*
 * Description
 * The TEE_GetNextPersistentObject function gets the next object in an enumeration
 * and returns information about the object: type, size, identifier, etc.
 * Parameters
 * • objectEnumerator: A handle on the object enumeration
 * • objectInfo: A pointer to a TEE_ObjectInfo filled with the object information
 *               as specified in the function TEE_GetObjectInfo1 in section 5.5.1. (see specification)
 *               It may be NULL.
 * • objectID: Pointer to an array able to hold at least TEE_OBJECT_ID_MAX_LEN bytes.
 *             On exit the object identifier is written to this location
 * • objectIDLen: Filled with the size of the object identifier (from 0 to TEE_OBJECT_ID_MAX_LEN)
 * Return Code
 * • TEE_SUCCESS: In case of success
 * • TEE_ERROR_ITEM_NOT_FOUND: If there are no more elements in the object enumeration
 *                             or if no enumeration is started on this handle
 * • TEE_ERROR_CORRUPT_OBJECT: If the storage or returned object is corrupt
 * • TEE_ERROR_STORAGE_NOT_AVAILABLE: If the persistent object is stored in a storage
 *                                    area which is currently inaccessible.
 * Panic Reasons
 * • objectEnumerator is not a valid handle on an object enumerator.
 * • objectID is NULL.
 * • objectIDLen is NULL.
 * • If the Implementation detects any other error which is not explicitly associated with a defined return code for this function.
*/
TEE_Result TEE_GetNextPersistentObject(TEE_ObjectEnumHandle objectEnumerator, TEE_ObjectInfo* objectInfo, void* objectID, uint32_t* objectIDLen);

/******************************************************************************
* 5.8 Data Stream Access Functions
******************************************************************************/

/*
 * Description
 * The TEE_ReadObjectData function attempts to read size bytes from the data stream
 * associated with the object object into the buffer pointed to by buffer.
 * Parameters
 * • object: The object handle
 * • buffer: A pointer to the memory which, upon successful completion, contains
 *           the bytes read
 * • size: The number of bytes to read
 * • count: A pointer to the variable which upon successful completion contains
 *          the number of bytes read
 * Return Code
 * • TEE_SUCCESS: In case of success
 * • TEE_ERROR_CORRUPT_OBJECT: If the object is corrupt. The object handle is closed.
 * • TEE_ERROR_STORAGE_NOT_AVAILABLE: If the persistent object is stored in a
 *                                    storage area which is currently inaccessible.
 * Panic Reasons
 * • object is not a valid handle on a persistent object opened with the read
 *   access right.
 * • If the Implementation detects any other error which is not explicitly
 *   associated with a defined return code for this function.
*/
TEE_Result TEE_ReadObjectData(TEE_ObjectHandle object, void* buffer, uint32_t size, uint32_t* count);

/*
 * Description
 * The TEE_WriteObjectData function writes size bytes from the buffer pointed to
 * by buffer to the data stream associated with the open object handle object
 * Parameters
 * • object: The object handle
 * • buffer: The buffer containing the data to be written
 * • size: The number of bytes to write
 * Return Code
 * • TEE_SUCCESS: In case of success
 * • TEE_ERROR_STORAGE_NO_SPACE: If insufficient storage space is available
 * • TEE_ERROR_OVERFLOW: If the value of the data position indicator resulting from
 *                       this operation would be greater than TEE_DATA_MAX_POSITION
 * • TEE_ERROR_CORRUPT_OBJECT: If the object is corrupt. The object handle is closed.
 * • TEE_ERROR_STORAGE_NOT_AVAILABLE: If the persistent object is stored in a
 *                                    storage area which is currently inaccessible.
 * Panic Reasons
 * • object is not a valid handle on a persistent object opened with the write
 *   access right.
 * • If the Implementation detects any other error which is not explicitly
 *   associated with a defined return code for this function.
*/
TEE_Result TEE_WriteObjectData(TEE_ObjectHandle object, const void* buffer, uint32_t size);

/*
 * Description
 * The function TEE_TruncateObjectData changes the size of a data stream. If
 * size is less than the current size of the data stream then all bytes beyond
 * size are removed. If size is greater than the current size of the data stream
 * then the data stream is extended by adding zero bytes at the end of the stream.
 * Parameters
 * • object: The object handle
 * • size: The new size of the data stream
 * Return Code
 * • TEE_SUCCESS: In case of success
 * • TEE_ERROR_STORAGE_NO_SPACE: If insufficient storage space is available to
 *                               perform the operation
 * • TEE_ERROR_CORRUPT_OBJECT: If the object is corrupt. The object handle is closed.
 * • TEE_ERROR_STORAGE_NOT_AVAILABLE: If the persistent object is stored in
 *                                    a storage area which is currently inaccessible.
 * Panic Reasons
 * • object is not a valid handle on a persistent object opened with the write
 *   access right.
 * • If the Implementation detects any other error which is not explicitly
 *   associated with a defined return code for this function.
*/
TEE_Result TEE_TruncateObjectData(TEE_ObjectHandle object, uint32_t size);

/*
 * Description
 * The TEE_SeekObjectData function sets the data position indicator associated
 * with the object handle.
 * Parameters
 * • object: The object handle
 * • offset: The number of bytes to move the data position. A positive value moves
 *           the data position forward; a negative value moves the data position backward.
 * • whence: The position in the data stream from which to calculate the new position
 * Return Code
 * • TEE_SUCCESS: In case of success
 * • TEE_ERROR_OVERFLOW: If the value of the data position indicator resulting from
 *                       this operation would be greater than TEE_DATA_MAX_POSITION
 * • TEE_ERROR_CORRUPT_OBJECT: If the object is corrupt. The object handle is closed.
 * • TEE_ERROR_STORAGE_NOT_AVAILABLE: If the persistent object is stored in a storage
 *                                    area which is currently inaccessible.
 * Panic Reasons
 * • object is not a valid handle on a persistent object.
 * • If the Implementation detects any other error which is not explicitly associated
 *   with a defined return code for this function.
*/
TEE_Result TEE_SeekObjectData(TEE_ObjectHandle object, int32_t offset, TEE_Whence whence);

/******************************************************************************
* 6 Cryptographic Operations API
******************************************************************************/

/******************************************************************************
* 6.1 Data Types
******************************************************************************/

typedef enum {
    TEE_MODE_ENCRYPT, // Encryption mode
    TEE_MODE_DECRYPT, // Decryption mode
    TEE_MODE_SIGN,    // Signature generation mode
    TEE_MODE_VERIFY,  // Signature verification mode
    TEE_MODE_MAC,     // MAC mode
    TEE_MODE_DIGEST,  // Digest mode
    TEE_MODE_DERIVE,  // Key derivation mode
} TEE_OperationMode;


typedef struct {
    uint32_t algorithm;
    uint32_t operationClass;
    uint32_t mode;
    uint32_t digestLength;
    uint32_t maxKeySize;
    uint32_t keySize;
    uint32_t requiredKeyUsage;
    uint32_t handleState;
} TEE_OperationInfo;

typedef struct {
    uint32_t keySize;
    uint32_t requiredKeyUsage;
} TEE_OperationInfoKey;

typedef struct {
    uint32_t   algorithm;
    uint32_t   operationClass;
    uint32_t   mode;
    uint32_t   digestLength;
    uint32_t   maxKeySize;
    uint32_t   handleState;
    uint32_t   operationState;
    uint32_t   numberOfKeys;
    TEE_OperationInfoKey keyInformation[];
} TEE_OperationInfoMultiple;

typedef struct __TEE_OperationHandle* TEE_OperationHandle;

/******************************************************************************
* 6.2 Generic Operation Functions
******************************************************************************/

TEE_Result TEE_AllocateOperation( TEE_OperationHandle *operation, uint32_t algorithm, uint32_t mode, uint32_t maxKeySize);
void TEE_FreeOperation( TEE_OperationHandle operation);
void TEE_GetOperationInfo( TEE_OperationHandle operation, TEE_OperationInfo* operationInfo);
TEE_Result TEE_GetOperationInfoMultiple( TEE_OperationHandle operation, TEE_OperationInfoMultiple* operationInfoMultiple, uint32_t* operationSize);
void TEE_ResetOperation( TEE_OperationHandle operation);
TEE_Result TEE_SetOperationKey( TEE_OperationHandle operation, TEE_ObjectHandle key);
TEE_Result TEE_SetOperationKey2( TEE_OperationHandle operation, TEE_ObjectHandle key1, TEE_ObjectHandle key2);
void TEE_CopyOperation( TEE_OperationHandle dstOperation, TEE_OperationHandle srcOperation);

/******************************************************************************
* 6.3 Message Digest Functions
******************************************************************************/

void TEE_DigestUpdate( TEE_OperationHandle operation, const void* chunk, uint32_t chunkSize);
TEE_Result TEE_DigestDoFinal( TEE_OperationHandle operation, const void* chunk, uint32_t chunkLen, void* hash, uint32_t *hashLen);

/******************************************************************************
* 6.4 Symmetric Cipher Functions
******************************************************************************/

void TEE_CipherInit( TEE_OperationHandle operation, const void* IV, uint32_t IVLen);
TEE_Result TEE_CipherUpdate( TEE_OperationHandle operation, const void* srcData, uint32_t srcLen, void* destData, uint32_t *destLen);
TEE_Result TEE_CipherDoFinal( TEE_OperationHandle operation, const void* srcData, uint32_t srcLen, void* destData, uint32_t *destLen);

/******************************************************************************
* 6.5 MAC Functions
******************************************************************************/

void TEE_MACInit( TEE_OperationHandle operation, const void* IV, uint32_t IVLen);
void TEE_MACUpdate( TEE_OperationHandle operation, const void* chunk, uint32_t chunkSize);
TEE_Result TEE_MACComputeFinal( TEE_OperationHandle operation, const void* message, uint32_t messageLen, void* mac, uint32_t *macLen);
TEE_Result TEE_MACCompareFinal( TEE_OperationHandle operation, const void* message, uint32_t messageLen, const void* mac, uint32_t macLen);

/******************************************************************************
* 6.6 Authenticated Encryption Functions
******************************************************************************/

TEE_Result TEE_AEInit(TEE_OperationHandle operation, const void* nonce, uint32_t nonceLen, uint32_t tagLen, uint32_t AADLen, uint32_t payloadLen);
void TEE_AEUpdateAAD(TEE_OperationHandle operation, const void* AADdata, uint32_t AADdataLen);
TEE_Result TEE_AEUpdate(TEE_OperationHandle operation, const void* srcData, uint32_t srcLen, void* destData, uint32_t *destLen);
TEE_Result TEE_AEEncryptFinal(TEE_OperationHandle operation, const void* srcData, uint32_t srcLen, void* destData, uint32_t* destLen, void* tag, uint32_t* tagLen);
TEE_Result TEE_AEDecryptFinal(TEE_OperationHandle operation, const void* srcData, uint32_t srcLen, void* destData, uint32_t *destLen, void* tag, uint32_t tagLen);

/******************************************************************************
* 6.7 Asymmetric Functions
******************************************************************************/

TEE_Result TEE_AsymmetricEncrypt( TEE_OperationHandle operation, const TEE_Attribute* params, uint32_t paramCount, const void* srcData, uint32_t srcLen, void* destData, uint32_t *destLen );

TEE_Result TEE_AsymmetricDecrypt( TEE_OperationHandle operation, const TEE_Attribute* params, uint32_t paramCount, const void* srcData, uint32_t srcLen, void* destData, uint32_t *destLen);
TEE_Result TEE_AsymmetricSignDigest( TEE_OperationHandle operation, const TEE_Attribute* params, uint32_t paramCount, const void* digest, uint32_t digestLen, void* signature, uint32_t *signatureLen );
TEE_Result TEE_AsymmetricVerifyDigest( TEE_OperationHandle operation, const TEE_Attribute* params, uint32_t paramCount, const void* digest, uint32_t digestLen, const void* signature, uint32_t signatureLen);

/******************************************************************************
* 6.8 Key Derivation Functions
******************************************************************************/

void TEE_DeriveKey( TEE_OperationHandle operation, const TEE_Attribute* params, uint32_t paramCount, TEE_ObjectHandle derivedKey);

/******************************************************************************
* 6.9 Random Data Generation Function
******************************************************************************/

void TEE_GenerateRandom(void* randomBuffer, uint32_t randomBufferLen);

/******************************************************************************
* 6.10 Cryptographic Algorithms Specification
******************************************************************************/


typedef enum {
    TEE_ALG_AES_ECB_NOPAD                 = 0x10000010,
    TEE_ALG_AES_CBC_NOPAD                 = 0x10000110,
    TEE_ALG_AES_CTR                       = 0x10000210,
    TEE_ALG_AES_CTS                       = 0x10000310,
    TEE_ALG_AES_XTS                       = 0x10000410,
    TEE_ALG_AES_CBC_MAC_NOPAD             = 0x30000110,
    TEE_ALG_AES_CBC_MAC_PKCS5             = 0x30000510,
    TEE_ALG_AES_CBC_MAC_ISO9797_M2        = 0x30000710,
    TEE_ALG_AES_CMAC                      = 0x30000610,
    TEE_ALG_AES_CCM                       = 0x40000710,
    TEE_ALG_AES_GCM                       = 0x40000810,
    TEE_ALG_DES_ECB_NOPAD                 = 0x10000011,
    TEE_ALG_DES_CBC_NOPAD                 = 0x10000111,
    TEE_ALG_DES_CBC_MAC_NOPAD             = 0x30000111,
    TEE_ALG_DES_CBC_MAC_PKCS5             = 0x30000511,
    TEE_ALG_DES3_ECB_NOPAD                = 0x10000013,
    TEE_ALG_DES3_CBC_NOPAD                = 0x10000113,
    TEE_ALG_DES3_CBC_MAC_NOPAD            = 0x30000113,
    TEE_ALG_DES3_CBC_MAC_PKCS5            = 0x30000513,
    TEE_ALG_RSASSA_PKCS1_V1_5_MD5         = 0x70001830,
    TEE_ALG_RSASSA_PKCS1_V1_5_SHA1        = 0x70002830,
    TEE_ALG_RSASSA_PKCS1_V1_5_SHA224      = 0x70003830,
    TEE_ALG_RSASSA_PKCS1_V1_5_SHA256      = 0x70004830,
    TEE_ALG_RSASSA_PKCS1_V1_5_SHA384      = 0x70005830,
    TEE_ALG_RSASSA_PKCS1_V1_5_SHA512      = 0x70006830,
    TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA1    = 0x70212930,
    TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA224  = 0x70313930,
    TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA256  = 0x70414930,
    TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA384  = 0x70515930,
    TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA512  = 0x70616930,
    TEE_ALG_RSAES_PKCS1_V1_5              = 0x60000130,
    TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA1    = 0x60210230,
    TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA224  = 0x60310230,
    TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA256  = 0x60410230,
    TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA384  = 0x60510230,
    TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA512  = 0x60610230,
    TEE_ALG_RSA_NOPAD                     = 0x60000030,
    TEE_ALG_DSA_SHA1                      = 0x70002131,
    TEE_ALG_DSA_SHA224                    = 0x70003131,
    TEE_ALG_DSA_SHA256                    = 0x70004131,
    TEE_ALG_DH_DERIVE_SHARED_SECRET       = 0x80000032,
    TEE_ALG_MD5                           = 0x50000001,
    TEE_ALG_SHA1                          = 0x50000002,
    TEE_ALG_SHA224                        = 0x50000003,
    TEE_ALG_SHA256                        = 0x50000004,
    TEE_ALG_SHA384                        = 0x50000005,
    TEE_ALG_SHA512                        = 0x50000006,
    TEE_ALG_HMAC_MD5                      = 0x30000001,
    TEE_ALG_HMAC_SHA1                     = 0x30000002,
    TEE_ALG_HMAC_SHA224                   = 0x30000003,
    TEE_ALG_HMAC_SHA256                   = 0x30000004,
    TEE_ALG_HMAC_SHA384                   = 0x30000005,
    TEE_ALG_HMAC_SHA512                   = 0x30000006,
#ifdef ECC_IMPLEMENTATION
    TEE_ALG_ECDSA_P160                    = 0x70000041,          //P160
    TEE_ALG_ECDSA_P192                    = 0x70001041,          //P192
    TEE_ALG_ECDSA_P224                    = 0x70002041,          //P224
    TEE_ALG_ECDSA_P256                    = 0x70003041,          //P256
    TEE_ALG_ECDSA_P384                    = 0x70004041,          //P384
    TEE_ALG_ECDSA_P521                    = 0x70005041,          //P521
    TEE_ALG_ECDH_P192                     = 0x80001042,          //P192
    TEE_ALG_ECDH_P224                     = 0x80002042,          //P224
    TEE_ALG_ECDH_P256                     = 0x80003042,          //P256
    TEE_ALG_ECDH_P384                     = 0x80004042,          //P384
    TEE_ALG_ECDH_P521                     = 0x80005042,          //P521
#endif // ECC_IMPLEMENTATION
#ifdef NON_GP_PADDING
    TEE_ALG_AES_ECB_PKCS5                 = 0x11000010,     // PKCS#5 padding is identical to PKCS#7 padding,
    TEE_ALG_AES_ECB_PKCS7                 = 0x12000010,   // except that it has only been defined for block
    TEE_ALG_AES_CBC_PKCS5                 = 0x11000110,    // ciphers that use a 64 bit (8 byte) block size.
    TEE_ALG_AES_CBC_PKCS7                 = 0x12000110,    // In practice the two can be used interchangeably.
                                    // http://en.wikipedia.org/wiki/Padding_%28cryptography%29#PKCS7

    TEE_ALG_AES_ECB_ISO9797_M1            = 0x13000010,
    TEE_ALG_AES_ECB_ISO9797_M2            = 0x14000010,
    TEE_ALG_AES_CBC_ISO9797_M1            = 0x13000110,
    TEE_ALG_AES_CBC_ISO9797_M2            = 0x14000110,
    TEE_ALG_AES_CTR_NOPAD                 = 0x15000210,
#endif
    TEE_ALG_AES_CFB_128                   = 0x100000C0,    // These algorithms corresponds to 128-bit CFB mode,
    TEE_ALG_AES_CFB_8                     = 0x100000C1,    // the 8-bit CFB mode and the 1-bit CFB mode respectively
    TEE_ALG_AES_CFB_1                     = 0x100000C2,    // and intended to be used with TEE_Cipher* functions family.
                                    // Supported key lengths: 128, 192 and 256 bits.
                                    // For reference, please see NIST SP 800-38A document.
/* NOTE: currently physically contiguous memory is needed for HW crypto (IN and OUT) */
    TEE_ALG_AES_ECB_NOPAD_HW              = 0x100000D0,
    TEE_ALG_AES_CBC_NOPAD_HW              = 0x100001D0,
    TEE_ALG_AES_CTR_HW                    = 0x100002D0,
    TEE_ALG_AES_CTS_HW                    = 0x100003D0,
} TEE_CRYPTO_ALGORITHMS;


typedef enum {
    TEE_TYPE_AES                          = 0xA0000010,
    TEE_TYPE_DES                          = 0xA0000011,
    TEE_TYPE_DES3                         = 0xA0000013, // currently possible key sizes is 128 bits (for real key size 112) and 192 bits (for real key size 168)
    TEE_TYPE_HMAC_MD5                     = 0xA0000001, // "real size" should be understood as key size without parity bits
    TEE_TYPE_HMAC_SHA1                    = 0xA0000002,
    TEE_TYPE_HMAC_SHA224                  = 0xA0000003,
    TEE_TYPE_HMAC_SHA256                  = 0xA0000004,
    TEE_TYPE_HMAC_SHA384                  = 0xA0000005,
    TEE_TYPE_HMAC_SHA512                  = 0xA0000006,
    TEE_TYPE_RSA_PUBLIC_KEY               = 0xA0000030,
    TEE_TYPE_RSA_KEYPAIR                  = 0xA1000030,
    TEE_TYPE_DSA_PUBLIC_KEY               = 0xA0000031,
    TEE_TYPE_DSA_KEYPAIR                  = 0xA1000031,
    TEE_TYPE_DH_KEYPAIR                   = 0xA1000032,
#ifdef ECC_IMPLEMENTATION
    TEE_TYPE_ECDSA_PUBLIC_KEY             = 0xA0000041,
    TEE_TYPE_ECDSA_KEYPAIR                = 0xA1000041,
    TEE_TYPE_ECDH_PUBLIC_KEY              = 0xA0000042,
    TEE_TYPE_ECDH_KEYPAIR                 = 0xA1000042,
#endif // ECC_IMPLEMENTATION
    TEE_TYPE_GENERIC_SECRET               = 0xA0000000,
    TEE_TYPE_CORRUPTED_OBJECT             = 0xA00000BE,
    TEE_TYPE_DATA                         = 0xA00000BF,
    TEE_TYPE_CERT_ROOT_GSL                = 0xA00000A0,     // GPD System Loader root Certificate
    TEE_TYPE_CERT_ROOT_AP                 = 0xA00000A1,     //Application provider root Certificate
    TEE_TYPE_CERT_ROOT_CRL                = 0xA00000A2,     //Certificate type CRL
    TEE_TYPE_CERT_GENERAL_AP1             = 0xA00000A3
    // more for application certificate?
} TEE_OBJECT_TYPES;


/******************************************************************************
*  6.11 Object or Operation Attributes
******************************************************************************/


typedef enum {
    TEE_ATTR_SECRET_VALUE                 = 0xC0000000,
    TEE_ATTR_RSA_MODULUS                  = 0xD0000130,
    TEE_ATTR_RSA_PUBLIC_EXPONENT          = 0xD0000230,
    TEE_ATTR_RSA_PRIVATE_EXPONENT         = 0xC0000330,
    TEE_ATTR_RSA_PRIME1                   = 0xC0000430,
    TEE_ATTR_RSA_PRIME2                   = 0xC0000530,
    TEE_ATTR_RSA_EXPONENT1                = 0xC0000630,
    TEE_ATTR_RSA_EXPONENT2                = 0xC0000730,
    TEE_ATTR_RSA_COEFFICIENT              = 0xC0000830,
    TEE_ATTR_DSA_PRIME                    = 0xD0001031,
    TEE_ATTR_DSA_SUBPRIME                 = 0xD0001131,
    TEE_ATTR_DSA_BASE                     = 0xD0001231,
    TEE_ATTR_DSA_PUBLIC_VALUE             = 0xD0000131,
    TEE_ATTR_DSA_PRIVATE_VALUE            = 0xC0000231,
    TEE_ATTR_DH_PRIME                     = 0xD0001032,
    TEE_ATTR_DH_SUBPRIME                  = 0xD0001132,
    TEE_ATTR_DH_BASE                      = 0xD0001232,
    TEE_ATTR_DH_X_BITS                    = 0xF0001332,
    TEE_ATTR_DH_PUBLIC_VALUE              = 0xD0000132,
    TEE_ATTR_DH_PRIVATE_VALUE             = 0xC0000232,
    TEE_ATTR_RSA_OAEP_LABEL               = 0xD0000930,
    TEE_ATTR_RSA_PSS_SALT_LENGTH          = 0xF0000A30,

#ifdef ECC_IMPLEMENTATION
    TEE_ATTR_ECDSA_PRIME                  = 0xD0001041,
    TEE_ATTR_ECDSA_COFF_A                 = 0xD0001141,
    TEE_ATTR_ECDSA_COFF_B                 = 0xD0001241,
    TEE_ATTR_ECDSA_GENERATOR_X            = 0xD0001341,
    TEE_ATTR_ECDSA_GENERATOR_Y            = 0xD0001441,
    TEE_ATTR_ECDSA_ORDER                  = 0xD0001541,
    TEE_ATTR_ECC_PUBLIC_VALUE_X           = 0xD0000141,
    TEE_ATTR_ECC_PUBLIC_VALUE_Y           = 0xD0000241,
    TEE_ATTR_ECC_PRIVATE_VALUE            = 0xC0000241,
    TEE_ATTR_ECC_CURVE                    = 0xF0000441,
    TEE_ECC_CURVE_NIST_P192               = 0x00000001,
    TEE_ECC_CURVE_NIST_P224               = 0x00000002,
    TEE_ECC_CURVE_NIST_P256               = 0x00000003,
    TEE_ECC_CURVE_NIST_P384               = 0x00000004,
    TEE_ECC_CURVE_NIST_P521               = 0x00000005,
    /*
     * Attribute for signature format in ECDSA.
     * You can use this attribute in functions TEE_AsymmetricSignDigest and TEE_AsymmetricVerifyDigest for ECDSA algorithm.
     * You should set second argument of these function (params) with next attribute type.
     * Value .a of this attribute sets format of signature: two bigints format or ASN.1 format.
     * If you set params to NULL in TEE_AsymmetricSignDigest or TEE_AsymmetricVerifyDigest, two bigints format will be used
     * by default.
     */
    TEE_ATTR_ECDSA_SIGN_FORMAT            = 0xF0001641,
    TEE_ECDSA_SIGN_FORMAT_BIGINT          = 0x80000001,
    TEE_ECDSA_SIGN_FORMAT_ASN             = 0x80000002,

#endif // ECC_IMPLEMENTATION

    TEE_ATTR_DSA_SIGN_FORMAT              = 0xF0001331,
    TEE_DSA_SIGN_FORMAT_BIGINT            = 0x80000001,
    TEE_DSA_SIGN_FORMAT_ASN               = 0x80000002,

    /*
     * This attribute is used for RSA-OAEP encrypt/decrypt and sets hash function for label.
     * Value .a of this attribute sets hash function for label. It may be:
     * - TEE_ALG_SHA1
     * - TEE_ALG_SHA224
     * - TEE_ALG_SHA256
     * - TEE_ALG_SHA384
     * - TEE_ALG_SHA512
     * When this attribute doesn't set, label hash function will be same as MGF hash function.
     */
    TEE_ATTR_RSA_OAEP_LABEL_HASH          = 0xF0001030,

    //Certificate attribute start
    TEE_ATTR_CERT_RAW                     = 0xD0000A01,
    TEE_ATTR_CERT_TBS                     = 0xD0000A02,
    TEE_ATTR_CERT_VERSION                 = 0xF0000A01,
    TEE_ATTR_CERT_SERIAL                  = 0xD0000A03,
    TEE_ATTR_CERT_SIG_OID1                = 0xD0000A04,
    TEE_ATTR_CERT_ISSUER_RAW              = 0xD0000A05,
    TEE_ATTR_CERT_SUBJECT_RAW             = 0xD0000A06,
    TEE_ATTR_CERT_ISSUER                  = 0xD0000A07,
    TEE_ATTR_CERT_SUBJECT                 = 0xD0000A08,
    TEE_ATTR_CERT_VALID_FROM              = 0xD0000A09,
    TEE_ATTR_CERT_VALID_TO                = 0xD0000A0A,
    TEE_ATTR_CERT_PK_OID                  = 0xD0000A0B,
    TEE_ATTR_CERT_ISSUER_ID               = 0xD0000A0C,
    TEE_ATTR_CERT_SUBJECT_ID              = 0xD0000A0D,
    TEE_ATTR_CERT_V3EXT                   = 0xD0000A0E,
    TEE_ATTR_CERT_EXT_TYPE                = 0xF0000A02,
    TEE_ATTR_CERT_CA_ISTRUE               = 0xF0000A03,
    TEE_ATTR_CERT_MAX_PATHLEN             = 0xF0000A04,
    TEE_ATTR_CERT_KEY_USAGE               = 0xF0000A05,
    TEE_ATTR_CERT_EXT_KEY_USAGE           = 0xD0000A0F,
    TEE_ATTR_CERT_KEY_NS_TYPE             = 0xF0000A06,
    TEE_ATTR_CERT_SIG_OID2                = 0xD0000A10,
    TEE_ATTR_CERT_SIG                     = 0xD0000A11,
    TEE_ATTR_CERT_SIG_ALGO                = 0xF0000A07,
    TEE_ATTR_CERT_NEXT_CHAIN              = 0xD0000A12,
    //Certificate attribute end

    TEE_ATTR_FLAG_VALUE                   = 0x20000000,
    TEE_ATTR_FLAG_PUBLIC                  = 0x10000000
} TEE_OBJECT_ATTRIBUTES;




/******************************************************************************
*  7 Time API
******************************************************************************/

/******************************************************************************
*  7.1 Data Types
******************************************************************************/

typedef struct {
    uint32_t seconds;
    uint32_t millis;
}
TEE_Time;

/******************************************************************************
*  7.2 Time Functions
******************************************************************************/

void TEE_GetSystemTime(TEE_Time* time);
TEE_Result TEE_Wait(uint32_t timeout);
TEE_Result TEE_GetTAPersistentTime(TEE_Time* time);
TEE_Result TEE_SetTAPersistentTime(TEE_Time* time);
void TEE_GetREETime(TEE_Time* time);


/******************************************************************************
*  8 TEE Arithmetical API
******************************************************************************/

#define  TEE_BigIntSizeInU32(n)   (((n+31)/32)+2)

/******************************************************************************
*  8.3 Data Types
******************************************************************************/

typedef uint32_t TEE_BigInt;
typedef uint32_t TEE_BigIntFMMContext;
typedef uint32_t TEE_BigIntFMM;


/******************************************************************************
* 8.4 Memory Allocation and Size of Objects
******************************************************************************/

uint32_t TEE_BigIntFMMContextSizeInU32(const uint32_t modulusSizeInBits);
uint32_t TEE_BigIntFMMSizeInU32(const uint32_t modulusSizeInBits);

/******************************************************************************
* 8.5 Initialization Functions
******************************************************************************/

void TEE_BigIntInit(TEE_BigInt* value, const uint32_t length);
void TEE_BigIntInitFMMContext(TEE_BigIntFMMContext* context, const uint32_t len, const TEE_BigInt* modulus);
void TEE_BigIntInitFMM(TEE_BigIntFMM* object, const uint32_t len);

/******************************************************************************
* 8.6 Converter Functions
******************************************************************************/

TEE_Result TEE_BigIntConvertFromOctetString(TEE_BigInt* dest, const uint8_t* buffer, const uint32_t sz_buffer, const int32_t sign);
TEE_Result TEE_BigIntConvertToOctetString(void* buffer, uint32_t* sz_buffer_out, const TEE_BigInt* value);
void TEE_BigIntConvertFromS32(TEE_BigInt* result, int32_t input);
TEE_Result TEE_BigIntConvertToS32(int32_t* result, const TEE_BigInt* input);

/******************************************************************************
* 8.7 Logical Operations
******************************************************************************/

int32_t TEE_BigIntCmp(const TEE_BigInt* op1, const TEE_BigInt* op2);
int32_t TEE_BigIntCmpS32(const TEE_BigInt* value1, int32_t value2);
void TEE_BigIntShiftRight(TEE_BigInt* destination, const TEE_BigInt* source, const uint32_t bits);
bool TEE_BigIntGetBit(const TEE_BigInt* object, uint32_t index);
uint32_t TEE_BigIntGetBitCount(const TEE_BigInt* object);

/******************************************************************************
* 8.8 Basic Arithmetic Operations
******************************************************************************/

void TEE_BigIntAdd(TEE_BigInt* dest, const TEE_BigInt* op1, const TEE_BigInt* op2);
void TEE_BigIntSub(TEE_BigInt* dest, const TEE_BigInt* op1, const TEE_BigInt* op2);
void TEE_BigIntNeg(TEE_BigInt* dest, const TEE_BigInt* op);
void TEE_BigIntMul(TEE_BigInt* dest, const TEE_BigInt* op1, const TEE_BigInt* op2);
void TEE_BigIntSquare(TEE_BigInt* dest, const TEE_BigInt* op);
void TEE_BigIntDiv(TEE_BigInt* dest_q, TEE_BigInt* dest_r, const TEE_BigInt* op1, const TEE_BigInt* op2);

/******************************************************************************
* 8.9 Modular Arithmetic Operations
******************************************************************************/

void TEE_BigIntMod(TEE_BigInt* dest, const TEE_BigInt* op, const TEE_BigInt* n);
void TEE_BigIntAddMod(TEE_BigInt* dest, const TEE_BigInt* op1, const TEE_BigInt* op2, const TEE_BigInt* n);
void TEE_BigIntSubMod(TEE_BigInt* dest, const TEE_BigInt* op1, const TEE_BigInt* op2, const TEE_BigInt* n);
void TEE_BigIntMulMod(TEE_BigInt* dest, const TEE_BigInt* op1, const TEE_BigInt* op2, const TEE_BigInt* n);
void TEE_BigIntSquareMod(TEE_BigInt* dest, const TEE_BigInt* op, const TEE_BigInt* n);
void TEE_BigIntInvMod(TEE_BigInt* dest, const TEE_BigInt* op, const TEE_BigInt* n);

/******************************************************************************
* 8.10 Other Arithmetic Operations
******************************************************************************/

bool TEE_BigIntRelativePrime(const TEE_BigInt* op1, const TEE_BigInt* op2);
void TEE_BigIntComputeExtendedGcd(TEE_BigInt* gcd, TEE_BigInt* u, TEE_BigInt* v, const TEE_BigInt* op1, const TEE_BigInt* op2);
int32_t TEE_BigIntIsProbablePrime(const TEE_BigInt* op, uint32_t confidenceLevel);

/******************************************************************************
* 8.11 Fast Modular Multiplication Operations
******************************************************************************/

void TEE_BigIntConvertToFMM(TEE_BigIntFMM* dest, const TEE_BigInt* src, const TEE_BigInt* n, const TEE_BigIntFMMContext* context);
void TEE_BigIntConvertFromFMM(TEE_BigInt* dest, const TEE_BigIntFMM* src, const TEE_BigInt* n, const TEE_BigIntFMMContext* context);
void TEE_BigIntComputeFMM(TEE_BigIntFMM* dest, const TEE_BigIntFMM* op1, const TEE_BigIntFMM* op2, const TEE_BigInt* n, const TEE_BigIntFMMContext* context);

enum tee_function_id {
    ID_TA_CloseSessionEntryPoint = 0x101,
    ID_TA_CreateEntryPoint = 0x102,
    ID_TA_DestroyEntryPoint = 0x103,
    ID_TA_InvokeCommandEntryPoint = 0x104,
    ID_TA_OpenSessionEntryPoint = 0x105,
    ID_TEE_AllocatePropertyEnumerator = 0x201,
    ID_TEE_FreePropertyEnumerator = 0x202,
    ID_TEE_GetNextProperty = 0x203,
    ID_TEE_GetPropertyAsBinaryBlock = 0x204,
    ID_TEE_GetPropertyAsBool = 0x205,
    ID_TEE_GetPropertyAsIdentity = 0x206,
    ID_TEE_GetPropertyAsString = 0x207,
    ID_TEE_GetPropertyAsU32 = 0x208,
    ID_TEE_GetPropertyAsUUID = 0x209,
    ID_TEE_GetPropertyName = 0x20A,
    ID_TEE_ResetPropertyEnumerator = 0x20B,
    ID_TEE_StartPropertyEnumerator = 0x20C,
    ID_TEE_Panic = 0x301,
    ID_TEE_CloseTASession = 0x401,
    ID_TEE_InvokeTACommand = 0x402,
    ID_TEE_OpenTASession = 0x403,
    ID_TEE_GetCancellationFlag = 0x501,
    ID_TEE_MaskCancellation = 0x502,
    ID_TEE_UnmaskCancellation = 0x503,
    ID_TEE_CheckMemoryAccessRights = 0x601,
    ID_TEE_Free = 0x602,
    ID_TEE_GetInstanceData = 0x603,
    ID_TEE_Malloc = 0x604,
    ID_TEE_MemCompare = 0x605,
    ID_TEE_MemFill = 0x606,
    ID_TEE_MemMove = 0x607,
    ID_TEE_Realloc = 0x608,
    ID_TEE_SetInstanceData = 0x609,
    ID_TEE_CloseObject = 0x701,
    ID_TEE_GetObjectBufferAttribute = 0x702,
    ID_TEE_GetObjectInfo = 0x703,
    ID_TEE_GetObjectValueAttribute = 0x704,
    ID_TEE_RestrictObjectUsage = 0x705,
    ID_TEE_GetObjectInfo1 = 0x706,
    ID_TEE_RestrictObjectUsage1 = 0x707,
    ID_TEE_AllocateTransientObject = 0x801,
    ID_TEE_CopyObjectAttributes = 0x802,
    ID_TEE_FreeTransientObject = 0x803,
    ID_TEE_GenerateKey = 0x804,
    ID_TEE_InitRefAttribute = 0x805,
    ID_TEE_InitValueAttribute = 0x806,
    ID_TEE_PopulateTransientObject = 0x807,
    ID_TEE_ResetTransientObject = 0x808,
    ID_TEE_CopyObjectAttributes1 = 0x809,
    ID_TEE_CloseAndDeletePersistentObject = 0x901,
    ID_TEE_CreatePersistentObject = 0x902,
    ID_TEE_OpenPersistentObject = 0x903,
    ID_TEE_RenamePersistentObject = 0x904,
    ID_TEE_CloseAndDeletePersistentObject1 = 0x905,
    ID_TEE_AllocatePersistentObjectEnumerator = 0xA01,
    ID_TEE_FreePersistentObjectEnumerator = 0xA02,
    ID_TEE_GetNextPersistentObject = 0xA03,
    ID_TEE_ResetPersistentObjectEnumerator = 0xA04,
    ID_TEE_StartPersistentObjectEnumerator = 0xA05,
    ID_TEE_ReadObjectData = 0xB01,
    ID_TEE_SeekObjectData = 0xB02,
    ID_TEE_TruncateObjectData = 0xB03,
    ID_TEE_WriteObjectData = 0xB04,
    ID_TEE_AllocateOperation = 0xC01,
    ID_TEE_CopyOperation = 0xC02,
    ID_TEE_FreeOperation = 0xC03,
    ID_TEE_GetOperationInfo = 0xC04,
    ID_TEE_ResetOperation = 0xC05,
    ID_TEE_SetOperationKey = 0xC06,
    ID_TEE_SetOperationKey2 = 0xC07,
    ID_TEE_GetOperationInfoMultiple = 0xC08,
    ID_TEE_DigestDoFinal = 0xD01,
    ID_TEE_DigestUpdate = 0xD02,
    ID_TEE_CipherDoFinal = 0xE01,
    ID_TEE_CipherInit = 0xE02,
    ID_TEE_CipherUpdate = 0xE03,
    ID_TEE_MACCompareFinal = 0xF01,
    ID_TEE_MACComputeFinal = 0xF02,
    ID_TEE_MACInit = 0xF03,
    ID_TEE_MACUpdate = 0xF04,
    ID_TEE_AEDecryptFinal = 0x1001,
    ID_TEE_AEEncryptFinal = 0x1002,
    ID_TEE_AEInit = 0x1003,
    ID_TEE_AEUpdate = 0x1004,
    ID_TEE_AEUpdateAAD = 0x1005,
    ID_TEE_AsymmetricDecrypt = 0x1101,
    ID_TEE_AsymmetricEncrypt = 0x1102,
    ID_TEE_AsymmetricSignDigest = 0x1103,
    ID_TEE_AsymmetricVerifyDigest = 0x1104,
    ID_TEE_DeriveKey = 0x1201,
    ID_TEE_GenerateRandom = 0x1301,
    ID_TEE_GetREETime = 0x1401,
    ID_TEE_GetSystemTime = 0x1402,
    ID_TEE_GetTAPersistentTime = 0x1403,
    ID_TEE_SetTAPersistentTime = 0x1404,
    ID_TEE_Wait = 0x1405,
    ID_TEE_BigIntFMMContextSizeInU32 = 0x1501,
    ID_TEE_BigIntFMMSizeInU32 = 0x1502,
    ID_TEE_BigIntInit = 0x1601,
    ID_TEE_BigIntInitFMM = 0x1602,
    ID_TEE_BigIntInitFMMContext = 0x1603,
    ID_TEE_BigIntConvertFromOctetString = 0x1701,
    ID_TEE_BigIntConvertFromS32 = 0x1702,
    ID_TEE_BigIntConvertToOctetString = 0x1703,
    ID_TEE_BigIntConvertToS32 = 0x1704,
    ID_TEE_BigIntCmp = 0x1801,
    ID_TEE_BigIntCmpS32 = 0x1802,
    ID_TEE_BigIntGetBit = 0x1803,
    ID_TEE_BigIntGetBitCount = 0x1804,
    ID_TEE_BigIntShiftRight = 0x1805,
    ID_TEE_BigIntAdd = 0x1901,
    ID_TEE_BigIntDiv = 0x1902,
    ID_TEE_BigIntMul = 0x1903,
    ID_TEE_BigIntNeg = 0x1904,
    ID_TEE_BigIntSquare = 0x1905,
    ID_TEE_BigIntSub = 0x1906,
    ID_TEE_BigIntAddMod = 0x1A01,
    ID_TEE_BigIntInvMod = 0x1A02,
    ID_TEE_BigIntMod = 0x1A03,
    ID_TEE_BigIntMulMod = 0x1A04,
    ID_TEE_BigIntSquareMod = 0x1A05,
    ID_TEE_BigIntSubMod = 0x1A06,
    ID_TEE_BigIntComputeExtendedGcd = 0x1B01,
    ID_TEE_BigIntIsProbablePrime = 0x1B02,
    ID_TEE_BigIntRelativePrime = 0x1B03,
    ID_TEE_BigIntComputeFMM = 0x1C01,
    ID_TEE_BigIntConvertFromFMM = 0x1C02,
    ID_TEE_BigIntConvertToFMM = 0x1C03,
};

#ifdef  __cplusplus
}
#endif

#endif // _TEE_INTERNAL_API_H
