Blocking certain calls

I want to do something slightly odd. I'm assuming there are no means to do what I want, but I just wasted some time chasing down an issue relating to this, so:

I have a build system for a somewhat large project written in Rust. It has two major phases; one single-threaded which transitions over to the other, which is multi-threaded. During the single-threaded phase it's perfectly okay for a functions to change the current working directory (because each new major function changes its directory to where it needs to be).

For obvious reasons changing directory in a multi-threaded is a major no-no.

I would like to block std::env::set_current_dir from being called. Yes, I know there are other ways to do that, like libc::chdir. If someone is actively looking for a footgun, there isn't much I can do about it -- but what I want to protect against is someone down the line accidentally not being aware of a particular module belonging to the multithreaded phase and calling set_current_dir in it. (This constraint could be enforced on a module basis).

Is there something akin to:

#[croak_on_encountering(std::env::set_current_dir)]

.. ?

Doesn't really matter if it's compile time or runtime, as long as it goes very kaboom so it's impossible to miss.

No, I'm pretty sure there isn't.

2 Likes

Can you use #[no_std]? That will disable use of std everywhere in your program. You can still get environment variables with core::env at compile time, without allowing it to be changed.

Here's a silly idea: have your own function called set_current_dir that's imported into each module associated with the multi-threaded phase.

fn set_current_dir<P: AsRef<Path>>(_path: P) -> std::io::Result<()> {
    panic!("no `chdir` in the multi-threaded phase!")
}

It doesn't help if someone uses the qualified path std::env::set_current_dir, but if they just write set_current_dir then rustc should throw a name resolution error and hopefully that gives people pause/causes them to look at the code for the in-crate set_current_dir (where they'll see the panic message or an explanatory comment).

Never tried anything like this but I'm wondering how difficult it'd be to use https://crates.io/crates/libc and patch chmod() function to do whatever you need it to do (like enable the actual call only if some global flag is on.)

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.