Skip to content

Commit 75d014f

Browse files
committed
enfore that unsafe rules that are not overriden by refcount are not unsafe
1 parent 6dc08de commit 75d014f

74 files changed

Lines changed: 682 additions & 1348 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.gitignore‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,6 @@ _buildconfig.py
44
Cargo.lock
55
target/
66

7-
rules/rustls/rustls.h
8-
97
# Python
108
*.pyc
119
__pycache__

‎CMakeLists.txt‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -165,8 +165,6 @@ add_custom_target("check"
165165
DEPENDS check-libcc2rs check-libcc2rs-macros check-unit
166166
)
167167

168-
set(RUSTLS_HEADER "${PROJECT_SOURCE_DIR}/rules/rustls/rustls.h")
169-
170168
set(PREPROCESSOR_BIN "${CMAKE_BINARY_DIR}/rule-preprocessor-target/release/rule-preprocessor")
171169
set(PREPROCESSOR_ARTIFACTS "${CMAKE_BINARY_DIR}/rule-preprocessor-target/artifacts.json")
172170
set(RULES_LIB "${CMAKE_BINARY_DIR}/rules-target/release/librules.rlib")
@@ -192,7 +190,7 @@ execute_process(
192190
)
193191

194192
add_custom_command(
195-
OUTPUT ${RUSTLS_HEADER} ${RULES_LIB}
193+
OUTPUT ${RULES_LIB}
196194
COMMAND ${CARGO_ENV_RULES}
197195
cargo +${RUST_STABLE_VERSION} build --release
198196
--manifest-path "${PROJECT_SOURCE_DIR}/rules/Cargo.toml"
@@ -243,7 +241,7 @@ foreach(_rule_dir IN LISTS rule_subdirs)
243241
OUTPUT ${_part}
244242
COMMAND ${CMAKE_COMMAND} -E make_directory ${rules_index_parts_dir}
245243
COMMAND $<TARGET_FILE:cpp-rule-indexer> --dir ${_rule_dir} -o ${_part}
246-
DEPENDS ${_cpp_srcs} ${_rule_headers} ${rule_common_headers} ${rule_indexer_sources} ${RUSTLS_HEADER}
244+
DEPENDS ${_cpp_srcs} ${_rule_headers} ${rule_common_headers} ${rule_indexer_sources}
247245
VERBATIM
248246
)
249247
list(APPEND rules_index_parts ${_part})

‎rule-preprocessor/src/semantic.rs‎

Lines changed: 124 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// Copyright (c) 2022-present INESC-ID.
22
// Distributed under the MIT license that can be found in the LICENSE file.
33

4-
use crate::ir::{Access, FnIr, RuleIr, RulesIR};
4+
use crate::ir::{Access, FnIr, Model, RuleIr, RulesIR};
55
use std::collections::HashMap;
66
use std::path::{Path, PathBuf};
77

