Skip to content

Commit 6112b22

Browse files
committed
Implement Win64 eh_personality natively.
1 parent 28869d4 commit 6112b22

File tree

24 files changed

+660
-235
lines changed

24 files changed

+660
-235
lines changed

src/doc/trpl/lang-items.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ fn main(argc: isize, argv: *const *const u8) -> isize {
5454
#[lang = "stack_exhausted"] extern fn stack_exhausted() {}
5555
#[lang = "eh_personality"] extern fn eh_personality() {}
5656
#[lang = "panic_fmt"] fn panic_fmt() -> ! { loop {} }
57+
# #[lang = "eh_unwind_resume"] extern fn rust_eh_unwind_resume() {}
5758
```
5859

5960
Note the use of `abort`: the `exchange_malloc` lang item is assumed to

src/doc/trpl/no-stdlib.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ fn start(_argc: isize, _argv: *const *const u8) -> isize {
3939
#[lang = "stack_exhausted"] extern fn stack_exhausted() {}
4040
#[lang = "eh_personality"] extern fn eh_personality() {}
4141
#[lang = "panic_fmt"] fn panic_fmt() -> ! { loop {} }
42+
# #[lang = "eh_unwind_resume"] extern fn rust_eh_unwind_resume() {}
4243
# // fn main() {} tricked you, rustdoc!
4344
```
4445

@@ -63,6 +64,7 @@ pub extern fn main(argc: i32, argv: *const *const u8) -> i32 {
6364
#[lang = "stack_exhausted"] extern fn stack_exhausted() {}
6465
#[lang = "eh_personality"] extern fn eh_personality() {}
6566
#[lang = "panic_fmt"] fn panic_fmt() -> ! { loop {} }
67+
# #[lang = "eh_unwind_resume"] extern fn rust_eh_unwind_resume() {}
6668
# // fn main() {} tricked you, rustdoc!
6769
```
6870

@@ -150,6 +152,7 @@ extern fn panic_fmt(args: &core::fmt::Arguments,
150152
151153
#[lang = "stack_exhausted"] extern fn stack_exhausted() {}
152154
#[lang = "eh_personality"] extern fn eh_personality() {}
155+
# #[lang = "eh_unwind_resume"] extern fn rust_eh_unwind_resume() {}
153156
# #[start] fn start(argc: isize, argv: *const *const u8) -> isize { 0 }
154157
# fn main() {}
155158
```

src/librustc/middle/lang_items.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,7 @@ lets_do_this! {
327327

328328
EhPersonalityLangItem, "eh_personality", eh_personality;
329329
EhPersonalityCatchLangItem, "eh_personality_catch", eh_personality_catch;
330+
EhUnwindResumeLangItem, "eh_unwind_resume", eh_unwind_resume;
330331
MSVCTryFilterLangItem, "msvc_try_filter", msvc_try_filter;
331332

332333
ExchangeHeapLangItem, "exchange_heap", exchange_heap;

src/librustc/middle/weak_lang_items.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,10 @@ pub fn check_crate(krate: &ast::Crate,
4545
if items.eh_personality().is_none() {
4646
items.missing.push(lang_items::EhPersonalityLangItem);
4747
}
48+
if sess.target.target.options.custom_unwind_resume &
49+
items.eh_unwind_resume().is_none() {
50+
items.missing.push(lang_items::EhUnwindResumeLangItem);
51+
}
4852

4953
{
5054
let mut cx = Context { sess: sess, items: items };
@@ -122,4 +126,5 @@ weak_lang_items! {
122126
panic_fmt, PanicFmtLangItem, rust_begin_unwind;
123127
stack_exhausted, StackExhaustedLangItem, rust_stack_exhausted;
124128
eh_personality, EhPersonalityLangItem, rust_eh_personality;
129+
eh_unwind_resume, EhUnwindResumeLangItem, rust_eh_unwind_resume;
125130
}

src/librustc_back/target/mod.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,11 @@ pub struct TargetOptions {
171171
/// currently only "gnu" is used to fall into LLVM. Unknown strings cause
172172
/// the system linker to be used.
173173
pub archive_format: String,
174+
/// Whether the target uses a custom unwind resumption routine.
175+
/// By default LLVM lowers `resume` instructions into calls to `_Unwind_Resume`
176+
/// defined in libgcc. If this option is enabled, the target must provide
177+
/// `eh_unwind_resume` lang item.
178+
pub custom_unwind_resume: bool,
174179
}
175180

176181
impl Default for TargetOptions {
@@ -209,6 +214,7 @@ impl Default for TargetOptions {
209214
pre_link_objects: Vec::new(),
210215
post_link_objects: Vec::new(),
211216
archive_format: String::new(),
217+
custom_unwind_resume: false,
212218
}
213219
}
214220
}

src/librustc_back/target/x86_64_pc_windows_gnu.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ pub fn target() -> Target {
1616
// On Win64 unwinding is handled by the OS, so we can link libgcc statically.
1717
base.pre_link_args.push("-static-libgcc".to_string());
1818
base.pre_link_args.push("-m64".to_string());
19+
base.custom_unwind_resume = true;
1920

2021
Target {
2122
llvm_target: "x86_64-pc-windows-gnu".to_string(),

src/librustc_trans/trans/base.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2171,6 +2171,12 @@ fn finish_register_fn(ccx: &CrateContext, sym: String, node_id: ast::NodeId,
21712171
llvm::SetDLLStorageClass(llfn, llvm::DLLExportStorageClass);
21722172
}
21732173
}
2174+
if ccx.tcx().lang_items.eh_unwind_resume() == Some(def) {
2175+
llvm::SetLinkage(llfn, llvm::ExternalLinkage);
2176+
if ccx.use_dll_storage_attrs() {
2177+
llvm::SetDLLStorageClass(llfn, llvm::DLLExportStorageClass);
2178+
}
2179+
}
21742180
}
21752181

21762182
fn register_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,

src/librustc_trans/trans/cleanup.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -846,6 +846,8 @@ impl<'blk, 'tcx> CleanupHelperMethods<'blk, 'tcx> for FunctionContext<'blk, 'tcx
846846

847847
debug!("get_or_create_landing_pad");
848848

849+
self.inject_unwind_resume_hook();
850+
849851
// Check if a landing pad block exists; if not, create one.
850852
{
851853
let mut scopes = self.scopes.borrow_mut();

src/librustc_trans/trans/common.rs

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -561,6 +561,55 @@ impl<'a, 'tcx> FunctionContext<'a, 'tcx> {
561561
}
562562
}
563563
}
564+
565+
/// By default, LLVM lowers `resume` instructions into calls to `_Unwind_Resume`
566+
/// defined in libgcc, however, unlike personality routines, there is no easy way to
567+
/// override that symbol. This method injects a local-scoped `_Unwind_Resume` function
568+
/// which immediately defers to the user-defined `eh_unwind_resume` lang item.
569+
pub fn inject_unwind_resume_hook(&self) {
570+
let ccx = self.ccx;
571+
if !ccx.sess().target.target.options.custom_unwind_resume ||
572+
ccx.unwind_resume_hooked().get() {
573+
return;
574+
}
575+
576+
let new_resume = match ccx.tcx().lang_items.eh_unwind_resume() {
577+
Some(did) => callee::trans_fn_ref(ccx, did, ExprId(0), &self.param_substs).val,
578+
None => {
579+
let fty = Type::variadic_func(&[], &Type::void(self.ccx));
580+
declare::declare_cfn(self.ccx, "rust_eh_unwind_resume", fty,
581+
self.ccx.tcx().mk_nil())
582+
}
583+
};
584+
585+
unsafe {
586+
let resume_type = Type::func(&[Type::i8(ccx).ptr_to()], &Type::void(ccx));
587+
let old_resume = llvm::LLVMAddFunction(ccx.llmod(),
588+
"_Unwind_Resume\0".as_ptr() as *const _,
589+
resume_type.to_ref());
590+
llvm::SetLinkage(old_resume, llvm::InternalLinkage);
591+
let llbb = llvm::LLVMAppendBasicBlockInContext(ccx.llcx(),
592+
old_resume,
593+
"\0".as_ptr() as *const _);
594+
let builder = ccx.builder();
595+
builder.position_at_end(llbb);
596+
builder.call(new_resume, &[llvm::LLVMGetFirstParam(old_resume)], None);
597+
builder.unreachable(); // it should never return
598+
599+
// Until DwarfEHPrepare pass has run, _Unwind_Resume is not referenced by any live code
600+
// and is subject to dead code elimination. Here we add _Unwind_Resume to @llvm.globals
601+
// to prevent that.
602+
let i8p_ty = Type::i8p(ccx);
603+
let used_ty = Type::array(&i8p_ty, 1);
604+
let used = llvm::LLVMAddGlobal(ccx.llmod(), used_ty.to_ref(),
605+
"llvm.used\0".as_ptr() as *const _);
606+
let old_resume = llvm::LLVMConstBitCast(old_resume, i8p_ty.to_ref());
607+
llvm::LLVMSetInitializer(used, C_array(i8p_ty, &[old_resume]));
608+
llvm::SetLinkage(used, llvm::AppendingLinkage);
609+
llvm::LLVMSetSection(used, "llvm.metadata\0".as_ptr() as *const _)
610+
}
611+
ccx.unwind_resume_hooked().set(true);
612+
}
564613
}
565614

566615
// Basic block context. We create a block context for each basic block

src/librustc_trans/trans/context.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,7 @@ pub struct LocalCrateContext<'tcx> {
146146

147147
eh_personality: RefCell<Option<ValueRef>>,
148148
rust_try_fn: RefCell<Option<ValueRef>>,
149+
unwind_resume_hooked: Cell<bool>,
149150

150151
intrinsics: RefCell<FnvHashMap<&'static str, ValueRef>>,
151152

@@ -466,6 +467,7 @@ impl<'tcx> LocalCrateContext<'tcx> {
466467
dbg_cx: dbg_cx,
467468
eh_personality: RefCell::new(None),
468469
rust_try_fn: RefCell::new(None),
470+
unwind_resume_hooked: Cell::new(false),
469471
intrinsics: RefCell::new(FnvHashMap()),
470472
n_llvm_insns: Cell::new(0),
471473
trait_cache: RefCell::new(FnvHashMap()),
@@ -735,6 +737,10 @@ impl<'b, 'tcx> CrateContext<'b, 'tcx> {
735737
&self.local.rust_try_fn
736738
}
737739

740+
pub fn unwind_resume_hooked<'a>(&'a self) -> &'a Cell<bool> {
741+
&self.local.unwind_resume_hooked
742+
}
743+
738744
fn intrinsics<'a>(&'a self) -> &'a RefCell<FnvHashMap<&'static str, ValueRef>> {
739745
&self.local.intrinsics
740746
}

