You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: text/0000-const-ub.md
+40-65Lines changed: 40 additions & 65 deletions
Original file line number
Diff line number
Diff line change
@@ -6,9 +6,7 @@
6
6
# Summary
7
7
[summary]: #summary
8
8
9
-
Define how UB during const evaluation is treated:
10
-
some kinds of UB must be detected, the remaining UB conditions are ignored and evaluation continues in a well-defined way.
11
-
However, CTFE queries causing UB are not subject to stability guarantees and thus may fail to build in the future (e.g. when more UB is being detected).
9
+
Define UB during const evaluation to lead to an unspecified result for the affected CTFE query, but not otherwise infect the compilation process.
12
10
13
11
# Motivation
14
12
[motivation]: #motivation
@@ -25,98 +23,79 @@ Computing these initial values is called compile-time function evaluation (CTFE)
25
23
CTFE in Rust is very powerful and permits running almost arbitrary Rust code.
26
24
This raises the question, what happens when there is `unsafe` code and it causes [Undefined Behavior (UB)][UB]?
27
25
28
-
The answer depends on the kind of UB: some kinds of UB are guaranteed to be detected,
29
-
while other kinds of UB might either be detected, or else evaluation will continue as if the violated UB condition did not exist (i.e., as if this operation was actually defined).
30
-
This can change from compiler version to compiler version: CTFE code that causes UB could build fine with one compiler and fail to build with another.
26
+
The answer is that in this case, the final value that is currently being executed is arbitrary.
27
+
For example, when UB arises while computing an array length, then the final array length can be any `usize`, or it can be (partially) uninitialized.
28
+
No guarantees are made about this final value, and it can be different depending on host and target architecture, compiler flags, and more.
29
+
However, UB will not otherwise adversely affect the currently running compiler; type-checking and lints and everything else will work correctly given whatever the result of the CTFE computation is.
31
30
32
-
This RFC does not alter the general policy that unsound code is not subject to strict stability guarantees.
33
-
In other words, unsafe code may not rely on all future versions of Rust to implement this RFC.
34
-
The RFC only helps *consumers* of unsafe code to be sure that right now, all UB during CTFE will be detected or non-consequential (i.e., evaluation will proceed as if there was no UB).
35
-
It does not grant any new possibilities to *authors* of unsafe code; in particular, it is still considered a critical bug for CTFE code to raise UB, and no stability guarantees are made for such code (as is the case with regular runtime code raising UB).
31
+
Note, however, that this means compile-time UB can later cause runtime UB when the program is actually executed:
32
+
for example, if there is UB while computing the initial value of a `Vec<i32>`, the result might be a completely invalid vector that causes UB at runtime when used in the program.
Sometimes, the compiler might be able to detect such problems and show an error or warning about CTFE computation having gone wrong (for example, the compiler might detect when the array length ends up being uninitialized).
35
+
But other times, this might not be the case -- there is no guarantee that UB is reliably detected during CTFE.
36
+
This can change from compiler version to compiler version: CTFE code that causes UB could build fine with one compiler and fail to build with another.
37
+
(This is in accordance with the general policy that unsound code is not subject to stability guarantees.)
38
+
Implementations are encouraged to perform as many UB checks as they feasibly can, and they are encouraged to document which UB is and is not detected during CTFE and what the consequences of undetected UB can be, but none of this is required.
The following kinds of UB are detected by CTFE, and will cause compilation to stop with an error:
42
+
For `rustc` specifically at the time the RFC is written, a lot of UB will actually be detected reliably:
43
43
* Dereferencing dangling pointers.
44
-
* Using an invalid value in an arithmetic, logical or control-flow operation.
45
-
46
-
These kinds of UB have in common that there is nothing sensible evaluation can do besides stopping with an error.
44
+
* Using an invalid value in an arithmetic, logical or control-flow operation (e.g. using `3` transmuted to a `bool` value in an `if`, or using an uninitialized integer in `+` or `|`).
45
+
* Violating the precondition of an intrinsic (e.g., reaching an `unreachable` or violating the assumptions of `exact_div`).
47
46
48
-
Other kinds of UB might or might not be detected depending on the implementation:
49
-
* Dereferencing unaligned pointers.
50
-
* Violating Rust's aliasing rules.
51
-
* Producing an invalid value (but not using it in one of the ways defined above).
52
-
* Any [other UB][UB] not listed here.
47
+
If any of these errors arise during CTFE, they will currently be reliably detected and a CTFE error will be raised.
53
48
54
-
Implementations should document which of these kinds of UB they detect.
55
-
In rustc, none of this UB will be detected for now.
56
-
However, code causing any kind of UB is still considered buggy and not subject to stability guarantees.
57
-
Hence, rustc may start detecting more UB in the future.
49
+
Other kinds of UB are ignored, and evaluation continues as if there was no error.
50
+
* Dereferencing unaligned pointers: memory is accessed at the given address even if it is insufficiently aligned.
51
+
* Violating Rust's aliasing rules: memory is read/written even if that violates aliasing guarantees.
52
+
* Producing an invalid value (but not using it in one of the ways defined above): evaluation continues despite the fact that an invalid value was produced.
58
53
59
-
All of this UB has in common that there is an easy way to continue evaluation even though the program has caused UB:
60
-
we can just access the underlying memory despite alignment and/or aliasing rules being violated, and we can just ignore the existence of an invalid value as long as it is not used in some arithmetic, logical or control-flow operation.
61
-
There is no guarantee that CTFE detects such UB: evaluation may either fail with an error, or continue with the some well-defined result.
62
-
In the latter case, implementations should document how evaluation will proceed, i.e., how the result is computed.
54
+
`rustc` also currently makes no attempt at detecting library UB.
63
55
64
-
In particular, the RFC does not mandate whether UB caused by implementation-defined compiler intrinsics (insofar as they are supported by CTFE) is detected.
65
-
However, implementations should document for each intrinsic whether UB is detected, and (if UB is ignored for an intrinsic), what the behavior of CTFE will be when UB occurs.
66
-
For rustc, all intrinsic-specific UB (e.g., reaching an `unreachable` or violating the assumptions of `exact_div`) will be detected, but if intrinsics perform memory accesses, they are treated like regular accesses for UB detection (e.g., aliasing or alignment violations are not detected, and execution proceeds just ignoring this check).
56
+
No UB-exploiting MIR optimizations are currently being performed for CTFE, so a CTFE execution currently will never go wrong in arbitrary ways: UB is either detected, or evaluation continues in a well-defined manner as described above.
67
57
68
-
The RFC also does not mandate detecting any library UB, i.e., UB caused by violating the contract of a (standard) library function.
69
-
The same conditions as for intrinsics apply: implementations should document which UB is detected.
70
-
If library UB is ignored, execution must continue by just following the rules of the Abstract Machine for the current implementation of the library function, treating it as if that code had no contract applied to it.
71
-
In rustc, no library UB will be detected.
58
+
However, this is just a snapshot of what `rustc` currently does.
59
+
None of this is *guaranteed*, and `rustc` may relax or otherwise change its UB checking any time.
72
60
73
-
If the compile-time evaluation uses operations that are specified as non-deterministic,
74
-
and only some of the non-deterministic choices lead to CTFE-detected UB,
75
-
then CTFE may choose any possible execution and thus miss the possible UB.
76
-
For example, if we end up specifying the value of padding after a typed copy to be non-deterministically chosen, then padding will be initialized in some executions and uninitialized in others.
77
-
If the program then performs integer arithmetic on a padding byte, that might or might not be detected as UB, depending on the non-deterministic choice made by CTFE.
This requirement implies that CTFE must happen on code that was *not subject to UB-exploiting optimizations*.
82
-
In general, optimizations of Rust code may assume that the source program does not have UB, so programs that exhibit UB can simply be ignored when arguing for the correctness of an optimization.
83
-
However, this can lead to programs with UB being translated into programs without UB, so if constant evaluation runs after such an optimization, it might fail to detect the UB.
84
-
The only permissible optimizations are those that preserve all UB and that preserve the behavior of programs whose UB CTFE does not detect.
85
-
Formally speaking this means they must be correct optimizations for the abstract machine *that CTFE actually implements*, not just for the abstract machine that specifies Rust; and moreover they must preserve the location and kind of UB that is detected by CTFE.
66
+
When UB arises as part of CTFE, the result of this evaluation is an unspecified constant, i.e., it is arbitrary, and might not even be of the right type.
67
+
The compiler might be able to detect that UB occurred and raise an error or a warning, but this is not mandated, and absence of lints does not imply absence of UB.
68
+
However, the rest of the compiler will continue to function properly, and compilation *itself* will not raise UB.
86
69
87
70
# Drawbacks
88
71
[drawbacks]: #drawbacks
89
72
90
-
To be able to either detect UB or continue evaluation in a well-defined way, CTFE must run on unoptimized code.
91
-
This means when compiling a `const fn` in some crate, the unoptimized code needs to be stored.
92
-
So either the code is stored twice (optimized and unoptimized), or optimizations can only happen after all CTFE results have been computed.
93
-
[Experiments in rustc](https://perf.rust-lang.org/compare.html?start=35debd4c111610317346f46d791f32551d449bd8&end=3dbdd3b981f75f965ac04452739653a3d47ff0ed) showed a severe performance impact on CTFE stress-tests, but no impact on real code except for a slowdown of "incr-unchanged" (which are rather fast so small changes lead to large percentages).
73
+
This means UB during CTFE can silently "corrupt" the build in a way that the final program has UB when being executed
74
+
(but not more so than if the CTFE code would instead have been run at runtime).
The most obvious alternative is to say that UB during CTFE will definitely be detected.
99
80
However, that is expensive and might even be impossible.
100
81
Even Miri does not currently detect all UB, and Miri is already performing many additional checks that would significantly slow down CTFE.
101
-
Furthermore, implementing these checks requires a more precise understanding of UB than we currently have; basically, this would block having any potentially-UB operations at const-time on having a spec for Rust that precisely describes their UB in a checkable way.
82
+
Furthermore, since optimizations can "hide" UB (an optimization can turn a program with UB into one without), this means we would have to run CTFE on unoptimized MIR.
83
+
And finally, implementing these checks requires a more precise understanding of UB than we currently have; basically, this would block having any potentially-UB operations at const-time on having a spec for Rust that precisely describes their UB in a checkable way.
102
84
In particular, this would mean we need to decide on an aliasing model before permitting raw pointers in CTFE.
103
85
104
-
To avoid the need for keeping the unoptimized sources of `const fn` around, we could weaken the requirement for detecting UB and instead say that UB might cause arbitrary evaluation results.
105
-
Under the assumption that unsound code is not subject to the usual stability guarantees, this is an option we can still move to in the future, should it turn out that the proposal made in this RFC is too expensive.
106
-
107
86
Another extreme alternative would be to say that UB during CTFE may have arbitrary effects in the host compiler, including host-level UB.
108
87
Basically this would mean that CTFE would be allowed to "leave its sandbox".
109
88
This would allow JIT'ing CTFE and running the resulting code unchecked.
110
89
While compiling untrusted code should only be done with care (including additional sandboxing), this seems like an unnecessary extra footgun.
111
90
91
+
A possible middle-ground is to guarantee to detect *some UB*.
92
+
However, what is cheap and/or easy to detect might change over time as the implementation of CTFE evolves, so to avoid drawing Rust into a corner, this RFC avoids making any such guarantees.
93
+
112
94
# Prior art
113
95
[prior-art]: #prior-art
114
96
115
97
C++ requires compilers to detect UB in `constexpr`.
116
98
However, the fragment of C++ that is available to `constexpr` excludes pointer casts, pointer arithmetic (beyond array bounds), and union-based type punning, which makes such checks not very complicated and avoids most of the poorly specified parts of UB.
117
-
The corresponding type-punning-free fragment of Rust (no raw pointers, no `union`, no `transmute`) can only cause UB that is defined to be definitely detected during CTFE.
118
-
In that sense, Rust achieves feature parity with C++ in terms of UB detection during CTFE.
119
-
(Indeed, this was the prime motivation for making such strict UB detection requirements in the first place.)
120
99
121
100
# Unresolved questions
122
101
[unresolved-questions]: #unresolved-questions
@@ -128,9 +107,5 @@ Currently none.
128
107
129
108
This RFC provides an easy way forward for "unconst" operations, i.e., operations that are safe at run-time but not at compile-time.
130
109
Primary examples of such operations are anything involving the integer representation of pointers, which cannot be known at compile-time.
131
-
If this RFC were accepted, we could declare such operations "definitely detected UB" during CTFE (and thus naturally they would only be permitted in an `unsafe` block).
132
-
133
-
If UB checks turn out to be expensive, the RFC leaves the option of adding a flag to let users opt-out of UB checking.
134
-
This will speed up compilation, and not change behavior of correct code.
135
-
136
-
The RFC clarifies that there is no *guarantee* that code with UB is evaluated in any particular way, so if we want to detect more UB during CTFE in the future, we are free to do so from a stability perspective.
110
+
If this RFC were accepted, we could declare such operations UB during CTFE (and thus naturally they would only be permitted in an `unsafe` block).
111
+
This still leaves the door open for providing better guarantees in the future.
0 commit comments