1 //===-- llvm/Support/ARMWinEH.h - Windows on ARM EH Constants ---*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #ifndef LLVM_SUPPORT_ARMWINEH_H
10 #define LLVM_SUPPORT_ARMWINEH_H
11 
12 #include "llvm/ADT/ArrayRef.h"
13 #include "llvm/Support/Endian.h"
14 
15 namespace llvm {
16 namespace ARM {
17 namespace WinEH {
18 enum class RuntimeFunctionFlag {
19   RFF_Unpacked,       /// unpacked entry
20   RFF_Packed,         /// packed entry
21   RFF_PackedFragment, /// packed entry representing a fragment
22   RFF_Reserved,       /// reserved
23 };
24 
25 enum class ReturnType {
26   RT_POP,             /// return via pop {pc} (L flag must be set)
27   RT_B,               /// 16-bit branch
28   RT_BW,              /// 32-bit branch
29   RT_NoEpilogue,      /// no epilogue (fragment)
30 };
31 
32 /// RuntimeFunction - An entry in the table of procedure data (.pdata)
33 ///
34 ///  3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0
35 ///  1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
36 /// +---------------------------------------------------------------+
37 /// |                     Function Start RVA                        |
38 /// +-------------------+-+-+-+-----+-+---+---------------------+---+
39 /// |    Stack Adjust   |C|L|R| Reg |H|Ret|   Function Length   |Flg|
40 /// +-------------------+-+-+-+-----+-+---+---------------------+---+
41 ///
42 /// Flag : 2-bit field with the following meanings:
43 ///   - 00 = packed unwind data not used; reamining bits point to .xdata record
44 ///   - 01 = packed unwind data
45 ///   - 10 = packed unwind data, function assumed to have no prologue; useful
46 ///          for function fragments that are discontiguous with the start of the
47 ///          function
48 ///   - 11 = reserved
49 /// Function Length : 11-bit field providing the length of the entire function
50 ///                   in bytes, divided by 2; if the function is greater than
51 ///                   4KB, a full .xdata record must be used instead
52 /// Ret : 2-bit field indicating how the function returns
53 ///   - 00 = return via pop {pc} (the L bit must be set)
54 ///   - 01 = return via 16-bit branch
55 ///   - 10 = return via 32-bit branch
56 ///   - 11 = no epilogue; useful for function fragments that may only contain a
57 ///          prologue but the epilogue is elsewhere
58 /// H : 1-bit flag indicating whether the function "homes" the integer parameter
59 ///     registers (r0-r3), allocating 16-bytes on the stack
60 /// Reg : 3-bit field indicating the index of the last saved non-volatile
61 ///       register.  If the R bit is set to 0, then only integer registers are
62 ///       saved (r4-rN, where N is 4 + Reg).  If the R bit is set to 1, then
63 ///       only floating-point registers are being saved (d8-dN, where N is
64 ///       8 + Reg).  The special case of the R bit being set to 1 and Reg equal
65 ///       to 7 indicates that no registers are saved.
66 /// R : 1-bit flag indicating whether the non-volatile registers are integer or
67 ///     floating-point.  0 indicates integer, 1 indicates floating-point.  The
68 ///     special case of the R-flag being set and Reg being set to 7 indicates
69 ///     that no non-volatile registers are saved.
70 /// L : 1-bit flag indicating whether the function saves/restores the link
71 ///     register (LR)
72 /// C : 1-bit flag indicating whether the function includes extra instructions
73 ///     to setup a frame chain for fast walking.  If this flag is set, r11 is
74 ///     implicitly added to the list of saved non-volatile integer registers.
75 /// Stack Adjust : 10-bit field indicating the number of bytes of stack that are
76 ///                allocated for this function.  Only values between 0x000 and
77 ///                0x3f3 can be directly encoded.  If the value is 0x3f4 or
78 ///                greater, then the low 4 bits have special meaning as follows:
79 ///                - Bit 0-1
80 ///                  indicate the number of words' of adjustment (1-4), minus 1
81 ///                - Bit 2
82 ///                  indicates if the prologue combined adjustment into push
83 ///                - Bit 3
84 ///                  indicates if the epilogue combined adjustment into pop
85 ///
86 /// RESTRICTIONS:
87 ///   - IF C is SET:
88 ///     + L flag must be set since frame chaining requires r11 and lr
89 ///     + r11 must NOT be included in the set of registers described by Reg
90 ///   - IF Ret is 0:
91 ///     + L flag must be set
92 
93 // NOTE: RuntimeFunction is meant to be a simple class that provides raw access
94 // to all fields in the structure.  The accessor methods reflect the names of
95 // the bitfields that they correspond to.  Although some obvious simplifications
96 // are possible via merging of methods, it would prevent the use of this class
97 // to fully inspect the contents of the data structure which is particularly
98 // useful for scenarios such as llvm-readobj to aid in testing.
99 
100 class RuntimeFunction {
101 public:
102   const support::ulittle32_t BeginAddress;
103   const support::ulittle32_t UnwindData;
104 
RuntimeFunction(const support::ulittle32_t * Data)105   RuntimeFunction(const support::ulittle32_t *Data)
106     : BeginAddress(Data[0]), UnwindData(Data[1]) {}
107 
RuntimeFunction(const support::ulittle32_t BeginAddress,const support::ulittle32_t UnwindData)108   RuntimeFunction(const support::ulittle32_t BeginAddress,
109                   const support::ulittle32_t UnwindData)
110     : BeginAddress(BeginAddress), UnwindData(UnwindData) {}
111 
Flag()112   RuntimeFunctionFlag Flag() const {
113     return RuntimeFunctionFlag(UnwindData & 0x3);
114   }
115 
ExceptionInformationRVA()116   uint32_t ExceptionInformationRVA() const {
117     assert(Flag() == RuntimeFunctionFlag::RFF_Unpacked &&
118            "unpacked form required for this operation");
119     return (UnwindData & ~0x3);
120   }
121 
PackedUnwindData()122   uint32_t PackedUnwindData() const {
123     assert((Flag() == RuntimeFunctionFlag::RFF_Packed ||
124             Flag() == RuntimeFunctionFlag::RFF_PackedFragment) &&
125            "packed form required for this operation");
126     return (UnwindData & ~0x3);
127   }
FunctionLength()128   uint32_t FunctionLength() const {
129     assert((Flag() == RuntimeFunctionFlag::RFF_Packed ||
130             Flag() == RuntimeFunctionFlag::RFF_PackedFragment) &&
131            "packed form required for this operation");
132     return (((UnwindData & 0x00001ffc) >> 2) << 1);
133   }
Ret()134   ReturnType Ret() const {
135     assert((Flag() == RuntimeFunctionFlag::RFF_Packed ||
136             Flag() == RuntimeFunctionFlag::RFF_PackedFragment) &&
137            "packed form required for this operation");
138     assert(((UnwindData & 0x00006000) || L()) && "L must be set to 1");
139     return ReturnType((UnwindData & 0x00006000) >> 13);
140   }
H()141   bool H() const {
142     assert((Flag() == RuntimeFunctionFlag::RFF_Packed ||
143             Flag() == RuntimeFunctionFlag::RFF_PackedFragment) &&
144            "packed form required for this operation");
145     return ((UnwindData & 0x00008000) >> 15);
146   }
Reg()147   uint8_t Reg() const {
148     assert((Flag() == RuntimeFunctionFlag::RFF_Packed ||
149             Flag() == RuntimeFunctionFlag::RFF_PackedFragment) &&
150            "packed form required for this operation");
151     return ((UnwindData & 0x00070000) >> 16);
152   }
R()153   bool R() const {
154     assert((Flag() == RuntimeFunctionFlag::RFF_Packed ||
155             Flag() == RuntimeFunctionFlag::RFF_PackedFragment) &&
156            "packed form required for this operation");
157     return ((UnwindData & 0x00080000) >> 19);
158   }
L()159   bool L() const {
160     assert((Flag() == RuntimeFunctionFlag::RFF_Packed ||
161             Flag() == RuntimeFunctionFlag::RFF_PackedFragment) &&
162            "packed form required for this operation");
163     return ((UnwindData & 0x00100000) >> 20);
164   }
C()165   bool C() const {
166     assert((Flag() == RuntimeFunctionFlag::RFF_Packed ||
167             Flag() == RuntimeFunctionFlag::RFF_PackedFragment) &&
168            "packed form required for this operation");
169     assert(((~UnwindData & 0x00200000) || L()) &&
170            "L flag must be set, chaining requires r11 and LR");
171     assert(((~UnwindData & 0x00200000) || (Reg() < 7) || R()) &&
172            "r11 must not be included in Reg; C implies r11");
173     return ((UnwindData & 0x00200000) >> 21);
174   }
StackAdjust()175   uint16_t StackAdjust() const {
176     assert((Flag() == RuntimeFunctionFlag::RFF_Packed ||
177             Flag() == RuntimeFunctionFlag::RFF_PackedFragment) &&
178            "packed form required for this operation");
179     return ((UnwindData & 0xffc00000) >> 22);
180   }
181 };
182 
183 /// PrologueFolding - pseudo-flag derived from Stack Adjust indicating that the
184 /// prologue has stack adjustment combined into the push
PrologueFolding(const RuntimeFunction & RF)185 inline bool PrologueFolding(const RuntimeFunction &RF) {
186   return RF.StackAdjust() >= 0x3f4 && (RF.StackAdjust() & 0x4);
187 }
188 /// Epilogue - pseudo-flag derived from Stack Adjust indicating that the
189 /// epilogue has stack adjustment combined into the pop
EpilogueFolding(const RuntimeFunction & RF)190 inline bool EpilogueFolding(const RuntimeFunction &RF) {
191   return RF.StackAdjust() >= 0x3f4 && (RF.StackAdjust() & 0x8);
192 }
193 /// StackAdjustment - calculated stack adjustment in words.  The stack
194 /// adjustment should be determined via this function to account for the special
195 /// handling the special encoding when the value is >= 0x3f4.
StackAdjustment(const RuntimeFunction & RF)196 inline uint16_t StackAdjustment(const RuntimeFunction &RF) {
197   uint16_t Adjustment = RF.StackAdjust();
198   if (Adjustment >= 0x3f4)
199     return (Adjustment & 0x3) ? ((Adjustment & 0x3) << 2) - 1 : 0;
200   return Adjustment;
201 }
202 
203 /// SavedRegisterMask - Utility function to calculate the set of saved general
204 /// purpose (r0-r15) and VFP (d0-d31) registers.
205 std::pair<uint16_t, uint32_t> SavedRegisterMask(const RuntimeFunction &RF);
206 
207 /// ExceptionDataRecord - An entry in the table of exception data (.xdata)
208 ///
209 /// The format on ARM is:
210 ///
211 ///  3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0
212 ///  1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
213 /// +-------+---------+-+-+-+---+-----------------------------------+
214 /// | C Wrd | Epi Cnt |F|E|X|Ver|         Function Length           |
215 /// +-------+--------+'-'-'-'---'---+-------------------------------+
216 /// |    Reserved    |Ex. Code Words|   (Extended Epilogue Count)   |
217 /// +-------+--------+--------------+-------------------------------+
218 ///
219 /// The format on ARM64 is:
220 ///
221 ///  3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0
222 ///  1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
223 /// +---------+---------+-+-+---+-----------------------------------+
224 /// |  C Wrd  | Epi Cnt |E|X|Ver|         Function Length           |
225 /// +---------+------+--'-'-'---'---+-------------------------------+
226 /// |    Reserved    |Ex. Code Words|   (Extended Epilogue Count)   |
227 /// +-------+--------+--------------+-------------------------------+
228 ///
229 /// Function Length : 18-bit field indicating the total length of the function
230 ///                   in bytes divided by 2.  If a function is larger than
231 ///                   512KB, then multiple pdata and xdata records must be used.
232 /// Vers : 2-bit field describing the version of the remaining structure.  Only
233 ///        version 0 is currently defined (values 1-3 are not permitted).
234 /// X : 1-bit field indicating the presence of exception data
235 /// E : 1-bit field indicating that the single epilogue is packed into the
236 ///     header
237 /// F : 1-bit field indicating that the record describes a function fragment
238 ///     (implies that no prologue is present, and prologue processing should be
239 ///     skipped) (ARM only)
240 /// Epilogue Count : 5-bit field that differs in meaning based on the E field.
241 ///
242 ///                  If E is set, then this field specifies the index of the
243 ///                  first unwind code describing the (only) epilogue.
244 ///
245 ///                  Otherwise, this field indicates the number of exception
246 ///                  scopes.  If more than 31 scopes exist, then this field and
247 ///                  the Code Words field must both be set to 0 to indicate that
248 ///                  an extension word is required.
249 /// Code Words : 4-bit (5-bit on ARM64) field that specifies the number of
250 ///              32-bit words needed to contain all the unwind codes.  If more
251 ///              than 15 words (31 words on ARM64) are required, then this field
252 ///              and the Epilogue Count field must both be set to 0 to indicate
253 ///              that an extension word is required.
254 /// Extended Epilogue Count, Extended Code Words :
255 ///                          Valid only if Epilog Count and Code Words are both
256 ///                          set to 0.  Provides an 8-bit extended code word
257 ///                          count and 16-bits for epilogue count
258 ///
259 /// The epilogue scope format on ARM is:
260 ///
261 ///  3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0
262 ///  1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
263 /// +----------------+------+---+---+-------------------------------+
264 /// |  Ep Start Idx  | Cond |Res|       Epilogue Start Offset       |
265 /// +----------------+------+---+-----------------------------------+
266 ///
267 /// The epilogue scope format on ARM64 is:
268 ///
269 ///  3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0
270 ///  1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
271 /// +-------------------+-------+---+-------------------------------+
272 /// |  Ep Start Idx     |  Res  |   Epilogue Start Offset           |
273 /// +-------------------+-------+-----------------------------------+
274 ///
275 /// If the E bit is unset in the header, the header is followed by a series of
276 /// epilogue scopes, which are sorted by their offset.
277 ///
278 /// Epilogue Start Offset: 18-bit field encoding the offset of epilogue relative
279 ///                        to the start of the function in bytes divided by two
280 /// Res : 2-bit field reserved for future expansion (must be set to 0)
281 /// Condition : (ARM only) 4-bit field providing the condition under which the
282 ///             epilogue is executed.  Unconditional epilogues should set this
283 ///             field to 0xe. Epilogues must be entirely conditional or
284 ///             unconditional, and in Thumb-2 mode.  The epilogue begins with
285 ///             the first instruction after the IT opcode.
286 /// Epilogue Start Index : 8-bit field indicating the byte index of the first
287 ///                        unwind code describing the epilogue
288 ///
289 ///  3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0
290 ///  1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
291 /// +---------------+---------------+---------------+---------------+
292 /// | Unwind Code 3 | Unwind Code 2 | Unwind Code 1 | Unwind Code 0 |
293 /// +---------------+---------------+---------------+---------------+
294 ///
295 /// Following the epilogue scopes, the byte code describing the unwinding
296 /// follows.  This is padded to align up to word alignment.  Bytes are stored in
297 /// little endian.
298 ///
299 ///  3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0
300 ///  1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
301 /// +---------------------------------------------------------------+
302 /// |           Exception Handler RVA (requires X = 1)              |
303 /// +---------------------------------------------------------------+
304 /// |  (possibly followed by data required for exception handler)   |
305 /// +---------------------------------------------------------------+
306 ///
307 /// If the X bit is set in the header, the unwind byte code is followed by the
308 /// exception handler information.  This constants of one Exception Handler RVA
309 /// which is the address to the exception handler, followed immediately by the
310 /// variable length data associated with the exception handler.
311 ///
312 
313 struct EpilogueScope {
314   const support::ulittle32_t ES;
315 
EpilogueScopeEpilogueScope316   EpilogueScope(const support::ulittle32_t Data) : ES(Data) {}
317   // Same for both ARM and AArch64.
EpilogueStartOffsetEpilogueScope318   uint32_t EpilogueStartOffset() const {
319     return (ES & 0x0003ffff);
320   }
321 
322   // Different implementations for ARM and AArch64.
ResARMEpilogueScope323   uint8_t ResARM() const {
324     return ((ES & 0x000c0000) >> 18);
325   }
326 
ResAArch64EpilogueScope327   uint8_t ResAArch64() const {
328     return ((ES & 0x000f0000) >> 18);
329   }
330 
331   // Condition is only applicable to ARM.
ConditionEpilogueScope332   uint8_t Condition() const {
333     return ((ES & 0x00f00000) >> 20);
334   }
335 
336   // Different implementations for ARM and AArch64.
EpilogueStartIndexARMEpilogueScope337   uint8_t EpilogueStartIndexARM() const {
338     return ((ES & 0xff000000) >> 24);
339   }
340 
EpilogueStartIndexAArch64EpilogueScope341   uint16_t EpilogueStartIndexAArch64() const {
342     return ((ES & 0xffc00000) >> 22);
343   }
344 };
345 
346 struct ExceptionDataRecord;
347 inline size_t HeaderWords(const ExceptionDataRecord &XR);
348 
349 struct ExceptionDataRecord {
350   const support::ulittle32_t *Data;
351   bool isAArch64;
352 
ExceptionDataRecordExceptionDataRecord353   ExceptionDataRecord(const support::ulittle32_t *Data, bool isAArch64) :
354     Data(Data), isAArch64(isAArch64) {}
355 
FunctionLengthExceptionDataRecord356   uint32_t FunctionLength() const {
357     return (Data[0] & 0x0003ffff);
358   }
359 
FunctionLengthInBytesARMExceptionDataRecord360   uint32_t FunctionLengthInBytesARM() const {
361     return FunctionLength() << 1;
362   }
363 
FunctionLengthInBytesAArch64ExceptionDataRecord364   uint32_t FunctionLengthInBytesAArch64() const {
365     return FunctionLength() << 2;
366   }
367 
VersExceptionDataRecord368   uint8_t Vers() const {
369     return (Data[0] & 0x000C0000) >> 18;
370   }
371 
XExceptionDataRecord372   bool X() const {
373     return ((Data[0] & 0x00100000) >> 20);
374   }
375 
EExceptionDataRecord376   bool E() const {
377     return ((Data[0] & 0x00200000) >> 21);
378   }
379 
FExceptionDataRecord380   bool F() const {
381     assert(!isAArch64 && "Fragments are only supported on ARMv7 WinEH");
382     return ((Data[0] & 0x00400000) >> 22);
383   }
384 
EpilogueCountExceptionDataRecord385   uint16_t EpilogueCount() const {
386     if (HeaderWords(*this) == 1) {
387       if (isAArch64)
388         return (Data[0] & 0x07C00000) >> 22;
389       return (Data[0] & 0x0f800000) >> 23;
390     }
391     return Data[1] & 0x0000ffff;
392   }
393 
CodeWordsExceptionDataRecord394   uint8_t CodeWords() const {
395     if (HeaderWords(*this) == 1) {
396       if (isAArch64)
397         return (Data[0] & 0xf8000000) >> 27;
398       return (Data[0] & 0xf0000000) >> 28;
399     }
400     return (Data[1] & 0x00ff0000) >> 16;
401   }
402 
EpilogueScopesExceptionDataRecord403   ArrayRef<support::ulittle32_t> EpilogueScopes() const {
404     assert(E() == 0 && "epilogue scopes are only present when the E bit is 0");
405     size_t Offset = HeaderWords(*this);
406     return makeArrayRef(&Data[Offset], EpilogueCount());
407   }
408 
UnwindByteCodeExceptionDataRecord409   ArrayRef<uint8_t> UnwindByteCode() const {
410     const size_t Offset = HeaderWords(*this)
411                         + (E() ? 0 :  EpilogueCount());
412     const uint8_t *ByteCode =
413       reinterpret_cast<const uint8_t *>(&Data[Offset]);
414     return makeArrayRef(ByteCode, CodeWords() * sizeof(uint32_t));
415   }
416 
ExceptionHandlerRVAExceptionDataRecord417   uint32_t ExceptionHandlerRVA() const {
418     assert(X() && "Exception Handler RVA is only valid if the X bit is set");
419     return Data[HeaderWords(*this) + EpilogueCount() + CodeWords()];
420   }
421 
ExceptionHandlerParameterExceptionDataRecord422   uint32_t ExceptionHandlerParameter() const {
423     assert(X() && "Exception Handler RVA is only valid if the X bit is set");
424     return Data[HeaderWords(*this) + EpilogueCount() + CodeWords() + 1];
425   }
426 };
427 
HeaderWords(const ExceptionDataRecord & XR)428 inline size_t HeaderWords(const ExceptionDataRecord &XR) {
429   if (XR.isAArch64)
430     return (XR.Data[0] & 0xffc00000) ? 1 : 2;
431   return (XR.Data[0] & 0xff800000) ? 1 : 2;
432 }
433 }
434 }
435 }
436 
437 #endif
438