Skip to content

Commit 6793451

Browse files
committed
Target modifiers (special marked options) are recorded in metainfo and compared to be equal in different crates
1 parent bca5fde commit 6793451

File tree

14 files changed

+369
-6
lines changed

14 files changed

+369
-6
lines changed

Diff for: compiler/rustc_interface/src/passes.rs

+1
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,7 @@ fn configure_and_expand(
281281

282282
resolver.resolve_crate(&krate);
283283

284+
CStore::from_tcx(tcx).report_incompatible_target_modifiers(tcx, &krate, resolver.lint_buffer());
284285
krate
285286
}
286287

Diff for: compiler/rustc_lint/messages.ftl

+10
Original file line numberDiff line numberDiff line change
@@ -415,6 +415,16 @@ lint_improper_ctypes_union_layout_help = consider adding a `#[repr(C)]` or `#[re
415415
lint_improper_ctypes_union_layout_reason = this union has unspecified layout
416416
lint_improper_ctypes_union_non_exhaustive = this union is non-exhaustive
417417
418+
lint_incompatible_target_modifiers =
419+
mixing `{$flag_name_suffixed}` will cause an ABI mismatch
420+
.note1 = `{$flag_name_suffixed}`=`{$flag_local_value}` in crate `{$local_crate}`, `{$flag_name_suffixed}`=`{$flag_extern_value}` in crate `{$extern_crate}`
421+
.help = This error occurs because the `{$flag_name_suffixed}` flag modifies the ABI,
422+
and different crates in your project were compiled with inconsistent settings
423+
.suggestion = To resolve this, ensure that `{$flag_name_suffixed}` is set to the same value
424+
for all crates during compilation
425+
.note2 = To ignore this error, recompile with the following flag:
426+
-Cunsafe-allow-abi-mismatch=`{$flag_name}`
427+
418428
lint_incomplete_include =
419429
include macro expected single expression in source
420430

Diff for: 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_suffixed,
430+
flag_local_value,
431+
flag_extern_value,
432+
} => lints::IncompatibleTargetModifiers {
433+
extern_crate,
434+
local_crate,
435+
flag_name,
436+
flag_name_suffixed,
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(),

Diff for: compiler/rustc_lint/src/lints.rs

+14
Original file line numberDiff line numberDiff line change
@@ -2470,6 +2470,20 @@ pub(crate) struct UnusedCrateDependency {
24702470
pub local_crate: Symbol,
24712471
}
24722472

2473+
#[derive(LintDiagnostic)]
2474+
#[diag(lint_incompatible_target_modifiers)]
2475+
#[help]
2476+
#[note(lint_note1)]
2477+
#[note(lint_note2)]
2478+
pub(crate) struct IncompatibleTargetModifiers {
2479+
pub extern_crate: Symbol,
2480+
pub local_crate: Symbol,
2481+
pub flag_name: String,
2482+
pub flag_name_suffixed: String,
2483+
pub flag_local_value: String,
2484+
pub flag_extern_value: String,
2485+
}
2486+
24732487
#[derive(LintDiagnostic)]
24742488
#[diag(lint_wasm_c_abi)]
24752489
pub(crate) struct WasmCAbi;

Diff for: compiler/rustc_lint_defs/src/builtin.rs

+38
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ declare_lint_pass! {
4949
FUZZY_PROVENANCE_CASTS,
5050
HIDDEN_GLOB_REEXPORTS,
5151
ILL_FORMED_ATTRIBUTE_INPUT,
52+
INCOMPATIBLE_TARGET_MODIFIERS,
5253
INCOMPLETE_INCLUDE,
5354
INEFFECTIVE_UNSTABLE_TRAIT_IMPL,
5455
INLINE_NO_SANITIZE,
@@ -578,6 +579,43 @@ declare_lint! {
578579
crate_level_only
579580
}
580581

582+
declare_lint! {
583+
/// The `incompatible_target_modifiers` lint detects crates with incompatible target modifiers
584+
/// (abi-changing or vulnerability-affecting flags).
585+
///
586+
/// ### Example
587+
///
588+
/// ```rust,ignore (needs extern crate)
589+
/// #![deny(incompatible_target_modifiers)]
590+
/// ```
591+
///
592+
/// When main and dependency crates are compiled with `-Zregparm=1` and `-Zregparm=2` correspondingly.
593+
///
594+
/// This will produce:
595+
///
596+
/// ```text
597+
/// error: crate `incompatible_regparm` has incompatible target modifier with extern crate `wrong_regparm`: `regparm = ( Some(1) | Some(2) )`
598+
/// --> $DIR/incompatible_regparm.rs:5:1
599+
/// |
600+
/// 1 | #![no_core]
601+
/// | ^
602+
/// |
603+
/// = note: `#[deny(incompatible_target_modifiers)]` on by default
604+
/// ```
605+
///
606+
/// ### Explanation
607+
///
608+
/// `Target modifiers` are compilation flags that affects abi or vulnerability resistance.
609+
/// Linking together crates with incompatible target modifiers would produce incorrect code
610+
/// or degradation of vulnerability resistance.
611+
/// So this lint should find such inconsistency.
612+
///
613+
pub INCOMPATIBLE_TARGET_MODIFIERS,
614+
Deny,
615+
"Incompatible target modifiers",
616+
crate_level_only
617+
}
618+
581619
declare_lint! {
582620
/// The `unused_qualifications` lint detects unnecessarily qualified
583621
/// names.

Diff for: compiler/rustc_lint_defs/src/lib.rs

+8
Original file line numberDiff line numberDiff line change
@@ -719,6 +719,14 @@ pub enum BuiltinLintDiag {
719719
AvoidUsingIntelSyntax,
720720
AvoidUsingAttSyntax,
721721
IncompleteInclude,
722+
IncompatibleTargetModifiers {
723+
extern_crate: Symbol,
724+
local_crate: Symbol,
725+
flag_name: String,
726+
flag_name_suffixed: String,
727+
flag_local_value: String,
728+
flag_extern_value: String,
729+
},
722730
UnnameableTestItems,
723731
DuplicateMacroAttribute,
724732
CfgAttrNoAttributes,

Diff for: compiler/rustc_metadata/src/creader.rs

+113-2
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ use rustc_middle::bug;
2424
use rustc_middle::ty::{TyCtxt, TyCtxtFeed};
2525
use rustc_session::config::{self, CrateType, ExternLocation};
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,94 @@ 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+
if let Some(vec) = &sess.opts.cg.unsafe_allow_abi_mismatch
306+
&& vec.is_empty()
307+
{
308+
return;
309+
}
310+
let span = krate.spans.inner_span.shrink_to_lo();
311+
312+
let splitter = |v: &String| {
313+
let splitted: Vec<_> = v.split("=").collect();
314+
(splitted[0].to_string(), splitted[1].to_string())
315+
};
316+
let name = tcx.crate_name(LOCAL_CRATE);
317+
let mods = sess.opts.gather_target_modifiers();
318+
for (_cnum, data) in self.iter_crate_data() {
319+
if data.is_proc_macro_crate() {
320+
continue;
321+
}
322+
let mut report_diff =
323+
|flag_name: &String, flag_local_value: &String, flag_extern_value: &String| {
324+
if let Some(vec) = &sess.opts.cg.unsafe_allow_abi_mismatch {
325+
if vec.contains(flag_name) {
326+
return;
327+
}
328+
}
329+
lints.buffer_lint(
330+
lint::builtin::INCOMPATIBLE_TARGET_MODIFIERS,
331+
ast::CRATE_NODE_ID,
332+
span,
333+
BuiltinLintDiag::IncompatibleTargetModifiers {
334+
extern_crate: data.name(),
335+
local_crate: name,
336+
flag_name: flag_name.to_string(),
337+
flag_name_suffixed: flag_name.to_string(),
338+
flag_local_value: flag_local_value.to_string(),
339+
flag_extern_value: flag_extern_value.to_string(),
340+
},
341+
);
342+
};
343+
let mut it1 = mods.iter().map(splitter);
344+
let mut it2 = data.target_modifiers().map(splitter);
345+
let mut left_name_val: Option<(String, String)> = None;
346+
let mut right_name_val: Option<(String, String)> = None;
347+
let no_val = "*".to_string();
348+
loop {
349+
left_name_val = left_name_val.or_else(|| it1.next());
350+
right_name_val = right_name_val.or_else(|| it2.next());
351+
match (&left_name_val, &right_name_val) {
352+
(Some(l), Some(r)) => match l.0.cmp(&r.0) {
353+
cmp::Ordering::Equal => {
354+
if l.1 != r.1 {
355+
report_diff(&l.0, &l.1, &r.1);
356+
}
357+
left_name_val = None;
358+
right_name_val = None;
359+
}
360+
cmp::Ordering::Greater => {
361+
report_diff(&r.0, &no_val, &r.1);
362+
right_name_val = None;
363+
}
364+
cmp::Ordering::Less => {
365+
report_diff(&l.0, &l.1, &no_val);
366+
left_name_val = None;
367+
}
368+
},
369+
(Some(l), None) => {
370+
report_diff(&l.0, &l.1, &no_val);
371+
left_name_val = None;
372+
}
373+
(None, Some(r)) => {
374+
report_diff(&r.0, &no_val, &r.1);
375+
right_name_val = None;
376+
}
377+
(None, None) => break,
378+
}
379+
}
380+
}
381+
}
382+
293383
pub fn new(metadata_loader: Box<MetadataLoaderDyn>) -> CStore {
294384
CStore {
295385
metadata_loader,
@@ -432,6 +522,7 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> {
432522
};
433523

434524
let cnum_map = self.resolve_crate_deps(root, &crate_root, &metadata, cnum, dep_kind)?;
525+
let target_modifiers = self.resolve_target_modifiers(&crate_root, &metadata, cnum)?;
435526

436527
let raw_proc_macros = if crate_root.is_proc_macro_crate() {
437528
let temp_root;
@@ -456,6 +547,7 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> {
456547
raw_proc_macros,
457548
cnum,
458549
cnum_map,
550+
target_modifiers,
459551
dep_kind,
460552
source,
461553
private_dep,
@@ -689,6 +781,25 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> {
689781
Ok(crate_num_map)
690782
}
691783

784+
fn resolve_target_modifiers(
785+
&mut self,
786+
crate_root: &CrateRoot,
787+
metadata: &MetadataBlob,
788+
krate: CrateNum,
789+
) -> Result<TargetModifiers, CrateError> {
790+
debug!("resolving target modifiers of external crate");
791+
if crate_root.is_proc_macro_crate() {
792+
return Ok(TargetModifiers::new());
793+
}
794+
let mods = crate_root.decode_target_modifiers(metadata);
795+
let mut target_modifiers = TargetModifiers::with_capacity(mods.len());
796+
for modifier in mods {
797+
target_modifiers.push(modifier);
798+
}
799+
debug!("resolve_target_modifiers: target mods for {:?} is {:?}", krate, target_modifiers);
800+
Ok(target_modifiers)
801+
}
802+
692803
fn dlsym_proc_macros(
693804
&self,
694805
path: &Path,

Diff for: compiler/rustc_metadata/src/rmeta/decoder.rs

+18
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,9 @@ impl MetadataBlob {
7373
/// own crate numbers.
7474
pub(crate) type CrateNumMap = IndexVec<CrateNum, CrateNum>;
7575

76+
/// Target modifiers - abi / vulnerability-resist affecting flags
77+
pub(crate) type TargetModifiers = Vec<String>;
78+
7679
pub(crate) struct CrateMetadata {
7780
/// The primary crate data - binary metadata blob.
7881
blob: MetadataBlob,
@@ -110,6 +113,8 @@ pub(crate) struct CrateMetadata {
110113
cnum_map: CrateNumMap,
111114
/// Same ID set as `cnum_map` plus maybe some injected crates like panic runtime.
112115
dependencies: Vec<CrateNum>,
116+
/// Target modifiers - abi and vulnerability-resist affecting flags the crate was compiled with
117+
target_modifiers: TargetModifiers,
113118
/// How to link (or not link) this crate to the currently compiled crate.
114119
dep_kind: CrateDepKind,
115120
/// Filesystem location of this crate.
@@ -960,6 +965,13 @@ impl CrateRoot {
960965
) -> impl ExactSizeIterator<Item = CrateDep> + Captures<'a> {
961966
self.crate_deps.decode(metadata)
962967
}
968+
969+
pub(crate) fn decode_target_modifiers<'a>(
970+
&self,
971+
metadata: &'a MetadataBlob,
972+
) -> impl ExactSizeIterator<Item = String> + Captures<'a> {
973+
self.target_modifiers.decode(metadata)
974+
}
963975
}
964976

965977
impl<'a> CrateMetadataRef<'a> {
@@ -1815,6 +1827,7 @@ impl CrateMetadata {
18151827
raw_proc_macros: Option<&'static [ProcMacro]>,
18161828
cnum: CrateNum,
18171829
cnum_map: CrateNumMap,
1830+
target_modifiers: TargetModifiers,
18181831
dep_kind: CrateDepKind,
18191832
source: CrateSource,
18201833
private_dep: bool,
@@ -1846,6 +1859,7 @@ impl CrateMetadata {
18461859
cnum,
18471860
cnum_map,
18481861
dependencies,
1862+
target_modifiers,
18491863
dep_kind,
18501864
source: Lrc::new(source),
18511865
private_dep,
@@ -1875,6 +1889,10 @@ impl CrateMetadata {
18751889
self.dependencies.push(cnum);
18761890
}
18771891

1892+
pub(crate) fn target_modifiers(&self) -> impl Iterator<Item = &String> + '_ {
1893+
self.target_modifiers.iter()
1894+
}
1895+
18781896
pub(crate) fn update_extern_crate(&mut self, new_extern_crate: ExternCrate) -> bool {
18791897
let update =
18801898
Some(new_extern_crate.rank()) > self.extern_crate.as_ref().map(ExternCrate::rank);

Diff for: compiler/rustc_metadata/src/rmeta/encoder.rs

+8
Original file line numberDiff line numberDiff line change
@@ -692,6 +692,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
692692
// Encode source_map. This needs to be done last, because encoding `Span`s tells us which
693693
// `SourceFiles` we actually need to encode.
694694
let source_map = stat!("source-map", || self.encode_source_map());
695+
let target_modifiers = stat!("target-modifiers", || self.encode_target_modifiers());
695696

696697
let root = stat!("final", || {
697698
let attrs = tcx.hir().krate_attrs();
@@ -732,6 +733,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
732733
native_libraries,
733734
foreign_modules,
734735
source_map,
736+
target_modifiers,
735737
traits,
736738
impls,
737739
incoherent_impls,
@@ -1978,6 +1980,12 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
19781980
self.lazy_array(deps.iter().map(|(_, dep)| dep))
19791981
}
19801982

1983+
fn encode_target_modifiers(&mut self) -> LazyArray<String> {
1984+
empty_proc_macro!(self);
1985+
let tcx = self.tcx;
1986+
self.lazy_array(tcx.sess.opts.gather_target_modifiers())
1987+
}
1988+
19811989
fn encode_lib_features(&mut self) -> LazyArray<(Symbol, FeatureStability)> {
19821990
empty_proc_macro!(self);
19831991
let tcx = self.tcx;

Diff for: compiler/rustc_metadata/src/rmeta/mod.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use std::marker::PhantomData;
22
use std::num::NonZero;
33

4-
pub(crate) use decoder::{CrateMetadata, CrateNumMap, MetadataBlob};
4+
pub(crate) use decoder::{CrateMetadata, CrateNumMap, MetadataBlob, TargetModifiers};
55
use decoder::{DecodeContext, Metadata};
66
use def_path_hash_map::DefPathHashMapRef;
77
use encoder::EncodeContext;
@@ -283,6 +283,7 @@ pub(crate) struct CrateRoot {
283283
def_path_hash_map: LazyValue<DefPathHashMapRef<'static>>,
284284

285285
source_map: LazyTable<u32, Option<LazyValue<rustc_span::SourceFile>>>,
286+
target_modifiers: LazyArray<String>,
286287

287288
compiler_builtins: bool,
288289
needs_allocator: bool,

0 commit comments

Comments
 (0)