Skip to content

Commit e1ff91f

Browse files
committed
Auto merge of rust-lang#83813 - cbeuw:remap-std, r=michaelwoerister
Fix `--remap-path-prefix` not correctly remapping `rust-src` component paths and unify handling of path mapping with virtualized paths This PR fixes rust-lang#73167 ("Binaries end up containing path to the rust-src component despite `--remap-path-prefix`") by preventing real local filesystem paths from reaching compilation output if the path is supposed to be remapped. `RealFileName::Named` introduced in rust-lang#72767 is now renamed as `LocalPath`, because this variant wraps a (most likely) valid local filesystem path. `RealFileName::Devirtualized` is renamed as `Remapped` to be used for remapped path from a real path via `--remap-path-prefix` argument, as well as real path inferred from a virtualized (during compiler bootstrapping) `/rustc/...` path. The `local_path` field is now an `Option<PathBuf>`, as it will be set to `None` before serialisation, so it never reaches any build output. Attempting to serialise a non-`None` `local_path` will cause an assertion faliure. When a path is remapped, a `RealFileName::Remapped` variant is created. The original path is preserved in `local_path` field and the remapped path is saved in `virtual_name` field. Previously, the `local_path` is directly modified which goes against its purpose of "suitable for reading from the file system on the local host". `rustc_span::SourceFile`'s fields `unmapped_path` (introduced by rust-lang#44940) and `name_was_remapped` (introduced by rust-lang#41508 when `--remap-path-prefix` feature originally added) are removed, as these two pieces of information can be inferred from the `name` field: if it's anything other than a `FileName::Real(_)`, or if it is a `FileName::Real(RealFileName::LocalPath(_))`, then clearly `name_was_remapped` would've been false and `unmapped_path` would've been `None`. If it is a `FileName::Real(RealFileName::Remapped{local_path, virtual_name})`, then `name_was_remapped` would've been true and `unmapped_path` would've been `Some(local_path)`. cc `@eddyb` who implemented `/rustc/...` path devirtualisation
2 parents ac923d9 + 37dbe86 commit e1ff91f

File tree

48 files changed

+442
-265
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

48 files changed

+442
-265
lines changed

compiler/rustc_builtin_macros/src/source_util.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,9 @@ pub fn expand_file(
6161

6262
let topmost = cx.expansion_cause().unwrap_or(sp);
6363
let loc = cx.source_map().lookup_char_pos(topmost.lo());
64-
base::MacEager::expr(cx.expr_str(topmost, Symbol::intern(&loc.file.name.to_string())))
64+
base::MacEager::expr(
65+
cx.expr_str(topmost, Symbol::intern(&loc.file.name.prefer_remapped().to_string_lossy())),
66+
)
6567
}
6668

