1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
use std::borrow::Cow;
use std::convert::TryFrom;
use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
use rustc_middle::ty::layout::{self, LayoutOf as _, TyAndLayout};
use rustc_middle::ty::Instance;
use rustc_middle::{
mir,
ty::{self, Ty},
};
use rustc_target::abi;
use rustc_target::spec::abi::Abi;
use super::{
FnVal, ImmTy, InterpCx, InterpResult, MPlaceTy, Machine, OpTy, PlaceTy, Scalar,
StackPopCleanup, StackPopUnwind,
};
impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
fn fn_can_unwind(&self, attrs: CodegenFnAttrFlags, abi: Abi) -> bool {
layout::fn_can_unwind(*self.tcx, attrs, abi)
}
pub(super) fn eval_terminator(
&mut self,
terminator: &mir::Terminator<'tcx>,
) -> InterpResult<'tcx> {
use rustc_middle::mir::TerminatorKind::*;
match terminator.kind {
Return => {
self.pop_stack_frame( false)?
}
Goto { target } => self.go_to_block(target),
SwitchInt { ref discr, ref targets, switch_ty } => {
let discr = self.read_immediate(&self.eval_operand(discr, None)?)?;
trace!("SwitchInt({:?})", *discr);
assert_eq!(discr.layout.ty, switch_ty);
assert!(!targets.iter().is_empty());
let mut target_block = targets.otherwise();
for (const_int, target) in targets.iter() {
let res = self
.overflowing_binary_op(
mir::BinOp::Eq,
&discr,
&ImmTy::from_uint(const_int, discr.layout),
)?
.0;
if res.to_bool()? {
target_block = target;
break;
}
}
self.go_to_block(target_block);
}
Call { ref func, ref args, destination, ref cleanup, from_hir_call: _, fn_span: _ } => {
let old_stack = self.frame_idx();
let old_loc = self.frame().loc;
let func = self.eval_operand(func, None)?;
let (fn_val, abi, caller_can_unwind) = match *func.layout.ty.kind() {
ty::FnPtr(sig) => {
let caller_abi = sig.abi();
let fn_ptr = self.read_pointer(&func)?;
let fn_val = self.memory.get_fn(fn_ptr)?;
(
fn_val,
caller_abi,
self.fn_can_unwind(CodegenFnAttrFlags::empty(), caller_abi),
)
}
ty::FnDef(def_id, substs) => {
let sig = func.layout.ty.fn_sig(*self.tcx);
(
FnVal::Instance(
self.resolve(ty::WithOptConstParam::unknown(def_id), substs)?,
),
sig.abi(),
self.fn_can_unwind(self.tcx.codegen_fn_attrs(def_id).flags, sig.abi()),
)
}
_ => span_bug!(
terminator.source_info.span,
"invalid callee of type {:?}",
func.layout.ty
),
};
let args = self.eval_operands(args)?;
let dest_place;
let ret = match destination {
Some((dest, ret)) => {
dest_place = self.eval_place(dest)?;
Some((&dest_place, ret))
}
None => None,
};
self.eval_fn_call(
fn_val,
abi,
&args[..],
ret,
match (cleanup, caller_can_unwind) {
(Some(cleanup), true) => StackPopUnwind::Cleanup(*cleanup),
(None, true) => StackPopUnwind::Skip,
(_, false) => StackPopUnwind::NotAllowed,
},
)?;
if self.frame_idx() == old_stack && self.frame().loc == old_loc {
span_bug!(terminator.source_info.span, "evaluating this call made no progress");
}
}
Drop { place, target, unwind } => {
let place = self.eval_place(place)?;
let ty = place.layout.ty;
trace!("TerminatorKind::drop: {:?}, type {}", place, ty);
let instance = Instance::resolve_drop_in_place(*self.tcx, ty);
self.drop_in_place(&place, instance, target, unwind)?;
}
Assert { ref cond, expected, ref msg, target, cleanup } => {
let cond_val =
self.read_immediate(&self.eval_operand(cond, None)?)?.to_scalar()?.to_bool()?;
if expected == cond_val {
self.go_to_block(target);
} else {
M::assert_panic(self, msg, cleanup)?;
}
}
Abort => {
M::abort(self, "the program aborted execution".to_owned())?;
}
Resume => {
trace!("unwinding: resuming from cleanup");
self.pop_stack_frame( true)?;
return Ok(());
}
Unreachable => throw_ub!(Unreachable),
DropAndReplace { .. }
| FalseEdge { .. }
| FalseUnwind { .. }
| Yield { .. }
| GeneratorDrop => span_bug!(
terminator.source_info.span,
"{:#?} should have been eliminated by MIR pass",
terminator.kind
),
InlineAsm { .. } => throw_unsup_format!("inline assembly is not supported"),
}
Ok(())
}
fn check_argument_compat(
rust_abi: bool,
caller: TyAndLayout<'tcx>,
callee: TyAndLayout<'tcx>,
) -> bool {
if caller.ty == callee.ty {
return true;
}
if !rust_abi {
return false;
}
match (caller.abi, callee.abi) {
(abi::Abi::Scalar(caller), abi::Abi::Scalar(callee)) => caller.value == callee.value,
(abi::Abi::ScalarPair(caller1, caller2), abi::Abi::ScalarPair(callee1, callee2)) => {
caller1.value == callee1.value && caller2.value == callee2.value
}
_ => false,
}
}
fn pass_argument(
&mut self,
rust_abi: bool,
caller_arg: &mut impl Iterator<Item = OpTy<'tcx, M::PointerTag>>,
callee_arg: &PlaceTy<'tcx, M::PointerTag>,
) -> InterpResult<'tcx> {
if rust_abi && callee_arg.layout.is_zst() {
trace!("Skipping callee ZST");
return Ok(());
}
let caller_arg = caller_arg.next().ok_or_else(|| {
err_ub_format!("calling a function with fewer arguments than it requires")
})?;
if rust_abi {
assert!(!caller_arg.layout.is_zst(), "ZSTs must have been already filtered out");
}
if !Self::check_argument_compat(rust_abi, caller_arg.layout, callee_arg.layout) {
throw_ub_format!(
"calling a function with argument of type {:?} passing data of type {:?}",
callee_arg.layout.ty,
caller_arg.layout.ty
)
}
self.copy_op_transmute(&caller_arg, callee_arg)
}
pub(crate) fn eval_fn_call(
&mut self,
fn_val: FnVal<'tcx, M::ExtraFnVal>,
caller_abi: Abi,
args: &[OpTy<'tcx, M::PointerTag>],
ret: Option<(&PlaceTy<'tcx, M::PointerTag>, mir::BasicBlock)>,
mut unwind: StackPopUnwind,
) -> InterpResult<'tcx> {
trace!("eval_fn_call: {:#?}", fn_val);
let instance = match fn_val {
FnVal::Instance(instance) => instance,
FnVal::Other(extra) => {
return M::call_extra_fn(self, extra, caller_abi, args, ret, unwind);
}
};
let get_abi = |this: &Self, instance_ty: Ty<'tcx>| match instance_ty.kind() {
ty::FnDef(..) => instance_ty.fn_sig(*this.tcx).abi(),
ty::Closure(..) => Abi::RustCall,
ty::Generator(..) => Abi::Rust,
_ => span_bug!(this.cur_span(), "unexpected callee ty: {:?}", instance_ty),
};
let check_abi = |callee_abi: Abi| -> InterpResult<'tcx> {
let normalize_abi = |abi| match abi {
Abi::Rust | Abi::RustCall | Abi::RustIntrinsic | Abi::PlatformIntrinsic =>
{
Abi::Rust
}
abi => abi,
};
if normalize_abi(caller_abi) != normalize_abi(callee_abi) {
throw_ub_format!(
"calling a function with ABI {} using caller ABI {}",
callee_abi.name(),
caller_abi.name()
)
}
Ok(())
};
match instance.def {
ty::InstanceDef::Intrinsic(..) => {
if M::enforce_abi(self) {
check_abi(get_abi(self, instance.ty(*self.tcx, self.param_env)))?;
}
assert!(caller_abi == Abi::RustIntrinsic || caller_abi == Abi::PlatformIntrinsic);
M::call_intrinsic(self, instance, args, ret, unwind)
}
ty::InstanceDef::VtableShim(..)
| ty::InstanceDef::ReifyShim(..)
| ty::InstanceDef::ClosureOnceShim { .. }
| ty::InstanceDef::FnPtrShim(..)
| ty::InstanceDef::DropGlue(..)
| ty::InstanceDef::CloneShim(..)
| ty::InstanceDef::Item(_) => {
let body =
match M::find_mir_or_eval_fn(self, instance, caller_abi, args, ret, unwind)? {
Some(body) => body,
None => return Ok(()),
};
let callee_def_id = body.source.def_id();
let callee_abi = get_abi(self, self.tcx.type_of(callee_def_id));
if M::enforce_abi(self) {
check_abi(callee_abi)?;
}
if !matches!(unwind, StackPopUnwind::NotAllowed)
&& !self
.fn_can_unwind(self.tcx.codegen_fn_attrs(callee_def_id).flags, callee_abi)
{
unwind = StackPopUnwind::NotAllowed;
}
self.push_stack_frame(
instance,
body,
ret.map(|p| p.0),
StackPopCleanup::Goto { ret: ret.map(|p| p.1), unwind },
)?;
let res: InterpResult<'tcx> = try {
trace!(
"caller ABI: {:?}, args: {:#?}",
caller_abi,
args.iter()
.map(|arg| (arg.layout.ty, format!("{:?}", **arg)))
.collect::<Vec<_>>()
);
trace!(
"spread_arg: {:?}, locals: {:#?}",
body.spread_arg,
body.args_iter()
.map(|local| (
local,
self.layout_of_local(self.frame(), local, None).unwrap().ty
))
.collect::<Vec<_>>()
);
let rust_abi = match caller_abi {
Abi::Rust | Abi::RustCall => true,
_ => false,
};
let caller_args: Cow<'_, [OpTy<'tcx, M::PointerTag>]> =
if caller_abi == Abi::RustCall && !args.is_empty() {
let (untuple_arg, args) = args.split_last().unwrap();
trace!("eval_fn_call: Will pass last argument by untupling");
Cow::from(
args.iter()
.map(|&a| Ok(a))
.chain(
(0..untuple_arg.layout.fields.count())
.map(|i| self.operand_field(untuple_arg, i)),
)
.collect::<InterpResult<'_, Vec<OpTy<'tcx, M::PointerTag>>>>(
)?,
)
} else {
Cow::from(args)
};
let mut caller_iter =
caller_args.iter().filter(|op| !rust_abi || !op.layout.is_zst()).copied();
for local in body.args_iter() {
let dest = self.eval_place(mir::Place::from(local))?;
if Some(local) == body.spread_arg {
for i in 0..dest.layout.fields.count() {
let dest = self.place_field(&dest, i)?;
self.pass_argument(rust_abi, &mut caller_iter, &dest)?;
}
} else {
self.pass_argument(rust_abi, &mut caller_iter, &dest)?;
}
}
if caller_iter.next().is_some() {
throw_ub_format!("calling a function with more arguments than it expected")
}
if let Some((caller_ret, _)) = ret {
let callee_ret = self.eval_place(mir::Place::return_place())?;
if !Self::check_argument_compat(
rust_abi,
caller_ret.layout,
callee_ret.layout,
) {
throw_ub_format!(
"calling a function with return type {:?} passing \
return place of type {:?}",
callee_ret.layout.ty,
caller_ret.layout.ty
)
}
} else {
let local = mir::RETURN_PLACE;
let callee_layout = self.layout_of_local(self.frame(), local, None)?;
if !callee_layout.abi.is_uninhabited() {
throw_ub_format!("calling a returning function without a return place")
}
}
};
match res {
Err(err) => {
self.stack_mut().pop();
Err(err)
}
Ok(()) => Ok(()),
}
}
ty::InstanceDef::Virtual(_, idx) => {
let mut args = args.to_vec();
let receiver_place = match args[0].layout.ty.builtin_deref(true) {
Some(_) => {
self.deref_operand(&args[0])?
}
None => {
args[0].assert_mem_place()
}
};
let vtable = self.scalar_to_ptr(receiver_place.vtable());
let fn_val = self.get_vtable_slot(vtable, u64::try_from(idx).unwrap())?;
assert!(receiver_place.layout.is_unsized());
let receiver_ptr_ty = self.tcx.mk_mut_ptr(receiver_place.layout.ty);
let this_receiver_ptr = self.layout_of(receiver_ptr_ty)?.field(self, 0);
args[0] = OpTy::from(ImmTy::from_immediate(
Scalar::from_maybe_pointer(receiver_place.ptr, self).into(),
this_receiver_ptr,
));
trace!("Patched self operand to {:#?}", args[0]);
self.eval_fn_call(fn_val, caller_abi, &args, ret, unwind)
}
}
}
fn drop_in_place(
&mut self,
place: &PlaceTy<'tcx, M::PointerTag>,
instance: ty::Instance<'tcx>,
target: mir::BasicBlock,
unwind: Option<mir::BasicBlock>,
) -> InterpResult<'tcx> {
trace!("drop_in_place: {:?},\n {:?}, {:?}", *place, place.layout.ty, instance);
let place = self.force_allocation(place)?;
let (instance, place) = match place.layout.ty.kind() {
ty::Dynamic(..) => {
self.unpack_dyn_trait(&place)?
}
_ => (instance, place),
};
let arg = ImmTy::from_immediate(
place.to_ref(self),
self.layout_of(self.tcx.mk_mut_ptr(place.layout.ty))?,
);
let ty = self.tcx.mk_unit();
let dest = MPlaceTy::dangling(self.layout_of(ty)?);
self.eval_fn_call(
FnVal::Instance(instance),
Abi::Rust,
&[arg.into()],
Some((&dest.into(), target)),
match unwind {
Some(cleanup) => StackPopUnwind::Cleanup(cleanup),
None => StackPopUnwind::Skip,
},
)
}
}