【发布时间】:2018-08-22 16:21:47
【问题描述】:
我希望这个问题不会超出 SO 的范围;如果是(对不起),请告诉我它属于哪里,我会试着把它移到那里。
SAL annotations 用于 C/C++ 中的静态代码分析的概念对我来说似乎非常有用。以MSDN: Understanding SAL 上错误实现的wmemcpy 示例为例:
wchar_t * wmemcpy(
_Out_writes_all_(count) wchar_t *dest,
_In_reads_(count) const wchar_t *src,
size_t count)
{
size_t i;
for (i = 0; i <= count; i++) { // BUG: off-by-one error
dest[i] = src[i];
}
return dest;
}
MSDN 说“一个代码分析工具可以通过单独分析这个函数来捕捉错误”,这看起来很棒,但问题是当我将此代码粘贴到 VS 2017 社区时没有警告这会在代码分析中弹出,即使启用了所有分析警告。 (其他警告,如C26481 Don't use pointer arithmetic. Use span instead (bounds.1).。)
另一个应该产生警告的例子(至少根据an answer to What is the purpose of SAL (Source Annotation Language) and what is the difference between SAL 1 and 2?),但不会:
_Success_(return) bool GetASmallInt(_Out_range_(0, 10) int& an_int);
//main:
int result;
const auto ret = GetASmallInt(result);
std::cout << result;
还有一个不正确警告的情况:
struct MyStruct { int *a; };
void RetrieveMyStruct(_Out_ MyStruct *result) {
result->a = new int(42);
}
//main:
MyStruct s;
RetrieveMyStruct(&s);
// C26486 Don't pass a pointer that may be invalid to a function. Parameter 1 's.a' in call to 'RetrieveMyStruct' may be invalid (lifetime.1).
// Don't pass a pointer that may be invalid to a function. The parameter in a call may be invalid (lifetime.1).
result 显然标有_Out_ 而不是_In_ 或_Inout_,因此在这种情况下此警告没有意义。
我的问题是:为什么 Visual Studio 的基于 SAL 的代码分析看起来很糟糕;我错过了什么吗? Visual Studio Professional 或 Enterprise 在这方面可能更好吗?或者有什么工具可以做得更好?
如果它真的很糟糕:这是一个已知问题吗?是否有计划改进这种类型的分析?
相关:visual studio 2013 static code analysis - how reliable is it?
【问题讨论】:
-
我认为这个问题在范围内,我也认为你可能没有得到任何答案。我相信,您可能更有机会在专门针对 MSVC 的特定 Microsoft 论坛中发布相同的示例。
-
@SergeyA 谢谢,你可能是对的。如果我没有得到明确的答案,我会尝试!
-
至于你的最后一个例子,如果你使用
_Outptr_,也会发生同样的情况吗? -
@MaxLanghof 是的,但我认为
_Outptr_在这种情况下不是正确的注释(而且我在使用它时也会收到很多其他警告),因为我没有返回指针(你需要一个MyStruct**来做到这一点)。使用_Out_的示例WINAPI 函数是BeginPaint;PAINTSTRUCT ps; HDC hdc = BeginPaint(hWnd, &ps);也会发出警告。
标签: c++ visual-studio-2017 static-analysis sal