Skip to content

Commit aeb4738

Browse files
committed
Auto merge of #71825 - contrun:cg-option-strip, r=petrochenkov
add codegen option strip closes #71757 I don't know if the flags added here works for all linkers. I only tested on my Linux pc. I also don't know what is the best for emlinker, PtxLinker, MsvcLinker. The option for WasmLd is copied from https://aransentin.github.io/cwasm/.
2 parents 9912925 + a6c2f73 commit aeb4738

File tree

5 files changed

+81
-38
lines changed

5 files changed

+81
-38
lines changed

src/librustc_codegen_ssa/back/link.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1500,8 +1500,8 @@ fn linker_with_args<'a, B: ArchiveBuilder<'a>>(
15001500
cmd.optimize();
15011501

15021502
// OBJECT-FILES-NO, AUDIT-ORDER
1503-
// Pass debuginfo flags down to the linker.
1504-
cmd.debuginfo();
1503+
// Pass debuginfo and strip flags down to the linker.
1504+
cmd.debuginfo(sess.opts.debugging_opts.strip);
15051505

15061506
// OBJECT-FILES-NO, AUDIT-ORDER
15071507
// We want to prevent the compiler from accidentally leaking in any system libraries,

src/librustc_codegen_ssa/back/linker.rs

+51-32
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
1414
use rustc_middle::middle::dependency_format::Linkage;
1515
use rustc_middle::ty::TyCtxt;
1616
use rustc_serialize::{json, Encoder};
17-
use rustc_session::config::{self, CrateType, DebugInfo, LinkerPluginLto, Lto, OptLevel};
17+
use rustc_session::config::{self, CrateType, DebugInfo, LinkerPluginLto, Lto, OptLevel, Strip};
1818
use rustc_session::Session;
1919
use rustc_span::symbol::Symbol;
2020
use rustc_target::spec::{LinkerFlavor, LldFlavor};
@@ -122,7 +122,7 @@ pub trait Linker {
122122
fn optimize(&mut self);
123123
fn pgo_gen(&mut self);
124124
fn control_flow_guard(&mut self);
125-
fn debuginfo(&mut self);
125+
fn debuginfo(&mut self, strip: Strip);
126126
fn no_default_libraries(&mut self);
127127
fn build_dylib(&mut self, out_filename: &Path);
128128
fn build_static_executable(&mut self);
@@ -392,15 +392,16 @@ impl<'a> Linker for GccLinker<'a> {
392392
self.sess.warn("Windows Control Flow Guard is not supported by this linker.");
393393
}
394394

395-
fn debuginfo(&mut self) {
396-
if let DebugInfo::None = self.sess.opts.debuginfo {
397-
// If we are building without debuginfo enabled and we were called with
398-
// `-Zstrip-debuginfo-if-disabled=yes`, tell the linker to strip any debuginfo
399-
// found when linking to get rid of symbols from libstd.
400-
if self.sess.opts.debugging_opts.strip_debuginfo_if_disabled {
401-
self.linker_arg("-S");
395+
fn debuginfo(&mut self, strip: Strip) {
396+
match strip {
397+
Strip::None => {}
398+
Strip::Debuginfo => {
399+
self.linker_arg("--strip-debug");
402400
}
403-
};
401+
Strip::Symbols => {
402+
self.linker_arg("--strip-all");
403+
}
404+
}
404405
}
405406

406407
fn no_default_libraries(&mut self) {
@@ -686,29 +687,37 @@ impl<'a> Linker for MsvcLinker<'a> {
686687
self.cmd.arg("/guard:cf");
687688
}
688689

689-
fn debuginfo(&mut self) {
690-
// This will cause the Microsoft linker to generate a PDB file
691-
// from the CodeView line tables in the object files.
692-
self.cmd.arg("/DEBUG");
693-
694-
// This will cause the Microsoft linker to embed .natvis info into the PDB file
695-
let natvis_dir_path = self.sess.sysroot.join("lib\\rustlib\\etc");
696-
if let Ok(natvis_dir) = fs::read_dir(&natvis_dir_path) {
697-
for entry in natvis_dir {
698-
match entry {
699-
Ok(entry) => {
700-
let path = entry.path();
701-
if path.extension() == Some("natvis".as_ref()) {
702-
let mut arg = OsString::from("/NATVIS:");
703-
arg.push(path);
704-
self.cmd.arg(arg);
690+
fn debuginfo(&mut self, strip: Strip) {
691+
match strip {
692+
Strip::None => {
693+
// This will cause the Microsoft linker to generate a PDB file
694+
// from the CodeView line tables in the object files.
695+
self.cmd.arg("/DEBUG");
696+
697+
// This will cause the Microsoft linker to embed .natvis info into the PDB file
698+
let natvis_dir_path = self.sess.sysroot.join("lib\\rustlib\\etc");
699+
if let Ok(natvis_dir) = fs::read_dir(&natvis_dir_path) {
700+
for entry in natvis_dir {
701+
match entry {
702+
Ok(entry) => {
703+
let path = entry.path();
704+
if path.extension() == Some("natvis".as_ref()) {
705+
let mut arg = OsString::from("/NATVIS:");
706+
arg.push(path);
707+
self.cmd.arg(arg);
708+
}
709+
}
710+
Err(err) => {
711+
self.sess
712+
.warn(&format!("error enumerating natvis directory: {}", err));
713+
}
705714
}
706715
}
707-
Err(err) => {
708-
self.sess.warn(&format!("error enumerating natvis directory: {}", err));
709-
}
710716
}
711717
}
718+
Strip::Debuginfo | Strip::Symbols => {
719+
self.cmd.arg("/DEBUG:NONE");
720+
}
712721
}
713722
}
714723

@@ -889,7 +898,7 @@ impl<'a> Linker for EmLinker<'a> {
889898
self.sess.warn("Windows Control Flow Guard is not supported by this linker.");
890899
}
891900

892-
fn debuginfo(&mut self) {
901+
fn debuginfo(&mut self, _strip: Strip) {
893902
// Preserve names or generate source maps depending on debug info
894903
self.cmd.arg(match self.sess.opts.debuginfo {
895904
DebugInfo::None => "-g0",
@@ -1081,7 +1090,17 @@ impl<'a> Linker for WasmLd<'a> {
10811090

10821091
fn pgo_gen(&mut self) {}
10831092

1084-
fn debuginfo(&mut self) {}
1093+
fn debuginfo(&mut self, strip: Strip) {
1094+
match strip {
1095+
Strip::None => {}
1096+
Strip::Debuginfo => {
1097+
self.cmd.arg("--strip-debug");
1098+
}
1099+
Strip::Symbols => {
1100+
self.cmd.arg("--strip-all");
1101+
}
1102+
}
1103+
}
10851104

10861105
fn control_flow_guard(&mut self) {
10871106
self.sess.warn("Windows Control Flow Guard is not supported by this linker.");
@@ -1184,7 +1203,7 @@ impl<'a> Linker for PtxLinker<'a> {
11841203
self.cmd.arg("-L").arg(path);
11851204
}
11861205

1187-
fn debuginfo(&mut self) {
1206+
fn debuginfo(&mut self, _strip: Strip) {
11881207
self.cmd.arg("--debug");
11891208
}
11901209

src/librustc_interface/tests.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use crate::interface::parse_cfgspecs;
33
use rustc_data_structures::fx::FxHashSet;
44
use rustc_errors::{emitter::HumanReadableErrorType, registry, ColorConfig};
55
use rustc_middle::middle::cstore;
6+
use rustc_session::config::Strip;
67
use rustc_session::config::{build_configuration, build_session_options, to_crate_config};
78
use rustc_session::config::{rustc_optgroups, ErrorOutputType, ExternLocation, Options, Passes};
89
use rustc_session::config::{CFGuard, ExternEntry, LinkerPluginLto, LtoCli, SwitchWithOptPath};
@@ -500,6 +501,7 @@ fn test_debugging_options_tracking_hash() {
500501
untracked!(self_profile, SwitchWithOptPath::Enabled(None));
501502
untracked!(self_profile_events, Some(vec![String::new()]));
502503
untracked!(span_free_formats, true);
504+
untracked!(strip, Strip::None);
503505
untracked!(terminal_width, Some(80));
504506
untracked!(threads, 99);
505507
untracked!(time, true);
@@ -564,7 +566,6 @@ fn test_debugging_options_tracking_hash() {
564566
tracked!(share_generics, Some(true));
565567
tracked!(show_span, Some(String::from("abc")));
566568
tracked!(src_hash_algorithm, Some(SourceFileHashAlgorithm::Sha1));
567-
tracked!(strip_debuginfo_if_disabled, true);
568569
tracked!(symbol_mangling_version, SymbolManglingVersion::V0);
569570
tracked!(teach, true);
570571
tracked!(thinlto, Some(true));

src/librustc_session/config.rs

+13
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,19 @@ impl FromStr for Sanitizer {
6969
}
7070
}
7171

72+
/// The different settings that the `-Z strip` flag can have.
73+
#[derive(Clone, Copy, PartialEq, Hash, Debug)]
74+
pub enum Strip {
75+
/// Do not strip at all.
76+
None,
77+
78+
/// Strip debuginfo.
79+
Debuginfo,
80+
81+
/// Strip all symbols.
82+
Symbols,
83+
}
84+
7285
/// The different settings that the `-Z control_flow_guard` flag can have.
7386
#[derive(Clone, Copy, PartialEq, Hash, Debug)]
7487
pub enum CFGuard {

src/librustc_session/options.rs

+13-3
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,7 @@ macro_rules! options {
253253
pub const parse_sanitizer_list: &str = "comma separated list of sanitizers";
254254
pub const parse_sanitizer_memory_track_origins: &str = "0, 1, or 2";
255255
pub const parse_cfguard: &str = "either `disabled`, `nochecks`, or `checks`";
256+
pub const parse_strip: &str = "either `none`, `debuginfo`, or `symbols`";
256257
pub const parse_linker_flavor: &str = ::rustc_target::spec::LinkerFlavor::one_of();
257258
pub const parse_optimization_fuel: &str = "crate=integer";
258259
pub const parse_unpretty: &str = "`string` or `string=string`";
@@ -491,6 +492,16 @@ macro_rules! options {
491492
}
492493
}
493494

495+
fn parse_strip(slot: &mut Strip, v: Option<&str>) -> bool {
496+
match v {
497+
Some("none") => *slot = Strip::None,
498+
Some("debuginfo") => *slot = Strip::Debuginfo,
499+
Some("symbols") => *slot = Strip::Symbols,
500+
_ => return false,
501+
}
502+
true
503+
}
504+
494505
fn parse_cfguard(slot: &mut CFGuard, v: Option<&str>) -> bool {
495506
match v {
496507
Some("disabled") => *slot = CFGuard::Disabled,
@@ -964,9 +975,8 @@ options! {DebuggingOptions, DebuggingSetter, basic_debugging_options,
964975
"exclude spans when debug-printing compiler state (default: no)"),
965976
src_hash_algorithm: Option<SourceFileHashAlgorithm> = (None, parse_src_file_hash, [TRACKED],
966977
"hash algorithm of source files in debug info (`md5`, or `sha1`)"),
967-
strip_debuginfo_if_disabled: bool = (false, parse_bool, [TRACKED],
968-
"tell the linker to strip debuginfo when building without debuginfo enabled \
969-
(default: no)"),
978+
strip: Strip = (Strip::None, parse_strip, [UNTRACKED],
979+
"tell the linker which information to strip (`none` (default), `debuginfo` or `symbols`)"),
970980
symbol_mangling_version: SymbolManglingVersion = (SymbolManglingVersion::Legacy,
971981
parse_symbol_mangling_version, [TRACKED],
972982
"which mangling version to use for symbol names"),

0 commit comments

Comments
 (0)