src/librustc_trans/trans/intrinsic.rs

Lines changed: 44 additions & 104 deletions
Original file line numberDiff line numberDiff line change
@@ -1159,26 +1159,14 @@ fn trans_msvc_try<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
11591159
// of exceptions (e.g. the normal semantics of LLVM's landingpad and invoke
11601160
// instructions).
11611161
//
1162-
// This translation is a little surprising for two reasons:
1162+
// This translation is a little surprising because
1163+
// we always call a shim function instead of inlining the call to `invoke`
1164+
// manually here. This is done because in LLVM we're only allowed to have one
1165+
// personality per function definition. The call to the `try` intrinsic is
1166+
// being inlined into the function calling it, and that function may already
1167+
// have other personality functions in play. By calling a shim we're
1168+
// guaranteed that our shim will have the right personality function.
11631169
//
1164-
// 1. We always call a shim function instead of inlining the call to `invoke`
1165-
// manually here. This is done because in LLVM we're only allowed to have one
1166-
// personality per function definition. The call to the `try` intrinsic is
1167-
// being inlined into the function calling it, and that function may already
1168-
// have other personality functions in play. By calling a shim we're
1169-
// guaranteed that our shim will have the right personality function.
1170-
//
1171-
// 2. Instead of making one shim (explained above), we make two shims! The
1172-
// reason for this has to do with the technical details about the
1173-
// implementation of unwinding in the runtime, but the tl;dr; is that the
1174-
// outer shim's personality function says "catch rust exceptions" and the
1175-
// inner shim's landing pad will not `resume` the exception being thrown.
1176-
// This means that the outer shim's landing pad is never run and the inner
1177-
// shim's return value is the return value of the whole call.
1178-
//
1179-
// The double-shim aspect is currently done for implementation ease on the
1180-
// runtime side of things, and more info can be found in
1181-
// src/libstd/rt/unwind/gcc.rs.
11821170
fn trans_gnu_try<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
11831171
func: ValueRef,
11841172
data: ValueRef,
@@ -1188,108 +1176,61 @@ fn trans_gnu_try<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
11881176
let ccx = bcx.ccx();
11891177
let dloc = DebugLoc::None;
11901178

