Skip to content

Commit 7b0976b

Browse files
committed
Auto merge of rust-lang#119286 - jyn514:linker-output, r=<try>
show linker output even if the linker succeeds Show stderr and stderr by default, controlled by a new `linker_messages` lint. fixes rust-lang#83436. fixes rust-lang#38206. 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 try-job: aarch64-apple dist-x86_64-msvc r? `@bjorn3`
2 parents af952c1 + cffd850 commit 7b0976b

File tree

26 files changed

+362
-87
lines changed

26 files changed

+362
-87
lines changed

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

+85-30
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;
18+
use rustc_errors::{DiagCtxtHandle, 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;
@@ -749,6 +752,14 @@ fn link_dwarf_object(sess: &Session, cg_results: &CodegenResults, executable_out
749752
}
750753
}
751754

755+
#[derive(LintDiagnostic)]
756+
#[diag(codegen_ssa_linker_output)]
757+
/// Translating this is kind of useless. We don't pass translation flags to the linker, so we'd just
758+
/// end up with inconsistent languages within the same diagnostic.
759+
struct LinkerOutput {
760+
inner: String,
761+
}
762+
752763
/// Create a dynamic library or executable.
753764
///
754765
/// This will invoke the system linker/cc to create the resulting file. This links to all upstream
@@ -981,6 +992,20 @@ fn link_natively(
981992

982993
match prog {
983994
Ok(prog) => {
995+
let is_msvc_link_exe = if let Some(code) = prog.status.code() {
996+
sess.target.is_like_msvc
997+
&& flavor == LinkerFlavor::Msvc(Lld::No)
998+
// Respect the command line override
999+
&& sess.opts.cg.linker.is_none()
1000+
// Match exactly "link.exe"
1001+
&& linker_path.to_str() == Some("link.exe")
1002+
// All Microsoft `link.exe` linking error codes are
1003+
// four digit numbers in the range 1000 to 9999 inclusive
1004+
&& (code < 1000 || code > 9999)
1005+
} else {
1006+
false
1007+
};
1008+
9841009
if !prog.status.success() {
9851010
let mut output = prog.stderr.clone();
9861011
output.extend_from_slice(&prog.stdout);
@@ -996,40 +1021,70 @@ fn link_natively(
9961021
// If MSVC's `link.exe` was expected but the return code
9971022
// is not a Microsoft LNK error then suggest a way to fix or
9981023
// install the Visual Studio build tools.
999-
if let Some(code) = prog.status.code() {
1000-
if sess.target.is_like_msvc
1001-
&& flavor == LinkerFlavor::Msvc(Lld::No)
1002-
// Respect the command line override
1003-
&& sess.opts.cg.linker.is_none()
1004-
// Match exactly "link.exe"
1005-
&& linker_path.to_str() == Some("link.exe")
1006-
// All Microsoft `link.exe` linking error codes are
1007-
// four digit numbers in the range 1000 to 9999 inclusive
1008-
&& (code < 1000 || code > 9999)
1009-
{
1010-
let is_vs_installed = windows_registry::find_vs_version().is_ok();
1011-
let has_linker =
1012-
windows_registry::find_tool(&sess.target.arch, "link.exe").is_some();
1013-
1014-
sess.dcx().emit_note(errors::LinkExeUnexpectedError);
1015-
if is_vs_installed && has_linker {
1016-
// the linker is broken
1017-
sess.dcx().emit_note(errors::RepairVSBuildTools);
1018-
sess.dcx().emit_note(errors::MissingCppBuildToolComponent);
1019-
} else if is_vs_installed {
1020-
// the linker is not installed
1021-
sess.dcx().emit_note(errors::SelectCppBuildToolWorkload);
1022-
} else {
1023-
// visual studio is not installed
1024-
sess.dcx().emit_note(errors::VisualStudioNotInstalled);
1025-
}
1024+
if is_msvc_link_exe {
1025+
let is_vs_installed = windows_registry::find_vs_version().is_ok();
1026+
let has_linker =
1027+
windows_registry::find_tool(&sess.target.arch, "link.exe").is_some();
1028+
1029+
sess.dcx().emit_note(errors::LinkExeUnexpectedError);
1030+
if is_vs_installed && has_linker {
1031+
// the linker is broken
1032+
sess.dcx().emit_note(errors::RepairVSBuildTools);
1033+
sess.dcx().emit_note(errors::MissingCppBuildToolComponent);
1034+
} else if is_vs_installed {
1035+
// the linker is not installed
1036+
sess.dcx().emit_note(errors::SelectCppBuildToolWorkload);
1037+
} else {
1038+
// visual studio is not installed
1039+
sess.dcx().emit_note(errors::VisualStudioNotInstalled);
10261040
}
10271041
}
10281042

10291043
sess.dcx().abort_if_errors();
10301044
}
1031-
info!("linker stderr:\n{}", escape_string(&prog.stderr));
1032-
info!("linker stdout:\n{}", escape_string(&prog.stdout));
1045+
1046+
let stderr = escape_string(&prog.stderr);
1047+
let mut stdout = escape_string(&prog.stdout);
1048+
info!("linker stderr:\n{}", &stderr);
1049+
info!("linker stdout:\n{}", &stdout);
1050+
1051+
// Hide some progress messages from link.exe that we don't care about.
1052+
// See https://github.com/chromium/chromium/blob/bfa41e41145ffc85f041384280caf2949bb7bd72/build/toolchain/win/tool_wrapper.py#L144-L146
1053+
if is_msvc_link_exe {
1054+
if let Ok(str) = str::from_utf8(&prog.stdout) {
1055+
let mut output = String::with_capacity(str.len());
1056+
for line in stdout.lines() {
1057+
if line.starts_with(" Creating library")
1058+
|| line.starts_with("Generating code")
1059+
|| line.starts_with("Finished generating code")
1060+
{
1061+
continue;
1062+
}
1063+
output += line;
1064+
output += "\r\n"
1065+
}
1066+
stdout = escape_string(output.trim().as_bytes())
1067+
}
1068+
}
1069+
1070+
let (level, src) = codegen_results.crate_info.lint_levels.linker_messages;
1071+
let lint = |msg| {
1072+
lint_level(sess, LINKER_MESSAGES, level, src, None, |diag| {
1073+
LinkerOutput { inner: msg }.decorate_lint(diag)
1074+
})
1075+
};
1076+
1077+
if !prog.stderr.is_empty() {
1078+
// We already print `warning:` at the start of the diagnostic. Remove it from the linker output if present.
1079+
let stderr = stderr
1080+
.strip_prefix("warning: ")
1081+
.unwrap_or(&stderr)
1082+
.replace(": warning: ", ": ");
1083+
lint(format!("linker stderr: {stderr}"));
1084+
}
1085+
if !stdout.is_empty() {
1086+
lint(format!("linker stdout: {}", stdout))
1087+
}
10331088
}
10341089
Err(e) => {
10351090
let linker_not_found = e.kind() == io::ErrorKind::NotFound;

compiler/rustc_codegen_ssa/src/base.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,8 @@ use crate::mir::operand::OperandValue;
4444
use crate::mir::place::PlaceRef;
4545
use crate::traits::*;
4646
use crate::{
47-
CachedModuleCodegen, CompiledModule, CrateInfo, ModuleCodegen, ModuleKind, errors, meth, mir,
47+
CachedModuleCodegen, CodegenLintLevels, CompiledModule, CrateInfo, ModuleCodegen, ModuleKind,
48+
errors, meth, mir,
4849
};
4950

5051
pub(crate) fn bin_op_to_icmp_predicate(op: BinOp, signed: bool) -> IntPredicate {
@@ -927,6 +928,7 @@ impl CrateInfo {
927928
dependency_formats: Lrc::clone(tcx.dependency_formats(())),
928929
windows_subsystem,
929930
natvis_debugger_visualizers: Default::default(),
931+
lint_levels: CodegenLintLevels::from_tcx(tcx),
930932
};
931933

932934
info.native_libraries.reserve(n_crates);

compiler/rustc_codegen_ssa/src/lib.rs

+22
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;
4651

@@ -200,6 +205,7 @@ pub struct CrateInfo {
200205
pub dependency_formats: Lrc<Dependencies>,
201206
pub windows_subsystem: Option<String>,
202207
pub natvis_debugger_visualizers: BTreeSet<DebuggerVisualizerFile>,
208+
pub lint_levels: CodegenLintLevels,
203209
}
204210

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

compiler/rustc_errors/src/json.rs

+30-17
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ use rustc_error_messages::FluentArgs;
2121
use rustc_lint_defs::Applicability;
2222
use rustc_span::Span;
2323
use rustc_span::hygiene::ExpnData;
24-
use rustc_span::source_map::SourceMap;
24+
use rustc_span::source_map::{FilePathMapping, SourceMap};
2525
use serde::Serialize;
2626
use termcolor::{ColorSpec, WriteColor};
2727

@@ -45,7 +45,7 @@ pub struct JsonEmitter {
4545
#[setters(skip)]
4646
dst: IntoDynSyncSend<Box<dyn Write + Send>>,
4747
#[setters(skip)]
48-
sm: Lrc<SourceMap>,
48+
sm: Option<Lrc<SourceMap>>,
4949
fluent_bundle: Option<Lrc<FluentBundle>>,
5050
#[setters(skip)]
5151
fallback_bundle: LazyFallbackBundle,
@@ -65,7 +65,7 @@ pub struct JsonEmitter {
6565
impl JsonEmitter {
6666
pub fn new(
6767
dst: Box<dyn Write + Send>,
68-
sm: Lrc<SourceMap>,
68+
sm: Option<Lrc<SourceMap>>,
6969
fallback_bundle: LazyFallbackBundle,
7070
pretty: bool,
7171
json_rendered: HumanReadableErrorType,
@@ -171,7 +171,7 @@ impl Emitter for JsonEmitter {
171171
}
172172

173173
fn source_map(&self) -> Option<&SourceMap> {
174-
Some(&self.sm)
174+
self.sm.as_deref()
175175
}
176176

177177
fn should_show_explain(&self) -> bool {
@@ -371,7 +371,7 @@ impl Diagnostic {
371371
}
372372
HumanEmitter::new(dst, Lrc::clone(&je.fallback_bundle))
373373
.short_message(short)
374-
.sm(Some(Lrc::clone(&je.sm)))
374+
.sm(je.sm.clone())
375375
.fluent_bundle(je.fluent_bundle.clone())
376376
.diagnostic_width(je.diagnostic_width)
377377
.macro_backtrace(je.macro_backtrace)
@@ -458,22 +458,33 @@ impl DiagnosticSpan {
458458
mut backtrace: impl Iterator<Item = ExpnData>,
459459
je: &JsonEmitter,
460460
) -> DiagnosticSpan {
461-
let start = je.sm.lookup_char_pos(span.lo());
461+
let empty_source_map;
462+
let sm = match &je.sm {
463+
Some(s) => s,
464+
None => {
465+
span = rustc_span::DUMMY_SP;
466+
empty_source_map = Arc::new(SourceMap::new(FilePathMapping::empty()));
467+
empty_source_map
468+
.new_source_file(std::path::PathBuf::from("empty.rs").into(), String::new());
469+
&empty_source_map
470+
}
471+
};
472+
let start = sm.lookup_char_pos(span.lo());
462473
// If this goes from the start of a line to the end and the replacement
463474
// is an empty string, increase the length to include the newline so we don't
464475
// leave an empty line
465476
if start.col.0 == 0
466477
&& suggestion.map_or(false, |(s, _)| s.is_empty())
467-
&& let Ok(after) = je.sm.span_to_next_source(span)
478+
&& let Ok(after) = sm.span_to_next_source(span)
468479
&& after.starts_with('\n')
469480
{
470481
span = span.with_hi(span.hi() + rustc_span::BytePos(1));
471482
}
472-
let end = je.sm.lookup_char_pos(span.hi());
483+
let end = sm.lookup_char_pos(span.hi());
473484
let backtrace_step = backtrace.next().map(|bt| {
474485
let call_site = Self::from_span_full(bt.call_site, false, None, None, backtrace, je);
475486
let def_site_span = Self::from_span_full(
476-
je.sm.guess_head_span(bt.def_site),
487+
sm.guess_head_span(bt.def_site),
477488
false,
478489
None,
479490
None,
@@ -488,7 +499,7 @@ impl DiagnosticSpan {
488499
});
489500

490501
DiagnosticSpan {
491-
file_name: je.sm.filename_for_diagnostics(&start.file.name).to_string(),
502+
file_name: sm.filename_for_diagnostics(&start.file.name).to_string(),
492503
byte_start: start.file.original_relative_byte_pos(span.lo()).0,
493504
byte_end: start.file.original_relative_byte_pos(span.hi()).0,
494505
line_start: start.line,
@@ -558,19 +569,20 @@ impl DiagnosticSpanLine {
558569
/// `span` within the line.
559570
fn from_span(span: Span, je: &JsonEmitter) -> Vec<DiagnosticSpanLine> {
560571
je.sm
561-
.span_to_lines(span)
562-
.map(|lines| {
572+
.as_ref()
573+
.and_then(|sm| {
574+
let lines = sm.span_to_lines(span).ok()?;
563575
// We can't get any lines if the source is unavailable.
564576
if !should_show_source_code(
565577
&je.ignored_directories_in_source_blocks,
566-
&je.sm,
578+
&sm,
567579
&lines.file,
568580
) {
569-
return vec![];
581+
return None;
570582
}
571583

572584
let sf = &*lines.file;
573-
lines
585+
let span_lines = lines
574586
.lines
575587
.iter()
576588
.map(|line| {
@@ -581,8 +593,9 @@ impl DiagnosticSpanLine {
581593
line.end_col.0 + 1,
582594
)
583595
})
584-
.collect()
596+
.collect();
597+
Some(span_lines)
585598
})
586-
.unwrap_or_else(|_| vec![])
599+
.unwrap_or_default()
587600
}
588601
}

compiler/rustc_errors/src/json/tests.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ fn test_positions(code: &str, span: (u32, u32), expected_output: SpanTestData) {
4747
let output = Arc::new(Mutex::new(Vec::new()));
4848
let je = JsonEmitter::new(
4949
Box::new(Shared { data: output.clone() }),
50-
sm,
50+
Some(sm),
5151
fallback_bundle,
5252
true, // pretty
5353
HumanReadableErrorType::Short,

0 commit comments

Comments
 (0)