#include "X86.h"
#include "llvm/ADT/PostOrderIterator.h"
#include "llvm/Analysis/CFG.h"
#include "llvm/Analysis/EHPersonalities.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/CodeGen/WinEHFuncInfo.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/IntrinsicsX86.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/Support/Debug.h"
#include <deque>
using namespace llvm;
#define DEBUG_TYPE "winehstate"
namespace {
const int OverdefinedState = INT_MIN;
class WinEHStatePass : public FunctionPass {
public:
static char ID;
WinEHStatePass() : FunctionPass(ID) { }
bool runOnFunction(Function &Fn) override;
bool doInitialization(Module &M) override;
bool doFinalization(Module &M) override;
void getAnalysisUsage(AnalysisUsage &AU) const override;
StringRef getPassName() const override {
return "Windows 32-bit x86 EH state insertion";
}
private:
void emitExceptionRegistrationRecord(Function *F);
void linkExceptionRegistration(IRBuilder<> &Builder, Function *Handler);
void unlinkExceptionRegistration(IRBuilder<> &Builder);
void addStateStores(Function &F, WinEHFuncInfo &FuncInfo);
void insertStateNumberStore(Instruction *IP, int State);
Value *emitEHLSDA(IRBuilder<> &Builder, Function *F);
Function *generateLSDAInEAXThunk(Function *ParentFunc);
bool isStateStoreNeeded(EHPersonality Personality, CallBase &Call);
void rewriteSetJmpCall(IRBuilder<> &Builder, Function &F, CallBase &Call,
Value *State);
int getBaseStateForBB(DenseMap<BasicBlock *, ColorVector> &BlockColors,
WinEHFuncInfo &FuncInfo, BasicBlock *BB);
int getStateForCall(DenseMap<BasicBlock *, ColorVector> &BlockColors,
WinEHFuncInfo &FuncInfo, CallBase &Call);
Type *getEHLinkRegistrationType();
Type *getSEHRegistrationType();
Type *getCXXEHRegistrationType();
Module *TheModule = nullptr;
StructType *EHLinkRegistrationTy = nullptr;
StructType *CXXEHRegistrationTy = nullptr;
StructType *SEHRegistrationTy = nullptr;
FunctionCallee SetJmp3 = nullptr;
FunctionCallee CxxLongjmpUnwind = nullptr;
EHPersonality Personality = EHPersonality::Unknown;
Function *PersonalityFn = nullptr;
bool UseStackGuard = false;
int ParentBaseState = 0;
FunctionCallee SehLongjmpUnwind = nullptr;
Constant *Cookie = nullptr;
AllocaInst *RegNode = nullptr;
AllocaInst *EHGuardNode = nullptr;
int StateFieldIndex = ~0U;
Value *Link = nullptr;
};
}
FunctionPass *llvm::createX86WinEHStatePass() { return new WinEHStatePass(); }
char WinEHStatePass::ID = 0;
INITIALIZE_PASS(WinEHStatePass, "x86-winehstate",
"Insert stores for EH state numbers", false, false)
bool WinEHStatePass::doInitialization(Module &M) {
TheModule = &M;
return false;
}
bool WinEHStatePass::doFinalization(Module &M) {
assert(TheModule == &M);
TheModule = nullptr;
EHLinkRegistrationTy = nullptr;
CXXEHRegistrationTy = nullptr;
SEHRegistrationTy = nullptr;
SetJmp3 = nullptr;
CxxLongjmpUnwind = nullptr;
SehLongjmpUnwind = nullptr;
Cookie = nullptr;
return false;
}
void WinEHStatePass::getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
}
bool WinEHStatePass::runOnFunction(Function &F) {
if (F.hasAvailableExternallyLinkage())
return false;
if (!F.hasPersonalityFn())
return false;
PersonalityFn =
dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
if (!PersonalityFn)
return false;
Personality = classifyEHPersonality(PersonalityFn);
if (!isFuncletEHPersonality(Personality))
return false;
bool HasPads = false;
for (BasicBlock &BB : F) {
if (BB.isEHPad()) {
HasPads = true;
break;
}
}
if (!HasPads)
return false;
Type *Int8PtrType = Type::getInt8PtrTy(TheModule->getContext());
SetJmp3 = TheModule->getOrInsertFunction(
"_setjmp3", FunctionType::get(
Type::getInt32Ty(TheModule->getContext()),
{Int8PtrType, Type::getInt32Ty(TheModule->getContext())},
true));
emitExceptionRegistrationRecord(&F);
WinEHFuncInfo FuncInfo;
addStateStores(F, FuncInfo);
PersonalityFn = nullptr;
Personality = EHPersonality::Unknown;
UseStackGuard = false;
RegNode = nullptr;
EHGuardNode = nullptr;
return true;
}
Type *WinEHStatePass::getEHLinkRegistrationType() {
if (EHLinkRegistrationTy)
return EHLinkRegistrationTy;
LLVMContext &Context = TheModule->getContext();
EHLinkRegistrationTy = StructType::create(Context, "EHRegistrationNode");
Type *FieldTys[] = {
EHLinkRegistrationTy->getPointerTo(0), Type::getInt8PtrTy(Context) };
EHLinkRegistrationTy->setBody(FieldTys, false);
return EHLinkRegistrationTy;
}
Type *WinEHStatePass::getCXXEHRegistrationType() {
if (CXXEHRegistrationTy)
return CXXEHRegistrationTy;
LLVMContext &Context = TheModule->getContext();
Type *FieldTys[] = {
Type::getInt8PtrTy(Context), getEHLinkRegistrationType(), Type::getInt32Ty(Context) };
CXXEHRegistrationTy =
StructType::create(FieldTys, "CXXExceptionRegistration");
return CXXEHRegistrationTy;
}
Type *WinEHStatePass::getSEHRegistrationType() {
if (SEHRegistrationTy)
return SEHRegistrationTy;
LLVMContext &Context = TheModule->getContext();
Type *FieldTys[] = {
Type::getInt8PtrTy(Context), Type::getInt8PtrTy(Context), getEHLinkRegistrationType(), Type::getInt32Ty(Context), Type::getInt32Ty(Context) };
SEHRegistrationTy = StructType::create(FieldTys, "SEHExceptionRegistration");
return SEHRegistrationTy;
}
void WinEHStatePass::emitExceptionRegistrationRecord(Function *F) {
assert(Personality == EHPersonality::MSVC_CXX ||
Personality == EHPersonality::MSVC_X86SEH);
Type *RegNodeTy;
IRBuilder<> Builder(&F->getEntryBlock(), F->getEntryBlock().begin());
Type *Int8PtrType = Builder.getInt8PtrTy();
Type *Int32Ty = Builder.getInt32Ty();
Type *VoidTy = Builder.getVoidTy();
if (Personality == EHPersonality::MSVC_CXX) {
RegNodeTy = getCXXEHRegistrationType();
RegNode = Builder.CreateAlloca(RegNodeTy);
Value *SP = Builder.CreateCall(
Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
StateFieldIndex = 2;
ParentBaseState = -1;
insertStateNumberStore(&*Builder.GetInsertPoint(), ParentBaseState);
Function *Trampoline = generateLSDAInEAXThunk(F);
Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 1);
linkExceptionRegistration(Builder, Trampoline);
CxxLongjmpUnwind = TheModule->getOrInsertFunction(
"__CxxLongjmpUnwind",
FunctionType::get(VoidTy, Int8PtrType, false));
cast<Function>(CxxLongjmpUnwind.getCallee()->stripPointerCasts())
->setCallingConv(CallingConv::X86_StdCall);
} else if (Personality == EHPersonality::MSVC_X86SEH) {
StringRef PersonalityName = PersonalityFn->getName();
UseStackGuard = (PersonalityName == "_except_handler4");
RegNodeTy = getSEHRegistrationType();
RegNode = Builder.CreateAlloca(RegNodeTy);
if (UseStackGuard)
EHGuardNode = Builder.CreateAlloca(Int32Ty);
Value *SP = Builder.CreateCall(
Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
StateFieldIndex = 4;
ParentBaseState = UseStackGuard ? -2 : -1;
insertStateNumberStore(&*Builder.GetInsertPoint(), ParentBaseState);
Value *LSDA = emitEHLSDA(Builder, F);
LSDA = Builder.CreatePtrToInt(LSDA, Int32Ty);
if (UseStackGuard) {
Cookie = TheModule->getOrInsertGlobal("__security_cookie", Int32Ty);
Value *Val = Builder.CreateLoad(Int32Ty, Cookie, "cookie");
LSDA = Builder.CreateXor(LSDA, Val);
}
Builder.CreateStore(LSDA, Builder.CreateStructGEP(RegNodeTy, RegNode, 3));
if (UseStackGuard) {
Value *Val = Builder.CreateLoad(Int32Ty, Cookie);
Value *FrameAddr = Builder.CreateCall(
Intrinsic::getDeclaration(
TheModule, Intrinsic::frameaddress,
Builder.getInt8PtrTy(
TheModule->getDataLayout().getAllocaAddrSpace())),
Builder.getInt32(0), "frameaddr");
Value *FrameAddrI32 = Builder.CreatePtrToInt(FrameAddr, Int32Ty);
FrameAddrI32 = Builder.CreateXor(FrameAddrI32, Val);
Builder.CreateStore(FrameAddrI32, EHGuardNode);
}
Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 2);
linkExceptionRegistration(Builder, PersonalityFn);
SehLongjmpUnwind = TheModule->getOrInsertFunction(
UseStackGuard ? "_seh_longjmp_unwind4" : "_seh_longjmp_unwind",
FunctionType::get(Type::getVoidTy(TheModule->getContext()), Int8PtrType,
false));
cast<Function>(SehLongjmpUnwind.getCallee()->stripPointerCasts())
->setCallingConv(CallingConv::X86_StdCall);
} else {
llvm_unreachable("unexpected personality function");
}
for (BasicBlock &BB : *F) {
Instruction *T = BB.getTerminator();
if (!isa<ReturnInst>(T))
continue;
Builder.SetInsertPoint(T);
unlinkExceptionRegistration(Builder);
}
}
Value *WinEHStatePass::emitEHLSDA(IRBuilder<> &Builder, Function *F) {
Value *FI8 = Builder.CreateBitCast(F, Type::getInt8PtrTy(F->getContext()));
return Builder.CreateCall(
Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
}
Function *WinEHStatePass::generateLSDAInEAXThunk(Function *ParentFunc) {
LLVMContext &Context = ParentFunc->getContext();
Type *Int32Ty = Type::getInt32Ty(Context);
Type *Int8PtrType = Type::getInt8PtrTy(Context);
Type *ArgTys[5] = {Int8PtrType, Int8PtrType, Int8PtrType, Int8PtrType,
Int8PtrType};
FunctionType *TrampolineTy =
FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 4),
false);
FunctionType *TargetFuncTy =
FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 5),
false);
Function *Trampoline =
Function::Create(TrampolineTy, GlobalValue::InternalLinkage,
Twine("__ehhandler$") + GlobalValue::dropLLVMManglingEscape(
ParentFunc->getName()),
TheModule);
if (auto *C = ParentFunc->getComdat())
Trampoline->setComdat(C);
BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", Trampoline);
IRBuilder<> Builder(EntryBB);
Value *LSDA = emitEHLSDA(Builder, ParentFunc);
Value *CastPersonality =
Builder.CreateBitCast(PersonalityFn, TargetFuncTy->getPointerTo());
auto AI = Trampoline->arg_begin();
Value *Args[5] = {LSDA, &*AI++, &*AI++, &*AI++, &*AI++};
CallInst *Call = Builder.CreateCall(TargetFuncTy, CastPersonality, Args);
Call->setTailCall(true);
Call->addParamAttr(0, Attribute::InReg);
Builder.CreateRet(Call);
return Trampoline;
}
void WinEHStatePass::linkExceptionRegistration(IRBuilder<> &Builder,
Function *Handler) {
Handler->addFnAttr("safeseh");
Type *LinkTy = getEHLinkRegistrationType();
Value *HandlerI8 = Builder.CreateBitCast(Handler, Builder.getInt8PtrTy());
Builder.CreateStore(HandlerI8, Builder.CreateStructGEP(LinkTy, Link, 1));
Constant *FSZero =
Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
Value *Next = Builder.CreateLoad(LinkTy->getPointerTo(), FSZero);
Builder.CreateStore(Next, Builder.CreateStructGEP(LinkTy, Link, 0));
Builder.CreateStore(Link, FSZero);
}
void WinEHStatePass::unlinkExceptionRegistration(IRBuilder<> &Builder) {
if (auto *GEP = dyn_cast<GetElementPtrInst>(Link)) {
GEP = cast<GetElementPtrInst>(GEP->clone());
Builder.Insert(GEP);
Link = GEP;
}
Type *LinkTy = getEHLinkRegistrationType();
Value *Next = Builder.CreateLoad(LinkTy->getPointerTo(),
Builder.CreateStructGEP(LinkTy, Link, 0));
Constant *FSZero =
Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
Builder.CreateStore(Next, FSZero);
}
void WinEHStatePass::rewriteSetJmpCall(IRBuilder<> &Builder, Function &F,
CallBase &Call, Value *State) {
if (Call.arg_size() != 2)
return;
SmallVector<OperandBundleDef, 1> OpBundles;
Call.getOperandBundlesAsDefs(OpBundles);
SmallVector<Value *, 3> OptionalArgs;
if (Personality == EHPersonality::MSVC_CXX) {
OptionalArgs.push_back(CxxLongjmpUnwind.getCallee());
OptionalArgs.push_back(State);
OptionalArgs.push_back(emitEHLSDA(Builder, &F));
} else if (Personality == EHPersonality::MSVC_X86SEH) {
OptionalArgs.push_back(SehLongjmpUnwind.getCallee());
OptionalArgs.push_back(State);
if (UseStackGuard)
OptionalArgs.push_back(Cookie);
} else {
llvm_unreachable("unhandled personality!");
}
SmallVector<Value *, 5> Args;
Args.push_back(
Builder.CreateBitCast(Call.getArgOperand(0), Builder.getInt8PtrTy()));
Args.push_back(Builder.getInt32(OptionalArgs.size()));
Args.append(OptionalArgs.begin(), OptionalArgs.end());
CallBase *NewCall;
if (auto *CI = dyn_cast<CallInst>(&Call)) {
CallInst *NewCI = Builder.CreateCall(SetJmp3, Args, OpBundles);
NewCI->setTailCallKind(CI->getTailCallKind());
NewCall = NewCI;
} else {
auto *II = cast<InvokeInst>(&Call);
NewCall = Builder.CreateInvoke(
SetJmp3, II->getNormalDest(), II->getUnwindDest(), Args, OpBundles);
}
NewCall->setCallingConv(Call.getCallingConv());
NewCall->setAttributes(Call.getAttributes());
NewCall->setDebugLoc(Call.getDebugLoc());
NewCall->takeName(&Call);
Call.replaceAllUsesWith(NewCall);
Call.eraseFromParent();
}
int WinEHStatePass::getBaseStateForBB(
DenseMap<BasicBlock *, ColorVector> &BlockColors, WinEHFuncInfo &FuncInfo,
BasicBlock *BB) {
int BaseState = ParentBaseState;
auto &BBColors = BlockColors[BB];
assert(BBColors.size() == 1 && "multi-color BB not removed by preparation");
BasicBlock *FuncletEntryBB = BBColors.front();
if (auto *FuncletPad =
dyn_cast<FuncletPadInst>(FuncletEntryBB->getFirstNonPHI())) {
auto BaseStateI = FuncInfo.FuncletBaseStateMap.find(FuncletPad);
if (BaseStateI != FuncInfo.FuncletBaseStateMap.end())
BaseState = BaseStateI->second;
}
return BaseState;
}
int WinEHStatePass::getStateForCall(
DenseMap<BasicBlock *, ColorVector> &BlockColors, WinEHFuncInfo &FuncInfo,
CallBase &Call) {
if (auto *II = dyn_cast<InvokeInst>(&Call)) {
assert(FuncInfo.InvokeStateMap.count(II) && "invoke has no state!");
return FuncInfo.InvokeStateMap[II];
}
return getBaseStateForBB(BlockColors, FuncInfo, Call.getParent());
}
static int getPredState(DenseMap<BasicBlock *, int> &FinalStates, Function &F,
int ParentBaseState, BasicBlock *BB) {
if (&F.getEntryBlock() == BB)
return ParentBaseState;
if (BB->isEHPad())
return OverdefinedState;
int CommonState = OverdefinedState;
for (BasicBlock *PredBB : predecessors(BB)) {
auto PredEndState = FinalStates.find(PredBB);
if (PredEndState == FinalStates.end())
return OverdefinedState;
if (isa<CatchReturnInst>(PredBB->getTerminator()))
return OverdefinedState;
int PredState = PredEndState->second;
assert(PredState != OverdefinedState &&
"overdefined BBs shouldn't be in FinalStates");
if (CommonState == OverdefinedState)
CommonState = PredState;
if (CommonState != PredState)
return OverdefinedState;
}
return CommonState;
}
static int getSuccState(DenseMap<BasicBlock *, int> &InitialStates, Function &F,
int ParentBaseState, BasicBlock *BB) {
if (isa<CatchReturnInst>(BB->getTerminator()))
return OverdefinedState;
int CommonState = OverdefinedState;
for (BasicBlock *SuccBB : successors(BB)) {
auto SuccStartState = InitialStates.find(SuccBB);
if (SuccStartState == InitialStates.end())
return OverdefinedState;
if (SuccBB->isEHPad())
return OverdefinedState;
int SuccState = SuccStartState->second;
assert(SuccState != OverdefinedState &&
"overdefined BBs shouldn't be in FinalStates");
if (CommonState == OverdefinedState)
CommonState = SuccState;
if (CommonState != SuccState)
return OverdefinedState;
}
return CommonState;
}
bool WinEHStatePass::isStateStoreNeeded(EHPersonality Personality,
CallBase &Call) {
if (isAsynchronousEHPersonality(Personality))
return !Call.doesNotAccessMemory();
return !Call.doesNotThrow();
}
void WinEHStatePass::addStateStores(Function &F, WinEHFuncInfo &FuncInfo) {
IRBuilder<> Builder(RegNode->getNextNode());
Value *RegNodeI8 = Builder.CreateBitCast(RegNode, Builder.getInt8PtrTy());
Builder.CreateCall(
Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_ehregnode),
{RegNodeI8});
if (EHGuardNode) {
IRBuilder<> Builder(EHGuardNode->getNextNode());
Value *EHGuardNodeI8 =
Builder.CreateBitCast(EHGuardNode, Builder.getInt8PtrTy());
Builder.CreateCall(
Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_ehguard),
{EHGuardNodeI8});
}
if (isAsynchronousEHPersonality(Personality))
calculateSEHStateNumbers(&F, FuncInfo);
else
calculateWinCXXEHStateNumbers(&F, FuncInfo);
DenseMap<BasicBlock *, ColorVector> BlockColors = colorEHFunclets(F);
ReversePostOrderTraversal<Function *> RPOT(&F);
DenseMap<BasicBlock *, int> InitialStates;
DenseMap<BasicBlock *, int> FinalStates;
std::deque<BasicBlock *> Worklist;
for (BasicBlock *BB : RPOT) {
int InitialState = OverdefinedState;
int FinalState;
if (&F.getEntryBlock() == BB)
InitialState = FinalState = ParentBaseState;
for (Instruction &I : *BB) {
auto *Call = dyn_cast<CallBase>(&I);
if (!Call || !isStateStoreNeeded(Personality, *Call))
continue;
int State = getStateForCall(BlockColors, FuncInfo, *Call);
if (InitialState == OverdefinedState)
InitialState = State;
FinalState = State;
}
if (InitialState == OverdefinedState) {
Worklist.push_back(BB);
continue;
}
LLVM_DEBUG(dbgs() << "X86WinEHState: " << BB->getName()
<< " InitialState=" << InitialState << '\n');
LLVM_DEBUG(dbgs() << "X86WinEHState: " << BB->getName()
<< " FinalState=" << FinalState << '\n');
InitialStates.insert({BB, InitialState});
FinalStates.insert({BB, FinalState});
}
while (!Worklist.empty()) {
BasicBlock *BB = Worklist.front();
Worklist.pop_front();
if (InitialStates.count(BB) != 0)
continue;
int PredState = getPredState(FinalStates, F, ParentBaseState, BB);
if (PredState == OverdefinedState)
continue;
InitialStates.insert({BB, PredState});
FinalStates.insert({BB, PredState});
for (BasicBlock *SuccBB : successors(BB))
Worklist.push_back(SuccBB);
}
for (BasicBlock *BB : RPOT) {
int SuccState = getSuccState(InitialStates, F, ParentBaseState, BB);
if (SuccState == OverdefinedState)
continue;
FinalStates.insert({BB, SuccState});
}
for (BasicBlock *BB : RPOT) {
auto &BBColors = BlockColors[BB];
BasicBlock *FuncletEntryBB = BBColors.front();
if (isa<CleanupPadInst>(FuncletEntryBB->getFirstNonPHI()))
continue;
int PrevState = getPredState(FinalStates, F, ParentBaseState, BB);
LLVM_DEBUG(dbgs() << "X86WinEHState: " << BB->getName()
<< " PrevState=" << PrevState << '\n');
for (Instruction &I : *BB) {
auto *Call = dyn_cast<CallBase>(&I);
if (!Call || !isStateStoreNeeded(Personality, *Call))
continue;
int State = getStateForCall(BlockColors, FuncInfo, *Call);
if (State != PrevState)
insertStateNumberStore(&I, State);
PrevState = State;
}
auto EndState = FinalStates.find(BB);
if (EndState != FinalStates.end())
if (EndState->second != PrevState)
insertStateNumberStore(BB->getTerminator(), EndState->second);
}
SmallVector<CallBase *, 1> SetJmp3Calls;
for (BasicBlock *BB : RPOT) {
for (Instruction &I : *BB) {
auto *Call = dyn_cast<CallBase>(&I);
if (!Call)
continue;
if (Call->getCalledOperand()->stripPointerCasts() !=
SetJmp3.getCallee()->stripPointerCasts())
continue;
SetJmp3Calls.push_back(Call);
}
}
for (CallBase *Call : SetJmp3Calls) {
auto &BBColors = BlockColors[Call->getParent()];
BasicBlock *FuncletEntryBB = BBColors.front();
bool InCleanup = isa<CleanupPadInst>(FuncletEntryBB->getFirstNonPHI());
IRBuilder<> Builder(Call);
Value *State;
if (InCleanup) {
Value *StateField = Builder.CreateStructGEP(RegNode->getAllocatedType(),
RegNode, StateFieldIndex);
State = Builder.CreateLoad(Builder.getInt32Ty(), StateField);
} else {
State = Builder.getInt32(getStateForCall(BlockColors, FuncInfo, *Call));
}
rewriteSetJmpCall(Builder, F, *Call, State);
}
}
void WinEHStatePass::insertStateNumberStore(Instruction *IP, int State) {
IRBuilder<> Builder(IP);
Value *StateField = Builder.CreateStructGEP(RegNode->getAllocatedType(),
RegNode, StateFieldIndex);
Builder.CreateStore(Builder.getInt32(State), StateField);
}