Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to train Coverity for "suspicious sizeof" or SIZEOF_MISMATCH finding?

I have a template function with a specialization that performs zeroization:

template <class T>
void SecureWipeBuffer(T *buf, size_t n)
{
    volatile T *p = buf+n;
    while (n--)
        *((volatile T*)(--p)) = 0;
}
...

template <>
void SecureWipeBuffer(word64* p, size_t n)
{
   asm volatile("rep stosq" : "+c"(n), "+D"(p) : "a"(0) : "memory");
}

Coverity is producing a finding on SecureWipeBuffer:

word64 val;
...
SecureWipeBuffer(&val, 1);

The finding is:

>>>     CID 164713:  Incorrect expression  (SIZEOF_MISMATCH)
>>>     Passing argument "&val" of type "word64 *" and argument "1UL" to function "SecureWipeBuffer" is suspicious because "sizeof (word64)" /*8*/ is expected.
275             SecureWipeBuffer(&val, 1);

How do train Coverity that SecureWipeBuffer takes a count of elements, and not a count of bytes?


EDIT: we've picked up two similar findings with our Windows code. In addition, Coverity is producing findings on standard library functions. Its as if it does not realize C++ deals with counts of elements, and not counts of bytes.

Below is from Microsft standard library code in <xmemory>

 25    if (_Count == 0)
 26        ;
 27    else if (((size_t)(-1) / sizeof (_Ty) < _Count)
    CID 12348 (#1 of 1): Wrong sizeof argument (SIZEOF_MISMATCH)
    suspicious_sizeof: Passing argument _Count * 4U /* sizeof (std::allocator<void *>::value_type) */
    to function operator new which returns a value of type std::allocator<void *>::value_type is suspicious.
 28        || (_Ptr = ::operator new(_Count * sizeof (_Ty))) == 0)
 29            _Xbad_alloc();  // report no memory
like image 727
jww Avatar asked Jul 15 '16 01:07

jww


1 Answers

I found this Github, which tries to suppress that*, by doing this:

  std::fill_n(out, spec_.width_ - 1, fill);
  out += spec_.width_ - 1;
} else if (spec_.align_ == ALIGN_CENTER) {
  // coverity[suspicious_sizeof]
  out = writer_.fill_padding(out, spec_.width_, 1, fill);
} else {
  std::fill_n(out + 1, spec_.width_ - 1, fill);

which is also advised in Silencing false positives in Coverity Prevent, and another approach is covered here: Coverity SA - excluding boost, stlport errors.


*I am not sure if that's what you want, but that's all I got!

like image 125
gsamaras Avatar answered Sep 28 '22 18:09

gsamaras