1use rustc_abi::{Align, AlignFromBytesError, Size};
2use rustc_ast::expand::allocator::SpecialAllocatorMethod;
3use rustc_middle::ty::Ty;
4use rustc_span::Symbol;
5use rustc_target::callconv::FnAbi;
6use rustc_target::spec::{Arch, Os};
7
8use crate::*;
9
10impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
11pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
12 fn malloc_align(&self, size: u64) -> Align {
14 let ecx = self.eval_context_ref();
15 let os = &ecx.tcx.sess.target.os;
23 let max_fundamental_align = match &ecx.tcx.sess.target.arch {
24 Arch::RiscV32 if matches!(os, Os::EspIdf | Os::Zkvm) => 4,
25 Arch::Xtensa if matches!(os, Os::EspIdf) => 4,
26 Arch::X86
27 | Arch::Arm
28 | Arch::M68k
29 | Arch::CSky
30 | Arch::LoongArch32
31 | Arch::Mips
32 | Arch::Mips32r6
33 | Arch::PowerPC
34 | Arch::PowerPC64
35 | Arch::Sparc
36 | Arch::Wasm32
37 | Arch::Hexagon
38 | Arch::RiscV32
39 | Arch::Xtensa => 8,
40 Arch::X86_64
41 | Arch::AArch64
42 | Arch::Arm64EC
43 | Arch::LoongArch64
44 | Arch::Mips64
45 | Arch::Mips64r6
46 | Arch::S390x
47 | Arch::Sparc64
48 | Arch::RiscV64
49 | Arch::Wasm64 => 16,
50 arch @ (Arch::AmdGpu
51 | Arch::Avr
52 | Arch::Bpf
53 | Arch::Msp430
54 | Arch::Nvptx64
55 | Arch::SpirV
56 | Arch::Other(_)) => bug!("unsupported target architecture for malloc: `{arch}`"),
57 };
58 if size >= max_fundamental_align {
67 return Align::from_bytes(max_fundamental_align).unwrap();
68 }
69 if size == 0 {
71 return Align::ONE;
72 }
73 fn prev_power_of_two(x: u64) -> u64 {
75 let next_pow2 = x.next_power_of_two();
76 if next_pow2 == x {
77 x
79 } else {
80 next_pow2 / 2
82 }
83 }
84 Align::from_bytes(prev_power_of_two(size)).unwrap()
85 }
86
87 fn check_rust_alloc_request(&self, size: u64, align: u64) -> InterpResult<'tcx> {
90 let ecx = self.eval_context_ref();
91 if size == 0 {
92 throw_ub_format!("creating allocation with size 0");
93 }
94 if size > ecx.max_size_of_val().bytes() {
95 throw_ub_format!("creating an allocation larger than half the address space");
96 }
97 if let Err(e) = Align::from_bytes(align) {
98 match e {
99 AlignFromBytesError::TooLarge(_) => {
100 throw_unsup_format!(
101 "creating allocation with alignment {align} exceeding rustc's maximum \
102 supported value"
103 );
104 }
105 AlignFromBytesError::NotPowerOfTwo(_) => {
106 throw_ub_format!("creating allocation with non-power-of-two alignment {align}");
107 }
108 AlignFromBytesError::NotWholeNumberOfBytes(_) => unreachable!(),
109 }
110 }
111
112 interp_ok(())
113 }
114
115 fn rust_special_allocator_method(
116 &mut self,
117 method: SpecialAllocatorMethod,
118 link_name: Symbol,
119 abi: &FnAbi<'tcx, Ty<'tcx>>,
120 args: &[OpTy<'tcx>],
121 dest: &PlaceTy<'tcx>,
122 ) -> InterpResult<'tcx> {
123 let ecx = self.eval_context_mut();
124
125 match method {
126 SpecialAllocatorMethod::Alloc | SpecialAllocatorMethod::AllocZeroed => {
127 let [size, align] = &ecx.check_shim_sig(
128 shim_sig!(extern "Rust" fn(usize, core::mem::Alignment) -> *()),
129 (link_name, abi, args),
130 )?;
131 let size = ecx.read_target_usize(size)?;
132 let align = ecx.read_target_usize(align)?;
133
134 ecx.check_rust_alloc_request(size, align)?;
135
136 let ptr = ecx.allocate_ptr(
137 Size::from_bytes(size),
138 Align::from_bytes(align).unwrap(),
139 MiriMemoryKind::Rust.into(),
140 if matches!(method, SpecialAllocatorMethod::AllocZeroed) {
141 AllocInit::Zero
142 } else {
143 AllocInit::Uninit
144 },
145 )?;
146
147 ecx.write_pointer(ptr, dest)
148 }
149 SpecialAllocatorMethod::Dealloc => {
150 let [ptr, old_size, align] = &ecx.check_shim_sig(
151 shim_sig!(extern "Rust" fn(*(), usize, core::mem::Alignment) -> ()),
152 (link_name, abi, args),
153 )?;
154 let ptr = ecx.read_pointer(ptr)?;
155 let old_size = ecx.read_target_usize(old_size)?;
156 let align = ecx.read_target_usize(align)?;
157
158 ecx.deallocate_ptr(
160 ptr,
161 Some((Size::from_bytes(old_size), Align::from_bytes(align).unwrap())),
162 MiriMemoryKind::Rust.into(),
163 )
164 }
165 SpecialAllocatorMethod::Realloc => {
166 let [ptr, old_size, align, new_size] = &ecx.check_shim_sig(
167 shim_sig!(extern "Rust" fn(*(), usize, core::mem::Alignment, usize) -> *()),
168 (link_name, abi, args),
169 )?;
170 let ptr = ecx.read_pointer(ptr)?;
171 let old_size = ecx.read_target_usize(old_size)?;
172 let align = ecx.read_target_usize(align)?;
173 let new_size = ecx.read_target_usize(new_size)?;
174 ecx.check_rust_alloc_request(new_size, align)?;
177
178 let align = Align::from_bytes(align).unwrap();
179 let new_ptr = ecx.reallocate_ptr(
180 ptr,
181 Some((Size::from_bytes(old_size), align)),
182 Size::from_bytes(new_size),
183 align,
184 MiriMemoryKind::Rust.into(),
185 AllocInit::Uninit,
186 )?;
187 ecx.write_pointer(new_ptr, dest)
188 }
189 }
190 }
191
192 fn malloc(&mut self, size: u64, init: AllocInit) -> InterpResult<'tcx, Pointer> {
193 let ecx = self.eval_context_mut();
194 let align = ecx.malloc_align(size);
195 let ptr =
196 ecx.allocate_ptr(Size::from_bytes(size), align, MiriMemoryKind::C.into(), init)?;
197 interp_ok(ptr.into())
198 }
199
200 fn posix_memalign(
201 &mut self,
202 memptr: &OpTy<'tcx>,
203 align: &OpTy<'tcx>,
204 size: &OpTy<'tcx>,
205 ) -> InterpResult<'tcx, Scalar> {
206 let ecx = self.eval_context_mut();
207 let memptr = ecx.deref_pointer(memptr)?;
208 let align = ecx.read_target_usize(align)?;
209 let size = ecx.read_target_usize(size)?;
210
211 if !align.is_power_of_two() || align < ecx.pointer_size().bytes() {
214 interp_ok(ecx.eval_libc("EINVAL"))
215 } else {
216 let ptr = ecx.allocate_ptr(
217 Size::from_bytes(size),
218 Align::from_bytes(align).unwrap(),
219 MiriMemoryKind::C.into(),
220 AllocInit::Uninit,
221 )?;
222 ecx.write_pointer(ptr, &memptr)?;
223 interp_ok(Scalar::from_i32(0))
224 }
225 }
226
227 fn free(&mut self, ptr: Pointer) -> InterpResult<'tcx> {
228 let ecx = self.eval_context_mut();
229 if !ecx.ptr_is_null(ptr)? {
230 ecx.deallocate_ptr(ptr, None, MiriMemoryKind::C.into())?;
231 }
232 interp_ok(())
233 }
234
235 fn realloc(&mut self, old_ptr: Pointer, new_size: u64) -> InterpResult<'tcx, Pointer> {
236 let ecx = self.eval_context_mut();
237 let new_align = ecx.malloc_align(new_size);
238 if ecx.ptr_is_null(old_ptr)? {
239 self.malloc(new_size, AllocInit::Uninit)
241 } else {
242 if new_size == 0 {
243 throw_ub_format!("`realloc` with a size of zero");
246 } else {
247 let new_ptr = ecx.reallocate_ptr(
248 old_ptr,
249 None,
250 Size::from_bytes(new_size),
251 new_align,
252 MiriMemoryKind::C.into(),
253 AllocInit::Uninit,
254 )?;
255 interp_ok(new_ptr.into())
256 }
257 }
258 }
259
260 fn aligned_alloc(
261 &mut self,
262 align: &OpTy<'tcx>,
263 size: &OpTy<'tcx>,
264 ) -> InterpResult<'tcx, Pointer> {
265 let ecx = self.eval_context_mut();
266 let align = ecx.read_target_usize(align)?;
267 let size = ecx.read_target_usize(size)?;
268
269 match size.checked_rem(align) {
288 Some(0) if align.is_power_of_two() => {
289 let align = align.max(ecx.malloc_align(size).bytes());
290 let ptr = ecx.allocate_ptr(
291 Size::from_bytes(size),
292 Align::from_bytes(align).unwrap(),
293 MiriMemoryKind::C.into(),
294 AllocInit::Uninit,
295 )?;
296 interp_ok(ptr.into())
297 }
298 _ => interp_ok(Pointer::null()),
299 }
300 }
301}