C++ 中的大量操作会导致未定义的行为,其中规范对于程序的行为应该是什么完全保持沉默,并允许任何事情发生。因此,在各种情况下,人们的代码可以在调试模式下编译,但不能在发布模式下编译,或者在进行看似不相关的更改之前一直有效,或者在一台机器上工作但在另一台机器上工作,等等。
我的问题是是否有一个实用程序可以查看 C++ 代码的执行情况并标记程序调用未定义行为的所有实例。虽然我们有像 valgrind 和检查的 STL 实现这样的工具很好,但这些工具并不像我想象的那么强大 - 例如,如果你丢弃仍然分配的内存,并且检查的 STL 实现,valgrind 可能会出现误报不会捕获通过基类指针的删除。
这个工具存在吗?或者把它放在身边还有用吗?
编辑:我知道,一般来说,静态检查 C++ 程序是否可能执行具有未定义行为的内容是无法确定的。但是,可以确定 C++ 的特定执行是否产生未定义的行为。实现此目的的一种方法是创建一个 C++ 解释器,根据规范中规定的定义逐步执行代码,在每个点确定代码是否具有未定义的行为。这不会检测特定程序执行中未发生的未定义行为,但会发现程序中实际表现出来的任何未定义行为。这与图灵如何识别来确定 TM 是否接受某些输入有关,即使它通常仍然是不可判定的。
谢谢!
A huge number of operations in C++ result in undefined behavior, where the spec is completely mute about what the program's behavior ought to be and allows for anything to happen. Because of this, there are all sorts of cases where people have code that compiles in debug but not release mode, or that works until a seemingly unrelated change is made, or that works on one machine but not another, etc.
My question is whether there is a utility that looks at the execution of C++ code and flags all instances where the program invokes undefined behavior. While it's nice that we have tools like valgrind and checked STL implementations, these aren't as strong as what I'm thinking about - valgrind can have false negatives if you trash memory that you still have allocated, for example, and checked STL implementations won't catch deleting through a base class pointer.
Does this tool exist? Or would it even be useful to have it lying around at all?
EDIT: I am aware that in general it is undecidable to statically check whether a C++ program may ever execute something that has undefined behavior. However, it is possible to determine whether a specific execution of a C++ produced undefined behavior. One way to do this would be to make a C++ interpreter that steps through the code according to the definitions set out in the spec, at each point determining whether or not the code has undefined behavior. This won't detect undefined behavior that doesn't occur on a particular program execution, but it will find any undefined behavior that actually manifests itself in the program. This is related to how it is Turing-recognizable to determine if a TM accepts some input, even if it's still undecidable in general.
Thanks!
发布评论
评论(10)
约翰·雷格尔 在通过查找死代码来查找未定义的行为错误指出了一个名为STACK 我引用了站点(强调我的):
同样在C++11中,对于constexpr变量和函数未定义行为应该在编译时捕获。
我们还有 gcc ubsan:
和 Clang 静态分析器,其中包括 对未定义行为进行多次检查。例如
clangs
-fsanitize 检查其中包括-fsanitize=undefined
:对于C,我们可以看看他的文章是时候认真对待利用未定义行为了 其中说:
这是一个kcc 链接,我引用:
这里有一个 Frama-C 链接,一篇文章 其中第一次使用 Frama-C 作为本文描述了 C 解释器以及附录。
John Regehr in Finding Undefined Behavior Bugs by Finding Dead Code points out a tool called STACK and I quote from the site (emphasis mine):
Also in C++11 for the case of constexpr variables and functions undefined behavior should be caught at compile time.
We also have gcc ubsan:
and Clang Static Analyzer which includes many checks for undefined behavior. For example
clangs
-fsanitize checks which includes-fsanitize=undefined
:and for C we can look at his article It’s Time to Get Serious About Exploiting Undefined Behavior which says:
Here is a link to kcc and I quote:
and here are a link to Frama-C, an article where the first use of Frama-C as a C interpreter is described and an addendum to the article.
这是一个很好的问题,但让我来解释一下为什么我认为这通常是不可能的(或者至少非常困难)。
据推测,这样的实现几乎是一个 C++ 解释器,或者至少是一个类似于 Lisp 或 Java 的编译器。它需要为每个指针保留额外的数据,以确保您不会在数组之外执行算术或取消引用已释放的内容或其他内容。
现在,考虑以下代码:
*p = 17
是未定义的行为吗?一方面,它在释放后取消引用p
。另一方面,取消引用q
很好,并且p == q
...但这不是真正的重点。关键是
if
的计算结果是否为 true 完全取决于堆实现的细节,而这些细节可能因实现而异。因此,用一些实际的未定义行为替换 *p = 17 ,您的程序很可能在普通编译器上崩溃,但在假设的“UB 检测器”上运行良好。 (典型的 C++ 实现将使用 LIFO 空闲列表,因此指针很可能相等。假设的“UB 检测器”可能更像垃圾收集语言,以便检测释放后使用问题。)换句话说,我怀疑仅仅实现定义行为的存在使得编写适用于所有程序的“UB检测器”变得不可能。
也就是说,创建“超级严格的 C++ 编译器”的项目将会非常有趣。如果您想开始,请告诉我。 :-)
This is a great question, but let me give an idea for why I think it might be impossible (or at least very hard) in general.
Presumably, such an implementation would almost be a C++ interpreter, or at least a compiler for something more like Lisp or Java. It would need to keep extra data for each pointer to ensure you did not perform arithmetic outside of an array or dereference something that was already freed or whatever.
Now, consider the following code:
Is the
*p = 17
undefined behavior? On the one hand, it dereferencesp
after it has been freed. On the other hand, dereferencingq
is fine andp == q
...But that is not really the point. The point is that whether the
if
evaluates to true at all depends on the details of the heap implementation, which can vary from implementation to implementation. So replace*p = 17
by some actual undefined behavior, and you have a program that might very well blow up on a normal compiler but run fine on your hypothetical "UB detector". (A typical C++ implementation will use a LIFO free list, so the pointers have a good chance of being equal. A hypothetical "UB detector" might work more like a garbage collected language in order to detect use-after-free problems.)Put another way, the existence of merely implementation-defined behavior makes it impossible to write a "UB detector" that works for all programs, I suspect.
That said, a project to create an "uber-strict C++ compiler" would be very interesting. Let me know if you want to start one. :-)
Clang 有一套清理器,可以捕获各种形式的未定义行为。他们的最终目标是能够捕获所有 C++ 核心语言未定义行为,但目前缺少对一些棘手形式的未定义行为的检查。
对于一组不错的清理程序,请尝试:
-fsanitize=address
检查是否使用了错误指针(未指向有效内存),并且-fsanitize=undefined
启用一组轻量级 UB 检查(整数溢出、错误移位、指针未对齐……)。-fsanitize=memory
(用于检测未初始化的内存读取)和-fsanitize=thread
(用于检测数据争用)也很有用,但这些都不能与组合使用>-fsanitize=address
也不能相互影响,因为这三者都会对程序的地址空间产生侵入性影响。Clang has a suite of sanitizers that catch various forms of undefined behavior. Their eventual goal is to be able to catch all C++ core language undefined behavior, but checks for a few tricky forms of undefined behavior are missing right now.
For a decent set of sanitizers, try:
-fsanitize=address
checks for use of bad pointers (not pointing to valid memory), and-fsanitize=undefined
enables a set of lightweight UB checks (integer overflow, bad shifts, misaligned pointers, ...).-fsanitize=memory
(for detecting uninitialized memory reads) and-fsanitize=thread
(for detecting data races) are also useful, but neither of these can be combined with-fsanitize=address
nor with each other because all three have an invasive impact on the program's address space.使用
g++
(最好也带有适当的
-std
参数)将拾取-Wall
让您包含的 UB 事物 的很多情况:以及您可以使用
printf
和scanf
系列函数的说明符执行的各种不允许的操作。Using
g++
(preferably with an appropriate
-std
argument as well) will pick up quite a few case of U.B.Things that
-Wall
gets you include:and various disallowed things you can do with specifiers to
printf
andscanf
family functions.您可能想了解SAFECode。
这是伊利诺伊大学的一个研究项目,目标在首页上注明(上面链接):
对我来说真正有趣的是,只要可以证明程序静态正确,就消除运行时检查,例如:
不应比常规版本产生更多开销。
据我所知,以一种更轻松的方式,Clang 对未定义的行为也有一些保证,但我无法掌握它。 。
You might want to read about SAFECode.
This is a research project from the University of Illinois, the goal is stated on the front page (linked above):
What is really interesting to me is the elimination of the runtime checks whenever the program can be proved to be correct statically, for example:
Should not incur any more overhead than the regular version.
In a lighter fashion, Clang has some guarantees about undefined behavior too as far as I recall, but I cannot get my hands on it...
clang 编译器可以检测一些未定义的行为并发出警告。可能没有您想要的那么完整,但这绝对是一个好的开始。
The
clang
compiler can detect some undefined behaviors and warn against them. Probably not as complete as you want, but it's definitely a good start.不幸的是我不知道有任何这样的工具。通常,UB 正是这样定义的,因为编译器很难或不可能在所有情况下对其进行诊断。
事实上,你最好的工具可能是编译器警告:它们经常警告 UB 类型项(例如,基类中的非虚拟析构函数、滥用严格别名规则等)。
代码审查还可以帮助发现依赖 UB 的情况。
然后你必须依靠 valgrind 来捕获剩余的情况。
Unfortunately I'm not aware of any such tool. Typically UB is defined as such precisely because it would be hard or impossible for a compiler to diagnose it in all cases.
In fact your best tool is probably compiler warnings: They often warn about UB type items (for example, non-virtual destructor in base classes, abusing the strict-aliasing rules, etc).
Code review can also help catch cases where UB is relied upon.
Then you have to rely on valgrind to capture the remaining cases.
作为一个侧面观察,根据可计算性理论,你不可能有一个程序可以检测所有可能的未定义行为。
您只能拥有使用启发式方法并检测遵循特定模式的某些特定情况的工具。或者,在某些情况下,您可以证明程序的行为符合您的要求。但一般情况下您无法检测到未定义的行为。
编辑
如果程序未在给定输入上终止(挂起、永远循环),则其输出未定义。
如果你同意这个定义,那么判断一个程序是否终止就是众所周知的“Halting Problem”,它已经被证明是不可判定的,即不存在程序(图灵机、C程序、C++程序、Pascal程序、任何语言)都可以解决这个问题。
简单地说:不存在任何程序 P 可以将任何程序 Q 和输入数据 I 作为输入,并且如果 Q(I) 终止则打印为输出 TRUE,否则如果 Q(I) 未终止则打印为 FALSE。
有关详细信息,您可以查看http://en.wikipedia.org/wiki/Halting_problem。
Just as a side observation, according to the theory of computability, you cannot have a program that detects all possible undefined behaviours.
You can only have tools that use heuristics and detect some particular cases that follow certain patterns. Or you can in certain cases prove that a program behaves as you want. But you cannot detect undefined behaviour in general.
Edit
If a program does not terminate (hangs, loops forever) on a given input, then its output is undefined.
If you agree on this definition, then determining whether a program terminates is the well-known "Halting Problem", which has been proven to be undecidable, i.e. there exists no program (Turing Machine, C program, C++ program, Pascal program, in whatever language) that can solve this problem in general.
Simply put: there exists no program P that can take as input any program Q and input data I and print as output TRUE if Q(I) terminates, or else print FALSE if Q(I) does not terminate.
For more information you can look at http://en.wikipedia.org/wiki/Halting_problem.
未定义的行为是未定义。您能做的最好的事情就是迂腐地遵守标准,正如其他人所建议的那样,但是,您无法测试未定义的内容,因为您不知道它是什么。如果你知道它是什么并且标准指定了它,那么它就不会是未定义的。
但是,如果您出于某种原因,确实依赖于标准所说的未定义,并且它产生了特定的结果,那么您可以选择定义它,并编写一些单元测试来确认对于您的特定构建,它是定义的。然而,最好尽可能避免未定义的行为。
Undefined behaviour is undefined. The best you can do is conform to the standard pedantically, as others have suggested, however, you can not test for what is undefined, because you don't know what it is. If you knew what it was and standards specified it, it would not be undefined.
However, if you for some reason, do actually rely on what the standard says is undefined, and it results in a particular result, then you may choose to define it, and write some unit tests to confirm that for your particular build, it is defined. It is much better, however, to simply avoid undefined behaviour whenever possible.
看看PCLint,它在检测 C++ 中的许多坏东西方面相当不错。
这里是它捕获的内容的子集
Take a look at PCLint its pretty decent at detecting a lot of bad things in C++.
Here's a subset of what it catches