File: | lib/DebugInfo/CodeView/TypeRecordMapping.cpp |
Warning: | line 278, column 28 The right operand of '<' is a garbage value |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===- TypeRecordMapping.cpp ------------------------------------*- C++ -*-===// | |||
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 | #include "llvm/DebugInfo/CodeView/TypeRecordMapping.h" | |||
11 | ||||
12 | using namespace llvm; | |||
13 | using namespace llvm::codeview; | |||
14 | ||||
15 | #define error(X)if (auto EC = X) return EC; \ | |||
16 | if (auto EC = X) \ | |||
17 | return EC; | |||
18 | ||||
19 | namespace { | |||
20 | struct MapOneMethodRecord { | |||
21 | explicit MapOneMethodRecord(bool IsFromOverloadList) | |||
22 | : IsFromOverloadList(IsFromOverloadList) {} | |||
23 | ||||
24 | Error operator()(CodeViewRecordIO &IO, OneMethodRecord &Method) const { | |||
25 | error(IO.mapInteger(Method.Attrs.Attrs))if (auto EC = IO.mapInteger(Method.Attrs.Attrs)) return EC;; | |||
26 | if (IsFromOverloadList) { | |||
27 | uint16_t Padding = 0; | |||
28 | error(IO.mapInteger(Padding))if (auto EC = IO.mapInteger(Padding)) return EC;; | |||
29 | } | |||
30 | error(IO.mapInteger(Method.Type))if (auto EC = IO.mapInteger(Method.Type)) return EC;; | |||
31 | if (Method.isIntroducingVirtual()) { | |||
32 | error(IO.mapInteger(Method.VFTableOffset))if (auto EC = IO.mapInteger(Method.VFTableOffset)) return EC;; | |||
33 | } else if (!IO.isWriting()) | |||
34 | Method.VFTableOffset = -1; | |||
35 | ||||
36 | if (!IsFromOverloadList) | |||
37 | error(IO.mapStringZ(Method.Name))if (auto EC = IO.mapStringZ(Method.Name)) return EC;; | |||
38 | ||||
39 | return Error::success(); | |||
40 | } | |||
41 | ||||
42 | private: | |||
43 | bool IsFromOverloadList; | |||
44 | }; | |||
45 | } | |||
46 | ||||
47 | static Error mapNameAndUniqueName(CodeViewRecordIO &IO, StringRef &Name, | |||
48 | StringRef &UniqueName, bool HasUniqueName) { | |||
49 | if (IO.isWriting()) { | |||
50 | // Try to be smart about what we write here. We can't write anything too | |||
51 | // large, so if we're going to go over the limit, truncate both the name | |||
52 | // and unique name by the same amount. | |||
53 | size_t BytesLeft = IO.maxFieldLength(); | |||
54 | if (HasUniqueName) { | |||
55 | size_t BytesNeeded = Name.size() + UniqueName.size() + 2; | |||
56 | StringRef N = Name; | |||
57 | StringRef U = UniqueName; | |||
58 | if (BytesNeeded > BytesLeft) { | |||
59 | size_t BytesToDrop = (BytesNeeded - BytesLeft); | |||
60 | size_t DropN = std::min(N.size(), BytesToDrop / 2); | |||
61 | size_t DropU = std::min(U.size(), BytesToDrop - DropN); | |||
62 | ||||
63 | N = N.drop_back(DropN); | |||
64 | U = U.drop_back(DropU); | |||
65 | } | |||
66 | ||||
67 | error(IO.mapStringZ(N))if (auto EC = IO.mapStringZ(N)) return EC;; | |||
68 | error(IO.mapStringZ(U))if (auto EC = IO.mapStringZ(U)) return EC;; | |||
69 | } else { | |||
70 | // Cap the length of the string at however many bytes we have available, | |||
71 | // plus one for the required null terminator. | |||
72 | auto N = StringRef(Name).take_front(BytesLeft - 1); | |||
73 | error(IO.mapStringZ(N))if (auto EC = IO.mapStringZ(N)) return EC;; | |||
74 | } | |||
75 | } else { | |||
76 | error(IO.mapStringZ(Name))if (auto EC = IO.mapStringZ(Name)) return EC;; | |||
77 | if (HasUniqueName) | |||
78 | error(IO.mapStringZ(UniqueName))if (auto EC = IO.mapStringZ(UniqueName)) return EC;; | |||
79 | } | |||
80 | ||||
81 | return Error::success(); | |||
82 | } | |||
83 | ||||
84 | Error TypeRecordMapping::visitTypeBegin(CVType &CVR) { | |||
85 | assert(!TypeKind.hasValue() && "Already in a type mapping!")(static_cast <bool> (!TypeKind.hasValue() && "Already in a type mapping!" ) ? void (0) : __assert_fail ("!TypeKind.hasValue() && \"Already in a type mapping!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/lib/DebugInfo/CodeView/TypeRecordMapping.cpp" , 85, __extension__ __PRETTY_FUNCTION__)); | |||
86 | assert(!MemberKind.hasValue() && "Already in a member mapping!")(static_cast <bool> (!MemberKind.hasValue() && "Already in a member mapping!" ) ? void (0) : __assert_fail ("!MemberKind.hasValue() && \"Already in a member mapping!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/lib/DebugInfo/CodeView/TypeRecordMapping.cpp" , 86, __extension__ __PRETTY_FUNCTION__)); | |||
87 | ||||
88 | // FieldList and MethodList records can be any length because they can be | |||
89 | // split with continuation records. All other record types cannot be | |||
90 | // longer than the maximum record length. | |||
91 | Optional<uint32_t> MaxLen; | |||
92 | if (CVR.Type != TypeLeafKind::LF_FIELDLIST && | |||
93 | CVR.Type != TypeLeafKind::LF_METHODLIST) | |||
94 | MaxLen = MaxRecordLength - sizeof(RecordPrefix); | |||
95 | error(IO.beginRecord(MaxLen))if (auto EC = IO.beginRecord(MaxLen)) return EC;; | |||
96 | TypeKind = CVR.Type; | |||
97 | return Error::success(); | |||
98 | } | |||
99 | ||||
100 | Error TypeRecordMapping::visitTypeEnd(CVType &Record) { | |||
101 | assert(TypeKind.hasValue() && "Not in a type mapping!")(static_cast <bool> (TypeKind.hasValue() && "Not in a type mapping!" ) ? void (0) : __assert_fail ("TypeKind.hasValue() && \"Not in a type mapping!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/lib/DebugInfo/CodeView/TypeRecordMapping.cpp" , 101, __extension__ __PRETTY_FUNCTION__)); | |||
102 | assert(!MemberKind.hasValue() && "Still in a member mapping!")(static_cast <bool> (!MemberKind.hasValue() && "Still in a member mapping!" ) ? void (0) : __assert_fail ("!MemberKind.hasValue() && \"Still in a member mapping!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/lib/DebugInfo/CodeView/TypeRecordMapping.cpp" , 102, __extension__ __PRETTY_FUNCTION__)); | |||
103 | ||||
104 | error(IO.endRecord())if (auto EC = IO.endRecord()) return EC;; | |||
105 | ||||
106 | TypeKind.reset(); | |||
107 | return Error::success(); | |||
108 | } | |||
109 | ||||
110 | Error TypeRecordMapping::visitMemberBegin(CVMemberRecord &Record) { | |||
111 | assert(TypeKind.hasValue() && "Not in a type mapping!")(static_cast <bool> (TypeKind.hasValue() && "Not in a type mapping!" ) ? void (0) : __assert_fail ("TypeKind.hasValue() && \"Not in a type mapping!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/lib/DebugInfo/CodeView/TypeRecordMapping.cpp" , 111, __extension__ __PRETTY_FUNCTION__)); | |||
112 | assert(!MemberKind.hasValue() && "Already in a member mapping!")(static_cast <bool> (!MemberKind.hasValue() && "Already in a member mapping!" ) ? void (0) : __assert_fail ("!MemberKind.hasValue() && \"Already in a member mapping!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/lib/DebugInfo/CodeView/TypeRecordMapping.cpp" , 112, __extension__ __PRETTY_FUNCTION__)); | |||
113 | ||||
114 | // The largest possible subrecord is one in which there is a record prefix, | |||
115 | // followed by the subrecord, followed by a continuation, and that entire | |||
116 | // sequence spaws `MaxRecordLength` bytes. So the record's length is | |||
117 | // calculated as follows. | |||
118 | constexpr uint32_t ContinuationLength = 8; | |||
119 | error(IO.beginRecord(MaxRecordLength - sizeof(RecordPrefix) -if (auto EC = IO.beginRecord(MaxRecordLength - sizeof(RecordPrefix ) - ContinuationLength)) return EC; | |||
120 | ContinuationLength))if (auto EC = IO.beginRecord(MaxRecordLength - sizeof(RecordPrefix ) - ContinuationLength)) return EC;; | |||
121 | ||||
122 | MemberKind = Record.Kind; | |||
123 | return Error::success(); | |||
124 | } | |||
125 | ||||
126 | Error TypeRecordMapping::visitMemberEnd(CVMemberRecord &Record) { | |||
127 | assert(TypeKind.hasValue() && "Not in a type mapping!")(static_cast <bool> (TypeKind.hasValue() && "Not in a type mapping!" ) ? void (0) : __assert_fail ("TypeKind.hasValue() && \"Not in a type mapping!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/lib/DebugInfo/CodeView/TypeRecordMapping.cpp" , 127, __extension__ __PRETTY_FUNCTION__)); | |||
128 | assert(MemberKind.hasValue() && "Not in a member mapping!")(static_cast <bool> (MemberKind.hasValue() && "Not in a member mapping!" ) ? void (0) : __assert_fail ("MemberKind.hasValue() && \"Not in a member mapping!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/lib/DebugInfo/CodeView/TypeRecordMapping.cpp" , 128, __extension__ __PRETTY_FUNCTION__)); | |||
129 | ||||
130 | if (!IO.isWriting()) { | |||
131 | if (auto EC = IO.skipPadding()) | |||
132 | return EC; | |||
133 | } | |||
134 | ||||
135 | MemberKind.reset(); | |||
136 | error(IO.endRecord())if (auto EC = IO.endRecord()) return EC;; | |||
137 | return Error::success(); | |||
138 | } | |||
139 | ||||
140 | Error TypeRecordMapping::visitKnownRecord(CVType &CVR, ModifierRecord &Record) { | |||
141 | error(IO.mapInteger(Record.ModifiedType))if (auto EC = IO.mapInteger(Record.ModifiedType)) return EC;; | |||
142 | error(IO.mapEnum(Record.Modifiers))if (auto EC = IO.mapEnum(Record.Modifiers)) return EC;; | |||
143 | ||||
144 | return Error::success(); | |||
145 | } | |||
146 | ||||
147 | Error TypeRecordMapping::visitKnownRecord(CVType &CVR, | |||
148 | ProcedureRecord &Record) { | |||
149 | error(IO.mapInteger(Record.ReturnType))if (auto EC = IO.mapInteger(Record.ReturnType)) return EC;; | |||
150 | error(IO.mapEnum(Record.CallConv))if (auto EC = IO.mapEnum(Record.CallConv)) return EC;; | |||
151 | error(IO.mapEnum(Record.Options))if (auto EC = IO.mapEnum(Record.Options)) return EC;; | |||
152 | error(IO.mapInteger(Record.ParameterCount))if (auto EC = IO.mapInteger(Record.ParameterCount)) return EC ;; | |||
153 | error(IO.mapInteger(Record.ArgumentList))if (auto EC = IO.mapInteger(Record.ArgumentList)) return EC;; | |||
154 | ||||
155 | return Error::success(); | |||
156 | } | |||
157 | ||||
158 | Error TypeRecordMapping::visitKnownRecord(CVType &CVR, | |||
159 | MemberFunctionRecord &Record) { | |||
160 | error(IO.mapInteger(Record.ReturnType))if (auto EC = IO.mapInteger(Record.ReturnType)) return EC;; | |||
161 | error(IO.mapInteger(Record.ClassType))if (auto EC = IO.mapInteger(Record.ClassType)) return EC;; | |||
162 | error(IO.mapInteger(Record.ThisType))if (auto EC = IO.mapInteger(Record.ThisType)) return EC;; | |||
163 | error(IO.mapEnum(Record.CallConv))if (auto EC = IO.mapEnum(Record.CallConv)) return EC;; | |||
164 | error(IO.mapEnum(Record.Options))if (auto EC = IO.mapEnum(Record.Options)) return EC;; | |||
165 | error(IO.mapInteger(Record.ParameterCount))if (auto EC = IO.mapInteger(Record.ParameterCount)) return EC ;; | |||
166 | error(IO.mapInteger(Record.ArgumentList))if (auto EC = IO.mapInteger(Record.ArgumentList)) return EC;; | |||
167 | error(IO.mapInteger(Record.ThisPointerAdjustment))if (auto EC = IO.mapInteger(Record.ThisPointerAdjustment)) return EC;; | |||
168 | ||||
169 | return Error::success(); | |||
170 | } | |||
171 | ||||
172 | Error TypeRecordMapping::visitKnownRecord(CVType &CVR, ArgListRecord &Record) { | |||
173 | error(IO.mapVectorN<uint32_t>(if (auto EC = IO.mapVectorN<uint32_t>( Record.ArgIndices , [](CodeViewRecordIO &IO, TypeIndex &N) { return IO. mapInteger(N); })) return EC; | |||
174 | Record.ArgIndices,if (auto EC = IO.mapVectorN<uint32_t>( Record.ArgIndices , [](CodeViewRecordIO &IO, TypeIndex &N) { return IO. mapInteger(N); })) return EC; | |||
175 | [](CodeViewRecordIO &IO, TypeIndex &N) { return IO.mapInteger(N); }))if (auto EC = IO.mapVectorN<uint32_t>( Record.ArgIndices , [](CodeViewRecordIO &IO, TypeIndex &N) { return IO. mapInteger(N); })) return EC;; | |||
176 | ||||
177 | return Error::success(); | |||
178 | } | |||
179 | ||||
180 | Error TypeRecordMapping::visitKnownRecord(CVType &CVR, | |||
181 | StringListRecord &Record) { | |||
182 | error(IO.mapVectorN<uint32_t>(if (auto EC = IO.mapVectorN<uint32_t>( Record.StringIndices , [](CodeViewRecordIO &IO, TypeIndex &N) { return IO. mapInteger(N); })) return EC; | |||
183 | Record.StringIndices,if (auto EC = IO.mapVectorN<uint32_t>( Record.StringIndices , [](CodeViewRecordIO &IO, TypeIndex &N) { return IO. mapInteger(N); })) return EC; | |||
184 | [](CodeViewRecordIO &IO, TypeIndex &N) { return IO.mapInteger(N); }))if (auto EC = IO.mapVectorN<uint32_t>( Record.StringIndices , [](CodeViewRecordIO &IO, TypeIndex &N) { return IO. mapInteger(N); })) return EC;; | |||
185 | ||||
186 | return Error::success(); | |||
187 | } | |||
188 | ||||
189 | Error TypeRecordMapping::visitKnownRecord(CVType &CVR, PointerRecord &Record) { | |||
190 | error(IO.mapInteger(Record.ReferentType))if (auto EC = IO.mapInteger(Record.ReferentType)) return EC;; | |||
191 | error(IO.mapInteger(Record.Attrs))if (auto EC = IO.mapInteger(Record.Attrs)) return EC;; | |||
192 | ||||
193 | if (Record.isPointerToMember()) { | |||
194 | if (!IO.isWriting()) | |||
195 | Record.MemberInfo.emplace(); | |||
196 | ||||
197 | MemberPointerInfo &M = *Record.MemberInfo; | |||
198 | error(IO.mapInteger(M.ContainingType))if (auto EC = IO.mapInteger(M.ContainingType)) return EC;; | |||
199 | error(IO.mapEnum(M.Representation))if (auto EC = IO.mapEnum(M.Representation)) return EC;; | |||
200 | } | |||
201 | ||||
202 | return Error::success(); | |||
203 | } | |||
204 | ||||
205 | Error TypeRecordMapping::visitKnownRecord(CVType &CVR, ArrayRecord &Record) { | |||
206 | error(IO.mapInteger(Record.ElementType))if (auto EC = IO.mapInteger(Record.ElementType)) return EC;; | |||
207 | error(IO.mapInteger(Record.IndexType))if (auto EC = IO.mapInteger(Record.IndexType)) return EC;; | |||
208 | error(IO.mapEncodedInteger(Record.Size))if (auto EC = IO.mapEncodedInteger(Record.Size)) return EC;; | |||
209 | error(IO.mapStringZ(Record.Name))if (auto EC = IO.mapStringZ(Record.Name)) return EC;; | |||
210 | ||||
211 | return Error::success(); | |||
212 | } | |||
213 | ||||
214 | Error TypeRecordMapping::visitKnownRecord(CVType &CVR, ClassRecord &Record) { | |||
215 | assert((CVR.Type == TypeLeafKind::LF_STRUCTURE) ||(static_cast <bool> ((CVR.Type == TypeLeafKind::LF_STRUCTURE ) || (CVR.Type == TypeLeafKind::LF_CLASS) || (CVR.Type == TypeLeafKind ::LF_INTERFACE)) ? void (0) : __assert_fail ("(CVR.Type == TypeLeafKind::LF_STRUCTURE) || (CVR.Type == TypeLeafKind::LF_CLASS) || (CVR.Type == TypeLeafKind::LF_INTERFACE)" , "/build/llvm-toolchain-snapshot-7~svn326246/lib/DebugInfo/CodeView/TypeRecordMapping.cpp" , 217, __extension__ __PRETTY_FUNCTION__)) | |||
216 | (CVR.Type == TypeLeafKind::LF_CLASS) ||(static_cast <bool> ((CVR.Type == TypeLeafKind::LF_STRUCTURE ) || (CVR.Type == TypeLeafKind::LF_CLASS) || (CVR.Type == TypeLeafKind ::LF_INTERFACE)) ? void (0) : __assert_fail ("(CVR.Type == TypeLeafKind::LF_STRUCTURE) || (CVR.Type == TypeLeafKind::LF_CLASS) || (CVR.Type == TypeLeafKind::LF_INTERFACE)" , "/build/llvm-toolchain-snapshot-7~svn326246/lib/DebugInfo/CodeView/TypeRecordMapping.cpp" , 217, __extension__ __PRETTY_FUNCTION__)) | |||
217 | (CVR.Type == TypeLeafKind::LF_INTERFACE))(static_cast <bool> ((CVR.Type == TypeLeafKind::LF_STRUCTURE ) || (CVR.Type == TypeLeafKind::LF_CLASS) || (CVR.Type == TypeLeafKind ::LF_INTERFACE)) ? void (0) : __assert_fail ("(CVR.Type == TypeLeafKind::LF_STRUCTURE) || (CVR.Type == TypeLeafKind::LF_CLASS) || (CVR.Type == TypeLeafKind::LF_INTERFACE)" , "/build/llvm-toolchain-snapshot-7~svn326246/lib/DebugInfo/CodeView/TypeRecordMapping.cpp" , 217, __extension__ __PRETTY_FUNCTION__)); | |||
218 | ||||
219 | error(IO.mapInteger(Record.MemberCount))if (auto EC = IO.mapInteger(Record.MemberCount)) return EC;; | |||
220 | error(IO.mapEnum(Record.Options))if (auto EC = IO.mapEnum(Record.Options)) return EC;; | |||
221 | error(IO.mapInteger(Record.FieldList))if (auto EC = IO.mapInteger(Record.FieldList)) return EC;; | |||
222 | error(IO.mapInteger(Record.DerivationList))if (auto EC = IO.mapInteger(Record.DerivationList)) return EC ;; | |||
223 | error(IO.mapInteger(Record.VTableShape))if (auto EC = IO.mapInteger(Record.VTableShape)) return EC;; | |||
224 | error(IO.mapEncodedInteger(Record.Size))if (auto EC = IO.mapEncodedInteger(Record.Size)) return EC;; | |||
225 | error(mapNameAndUniqueName(IO, Record.Name, Record.UniqueName,if (auto EC = mapNameAndUniqueName(IO, Record.Name, Record.UniqueName , Record.hasUniqueName())) return EC; | |||
226 | Record.hasUniqueName()))if (auto EC = mapNameAndUniqueName(IO, Record.Name, Record.UniqueName , Record.hasUniqueName())) return EC;; | |||
227 | ||||
228 | return Error::success(); | |||
229 | } | |||
230 | ||||
231 | Error TypeRecordMapping::visitKnownRecord(CVType &CVR, UnionRecord &Record) { | |||
232 | error(IO.mapInteger(Record.MemberCount))if (auto EC = IO.mapInteger(Record.MemberCount)) return EC;; | |||
233 | error(IO.mapEnum(Record.Options))if (auto EC = IO.mapEnum(Record.Options)) return EC;; | |||
234 | error(IO.mapInteger(Record.FieldList))if (auto EC = IO.mapInteger(Record.FieldList)) return EC;; | |||
235 | error(IO.mapEncodedInteger(Record.Size))if (auto EC = IO.mapEncodedInteger(Record.Size)) return EC;; | |||
236 | error(mapNameAndUniqueName(IO, Record.Name, Record.UniqueName,if (auto EC = mapNameAndUniqueName(IO, Record.Name, Record.UniqueName , Record.hasUniqueName())) return EC; | |||
237 | Record.hasUniqueName()))if (auto EC = mapNameAndUniqueName(IO, Record.Name, Record.UniqueName , Record.hasUniqueName())) return EC;; | |||
238 | ||||
239 | return Error::success(); | |||
240 | } | |||
241 | ||||
242 | Error TypeRecordMapping::visitKnownRecord(CVType &CVR, EnumRecord &Record) { | |||
243 | error(IO.mapInteger(Record.MemberCount))if (auto EC = IO.mapInteger(Record.MemberCount)) return EC;; | |||
244 | error(IO.mapEnum(Record.Options))if (auto EC = IO.mapEnum(Record.Options)) return EC;; | |||
245 | error(IO.mapInteger(Record.UnderlyingType))if (auto EC = IO.mapInteger(Record.UnderlyingType)) return EC ;; | |||
246 | error(IO.mapInteger(Record.FieldList))if (auto EC = IO.mapInteger(Record.FieldList)) return EC;; | |||
247 | error(mapNameAndUniqueName(IO, Record.Name, Record.UniqueName,if (auto EC = mapNameAndUniqueName(IO, Record.Name, Record.UniqueName , Record.hasUniqueName())) return EC; | |||
248 | Record.hasUniqueName()))if (auto EC = mapNameAndUniqueName(IO, Record.Name, Record.UniqueName , Record.hasUniqueName())) return EC;; | |||
249 | ||||
250 | return Error::success(); | |||
251 | } | |||
252 | ||||
253 | Error TypeRecordMapping::visitKnownRecord(CVType &CVR, BitFieldRecord &Record) { | |||
254 | error(IO.mapInteger(Record.Type))if (auto EC = IO.mapInteger(Record.Type)) return EC;; | |||
255 | error(IO.mapInteger(Record.BitSize))if (auto EC = IO.mapInteger(Record.BitSize)) return EC;; | |||
256 | error(IO.mapInteger(Record.BitOffset))if (auto EC = IO.mapInteger(Record.BitOffset)) return EC;; | |||
257 | ||||
258 | return Error::success(); | |||
259 | } | |||
260 | ||||
261 | Error TypeRecordMapping::visitKnownRecord(CVType &CVR, | |||
262 | VFTableShapeRecord &Record) { | |||
263 | uint16_t Size; | |||
| ||||
264 | if (IO.isWriting()) { | |||
265 | ArrayRef<VFTableSlotKind> Slots = Record.getSlots(); | |||
266 | Size = Slots.size(); | |||
267 | error(IO.mapInteger(Size))if (auto EC = IO.mapInteger(Size)) return EC;; | |||
268 | ||||
269 | for (size_t SlotIndex = 0; SlotIndex < Slots.size(); SlotIndex += 2) { | |||
270 | uint8_t Byte = static_cast<uint8_t>(Slots[SlotIndex]) << 4; | |||
271 | if ((SlotIndex + 1) < Slots.size()) { | |||
272 | Byte |= static_cast<uint8_t>(Slots[SlotIndex + 1]); | |||
273 | } | |||
274 | error(IO.mapInteger(Byte))if (auto EC = IO.mapInteger(Byte)) return EC;; | |||
275 | } | |||
276 | } else { | |||
277 | error(IO.mapInteger(Size))if (auto EC = IO.mapInteger(Size)) return EC;; | |||
278 | for (uint16_t I = 0; I < Size; I += 2) { | |||
| ||||
279 | uint8_t Byte; | |||
280 | error(IO.mapInteger(Byte))if (auto EC = IO.mapInteger(Byte)) return EC;; | |||
281 | Record.Slots.push_back(static_cast<VFTableSlotKind>(Byte & 0xF)); | |||
282 | if ((I + 1) < Size) | |||
283 | Record.Slots.push_back(static_cast<VFTableSlotKind>(Byte >> 4)); | |||
284 | } | |||
285 | } | |||
286 | ||||
287 | return Error::success(); | |||
288 | } | |||
289 | ||||
290 | Error TypeRecordMapping::visitKnownRecord(CVType &CVR, VFTableRecord &Record) { | |||
291 | error(IO.mapInteger(Record.CompleteClass))if (auto EC = IO.mapInteger(Record.CompleteClass)) return EC;; | |||
292 | error(IO.mapInteger(Record.OverriddenVFTable))if (auto EC = IO.mapInteger(Record.OverriddenVFTable)) return EC;; | |||
293 | error(IO.mapInteger(Record.VFPtrOffset))if (auto EC = IO.mapInteger(Record.VFPtrOffset)) return EC;; | |||
294 | uint32_t NamesLen = 0; | |||
295 | if (IO.isWriting()) { | |||
296 | for (auto Name : Record.MethodNames) | |||
297 | NamesLen += Name.size() + 1; | |||
298 | } | |||
299 | error(IO.mapInteger(NamesLen))if (auto EC = IO.mapInteger(NamesLen)) return EC;; | |||
300 | error(IO.mapVectorTail(if (auto EC = IO.mapVectorTail( Record.MethodNames, [](CodeViewRecordIO &IO, StringRef &S) { return IO.mapStringZ(S); })) return EC; | |||
301 | Record.MethodNames,if (auto EC = IO.mapVectorTail( Record.MethodNames, [](CodeViewRecordIO &IO, StringRef &S) { return IO.mapStringZ(S); })) return EC; | |||
302 | [](CodeViewRecordIO &IO, StringRef &S) { return IO.mapStringZ(S); }))if (auto EC = IO.mapVectorTail( Record.MethodNames, [](CodeViewRecordIO &IO, StringRef &S) { return IO.mapStringZ(S); })) return EC;; | |||
303 | ||||
304 | return Error::success(); | |||
305 | } | |||
306 | ||||
307 | Error TypeRecordMapping::visitKnownRecord(CVType &CVR, StringIdRecord &Record) { | |||
308 | error(IO.mapInteger(Record.Id))if (auto EC = IO.mapInteger(Record.Id)) return EC;; | |||
309 | error(IO.mapStringZ(Record.String))if (auto EC = IO.mapStringZ(Record.String)) return EC;; | |||
310 | ||||
311 | return Error::success(); | |||
312 | } | |||
313 | ||||
314 | Error TypeRecordMapping::visitKnownRecord(CVType &CVR, | |||
315 | UdtSourceLineRecord &Record) { | |||
316 | error(IO.mapInteger(Record.UDT))if (auto EC = IO.mapInteger(Record.UDT)) return EC;; | |||
317 | error(IO.mapInteger(Record.SourceFile))if (auto EC = IO.mapInteger(Record.SourceFile)) return EC;; | |||
318 | error(IO.mapInteger(Record.LineNumber))if (auto EC = IO.mapInteger(Record.LineNumber)) return EC;; | |||
319 | ||||
320 | return Error::success(); | |||
321 | } | |||
322 | ||||
323 | Error TypeRecordMapping::visitKnownRecord(CVType &CVR, | |||
324 | UdtModSourceLineRecord &Record) { | |||
325 | error(IO.mapInteger(Record.UDT))if (auto EC = IO.mapInteger(Record.UDT)) return EC;; | |||
326 | error(IO.mapInteger(Record.SourceFile))if (auto EC = IO.mapInteger(Record.SourceFile)) return EC;; | |||
327 | error(IO.mapInteger(Record.LineNumber))if (auto EC = IO.mapInteger(Record.LineNumber)) return EC;; | |||
328 | error(IO.mapInteger(Record.Module))if (auto EC = IO.mapInteger(Record.Module)) return EC;; | |||
329 | ||||
330 | return Error::success(); | |||
331 | } | |||
332 | ||||
333 | Error TypeRecordMapping::visitKnownRecord(CVType &CVR, FuncIdRecord &Record) { | |||
334 | error(IO.mapInteger(Record.ParentScope))if (auto EC = IO.mapInteger(Record.ParentScope)) return EC;; | |||
335 | error(IO.mapInteger(Record.FunctionType))if (auto EC = IO.mapInteger(Record.FunctionType)) return EC;; | |||
336 | error(IO.mapStringZ(Record.Name))if (auto EC = IO.mapStringZ(Record.Name)) return EC;; | |||
337 | ||||
338 | return Error::success(); | |||
339 | } | |||
340 | ||||
341 | Error TypeRecordMapping::visitKnownRecord(CVType &CVR, | |||
342 | MemberFuncIdRecord &Record) { | |||
343 | error(IO.mapInteger(Record.ClassType))if (auto EC = IO.mapInteger(Record.ClassType)) return EC;; | |||
344 | error(IO.mapInteger(Record.FunctionType))if (auto EC = IO.mapInteger(Record.FunctionType)) return EC;; | |||
345 | error(IO.mapStringZ(Record.Name))if (auto EC = IO.mapStringZ(Record.Name)) return EC;; | |||
346 | ||||
347 | return Error::success(); | |||
348 | } | |||
349 | ||||
350 | Error TypeRecordMapping::visitKnownRecord(CVType &CVR, | |||
351 | BuildInfoRecord &Record) { | |||
352 | error(IO.mapVectorN<uint16_t>(if (auto EC = IO.mapVectorN<uint16_t>( Record.ArgIndices , [](CodeViewRecordIO &IO, TypeIndex &N) { return IO. mapInteger(N); })) return EC; | |||
353 | Record.ArgIndices,if (auto EC = IO.mapVectorN<uint16_t>( Record.ArgIndices , [](CodeViewRecordIO &IO, TypeIndex &N) { return IO. mapInteger(N); })) return EC; | |||
354 | [](CodeViewRecordIO &IO, TypeIndex &N) { return IO.mapInteger(N); }))if (auto EC = IO.mapVectorN<uint16_t>( Record.ArgIndices , [](CodeViewRecordIO &IO, TypeIndex &N) { return IO. mapInteger(N); })) return EC;; | |||
355 | ||||
356 | return Error::success(); | |||
357 | } | |||
358 | ||||
359 | Error TypeRecordMapping::visitKnownRecord(CVType &CVR, | |||
360 | MethodOverloadListRecord &Record) { | |||
361 | // TODO: Split the list into multiple records if it's longer than 64KB, using | |||
362 | // a subrecord of TypeRecordKind::Index to chain the records together. | |||
363 | error(IO.mapVectorTail(Record.Methods, MapOneMethodRecord(true)))if (auto EC = IO.mapVectorTail(Record.Methods, MapOneMethodRecord (true))) return EC;; | |||
364 | ||||
365 | return Error::success(); | |||
366 | } | |||
367 | ||||
368 | Error TypeRecordMapping::visitKnownRecord(CVType &CVR, | |||
369 | FieldListRecord &Record) { | |||
370 | error(IO.mapByteVectorTail(Record.Data))if (auto EC = IO.mapByteVectorTail(Record.Data)) return EC;; | |||
371 | ||||
372 | return Error::success(); | |||
373 | } | |||
374 | ||||
375 | Error TypeRecordMapping::visitKnownRecord(CVType &CVR, | |||
376 | TypeServer2Record &Record) { | |||
377 | error(IO.mapGuid(Record.Guid))if (auto EC = IO.mapGuid(Record.Guid)) return EC;; | |||
378 | error(IO.mapInteger(Record.Age))if (auto EC = IO.mapInteger(Record.Age)) return EC;; | |||
379 | error(IO.mapStringZ(Record.Name))if (auto EC = IO.mapStringZ(Record.Name)) return EC;; | |||
380 | return Error::success(); | |||
381 | } | |||
382 | ||||
383 | Error TypeRecordMapping::visitKnownRecord(CVType &CVR, LabelRecord &Record) { | |||
384 | error(IO.mapEnum(Record.Mode))if (auto EC = IO.mapEnum(Record.Mode)) return EC;; | |||
385 | return Error::success(); | |||
386 | } | |||
387 | ||||
388 | Error TypeRecordMapping::visitKnownMember(CVMemberRecord &CVR, | |||
389 | BaseClassRecord &Record) { | |||
390 | error(IO.mapInteger(Record.Attrs.Attrs))if (auto EC = IO.mapInteger(Record.Attrs.Attrs)) return EC;; | |||
391 | error(IO.mapInteger(Record.Type))if (auto EC = IO.mapInteger(Record.Type)) return EC;; | |||
392 | error(IO.mapEncodedInteger(Record.Offset))if (auto EC = IO.mapEncodedInteger(Record.Offset)) return EC;; | |||
393 | ||||
394 | return Error::success(); | |||
395 | } | |||
396 | ||||
397 | Error TypeRecordMapping::visitKnownMember(CVMemberRecord &CVR, | |||
398 | EnumeratorRecord &Record) { | |||
399 | error(IO.mapInteger(Record.Attrs.Attrs))if (auto EC = IO.mapInteger(Record.Attrs.Attrs)) return EC;; | |||
400 | ||||
401 | // FIXME: Handle full APInt such as __int128. | |||
402 | error(IO.mapEncodedInteger(Record.Value))if (auto EC = IO.mapEncodedInteger(Record.Value)) return EC;; | |||
403 | error(IO.mapStringZ(Record.Name))if (auto EC = IO.mapStringZ(Record.Name)) return EC;; | |||
404 | ||||
405 | return Error::success(); | |||
406 | } | |||
407 | ||||
408 | Error TypeRecordMapping::visitKnownMember(CVMemberRecord &CVR, | |||
409 | DataMemberRecord &Record) { | |||
410 | error(IO.mapInteger(Record.Attrs.Attrs))if (auto EC = IO.mapInteger(Record.Attrs.Attrs)) return EC;; | |||
411 | error(IO.mapInteger(Record.Type))if (auto EC = IO.mapInteger(Record.Type)) return EC;; | |||
412 | error(IO.mapEncodedInteger(Record.FieldOffset))if (auto EC = IO.mapEncodedInteger(Record.FieldOffset)) return EC;; | |||
413 | error(IO.mapStringZ(Record.Name))if (auto EC = IO.mapStringZ(Record.Name)) return EC;; | |||
414 | ||||
415 | return Error::success(); | |||
416 | } | |||
417 | ||||
418 | Error TypeRecordMapping::visitKnownMember(CVMemberRecord &CVR, | |||
419 | OverloadedMethodRecord &Record) { | |||
420 | error(IO.mapInteger(Record.NumOverloads))if (auto EC = IO.mapInteger(Record.NumOverloads)) return EC;; | |||
421 | error(IO.mapInteger(Record.MethodList))if (auto EC = IO.mapInteger(Record.MethodList)) return EC;; | |||
422 | error(IO.mapStringZ(Record.Name))if (auto EC = IO.mapStringZ(Record.Name)) return EC;; | |||
423 | ||||
424 | return Error::success(); | |||
425 | } | |||
426 | ||||
427 | Error TypeRecordMapping::visitKnownMember(CVMemberRecord &CVR, | |||
428 | OneMethodRecord &Record) { | |||
429 | const bool IsFromOverloadList = (TypeKind == LF_METHODLIST); | |||
430 | MapOneMethodRecord Mapper(IsFromOverloadList); | |||
431 | return Mapper(IO, Record); | |||
432 | } | |||
433 | ||||
434 | Error TypeRecordMapping::visitKnownMember(CVMemberRecord &CVR, | |||
435 | NestedTypeRecord &Record) { | |||
436 | uint16_t Padding = 0; | |||
437 | error(IO.mapInteger(Padding))if (auto EC = IO.mapInteger(Padding)) return EC;; | |||
438 | error(IO.mapInteger(Record.Type))if (auto EC = IO.mapInteger(Record.Type)) return EC;; | |||
439 | error(IO.mapStringZ(Record.Name))if (auto EC = IO.mapStringZ(Record.Name)) return EC;; | |||
440 | ||||
441 | return Error::success(); | |||
442 | } | |||
443 | ||||
444 | Error TypeRecordMapping::visitKnownMember(CVMemberRecord &CVR, | |||
445 | StaticDataMemberRecord &Record) { | |||
446 | ||||
447 | error(IO.mapInteger(Record.Attrs.Attrs))if (auto EC = IO.mapInteger(Record.Attrs.Attrs)) return EC;; | |||
448 | error(IO.mapInteger(Record.Type))if (auto EC = IO.mapInteger(Record.Type)) return EC;; | |||
449 | error(IO.mapStringZ(Record.Name))if (auto EC = IO.mapStringZ(Record.Name)) return EC;; | |||
450 | ||||
451 | return Error::success(); | |||
452 | } | |||
453 | ||||
454 | Error TypeRecordMapping::visitKnownMember(CVMemberRecord &CVR, | |||
455 | VirtualBaseClassRecord &Record) { | |||
456 | ||||
457 | error(IO.mapInteger(Record.Attrs.Attrs))if (auto EC = IO.mapInteger(Record.Attrs.Attrs)) return EC;; | |||
458 | error(IO.mapInteger(Record.BaseType))if (auto EC = IO.mapInteger(Record.BaseType)) return EC;; | |||
459 | error(IO.mapInteger(Record.VBPtrType))if (auto EC = IO.mapInteger(Record.VBPtrType)) return EC;; | |||
460 | error(IO.mapEncodedInteger(Record.VBPtrOffset))if (auto EC = IO.mapEncodedInteger(Record.VBPtrOffset)) return EC;; | |||
461 | error(IO.mapEncodedInteger(Record.VTableIndex))if (auto EC = IO.mapEncodedInteger(Record.VTableIndex)) return EC;; | |||
462 | ||||
463 | return Error::success(); | |||
464 | } | |||
465 | ||||
466 | Error TypeRecordMapping::visitKnownMember(CVMemberRecord &CVR, | |||
467 | VFPtrRecord &Record) { | |||
468 | uint16_t Padding = 0; | |||
469 | error(IO.mapInteger(Padding))if (auto EC = IO.mapInteger(Padding)) return EC;; | |||
470 | error(IO.mapInteger(Record.Type))if (auto EC = IO.mapInteger(Record.Type)) return EC;; | |||
471 | ||||
472 | return Error::success(); | |||
473 | } | |||
474 | ||||
475 | Error TypeRecordMapping::visitKnownMember(CVMemberRecord &CVR, | |||
476 | ListContinuationRecord &Record) { | |||
477 | uint16_t Padding = 0; | |||
478 | error(IO.mapInteger(Padding))if (auto EC = IO.mapInteger(Padding)) return EC;; | |||
479 | error(IO.mapInteger(Record.ContinuationIndex))if (auto EC = IO.mapInteger(Record.ContinuationIndex)) return EC;; | |||
480 | ||||
481 | return Error::success(); | |||
482 | } |
1 | //===- CodeViewRecordIO.h ---------------------------------------*- C++ -*-===// |
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 | #ifndef LLVM_DEBUGINFO_CODEVIEW_CODEVIEWRECORDIO_H |
11 | #define LLVM_DEBUGINFO_CODEVIEW_CODEVIEWRECORDIO_H |
12 | |
13 | #include "llvm/ADT/APSInt.h" |
14 | #include "llvm/ADT/None.h" |
15 | #include "llvm/ADT/Optional.h" |
16 | #include "llvm/ADT/SmallVector.h" |
17 | #include "llvm/ADT/StringRef.h" |
18 | #include "llvm/DebugInfo/CodeView/CodeViewError.h" |
19 | #include "llvm/DebugInfo/CodeView/TypeRecord.h" |
20 | #include "llvm/Support/BinaryStreamReader.h" |
21 | #include "llvm/Support/BinaryStreamWriter.h" |
22 | #include "llvm/Support/Error.h" |
23 | #include <cassert> |
24 | #include <cstdint> |
25 | #include <type_traits> |
26 | |
27 | namespace llvm { |
28 | namespace codeview { |
29 | |
30 | class CodeViewRecordIO { |
31 | uint32_t getCurrentOffset() const { |
32 | return (isWriting()) ? Writer->getOffset() : Reader->getOffset(); |
33 | } |
34 | |
35 | public: |
36 | explicit CodeViewRecordIO(BinaryStreamReader &Reader) : Reader(&Reader) {} |
37 | explicit CodeViewRecordIO(BinaryStreamWriter &Writer) : Writer(&Writer) {} |
38 | |
39 | Error beginRecord(Optional<uint32_t> MaxLength); |
40 | Error endRecord(); |
41 | |
42 | Error mapInteger(TypeIndex &TypeInd); |
43 | |
44 | bool isReading() const { return Reader != nullptr; } |
45 | bool isWriting() const { return !isReading(); } |
46 | |
47 | uint32_t maxFieldLength() const; |
48 | |
49 | template <typename T> Error mapObject(T &Value) { |
50 | if (isWriting()) |
51 | return Writer->writeObject(Value); |
52 | |
53 | const T *ValuePtr; |
54 | if (auto EC = Reader->readObject(ValuePtr)) |
55 | return EC; |
56 | Value = *ValuePtr; |
57 | return Error::success(); |
58 | } |
59 | |
60 | template <typename T> Error mapInteger(T &Value) { |
61 | if (isWriting()) |
62 | return Writer->writeInteger(Value); |
63 | |
64 | return Reader->readInteger(Value); |
65 | } |
66 | |
67 | template <typename T> Error mapEnum(T &Value) { |
68 | if (sizeof(Value) > maxFieldLength()) |
69 | return make_error<CodeViewError>(cv_error_code::insufficient_buffer); |
70 | |
71 | using U = typename std::underlying_type<T>::type; |
72 | U X; |
73 | if (isWriting()) |
74 | X = static_cast<U>(Value); |
75 | |
76 | if (auto EC = mapInteger(X)) |
77 | return EC; |
78 | if (isReading()) |
79 | Value = static_cast<T>(X); |
80 | return Error::success(); |
81 | } |
82 | |
83 | Error mapEncodedInteger(int64_t &Value); |
84 | Error mapEncodedInteger(uint64_t &Value); |
85 | Error mapEncodedInteger(APSInt &Value); |
86 | Error mapStringZ(StringRef &Value); |
87 | Error mapGuid(GUID &Guid); |
88 | |
89 | Error mapStringZVectorZ(std::vector<StringRef> &Value); |
90 | |
91 | template <typename SizeType, typename T, typename ElementMapper> |
92 | Error mapVectorN(T &Items, const ElementMapper &Mapper) { |
93 | SizeType Size; |
94 | if (isWriting()) { |
95 | Size = static_cast<SizeType>(Items.size()); |
96 | if (auto EC = Writer->writeInteger(Size)) |
97 | return EC; |
98 | |
99 | for (auto &X : Items) { |
100 | if (auto EC = Mapper(*this, X)) |
101 | return EC; |
102 | } |
103 | } else { |
104 | if (auto EC = Reader->readInteger(Size)) |
105 | return EC; |
106 | for (SizeType I = 0; I < Size; ++I) { |
107 | typename T::value_type Item; |
108 | if (auto EC = Mapper(*this, Item)) |
109 | return EC; |
110 | Items.push_back(Item); |
111 | } |
112 | } |
113 | |
114 | return Error::success(); |
115 | } |
116 | |
117 | template <typename T, typename ElementMapper> |
118 | Error mapVectorTail(T &Items, const ElementMapper &Mapper) { |
119 | if (isWriting()) { |
120 | for (auto &Item : Items) { |
121 | if (auto EC = Mapper(*this, Item)) |
122 | return EC; |
123 | } |
124 | } else { |
125 | typename T::value_type Field; |
126 | // Stop when we run out of bytes or we hit record padding bytes. |
127 | while (!Reader->empty() && Reader->peek() < 0xf0 /* LF_PAD0 */) { |
128 | if (auto EC = Mapper(*this, Field)) |
129 | return EC; |
130 | Items.push_back(Field); |
131 | } |
132 | } |
133 | return Error::success(); |
134 | } |
135 | |
136 | Error mapByteVectorTail(ArrayRef<uint8_t> &Bytes); |
137 | Error mapByteVectorTail(std::vector<uint8_t> &Bytes); |
138 | |
139 | Error padToAlignment(uint32_t Align); |
140 | Error skipPadding(); |
141 | |
142 | private: |
143 | Error writeEncodedSignedInteger(const int64_t &Value); |
144 | Error writeEncodedUnsignedInteger(const uint64_t &Value); |
145 | |
146 | struct RecordLimit { |
147 | uint32_t BeginOffset; |
148 | Optional<uint32_t> MaxLength; |
149 | |
150 | Optional<uint32_t> bytesRemaining(uint32_t CurrentOffset) const { |
151 | if (!MaxLength.hasValue()) |
152 | return None; |
153 | assert(CurrentOffset >= BeginOffset)(static_cast <bool> (CurrentOffset >= BeginOffset) ? void (0) : __assert_fail ("CurrentOffset >= BeginOffset", "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/DebugInfo/CodeView/CodeViewRecordIO.h" , 153, __extension__ __PRETTY_FUNCTION__)); |
154 | |
155 | uint32_t BytesUsed = CurrentOffset - BeginOffset; |
156 | if (BytesUsed >= *MaxLength) |
157 | return 0; |
158 | return *MaxLength - BytesUsed; |
159 | } |
160 | }; |
161 | |
162 | SmallVector<RecordLimit, 2> Limits; |
163 | |
164 | BinaryStreamReader *Reader = nullptr; |
165 | BinaryStreamWriter *Writer = nullptr; |
166 | }; |
167 | |
168 | } // end namespace codeview |
169 | } // end namespace llvm |
170 | |
171 | #endif // LLVM_DEBUGINFO_CODEVIEW_CODEVIEWRECORDIO_H |
1 | //===- BinaryStreamReader.h - Reads objects from a binary stream *- C++ -*-===// |
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 | #ifndef LLVM_SUPPORT_BINARYSTREAMREADER_H |
11 | #define LLVM_SUPPORT_BINARYSTREAMREADER_H |
12 | |
13 | #include "llvm/ADT/ArrayRef.h" |
14 | #include "llvm/ADT/STLExtras.h" |
15 | #include "llvm/Support/BinaryStreamArray.h" |
16 | #include "llvm/Support/BinaryStreamRef.h" |
17 | #include "llvm/Support/ConvertUTF.h" |
18 | #include "llvm/Support/Endian.h" |
19 | #include "llvm/Support/Error.h" |
20 | #include "llvm/Support/type_traits.h" |
21 | |
22 | #include <string> |
23 | #include <type_traits> |
24 | |
25 | namespace llvm { |
26 | |
27 | /// \brief Provides read only access to a subclass of `BinaryStream`. Provides |
28 | /// bounds checking and helpers for writing certain common data types such as |
29 | /// null-terminated strings, integers in various flavors of endianness, etc. |
30 | /// Can be subclassed to provide reading of custom datatypes, although no |
31 | /// are overridable. |
32 | class BinaryStreamReader { |
33 | public: |
34 | BinaryStreamReader() = default; |
35 | explicit BinaryStreamReader(BinaryStreamRef Ref); |
36 | explicit BinaryStreamReader(BinaryStream &Stream); |
37 | explicit BinaryStreamReader(ArrayRef<uint8_t> Data, |
38 | llvm::support::endianness Endian); |
39 | explicit BinaryStreamReader(StringRef Data, llvm::support::endianness Endian); |
40 | |
41 | BinaryStreamReader(const BinaryStreamReader &Other) |
42 | : Stream(Other.Stream), Offset(Other.Offset) {} |
43 | |
44 | BinaryStreamReader &operator=(const BinaryStreamReader &Other) { |
45 | Stream = Other.Stream; |
46 | Offset = Other.Offset; |
47 | return *this; |
48 | } |
49 | |
50 | virtual ~BinaryStreamReader() {} |
51 | |
52 | /// Read as much as possible from the underlying string at the current offset |
53 | /// without invoking a copy, and set \p Buffer to the resulting data slice. |
54 | /// Updates the stream's offset to point after the newly read data. |
55 | /// |
56 | /// \returns a success error code if the data was successfully read, otherwise |
57 | /// returns an appropriate error code. |
58 | Error readLongestContiguousChunk(ArrayRef<uint8_t> &Buffer); |
59 | |
60 | /// Read \p Size bytes from the underlying stream at the current offset and |
61 | /// and set \p Buffer to the resulting data slice. Whether a copy occurs |
62 | /// depends on the implementation of the underlying stream. Updates the |
63 | /// stream's offset to point after the newly read data. |
64 | /// |
65 | /// \returns a success error code if the data was successfully read, otherwise |
66 | /// returns an appropriate error code. |
67 | Error readBytes(ArrayRef<uint8_t> &Buffer, uint32_t Size); |
68 | |
69 | /// Read an integer of the specified endianness into \p Dest and update the |
70 | /// stream's offset. The data is always copied from the stream's underlying |
71 | /// buffer into \p Dest. Updates the stream's offset to point after the newly |
72 | /// read data. |
73 | /// |
74 | /// \returns a success error code if the data was successfully read, otherwise |
75 | /// returns an appropriate error code. |
76 | template <typename T> Error readInteger(T &Dest) { |
77 | static_assert(std::is_integral<T>::value, |
78 | "Cannot call readInteger with non-integral value!"); |
79 | |
80 | ArrayRef<uint8_t> Bytes; |
81 | if (auto EC = readBytes(Bytes, sizeof(T))) |
82 | return EC; |
83 | |
84 | Dest = llvm::support::endian::read<T, llvm::support::unaligned>( |
85 | Bytes.data(), Stream.getEndian()); |
86 | return Error::success(); |
87 | } |
88 | |
89 | /// Similar to readInteger. |
90 | template <typename T> Error readEnum(T &Dest) { |
91 | static_assert(std::is_enum<T>::value, |
92 | "Cannot call readEnum with non-enum value!"); |
93 | typename std::underlying_type<T>::type N; |
94 | if (auto EC = readInteger(N)) |
95 | return EC; |
96 | Dest = static_cast<T>(N); |
97 | return Error::success(); |
98 | } |
99 | |
100 | /// Read a null terminated string from \p Dest. Whether a copy occurs depends |
101 | /// on the implementation of the underlying stream. Updates the stream's |
102 | /// offset to point after the newly read data. |
103 | /// |
104 | /// \returns a success error code if the data was successfully read, otherwise |
105 | /// returns an appropriate error code. |
106 | Error readCString(StringRef &Dest); |
107 | |
108 | /// Similar to readCString, however read a null-terminated UTF16 string |
109 | /// instead. |
110 | /// |
111 | /// \returns a success error code if the data was successfully read, otherwise |
112 | /// returns an appropriate error code. |
113 | Error readWideString(ArrayRef<UTF16> &Dest); |
114 | |
115 | /// Read a \p Length byte string into \p Dest. Whether a copy occurs depends |
116 | /// on the implementation of the underlying stream. Updates the stream's |
117 | /// offset to point after the newly read data. |
118 | /// |
119 | /// \returns a success error code if the data was successfully read, otherwise |
120 | /// returns an appropriate error code. |
121 | Error readFixedString(StringRef &Dest, uint32_t Length); |
122 | |
123 | /// Read the entire remainder of the underlying stream into \p Ref. This is |
124 | /// equivalent to calling getUnderlyingStream().slice(Offset). Updates the |
125 | /// stream's offset to point to the end of the stream. Never causes a copy. |
126 | /// |
127 | /// \returns a success error code if the data was successfully read, otherwise |
128 | /// returns an appropriate error code. |
129 | Error readStreamRef(BinaryStreamRef &Ref); |
130 | |
131 | /// Read \p Length bytes from the underlying stream into \p Ref. This is |
132 | /// equivalent to calling getUnderlyingStream().slice(Offset, Length). |
133 | /// Updates the stream's offset to point after the newly read object. Never |
134 | /// causes a copy. |
135 | /// |
136 | /// \returns a success error code if the data was successfully read, otherwise |
137 | /// returns an appropriate error code. |
138 | Error readStreamRef(BinaryStreamRef &Ref, uint32_t Length); |
139 | |
140 | /// Read \p Length bytes from the underlying stream into \p Stream. This is |
141 | /// equivalent to calling getUnderlyingStream().slice(Offset, Length). |
142 | /// Updates the stream's offset to point after the newly read object. Never |
143 | /// causes a copy. |
144 | /// |
145 | /// \returns a success error code if the data was successfully read, otherwise |
146 | /// returns an appropriate error code. |
147 | Error readSubstream(BinarySubstreamRef &Stream, uint32_t Size); |
148 | |
149 | /// Get a pointer to an object of type T from the underlying stream, as if by |
150 | /// memcpy, and store the result into \p Dest. It is up to the caller to |
151 | /// ensure that objects of type T can be safely treated in this manner. |
152 | /// Updates the stream's offset to point after the newly read object. Whether |
153 | /// a copy occurs depends upon the implementation of the underlying |
154 | /// stream. |
155 | /// |
156 | /// \returns a success error code if the data was successfully read, otherwise |
157 | /// returns an appropriate error code. |
158 | template <typename T> Error readObject(const T *&Dest) { |
159 | ArrayRef<uint8_t> Buffer; |
160 | if (auto EC = readBytes(Buffer, sizeof(T))) |
161 | return EC; |
162 | Dest = reinterpret_cast<const T *>(Buffer.data()); |
163 | return Error::success(); |
164 | } |
165 | |
166 | /// Get a reference to a \p NumElements element array of objects of type T |
167 | /// from the underlying stream as if by memcpy, and store the resulting array |
168 | /// slice into \p array. It is up to the caller to ensure that objects of |
169 | /// type T can be safely treated in this manner. Updates the stream's offset |
170 | /// to point after the newly read object. Whether a copy occurs depends upon |
171 | /// the implementation of the underlying stream. |
172 | /// |
173 | /// \returns a success error code if the data was successfully read, otherwise |
174 | /// returns an appropriate error code. |
175 | template <typename T> |
176 | Error readArray(ArrayRef<T> &Array, uint32_t NumElements) { |
177 | ArrayRef<uint8_t> Bytes; |
178 | if (NumElements == 0) { |
179 | Array = ArrayRef<T>(); |
180 | return Error::success(); |
181 | } |
182 | |
183 | if (NumElements > UINT32_MAX(4294967295U) / sizeof(T)) |
184 | return make_error<BinaryStreamError>( |
185 | stream_error_code::invalid_array_size); |
186 | |
187 | if (auto EC = readBytes(Bytes, NumElements * sizeof(T))) |
188 | return EC; |
189 | |
190 | assert(alignmentAdjustment(Bytes.data(), alignof(T)) == 0 &&(static_cast <bool> (alignmentAdjustment(Bytes.data(), alignof (T)) == 0 && "Reading at invalid alignment!") ? void ( 0) : __assert_fail ("alignmentAdjustment(Bytes.data(), alignof(T)) == 0 && \"Reading at invalid alignment!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/Support/BinaryStreamReader.h" , 191, __extension__ __PRETTY_FUNCTION__)) |
191 | "Reading at invalid alignment!")(static_cast <bool> (alignmentAdjustment(Bytes.data(), alignof (T)) == 0 && "Reading at invalid alignment!") ? void ( 0) : __assert_fail ("alignmentAdjustment(Bytes.data(), alignof(T)) == 0 && \"Reading at invalid alignment!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/Support/BinaryStreamReader.h" , 191, __extension__ __PRETTY_FUNCTION__)); |
192 | |
193 | Array = ArrayRef<T>(reinterpret_cast<const T *>(Bytes.data()), NumElements); |
194 | return Error::success(); |
195 | } |
196 | |
197 | /// Read a VarStreamArray of size \p Size bytes and store the result into |
198 | /// \p Array. Updates the stream's offset to point after the newly read |
199 | /// array. Never causes a copy (although iterating the elements of the |
200 | /// VarStreamArray may, depending upon the implementation of the underlying |
201 | /// stream). |
202 | /// |
203 | /// \returns a success error code if the data was successfully read, otherwise |
204 | /// returns an appropriate error code. |
205 | template <typename T, typename U> |
206 | Error readArray(VarStreamArray<T, U> &Array, uint32_t Size) { |
207 | BinaryStreamRef S; |
208 | if (auto EC = readStreamRef(S, Size)) |
209 | return EC; |
210 | Array.setUnderlyingStream(S); |
211 | return Error::success(); |
212 | } |
213 | |
214 | /// Read a FixedStreamArray of \p NumItems elements and store the result into |
215 | /// \p Array. Updates the stream's offset to point after the newly read |
216 | /// array. Never causes a copy (although iterating the elements of the |
217 | /// FixedStreamArray may, depending upon the implementation of the underlying |
218 | /// stream). |
219 | /// |
220 | /// \returns a success error code if the data was successfully read, otherwise |
221 | /// returns an appropriate error code. |
222 | template <typename T> |
223 | Error readArray(FixedStreamArray<T> &Array, uint32_t NumItems) { |
224 | if (NumItems == 0) { |
225 | Array = FixedStreamArray<T>(); |
226 | return Error::success(); |
227 | } |
228 | |
229 | if (NumItems > UINT32_MAX(4294967295U) / sizeof(T)) |
230 | return make_error<BinaryStreamError>( |
231 | stream_error_code::invalid_array_size); |
232 | |
233 | BinaryStreamRef View; |
234 | if (auto EC = readStreamRef(View, NumItems * sizeof(T))) |
235 | return EC; |
236 | |
237 | Array = FixedStreamArray<T>(View); |
238 | return Error::success(); |
239 | } |
240 | |
241 | bool empty() const { return bytesRemaining() == 0; } |
242 | void setOffset(uint32_t Off) { Offset = Off; } |
243 | uint32_t getOffset() const { return Offset; } |
244 | uint32_t getLength() const { return Stream.getLength(); } |
245 | uint32_t bytesRemaining() const { return getLength() - getOffset(); } |
246 | |
247 | /// Advance the stream's offset by \p Amount bytes. |
248 | /// |
249 | /// \returns a success error code if at least \p Amount bytes remain in the |
250 | /// stream, otherwise returns an appropriate error code. |
251 | Error skip(uint32_t Amount); |
252 | |
253 | /// Examine the next byte of the underlying stream without advancing the |
254 | /// stream's offset. If the stream is empty the behavior is undefined. |
255 | /// |
256 | /// \returns the next byte in the stream. |
257 | uint8_t peek() const; |
258 | |
259 | Error padToAlignment(uint32_t Align); |
260 | |
261 | std::pair<BinaryStreamReader, BinaryStreamReader> |
262 | split(uint32_t Offset) const; |
263 | |
264 | private: |
265 | BinaryStreamRef Stream; |
266 | uint32_t Offset = 0; |
267 | }; |
268 | } // namespace llvm |
269 | |
270 | #endif // LLVM_SUPPORT_BINARYSTREAMREADER_H |
1 | //===- llvm/Support/Error.h - Recoverable error handling --------*- C++ -*-===// |
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 defines an API used to report recoverable errors. |
11 | // |
12 | //===----------------------------------------------------------------------===// |
13 | |
14 | #ifndef LLVM_SUPPORT_ERROR_H |
15 | #define LLVM_SUPPORT_ERROR_H |
16 | |
17 | #include "llvm/ADT/SmallVector.h" |
18 | #include "llvm/ADT/STLExtras.h" |
19 | #include "llvm/ADT/StringExtras.h" |
20 | #include "llvm/ADT/Twine.h" |
21 | #include "llvm/Config/abi-breaking.h" |
22 | #include "llvm/Support/AlignOf.h" |
23 | #include "llvm/Support/Compiler.h" |
24 | #include "llvm/Support/Debug.h" |
25 | #include "llvm/Support/ErrorHandling.h" |
26 | #include "llvm/Support/ErrorOr.h" |
27 | #include "llvm/Support/raw_ostream.h" |
28 | #include <algorithm> |
29 | #include <cassert> |
30 | #include <cstdint> |
31 | #include <cstdlib> |
32 | #include <functional> |
33 | #include <memory> |
34 | #include <new> |
35 | #include <string> |
36 | #include <system_error> |
37 | #include <type_traits> |
38 | #include <utility> |
39 | #include <vector> |
40 | |
41 | namespace llvm { |
42 | |
43 | class ErrorSuccess; |
44 | |
45 | /// Base class for error info classes. Do not extend this directly: Extend |
46 | /// the ErrorInfo template subclass instead. |
47 | class ErrorInfoBase { |
48 | public: |
49 | virtual ~ErrorInfoBase() = default; |
50 | |
51 | /// Print an error message to an output stream. |
52 | virtual void log(raw_ostream &OS) const = 0; |
53 | |
54 | /// Return the error message as a string. |
55 | virtual std::string message() const { |
56 | std::string Msg; |
57 | raw_string_ostream OS(Msg); |
58 | log(OS); |
59 | return OS.str(); |
60 | } |
61 | |
62 | /// Convert this error to a std::error_code. |
63 | /// |
64 | /// This is a temporary crutch to enable interaction with code still |
65 | /// using std::error_code. It will be removed in the future. |
66 | virtual std::error_code convertToErrorCode() const = 0; |
67 | |
68 | // Returns the class ID for this type. |
69 | static const void *classID() { return &ID; } |
70 | |
71 | // Returns the class ID for the dynamic type of this ErrorInfoBase instance. |
72 | virtual const void *dynamicClassID() const = 0; |
73 | |
74 | // Check whether this instance is a subclass of the class identified by |
75 | // ClassID. |
76 | virtual bool isA(const void *const ClassID) const { |
77 | return ClassID == classID(); |
78 | } |
79 | |
80 | // Check whether this instance is a subclass of ErrorInfoT. |
81 | template <typename ErrorInfoT> bool isA() const { |
82 | return isA(ErrorInfoT::classID()); |
83 | } |
84 | |
85 | private: |
86 | virtual void anchor(); |
87 | |
88 | static char ID; |
89 | }; |
90 | |
91 | /// Lightweight error class with error context and mandatory checking. |
92 | /// |
93 | /// Instances of this class wrap a ErrorInfoBase pointer. Failure states |
94 | /// are represented by setting the pointer to a ErrorInfoBase subclass |
95 | /// instance containing information describing the failure. Success is |
96 | /// represented by a null pointer value. |
97 | /// |
98 | /// Instances of Error also contains a 'Checked' flag, which must be set |
99 | /// before the destructor is called, otherwise the destructor will trigger a |
100 | /// runtime error. This enforces at runtime the requirement that all Error |
101 | /// instances be checked or returned to the caller. |
102 | /// |
103 | /// There are two ways to set the checked flag, depending on what state the |
104 | /// Error instance is in. For Error instances indicating success, it |
105 | /// is sufficient to invoke the boolean conversion operator. E.g.: |
106 | /// |
107 | /// @code{.cpp} |
108 | /// Error foo(<...>); |
109 | /// |
110 | /// if (auto E = foo(<...>)) |
111 | /// return E; // <- Return E if it is in the error state. |
112 | /// // We have verified that E was in the success state. It can now be safely |
113 | /// // destroyed. |
114 | /// @endcode |
115 | /// |
116 | /// A success value *can not* be dropped. For example, just calling 'foo(<...>)' |
117 | /// without testing the return value will raise a runtime error, even if foo |
118 | /// returns success. |
119 | /// |
120 | /// For Error instances representing failure, you must use either the |
121 | /// handleErrors or handleAllErrors function with a typed handler. E.g.: |
122 | /// |
123 | /// @code{.cpp} |
124 | /// class MyErrorInfo : public ErrorInfo<MyErrorInfo> { |
125 | /// // Custom error info. |
126 | /// }; |
127 | /// |
128 | /// Error foo(<...>) { return make_error<MyErrorInfo>(...); } |
129 | /// |
130 | /// auto E = foo(<...>); // <- foo returns failure with MyErrorInfo. |
131 | /// auto NewE = |
132 | /// handleErrors(E, |
133 | /// [](const MyErrorInfo &M) { |
134 | /// // Deal with the error. |
135 | /// }, |
136 | /// [](std::unique_ptr<OtherError> M) -> Error { |
137 | /// if (canHandle(*M)) { |
138 | /// // handle error. |
139 | /// return Error::success(); |
140 | /// } |
141 | /// // Couldn't handle this error instance. Pass it up the stack. |
142 | /// return Error(std::move(M)); |
143 | /// ); |
144 | /// // Note - we must check or return NewE in case any of the handlers |
145 | /// // returned a new error. |
146 | /// @endcode |
147 | /// |
148 | /// The handleAllErrors function is identical to handleErrors, except |
149 | /// that it has a void return type, and requires all errors to be handled and |
150 | /// no new errors be returned. It prevents errors (assuming they can all be |
151 | /// handled) from having to be bubbled all the way to the top-level. |
152 | /// |
153 | /// *All* Error instances must be checked before destruction, even if |
154 | /// they're moved-assigned or constructed from Success values that have already |
155 | /// been checked. This enforces checking through all levels of the call stack. |
156 | class LLVM_NODISCARD[[clang::warn_unused_result]] Error { |
157 | // ErrorList needs to be able to yank ErrorInfoBase pointers out of this |
158 | // class to add to the error list. |
159 | friend class ErrorList; |
160 | |
161 | // handleErrors needs to be able to set the Checked flag. |
162 | template <typename... HandlerTs> |
163 | friend Error handleErrors(Error E, HandlerTs &&... Handlers); |
164 | |
165 | // Expected<T> needs to be able to steal the payload when constructed from an |
166 | // error. |
167 | template <typename T> friend class Expected; |
168 | |
169 | protected: |
170 | /// Create a success value. Prefer using 'Error::success()' for readability |
171 | Error() { |
172 | setPtr(nullptr); |
173 | setChecked(false); |
174 | } |
175 | |
176 | public: |
177 | /// Create a success value. |
178 | static ErrorSuccess success(); |
179 | |
180 | // Errors are not copy-constructable. |
181 | Error(const Error &Other) = delete; |
182 | |
183 | /// Move-construct an error value. The newly constructed error is considered |
184 | /// unchecked, even if the source error had been checked. The original error |
185 | /// becomes a checked Success value, regardless of its original state. |
186 | Error(Error &&Other) { |
187 | setChecked(true); |
188 | *this = std::move(Other); |
189 | } |
190 | |
191 | /// Create an error value. Prefer using the 'make_error' function, but |
192 | /// this constructor can be useful when "re-throwing" errors from handlers. |
193 | Error(std::unique_ptr<ErrorInfoBase> Payload) { |
194 | setPtr(Payload.release()); |
195 | setChecked(false); |
196 | } |
197 | |
198 | // Errors are not copy-assignable. |
199 | Error &operator=(const Error &Other) = delete; |
200 | |
201 | /// Move-assign an error value. The current error must represent success, you |
202 | /// you cannot overwrite an unhandled error. The current error is then |
203 | /// considered unchecked. The source error becomes a checked success value, |
204 | /// regardless of its original state. |
205 | Error &operator=(Error &&Other) { |
206 | // Don't allow overwriting of unchecked values. |
207 | assertIsChecked(); |
208 | setPtr(Other.getPtr()); |
209 | |
210 | // This Error is unchecked, even if the source error was checked. |
211 | setChecked(false); |
212 | |
213 | // Null out Other's payload and set its checked bit. |
214 | Other.setPtr(nullptr); |
215 | Other.setChecked(true); |
216 | |
217 | return *this; |
218 | } |
219 | |
220 | /// Destroy a Error. Fails with a call to abort() if the error is |
221 | /// unchecked. |
222 | ~Error() { |
223 | assertIsChecked(); |
224 | delete getPtr(); |
225 | } |
226 | |
227 | /// Bool conversion. Returns true if this Error is in a failure state, |
228 | /// and false if it is in an accept state. If the error is in a Success state |
229 | /// it will be considered checked. |
230 | explicit operator bool() { |
231 | setChecked(getPtr() == nullptr); |
232 | return getPtr() != nullptr; |
233 | } |
234 | |
235 | /// Check whether one error is a subclass of another. |
236 | template <typename ErrT> bool isA() const { |
237 | return getPtr() && getPtr()->isA(ErrT::classID()); |
238 | } |
239 | |
240 | /// Returns the dynamic class id of this error, or null if this is a success |
241 | /// value. |
242 | const void* dynamicClassID() const { |
243 | if (!getPtr()) |
244 | return nullptr; |
245 | return getPtr()->dynamicClassID(); |
246 | } |
247 | |
248 | private: |
249 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
250 | // assertIsChecked() happens very frequently, but under normal circumstances |
251 | // is supposed to be a no-op. So we want it to be inlined, but having a bunch |
252 | // of debug prints can cause the function to be too large for inlining. So |
253 | // it's important that we define this function out of line so that it can't be |
254 | // inlined. |
255 | LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) |
256 | void fatalUncheckedError() const; |
257 | #endif |
258 | |
259 | void assertIsChecked() { |
260 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
261 | if (LLVM_UNLIKELY(!getChecked() || getPtr())__builtin_expect((bool)(!getChecked() || getPtr()), false)) |
262 | fatalUncheckedError(); |
263 | #endif |
264 | } |
265 | |
266 | ErrorInfoBase *getPtr() const { |
267 | return reinterpret_cast<ErrorInfoBase*>( |
268 | reinterpret_cast<uintptr_t>(Payload) & |
269 | ~static_cast<uintptr_t>(0x1)); |
270 | } |
271 | |
272 | void setPtr(ErrorInfoBase *EI) { |
273 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
274 | Payload = reinterpret_cast<ErrorInfoBase*>( |
275 | (reinterpret_cast<uintptr_t>(EI) & |
276 | ~static_cast<uintptr_t>(0x1)) | |
277 | (reinterpret_cast<uintptr_t>(Payload) & 0x1)); |
278 | #else |
279 | Payload = EI; |
280 | #endif |
281 | } |
282 | |
283 | bool getChecked() const { |
284 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
285 | return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0; |
286 | #else |
287 | return true; |
288 | #endif |
289 | } |
290 | |
291 | void setChecked(bool V) { |
292 | Payload = reinterpret_cast<ErrorInfoBase*>( |
293 | (reinterpret_cast<uintptr_t>(Payload) & |
294 | ~static_cast<uintptr_t>(0x1)) | |
295 | (V ? 0 : 1)); |
296 | } |
297 | |
298 | std::unique_ptr<ErrorInfoBase> takePayload() { |
299 | std::unique_ptr<ErrorInfoBase> Tmp(getPtr()); |
300 | setPtr(nullptr); |
301 | setChecked(true); |
302 | return Tmp; |
303 | } |
304 | |
305 | ErrorInfoBase *Payload = nullptr; |
306 | }; |
307 | |
308 | /// Subclass of Error for the sole purpose of identifying the success path in |
309 | /// the type system. This allows to catch invalid conversion to Expected<T> at |
310 | /// compile time. |
311 | class ErrorSuccess : public Error {}; |
312 | |
313 | inline ErrorSuccess Error::success() { return ErrorSuccess(); } |
314 | |
315 | /// Make a Error instance representing failure using the given error info |
316 | /// type. |
317 | template <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) { |
318 | return Error(llvm::make_unique<ErrT>(std::forward<ArgTs>(Args)...)); |
319 | } |
320 | |
321 | /// Base class for user error types. Users should declare their error types |
322 | /// like: |
323 | /// |
324 | /// class MyError : public ErrorInfo<MyError> { |
325 | /// .... |
326 | /// }; |
327 | /// |
328 | /// This class provides an implementation of the ErrorInfoBase::kind |
329 | /// method, which is used by the Error RTTI system. |
330 | template <typename ThisErrT, typename ParentErrT = ErrorInfoBase> |
331 | class ErrorInfo : public ParentErrT { |
332 | public: |
333 | static const void *classID() { return &ThisErrT::ID; } |
334 | |
335 | const void *dynamicClassID() const override { return &ThisErrT::ID; } |
336 | |
337 | bool isA(const void *const ClassID) const override { |
338 | return ClassID == classID() || ParentErrT::isA(ClassID); |
339 | } |
340 | }; |
341 | |
342 | /// Special ErrorInfo subclass representing a list of ErrorInfos. |
343 | /// Instances of this class are constructed by joinError. |
344 | class ErrorList final : public ErrorInfo<ErrorList> { |
345 | // handleErrors needs to be able to iterate the payload list of an |
346 | // ErrorList. |
347 | template <typename... HandlerTs> |
348 | friend Error handleErrors(Error E, HandlerTs &&... Handlers); |
349 | |
350 | // joinErrors is implemented in terms of join. |
351 | friend Error joinErrors(Error, Error); |
352 | |
353 | public: |
354 | void log(raw_ostream &OS) const override { |
355 | OS << "Multiple errors:\n"; |
356 | for (auto &ErrPayload : Payloads) { |
357 | ErrPayload->log(OS); |
358 | OS << "\n"; |
359 | } |
360 | } |
361 | |
362 | std::error_code convertToErrorCode() const override; |
363 | |
364 | // Used by ErrorInfo::classID. |
365 | static char ID; |
366 | |
367 | private: |
368 | ErrorList(std::unique_ptr<ErrorInfoBase> Payload1, |
369 | std::unique_ptr<ErrorInfoBase> Payload2) { |
370 | assert(!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() &&(static_cast <bool> (!Payload1->isA<ErrorList> () && !Payload2->isA<ErrorList>() && "ErrorList constructor payloads should be singleton errors") ? void (0) : __assert_fail ("!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() && \"ErrorList constructor payloads should be singleton errors\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/Support/Error.h" , 371, __extension__ __PRETTY_FUNCTION__)) |
371 | "ErrorList constructor payloads should be singleton errors")(static_cast <bool> (!Payload1->isA<ErrorList> () && !Payload2->isA<ErrorList>() && "ErrorList constructor payloads should be singleton errors") ? void (0) : __assert_fail ("!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() && \"ErrorList constructor payloads should be singleton errors\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/Support/Error.h" , 371, __extension__ __PRETTY_FUNCTION__)); |
372 | Payloads.push_back(std::move(Payload1)); |
373 | Payloads.push_back(std::move(Payload2)); |
374 | } |
375 | |
376 | static Error join(Error E1, Error E2) { |
377 | if (!E1) |
378 | return E2; |
379 | if (!E2) |
380 | return E1; |
381 | if (E1.isA<ErrorList>()) { |
382 | auto &E1List = static_cast<ErrorList &>(*E1.getPtr()); |
383 | if (E2.isA<ErrorList>()) { |
384 | auto E2Payload = E2.takePayload(); |
385 | auto &E2List = static_cast<ErrorList &>(*E2Payload); |
386 | for (auto &Payload : E2List.Payloads) |
387 | E1List.Payloads.push_back(std::move(Payload)); |
388 | } else |
389 | E1List.Payloads.push_back(E2.takePayload()); |
390 | |
391 | return E1; |
392 | } |
393 | if (E2.isA<ErrorList>()) { |
394 | auto &E2List = static_cast<ErrorList &>(*E2.getPtr()); |
395 | E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload()); |
396 | return E2; |
397 | } |
398 | return Error(std::unique_ptr<ErrorList>( |
399 | new ErrorList(E1.takePayload(), E2.takePayload()))); |
400 | } |
401 | |
402 | std::vector<std::unique_ptr<ErrorInfoBase>> Payloads; |
403 | }; |
404 | |
405 | /// Concatenate errors. The resulting Error is unchecked, and contains the |
406 | /// ErrorInfo(s), if any, contained in E1, followed by the |
407 | /// ErrorInfo(s), if any, contained in E2. |
408 | inline Error joinErrors(Error E1, Error E2) { |
409 | return ErrorList::join(std::move(E1), std::move(E2)); |
410 | } |
411 | |
412 | /// Tagged union holding either a T or a Error. |
413 | /// |
414 | /// This class parallels ErrorOr, but replaces error_code with Error. Since |
415 | /// Error cannot be copied, this class replaces getError() with |
416 | /// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the |
417 | /// error class type. |
418 | template <class T> class LLVM_NODISCARD[[clang::warn_unused_result]] Expected { |
419 | template <class T1> friend class ExpectedAsOutParameter; |
420 | template <class OtherT> friend class Expected; |
421 | |
422 | static const bool isRef = std::is_reference<T>::value; |
423 | |
424 | using wrap = ReferenceStorage<typename std::remove_reference<T>::type>; |
425 | |
426 | using error_type = std::unique_ptr<ErrorInfoBase>; |
427 | |
428 | public: |
429 | using storage_type = typename std::conditional<isRef, wrap, T>::type; |
430 | using value_type = T; |
431 | |
432 | private: |
433 | using reference = typename std::remove_reference<T>::type &; |
434 | using const_reference = const typename std::remove_reference<T>::type &; |
435 | using pointer = typename std::remove_reference<T>::type *; |
436 | using const_pointer = const typename std::remove_reference<T>::type *; |
437 | |
438 | public: |
439 | /// Create an Expected<T> error value from the given Error. |
440 | Expected(Error Err) |
441 | : HasError(true) |
442 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
443 | // Expected is unchecked upon construction in Debug builds. |
444 | , Unchecked(true) |
445 | #endif |
446 | { |
447 | assert(Err && "Cannot create Expected<T> from Error success value.")(static_cast <bool> (Err && "Cannot create Expected<T> from Error success value." ) ? void (0) : __assert_fail ("Err && \"Cannot create Expected<T> from Error success value.\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/Support/Error.h" , 447, __extension__ __PRETTY_FUNCTION__)); |
448 | new (getErrorStorage()) error_type(Err.takePayload()); |
449 | } |
450 | |
451 | /// Forbid to convert from Error::success() implicitly, this avoids having |
452 | /// Expected<T> foo() { return Error::success(); } which compiles otherwise |
453 | /// but triggers the assertion above. |
454 | Expected(ErrorSuccess) = delete; |
455 | |
456 | /// Create an Expected<T> success value from the given OtherT value, which |
457 | /// must be convertible to T. |
458 | template <typename OtherT> |
459 | Expected(OtherT &&Val, |
460 | typename std::enable_if<std::is_convertible<OtherT, T>::value>::type |
461 | * = nullptr) |
462 | : HasError(false) |
463 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
464 | // Expected is unchecked upon construction in Debug builds. |
465 | , Unchecked(true) |
466 | #endif |
467 | { |
468 | new (getStorage()) storage_type(std::forward<OtherT>(Val)); |
469 | } |
470 | |
471 | /// Move construct an Expected<T> value. |
472 | Expected(Expected &&Other) { moveConstruct(std::move(Other)); } |
473 | |
474 | /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT |
475 | /// must be convertible to T. |
476 | template <class OtherT> |
477 | Expected(Expected<OtherT> &&Other, |
478 | typename std::enable_if<std::is_convertible<OtherT, T>::value>::type |
479 | * = nullptr) { |
480 | moveConstruct(std::move(Other)); |
481 | } |
482 | |
483 | /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT |
484 | /// isn't convertible to T. |
485 | template <class OtherT> |
486 | explicit Expected( |
487 | Expected<OtherT> &&Other, |
488 | typename std::enable_if<!std::is_convertible<OtherT, T>::value>::type * = |
489 | nullptr) { |
490 | moveConstruct(std::move(Other)); |
491 | } |
492 | |
493 | /// Move-assign from another Expected<T>. |
494 | Expected &operator=(Expected &&Other) { |
495 | moveAssign(std::move(Other)); |
496 | return *this; |
497 | } |
498 | |
499 | /// Destroy an Expected<T>. |
500 | ~Expected() { |
501 | assertIsChecked(); |
502 | if (!HasError) |
503 | getStorage()->~storage_type(); |
504 | else |
505 | getErrorStorage()->~error_type(); |
506 | } |
507 | |
508 | /// \brief Return false if there is an error. |
509 | explicit operator bool() { |
510 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
511 | Unchecked = HasError; |
512 | #endif |
513 | return !HasError; |
514 | } |
515 | |
516 | /// \brief Returns a reference to the stored T value. |
517 | reference get() { |
518 | assertIsChecked(); |
519 | return *getStorage(); |
520 | } |
521 | |
522 | /// \brief Returns a const reference to the stored T value. |
523 | const_reference get() const { |
524 | assertIsChecked(); |
525 | return const_cast<Expected<T> *>(this)->get(); |
526 | } |
527 | |
528 | /// \brief Check that this Expected<T> is an error of type ErrT. |
529 | template <typename ErrT> bool errorIsA() const { |
530 | return HasError && (*getErrorStorage())->template isA<ErrT>(); |
531 | } |
532 | |
533 | /// \brief Take ownership of the stored error. |
534 | /// After calling this the Expected<T> is in an indeterminate state that can |
535 | /// only be safely destructed. No further calls (beside the destructor) should |
536 | /// be made on the Expected<T> vaule. |
537 | Error takeError() { |
538 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
539 | Unchecked = false; |
540 | #endif |
541 | return HasError ? Error(std::move(*getErrorStorage())) : Error::success(); |
542 | } |
543 | |
544 | /// \brief Returns a pointer to the stored T value. |
545 | pointer operator->() { |
546 | assertIsChecked(); |
547 | return toPointer(getStorage()); |
548 | } |
549 | |
550 | /// \brief Returns a const pointer to the stored T value. |
551 | const_pointer operator->() const { |
552 | assertIsChecked(); |
553 | return toPointer(getStorage()); |
554 | } |
555 | |
556 | /// \brief Returns a reference to the stored T value. |
557 | reference operator*() { |
558 | assertIsChecked(); |
559 | return *getStorage(); |
560 | } |
561 | |
562 | /// \brief Returns a const reference to the stored T value. |
563 | const_reference operator*() const { |
564 | assertIsChecked(); |
565 | return *getStorage(); |
566 | } |
567 | |
568 | private: |
569 | template <class T1> |
570 | static bool compareThisIfSameType(const T1 &a, const T1 &b) { |
571 | return &a == &b; |
572 | } |
573 | |
574 | template <class T1, class T2> |
575 | static bool compareThisIfSameType(const T1 &a, const T2 &b) { |
576 | return false; |
577 | } |
578 | |
579 | template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) { |
580 | HasError = Other.HasError; |
581 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
582 | Unchecked = true; |
583 | Other.Unchecked = false; |
584 | #endif |
585 | |
586 | if (!HasError) |
587 | new (getStorage()) storage_type(std::move(*Other.getStorage())); |
588 | else |
589 | new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage())); |
590 | } |
591 | |
592 | template <class OtherT> void moveAssign(Expected<OtherT> &&Other) { |
593 | assertIsChecked(); |
594 | |
595 | if (compareThisIfSameType(*this, Other)) |
596 | return; |
597 | |
598 | this->~Expected(); |
599 | new (this) Expected(std::move(Other)); |
600 | } |
601 | |
602 | pointer toPointer(pointer Val) { return Val; } |
603 | |
604 | const_pointer toPointer(const_pointer Val) const { return Val; } |
605 | |
606 | pointer toPointer(wrap *Val) { return &Val->get(); } |
607 | |
608 | const_pointer toPointer(const wrap *Val) const { return &Val->get(); } |
609 | |
610 | storage_type *getStorage() { |
611 | assert(!HasError && "Cannot get value when an error exists!")(static_cast <bool> (!HasError && "Cannot get value when an error exists!" ) ? void (0) : __assert_fail ("!HasError && \"Cannot get value when an error exists!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/Support/Error.h" , 611, __extension__ __PRETTY_FUNCTION__)); |
612 | return reinterpret_cast<storage_type *>(TStorage.buffer); |
613 | } |
614 | |
615 | const storage_type *getStorage() const { |
616 | assert(!HasError && "Cannot get value when an error exists!")(static_cast <bool> (!HasError && "Cannot get value when an error exists!" ) ? void (0) : __assert_fail ("!HasError && \"Cannot get value when an error exists!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/Support/Error.h" , 616, __extension__ __PRETTY_FUNCTION__)); |
617 | return reinterpret_cast<const storage_type *>(TStorage.buffer); |
618 | } |
619 | |
620 | error_type *getErrorStorage() { |
621 | assert(HasError && "Cannot get error when a value exists!")(static_cast <bool> (HasError && "Cannot get error when a value exists!" ) ? void (0) : __assert_fail ("HasError && \"Cannot get error when a value exists!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/Support/Error.h" , 621, __extension__ __PRETTY_FUNCTION__)); |
622 | return reinterpret_cast<error_type *>(ErrorStorage.buffer); |
623 | } |
624 | |
625 | const error_type *getErrorStorage() const { |
626 | assert(HasError && "Cannot get error when a value exists!")(static_cast <bool> (HasError && "Cannot get error when a value exists!" ) ? void (0) : __assert_fail ("HasError && \"Cannot get error when a value exists!\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/Support/Error.h" , 626, __extension__ __PRETTY_FUNCTION__)); |
627 | return reinterpret_cast<const error_type *>(ErrorStorage.buffer); |
628 | } |
629 | |
630 | // Used by ExpectedAsOutParameter to reset the checked flag. |
631 | void setUnchecked() { |
632 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
633 | Unchecked = true; |
634 | #endif |
635 | } |
636 | |
637 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
638 | LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) |
639 | LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) |
640 | void fatalUncheckedExpected() const { |
641 | dbgs() << "Expected<T> must be checked before access or destruction.\n"; |
642 | if (HasError) { |
643 | dbgs() << "Unchecked Expected<T> contained error:\n"; |
644 | (*getErrorStorage())->log(dbgs()); |
645 | } else |
646 | dbgs() << "Expected<T> value was in success state. (Note: Expected<T> " |
647 | "values in success mode must still be checked prior to being " |
648 | "destroyed).\n"; |
649 | abort(); |
650 | } |
651 | #endif |
652 | |
653 | void assertIsChecked() { |
654 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
655 | if (LLVM_UNLIKELY(Unchecked)__builtin_expect((bool)(Unchecked), false)) |
656 | fatalUncheckedExpected(); |
657 | #endif |
658 | } |
659 | |
660 | union { |
661 | AlignedCharArrayUnion<storage_type> TStorage; |
662 | AlignedCharArrayUnion<error_type> ErrorStorage; |
663 | }; |
664 | bool HasError : 1; |
665 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
666 | bool Unchecked : 1; |
667 | #endif |
668 | }; |
669 | |
670 | /// Report a serious error, calling any installed error handler. See |
671 | /// ErrorHandling.h. |
672 | LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) void report_fatal_error(Error Err, |
673 | bool gen_crash_diag = true); |
674 | |
675 | /// Report a fatal error if Err is a failure value. |
676 | /// |
677 | /// This function can be used to wrap calls to fallible functions ONLY when it |
678 | /// is known that the Error will always be a success value. E.g. |
679 | /// |
680 | /// @code{.cpp} |
681 | /// // foo only attempts the fallible operation if DoFallibleOperation is |
682 | /// // true. If DoFallibleOperation is false then foo always returns |
683 | /// // Error::success(). |
684 | /// Error foo(bool DoFallibleOperation); |
685 | /// |
686 | /// cantFail(foo(false)); |
687 | /// @endcode |
688 | inline void cantFail(Error Err, const char *Msg = nullptr) { |
689 | if (Err) { |
690 | if (!Msg) |
691 | Msg = "Failure value returned from cantFail wrapped call"; |
692 | llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/Support/Error.h" , 692); |
693 | } |
694 | } |
695 | |
696 | /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and |
697 | /// returns the contained value. |
698 | /// |
699 | /// This function can be used to wrap calls to fallible functions ONLY when it |
700 | /// is known that the Error will always be a success value. E.g. |
701 | /// |
702 | /// @code{.cpp} |
703 | /// // foo only attempts the fallible operation if DoFallibleOperation is |
704 | /// // true. If DoFallibleOperation is false then foo always returns an int. |
705 | /// Expected<int> foo(bool DoFallibleOperation); |
706 | /// |
707 | /// int X = cantFail(foo(false)); |
708 | /// @endcode |
709 | template <typename T> |
710 | T cantFail(Expected<T> ValOrErr, const char *Msg = nullptr) { |
711 | if (ValOrErr) |
712 | return std::move(*ValOrErr); |
713 | else { |
714 | if (!Msg) |
715 | Msg = "Failure value returned from cantFail wrapped call"; |
716 | llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/Support/Error.h" , 716); |
717 | } |
718 | } |
719 | |
720 | /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and |
721 | /// returns the contained reference. |
722 | /// |
723 | /// This function can be used to wrap calls to fallible functions ONLY when it |
724 | /// is known that the Error will always be a success value. E.g. |
725 | /// |
726 | /// @code{.cpp} |
727 | /// // foo only attempts the fallible operation if DoFallibleOperation is |
728 | /// // true. If DoFallibleOperation is false then foo always returns a Bar&. |
729 | /// Expected<Bar&> foo(bool DoFallibleOperation); |
730 | /// |
731 | /// Bar &X = cantFail(foo(false)); |
732 | /// @endcode |
733 | template <typename T> |
734 | T& cantFail(Expected<T&> ValOrErr, const char *Msg = nullptr) { |
735 | if (ValOrErr) |
736 | return *ValOrErr; |
737 | else { |
738 | if (!Msg) |
739 | Msg = "Failure value returned from cantFail wrapped call"; |
740 | llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/Support/Error.h" , 740); |
741 | } |
742 | } |
743 | |
744 | /// Helper for testing applicability of, and applying, handlers for |
745 | /// ErrorInfo types. |
746 | template <typename HandlerT> |
747 | class ErrorHandlerTraits |
748 | : public ErrorHandlerTraits<decltype( |
749 | &std::remove_reference<HandlerT>::type::operator())> {}; |
750 | |
751 | // Specialization functions of the form 'Error (const ErrT&)'. |
752 | template <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> { |
753 | public: |
754 | static bool appliesTo(const ErrorInfoBase &E) { |
755 | return E.template isA<ErrT>(); |
756 | } |
757 | |
758 | template <typename HandlerT> |
759 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { |
760 | assert(appliesTo(*E) && "Applying incorrect handler")(static_cast <bool> (appliesTo(*E) && "Applying incorrect handler" ) ? void (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/Support/Error.h" , 760, __extension__ __PRETTY_FUNCTION__)); |
761 | return H(static_cast<ErrT &>(*E)); |
762 | } |
763 | }; |
764 | |
765 | // Specialization functions of the form 'void (const ErrT&)'. |
766 | template <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> { |
767 | public: |
768 | static bool appliesTo(const ErrorInfoBase &E) { |
769 | return E.template isA<ErrT>(); |
770 | } |
771 | |
772 | template <typename HandlerT> |
773 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { |
774 | assert(appliesTo(*E) && "Applying incorrect handler")(static_cast <bool> (appliesTo(*E) && "Applying incorrect handler" ) ? void (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/Support/Error.h" , 774, __extension__ __PRETTY_FUNCTION__)); |
775 | H(static_cast<ErrT &>(*E)); |
776 | return Error::success(); |
777 | } |
778 | }; |
779 | |
780 | /// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'. |
781 | template <typename ErrT> |
782 | class ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> { |
783 | public: |
784 | static bool appliesTo(const ErrorInfoBase &E) { |
785 | return E.template isA<ErrT>(); |
786 | } |
787 | |
788 | template <typename HandlerT> |
789 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { |
790 | assert(appliesTo(*E) && "Applying incorrect handler")(static_cast <bool> (appliesTo(*E) && "Applying incorrect handler" ) ? void (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/Support/Error.h" , 790, __extension__ __PRETTY_FUNCTION__)); |
791 | std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release())); |
792 | return H(std::move(SubE)); |
793 | } |
794 | }; |
795 | |
796 | /// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'. |
797 | template <typename ErrT> |
798 | class ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> { |
799 | public: |
800 | static bool appliesTo(const ErrorInfoBase &E) { |
801 | return E.template isA<ErrT>(); |
802 | } |
803 | |
804 | template <typename HandlerT> |
805 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { |
806 | assert(appliesTo(*E) && "Applying incorrect handler")(static_cast <bool> (appliesTo(*E) && "Applying incorrect handler" ) ? void (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\"" , "/build/llvm-toolchain-snapshot-7~svn326246/include/llvm/Support/Error.h" , 806, __extension__ __PRETTY_FUNCTION__)); |
807 | std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release())); |
808 | H(std::move(SubE)); |
809 | return Error::success(); |
810 | } |
811 | }; |
812 | |
813 | // Specialization for member functions of the form 'RetT (const ErrT&)'. |
814 | template <typename C, typename RetT, typename ErrT> |
815 | class ErrorHandlerTraits<RetT (C::*)(ErrT &)> |
816 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; |
817 | |
818 | // Specialization for member functions of the form 'RetT (const ErrT&) const'. |
819 | template <typename C, typename RetT, typename ErrT> |
820 | class ErrorHandlerTraits<RetT (C::*)(ErrT &) const> |
821 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; |
822 | |
823 | // Specialization for member functions of the form 'RetT (const ErrT&)'. |
824 | template <typename C, typename RetT, typename ErrT> |
825 | class ErrorHandlerTraits<RetT (C::*)(const ErrT &)> |
826 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; |
827 | |
828 | // Specialization for member functions of the form 'RetT (const ErrT&) const'. |
829 | template <typename C, typename RetT, typename ErrT> |
830 | class ErrorHandlerTraits<RetT (C::*)(const ErrT &) const> |
831 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; |
832 | |
833 | /// Specialization for member functions of the form |
834 | /// 'RetT (std::unique_ptr<ErrT>)'. |
835 | template <typename C, typename RetT, typename ErrT> |
836 | class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>)> |
837 | : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {}; |
838 | |
839 | /// Specialization for member functions of the form |
840 | /// 'RetT (std::unique_ptr<ErrT>) const'. |
841 | template <typename C, typename RetT, typename ErrT> |
842 | class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>) const> |
843 | : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {}; |
844 | |
845 | inline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) { |
846 | return Error(std::move(Payload)); |
847 | } |
848 | |
849 | template <typename HandlerT, typename... HandlerTs> |
850 | Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload, |
851 | HandlerT &&Handler, HandlerTs &&... Handlers) { |
852 | if (ErrorHandlerTraits<HandlerT>::appliesTo(*Payload)) |
853 | return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler), |
854 | std::move(Payload)); |
855 | return handleErrorImpl(std::move(Payload), |
856 | std::forward<HandlerTs>(Handlers)...); |
857 | } |
858 | |
859 | /// Pass the ErrorInfo(s) contained in E to their respective handlers. Any |
860 | /// unhandled errors (or Errors returned by handlers) are re-concatenated and |
861 | /// returned. |
862 | /// Because this function returns an error, its result must also be checked |
863 | /// or returned. If you intend to handle all errors use handleAllErrors |
864 | /// (which returns void, and will abort() on unhandled errors) instead. |
865 | template <typename... HandlerTs> |
866 | Error handleErrors(Error E, HandlerTs &&... Hs) { |
867 | if (!E) |
868 | return Error::success(); |
869 | |
870 | std::unique_ptr<ErrorInfoBase> Payload = E.takePayload(); |
871 | |
872 | if (Payload->isA<ErrorList>()) { |
873 | ErrorList &List = static_cast<ErrorList &>(*Payload); |
874 | Error R; |
875 | for (auto &P : List.Payloads) |
876 | R = ErrorList::join( |
877 | std::move(R), |
878 | handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...)); |
879 | return R; |
880 | } |
881 | |
882 | return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...); |
883 | } |
884 | |
885 | /// Behaves the same as handleErrors, except that it requires that all |
886 | /// errors be handled by the given handlers. If any unhandled error remains |
887 | /// after the handlers have run, report_fatal_error() will be called. |
888 | template <typename... HandlerTs> |
889 | void handleAllErrors(Error E, HandlerTs &&... Handlers) { |
890 | cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...)); |
891 | } |
892 | |
893 | /// Check that E is a non-error, then drop it. |
894 | /// If E is an error report_fatal_error will be called. |
895 | inline void handleAllErrors(Error E) { |
896 | cantFail(std::move(E)); |
897 | } |
898 | |
899 | /// Handle any errors (if present) in an Expected<T>, then try a recovery path. |
900 | /// |
901 | /// If the incoming value is a success value it is returned unmodified. If it |
902 | /// is a failure value then it the contained error is passed to handleErrors. |
903 | /// If handleErrors is able to handle the error then the RecoveryPath functor |
904 | /// is called to supply the final result. If handleErrors is not able to |
905 | /// handle all errors then the unhandled errors are returned. |
906 | /// |
907 | /// This utility enables the follow pattern: |
908 | /// |
909 | /// @code{.cpp} |
910 | /// enum FooStrategy { Aggressive, Conservative }; |
911 | /// Expected<Foo> foo(FooStrategy S); |
912 | /// |
913 | /// auto ResultOrErr = |
914 | /// handleExpected( |
915 | /// foo(Aggressive), |
916 | /// []() { return foo(Conservative); }, |
917 | /// [](AggressiveStrategyError&) { |
918 | /// // Implicitly conusme this - we'll recover by using a conservative |
919 | /// // strategy. |
920 | /// }); |
921 | /// |
922 | /// @endcode |
923 | template <typename T, typename RecoveryFtor, typename... HandlerTs> |
924 | Expected<T> handleExpected(Expected<T> ValOrErr, RecoveryFtor &&RecoveryPath, |
925 | HandlerTs &&... Handlers) { |
926 | if (ValOrErr) |
927 | return ValOrErr; |
928 | |
929 | if (auto Err = handleErrors(ValOrErr.takeError(), |
930 | std::forward<HandlerTs>(Handlers)...)) |
931 | return std::move(Err); |
932 | |
933 | return RecoveryPath(); |
934 | } |
935 | |
936 | /// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner |
937 | /// will be printed before the first one is logged. A newline will be printed |
938 | /// after each error. |
939 | /// |
940 | /// This is useful in the base level of your program to allow clean termination |
941 | /// (allowing clean deallocation of resources, etc.), while reporting error |
942 | /// information to the user. |
943 | void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner); |
944 | |
945 | /// Write all error messages (if any) in E to a string. The newline character |
946 | /// is used to separate error messages. |
947 | inline std::string toString(Error E) { |
948 | SmallVector<std::string, 2> Errors; |
949 | handleAllErrors(std::move(E), [&Errors](const ErrorInfoBase &EI) { |
950 | Errors.push_back(EI.message()); |
951 | }); |
952 | return join(Errors.begin(), Errors.end(), "\n"); |
953 | } |
954 | |
955 | /// Consume a Error without doing anything. This method should be used |
956 | /// only where an error can be considered a reasonable and expected return |
957 | /// value. |
958 | /// |
959 | /// Uses of this method are potentially indicative of design problems: If it's |
960 | /// legitimate to do nothing while processing an "error", the error-producer |
961 | /// might be more clearly refactored to return an Optional<T>. |
962 | inline void consumeError(Error Err) { |
963 | handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {}); |
964 | } |
965 | |
966 | /// Helper for converting an Error to a bool. |
967 | /// |
968 | /// This method returns true if Err is in an error state, or false if it is |
969 | /// in a success state. Puts Err in a checked state in both cases (unlike |
970 | /// Error::operator bool(), which only does this for success states). |
971 | inline bool errorToBool(Error Err) { |
972 | bool IsError = static_cast<bool>(Err); |
973 | if (IsError) |
974 | consumeError(std::move(Err)); |
975 | return IsError; |
976 | } |
977 | |
978 | /// Helper for Errors used as out-parameters. |
979 | /// |
980 | /// This helper is for use with the Error-as-out-parameter idiom, where an error |
981 | /// is passed to a function or method by reference, rather than being returned. |
982 | /// In such cases it is helpful to set the checked bit on entry to the function |
983 | /// so that the error can be written to (unchecked Errors abort on assignment) |
984 | /// and clear the checked bit on exit so that clients cannot accidentally forget |
985 | /// to check the result. This helper performs these actions automatically using |
986 | /// RAII: |
987 | /// |
988 | /// @code{.cpp} |
989 | /// Result foo(Error &Err) { |
990 | /// ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set |
991 | /// // <body of foo> |
992 | /// // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed. |
993 | /// } |
994 | /// @endcode |
995 | /// |
996 | /// ErrorAsOutParameter takes an Error* rather than Error& so that it can be |
997 | /// used with optional Errors (Error pointers that are allowed to be null). If |
998 | /// ErrorAsOutParameter took an Error reference, an instance would have to be |
999 | /// created inside every condition that verified that Error was non-null. By |
1000 | /// taking an Error pointer we can just create one instance at the top of the |
1001 | /// function. |
1002 | class ErrorAsOutParameter { |
1003 | public: |
1004 | ErrorAsOutParameter(Error *Err) : Err(Err) { |
1005 | // Raise the checked bit if Err is success. |
1006 | if (Err) |
1007 | (void)!!*Err; |
1008 | } |
1009 | |
1010 | ~ErrorAsOutParameter() { |
1011 | // Clear the checked bit. |
1012 | if (Err && !*Err) |
1013 | *Err = Error::success(); |
1014 | } |
1015 | |
1016 | private: |
1017 | Error *Err; |
1018 | }; |
1019 | |
1020 | /// Helper for Expected<T>s used as out-parameters. |
1021 | /// |
1022 | /// See ErrorAsOutParameter. |
1023 | template <typename T> |
1024 | class ExpectedAsOutParameter { |
1025 | public: |
1026 | ExpectedAsOutParameter(Expected<T> *ValOrErr) |
1027 | : ValOrErr(ValOrErr) { |
1028 | if (ValOrErr) |
1029 | (void)!!*ValOrErr; |
1030 | } |
1031 | |
1032 | ~ExpectedAsOutParameter() { |
1033 | if (ValOrErr) |
1034 | ValOrErr->setUnchecked(); |
1035 | } |
1036 | |
1037 | private: |
1038 | Expected<T> *ValOrErr; |
1039 | }; |
1040 | |
1041 | /// This class wraps a std::error_code in a Error. |
1042 | /// |
1043 | /// This is useful if you're writing an interface that returns a Error |
1044 | /// (or Expected) and you want to call code that still returns |
1045 | /// std::error_codes. |
1046 | class ECError : public ErrorInfo<ECError> { |
1047 | friend Error errorCodeToError(std::error_code); |
1048 | |
1049 | public: |
1050 | void setErrorCode(std::error_code EC) { this->EC = EC; } |
1051 | std::error_code convertToErrorCode() const override { return EC; } |
1052 | void log(raw_ostream &OS) const override { OS << EC.message(); } |
1053 | |
1054 | // Used by ErrorInfo::classID. |
1055 | static char ID; |
1056 | |
1057 | protected: |
1058 | ECError() = default; |
1059 | ECError(std::error_code EC) : EC(EC) {} |
1060 | |
1061 | std::error_code EC; |
1062 | }; |
1063 | |
1064 | /// The value returned by this function can be returned from convertToErrorCode |
1065 | /// for Error values where no sensible translation to std::error_code exists. |
1066 | /// It should only be used in this situation, and should never be used where a |
1067 | /// sensible conversion to std::error_code is available, as attempts to convert |
1068 | /// to/from this error will result in a fatal error. (i.e. it is a programmatic |
1069 | ///error to try to convert such a value). |
1070 | std::error_code inconvertibleErrorCode(); |
1071 | |
1072 | /// Helper for converting an std::error_code to a Error. |
1073 | Error errorCodeToError(std::error_code EC); |
1074 | |
1075 | /// Helper for converting an ECError to a std::error_code. |
1076 | /// |
1077 | /// This method requires that Err be Error() or an ECError, otherwise it |
1078 | /// will trigger a call to abort(). |
1079 | std::error_code errorToErrorCode(Error Err); |
1080 | |
1081 | /// Convert an ErrorOr<T> to an Expected<T>. |
1082 | template <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) { |
1083 | if (auto EC = EO.getError()) |
1084 | return errorCodeToError(EC); |
1085 | return std::move(*EO); |
1086 | } |
1087 | |
1088 | /// Convert an Expected<T> to an ErrorOr<T>. |
1089 | template <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) { |
1090 | if (auto Err = E.takeError()) |
1091 | return errorToErrorCode(std::move(Err)); |
1092 | return std::move(*E); |
1093 | } |
1094 | |
1095 | /// This class wraps a string in an Error. |
1096 | /// |
1097 | /// StringError is useful in cases where the client is not expected to be able |
1098 | /// to consume the specific error message programmatically (for example, if the |
1099 | /// error message is to be presented to the user). |
1100 | class StringError : public ErrorInfo<StringError> { |
1101 | public: |
1102 | static char ID; |
1103 | |
1104 | StringError(const Twine &S, std::error_code EC); |
1105 | |
1106 | void log(raw_ostream &OS) const override; |
1107 | std::error_code convertToErrorCode() const override; |
1108 | |
1109 | const std::string &getMessage() const { return Msg; } |
1110 | |
1111 | private: |
1112 | std::string Msg; |
1113 | std::error_code EC; |
1114 | }; |
1115 | |
1116 | /// Helper for check-and-exit error handling. |
1117 | /// |
1118 | /// For tool use only. NOT FOR USE IN LIBRARY CODE. |
1119 | /// |
1120 | class ExitOnError { |
1121 | public: |
1122 | /// Create an error on exit helper. |
1123 | ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1) |
1124 | : Banner(std::move(Banner)), |
1125 | GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {} |
1126 | |
1127 | /// Set the banner string for any errors caught by operator(). |
1128 | void setBanner(std::string Banner) { this->Banner = std::move(Banner); } |
1129 | |
1130 | /// Set the exit-code mapper function. |
1131 | void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) { |
1132 | this->GetExitCode = std::move(GetExitCode); |
1133 | } |
1134 | |
1135 | /// Check Err. If it's in a failure state log the error(s) and exit. |
1136 | void operator()(Error Err) const { checkError(std::move(Err)); } |
1137 | |
1138 | /// Check E. If it's in a success state then return the contained value. If |
1139 | /// it's in a failure state log the error(s) and exit. |
1140 | template <typename T> T operator()(Expected<T> &&E) const { |
1141 | checkError(E.takeError()); |
1142 | return std::move(*E); |
1143 | } |
1144 | |
1145 | /// Check E. If it's in a success state then return the contained reference. If |
1146 | /// it's in a failure state log the error(s) and exit. |
1147 | template <typename T> T& operator()(Expected<T&> &&E) const { |
1148 | checkError(E.takeError()); |
1149 | return *E; |
1150 | } |
1151 | |
1152 | private: |
1153 | void checkError(Error Err) const { |
1154 | if (Err) { |
1155 | int ExitCode = GetExitCode(Err); |
1156 | logAllUnhandledErrors(std::move(Err), errs(), Banner); |
1157 | exit(ExitCode); |
1158 | } |
1159 | } |
1160 | |
1161 | std::string Banner; |
1162 | std::function<int(const Error &)> GetExitCode; |
1163 | }; |
1164 | |
1165 | } // end namespace llvm |
1166 | |
1167 | #endif // LLVM_SUPPORT_ERROR_H |