void clDifferenceVectorCopy(ClDifferenceVectorT *dest, ClDifferenceVectorT *src)
{
    if(!dest || !src) return;
    memcpy(dest, src, sizeof(*dest));
    if(src->dataVectors)
    {
        if(src->numDataVectors)
        {
            dest->dataVectors = (ClDataVectorT*) clHeapCalloc(src->numDataVectors, sizeof(*dest->dataVectors));
            CL_ASSERT(dest->dataVectors != NULL);
            memcpy(dest->dataVectors, src->dataVectors,
                   sizeof(*dest->dataVectors) * src->numDataVectors);
        }
        else dest->dataVectors = NULL;
    }
    else dest->numDataVectors = 0;
    if(src->md5List)
    {
        if(src->md5Blocks)
        {
            dest->md5List = (ClMD5T*) clHeapCalloc(src->md5Blocks, sizeof(*dest->md5List));
            CL_ASSERT(dest->md5List != NULL);
            memcpy(dest->md5List, src->md5List, sizeof(*dest->md5List) * src->md5Blocks);
        }
        else dest->md5List = NULL;
    }
    else dest->md5Blocks = 0;

}
ClRcT
clTestSectionCreate(ClCkptHdlT  ckptHdl, 
                    ClUint32T   sectionIdx)
{
    ClRcT                             rc            = CL_OK;
    ClCkptSectionCreationAttributesT  secCreateAttr = {0};

    secCreateAttr.sectionId = clHeapCalloc(1, sizeof(ClCkptSectionIdT));
    if( NULL == secCreateAttr.sectionId ) 
    {
        return CL_OK;
    }
    secCreateAttr.expirationTime = CL_TIME_END;
    secCreateAttr.sectionId->id = clHeapCalloc(1, 15);
    if( NULL == secCreateAttr.sectionId->id ) 
    {
        clHeapFree(secCreateAttr.sectionId);
        return CL_OK;
    }
    snprintf((ClCharT *) secCreateAttr.sectionId->id,15, "section%d", sectionIdx);
    secCreateAttr.sectionId->idLen = strlen((ClCharT *) secCreateAttr.sectionId->id) + 1; 
    rc = clCkptSectionCreate(ckptHdl, &secCreateAttr, NULL, 0);
    if( CL_OK != rc )
    {
        return rc;
    }
    clHeapFree(secCreateAttr.sectionId->id);
    clHeapFree(secCreateAttr.sectionId);
    return CL_OK;
}
ClRcT
clLogCompEntryUnpackNAdd(ClBufferHandleT        msg,
                         ClLogStreamOwnerDataT  *pStreamOwnerData)
{
    ClRcT             rc        = CL_OK;
    ClLogCompKeyT     compKey   = {0};
    ClLogCompKeyT     *pCompKey = NULL;
    ClLogSOCompDataT  compData  = {0};
    ClLogSOCompDataT  *pData    = NULL;

    CL_LOG_DEBUG_TRACE(("Enter"));

    rc = VDECL_VER(clXdrUnmarshallClLogCompKeyT, 4, 0, 0)(msg, &compKey);
    if( CL_OK != rc )
    {
        CL_LOG_DEBUG_ERROR(("VDECL_VER(clXdrUnmarshallClLogCompKeyT, 4, 0, 0)(): rc[0x %x]", rc));
        return rc;
    }
    rc = VDECL_VER(clXdrUnmarshallClLogSOCompDataT, 4, 0, 0)(msg, &compData);
    if( CL_OK != rc )
    {
        CL_LOG_DEBUG_ERROR(("VDECL_VER(clXdrUnmarshallClLogSOCompDataT, 4, 0, 0)(): rc[0x %x]", rc));    
        return rc;
    }

    pCompKey = (ClLogCompKeyT*)clHeapCalloc(1, sizeof(ClLogCompKeyT));
    if( NULL == pCompKey )
    {
        CL_LOG_DEBUG_ERROR(( "clHeapCalloc()"));
        return CL_LOG_RC(CL_ERR_NO_MEMORY);
    }    
    *pCompKey = compKey;
    CL_LOG_DEBUG_VERBOSE(("compKey.nodeAddress: %u", compKey.nodeAddr));
    CL_LOG_DEBUG_VERBOSE(("compKey.compId     : %u", compKey.compId));

    pData = (ClLogSOCompDataT*)clHeapCalloc(1, sizeof(ClLogSOCompDataT));
    if( NULL == pData )
    {
        CL_LOG_DEBUG_ERROR(( "clHeapCalloc()"));
        clHeapFree(pCompKey);
        return CL_LOG_RC(CL_ERR_NO_MEMORY);
    }    
    *pData = compData;
    CL_LOG_DEBUG_VERBOSE(("compData.refCount    : %u", pData->refCount));
    CL_LOG_DEBUG_VERBOSE(("compData.ackerCnt    : %u", pData->ackerCnt));
    CL_LOG_DEBUG_VERBOSE(("compData.nonAckerCnt : %u", pData->nonAckerCnt));

    rc = clCntNodeAdd(pStreamOwnerData->hCompTable, 
                      (ClCntKeyHandleT) pCompKey,
                      (ClCntDataHandleT) pData, NULL);
    if( CL_OK != rc )
    {
        CL_LOG_DEBUG_ERROR(( "clCntNodeAdd(): rc[0x %x]", rc));
        clHeapFree(pData);
        clHeapFree(pCompKey);
    }

    CL_LOG_DEBUG_TRACE(("Exit"));
    return CL_OK;
}
ClRcT clCpmNodeNameGet(ClUint32T argc, ClCharT *argv[], ClCharT **retStr)
{
    ClRcT rc = CL_OK;
    ClNameT nodeName={0};
    *retStr = NULL;
    if(argc > 1 )
    {
        ClCharT tempStr[0x100];
        rc = CL_CPM_RC(CL_ERR_INVALID_PARAMETER);
        snprintf(tempStr, sizeof(tempStr),
                 "Usage: nodename\n");
        *retStr = (ClCharT *) clHeapAllocate(strlen(tempStr) + 1);
        if (*retStr)
            strcpy(*retStr, tempStr);
        goto out;
    }
    rc = clCpmLocalNodeNameGet(&nodeName);
    if(rc != CL_OK)
    {
        rc = CL_CPM_RC(CL_ERR_UNSPECIFIED);
        goto out;
    }
    *retStr = clHeapCalloc(1,nodeName.length+1);
    if(!*retStr)
    {
        rc = CL_CPM_RC(CL_ERR_NO_MEMORY);
        goto out;
    }
    strncpy(*retStr,nodeName.value,nodeName.length);
    rc = CL_OK;

    out:
    return rc;
}
ClRcT
clBitmap2BufferGet(ClBitmapHandleT  hBitmap,
                   ClUint32T        *pListLen,
                   ClUint8T         **ppPositionList)
{
    ClBitmapInfoT  *pBitmapInfo = hBitmap;
    ClRcT          rc           = CL_OK;

    if( CL_BM_INVALID_BITMAP_HANDLE == hBitmap )
    {
        CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("Invalid Handle"));
        return CL_BITMAP_RC(CL_ERR_INVALID_HANDLE);
    }

    rc = clOsalMutexLock(pBitmapInfo->bitmapLock);
    if( CL_OK != rc )
    {
        CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("clOsalMutexLock() rc: %x", rc)); 
        return rc;
    }
    *ppPositionList = clHeapCalloc(pBitmapInfo->nBytes, sizeof(ClUint8T));
    if( NULL == *ppPositionList )
    {
        CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("clHeapCalloc()"));
        clOsalMutexUnlock(pBitmapInfo->bitmapLock);
        return rc;
    }
    memcpy(*ppPositionList, pBitmapInfo->pBitmap, pBitmapInfo->nBytes);
    *pListLen = pBitmapInfo->nBytes;

    clOsalMutexUnlock(pBitmapInfo->bitmapLock);
    CL_DEBUG_PRINT(CL_DEBUG_TRACE, ("Exit"));
    return rc;
}
ClRcT
clNameSvcEntryDeserializer(ClUint32T  dsId,
                           ClAddrT    pBuffer,
                           ClUint32T  size,
                           ClPtrT cookie)
{
    ClRcT           rc            = CL_OK;
    ClNsEntryPackT  *pNsEntryInfo = (ClNsEntryPackT *)cookie;
    
    CL_NAME_DEBUG_TRACE(("Enter"));
    
    memcpy(&pNsEntryInfo->type, pBuffer, sizeof(pNsEntryInfo->type));
    pBuffer += sizeof(pNsEntryInfo->type);
    memcpy(&pNsEntryInfo->nsInfo, pBuffer, sizeof(ClNameSvcInfoIDLT));
    pBuffer += sizeof(ClNameSvcInfoIDLT);
    if( pNsEntryInfo->nsInfo.attrCount > 0 )
    {
       pNsEntryInfo->nsInfo.attr = clHeapCalloc(pNsEntryInfo->nsInfo.attrLen,
                                                sizeof(ClCharT));
       if( NULL == pNsEntryInfo->nsInfo.attr )
       {
            CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("clHeapCalloc(): "));        
            return CL_NS_RC(CL_ERR_NO_MEMORY);
       }    
       memcpy(pNsEntryInfo->nsInfo.attr, pBuffer,
               pNsEntryInfo->nsInfo.attrLen);
    }    

    CL_NAME_DEBUG_TRACE(("Exit"));
    return rc;
}    
static ClUint32T differenceVectorGet(ClDifferenceVectorKeyT *key, ClUint8T *data, ClOffsetT offset, ClSizeT size,
                                     ClDifferenceVectorT *vector, ClBoolT copyData,
                                     ClDifferenceBlockT **pBlock)
{
    ClDifferenceBlockT *block;
    block = differenceVectorAdd(key, NULL);
    CL_ASSERT(block != NULL);
    if(pBlock) *pBlock = block;
    /*
     * Store the data too if enabled. Heavy though coz of duplication.
     */
    if(copyData)
    {
        if(block->size < offset+size)
        {
            if(block->data) clHeapFree(block->data);
            block->data = (ClUint8T*) clHeapCalloc(1, offset+size);
            CL_ASSERT(block->data != NULL);
            block->size = offset+size;
        }
        if(block->data)
            memcpy(block->data + offset, data + offset, size);
    }
    return __differenceVectorGet(block, data, offset, size, vector);
}
ClRcT
clLogStreamOwnerEntrySerialiser(ClUint32T  dsId,
                                ClAddrT    *pBuffer,
                                ClUint32T  *pSize,
                                ClPtrT     cookie)
{
    ClRcT      rc          = CL_OK;
    ClBufferHandleT  msg = (ClBufferHandleT) cookie;

    CL_LOG_DEBUG_TRACE(("Enter"));

    rc = clBufferLengthGet(msg, pSize);
    if( CL_OK != rc )
    {
        CL_LOG_DEBUG_ERROR(("clBufferLengthGet(): rc[0x %x]", rc));
        return rc;
    }
    *pBuffer = (ClAddrT)clHeapCalloc(*pSize, sizeof(ClUint8T));
    if( NULL == *pBuffer )
    {
        CL_LOG_DEBUG_ERROR(("clHeapCalloc()"));
        return rc;
    }    
    rc = clBufferNBytesRead(msg, (ClUint8T *) *pBuffer, pSize); 
    if( CL_OK != rc )
    {
        CL_LOG_DEBUG_ERROR(("clBufferNBytesRead(): rc[0x %x]", rc));
        clHeapFree(*pBuffer);
        return rc;
    }
        
    CL_LOG_DEBUG_TRACE(("Exit"));
    return rc;
}    
static ClRcT clCorDeltaDbContAdd(ClCorDeltaSaveKeyT *deltaDbKey, ClDBRecordT deltaDbData, ClUint32T dataSize)
{
	ClRcT	rc = CL_OK;
	ClCorDeltaSaveKeyT *tempKey = deltaDbKey;
	ClCorDeltaContDataT *tempCont = clHeapCalloc(1, sizeof(ClCorDeltaContDataT));

    CL_ASSERT(tempCont != NULL);

    tempCont->data = deltaDbData;
    tempCont->dataSize = dataSize;

    if( tempKey == NULL || tempCont->data == NULL)
    {
		clLogWrite(CL_LOG_HANDLE_APP, CL_LOG_DEBUG, NULL,
				CL_LOG_MESSAGE_0_MEMORY_ALLOCATION_FAILED);
		CL_DEBUG_PRINT(CL_DEBUG_ERROR,(CL_COR_ERR_STR(CL_COR_ERR_NO_MEM)));
		return CL_COR_SET_RC(CL_COR_ERR_NO_MEM);
    }

    rc = clCntNodeAdd(gCorDeltaSaveKeyTable, (ClCntKeyHandleT) tempKey, (ClCntDataHandleT) tempCont , NULL);
    if(CL_OK != rc)
    {
        if (CL_GET_ERROR_CODE(rc) == CL_ERR_DUPLICATE)
            rc = CL_OK;
        else
            CL_COR_RETURN_ERROR(CL_DEBUG_ERROR, "Could not add node in the Delta Save Key Table", rc);    

        clHeapFree(tempCont);
    }  
	
	return rc;
}
static ClDifferenceBlockT *differenceVectorAdd(ClDifferenceVectorKeyT *key,
                                               ClBoolT *lastStatus)
{
    ClDifferenceBlockT *block;
    ClUint32T hashKey = 0;
    ClBoolT status = CL_TRUE;

    block = differenceVectorFind(key, &hashKey);
    if(!block)
    {
        block = (ClDifferenceBlockT *) clHeapCalloc(1, sizeof(*block));
        CL_ASSERT(block != NULL);
        block->key.groupKey = clStringDup(key->groupKey);
        CL_ASSERT(block->key.groupKey != NULL);
        block->key.sectionKey = clStringDup(key->sectionKey);
        CL_ASSERT(block->key.sectionKey != NULL);
        hashAdd(differenceVectorTable, hashKey, &block->hash);
        status = CL_FALSE;
    }

    if(lastStatus)
        *lastStatus = status;

    return block;
}
ClRcT
clHandleWithAddressCreate (
                ClHandleDatabaseHandleT databaseHandle,
                ClInt32T instance_size,
                ClIocPhysicalAddressT compAddr,
                ClHandleT *handle_out)
{
  ClWordT        idx       = 0;
  void           *instance    = NULL;
  ClRcT          rc           = CL_OK;
  ClHdlDatabaseT *hdbp        = (ClHdlDatabaseT*) databaseHandle;

  nullChkRet(handle_out);
  hdlDbValidityChk(hdbp);

  instance = clHeapCalloc (1, instance_size);
  if (instance == NULL)
    {
      rc = CL_HANDLE_RC(CL_ERR_NO_MEMORY);
      return rc;
    }

  rc =  clHandleAdd (databaseHandle, instance, &compAddr, handle_out);
  idx = CL_HDL_IDX(*handle_out)-1;

  hdbp->handles[idx].flags = HANDLE_ALLOC_FLAG;

  if (rc != CL_OK)
  {
      clHeapFree(instance);
  }
  return rc;
}
/*
 * The operations for the FILE type backing storage.
 */