@@ -77,7 +77,6 @@ fn build_rustc_args(crate_root: &Path) -> Vec<String> {
7777
"libcc2rs",
7878
"libcc2rs_macros",
7979
"libc",
80-
"rustls_ffi",
8180
"nix",
8281
"jiff",
8382
"xattr",
@@ -196,6 +195,95 @@ impl<'tcx> FnDecl<'tcx> {
196195
}
197196
visitor.visit_expr(self.body.value, Access::Borrow);
198197
}
198+
199+
fn unsafe_uses(&self, tcx: rustc_middle::ty::TyCtxt<'tcx>) -> UnsafeUses {
200+
use rustc_hir::intravisit::Visitor;
201+
let mut finder = UnsafeFinder {
202+
tcx,
203+
typeck: tcx.typeck_body(self.body.id()),
204+
uses: UnsafeUses::default(),
205+
};
206+
finder.visit_expr(self.body.value);
207+
finder.uses
208+
}
209+
}
210+
211+
/// What a rule body has that needs an unsafe context.
212+
#[derive(Default)]
213+
struct UnsafeUses {
214+
block: bool,
215+
op: bool,
216+
}
217+
218+
struct UnsafeFinder<'tcx> {
219+
tcx: rustc_middle::ty::TyCtxt<'tcx>,
220+
typeck: &'tcx rustc_middle::ty::TypeckResults<'tcx>,
221+
uses: UnsafeUses,
222+
}
223+
224+
impl<'tcx> UnsafeFinder<'tcx> {
225+
fn is_unsafe_op(&self, expr: &'tcx rustc_hir::Expr<'tcx>) -> bool {
226+
use rustc_hir::def::{DefKind, Res};
227+
use rustc_middle::ty::TyKind;
228+
229+
match &expr.kind {
230+
rustc_hir::ExprKind::Call(callee, _) => {
231+
let ty = self.typeck.expr_ty_adjusted(callee);
232+
matches!(ty.kind(), TyKind::FnDef(..) | TyKind::FnPtr(..))
233+
&& ty.fn_sig(self.tcx).safety().is_unsafe()
234+
}
235+
rustc_hir::ExprKind::MethodCall(..) => self
236+
.typeck
237+
.type_dependent_def_id(expr.hir_id)
238+
.is_some_and(|def_id| self.tcx.fn_sig(def_id).skip_binder().safety().is_unsafe()),
239+
rustc_hir::ExprKind::Unary(rustc_hir::UnOp::Deref, inner) => {
240+
self.typeck.expr_ty_adjusted(inner).is_raw_ptr()
241+
}
242+
rustc_hir::ExprKind::Field(base, _) => self
243+
.typeck
244+
.expr_ty_adjusted(base)
245+
.ty_adt_def()
246+
.is_some_and(|adt| adt.is_union()),
247+
rustc_hir::ExprKind::Path(qpath) => match self.typeck.qpath_res(qpath, expr.hir_id) {
248+
Res::Def(DefKind::Static { mutability, .. }, def_id) => {
249+
mutability.is_mut() || self.tcx.is_foreign_item(def_id)
250+
}
251+
_ => false,
252+
},
253+
rustc_hir::ExprKind::InlineAsm(_) => true,
254+
_ => false,
255+
}
256+
}
257+
}
258+
259+
impl<'tcx> rustc_hir::intravisit::Visitor<'tcx> for UnsafeFinder<'tcx> {
260+
type NestedFilter = rustc_middle::hir::nested_filter::OnlyBodies;
261+
262+
fn maybe_tcx(&mut self) -> rustc_middle::ty::TyCtxt<'tcx> {
263+
self.tcx
264+
}
265+
266+
fn visit_block(&mut self, block: &'tcx rustc_hir::Block<'tcx>) {
267+
let rustc_hir::BlockCheckMode::UnsafeBlock(source) = block.rules else {
268+
rustc_hir::intravisit::walk_block(self, block);
269+
return;
270+
};
271+
// Like the `unsafe_code` lint, trust the unsafe blocks of the compiler
272+
// and of the macros that allow internal unsafe, e.g., `panic!`.
273+
if source == rustc_hir::UnsafeSource::UserProvided && !block.span.allows_unsafe() {
274+
// The unsafe block of a macro is an unsafe operation of the rule.
275+
if block.span.from_expansion() {
276+
self.uses.op = true;
277+
} else {
278+
self.uses.block = true;
279+
}
280+
}
281+
}
282+
283+
fn visit_expr(&mut self, expr: &'tcx rustc_hir::Expr<'tcx>) {
284+
self.uses.op |= self.is_unsafe_op(expr);
285+
rustc_hir::intravisit::walk_expr(self, expr);
286+
}
199287
}
200288

