Skip to content

Commit cce055d

Browse files
authored
Rollup merge of rust-lang#67137 - anp:tracked-panic-internals, r=eddyb
libstd uses `core::panic::Location` where possible. cc @eddyb
2 parents cd8377d + 27b25eb commit cce055d

17 files changed

+90
-94
lines changed

src/libcore/macros/mod.rs

+3-9
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,21 @@
11
#[doc(include = "panic.md")]
22
#[macro_export]
3-
#[allow_internal_unstable(core_panic,
4-
// FIXME(anp, eddyb) `core_intrinsics` is used here to allow calling
5-
// the `caller_location` intrinsic, but once `#[track_caller]` is implemented,
6-
// `panicking::{panic, panic_fmt}` can use that instead of a `Location` argument.
7-
core_intrinsics,
8-
const_caller_location,
9-
)]
3+
#[allow_internal_unstable(core_panic, track_caller)]
104
#[stable(feature = "core", since = "1.6.0")]
115
macro_rules! panic {
126
() => (
137
$crate::panic!("explicit panic")
148
);
159
($msg:expr) => (
16-
$crate::panicking::panic($msg, $crate::intrinsics::caller_location())
10+
$crate::panicking::panic($msg)
1711
);
1812
($msg:expr,) => (
1913
$crate::panic!($msg)
2014
);
2115
($fmt:expr, $($arg:tt)+) => (
2216
$crate::panicking::panic_fmt(
2317
$crate::format_args!($fmt, $($arg)+),
24-
$crate::intrinsics::caller_location(),
18+
$crate::panic::Location::caller(),
2519
)
2620
);
2721
}