6769
pub fn expand_stringify(

compiler/rustc_codegen_cranelift/src/common.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -334,7 +334,9 @@ impl<'tcx> FunctionCx<'_, '_, 'tcx> {
334334
let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
335335
let caller = self.tcx.sess.source_map().lookup_char_pos(topmost.lo());
336336
let const_loc = self.tcx.const_caller_location((
337-
rustc_span::symbol::Symbol::intern(&caller.file.name.to_string()),
337+
rustc_span::symbol::Symbol::intern(
338+
&caller.file.name.prefer_remapped().to_string_lossy(),
339+
),
338340
caller.line as u32,
339341
caller.col_display as u32 + 1,
340342
));

compiler/rustc_codegen_cranelift/src/debuginfo/line_info.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ fn line_program_add_file(
6666
) -> FileId {
6767
match &file.name {
6868
FileName::Real(path) => {
69-
let (dir_path, file_name) = split_path_dir_and_file(path.stable_name());
69+
let (dir_path, file_name) = split_path_dir_and_file(path.remapped_path_if_available());
7070
let dir_name = osstr_as_utf8_bytes(dir_path.as_os_str());
7171
let file_name = osstr_as_utf8_bytes(file_name);
7272

@@ -87,7 +87,7 @@ fn line_program_add_file(
8787
filename => {
8888
let dir_id = line_program.default_directory();
8989
let dummy_file_name = LineString::new(
90-
filename.to_string().into_bytes(),
90+
filename.prefer_remapped().to_string().into_bytes(),
9191
line_program.encoding(),
9292
line_strings,
9393
);

compiler/rustc_codegen_cranelift/src/debuginfo/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ impl<'tcx> DebugContext<'tcx> {
6464
// FIXME: how to get version when building out of tree?
6565
// Normally this would use option_env!("CFG_VERSION").
6666
let producer = format!("cg_clif (rustc {})", "unknown version");
67-
let comp_dir = tcx.sess.working_dir.0.to_string_lossy().into_owned();
67+
let comp_dir = tcx.sess.working_dir.to_string_lossy(false).into_owned();
6868
let (name, file_info) = match tcx.sess.local_crate_source_file.clone() {
6969
Some(path) => {
7070
let name = path.to_string_lossy().into_owned();

compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -760,12 +760,12 @@ fn hex_encode(data: &[u8]) -> String {
760760
}
761761

762762
pub fn file_metadata(cx: &CodegenCx<'ll, '_>, source_file: &SourceFile) -> &'ll DIFile {
763-
debug!("file_metadata: file_name: {}", source_file.name);
763+
debug!("file_metadata: file_name: {:?}", source_file.name);
764764

765765
let hash = Some(&source_file.src_hash);
766-
let file_name = Some(source_file.name.to_string());
766+
let file_name = Some(source_file.name.prefer_remapped().to_string());
767767
let directory = if source_file.is_real_file() && !source_file.is_imported() {
768-
Some(cx.sess().working_dir.0.to_string_lossy().to_string())
768+
Some(cx.sess().working_dir.to_string_lossy(false).to_string())
769769
} else {
770770
// If the path comes from an upstream crate we assume it has been made
771771
// independent of the compiler's working directory one way or another.
@@ -993,7 +993,7 @@ pub fn compile_unit_metadata(
993993
let producer = format!("clang LLVM ({})", rustc_producer);
994994

995995
let name_in_debuginfo = name_in_debuginfo.to_string_lossy();
996-
let work_dir = tcx.sess.working_dir.0.to_string_lossy();
996+
let work_dir = tcx.sess.working_dir.to_string_lossy(false);
997997
let flags = "\0";
998998
let out_dir = &tcx.output_filenames(LOCAL_CRATE).out_directory;
999999
let split_name = if tcx.sess.target_can_use_split_dwarf() {

compiler/rustc_codegen_ssa/src/mir/block.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1144,7 +1144,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
11441144
let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
11451145
let caller = tcx.sess.source_map().lookup_char_pos(topmost.lo());
11461146
let const_loc = tcx.const_caller_location((
1147-
Symbol::intern(&caller.file.name.to_string()),
1147+
Symbol::intern(&caller.file.name.prefer_remapped().to_string_lossy()),
11481148
caller.line as u32,
11491149
caller.col_display as u32 + 1,
11501150
));

compiler/rustc_errors/src/annotate_snippet_emitter_writer.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,8 @@ impl AnnotateSnippetEmitterWriter {
126126
}
127127
// owned: line source, line index, annotations
128128
type Owned = (String, usize, Vec<crate::snippet::Annotation>);
129-
let origin = primary_lo.file.name.to_string();
129+
let filename = primary_lo.file.name.prefer_local();
130+
let origin = filename.to_string_lossy();
130131
let annotated_files: Vec<Owned> = annotated_files
131132
.into_iter()
132133
.flat_map(|annotated_file| {

compiler/rustc_errors/src/emitter.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -1324,7 +1324,7 @@ impl EmitterWriter {
13241324
buffer_msg_line_offset,
13251325
&format!(
13261326
"{}:{}:{}",
1327-
loc.file.name,
1327+
loc.file.name.prefer_local(),
13281328
sm.doctest_offset_line(&loc.file.name, loc.line),
13291329
loc.col.0 + 1,
13301330
),
@@ -1338,7 +1338,7 @@ impl EmitterWriter {
13381338
0,
13391339
&format!(
13401340
"{}:{}:{}: ",
1341-
loc.file.name,
1341+
loc.file.name.prefer_local(),
13421342
sm.doctest_offset_line(&loc.file.name, loc.line),
13431343
loc.col.0 + 1,
13441344
),
@@ -1362,12 +1362,12 @@ impl EmitterWriter {
13621362
};
13631363
format!(
13641364
"{}:{}{}",
1365-
annotated_file.file.name,
1365+
annotated_file.file.name.prefer_local(),
13661366
sm.doctest_offset_line(&annotated_file.file.name, first_line.line_index),
13671367
col
13681368
)
13691369
} else {
1370-
annotated_file.file.name.to_string()
1370+
format!("{}", annotated_file.file.name.prefer_local())
13711371
};
13721372
buffer.append(buffer_msg_line_offset + 1, &loc, Style::LineAndColumn);
13731373
for _ in 0..max_line_num_len {

compiler/rustc_errors/src/json.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -468,7 +468,7 @@ impl DiagnosticSpan {
468468
});
469469

470470
DiagnosticSpan {
471-
file_name: start.file.name.to_string(),
471+
file_name: start.file.name.prefer_local().to_string(),
472472
byte_start: start.file.original_relative_byte_pos(span.lo()).0,
473473
byte_end: start.file.original_relative_byte_pos(span.hi()).0,
474474
line_start: start.line,

compiler/rustc_expand/src/base.rs

+8-3
Original file line numberDiff line numberDiff line change
@@ -1084,13 +1084,18 @@ impl<'a> ExtCtxt<'a> {
10841084
// after macro expansion (that is, they are unhygienic).
10851085
if !path.is_absolute() {
10861086
let callsite = span.source_callsite();
1087-
let mut result = match self.source_map().span_to_unmapped_path(callsite) {
1088-
FileName::Real(name) => name.into_local_path(),
1087+
let mut result = match self.source_map().span_to_filename(callsite) {
1088+
FileName::Real(name) => name
1089+
.into_local_path()
1090+
.expect("attempting to resolve a file path in an external file"),
10891091
FileName::DocTest(path, _) => path,
10901092
other => {
10911093
return Err(self.struct_span_err(
10921094
span,
1093-
&format!("cannot resolve relative path in non-file source `{}`", other),
1095+
&format!(
1096+
"cannot resolve relative path in non-file source `{}`",
1097+
other.prefer_local()
1098+
),
10941099
));
10951100
}
10961101
};

compiler/rustc_expand/src/expand.rs

+5-3
Original file line numberDiff line numberDiff line change
@@ -361,9 +361,11 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
361361
// FIXME: Avoid visiting the crate as a `Mod` item,
362362
// make crate a first class expansion target instead.
363363
pub fn expand_crate(&mut self, mut krate: ast::Crate) -> ast::Crate {
364-
let file_path = match self.cx.source_map().span_to_unmapped_path(krate.span) {
365-
FileName::Real(name) => name.into_local_path(),
366-
other => PathBuf::from(other.to_string()),
364+
let file_path = match self.cx.source_map().span_to_filename(krate.span) {
365+
FileName::Real(name) => name
366+
.into_local_path()
367+
.expect("attempting to resolve a file path in an external file"),
368+
other => PathBuf::from(other.prefer_local().to_string()),
367369
};
368370
let dir_path = file_path.parent().unwrap_or(&file_path).to_owned();
369371
self.cx.root_path = dir_path.clone();

compiler/rustc_expand/src/proc_macro_server.rs

+4-3
Original file line numberDiff line numberDiff line change
@@ -638,10 +638,11 @@ impl server::SourceFile for Rustc<'_> {
638638
match file.name {
639639
FileName::Real(ref name) => name
640640
.local_path()
641+
.expect("attempting to get a file path in an imported file in `proc_macro::SourceFile::path`")
641642
.to_str()
642643
.expect("non-UTF8 file path in `proc_macro::SourceFile::path`")
643644
.to_string(),
644-
_ => file.name.to_string(),
645+
_ => file.name.prefer_local().to_string(),
645646
}
646647
}
647648
fn is_real(&mut self, file: &Self::SourceFile) -> bool {
@@ -785,7 +786,7 @@ fn ident_name_compatibility_hack(
785786
if let ExpnKind::Macro { name: macro_name, .. } = orig_span.ctxt().outer_expn_data().kind {
786787
let source_map = rustc.sess.source_map();
787788
let filename = source_map.span_to_filename(orig_span);
788-
if let FileName::Real(RealFileName::Named(path)) = filename {
789+
if let FileName::Real(RealFileName::LocalPath(path)) = filename {
789790
let matches_prefix = |prefix, filename| {
790791
// Check for a path that ends with 'prefix*/src/<filename>'
791792
let mut iter = path.components().rev();
@@ -848,7 +849,7 @@ fn ident_name_compatibility_hack(
848849
if macro_name == sym::tuple_from_req && matches_prefix("actix-web", "extract.rs") {
849850
let snippet = source_map.span_to_snippet(orig_span);
850851
if snippet.as_deref() == Ok("$T") {
851-
if let FileName::Real(RealFileName::Named(macro_path)) =
852+
if let FileName::Real(RealFileName::LocalPath(macro_path)) =
852853
source_map.span_to_filename(rustc.def_site)
853854
{
854855
if macro_path.to_string_lossy().contains("pin-project-internal-0.") {

compiler/rustc_infer/src/infer/error_reporting/mod.rs

+11-5
Original file line numberDiff line numberDiff line change
@@ -1604,13 +1604,19 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
16041604
match (&terr, expected == found) {
16051605
(TypeError::Sorts(values), extra) => {
16061606
let sort_string = |ty: Ty<'tcx>| match (extra, ty.kind()) {
1607-
(true, ty::Opaque(def_id, _)) => format!(
1608-
" (opaque type at {})",
1609-
self.tcx
1607+
(true, ty::Opaque(def_id, _)) => {
1608+
let pos = self
1609+
.tcx
16101610
.sess
16111611
.source_map()
1612-
.mk_substr_filename(self.tcx.def_span(*def_id)),
1613-
),
1612+
.lookup_char_pos(self.tcx.def_span(*def_id).lo());
1613+
format!(
1614+
" (opaque type at <{}:{}:{}>)",
1615+
pos.file.name.prefer_local(),
1616+
pos.line,
1617+
pos.col.to_usize() + 1,
1618+
)
1619+
}
16141620
(true, _) => format!(" ({})", ty.sort_string(self.tcx)),
16151621
(false, _) => "".to_string(),
16161622
};

compiler/rustc_interface/src/passes.rs

+6-10
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,6 @@ use rustc_session::output::{filename_for_input, filename_for_metadata};
3535
use rustc_session::search_paths::PathKind;
3636
use rustc_session::Session;
3737
use rustc_span::symbol::{Ident, Symbol};
38-
use rustc_span::{FileName, RealFileName};
3938
use rustc_trait_selection::traits;
4039
use rustc_typeck as typeck;
4140
use tracing::{info, warn};
@@ -531,10 +530,10 @@ fn output_conflicts_with_dir(output_paths: &[PathBuf]) -> Option<PathBuf> {
531530
check_output(output_paths, check)
532531
}
533532

534-
fn escape_dep_filename(filename: &FileName) -> String {
533+
fn escape_dep_filename(filename: &String) -> String {
535534
// Apparently clang and gcc *only* escape spaces:
536535
// http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
537-
filename.to_string().replace(" ", "\\ ")
536+
filename.replace(" ", "\\ ")
538537
}
539538

540539
// Makefile comments only need escaping newlines and `\`.
@@ -574,7 +573,7 @@ fn write_out_deps(
574573
.iter()
575574
.filter(|fmap| fmap.is_real_file())
576575
.filter(|fmap| !fmap.is_imported())
577-
.map(|fmap| escape_dep_filename(&fmap.unmapped_path.as_ref().unwrap_or(&fmap.name)))
576+
.map(|fmap| escape_dep_filename(&fmap.name.prefer_local().to_string()))
578577
.collect();
579578

580579
if let Some(ref backend) = sess.opts.debugging_opts.codegen_backend {
@@ -586,16 +585,13 @@ fn write_out_deps(
586585
for cnum in resolver.cstore().crates_untracked() {
587586
let source = resolver.cstore().crate_source_untracked(cnum);
588587
if let Some((path, _)) = source.dylib {
589-
let file_name = FileName::Real(RealFileName::Named(path));
590-
files.push(escape_dep_filename(&file_name));
588+
files.push(escape_dep_filename(&path.display().to_string()));
591589
}
592590
if let Some((path, _)) = source.rlib {
593-
let file_name = FileName::Real(RealFileName::Named(path));
594-
files.push(escape_dep_filename(&file_name));
591+
files.push(escape_dep_filename(&path.display().to_string()));
595592
}
596593
if let Some((path, _)) = source.rmeta {
597-
let file_name = FileName::Real(RealFileName::Named(path));
598-
files.push(escape_dep_filename(&file_name));
594+
files.push(escape_dep_filename(&path.display().to_string()));
599595
}
600596
}
601597
});

compiler/rustc_interface/src/tests.rs

+1
Original file line numberDiff line numberDiff line change
@@ -724,6 +724,7 @@ fn test_debugging_options_tracking_hash() {
724724
tracked!(profile_emit, Some(PathBuf::from("abc")));
725725
tracked!(relax_elf_relocations, Some(true));
726726
tracked!(relro_level, Some(RelroLevel::Full));
727+
tracked!(simulate_remapped_rust_src_base, Some(PathBuf::from("/rustc/abc")));
727728
tracked!(report_delayed_bugs, true);
728729
tracked!(sanitizer, SanitizerSet::ADDRESS);
729730
tracked!(sanitizer_memory_track_origins, 2);

compiler/rustc_metadata/src/rmeta/decoder.rs

+32-9
Original file line numberDiff line numberDiff line change
@@ -1651,9 +1651,11 @@ impl<'a, 'tcx> CrateMetadataRef<'a> {
16511651
if let Some(virtual_dir) = virtual_rust_source_base_dir {
16521652
if let Some(real_dir) = &sess.opts.real_rust_source_base_dir {
16531653
if let rustc_span::FileName::Real(old_name) = name {
1654-
if let rustc_span::RealFileName::Named(one_path) = old_name {
1655-
if let Ok(rest) = one_path.strip_prefix(virtual_dir) {
1656-
let virtual_name = one_path.clone();
1654+
if let rustc_span::RealFileName::Remapped { local_path: _, virtual_name } =
1655+
old_name
1656+
{
1657+
if let Ok(rest) = virtual_name.strip_prefix(virtual_dir) {
1658+
let virtual_name = virtual_name.clone();
16571659

16581660
// The std library crates are in
16591661
// `$sysroot/lib/rustlib/src/rust/library`, whereas other crates
@@ -1689,8 +1691,8 @@ impl<'a, 'tcx> CrateMetadataRef<'a> {
16891691
virtual_name.display(),
16901692
new_path.display(),
16911693
);
1692-
let new_name = rustc_span::RealFileName::Devirtualized {
1693-
local_path: new_path,
1694+
let new_name = rustc_span::RealFileName::Remapped {
1695+
local_path: Some(new_path),
16941696
virtual_name,
16951697
};
16961698
*old_name = new_name;
@@ -1710,7 +1712,6 @@ impl<'a, 'tcx> CrateMetadataRef<'a> {
17101712
// containing the information we need.
17111713
let rustc_span::SourceFile {
17121714
mut name,
1713-
name_was_remapped,
17141715
src_hash,
17151716
start_pos,
17161717
end_pos,
@@ -1722,11 +1723,34 @@ impl<'a, 'tcx> CrateMetadataRef<'a> {
17221723
..
17231724
} = source_file_to_import;
17241725

1726+
// If this file is under $sysroot/lib/rustlib/src/ but has not been remapped
1727+
// during rust bootstrapping by `remap-debuginfo = true`, and the user
1728+
// wish to simulate that behaviour by -Z simulate-remapped-rust-src-base,
1729+
// then we change `name` to a similar state as if the rust was bootstrapped
1730+
// with `remap-debuginfo = true`.
1731+
// This is useful for testing so that tests about the effects of
1732+
// `try_to_translate_virtual_to_real` don't have to worry about how the
1733+
// compiler is bootstrapped.
1734+
if let Some(virtual_dir) =
1735+
&sess.opts.debugging_opts.simulate_remapped_rust_src_base
1736+
{
1737+
if let Some(real_dir) = &sess.opts.real_rust_source_base_dir {
1738+
if let rustc_span::FileName::Real(ref mut old_name) = name {
1739+
if let rustc_span::RealFileName::LocalPath(local) = old_name {
1740+
if let Ok(rest) = local.strip_prefix(real_dir) {
1741+
*old_name = rustc_span::RealFileName::Remapped {
1742+
local_path: None,
1743+
virtual_name: virtual_dir.join(rest),
1744+
};
1745+
}
1746+
}
1747+
}
1748+
}
1749+
}
1750+
17251751
// If this file's path has been remapped to `/rustc/$hash`,
17261752
// we might be able to reverse that (also see comments above,
17271753
// on `try_to_translate_virtual_to_real`).
1728-
// FIXME(eddyb) we could check `name_was_remapped` here,
1729-
// but in practice it seems to be always `false`.
17301754
try_to_translate_virtual_to_real(&mut name);
17311755

17321756
let source_length = (end_pos - start_pos).to_usize();
@@ -1751,7 +1775,6 @@ impl<'a, 'tcx> CrateMetadataRef<'a> {
17511775

17521776
let local_version = sess.source_map().new_imported_source_file(
17531777
name,
1754-
name_was_remapped,
17551778
src_hash,
17561779
name_hash,
17571780
source_length,

0 commit comments

Comments
 (0)