This post is focusing on general idea of Coverity Modeling based on Coverity 4.5.1 and Coverity 5.4.1 including why and how to do Coverity Modeling. Of course, Coverity official document would always be a good reference to start with. More over, will this post could be a not too bad annex for official document for Coverity Modeling.
1. Why Modeling?
There are 2 destinations to do modeling: 1st is to find new defect (because of maximum path analyzing limitation, some of functions would not be analyzed. Then Modeling is forcing Coverity to do the analysis for these functions); 2nd is to remove the false alarm (because of some reason, like complex internal logic, certain function could not be analyzed correctly. In such case, then modeling is needed to help Coverity forget such a function).
2. How Modeling – to remove false positives?
// Coverity 4.5.1
// SIPia_clone is a very complex memory allocate function which could not be
// analyzed normally. However, to make sure the model.c could be built
// successfully, all the necessary structures used in this function needs to
// be declared explicitly.
// To find a new defect
// Create a stub C function that uses the standard C library function to
// emulate the behavior of that function – in such case is ‘malloc’.
/* Declaration of SIPia_Msg here */
SIPia_Msg *
SIPia_clone(SIPia_Msg *baseMsg_ptr, int addSize)
{
int msgBlkSize;
SIPia_Msg* newMsg_ptr;
/*
* Allocate a new block of system memory for cloned message.
*/
msgBlkSize = baseMsg_ptr->blkMgr.blkSize + addSize;
newMsg_ptr = (SIPia_Msg *)malloc(msgBlkSize);
return(newMsg_ptr);
}
// To remove the false positives, we need to use Coverity primitives
// to rewrite – in such case below is ‘__coverity_alloc__’, although there is
// another option here – empty function.
/* Declaration of SIPia_Msg here */
SIPia_Msg *
SIPia_clone(SIPia_Msg *baseMsg_ptr, int addSize)
{
int msgBlkSize;
SIPia_Msg* newMsg_ptr;
/*
* Allocate a new block of system memory for cloned message.
*/
msgBlkSize = baseMsg_ptr->blkMgr.blkSize + addSize;
newMsg_ptr = (SIPia_Msg *)__coverity_alloc__(msgBlkSize);
return(newMsg_ptr);
}
// Coverity 5.4.1
// There is a bit of difference between Coverity 4.5.1 and Coverity 5.4.1
// except more Coverity Modeling primitives. When compiling modeling for
// removing false postivite, some of the C library functions may cause build
// error like below:
// home/coverity/model_libs/msc/msc_all.c", line 211: error #20: identifier
// "memcpy" is undefined
// memcpy (( UBYTE *)((ULONG)newIMsg + sizeof(IMSG)),
// For such a case, ‘memcpy’ needsto rewrite based on the the follow source:
// cov-sa-linux-5.4.1/library/generic/common/mem.c
static void *escape;
void *memcpy(void *d, void *s, size_t n)
{
__coverity_negative_sink__(n);
if(n != 0) {
((char *)d)[n-1] = ((char *)s)[n-1];
*(char*)d = *(char*)s;
__coverity_writeall__(d);
escape = *((void **)s);
}
return d;
}
Just a check if comment would be lost here…