Skip to content

Commit ebb1189

Browse files
committed
Auto merge of #116930 - RalfJung:raw-ptr-match, r=<try>
patterns: reject raw pointers that are not just integers Matching against `0 as *const i32` is fine, matching against `&42 as *const i32` is not. Cc `@oli-obk` `@lcnr`
2 parents 36b61e5 + 0787e62 commit ebb1189

File tree

10 files changed

+93
-33
lines changed

10 files changed

+93
-33
lines changed

compiler/rustc_const_eval/src/const_eval/valtrees.rs

+27-10
Original file line numberDiff line numberDiff line change
@@ -97,11 +97,27 @@ pub(crate) fn const_to_valtree_inner<'tcx>(
9797
Ok(ty::ValTree::Leaf(val.assert_int()))
9898
}
9999

100-
// Raw pointers are not allowed in type level constants, as we cannot properly test them for
101-
// equality at compile-time (see `ptr_guaranteed_cmp`).
100+
ty::RawPtr(_) => {
101+
// Not all raw pointers are allowed, as we cannot properly test them for
102+
// equality at compile-time (see `ptr_guaranteed_cmp`).
103+
// However we allow those that are just integers in disguise.
104+
// (We could allow wide raw pointers where both sides are integers in the future,
105+
// but for now we reject them.)
106+
let Ok(val) = ecx.read_scalar(place) else {
107+
return Err(ValTreeCreationError::Other);
108+
};
109+
// We are in the CTFE machine, so ptr-to-int casts will fail.
110+
// This can only be `Ok` if `val` already is an integer.
111+
let Ok(val) = val.try_to_int() else {
112+
return Err(ValTreeCreationError::Other);
113+
};
114+
// It's just a ScalarInt!
115+
Ok(ty::ValTree::Leaf(val))
116+
}
117+
102118
// Technically we could allow function pointers (represented as `ty::Instance`), but this is not guaranteed to
103119
// agree with runtime equality tests.
104-
ty::FnPtr(_) | ty::RawPtr(_) => Err(ValTreeCreationError::NonSupportedType),
120+
ty::FnPtr(_) => Err(ValTreeCreationError::NonSupportedType),
105121