201289
struct MethodResolver {
@@ -204,6 +292,13 @@ struct MethodResolver {
204292

205293
impl MethodResolver {
206294
fn resolve_rule<'tcx>(&mut self, tcx: rustc_middle::ty::TyCtxt<'tcx>, f: &FnDecl<'tcx>) {
295+
// The refcount model falls back to the unsafe rules it does not have.
296+
let used_by_refcount = f.source_file.ends_with(Model::Refcount.src_filename())
297+
|| !self
298+
.ir
299+
.refcount_ir
300+
.as_ref()
301+
.is_some_and(|ir| ir.contains_key(&f.name));
207302
let Some(file_ir) = self.ir.get_mut(&f.source_file) else {
208303
return;
209304
};
@@ -213,7 +308,33 @@ impl MethodResolver {
213308
let ret_ty = tcx.fn_sig(f.def_id).skip_binder().output().skip_binder();
214309
type_ir.type_info.derives = type_derives(tcx, tcx.param_env(f.def_id), ret_ty);
215310
}
216-
None => {}
311+
None => return,
312+
}
313+
314+
// A rule is either unsafe as a whole or does nothing unsafe.
315+
let uses = f.unsafe_uses(tcx);
316+
assert!(
317+
!uses.block,
318+
"{} ({}): rules must not have unsafe blocks; mark the rule unsafe instead",
319+
f.name, f.source_file
320+
);
321+
if tcx.fn_sig(f.def_id).skip_binder().safety().is_unsafe() {
322+
assert!(
323+
!used_by_refcount,
324+
"{} ({}): the refcount model uses this rule, so it must not be unsafe",
325+
f.name, f.source_file
326+
);
327+
assert!(
328+
uses.op,
329+
"{} ({}): the rule does no unsafe operation, so it must not be unsafe",
330+
f.name, f.source_file
331+
);
332+
} else {
333+
assert!(
334+
!uses.op,
335+
"{} ({}): the rule does an unsafe operation, so it must be unsafe",
336+
f.name, f.source_file
337+
);
217338
}
218339
}
219340

‎rules/Cargo.toml‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ path = "src/lib.rs"
1111
[dependencies]
1212
libc = "0.2.148"
1313
libcc2rs = { version = "0.1.0", path = "../libcc2rs" }
14-
rustls-ffi = { version = "0.15.3", default-features = false }
1514
nix = { version = "0.30", features = ["socket", "net", "fs", "poll", "time", "user", "dir", "term", "event", "hostname"] }
1615
jiff = "0.2"
1716
xattr = "1"

‎rules/any/tgt_unsafe.rs‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,19 +7,19 @@ fn t1() -> Option<Box<dyn std::any::Any>> {
77
None
88
}
99

10-
unsafe fn f1() -> Option<Box<dyn std::any::Any>> {
10+
fn f1() -> Option<Box<dyn std::any::Any>> {
1111
None
1212
}
1313

14-
unsafe fn f6(a0: &mut Option<Box<dyn std::any::Any>>) {
14+
fn f6(a0: &mut Option<Box<dyn std::any::Any>>) {
1515
*a0 = None
1616
}
1717

18-
unsafe fn f8(a0: Option<Box<dyn std::any::Any>>) -> bool {
18+
fn f8(a0: Option<Box<dyn std::any::Any>>) -> bool {
1919
a0.is_some()
2020
}
2121

22-
unsafe fn f14<T1: 'static>(a0: &mut Option<Box<dyn std::any::Any>>, init: cpp_type!("std::decay_t<T1>", T1)) -> &mut T1 {
22+
fn f14<T1: 'static>(a0: &mut Option<Box<dyn std::any::Any>>, init: cpp_type!("std::decay_t<T1>", T1)) -> &mut T1 {
2323
*a0 = Some(Box::new(init));
2424
a0.as_mut().unwrap().downcast_mut::<T1>().unwrap()
2525
}
@@ -31,6 +31,6 @@ unsafe fn f19<T1: 'static>(a0: *mut Option<Box<dyn std::any::Any>>) -> *mut T1 {
3131
}
3232
}
3333

34-
unsafe fn f27<T1: 'static>(init: cpp_type!("std::decay_t<T1>", T1)) -> Option<Box<dyn std::any::Any>> {
34+
fn f27<T1: 'static>(init: cpp_type!("std::decay_t<T1>", T1)) -> Option<Box<dyn std::any::Any>> {
3535
Some(Box::new(init))
3636
}

‎rules/arpa_inet/tgt_unsafe.rs‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
11
// Copyright (c) 2022-present INESC-ID.
22
// Distributed under the MIT license that can be found in the LICENSE file.
33

