Skip to content

Commit a4a5208

Browse files
committed
Pass -pg to linker when using -Zinstrument-mcount
Clang and gcc use this option to control linking behavior too. Some targets need to be linked against a special crt which enables profiling at runtime. This makes using gprof a little easier with Rust binaries. Otherwise, rustc must be passed `-Clink-args=-pg` to ensure the correct startup code is linked.
1 parent d00ba92 commit a4a5208

4 files changed

Lines changed: 33 additions & 0 deletions

File tree

compiler/rustc_codegen_ssa/src/back/link.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2672,6 +2672,10 @@ fn add_order_independent_options(
26722672
cmd.pgo_gen();
26732673
}
26742674

2675+
if sess.opts.unstable_opts.instrument_mcount {
2676+
cmd.enable_profiling();
2677+
}
2678+
26752679
if sess.opts.cg.control_flow_guard != CFGuard::Disabled {
26762680
cmd.control_flow_guard();
26772681
}

compiler/rustc_codegen_ssa/src/back/linker.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -352,6 +352,7 @@ pub(crate) trait Linker {
352352
fn add_no_exec(&mut self) {}
353353
fn add_as_needed(&mut self) {}
354354
fn reset_per_library_state(&mut self) {}
355+
fn enable_profiling(&mut self) {}
355356
}
356357

357358
impl dyn Linker + '_ {
@@ -731,6 +732,12 @@ impl<'a> Linker for GccLinker<'a> {
731732
self.link_or_cc_args(&["-u", "__llvm_profile_runtime"]);
732733
}
733734

735+
fn enable_profiling(&mut self) {
736+
// This flag is also used when linking to choose target specific
737+
// libraries needed to enable profiling.
738+
self.cc_arg("-pg");
739+
}
740+
734741
fn control_flow_guard(&mut self) {}
735742

736743
fn ehcont_guard(&mut self) {}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
fn main() {
2+
println!("Hello World!");
3+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// When building a binary instrumented with mcount, verify the
2+
// binary is linked with the correct crt to enable profiling.
3+
//
4+
//@ only-gnu
5+
//@ ignore-cross-compile
6+
7+
use run_make_support::{path, run, rustc};
8+
9+
fn main() {
10+
// Compile instrumentation enabled binary, and verify -pg is passed
11+
let link_args =
12+
rustc().input("main.rs").arg("-Zinstrument-mcount").print("link-args").run().stdout_utf8();
13+
assert!(link_args.contains("\"-pg\""));
14+
15+
// Run it, and verify gmon.out is created
16+
assert!(!path("gmon.out").exists());
17+
run("main");
18+
assert!(path("gmon.out").exists());
19+
}

0 commit comments

Comments
 (0)