1 //===-- CodeGen/AsmPrinter/Win64Exception.cpp - Dwarf Exception Impl ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for writing Win64 exception info into asm files.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "Win64Exception.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/CodeGen/AsmPrinter.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineModuleInfo.h"
22 #include "llvm/CodeGen/WinEHFuncInfo.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/Mangler.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCContext.h"
28 #include "llvm/MC/MCExpr.h"
29 #include "llvm/MC/MCSection.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/MC/MCSymbol.h"
32 #include "llvm/Support/Dwarf.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/FormattedStream.h"
35 #include "llvm/Target/TargetFrameLowering.h"
36 #include "llvm/Target/TargetLoweringObjectFile.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 using namespace llvm;
40 
Win64Exception(AsmPrinter * A)41 Win64Exception::Win64Exception(AsmPrinter *A)
42   : EHStreamer(A), shouldEmitPersonality(false), shouldEmitLSDA(false),
43     shouldEmitMoves(false) {}
44 
~Win64Exception()45 Win64Exception::~Win64Exception() {}
46 
47 /// endModule - Emit all exception information that should come after the
48 /// content.
endModule()49 void Win64Exception::endModule() {
50 }
51 
beginFunction(const MachineFunction * MF)52 void Win64Exception::beginFunction(const MachineFunction *MF) {
53   shouldEmitMoves = shouldEmitPersonality = shouldEmitLSDA = false;
54 
55   // If any landing pads survive, we need an EH table.
56   bool hasLandingPads = !MMI->getLandingPads().empty();
57 
58   shouldEmitMoves = Asm->needsSEHMoves();
59 
60   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
61   unsigned PerEncoding = TLOF.getPersonalityEncoding();
62   const Function *Per = MF->getMMI().getPersonality();
63 
64   shouldEmitPersonality = hasLandingPads &&
65     PerEncoding != dwarf::DW_EH_PE_omit && Per;
66 
67   unsigned LSDAEncoding = TLOF.getLSDAEncoding();
68   shouldEmitLSDA = shouldEmitPersonality &&
69     LSDAEncoding != dwarf::DW_EH_PE_omit;
70 
71 
72   // If this was an outlined handler, we need to define the label corresponding
73   // to the offset of the parent frame relative to the stack pointer after the
74   // prologue.
75   const Function *F = MF->getFunction();
76   const Function *ParentF = MMI->getWinEHParent(F);
77   if (F != ParentF) {
78     WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(ParentF);
79     auto I = FuncInfo.CatchHandlerParentFrameObjOffset.find(F);
80     if (I != FuncInfo.CatchHandlerParentFrameObjOffset.end()) {
81       MCSymbol *HandlerTypeParentFrameOffset =
82           Asm->OutContext.getOrCreateParentFrameOffsetSymbol(
83               GlobalValue::getRealLinkageName(F->getName()));
84 
85       // Emit a symbol assignment.
86       Asm->OutStreamer.EmitAssignment(
87           HandlerTypeParentFrameOffset,
88           MCConstantExpr::Create(I->second, Asm->OutContext));
89     }
90   }
91 
92   if (!shouldEmitPersonality && !shouldEmitMoves)
93     return;
94 
95   Asm->OutStreamer.EmitWinCFIStartProc(Asm->CurrentFnSym);
96 
97   if (!shouldEmitPersonality)
98     return;
99 
100   const MCSymbol *PersHandlerSym =
101       TLOF.getCFIPersonalitySymbol(Per, *Asm->Mang, Asm->TM, MMI);
102   Asm->OutStreamer.EmitWinEHHandler(PersHandlerSym, true, true);
103 }
104 
105 /// endFunction - Gather and emit post-function exception information.
106 ///
endFunction(const MachineFunction * MF)107 void Win64Exception::endFunction(const MachineFunction *MF) {
108   if (!shouldEmitPersonality && !shouldEmitMoves)
109     return;
110 
111   EHPersonality Per = MMI->getPersonalityType();
112 
113   // Get rid of any dead landing pads if we're not using a Windows EH scheme. In
114   // Windows EH schemes, the landing pad is not actually reachable. It only
115   // exists so that we can emit the right table data.
116   if (!isMSVCEHPersonality(Per))
117     MMI->TidyLandingPads();
118 
119   if (shouldEmitPersonality) {
120     Asm->OutStreamer.PushSection();
121 
122     // Emit an UNWIND_INFO struct describing the prologue.
123     Asm->OutStreamer.EmitWinEHHandlerData();
124 
125     // Emit the tables appropriate to the personality function in use. If we
126     // don't recognize the personality, assume it uses an Itanium-style LSDA.
127     if (Per == EHPersonality::MSVC_Win64SEH)
128       emitCSpecificHandlerTable();
129     else if (Per == EHPersonality::MSVC_CXX)
130       emitCXXFrameHandler3Table(MF);
131     else
132       emitExceptionTable();
133 
134     Asm->OutStreamer.PopSection();
135   }
136   Asm->OutStreamer.EmitWinCFIEndProc();
137 }
138 
createImageRel32(const MCSymbol * Value)139 const MCExpr *Win64Exception::createImageRel32(const MCSymbol *Value) {
140   if (!Value)
141     return MCConstantExpr::Create(0, Asm->OutContext);
142   return MCSymbolRefExpr::Create(Value, MCSymbolRefExpr::VK_COFF_IMGREL32,
143                                  Asm->OutContext);
144 }
145 
createImageRel32(const GlobalValue * GV)146 const MCExpr *Win64Exception::createImageRel32(const GlobalValue *GV) {
147   if (!GV)
148     return MCConstantExpr::Create(0, Asm->OutContext);
149   return createImageRel32(Asm->getSymbol(GV));
150 }
151 
152 /// Emit the language-specific data that __C_specific_handler expects.  This
153 /// handler lives in the x64 Microsoft C runtime and allows catching or cleaning
154 /// up after faults with __try, __except, and __finally.  The typeinfo values
155 /// are not really RTTI data, but pointers to filter functions that return an
156 /// integer (1, 0, or -1) indicating how to handle the exception. For __finally
157 /// blocks and other cleanups, the landing pad label is zero, and the filter
158 /// function is actually a cleanup handler with the same prototype.  A catch-all
159 /// entry is modeled with a null filter function field and a non-zero landing
160 /// pad label.
161 ///
162 /// Possible filter function return values:
163 ///   EXCEPTION_EXECUTE_HANDLER (1):
164 ///     Jump to the landing pad label after cleanups.
165 ///   EXCEPTION_CONTINUE_SEARCH (0):
166 ///     Continue searching this table or continue unwinding.
167 ///   EXCEPTION_CONTINUE_EXECUTION (-1):
168 ///     Resume execution at the trapping PC.
169 ///
170 /// Inferred table structure:
171 ///   struct Table {
172 ///     int NumEntries;
173 ///     struct Entry {
174 ///       imagerel32 LabelStart;
175 ///       imagerel32 LabelEnd;
176 ///       imagerel32 FilterOrFinally;  // One means catch-all.
177 ///       imagerel32 LabelLPad;        // Zero means __finally.
178 ///     } Entries[NumEntries];
179 ///   };
emitCSpecificHandlerTable()180 void Win64Exception::emitCSpecificHandlerTable() {
181   const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
182 
183   // Simplifying assumptions for first implementation:
184   // - Cleanups are not implemented.
185   // - Filters are not implemented.
186 
187   // The Itanium LSDA table sorts similar landing pads together to simplify the
188   // actions table, but we don't need that.
189   SmallVector<const LandingPadInfo *, 64> LandingPads;
190   LandingPads.reserve(PadInfos.size());
191   for (const auto &LP : PadInfos)
192     LandingPads.push_back(&LP);
193 
194   // Compute label ranges for call sites as we would for the Itanium LSDA, but
195   // use an all zero action table because we aren't using these actions.
196   SmallVector<unsigned, 64> FirstActions;
197   FirstActions.resize(LandingPads.size());
198   SmallVector<CallSiteEntry, 64> CallSites;
199   computeCallSiteTable(CallSites, LandingPads, FirstActions);
200 
201   MCSymbol *EHFuncBeginSym = Asm->getFunctionBegin();
202   MCSymbol *EHFuncEndSym = Asm->getFunctionEnd();
203 
204   // Emit the number of table entries.
205   unsigned NumEntries = 0;
206   for (const CallSiteEntry &CSE : CallSites) {
207     if (!CSE.LPad)
208       continue; // Ignore gaps.
209     for (int Selector : CSE.LPad->TypeIds) {
210       // Ignore C++ filter clauses in SEH.
211       // FIXME: Implement cleanup clauses.
212       if (isCatchEHSelector(Selector))
213         ++NumEntries;
214     }
215   }
216   Asm->OutStreamer.EmitIntValue(NumEntries, 4);
217 
218   // Emit the four-label records for each call site entry. The table has to be
219   // sorted in layout order, and the call sites should already be sorted.
220   for (const CallSiteEntry &CSE : CallSites) {
221     // Ignore gaps. Unlike the Itanium model, unwinding through a frame without
222     // an EH table entry will propagate the exception rather than terminating
223     // the program.
224     if (!CSE.LPad)
225       continue;
226     const LandingPadInfo *LPad = CSE.LPad;
227 
228     // Compute the label range. We may reuse the function begin and end labels
229     // rather than forming new ones.
230     const MCExpr *Begin =
231         createImageRel32(CSE.BeginLabel ? CSE.BeginLabel : EHFuncBeginSym);
232     const MCExpr *End;
233     if (CSE.EndLabel) {
234       // The interval is half-open, so we have to add one to include the return
235       // address of the last invoke in the range.
236       End = MCBinaryExpr::CreateAdd(createImageRel32(CSE.EndLabel),
237                                     MCConstantExpr::Create(1, Asm->OutContext),
238                                     Asm->OutContext);
239     } else {
240       End = createImageRel32(EHFuncEndSym);
241     }
242 
243     // These aren't really type info globals, they are actually pointers to
244     // filter functions ordered by selector. The zero selector is used for
245     // cleanups, so slot zero corresponds to selector 1.
246     const std::vector<const GlobalValue *> &SelectorToFilter = MMI->getTypeInfos();
247 
248     // Do a parallel iteration across typeids and clause labels, skipping filter
249     // clauses.
250     size_t NextClauseLabel = 0;
251     for (size_t I = 0, E = LPad->TypeIds.size(); I < E; ++I) {
252       // AddLandingPadInfo stores the clauses in reverse, but there is a FIXME
253       // to change that.
254       int Selector = LPad->TypeIds[E - I - 1];
255 
256       // Ignore C++ filter clauses in SEH.
257       // FIXME: Implement cleanup clauses.
258       if (!isCatchEHSelector(Selector))
259         continue;
260 
261       Asm->OutStreamer.EmitValue(Begin, 4);
262       Asm->OutStreamer.EmitValue(End, 4);
263       if (isCatchEHSelector(Selector)) {
264         assert(unsigned(Selector - 1) < SelectorToFilter.size());
265         const GlobalValue *TI = SelectorToFilter[Selector - 1];
266         if (TI) // Emit the filter function pointer.
267           Asm->OutStreamer.EmitValue(createImageRel32(Asm->getSymbol(TI)), 4);
268         else  // Otherwise, this is a "catch i8* null", or catch all.
269           Asm->OutStreamer.EmitIntValue(1, 4);
270       }
271       MCSymbol *ClauseLabel = LPad->ClauseLabels[NextClauseLabel++];
272       Asm->OutStreamer.EmitValue(createImageRel32(ClauseLabel), 4);
273     }
274   }
275 }
276 
emitCXXFrameHandler3Table(const MachineFunction * MF)277 void Win64Exception::emitCXXFrameHandler3Table(const MachineFunction *MF) {
278   const Function *F = MF->getFunction();
279   const Function *ParentF = MMI->getWinEHParent(F);
280   auto &OS = Asm->OutStreamer;
281   WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(ParentF);
282 
283   StringRef ParentLinkageName =
284       GlobalValue::getRealLinkageName(ParentF->getName());
285 
286   MCSymbol *FuncInfoXData =
287       Asm->OutContext.GetOrCreateSymbol(Twine("$cppxdata$", ParentLinkageName));
288   OS.EmitValue(createImageRel32(FuncInfoXData), 4);
289 
290   // The Itanium LSDA table sorts similar landing pads together to simplify the
291   // actions table, but we don't need that.
292   SmallVector<const LandingPadInfo *, 64> LandingPads;
293   const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
294   LandingPads.reserve(PadInfos.size());
295   for (const auto &LP : PadInfos)
296     LandingPads.push_back(&LP);
297 
298   RangeMapType PadMap;
299   computePadMap(LandingPads, PadMap);
300 
301   // The end label of the previous invoke or nounwind try-range.
302   MCSymbol *LastLabel = Asm->getFunctionBegin();
303 
304   // Whether there is a potentially throwing instruction (currently this means
305   // an ordinary call) between the end of the previous try-range and now.
306   bool SawPotentiallyThrowing = false;
307 
308   int LastEHState = -2;
309 
310   // The parent function and the catch handlers contribute to the 'ip2state'
311   // table.
312   for (const auto &MBB : *MF) {
313     for (const auto &MI : MBB) {
314       if (!MI.isEHLabel()) {
315         if (MI.isCall())
316           SawPotentiallyThrowing |= !callToNoUnwindFunction(&MI);
317         continue;
318       }
319 
320       // End of the previous try-range?
321       MCSymbol *BeginLabel = MI.getOperand(0).getMCSymbol();
322       if (BeginLabel == LastLabel)
323         SawPotentiallyThrowing = false;
324 
325       // Beginning of a new try-range?
326       RangeMapType::const_iterator L = PadMap.find(BeginLabel);
327       if (L == PadMap.end())
328         // Nope, it was just some random label.
329         continue;
330 
331       const PadRange &P = L->second;
332       const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
333       assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
334              "Inconsistent landing pad map!");
335 
336       if (SawPotentiallyThrowing) {
337         FuncInfo.IPToStateList.push_back(std::make_pair(LastLabel, -1));
338         SawPotentiallyThrowing = false;
339         LastEHState = -1;
340       }
341 
342       if (LandingPad->WinEHState != LastEHState)
343         FuncInfo.IPToStateList.push_back(
344             std::make_pair(BeginLabel, LandingPad->WinEHState));
345       LastEHState = LandingPad->WinEHState;
346       LastLabel = LandingPad->EndLabels[P.RangeIndex];
347     }
348   }
349 
350   // Defer emission until we've visited the parent function and all the catch
351   // handlers.  Cleanups don't contribute to the ip2state table yet, so don't
352   // count them.
353   if (ParentF != F && !FuncInfo.CatchHandlerMaxState.count(F))
354     return;
355   ++FuncInfo.NumIPToStateFuncsVisited;
356   if (FuncInfo.NumIPToStateFuncsVisited != FuncInfo.CatchHandlerMaxState.size())
357     return;
358 
359   MCSymbol *UnwindMapXData = nullptr;
360   MCSymbol *TryBlockMapXData = nullptr;
361   MCSymbol *IPToStateXData = nullptr;
362   if (!FuncInfo.UnwindMap.empty())
363     UnwindMapXData = Asm->OutContext.GetOrCreateSymbol(
364         Twine("$stateUnwindMap$", ParentLinkageName));
365   if (!FuncInfo.TryBlockMap.empty())
366     TryBlockMapXData = Asm->OutContext.GetOrCreateSymbol(
367         Twine("$tryMap$", ParentLinkageName));
368   if (!FuncInfo.IPToStateList.empty())
369     IPToStateXData = Asm->OutContext.GetOrCreateSymbol(
370         Twine("$ip2state$", ParentLinkageName));
371 
372   // FuncInfo {
373   //   uint32_t           MagicNumber
374   //   int32_t            MaxState;
375   //   UnwindMapEntry    *UnwindMap;
376   //   uint32_t           NumTryBlocks;
377   //   TryBlockMapEntry  *TryBlockMap;
378   //   uint32_t           IPMapEntries;
379   //   IPToStateMapEntry *IPToStateMap;
380   //   uint32_t           UnwindHelp; // (x64/ARM only)
381   //   ESTypeList        *ESTypeList;
382   //   int32_t            EHFlags;
383   // }
384   // EHFlags & 1 -> Synchronous exceptions only, no async exceptions.
385   // EHFlags & 2 -> ???
386   // EHFlags & 4 -> The function is noexcept(true), unwinding can't continue.
387   OS.EmitLabel(FuncInfoXData);
388   OS.EmitIntValue(0x19930522, 4);                      // MagicNumber
389   OS.EmitIntValue(FuncInfo.UnwindMap.size(), 4);       // MaxState
390   OS.EmitValue(createImageRel32(UnwindMapXData), 4);   // UnwindMap
391   OS.EmitIntValue(FuncInfo.TryBlockMap.size(), 4);     // NumTryBlocks
392   OS.EmitValue(createImageRel32(TryBlockMapXData), 4); // TryBlockMap
393   OS.EmitIntValue(FuncInfo.IPToStateList.size(), 4);   // IPMapEntries
394   OS.EmitValue(createImageRel32(IPToStateXData), 4);   // IPToStateMap
395   OS.EmitIntValue(FuncInfo.UnwindHelpFrameOffset, 4);  // UnwindHelp
396   OS.EmitIntValue(0, 4);                               // ESTypeList
397   OS.EmitIntValue(1, 4);                               // EHFlags
398 
399   // UnwindMapEntry {
400   //   int32_t ToState;
401   //   void  (*Action)();
402   // };
403   if (UnwindMapXData) {
404     OS.EmitLabel(UnwindMapXData);
405     for (const WinEHUnwindMapEntry &UME : FuncInfo.UnwindMap) {
406       OS.EmitIntValue(UME.ToState, 4);                // ToState
407       OS.EmitValue(createImageRel32(UME.Cleanup), 4); // Action
408     }
409   }
410 
411   // TryBlockMap {
412   //   int32_t      TryLow;
413   //   int32_t      TryHigh;
414   //   int32_t      CatchHigh;
415   //   int32_t      NumCatches;
416   //   HandlerType *HandlerArray;
417   // };
418   if (TryBlockMapXData) {
419     OS.EmitLabel(TryBlockMapXData);
420     SmallVector<MCSymbol *, 1> HandlerMaps;
421     for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
422       WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
423       MCSymbol *HandlerMapXData = nullptr;
424 
425       if (!TBME.HandlerArray.empty())
426         HandlerMapXData =
427             Asm->OutContext.GetOrCreateSymbol(Twine("$handlerMap$")
428                                                   .concat(Twine(I))
429                                                   .concat("$")
430                                                   .concat(ParentLinkageName));
431 
432       HandlerMaps.push_back(HandlerMapXData);
433 
434       int CatchHigh = -1;
435       for (WinEHHandlerType &HT : TBME.HandlerArray)
436         CatchHigh =
437             std::max(CatchHigh, FuncInfo.CatchHandlerMaxState[HT.Handler]);
438 
439       assert(TBME.TryLow <= TBME.TryHigh);
440       assert(CatchHigh > TBME.TryHigh);
441       OS.EmitIntValue(TBME.TryLow, 4);                    // TryLow
442       OS.EmitIntValue(TBME.TryHigh, 4);                   // TryHigh
443       OS.EmitIntValue(CatchHigh, 4);                      // CatchHigh
444       OS.EmitIntValue(TBME.HandlerArray.size(), 4);       // NumCatches
445       OS.EmitValue(createImageRel32(HandlerMapXData), 4); // HandlerArray
446     }
447 
448     for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
449       WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
450       MCSymbol *HandlerMapXData = HandlerMaps[I];
451       if (!HandlerMapXData)
452         continue;
453       // HandlerType {
454       //   int32_t         Adjectives;
455       //   TypeDescriptor *Type;
456       //   int32_t         CatchObjOffset;
457       //   void          (*Handler)();
458       //   int32_t         ParentFrameOffset; // x64 only
459       // };
460       OS.EmitLabel(HandlerMapXData);
461       for (const WinEHHandlerType &HT : TBME.HandlerArray) {
462         MCSymbol *ParentFrameOffset =
463             Asm->OutContext.getOrCreateParentFrameOffsetSymbol(
464                 GlobalValue::getRealLinkageName(HT.Handler->getName()));
465         const MCSymbolRefExpr *ParentFrameOffsetRef = MCSymbolRefExpr::Create(
466             ParentFrameOffset, MCSymbolRefExpr::VK_None, Asm->OutContext);
467 
468         // Get the frame escape label with the offset of the catch object. If
469         // the index is -1, then there is no catch object, and we should emit an
470         // offset of zero, indicating that no copy will occur.
471         const MCExpr *FrameAllocOffsetRef = nullptr;
472         if (HT.CatchObjRecoverIdx >= 0) {
473           MCSymbol *FrameAllocOffset =
474               Asm->OutContext.getOrCreateFrameAllocSymbol(
475                   GlobalValue::getRealLinkageName(ParentF->getName()),
476                   HT.CatchObjRecoverIdx);
477           FrameAllocOffsetRef = MCSymbolRefExpr::Create(
478               FrameAllocOffset, MCSymbolRefExpr::VK_None, Asm->OutContext);
479         } else {
480           FrameAllocOffsetRef = MCConstantExpr::Create(0, Asm->OutContext);
481         }
482 
483         OS.EmitIntValue(HT.Adjectives, 4);                    // Adjectives
484         OS.EmitValue(createImageRel32(HT.TypeDescriptor), 4); // Type
485         OS.EmitValue(FrameAllocOffsetRef, 4);                 // CatchObjOffset
486         OS.EmitValue(createImageRel32(HT.Handler), 4);        // Handler
487         OS.EmitValue(ParentFrameOffsetRef, 4);                // ParentFrameOffset
488       }
489     }
490   }
491 
492   // IPToStateMapEntry {
493   //   void   *IP;
494   //   int32_t State;
495   // };
496   if (IPToStateXData) {
497     OS.EmitLabel(IPToStateXData);
498     for (auto &IPStatePair : FuncInfo.IPToStateList) {
499       OS.EmitValue(createImageRel32(IPStatePair.first), 4); // IP
500       OS.EmitIntValue(IPStatePair.second, 4);               // State
501     }
502   }
503 }
504