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 6fa9e3d

Browse files
committedNov 29, 2024·
Auto merge of rust-lang#119286 - jyn514:linker-output, r=<try>
show linker output even if the linker succeeds - show stderr by default - show stdout if `--verbose` is passed - remove both from RUSTC_LOG - hide the linker cli args unless `--verbose` is passed fixes rust-lang#83436. fixes rust-lang#38206. fixes rust-lang#109979. helps with rust-lang#46998. cc https://rust-lang.zulipchat.com/#narrow/stream/233931-t-compiler.2Fmajor-changes/topic/uplift.20some.20-Zverbose.20calls.20and.20rename.20to.E2.80.A6.20compiler-team.23706/near/408986134 this is based on rust-lang#119129 for convenience so i didn't have to duplicate the changes around saving `--verbose` in rust-lang@cb6d033#diff-7a49efa20548d6806dbe1c66dd4dc445fda18fcbbf1709520cadecc4841aae12 try-job: aarch64-apple r? `@bjorn3`
2 parents 0c4f3a4 + fc8b598 commit 6fa9e3d

File tree

27 files changed

+328
-79
lines changed

27 files changed

+328
-79
lines changed
 

‎compiler/rustc_codegen_llvm/src/lib.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ use rustc_codegen_ssa::back::write::{
3434
CodegenContext, FatLtoInput, ModuleConfig, TargetMachineFactoryConfig, TargetMachineFactoryFn,
3535
};
3636
use rustc_codegen_ssa::traits::*;
37-
use rustc_codegen_ssa::{CodegenResults, CompiledModule, ModuleCodegen};
37+
use rustc_codegen_ssa::{CodegenLintLevels, CodegenResults, CompiledModule, ModuleCodegen};
3838
use rustc_data_structures::fx::FxIndexMap;
3939
use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed, FatalError};
4040
use rustc_metadata::EncodedMetadata;
@@ -374,6 +374,7 @@ impl CodegenBackend for LlvmCodegenBackend {
374374
&self,
375375
sess: &Session,
376376
codegen_results: CodegenResults,
377+
lint_levels: CodegenLintLevels,
377378
outputs: &OutputFilenames,
378379
) -> Result<(), ErrorGuaranteed> {
379380
use rustc_codegen_ssa::back::link::link_binary;
@@ -382,7 +383,7 @@ impl CodegenBackend for LlvmCodegenBackend {
382383

383384
// Run the linker on any artifacts that resulted from the LLVM run.
384385
// This should produce either a finished executable or library.
385-
link_binary(sess, &LlvmArchiveBuilderBuilder, codegen_results, outputs)
386+
link_binary(sess, &LlvmArchiveBuilderBuilder, codegen_results, lint_levels, outputs)
386387
}
387388
}
388389

‎compiler/rustc_codegen_ssa/messages.ftl

+2
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,8 @@ codegen_ssa_linker_file_stem = couldn't extract file stem from specified linker
183183
codegen_ssa_linker_not_found = linker `{$linker_path}` not found
184184
.note = {$error}
185185
186+
codegen_ssa_linker_output = {$inner}
187+
186188
codegen_ssa_linker_unsupported_modifier = `as-needed` modifier not supported for current linker
187189
188190
codegen_ssa_linking_failed = linking with `{$linker_path}` failed: {$exit_status}

‎compiler/rustc_codegen_ssa/src/back/link.rs

+38-5
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,14 @@ use rustc_ast::CRATE_NODE_ID;
1515
use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
1616
use rustc_data_structures::memmap::Mmap;
1717
use rustc_data_structures::temp_dir::MaybeTempDir;
18-
use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed, FatalError};
18+
use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed, FatalError, LintDiagnostic};
1919
use rustc_fs_util::{fix_windows_verbatim_for_gcc, try_canonicalize};
2020
use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
21+
use rustc_macros::LintDiagnostic;
2122
use rustc_metadata::fs::{METADATA_FILENAME, copy_to_stdout, emit_wrapper_file};
2223
use rustc_metadata::{find_native_static_library, walk_native_lib_search_dirs};
2324
use rustc_middle::bug;
25+
use rustc_middle::lint::lint_level;
2426
use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile;
2527
use rustc_middle::middle::dependency_format::Linkage;
2628
use rustc_middle::middle::exported_symbols::SymbolExportKind;
@@ -29,6 +31,7 @@ use rustc_session::config::{
2931
OutputType, PrintKind, SplitDwarfKind, Strip,
3032
};
3133
use rustc_session::cstore::DllImport;
34+
use rustc_session::lint::builtin::LINKER_MESSAGES;
3235
use rustc_session::output::{check_file_is_writeable, invalid_output_for_target, out_filename};
3336
use rustc_session::search_paths::PathKind;
3437
use rustc_session::utils::NativeLibKind;
@@ -52,7 +55,7 @@ use super::metadata::{MetadataPosition, create_wrapper_file};
5255
use super::rpath::{self, RPathConfig};
5356
use super::{apple, versioned_llvm_target};
5457
use crate::{
55-
CodegenResults, CompiledModule, CrateInfo, NativeLib, common, errors,
58+
CodegenLintLevels, CodegenResults, CompiledModule, CrateInfo, NativeLib, common, errors,
5659
looks_like_rust_object_file,
5760
};
5861

