Skip to main content

rustc_lint/
runtime_symbols.rs

1use rustc_hir::def_id::{DefId, LocalDefId};
2use rustc_hir::{self as hir, FnSig, ForeignItemKind, LanguageItems};
3use rustc_infer::infer::DefineOpaqueTypes;
4use rustc_middle::ty::{self, Instance, Ty};
5use rustc_session::{declare_lint, declare_lint_pass};
6use rustc_span::Span;
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
76static EXPECTED_SYMBOLS: &[ExpectedSymbol] = &[
77    // `core` symbols
78    ExpectedSymbol { symbol: "memcpy", lang: LanguageItems::memcpy_fn },
79    ExpectedSymbol { symbol: "memmove", lang: LanguageItems::memmove_fn },
80    ExpectedSymbol { symbol: "memset", lang: LanguageItems::memset_fn },
81    ExpectedSymbol { symbol: "memcmp", lang: LanguageItems::memcmp_fn },
82    ExpectedSymbol { symbol: "bcmp", lang: LanguageItems::bcmp_fn },
83    ExpectedSymbol { symbol: "strlen", lang: LanguageItems::strlen_fn },
84    // POSIX symbols
85    ExpectedSymbol { symbol: "open", lang: LanguageItems::open_fn },
86    ExpectedSymbol { symbol: "read", lang: LanguageItems::read_fn },
87    ExpectedSymbol { symbol: "write", lang: LanguageItems::write_fn },
88    ExpectedSymbol { symbol: "close", lang: LanguageItems::close_fn },
89    ExpectedSymbol { symbol: "malloc", lang: LanguageItems::malloc_fn },
90    ExpectedSymbol { symbol: "realloc", lang: LanguageItems::realloc_fn },
91    ExpectedSymbol { symbol: "free", lang: LanguageItems::free_fn },
92    ExpectedSymbol { symbol: "exit", lang: LanguageItems::exit_fn },
93];
94
95#[derive(#[automatically_derived]
impl ::core::marker::Copy for ExpectedSymbol { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ExpectedSymbol {
    #[inline]
    fn clone(&self) -> ExpectedSymbol {
        let _: ::core::clone::AssertParamIsClone<&'static str>;
        let _:
                ::core::clone::AssertParamIsClone<fn(&LanguageItems)
                    -> Option<DefId>>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ExpectedSymbol {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "ExpectedSymbol", "symbol", &self.symbol, "lang", &&self.lang)
    }
}Debug)]
96struct ExpectedSymbol {
97    symbol: &'static str,
98    lang: fn(&LanguageItems) -> Option<DefId>,
99}
100
101impl<'tcx> LateLintPass<'tcx> for RuntimeSymbols {
102    fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) {
103        // Bail-out if the item is not a function/method or static.
104        match item.kind {
105            hir::ItemKind::Fn { sig, ident: _, generics, body: _, has_body: _ } => {
106                // Generic functions cannot have the same runtime symbol as we do not allow
107                // any symbol attributes.
108                if !generics.params.is_empty() {
109                    return;
110                }
111
112                // Try to get the overridden symbol name of this function (our mangling
113                // cannot ever conflict with runtime symbols, so no need to check for those).
114                let Some(symbol_name) = rustc_symbol_mangling::symbol_name_from_attrs(
115                    cx.tcx,
116                    rustc_middle::ty::InstanceKind::Item(item.owner_id.to_def_id()),
117                ) else {
118                    return;
119                };
120
121                check_fn(cx, &symbol_name, sig, item.owner_id.def_id);
122            }
123            hir::ItemKind::Static(..) => {
124                // Compute the symbol name of this static (without mangling, as our mangling
125                // cannot ever conflict with runtime symbols).
126                let Some(symbol_name) = rustc_symbol_mangling::symbol_name_from_attrs(
127                    cx.tcx,
128                    rustc_middle::ty::InstanceKind::Item(item.owner_id.to_def_id()),
129                ) else {
130                    return;
131                };
132
133                let def_id = item.owner_id.def_id;
134
135                check_static(cx, &symbol_name, def_id, item.span);
136            }
137            hir::ItemKind::ForeignMod { abi: _, items } => {
138                for item in items {
139                    let item = cx.tcx.hir_foreign_item(*item);
140
141                    let did = item.owner_id.def_id;
142                    let instance = Instance::new_raw(
143                        did.to_def_id(),
144                        ty::List::identity_for_item(cx.tcx, did),
145                    );
146                    let symbol_name = cx.tcx.symbol_name(instance);
147
148                    match item.kind {
149                        ForeignItemKind::Fn(fn_sig, _idents, _generics) => {
150                            check_fn(cx, &symbol_name.name, fn_sig, did);
151                        }
152                        ForeignItemKind::Static(..) => {
153                            check_static(cx, &symbol_name.name, did, item.span);
154                        }
155                        ForeignItemKind::Type => return,
156                    }
157                }
158            }
159            _ => return,
160        }
161    }
162}
163
164fn check_fn(cx: &LateContext<'_>, symbol_name: &str, sig: FnSig<'_>, did: LocalDefId) {
165    let Some(expected_symbol) = EXPECTED_SYMBOLS.iter().find(|es| es.symbol == symbol_name) else {
166        // The symbol name does not correspond to a runtime symbols, bail out
167        return;
168    };
169
170    let Some(expected_def_id) = (expected_symbol.lang)(&cx.tcx.lang_items()) else {
171        // Can't find the corresponding language item, bail out
172        return;
173    };
174
175    // Get the two function signatures
176    let lang_sig = cx.tcx.normalize_erasing_regions(
177        cx.typing_env(),
178        cx.tcx.fn_sig(expected_def_id).instantiate_identity(),
179    );
180    let user_sig = cx
181        .tcx
182        .normalize_erasing_regions(cx.typing_env(), cx.tcx.fn_sig(did).instantiate_identity());
183
184    // Compare the two signatures with an inference context
185    let infcx = cx.tcx.infer_ctxt().build(cx.typing_mode());
186    let cause = rustc_middle::traits::ObligationCause::misc(sig.span, did);
187    let result = infcx.at(&cause, cx.param_env).eq(DefineOpaqueTypes::No, lang_sig, user_sig);
188
189    // If they don't match, emit our own mismatch signatures
190    if let Err(_terr) = result {
191        // Create fn pointers for diagnostics purpose
192        let expected = Ty::new_fn_ptr(cx.tcx, lang_sig);
193        let actual = Ty::new_fn_ptr(cx.tcx, user_sig);
194
195        if lang_sig.abi() != user_sig.abi()
196            || lang_sig.c_variadic() != user_sig.c_variadic()
197            || lang_sig.inputs().skip_binder().len() != user_sig.inputs().skip_binder().len()
198            || (!lang_sig.output().skip_binder().is_unit()
199                && user_sig.output().skip_binder().is_unit())
200        {
201            cx.emit_span_lint(
202                INVALID_RUNTIME_SYMBOL_DEFINITIONS,
203                sig.span,
204                RedefiningRuntimeSymbolsDiag::FnDefInvalid {
205                    symbol_name: symbol_name.to_string(),
206                    found_fn_sig: actual,
207                    expected_fn_sig: expected,
208                },
209            );
210        } else {
211            cx.emit_span_lint(
212                SUSPICIOUS_RUNTIME_SYMBOL_DEFINITIONS,
213                sig.span,
214                RedefiningRuntimeSymbolsDiag::FnDefSuspicious {
215                    symbol_name: symbol_name.to_string(),
216                    found_fn_sig: actual,
217                    expected_fn_sig: expected,
218                },
219            );
220        };
221    }
222}
223
224fn check_static<'tcx>(cx: &LateContext<'tcx>, symbol_name: &str, did: LocalDefId, sp: Span) {
225    let Some(expected_symbol) = EXPECTED_SYMBOLS.iter().find(|es| es.symbol == symbol_name) else {
226        // The symbol name does not correspond to a runtime symbols, bail out
227        return;
228    };
229
230    let Some(expected_def_id) = (expected_symbol.lang)(&cx.tcx.lang_items()) else {
231        // Can't find the corresponding language item, bail out
232        return;
233    };
234
235    // Get the static type
236    let static_ty = cx.tcx.type_of(did).instantiate_identity().skip_norm_wip();
237
238    // Peel Option<...> and get the inner type (see std weak! macro with #[linkage = "extern_weak"])
239    let inner_static_ty: Ty<'_> = match static_ty.kind() {
240        ty::Adt(def, args) if Some(def.did()) == cx.tcx.lang_items().option_type() => {
241            args.type_at(0)
242        }
243        _ => static_ty,
244    };
245
246    // Get the expected symbol function signature
247    let lang_sig = cx.tcx.normalize_erasing_regions(
248        cx.typing_env(),
249        cx.tcx.fn_sig(expected_def_id).instantiate_identity(),
250    );
251
252    let expected = Ty::new_fn_ptr(cx.tcx, lang_sig);
253
254    // Compare the expected function signature with the static type, report an error if they don't match
255    if expected != inner_static_ty {
256        cx.emit_span_lint(
257            INVALID_RUNTIME_SYMBOL_DEFINITIONS,
258            sp,
259            RedefiningRuntimeSymbolsDiag::Static {
260                static_ty,
261                symbol_name: symbol_name.to_string(),
262                expected_fn_sig: expected,
263            },
264        );
265    }
266}