Skip to content

Commit 60fa909

Browse files
authored
Merge pull request #1551 from N1ark/consts-rework-prov
Handle `TypeId` provenance
2 parents f569863 + 5a56c01 commit 60fa909

31 files changed

Lines changed: 578 additions & 104 deletions

‎charon-ml/src/CharonVersion.ml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
(* This is an automatically generated file, generated from `charon/Cargo.toml`. *)
22
(* To re-generate this file, rune `make` in the root directory *)
3-
let supported_charon_version = "0.1.297"
3+
let supported_charon_version = "0.1.298"

‎charon-ml/src/PrintFmt.ml‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -476,13 +476,18 @@ and pp_provenance (env : fmt_env) (fmt : Format.formatter)
476476
match pv with
477477
| ProvGlobal gref -> Format.fprintf fmt "&%a" (pp_global_decl_ref env) gref
478478
| ProvFunction (fn_ptr, _) -> Format.fprintf fmt "&%a" (pp_fn_ptr env) fn_ptr
479+
| ProvTypeId ty -> Format.fprintf fmt "&TypeId(%a)" (pp_ty env) ty
479480
| ProvUnknown -> pp_string fmt "&?"
480481

481482
and pp_byte (env : fmt_env) (fmt : Format.formatter) (cv : byte) : unit =
482483
match cv with
483484
| Uninit -> pp_string fmt "--"
484485
| Value b -> Format.fprintf fmt "0x%02x" b
485-
| Provenance (p, i) -> Format.fprintf fmt "%a[%d]" (pp_provenance env) p i
486+
| Provenance (p, ofs, i) ->
487+
let ofs = Scalars.get_val ofs in
488+
if Z.equal ofs Z.zero then
489+
Format.fprintf fmt "%a[%d]" (pp_provenance env) p i
490+
else Format.fprintf fmt "%a+%a[%d]" (pp_provenance env) p pp_big_int ofs i
486491