1191-
// Type indicator for the exception being thrown, not entirely sure
1192-
// what's going on here but it's what all the examples in LLVM use.
1193-
let lpad_ty = Type::struct_(ccx, &[Type::i8p(ccx), Type::i32(ccx)],
1194-
false);
1179+
// Translates the shims described above:
1180+
//
1181+
// bcx:
1182+
// invoke %func(%args...) normal %normal unwind %catch
1183+
//
1184+
// normal:
1185+
// ret null
1186+
//
1187+
// catch:
1188+
// (ptr, _) = landingpad
1189+
// ret ptr
11951190

1196-
// Define the "inner try" shim
1197-
let rust_try_inner = declare::define_internal_rust_fn(ccx,
1198-
"__rust_try_inner",
1199-
try_fn_ty);
1200-
trans_rust_try(ccx, rust_try_inner, lpad_ty, bcx.fcx.eh_personality(),
1201-
output, dloc, &mut |bcx, then, catch| {
1202-
let func = llvm::get_param(rust_try_inner, 0);
1203-
let data = llvm::get_param(rust_try_inner, 1);
1204-
Invoke(bcx, func, &[data], then.llbb, catch.llbb, None, dloc);
1205-
C_null(Type::i8p(ccx))
1206-
});
1207-
1208-
// Define the "outer try" shim.
1209-
let rust_try = declare::define_internal_rust_fn(ccx, "__rust_try",
1210-
try_fn_ty);
1191+
let rust_try = declare::define_internal_rust_fn(ccx, "__rust_try", try_fn_ty);
12111192
let catch_pers = match bcx.tcx().lang_items.eh_personality_catch() {
12121193
Some(did) => callee::trans_fn_ref(ccx, did, ExprId(0),
12131194
bcx.fcx.param_substs).val,
12141195
None => bcx.tcx().sess.bug("eh_personality_catch not defined"),
12151196
};
1216-
trans_rust_try(ccx, rust_try, lpad_ty, catch_pers, output, dloc,
1217-
&mut |bcx, then, catch| {
1218-
let func = llvm::get_param(rust_try, 0);
1219-
let data = llvm::get_param(rust_try, 1);
1220-
Invoke(bcx, rust_try_inner, &[func, data], then.llbb, catch.llbb,
1221-
None, dloc)
1222-
});
1223-
return rust_try
1224-
});
12251197

