Skip to content

Commit 384623d

Browse files
committed
function pointers
1 parent 6721121 commit 384623d

File tree

6 files changed

+184
-88
lines changed

6 files changed

+184
-88
lines changed

src/error.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use memory::Pointer;
66
#[derive(Clone, Debug)]
77
pub enum EvalError {
88
DanglingPointerDeref,
9+
InvalidFunctionPointer,
910
InvalidBool,
1011
InvalidDiscriminant,
1112
PointerOutOfBounds {
@@ -28,6 +29,8 @@ impl Error for EvalError {
2829
match *self {
2930
EvalError::DanglingPointerDeref =>
3031
"dangling pointer was dereferenced",
32+
EvalError::InvalidFunctionPointer =>
33+
"tried to use a pointer as a function pointer",
3134
EvalError::InvalidBool =>
3235
"invalid boolean value read",
3336
EvalError::InvalidDiscriminant =>

src/interpreter/mod.rs

Lines changed: 111 additions & 81 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,15 @@ use rustc::traits::{self, ProjectionMode};
66
use rustc::ty::fold::TypeFoldable;
77
use rustc::ty::layout::{self, Layout, Size};
88
use rustc::ty::subst::{self, Subst, Substs};
9-
use rustc::ty::{self, Ty, TyCtxt};
9+
use rustc::ty::{self, Ty, TyCtxt, BareFnTy};
1010
use rustc::util::nodemap::DefIdMap;
1111
use std::cell::RefCell;
1212
use std::ops::Deref;
1313
use std::rc::Rc;
1414
use std::{iter, mem};
1515
use syntax::ast;
1616
use syntax::attr;
17-
use syntax::codemap::{self, DUMMY_SP};
17+
use syntax::codemap::{self, DUMMY_SP, Span};
1818

1919
use error::{EvalError, EvalResult};
2020
use memory::{Memory, Pointer};
@@ -39,7 +39,7 @@ pub struct EvalContext<'a, 'tcx: 'a> {
3939
mir_cache: RefCell<DefIdMap<Rc<mir::Mir<'tcx>>>>,
4040

4141
/// The virtual memory system.
42-
memory: Memory,
42+
memory: Memory<'tcx>,
4343

4444
/// Precomputed statics, constants and promoteds
4545
statics: HashMap<ConstantId<'tcx>, Pointer>,
@@ -421,81 +421,15 @@ impl<'a, 'tcx> EvalContext<'a, 'tcx> {
421421

422422
let func_ty = self.operand_ty(func);
423423
match func_ty.sty {
424+
ty::TyFnPtr(bare_fn_ty) => {
425+
let ptr = self.eval_operand(func)?;
426+
assert_eq!(ptr.offset, 0);
427+
let fn_ptr = self.memory.read_ptr(ptr)?;
428+
let (def_id, substs) = self.memory.get_fn(fn_ptr.alloc_id)?;
429+
self.eval_fn_call(def_id, substs, bare_fn_ty, return_ptr, args, terminator.span)?
430+
},
424431
ty::TyFnDef(def_id, substs, fn_ty) => {
425-
use syntax::abi::Abi;
426-
match fn_ty.abi {
427-
Abi::RustIntrinsic => {
428-
let name = self.tcx.item_name(def_id).as_str();
429-
match fn_ty.sig.0.output {
430-
ty::FnConverging(ty) => {
431-
let size = self.type_size(ty, self.substs());
432-
let ret = return_ptr.unwrap();
433-
self.call_intrinsic(&name, substs, args, ret, size)?
434-
}
435-
ty::FnDiverging => unimplemented!(),
436-
}
437-
}
438-
439-
Abi::C => {
440-
match fn_ty.sig.0.output {
441-
ty::FnConverging(ty) => {
442-
let size = self.type_size(ty, self.substs());
443-
self.call_c_abi(def_id, args, return_ptr.unwrap(), size)?
444-
}
445-
ty::FnDiverging => unimplemented!(),
446-
}
447-
}
448-
449-
Abi::Rust | Abi::RustCall => {
450-
// TODO(solson): Adjust the first argument when calling a Fn or
451-
// FnMut closure via FnOnce::call_once.
452-
453-
// Only trait methods can have a Self parameter.
454-
let (resolved_def_id, resolved_substs) = if substs.self_ty().is_some() {
455-
self.trait_method(def_id, substs)
456-
} else {
457-
(def_id, substs)
458-
};
459-
460-
let mut arg_srcs = Vec::new();
461-
for arg in args {
462-
let src = self.eval_operand(arg)?;
463-
let src_ty = self.operand_ty(arg);
464-
arg_srcs.push((src, src_ty));
465-
}
466-
467-
if fn_ty.abi == Abi::RustCall && !args.is_empty() {
468-
arg_srcs.pop();
469-
let last_arg = args.last().unwrap();
470-
let last = self.eval_operand(last_arg)?;
471-
let last_ty = self.operand_ty(last_arg);
472-
let last_layout = self.type_layout(last_ty, self.substs());
473-
match (&last_ty.sty, last_layout) {
474-
(&ty::TyTuple(fields),
475-
&Layout::Univariant { ref variant, .. }) => {
476-
let offsets = iter::once(0)
477-
.chain(variant.offset_after_field.iter()
478-
.map(|s| s.bytes()));
479-
for (offset, ty) in offsets.zip(fields) {
480-
let src = last.offset(offset as isize);
481-
arg_srcs.push((src, ty));
482-
}
483-
}
484-
ty => panic!("expected tuple as last argument in function with 'rust-call' ABI, got {:?}", ty),
485-
}
486-
}
487-
488-
let mir = self.load_mir(resolved_def_id);
489-
self.push_stack_frame(def_id, terminator.span, mir, resolved_substs, return_ptr);
490-
491-
for (i, (src, src_ty)) in arg_srcs.into_iter().enumerate() {
492-
let dest = self.frame().locals[i];
493-
self.move_(src, dest, src_ty)?;
494-
}
495-
}
496-
497-
abi => return Err(EvalError::Unimplemented(format!("can't handle function with {:?} ABI", abi))),
498-
}
432+
self.eval_fn_call(def_id, substs, fn_ty, return_ptr, args, terminator.span)?
499433
}
500434

501435
_ => return Err(EvalError::Unimplemented(format!("can't handle callee of type {:?}", func_ty))),
@@ -515,6 +449,93 @@ impl<'a, 'tcx> EvalContext<'a, 'tcx> {
515449
Ok(())
516450
}
517451

452+
pub fn eval_fn_call(
453+
&mut self,
454+
def_id: DefId,
455+
substs: &'tcx Substs<'tcx>,
456+
fn_ty: &'tcx BareFnTy,
457+
return_ptr: Option<Pointer>,
458+
args: &[mir::Operand<'tcx>],
459+
span: Span,
460+
) -> EvalResult<()> {
461+
use syntax::abi::Abi;
462+
match fn_ty.abi {
463+
Abi::RustIntrinsic => {
464+
let name = self.tcx.item_name(def_id).as_str();
465+
match fn_ty.sig.0.output {
466+
ty::FnConverging(ty) => {
467+
let size = self.type_size(ty, self.substs());
468+
let ret = return_ptr.unwrap();
469+
self.call_intrinsic(&name, substs, args, ret, size)
470+
}
471+
ty::FnDiverging => unimplemented!(),
472+
}
473+
}
474+
475+
Abi::C => {
476+
match fn_ty.sig.0.output {
477+
ty::FnConverging(ty) => {
478+
let size = self.type_size(ty, self.substs());
479+
self.call_c_abi(def_id, args, return_ptr.unwrap(), size)
480+
}
481+
ty::FnDiverging => unimplemented!(),
482+
}
483+
}
484+
485+
Abi::Rust | Abi::RustCall => {
486+
// TODO(solson): Adjust the first argument when calling a Fn or
487+
// FnMut closure via FnOnce::call_once.
488+
489+
// Only trait methods can have a Self parameter.
490+
let (resolved_def_id, resolved_substs) = if substs.self_ty().is_some() {
491+
self.trait_method(def_id, substs)
492+
} else {
493+
(def_id, substs)
494+
};
495+
496+
let mut arg_srcs = Vec::new();
497+
for arg in args {
498+
let src = self.eval_operand(arg)?;
499+
let src_ty = self.operand_ty(arg);
500+
arg_srcs.push((src, src_ty));
501+
}
502+
503+
if fn_ty.abi == Abi::RustCall && !args.is_empty() {
504+
arg_srcs.pop();
505+
let last_arg = args.last().unwrap();
506+
let last = self.eval_operand(last_arg)?;
507+
let last_ty = self.operand_ty(last_arg);
508+
let last_layout = self.type_layout(last_ty, self.substs());
509+
match (&last_ty.sty, last_layout) {
510+
(&ty::TyTuple(fields),
511+
&Layout::Univariant { ref variant, .. }) => {
512+
let offsets = iter::once(0)
513+
.chain(variant.offset_after_field.iter()
514+
.map(|s| s.bytes()));
515+
for (offset, ty) in offsets.zip(fields) {
516+
let src = last.offset(offset as isize);
517+
arg_srcs.push((src, ty));
518+
}
519+
}
520+
ty => panic!("expected tuple as last argument in function with 'rust-call' ABI, got {:?}", ty),
521+
}
522+
}
523+
524+
let mir = self.load_mir(resolved_def_id);
525+
self.push_stack_frame(def_id, span, mir, resolved_substs, return_ptr);
526+
527+
for (i, (src, src_ty)) in arg_srcs.into_iter().enumerate() {
528+
let dest = self.frame().locals[i];
529+
self.move_(src, dest, src_ty)?;
530+
}
531+
532+
Ok(())
533+
}
534+
535+
abi => Err(EvalError::Unimplemented(format!("can't handle function with {:?} ABI", abi))),
536+
}
537+
}
538+
518539
fn drop(&mut self, ptr: Pointer, ty: Ty<'tcx>) -> EvalResult<()> {
519540
if !self.type_needs_drop(ty) {
520541
debug!("no need to drop {:?}", ty);
@@ -989,12 +1010,11 @@ impl<'a, 'tcx> EvalContext<'a, 'tcx> {
9891010
}
9901011

9911012
Cast(kind, ref operand, dest_ty) => {
992-
let src = self.eval_operand(operand)?;
993-
let src_ty = self.operand_ty(operand);
994-
9951013
use rustc::mir::repr::CastKind::*;
9961014
match kind {
9971015
Unsize => {
1016+
let src = self.eval_operand(operand)?;
1017+
let src_ty = self.operand_ty(operand);
9981018
self.move_(src, dest, src_ty)?;
9991019
let src_pointee_ty = pointee_type(src_ty).unwrap();
10001020
let dest_pointee_ty = pointee_type(dest_ty).unwrap();
@@ -1010,11 +1030,20 @@ impl<'a, 'tcx> EvalContext<'a, 'tcx> {
10101030
}
10111031

10121032
Misc => {
1033+
let src = self.eval_operand(operand)?;
10131034
// FIXME(solson): Wrong for almost everything.
10141035
let size = dest_layout.size(&self.tcx.data_layout).bytes() as usize;
10151036
self.memory.copy(src, dest, size)?;
10161037
}
10171038

1039+
ReifyFnPointer => match self.operand_ty(operand).sty {
1040+
ty::TyFnDef(def_id, substs, _) => {
1041+
let fn_ptr = self.memory.create_fn_ptr(def_id, substs);
1042+
self.memory.write_ptr(dest, fn_ptr)?;
1043+
},
1044+
ref other => panic!("reify fn pointer on {:?}", other),
1045+
},
1046+
10181047
_ => return Err(EvalError::Unimplemented(format!("can't handle cast: {:?}", rvalue))),
10191048
}
10201049
}
@@ -1103,7 +1132,8 @@ impl<'a, 'tcx> EvalContext<'a, 'tcx> {
11031132
Value { ref value } => Ok(self.const_to_ptr(value)?),
11041133
Item { def_id, substs } => {
11051134
if let ty::TyFnDef(..) = ty.sty {
1106-
Err(EvalError::Unimplemented("unimplemented: mentions of function items".to_string()))
1135+
// function items are zero sized
1136+
Ok(self.memory.allocate(0))
11071137
} else {
11081138
let cid = ConstantId {
11091139
def_id: def_id,

src/memory.rs

Lines changed: 35 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@ use std::collections::Bound::{Included, Excluded};
33
use std::collections::{btree_map, BTreeMap, HashMap, HashSet, VecDeque};
44
use std::{fmt, iter, mem, ptr};
55

6+
use rustc::hir::def_id::DefId;
7+
use rustc::ty::subst::Substs;
8+
69
use error::{EvalError, EvalResult};
710
use primval::PrimVal;
811

@@ -42,22 +45,37 @@ impl Pointer {
4245
// Top-level interpreter memory
4346
////////////////////////////////////////////////////////////////////////////////
4447

45-
pub struct Memory {
48+
pub struct Memory<'tcx> {
4649
alloc_map: HashMap<AllocId, Allocation>,
50+
functions: HashMap<AllocId, (DefId, &'tcx Substs<'tcx>)>,
4751
next_id: AllocId,
4852
pub pointer_size: usize,
4953
}
5054

51-
impl Memory {
55+
impl<'tcx> Memory<'tcx> {
5256
// FIXME: pass tcx.data_layout (This would also allow it to use primitive type alignments to diagnose unaligned memory accesses.)
5357
pub fn new(pointer_size: usize) -> Self {
5458
Memory {
5559
alloc_map: HashMap::new(),
60+
functions: HashMap::new(),
5661
next_id: AllocId(0),
5762
pointer_size: pointer_size,
5863
}
5964
}
6065

66+
// FIXME: never create two pointers to the same def_id + substs combination
67+
// maybe re-use the statics cache of the gecx?
68+
pub fn create_fn_ptr(&mut self, def_id: DefId, substs: &'tcx Substs<'tcx>) -> Pointer {
69+
let id = self.next_id;
70+
debug!("creating fn ptr: {}", id);
71+
self.next_id.0 += 1;
72+
self.functions.insert(id, (def_id, substs));
73+
Pointer {
74+
alloc_id: id,
75+
offset: 0,
76+
}
77+
}
78+
6179
pub fn allocate(&mut self, size: usize) -> Pointer {
6280
let alloc = Allocation {
6381
bytes: vec![0; size],
@@ -125,6 +143,11 @@ impl Memory {
125143
self.alloc_map.get_mut(&id).ok_or(EvalError::DanglingPointerDeref)
126144
}
127145

146+
pub fn get_fn(&self, id: AllocId) -> EvalResult<(DefId, &'tcx Substs<'tcx>)> {
147+
debug!("reading fn ptr: {}", id);
148+
self.functions.get(&id).map(|&did| did).ok_or(EvalError::InvalidFunctionPointer)
149+
}
150+
128151
/// Print an allocation and all allocations it points to, recursively.
129152
pub fn dump(&self, id: AllocId) {
130153
let mut allocs_seen = HashSet::new();
@@ -137,12 +160,18 @@ impl Memory {
137160
print!("{}", prefix);
138161
let mut relocations = vec![];
139162

140-
let alloc = match self.alloc_map.get(&id) {
141-
Some(a) => a,
142-
None => {
163+
let alloc = match (self.alloc_map.get(&id), self.functions.get(&id)) {
164+
(Some(a), None) => a,
165+
(None, Some(_)) => {
166+
// FIXME: print function name
167+
println!("function pointer");
168+
continue;
169+
},
170+
(None, None) => {
143171
println!("(deallocated)");
144172
continue;
145-
}
173+
},
174+
(Some(_), Some(_)) => unreachable!(),
146175
};
147176

148177
for i in 0..alloc.bytes.len() {

tests/compile-fail/unimplemented.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
#![feature(custom_attribute)]
22
#![allow(dead_code, unused_attributes)]
33

4-
//error-pattern:unimplemented: mentions of function items
4+
//error-pattern:begin_panic_fmt
55

66

77
#[miri_run]

tests/run-pass/function_pointers.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
#![feature(custom_attribute)]
2+
#![allow(dead_code, unused_attributes)]
3+
4+
fn f() -> i32 {
5+
42
6+
}
7+
8+
fn return_fn_ptr() -> fn() -> i32 {
9+
f
10+
}
11+
12+
#[miri_run]
13+
fn call_fn_ptr() -> i32 {
14+
return_fn_ptr()()
15+
}
16+
17+
fn main() {}

0 commit comments

Comments
 (0)