ClRcT clBackingStorageInitFile(const ClBackingStorageAttributesT *pAttr, ClPtrT *pPrivateData)
{
    ClBackingStorageAttributesFileT *pFileAttr = NULL;
    ClRcT rc = CL_BACKING_STORAGE_RC(CL_ERR_LIBRARY);
    ClFdT fd = -1;

    fd = open(pAttr->location, pAttr->mode, 0666);
    if(fd < 0)
    {
        clLogError(CL_LOG_AREA_BACKING_STORAGE, CL_LOG_CONTEXT_INIT_FILE, "open failed with error [%s]", strerror(errno));
        goto out;
    }
    rc = CL_BACKING_STORAGE_RC(CL_ERR_NO_MEMORY);
    pFileAttr = (ClBackingStorageAttributesFileT *) clHeapCalloc(1, sizeof(*pFileAttr));
    if(!pFileAttr)
    {
        clLogError(CL_LOG_AREA_BACKING_STORAGE, CL_LOG_CONTEXT_INIT_FILE, "No memory");
        goto out;
    }
    memcpy(&pFileAttr->baseAttr, pAttr, sizeof(pFileAttr->baseAttr));
    pFileAttr->fd = fd;
    *pPrivateData = (ClPtrT)pFileAttr;
    rc = CL_OK;
    out:
    return rc;
}
static ClRcT fileEntryRecoverBaseVersion(ClLogMasterEoDataT *pMasterEoEntry,
        ClBufferHandleT hFileEntryBuf)
{
    ClRcT rc = CL_OK;
    ClLogFileKeyT        fileKey       = {{0}};
    ClLogFileKeyT        *pFileKey     = NULL;
    ClLogFileDataT       *pFileData    = NULL;

    rc = clLogMasterFileKeyUnpack(&fileKey, hFileEntryBuf);
    if( CL_OK != rc )
    {
        return rc;
    }
    clLogInfo(CL_LOG_AREA_MASTER, CL_LOG_CTX_CKPT_READ,
              "Recreating files fileName: %.*s fileLocation: %.*s",
              fileKey.fileName.length, fileKey.fileName.pValue,
              fileKey.fileLocation.length, fileKey.fileLocation.pValue);

    rc = clLogFileKeyCreate(&fileKey.fileName, &fileKey.fileLocation,
                            pMasterEoEntry->maxFiles, &pFileKey);
    if( CL_OK != rc )
    {
        clHeapFree(fileKey.fileName.pValue);
        clHeapFree(fileKey.fileLocation.pValue);
        return rc;
    }
    clHeapFree(fileKey.fileName.pValue);
    clHeapFree(fileKey.fileLocation.pValue);

    /* find out the filelocation is available */
    pFileData = (ClLogFileDataT*) clHeapCalloc(1, sizeof(ClLogFileDataT));
    if( NULL == pFileData )
    {
        CL_LOG_DEBUG_ERROR(("clHeapCalloc()"));
        clLogFileKeyDestroy(pFileKey);
        return rc;
    }

    pFileData->nActiveStreams = 0;
    rc = clLogMasterFileDataRecreate(pFileData, hFileEntryBuf);
    if( CL_OK != rc )
    {
        clLogFileKeyDestroy(pFileKey);
        return rc;
    }

    rc = clCntNodeAdd(pMasterEoEntry->hMasterFileTable,
                      (ClCntKeyHandleT) pFileKey,
                      (ClCntDataHandleT) pFileData, NULL);
    if( CL_OK != rc )
    {
        CL_LOG_DEBUG_ERROR(("clCntNodeAdd()"));
        CL_LOG_CLEANUP(clCntDelete(pFileData->hStreamTable), CL_OK); //FIXME
        clHeapFree(pFileData);
        clLogFileKeyDestroy(pFileKey);
        return rc;
    }

    return rc;
}
static ClRcT
clLogMasterFileEntrySecIdGet(ClLogFileKeyT     *pFileKey,
                             ClCkptSectionIdT  *pSecId)
{
    ClRcT rc = CL_OK;

    CL_LOG_DEBUG_TRACE(("Enter: namelen: %u locationlen: %u",
                        pFileKey->fileName.length,
                        pFileKey->fileLocation.length));

    CL_LOG_PARAM_CHK((NULL == pFileKey->fileName.pValue),
                     CL_LOG_RC(CL_ERR_NULL_POINTER));
    CL_LOG_PARAM_CHK((NULL == pFileKey->fileLocation.pValue),
                     CL_LOG_RC(CL_ERR_NULL_POINTER));
    CL_LOG_PARAM_CHK((NULL == pSecId), CL_LOG_RC(CL_ERR_NULL_POINTER));

    /*
     * ClString: Assuming length includes NULL terminator also.
     * So we idLen will include 2 more than the characters.
     * One we will use for / so we need to decrement it by 1
     */
    pSecId->idLen = pFileKey->fileName.length + pFileKey->fileLocation.length + 1;
    pSecId->id    = (ClUint8T*) clHeapCalloc(pSecId->idLen, sizeof(ClCharT));
    if( NULL == pSecId->id )
    {
        CL_LOG_DEBUG_ERROR(("clHeapCalloc()"));
        return CL_LOG_RC(CL_ERR_NO_MEMORY);
    }
    snprintf((ClCharT *) pSecId->id, pSecId->idLen, "%s/%s", pFileKey->fileLocation.pValue,
             pFileKey->fileName.pValue);

    CL_LOG_DEBUG_TRACE(("Exit [%*s]", pSecId->idLen, pSecId->id));
    return rc;
}
static ClRcT clAmsEntityTrigger(ClAmsEntityTriggerT *pEntityTrigger,
                                ClMetricIdT id,
                                ClBoolT reset)
{
    ClAmsEntityTriggerT *pEntityTriggerRecovery = NULL;
    ClRcT rc = CL_OK;
    pEntityTriggerRecovery = (ClAmsEntityTriggerT*) clHeapCalloc(1, sizeof(*pEntityTriggerRecovery));
    CL_ASSERT(pEntityTriggerRecovery != NULL);
    /*
     *Safe w.r.t deletes behind our back while the trigger is running from the recovery queue.
     */
    memcpy(pEntityTriggerRecovery, pEntityTrigger, sizeof(*pEntityTrigger));
    pEntityTriggerRecovery->recoveryThresholdId = id;
    if(reset == CL_TRUE)
    {
        ClMetricIdT start = id;
        ClMetricIdT end = (ClMetricIdT) (start+1);
        register ClInt32T i;
        if(start == CL_METRIC_ALL)
        {
            start = (ClMetricIdT) (start+1);
            end = CL_METRIC_MAX;
        }
        for(i = start; i < end; ++i)
        {
            pEntityTriggerRecovery->thresholds[i].recoveryReset = CL_TRUE;
        }
    }

    rc = clAmsEntityTriggerRecoveryListAdd(pEntityTriggerRecovery);
    return rc;
}
ClStringT *clStringDup(const ClStringT *str)
{
    ClStringT *dest;
    if(!str) return NULL;
    dest = (ClStringT *) clHeapCalloc(1, sizeof(*dest));
    if(!dest) return NULL;
    dest->pValue = (ClCharT*) clHeapCalloc(str->length, sizeof(*dest->pValue));
    if(!dest->pValue)
    {
        clHeapFree(dest);
        return NULL;
    }
    if(str->pValue)
        memcpy(dest->pValue, str->pValue, str->length);
    dest->length = str->length;
    return dest;
}
ClRcT
clTestCheckpointReadWithOffSet(ClCkptHdlT  ckptHdl,
               ClUint32T   numSections)
{
    ClRcT           rc = CL_OK;
    ClUint32T       i = 0;
    ClCkptIOVectorElementT  iov[numSections];
    ClUint32T               readIdx = 0;

    memset(iov, 0, numSections * sizeof(ClCkptIOVectorElementT));
    for( i = 0; i < numSections; i++ )
    {
        if( numSections != 1 )
        {
            iov[i].sectionId.id = clHeapCalloc(1, 15);
            if( NULL == iov[i].sectionId.id )
            {   
                return CL_OK;
            }
            snprintf( (ClCharT *) iov[i].sectionId.id, 15,"section%d", i);
            iov[i].sectionId.idLen = strlen((ClCharT *) iov[i].sectionId.id) + 1;
        }
        iov[i].dataSize = 30;
        if( NULL != (iov[i].dataBuffer = clHeapCalloc(1, iov[i].dataSize)) )
        {
            iov[i].dataBuffer = NULL;
        }
        iov[i].readSize = 0;
        iov[i].dataOffset = 20;
    }
            rc = clCkptCheckpointRead(ckptHdl, iov, numSections, &readIdx); 
            if( CL_OK != rc )
            {
                return rc;
            }
    for( i = 0; i < numSections; i++ )
    {
        if( NULL != iov[i].sectionId.id ) 
        {
            clHeapFree(iov[i].sectionId.id);
        }
            clHeapFree(iov[i].dataBuffer);
    }
    return CL_OK;
}
ClRcT
clLogClntFileKeyCreate(ClCharT           *fileName,
                       ClCharT           *fileLocation,
                       ClLogClntFileKeyT  **pFileKey)
{
    ClRcT  rc = CL_OK;

    CL_LOG_DEBUG_TRACE(("Enter"));

    *pFileKey = clHeapCalloc(1, sizeof(ClLogClntFileKeyT));
    if( NULL == *pFileKey )
    {
        CL_LOG_DEBUG_ERROR(("clHeapCalloc()"));
        return CL_LOG_RC(CL_ERR_NO_MEMORY);
    }

    (*pFileKey)->fileName.length = strlen(fileName) + 1;
    (*pFileKey)->fileName.pValue = clHeapCalloc((*pFileKey)->fileName.length,
                                                sizeof(ClCharT));
    if( NULL == (*pFileKey)->fileName.pValue )
    {
        CL_LOG_DEBUG_ERROR(("clHeapCalloc()"));
        clHeapFree(*pFileKey);
        return CL_LOG_RC(CL_ERR_NO_MEMORY);
    }

    (*pFileKey)->fileLocation.length = strlen(fileLocation) + 1;
    (*pFileKey)->fileLocation.pValue = clHeapCalloc((*pFileKey)->fileLocation.length,
                                                    sizeof(ClCharT));
    if( NULL == (*pFileKey)->fileLocation.pValue )
    {
        CL_LOG_DEBUG_ERROR(("clHeapCalloc()"));
        clHeapFree((*pFileKey)->fileName.pValue);
        clHeapFree(*pFileKey);
        return CL_LOG_RC(CL_ERR_NO_MEMORY);
    }

    strncpy((*pFileKey)->fileName.pValue, fileName,
            (*pFileKey)->fileName.length);
    strncpy((*pFileKey)->fileLocation.pValue, fileLocation,
            (*pFileKey)->fileLocation.length);
          
    CL_LOG_DEBUG_TRACE(("Exit"));
    return rc;
}
ClCharT *clStrdup(const ClCharT *str)
{
    ClCharT *dest = NULL;
    if(!str) return NULL;
    dest = (ClCharT *) clHeapCalloc(1, strlen(str)+1);
    if(!dest) return NULL;
    strcpy(dest, str);
    return dest;
}
/* A helper function so that we can someday queue unused ClJobTs instead of constantly alloc/dealloc */
static ClJobT* getJob(ClJobQueueT* hdl, ClCallbackT job,ClPtrT data)
{
    ClJobT* ret = (ClJobT*) clHeapCalloc(1, sizeof(ClJobT));
    if (ret)
    {
        ret->job  = job;
        ret->data = data;
    }
    return ret;
}
ClUint32T clGetTable ( ClSnmpReqInfoT* reqInfo,
        void* data, 
        ClInt32T* pErrCode)
{
    ClMedOpT        opInfo;
    ClMedVarBindT   *tempVarInfo = NULL;
    ClInt32T        errorCode = CL_OK;
    ClInt32T        retVal = 0;
    ClCharT         oid[CL_SNMP_DISPLAY_STRING_SIZE];

    opInfo.varCount = 1;
    tempVarInfo =
        (ClMedVarBindT *) clHeapCalloc(1,opInfo.varCount * sizeof (ClMedVarBindT));   
    if (tempVarInfo == NULL)
    {
        clLogError("SNM","OPE", "Failed while allocating the varbind.");
        return (CL_RC(CL_CID_SNMP, CL_ERR_NO_MEMORY));
    }
    retVal = 0;
    strcpy(oid, reqInfo->oid);
    /*oid received till this point is that of the table. Add .1.1 to 
      get oid of the first entry in the table
     */
    strcat(oid,".1.1");

    opInfo.varInfo = tempVarInfo;
    opInfo.varInfo[0].pVal = data;
    opInfo.varInfo[0].errId = 0;
    opInfo.varInfo[0].pInst = reqInfo;
    opInfo.opCode = reqInfo->opCode;
    opInfo.varInfo[0].attrId.id = (ClUint8T*)oid;
    opInfo.varInfo[0].attrId.len = (ClUint32T)strlen(oid) + 1;
    opInfo.varInfo[0].len = reqInfo->dataLen;

    errorCode = clMedOperationExecute (gSubAgentInfo.medHdl, &opInfo);

    if ((opInfo.varInfo[0].errId == 0) && (errorCode == 0))
    {
        clHeapFree (tempVarInfo);
        return (CL_OK);
    }
    else
    {
        if (errorCode != CL_OK)
            *pErrCode = errorCode;
        else
            *pErrCode = opInfo.varInfo[0].errId;

        clLogError(CL_LOG_AREA_UNSPECIFIED,CL_LOG_CONTEXT_UNSPECIFIED,
                   "clMedOperationExecute returned error. error code = %x, error id = %d",
                   errorCode, opInfo.varInfo[0].errId);
    }
    clHeapFree (tempVarInfo);
    return (errorCode);
}
ClRcT clTransportNotifyRegister(ClTransportNotifyCallbackT callback, ClPtrT arg)
{
    ClTransportNotifyRegistrantT *registrant = NULL;
    if(!callback) return CL_ERR_INVALID_PARAMETER;
    registrant = clHeapCalloc(1, sizeof(*registrant));
    CL_ASSERT(registrant != NULL);
    registrant->callback = callback;
    registrant->arg = arg;
    clListAddTail(&registrant->list, &gClXportNotifyRegistrants);
    return CL_OK;
}
ClRcT
clLogMasterCompData2BufferGet(ClLogCompDataT  *pCompData,
                              ClUint8T        **ppBuffer,
                              ClUint32T       *pDataSize)
{
    ClRcT            rc  = CL_OK;
    ClBufferHandleT  msg = CL_HANDLE_INVALID_VALUE;

    CL_LOG_DEBUG_TRACE(("Enter"));

    rc = clBufferCreate(&msg);
    if(CL_OK != rc )
    {
        CL_LOG_DEBUG_ERROR(("clBufferCreate(): rc[0x %x]", rc));
        return rc;
    }

    rc = VDECL_VER(clXdrMarshallClLogCompDataT, 4, 0, 0)(pCompData, msg, 0);
    if( CL_OK != rc )
    {
        CL_LOG_DEBUG_ERROR(("clLogMarshallClLogCompDataT(): rc[0x %x]", rc));
        CL_LOG_CLEANUP(clBufferDelete(&msg), CL_OK);
        return rc;
    }

    rc = clBufferLengthGet(msg, pDataSize);
    if( CL_OK != rc )
    {
        CL_LOG_DEBUG_ERROR(("clBufferLengthGet(): rc[0x %x]", rc));
        CL_LOG_CLEANUP(clBufferDelete(&msg), CL_OK);
        return rc;
    }

    *ppBuffer = (ClUint8T*) clHeapCalloc(*pDataSize, sizeof(ClUint8T));
    if( NULL == *ppBuffer )
    {
        CL_LOG_DEBUG_ERROR(("clHeapCalloc()"));
        CL_LOG_CLEANUP(clBufferDelete(&msg), CL_OK);
        return CL_LOG_RC(CL_ERR_NO_MEMORY);
    }

    rc = clBufferNBytesRead(msg, *ppBuffer, pDataSize);
    if( CL_OK != rc )
    {
        CL_LOG_DEBUG_ERROR(("clBufferNBytesRead(): rc[0x %x]", rc));
        clHeapFree(*ppBuffer);
        CL_LOG_CLEANUP(clBufferDelete(&msg), CL_OK);
        return rc;
    }
    CL_LOG_CLEANUP(clBufferDelete(&msg), CL_OK);

    CL_LOG_DEBUG_TRACE(("Exit"));
    return CL_OK;
}
static void clAmsMgmtOIExtendedCacheAdd(ClAmsMgmtOIExtendedClassTypeT type,
                                        ClCorInstanceIdT instance, 
                                        ClAmsMgmtOIExtendedEntityConfigT *pConfig,
                                        ClUint32T configSize)
{
    struct hashStruct **table = NULL;
    ClAmsMgmtOIExtendedCacheT *cacheEntry = NULL;
    if(type >= CL_AMS_MGMT_OI_EXTENDED_CLASS_MAX || !pConfig || !configSize)
        return;
    clOsalMutexLock(&gClAmsMgmtOICacheMutex);
    table = gClAmsMgmtOIExtendedCacheTable[type];
    if( (cacheEntry = clAmsMgmtOIExtendedCacheFind(table, instance) ) )
    {
        CL_ASSERT(cacheEntry->pConfig != NULL);
        if(cacheEntry->configSize != configSize)
        {
            clHeapFree(cacheEntry->pConfig);
            cacheEntry->pConfig = clHeapCalloc(1, configSize);
            CL_ASSERT(cacheEntry->pConfig != NULL);
            cacheEntry->configSize = configSize;
        }
        memcpy(cacheEntry->pConfig, pConfig, configSize);
    }
    else
    {
        ClAmsMgmtOIExtendedEntityConfigT *pExtendedConfig = NULL;
        cacheEntry = clHeapCalloc(1, sizeof(*cacheEntry));
        CL_ASSERT(cacheEntry != NULL);
        pExtendedConfig = clHeapCalloc(1, configSize);
        CL_ASSERT(pExtendedConfig != NULL);
        cacheEntry->pConfig = pExtendedConfig;
        cacheEntry->instance = instance;
        memcpy(cacheEntry->pConfig, pConfig, configSize);
        hashAdd(table, entityCacheHashKey(instance), &cacheEntry->hash);
        clLogNotice("AMF", "MGMT", "Added entity [%s], instance [%d] to the extended class [%s]",
                    pConfig->entity.name.value, instance, gClAmsMgmtOIExtendedCacheStrTable[type]);
    }
    clOsalMutexUnlock(&gClAmsMgmtOICacheMutex);
}
ClRcT
clLogFileHdlrStreamAttributesCopy(ClLogStreamAttrIDLT     *pSource,
                                  ClLogStreamAttributesT  *pDest)
{
    ClRcT  rc = CL_OK;

    CL_LOG_DEBUG_TRACE(("Enter"));

    pDest->fileUnitSize    = pSource->fileUnitSize;
    pDest->recordSize      = pSource->recordSize;
    pDest->haProperty      = pSource->haProperty;
    pDest->fileFullAction  = pSource->fileFullAction;
    pDest->maxFilesRotated = pSource->maxFilesRotated;
    pDest->flushFreq       = pSource->flushFreq;
    pDest->flushInterval   = pSource->flushInterval;
    pDest->waterMark       = pSource->waterMark;
    pDest->fileName     
        = clHeapCalloc(pSource->fileName.length, sizeof(ClCharT));
    if( NULL == pDest->fileName )
    {
        CL_LOG_DEBUG_ERROR(("clHeapCalloc()"));
        return CL_LOG_RC(CL_ERR_NO_MEMORY);
    }           
    pDest->fileLocation  
        = clHeapCalloc(pSource->fileLocation.length, sizeof(ClCharT));
    if( NULL == pDest->fileLocation )
    {
        CL_LOG_DEBUG_ERROR(("clHeapCalloc()"));
        clHeapFree(pDest->fileName);
        return CL_LOG_RC(CL_ERR_NO_MEMORY);
    }           
    memcpy(pDest->fileName, pSource->fileName.pValue, pSource->fileName.length);
    memcpy(pDest->fileLocation, pSource->fileLocation.pValue, 
           pSource->fileLocation.length);

    CL_LOG_DEBUG_TRACE(("Exit"));
    return rc;
}
ClRcT
clTestCkptRead_withTime(ClCkptHdlT  ckptHdl,
               ClUint32T   numSections)
{
    ClRcT           rc = CL_OK;
    ClUint32T       i = 0, j = 0;
    ClCkptIOVectorElementT  iov[numSections];
    ClUint32T               readIdx = 0;
    ClUint32T         timeDelay[] = {1000000, 100000, 10000, 1000, 100, 10 , 0};

    memset(iov, 0, numSections * sizeof(ClCkptIOVectorElementT));
    for( i = 0; i < numSections; i++ )
    {
        if( numSections != 1 )
        {
            iov[i].sectionId.id = clHeapCalloc(1, 15);
            if( NULL == iov[i].sectionId.id )
            {   
                return CL_OK;
            }
            snprintf( (ClCharT *) iov[i].sectionId.id,15, "section%d", i);
            iov[i].sectionId.idLen = strlen((ClCharT *) iov[i].sectionId.id) + 1;
        }
        iov[i].dataSize = 0;
        iov[i].dataBuffer = NULL;
        iov[i].readSize = 0;
        iov[i].dataOffset = 0;
    }
    for( i = 0; i < (sizeof(timeDelay) / sizeof(sizeof(timeDelay[0]))); i++ )
    {
        for( j = 0; j < 1000; j++ )
        {
            rc = clCkptCheckpointRead(ckptHdl, iov, numSections, &readIdx); 
            for( i = 0; i < numSections; i++ )
            {
                clHeapFree(iov[i].dataBuffer);
                iov[i].dataBuffer = NULL; 
            }
            usleep(timeDelay[i]);
        }
    }
    for( i = 0; i < numSections; i++ )
    {
        if( NULL != iov[i].sectionId.id ) 
        {
            clHeapFree(iov[i].sectionId.id);
        }
    }
    return CL_OK;
}
static ClTransportNotifyMapT *addNotifyMap(ClInt32T watchFd, ClInt32T port)
{
    ClTransportNotifyMapT *notify;
    if(port < 0) return NULL;
    if( !(notify = findNotifyMap(watchFd, port)))
    {
        ClUint32T hash = TRANSPORT_NOTIFY_HASH(port);
        notify = clHeapCalloc(1, sizeof(*notify));
        CL_ASSERT(notify != NULL);
        hashAdd(gNotifyMap, hash, &notify->hash);
    }
    notify->watchFd = watchFd;
    notify->port = port;
    return notify;
}
ClRcT clDebugPrint(ClDebugPrintHandleT handle, const char* fmtStr, ...)
{
    char buf[CL_DEBUG_MAX_PRINT];
    char *space = buf;
    va_list args;
    ClRcT rc = CL_OK;
    ClBufferHandleT msg = (ClBufferHandleT)handle;
    ClInt32T c = 0, bytes = 0;

    /*
     * Estimate the space required for the buffer
     */
    va_start(args, fmtStr);
    bytes = vsnprintf((ClCharT*)&c, 1, fmtStr, args);
    va_end(args);
    
    if(!bytes) goto failure;

    if(bytes >= sizeof(buf))
    {
        space = clHeapCalloc(1, bytes + 1);
        CL_ASSERT(space != NULL);
    }

    va_start(args, fmtStr);
    vsnprintf(space, bytes+1, fmtStr, args);
    va_end(args);

    if (0 != msg)
    {
        rc = clBufferNBytesWrite(msg, (ClUint8T*)space, bytes);
        if (CL_OK != rc)
        {
            goto failure;
        }
    }
    else
    {
        rc = CL_DEBUG_RC(CL_ERR_INVALID_PARAMETER);
        goto failure;
    }

failure:
    if(space != buf)
        clHeapFree(space);

    return rc;
}
ClRcT
clTestSectionOverwrite_withTime(ClCkptHdlT  ckptHdl,
                      ClUint32T   numSections,
                      ClUint32T   sectionSize)
{
    ClRcT             rc = CL_OK;
    ClUint32T         i  = 0, j = 0, secNum = 0;
    ClUint8T          data[sectionSize];
    ClCkptSectionIdT  secId[numSections];
    ClUint32T         timeDelay[] = {1000000, 100000, 10000, 1000, 100, 10 , 0};

    memset(data, 'a', sectionSize);
    for( i = 0; i < numSections; i++ )
    {
        secId[i].id = clHeapCalloc(1, 15); 
        if( NULL == secId[i].id )
        {
            return CL_OK;
        }
        snprintf((ClCharT *) secId[i].id, 15, "section%d", i);
        secId[i].idLen = strlen((ClCharT *) secId[i].id) + 1;
    }

    for( i = 0; i < sizeof(timeDelay) / sizeof(timeDelay[0]); i++ )
    {
        for( j = 0; j < 1000; j++ )
        {
            for( secNum = 0; secNum < numSections; secNum++ )
            {
                rc = clCkptSectionOverwrite(ckptHdl, &secId[secNum], data, sectionSize);
                if( CL_OK != rc )
                {
                   printf("Section overwrite failed rc[0x %x]", rc);
                }
                usleep(timeDelay[i]);
            }
        }
    }

    if( numSections != 1 )
    {
        for( i = 0; i < numSections; i++ )
        {
            clHeapFree(secId[i].id);
        }
    }
    return CL_OK;
}
ClRcT clJobQueueCreate(ClJobQueueT** hdl, ClUint32T maxJobs, ClUint32T maxTasks)
{
    ClRcT rc;
    *hdl = (ClJobQueueT*) clHeapCalloc(1, sizeof(ClJobQueueT));
    if (*hdl == NULL) return CL_JOBQUEUE_RC(CL_ERR_NO_MEMORY);

    rc = clJobQueueInit(*hdl, maxJobs, maxTasks);
    if (rc != CL_OK)
    {
        clHeapFree(*hdl);
        *hdl = NULL;
    }
    else (*hdl)->flags |= CreatedJobQueue;

    return rc;  
}