Skip to content

bootstrap: Fix stack printing when a step cycle is detected #138216

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 9, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions src/bootstrap/src/core/build_steps/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -367,3 +367,28 @@ impl Step for FeaturesStatusDump {
cmd.run(builder);
}
}

/// Dummy step that can be used to deliberately trigger bootstrap's step cycle
/// detector, for automated and manual testing.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct CyclicStep {
n: u32,
}

impl Step for CyclicStep {
type Output = ();

fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
run.alias("cyclic-step")
}

fn make_run(run: RunConfig<'_>) {
// Start with n=2, so that we build up a few stack entries before panicking.
run.builder.ensure(CyclicStep { n: 2 })
}

fn run(self, builder: &Builder<'_>) -> Self::Output {
// When n=0, the step will try to ensure itself, causing a step cycle.
builder.ensure(CyclicStep { n: self.n.saturating_sub(1) })
}
}
18 changes: 17 additions & 1 deletion src/bootstrap/src/core/builder/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ pub struct Builder<'a> {

/// A stack of [`Step`]s to run before we can run this builder. The output
/// of steps is cached in [`Self::cache`].
stack: RefCell<Vec<Box<dyn Any>>>,
stack: RefCell<Vec<Box<dyn AnyDebug>>>,

/// The total amount of time we spent running [`Step`]s in [`Self::stack`].
time_spent_on_dependencies: Cell<Duration>,
Expand All @@ -69,6 +69,21 @@ impl Deref for Builder<'_> {
}
}

/// This trait is similar to `Any`, except that it also exposes the underlying
/// type's [`Debug`] implementation.
///
/// (Trying to debug-print `dyn Any` results in the unhelpful `"Any { .. }"`.)
trait AnyDebug: Any + Debug {}
impl<T: Any + Debug> AnyDebug for T {}
impl dyn AnyDebug {
/// Equivalent to `<dyn Any>::downcast_ref`.
fn downcast_ref<T: Any>(&self) -> Option<&T> {
(self as &dyn Any).downcast_ref()
}

// Feel free to add other `dyn Any` methods as necessary.
}

pub trait Step: 'static + Clone + Debug + PartialEq + Eq + Hash {
/// Result type of `Step::run`.
type Output: Clone;
Expand Down Expand Up @@ -1101,6 +1116,7 @@ impl<'a> Builder<'a> {
run::GenerateCompletions,
run::UnicodeTableGenerator,
run::FeaturesStatusDump,
run::CyclicStep,
),
Kind::Setup => {
describe!(setup::Profile, setup::Hook, setup::Link, setup::Editor)
Expand Down
34 changes: 33 additions & 1 deletion src/bootstrap/src/core/builder/tests.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::thread;
use std::{panic, thread};

use llvm::prebuilt_llvm_config;

Expand Down Expand Up @@ -1135,3 +1135,35 @@ fn test_get_tool_rustc_compiler() {
let actual = tool::get_tool_rustc_compiler(&builder, compiler);
assert_eq!(expected, actual);
}

/// When bootstrap detects a step dependency cycle (which is a bug), its panic
/// message should show the actual steps on the stack, not just several copies
/// of `Any { .. }`.
#[test]
fn step_cycle_debug() {
let cmd = ["run", "cyclic-step"].map(str::to_owned);
let config = configure_with_args(&cmd, &[TEST_TRIPLE_1], &[TEST_TRIPLE_1]);

let err = panic::catch_unwind(|| run_build(&config.paths.clone(), config)).unwrap_err();
let err = err.downcast_ref::<String>().unwrap().as_str();

assert!(!err.contains("Any"));
assert!(err.contains("CyclicStep { n: 1 }"));
}

/// The `AnyDebug` trait should delegate to the underlying type's `Debug`, and
/// should also allow downcasting as expected.
#[test]
fn any_debug() {
#[derive(Debug, PartialEq, Eq)]
struct MyStruct {
x: u32,
}

let x: &dyn AnyDebug = &MyStruct { x: 7 };

// Debug-formatting should delegate to the underlying type.
assert_eq!(format!("{x:?}"), format!("{:?}", MyStruct { x: 7 }));
// Downcasting to the underlying type should succeed.
assert_eq!(x.downcast_ref::<MyStruct>(), Some(&MyStruct { x: 7 }));
}
Loading