106122
ty::Ref(_, _, _) => {
107123
let Ok(derefd_place)= ecx.deref_pointer(place) else {
@@ -222,12 +238,14 @@ pub fn valtree_to_const_value<'tcx>(
222238
assert!(valtree.unwrap_branch().is_empty());
223239
mir::ConstValue::ZeroSized
224240
}
225-
ty::Bool | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Char => match valtree {
226-
ty::ValTree::Leaf(scalar_int) => mir::ConstValue::Scalar(Scalar::Int(scalar_int)),
227-
ty::ValTree::Branch(_) => bug!(
228-
"ValTrees for Bool, Int, Uint, Float or Char should have the form ValTree::Leaf"
229-
),
230-
},
241+
ty::Bool | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Char | ty::RawPtr(_) => {
242+
match valtree {
243+
ty::ValTree::Leaf(scalar_int) => mir::ConstValue::Scalar(Scalar::Int(scalar_int)),
244+
ty::ValTree::Branch(_) => bug!(
245+
"ValTrees for Bool, Int, Uint, Float, Char or RawPtr should have the form ValTree::Leaf"
246+
),
247+
}
248+
}
231249
ty::Ref(_, inner_ty, _) => {
232250
let mut ecx = mk_eval_cx(tcx, DUMMY_SP, param_env, CanAccessStatics::No);
233251
let imm = valtree_to_ref(&mut ecx, valtree, *inner_ty);
@@ -281,7 +299,6 @@ pub fn valtree_to_const_value<'tcx>(
281299
| ty::Generator(..)
282300
| ty::GeneratorWitness(..)
283301
| ty::FnPtr(_)
284-
| ty::RawPtr(_)
285302
| ty::Str
286303
| ty::Slice(_)
287304
| ty::Dynamic(..) => bug!("no ValTree should have been created for type {:?}", ty.kind()),

compiler/rustc_lint_defs/src/builtin.rs

+4-3
Original file line numberDiff line numberDiff line change
@@ -2217,15 +2217,16 @@ declare_lint! {
22172217
///
22182218
/// ### Explanation
22192219
///
2220-
/// Previous versions of Rust allowed function pointers and wide raw pointers in patterns.
2220+
/// Previous versions of Rust allowed function pointers and all raw pointers in patterns.
22212221
/// While these work in many cases as expected by users, it is possible that due to
22222222
/// optimizations pointers are "not equal to themselves" or pointers to different functions
22232223
/// compare as equal during runtime. This is because LLVM optimizations can deduplicate
22242224
/// functions if their bodies are the same, thus also making pointers to these functions point
22252225
/// to the same location. Additionally functions may get duplicated if they are instantiated
2226-
/// in different crates and not deduplicated again via LTO.
2226+
/// in different crates and not deduplicated again via LTO. Pointer identity for memory
2227+
/// created by `const` is similarly unreliable.
22272228
pub POINTER_STRUCTURAL_MATCH,
2228-
Allow,
2229+
Forbid,
22292230
"pointers are not structural-match",
22302231
@future_incompatible = FutureIncompatibleInfo {
22312232
reason: FutureIncompatibilityReason::FutureReleaseErrorDontReportInDeps,

compiler/rustc_mir_build/messages.ftl

+1-1
Original file line numberDiff line numberDiff line change
@@ -242,7 +242,7 @@ mir_build_overlapping_range_endpoints = multiple patterns overlap on their endpo
242242
mir_build_pattern_not_covered = refutable pattern in {$origin}
243243
.pattern_ty = the matched value is of type `{$pattern_ty}`
244244
245-
mir_build_pointer_pattern = function pointers and unsized pointers in patterns behave unpredictably and should not be relied upon. See https://github.com/rust-lang/rust/issues/70861 for details.
245+
mir_build_pointer_pattern = function pointers and raw pointers not derived from integers in patterns behave unpredictably and should not be relied upon. See https://github.com/rust-lang/rust/issues/70861 for details.
246246
247247
mir_build_privately_uninhabited = pattern `{$witness_1}` is currently uninhabited, but this variant contains private fields which may become inhabited in the future
248248

compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs

+25-8
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,8 @@ impl<'tcx> ConstToPat<'tcx> {
123123
});
124124
debug!(?check_body_for_struct_match_violation, ?mir_structural_match_violation);
125125

126+
let have_valtree =
127+
matches!(cv, mir::Const::Ty(c) if matches!(c.kind(), ty::ConstKind::Value(_)));
126128
let inlined_const_as_pat = match cv {
127129
mir::Const::Ty(c) => match c.kind() {
128130
ty::ConstKind::Param(_)
@@ -238,7 +240,9 @@ impl<'tcx> ConstToPat<'tcx> {
238240
}
239241
} else if !self.saw_const_match_lint.get() {
240242
match cv.ty().kind() {
241-
ty::RawPtr(pointee) if pointee.ty.is_sized(self.tcx(), self.param_env) => {}
243+
ty::RawPtr(..) if have_valtree => {
244+
// This is a good raw pointer, it was accepted by valtree construction.
245+
}
242246
ty::FnPtr(..) | ty::RawPtr(..) => {
243247
self.tcx().emit_spanned_lint(
244248
lint::builtin::POINTER_STRUCTURAL_MATCH,
@@ -389,11 +393,19 @@ impl<'tcx> ConstToPat<'tcx> {
389393
subpatterns: self
390394
.field_pats(cv.unwrap_branch().iter().copied().zip(fields.iter()))?,
391395
},
392-
ty::Adt(def, args) => PatKind::Leaf {
393-
subpatterns: self.field_pats(cv.unwrap_branch().iter().copied().zip(
394-
def.non_enum_variant().fields.iter().map(|field| field.ty(self.tcx(), args)),
395-
))?,
396-
},
396+
ty::Adt(def, args) => {
397+
assert!(!def.is_union()); // Valtree construction would never succeed for unions.
398+
PatKind::Leaf {
399+
subpatterns: self.field_pats(
400+
cv.unwrap_branch().iter().copied().zip(
401+
def.non_enum_variant()
402+
.fields
403+
.iter()
404+
.map(|field| field.ty(self.tcx(), args)),
405+
),
406+
)?,
407+
}
408+
}
397409
ty::Slice(elem_ty) => PatKind::Slice {
398410
prefix: cv
399411
.unwrap_branch()
@@ -480,10 +492,15 @@ impl<'tcx> ConstToPat<'tcx> {
480492
}
481493
}
482494
},
483-
ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) => {
495+
ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::RawPtr(..) => {
496+
// The raw pointers we see here have been "vetted" by valtree construction to be
497+
// just integers, so we simply allow them.
484498
PatKind::Constant { value: mir::Const::Ty(ty::Const::new_value(tcx, cv, ty)) }
485499
}
486-
ty::FnPtr(..) | ty::RawPtr(..) => unreachable!(),
500+
ty::FnPtr(..) => {
501+
// Valtree construction would never succeed for these, so this is unreachable.
502+
unreachable!()
503+
}
487504
_ => {
488505
let err = InvalidPattern { span, non_sm_ty: ty };
489506
let e = tcx.sess.emit_err(err);

tests/ui/consts/const_in_pattern/issue-44333.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,9 @@ const BAR: Func = bar;
1616

1717
fn main() {
1818
match test(std::env::consts::ARCH.len()) {
19-
FOO => println!("foo"), //~ WARN pointers in patterns behave unpredictably
19+
FOO => println!("foo"), //~ WARN behave unpredictably
2020
//~^ WARN will become a hard error
21-
BAR => println!("bar"), //~ WARN pointers in patterns behave unpredictably
21+
BAR => println!("bar"), //~ WARN behave unpredictably
2222
//~^ WARN will become a hard error
2323
_ => unreachable!(),
2424
}

tests/ui/consts/const_in_pattern/issue-44333.stderr

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
warning: function pointers and unsized pointers in patterns behave unpredictably and should not be relied upon. See https://github.com/rust-lang/rust/issues/70861 for details.
1+
warning: function pointers and raw pointers not derived from integers in patterns behave unpredictably and should not be relied upon. See https://github.com/rust-lang/rust/issues/70861 for details.
22
--> $DIR/issue-44333.rs:19:9
33
|
44
LL | FOO => println!("foo"),
@@ -12,7 +12,7 @@ note: the lint level is defined here
1212
LL | #![warn(pointer_structural_match)]
1313
| ^^^^^^^^^^^^^^^^^^^^^^^^
1414

15-
warning: function pointers and unsized pointers in patterns behave unpredictably and should not be relied upon. See https://github.com/rust-lang/rust/issues/70861 for details.
15+
warning: function pointers and raw pointers not derived from integers in patterns behave unpredictably and should not be relied upon. See https://github.com/rust-lang/rust/issues/70861 for details.
1616
--> $DIR/issue-44333.rs:21:9
1717
|
1818
LL | BAR => println!("bar"),
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
1-
// run-pass
2-
3-
#![warn(pointer_structural_match)]
1+
#![deny(pointer_structural_match)]
42
#![allow(dead_code)]
53
const C: *const u8 = &0;
64

75
fn foo(x: *const u8) {
86
match x {
9-
C => {}
7+
C => {} //~ERROR: behave unpredictably
8+
//~| previously accepted
109
_ => {}
1110
}
1211
}
@@ -15,7 +14,8 @@ const D: *const [u8; 4] = b"abcd";
1514

1615
fn main() {
1716
match D {
18-
D => {}
17+
D => {} //~ERROR: behave unpredictably
18+
//~| previously accepted
1919
_ => {}
2020
}
2121
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
error: function pointers and raw pointers not derived from integers in patterns behave unpredictably and should not be relied upon. See https://github.com/rust-lang/rust/issues/70861 for details.
2+
--> $DIR/issue-34784-match-on-non-int-raw-ptr.rs:7:9
3+
|
4+
LL | C => {}
5+
| ^
6+
|
7+
= warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
8+
= note: for more information, see issue #62411 <https://github.com/rust-lang/rust/issues/70861>
9+
note: the lint level is defined here
10+
--> $DIR/issue-34784-match-on-non-int-raw-ptr.rs:1:9
11+
|
12+
LL | #![deny(pointer_structural_match)]
13+
| ^^^^^^^^^^^^^^^^^^^^^^^^
14+
15+
error: function pointers and raw pointers not derived from integers in patterns behave unpredictably and should not be relied upon. See https://github.com/rust-lang/rust/issues/70861 for details.
16+
--> $DIR/issue-34784-match-on-non-int-raw-ptr.rs:17:9
17+
|
18+
LL | D => {}
19+
| ^
20+
|
21+
= warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
22+
= note: for more information, see issue #62411 <https://github.com/rust-lang/rust/issues/70861>
23+
24+
error: aborting due to 2 previous errors
25+

tests/ui/rfcs/rfc-1445-restrict-constants-in-patterns/issue-63479-match-fnptr.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ fn main() {
3333
let s = B(my_fn);
3434
match s {
3535
B(TEST) => println!("matched"),
36-
//~^ WARN pointers in patterns behave unpredictably
36+
//~^ WARN behave unpredictably
3737
//~| WARN this was previously accepted by the compiler but is being phased out
3838
_ => panic!("didn't match")
3939
};

tests/ui/rfcs/rfc-1445-restrict-constants-in-patterns/issue-63479-match-fnptr.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
warning: function pointers and unsized pointers in patterns behave unpredictably and should not be relied upon. See https://github.com/rust-lang/rust/issues/70861 for details.
1+
warning: function pointers and raw pointers not derived from integers in patterns behave unpredictably and should not be relied upon. See https://github.com/rust-lang/rust/issues/70861 for details.
22
--> $DIR/issue-63479-match-fnptr.rs:35:7
33
|
44
LL | B(TEST) => println!("matched"),

0 commit comments

Comments
 (0)