Skip to content

Commit 8fb194c

Browse files
authored
Rollup merge of #89920 - hudson-ayers:location-detail-control, r=davidtwco
Implement -Z location-detail flag This PR implements the `-Z location-detail` flag as described in rust-lang/rfcs#2091 . `-Z location-detail=val` controls what location details are tracked when using `caller_location`. This allows users to control what location details are printed as part of panic messages, by allowing them to exclude any combination of filenames, line numbers, and column numbers. This option is intended to provide users with a way to mitigate the size impact of `#[track_caller]`. Some measurements of the savings of this approach on an embedded binary can be found here: #70579 (comment) . Closes #70580 (unless people want to leave that open as a place for discussion of further improvements). This is my first real PR to rust, so any help correcting mistakes / understanding side effects / improving my tests is appreciated :) I have one question: RFC 2091 specified this as a debugging option (I think that is what -Z implies?). Does that mean this can never be stabilized without a separate MCP? If so, do I need to submit an MCP now, or is the initial RFC specifying this option sufficient for this to be merged as is, and then an MCP would be needed for eventual stabilization?
2 parents 736e8eb + b802629 commit 8fb194c

13 files changed

+135
-6
lines changed

compiler/rustc_const_eval/src/interpret/intrinsics/caller_location.rs

+11-4
Original file line numberDiff line numberDiff line change
@@ -80,10 +80,17 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
8080
line: u32,
8181
col: u32,
8282
) -> MPlaceTy<'tcx, M::PointerTag> {
83-
let file =
84-
self.allocate_str(&filename.as_str(), MemoryKind::CallerLocation, Mutability::Not);
85-
let line = Scalar::from_u32(line);
86-
let col = Scalar::from_u32(col);
83+
let loc_details = &self.tcx.sess.opts.debugging_opts.location_detail;
84+
let file = if loc_details.file {
85+
self.allocate_str(&filename.as_str(), MemoryKind::CallerLocation, Mutability::Not)
86+
} else {
87+
// FIXME: This creates a new allocation each time. It might be preferable to
88+
// perform this allocation only once, and re-use the `MPlaceTy`.
89+
// See https://github.com/rust-lang/rust/pull/89920#discussion_r730012398
90+
self.allocate_str("<redacted>", MemoryKind::CallerLocation, Mutability::Not)
91+
};
92+
let line = if loc_details.line { Scalar::from_u32(line) } else { Scalar::from_u32(0) };
93+
let col = if loc_details.column { Scalar::from_u32(col) } else { Scalar::from_u32(0) };
8794

8895
// Allocate memory for `CallerLocation` struct.
8996
let loc_ty = self