487492
and pp_unsizing_metadata (env : fmt_env) (fmt : Format.formatter)
488493
(meta : unsizing_metadata) : unit =
@@ -643,6 +648,8 @@ and pp_global_place (env : fmt_env) (fmt : Format.formatter) (p : global_place)
643648
match p.global_place_kind with
644649
| GlobalPlaceGlobal (ProvGlobal gref) -> pp_global_decl_ref env fmt gref
645650
| GlobalPlaceGlobal (ProvFunction (fn_ptr, _)) -> pp_fn_ptr env fmt fn_ptr
651+
| GlobalPlaceGlobal (ProvTypeId ty) ->
652+
Format.fprintf fmt "TypeId(%a)" (pp_ty env) ty
646653
| GlobalPlaceGlobal ProvUnknown -> pp_string fmt "?"
647654
| GlobalPlaceValue c -> pp_constant_expr env fmt c
648655
| GlobalPlaceProjection (subplace, proj) -> (

‎charon-ml/src/generated/Generated_OfJson.ml‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -492,10 +492,11 @@ and byte_of_json (ctx : of_json_ctx) (js : json) : (byte, string) result =
492492
| `Assoc [ ("Value", _0) ] ->
493493
let* _0 = int_of_json ctx _0 in
494494
Ok (Value _0)
495-
| `Assoc [ ("Provenance", `List [ _0; _1 ]) ] ->
495+
| `Assoc [ ("Provenance", `List [ _0; _1; _2 ]) ] ->
496496
let* _0 = global_provenance_of_json ctx _0 in
497-
let* _1 = int_of_json ctx _1 in
498-
Ok (Provenance (_0, _1))
497+
let* _1 = integer_value_of_json ctx _1 in
498+
let* _2 = int_of_json ctx _2 in
499+
Ok (Provenance (_0, _1, _2))
499500
| _ -> Error "")
500501

501502
and call_of_json (ctx : of_json_ctx) (js : json) : (call, string) result =
@@ -1005,6 +1006,9 @@ and global_provenance_of_json (ctx : of_json_ctx) (js : json) :
10051006
let* _0 = fn_ptr_of_json ctx _0 in
10061007
let* _1 = ty_of_json ctx _1 in
10071008
Ok (ProvFunction (_0, _1))
1009+
| `Assoc [ ("TypeId", _0) ] ->
1010+
let* _0 = ty_of_json ctx _0 in
1011+
Ok (ProvTypeId _0)
10081012
| `String "Unknown" -> Ok ProvUnknown
10091013
| _ -> Error "")
10101014

‎charon-ml/src/generated/Generated_OfPostcard.ml‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -444,8 +444,9 @@ and byte_of_postcard (ctx : of_postcard_ctx) (st : postcard_state) :
444444
Ok (Value _0)
445445
| 2 ->
446446
let* _0 = global_provenance_of_postcard ctx st in
447-
let* _1 = u8_of_postcard ctx st in
448-
Ok (Provenance (_0, _1))
447+
let* _1 = integer_value_of_postcard ctx st in
448+
let* _2 = u8_of_postcard ctx st in
449+
Ok (Provenance (_0, _1, _2))
449450
| _ -> Error ("unknown enum variant tag: " ^ string_of_int __tag))
450451

451452
and call_of_postcard (ctx : of_postcard_ctx) (st : postcard_state) :
@@ -895,7 +896,10 @@ and global_provenance_of_postcard (ctx : of_postcard_ctx) (st : postcard_state)
895896
let* _0 = fn_ptr_of_postcard ctx st in
896897
let* _1 = ty_of_postcard ctx st in
897898
Ok (ProvFunction (_0, _1))
898-
| 2 -> Ok ProvUnknown
899+
| 2 ->
900+
let* _0 = ty_of_postcard ctx st in
901+
Ok (ProvTypeId _0)
902+
| 3 -> Ok ProvUnknown
899903
| _ -> Error ("unknown enum variant tag: " ^ string_of_int __tag))
900904

901905
and hash_consed_of_postcard :

‎charon-ml/src/generated/Generated_Types.ml‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -253,10 +253,11 @@ and builtin_impl_data =
253253
and byte =
254254
| Uninit (** An uninitialized byte *)
255255
| Value of int (** A concrete byte value *)
256-
| Provenance of global_provenance * int
257-
(** A byte that is part of a pointer with provenance. The u8 is the offset
258-
within the pointer. Note that we do not have an actual value for this
259-
pointer byte, unlike MiniRust, as that is non-deterministic. *)
256+
| Provenance of global_provenance * integer_value * int
257+
(** A byte that is part of a pointer with provenance, at the given offset
258+
into the pointee. The u8 is the index of this byte within the pointer.
259+
Note that we do not have an actual value for this pointer byte, unlike
260+
MiniRust, as that is non-deterministic. *)
260261

261262
(** Cast the operand to a new type. *)
262263
and cast_kind =
@@ -516,6 +517,12 @@ and global_provenance =
516517
| ProvGlobal of global_decl_ref
517518
| ProvFunction of fn_ptr * ty
518519
(** A function, with the type of function pointers to it. *)
520+
| ProvTypeId of ty
521+
(** The allocation backing the [TypeId] of this type. Note that [TypeId]s
522+
always have 16 bytes worth of provenance, regardless of the platform's
523+
pointer size, so [[Byte::Provenance]]'s byte index can go up to 16! In
524+
other words, the bytes of a full [TypeId] are
525+
[Provenance(TypeId(ty), 0, 0..16)]. *)
519526
| ProvUnknown
520527

521528
(** Hash-consed data structure: a reference-counted wrapper that guarantees that

‎charon/Cargo.lock‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎charon/Cargo.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ tracing = { version = "0.1", features = ["max_level_trace"] }
2727

2828
[package]
2929
name = "charon"
30-
version = "0.1.297"
30+
version = "0.1.298"
3131
authors.workspace = true
3232
edition.workspace = true
3333
license.workspace = true

‎charon/rustc_const_uneval/src/lib.rs‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ mod valtree;
1818

1919
pub use eval::promoted_body;
2020

21-
use rustc_abi::{ExternAbi, FieldIdx, VariantIdx};
21+
use rustc_abi::{ExternAbi, FieldIdx, Size, VariantIdx};
2222
use rustc_hir::def_id::DefId;
2323
use rustc_middle::mir::{self, interpret};
2424
use rustc_middle::ty::{self, Ty, TyCtxt};
@@ -123,6 +123,8 @@ pub enum ConstKind<'tcx> {
123123
},
124124
/// A function pointer.
125125
FnPtr(FnTarget<'tcx>),
126+
/// The `TypeId` of this type.
127+
TypeId(Ty<'tcx>),
126128
/// A valid reference or raw pointer; `ty` tells which.
127129
Ptr {
128130
target: PtrTarget<'tcx>,
@@ -168,7 +170,7 @@ impl<'tcx> ConstKind<'tcx> {
168170
#[derive(Debug, Clone)]
169171
pub enum PtrTarget<'tcx> {
170172
/// A place inside a global (anything with provenance): `projections` applied to the allocation
171-
/// of `target`, whose type is `ty`. A function has no contents, so its type is `()`.
173+
/// of `target`, whose type is `ty`. Allocations without contents have type `()`.
172174
Global {
173175
target: AllocTarget<'tcx>,
174176
ty: Ty<'tcx>,
@@ -216,9 +218,9 @@ pub enum Byte<'tcx> {
216218
Uninit,
217219
/// A concrete byte value.
218220
Value(u8),
219-
/// A byte of a pointer into the given allocation. The `u8` is the index of this byte within the
220-
/// pointer.
221-
Ptr(AllocTarget<'tcx>, u8),
221+
/// A byte of a pointer at the given offset into the given allocation. The `u8` is the index of
222+
/// this byte within the pointer.
223+
Ptr(AllocTarget<'tcx>, Size, u8),
222224
}
223225

224226
/// A global allocation.

‎charon/rustc_const_uneval/src/memory.rs‎

Lines changed: 73 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
use crate::*;
33
use interpret::GlobalAlloc;
44
use rustc_abi::{FieldIdx, Size};
5+
use rustc_attr_ir::LangItem;
56
use rustc_const_eval::const_eval::CompileTimeInterpCx;
67
use rustc_const_eval::interpret::{
78
FnVal, ImmTy, Immediate, InterpResult, MPlaceTy, OpTy, Projectable, interp_ok,
@@ -68,9 +69,11 @@ impl<'tcx> ConstReader<'tcx> {
6869
}
6970
}
7071
interpret::Scalar::Ptr(ptr, size) => {
71-
let target = self.alloc_target(ptr.provenance.alloc_id());
72+
let (prov, ptr_offset) = ptr.into_raw_parts();
73+
let target = self.alloc_target(prov.alloc_id());
7274
for i in 0..size.get() {
73-
bytes[offset.bytes_usize() + i as usize] = Byte::Ptr(target, i);
75+
bytes[offset.bytes_usize() + i as usize] =
76+
self.ptr_byte(target, ptr_offset, i);
7477
}
7578
}
7679
};
@@ -114,12 +117,25 @@ impl<'tcx> ConstReader<'tcx> {
114117
.collect();
115118

116119
// A pointer may straddle the boundaries of `range`.
120+
let ptr_size = self.tcx.data_layout.pointer_size();
117121
for (prov_range, prov) in alloc.provenance().get_range(range, ecx) {
118122
let target = self.alloc_target(prov.alloc_id());
123+
// This is either a whole pointer, or a single byte of one whose index and pointer
124+
// bytes are stored with its provenance.
125+
let (first_idx, ptr_bytes) = if prov_range.size == ptr_size {
126+
(0, alloc.get_bytes_unchecked(prov_range))
127+
} else {
128+
let frag = alloc.provenance().get_byte(prov_range.start, ecx).unwrap();
129+
(frag.idx, &frag.bytes[..ptr_size.bytes_usize()])
130+
};
131+
let ptr_offset =
132+
interpret::read_target_uint(self.tcx.data_layout.endian, ptr_bytes).unwrap();
133+
let ptr_offset = Size::from_bytes(ptr_offset);
119134
for i in 0..prov_range.size.bytes() {
120135
let pos = prov_range.start + Size::from_bytes(i);
121136
if range.start <= pos && pos < range.end() {
122-
bytes[(pos - range.start).bytes_usize()] = Byte::Ptr(target, i as u8);
137+
bytes[(pos - range.start).bytes_usize()] =
138+
self.ptr_byte(target, ptr_offset, first_idx + i as u8);
123139
}
124140
}
125141
}
@@ -146,6 +162,54 @@ impl<'tcx> ConstReader<'tcx> {
146162
})
147163
}
148164

165+
/// The type whose `TypeId` `op` is.
166+
fn read_type_id(
167+
&self,
168+
ecx: &CompileTimeInterpCx<'tcx>,
169+
op: &OpTy<'tcx>,
170+
) -> InterpResult<'tcx, Option<Ty<'tcx>>> {
171+
let bytes = self.read_raw_bytes(ecx, op)?;
172+
if let Some(&Byte::Ptr(AllocTarget::TypeId(ty), ..)) = bytes.first()
173+
&& bytes.iter().enumerate().all(|(k, &byte)| {
174+
matches!(byte, Byte::Ptr(AllocTarget::TypeId(byte_ty), offset, i)
175+
if byte_ty == ty && offset == Size::ZERO && i as usize == k)
176+
})
177+
{
178+
return interp_ok(Some(ty));
179+
}
180+
interp_ok(None)
181+
}
182+
183+
/// The byte at index `i` of a pointer at `offset` into `target`.
184+
///
185+
/// Use this, rather than building a [`Byte::Ptr`] manually, as this does some tricks to
186+
/// avoid leaking the hash of `TypeId` targets (which are encoded in the pointer's offset).
187+
fn ptr_byte(&self, target: AllocTarget<'tcx>, offset: Size, i: u8) -> Byte<'tcx> {
188+
if let AllocTarget::TypeId(ty) = target {
189+
let ptr_size = self.tcx.data_layout.pointer_size();
190+
let hash = self.type_id_hash(ty);
191+
// if nothing matches, we assume chunk 0 and leak the (relative) offset :(
192+
let chunk = hash.iter().position(|&h| h == offset.bytes()).unwrap_or(0);
193+
let offset = ptr_size.truncate(offset.bytes().wrapping_sub(hash[chunk]).into());
194+
let i = chunk as u8 * ptr_size.bytes() as u8 + i;
195+
return Byte::Ptr(target, Size::from_bytes(offset), i);
196+
}
197+
Byte::Ptr(target, offset, i)
198+
}
199+
200+
/// The values of the pointers that make up the `TypeId` of `ty`.
201+
fn type_id_hash(&self, ty: Ty<'tcx>) -> Vec<u64> {
202+
let dl = &self.tcx.data_layout;
203+
let hash = self.tcx.type_id_hash(ty).as_u128();
204+
let hash = match dl.endian {
205+
rustc_abi::Endian::Little => hash.to_le_bytes(),
206+
rustc_abi::Endian::Big => hash.to_be_bytes(),
207+
};
208+
hash.chunks(dl.pointer_size().bytes_usize())
209+
.map(|chunk| interpret::read_target_uint(dl.endian, chunk).unwrap() as u64)
210+
.collect()
211+
}
212+
149213
/// Read an evaluated operand back as a structured constant.
150214
pub(crate) fn read_op(
151215
&self,
@@ -171,6 +235,12 @@ impl<'tcx> ConstReader<'tcx> {
171235
ty::Adt(adt_def, ..) if adt_def.is_union() => {
172236
ConstKind::Memory(self.read_raw_bytes(ecx, &op)?)
173237
}
238+
ty::Adt(adt_def, ..)
239+
if self.tcx.is_lang_item(adt_def.did(), LangItem::TypeId)
240+
&& let Some(ty) = self.read_type_id(ecx, &op)? =>
241+
{
242+
ConstKind::TypeId(ty)
243+
}
174244
ty::Adt(adt_def, ..) => {
175245
let variant = ecx.read_discriminant(&op)?;
176246
let op = if adt_def.is_enum() {

‎charon/rustc_const_uneval/src/pointer.rs‎

Lines changed: 32 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,25 @@
22
use crate::*;
33
use rustc_abi::{FieldIdx, FieldsShape, Size};
44
use rustc_const_eval::const_eval::CompileTimeInterpCx;
5-
use rustc_const_eval::interpret::{InterpResult, MPlaceTy, OpTy, Projectable, interp_ok};
5+
use rustc_const_eval::interpret::{AllocId, InterpResult, MPlaceTy, OpTy, Projectable, interp_ok};
66

77
impl<'tcx> ConstReader<'tcx> {
8+
/// Whether this allocation target should be read through a pointer -- it is otherwise
9+
/// read directly, breaking sharing.
10+
fn should_use_pointer(&self, tgt: AllocTarget, in_bounds: bool, alloc_id: AllocId) -> bool {
11+
match tgt {
12+
AllocTarget::Global(global) => {
13+
self.is_named_global(global)
14+
// We can't read the pointee of a pointer outside of its allocation, so we
15+
// name the allocation even if we otherwise inline them.
16+
|| !in_bounds
17+
&& matches!(self.tcx.global_alloc(alloc_id), interpret::GlobalAlloc::Memory(_))
18+
}
19+
AllocTarget::Fn(_) => true,
20+
AllocTarget::VTable(..) | AllocTarget::TypeId(..) => false,
21+
}
22+
}
23+
824
/// Read a reference or raw pointer. Pointers to globals that we name are kept as pointers to
925
/// these globals, and we fall back to reading the pointee for other cases.
1026
pub(crate) fn read_pointer(
@@ -27,6 +43,14 @@ impl<'tcx> ConstReader<'tcx> {
2743
kind,
2844
});
2945
};
46+
// A pointer into the allocation of a `TypeId` can only be expressed as bytes.
47+
if let AllocTarget::TypeId(_) = self.alloc_target(alloc_id) {
48+
let kind = ConstKind::Memory(self.read_raw_bytes(ecx, op)?);
49+
return interp_ok(Const {
50+
ty: op.layout.ty,
51+
kind,
52+
});
53+
}
3054

3155
let ty = place.layout.ty;
3256
let unsize = if place.meta().has_meta() {
@@ -46,20 +70,10 @@ impl<'tcx> ConstReader<'tcx> {
4670
// A pointer outside of its allocation (one-past-the-end is fine) needs a wrapping offset.
4771
let in_bounds = offset <= ecx.get_alloc_info(alloc_id).size;
4872
let kind = if let Some(view_ty) = view_ty
49-
&& match alloc_target {
50-
AllocTarget::Global(global) => {
51-
self.is_named_global(global)
52-
// We can't read the pointee of a pointer outside of its allocation, so we
53-
// name the allocation even if we otherwise inline them.
54-
|| !in_bounds
55-
&& matches!(tcx.global_alloc(alloc_id), interpret::GlobalAlloc::Memory(_))
56-
}
57-
AllocTarget::Fn(_) => true,
58-
AllocTarget::VTable(..) | AllocTarget::TypeId(..) => false,
59-
}
60-
&& let Some((decl_ty, projections, end_ty)) =
61-
self.place_in_global(ecx, &place, alloc_target, offset, in_bounds, view_ty)
73+
&& self.should_use_pointer(alloc_target, in_bounds, alloc_id)
6274
{
75+
let (decl_ty, projections, end_ty) =
76+
self.place_in_global(ecx, &place, alloc_target, offset, in_bounds, view_ty)?;
6377
let target = PtrTarget::Global {
6478
target: alloc_target,
6579
ty: decl_ty,
@@ -143,10 +157,10 @@ impl<'tcx> ConstReader<'tcx> {
143157
offset: Size,
144158
in_bounds: bool,
145159
ty: Ty<'tcx>,
146-
) -> Option<(Ty<'tcx>, ProjectionPath<'tcx>, Ty<'tcx>)> {
160+
) -> InterpResult<'tcx, (Ty<'tcx>, ProjectionPath<'tcx>, Ty<'tcx>)> {
147161
let tcx = self.tcx;
148162
let ty = tcx.erase_and_anonymize_regions(ty);
149-
let size = ecx.layout_of(ty).ok()?.size;
163+
let size = ecx.layout_of(ty)?.size;
150164
let decl_ty = match global {
151165
AllocTarget::Global(global) => tcx.erase_and_anonymize_regions(self.global_ty(global)),
152166
// Other allocations have no contents.
@@ -158,7 +172,7 @@ impl<'tcx> ConstReader<'tcx> {
158172
{
159173
let (prov, _) = place.ptr().into_raw_parts();
160174
let ptr = interpret::Pointer::new(prov, Size::ZERO);
161-
let base = ecx.ptr_to_mplace(ptr, ecx.layout_of(decl_ty).ok()?);
175+
let base = ecx.ptr_to_mplace(ptr, ecx.layout_of(decl_ty)?);
162176
structural_path(ecx, base, offset, ty, size)
163177
} else {
164178
// The offset of a pointer outside of its allocation may be negative.
@@ -171,7 +185,7 @@ impl<'tcx> ConstReader<'tcx> {
171185
let end_ty = if proj.is_some() { ty } else { decl_ty };
172186
(proj.map(|proj| (proj, ty)).into_iter().collect(), end_ty)
173187
};
174-
Some((decl_ty, path, end_ty))
188+
interp_ok((decl_ty, path, end_ty))
175189
}
176190
}
177191

0 commit comments

Comments
 (0)