1226-
// Note that no invoke is used here because by definition this function
1227-
// can't panic (that's what it's catching).
1228-
let ret = Call(bcx, llfn, &[func, data], None, dloc);
1229-
Store(bcx, ret, dest);
1230-
return bcx;
1231-
1232-
// Translates both the inner and outer shims described above. The only
1233-
// difference between these two is the function invoked and the personality
1234-
// involved, so a common routine is shared.
1235-
//
1236-
// bcx:
1237-
// invoke %func(%args...) normal %normal unwind %unwind
1238-
//
1239-
// normal:
1240-
// ret null
1241-
//
1242-
// unwind:
1243-
// (ptr, _) = landingpad
1244-
// br (ptr != null), done, reraise
1245-
//
1246-
// done:
1247-
// ret ptr
1248-
//
1249-
// reraise:
1250-
// resume
1251-
//
1252-
// Note that the branch checking for `null` here isn't actually necessary,
1253-
// it's just an unfortunate hack to make sure that LLVM doesn't optimize too
1254-
// much. If this were not present, then LLVM would correctly deduce that our
1255-
// inner shim should be tagged with `nounwind` (as it catches all
1256-
// exceptions) and then the outer shim's `invoke` will be translated to just
1257-
// a simple call, destroying that entry for the personality function.
1258-
//
1259-
// To ensure that both shims always have an `invoke` this check against null
1260-
// confuses LLVM enough to the point that it won't infer `nounwind` and
1261-
// we'll proceed as normal.
1262-
fn trans_rust_try<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1263-
llfn: ValueRef,
1264-
lpad_ty: Type,
1265-
personality: ValueRef,
1266-
output: ty::FnOutput<'tcx>,
1267-
dloc: DebugLoc,
1268-
invoke: &mut FnMut(Block, Block, Block) -> ValueRef) {
12691198
let (fcx, block_arena);
12701199
block_arena = TypedArena::new();
1271-
fcx = new_fn_ctxt(ccx, llfn, ast::DUMMY_NODE_ID, false,
1200+
fcx = new_fn_ctxt(ccx, rust_try, ast::DUMMY_NODE_ID, false,
12721201
output, ccx.tcx().mk_substs(Substs::trans_empty()),
12731202
None, &block_arena);
12741203
let bcx = init_function(&fcx, true, output);
12751204
let then = bcx.fcx.new_temp_block("then");
12761205
let catch = bcx.fcx.new_temp_block("catch");
1277-
let reraise = bcx.fcx.new_temp_block("reraise");
1278-
let catch_return = bcx.fcx.new_temp_block("catch-return");
12791206

1280-
let invoke_ret = invoke(bcx, then, catch);
1281-
Ret(then, invoke_ret, dloc);
1282-
let vals = LandingPad(catch, lpad_ty, personality, 1);
1207+
let func = llvm::get_param(rust_try, 0);
1208+
let data = llvm::get_param(rust_try, 1);
1209+
Invoke(bcx, func, &[data], then.llbb, catch.llbb, None, dloc);
1210+
Ret(then, C_null(Type::i8p(ccx)), dloc);
1211+
1212+
// Type indicator for the exception being thrown.
1213+
// The first value in this tuple is a pointer to the exception object being thrown.
1214+
// The second value is a "selector" indicating which of the landing pad clauses
1215+
// the exception's type had been matched to. rust_try ignores the selector.
1216+
let lpad_ty = Type::struct_(ccx, &[Type::i8p(ccx), Type::i32(ccx)],
1217+
false);
1218+
let vals = LandingPad(catch, lpad_ty, catch_pers, 1);
12831219
AddClause(catch, vals, C_null(Type::i8p(ccx)));
12841220
let ptr = ExtractValue(catch, vals, 0);
1285-
let valid = ICmp(catch, llvm::IntNE, ptr, C_null(Type::i8p(ccx)), dloc);
1286-
CondBr(catch, valid, catch_return.llbb, reraise.llbb, dloc);
1287-
Ret(catch_return, ptr, dloc);
1288-
Resume(reraise, vals);
1289-
}
1221+
Ret(catch, ptr, dloc);
1222+
1223+
return rust_try
1224+
});
1225+
1226+
// Note that no invoke is used here because by definition this function
1227+
// can't panic (that's what it's catching).
1228+
let ret = Call(bcx, llfn, &[func, data], None, dloc);
1229+
Store(bcx, ret, dest);
1230+
return bcx;
12901231
}
12911232

1292-
// Helper to generate the `Ty` associated with `rust_Try`
1233+
// Helper to generate the `Ty` associated with `rust_try`
12931234
fn get_rust_try_fn<'a, 'tcx>(fcx: &FunctionContext<'a, 'tcx>,
12941235
f: &mut FnMut(Ty<'tcx>,
12951236
ty::FnOutput<'tcx>) -> ValueRef)
@@ -1299,8 +1240,7 @@ fn get_rust_try_fn<'a, 'tcx>(fcx: &FunctionContext<'a, 'tcx>,
12991240
return llfn
13001241
}
13011242

1302-
// Define the types up front for the signatures of the rust_try and
1303-
// rust_try_inner functions.
1243+
// Define the type up front for the signature of the rust_try function.
13041244
let tcx = ccx.tcx();
13051245
let i8p = tcx.mk_mut_ptr(tcx.types.i8);
13061246
let fn_ty = tcx.mk_bare_fn(ty::BareFnTy {

0 commit comments

Comments
 (0)