Skip to main content

rustc_lint/
runtime_symbols.rs

1use rustc_hir::def_id::LocalDefId;
2use rustc_hir::{self as hir, CanonicalSymbol, FnSig, ForeignItemKind};
3use rustc_infer::infer::DefineOpaqueTypes;
4use rustc_middle::ty::{self, Instance, Ty};
5use rustc_session::{declare_lint, declare_lint_pass};
6use rustc_span::{Span, Symbol};
7use rustc_trait_selection::infer::TyCtxtInferExt;
8
9use crate::lints::RedefiningRuntimeSymbolsDiag;
10use crate::{LateContext, LateLintPass, LintContext};
11
12#[doc =
r" The `invalid_runtime_symbol_definitions` lint checks the signature of items whose"]
#[doc =
r" symbol name is a runtime symbol expected by `core` or `std` differs significantly from the"]
#[doc =
r" expected signature (like mismatch ABI, mismatch C variadics, mismatch argument count,"]
#[doc = r" missing return type, ...)."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" #[unsafe(no_mangle)]"]
#[doc = r" pub fn strlen() {} // invalid definition of the `strlen` function"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" Up-most care is required when defining runtime symbols assumed and"]
#[doc =
r" used by the standard library. They must follow the C specification, not use any"]
#[doc = r" standard-library facility or undefined behavior may occur."]
#[doc = r""]
#[doc =
r" The symbols currently checked are `memcpy`, `memmove`, `memset`, `memcmp`,"]
#[doc =
r" `bcmp`, `strlen`, as well as the following POSIX symbols: `open`, `read`, `write`"]
#[doc = r" `close`, `malloc`, `realloc`, `free` and `exit`."]
#[doc = r""]
#[doc =
r" [^1]: https://doc.rust-lang.org/core/index.html#how-to-use-the-core-library"]
pub static INVALID_RUNTIME_SYMBOL_DEFINITIONS: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "INVALID_RUNTIME_SYMBOL_DEFINITIONS",
            default_level: ::rustc_lint_defs::Deny,
            desc: "invalid definition of a symbol used by the standard library",
            is_externally_loaded: false,
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
13    /// The `invalid_runtime_symbol_definitions` lint checks the signature of items whose
14    /// symbol name is a runtime symbol expected by `core` or `std` differs significantly from the
15    /// expected signature (like mismatch ABI, mismatch C variadics, mismatch argument count,
16    /// missing return type, ...).
17    ///
18    /// ### Example
19    ///
20    /// ```rust,compile_fail
21    /// #[unsafe(no_mangle)]
22    /// pub fn strlen() {} // invalid definition of the `strlen` function
23    /// ```
24    ///
25    /// {{produces}}
26    ///
27    /// ### Explanation
28    ///
29    /// Up-most care is required when defining runtime symbols assumed and
30    /// used by the standard library. They must follow the C specification, not use any
31    /// standard-library facility or undefined behavior may occur.
32    ///
33    /// The symbols currently checked are `memcpy`, `memmove`, `memset`, `memcmp`,
34    /// `bcmp`, `strlen`, as well as the following POSIX symbols: `open`, `read`, `write`
35    /// `close`, `malloc`, `realloc`, `free` and `exit`.
36    ///
37    /// [^1]: https://doc.rust-lang.org/core/index.html#how-to-use-the-core-library
38    pub INVALID_RUNTIME_SYMBOL_DEFINITIONS,
39    Deny,
40    "invalid definition of a symbol used by the standard library"
41}
42
43#[doc =
r" The `suspicious_runtime_symbol_definitions` lint checks the signature of items whose"]
#[doc = r" symbol name is a runtime symbol expected by `core` or `std`."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,no_run,standalone_crate"]
#[doc = r" #[unsafe(no_mangle)]"]
#[doc = r#" pub extern "C" fn strlen(ptr: *mut f32) -> usize { 0 }"#]
#[doc = r" // suspicious definition of the `strlen` function"]
#[doc = r" // `ptr` should be `*const std::ffi::c_char`"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" Up-most care is required when defining runtime symbols assumed and"]
#[doc =
r" used by the standard library. They must follow the C specification, not use any"]
#[doc = r" standard-library facility or undefined behavior may occur."]
#[doc = r""]
#[doc =
r" The symbols currently checked are `memcpy`, `memmove`, `memset`, `memcmp`,"]
#[doc =
r" `bcmp`, `strlen`, as well as the following POSIX symbols: `open`, `read`, `write`"]
#[doc = r" `close`, `malloc`, `realloc`, `free` and `exit`."]
#[doc = r""]
#[doc =
r" [^1]: https://doc.rust-lang.org/core/index.html#how-to-use-the-core-library"]
pub static SUSPICIOUS_RUNTIME_SYMBOL_DEFINITIONS: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "SUSPICIOUS_RUNTIME_SYMBOL_DEFINITIONS",
            default_level: ::rustc_lint_defs::Warn,
            desc: "suspicious definition of a symbol used by the standard library",
            is_externally_loaded: false,
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
44    /// The `suspicious_runtime_symbol_definitions` lint checks the signature of items whose
45    /// symbol name is a runtime symbol expected by `core` or `std`.
46    ///
47    /// ### Example
48    ///
49    /// ```rust,no_run,standalone_crate
50    /// #[unsafe(no_mangle)]
51    /// pub extern "C" fn strlen(ptr: *mut f32) -> usize { 0 }
52    /// // suspicious definition of the `strlen` function
53    /// // `ptr` should be `*const std::ffi::c_char`
54    /// ```
55    ///
56    /// {{produces}}
57    ///
58    /// ### Explanation
59    ///
60    /// Up-most care is required when defining runtime symbols assumed and
61    /// used by the standard library. They must follow the C specification, not use any
62    /// standard-library facility or undefined behavior may occur.
63    ///
64    /// The symbols currently checked are `memcpy`, `memmove`, `memset`, `memcmp`,
65    /// `bcmp`, `strlen`, as well as the following POSIX symbols: `open`, `read`, `write`
66    /// `close`, `malloc`, `realloc`, `free` and `exit`.
67    ///
68    /// [^1]: https://doc.rust-lang.org/core/index.html#how-to-use-the-core-library
69    pub SUSPICIOUS_RUNTIME_SYMBOL_DEFINITIONS,
70    Warn,
71    "suspicious definition of a symbol used by the standard library"
72}
73
74pub struct RuntimeSymbols;
#[automatically_derived]
impl ::core::marker::Copy for RuntimeSymbols { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for RuntimeSymbols { }
#[automatically_derived]
impl ::core::clone::Clone for RuntimeSymbols {
    #[inline]
    fn clone(&self) -> RuntimeSymbols { *self }
}
impl ::rustc_lint_defs::LintPass for RuntimeSymbols {
    fn name(&self) -> &'static str { "RuntimeSymbols" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [INVALID_RUNTIME_SYMBOL_DEFINITIONS,
                        SUSPICIOUS_RUNTIME_SYMBOL_DEFINITIONS]))
    }
}
impl RuntimeSymbols {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [INVALID_RUNTIME_SYMBOL_DEFINITIONS,
                        SUSPICIOUS_RUNTIME_SYMBOL_DEFINITIONS]))
    }
}declare_lint_pass!(RuntimeSymbols => [INVALID_RUNTIME_SYMBOL_DEFINITIONS, SUSPICIOUS_RUNTIME_SYMBOL_DEFINITIONS]);
75
76impl<'tcx> LateLintPass<'tcx> for RuntimeSymbols {
77    fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) {
78        // Bail-out if the item is not a function/method or static.
79        match item.kind {
80            hir::ItemKind::Fn { sig, ident: _, generics, body: _, has_body: _ } => {
81                // Generic functions cannot have the same runtime symbol as we do not allow
82                // any symbol attributes.
83                if !generics.params.is_empty() {
84                    return;
85                }
86
87                // Try to get the overridden symbol name of this function (our mangling
88                // cannot ever conflict with runtime symbols, so no need to check for those).
89                let Some(symbol_name) = rustc_symbol_mangling::symbol_name_from_attrs(
90                    cx.tcx,
91                    rustc_middle::ty::InstanceKind::Item(item.owner_id.to_def_id()),
92                ) else {
93                    return;
94                };
95
96                check_fn(cx, &symbol_name, sig, item.owner_id.def_id);
97            }
98            hir::ItemKind::Static(..) => {
99                // Compute the symbol name of this static (without mangling, as our mangling
100                // cannot ever conflict with runtime symbols).
101                let Some(symbol_name) = rustc_symbol_mangling::symbol_name_from_attrs(
102                    cx.tcx,
103                    rustc_middle::ty::InstanceKind::Item(item.owner_id.to_def_id()),
104                ) else {
105                    return;
106                };
107
108                let def_id = item.owner_id.def_id;
109
110                check_static(cx, &symbol_name, def_id, item.span);
111            }
112            hir::ItemKind::ForeignMod { abi: _, items } => {
113                for item in items {
114                    let item = cx.tcx.hir_foreign_item(*item);
115
116                    let did = item.owner_id.def_id;
117                    let instance = Instance::new_raw(
118                        did.to_def_id(),
119                        ty::List::identity_for_item(cx.tcx, did),
120                    );
121                    let symbol_name = cx.tcx.symbol_name(instance);
122
123                    match item.kind {
124                        ForeignItemKind::Fn(fn_sig, _idents, _generics) => {
125                            check_fn(cx, &symbol_name.name, fn_sig, did);
126                        }
127                        ForeignItemKind::Static(..) => {
128                            check_static(cx, &symbol_name.name, did, item.span);
129                        }
130                        ForeignItemKind::Type => return,
131                    }
132                }
133            }
134            _ => return,
135        }
136    }
137}
138
139fn check_fn(cx: &LateContext<'_>, symbol_name: &str, sig: FnSig<'_>, did: LocalDefId) {
140    let s = Symbol::intern(symbol_name);
141    let Some(CanonicalSymbol { symbol: _, def_id: expected_def_id }) =
142        cx.tcx.all_canonical_symbols(()).iter().find(|cs| cs.symbol == s)
143    else {
144        // The symbol name does not correspond to a runtime symbols, bail out
145        return;
146    };
147
148    // Get the two function signatures
149    let lang_sig = cx.tcx.normalize_erasing_regions(
150        cx.typing_env(),
151        cx.tcx.fn_sig(expected_def_id).instantiate_identity(),
152    );
153    let user_sig = cx
154        .tcx
155        .normalize_erasing_regions(cx.typing_env(), cx.tcx.fn_sig(did).instantiate_identity());
156
157    // Compare the two signatures with an inference context
158    let infcx = cx.tcx.infer_ctxt().build(cx.typing_mode());
159    let cause = rustc_middle::traits::ObligationCause::misc(sig.span, did);
160    let result = infcx.at(&cause, cx.param_env).eq(DefineOpaqueTypes::No, lang_sig, user_sig);
161
162    // If they don't match, emit our own mismatch signatures
163    if let Err(_terr) = result {
164        // Create fn pointers for diagnostics purpose
165        let expected = Ty::new_fn_ptr(cx.tcx, lang_sig);
166        let actual = Ty::new_fn_ptr(cx.tcx, user_sig);
167
168        if lang_sig.abi() != user_sig.abi()
169            || lang_sig.c_variadic() != user_sig.c_variadic()
170            || lang_sig.inputs().skip_binder().len() != user_sig.inputs().skip_binder().len()
171            || (!lang_sig.output().skip_binder().is_unit()
172                && user_sig.output().skip_binder().is_unit())
173        {
174            cx.emit_span_lint(
175                INVALID_RUNTIME_SYMBOL_DEFINITIONS,
176                sig.span,
177                RedefiningRuntimeSymbolsDiag::FnDefInvalid {
178                    symbol_name: symbol_name.to_string(),
179                    found_fn_sig: actual,
180                    expected_fn_sig: expected,
181                },
182            );
183        } else {
184            cx.emit_span_lint(
185                SUSPICIOUS_RUNTIME_SYMBOL_DEFINITIONS,
186                sig.span,
187                RedefiningRuntimeSymbolsDiag::FnDefSuspicious {
188                    symbol_name: symbol_name.to_string(),
189                    found_fn_sig: actual,
190                    expected_fn_sig: expected,
191                },
192            );
193        };
194    }
195}
196
197fn check_static<'tcx>(cx: &LateContext<'tcx>, symbol_name: &str, did: LocalDefId, sp: Span) {
198    let s = Symbol::intern(symbol_name);
199    let Some(CanonicalSymbol { symbol: _, def_id: expected_def_id }) =
200        cx.tcx.all_canonical_symbols(()).iter().find(|cs| cs.symbol == s)
201    else {
202        // The symbol name does not correspond to a runtime symbols, bail out
203        return;
204    };
205
206    // Get the static type
207    let static_ty = cx.tcx.type_of(did).instantiate_identity().skip_norm_wip();
208
209    // Peel Option<...> and get the inner type (see std weak! macro with #[linkage = "extern_weak"])
210    let inner_static_ty: Ty<'_> = match static_ty.kind() {
211        ty::Adt(def, args) if Some(def.did()) == cx.tcx.lang_items().option_type() => {
212            args.type_at(0)
213        }
214        _ => static_ty,
215    };
216
217    // Get the expected symbol function signature
218    let lang_sig = cx.tcx.normalize_erasing_regions(
219        cx.typing_env(),
220        cx.tcx.fn_sig(expected_def_id).instantiate_identity(),
221    );
222
223    let expected = Ty::new_fn_ptr(cx.tcx, lang_sig);
224
225    // Compare the expected function signature with the static type, report an error if they don't match
226    if expected != inner_static_ty {
227        cx.emit_span_lint(
228            INVALID_RUNTIME_SYMBOL_DEFINITIONS,
229            sp,
230            RedefiningRuntimeSymbolsDiag::Static {
231                static_ty,
232                symbol_name: symbol_name.to_string(),
233                expected_fn_sig: expected,
234            },
235        );
236    }
237}