Skip to content

Commit a435bca

Browse files
Rollup merge of #166081 - folkertdev:test-asm-const-vtable-ptr, r=JonathanBrouwer
test `feature(asm_const_ptr)` with a vtable This tests an interesting interaction between features, and a special code path for generating vtables. I'm especially interested in how/whether the GCC backend supports this correctly.
2 parents fbeaa76 + b0c9ab5 commit a435bca

1 file changed

Lines changed: 76 additions & 0 deletions

File tree

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
//@ only-x86_64
2+
//@ only-linux
3+
//@ needs-asm-support
4+
//@ run-pass
5+
#![feature(asm_const_ptr, ptr_metadata)]
6+
use std::mem::MaybeUninit;
7+
8+
// Test an asm const operand being passed a vtable.
9+
10+
trait Trait {
11+
#[allow(unused)]
12+
extern "C" fn method(&self, a: i32, b: i32) -> i32 {
13+
a.wrapping_add(b)
14+
}
15+
}
16+
17+
struct Struct;
18+
19+
impl Trait for Struct {}
20+
21+
/// Get a pointer to the vtable from a `&dyn Trait`.
22+
const fn vtable_of(x: &dyn Trait) -> *const () {
23+
let meta: std::ptr::DynMetadata<dyn Trait> = std::ptr::metadata(x);
24+
unsafe { std::mem::transmute(meta) }
25+
}
26+
27+
const VTABLE: *const () = vtable_of(&Struct);
28+
29+
#[repr(C)]
30+
struct ManualVTable {
31+
drop_in_place: Option<fn(_: *mut Struct)>,
32+
size: usize,
33+
align: usize,
34+
method: extern "C" fn(_: &Struct, _: i32, _: i32) -> i32,
35+
}
36+
37+
fn read() -> ManualVTable {
38+
let drop_in_place: MaybeUninit<fn(_: *mut Struct)>;
39+
let size: usize;
40+
let align: usize;
41+
let method: extern "C" fn(_: &Struct, _: i32, _: i32) -> i32;
42+
43+
unsafe {
44+
#[rustfmt::skip]
45+
std::arch::asm!(
46+
"lea {vtable}, [rip + {input}]",
47+
"mov {drop_in_place}, qword ptr [{vtable}]",
48+
"mov {size}, qword ptr [{vtable} + 8]",
49+
"mov {align}, qword ptr [{vtable} + 16]",
50+
"mov {method}, qword ptr [{vtable} + 24]",
51+
input = const VTABLE,
52+
vtable = out(reg) _,
53+
drop_in_place = out(reg) drop_in_place,
54+
size = out(reg) size,
55+
align = out(reg) align,
56+
method = out(reg) method,
57+
);
58+
59+
let drop_in_place: Option<fn(_: *mut Struct)> =
60+
std::mem::transmute::<_, MaybeUninit<_>>(drop_in_place).assume_init();
61+
62+
ManualVTable { drop_in_place, size, align, method }
63+
}
64+
}
65+
66+
fn main() {
67+
let ManualVTable { drop_in_place, size, align, method } = read();
68+
69+
assert!(drop_in_place.is_none());
70+
71+
assert_eq!(size, 0);
72+
assert_eq!(align, 1);
73+
74+
assert_eq!(method(&Struct, 1, 2), 3);
75+
assert_eq!(method(&Struct, 4, 5), 9);
76+
}

0 commit comments

Comments
 (0)