4-
unsafe fn f1(a0: u32) -> u32 {
4+
fn f1(a0: u32) -> u32 {
55
u32::from_be(a0)
66
}
7-
unsafe fn f2(a0: u16) -> u16 {
7+
fn f2(a0: u16) -> u16 {
88
u16::from_be(a0)
99
}
10-
unsafe fn f3(a0: u16) -> u16 {
10+
fn f3(a0: u16) -> u16 {
1111
u16::to_be(a0)
1212
}
13-
unsafe fn f4(a0: u32) -> u32 {
13+
fn f4(a0: u32) -> u32 {
1414
u32::to_be(a0)
1515
}
1616
unsafe fn f5(a0: i32, a1: *const libc::c_char, a2: *mut ::libc::c_void) -> i32 {

‎rules/array/tgt_unsafe.rs‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -27,15 +27,15 @@ fn t6<T2>() -> T2 {
2727
unimplemented!()
2828
}
2929

30-
unsafe fn f1<T1, const T2: usize>(a0: [T1; T2]) -> *const T1 {
30+
fn f1<T1, const T2: usize>(a0: [T1; T2]) -> *const T1 {
3131
a0.as_ptr()
3232
}
3333

34-
unsafe fn f2<T1, const T2: usize>(a0: [T1; T2]) -> usize {
34+
fn f2<T1, const T2: usize>(a0: [T1; T2]) -> usize {
3535
T2
3636
}
3737

38-
unsafe fn f3<T1, const T2: usize>(a0: &mut [T1; T2]) -> *mut T1 {
38+
fn f3<T1, const T2: usize>(a0: &mut [T1; T2]) -> *mut T1 {
3939
a0.as_mut_ptr()
4040
}
4141

@@ -53,7 +53,7 @@ unsafe fn f5<'a, T1: MoveAssignUnsafe, const T2: usize>(
5353
a0
5454
}
5555

56-
unsafe fn f6<T1: Clone, const T2: usize>(a0: [T1; T2]) -> [T1; T2] {
56+
fn f6<T1: Clone, const T2: usize>(a0: [T1; T2]) -> [T1; T2] {
5757
a0.clone()
5858
}
5959

@@ -67,22 +67,22 @@ unsafe fn f7<'a, T1: CopyAssignUnsafe, const T2: usize>(
6767
a0
6868
}
6969

70-
unsafe fn f8<T1, const T2: usize>(a0: [T1; T2]) -> [T1; T2] {
70+
fn f8<T1, const T2: usize>(a0: [T1; T2]) -> [T1; T2] {
7171
a0
7272
}
7373

74-
unsafe fn f9<const T1: usize, T2, const T3: usize>(a0: &mut [T2; T3]) -> &mut T2 {
74+
fn f9<const T1: usize, T2, const T3: usize>(a0: &mut [T2; T3]) -> &mut T2 {
7575
&mut a0[T1]
7676
}
7777

78-
unsafe fn f10<const T1: usize, T2, const T3: usize>(a0: &[T2; T3]) -> &T2 {
78+
fn f10<const T1: usize, T2, const T3: usize>(a0: &[T2; T3]) -> &T2 {
7979
&a0[T1]
8080
}
8181

82-
unsafe fn f11<const T1: usize, T2, const T3: usize>(a0: &mut [T2; T3]) -> &mut T2 {
82+
fn f11<const T1: usize, T2, const T3: usize>(a0: &mut [T2; T3]) -> &mut T2 {
8383
&mut a0[T1]
8484
}
8585

86-
unsafe fn f12<const T1: usize, T2, const T3: usize>(a0: &[T2; T3]) -> &T2 {
86+
fn f12<const T1: usize, T2, const T3: usize>(a0: &[T2; T3]) -> &T2 {
8787
&a0[T1]
8888
}

‎rules/bit/tgt_unsafe.rs‎

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,47 +3,47 @@
33

44
// The patterns take any unsigned type; u32 only type-checks the bodies.
55

6-
unsafe fn f1(a0: u32) -> bool {
6+
fn f1(a0: u32) -> bool {
77
a0.is_power_of_two()
88
}
99

10-
unsafe fn f2(a0: u32) -> u32 {
10+
fn f2(a0: u32) -> u32 {
1111
a0.next_power_of_two()
1212
}
1313

14-
unsafe fn f3(a0: u32) -> u32 {
14+
fn f3(a0: u32) -> u32 {
1515
a0.isolate_highest_one()
1616
}
1717

18-
unsafe fn f4(a0: u32) -> i32 {
18+
fn f4(a0: u32) -> i32 {
1919
a0.bit_width() as i32
2020
}
2121

2222
// A negative count rotates the other way, as a count modulo the width.
23-
unsafe fn f5(a0: u32, a1: i32) -> u32 {
23+
fn f5(a0: u32, a1: i32) -> u32 {
2424
a0.rotate_left(a1 as u32)
2525
}
2626

27-
unsafe fn f6(a0: u32, a1: i32) -> u32 {
27+
fn f6(a0: u32, a1: i32) -> u32 {
2828
a0.rotate_right(a1 as u32)
2929
}
3030

31-
unsafe fn f7(a0: u32) -> i32 {
31+
fn f7(a0: u32) -> i32 {
3232
a0.leading_zeros() as i32
3333
}
3434

35-
unsafe fn f8(a0: u32) -> i32 {
35+
fn f8(a0: u32) -> i32 {
3636
a0.leading_ones() as i32
3737
}
3838

39-
unsafe fn f9(a0: u32) -> i32 {
39+
fn f9(a0: u32) -> i32 {
4040
a0.trailing_zeros() as i32
4141
}
4242

43-
unsafe fn f10(a0: u32) -> i32 {
43+
fn f10(a0: u32) -> i32 {
4444
a0.trailing_ones() as i32
4545
}
4646

47-
unsafe fn f11(a0: u32) -> i32 {
47+
fn f11(a0: u32) -> i32 {
4848
a0.count_ones() as i32
4949
}

0 commit comments

Comments
 (0)