compiler/rustc_interface/src/tests.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@ use rustc_errors::{emitter::HumanReadableErrorType, registry, ColorConfig};
55
use rustc_session::config::InstrumentCoverage;
66
use rustc_session::config::Strip;
77
use rustc_session::config::{build_configuration, build_session_options, to_crate_config};
8-
use rustc_session::config::{rustc_optgroups, ErrorOutputType, ExternLocation, Options, Passes};
8+
use rustc_session::config::{
9+
rustc_optgroups, ErrorOutputType, ExternLocation, LocationDetail, Options, Passes,
10+
};
911
use rustc_session::config::{CFGuard, ExternEntry, LinkerPluginLto, LtoCli, SwitchWithOptPath};
1012
use rustc_session::config::{
1113
Externs, OutputType, OutputTypes, SymbolManglingVersion, WasiExecModel,
@@ -733,6 +735,7 @@ fn test_debugging_options_tracking_hash() {
733735
tracked!(instrument_mcount, true);
734736
tracked!(link_only, true);
735737
tracked!(llvm_plugins, vec![String::from("plugin_name")]);
738+
tracked!(location_detail, LocationDetail { file: true, line: false, column: false });
736739
tracked!(merge_functions, Some(MergeFunctions::Disabled));
737740
tracked!(mir_emit_retag, true);
738741
tracked!(mir_opt_level, Some(4));

compiler/rustc_session/src/config.rs

+16-1
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,20 @@ impl LinkerPluginLto {
174174
}
175175
}
176176

177+
/// The different settings that can be enabled via the `-Z location-detail` flag.
178+
#[derive(Clone, PartialEq, Hash, Debug)]
179+
pub struct LocationDetail {
180+
pub file: bool,
181+
pub line: bool,
182+
pub column: bool,
183+
}
184+
185+
impl LocationDetail {
186+
pub fn all() -> Self {
187+
Self { file: true, line: true, column: true }
188+
}
189+
}
190+
177191
#[derive(Clone, PartialEq, Hash, Debug)]
178192
pub enum SwitchWithOptPath {
179193
Enabled(Option<PathBuf>),
@@ -2422,7 +2436,7 @@ crate mod dep_tracking {
24222436
use super::LdImpl;
24232437
use super::{
24242438
CFGuard, CrateType, DebugInfo, ErrorOutputType, InstrumentCoverage, LinkerPluginLto,
2425-
LtoCli, OptLevel, OutputType, OutputTypes, Passes, SourceFileHashAlgorithm,
2439+
LocationDetail, LtoCli, OptLevel, OutputType, OutputTypes, Passes, SourceFileHashAlgorithm,
24262440
SwitchWithOptPath, SymbolManglingVersion, TrimmedDefPaths,
24272441
};
24282442
use crate::lint;
@@ -2513,6 +2527,7 @@ crate mod dep_tracking {
25132527
Option<LdImpl>,
25142528
OutputType,
25152529
RealFileName,
2530+
LocationDetail,
25162531
);
25172532

25182533
impl<T1, T2> DepTrackingHash for (T1, T2)

compiler/rustc_session/src/options.rs

+24
Original file line numberDiff line numberDiff line change
@@ -368,6 +368,8 @@ mod desc {
368368
"either a boolean (`yes`, `no`, `on`, `off`, etc), `thin`, `fat`, or omitted";
369369
pub const parse_linker_plugin_lto: &str =
370370
"either a boolean (`yes`, `no`, `on`, `off`, etc), or the path to the linker plugin";
371+
pub const parse_location_detail: &str =
372+
"comma seperated list of location details to track: `file`, `line`, or `column`";
371373
pub const parse_switch_with_opt_path: &str =
372374
"an optional path to the profiling data output directory";
373375
pub const parse_merge_functions: &str = "one of: `disabled`, `trampolines`, or `aliases`";
@@ -484,6 +486,25 @@ mod parse {
484486
}
485487
}
486488

489+
crate fn parse_location_detail(ld: &mut LocationDetail, v: Option<&str>) -> bool {
490+
if let Some(v) = v {
491+
ld.line = false;
492+
ld.file = false;
493+
ld.column = false;
494+
for s in v.split(',') {
495+
match s {
496+
"file" => ld.file = true,
497+
"line" => ld.line = true,
498+
"column" => ld.column = true,
499+
_ => return false,
500+
}
501+
}
502+
true
503+
} else {
504+
false
505+
}
506+
}
507+
487508
crate fn parse_opt_comma_list(slot: &mut Option<Vec<String>>, v: Option<&str>) -> bool {
488509
match v {
489510
Some(s) => {
@@ -1152,6 +1173,9 @@ options! {
11521173
"a list LLVM plugins to enable (space separated)"),
11531174
llvm_time_trace: bool = (false, parse_bool, [UNTRACKED],
11541175
"generate JSON tracing data file from LLVM data (default: no)"),
1176+
location_detail: LocationDetail = (LocationDetail::all(), parse_location_detail, [TRACKED],
1177+
"comma seperated list of location details to be tracked when using caller_location \
1178+
valid options are `file`, `line`, and `column` (default: all)"),
11551179
ls: bool = (false, parse_bool, [UNTRACKED],
11561180
"list the symbols defined by a library crate (default: no)"),
11571181
macro_backtrace: bool = (false, parse_bool, [UNTRACKED],
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# `location-detail`
2+
3+
The tracking issue for this feature is: [#70580](https://github.com/rust-lang/rust/issues/70580).
4+
5+
------------------------
6+
7+
Option `-Z location-detail=val` controls what location details are tracked when
8+
using `caller_location`. This allows users to control what location details
9+
are printed as part of panic messages, by allowing them to exclude any combination
10+
of filenames, line numbers, and column numbers. This option is intended to provide
11+
users with a way to mitigate the size impact of `#[track_caller]`.
12+
13+
This option supports a comma separated list of location details to be included. Valid options
14+
within this list are:
15+
16+
- `file` - the filename of the panic will be included in the panic output
17+
- `line` - the source line of the panic will be included in the panic output
18+
- `column` - the source column of the panic will be included in the panic output
19+
20+
Any combination of these three options are supported. If this option is not specified,
21+
all three are included by default.
22+
23+
An example of a panic output when using `-Z location-detail=line`:
24+
```text
25+
panicked at 'Process blink had a fault', <redacted>:323:0
26+
```
27+
28+
The code size savings from this option are two-fold. First, the `&'static str` values
29+
for each path to a file containing a panic are removed from the binary. For projects
30+
with deep directory structures and many files with panics, this can add up. This category
31+
of savings can only be realized by excluding filenames from the panic output. Second,
32+
savings can be realized by allowing multiple panics to be fused into a single panicking
33+
branch. It is often the case that within a single file, multiple panics with the same
34+
panic message exist -- e.g. two calls to `Option::unwrap()` in a single line, or
35+
two calls to `Result::expect()` on adjacent lines. If column and line information
36+
are included in the `Location` struct passed to the panic handler, these branches cannot
37+
be fused, as the output is different depending on which panic occurs. However if line
38+
and column information is identical for all panics, these branches can be fused, which
39+
can lead to substantial code size savings, especially for small embedded binaries with
40+
many panics.
41+
42+
The savings from this option are amplified when combined with the use of `-Zbuild-std`, as
43+
otherwise paths for panics within the standard library are still included in your binary.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
// run-fail
2+
// check-run-results
3+
// compile-flags: -Zlocation-detail=line,file
4+
5+
fn main() {
6+
panic!("column-redacted");
7+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
thread 'main' panicked at 'column-redacted', $DIR/location-detail-panic-no-column.rs:6:0
2+
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
// run-fail
2+
// check-run-results
3+
// compile-flags: -Zlocation-detail=line,column
4+
5+
fn main() {
6+
panic!("file-redacted");
7+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
thread 'main' panicked at 'file-redacted', <redacted>:6:5
2+
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
// run-fail
2+
// check-run-results
3+
// compile-flags: -Zlocation-detail=file,column
4+
5+
fn main() {
6+
panic!("line-redacted");
7+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
thread 'main' panicked at 'line-redacted', $DIR/location-detail-panic-no-line.rs:0:5
2+
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
// run-fail
2+
// check-run-results
3+
// compile-flags: -Zlocation-detail=line,column
4+
5+
fn main() {
6+
let opt: Option<u32> = None;
7+
opt.unwrap();
8+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
thread 'main' panicked at 'called `Option::unwrap()` on a `None` value', <redacted>:7:9
2+
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

0 commit comments

Comments
 (0)