Add nul-terminated filename for #[track_caller] by Darksonn · Pull Request #131828 · rust-lang/rust (original) (raw)
ACP: Add nul-terminated version of core::panic::Location::file
When using #[track_caller]
you can get the filename of the caller using Location::caller().file()
. We would like to utilize this in the Linux kernel to implement a Rust equivalent of the following utility:
/**
- might_sleep - annotation for functions that can sleep
- this macro will print a stack trace if it is executed in an atomic
- context (spinlock, irq-handler, ...). Additional sections where blocking is
- not allowed can be annotated with non_block_start() and non_block_end()
- pairs.
- This is a useful debugging help to be able to catch problems early and not
- be bitten later when the calling function happens to sleep when it is not
- supposed to. */
#define might_sleep() do { __might_sleep(FILE, LINE); might_resched(); } while (0)
It's essentially an assertion that crashes the kernel if a function is used in the wrong context. The filename and line number is used in the error message when it fails. Unfortunately, the __might_sleep
function requires the filename to be a nul-terminated string. Thus, extend Location
with a function that returns the filename as a &CStr
.
Note that unlike with things like the file!()
macro, it's impossible for us to do this ourselves statically. Copying the filename into another string to nul-terminate it is not a great solution because we need to create the string even if the assertion doesn't fail, as the assertion happens on the C side.
For more context, please see zulip and the Linux kernel mailing list. This is one of RfL's wanted features in core.