c++ - 如何针对 "suspicious sizeof"或 SIZEOF_MISMATCH 结果训练 Coverity?

标签 c++ static-analysis modeling coverity

我有一个模板函数,它具有执行归零的特化:

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 在 SecureWipeBuffer 上产生了一个发现:

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

结果是:

>>>     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);

如何训练 Coverity SecureWipeBuffer计算元素数,而不是字节数?


编辑:我们在 Windows 代码中发现了两个相似的发现。此外,Coverity 正在生成关于标准库函数的调查结果。它好像没有意识到 C++ 处理的是元素计数,而不是字节计数。

以下是来自 <xmemory> 中的 Microsoft 标准库代码

 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

最佳答案

我找到了这个 Github ,它试图通过这样做来抑制*:

  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);

Silencing false positives in Coverity Prevent 中也有建议,这里介绍了另一种方法:Coverity SA - excluding boost, stlport errors .


*我不确定这是否是您想要的,但我只有这些!

关于c++ - 如何针对 "suspicious sizeof"或 SIZEOF_MISMATCH 结果训练 Coverity?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38386419/

相关文章:

c++ - 有没有一种方法可以根据创建的派生类分配成员?

java - 从抽象语法树中查找变量/方法引用

modeling - Alloy 中定义的约束如何产生更好的软件?

resources - 序列图 : Interactions with resources (DB, 网络、缓存等)

c# - 使用 ISDN 调制解调器 (C#) 在第一次 bip 后调用电话号码时挂断

c++ - 如何在 C++ 中使用 HidD_GetHidGuid()?

c++ - 在数组中创建位置层次结构

sonarqube - Dockerfiles 的静态代码分析?

memory-leaks - 使用静态分析工具检查Linux设备驱动程序中的空指针和内存泄漏

c# - 对领域建模完全陌生,不知道从哪里开始