src/libcore/panicking.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,9 @@ use crate::panic::{Location, PanicInfo};
3636
// never inline unless panic_immediate_abort to avoid code
3737
// bloat at the call sites as much as possible
3838
#[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
39+
#[track_caller]
3940
#[lang = "panic"] // needed by codegen for panic on overflow and other `Assert` MIR terminators
40-
pub fn panic(expr: &str, location: &Location<'_>) -> ! {
41+
pub fn panic(expr: &str) -> ! {
4142
if cfg!(feature = "panic_immediate_abort") {
4243
unsafe { super::intrinsics::abort() }
4344
}
@@ -48,7 +49,7 @@ pub fn panic(expr: &str, location: &Location<'_>) -> ! {
4849
// truncation and padding (even though none is used here). Using
4950
// Arguments::new_v1 may allow the compiler to omit Formatter::pad from the
5051
// output binary, saving up to a few kilobytes.
51-
panic_fmt(fmt::Arguments::new_v1(&[expr], &[]), location)
52+
panic_fmt(fmt::Arguments::new_v1(&[expr], &[]), Location::caller())
5253
}
5354

5455
#[cold]

src/librustc_expand/build.rs

+2-8
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use syntax::ast::{self, AttrVec, BlockCheckMode, Expr, Ident, PatKind, UnOp};
66
use syntax::attr;
77
use syntax::ptr::P;
88

9-
use rustc_span::{Pos, Span};
9+
use rustc_span::Span;
1010

1111
impl<'a> ExtCtxt<'a> {
1212
pub fn path(&self, span: Span, strs: Vec<ast::Ident>) -> ast::Path {
@@ -350,16 +350,10 @@ impl<'a> ExtCtxt<'a> {
350350
}
351351

352352
pub fn expr_fail(&self, span: Span, msg: Symbol) -> P<ast::Expr> {
353-
let loc = self.source_map().lookup_char_pos(span.lo());
354-
let expr_file = self.expr_str(span, Symbol::intern(&loc.file.name.to_string()));
355-
let expr_line = self.expr_u32(span, loc.line as u32);
356-
let expr_col = self.expr_u32(span, loc.col.to_usize() as u32 + 1);
357-
let expr_loc_tuple = self.expr_tuple(span, vec![expr_file, expr_line, expr_col]);
358-
let expr_loc_ptr = self.expr_addr_of(span, expr_loc_tuple);
359353
self.expr_call_global(
360354
span,
361355
[sym::std, sym::rt, sym::begin_panic].iter().map(|s| Ident::new(*s, span)).collect(),
362-
vec![self.expr_str(span, msg), expr_loc_ptr],
356+
vec![self.expr_str(span, msg)],
363357
)
364358
}
365359

src/librustc_mir/const_eval/machine.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,7 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir,
177177

178178
fn find_mir_or_eval_fn(
179179
ecx: &mut InterpCx<'mir, 'tcx, Self>,
180+
span: Span,
180181
instance: ty::Instance<'tcx>,
181182
args: &[OpTy<'tcx>],
182183
ret: Option<(PlaceTy<'tcx>, mir::BasicBlock)>,
@@ -199,7 +200,7 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir,
199200
// Some functions we support even if they are non-const -- but avoid testing
200201
// that for const fn! We certainly do *not* want to actually call the fn
201202
// though, so be sure we return here.
202-
return if ecx.hook_panic_fn(instance, args, ret)? {
203+
return if ecx.hook_panic_fn(span, instance, args)? {
203204
Ok(None)
204205
} else {
205206
throw_unsup_format!("calling non-const function `{}`", instance)

src/librustc_mir/interpret/intrinsics.rs

+8-34
Original file line numberDiff line numberDiff line change
@@ -366,47 +366,21 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
366366
/// Returns `true` if an intercept happened.
367367
pub fn hook_panic_fn(
368368
&mut self,
369+
span: Span,
369370
instance: ty::Instance<'tcx>,
370371
args: &[OpTy<'tcx, M::PointerTag>],
371-
_ret: Option<(PlaceTy<'tcx, M::PointerTag>, mir::BasicBlock)>,
372372
) -> InterpResult<'tcx, bool> {
373373
let def_id = instance.def_id();
374-
if Some(def_id) == self.tcx.lang_items().panic_fn() {
375-
// &'static str, &core::panic::Location { &'static str, u32, u32 }
376-
assert!(args.len() == 2);
374+
if Some(def_id) == self.tcx.lang_items().panic_fn()
375+
|| Some(def_id) == self.tcx.lang_items().begin_panic_fn()
376+
{
377+
// &'static str
378+
assert!(args.len() == 1);
377379

378380
let msg_place = self.deref_operand(args[0])?;
379381
let msg = Symbol::intern(self.read_str(msg_place)?);
380-
381-
let location = self.deref_operand(args[1])?;
382-
let (file, line, col) = (
383-
self.mplace_field(location, 0)?,
384-
self.mplace_field(location, 1)?,
385-
self.mplace_field(location, 2)?,
386-
);
387-
388-
let file_place = self.deref_operand(file.into())?;
389-
let file = Symbol::intern(self.read_str(file_place)?);
390-
let line = self.read_scalar(line.into())?.to_u32()?;
391-
let col = self.read_scalar(col.into())?.to_u32()?;
392-
throw_panic!(Panic { msg, file, line, col })
393-
} else if Some(def_id) == self.tcx.lang_items().begin_panic_fn() {
394-
assert!(args.len() == 2);
395-
// &'static str, &(&'static str, u32, u32)
396-
let msg = args[0];
397-
let place = self.deref_operand(args[1])?;
398-
let (file, line, col) = (
399-
self.mplace_field(place, 0)?,
400-
self.mplace_field(place, 1)?,
401-
self.mplace_field(place, 2)?,
402-
);
403-
404-
let msg_place = self.deref_operand(msg.into())?;
405-
let msg = Symbol::intern(self.read_str(msg_place)?);
406-
let file_place = self.deref_operand(file.into())?;
407-
let file = Symbol::intern(self.read_str(file_place)?);
408-
let line = self.read_scalar(line.into())?.to_u32()?;
409-
let col = self.read_scalar(col.into())?.to_u32()?;
382+
let span = self.find_closest_untracked_caller_location().unwrap_or(span);
383+
let (file, line, col) = self.location_triple_for_span(span);
410384
throw_panic!(Panic { msg, file, line, col })
411385
} else {
412386
return Ok(false);

src/librustc_mir/interpret/intrinsics/caller_location.rs

+9-3
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,9 @@ use crate::interpret::{
99
};
1010

1111
impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
12-
/// Walks up the callstack from the intrinsic's callsite, searching for the first frame which is
13-
/// not `#[track_caller]`.
12+
/// Walks up the callstack from the intrinsic's callsite, searching for the first callsite in a
13+
/// frame which is not `#[track_caller]`. If the first frame found lacks `#[track_caller]`, then
14+
/// `None` is returned and the callsite of the function invocation itself should be used.
1415
crate fn find_closest_untracked_caller_location(&self) -> Option<Span> {
1516
let mut caller_span = None;
1617
for next_caller in self.stack.iter().rev() {
@@ -54,9 +55,14 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
5455
}
5556

5657
pub fn alloc_caller_location_for_span(&mut self, span: Span) -> MPlaceTy<'tcx, M::PointerTag> {
58+
let (file, line, column) = self.location_triple_for_span(span);
59+
self.alloc_caller_location(file, line, column)
60+
}
61+
62+
pub(super) fn location_triple_for_span(&self, span: Span) -> (Symbol, u32, u32) {
5763
let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
5864
let caller = self.tcx.sess.source_map().lookup_char_pos(topmost.lo());
59-
self.alloc_caller_location(
65+
(
6066
Symbol::intern(&caller.file.name.to_string()),
6167
caller.line as u32,
6268
caller.col_display as u32 + 1,

src/librustc_mir/interpret/machine.rs

+1
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,7 @@ pub trait Machine<'mir, 'tcx>: Sized {
139139
/// was used.
140140
fn find_mir_or_eval_fn(
141141
ecx: &mut InterpCx<'mir, 'tcx, Self>,
142+
span: Span,
142143
instance: ty::Instance<'tcx>,
143144
args: &[OpTy<'tcx, Self::PointerTag>],
144145
ret: Option<(PlaceTy<'tcx, Self::PointerTag>, mir::BasicBlock)>,

src/librustc_mir/interpret/terminator.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -238,7 +238,7 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
238238
| ty::InstanceDef::CloneShim(..)
239239
| ty::InstanceDef::Item(_) => {
240240
// We need MIR for this fn
241-
let body = match M::find_mir_or_eval_fn(self, instance, args, ret, unwind)? {
241+
let body = match M::find_mir_or_eval_fn(self, span, instance, args, ret, unwind)? {
242242
Some(body) => body,
243243
None => return Ok(()),
244244
};

src/librustc_mir/transform/const_prop.rs

+1
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,7 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for ConstPropMachine {
125125

126126
fn find_mir_or_eval_fn(
127127
_ecx: &mut InterpCx<'mir, 'tcx, Self>,
128+
_span: Span,
128129
_instance: ty::Instance<'tcx>,
129130
_args: &[OpTy<'tcx>],
130131
_ret: Option<(PlaceTy<'tcx>, BasicBlock)>,

src/libstd/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,7 @@
305305
#![feature(thread_local)]
306306
#![feature(toowned_clone_into)]
307307
#![feature(trace_macros)]
308+
#![feature(track_caller)]
308309
#![feature(try_reserve)]
309310
#![feature(unboxed_closures)]
310311
#![feature(untagged_unions)]

src/libstd/macros.rs

+16-2
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
//! library. Each macro is available for use when linking against the standard
55
//! library.
66
7+
#[cfg(bootstrap)]
78
#[doc(include = "../libcore/macros/panic.md")]
89
#[macro_export]
910
#[stable(feature = "rust1", since = "1.0.0")]
@@ -19,8 +20,21 @@ macro_rules! panic {
1920
$crate::panic!($msg)
2021
});
2122
($fmt:expr, $($arg:tt)+) => ({
22-
$crate::rt::begin_panic_fmt(&$crate::format_args!($fmt, $($arg)+),
23-
&($crate::file!(), $crate::line!(), $crate::column!()))
23+
$crate::rt::begin_panic_fmt(&$crate::format_args!($fmt, $($arg)+))
24+
});
25+
}
26+
27+
#[cfg(not(bootstrap))]
28+
#[doc(include = "../libcore/macros/panic.md")]
29+
#[macro_export]
30+
#[stable(feature = "rust1", since = "1.0.0")]
31+
#[allow_internal_unstable(libstd_sys_internals)]
32+
macro_rules! panic {
33+
() => ({ $crate::panic!("explicit panic") });
34+
($msg:expr) => ({ $crate::rt::begin_panic($msg) });
35+
($msg:expr,) => ({ $crate::panic!($msg) });
36+
($fmt:expr, $($arg:tt)+) => ({
37+
$crate::rt::begin_panic_fmt(&$crate::format_args!($fmt, $($arg)+))
2438
});
2539
}
2640

src/libstd/panicking.rs

+17-26
Original file line numberDiff line numberDiff line change
@@ -313,17 +313,15 @@ pub fn panicking() -> bool {
313313
#[cold]
314314
// If panic_immediate_abort, inline the abort call,
315315
// otherwise avoid inlining because of it is cold path.
316+
#[cfg_attr(not(feature = "panic_immediate_abort"), track_caller)]
316317
#[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
317318
#[cfg_attr(feature = "panic_immediate_abort", inline)]
318-
pub fn begin_panic_fmt(msg: &fmt::Arguments<'_>, file_line_col: &(&'static str, u32, u32)) -> ! {
319+
pub fn begin_panic_fmt(msg: &fmt::Arguments<'_>) -> ! {
319320
if cfg!(feature = "panic_immediate_abort") {
320321
unsafe { intrinsics::abort() }
321322
}
322323

323-
// Just package everything into a `PanicInfo` and continue like libcore panics.
324-
let (file, line, col) = *file_line_col;
325-
let location = Location::internal_constructor(file, line, col);
326-
let info = PanicInfo::internal_constructor(Some(msg), &location);
324+
let info = PanicInfo::internal_constructor(Some(msg), Location::caller());
327325
begin_panic_handler(&info)
328326
}
329327

@@ -356,6 +354,9 @@ pub fn begin_panic_handler(info: &PanicInfo<'_>) -> ! {
356354

357355
unsafe impl<'a> BoxMeUp for PanicPayload<'a> {
358356
fn take_box(&mut self) -> *mut (dyn Any + Send) {
357+
// We do two allocations here, unfortunately. But (a) they're required with the current
358+
// scheme, and (b) we don't handle panic + OOM properly anyway (see comment in
359+
// begin_panic below).
359360
let contents = mem::take(self.fill());
360361
Box::into_raw(Box::new(contents))
361362
}
@@ -365,15 +366,9 @@ pub fn begin_panic_handler(info: &PanicInfo<'_>) -> ! {
365366
}
366367
}
367368

368-
// We do two allocations here, unfortunately. But (a) they're
369-
// required with the current scheme, and (b) we don't handle
370-
// panic + OOM properly anyway (see comment in begin_panic
371-
// below).
372-
373369
let loc = info.location().unwrap(); // The current implementation always returns Some
374370
let msg = info.message().unwrap(); // The current implementation always returns Some
375-
let file_line_col = (loc.file(), loc.line(), loc.column());
376-
rust_panic_with_hook(&mut PanicPayload::new(msg), info.message(), &file_line_col);
371+
rust_panic_with_hook(&mut PanicPayload::new(msg), info.message(), loc);
377372
}
378373

379374
/// This is the entry point of panicking for the non-format-string variants of
@@ -386,19 +381,13 @@ pub fn begin_panic_handler(info: &PanicInfo<'_>) -> ! {
386381
// bloat at the call sites as much as possible
387382
#[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
388383
#[cold]
389-
pub fn begin_panic<M: Any + Send>(msg: M, file_line_col: &(&'static str, u32, u32)) -> ! {
384+
#[track_caller]
385+
pub fn begin_panic<M: Any + Send>(msg: M, #[cfg(bootstrap)] _: &(&str, u32, u32)) -> ! {
390386
if cfg!(feature = "panic_immediate_abort") {
391387
unsafe { intrinsics::abort() }
392388
}
393389

394-
// Note that this should be the only allocation performed in this code path.
395-
// Currently this means that panic!() on OOM will invoke this code path,
396-
// but then again we're not really ready for panic on OOM anyway. If
397-
// we do start doing this, then we should propagate this allocation to
398-
// be performed in the parent of this thread instead of the thread that's
399-
// panicking.
400-
401-
rust_panic_with_hook(&mut PanicPayload::new(msg), None, file_line_col);
390+
rust_panic_with_hook(&mut PanicPayload::new(msg), None, Location::caller());
402391

403392
struct PanicPayload<A> {
404393
inner: Option<A>,
@@ -412,6 +401,11 @@ pub fn begin_panic<M: Any + Send>(msg: M, file_line_col: &(&'static str, u32, u3
412401

413402
unsafe impl<A: Send + 'static> BoxMeUp for PanicPayload<A> {
414403
fn take_box(&mut self) -> *mut (dyn Any + Send) {
404+
// Note that this should be the only allocation performed in this code path. Currently
405+
// this means that panic!() on OOM will invoke this code path, but then again we're not
406+
// really ready for panic on OOM anyway. If we do start doing this, then we should
407+
// propagate this allocation to be performed in the parent of this thread instead of the
408+
// thread that's panicking.
415409
let data = match self.inner.take() {
416410
Some(a) => Box::new(a) as Box<dyn Any + Send>,
417411
None => process::abort(),
@@ -436,10 +430,8 @@ pub fn begin_panic<M: Any + Send>(msg: M, file_line_col: &(&'static str, u32, u3
436430
fn rust_panic_with_hook(
437431
payload: &mut dyn BoxMeUp,
438432
message: Option<&fmt::Arguments<'_>>,
439-
file_line_col: &(&str, u32, u32),
433+
location: &Location<'_>,
440434
) -> ! {
441-
let (file, line, col) = *file_line_col;
442-
443435
let panics = update_panic_count(1);
444436

445437
// If this is the third nested call (e.g., panics == 2, this is 0-indexed),
@@ -456,8 +448,7 @@ fn rust_panic_with_hook(
456448
}
457449

458450
unsafe {
459-
let location = Location::internal_constructor(file, line, col);
460-
let mut info = PanicInfo::internal_constructor(message, &location);
451+
let mut info = PanicInfo::internal_constructor(message, location);
461452
HOOK_LOCK.read();
462453
match HOOK {
463454
// Some platforms (like wasm) know that printing to stderr won't ever actually

src/test/mir-opt/retain-never-const.rs

+1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
#![feature(const_panic)]
88
#![feature(never_type)]
9+
#![warn(const_err)]
910

1011
struct PrintName<T>(T);
1112

src/test/ui/extern/issue-64655-allow-unwind-when-calling-panic-directly.rs

+2-4
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
//[thin]compile-flags: -C lto=thin
2323
//[fat]compile-flags: -C lto=fat
2424

25-
#![feature(core_panic, panic_internals)]
25+
#![feature(core_panic)]
2626

2727
// (For some reason, reproducing the LTO issue requires pulling in std
2828
// explicitly this way.)
@@ -50,9 +50,7 @@ fn main() {
5050
}
5151

5252
let _guard = Droppable;
53-
let s = "issue-64655-allow-unwind-when-calling-panic-directly.rs";
54-
let location = core::panic::Location::internal_constructor(s, 17, 4);
55-
core::panicking::panic("???", &location);
53+
core::panicking::panic("???");
5654
});
5755

5856
let wait = handle.join();

src/test/ui/rfc-2091-track-caller/caller-location-intrinsic.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,16 @@
44

55
#[inline(never)]
66
#[track_caller]
7-
fn defeat_const_prop() -> &'static core::panic::Location<'static> {
7+
fn codegen_caller_loc() -> &'static core::panic::Location<'static> {
88
core::panic::Location::caller()
99
}
1010

1111
macro_rules! caller_location_from_macro {
12-
() => (defeat_const_prop());
12+
() => (codegen_caller_loc());
1313
}
1414

1515
fn main() {
16-
let loc = defeat_const_prop();
16+
let loc = codegen_caller_loc();
1717
assert_eq!(loc.file(), file!());
1818
assert_eq!(loc.line(), 16);
1919
assert_eq!(loc.column(), 15);

0 commit comments

Comments
 (0)