@@ -70,6 +73,7 @@ pub fn link_binary(
7073
sess: &Session,
7174
archive_builder_builder: &dyn ArchiveBuilderBuilder,
7275
codegen_results: CodegenResults,
76+
lint_levels: CodegenLintLevels,
7377
outputs: &OutputFilenames,
7478
) -> Result<(), ErrorGuaranteed> {
7579
let _timer = sess.timer("link_binary");
@@ -138,6 +142,7 @@ pub fn link_binary(
138142
crate_type,
139143
&out_filename,
140144
&codegen_results,
145+
lint_levels,
141146
path.as_ref(),
142147
)?;
143148
}
@@ -762,6 +767,14 @@ fn link_dwarf_object(sess: &Session, cg_results: &CodegenResults, executable_out
762767
}
763768
}
764769

770+
#[derive(LintDiagnostic)]
771+
#[diag(codegen_ssa_linker_output)]
772+
/// Translating this is kind of useless. We don't pass translation flags to the linker, so we'd just
773+
/// end up with inconsistent languages within the same diagnostic.
774+
struct LinkerOutput {
775+
inner: String,
776+
}
777+
765778
/// Create a dynamic library or executable.
766779
///
767780
/// This will invoke the system linker/cc to create the resulting file. This links to all upstream
@@ -772,6 +785,7 @@ fn link_natively(
772785
crate_type: CrateType,
773786
out_filename: &Path,
774787
codegen_results: &CodegenResults,
788+
lint_levels: CodegenLintLevels,
775789
tmpdir: &Path,
776790
) -> Result<(), ErrorGuaranteed> {
777791
info!("preparing {:?} to {:?}", crate_type, out_filename);
@@ -998,12 +1012,12 @@ fn link_natively(
9981012
let mut output = prog.stderr.clone();
9991013
output.extend_from_slice(&prog.stdout);
10001014
let escaped_output = escape_linker_output(&output, flavor);
1001-
// FIXME: Add UI tests for this error.
10021015
let err = errors::LinkingFailed {
10031016
linker_path: &linker_path,
10041017
exit_status: prog.status,
10051018
command: &cmd,
10061019
escaped_output,
1020+
verbose: sess.opts.verbose,
10071021
};
10081022
sess.dcx().emit_err(err);
10091023
// If MSVC's `link.exe` was expected but the return code
@@ -1045,8 +1059,27 @@ fn link_natively(
10451059

10461060
sess.dcx().abort_if_errors();
10471061
}
1048-
info!("linker stderr:\n{}", escape_string(&prog.stderr));
1049-
info!("linker stdout:\n{}", escape_string(&prog.stdout));
1062+
1063+
let (level, src) = lint_levels.linker_messages;
1064+
let lint = |msg| {
1065+
lint_level(sess, LINKER_MESSAGES, level, src, None, |diag| {
1066+
LinkerOutput { inner: msg }.decorate_lint(diag)
1067+
})
1068+
};
1069+
1070+
if !prog.stderr.is_empty() {
1071+
// We already print `warning:` at the start of the diagnostic. Remove it from the linker output if present.
1072+
let stderr = escape_string(&prog.stderr);
1073+
debug!("original stderr: {stderr}");
1074+
let stderr = stderr
1075+
.strip_prefix("warning: ")
1076+
.unwrap_or(&stderr)
1077+
.replace(": warning: ", ": ");
1078+
lint(format!("linker stderr: {stderr}"));
1079+
}
1080+
if !prog.stdout.is_empty() && sess.opts.verbose {
1081+
lint(format!("linker stdout: {}", escape_string(&prog.stdout)))
1082+
}
10501083
}
10511084
Err(e) => {
10521085
let linker_not_found = e.kind() == io::ErrorKind::NotFound;

‎compiler/rustc_codegen_ssa/src/errors.rs

+8-1
Original file line numberDiff line numberDiff line change
@@ -349,6 +349,7 @@ pub(crate) struct LinkingFailed<'a> {
349349
pub exit_status: ExitStatus,
350350
pub command: &'a Command,
351351
pub escaped_output: String,
352+
pub verbose: bool,
352353
}
353354

354355
impl<G: EmissionGuarantee> Diagnostic<'_, G> for LinkingFailed<'_> {
@@ -359,7 +360,13 @@ impl<G: EmissionGuarantee> Diagnostic<'_, G> for LinkingFailed<'_> {
359360

360361
let contains_undefined_ref = self.escaped_output.contains("undefined reference to");
361362

362-
diag.note(format!("{:?}", self.command)).note(self.escaped_output);
363+
if self.verbose {
364+
diag.note(format!("{:?}", self.command));
365+
} else {
366+
diag.note("use `--verbose` to show all linker arguments");
367+
}
368+
369+
diag.note(self.escaped_output);
363370

364371
// Trying to match an error from OS linkers
365372
// which by now we have no way to translate.

‎compiler/rustc_codegen_ssa/src/lib.rs

+26-2
Original file line numberDiff line numberDiff line change
@@ -29,18 +29,23 @@ use rustc_ast as ast;
2929
use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
3030
use rustc_data_structures::sync::Lrc;
3131
use rustc_data_structures::unord::UnordMap;
32+
use rustc_hir::CRATE_HIR_ID;
3233
use rustc_hir::def_id::CrateNum;
3334
use rustc_macros::{Decodable, Encodable, HashStable};
3435
use rustc_middle::dep_graph::WorkProduct;
36+
use rustc_middle::lint::LintLevelSource;
3537
use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile;
3638
use rustc_middle::middle::dependency_format::Dependencies;
3739
use rustc_middle::middle::exported_symbols::SymbolExportKind;
40+
use rustc_middle::ty::TyCtxt;
3841
use rustc_middle::util::Providers;
3942
use rustc_serialize::opaque::{FileEncoder, MemDecoder};
4043
use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
4144
use rustc_session::Session;
4245
use rustc_session::config::{CrateType, OutputFilenames, OutputType, RUST_CGU_EXT};
4346
use rustc_session::cstore::{self, CrateSource};
47+
use rustc_session::lint::Level;
48+
use rustc_session::lint::builtin::LINKER_MESSAGES;
4449
use rustc_session::utils::NativeLibKind;
4550
use rustc_span::symbol::Symbol;
4651

@@ -251,6 +256,7 @@ impl CodegenResults {
251256
sess: &Session,
252257
rlink_file: &Path,
253258
codegen_results: &CodegenResults,
259+
lint_levels: CodegenLintLevels,
254260
outputs: &OutputFilenames,
255261
) -> Result<usize, io::Error> {
256262
let mut encoder = FileEncoder::new(rlink_file)?;
@@ -260,14 +266,15 @@ impl CodegenResults {
260266
encoder.emit_raw_bytes(&RLINK_VERSION.to_be_bytes());
261267
encoder.emit_str(sess.cfg_version);
262268
Encodable::encode(codegen_results, &mut encoder);
269+
Encodable::encode(&lint_levels, &mut encoder);
263270
Encodable::encode(outputs, &mut encoder);
264271
encoder.finish().map_err(|(_path, err)| err)
265272
}
266273

267274
pub fn deserialize_rlink(
268275
sess: &Session,
269276
data: Vec<u8>,
270-
) -> Result<(Self, OutputFilenames), CodegenErrors> {
277+
) -> Result<(Self, CodegenLintLevels, OutputFilenames), CodegenErrors> {
271278
// The Decodable machinery is not used here because it panics if the input data is invalid
272279
// and because its internal representation may change.
273280
if !data.starts_with(RLINK_MAGIC) {
@@ -298,7 +305,24 @@ impl CodegenResults {
298305
}
299306

300307
let codegen_results = CodegenResults::decode(&mut decoder);
308+
let lint_levels = CodegenLintLevels::decode(&mut decoder);
301309
let outputs = OutputFilenames::decode(&mut decoder);
302-
Ok((codegen_results, outputs))
310+
Ok((codegen_results, lint_levels, outputs))
311+
}
312+
}
313+
314+
/// A list of lint levels used in codegen.
315+
///
316+
/// When using `-Z link-only`, we don't have access to the tcx and must work
317+
/// solely from the `.rlink` file. `Lint`s are defined too early to be encodeable.
318+
/// Instead, encode exactly the information we need.
319+
#[derive(Copy, Clone, Encodable, Decodable)]
320+
pub struct CodegenLintLevels {
321+
linker_messages: (Level, LintLevelSource),
322+
}
323+
324+
impl CodegenLintLevels {
325+
pub fn from_tcx(tcx: TyCtxt<'_>) -> Self {
326+
Self { linker_messages: tcx.lint_level_at_node(LINKER_MESSAGES, CRATE_HIR_ID) }
303327
}
304328
}

‎compiler/rustc_codegen_ssa/src/traits/backend.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ use super::write::WriteBackendMethods;
1919
use crate::back::archive::ArArchiveBuilderBuilder;
2020
use crate::back::link::link_binary;
2121
use crate::back::write::TargetMachineFactoryFn;
22-
use crate::{CodegenResults, ModuleCodegen};
22+
use crate::{CodegenLintLevels, CodegenResults, ModuleCodegen};
2323

2424
pub trait BackendTypes {
2525
type Value: CodegenObject;
@@ -88,9 +88,10 @@ pub trait CodegenBackend {
8888
&self,
8989
sess: &Session,
9090
codegen_results: CodegenResults,
91+
lint_levels: CodegenLintLevels,
9192
outputs: &OutputFilenames,
9293
) -> Result<(), ErrorGuaranteed> {
93-
link_binary(sess, &ArArchiveBuilderBuilder, codegen_results, outputs)
94+
link_binary(sess, &ArArchiveBuilderBuilder, codegen_results, lint_levels, outputs)
9495
}
9596

9697
/// Returns `true` if this backend can be safely called from multiple threads.

‎compiler/rustc_driver_impl/src/lib.rs

+28-21
Original file line numberDiff line numberDiff line change
@@ -645,27 +645,34 @@ fn process_rlink(sess: &Session, compiler: &interface::Compiler) {
645645
let rlink_data = fs::read(file).unwrap_or_else(|err| {
646646
dcx.emit_fatal(RlinkUnableToRead { err });
647647
});
648-
let (codegen_results, outputs) = match CodegenResults::deserialize_rlink(sess, rlink_data) {
649-
Ok((codegen, outputs)) => (codegen, outputs),
650-
Err(err) => {
651-
match err {
652-
CodegenErrors::WrongFileType => dcx.emit_fatal(RLinkWrongFileType),
653-
CodegenErrors::EmptyVersionNumber => dcx.emit_fatal(RLinkEmptyVersionNumber),
654-
CodegenErrors::EncodingVersionMismatch { version_array, rlink_version } => dcx
655-
.emit_fatal(RLinkEncodingVersionMismatch { version_array, rlink_version }),
656-
CodegenErrors::RustcVersionMismatch { rustc_version } => {
657-
dcx.emit_fatal(RLinkRustcVersionMismatch {
658-
rustc_version,
659-
current_version: sess.cfg_version,
660-
})
661-
}
662-
CodegenErrors::CorruptFile => {
663-
dcx.emit_fatal(RlinkCorruptFile { file });
664-
}
665-
};
666-
}
667-
};
668-
if compiler.codegen_backend.link(sess, codegen_results, &outputs).is_err() {
648+
let (codegen_results, lint_levels, outputs) =
649+
match CodegenResults::deserialize_rlink(sess, rlink_data) {
650+
Ok((codegen, lints, outputs)) => (codegen, lints, outputs),
651+
Err(err) => {
652+
match err {
653+
CodegenErrors::WrongFileType => dcx.emit_fatal(RLinkWrongFileType),
654+
CodegenErrors::EmptyVersionNumber => {
655+
dcx.emit_fatal(RLinkEmptyVersionNumber)
656+
}
657+
CodegenErrors::EncodingVersionMismatch { version_array, rlink_version } => {
658+
dcx.emit_fatal(RLinkEncodingVersionMismatch {
659+
version_array,
660+
rlink_version,
661+
})
662+
}
663+
CodegenErrors::RustcVersionMismatch { rustc_version } => {
664+
dcx.emit_fatal(RLinkRustcVersionMismatch {
665+
rustc_version,
666+
current_version: sess.cfg_version,
667+
})
668+
}
669+
CodegenErrors::CorruptFile => {
670+
dcx.emit_fatal(RlinkCorruptFile { file });
671+
}
672+
};
673+
}
674+
};
675+
if compiler.codegen_backend.link(sess, codegen_results, lint_levels, &outputs).is_err() {
669676
FatalError.raise();
670677
}
671678
} else {

‎compiler/rustc_interface/src/queries.rs

+5-2
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@ use std::cell::{RefCell, RefMut};
33
use std::sync::Arc;
44

55
use rustc_ast as ast;
6-
use rustc_codegen_ssa::CodegenResults;
76
use rustc_codegen_ssa::traits::CodegenBackend;
7+
use rustc_codegen_ssa::{CodegenLintLevels, CodegenResults};
88
use rustc_data_structures::steal::Steal;
99
use rustc_data_structures::svh::Svh;
1010
use rustc_data_structures::sync::{OnceLock, WorkerLocal};
@@ -117,6 +117,7 @@ impl<'tcx> Queries<'tcx> {
117117
pub struct Linker {
118118
dep_graph: DepGraph,
119119
output_filenames: Arc<OutputFilenames>,
120+
lint_levels: CodegenLintLevels,
120121
// Only present when incr. comp. is enabled.
121122
crate_hash: Option<Svh>,
122123
ongoing_codegen: Box<dyn Any>,
@@ -144,6 +145,7 @@ impl Linker {
144145
Ok(Linker {
145146
dep_graph: tcx.dep_graph.clone(),
146147
output_filenames: Arc::clone(tcx.output_filenames(())),
148+
lint_levels: CodegenLintLevels::from_tcx(tcx),
147149
crate_hash: if tcx.needs_crate_hash() {
148150
Some(tcx.crate_hash(LOCAL_CRATE))
149151
} else {
@@ -187,6 +189,7 @@ impl Linker {
187189
sess,
188190
&rlink_file,
189191
&codegen_results,
192+
self.lint_levels,
190193
&*self.output_filenames,
191194
)
192195
.map_err(|error| {
@@ -196,7 +199,7 @@ impl Linker {
196199
}
197200

198201
let _timer = sess.prof.verbose_generic_activity("link_crate");
199-
codegen_backend.link(sess, codegen_results, &self.output_filenames)
202+
codegen_backend.link(sess, codegen_results, self.lint_levels, &self.output_filenames)
200203
}
201204
}
202205

‎compiler/rustc_lint/src/levels.rs

+13-8
Original file line numberDiff line numberDiff line change
@@ -130,12 +130,17 @@ fn lints_that_dont_need_to_run(tcx: TyCtxt<'_>, (): ()) -> FxIndexSet<LintId> {
130130
!has_future_breakage && !lint.eval_always
131131
})
132132
.filter_map(|lint| {
133-
let lint_level = map.lint_level_id_at_node(tcx, LintId::of(lint), CRATE_HIR_ID);
134-
if matches!(lint_level, (Level::Allow, ..))
135-
|| (matches!(lint_level, (.., LintLevelSource::Default)))
136-
&& lint.default_level(tcx.sess.edition()) == Level::Allow
137-
{
138-
Some(LintId::of(lint))
133+
if !lint.eval_always {
134+
let lint_level =
135+
map.lint_level_id_at_node(Some(tcx), tcx.sess, LintId::of(lint), CRATE_HIR_ID);
136+
if matches!(lint_level, (Level::Allow, ..))
137+
|| (matches!(lint_level, (.., LintLevelSource::Default)))
138+
&& lint.default_level(tcx.sess.edition()) == Level::Allow
139+
{
140+
Some(LintId::of(lint))
141+
} else {
142+
None
143+
}
139144
} else {
140145
None
141146
}
@@ -248,8 +253,8 @@ impl LintLevelsProvider for LintLevelQueryMap<'_> {
248253
fn insert(&mut self, id: LintId, lvl: LevelAndSource) {
249254
self.specs.specs.get_mut_or_insert_default(self.cur.local_id).insert(id, lvl);
250255
}
251-
fn get_lint_level(&self, lint: &'static Lint, _: &Session) -> LevelAndSource {
252-
self.specs.lint_level_id_at_node(self.tcx, LintId::of(lint), self.cur)
256+
fn get_lint_level(&self, lint: &'static Lint, sess: &Session) -> LevelAndSource {
257+
self.specs.lint_level_id_at_node(Some(self.tcx), sess, LintId::of(lint), self.cur)
253258
}
254259
fn push_expectation(&mut self, id: LintExpectationId, expectation: LintExpectation) {
255260
self.specs.expectations.push((id, expectation))

‎compiler/rustc_lint_defs/src/builtin.rs

+34
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ declare_lint_pass! {
6060
LARGE_ASSIGNMENTS,
6161
LATE_BOUND_LIFETIME_ARGUMENTS,
6262
LEGACY_DERIVE_HELPERS,
63+
LINKER_MESSAGES,
6364
LONG_RUNNING_CONST_EVAL,
6465
LOSSY_PROVENANCE_CASTS,
6566
MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
@@ -4080,6 +4081,39 @@ declare_lint! {
40804081
"call to foreign functions or function pointers with FFI-unwind ABI"
40814082
}
40824083

4084+
declare_lint! {
4085+
/// The `linker_messages` lint forwards warnings from the linker.
4086+
///
4087+
/// ### Example
4088+
///
4089+
/// ```rust,ignore (needs CLI args, platform-specific)
4090+
/// extern "C" {
4091+
/// fn foo();
4092+
/// }
4093+
/// fn main () { unsafe { foo(); } }
4094+
/// ```
4095+
///
4096+
/// On Linux, using `gcc -Wl,--warn-unresolved-symbols` as a linker, this will produce
4097+
///
4098+
/// ```text
4099+
/// warning: linker stderr: rust-lld: undefined symbol: foo
4100+
/// >>> referenced by rust_out.69edbd30df4ae57d-cgu.0
4101+
/// >>> rust_out.rust_out.69edbd30df4ae57d-cgu.0.rcgu.o:(rust_out::main::h3a90094b06757803)
4102+
/// |
4103+
/// = note: `#[warn(linker_messages)]` on by default
4104+
///
4105+
/// warning: 1 warning emitted
4106+
/// ```
4107+
///
4108+
/// ### Explanation
4109+
///
4110+
/// Linkers emit platform-specific and program-specific warnings that cannot be predicted in advance by the rust compiler.
4111+
/// They are forwarded by default, but can be disabled by adding `#![allow(linker_messages)]` at the crate root.
4112+
pub LINKER_MESSAGES,
4113+
Warn,
4114+
"warnings emitted at runtime by the target-specific linker program"
4115+
}
4116+
40834117
declare_lint! {
40844118
/// The `named_arguments_used_positionally` lint detects cases where named arguments are only
40854119
/// used positionally in format strings. This usage is valid but potentially very confusing.

‎compiler/rustc_lint_defs/src/lib.rs

+13-1
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,19 @@ impl<HCX: rustc_hir::HashStableContext> ToStableHashKey<HCX> for LintExpectation
161161
/// Setting for how to handle a lint.
162162
///
163163
/// See: <https://doc.rust-lang.org/rustc/lints/levels.html>
164-
#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash, HashStable_Generic)]
164+
#[derive(
165+
Clone,
166+
Copy,
167+
PartialEq,
168+
PartialOrd,
169+
Eq,
170+
Ord,
171+
Debug,
172+
Hash,
173+
Encodable,
174+
Decodable,
175+
HashStable_Generic
176+
)]
165177
pub enum Level {
166178
/// The `allow` level will not issue any message.
167179
Allow,

‎compiler/rustc_middle/src/lint.rs

+30-18
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@ use std::cmp;
33
use rustc_data_structures::fx::FxIndexMap;
44
use rustc_data_structures::sorted_map::SortedMap;
55
use rustc_errors::{Diag, MultiSpan};
6-
use rustc_hir::{HirId, ItemLocalId};
7-
use rustc_macros::HashStable;
6+
use rustc_hir::{CRATE_HIR_ID, HirId, ItemLocalId};
7+
use rustc_macros::{Decodable, Encodable, HashStable};
88
use rustc_session::Session;
99
use rustc_session::lint::builtin::{self, FORBIDDEN_LINT_GROUPS};
1010
use rustc_session::lint::{FutureIncompatibilityReason, Level, Lint, LintExpectationId, LintId};
@@ -15,7 +15,7 @@ use tracing::instrument;
1515
use crate::ty::TyCtxt;
1616

1717
/// How a lint level was set.
18-
#[derive(Clone, Copy, PartialEq, Eq, HashStable, Debug)]
18+
#[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, HashStable, Debug)]
1919
pub enum LintLevelSource {
2020
/// Lint is at the default level as declared in rustc.
2121
Default,
@@ -119,7 +119,7 @@ impl ShallowLintLevelMap {
119119
#[instrument(level = "trace", skip(self, tcx), ret)]
120120
fn probe_for_lint_level(
121121
&self,
122-
tcx: TyCtxt<'_>,
122+
tcx: Option<TyCtxt<'_>>,
123123
id: LintId,
124124
start: HirId,
125125
) -> (Option<Level>, LintLevelSource) {
@@ -132,31 +132,38 @@ impl ShallowLintLevelMap {
132132
let mut owner = start.owner;
133133
let mut specs = &self.specs;
134134

135-
for parent in tcx.hir().parent_id_iter(start) {
136-
if parent.owner != owner {
137-
owner = parent.owner;
138-
specs = &tcx.shallow_lint_levels_on(owner).specs;
139-
}
140-
if let Some(map) = specs.get(&parent.local_id)
141-
&& let Some(&(level, src)) = map.get(&id)
142-
{
143-
return (Some(level), src);
135+
if let Some(tcx) = tcx {
136+
for parent in tcx.hir().parent_id_iter(start) {
137+
if parent.owner != owner {
138+
owner = parent.owner;
139+
specs = &tcx.shallow_lint_levels_on(owner).specs;
140+
}
141+
if let Some(map) = specs.get(&parent.local_id)
142+
&& let Some(&(level, src)) = map.get(&id)
143+
{
144+
return (Some(level), src);
145+
}
144146
}
145147
}
146148

147149
(None, LintLevelSource::Default)
148150
}
149151

150152
/// Fetch and return the user-visible lint level for the given lint at the given HirId.
151-
#[instrument(level = "trace", skip(self, tcx), ret)]
153+
#[instrument(level = "trace", skip(self, tcx, sess), ret)]
152154
pub fn lint_level_id_at_node(
153155
&self,
154-
tcx: TyCtxt<'_>,
156+
tcx: Option<TyCtxt<'_>>,
157+
sess: &Session,
155158
lint: LintId,
156159
cur: HirId,
157160
) -> (Level, LintLevelSource) {
161+
assert!(
162+
tcx.is_some() || cur == CRATE_HIR_ID,
163+
"must pass in a tcx to access any level other than the root"
164+
);
158165
let (level, mut src) = self.probe_for_lint_level(tcx, lint, cur);
159-
let level = reveal_actual_level(level, &mut src, tcx.sess, lint, |lint| {
166+
let level = reveal_actual_level(level, &mut src, sess, lint, |lint| {
160167
self.probe_for_lint_level(tcx, lint, cur)
161168
});
162169
(level, src)
@@ -166,14 +173,19 @@ impl ShallowLintLevelMap {
166173
impl TyCtxt<'_> {
167174
/// Fetch and return the user-visible lint level for the given lint at the given HirId.
168175
pub fn lint_level_at_node(self, lint: &'static Lint, id: HirId) -> (Level, LintLevelSource) {
169-
self.shallow_lint_levels_on(id.owner).lint_level_id_at_node(self, LintId::of(lint), id)
176+
self.shallow_lint_levels_on(id.owner).lint_level_id_at_node(
177+
Some(self),
178+
self.sess,
179+
LintId::of(lint),
180+
id,
181+
)
170182
}
171183
}
172184

173185
/// This struct represents a lint expectation and holds all required information
174186
/// to emit the `unfulfilled_lint_expectations` lint if it is unfulfilled after
175187
/// the `LateLintPass` has completed.
176-
#[derive(Clone, Debug, HashStable)]
188+
#[derive(Clone, Debug, Encodable, Decodable, HashStable)]
177189
pub struct LintExpectation {
178190
/// The reason for this expectation that can optionally be added as part of
179191
/// the attribute. It will be displayed as part of the lint message.

‎compiler/rustc_passes/messages.ftl

+3
Original file line numberDiff line numberDiff line change
@@ -798,6 +798,9 @@ passes_unused_duplicate =
798798
passes_unused_empty_lints_note =
799799
attribute `{$name}` with an empty list has no effect
800800
801+
passes_unused_linker_warnings_note =
802+
the `linker_warnings` lint can only be controlled at the root of a crate with `--crate-type bin`
803+
801804
passes_unused_multiple =
802805
multiple `{$name}` attributes
803806
.suggestion = remove this attribute

‎compiler/rustc_passes/src/check_attr.rs

+10
Original file line numberDiff line numberDiff line change
@@ -2271,6 +2271,16 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
22712271
&& item.path == sym::reason
22722272
{
22732273
errors::UnusedNote::NoLints { name: attr.name_or_empty() }
2274+
} else if matches!(
2275+
attr.name_or_empty(),
2276+
sym::allow | sym::warn | sym::deny | sym::forbid | sym::expect
2277+
) && let Some(meta) = attr.meta_item_list()
2278+
&& meta.iter().any(|meta| {
2279+
meta.meta_item().map_or(false, |item| item.path == sym::linker_messages)
2280+
})
2281+
&& hir_id != CRATE_HIR_ID
2282+
{
2283+
errors::UnusedNote::LinkerWarningsBinaryCrateOnly
22742284
} else if attr.name_or_empty() == sym::default_method_body_is_const {
22752285
errors::UnusedNote::DefaultMethodBodyConst
22762286
} else {

‎compiler/rustc_passes/src/errors.rs

+2
Original file line numberDiff line numberDiff line change
@@ -762,6 +762,8 @@ pub(crate) enum UnusedNote {
762762
NoLints { name: Symbol },
763763
#[note(passes_unused_default_method_body_const_note)]
764764
DefaultMethodBodyConst,
765+
#[note(passes_unused_linker_warnings_note)]
766+
LinkerWarningsBinaryCrateOnly,
765767
}
766768

767769
#[derive(LintDiagnostic)]

‎compiler/rustc_span/src/symbol.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1153,6 +1153,7 @@ symbols! {
11531153
link_section,
11541154
linkage,
11551155
linker,
1156+
linker_messages,
11561157
lint_reasons,
11571158
literal,
11581159
load,

‎src/bootstrap/src/core/build_steps/compile.rs

+5
Original file line numberDiff line numberDiff line change
@@ -592,6 +592,11 @@ pub fn std_cargo(builder: &Builder<'_>, target: TargetSelection, stage: u32, car
592592
// separate setting for the compiler.
593593
cargo.rustflag("-Cforce-frame-pointers=yes");
594594

595+
// Ignore linker warnings on macOS for now. These are complicated to fix and don't affect the build.
596+
if target.contains("apple-darwin") {
597+
cargo.rustflag("-Alinker-messages");
598+
}
599+
595600
let html_root =
596601
format!("-Zcrate-attr=doc(html_root_url=\"{}/\")", builder.doc_rust_lang_org_channel(),);
597602
cargo.rustflag(&html_root);

‎src/tools/run-make-support/src/external_deps/rustc.rs

+6
Original file line numberDiff line numberDiff line change
@@ -319,6 +319,12 @@ impl Rustc {
319319
self
320320
}
321321

322+
/// Pass the `--verbose` flag.
323+
pub fn verbose(&mut self) -> &mut Self {
324+
self.cmd.arg("--verbose");
325+
self
326+
}
327+
322328
/// `EXTRARSCXXFLAGS`
323329
pub fn extra_rs_cxx_flags(&mut self) -> &mut Self {
324330
// Adapted from tools.mk (trimmed):

‎tests/run-make/link-args-order/rmake.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -15,15 +15,17 @@ fn main() {
1515
.link_args("b c")
1616
.link_args("d e")
1717
.link_arg("f")
18+
.arg("--print=link-args")
1819
.run_fail()
19-
.assert_stderr_contains(r#""a" "b" "c" "d" "e" "f""#);
20+
.assert_stdout_contains(r#""a" "b" "c" "d" "e" "f""#);
2021
rustc()
2122
.input("empty.rs")
2223
.linker_flavor(linker)
2324
.arg("-Zpre-link-arg=a")
2425
.arg("-Zpre-link-args=b c")
2526
.arg("-Zpre-link-args=d e")
2627
.arg("-Zpre-link-arg=f")
28+
.arg("--print=link-args")
2729
.run_fail()
28-
.assert_stderr_contains(r#""a" "b" "c" "d" "e" "f""#);
30+
.assert_stdout_contains(r#""a" "b" "c" "d" "e" "f""#);
2931
}

‎tests/run-make/link-dedup/rmake.rs

+6-6
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,13 @@ fn main() {
1414
rustc().input("depb.rs").run();
1515
rustc().input("depc.rs").run();
1616

17-
let output = rustc().input("empty.rs").cfg("bar").run_fail();
18-
output.assert_stderr_contains(needle_from_libs(&["testa", "testb", "testa"]));
17+
let output = rustc().input("empty.rs").cfg("bar").arg("--print=link-args").run_fail();
18+
output.assert_stdout_contains(needle_from_libs(&["testa", "testb", "testa"]));
1919

20-
let output = rustc().input("empty.rs").run_fail();
21-
output.assert_stderr_contains(needle_from_libs(&["testa"]));
22-
output.assert_stderr_not_contains(needle_from_libs(&["testb"]));
23-
output.assert_stderr_not_contains(needle_from_libs(&["testa", "testa", "testa"]));
20+
let output = rustc().input("empty.rs").arg("--print=link-args").run_fail();
21+
output.assert_stdout_contains(needle_from_libs(&["testa"]));
22+
output.assert_stdout_not_contains(needle_from_libs(&["testb"]));
23+
output.assert_stdout_not_contains(needle_from_libs(&["testa", "testa", "testa"]));
2424
// Adjacent identical native libraries are no longer deduplicated if
2525
// they come from different crates (https://github.com/rust-lang/rust/pull/103311)
2626
// so the following will fail:
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
fn main() {
2+
for arg in std::env::args() {
3+
match &*arg {
4+
"run_make_info" => println!("foo"),
5+
"run_make_warn" => eprintln!("warning: bar"),
6+
"run_make_error" => {
7+
eprintln!("error: baz");
8+
std::process::exit(1);
9+
}
10+
_ => (),
11+
}
12+
}
13+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
#!/bin/sh
2+
3+
code=0
4+
while ! [ $# = 0 ]; do
5+
case "$1" in
6+
run_make_info) echo "foo"
7+
;;
8+
run_make_warn) echo "warning: bar" >&2
9+
;;
10+
run_make_error) echo "error: baz" >&2; code=1
11+
;;
12+
*) ;; # rustc passes lots of args we don't care about
13+
esac
14+
shift
15+
done
16+
17+
exit $code

‎tests/run-make/linker-warning/main.rs

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
fn main() {}
+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
use std::path::Path;
2+
3+
use run_make_support::rfs::remove_file;
4+
use run_make_support::{Rustc, rustc};
5+
6+
fn run_rustc() -> Rustc {
7+
let mut rustc = rustc();
8+
rustc.arg("main.rs").output("main").linker("./fake-linker");
9+
rustc
10+
}
11+
12+
fn main() {
13+
// first, compile our linker
14+
rustc().arg("fake-linker.rs").output("fake-linker").run();
15+
16+
// Run rustc with our fake linker, and make sure it shows warnings
17+
let warnings = run_rustc().link_arg("run_make_warn").run();
18+
warnings.assert_stderr_contains("warning: linker stderr: bar");
19+
20+
// Make sure it shows stdout, but only when --verbose is passed
21+
run_rustc()
22+
.link_arg("run_make_info")
23+
.verbose()
24+
.run()
25+
.assert_stderr_contains("warning: linker stdout: foo");
26+
run_rustc()
27+
.link_arg("run_make_info")
28+
.run()
29+
.assert_stderr_not_contains("warning: linker stdout: foo");
30+
31+
// Make sure we short-circuit this new path if the linker exits with an error
32+
// (so the diagnostic is less verbose)
33+
run_rustc().link_arg("run_make_error").run_fail().assert_stderr_contains("note: error: baz");
34+
35+
// Make sure we don't show the linker args unless `--verbose` is passed
36+
run_rustc()
37+
.link_arg("run_make_error")
38+
.verbose()
39+
.run_fail()
40+
.assert_stderr_contains_regex("fake-linker.*run_make_error");
41+
run_rustc()
42+
.link_arg("run_make_error")
43+
.run_fail()
44+
.assert_stderr_not_contains_regex("fake-linker.*run_make_error");
45+
}

‎tests/run-make/rust-lld-by-default-nightly/rmake.rs

+4-3
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ fn main() {
1313
// A regular compilation should use rust-lld by default. We'll check that by asking the linker
1414
// to display its version number with a link-arg.
1515
let output = rustc()
16-
.env("RUSTC_LOG", "rustc_codegen_ssa::back::link=info")
16+
.verbose()
1717
.link_arg("-Wl,-v")
1818
.input("main.rs")
1919
.run();
@@ -25,7 +25,7 @@ fn main() {
2525

2626
// But it can still be disabled by turning the linker feature off.
2727
let output = rustc()
28-
.env("RUSTC_LOG", "rustc_codegen_ssa::back::link=info")
28+
.verbose()
2929
.link_arg("-Wl,-v")
3030
.arg("-Zlinker-features=-lld")
3131
.input("main.rs")
@@ -38,6 +38,7 @@ fn main() {
3838
}
3939

4040
fn find_lld_version_in_logs(stderr: String) -> bool {
41-
let lld_version_re = Regex::new(r"^LLD [0-9]+\.[0-9]+\.[0-9]+").unwrap();
41+
let lld_version_re =
42+
Regex::new(r"^warning: linker stdout: LLD [0-9]+\.[0-9]+\.[0-9]+").unwrap();
4243
stderr.lines().any(|line| lld_version_re.is_match(line.trim()))
4344
}

‎tests/run-make/rust-lld-custom-target/rmake.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ fn main() {
1515
// Compile to a custom target spec with rust-lld enabled by default. We'll check that by asking
1616
// the linker to display its version number with a link-arg.
1717
let output = rustc()
18-
.env("RUSTC_LOG", "rustc_codegen_ssa::back::link=info")
18+
.verbose()
1919
.crate_type("cdylib")
2020
.target("custom-target.json")
2121
.link_arg("-Wl,-v")
@@ -44,6 +44,7 @@ fn main() {
4444
}
4545

4646
fn find_lld_version_in_logs(stderr: String) -> bool {
47-
let lld_version_re = Regex::new(r"^LLD [0-9]+\.[0-9]+\.[0-9]+").unwrap();
47+
let lld_version_re =
48+
Regex::new(r"^warning: linker stdout: LLD [0-9]+\.[0-9]+\.[0-9]+").unwrap();
4849
stderr.lines().any(|line| lld_version_re.is_match(line.trim()))
4950
}

‎tests/run-make/rust-lld/rmake.rs

+5-4
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,10 @@ fn main() {
1414
// Opt-in to lld and the self-contained linker, to link with rust-lld. We'll check that by
1515
// asking the linker to display its version number with a link-arg.
1616
let output = rustc()
17-
.env("RUSTC_LOG", "rustc_codegen_ssa::back::link=info")
1817
.arg("-Zlinker-features=+lld")
1918
.arg("-Clink-self-contained=+linker")
2019
.arg("-Zunstable-options")
20+
.arg("--verbose")
2121
.link_arg(linker_version_flag)
2222
.input("main.rs")
2323
.run();
@@ -29,8 +29,8 @@ fn main() {
2929

3030
// It should not be used when we explicitly opt-out of lld.
3131
let output = rustc()
32-
.env("RUSTC_LOG", "rustc_codegen_ssa::back::link=info")
3332
.link_arg(linker_version_flag)
33+
.arg("--verbose")
3434
.arg("-Zlinker-features=-lld")
3535
.input("main.rs")
3636
.run();
@@ -43,8 +43,8 @@ fn main() {
4343
// While we're here, also check that the last linker feature flag "wins" when passed multiple
4444
// times to rustc.
4545
let output = rustc()
46-
.env("RUSTC_LOG", "rustc_codegen_ssa::back::link=info")
4746
.link_arg(linker_version_flag)
47+
.arg("--verbose")
4848
.arg("-Clink-self-contained=+linker")
4949
.arg("-Zunstable-options")
5050
.arg("-Zlinker-features=-lld")
@@ -60,6 +60,7 @@ fn main() {
6060
}
6161

6262
fn find_lld_version_in_logs(stderr: String) -> bool {
63-
let lld_version_re = Regex::new(r"^LLD [0-9]+\.[0-9]+\.[0-9]+").unwrap();
63+
let lld_version_re =
64+
Regex::new(r"^warning: linker stdout: LLD [0-9]+\.[0-9]+\.[0-9]+").unwrap();
6465
stderr.lines().any(|line| lld_version_re.is_match(line.trim()))
6566
}

0 commit comments

Comments
 (0)
Please sign in to comment.