Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 97a8240

Browse files
committedNov 28, 2024
Target modifiers (special marked options) are recorded in metainfo and compared to be equal in different crates
1 parent f005c74 commit 97a8240

File tree

18 files changed

+478
-21
lines changed

18 files changed

+478
-21
lines changed
 

‎compiler/rustc_driver_impl/src/lib.rs

+4-3
Original file line numberDiff line numberDiff line change
@@ -1170,11 +1170,12 @@ fn describe_codegen_flags() {
11701170

11711171
fn print_flag_list<T>(
11721172
cmdline_opt: &str,
1173-
flag_list: &[(&'static str, T, &'static str, &'static str)],
1173+
flag_list: &[(&'static str, T, &'static str, &'static str, bool)],
11741174
) {
1175-
let max_len = flag_list.iter().map(|&(name, _, _, _)| name.chars().count()).max().unwrap_or(0);
1175+
let max_len =
1176+
flag_list.iter().map(|&(name, _, _, _, _)| name.chars().count()).max().unwrap_or(0);
11761177

1177-
for &(name, _, _, desc) in flag_list {
1178+
for &(name, _, _, desc, _) in flag_list {
11781179
safe_println!(
11791180
" {} {:>width$}=val -- {}",
11801181
cmdline_opt,

‎compiler/rustc_interface/src/passes.rs

+1
Original file line numberDiff line numberDiff line change
@@ -270,6 +270,7 @@ fn configure_and_expand(
270270

271271
resolver.resolve_crate(&krate);
272272

273+
CStore::from_tcx(tcx).report_incompatible_target_modifiers(tcx, &krate, resolver.lint_buffer());
273274
krate
274275
}
275276

‎compiler/rustc_lint/messages.ftl

+7
Original file line numberDiff line numberDiff line change
@@ -414,6 +414,13 @@ lint_improper_ctypes_union_layout_help = consider adding a `#[repr(C)]` or `#[re
414414
lint_improper_ctypes_union_layout_reason = this union has unspecified layout
415415
lint_improper_ctypes_union_non_exhaustive = this union is non-exhaustive
416416

417+
lint_incompatible_target_modifiers =
418+
mixing `{$flag_name_prefixed}` will cause an ABI mismatch
419+
.note1 = `{$flag_name_prefixed}={$flag_local_value}` in this crate is incompatible with `{$flag_name_prefixed}={$flag_extern_value}` in dependency `{$extern_crate}`
420+
.help = `{$flag_name_prefixed}` modifies the ABI and Rust crates compiled with different values of this flag cannot be used together safely
421+
.suggestion = set `{$flag_name_prefixed}=${flag_extern_value}` in this crate or `{$flag_name_prefixed}=${flag_local_value}` in `{$extern_crate}`
422+
.note2 = alternatively, use `-Cunsafe-allow-abi-mismatch={$flag_name}` to silence this error
423+
417424
lint_incomplete_include =
418425
include macro expected single expression in source
419426

‎compiler/rustc_lint/src/context/diagnostics.rs

+16
Original file line numberDiff line numberDiff line change
@@ -422,6 +422,22 @@ pub(super) fn decorate_lint(sess: &Session, diagnostic: BuiltinLintDiag, diag: &
422422
lints::UnusedCrateDependency { extern_crate, local_crate }.decorate_lint(diag)
423423
}
424424
BuiltinLintDiag::WasmCAbi => lints::WasmCAbi.decorate_lint(diag),
425+
BuiltinLintDiag::IncompatibleTargetModifiers {
426+
extern_crate,
427+
local_crate,
428+
flag_name,
429+
flag_name_prefixed,
430+
flag_local_value,
431+
flag_extern_value,
432+
} => lints::IncompatibleTargetModifiers {
433+
extern_crate,
434+
local_crate,
435+
flag_name,
436+
flag_name_prefixed,
437+
flag_local_value,
438+
flag_extern_value,
439+
}
440+
.decorate_lint(diag),
425441
BuiltinLintDiag::IllFormedAttributeInput { suggestions } => {
426442
lints::IllFormedAttributeInput {
427443
num_suggestions: suggestions.len(),

‎compiler/rustc_lint/src/lints.rs

+14
Original file line numberDiff line numberDiff line change
@@ -2474,6 +2474,20 @@ pub(crate) struct UnusedCrateDependency {
24742474
pub local_crate: Symbol,
24752475
}
24762476

2477+
#[derive(LintDiagnostic)]
2478+
#[diag(lint_incompatible_target_modifiers)]
2479+
#[help]
2480+
#[note(lint_note1)]
2481+
#[note(lint_note2)]
2482+
pub(crate) struct IncompatibleTargetModifiers {
2483+
pub extern_crate: Symbol,
2484+
pub local_crate: Symbol,
2485+
pub flag_name: String,
2486+
pub flag_name_prefixed: String,
2487+
pub flag_local_value: String,
2488+
pub flag_extern_value: String,
2489+
}
2490+
24772491
#[derive(LintDiagnostic)]
24782492
#[diag(lint_wasm_c_abi)]
24792493
pub(crate) struct WasmCAbi;

‎compiler/rustc_lint_defs/src/builtin.rs

+41
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ declare_lint_pass! {
5050
FUZZY_PROVENANCE_CASTS,
5151
HIDDEN_GLOB_REEXPORTS,
5252
ILL_FORMED_ATTRIBUTE_INPUT,
53+
INCOMPATIBLE_TARGET_MODIFIERS,
5354
INCOMPLETE_INCLUDE,
5455
INEFFECTIVE_UNSTABLE_TRAIT_IMPL,
5556
INLINE_NO_SANITIZE,
@@ -582,6 +583,46 @@ declare_lint! {
582583
crate_level_only
583584
}
584585

586+
declare_lint! {
587+
/// The `incompatible_target_modifiers` lint detects crates with incompatible target modifiers
588+
/// (abi-changing or vulnerability-affecting flags).
589+
///
590+
/// ### Example
591+
///
592+
/// ```rust,ignore (needs extern crate)
593+
/// #![deny(incompatible_target_modifiers)]
594+
/// ```
595+
///
596+
/// When main and dependency crates are compiled with `-Zregparm=1` and `-Zregparm=2` correspondingly.
597+
///
598+
/// This will produce:
599+
///
600+
/// ```text
601+
/// error: mixing `-Zregparm` will cause an ABI mismatch
602+
/// --> $DIR/incompatible_regparm.rs:12:1
603+
/// |
604+
/// LL | #![crate_type = "lib"]
605+
/// | ^
606+
/// |
607+
/// = help: `-Zregparm` modifies the ABI and Rust crates compiled with different values of this flag cannot be used together safely
608+
/// = note: `-Zregparm=1` in this crate is incompatible with `-Zregparm=2` in dependency `wrong_regparm`
609+
/// = note: alternatively, use `-Cunsafe-allow-abi-mismatch=regparm` to silence this error
610+
/// = note: `#[deny(incompatible_target_modifiers)]` on by default
611+
/// ```
612+
///
613+
/// ### Explanation
614+
///
615+
/// `Target modifiers` are compilation flags that affects abi or vulnerability resistance.
616+
/// Linking together crates with incompatible target modifiers would produce incorrect code
617+
/// or degradation of vulnerability resistance.
618+
/// So this lint should find such inconsistency.
619+
///
620+
pub INCOMPATIBLE_TARGET_MODIFIERS,
621+
Deny,
622+
"Incompatible target modifiers",
623+
crate_level_only
624+
}
625+
585626
declare_lint! {
586627
/// The `unused_qualifications` lint detects unnecessarily qualified
587628
/// names.

‎compiler/rustc_lint_defs/src/lib.rs

+8
Original file line numberDiff line numberDiff line change
@@ -768,6 +768,14 @@ pub enum BuiltinLintDiag {
768768
AvoidUsingIntelSyntax,
769769
AvoidUsingAttSyntax,
770770
IncompleteInclude,
771+
IncompatibleTargetModifiers {
772+
extern_crate: Symbol,
773+
local_crate: Symbol,
774+
flag_name: String,
775+
flag_name_prefixed: String,
776+
flag_local_value: String,
777+
flag_extern_value: String,
778+
},
771779
UnnameableTestItems,
772780
DuplicateMacroAttribute,
773781
CfgAttrNoAttributes,

‎compiler/rustc_metadata/src/creader.rs

+118-3
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,9 @@ use rustc_hir::definitions::Definitions;
2222
use rustc_index::IndexVec;
2323
use rustc_middle::bug;
2424
use rustc_middle::ty::{TyCtxt, TyCtxtFeed};
25-
use rustc_session::config::{self, CrateType, ExternLocation};
25+
use rustc_session::config::{self, CrateType, ExternLocation, TargetModifier};
2626
use rustc_session::cstore::{CrateDepKind, CrateSource, ExternCrate, ExternCrateSource};
27-
use rustc_session::lint::{self, BuiltinLintDiag};
27+
use rustc_session::lint::{self, BuiltinLintDiag, LintBuffer};
2828
use rustc_session::output::validate_crate_name;
2929
use rustc_session::search_paths::PathKind;
3030
use rustc_span::edition::Edition;
@@ -35,7 +35,9 @@ use tracing::{debug, info, trace};
3535

3636
use crate::errors;
3737
use crate::locator::{CrateError, CrateLocator, CratePaths};
38-
use crate::rmeta::{CrateDep, CrateMetadata, CrateNumMap, CrateRoot, MetadataBlob};
38+
use crate::rmeta::{
39+
CrateDep, CrateMetadata, CrateNumMap, CrateRoot, MetadataBlob, TargetModifiers,
40+
};
3941

4042
/// The backend's way to give the crate store access to the metadata in a library.
4143
/// Note that it returns the raw metadata bytes stored in the library file, whether
@@ -290,6 +292,98 @@ impl CStore {
290292
}
291293
}
292294

295+
pub fn report_incompatible_target_modifiers(
296+
&self,
297+
tcx: TyCtxt<'_>,
298+
krate: &Crate,
299+
lints: &mut LintBuffer,
300+
) {
301+
if tcx.crate_types().contains(&CrateType::ProcMacro) {
302+
return;
303+
}
304+
let sess = tcx.sess;
305+
let empty_vec = Vec::<String>::new();
306+
let allowed_flag_mismatches = match sess.opts.cg.unsafe_allow_abi_mismatch.as_ref() {
307+
Some(vec) => {
308+
if vec.is_empty() {
309+
// Setting `-Zunsafe-allow-abi-mismatch=` to an empty
310+
// value allows all target modifier mismatches.
311+
return;
312+
}
313+
vec
314+
}
315+
None => &empty_vec,
316+
};
317+
let span = krate.spans.inner_span.shrink_to_lo();
318+
319+
let name = tcx.crate_name(LOCAL_CRATE);
320+
let mods = sess.opts.gather_target_modifiers();
321+
for (_cnum, data) in self.iter_crate_data() {
322+
if data.is_proc_macro_crate() {
323+
continue;
324+
}
325+
let mut report_diff = |opt_name_hash: u64,
326+
flag_local_value: &String,
327+
flag_extern_value: &String| {
328+
let name_info = sess.opts.target_modifier_info_by_hash(opt_name_hash);
329+
let (prefix, opt_name) = name_info.expect("Target modifier not found by name hash");
330+
if allowed_flag_mismatches.contains(&opt_name) {
331+
return;
332+
}
333+
lints.buffer_lint(
334+
lint::builtin::INCOMPATIBLE_TARGET_MODIFIERS,
335+
ast::CRATE_NODE_ID,
336+
span,
337+
BuiltinLintDiag::IncompatibleTargetModifiers {
338+
extern_crate: data.name(),
339+
local_crate: name,
340+
flag_name: opt_name.clone(),
341+
flag_name_prefixed: format!("-{}{}", prefix, opt_name),
342+
flag_local_value: flag_local_value.to_string(),
343+
flag_extern_value: flag_extern_value.to_string(),
344+
},
345+
);
346+
};
347+
let mut it1 = mods.iter();
348+
let mut it2 = data.target_modifiers();
349+
let mut left_name_val: Option<TargetModifier> = None;
350+
let mut right_name_val: Option<TargetModifier> = None;
351+
let no_val = "*".to_string();
352+
loop {
353+
left_name_val = left_name_val.or_else(|| it1.next().cloned());
354+
right_name_val = right_name_val.or_else(|| it2.next().cloned());
355+
match (&left_name_val, &right_name_val) {
356+
(Some(l), Some(r)) => match l.name_hash.cmp(&r.name_hash) {
357+
cmp::Ordering::Equal => {
358+
if l.value_code != r.value_code {
359+
report_diff(l.name_hash, &l.value_name, &r.value_name);
360+
}
361+
left_name_val = None;
362+
right_name_val = None;
363+
}
364+
cmp::Ordering::Greater => {
365+
report_diff(r.name_hash, &no_val, &r.value_name);
366+
right_name_val = None;
367+
}
368+
cmp::Ordering::Less => {
369+
report_diff(l.name_hash, &l.value_name, &no_val);
370+
left_name_val = None;
371+
}
372+
},
373+
(Some(l), None) => {
374+
report_diff(l.name_hash, &l.value_name, &no_val);
375+
left_name_val = None;
376+
}
377+
(None, Some(r)) => {
378+
report_diff(r.name_hash, &no_val, &r.value_name);
379+
right_name_val = None;
380+
}
381+
(None, None) => break,
382+
}
383+
}
384+
}
385+
}
386+
293387
pub fn new(metadata_loader: Box<MetadataLoaderDyn>) -> CStore {
294388
CStore {
295389
metadata_loader,
@@ -432,6 +526,7 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> {
432526
};
433527

434528
let cnum_map = self.resolve_crate_deps(root, &crate_root, &metadata, cnum, dep_kind)?;
529+
let target_modifiers = self.resolve_target_modifiers(&crate_root, &metadata, cnum)?;
435530

436531
let raw_proc_macros = if crate_root.is_proc_macro_crate() {
437532
let temp_root;
@@ -456,6 +551,7 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> {
456551
raw_proc_macros,
457552
cnum,
458553
cnum_map,
554+
target_modifiers,
459555
dep_kind,
460556
source,
461557
private_dep,
@@ -694,6 +790,25 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> {
694790
Ok(crate_num_map)
695791
}
696792

793+
fn resolve_target_modifiers(
794+
&mut self,
795+
crate_root: &CrateRoot,
796+
metadata: &MetadataBlob,
797+
krate: CrateNum,
798+
) -> Result<TargetModifiers, CrateError> {
799+
debug!("resolving target modifiers of external crate");
800+
if crate_root.is_proc_macro_crate() {
801+
return Ok(TargetModifiers::new());
802+
}
803+
let mods = crate_root.decode_target_modifiers(metadata);
804+
let mut target_modifiers = TargetModifiers::with_capacity(mods.len());
805+
for modifier in mods {
806+
target_modifiers.push(modifier);
807+
}
808+
debug!("resolve_target_modifiers: target mods for {:?} is {:?}", krate, target_modifiers);
809+
Ok(target_modifiers)
810+
}
811+
697812
fn dlsym_proc_macros(
698813
&self,
699814
path: &Path,

‎compiler/rustc_metadata/src/rmeta/decoder.rs

+19
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ use rustc_middle::{bug, implement_ty_decoder};
2929
use rustc_serialize::opaque::MemDecoder;
3030
use rustc_serialize::{Decodable, Decoder};
3131
use rustc_session::Session;
32+
use rustc_session::config::TargetModifier;
3233
use rustc_session::cstore::{CrateSource, ExternCrate};
3334
use rustc_span::hygiene::HygieneDecodeContext;
3435
use rustc_span::symbol::kw;
@@ -74,6 +75,9 @@ impl MetadataBlob {
7475
/// own crate numbers.
7576
pub(crate) type CrateNumMap = IndexVec<CrateNum, CrateNum>;
7677

78+
/// Target modifiers - abi / vulnerability-resist affecting flags
79+
pub(crate) type TargetModifiers = Vec<TargetModifier>;
80+
7781
pub(crate) struct CrateMetadata {
7882
/// The primary crate data - binary metadata blob.
7983
blob: MetadataBlob,
@@ -111,6 +115,8 @@ pub(crate) struct CrateMetadata {
111115
cnum_map: CrateNumMap,
112116
/// Same ID set as `cnum_map` plus maybe some injected crates like panic runtime.
113117
dependencies: Vec<CrateNum>,
118+
/// Target modifiers - abi and vulnerability-resist affecting flags the crate was compiled with
119+
target_modifiers: TargetModifiers,
114120
/// How to link (or not link) this crate to the currently compiled crate.
115121
dep_kind: CrateDepKind,
116122
/// Filesystem location of this crate.
@@ -961,6 +967,13 @@ impl CrateRoot {
961967
) -> impl ExactSizeIterator<Item = CrateDep> + Captures<'a> {
962968
self.crate_deps.decode(metadata)
963969
}
970+
971+
pub(crate) fn decode_target_modifiers<'a>(
972+
&self,
973+
metadata: &'a MetadataBlob,
974+
) -> impl ExactSizeIterator<Item = TargetModifier> + Captures<'a> {
975+
self.target_modifiers.decode(metadata)
976+
}
964977
}
965978

966979
impl<'a> CrateMetadataRef<'a> {
@@ -1818,6 +1831,7 @@ impl CrateMetadata {
18181831
raw_proc_macros: Option<&'static [ProcMacro]>,
18191832
cnum: CrateNum,
18201833
cnum_map: CrateNumMap,
1834+
target_modifiers: TargetModifiers,
18211835
dep_kind: CrateDepKind,
18221836
source: CrateSource,
18231837
private_dep: bool,
@@ -1849,6 +1863,7 @@ impl CrateMetadata {
18491863
cnum,
18501864
cnum_map,
18511865
dependencies,
1866+
target_modifiers,
18521867
dep_kind,
18531868
source: Lrc::new(source),
18541869
private_dep,
@@ -1878,6 +1893,10 @@ impl CrateMetadata {
18781893
self.dependencies.push(cnum);
18791894
}
18801895

1896+
pub(crate) fn target_modifiers(&self) -> impl Iterator<Item = &TargetModifier> + '_ {
1897+
self.target_modifiers.iter()
1898+
}
1899+
18811900
pub(crate) fn update_extern_crate(&mut self, new_extern_crate: ExternCrate) -> bool {
18821901
let update =
18831902
Some(new_extern_crate.rank()) > self.extern_crate.as_ref().map(ExternCrate::rank);
There was a problem loading the remainder of the diff.

0 commit comments

Comments
 (0)
Failed to load comments.