File: | build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/tools/dsymutil/DwarfLinkerForBinary.cpp |
Warning: | line 191, column 29 Moved-from object 'Err' is moved |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===- tools/dsymutil/DwarfLinkerForBinary.cpp ----------------------------===// | |||
2 | // | |||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | |||
4 | // See https://llvm.org/LICENSE.txt for license information. | |||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | |||
6 | // | |||
7 | //===----------------------------------------------------------------------===// | |||
8 | ||||
9 | #include "DwarfLinkerForBinary.h" | |||
10 | #include "BinaryHolder.h" | |||
11 | #include "DebugMap.h" | |||
12 | #include "MachOUtils.h" | |||
13 | #include "dsymutil.h" | |||
14 | #include "llvm/ADT/ArrayRef.h" | |||
15 | #include "llvm/ADT/BitVector.h" | |||
16 | #include "llvm/ADT/DenseMap.h" | |||
17 | #include "llvm/ADT/DenseMapInfo.h" | |||
18 | #include "llvm/ADT/DenseSet.h" | |||
19 | #include "llvm/ADT/FoldingSet.h" | |||
20 | #include "llvm/ADT/Hashing.h" | |||
21 | #include "llvm/ADT/IntervalMap.h" | |||
22 | #include "llvm/ADT/None.h" | |||
23 | #include "llvm/ADT/Optional.h" | |||
24 | #include "llvm/ADT/PointerIntPair.h" | |||
25 | #include "llvm/ADT/STLExtras.h" | |||
26 | #include "llvm/ADT/SmallString.h" | |||
27 | #include "llvm/ADT/StringMap.h" | |||
28 | #include "llvm/ADT/StringRef.h" | |||
29 | #include "llvm/ADT/Triple.h" | |||
30 | #include "llvm/ADT/Twine.h" | |||
31 | #include "llvm/BinaryFormat/Dwarf.h" | |||
32 | #include "llvm/BinaryFormat/MachO.h" | |||
33 | #include "llvm/BinaryFormat/Swift.h" | |||
34 | #include "llvm/CodeGen/AccelTable.h" | |||
35 | #include "llvm/CodeGen/AsmPrinter.h" | |||
36 | #include "llvm/CodeGen/DIE.h" | |||
37 | #include "llvm/CodeGen/NonRelocatableStringpool.h" | |||
38 | #include "llvm/Config/config.h" | |||
39 | #include "llvm/DWARFLinker/DWARFLinkerDeclContext.h" | |||
40 | #include "llvm/DebugInfo/DIContext.h" | |||
41 | #include "llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h" | |||
42 | #include "llvm/DebugInfo/DWARF/DWARFContext.h" | |||
43 | #include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h" | |||
44 | #include "llvm/DebugInfo/DWARF/DWARFDebugLine.h" | |||
45 | #include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h" | |||
46 | #include "llvm/DebugInfo/DWARF/DWARFDie.h" | |||
47 | #include "llvm/DebugInfo/DWARF/DWARFFormValue.h" | |||
48 | #include "llvm/DebugInfo/DWARF/DWARFSection.h" | |||
49 | #include "llvm/DebugInfo/DWARF/DWARFUnit.h" | |||
50 | #include "llvm/MC/MCAsmBackend.h" | |||
51 | #include "llvm/MC/MCAsmInfo.h" | |||
52 | #include "llvm/MC/MCCodeEmitter.h" | |||
53 | #include "llvm/MC/MCContext.h" | |||
54 | #include "llvm/MC/MCDwarf.h" | |||
55 | #include "llvm/MC/MCInstrInfo.h" | |||
56 | #include "llvm/MC/MCObjectFileInfo.h" | |||
57 | #include "llvm/MC/MCObjectWriter.h" | |||
58 | #include "llvm/MC/MCRegisterInfo.h" | |||
59 | #include "llvm/MC/MCSection.h" | |||
60 | #include "llvm/MC/MCStreamer.h" | |||
61 | #include "llvm/MC/MCSubtargetInfo.h" | |||
62 | #include "llvm/MC/MCTargetOptions.h" | |||
63 | #include "llvm/MC/MCTargetOptionsCommandFlags.h" | |||
64 | #include "llvm/MC/TargetRegistry.h" | |||
65 | #include "llvm/Object/MachO.h" | |||
66 | #include "llvm/Object/ObjectFile.h" | |||
67 | #include "llvm/Object/SymbolicFile.h" | |||
68 | #include "llvm/Support/Allocator.h" | |||
69 | #include "llvm/Support/Casting.h" | |||
70 | #include "llvm/Support/Compiler.h" | |||
71 | #include "llvm/Support/DJB.h" | |||
72 | #include "llvm/Support/DataExtractor.h" | |||
73 | #include "llvm/Support/Error.h" | |||
74 | #include "llvm/Support/ErrorHandling.h" | |||
75 | #include "llvm/Support/ErrorOr.h" | |||
76 | #include "llvm/Support/FileSystem.h" | |||
77 | #include "llvm/Support/Format.h" | |||
78 | #include "llvm/Support/LEB128.h" | |||
79 | #include "llvm/Support/MathExtras.h" | |||
80 | #include "llvm/Support/MemoryBuffer.h" | |||
81 | #include "llvm/Support/Path.h" | |||
82 | #include "llvm/Support/ThreadPool.h" | |||
83 | #include "llvm/Support/ToolOutputFile.h" | |||
84 | #include "llvm/Support/WithColor.h" | |||
85 | #include "llvm/Support/raw_ostream.h" | |||
86 | #include "llvm/Target/TargetMachine.h" | |||
87 | #include "llvm/Target/TargetOptions.h" | |||
88 | #include <algorithm> | |||
89 | #include <cassert> | |||
90 | #include <cinttypes> | |||
91 | #include <climits> | |||
92 | #include <cstdint> | |||
93 | #include <cstdlib> | |||
94 | #include <cstring> | |||
95 | #include <limits> | |||
96 | #include <map> | |||
97 | #include <memory> | |||
98 | #include <string> | |||
99 | #include <system_error> | |||
100 | #include <tuple> | |||
101 | #include <utility> | |||
102 | #include <vector> | |||
103 | ||||
104 | namespace llvm { | |||
105 | ||||
106 | static mc::RegisterMCTargetOptionsFlags MOF; | |||
107 | ||||
108 | namespace dsymutil { | |||
109 | ||||
110 | static Error copySwiftInterfaces( | |||
111 | const std::map<std::string, std::string> &ParseableSwiftInterfaces, | |||
112 | StringRef Architecture, const LinkOptions &Options) { | |||
113 | std::error_code EC; | |||
114 | SmallString<128> InputPath; | |||
115 | SmallString<128> Path; | |||
116 | sys::path::append(Path, *Options.ResourceDir, "Swift", Architecture); | |||
117 | if ((EC = sys::fs::create_directories(Path.str(), true, | |||
118 | sys::fs::perms::all_all))) | |||
119 | return make_error<StringError>( | |||
120 | "cannot create directory: " + toString(errorCodeToError(EC)), EC); | |||
121 | unsigned BaseLength = Path.size(); | |||
122 | ||||
123 | for (auto &I : ParseableSwiftInterfaces) { | |||
124 | StringRef ModuleName = I.first; | |||
125 | StringRef InterfaceFile = I.second; | |||
126 | if (!Options.PrependPath.empty()) { | |||
127 | InputPath.clear(); | |||
128 | sys::path::append(InputPath, Options.PrependPath, InterfaceFile); | |||
129 | InterfaceFile = InputPath; | |||
130 | } | |||
131 | sys::path::append(Path, ModuleName); | |||
132 | Path.append(".swiftinterface"); | |||
133 | if (Options.Verbose) | |||
134 | outs() << "copy parseable Swift interface " << InterfaceFile << " -> " | |||
135 | << Path.str() << '\n'; | |||
136 | ||||
137 | // copy_file attempts an APFS clone first, so this should be cheap. | |||
138 | if ((EC = sys::fs::copy_file(InterfaceFile, Path.str()))) | |||
139 | warn(Twine("cannot copy parseable Swift interface ") + InterfaceFile + | |||
140 | ": " + toString(errorCodeToError(EC))); | |||
141 | Path.resize(BaseLength); | |||
142 | } | |||
143 | return Error::success(); | |||
144 | } | |||
145 | ||||
146 | /// Report a warning to the user, optionally including information about a | |||
147 | /// specific \p DIE related to the warning. | |||
148 | void DwarfLinkerForBinary::reportWarning(const Twine &Warning, | |||
149 | StringRef Context, | |||
150 | const DWARFDie *DIE) const { | |||
151 | ||||
152 | warn(Warning, Context); | |||
153 | ||||
154 | if (!Options.Verbose || !DIE) | |||
155 | return; | |||
156 | ||||
157 | DIDumpOptions DumpOpts; | |||
158 | DumpOpts.ChildRecurseDepth = 0; | |||
159 | DumpOpts.Verbose = Options.Verbose; | |||
160 | ||||
161 | WithColor::note() << " in DIE:\n"; | |||
162 | DIE->dump(errs(), 6 /* Indent */, DumpOpts); | |||
163 | } | |||
164 | ||||
165 | bool DwarfLinkerForBinary::createStreamer(const Triple &TheTriple, | |||
166 | raw_fd_ostream &OutFile) { | |||
167 | if (Options.NoOutput) | |||
168 | return true; | |||
169 | ||||
170 | Streamer = std::make_unique<DwarfStreamer>( | |||
171 | Options.FileType, OutFile, Options.Translator, | |||
172 | [&](const Twine &Error, StringRef Context, const DWARFDie *) { | |||
173 | error(Error, Context); | |||
174 | }, | |||
175 | [&](const Twine &Warning, StringRef Context, const DWARFDie *) { | |||
176 | warn(Warning, Context); | |||
177 | }); | |||
178 | return Streamer->init(TheTriple, "__DWARF"); | |||
179 | } | |||
180 | ||||
181 | ErrorOr<const object::ObjectFile &> | |||
182 | DwarfLinkerForBinary::loadObject(const DebugMapObject &Obj, | |||
183 | const Triple &Triple) { | |||
184 | auto ObjectEntry = | |||
185 | BinHolder.getObjectEntry(Obj.getObjectFilename(), Obj.getTimestamp()); | |||
186 | if (!ObjectEntry) { | |||
187 | auto Err = ObjectEntry.takeError(); | |||
188 | reportWarning(Twine(Obj.getObjectFilename()) + ": " + | |||
189 | toString(std::move(Err)), | |||
190 | Obj.getObjectFilename()); | |||
191 | return errorToErrorCode(std::move(Err)); | |||
| ||||
192 | } | |||
193 | ||||
194 | auto Object = ObjectEntry->getObject(Triple); | |||
195 | if (!Object) { | |||
196 | auto Err = Object.takeError(); | |||
197 | reportWarning(Twine(Obj.getObjectFilename()) + ": " + | |||
198 | toString(std::move(Err)), | |||
199 | Obj.getObjectFilename()); | |||
200 | return errorToErrorCode(std::move(Err)); | |||
201 | } | |||
202 | ||||
203 | return *Object; | |||
204 | } | |||
205 | ||||
206 | static Error remarksErrorHandler(const DebugMapObject &DMO, | |||
207 | DwarfLinkerForBinary &Linker, | |||
208 | std::unique_ptr<FileError> FE) { | |||
209 | bool IsArchive = DMO.getObjectFilename().endswith(")"); | |||
210 | // Don't report errors for missing remark files from static | |||
211 | // archives. | |||
212 | if (!IsArchive) | |||
213 | return Error(std::move(FE)); | |||
214 | ||||
215 | std::string Message = FE->message(); | |||
216 | Error E = FE->takeError(); | |||
217 | Error NewE = handleErrors(std::move(E), [&](std::unique_ptr<ECError> EC) { | |||
218 | if (EC->convertToErrorCode() != std::errc::no_such_file_or_directory) | |||
219 | return Error(std::move(EC)); | |||
220 | ||||
221 | Linker.reportWarning(Message, DMO.getObjectFilename()); | |||
222 | return Error(Error::success()); | |||
223 | }); | |||
224 | ||||
225 | if (!NewE) | |||
226 | return Error::success(); | |||
227 | ||||
228 | return createFileError(FE->getFileName(), std::move(NewE)); | |||
229 | } | |||
230 | ||||
231 | static Error emitRemarks(const LinkOptions &Options, StringRef BinaryPath, | |||
232 | StringRef ArchName, const remarks::RemarkLinker &RL) { | |||
233 | // Make sure we don't create the directories and the file if there is nothing | |||
234 | // to serialize. | |||
235 | if (RL.empty()) | |||
236 | return Error::success(); | |||
237 | ||||
238 | SmallString<128> InputPath; | |||
239 | SmallString<128> Path; | |||
240 | // Create the "Remarks" directory in the "Resources" directory. | |||
241 | sys::path::append(Path, *Options.ResourceDir, "Remarks"); | |||
242 | if (std::error_code EC = sys::fs::create_directories(Path.str(), true, | |||
243 | sys::fs::perms::all_all)) | |||
244 | return errorCodeToError(EC); | |||
245 | ||||
246 | // Append the file name. | |||
247 | // For fat binaries, also append a dash and the architecture name. | |||
248 | sys::path::append(Path, sys::path::filename(BinaryPath)); | |||
249 | if (Options.NumDebugMaps > 1) { | |||
250 | // More than one debug map means we have a fat binary. | |||
251 | Path += '-'; | |||
252 | Path += ArchName; | |||
253 | } | |||
254 | ||||
255 | std::error_code EC; | |||
256 | raw_fd_ostream OS(Options.NoOutput ? "-" : Path.str(), EC, | |||
257 | Options.RemarksFormat == remarks::Format::Bitstream | |||
258 | ? sys::fs::OF_None | |||
259 | : sys::fs::OF_Text); | |||
260 | if (EC) | |||
261 | return errorCodeToError(EC); | |||
262 | ||||
263 | if (Error E = RL.serialize(OS, Options.RemarksFormat)) | |||
264 | return E; | |||
265 | ||||
266 | return Error::success(); | |||
267 | } | |||
268 | ||||
269 | ErrorOr<DWARFFile &> | |||
270 | DwarfLinkerForBinary::loadObject(const DebugMapObject &Obj, | |||
271 | const DebugMap &DebugMap, | |||
272 | remarks::RemarkLinker &RL) { | |||
273 | auto ErrorOrObj = loadObject(Obj, DebugMap.getTriple()); | |||
274 | ||||
275 | if (ErrorOrObj) { | |||
276 | ContextForLinking.push_back( | |||
277 | std::unique_ptr<DWARFContext>(DWARFContext::create(*ErrorOrObj))); | |||
278 | AddressMapForLinking.push_back( | |||
279 | std::make_unique<AddressManager>(*this, *ErrorOrObj, Obj)); | |||
280 | ||||
281 | ObjectsForLinking.push_back(std::make_unique<DWARFFile>( | |||
282 | Obj.getObjectFilename(), ContextForLinking.back().get(), | |||
283 | AddressMapForLinking.back().get(), | |||
284 | Obj.empty() ? Obj.getWarnings() : EmptyWarnings)); | |||
285 | ||||
286 | Error E = RL.link(*ErrorOrObj); | |||
287 | if (Error NewE = handleErrors( | |||
288 | std::move(E), [&](std::unique_ptr<FileError> EC) -> Error { | |||
289 | return remarksErrorHandler(Obj, *this, std::move(EC)); | |||
290 | })) | |||
291 | return errorToErrorCode(std::move(NewE)); | |||
292 | ||||
293 | return *ObjectsForLinking.back(); | |||
294 | } | |||
295 | ||||
296 | return ErrorOrObj.getError(); | |||
297 | } | |||
298 | ||||
299 | static bool binaryHasStrippableSwiftReflectionSections( | |||
300 | const DebugMap &Map, const LinkOptions &Options, BinaryHolder &BinHolder) { | |||
301 | // If the input binary has strippable swift5 reflection sections, there is no | |||
302 | // need to copy them to the .dSYM. Only copy them for binaries where the | |||
303 | // linker omitted the reflection metadata. | |||
304 | if (!Map.getBinaryPath().empty() && | |||
305 | Options.FileType == OutputFileType::Object) { | |||
306 | ||||
307 | auto ObjectEntry = BinHolder.getObjectEntry(Map.getBinaryPath()); | |||
308 | // If ObjectEntry or Object has an error, no binary exists, therefore no | |||
309 | // reflection sections exist. | |||
310 | if (!ObjectEntry) { | |||
311 | // Any errors will be diagnosed later in the main loop, ignore them here. | |||
312 | llvm::consumeError(ObjectEntry.takeError()); | |||
313 | return false; | |||
314 | } | |||
315 | ||||
316 | auto Object = | |||
317 | ObjectEntry->getObjectAs<object::MachOObjectFile>(Map.getTriple()); | |||
318 | if (!Object) { | |||
319 | // Any errors will be diagnosed later in the main loop, ignore them here. | |||
320 | llvm::consumeError(Object.takeError()); | |||
321 | return false; | |||
322 | } | |||
323 | ||||
324 | for (auto &Section : Object->sections()) { | |||
325 | llvm::Expected<llvm::StringRef> NameOrErr = | |||
326 | Object->getSectionName(Section.getRawDataRefImpl()); | |||
327 | if (!NameOrErr) { | |||
328 | llvm::consumeError(NameOrErr.takeError()); | |||
329 | continue; | |||
330 | } | |||
331 | NameOrErr->consume_back("__TEXT"); | |||
332 | auto ReflectionSectionKind = | |||
333 | Object->mapReflectionSectionNameToEnumValue(*NameOrErr); | |||
334 | if (Object->isReflectionSectionStrippable(ReflectionSectionKind)) { | |||
335 | return true; | |||
336 | } | |||
337 | } | |||
338 | } | |||
339 | return false; | |||
340 | } | |||
341 | ||||
342 | /// Calculate the start of the strippable swift reflection sections in Dwarf. | |||
343 | /// Note that there's an assumption that the reflection sections will appear | |||
344 | /// in alphabetic order. | |||
345 | static std::vector<uint64_t> | |||
346 | calculateStartOfStrippableReflectionSections(const DebugMap &Map) { | |||
347 | using llvm::binaryformat::Swift5ReflectionSectionKind; | |||
348 | uint64_t AssocTySize = 0; | |||
349 | uint64_t FieldMdSize = 0; | |||
350 | for (const auto &Obj : Map.objects()) { | |||
351 | auto OF = | |||
352 | llvm::object::ObjectFile::createObjectFile(Obj->getObjectFilename()); | |||
353 | if (!OF) { | |||
354 | llvm::consumeError(OF.takeError()); | |||
355 | continue; | |||
356 | } | |||
357 | if (auto *MO = dyn_cast<llvm::object::MachOObjectFile>(OF->getBinary())) { | |||
358 | for (auto &Section : MO->sections()) { | |||
359 | llvm::Expected<llvm::StringRef> NameOrErr = | |||
360 | MO->getSectionName(Section.getRawDataRefImpl()); | |||
361 | if (!NameOrErr) { | |||
362 | llvm::consumeError(NameOrErr.takeError()); | |||
363 | continue; | |||
364 | } | |||
365 | NameOrErr->consume_back("__TEXT"); | |||
366 | auto ReflSectionKind = | |||
367 | MO->mapReflectionSectionNameToEnumValue(*NameOrErr); | |||
368 | switch (ReflSectionKind) { | |||
369 | case Swift5ReflectionSectionKind::assocty: | |||
370 | AssocTySize += Section.getSize(); | |||
371 | break; | |||
372 | case Swift5ReflectionSectionKind::fieldmd: | |||
373 | FieldMdSize += Section.getSize(); | |||
374 | break; | |||
375 | default: | |||
376 | break; | |||
377 | } | |||
378 | } | |||
379 | } | |||
380 | } | |||
381 | // Initialize the vector with enough space to fit every reflection section | |||
382 | // kind. | |||
383 | std::vector<uint64_t> SectionToOffset(Swift5ReflectionSectionKind::last, 0); | |||
384 | SectionToOffset[Swift5ReflectionSectionKind::assocty] = 0; | |||
385 | SectionToOffset[Swift5ReflectionSectionKind::fieldmd] = | |||
386 | llvm::alignTo(AssocTySize, 4); | |||
387 | SectionToOffset[Swift5ReflectionSectionKind::reflstr] = llvm::alignTo( | |||
388 | SectionToOffset[Swift5ReflectionSectionKind::fieldmd] + FieldMdSize, 4); | |||
389 | ||||
390 | return SectionToOffset; | |||
391 | } | |||
392 | ||||
393 | void DwarfLinkerForBinary::collectRelocationsToApplyToSwiftReflectionSections( | |||
394 | const object::SectionRef &Section, StringRef &Contents, | |||
395 | const llvm::object::MachOObjectFile *MO, | |||
396 | const std::vector<uint64_t> &SectionToOffsetInDwarf, | |||
397 | const llvm::dsymutil::DebugMapObject *Obj, | |||
398 | std::vector<MachOUtils::DwarfRelocationApplicationInfo> &RelocationsToApply) | |||
399 | const { | |||
400 | for (auto It = Section.relocation_begin(); It != Section.relocation_end(); | |||
401 | ++It) { | |||
402 | object::DataRefImpl RelocDataRef = It->getRawDataRefImpl(); | |||
403 | MachO::any_relocation_info MachOReloc = MO->getRelocation(RelocDataRef); | |||
404 | ||||
405 | if (!object::MachOObjectFile::isMachOPairedReloc( | |||
406 | MO->getAnyRelocationType(MachOReloc), MO->getArch())) { | |||
407 | reportWarning( | |||
408 | "Unimplemented relocation type in strippable reflection section ", | |||
409 | Obj->getObjectFilename()); | |||
410 | continue; | |||
411 | } | |||
412 | ||||
413 | auto CalculateAddressOfSymbolInDwarfSegment = | |||
414 | [&]() -> llvm::Optional<int64_t> { | |||
415 | auto Symbol = It->getSymbol(); | |||
416 | auto SymbolAbsoluteAddress = Symbol->getAddress(); | |||
417 | if (!SymbolAbsoluteAddress) | |||
418 | return {}; | |||
419 | auto Section = Symbol->getSection(); | |||
420 | if (!Section) { | |||
421 | llvm::consumeError(Section.takeError()); | |||
422 | return {}; | |||
423 | } | |||
424 | ||||
425 | if ((*Section)->getObject()->section_end() == *Section) | |||
426 | return {}; | |||
427 | ||||
428 | auto SectionStart = (*Section)->getAddress(); | |||
429 | auto SymbolAddressInSection = *SymbolAbsoluteAddress - SectionStart; | |||
430 | auto SectionName = (*Section)->getName(); | |||
431 | if (!SectionName) | |||
432 | return {}; | |||
433 | auto ReflSectionKind = | |||
434 | MO->mapReflectionSectionNameToEnumValue(*SectionName); | |||
435 | ||||
436 | int64_t SectionStartInLinkedBinary = | |||
437 | SectionToOffsetInDwarf[ReflSectionKind]; | |||
438 | ||||
439 | auto Addr = SectionStartInLinkedBinary + SymbolAddressInSection; | |||
440 | return Addr; | |||
441 | }; | |||
442 | ||||
443 | // The first symbol should always be in the section we're currently | |||
444 | // iterating over. | |||
445 | auto FirstSymbolAddress = CalculateAddressOfSymbolInDwarfSegment(); | |||
446 | ++It; | |||
447 | ||||
448 | bool ShouldSubtractDwarfVM = false; | |||
449 | // For the second symbol there are two possibilities. | |||
450 | llvm::Optional<int64_t> SecondSymbolAddress; | |||
451 | auto Sym = It->getSymbol(); | |||
452 | if (Sym != MO->symbol_end()) { | |||
453 | Expected<StringRef> SymbolName = Sym->getName(); | |||
454 | if (SymbolName) { | |||
455 | if (const auto *Mapping = Obj->lookupSymbol(*SymbolName)) { | |||
456 | // First possibility: the symbol exists in the binary, and exists in a | |||
457 | // non-strippable section (for example, typeref, or __TEXT,__const), | |||
458 | // in which case we look up its address in the binary, which dsymutil | |||
459 | // will copy verbatim. | |||
460 | SecondSymbolAddress = Mapping->getValue().BinaryAddress; | |||
461 | // Since the symbols live in different segments, we have to substract | |||
462 | // the start of the Dwarf's vmaddr so the value calculated points to | |||
463 | // the correct place. | |||
464 | ShouldSubtractDwarfVM = true; | |||
465 | } | |||
466 | } | |||
467 | } | |||
468 | ||||
469 | if (!SecondSymbolAddress) { | |||
470 | // Second possibility, this symbol is not present in the main binary, and | |||
471 | // must be in one of the strippable sections (for example, reflstr). | |||
472 | // Calculate its address in the same way as we did the first one. | |||
473 | SecondSymbolAddress = CalculateAddressOfSymbolInDwarfSegment(); | |||
474 | } | |||
475 | ||||
476 | if (!FirstSymbolAddress || !SecondSymbolAddress) | |||
477 | continue; | |||
478 | ||||
479 | auto SectionName = Section.getName(); | |||
480 | if (!SectionName) | |||
481 | continue; | |||
482 | ||||
483 | int32_t Addend; | |||
484 | memcpy(&Addend, Contents.data() + It->getOffset(), sizeof(int32_t)); | |||
485 | int32_t Value = (*SecondSymbolAddress + Addend) - *FirstSymbolAddress; | |||
486 | auto ReflSectionKind = | |||
487 | MO->mapReflectionSectionNameToEnumValue(*SectionName); | |||
488 | uint64_t AddressFromDwarfVM = | |||
489 | SectionToOffsetInDwarf[ReflSectionKind] + It->getOffset(); | |||
490 | RelocationsToApply.emplace_back(AddressFromDwarfVM, Value, | |||
491 | ShouldSubtractDwarfVM); | |||
492 | } | |||
493 | } | |||
494 | ||||
495 | void DwarfLinkerForBinary::copySwiftReflectionMetadata( | |||
496 | const llvm::dsymutil::DebugMapObject *Obj, DwarfStreamer *Streamer, | |||
497 | std::vector<uint64_t> &SectionToOffsetInDwarf, | |||
498 | std::vector<MachOUtils::DwarfRelocationApplicationInfo> | |||
499 | &RelocationsToApply) { | |||
500 | using binaryformat::Swift5ReflectionSectionKind; | |||
501 | auto OF = | |||
502 | llvm::object::ObjectFile::createObjectFile(Obj->getObjectFilename()); | |||
503 | if (!OF) { | |||
504 | llvm::consumeError(OF.takeError()); | |||
505 | return; | |||
506 | } | |||
507 | if (auto *MO = dyn_cast<llvm::object::MachOObjectFile>(OF->getBinary())) { | |||
508 | // Collect the swift reflection sections before emitting them. This is | |||
509 | // done so we control the order they're emitted. | |||
510 | std::array<Optional<object::SectionRef>, | |||
511 | Swift5ReflectionSectionKind::last + 1> | |||
512 | SwiftSections; | |||
513 | for (auto &Section : MO->sections()) { | |||
514 | llvm::Expected<llvm::StringRef> NameOrErr = | |||
515 | MO->getSectionName(Section.getRawDataRefImpl()); | |||
516 | if (!NameOrErr) { | |||
517 | llvm::consumeError(NameOrErr.takeError()); | |||
518 | continue; | |||
519 | } | |||
520 | NameOrErr->consume_back("__TEXT"); | |||
521 | auto ReflSectionKind = | |||
522 | MO->mapReflectionSectionNameToEnumValue(*NameOrErr); | |||
523 | if (MO->isReflectionSectionStrippable(ReflSectionKind)) | |||
524 | SwiftSections[ReflSectionKind] = Section; | |||
525 | } | |||
526 | // Make sure we copy the sections in alphabetic order. | |||
527 | auto SectionKindsToEmit = {Swift5ReflectionSectionKind::assocty, | |||
528 | Swift5ReflectionSectionKind::fieldmd, | |||
529 | Swift5ReflectionSectionKind::reflstr}; | |||
530 | for (auto SectionKind : SectionKindsToEmit) { | |||
531 | if (!SwiftSections[SectionKind]) | |||
532 | continue; | |||
533 | auto &Section = *SwiftSections[SectionKind]; | |||
534 | llvm::Expected<llvm::StringRef> SectionContents = Section.getContents(); | |||
535 | if (!SectionContents) | |||
536 | continue; | |||
537 | const auto *MO = | |||
538 | llvm::cast<llvm::object::MachOObjectFile>(Section.getObject()); | |||
539 | collectRelocationsToApplyToSwiftReflectionSections( | |||
540 | Section, *SectionContents, MO, SectionToOffsetInDwarf, Obj, | |||
541 | RelocationsToApply); | |||
542 | // Update the section start with the current section's contribution, so | |||
543 | // the next section we copy from a different .o file points to the correct | |||
544 | // place. | |||
545 | SectionToOffsetInDwarf[SectionKind] += Section.getSize(); | |||
546 | Streamer->emitSwiftReflectionSection(SectionKind, *SectionContents, | |||
547 | Section.getAlignment(), | |||
548 | Section.getSize()); | |||
549 | } | |||
550 | } | |||
551 | } | |||
552 | ||||
553 | bool DwarfLinkerForBinary::link(const DebugMap &Map) { | |||
554 | if (!createStreamer(Map.getTriple(), OutFile)) | |||
555 | return false; | |||
556 | ||||
557 | ObjectsForLinking.clear(); | |||
558 | ContextForLinking.clear(); | |||
559 | AddressMapForLinking.clear(); | |||
560 | ||||
561 | DebugMap DebugMap(Map.getTriple(), Map.getBinaryPath()); | |||
562 | ||||
563 | DWARFLinker GeneralLinker(Streamer.get(), DwarfLinkerClient::Dsymutil); | |||
564 | ||||
565 | remarks::RemarkLinker RL; | |||
566 | if (!Options.RemarksPrependPath.empty()) | |||
567 | RL.setExternalFilePrependPath(Options.RemarksPrependPath); | |||
568 | GeneralLinker.setObjectPrefixMap(&Options.ObjectPrefixMap); | |||
569 | ||||
570 | std::function<StringRef(StringRef)> TranslationLambda = [&](StringRef Input) { | |||
571 | assert(Options.Translator)(static_cast <bool> (Options.Translator) ? void (0) : __assert_fail ("Options.Translator", "llvm/tools/dsymutil/DwarfLinkerForBinary.cpp" , 571, __extension__ __PRETTY_FUNCTION__)); | |||
572 | return Options.Translator(Input); | |||
573 | }; | |||
574 | ||||
575 | GeneralLinker.setVerbosity(Options.Verbose); | |||
576 | GeneralLinker.setStatistics(Options.Statistics); | |||
577 | GeneralLinker.setVerifyInputDWARF(Options.VerifyInputDWARF); | |||
578 | GeneralLinker.setNoOutput(Options.NoOutput); | |||
579 | GeneralLinker.setNoODR(Options.NoODR); | |||
580 | GeneralLinker.setUpdate(Options.Update); | |||
581 | GeneralLinker.setNumThreads(Options.Threads); | |||
582 | GeneralLinker.setAccelTableKind(Options.TheAccelTableKind); | |||
583 | GeneralLinker.setPrependPath(Options.PrependPath); | |||
584 | GeneralLinker.setKeepFunctionForStatic(Options.KeepFunctionForStatic); | |||
585 | if (Options.Translator) | |||
586 | GeneralLinker.setStringsTranslator(TranslationLambda); | |||
587 | GeneralLinker.setWarningHandler( | |||
588 | [&](const Twine &Warning, StringRef Context, const DWARFDie *DIE) { | |||
589 | reportWarning(Warning, Context, DIE); | |||
590 | }); | |||
591 | GeneralLinker.setErrorHandler( | |||
592 | [&](const Twine &Error, StringRef Context, const DWARFDie *) { | |||
593 | error(Error, Context); | |||
594 | }); | |||
595 | GeneralLinker.setObjFileLoader( | |||
596 | [&DebugMap, &RL, this](StringRef ContainerName, | |||
597 | StringRef Path) -> ErrorOr<DWARFFile &> { | |||
598 | auto &Obj = DebugMap.addDebugMapObject( | |||
599 | Path, sys::TimePoint<std::chrono::seconds>(), MachO::N_OSO); | |||
600 | ||||
601 | if (auto ErrorOrObj = loadObject(Obj, DebugMap, RL)) { | |||
| ||||
602 | return *ErrorOrObj; | |||
603 | } else { | |||
604 | // Try and emit more helpful warnings by applying some heuristics. | |||
605 | StringRef ObjFile = ContainerName; | |||
606 | bool IsClangModule = sys::path::extension(Path).equals(".pcm"); | |||
607 | bool IsArchive = ObjFile.endswith(")"); | |||
608 | ||||
609 | if (IsClangModule) { | |||
610 | StringRef ModuleCacheDir = sys::path::parent_path(Path); | |||
611 | if (sys::fs::exists(ModuleCacheDir)) { | |||
612 | // If the module's parent directory exists, we assume that the | |||
613 | // module cache has expired and was pruned by clang. A more | |||
614 | // adventurous dsymutil would invoke clang to rebuild the module | |||
615 | // now. | |||
616 | if (!ModuleCacheHintDisplayed) { | |||
617 | WithColor::note() | |||
618 | << "The clang module cache may have expired since " | |||
619 | "this object file was built. Rebuilding the " | |||
620 | "object file will rebuild the module cache.\n"; | |||
621 | ModuleCacheHintDisplayed = true; | |||
622 | } | |||
623 | } else if (IsArchive) { | |||
624 | // If the module cache directory doesn't exist at all and the | |||
625 | // object file is inside a static library, we assume that the | |||
626 | // static library was built on a different machine. We don't want | |||
627 | // to discourage module debugging for convenience libraries within | |||
628 | // a project though. | |||
629 | if (!ArchiveHintDisplayed) { | |||
630 | WithColor::note() | |||
631 | << "Linking a static library that was built with " | |||
632 | "-gmodules, but the module cache was not found. " | |||
633 | "Redistributable static libraries should never be " | |||
634 | "built with module debugging enabled. The debug " | |||
635 | "experience will be degraded due to incomplete " | |||
636 | "debug information.\n"; | |||
637 | ArchiveHintDisplayed = true; | |||
638 | } | |||
639 | } | |||
640 | } | |||
641 | ||||
642 | return ErrorOrObj.getError(); | |||
643 | } | |||
644 | ||||
645 | llvm_unreachable("Unhandled DebugMap object")::llvm::llvm_unreachable_internal("Unhandled DebugMap object" , "llvm/tools/dsymutil/DwarfLinkerForBinary.cpp", 645); | |||
646 | }); | |||
647 | GeneralLinker.setSwiftInterfacesMap(&ParseableSwiftInterfaces); | |||
648 | bool ReflectionSectionsPresentInBinary = false; | |||
649 | // If there is no output specified, no point in checking the binary for swift5 | |||
650 | // reflection sections. | |||
651 | if (!Options.NoOutput) { | |||
652 | ReflectionSectionsPresentInBinary = | |||
653 | binaryHasStrippableSwiftReflectionSections(Map, Options, BinHolder); | |||
654 | } | |||
655 | ||||
656 | std::vector<MachOUtils::DwarfRelocationApplicationInfo> RelocationsToApply; | |||
657 | if (!Options.NoOutput && !ReflectionSectionsPresentInBinary) { | |||
658 | auto SectionToOffsetInDwarf = | |||
659 | calculateStartOfStrippableReflectionSections(Map); | |||
660 | for (const auto &Obj : Map.objects()) | |||
661 | copySwiftReflectionMetadata(Obj.get(), Streamer.get(), | |||
662 | SectionToOffsetInDwarf, RelocationsToApply); | |||
663 | } | |||
664 | ||||
665 | for (const auto &Obj : Map.objects()) { | |||
666 | // N_AST objects (swiftmodule files) should get dumped directly into the | |||
667 | // appropriate DWARF section. | |||
668 | if (Obj->getType() == MachO::N_AST) { | |||
669 | if (Options.Verbose) | |||
670 | outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n"; | |||
671 | ||||
672 | StringRef File = Obj->getObjectFilename(); | |||
673 | auto ErrorOrMem = MemoryBuffer::getFile(File); | |||
674 | if (!ErrorOrMem) { | |||
675 | warn("Could not open '" + File + "'\n"); | |||
676 | continue; | |||
677 | } | |||
678 | sys::fs::file_status Stat; | |||
679 | if (auto Err = sys::fs::status(File, Stat)) { | |||
680 | warn(Err.message()); | |||
681 | continue; | |||
682 | } | |||
683 | if (!Options.NoTimestamp) { | |||
684 | // The modification can have sub-second precision so we need to cast | |||
685 | // away the extra precision that's not present in the debug map. | |||
686 | auto ModificationTime = | |||
687 | std::chrono::time_point_cast<std::chrono::seconds>( | |||
688 | Stat.getLastModificationTime()); | |||
689 | if (Obj->getTimestamp() != sys::TimePoint<>() && | |||
690 | ModificationTime != Obj->getTimestamp()) { | |||
691 | // Not using the helper here as we can easily stream TimePoint<>. | |||
692 | WithColor::warning() | |||
693 | << File << ": timestamp mismatch between swift interface file (" | |||
694 | << sys::TimePoint<>(ModificationTime) << ") and debug map (" | |||
695 | << sys::TimePoint<>(Obj->getTimestamp()) << ")\n"; | |||
696 | continue; | |||
697 | } | |||
698 | } | |||
699 | ||||
700 | // Copy the module into the .swift_ast section. | |||
701 | if (!Options.NoOutput) | |||
702 | Streamer->emitSwiftAST((*ErrorOrMem)->getBuffer()); | |||
703 | ||||
704 | continue; | |||
705 | } | |||
706 | if (auto ErrorOrObj = loadObject(*Obj, Map, RL)) | |||
707 | GeneralLinker.addObjectFile(*ErrorOrObj); | |||
708 | else { | |||
709 | ObjectsForLinking.push_back(std::make_unique<DWARFFile>( | |||
710 | Obj->getObjectFilename(), nullptr, nullptr, | |||
711 | Obj->empty() ? Obj->getWarnings() : EmptyWarnings)); | |||
712 | GeneralLinker.addObjectFile(*ObjectsForLinking.back()); | |||
713 | } | |||
714 | } | |||
715 | ||||
716 | // link debug info for loaded object files. | |||
717 | GeneralLinker.link(); | |||
718 | ||||
719 | StringRef ArchName = Map.getTriple().getArchName(); | |||
720 | if (Error E = emitRemarks(Options, Map.getBinaryPath(), ArchName, RL)) | |||
721 | return error(toString(std::move(E))); | |||
722 | ||||
723 | if (Options.NoOutput) | |||
724 | return true; | |||
725 | ||||
726 | if (Options.ResourceDir && !ParseableSwiftInterfaces.empty()) { | |||
727 | StringRef ArchName = Triple::getArchTypeName(Map.getTriple().getArch()); | |||
728 | if (auto E = | |||
729 | copySwiftInterfaces(ParseableSwiftInterfaces, ArchName, Options)) | |||
730 | return error(toString(std::move(E))); | |||
731 | } | |||
732 | ||||
733 | if (Map.getTriple().isOSDarwin() && !Map.getBinaryPath().empty() && | |||
734 | Options.FileType == OutputFileType::Object) | |||
735 | return MachOUtils::generateDsymCompanion( | |||
736 | Options.VFS, Map, Options.Translator, | |||
737 | *Streamer->getAsmPrinter().OutStreamer, OutFile, RelocationsToApply); | |||
738 | ||||
739 | Streamer->finish(); | |||
740 | return true; | |||
741 | } | |||
742 | ||||
743 | /// Iterate over the relocations of the given \p Section and | |||
744 | /// store the ones that correspond to debug map entries into the | |||
745 | /// ValidRelocs array. | |||
746 | void DwarfLinkerForBinary::AddressManager::findValidRelocsMachO( | |||
747 | const object::SectionRef &Section, const object::MachOObjectFile &Obj, | |||
748 | const DebugMapObject &DMO, std::vector<ValidReloc> &ValidRelocs) { | |||
749 | Expected<StringRef> ContentsOrErr = Section.getContents(); | |||
750 | if (!ContentsOrErr) { | |||
751 | consumeError(ContentsOrErr.takeError()); | |||
752 | Linker.reportWarning("error reading section", DMO.getObjectFilename()); | |||
753 | return; | |||
754 | } | |||
755 | DataExtractor Data(*ContentsOrErr, Obj.isLittleEndian(), 0); | |||
756 | bool SkipNext = false; | |||
757 | ||||
758 | for (const object::RelocationRef &Reloc : Section.relocations()) { | |||
759 | if (SkipNext) { | |||
760 | SkipNext = false; | |||
761 | continue; | |||
762 | } | |||
763 | ||||
764 | object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl(); | |||
765 | MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef); | |||
766 | ||||
767 | if (object::MachOObjectFile::isMachOPairedReloc(Obj.getAnyRelocationType(MachOReloc), | |||
768 | Obj.getArch())) { | |||
769 | SkipNext = true; | |||
770 | Linker.reportWarning("unsupported relocation in " + *Section.getName() + | |||
771 | " section.", | |||
772 | DMO.getObjectFilename()); | |||
773 | continue; | |||
774 | } | |||
775 | ||||
776 | unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc); | |||
777 | uint64_t Offset64 = Reloc.getOffset(); | |||
778 | if ((RelocSize != 4 && RelocSize != 8)) { | |||
779 | Linker.reportWarning("unsupported relocation in " + *Section.getName() + | |||
780 | " section.", | |||
781 | DMO.getObjectFilename()); | |||
782 | continue; | |||
783 | } | |||
784 | uint64_t OffsetCopy = Offset64; | |||
785 | // Mach-o uses REL relocations, the addend is at the relocation offset. | |||
786 | uint64_t Addend = Data.getUnsigned(&OffsetCopy, RelocSize); | |||
787 | uint64_t SymAddress; | |||
788 | int64_t SymOffset; | |||
789 | ||||
790 | if (Obj.isRelocationScattered(MachOReloc)) { | |||
791 | // The address of the base symbol for scattered relocations is | |||
792 | // stored in the reloc itself. The actual addend will store the | |||
793 | // base address plus the offset. | |||
794 | SymAddress = Obj.getScatteredRelocationValue(MachOReloc); | |||
795 | SymOffset = int64_t(Addend) - SymAddress; | |||
796 | } else { | |||
797 | SymAddress = Addend; | |||
798 | SymOffset = 0; | |||
799 | } | |||
800 | ||||
801 | auto Sym = Reloc.getSymbol(); | |||
802 | if (Sym != Obj.symbol_end()) { | |||
803 | Expected<StringRef> SymbolName = Sym->getName(); | |||
804 | if (!SymbolName) { | |||
805 | consumeError(SymbolName.takeError()); | |||
806 | Linker.reportWarning("error getting relocation symbol name.", | |||
807 | DMO.getObjectFilename()); | |||
808 | continue; | |||
809 | } | |||
810 | if (const auto *Mapping = DMO.lookupSymbol(*SymbolName)) | |||
811 | ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping); | |||
812 | } else if (const auto *Mapping = DMO.lookupObjectAddress(SymAddress)) { | |||
813 | // Do not store the addend. The addend was the address of the symbol in | |||
814 | // the object file, the address in the binary that is stored in the debug | |||
815 | // map doesn't need to be offset. | |||
816 | ValidRelocs.emplace_back(Offset64, RelocSize, SymOffset, Mapping); | |||
817 | } | |||
818 | } | |||
819 | } | |||
820 | ||||
821 | /// Dispatch the valid relocation finding logic to the | |||
822 | /// appropriate handler depending on the object file format. | |||
823 | bool DwarfLinkerForBinary::AddressManager::findValidRelocs( | |||
824 | const object::SectionRef &Section, const object::ObjectFile &Obj, | |||
825 | const DebugMapObject &DMO, std::vector<ValidReloc> &Relocs) { | |||
826 | // Dispatch to the right handler depending on the file type. | |||
827 | if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj)) | |||
828 | findValidRelocsMachO(Section, *MachOObj, DMO, Relocs); | |||
829 | else | |||
830 | Linker.reportWarning(Twine("unsupported object file type: ") + | |||
831 | Obj.getFileName(), | |||
832 | DMO.getObjectFilename()); | |||
833 | if (Relocs.empty()) | |||
834 | return false; | |||
835 | ||||
836 | // Sort the relocations by offset. We will walk the DIEs linearly in | |||
837 | // the file, this allows us to just keep an index in the relocation | |||
838 | // array that we advance during our walk, rather than resorting to | |||
839 | // some associative container. See DwarfLinkerForBinary::NextValidReloc. | |||
840 | llvm::sort(Relocs); | |||
841 | return true; | |||
842 | } | |||
843 | ||||
844 | /// Look for relocations in the debug_info and debug_addr section that match | |||
845 | /// entries in the debug map. These relocations will drive the Dwarf link by | |||
846 | /// indicating which DIEs refer to symbols present in the linked binary. | |||
847 | /// \returns whether there are any valid relocations in the debug info. | |||
848 | bool DwarfLinkerForBinary::AddressManager::findValidRelocsInDebugSections( | |||
849 | const object::ObjectFile &Obj, const DebugMapObject &DMO) { | |||
850 | // Find the debug_info section. | |||
851 | bool FoundValidRelocs = false; | |||
852 | for (const object::SectionRef &Section : Obj.sections()) { | |||
853 | StringRef SectionName; | |||
854 | if (Expected<StringRef> NameOrErr = Section.getName()) | |||
855 | SectionName = *NameOrErr; | |||
856 | else | |||
857 | consumeError(NameOrErr.takeError()); | |||
858 | ||||
859 | SectionName = SectionName.substr(SectionName.find_first_not_of("._")); | |||
860 | if (SectionName == "debug_info") | |||
861 | FoundValidRelocs |= | |||
862 | findValidRelocs(Section, Obj, DMO, ValidDebugInfoRelocs); | |||
863 | if (SectionName == "debug_addr") | |||
864 | FoundValidRelocs |= | |||
865 | findValidRelocs(Section, Obj, DMO, ValidDebugAddrRelocs); | |||
866 | } | |||
867 | return FoundValidRelocs; | |||
868 | } | |||
869 | ||||
870 | std::vector<DwarfLinkerForBinary::AddressManager::ValidReloc> | |||
871 | DwarfLinkerForBinary::AddressManager::getRelocations( | |||
872 | const std::vector<ValidReloc> &Relocs, uint64_t StartPos, uint64_t EndPos) { | |||
873 | std::vector<DwarfLinkerForBinary::AddressManager::ValidReloc> Res; | |||
874 | ||||
875 | auto CurReloc = partition_point(Relocs, [StartPos](const ValidReloc &Reloc) { | |||
876 | return Reloc.Offset < StartPos; | |||
877 | }); | |||
878 | ||||
879 | while (CurReloc != Relocs.end() && CurReloc->Offset >= StartPos && | |||
880 | CurReloc->Offset < EndPos) { | |||
881 | Res.push_back(*CurReloc); | |||
882 | CurReloc++; | |||
883 | } | |||
884 | ||||
885 | return Res; | |||
886 | } | |||
887 | ||||
888 | void DwarfLinkerForBinary::AddressManager::printReloc(const ValidReloc &Reloc) { | |||
889 | const auto &Mapping = Reloc.Mapping->getValue(); | |||
890 | const uint64_t ObjectAddress = Mapping.ObjectAddress | |||
891 | ? uint64_t(*Mapping.ObjectAddress) | |||
892 | : std::numeric_limits<uint64_t>::max(); | |||
893 | ||||
894 | outs() << "Found valid debug map entry: " << Reloc.Mapping->getKey() << "\t" | |||
895 | << format("0x%016" PRIx64"l" "x" " => 0x%016" PRIx64"l" "x" "\n", ObjectAddress, | |||
896 | uint64_t(Mapping.BinaryAddress)); | |||
897 | } | |||
898 | ||||
899 | void DwarfLinkerForBinary::AddressManager::fillDieInfo( | |||
900 | const ValidReloc &Reloc, CompileUnit::DIEInfo &Info) { | |||
901 | Info.AddrAdjust = relocate(Reloc); | |||
902 | if (Reloc.Mapping->getValue().ObjectAddress) | |||
903 | Info.AddrAdjust -= uint64_t(*Reloc.Mapping->getValue().ObjectAddress); | |||
904 | Info.InDebugMap = true; | |||
905 | } | |||
906 | ||||
907 | bool DwarfLinkerForBinary::AddressManager::hasValidRelocationAt( | |||
908 | const std::vector<ValidReloc> &AllRelocs, uint64_t StartOffset, | |||
909 | uint64_t EndOffset, CompileUnit::DIEInfo &Info) { | |||
910 | std::vector<ValidReloc> Relocs = | |||
911 | getRelocations(AllRelocs, StartOffset, EndOffset); | |||
912 | ||||
913 | if (Relocs.size() == 0) | |||
914 | return false; | |||
915 | ||||
916 | if (Linker.Options.Verbose) | |||
917 | printReloc(Relocs[0]); | |||
918 | fillDieInfo(Relocs[0], Info); | |||
919 | ||||
920 | return true; | |||
921 | } | |||
922 | ||||
923 | /// Get the starting and ending (exclusive) offset for the | |||
924 | /// attribute with index \p Idx descibed by \p Abbrev. \p Offset is | |||
925 | /// supposed to point to the position of the first attribute described | |||
926 | /// by \p Abbrev. | |||
927 | /// \return [StartOffset, EndOffset) as a pair. | |||
928 | static std::pair<uint64_t, uint64_t> | |||
929 | getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx, | |||
930 | uint64_t Offset, const DWARFUnit &Unit) { | |||
931 | DataExtractor Data = Unit.getDebugInfoExtractor(); | |||
932 | ||||
933 | for (unsigned I = 0; I < Idx; ++I) | |||
934 | DWARFFormValue::skipValue(Abbrev->getFormByIndex(I), Data, &Offset, | |||
935 | Unit.getFormParams()); | |||
936 | ||||
937 | uint64_t End = Offset; | |||
938 | DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, | |||
939 | Unit.getFormParams()); | |||
940 | ||||
941 | return std::make_pair(Offset, End); | |||
942 | } | |||
943 | ||||
944 | bool DwarfLinkerForBinary::AddressManager::hasLiveMemoryLocation( | |||
945 | const DWARFDie &DIE, CompileUnit::DIEInfo &MyInfo) { | |||
946 | const auto *Abbrev = DIE.getAbbreviationDeclarationPtr(); | |||
947 | ||||
948 | Optional<uint32_t> LocationIdx = | |||
949 | Abbrev->findAttributeIndex(dwarf::DW_AT_location); | |||
950 | if (!LocationIdx) | |||
951 | return false; | |||
952 | ||||
953 | uint64_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode()); | |||
954 | uint64_t LocationOffset, LocationEndOffset; | |||
955 | std::tie(LocationOffset, LocationEndOffset) = | |||
956 | getAttributeOffsets(Abbrev, *LocationIdx, Offset, *DIE.getDwarfUnit()); | |||
957 | ||||
958 | // FIXME: Support relocations debug_addr. | |||
959 | return hasValidRelocationAt(ValidDebugInfoRelocs, LocationOffset, | |||
960 | LocationEndOffset, MyInfo); | |||
961 | } | |||
962 | ||||
963 | bool DwarfLinkerForBinary::AddressManager::hasLiveAddressRange( | |||
964 | const DWARFDie &DIE, CompileUnit::DIEInfo &MyInfo) { | |||
965 | const auto *Abbrev = DIE.getAbbreviationDeclarationPtr(); | |||
966 | ||||
967 | Optional<uint32_t> LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc); | |||
968 | if (!LowPcIdx) | |||
969 | return false; | |||
970 | ||||
971 | dwarf::Form Form = Abbrev->getFormByIndex(*LowPcIdx); | |||
972 | ||||
973 | if (Form == dwarf::DW_FORM_addr) { | |||
974 | uint64_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode()); | |||
975 | uint64_t LowPcOffset, LowPcEndOffset; | |||
976 | std::tie(LowPcOffset, LowPcEndOffset) = | |||
977 | getAttributeOffsets(Abbrev, *LowPcIdx, Offset, *DIE.getDwarfUnit()); | |||
978 | return hasValidRelocationAt(ValidDebugInfoRelocs, LowPcOffset, | |||
979 | LowPcEndOffset, MyInfo); | |||
980 | } | |||
981 | ||||
982 | if (Form == dwarf::DW_FORM_addrx) { | |||
983 | Optional<DWARFFormValue> AddrValue = DIE.find(dwarf::DW_AT_low_pc); | |||
984 | if (Optional<uint64_t> AddrOffsetSectionBase = | |||
985 | DIE.getDwarfUnit()->getAddrOffsetSectionBase()) { | |||
986 | uint64_t StartOffset = *AddrOffsetSectionBase + AddrValue->getRawUValue(); | |||
987 | uint64_t EndOffset = | |||
988 | StartOffset + DIE.getDwarfUnit()->getAddressByteSize(); | |||
989 | return hasValidRelocationAt(ValidDebugAddrRelocs, StartOffset, EndOffset, | |||
990 | MyInfo); | |||
991 | } else | |||
992 | Linker.reportWarning("no base offset for address table", SrcFileName); | |||
993 | } | |||
994 | ||||
995 | return false; | |||
996 | } | |||
997 | ||||
998 | uint64_t | |||
999 | DwarfLinkerForBinary::AddressManager::relocate(const ValidReloc &Reloc) const { | |||
1000 | return Reloc.Mapping->getValue().BinaryAddress + Reloc.Addend; | |||
1001 | } | |||
1002 | ||||
1003 | /// Apply the valid relocations found by findValidRelocs() to | |||
1004 | /// the buffer \p Data, taking into account that Data is at \p BaseOffset | |||
1005 | /// in the debug_info section. | |||
1006 | /// | |||
1007 | /// Like for findValidRelocs(), this function must be called with | |||
1008 | /// monotonic \p BaseOffset values. | |||
1009 | /// | |||
1010 | /// \returns whether any reloc has been applied. | |||
1011 | bool DwarfLinkerForBinary::AddressManager::applyValidRelocs( | |||
1012 | MutableArrayRef<char> Data, uint64_t BaseOffset, bool IsLittleEndian) { | |||
1013 | assert(areRelocationsResolved())(static_cast <bool> (areRelocationsResolved()) ? void ( 0) : __assert_fail ("areRelocationsResolved()", "llvm/tools/dsymutil/DwarfLinkerForBinary.cpp" , 1013, __extension__ __PRETTY_FUNCTION__)); | |||
1014 | std::vector<ValidReloc> Relocs = getRelocations( | |||
1015 | ValidDebugInfoRelocs, BaseOffset, BaseOffset + Data.size()); | |||
1016 | ||||
1017 | for (const ValidReloc &CurReloc : Relocs) { | |||
1018 | assert(CurReloc.Offset - BaseOffset < Data.size())(static_cast <bool> (CurReloc.Offset - BaseOffset < Data .size()) ? void (0) : __assert_fail ("CurReloc.Offset - BaseOffset < Data.size()" , "llvm/tools/dsymutil/DwarfLinkerForBinary.cpp", 1018, __extension__ __PRETTY_FUNCTION__)); | |||
1019 | assert(CurReloc.Offset - BaseOffset + CurReloc.Size <= Data.size())(static_cast <bool> (CurReloc.Offset - BaseOffset + CurReloc .Size <= Data.size()) ? void (0) : __assert_fail ("CurReloc.Offset - BaseOffset + CurReloc.Size <= Data.size()" , "llvm/tools/dsymutil/DwarfLinkerForBinary.cpp", 1019, __extension__ __PRETTY_FUNCTION__)); | |||
1020 | char Buf[8]; | |||
1021 | uint64_t Value = relocate(CurReloc); | |||
1022 | for (unsigned I = 0; I != CurReloc.Size; ++I) { | |||
1023 | unsigned Index = IsLittleEndian ? I : (CurReloc.Size - I - 1); | |||
1024 | Buf[I] = uint8_t(Value >> (Index * 8)); | |||
1025 | } | |||
1026 | assert(CurReloc.Size <= sizeof(Buf))(static_cast <bool> (CurReloc.Size <= sizeof(Buf)) ? void (0) : __assert_fail ("CurReloc.Size <= sizeof(Buf)", "llvm/tools/dsymutil/DwarfLinkerForBinary.cpp", 1026, __extension__ __PRETTY_FUNCTION__)); | |||
1027 | memcpy(&Data[CurReloc.Offset - BaseOffset], Buf, CurReloc.Size); | |||
1028 | } | |||
1029 | ||||
1030 | return Relocs.size() > 0; | |||
1031 | } | |||
1032 | ||||
1033 | llvm::Expected<uint64_t> | |||
1034 | DwarfLinkerForBinary::AddressManager::relocateIndexedAddr(uint64_t StartOffset, | |||
1035 | uint64_t EndOffset) { | |||
1036 | std::vector<ValidReloc> Relocs = | |||
1037 | getRelocations(ValidDebugAddrRelocs, StartOffset, EndOffset); | |||
1038 | if (Relocs.size() == 0) | |||
1039 | return createStringError( | |||
1040 | std::make_error_code(std::errc::invalid_argument), | |||
1041 | "no relocation for offset %llu in debug_addr section", StartOffset); | |||
1042 | ||||
1043 | return relocate(Relocs[0]); | |||
1044 | } | |||
1045 | ||||
1046 | bool linkDwarf(raw_fd_ostream &OutFile, BinaryHolder &BinHolder, | |||
1047 | const DebugMap &DM, LinkOptions Options) { | |||
1048 | DwarfLinkerForBinary Linker(OutFile, BinHolder, std::move(Options)); | |||
1049 | return Linker.link(DM); | |||
1050 | } | |||
1051 | ||||
1052 | } // namespace dsymutil | |||
1053 | } // namespace llvm |
1 | //===- llvm/Support/Error.h - Recoverable error handling --------*- C++ -*-===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | // This file defines an API used to report recoverable errors. |
10 | // |
11 | //===----------------------------------------------------------------------===// |
12 | |
13 | #ifndef LLVM_SUPPORT_ERROR_H |
14 | #define LLVM_SUPPORT_ERROR_H |
15 | |
16 | #include "llvm-c/Error.h" |
17 | #include "llvm/ADT/SmallVector.h" |
18 | #include "llvm/ADT/StringExtras.h" |
19 | #include "llvm/ADT/Twine.h" |
20 | #include "llvm/Config/abi-breaking.h" |
21 | #include "llvm/Support/AlignOf.h" |
22 | #include "llvm/Support/Compiler.h" |
23 | #include "llvm/Support/Debug.h" |
24 | #include "llvm/Support/ErrorHandling.h" |
25 | #include "llvm/Support/ErrorOr.h" |
26 | #include "llvm/Support/Format.h" |
27 | #include "llvm/Support/raw_ostream.h" |
28 | #include <cassert> |
29 | #include <cstdint> |
30 | #include <cstdlib> |
31 | #include <functional> |
32 | #include <memory> |
33 | #include <new> |
34 | #include <string> |
35 | #include <system_error> |
36 | #include <type_traits> |
37 | #include <utility> |
38 | #include <vector> |
39 | |
40 | namespace llvm { |
41 | |
42 | class ErrorSuccess; |
43 | |
44 | /// Base class for error info classes. Do not extend this directly: Extend |
45 | /// the ErrorInfo template subclass instead. |
46 | class ErrorInfoBase { |
47 | public: |
48 | virtual ~ErrorInfoBase() = default; |
49 | |
50 | /// Print an error message to an output stream. |
51 | virtual void log(raw_ostream &OS) const = 0; |
52 | |
53 | /// Return the error message as a string. |
54 | virtual std::string message() const { |
55 | std::string Msg; |
56 | raw_string_ostream OS(Msg); |
57 | log(OS); |
58 | return OS.str(); |
59 | } |
60 | |
61 | /// Convert this error to a std::error_code. |
62 | /// |
63 | /// This is a temporary crutch to enable interaction with code still |
64 | /// using std::error_code. It will be removed in the future. |
65 | virtual std::error_code convertToErrorCode() const = 0; |
66 | |
67 | // Returns the class ID for this type. |
68 | static const void *classID() { return &ID; } |
69 | |
70 | // Returns the class ID for the dynamic type of this ErrorInfoBase instance. |
71 | virtual const void *dynamicClassID() const = 0; |
72 | |
73 | // Check whether this instance is a subclass of the class identified by |
74 | // ClassID. |
75 | virtual bool isA(const void *const ClassID) const { |
76 | return ClassID == classID(); |
77 | } |
78 | |
79 | // Check whether this instance is a subclass of ErrorInfoT. |
80 | template <typename ErrorInfoT> bool isA() const { |
81 | return isA(ErrorInfoT::classID()); |
82 | } |
83 | |
84 | private: |
85 | virtual void anchor(); |
86 | |
87 | static char ID; |
88 | }; |
89 | |
90 | /// Lightweight error class with error context and mandatory checking. |
91 | /// |
92 | /// Instances of this class wrap a ErrorInfoBase pointer. Failure states |
93 | /// are represented by setting the pointer to a ErrorInfoBase subclass |
94 | /// instance containing information describing the failure. Success is |
95 | /// represented by a null pointer value. |
96 | /// |
97 | /// Instances of Error also contains a 'Checked' flag, which must be set |
98 | /// before the destructor is called, otherwise the destructor will trigger a |
99 | /// runtime error. This enforces at runtime the requirement that all Error |
100 | /// instances be checked or returned to the caller. |
101 | /// |
102 | /// There are two ways to set the checked flag, depending on what state the |
103 | /// Error instance is in. For Error instances indicating success, it |
104 | /// is sufficient to invoke the boolean conversion operator. E.g.: |
105 | /// |
106 | /// @code{.cpp} |
107 | /// Error foo(<...>); |
108 | /// |
109 | /// if (auto E = foo(<...>)) |
110 | /// return E; // <- Return E if it is in the error state. |
111 | /// // We have verified that E was in the success state. It can now be safely |
112 | /// // destroyed. |
113 | /// @endcode |
114 | /// |
115 | /// A success value *can not* be dropped. For example, just calling 'foo(<...>)' |
116 | /// without testing the return value will raise a runtime error, even if foo |
117 | /// returns success. |
118 | /// |
119 | /// For Error instances representing failure, you must use either the |
120 | /// handleErrors or handleAllErrors function with a typed handler. E.g.: |
121 | /// |
122 | /// @code{.cpp} |
123 | /// class MyErrorInfo : public ErrorInfo<MyErrorInfo> { |
124 | /// // Custom error info. |
125 | /// }; |
126 | /// |
127 | /// Error foo(<...>) { return make_error<MyErrorInfo>(...); } |
128 | /// |
129 | /// auto E = foo(<...>); // <- foo returns failure with MyErrorInfo. |
130 | /// auto NewE = |
131 | /// handleErrors(E, |
132 | /// [](const MyErrorInfo &M) { |
133 | /// // Deal with the error. |
134 | /// }, |
135 | /// [](std::unique_ptr<OtherError> M) -> Error { |
136 | /// if (canHandle(*M)) { |
137 | /// // handle error. |
138 | /// return Error::success(); |
139 | /// } |
140 | /// // Couldn't handle this error instance. Pass it up the stack. |
141 | /// return Error(std::move(M)); |
142 | /// ); |
143 | /// // Note - we must check or return NewE in case any of the handlers |
144 | /// // returned a new error. |
145 | /// @endcode |
146 | /// |
147 | /// The handleAllErrors function is identical to handleErrors, except |
148 | /// that it has a void return type, and requires all errors to be handled and |
149 | /// no new errors be returned. It prevents errors (assuming they can all be |
150 | /// handled) from having to be bubbled all the way to the top-level. |
151 | /// |
152 | /// *All* Error instances must be checked before destruction, even if |
153 | /// they're moved-assigned or constructed from Success values that have already |
154 | /// been checked. This enforces checking through all levels of the call stack. |
155 | class LLVM_NODISCARD[[clang::warn_unused_result]] Error { |
156 | // ErrorList needs to be able to yank ErrorInfoBase pointers out of Errors |
157 | // to add to the error list. It can't rely on handleErrors for this, since |
158 | // handleErrors does not support ErrorList handlers. |
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 | // wrap needs to be able to steal the payload. |
170 | friend LLVMErrorRef wrap(Error); |
171 | |
172 | protected: |
173 | /// Create a success value. Prefer using 'Error::success()' for readability |
174 | Error() { |
175 | setPtr(nullptr); |
176 | setChecked(false); |
177 | } |
178 | |
179 | public: |
180 | /// Create a success value. |
181 | static ErrorSuccess success(); |
182 | |
183 | // Errors are not copy-constructable. |
184 | Error(const Error &Other) = delete; |
185 | |
186 | /// Move-construct an error value. The newly constructed error is considered |
187 | /// unchecked, even if the source error had been checked. The original error |
188 | /// becomes a checked Success value, regardless of its original state. |
189 | Error(Error &&Other) { |
190 | setChecked(true); |
191 | *this = std::move(Other); |
192 | } |
193 | |
194 | /// Create an error value. Prefer using the 'make_error' function, but |
195 | /// this constructor can be useful when "re-throwing" errors from handlers. |
196 | Error(std::unique_ptr<ErrorInfoBase> Payload) { |
197 | setPtr(Payload.release()); |
198 | setChecked(false); |
199 | } |
200 | |
201 | // Errors are not copy-assignable. |
202 | Error &operator=(const Error &Other) = delete; |
203 | |
204 | /// Move-assign an error value. The current error must represent success, you |
205 | /// you cannot overwrite an unhandled error. The current error is then |
206 | /// considered unchecked. The source error becomes a checked success value, |
207 | /// regardless of its original state. |
208 | Error &operator=(Error &&Other) { |
209 | // Don't allow overwriting of unchecked values. |
210 | assertIsChecked(); |
211 | setPtr(Other.getPtr()); |
212 | |
213 | // This Error is unchecked, even if the source error was checked. |
214 | setChecked(false); |
215 | |
216 | // Null out Other's payload and set its checked bit. |
217 | Other.setPtr(nullptr); |
218 | Other.setChecked(true); |
219 | |
220 | return *this; |
221 | } |
222 | |
223 | /// Destroy a Error. Fails with a call to abort() if the error is |
224 | /// unchecked. |
225 | ~Error() { |
226 | assertIsChecked(); |
227 | delete getPtr(); |
228 | } |
229 | |
230 | /// Bool conversion. Returns true if this Error is in a failure state, |
231 | /// and false if it is in an accept state. If the error is in a Success state |
232 | /// it will be considered checked. |
233 | explicit operator bool() { |
234 | setChecked(getPtr() == nullptr); |
235 | return getPtr() != nullptr; |
236 | } |
237 | |
238 | /// Check whether one error is a subclass of another. |
239 | template <typename ErrT> bool isA() const { |
240 | return getPtr() && getPtr()->isA(ErrT::classID()); |
241 | } |
242 | |
243 | /// Returns the dynamic class id of this error, or null if this is a success |
244 | /// value. |
245 | const void* dynamicClassID() const { |
246 | if (!getPtr()) |
247 | return nullptr; |
248 | return getPtr()->dynamicClassID(); |
249 | } |
250 | |
251 | private: |
252 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
253 | // assertIsChecked() happens very frequently, but under normal circumstances |
254 | // is supposed to be a no-op. So we want it to be inlined, but having a bunch |
255 | // of debug prints can cause the function to be too large for inlining. So |
256 | // it's important that we define this function out of line so that it can't be |
257 | // inlined. |
258 | [[noreturn]] void fatalUncheckedError() const; |
259 | #endif |
260 | |
261 | void assertIsChecked() { |
262 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
263 | if (LLVM_UNLIKELY(!getChecked() || getPtr())__builtin_expect((bool)(!getChecked() || getPtr()), false)) |
264 | fatalUncheckedError(); |
265 | #endif |
266 | } |
267 | |
268 | ErrorInfoBase *getPtr() const { |
269 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
270 | return reinterpret_cast<ErrorInfoBase*>( |
271 | reinterpret_cast<uintptr_t>(Payload) & |
272 | ~static_cast<uintptr_t>(0x1)); |
273 | #else |
274 | return Payload; |
275 | #endif |
276 | } |
277 | |
278 | void setPtr(ErrorInfoBase *EI) { |
279 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
280 | Payload = reinterpret_cast<ErrorInfoBase*>( |
281 | (reinterpret_cast<uintptr_t>(EI) & |
282 | ~static_cast<uintptr_t>(0x1)) | |
283 | (reinterpret_cast<uintptr_t>(Payload) & 0x1)); |
284 | #else |
285 | Payload = EI; |
286 | #endif |
287 | } |
288 | |
289 | bool getChecked() const { |
290 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
291 | return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0; |
292 | #else |
293 | return true; |
294 | #endif |
295 | } |
296 | |
297 | void setChecked(bool V) { |
298 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
299 | Payload = reinterpret_cast<ErrorInfoBase*>( |
300 | (reinterpret_cast<uintptr_t>(Payload) & |
301 | ~static_cast<uintptr_t>(0x1)) | |
302 | (V ? 0 : 1)); |
303 | #endif |
304 | } |
305 | |
306 | std::unique_ptr<ErrorInfoBase> takePayload() { |
307 | std::unique_ptr<ErrorInfoBase> Tmp(getPtr()); |
308 | setPtr(nullptr); |
309 | setChecked(true); |
310 | return Tmp; |
311 | } |
312 | |
313 | friend raw_ostream &operator<<(raw_ostream &OS, const Error &E) { |
314 | if (auto *P = E.getPtr()) |
315 | P->log(OS); |
316 | else |
317 | OS << "success"; |
318 | return OS; |
319 | } |
320 | |
321 | ErrorInfoBase *Payload = nullptr; |
322 | }; |
323 | |
324 | /// Subclass of Error for the sole purpose of identifying the success path in |
325 | /// the type system. This allows to catch invalid conversion to Expected<T> at |
326 | /// compile time. |
327 | class ErrorSuccess final : public Error {}; |
328 | |
329 | inline ErrorSuccess Error::success() { return ErrorSuccess(); } |
330 | |
331 | /// Make a Error instance representing failure using the given error info |
332 | /// type. |
333 | template <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) { |
334 | return Error(std::make_unique<ErrT>(std::forward<ArgTs>(Args)...)); |
335 | } |
336 | |
337 | /// Base class for user error types. Users should declare their error types |
338 | /// like: |
339 | /// |
340 | /// class MyError : public ErrorInfo<MyError> { |
341 | /// .... |
342 | /// }; |
343 | /// |
344 | /// This class provides an implementation of the ErrorInfoBase::kind |
345 | /// method, which is used by the Error RTTI system. |
346 | template <typename ThisErrT, typename ParentErrT = ErrorInfoBase> |
347 | class ErrorInfo : public ParentErrT { |
348 | public: |
349 | using ParentErrT::ParentErrT; // inherit constructors |
350 | |
351 | static const void *classID() { return &ThisErrT::ID; } |
352 | |
353 | const void *dynamicClassID() const override { return &ThisErrT::ID; } |
354 | |
355 | bool isA(const void *const ClassID) const override { |
356 | return ClassID == classID() || ParentErrT::isA(ClassID); |
357 | } |
358 | }; |
359 | |
360 | /// Special ErrorInfo subclass representing a list of ErrorInfos. |
361 | /// Instances of this class are constructed by joinError. |
362 | class ErrorList final : public ErrorInfo<ErrorList> { |
363 | // handleErrors needs to be able to iterate the payload list of an |
364 | // ErrorList. |
365 | template <typename... HandlerTs> |
366 | friend Error handleErrors(Error E, HandlerTs &&... Handlers); |
367 | |
368 | // joinErrors is implemented in terms of join. |
369 | friend Error joinErrors(Error, Error); |
370 | |
371 | public: |
372 | void log(raw_ostream &OS) const override { |
373 | OS << "Multiple errors:\n"; |
374 | for (const auto &ErrPayload : Payloads) { |
375 | ErrPayload->log(OS); |
376 | OS << "\n"; |
377 | } |
378 | } |
379 | |
380 | std::error_code convertToErrorCode() const override; |
381 | |
382 | // Used by ErrorInfo::classID. |
383 | static char ID; |
384 | |
385 | private: |
386 | ErrorList(std::unique_ptr<ErrorInfoBase> Payload1, |
387 | std::unique_ptr<ErrorInfoBase> Payload2) { |
388 | 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\"" , "llvm/include/llvm/Support/Error.h", 389, __extension__ __PRETTY_FUNCTION__ )) |
389 | "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\"" , "llvm/include/llvm/Support/Error.h", 389, __extension__ __PRETTY_FUNCTION__ )); |
390 | Payloads.push_back(std::move(Payload1)); |
391 | Payloads.push_back(std::move(Payload2)); |
392 | } |
393 | |
394 | static Error join(Error E1, Error E2) { |
395 | if (!E1) |
396 | return E2; |
397 | if (!E2) |
398 | return E1; |
399 | if (E1.isA<ErrorList>()) { |
400 | auto &E1List = static_cast<ErrorList &>(*E1.getPtr()); |
401 | if (E2.isA<ErrorList>()) { |
402 | auto E2Payload = E2.takePayload(); |
403 | auto &E2List = static_cast<ErrorList &>(*E2Payload); |
404 | for (auto &Payload : E2List.Payloads) |
405 | E1List.Payloads.push_back(std::move(Payload)); |
406 | } else |
407 | E1List.Payloads.push_back(E2.takePayload()); |
408 | |
409 | return E1; |
410 | } |
411 | if (E2.isA<ErrorList>()) { |
412 | auto &E2List = static_cast<ErrorList &>(*E2.getPtr()); |
413 | E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload()); |
414 | return E2; |
415 | } |
416 | return Error(std::unique_ptr<ErrorList>( |
417 | new ErrorList(E1.takePayload(), E2.takePayload()))); |
418 | } |
419 | |
420 | std::vector<std::unique_ptr<ErrorInfoBase>> Payloads; |
421 | }; |
422 | |
423 | /// Concatenate errors. The resulting Error is unchecked, and contains the |
424 | /// ErrorInfo(s), if any, contained in E1, followed by the |
425 | /// ErrorInfo(s), if any, contained in E2. |
426 | inline Error joinErrors(Error E1, Error E2) { |
427 | return ErrorList::join(std::move(E1), std::move(E2)); |
428 | } |
429 | |
430 | /// Tagged union holding either a T or a Error. |
431 | /// |
432 | /// This class parallels ErrorOr, but replaces error_code with Error. Since |
433 | /// Error cannot be copied, this class replaces getError() with |
434 | /// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the |
435 | /// error class type. |
436 | /// |
437 | /// Example usage of 'Expected<T>' as a function return type: |
438 | /// |
439 | /// @code{.cpp} |
440 | /// Expected<int> myDivide(int A, int B) { |
441 | /// if (B == 0) { |
442 | /// // return an Error |
443 | /// return createStringError(inconvertibleErrorCode(), |
444 | /// "B must not be zero!"); |
445 | /// } |
446 | /// // return an integer |
447 | /// return A / B; |
448 | /// } |
449 | /// @endcode |
450 | /// |
451 | /// Checking the results of to a function returning 'Expected<T>': |
452 | /// @code{.cpp} |
453 | /// if (auto E = Result.takeError()) { |
454 | /// // We must consume the error. Typically one of: |
455 | /// // - return the error to our caller |
456 | /// // - toString(), when logging |
457 | /// // - consumeError(), to silently swallow the error |
458 | /// // - handleErrors(), to distinguish error types |
459 | /// errs() << "Problem with division " << toString(std::move(E)) << "\n"; |
460 | /// return; |
461 | /// } |
462 | /// // use the result |
463 | /// outs() << "The answer is " << *Result << "\n"; |
464 | /// @endcode |
465 | /// |
466 | /// For unit-testing a function returning an 'Expceted<T>', see the |
467 | /// 'EXPECT_THAT_EXPECTED' macros in llvm/Testing/Support/Error.h |
468 | |
469 | template <class T> class LLVM_NODISCARD[[clang::warn_unused_result]] Expected { |
470 | template <class T1> friend class ExpectedAsOutParameter; |
471 | template <class OtherT> friend class Expected; |
472 | |
473 | static constexpr bool isRef = std::is_reference<T>::value; |
474 | |
475 | using wrap = std::reference_wrapper<std::remove_reference_t<T>>; |
476 | |
477 | using error_type = std::unique_ptr<ErrorInfoBase>; |
478 | |
479 | public: |
480 | using storage_type = std::conditional_t<isRef, wrap, T>; |
481 | using value_type = T; |
482 | |
483 | private: |
484 | using reference = std::remove_reference_t<T> &; |
485 | using const_reference = const std::remove_reference_t<T> &; |
486 | using pointer = std::remove_reference_t<T> *; |
487 | using const_pointer = const std::remove_reference_t<T> *; |
488 | |
489 | public: |
490 | /// Create an Expected<T> error value from the given Error. |
491 | Expected(Error Err) |
492 | : HasError(true) |
493 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
494 | // Expected is unchecked upon construction in Debug builds. |
495 | , Unchecked(true) |
496 | #endif |
497 | { |
498 | 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.\"" , "llvm/include/llvm/Support/Error.h", 498, __extension__ __PRETTY_FUNCTION__ )); |
499 | new (getErrorStorage()) error_type(Err.takePayload()); |
500 | } |
501 | |
502 | /// Forbid to convert from Error::success() implicitly, this avoids having |
503 | /// Expected<T> foo() { return Error::success(); } which compiles otherwise |
504 | /// but triggers the assertion above. |
505 | Expected(ErrorSuccess) = delete; |
506 | |
507 | /// Create an Expected<T> success value from the given OtherT value, which |
508 | /// must be convertible to T. |
509 | template <typename OtherT> |
510 | Expected(OtherT &&Val, |
511 | std::enable_if_t<std::is_convertible<OtherT, T>::value> * = nullptr) |
512 | : HasError(false) |
513 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
514 | // Expected is unchecked upon construction in Debug builds. |
515 | , |
516 | Unchecked(true) |
517 | #endif |
518 | { |
519 | new (getStorage()) storage_type(std::forward<OtherT>(Val)); |
520 | } |
521 | |
522 | /// Move construct an Expected<T> value. |
523 | Expected(Expected &&Other) { moveConstruct(std::move(Other)); } |
524 | |
525 | /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT |
526 | /// must be convertible to T. |
527 | template <class OtherT> |
528 | Expected( |
529 | Expected<OtherT> &&Other, |
530 | std::enable_if_t<std::is_convertible<OtherT, T>::value> * = nullptr) { |
531 | moveConstruct(std::move(Other)); |
532 | } |
533 | |
534 | /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT |
535 | /// isn't convertible to T. |
536 | template <class OtherT> |
537 | explicit Expected( |
538 | Expected<OtherT> &&Other, |
539 | std::enable_if_t<!std::is_convertible<OtherT, T>::value> * = nullptr) { |
540 | moveConstruct(std::move(Other)); |
541 | } |
542 | |
543 | /// Move-assign from another Expected<T>. |
544 | Expected &operator=(Expected &&Other) { |
545 | moveAssign(std::move(Other)); |
546 | return *this; |
547 | } |
548 | |
549 | /// Destroy an Expected<T>. |
550 | ~Expected() { |
551 | assertIsChecked(); |
552 | if (!HasError) |
553 | getStorage()->~storage_type(); |
554 | else |
555 | getErrorStorage()->~error_type(); |
556 | } |
557 | |
558 | /// Return false if there is an error. |
559 | explicit operator bool() { |
560 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
561 | Unchecked = HasError; |
562 | #endif |
563 | return !HasError; |
564 | } |
565 | |
566 | /// Returns a reference to the stored T value. |
567 | reference get() { |
568 | assertIsChecked(); |
569 | return *getStorage(); |
570 | } |
571 | |
572 | /// Returns a const reference to the stored T value. |
573 | const_reference get() const { |
574 | assertIsChecked(); |
575 | return const_cast<Expected<T> *>(this)->get(); |
576 | } |
577 | |
578 | /// Returns \a takeError() after moving the held T (if any) into \p V. |
579 | template <class OtherT> |
580 | Error moveInto(OtherT &Value, |
581 | std::enable_if_t<std::is_assignable<OtherT &, T &&>::value> * = |
582 | nullptr) && { |
583 | if (*this) |
584 | Value = std::move(get()); |
585 | return takeError(); |
586 | } |
587 | |
588 | /// Check that this Expected<T> is an error of type ErrT. |
589 | template <typename ErrT> bool errorIsA() const { |
590 | return HasError && (*getErrorStorage())->template isA<ErrT>(); |
591 | } |
592 | |
593 | /// Take ownership of the stored error. |
594 | /// After calling this the Expected<T> is in an indeterminate state that can |
595 | /// only be safely destructed. No further calls (beside the destructor) should |
596 | /// be made on the Expected<T> value. |
597 | Error takeError() { |
598 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
599 | Unchecked = false; |
600 | #endif |
601 | return HasError ? Error(std::move(*getErrorStorage())) : Error::success(); |
602 | } |
603 | |
604 | /// Returns a pointer to the stored T value. |
605 | pointer operator->() { |
606 | assertIsChecked(); |
607 | return toPointer(getStorage()); |
608 | } |
609 | |
610 | /// Returns a const pointer to the stored T value. |
611 | const_pointer operator->() const { |
612 | assertIsChecked(); |
613 | return toPointer(getStorage()); |
614 | } |
615 | |
616 | /// Returns a reference to the stored T value. |
617 | reference operator*() { |
618 | assertIsChecked(); |
619 | return *getStorage(); |
620 | } |
621 | |
622 | /// Returns a const reference to the stored T value. |
623 | const_reference operator*() const { |
624 | assertIsChecked(); |
625 | return *getStorage(); |
626 | } |
627 | |
628 | private: |
629 | template <class T1> |
630 | static bool compareThisIfSameType(const T1 &a, const T1 &b) { |
631 | return &a == &b; |
632 | } |
633 | |
634 | template <class T1, class T2> |
635 | static bool compareThisIfSameType(const T1 &, const T2 &) { |
636 | return false; |
637 | } |
638 | |
639 | template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) { |
640 | HasError = Other.HasError; |
641 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
642 | Unchecked = true; |
643 | Other.Unchecked = false; |
644 | #endif |
645 | |
646 | if (!HasError) |
647 | new (getStorage()) storage_type(std::move(*Other.getStorage())); |
648 | else |
649 | new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage())); |
650 | } |
651 | |
652 | template <class OtherT> void moveAssign(Expected<OtherT> &&Other) { |
653 | assertIsChecked(); |
654 | |
655 | if (compareThisIfSameType(*this, Other)) |
656 | return; |
657 | |
658 | this->~Expected(); |
659 | new (this) Expected(std::move(Other)); |
660 | } |
661 | |
662 | pointer toPointer(pointer Val) { return Val; } |
663 | |
664 | const_pointer toPointer(const_pointer Val) const { return Val; } |
665 | |
666 | pointer toPointer(wrap *Val) { return &Val->get(); } |
667 | |
668 | const_pointer toPointer(const wrap *Val) const { return &Val->get(); } |
669 | |
670 | storage_type *getStorage() { |
671 | 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!\"" , "llvm/include/llvm/Support/Error.h", 671, __extension__ __PRETTY_FUNCTION__ )); |
672 | return reinterpret_cast<storage_type *>(&TStorage); |
673 | } |
674 | |
675 | const storage_type *getStorage() const { |
676 | 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!\"" , "llvm/include/llvm/Support/Error.h", 676, __extension__ __PRETTY_FUNCTION__ )); |
677 | return reinterpret_cast<const storage_type *>(&TStorage); |
678 | } |
679 | |
680 | error_type *getErrorStorage() { |
681 | 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!\"" , "llvm/include/llvm/Support/Error.h", 681, __extension__ __PRETTY_FUNCTION__ )); |
682 | return reinterpret_cast<error_type *>(&ErrorStorage); |
683 | } |
684 | |
685 | const error_type *getErrorStorage() const { |
686 | 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!\"" , "llvm/include/llvm/Support/Error.h", 686, __extension__ __PRETTY_FUNCTION__ )); |
687 | return reinterpret_cast<const error_type *>(&ErrorStorage); |
688 | } |
689 | |
690 | // Used by ExpectedAsOutParameter to reset the checked flag. |
691 | void setUnchecked() { |
692 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
693 | Unchecked = true; |
694 | #endif |
695 | } |
696 | |
697 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
698 | [[noreturn]] LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) void fatalUncheckedExpected() const { |
699 | dbgs() << "Expected<T> must be checked before access or destruction.\n"; |
700 | if (HasError) { |
701 | dbgs() << "Unchecked Expected<T> contained error:\n"; |
702 | (*getErrorStorage())->log(dbgs()); |
703 | } else |
704 | dbgs() << "Expected<T> value was in success state. (Note: Expected<T> " |
705 | "values in success mode must still be checked prior to being " |
706 | "destroyed).\n"; |
707 | abort(); |
708 | } |
709 | #endif |
710 | |
711 | void assertIsChecked() const { |
712 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
713 | if (LLVM_UNLIKELY(Unchecked)__builtin_expect((bool)(Unchecked), false)) |
714 | fatalUncheckedExpected(); |
715 | #endif |
716 | } |
717 | |
718 | union { |
719 | AlignedCharArrayUnion<storage_type> TStorage; |
720 | AlignedCharArrayUnion<error_type> ErrorStorage; |
721 | }; |
722 | bool HasError : 1; |
723 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
724 | bool Unchecked : 1; |
725 | #endif |
726 | }; |
727 | |
728 | /// Report a serious error, calling any installed error handler. See |
729 | /// ErrorHandling.h. |
730 | [[noreturn]] void report_fatal_error(Error Err, bool gen_crash_diag = true); |
731 | |
732 | /// Report a fatal error if Err is a failure value. |
733 | /// |
734 | /// This function can be used to wrap calls to fallible functions ONLY when it |
735 | /// is known that the Error will always be a success value. E.g. |
736 | /// |
737 | /// @code{.cpp} |
738 | /// // foo only attempts the fallible operation if DoFallibleOperation is |
739 | /// // true. If DoFallibleOperation is false then foo always returns |
740 | /// // Error::success(). |
741 | /// Error foo(bool DoFallibleOperation); |
742 | /// |
743 | /// cantFail(foo(false)); |
744 | /// @endcode |
745 | inline void cantFail(Error Err, const char *Msg = nullptr) { |
746 | if (Err) { |
747 | if (!Msg) |
748 | Msg = "Failure value returned from cantFail wrapped call"; |
749 | #ifndef NDEBUG |
750 | std::string Str; |
751 | raw_string_ostream OS(Str); |
752 | OS << Msg << "\n" << Err; |
753 | Msg = OS.str().c_str(); |
754 | #endif |
755 | llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "llvm/include/llvm/Support/Error.h" , 755); |
756 | } |
757 | } |
758 | |
759 | /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and |
760 | /// returns the contained value. |
761 | /// |
762 | /// This function can be used to wrap calls to fallible functions ONLY when it |
763 | /// is known that the Error will always be a success value. E.g. |
764 | /// |
765 | /// @code{.cpp} |
766 | /// // foo only attempts the fallible operation if DoFallibleOperation is |
767 | /// // true. If DoFallibleOperation is false then foo always returns an int. |
768 | /// Expected<int> foo(bool DoFallibleOperation); |
769 | /// |
770 | /// int X = cantFail(foo(false)); |
771 | /// @endcode |
772 | template <typename T> |
773 | T cantFail(Expected<T> ValOrErr, const char *Msg = nullptr) { |
774 | if (ValOrErr) |
775 | return std::move(*ValOrErr); |
776 | else { |
777 | if (!Msg) |
778 | Msg = "Failure value returned from cantFail wrapped call"; |
779 | #ifndef NDEBUG |
780 | std::string Str; |
781 | raw_string_ostream OS(Str); |
782 | auto E = ValOrErr.takeError(); |
783 | OS << Msg << "\n" << E; |
784 | Msg = OS.str().c_str(); |
785 | #endif |
786 | llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "llvm/include/llvm/Support/Error.h" , 786); |
787 | } |
788 | } |
789 | |
790 | /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and |
791 | /// returns the contained reference. |
792 | /// |
793 | /// This function can be used to wrap calls to fallible functions ONLY when it |
794 | /// is known that the Error will always be a success value. E.g. |
795 | /// |
796 | /// @code{.cpp} |
797 | /// // foo only attempts the fallible operation if DoFallibleOperation is |
798 | /// // true. If DoFallibleOperation is false then foo always returns a Bar&. |
799 | /// Expected<Bar&> foo(bool DoFallibleOperation); |
800 | /// |
801 | /// Bar &X = cantFail(foo(false)); |
802 | /// @endcode |
803 | template <typename T> |
804 | T& cantFail(Expected<T&> ValOrErr, const char *Msg = nullptr) { |
805 | if (ValOrErr) |
806 | return *ValOrErr; |
807 | else { |
808 | if (!Msg) |
809 | Msg = "Failure value returned from cantFail wrapped call"; |
810 | #ifndef NDEBUG |
811 | std::string Str; |
812 | raw_string_ostream OS(Str); |
813 | auto E = ValOrErr.takeError(); |
814 | OS << Msg << "\n" << E; |
815 | Msg = OS.str().c_str(); |
816 | #endif |
817 | llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "llvm/include/llvm/Support/Error.h" , 817); |
818 | } |
819 | } |
820 | |
821 | /// Helper for testing applicability of, and applying, handlers for |
822 | /// ErrorInfo types. |
823 | template <typename HandlerT> |
824 | class ErrorHandlerTraits |
825 | : public ErrorHandlerTraits<decltype( |
826 | &std::remove_reference<HandlerT>::type::operator())> {}; |
827 | |
828 | // Specialization functions of the form 'Error (const ErrT&)'. |
829 | template <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> { |
830 | public: |
831 | static bool appliesTo(const ErrorInfoBase &E) { |
832 | return E.template isA<ErrT>(); |
833 | } |
834 | |
835 | template <typename HandlerT> |
836 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { |
837 | assert(appliesTo(*E) && "Applying incorrect handler")(static_cast <bool> (appliesTo(*E) && "Applying incorrect handler" ) ? void (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\"" , "llvm/include/llvm/Support/Error.h", 837, __extension__ __PRETTY_FUNCTION__ )); |
838 | return H(static_cast<ErrT &>(*E)); |
839 | } |
840 | }; |
841 | |
842 | // Specialization functions of the form 'void (const ErrT&)'. |
843 | template <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> { |
844 | public: |
845 | static bool appliesTo(const ErrorInfoBase &E) { |
846 | return E.template isA<ErrT>(); |
847 | } |
848 | |
849 | template <typename HandlerT> |
850 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { |
851 | assert(appliesTo(*E) && "Applying incorrect handler")(static_cast <bool> (appliesTo(*E) && "Applying incorrect handler" ) ? void (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\"" , "llvm/include/llvm/Support/Error.h", 851, __extension__ __PRETTY_FUNCTION__ )); |
852 | H(static_cast<ErrT &>(*E)); |
853 | return Error::success(); |
854 | } |
855 | }; |
856 | |
857 | /// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'. |
858 | template <typename ErrT> |
859 | class ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> { |
860 | public: |
861 | static bool appliesTo(const ErrorInfoBase &E) { |
862 | return E.template isA<ErrT>(); |
863 | } |
864 | |
865 | template <typename HandlerT> |
866 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { |
867 | assert(appliesTo(*E) && "Applying incorrect handler")(static_cast <bool> (appliesTo(*E) && "Applying incorrect handler" ) ? void (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\"" , "llvm/include/llvm/Support/Error.h", 867, __extension__ __PRETTY_FUNCTION__ )); |
868 | std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release())); |
869 | return H(std::move(SubE)); |
870 | } |
871 | }; |
872 | |
873 | /// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'. |
874 | template <typename ErrT> |
875 | class ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> { |
876 | public: |
877 | static bool appliesTo(const ErrorInfoBase &E) { |
878 | return E.template isA<ErrT>(); |
879 | } |
880 | |
881 | template <typename HandlerT> |
882 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { |
883 | assert(appliesTo(*E) && "Applying incorrect handler")(static_cast <bool> (appliesTo(*E) && "Applying incorrect handler" ) ? void (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\"" , "llvm/include/llvm/Support/Error.h", 883, __extension__ __PRETTY_FUNCTION__ )); |
884 | std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release())); |
885 | H(std::move(SubE)); |
886 | return Error::success(); |
887 | } |
888 | }; |
889 | |
890 | // Specialization for member functions of the form 'RetT (const ErrT&)'. |
891 | template <typename C, typename RetT, typename ErrT> |
892 | class ErrorHandlerTraits<RetT (C::*)(ErrT &)> |
893 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; |
894 | |
895 | // Specialization for member functions of the form 'RetT (const ErrT&) const'. |
896 | template <typename C, typename RetT, typename ErrT> |
897 | class ErrorHandlerTraits<RetT (C::*)(ErrT &) const> |
898 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; |
899 | |
900 | // Specialization for member functions of the form 'RetT (const ErrT&)'. |
901 | template <typename C, typename RetT, typename ErrT> |
902 | class ErrorHandlerTraits<RetT (C::*)(const ErrT &)> |
903 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; |
904 | |
905 | // Specialization for member functions of the form 'RetT (const ErrT&) const'. |
906 | template <typename C, typename RetT, typename ErrT> |
907 | class ErrorHandlerTraits<RetT (C::*)(const ErrT &) const> |
908 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; |
909 | |
910 | /// Specialization for member functions of the form |
911 | /// 'RetT (std::unique_ptr<ErrT>)'. |
912 | template <typename C, typename RetT, typename ErrT> |
913 | class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>)> |
914 | : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {}; |
915 | |
916 | /// Specialization for member functions of the form |
917 | /// 'RetT (std::unique_ptr<ErrT>) const'. |
918 | template <typename C, typename RetT, typename ErrT> |
919 | class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>) const> |
920 | : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {}; |
921 | |
922 | inline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) { |
923 | return Error(std::move(Payload)); |
924 | } |
925 | |
926 | template <typename HandlerT, typename... HandlerTs> |
927 | Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload, |
928 | HandlerT &&Handler, HandlerTs &&... Handlers) { |
929 | if (ErrorHandlerTraits<HandlerT>::appliesTo(*Payload)) |
930 | return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler), |
931 | std::move(Payload)); |
932 | return handleErrorImpl(std::move(Payload), |
933 | std::forward<HandlerTs>(Handlers)...); |
934 | } |
935 | |
936 | /// Pass the ErrorInfo(s) contained in E to their respective handlers. Any |
937 | /// unhandled errors (or Errors returned by handlers) are re-concatenated and |
938 | /// returned. |
939 | /// Because this function returns an error, its result must also be checked |
940 | /// or returned. If you intend to handle all errors use handleAllErrors |
941 | /// (which returns void, and will abort() on unhandled errors) instead. |
942 | template <typename... HandlerTs> |
943 | Error handleErrors(Error E, HandlerTs &&... Hs) { |
944 | if (!E) |
945 | return Error::success(); |
946 | |
947 | std::unique_ptr<ErrorInfoBase> Payload = E.takePayload(); |
948 | |
949 | if (Payload->isA<ErrorList>()) { |
950 | ErrorList &List = static_cast<ErrorList &>(*Payload); |
951 | Error R; |
952 | for (auto &P : List.Payloads) |
953 | R = ErrorList::join( |
954 | std::move(R), |
955 | handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...)); |
956 | return R; |
957 | } |
958 | |
959 | return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...); |
960 | } |
961 | |
962 | /// Behaves the same as handleErrors, except that by contract all errors |
963 | /// *must* be handled by the given handlers (i.e. there must be no remaining |
964 | /// errors after running the handlers, or llvm_unreachable is called). |
965 | template <typename... HandlerTs> |
966 | void handleAllErrors(Error E, HandlerTs &&... Handlers) { |
967 | cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...)); |
968 | } |
969 | |
970 | /// Check that E is a non-error, then drop it. |
971 | /// If E is an error, llvm_unreachable will be called. |
972 | inline void handleAllErrors(Error E) { |
973 | cantFail(std::move(E)); |
974 | } |
975 | |
976 | /// Handle any errors (if present) in an Expected<T>, then try a recovery path. |
977 | /// |
978 | /// If the incoming value is a success value it is returned unmodified. If it |
979 | /// is a failure value then it the contained error is passed to handleErrors. |
980 | /// If handleErrors is able to handle the error then the RecoveryPath functor |
981 | /// is called to supply the final result. If handleErrors is not able to |
982 | /// handle all errors then the unhandled errors are returned. |
983 | /// |
984 | /// This utility enables the follow pattern: |
985 | /// |
986 | /// @code{.cpp} |
987 | /// enum FooStrategy { Aggressive, Conservative }; |
988 | /// Expected<Foo> foo(FooStrategy S); |
989 | /// |
990 | /// auto ResultOrErr = |
991 | /// handleExpected( |
992 | /// foo(Aggressive), |
993 | /// []() { return foo(Conservative); }, |
994 | /// [](AggressiveStrategyError&) { |
995 | /// // Implicitly conusme this - we'll recover by using a conservative |
996 | /// // strategy. |
997 | /// }); |
998 | /// |
999 | /// @endcode |
1000 | template <typename T, typename RecoveryFtor, typename... HandlerTs> |
1001 | Expected<T> handleExpected(Expected<T> ValOrErr, RecoveryFtor &&RecoveryPath, |
1002 | HandlerTs &&... Handlers) { |
1003 | if (ValOrErr) |
1004 | return ValOrErr; |
1005 | |
1006 | if (auto Err = handleErrors(ValOrErr.takeError(), |
1007 | std::forward<HandlerTs>(Handlers)...)) |
1008 | return std::move(Err); |
1009 | |
1010 | return RecoveryPath(); |
1011 | } |
1012 | |
1013 | /// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner |
1014 | /// will be printed before the first one is logged. A newline will be printed |
1015 | /// after each error. |
1016 | /// |
1017 | /// This function is compatible with the helpers from Support/WithColor.h. You |
1018 | /// can pass any of them as the OS. Please consider using them instead of |
1019 | /// including 'error: ' in the ErrorBanner. |
1020 | /// |
1021 | /// This is useful in the base level of your program to allow clean termination |
1022 | /// (allowing clean deallocation of resources, etc.), while reporting error |
1023 | /// information to the user. |
1024 | void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner = {}); |
1025 | |
1026 | /// Write all error messages (if any) in E to a string. The newline character |
1027 | /// is used to separate error messages. |
1028 | inline std::string toString(Error E) { |
1029 | SmallVector<std::string, 2> Errors; |
1030 | handleAllErrors(std::move(E), [&Errors](const ErrorInfoBase &EI) { |
1031 | Errors.push_back(EI.message()); |
1032 | }); |
1033 | return join(Errors.begin(), Errors.end(), "\n"); |
1034 | } |
1035 | |
1036 | /// Consume a Error without doing anything. This method should be used |
1037 | /// only where an error can be considered a reasonable and expected return |
1038 | /// value. |
1039 | /// |
1040 | /// Uses of this method are potentially indicative of design problems: If it's |
1041 | /// legitimate to do nothing while processing an "error", the error-producer |
1042 | /// might be more clearly refactored to return an Optional<T>. |
1043 | inline void consumeError(Error Err) { |
1044 | handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {}); |
1045 | } |
1046 | |
1047 | /// Convert an Expected to an Optional without doing anything. This method |
1048 | /// should be used only where an error can be considered a reasonable and |
1049 | /// expected return value. |
1050 | /// |
1051 | /// Uses of this method are potentially indicative of problems: perhaps the |
1052 | /// error should be propagated further, or the error-producer should just |
1053 | /// return an Optional in the first place. |
1054 | template <typename T> Optional<T> expectedToOptional(Expected<T> &&E) { |
1055 | if (E) |
1056 | return std::move(*E); |
1057 | consumeError(E.takeError()); |
1058 | return None; |
1059 | } |
1060 | |
1061 | /// Helper for converting an Error to a bool. |
1062 | /// |
1063 | /// This method returns true if Err is in an error state, or false if it is |
1064 | /// in a success state. Puts Err in a checked state in both cases (unlike |
1065 | /// Error::operator bool(), which only does this for success states). |
1066 | inline bool errorToBool(Error Err) { |
1067 | bool IsError = static_cast<bool>(Err); |
1068 | if (IsError) |
1069 | consumeError(std::move(Err)); |
1070 | return IsError; |
1071 | } |
1072 | |
1073 | /// Helper for Errors used as out-parameters. |
1074 | /// |
1075 | /// This helper is for use with the Error-as-out-parameter idiom, where an error |
1076 | /// is passed to a function or method by reference, rather than being returned. |
1077 | /// In such cases it is helpful to set the checked bit on entry to the function |
1078 | /// so that the error can be written to (unchecked Errors abort on assignment) |
1079 | /// and clear the checked bit on exit so that clients cannot accidentally forget |
1080 | /// to check the result. This helper performs these actions automatically using |
1081 | /// RAII: |
1082 | /// |
1083 | /// @code{.cpp} |
1084 | /// Result foo(Error &Err) { |
1085 | /// ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set |
1086 | /// // <body of foo> |
1087 | /// // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed. |
1088 | /// } |
1089 | /// @endcode |
1090 | /// |
1091 | /// ErrorAsOutParameter takes an Error* rather than Error& so that it can be |
1092 | /// used with optional Errors (Error pointers that are allowed to be null). If |
1093 | /// ErrorAsOutParameter took an Error reference, an instance would have to be |
1094 | /// created inside every condition that verified that Error was non-null. By |
1095 | /// taking an Error pointer we can just create one instance at the top of the |
1096 | /// function. |
1097 | class ErrorAsOutParameter { |
1098 | public: |
1099 | ErrorAsOutParameter(Error *Err) : Err(Err) { |
1100 | // Raise the checked bit if Err is success. |
1101 | if (Err) |
1102 | (void)!!*Err; |
1103 | } |
1104 | |
1105 | ~ErrorAsOutParameter() { |
1106 | // Clear the checked bit. |
1107 | if (Err && !*Err) |
1108 | *Err = Error::success(); |
1109 | } |
1110 | |
1111 | private: |
1112 | Error *Err; |
1113 | }; |
1114 | |
1115 | /// Helper for Expected<T>s used as out-parameters. |
1116 | /// |
1117 | /// See ErrorAsOutParameter. |
1118 | template <typename T> |
1119 | class ExpectedAsOutParameter { |
1120 | public: |
1121 | ExpectedAsOutParameter(Expected<T> *ValOrErr) |
1122 | : ValOrErr(ValOrErr) { |
1123 | if (ValOrErr) |
1124 | (void)!!*ValOrErr; |
1125 | } |
1126 | |
1127 | ~ExpectedAsOutParameter() { |
1128 | if (ValOrErr) |
1129 | ValOrErr->setUnchecked(); |
1130 | } |
1131 | |
1132 | private: |
1133 | Expected<T> *ValOrErr; |
1134 | }; |
1135 | |
1136 | /// This class wraps a std::error_code in a Error. |
1137 | /// |
1138 | /// This is useful if you're writing an interface that returns a Error |
1139 | /// (or Expected) and you want to call code that still returns |
1140 | /// std::error_codes. |
1141 | class ECError : public ErrorInfo<ECError> { |
1142 | friend Error errorCodeToError(std::error_code); |
1143 | |
1144 | virtual void anchor() override; |
1145 | |
1146 | public: |
1147 | void setErrorCode(std::error_code EC) { this->EC = EC; } |
1148 | std::error_code convertToErrorCode() const override { return EC; } |
1149 | void log(raw_ostream &OS) const override { OS << EC.message(); } |
1150 | |
1151 | // Used by ErrorInfo::classID. |
1152 | static char ID; |
1153 | |
1154 | protected: |
1155 | ECError() = default; |
1156 | ECError(std::error_code EC) : EC(EC) {} |
1157 | |
1158 | std::error_code EC; |
1159 | }; |
1160 | |
1161 | /// The value returned by this function can be returned from convertToErrorCode |
1162 | /// for Error values where no sensible translation to std::error_code exists. |
1163 | /// It should only be used in this situation, and should never be used where a |
1164 | /// sensible conversion to std::error_code is available, as attempts to convert |
1165 | /// to/from this error will result in a fatal error. (i.e. it is a programmatic |
1166 | /// error to try to convert such a value). |
1167 | std::error_code inconvertibleErrorCode(); |
1168 | |
1169 | /// Helper for converting an std::error_code to a Error. |
1170 | Error errorCodeToError(std::error_code EC); |
1171 | |
1172 | /// Helper for converting an ECError to a std::error_code. |
1173 | /// |
1174 | /// This method requires that Err be Error() or an ECError, otherwise it |
1175 | /// will trigger a call to abort(). |
1176 | std::error_code errorToErrorCode(Error Err); |
1177 | |
1178 | /// Convert an ErrorOr<T> to an Expected<T>. |
1179 | template <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) { |
1180 | if (auto EC = EO.getError()) |
1181 | return errorCodeToError(EC); |
1182 | return std::move(*EO); |
1183 | } |
1184 | |
1185 | /// Convert an Expected<T> to an ErrorOr<T>. |
1186 | template <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) { |
1187 | if (auto Err = E.takeError()) |
1188 | return errorToErrorCode(std::move(Err)); |
1189 | return std::move(*E); |
1190 | } |
1191 | |
1192 | /// This class wraps a string in an Error. |
1193 | /// |
1194 | /// StringError is useful in cases where the client is not expected to be able |
1195 | /// to consume the specific error message programmatically (for example, if the |
1196 | /// error message is to be presented to the user). |
1197 | /// |
1198 | /// StringError can also be used when additional information is to be printed |
1199 | /// along with a error_code message. Depending on the constructor called, this |
1200 | /// class can either display: |
1201 | /// 1. the error_code message (ECError behavior) |
1202 | /// 2. a string |
1203 | /// 3. the error_code message and a string |
1204 | /// |
1205 | /// These behaviors are useful when subtyping is required; for example, when a |
1206 | /// specific library needs an explicit error type. In the example below, |
1207 | /// PDBError is derived from StringError: |
1208 | /// |
1209 | /// @code{.cpp} |
1210 | /// Expected<int> foo() { |
1211 | /// return llvm::make_error<PDBError>(pdb_error_code::dia_failed_loading, |
1212 | /// "Additional information"); |
1213 | /// } |
1214 | /// @endcode |
1215 | /// |
1216 | class StringError : public ErrorInfo<StringError> { |
1217 | public: |
1218 | static char ID; |
1219 | |
1220 | // Prints EC + S and converts to EC |
1221 | StringError(std::error_code EC, const Twine &S = Twine()); |
1222 | |
1223 | // Prints S and converts to EC |
1224 | StringError(const Twine &S, std::error_code EC); |
1225 | |
1226 | void log(raw_ostream &OS) const override; |
1227 | std::error_code convertToErrorCode() const override; |
1228 | |
1229 | const std::string &getMessage() const { return Msg; } |
1230 | |
1231 | private: |
1232 | std::string Msg; |
1233 | std::error_code EC; |
1234 | const bool PrintMsgOnly = false; |
1235 | }; |
1236 | |
1237 | /// Create formatted StringError object. |
1238 | template <typename... Ts> |
1239 | inline Error createStringError(std::error_code EC, char const *Fmt, |
1240 | const Ts &... Vals) { |
1241 | std::string Buffer; |
1242 | raw_string_ostream Stream(Buffer); |
1243 | Stream << format(Fmt, Vals...); |
1244 | return make_error<StringError>(Stream.str(), EC); |
1245 | } |
1246 | |
1247 | Error createStringError(std::error_code EC, char const *Msg); |
1248 | |
1249 | inline Error createStringError(std::error_code EC, const Twine &S) { |
1250 | return createStringError(EC, S.str().c_str()); |
1251 | } |
1252 | |
1253 | template <typename... Ts> |
1254 | inline Error createStringError(std::errc EC, char const *Fmt, |
1255 | const Ts &... Vals) { |
1256 | return createStringError(std::make_error_code(EC), Fmt, Vals...); |
1257 | } |
1258 | |
1259 | /// This class wraps a filename and another Error. |
1260 | /// |
1261 | /// In some cases, an error needs to live along a 'source' name, in order to |
1262 | /// show more detailed information to the user. |
1263 | class FileError final : public ErrorInfo<FileError> { |
1264 | |
1265 | friend Error createFileError(const Twine &, Error); |
1266 | friend Error createFileError(const Twine &, size_t, Error); |
1267 | |
1268 | public: |
1269 | void log(raw_ostream &OS) const override { |
1270 | assert(Err && "Trying to log after takeError().")(static_cast <bool> (Err && "Trying to log after takeError()." ) ? void (0) : __assert_fail ("Err && \"Trying to log after takeError().\"" , "llvm/include/llvm/Support/Error.h", 1270, __extension__ __PRETTY_FUNCTION__ )); |
1271 | OS << "'" << FileName << "': "; |
1272 | if (Line.hasValue()) |
1273 | OS << "line " << Line.getValue() << ": "; |
1274 | Err->log(OS); |
1275 | } |
1276 | |
1277 | std::string messageWithoutFileInfo() const { |
1278 | std::string Msg; |
1279 | raw_string_ostream OS(Msg); |
1280 | Err->log(OS); |
1281 | return OS.str(); |
1282 | } |
1283 | |
1284 | StringRef getFileName() const { return FileName; } |
1285 | |
1286 | Error takeError() { return Error(std::move(Err)); } |
1287 | |
1288 | std::error_code convertToErrorCode() const override; |
1289 | |
1290 | // Used by ErrorInfo::classID. |
1291 | static char ID; |
1292 | |
1293 | private: |
1294 | FileError(const Twine &F, Optional<size_t> LineNum, |
1295 | std::unique_ptr<ErrorInfoBase> E) { |
1296 | assert(E && "Cannot create FileError from Error success value.")(static_cast <bool> (E && "Cannot create FileError from Error success value." ) ? void (0) : __assert_fail ("E && \"Cannot create FileError from Error success value.\"" , "llvm/include/llvm/Support/Error.h", 1296, __extension__ __PRETTY_FUNCTION__ )); |
1297 | FileName = F.str(); |
1298 | Err = std::move(E); |
1299 | Line = std::move(LineNum); |
1300 | } |
1301 | |
1302 | static Error build(const Twine &F, Optional<size_t> Line, Error E) { |
1303 | std::unique_ptr<ErrorInfoBase> Payload; |
1304 | handleAllErrors(std::move(E), |
1305 | [&](std::unique_ptr<ErrorInfoBase> EIB) -> Error { |
1306 | Payload = std::move(EIB); |
1307 | return Error::success(); |
1308 | }); |
1309 | return Error( |
1310 | std::unique_ptr<FileError>(new FileError(F, Line, std::move(Payload)))); |
1311 | } |
1312 | |
1313 | std::string FileName; |
1314 | Optional<size_t> Line; |
1315 | std::unique_ptr<ErrorInfoBase> Err; |
1316 | }; |
1317 | |
1318 | /// Concatenate a source file path and/or name with an Error. The resulting |
1319 | /// Error is unchecked. |
1320 | inline Error createFileError(const Twine &F, Error E) { |
1321 | return FileError::build(F, Optional<size_t>(), std::move(E)); |
1322 | } |
1323 | |
1324 | /// Concatenate a source file path and/or name with line number and an Error. |
1325 | /// The resulting Error is unchecked. |
1326 | inline Error createFileError(const Twine &F, size_t Line, Error E) { |
1327 | return FileError::build(F, Optional<size_t>(Line), std::move(E)); |
1328 | } |
1329 | |
1330 | /// Concatenate a source file path and/or name with a std::error_code |
1331 | /// to form an Error object. |
1332 | inline Error createFileError(const Twine &F, std::error_code EC) { |
1333 | return createFileError(F, errorCodeToError(EC)); |
1334 | } |
1335 | |
1336 | /// Concatenate a source file path and/or name with line number and |
1337 | /// std::error_code to form an Error object. |
1338 | inline Error createFileError(const Twine &F, size_t Line, std::error_code EC) { |
1339 | return createFileError(F, Line, errorCodeToError(EC)); |
1340 | } |
1341 | |
1342 | Error createFileError(const Twine &F, ErrorSuccess) = delete; |
1343 | |
1344 | /// Helper for check-and-exit error handling. |
1345 | /// |
1346 | /// For tool use only. NOT FOR USE IN LIBRARY CODE. |
1347 | /// |
1348 | class ExitOnError { |
1349 | public: |
1350 | /// Create an error on exit helper. |
1351 | ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1) |
1352 | : Banner(std::move(Banner)), |
1353 | GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {} |
1354 | |
1355 | /// Set the banner string for any errors caught by operator(). |
1356 | void setBanner(std::string Banner) { this->Banner = std::move(Banner); } |
1357 | |
1358 | /// Set the exit-code mapper function. |
1359 | void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) { |
1360 | this->GetExitCode = std::move(GetExitCode); |
1361 | } |
1362 | |
1363 | /// Check Err. If it's in a failure state log the error(s) and exit. |
1364 | void operator()(Error Err) const { checkError(std::move(Err)); } |
1365 | |
1366 | /// Check E. If it's in a success state then return the contained value. If |
1367 | /// it's in a failure state log the error(s) and exit. |
1368 | template <typename T> T operator()(Expected<T> &&E) const { |
1369 | checkError(E.takeError()); |
1370 | return std::move(*E); |
1371 | } |
1372 | |
1373 | /// Check E. If it's in a success state then return the contained reference. If |
1374 | /// it's in a failure state log the error(s) and exit. |
1375 | template <typename T> T& operator()(Expected<T&> &&E) const { |
1376 | checkError(E.takeError()); |
1377 | return *E; |
1378 | } |
1379 | |
1380 | private: |
1381 | void checkError(Error Err) const { |
1382 | if (Err) { |
1383 | int ExitCode = GetExitCode(Err); |
1384 | logAllUnhandledErrors(std::move(Err), errs(), Banner); |
1385 | exit(ExitCode); |
1386 | } |
1387 | } |
1388 | |
1389 | std::string Banner; |
1390 | std::function<int(const Error &)> GetExitCode; |
1391 | }; |
1392 | |
1393 | /// Conversion from Error to LLVMErrorRef for C error bindings. |
1394 | inline LLVMErrorRef wrap(Error Err) { |
1395 | return reinterpret_cast<LLVMErrorRef>(Err.takePayload().release()); |
1396 | } |
1397 | |
1398 | /// Conversion from LLVMErrorRef to Error for C error bindings. |
1399 | inline Error unwrap(LLVMErrorRef ErrRef) { |
1400 | return Error(std::unique_ptr<ErrorInfoBase>( |
1401 | reinterpret_cast<ErrorInfoBase *>(ErrRef))); |
1402 | } |
1403 | |
1404 | } // end namespace llvm |
1405 | |
1406 | #endif // LLVM_SUPPORT_ERROR_H |