Skip to content

Commit a74a284

Browse files
committed
Add tests for UB check in set_len, from_raw_parts_in, from_parts_in
Signed-off-by: xizheyin <xizheyin@smail.nju.edu.cn>
1 parent 48caa5f commit a74a284

File tree

3 files changed

+55
-0
lines changed

3 files changed

+55
-0
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
//@ run-fail
2+
//@ compile-flags: -Cdebug-assertions=yes
3+
//@ error-pattern: unsafe precondition(s) violated: Vec::from_parts_in requires that length <= capacity
4+
#![feature(allocator_api)]
5+
6+
use std::ptr::NonNull;
7+
8+
fn main() {
9+
let ptr: NonNull<i32> = std::ptr::NonNull::dangling();
10+
// Test Vec::from_parts_in with length > capacity
11+
unsafe {
12+
let alloc = std::alloc::Global;
13+
let _vec = Vec::from_parts_in(ptr, 10, 5, alloc);
14+
}
15+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
//@ run-fail
2+
//@ compile-flags: -Cdebug-assertions=yes
3+
//@ error-pattern: unsafe precondition(s) violated: Vec::from_raw_parts_in requires that length <= capacity
4+
//@ revisions: vec_from_raw_parts vec_from_raw_parts_in string_from_raw_parts
5+
6+
#![feature(allocator_api)]
7+
8+
fn main() {
9+
let ptr = std::ptr::null_mut::<u8>();
10+
// Test Vec::from_raw_parts with length > capacity
11+
unsafe {
12+
#[cfg(vec_from_raw_parts)]
13+
let _vec = Vec::from_raw_parts(ptr, 10, 5);
14+
}
15+
16+
// Test Vec::from_raw_parts_in with length > capacity
17+
unsafe {
18+
let alloc = std::alloc::Global;
19+
#[cfg(vec_from_raw_parts_in)]
20+
let _vec = Vec::from_raw_parts_in(ptr, 10, 5, alloc);
21+
}
22+
23+
// Test String::from_raw_parts with length > capacity
24+
// Because it calls Vec::from_raw_parts, it should also fail
25+
unsafe {
26+
#[cfg(string_from_raw_parts)]
27+
let _vec = String::from_raw_parts(ptr, 10, 5);
28+
}
29+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
//@ run-fail
2+
//@ compile-flags: -Cdebug-assertions=yes
3+
//@ error-pattern: unsafe precondition(s) violated: Vec::set_len requires that new_len <= capacity()
4+
5+
fn main() {
6+
let mut vec: Vec<i32> = Vec::with_capacity(5);
7+
// Test set_len with length > capacity
8+
unsafe {
9+
vec.set_len(10);
10+
}
11+
}

0 commit comments

Comments
 (0)