File: | include/llvm/Support/Error.h |
Warning: | line 201, column 5 Potential leak of memory pointed to by 'Payload._M_t._M_head_impl' |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===- Driver.cpp ---------------------------------------------------------===// | |||
2 | // | |||
3 | // The LLVM Linker | |||
4 | // | |||
5 | // This file is distributed under the University of Illinois Open Source | |||
6 | // License. See LICENSE.TXT for details. | |||
7 | // | |||
8 | //===----------------------------------------------------------------------===// | |||
9 | ||||
10 | #include "Driver.h" | |||
11 | #include "Config.h" | |||
12 | #include "ICF.h" | |||
13 | #include "InputFiles.h" | |||
14 | #include "MarkLive.h" | |||
15 | #include "MinGW.h" | |||
16 | #include "SymbolTable.h" | |||
17 | #include "Symbols.h" | |||
18 | #include "Writer.h" | |||
19 | #include "lld/Common/Args.h" | |||
20 | #include "lld/Common/Driver.h" | |||
21 | #include "lld/Common/ErrorHandler.h" | |||
22 | #include "lld/Common/Memory.h" | |||
23 | #include "lld/Common/Timer.h" | |||
24 | #include "lld/Common/Version.h" | |||
25 | #include "llvm/ADT/Optional.h" | |||
26 | #include "llvm/ADT/StringSwitch.h" | |||
27 | #include "llvm/BinaryFormat/Magic.h" | |||
28 | #include "llvm/Object/ArchiveWriter.h" | |||
29 | #include "llvm/Object/COFFImportFile.h" | |||
30 | #include "llvm/Object/COFFModuleDefinition.h" | |||
31 | #include "llvm/Option/Arg.h" | |||
32 | #include "llvm/Option/ArgList.h" | |||
33 | #include "llvm/Option/Option.h" | |||
34 | #include "llvm/Support/Debug.h" | |||
35 | #include "llvm/Support/LEB128.h" | |||
36 | #include "llvm/Support/Path.h" | |||
37 | #include "llvm/Support/Process.h" | |||
38 | #include "llvm/Support/TarWriter.h" | |||
39 | #include "llvm/Support/TargetSelect.h" | |||
40 | #include "llvm/Support/raw_ostream.h" | |||
41 | #include "llvm/ToolDrivers/llvm-lib/LibDriver.h" | |||
42 | #include <algorithm> | |||
43 | #include <future> | |||
44 | #include <memory> | |||
45 | ||||
46 | using namespace llvm; | |||
47 | using namespace llvm::object; | |||
48 | using namespace llvm::COFF; | |||
49 | using llvm::sys::Process; | |||
50 | ||||
51 | namespace lld { | |||
52 | namespace coff { | |||
53 | ||||
54 | static Timer InputFileTimer("Input File Reading", Timer::root()); | |||
55 | ||||
56 | Configuration *Config; | |||
57 | LinkerDriver *Driver; | |||
58 | ||||
59 | bool link(ArrayRef<const char *> Args, bool CanExitEarly, raw_ostream &Diag) { | |||
60 | errorHandler().LogName = args::getFilenameWithoutExe(Args[0]); | |||
61 | errorHandler().ErrorOS = &Diag; | |||
62 | errorHandler().ColorDiagnostics = Diag.has_colors(); | |||
63 | errorHandler().ErrorLimitExceededMsg = | |||
64 | "too many errors emitted, stopping now" | |||
65 | " (use /errorlimit:0 to see all errors)"; | |||
66 | errorHandler().ExitEarly = CanExitEarly; | |||
67 | Config = make<Configuration>(); | |||
68 | ||||
69 | Symtab = make<SymbolTable>(); | |||
70 | ||||
71 | Driver = make<LinkerDriver>(); | |||
72 | Driver->link(Args); | |||
73 | ||||
74 | // Call exit() if we can to avoid calling destructors. | |||
75 | if (CanExitEarly) | |||
76 | exitLld(errorCount() ? 1 : 0); | |||
77 | ||||
78 | freeArena(); | |||
79 | ObjFile::Instances.clear(); | |||
80 | ImportFile::Instances.clear(); | |||
81 | BitcodeFile::Instances.clear(); | |||
82 | return !errorCount(); | |||
83 | } | |||
84 | ||||
85 | // Drop directory components and replace extension with ".exe" or ".dll". | |||
86 | static std::string getOutputPath(StringRef Path) { | |||
87 | auto P = Path.find_last_of("\\/"); | |||
88 | StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1); | |||
89 | const char* E = Config->DLL ? ".dll" : ".exe"; | |||
90 | return (S.substr(0, S.rfind('.')) + E).str(); | |||
91 | } | |||
92 | ||||
93 | // ErrorOr is not default constructible, so it cannot be used as the type | |||
94 | // parameter of a future. | |||
95 | // FIXME: We could open the file in createFutureForFile and avoid needing to | |||
96 | // return an error here, but for the moment that would cost us a file descriptor | |||
97 | // (a limited resource on Windows) for the duration that the future is pending. | |||
98 | typedef std::pair<std::unique_ptr<MemoryBuffer>, std::error_code> MBErrPair; | |||
99 | ||||
100 | // Create a std::future that opens and maps a file using the best strategy for | |||
101 | // the host platform. | |||
102 | static std::future<MBErrPair> createFutureForFile(std::string Path) { | |||
103 | #if _WIN32 | |||
104 | // On Windows, file I/O is relatively slow so it is best to do this | |||
105 | // asynchronously. | |||
106 | auto Strategy = std::launch::async; | |||
107 | #else | |||
108 | auto Strategy = std::launch::deferred; | |||
109 | #endif | |||
110 | return std::async(Strategy, [=]() { | |||
111 | auto MBOrErr = MemoryBuffer::getFile(Path, | |||
112 | /*FileSize*/ -1, | |||
113 | /*RequiresNullTerminator*/ false); | |||
114 | if (!MBOrErr) | |||
115 | return MBErrPair{nullptr, MBOrErr.getError()}; | |||
116 | return MBErrPair{std::move(*MBOrErr), std::error_code()}; | |||
117 | }); | |||
118 | } | |||
119 | ||||
120 | // Symbol names are mangled by prepending "_" on x86. | |||
121 | static StringRef mangle(StringRef Sym) { | |||
122 | assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN)((Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN) ? static_cast <void> (0) : __assert_fail ("Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN" , "/build/llvm-toolchain-snapshot-8~svn345461/tools/lld/COFF/Driver.cpp" , 122, __PRETTY_FUNCTION__)); | |||
123 | if (Config->Machine == I386) | |||
124 | return Saver.save("_" + Sym); | |||
125 | return Sym; | |||
126 | } | |||
127 | ||||
128 | static bool findUnderscoreMangle(StringRef Sym) { | |||
129 | StringRef Entry = Symtab->findMangle(mangle(Sym)); | |||
130 | return !Entry.empty() && !isa<Undefined>(Symtab->find(Entry)); | |||
131 | } | |||
132 | ||||
133 | MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) { | |||
134 | MemoryBufferRef MBRef = *MB; | |||
135 | make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take ownership | |||
136 | ||||
137 | if (Driver->Tar) | |||
138 | Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()), | |||
139 | MBRef.getBuffer()); | |||
140 | return MBRef; | |||
141 | } | |||
142 | ||||
143 | void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB, | |||
144 | bool WholeArchive) { | |||
145 | StringRef Filename = MB->getBufferIdentifier(); | |||
146 | ||||
147 | MemoryBufferRef MBRef = takeBuffer(std::move(MB)); | |||
148 | FilePaths.push_back(Filename); | |||
149 | ||||
150 | // File type is detected by contents, not by file extension. | |||
151 | switch (identify_magic(MBRef.getBuffer())) { | |||
152 | case file_magic::windows_resource: | |||
153 | Resources.push_back(MBRef); | |||
154 | break; | |||
155 | case file_magic::archive: | |||
156 | if (WholeArchive) { | |||
157 | std::unique_ptr<Archive> File = | |||
158 | CHECK(Archive::create(MBRef), Filename + ": failed to parse archive")check2((Archive::create(MBRef)), [&] { return toString(Filename + ": failed to parse archive"); }); | |||
159 | ||||
160 | for (MemoryBufferRef M : getArchiveMembers(File.get())) | |||
161 | addArchiveBuffer(M, "<whole-archive>", Filename); | |||
162 | return; | |||
163 | } | |||
164 | Symtab->addFile(make<ArchiveFile>(MBRef)); | |||
165 | break; | |||
166 | case file_magic::bitcode: | |||
167 | Symtab->addFile(make<BitcodeFile>(MBRef)); | |||
168 | break; | |||
169 | case file_magic::coff_object: | |||
170 | case file_magic::coff_import_library: | |||
171 | Symtab->addFile(make<ObjFile>(MBRef)); | |||
172 | break; | |||
173 | case file_magic::coff_cl_gl_object: | |||
174 | error(Filename + ": is not a native COFF file. Recompile without /GL"); | |||
175 | break; | |||
176 | case file_magic::pecoff_executable: | |||
177 | if (Filename.endswith_lower(".dll")) { | |||
178 | error(Filename + ": bad file type. Did you specify a DLL instead of an " | |||
179 | "import library?"); | |||
180 | break; | |||
181 | } | |||
182 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
183 | default: | |||
184 | error(MBRef.getBufferIdentifier() + ": unknown file type"); | |||
185 | break; | |||
186 | } | |||
187 | } | |||
188 | ||||
189 | void LinkerDriver::enqueuePath(StringRef Path, bool WholeArchive) { | |||
190 | auto Future = | |||
191 | std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path)); | |||
192 | std::string PathStr = Path; | |||
193 | enqueueTask([=]() { | |||
194 | auto MBOrErr = Future->get(); | |||
195 | if (MBOrErr.second) | |||
| ||||
196 | error("could not open " + PathStr + ": " + MBOrErr.second.message()); | |||
197 | else | |||
198 | Driver->addBuffer(std::move(MBOrErr.first), WholeArchive); | |||
199 | }); | |||
200 | } | |||
201 | ||||
202 | void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName, | |||
203 | StringRef ParentName) { | |||
204 | file_magic Magic = identify_magic(MB.getBuffer()); | |||
205 | if (Magic == file_magic::coff_import_library) { | |||
206 | Symtab->addFile(make<ImportFile>(MB)); | |||
207 | return; | |||
208 | } | |||
209 | ||||
210 | InputFile *Obj; | |||
211 | if (Magic == file_magic::coff_object) { | |||
212 | Obj = make<ObjFile>(MB); | |||
213 | } else if (Magic == file_magic::bitcode) { | |||
214 | Obj = make<BitcodeFile>(MB); | |||
215 | } else { | |||
216 | error("unknown file type: " + MB.getBufferIdentifier()); | |||
217 | return; | |||
218 | } | |||
219 | ||||
220 | Obj->ParentName = ParentName; | |||
221 | Symtab->addFile(Obj); | |||
222 | log("Loaded " + toString(Obj) + " for " + SymName); | |||
223 | } | |||
224 | ||||
225 | void LinkerDriver::enqueueArchiveMember(const Archive::Child &C, | |||
226 | StringRef SymName, | |||
227 | StringRef ParentName) { | |||
228 | if (!C.getParent()->isThin()) { | |||
229 | MemoryBufferRef MB = CHECK(check2((C.getMemoryBufferRef()), [&] { return toString("could not get the buffer for the member defining symbol " + SymName); }) | |||
230 | C.getMemoryBufferRef(),check2((C.getMemoryBufferRef()), [&] { return toString("could not get the buffer for the member defining symbol " + SymName); }) | |||
231 | "could not get the buffer for the member defining symbol " + SymName)check2((C.getMemoryBufferRef()), [&] { return toString("could not get the buffer for the member defining symbol " + SymName); }); | |||
232 | enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); }); | |||
233 | return; | |||
234 | } | |||
235 | ||||
236 | auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile( | |||
237 | CHECK(C.getFullName(),check2((C.getFullName()), [&] { return toString("could not get the filename for the member defining symbol " + SymName); }) | |||
238 | "could not get the filename for the member defining symbol " +check2((C.getFullName()), [&] { return toString("could not get the filename for the member defining symbol " + SymName); }) | |||
239 | SymName)check2((C.getFullName()), [&] { return toString("could not get the filename for the member defining symbol " + SymName); }))); | |||
240 | enqueueTask([=]() { | |||
241 | auto MBOrErr = Future->get(); | |||
242 | if (MBOrErr.second) | |||
243 | fatal("could not get the buffer for the member defining " + SymName + | |||
244 | ": " + MBOrErr.second.message()); | |||
245 | Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName, | |||
246 | ParentName); | |||
247 | }); | |||
248 | } | |||
249 | ||||
250 | static bool isDecorated(StringRef Sym) { | |||
251 | return Sym.startswith("@") || Sym.contains("@@") || Sym.startswith("?") || | |||
252 | (!Config->MinGW && Sym.contains('@')); | |||
253 | } | |||
254 | ||||
255 | // Parses .drectve section contents and returns a list of files | |||
256 | // specified by /defaultlib. | |||
257 | void LinkerDriver::parseDirectives(StringRef S) { | |||
258 | ArgParser Parser; | |||
259 | // .drectve is always tokenized using Windows shell rules. | |||
260 | // /EXPORT: option can appear too many times, processing in fastpath. | |||
261 | opt::InputArgList Args; | |||
262 | std::vector<StringRef> Exports; | |||
263 | std::tie(Args, Exports) = Parser.parseDirectives(S); | |||
264 | ||||
265 | for (StringRef E : Exports) { | |||
266 | // If a common header file contains dllexported function | |||
267 | // declarations, many object files may end up with having the | |||
268 | // same /EXPORT options. In order to save cost of parsing them, | |||
269 | // we dedup them first. | |||
270 | if (!DirectivesExports.insert(E).second) | |||
271 | continue; | |||
272 | ||||
273 | Export Exp = parseExport(E); | |||
274 | if (Config->Machine == I386 && Config->MinGW) { | |||
275 | if (!isDecorated(Exp.Name)) | |||
276 | Exp.Name = Saver.save("_" + Exp.Name); | |||
277 | if (!Exp.ExtName.empty() && !isDecorated(Exp.ExtName)) | |||
278 | Exp.ExtName = Saver.save("_" + Exp.ExtName); | |||
279 | } | |||
280 | Exp.Directives = true; | |||
281 | Config->Exports.push_back(Exp); | |||
282 | } | |||
283 | ||||
284 | for (auto *Arg : Args) { | |||
285 | switch (Arg->getOption().getUnaliasedOption().getID()) { | |||
286 | case OPT_aligncomm: | |||
287 | parseAligncomm(Arg->getValue()); | |||
288 | break; | |||
289 | case OPT_alternatename: | |||
290 | parseAlternateName(Arg->getValue()); | |||
291 | break; | |||
292 | case OPT_defaultlib: | |||
293 | if (Optional<StringRef> Path = findLib(Arg->getValue())) | |||
294 | enqueuePath(*Path, false); | |||
295 | break; | |||
296 | case OPT_entry: | |||
297 | Config->Entry = addUndefined(mangle(Arg->getValue())); | |||
298 | break; | |||
299 | case OPT_failifmismatch: | |||
300 | checkFailIfMismatch(Arg->getValue()); | |||
301 | break; | |||
302 | case OPT_incl: | |||
303 | addUndefined(Arg->getValue()); | |||
304 | break; | |||
305 | case OPT_merge: | |||
306 | parseMerge(Arg->getValue()); | |||
307 | break; | |||
308 | case OPT_nodefaultlib: | |||
309 | Config->NoDefaultLibs.insert(doFindLib(Arg->getValue())); | |||
310 | break; | |||
311 | case OPT_section: | |||
312 | parseSection(Arg->getValue()); | |||
313 | break; | |||
314 | case OPT_subsystem: | |||
315 | parseSubsystem(Arg->getValue(), &Config->Subsystem, | |||
316 | &Config->MajorOSVersion, &Config->MinorOSVersion); | |||
317 | break; | |||
318 | case OPT_editandcontinue: | |||
319 | case OPT_fastfail: | |||
320 | case OPT_guardsym: | |||
321 | case OPT_natvis: | |||
322 | case OPT_throwingnew: | |||
323 | break; | |||
324 | default: | |||
325 | error(Arg->getSpelling() + " is not allowed in .drectve"); | |||
326 | } | |||
327 | } | |||
328 | } | |||
329 | ||||
330 | // Find file from search paths. You can omit ".obj", this function takes | |||
331 | // care of that. Note that the returned path is not guaranteed to exist. | |||
332 | StringRef LinkerDriver::doFindFile(StringRef Filename) { | |||
333 | bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos); | |||
334 | if (HasPathSep) | |||
335 | return Filename; | |||
336 | bool HasExt = Filename.contains('.'); | |||
337 | for (StringRef Dir : SearchPaths) { | |||
338 | SmallString<128> Path = Dir; | |||
339 | sys::path::append(Path, Filename); | |||
340 | if (sys::fs::exists(Path.str())) | |||
341 | return Saver.save(Path.str()); | |||
342 | if (!HasExt) { | |||
343 | Path.append(".obj"); | |||
344 | if (sys::fs::exists(Path.str())) | |||
345 | return Saver.save(Path.str()); | |||
346 | } | |||
347 | } | |||
348 | return Filename; | |||
349 | } | |||
350 | ||||
351 | static Optional<sys::fs::UniqueID> getUniqueID(StringRef Path) { | |||
352 | sys::fs::UniqueID Ret; | |||
353 | if (sys::fs::getUniqueID(Path, Ret)) | |||
354 | return None; | |||
355 | return Ret; | |||
356 | } | |||
357 | ||||
358 | // Resolves a file path. This never returns the same path | |||
359 | // (in that case, it returns None). | |||
360 | Optional<StringRef> LinkerDriver::findFile(StringRef Filename) { | |||
361 | StringRef Path = doFindFile(Filename); | |||
362 | ||||
363 | if (Optional<sys::fs::UniqueID> ID = getUniqueID(Path)) { | |||
364 | bool Seen = !VisitedFiles.insert(*ID).second; | |||
365 | if (Seen) | |||
366 | return None; | |||
367 | } | |||
368 | ||||
369 | if (Path.endswith_lower(".lib")) | |||
370 | VisitedLibs.insert(sys::path::filename(Path)); | |||
371 | return Path; | |||
372 | } | |||
373 | ||||
374 | // MinGW specific. If an embedded directive specified to link to | |||
375 | // foo.lib, but it isn't found, try libfoo.a instead. | |||
376 | StringRef LinkerDriver::doFindLibMinGW(StringRef Filename) { | |||
377 | if (Filename.contains('/') || Filename.contains('\\')) | |||
378 | return Filename; | |||
379 | ||||
380 | SmallString<128> S = Filename; | |||
381 | sys::path::replace_extension(S, ".a"); | |||
382 | StringRef LibName = Saver.save("lib" + S.str()); | |||
383 | return doFindFile(LibName); | |||
384 | } | |||
385 | ||||
386 | // Find library file from search path. | |||
387 | StringRef LinkerDriver::doFindLib(StringRef Filename) { | |||
388 | // Add ".lib" to Filename if that has no file extension. | |||
389 | bool HasExt = Filename.contains('.'); | |||
390 | if (!HasExt) | |||
391 | Filename = Saver.save(Filename + ".lib"); | |||
392 | StringRef Ret = doFindFile(Filename); | |||
393 | // For MinGW, if the find above didn't turn up anything, try | |||
394 | // looking for a MinGW formatted library name. | |||
395 | if (Config->MinGW && Ret == Filename) | |||
396 | return doFindLibMinGW(Filename); | |||
397 | return Ret; | |||
398 | } | |||
399 | ||||
400 | // Resolves a library path. /nodefaultlib options are taken into | |||
401 | // consideration. This never returns the same path (in that case, | |||
402 | // it returns None). | |||
403 | Optional<StringRef> LinkerDriver::findLib(StringRef Filename) { | |||
404 | if (Config->NoDefaultLibAll) | |||
405 | return None; | |||
406 | if (!VisitedLibs.insert(Filename.lower()).second) | |||
407 | return None; | |||
408 | ||||
409 | StringRef Path = doFindLib(Filename); | |||
410 | if (Config->NoDefaultLibs.count(Path)) | |||
411 | return None; | |||
412 | ||||
413 | if (Optional<sys::fs::UniqueID> ID = getUniqueID(Path)) | |||
414 | if (!VisitedFiles.insert(*ID).second) | |||
415 | return None; | |||
416 | return Path; | |||
417 | } | |||
418 | ||||
419 | // Parses LIB environment which contains a list of search paths. | |||
420 | void LinkerDriver::addLibSearchPaths() { | |||
421 | Optional<std::string> EnvOpt = Process::GetEnv("LIB"); | |||
422 | if (!EnvOpt.hasValue()) | |||
423 | return; | |||
424 | StringRef Env = Saver.save(*EnvOpt); | |||
425 | while (!Env.empty()) { | |||
426 | StringRef Path; | |||
427 | std::tie(Path, Env) = Env.split(';'); | |||
428 | SearchPaths.push_back(Path); | |||
429 | } | |||
430 | } | |||
431 | ||||
432 | Symbol *LinkerDriver::addUndefined(StringRef Name) { | |||
433 | Symbol *B = Symtab->addUndefined(Name); | |||
434 | if (!B->IsGCRoot) { | |||
435 | B->IsGCRoot = true; | |||
436 | Config->GCRoot.push_back(B); | |||
437 | } | |||
438 | return B; | |||
439 | } | |||
440 | ||||
441 | // Windows specific -- find default entry point name. | |||
442 | // | |||
443 | // There are four different entry point functions for Windows executables, | |||
444 | // each of which corresponds to a user-defined "main" function. This function | |||
445 | // infers an entry point from a user-defined "main" function. | |||
446 | StringRef LinkerDriver::findDefaultEntry() { | |||
447 | assert(Config->Subsystem != IMAGE_SUBSYSTEM_UNKNOWN &&((Config->Subsystem != IMAGE_SUBSYSTEM_UNKNOWN && "must handle /subsystem before calling this" ) ? static_cast<void> (0) : __assert_fail ("Config->Subsystem != IMAGE_SUBSYSTEM_UNKNOWN && \"must handle /subsystem before calling this\"" , "/build/llvm-toolchain-snapshot-8~svn345461/tools/lld/COFF/Driver.cpp" , 448, __PRETTY_FUNCTION__)) | |||
448 | "must handle /subsystem before calling this")((Config->Subsystem != IMAGE_SUBSYSTEM_UNKNOWN && "must handle /subsystem before calling this" ) ? static_cast<void> (0) : __assert_fail ("Config->Subsystem != IMAGE_SUBSYSTEM_UNKNOWN && \"must handle /subsystem before calling this\"" , "/build/llvm-toolchain-snapshot-8~svn345461/tools/lld/COFF/Driver.cpp" , 448, __PRETTY_FUNCTION__)); | |||
449 | ||||
450 | if (Config->MinGW) | |||
451 | return mangle(Config->Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI | |||
452 | ? "WinMainCRTStartup" | |||
453 | : "mainCRTStartup"); | |||
454 | ||||
455 | if (Config->Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI) { | |||
456 | if (findUnderscoreMangle("wWinMain")) { | |||
457 | if (!findUnderscoreMangle("WinMain")) | |||
458 | return mangle("wWinMainCRTStartup"); | |||
459 | warn("found both wWinMain and WinMain; using latter"); | |||
460 | } | |||
461 | return mangle("WinMainCRTStartup"); | |||
462 | } | |||
463 | if (findUnderscoreMangle("wmain")) { | |||
464 | if (!findUnderscoreMangle("main")) | |||
465 | return mangle("wmainCRTStartup"); | |||
466 | warn("found both wmain and main; using latter"); | |||
467 | } | |||
468 | return mangle("mainCRTStartup"); | |||
469 | } | |||
470 | ||||
471 | WindowsSubsystem LinkerDriver::inferSubsystem() { | |||
472 | if (Config->DLL) | |||
473 | return IMAGE_SUBSYSTEM_WINDOWS_GUI; | |||
474 | if (Config->MinGW) | |||
475 | return IMAGE_SUBSYSTEM_WINDOWS_CUI; | |||
476 | // Note that link.exe infers the subsystem from the presence of these | |||
477 | // functions even if /entry: or /nodefaultlib are passed which causes them | |||
478 | // to not be called. | |||
479 | bool HaveMain = findUnderscoreMangle("main"); | |||
480 | bool HaveWMain = findUnderscoreMangle("wmain"); | |||
481 | bool HaveWinMain = findUnderscoreMangle("WinMain"); | |||
482 | bool HaveWWinMain = findUnderscoreMangle("wWinMain"); | |||
483 | if (HaveMain || HaveWMain) { | |||
484 | if (HaveWinMain || HaveWWinMain) { | |||
485 | warn(std::string("found ") + (HaveMain ? "main" : "wmain") + " and " + | |||
486 | (HaveWinMain ? "WinMain" : "wWinMain") + | |||
487 | "; defaulting to /subsystem:console"); | |||
488 | } | |||
489 | return IMAGE_SUBSYSTEM_WINDOWS_CUI; | |||
490 | } | |||
491 | if (HaveWinMain || HaveWWinMain) | |||
492 | return IMAGE_SUBSYSTEM_WINDOWS_GUI; | |||
493 | return IMAGE_SUBSYSTEM_UNKNOWN; | |||
494 | } | |||
495 | ||||
496 | static uint64_t getDefaultImageBase() { | |||
497 | if (Config->is64()) | |||
498 | return Config->DLL ? 0x180000000 : 0x140000000; | |||
499 | return Config->DLL ? 0x10000000 : 0x400000; | |||
500 | } | |||
501 | ||||
502 | static std::string createResponseFile(const opt::InputArgList &Args, | |||
503 | ArrayRef<StringRef> FilePaths, | |||
504 | ArrayRef<StringRef> SearchPaths) { | |||
505 | SmallString<0> Data; | |||
506 | raw_svector_ostream OS(Data); | |||
507 | ||||
508 | for (auto *Arg : Args) { | |||
509 | switch (Arg->getOption().getID()) { | |||
510 | case OPT_linkrepro: | |||
511 | case OPT_INPUT: | |||
512 | case OPT_defaultlib: | |||
513 | case OPT_libpath: | |||
514 | case OPT_manifest: | |||
515 | case OPT_manifest_colon: | |||
516 | case OPT_manifestdependency: | |||
517 | case OPT_manifestfile: | |||
518 | case OPT_manifestinput: | |||
519 | case OPT_manifestuac: | |||
520 | break; | |||
521 | default: | |||
522 | OS << toString(*Arg) << "\n"; | |||
523 | } | |||
524 | } | |||
525 | ||||
526 | for (StringRef Path : SearchPaths) { | |||
527 | std::string RelPath = relativeToRoot(Path); | |||
528 | OS << "/libpath:" << quote(RelPath) << "\n"; | |||
529 | } | |||
530 | ||||
531 | for (StringRef Path : FilePaths) | |||
532 | OS << quote(relativeToRoot(Path)) << "\n"; | |||
533 | ||||
534 | return Data.str(); | |||
535 | } | |||
536 | ||||
537 | enum class DebugKind { Unknown, None, Full, FastLink, GHash, Dwarf, Symtab }; | |||
538 | ||||
539 | static DebugKind parseDebugKind(const opt::InputArgList &Args) { | |||
540 | auto *A = Args.getLastArg(OPT_debug, OPT_debug_opt); | |||
541 | if (!A) | |||
542 | return DebugKind::None; | |||
543 | if (A->getNumValues() == 0) | |||
544 | return DebugKind::Full; | |||
545 | ||||
546 | DebugKind Debug = StringSwitch<DebugKind>(A->getValue()) | |||
547 | .CaseLower("none", DebugKind::None) | |||
548 | .CaseLower("full", DebugKind::Full) | |||
549 | .CaseLower("fastlink", DebugKind::FastLink) | |||
550 | // LLD extensions | |||
551 | .CaseLower("ghash", DebugKind::GHash) | |||
552 | .CaseLower("dwarf", DebugKind::Dwarf) | |||
553 | .CaseLower("symtab", DebugKind::Symtab) | |||
554 | .Default(DebugKind::Unknown); | |||
555 | ||||
556 | if (Debug == DebugKind::FastLink) { | |||
557 | warn("/debug:fastlink unsupported; using /debug:full"); | |||
558 | return DebugKind::Full; | |||
559 | } | |||
560 | if (Debug == DebugKind::Unknown) { | |||
561 | error("/debug: unknown option: " + Twine(A->getValue())); | |||
562 | return DebugKind::None; | |||
563 | } | |||
564 | return Debug; | |||
565 | } | |||
566 | ||||
567 | static unsigned parseDebugTypes(const opt::InputArgList &Args) { | |||
568 | unsigned DebugTypes = static_cast<unsigned>(DebugType::None); | |||
569 | ||||
570 | if (auto *A = Args.getLastArg(OPT_debugtype)) { | |||
571 | SmallVector<StringRef, 3> Types; | |||
572 | A->getSpelling().split(Types, ',', /*KeepEmpty=*/false); | |||
573 | ||||
574 | for (StringRef Type : Types) { | |||
575 | unsigned V = StringSwitch<unsigned>(Type.lower()) | |||
576 | .Case("cv", static_cast<unsigned>(DebugType::CV)) | |||
577 | .Case("pdata", static_cast<unsigned>(DebugType::PData)) | |||
578 | .Case("fixup", static_cast<unsigned>(DebugType::Fixup)) | |||
579 | .Default(0); | |||
580 | if (V == 0) { | |||
581 | warn("/debugtype: unknown option: " + Twine(A->getValue())); | |||
582 | continue; | |||
583 | } | |||
584 | DebugTypes |= V; | |||
585 | } | |||
586 | return DebugTypes; | |||
587 | } | |||
588 | ||||
589 | // Default debug types | |||
590 | DebugTypes = static_cast<unsigned>(DebugType::CV); | |||
591 | if (Args.hasArg(OPT_driver)) | |||
592 | DebugTypes |= static_cast<unsigned>(DebugType::PData); | |||
593 | if (Args.hasArg(OPT_profile)) | |||
594 | DebugTypes |= static_cast<unsigned>(DebugType::Fixup); | |||
595 | ||||
596 | return DebugTypes; | |||
597 | } | |||
598 | ||||
599 | static std::string getMapFile(const opt::InputArgList &Args) { | |||
600 | auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file); | |||
601 | if (!Arg) | |||
602 | return ""; | |||
603 | if (Arg->getOption().getID() == OPT_lldmap_file) | |||
604 | return Arg->getValue(); | |||
605 | ||||
606 | assert(Arg->getOption().getID() == OPT_lldmap)((Arg->getOption().getID() == OPT_lldmap) ? static_cast< void> (0) : __assert_fail ("Arg->getOption().getID() == OPT_lldmap" , "/build/llvm-toolchain-snapshot-8~svn345461/tools/lld/COFF/Driver.cpp" , 606, __PRETTY_FUNCTION__)); | |||
607 | StringRef OutFile = Config->OutputFile; | |||
608 | return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str(); | |||
609 | } | |||
610 | ||||
611 | static std::string getImplibPath() { | |||
612 | if (!Config->Implib.empty()) | |||
613 | return Config->Implib; | |||
614 | SmallString<128> Out = StringRef(Config->OutputFile); | |||
615 | sys::path::replace_extension(Out, ".lib"); | |||
616 | return Out.str(); | |||
617 | } | |||
618 | ||||
619 | // | |||
620 | // The import name is caculated as the following: | |||
621 | // | |||
622 | // | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY | |||
623 | // -----+----------------+---------------------+------------------ | |||
624 | // LINK | {value} | {value}.{.dll/.exe} | {output name} | |||
625 | // LIB | {value} | {value}.dll | {output name}.dll | |||
626 | // | |||
627 | static std::string getImportName(bool AsLib) { | |||
628 | SmallString<128> Out; | |||
629 | ||||
630 | if (Config->ImportName.empty()) { | |||
631 | Out.assign(sys::path::filename(Config->OutputFile)); | |||
632 | if (AsLib) | |||
633 | sys::path::replace_extension(Out, ".dll"); | |||
634 | } else { | |||
635 | Out.assign(Config->ImportName); | |||
636 | if (!sys::path::has_extension(Out)) | |||
637 | sys::path::replace_extension(Out, | |||
638 | (Config->DLL || AsLib) ? ".dll" : ".exe"); | |||
639 | } | |||
640 | ||||
641 | return Out.str(); | |||
642 | } | |||
643 | ||||
644 | static void createImportLibrary(bool AsLib) { | |||
645 | std::vector<COFFShortExport> Exports; | |||
646 | for (Export &E1 : Config->Exports) { | |||
647 | COFFShortExport E2; | |||
648 | E2.Name = E1.Name; | |||
649 | E2.SymbolName = E1.SymbolName; | |||
650 | E2.ExtName = E1.ExtName; | |||
651 | E2.Ordinal = E1.Ordinal; | |||
652 | E2.Noname = E1.Noname; | |||
653 | E2.Data = E1.Data; | |||
654 | E2.Private = E1.Private; | |||
655 | E2.Constant = E1.Constant; | |||
656 | Exports.push_back(E2); | |||
657 | } | |||
658 | ||||
659 | auto HandleError = [](Error &&E) { | |||
660 | handleAllErrors(std::move(E), | |||
661 | [](ErrorInfoBase &EIB) { error(EIB.message()); }); | |||
662 | }; | |||
663 | std::string LibName = getImportName(AsLib); | |||
664 | std::string Path = getImplibPath(); | |||
665 | ||||
666 | if (!Config->Incremental) { | |||
667 | HandleError(writeImportLibrary(LibName, Path, Exports, Config->Machine, | |||
668 | Config->MinGW)); | |||
669 | return; | |||
670 | } | |||
671 | ||||
672 | // If the import library already exists, replace it only if the contents | |||
673 | // have changed. | |||
674 | ErrorOr<std::unique_ptr<MemoryBuffer>> OldBuf = MemoryBuffer::getFile( | |||
675 | Path, /*FileSize*/ -1, /*RequiresNullTerminator*/ false); | |||
676 | if (!OldBuf) { | |||
677 | HandleError(writeImportLibrary(LibName, Path, Exports, Config->Machine, | |||
678 | Config->MinGW)); | |||
679 | return; | |||
680 | } | |||
681 | ||||
682 | SmallString<128> TmpName; | |||
683 | if (std::error_code EC = | |||
684 | sys::fs::createUniqueFile(Path + ".tmp-%%%%%%%%.lib", TmpName)) | |||
685 | fatal("cannot create temporary file for import library " + Path + ": " + | |||
686 | EC.message()); | |||
687 | ||||
688 | if (Error E = writeImportLibrary(LibName, TmpName, Exports, Config->Machine, | |||
689 | Config->MinGW)) { | |||
690 | HandleError(std::move(E)); | |||
691 | return; | |||
692 | } | |||
693 | ||||
694 | std::unique_ptr<MemoryBuffer> NewBuf = check(MemoryBuffer::getFile( | |||
695 | TmpName, /*FileSize*/ -1, /*RequiresNullTerminator*/ false)); | |||
696 | if ((*OldBuf)->getBuffer() != NewBuf->getBuffer()) { | |||
697 | OldBuf->reset(); | |||
698 | HandleError(errorCodeToError(sys::fs::rename(TmpName, Path))); | |||
699 | } else { | |||
700 | sys::fs::remove(TmpName); | |||
701 | } | |||
702 | } | |||
703 | ||||
704 | static void parseModuleDefs(StringRef Path) { | |||
705 | std::unique_ptr<MemoryBuffer> MB = CHECK(check2((MemoryBuffer::getFile(Path, -1, false, true)), [& ] { return toString("could not open " + Path); }) | |||
706 | MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path)check2((MemoryBuffer::getFile(Path, -1, false, true)), [& ] { return toString("could not open " + Path); }); | |||
707 | COFFModuleDefinition M = check(parseCOFFModuleDefinition( | |||
708 | MB->getMemBufferRef(), Config->Machine, Config->MinGW)); | |||
709 | ||||
710 | if (Config->OutputFile.empty()) | |||
711 | Config->OutputFile = Saver.save(M.OutputFile); | |||
712 | Config->ImportName = Saver.save(M.ImportName); | |||
713 | if (M.ImageBase) | |||
714 | Config->ImageBase = M.ImageBase; | |||
715 | if (M.StackReserve) | |||
716 | Config->StackReserve = M.StackReserve; | |||
717 | if (M.StackCommit) | |||
718 | Config->StackCommit = M.StackCommit; | |||
719 | if (M.HeapReserve) | |||
720 | Config->HeapReserve = M.HeapReserve; | |||
721 | if (M.HeapCommit) | |||
722 | Config->HeapCommit = M.HeapCommit; | |||
723 | if (M.MajorImageVersion) | |||
724 | Config->MajorImageVersion = M.MajorImageVersion; | |||
725 | if (M.MinorImageVersion) | |||
726 | Config->MinorImageVersion = M.MinorImageVersion; | |||
727 | if (M.MajorOSVersion) | |||
728 | Config->MajorOSVersion = M.MajorOSVersion; | |||
729 | if (M.MinorOSVersion) | |||
730 | Config->MinorOSVersion = M.MinorOSVersion; | |||
731 | ||||
732 | for (COFFShortExport E1 : M.Exports) { | |||
733 | Export E2; | |||
734 | // In simple cases, only Name is set. Renamed exports are parsed | |||
735 | // and set as "ExtName = Name". If Name has the form "OtherDll.Func", | |||
736 | // it shouldn't be a normal exported function but a forward to another | |||
737 | // DLL instead. This is supported by both MS and GNU linkers. | |||
738 | if (E1.ExtName != E1.Name && StringRef(E1.Name).contains('.')) { | |||
739 | E2.Name = Saver.save(E1.ExtName); | |||
740 | E2.ForwardTo = Saver.save(E1.Name); | |||
741 | Config->Exports.push_back(E2); | |||
742 | continue; | |||
743 | } | |||
744 | E2.Name = Saver.save(E1.Name); | |||
745 | E2.ExtName = Saver.save(E1.ExtName); | |||
746 | E2.Ordinal = E1.Ordinal; | |||
747 | E2.Noname = E1.Noname; | |||
748 | E2.Data = E1.Data; | |||
749 | E2.Private = E1.Private; | |||
750 | E2.Constant = E1.Constant; | |||
751 | Config->Exports.push_back(E2); | |||
752 | } | |||
753 | } | |||
754 | ||||
755 | void LinkerDriver::enqueueTask(std::function<void()> Task) { | |||
756 | TaskQueue.push_back(std::move(Task)); | |||
757 | } | |||
758 | ||||
759 | bool LinkerDriver::run() { | |||
760 | ScopedTimer T(InputFileTimer); | |||
761 | ||||
762 | bool DidWork = !TaskQueue.empty(); | |||
763 | while (!TaskQueue.empty()) { | |||
764 | TaskQueue.front()(); | |||
765 | TaskQueue.pop_front(); | |||
766 | } | |||
767 | return DidWork; | |||
768 | } | |||
769 | ||||
770 | // Parse an /order file. If an option is given, the linker places | |||
771 | // COMDAT sections in the same order as their names appear in the | |||
772 | // given file. | |||
773 | static void parseOrderFile(StringRef Arg) { | |||
774 | // For some reason, the MSVC linker requires a filename to be | |||
775 | // preceded by "@". | |||
776 | if (!Arg.startswith("@")) { | |||
777 | error("malformed /order option: '@' missing"); | |||
778 | return; | |||
779 | } | |||
780 | ||||
781 | // Get a list of all comdat sections for error checking. | |||
782 | DenseSet<StringRef> Set; | |||
783 | for (Chunk *C : Symtab->getChunks()) | |||
784 | if (auto *Sec = dyn_cast<SectionChunk>(C)) | |||
785 | if (Sec->Sym) | |||
786 | Set.insert(Sec->Sym->getName()); | |||
787 | ||||
788 | // Open a file. | |||
789 | StringRef Path = Arg.substr(1); | |||
790 | std::unique_ptr<MemoryBuffer> MB = CHECK(check2((MemoryBuffer::getFile(Path, -1, false, true)), [& ] { return toString("could not open " + Path); }) | |||
791 | MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path)check2((MemoryBuffer::getFile(Path, -1, false, true)), [& ] { return toString("could not open " + Path); }); | |||
792 | ||||
793 | // Parse a file. An order file contains one symbol per line. | |||
794 | // All symbols that were not present in a given order file are | |||
795 | // considered to have the lowest priority 0 and are placed at | |||
796 | // end of an output section. | |||
797 | for (std::string S : args::getLines(MB->getMemBufferRef())) { | |||
798 | if (Config->Machine == I386 && !isDecorated(S)) | |||
799 | S = "_" + S; | |||
800 | ||||
801 | if (Set.count(S) == 0) { | |||
802 | if (Config->WarnMissingOrderSymbol) | |||
803 | warn("/order:" + Arg + ": missing symbol: " + S + " [LNK4037]"); | |||
804 | } | |||
805 | else | |||
806 | Config->Order[S] = INT_MIN(-2147483647 -1) + Config->Order.size(); | |||
807 | } | |||
808 | } | |||
809 | ||||
810 | static void markAddrsig(Symbol *S) { | |||
811 | if (auto *D = dyn_cast_or_null<Defined>(S)) | |||
812 | if (Chunk *C = D->getChunk()) | |||
813 | C->KeepUnique = true; | |||
814 | } | |||
815 | ||||
816 | static void findKeepUniqueSections() { | |||
817 | // Exported symbols could be address-significant in other executables or DSOs, | |||
818 | // so we conservatively mark them as address-significant. | |||
819 | for (Export &R : Config->Exports) | |||
820 | markAddrsig(R.Sym); | |||
821 | ||||
822 | // Visit the address-significance table in each object file and mark each | |||
823 | // referenced symbol as address-significant. | |||
824 | for (ObjFile *Obj : ObjFile::Instances) { | |||
825 | ArrayRef<Symbol *> Syms = Obj->getSymbols(); | |||
826 | if (Obj->AddrsigSec) { | |||
827 | ArrayRef<uint8_t> Contents; | |||
828 | Obj->getCOFFObj()->getSectionContents(Obj->AddrsigSec, Contents); | |||
829 | const uint8_t *Cur = Contents.begin(); | |||
830 | while (Cur != Contents.end()) { | |||
831 | unsigned Size; | |||
832 | const char *Err; | |||
833 | uint64_t SymIndex = decodeULEB128(Cur, &Size, Contents.end(), &Err); | |||
834 | if (Err) | |||
835 | fatal(toString(Obj) + ": could not decode addrsig section: " + Err); | |||
836 | if (SymIndex >= Syms.size()) | |||
837 | fatal(toString(Obj) + ": invalid symbol index in addrsig section"); | |||
838 | markAddrsig(Syms[SymIndex]); | |||
839 | Cur += Size; | |||
840 | } | |||
841 | } else { | |||
842 | // If an object file does not have an address-significance table, | |||
843 | // conservatively mark all of its symbols as address-significant. | |||
844 | for (Symbol *S : Syms) | |||
845 | markAddrsig(S); | |||
846 | } | |||
847 | } | |||
848 | } | |||
849 | ||||
850 | // link.exe replaces each %foo% in AltPath with the contents of environment | |||
851 | // variable foo, and adds the two magic env vars _PDB (expands to the basename | |||
852 | // of pdb's output path) and _EXT (expands to the extension of the output | |||
853 | // binary). | |||
854 | // lld only supports %_PDB% and %_EXT% and warns on references to all other env | |||
855 | // vars. | |||
856 | static void parsePDBAltPath(StringRef AltPath) { | |||
857 | SmallString<128> Buf; | |||
858 | StringRef PDBBasename = | |||
859 | sys::path::filename(Config->PDBPath, sys::path::Style::windows); | |||
860 | StringRef BinaryExtension = | |||
861 | sys::path::extension(Config->OutputFile, sys::path::Style::windows); | |||
862 | if (!BinaryExtension.empty()) | |||
863 | BinaryExtension = BinaryExtension.substr(1); // %_EXT% does not include '.'. | |||
864 | ||||
865 | // Invariant: | |||
866 | // +--------- Cursor ('a...' might be the empty string). | |||
867 | // | +----- FirstMark | |||
868 | // | | +- SecondMark | |||
869 | // v v v | |||
870 | // a...%...%... | |||
871 | size_t Cursor = 0; | |||
872 | while (Cursor < AltPath.size()) { | |||
873 | size_t FirstMark, SecondMark; | |||
874 | if ((FirstMark = AltPath.find('%', Cursor)) == StringRef::npos || | |||
875 | (SecondMark = AltPath.find('%', FirstMark + 1)) == StringRef::npos) { | |||
876 | // Didn't find another full fragment, treat rest of string as literal. | |||
877 | Buf.append(AltPath.substr(Cursor)); | |||
878 | break; | |||
879 | } | |||
880 | ||||
881 | // Found a full fragment. Append text in front of first %, and interpret | |||
882 | // text between first and second % as variable name. | |||
883 | Buf.append(AltPath.substr(Cursor, FirstMark - Cursor)); | |||
884 | StringRef Var = AltPath.substr(FirstMark, SecondMark - FirstMark + 1); | |||
885 | if (Var.equals_lower("%_pdb%")) | |||
886 | Buf.append(PDBBasename); | |||
887 | else if (Var.equals_lower("%_ext%")) | |||
888 | Buf.append(BinaryExtension); | |||
889 | else { | |||
890 | warn("only %_PDB% and %_EXT% supported in /pdbaltpath:, keeping " + | |||
891 | Var + " as literal"); | |||
892 | Buf.append(Var); | |||
893 | } | |||
894 | ||||
895 | Cursor = SecondMark + 1; | |||
896 | } | |||
897 | ||||
898 | Config->PDBAltPath = Buf; | |||
899 | } | |||
900 | ||||
901 | void LinkerDriver::link(ArrayRef<const char *> ArgsArr) { | |||
902 | // If the first command line argument is "/lib", link.exe acts like lib.exe. | |||
903 | // We call our own implementation of lib.exe that understands bitcode files. | |||
904 | if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) { | |||
905 | if (llvm::libDriverMain(ArgsArr.slice(1)) != 0) | |||
906 | fatal("lib failed"); | |||
907 | return; | |||
908 | } | |||
909 | ||||
910 | // Needed for LTO. | |||
911 | InitializeAllTargetInfos(); | |||
912 | InitializeAllTargets(); | |||
913 | InitializeAllTargetMCs(); | |||
914 | InitializeAllAsmParsers(); | |||
915 | InitializeAllAsmPrinters(); | |||
916 | ||||
917 | // Parse command line options. | |||
918 | ArgParser Parser; | |||
919 | opt::InputArgList Args = Parser.parseLINK(ArgsArr); | |||
920 | ||||
921 | // Parse and evaluate -mllvm options. | |||
922 | std::vector<const char *> V; | |||
923 | V.push_back("lld-link (LLVM option parsing)"); | |||
924 | for (auto *Arg : Args.filtered(OPT_mllvm)) | |||
925 | V.push_back(Arg->getValue()); | |||
926 | cl::ParseCommandLineOptions(V.size(), V.data()); | |||
927 | ||||
928 | // Handle /errorlimit early, because error() depends on it. | |||
929 | if (auto *Arg = Args.getLastArg(OPT_errorlimit)) { | |||
930 | int N = 20; | |||
931 | StringRef S = Arg->getValue(); | |||
932 | if (S.getAsInteger(10, N)) | |||
933 | error(Arg->getSpelling() + " number expected, but got " + S); | |||
934 | errorHandler().ErrorLimit = N; | |||
935 | } | |||
936 | ||||
937 | // Handle /help | |||
938 | if (Args.hasArg(OPT_help)) { | |||
939 | printHelp(ArgsArr[0]); | |||
940 | return; | |||
941 | } | |||
942 | ||||
943 | if (Args.hasArg(OPT_show_timing)) | |||
944 | Config->ShowTiming = true; | |||
945 | ||||
946 | ScopedTimer T(Timer::root()); | |||
947 | // Handle --version, which is an lld extension. This option is a bit odd | |||
948 | // because it doesn't start with "/", but we deliberately chose "--" to | |||
949 | // avoid conflict with /version and for compatibility with clang-cl. | |||
950 | if (Args.hasArg(OPT_dash_dash_version)) { | |||
951 | outs() << getLLDVersion() << "\n"; | |||
952 | return; | |||
953 | } | |||
954 | ||||
955 | // Handle /lldmingw early, since it can potentially affect how other | |||
956 | // options are handled. | |||
957 | Config->MinGW = Args.hasArg(OPT_lldmingw); | |||
958 | ||||
959 | if (auto *Arg = Args.getLastArg(OPT_linkrepro)) { | |||
960 | SmallString<64> Path = StringRef(Arg->getValue()); | |||
961 | sys::path::append(Path, "repro.tar"); | |||
962 | ||||
963 | Expected<std::unique_ptr<TarWriter>> ErrOrWriter = | |||
964 | TarWriter::create(Path, "repro"); | |||
965 | ||||
966 | if (ErrOrWriter) { | |||
967 | Tar = std::move(*ErrOrWriter); | |||
968 | } else { | |||
969 | error("/linkrepro: failed to open " + Path + ": " + | |||
970 | toString(ErrOrWriter.takeError())); | |||
971 | } | |||
972 | } | |||
973 | ||||
974 | if (!Args.hasArg(OPT_INPUT)) { | |||
975 | if (Args.hasArg(OPT_deffile)) | |||
976 | Config->NoEntry = true; | |||
977 | else | |||
978 | fatal("no input files"); | |||
979 | } | |||
980 | ||||
981 | // Construct search path list. | |||
982 | SearchPaths.push_back(""); | |||
983 | for (auto *Arg : Args.filtered(OPT_libpath)) | |||
984 | SearchPaths.push_back(Arg->getValue()); | |||
985 | addLibSearchPaths(); | |||
986 | ||||
987 | // Handle /ignore | |||
988 | for (auto *Arg : Args.filtered(OPT_ignore)) { | |||
989 | if (StringRef(Arg->getValue()) == "4037") | |||
990 | Config->WarnMissingOrderSymbol = false; | |||
991 | else if (StringRef(Arg->getValue()) == "4217") | |||
992 | Config->WarnLocallyDefinedImported = false; | |||
993 | // Other warning numbers are ignored. | |||
994 | } | |||
995 | ||||
996 | // Handle /out | |||
997 | if (auto *Arg = Args.getLastArg(OPT_out)) | |||
998 | Config->OutputFile = Arg->getValue(); | |||
999 | ||||
1000 | // Handle /verbose | |||
1001 | if (Args.hasArg(OPT_verbose)) | |||
1002 | Config->Verbose = true; | |||
1003 | errorHandler().Verbose = Config->Verbose; | |||
1004 | ||||
1005 | // Handle /force or /force:unresolved | |||
1006 | if (Args.hasArg(OPT_force, OPT_force_unresolved)) | |||
1007 | Config->ForceUnresolved = true; | |||
1008 | ||||
1009 | // Handle /force or /force:multiple | |||
1010 | if (Args.hasArg(OPT_force, OPT_force_multiple)) | |||
1011 | Config->ForceMultiple = true; | |||
1012 | ||||
1013 | // Handle /debug | |||
1014 | DebugKind Debug = parseDebugKind(Args); | |||
1015 | if (Debug == DebugKind::Full || Debug == DebugKind::Dwarf || | |||
1016 | Debug == DebugKind::GHash) { | |||
1017 | Config->Debug = true; | |||
1018 | Config->Incremental = true; | |||
1019 | } | |||
1020 | ||||
1021 | // Handle /debugtype | |||
1022 | Config->DebugTypes = parseDebugTypes(Args); | |||
1023 | ||||
1024 | // Handle /pdb | |||
1025 | bool ShouldCreatePDB = | |||
1026 | (Debug == DebugKind::Full || Debug == DebugKind::GHash); | |||
1027 | if (ShouldCreatePDB) { | |||
1028 | if (auto *Arg = Args.getLastArg(OPT_pdb)) | |||
1029 | Config->PDBPath = Arg->getValue(); | |||
1030 | if (auto *Arg = Args.getLastArg(OPT_pdbaltpath)) | |||
1031 | Config->PDBAltPath = Arg->getValue(); | |||
1032 | if (Args.hasArg(OPT_natvis)) | |||
1033 | Config->NatvisFiles = Args.getAllArgValues(OPT_natvis); | |||
1034 | ||||
1035 | if (auto *Arg = Args.getLastArg(OPT_pdb_source_path)) | |||
1036 | Config->PDBSourcePath = Arg->getValue(); | |||
1037 | } | |||
1038 | ||||
1039 | // Handle /noentry | |||
1040 | if (Args.hasArg(OPT_noentry)) { | |||
1041 | if (Args.hasArg(OPT_dll)) | |||
1042 | Config->NoEntry = true; | |||
1043 | else | |||
1044 | error("/noentry must be specified with /dll"); | |||
1045 | } | |||
1046 | ||||
1047 | // Handle /dll | |||
1048 | if (Args.hasArg(OPT_dll)) { | |||
1049 | Config->DLL = true; | |||
1050 | Config->ManifestID = 2; | |||
1051 | } | |||
1052 | ||||
1053 | // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase | |||
1054 | // because we need to explicitly check whether that option or its inverse was | |||
1055 | // present in the argument list in order to handle /fixed. | |||
1056 | auto *DynamicBaseArg = Args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no); | |||
1057 | if (DynamicBaseArg && | |||
1058 | DynamicBaseArg->getOption().getID() == OPT_dynamicbase_no) | |||
1059 | Config->DynamicBase = false; | |||
1060 | ||||
1061 | // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the | |||
1062 | // default setting for any other project type.", but link.exe defaults to | |||
1063 | // /FIXED:NO for exe outputs as well. Match behavior, not docs. | |||
1064 | bool Fixed = Args.hasFlag(OPT_fixed, OPT_fixed_no, false); | |||
1065 | if (Fixed) { | |||
1066 | if (DynamicBaseArg && | |||
1067 | DynamicBaseArg->getOption().getID() == OPT_dynamicbase) { | |||
1068 | error("/fixed must not be specified with /dynamicbase"); | |||
1069 | } else { | |||
1070 | Config->Relocatable = false; | |||
1071 | Config->DynamicBase = false; | |||
1072 | } | |||
1073 | } | |||
1074 | ||||
1075 | // Handle /appcontainer | |||
1076 | Config->AppContainer = | |||
1077 | Args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false); | |||
1078 | ||||
1079 | // Handle /machine | |||
1080 | if (auto *Arg = Args.getLastArg(OPT_machine)) | |||
1081 | Config->Machine = getMachineType(Arg->getValue()); | |||
1082 | ||||
1083 | // Handle /nodefaultlib:<filename> | |||
1084 | for (auto *Arg : Args.filtered(OPT_nodefaultlib)) | |||
1085 | Config->NoDefaultLibs.insert(doFindLib(Arg->getValue())); | |||
1086 | ||||
1087 | // Handle /nodefaultlib | |||
1088 | if (Args.hasArg(OPT_nodefaultlib_all)) | |||
1089 | Config->NoDefaultLibAll = true; | |||
1090 | ||||
1091 | // Handle /base | |||
1092 | if (auto *Arg = Args.getLastArg(OPT_base)) | |||
1093 | parseNumbers(Arg->getValue(), &Config->ImageBase); | |||
1094 | ||||
1095 | // Handle /stack | |||
1096 | if (auto *Arg = Args.getLastArg(OPT_stack)) | |||
1097 | parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit); | |||
1098 | ||||
1099 | // Handle /guard:cf | |||
1100 | if (auto *Arg = Args.getLastArg(OPT_guard)) | |||
1101 | parseGuard(Arg->getValue()); | |||
1102 | ||||
1103 | // Handle /heap | |||
1104 | if (auto *Arg = Args.getLastArg(OPT_heap)) | |||
1105 | parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit); | |||
1106 | ||||
1107 | // Handle /version | |||
1108 | if (auto *Arg = Args.getLastArg(OPT_version)) | |||
1109 | parseVersion(Arg->getValue(), &Config->MajorImageVersion, | |||
1110 | &Config->MinorImageVersion); | |||
1111 | ||||
1112 | // Handle /subsystem | |||
1113 | if (auto *Arg = Args.getLastArg(OPT_subsystem)) | |||
1114 | parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion, | |||
1115 | &Config->MinorOSVersion); | |||
1116 | ||||
1117 | // Handle /timestamp | |||
1118 | if (llvm::opt::Arg *Arg = Args.getLastArg(OPT_timestamp, OPT_repro)) { | |||
1119 | if (Arg->getOption().getID() == OPT_repro) { | |||
1120 | Config->Timestamp = 0; | |||
1121 | Config->Repro = true; | |||
1122 | } else { | |||
1123 | Config->Repro = false; | |||
1124 | StringRef Value(Arg->getValue()); | |||
1125 | if (Value.getAsInteger(0, Config->Timestamp)) | |||
1126 | fatal(Twine("invalid timestamp: ") + Value + | |||
1127 | ". Expected 32-bit integer"); | |||
1128 | } | |||
1129 | } else { | |||
1130 | Config->Repro = false; | |||
1131 | Config->Timestamp = time(nullptr); | |||
1132 | } | |||
1133 | ||||
1134 | // Handle /alternatename | |||
1135 | for (auto *Arg : Args.filtered(OPT_alternatename)) | |||
1136 | parseAlternateName(Arg->getValue()); | |||
1137 | ||||
1138 | // Handle /include | |||
1139 | for (auto *Arg : Args.filtered(OPT_incl)) | |||
1140 | addUndefined(Arg->getValue()); | |||
1141 | ||||
1142 | // Handle /implib | |||
1143 | if (auto *Arg = Args.getLastArg(OPT_implib)) | |||
1144 | Config->Implib = Arg->getValue(); | |||
1145 | ||||
1146 | // Handle /opt. | |||
1147 | bool DoGC = Debug == DebugKind::None || Args.hasArg(OPT_profile); | |||
1148 | unsigned ICFLevel = | |||
1149 | Args.hasArg(OPT_profile) ? 0 : 1; // 0: off, 1: limited, 2: on | |||
1150 | unsigned TailMerge = 1; | |||
1151 | for (auto *Arg : Args.filtered(OPT_opt)) { | |||
1152 | std::string Str = StringRef(Arg->getValue()).lower(); | |||
1153 | SmallVector<StringRef, 1> Vec; | |||
1154 | StringRef(Str).split(Vec, ','); | |||
1155 | for (StringRef S : Vec) { | |||
1156 | if (S == "ref") { | |||
1157 | DoGC = true; | |||
1158 | } else if (S == "noref") { | |||
1159 | DoGC = false; | |||
1160 | } else if (S == "icf" || S.startswith("icf=")) { | |||
1161 | ICFLevel = 2; | |||
1162 | } else if (S == "noicf") { | |||
1163 | ICFLevel = 0; | |||
1164 | } else if (S == "lldtailmerge") { | |||
1165 | TailMerge = 2; | |||
1166 | } else if (S == "nolldtailmerge") { | |||
1167 | TailMerge = 0; | |||
1168 | } else if (S.startswith("lldlto=")) { | |||
1169 | StringRef OptLevel = S.substr(7); | |||
1170 | if (OptLevel.getAsInteger(10, Config->LTOO) || Config->LTOO > 3) | |||
1171 | error("/opt:lldlto: invalid optimization level: " + OptLevel); | |||
1172 | } else if (S.startswith("lldltojobs=")) { | |||
1173 | StringRef Jobs = S.substr(11); | |||
1174 | if (Jobs.getAsInteger(10, Config->ThinLTOJobs) || | |||
1175 | Config->ThinLTOJobs == 0) | |||
1176 | error("/opt:lldltojobs: invalid job count: " + Jobs); | |||
1177 | } else if (S.startswith("lldltopartitions=")) { | |||
1178 | StringRef N = S.substr(17); | |||
1179 | if (N.getAsInteger(10, Config->LTOPartitions) || | |||
1180 | Config->LTOPartitions == 0) | |||
1181 | error("/opt:lldltopartitions: invalid partition count: " + N); | |||
1182 | } else if (S != "lbr" && S != "nolbr") | |||
1183 | error("/opt: unknown option: " + S); | |||
1184 | } | |||
1185 | } | |||
1186 | ||||
1187 | // Limited ICF is enabled if GC is enabled and ICF was never mentioned | |||
1188 | // explicitly. | |||
1189 | // FIXME: LLD only implements "limited" ICF, i.e. it only merges identical | |||
1190 | // code. If the user passes /OPT:ICF explicitly, LLD should merge identical | |||
1191 | // comdat readonly data. | |||
1192 | if (ICFLevel == 1 && !DoGC) | |||
1193 | ICFLevel = 0; | |||
1194 | Config->DoGC = DoGC; | |||
1195 | Config->DoICF = ICFLevel > 0; | |||
1196 | Config->TailMerge = (TailMerge == 1 && Config->DoICF) || TailMerge == 2; | |||
1197 | ||||
1198 | // Handle /lldsavetemps | |||
1199 | if (Args.hasArg(OPT_lldsavetemps)) | |||
1200 | Config->SaveTemps = true; | |||
1201 | ||||
1202 | // Handle /kill-at | |||
1203 | if (Args.hasArg(OPT_kill_at)) | |||
1204 | Config->KillAt = true; | |||
1205 | ||||
1206 | // Handle /lldltocache | |||
1207 | if (auto *Arg = Args.getLastArg(OPT_lldltocache)) | |||
1208 | Config->LTOCache = Arg->getValue(); | |||
1209 | ||||
1210 | // Handle /lldsavecachepolicy | |||
1211 | if (auto *Arg = Args.getLastArg(OPT_lldltocachepolicy)) | |||
1212 | Config->LTOCachePolicy = CHECK(check2((parseCachePruningPolicy(Arg->getValue())), [&] { return toString(Twine("/lldltocachepolicy: invalid cache policy: " ) + Arg->getValue()); }) | |||
1213 | parseCachePruningPolicy(Arg->getValue()),check2((parseCachePruningPolicy(Arg->getValue())), [&] { return toString(Twine("/lldltocachepolicy: invalid cache policy: " ) + Arg->getValue()); }) | |||
1214 | Twine("/lldltocachepolicy: invalid cache policy: ") + Arg->getValue())check2((parseCachePruningPolicy(Arg->getValue())), [&] { return toString(Twine("/lldltocachepolicy: invalid cache policy: " ) + Arg->getValue()); }); | |||
1215 | ||||
1216 | // Handle /failifmismatch | |||
1217 | for (auto *Arg : Args.filtered(OPT_failifmismatch)) | |||
1218 | checkFailIfMismatch(Arg->getValue()); | |||
1219 | ||||
1220 | // Handle /merge | |||
1221 | for (auto *Arg : Args.filtered(OPT_merge)) | |||
1222 | parseMerge(Arg->getValue()); | |||
1223 | ||||
1224 | // Add default section merging rules after user rules. User rules take | |||
1225 | // precedence, but we will emit a warning if there is a conflict. | |||
1226 | parseMerge(".idata=.rdata"); | |||
1227 | parseMerge(".didat=.rdata"); | |||
1228 | parseMerge(".edata=.rdata"); | |||
1229 | parseMerge(".xdata=.rdata"); | |||
1230 | parseMerge(".bss=.data"); | |||
1231 | ||||
1232 | if (Config->MinGW) { | |||
1233 | parseMerge(".ctors=.rdata"); | |||
1234 | parseMerge(".dtors=.rdata"); | |||
1235 | parseMerge(".CRT=.rdata"); | |||
1236 | } | |||
1237 | ||||
1238 | // Handle /section | |||
1239 | for (auto *Arg : Args.filtered(OPT_section)) | |||
1240 | parseSection(Arg->getValue()); | |||
1241 | ||||
1242 | // Handle /aligncomm | |||
1243 | for (auto *Arg : Args.filtered(OPT_aligncomm)) | |||
1244 | parseAligncomm(Arg->getValue()); | |||
1245 | ||||
1246 | // Handle /manifestdependency. This enables /manifest unless /manifest:no is | |||
1247 | // also passed. | |||
1248 | if (auto *Arg = Args.getLastArg(OPT_manifestdependency)) { | |||
1249 | Config->ManifestDependency = Arg->getValue(); | |||
1250 | Config->Manifest = Configuration::SideBySide; | |||
1251 | } | |||
1252 | ||||
1253 | // Handle /manifest and /manifest: | |||
1254 | if (auto *Arg = Args.getLastArg(OPT_manifest, OPT_manifest_colon)) { | |||
1255 | if (Arg->getOption().getID() == OPT_manifest) | |||
1256 | Config->Manifest = Configuration::SideBySide; | |||
1257 | else | |||
1258 | parseManifest(Arg->getValue()); | |||
1259 | } | |||
1260 | ||||
1261 | // Handle /manifestuac | |||
1262 | if (auto *Arg = Args.getLastArg(OPT_manifestuac)) | |||
1263 | parseManifestUAC(Arg->getValue()); | |||
1264 | ||||
1265 | // Handle /manifestfile | |||
1266 | if (auto *Arg = Args.getLastArg(OPT_manifestfile)) | |||
1267 | Config->ManifestFile = Arg->getValue(); | |||
1268 | ||||
1269 | // Handle /manifestinput | |||
1270 | for (auto *Arg : Args.filtered(OPT_manifestinput)) | |||
1271 | Config->ManifestInput.push_back(Arg->getValue()); | |||
1272 | ||||
1273 | if (!Config->ManifestInput.empty() && | |||
1274 | Config->Manifest != Configuration::Embed) { | |||
1275 | fatal("/manifestinput: requires /manifest:embed"); | |||
1276 | } | |||
1277 | ||||
1278 | // Handle miscellaneous boolean flags. | |||
1279 | Config->AllowBind = Args.hasFlag(OPT_allowbind, OPT_allowbind_no, true); | |||
1280 | Config->AllowIsolation = | |||
1281 | Args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true); | |||
1282 | Config->Incremental = | |||
1283 | Args.hasFlag(OPT_incremental, OPT_incremental_no, | |||
1284 | !Config->DoGC && !Config->DoICF && !Args.hasArg(OPT_order) && | |||
1285 | !Args.hasArg(OPT_profile)); | |||
1286 | Config->IntegrityCheck = | |||
1287 | Args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false); | |||
1288 | Config->NxCompat = Args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true); | |||
1289 | Config->TerminalServerAware = | |||
1290 | !Config->DLL && Args.hasFlag(OPT_tsaware, OPT_tsaware_no, true); | |||
1291 | Config->DebugDwarf = Debug == DebugKind::Dwarf; | |||
1292 | Config->DebugGHashes = Debug == DebugKind::GHash; | |||
1293 | Config->DebugSymtab = Debug == DebugKind::Symtab; | |||
1294 | ||||
1295 | Config->MapFile = getMapFile(Args); | |||
1296 | ||||
1297 | if (Config->Incremental && Args.hasArg(OPT_profile)) { | |||
1298 | warn("ignoring '/incremental' due to '/profile' specification"); | |||
1299 | Config->Incremental = false; | |||
1300 | } | |||
1301 | ||||
1302 | if (Config->Incremental && Args.hasArg(OPT_order)) { | |||
1303 | warn("ignoring '/incremental' due to '/order' specification"); | |||
1304 | Config->Incremental = false; | |||
1305 | } | |||
1306 | ||||
1307 | if (Config->Incremental && Config->DoGC) { | |||
1308 | warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to " | |||
1309 | "disable"); | |||
1310 | Config->Incremental = false; | |||
1311 | } | |||
1312 | ||||
1313 | if (Config->Incremental && Config->DoICF) { | |||
1314 | warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to " | |||
1315 | "disable"); | |||
1316 | Config->Incremental = false; | |||
1317 | } | |||
1318 | ||||
1319 | if (errorCount()) | |||
1320 | return; | |||
1321 | ||||
1322 | std::set<sys::fs::UniqueID> WholeArchives; | |||
1323 | AutoExporter Exporter; | |||
1324 | for (auto *Arg : Args.filtered(OPT_wholearchive_file)) { | |||
1325 | if (Optional<StringRef> Path = doFindFile(Arg->getValue())) { | |||
1326 | if (Optional<sys::fs::UniqueID> ID = getUniqueID(*Path)) | |||
1327 | WholeArchives.insert(*ID); | |||
1328 | Exporter.addWholeArchive(*Path); | |||
1329 | } | |||
1330 | } | |||
1331 | ||||
1332 | // A predicate returning true if a given path is an argument for | |||
1333 | // /wholearchive:, or /wholearchive is enabled globally. | |||
1334 | // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj" | |||
1335 | // needs to be handled as "/wholearchive:foo.obj foo.obj". | |||
1336 | auto IsWholeArchive = [&](StringRef Path) -> bool { | |||
1337 | if (Args.hasArg(OPT_wholearchive_flag)) | |||
1338 | return true; | |||
1339 | if (Optional<sys::fs::UniqueID> ID = getUniqueID(Path)) | |||
1340 | return WholeArchives.count(*ID); | |||
1341 | return false; | |||
1342 | }; | |||
1343 | ||||
1344 | // Create a list of input files. Files can be given as arguments | |||
1345 | // for /defaultlib option. | |||
1346 | for (auto *Arg : Args.filtered(OPT_INPUT, OPT_wholearchive_file)) | |||
1347 | if (Optional<StringRef> Path = findFile(Arg->getValue())) | |||
1348 | enqueuePath(*Path, IsWholeArchive(*Path)); | |||
1349 | ||||
1350 | for (auto *Arg : Args.filtered(OPT_defaultlib)) | |||
1351 | if (Optional<StringRef> Path = findLib(Arg->getValue())) | |||
1352 | enqueuePath(*Path, false); | |||
1353 | ||||
1354 | // Windows specific -- Create a resource file containing a manifest file. | |||
1355 | if (Config->Manifest == Configuration::Embed) | |||
1356 | addBuffer(createManifestRes(), false); | |||
1357 | ||||
1358 | // Read all input files given via the command line. | |||
1359 | run(); | |||
1360 | ||||
1361 | if (errorCount()) | |||
1362 | return; | |||
1363 | ||||
1364 | // We should have inferred a machine type by now from the input files, but if | |||
1365 | // not we assume x64. | |||
1366 | if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) { | |||
1367 | warn("/machine is not specified. x64 is assumed"); | |||
1368 | Config->Machine = AMD64; | |||
1369 | } | |||
1370 | Config->Wordsize = Config->is64() ? 8 : 4; | |||
1371 | ||||
1372 | // Input files can be Windows resource files (.res files). We use | |||
1373 | // WindowsResource to convert resource files to a regular COFF file, | |||
1374 | // then link the resulting file normally. | |||
1375 | if (!Resources.empty()) | |||
1376 | Symtab->addFile(make<ObjFile>(convertResToCOFF(Resources))); | |||
1377 | ||||
1378 | if (Tar) | |||
1379 | Tar->append("response.txt", | |||
1380 | createResponseFile(Args, FilePaths, | |||
1381 | ArrayRef<StringRef>(SearchPaths).slice(1))); | |||
1382 | ||||
1383 | // Handle /largeaddressaware | |||
1384 | Config->LargeAddressAware = Args.hasFlag( | |||
1385 | OPT_largeaddressaware, OPT_largeaddressaware_no, Config->is64()); | |||
1386 | ||||
1387 | // Handle /highentropyva | |||
1388 | Config->HighEntropyVA = | |||
1389 | Config->is64() && | |||
1390 | Args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true); | |||
1391 | ||||
1392 | if (!Config->DynamicBase && | |||
1393 | (Config->Machine == ARMNT || Config->Machine == ARM64)) | |||
1394 | error("/dynamicbase:no is not compatible with " + | |||
1395 | machineToStr(Config->Machine)); | |||
1396 | ||||
1397 | // Handle /export | |||
1398 | for (auto *Arg : Args.filtered(OPT_export)) { | |||
1399 | Export E = parseExport(Arg->getValue()); | |||
1400 | if (Config->Machine == I386) { | |||
1401 | if (!isDecorated(E.Name)) | |||
1402 | E.Name = Saver.save("_" + E.Name); | |||
1403 | if (!E.ExtName.empty() && !isDecorated(E.ExtName)) | |||
1404 | E.ExtName = Saver.save("_" + E.ExtName); | |||
1405 | } | |||
1406 | Config->Exports.push_back(E); | |||
1407 | } | |||
1408 | ||||
1409 | // Handle /def | |||
1410 | if (auto *Arg = Args.getLastArg(OPT_deffile)) { | |||
1411 | // parseModuleDefs mutates Config object. | |||
1412 | parseModuleDefs(Arg->getValue()); | |||
1413 | } | |||
1414 | ||||
1415 | // Handle generation of import library from a def file. | |||
1416 | if (!Args.hasArg(OPT_INPUT)) { | |||
1417 | fixupExports(); | |||
1418 | createImportLibrary(/*AsLib=*/true); | |||
1419 | return; | |||
1420 | } | |||
1421 | ||||
1422 | // Windows specific -- if no /subsystem is given, we need to infer | |||
1423 | // that from entry point name. Must happen before /entry handling, | |||
1424 | // and after the early return when just writing an import library. | |||
1425 | if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) { | |||
1426 | Config->Subsystem = inferSubsystem(); | |||
1427 | if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) | |||
1428 | fatal("subsystem must be defined"); | |||
1429 | } | |||
1430 | ||||
1431 | // Handle /entry and /dll | |||
1432 | if (auto *Arg = Args.getLastArg(OPT_entry)) { | |||
1433 | Config->Entry = addUndefined(mangle(Arg->getValue())); | |||
1434 | } else if (!Config->Entry && !Config->NoEntry) { | |||
1435 | if (Args.hasArg(OPT_dll)) { | |||
1436 | StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12" | |||
1437 | : "_DllMainCRTStartup"; | |||
1438 | Config->Entry = addUndefined(S); | |||
1439 | } else { | |||
1440 | // Windows specific -- If entry point name is not given, we need to | |||
1441 | // infer that from user-defined entry name. | |||
1442 | StringRef S = findDefaultEntry(); | |||
1443 | if (S.empty()) | |||
1444 | fatal("entry point must be defined"); | |||
1445 | Config->Entry = addUndefined(S); | |||
1446 | log("Entry name inferred: " + S); | |||
1447 | } | |||
1448 | } | |||
1449 | ||||
1450 | // Handle /delayload | |||
1451 | for (auto *Arg : Args.filtered(OPT_delayload)) { | |||
1452 | Config->DelayLoads.insert(StringRef(Arg->getValue()).lower()); | |||
1453 | if (Config->Machine == I386) { | |||
1454 | Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8"); | |||
1455 | } else { | |||
1456 | Config->DelayLoadHelper = addUndefined("__delayLoadHelper2"); | |||
1457 | } | |||
1458 | } | |||
1459 | ||||
1460 | // Set default image name if neither /out or /def set it. | |||
1461 | if (Config->OutputFile.empty()) { | |||
1462 | Config->OutputFile = | |||
1463 | getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue()); | |||
1464 | } | |||
1465 | ||||
1466 | if (ShouldCreatePDB) { | |||
1467 | // Put the PDB next to the image if no /pdb flag was passed. | |||
1468 | if (Config->PDBPath.empty()) { | |||
1469 | Config->PDBPath = Config->OutputFile; | |||
1470 | sys::path::replace_extension(Config->PDBPath, ".pdb"); | |||
1471 | } | |||
1472 | ||||
1473 | // The embedded PDB path should be the absolute path to the PDB if no | |||
1474 | // /pdbaltpath flag was passed. | |||
1475 | if (Config->PDBAltPath.empty()) { | |||
1476 | Config->PDBAltPath = Config->PDBPath; | |||
1477 | ||||
1478 | // It's important to make the path absolute and remove dots. This path | |||
1479 | // will eventually be written into the PE header, and certain Microsoft | |||
1480 | // tools won't work correctly if these assumptions are not held. | |||
1481 | sys::fs::make_absolute(Config->PDBAltPath); | |||
1482 | sys::path::remove_dots(Config->PDBAltPath); | |||
1483 | } else { | |||
1484 | // Don't do this earlier, so that Config->OutputFile is ready. | |||
1485 | parsePDBAltPath(Config->PDBAltPath); | |||
1486 | } | |||
1487 | } | |||
1488 | ||||
1489 | // Set default image base if /base is not given. | |||
1490 | if (Config->ImageBase == uint64_t(-1)) | |||
1491 | Config->ImageBase = getDefaultImageBase(); | |||
1492 | ||||
1493 | Symtab->addSynthetic(mangle("__ImageBase"), nullptr); | |||
1494 | if (Config->Machine == I386) { | |||
1495 | Symtab->addAbsolute("___safe_se_handler_table", 0); | |||
1496 | Symtab->addAbsolute("___safe_se_handler_count", 0); | |||
1497 | } | |||
1498 | ||||
1499 | Symtab->addAbsolute(mangle("__guard_fids_count"), 0); | |||
1500 | Symtab->addAbsolute(mangle("__guard_fids_table"), 0); | |||
1501 | Symtab->addAbsolute(mangle("__guard_flags"), 0); | |||
1502 | Symtab->addAbsolute(mangle("__guard_iat_count"), 0); | |||
1503 | Symtab->addAbsolute(mangle("__guard_iat_table"), 0); | |||
1504 | Symtab->addAbsolute(mangle("__guard_longjmp_count"), 0); | |||
1505 | Symtab->addAbsolute(mangle("__guard_longjmp_table"), 0); | |||
1506 | // Needed for MSVC 2017 15.5 CRT. | |||
1507 | Symtab->addAbsolute(mangle("__enclave_config"), 0); | |||
1508 | ||||
1509 | if (Config->MinGW) { | |||
1510 | Symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST__"), 0); | |||
1511 | Symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST_END__"), 0); | |||
1512 | Symtab->addAbsolute(mangle("__CTOR_LIST__"), 0); | |||
1513 | Symtab->addAbsolute(mangle("__DTOR_LIST__"), 0); | |||
1514 | } | |||
1515 | ||||
1516 | // This code may add new undefined symbols to the link, which may enqueue more | |||
1517 | // symbol resolution tasks, so we need to continue executing tasks until we | |||
1518 | // converge. | |||
1519 | do { | |||
1520 | // Windows specific -- if entry point is not found, | |||
1521 | // search for its mangled names. | |||
1522 | if (Config->Entry) | |||
1523 | Symtab->mangleMaybe(Config->Entry); | |||
1524 | ||||
1525 | // Windows specific -- Make sure we resolve all dllexported symbols. | |||
1526 | for (Export &E : Config->Exports) { | |||
1527 | if (!E.ForwardTo.empty()) | |||
1528 | continue; | |||
1529 | E.Sym = addUndefined(E.Name); | |||
1530 | if (!E.Directives) | |||
1531 | Symtab->mangleMaybe(E.Sym); | |||
1532 | } | |||
1533 | ||||
1534 | // Add weak aliases. Weak aliases is a mechanism to give remaining | |||
1535 | // undefined symbols final chance to be resolved successfully. | |||
1536 | for (auto Pair : Config->AlternateNames) { | |||
1537 | StringRef From = Pair.first; | |||
1538 | StringRef To = Pair.second; | |||
1539 | Symbol *Sym = Symtab->find(From); | |||
1540 | if (!Sym) | |||
1541 | continue; | |||
1542 | if (auto *U = dyn_cast<Undefined>(Sym)) | |||
1543 | if (!U->WeakAlias) | |||
1544 | U->WeakAlias = Symtab->addUndefined(To); | |||
1545 | } | |||
1546 | ||||
1547 | // Windows specific -- if __load_config_used can be resolved, resolve it. | |||
1548 | if (Symtab->findUnderscore("_load_config_used")) | |||
1549 | addUndefined(mangle("_load_config_used")); | |||
1550 | } while (run()); | |||
1551 | ||||
1552 | if (errorCount()) | |||
1553 | return; | |||
1554 | ||||
1555 | // Do LTO by compiling bitcode input files to a set of native COFF files then | |||
1556 | // link those files. | |||
1557 | Symtab->addCombinedLTOObjects(); | |||
1558 | run(); | |||
1559 | ||||
1560 | if (Config->MinGW) { | |||
1561 | // Load any further object files that might be needed for doing automatic | |||
1562 | // imports. | |||
1563 | // | |||
1564 | // For cases with no automatically imported symbols, this iterates once | |||
1565 | // over the symbol table and doesn't do anything. | |||
1566 | // | |||
1567 | // For the normal case with a few automatically imported symbols, this | |||
1568 | // should only need to be run once, since each new object file imported | |||
1569 | // is an import library and wouldn't add any new undefined references, | |||
1570 | // but there's nothing stopping the __imp_ symbols from coming from a | |||
1571 | // normal object file as well (although that won't be used for the | |||
1572 | // actual autoimport later on). If this pass adds new undefined references, | |||
1573 | // we won't iterate further to resolve them. | |||
1574 | Symtab->loadMinGWAutomaticImports(); | |||
1575 | run(); | |||
1576 | } | |||
1577 | ||||
1578 | // Make sure we have resolved all symbols. | |||
1579 | Symtab->reportRemainingUndefines(); | |||
1580 | if (errorCount()) | |||
1581 | return; | |||
1582 | ||||
1583 | // Handle /safeseh. | |||
1584 | if (Args.hasFlag(OPT_safeseh, OPT_safeseh_no, false)) { | |||
1585 | for (ObjFile *File : ObjFile::Instances) | |||
1586 | if (!File->hasSafeSEH()) | |||
1587 | error("/safeseh: " + File->getName() + " is not compatible with SEH"); | |||
1588 | if (errorCount()) | |||
1589 | return; | |||
1590 | } | |||
1591 | ||||
1592 | // In MinGW, all symbols are automatically exported if no symbols | |||
1593 | // are chosen to be exported. | |||
1594 | if (Config->DLL && ((Config->MinGW && Config->Exports.empty()) || | |||
1595 | Args.hasArg(OPT_export_all_symbols))) { | |||
1596 | Exporter.initSymbolExcludes(); | |||
1597 | ||||
1598 | Symtab->forEachSymbol([=](Symbol *S) { | |||
1599 | auto *Def = dyn_cast<Defined>(S); | |||
1600 | if (!Exporter.shouldExport(Def)) | |||
1601 | return; | |||
1602 | Export E; | |||
1603 | E.Name = Def->getName(); | |||
1604 | E.Sym = Def; | |||
1605 | if (Def->getChunk() && | |||
1606 | !(Def->getChunk()->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE)) | |||
1607 | E.Data = true; | |||
1608 | Config->Exports.push_back(E); | |||
1609 | }); | |||
1610 | } | |||
1611 | ||||
1612 | // Windows specific -- when we are creating a .dll file, we also | |||
1613 | // need to create a .lib file. | |||
1614 | if (!Config->Exports.empty() || Config->DLL) { | |||
1615 | fixupExports(); | |||
1616 | createImportLibrary(/*AsLib=*/false); | |||
1617 | assignExportOrdinals(); | |||
1618 | } | |||
1619 | ||||
1620 | // Handle /output-def (MinGW specific). | |||
1621 | if (auto *Arg = Args.getLastArg(OPT_output_def)) | |||
1622 | writeDefFile(Arg->getValue()); | |||
1623 | ||||
1624 | // Set extra alignment for .comm symbols | |||
1625 | for (auto Pair : Config->AlignComm) { | |||
1626 | StringRef Name = Pair.first; | |||
1627 | uint32_t Alignment = Pair.second; | |||
1628 | ||||
1629 | Symbol *Sym = Symtab->find(Name); | |||
1630 | if (!Sym) { | |||
1631 | warn("/aligncomm symbol " + Name + " not found"); | |||
1632 | continue; | |||
1633 | } | |||
1634 | ||||
1635 | // If the symbol isn't common, it must have been replaced with a regular | |||
1636 | // symbol, which will carry its own alignment. | |||
1637 | auto *DC = dyn_cast<DefinedCommon>(Sym); | |||
1638 | if (!DC) | |||
1639 | continue; | |||
1640 | ||||
1641 | CommonChunk *C = DC->getChunk(); | |||
1642 | C->Alignment = std::max(C->Alignment, Alignment); | |||
1643 | } | |||
1644 | ||||
1645 | // Windows specific -- Create a side-by-side manifest file. | |||
1646 | if (Config->Manifest == Configuration::SideBySide) | |||
1647 | createSideBySideManifest(); | |||
1648 | ||||
1649 | // Handle /order. We want to do this at this moment because we | |||
1650 | // need a complete list of comdat sections to warn on nonexistent | |||
1651 | // functions. | |||
1652 | if (auto *Arg = Args.getLastArg(OPT_order)) | |||
1653 | parseOrderFile(Arg->getValue()); | |||
1654 | ||||
1655 | // Identify unreferenced COMDAT sections. | |||
1656 | if (Config->DoGC) | |||
1657 | markLive(Symtab->getChunks()); | |||
1658 | ||||
1659 | // Identify identical COMDAT sections to merge them. | |||
1660 | if (Config->DoICF) { | |||
1661 | findKeepUniqueSections(); | |||
1662 | doICF(Symtab->getChunks()); | |||
1663 | } | |||
1664 | ||||
1665 | // Write the result. | |||
1666 | writeResult(); | |||
1667 | ||||
1668 | // Stop early so we can print the results. | |||
1669 | Timer::root().stop(); | |||
1670 | if (Config->ShowTiming) | |||
1671 | Timer::root().print(); | |||
1672 | } | |||
1673 | ||||
1674 | } // namespace coff | |||
1675 | } // namespace lld |
1 | //===- ErrorHandler.h -------------------------------------------*- C++ -*-===// |
2 | // |
3 | // The LLVM Linker |
4 | // |
5 | // This file is distributed under the University of Illinois Open Source |
6 | // License. See LICENSE.TXT for details. |
7 | // |
8 | //===----------------------------------------------------------------------===// |
9 | // |
10 | // We designed lld's error handlers with the following goals in mind: |
11 | // |
12 | // - Errors can occur at any place where we handle user input, but we don't |
13 | // want them to affect the normal execution path too much. Ideally, |
14 | // handling errors should be as simple as reporting them and exit (but |
15 | // without actually doing exit). |
16 | // |
17 | // In particular, the design to wrap all functions that could fail with |
18 | // ErrorOr<T> is rejected because otherwise we would have to wrap a large |
19 | // number of functions in lld with ErrorOr. With that approach, if some |
20 | // function F can fail, not only F but all functions that transitively call |
21 | // F have to be wrapped with ErrorOr. That seemed too much. |
22 | // |
23 | // - Finding only one error at a time is not sufficient. We want to find as |
24 | // many errors as possible with one execution of the linker. That means the |
25 | // linker needs to keep running after a first error and give up at some |
26 | // checkpoint (beyond which it would find cascading, false errors caused by |
27 | // the previous errors). |
28 | // |
29 | // - We want a simple interface to report errors. Unlike Clang, the data we |
30 | // handle is compiled binary, so we don't need an error reporting mechanism |
31 | // that's as sophisticated as the one that Clang has. |
32 | // |
33 | // The current lld's error handling mechanism is simple: |
34 | // |
35 | // - When you find an error, report it using error() and continue as far as |
36 | // you can. An internal error counter is incremented by one every time you |
37 | // call error(). |
38 | // |
39 | // A common idiom to handle an error is calling error() and then returning |
40 | // a reasonable default value. For example, if your function handles a |
41 | // user-supplied alignment value, and if you find an invalid alignment |
42 | // (e.g. 17 which is not 2^n), you may report it using error() and continue |
43 | // as if it were alignment 1 (which is the simplest reasonable value). |
44 | // |
45 | // Note that you should not continue with an invalid value; that breaks the |
46 | // internal consistency. You need to maintain all variables have some sane |
47 | // value even after an error occurred. So, when you have to continue with |
48 | // some value, always use a dummy value. |
49 | // |
50 | // - Find a reasonable checkpoint at where you want to stop the linker, and |
51 | // add code to return from the function if errorCount() > 0. In most cases, |
52 | // a checkpoint already exists, so you don't need to do anything for this. |
53 | // |
54 | // This interface satisfies all the goals that we mentioned above. |
55 | // |
56 | // You should never call fatal() except for reporting a corrupted input file. |
57 | // fatal() immediately terminates the linker, so the function is not desirable |
58 | // if you are using lld as a subroutine in other program, and with that you |
59 | // can find only one error at a time. |
60 | // |
61 | // warn() doesn't do anything but printing out a given message. |
62 | // |
63 | // It is not recommended to use llvm::outs() or llvm::errs() directly in lld |
64 | // because they are not thread-safe. The functions declared in this file are |
65 | // thread-safe. |
66 | // |
67 | //===----------------------------------------------------------------------===// |
68 | |
69 | #ifndef LLD_COMMON_ERRORHANDLER_H |
70 | #define LLD_COMMON_ERRORHANDLER_H |
71 | |
72 | #include "lld/Common/LLVM.h" |
73 | |
74 | #include "llvm/ADT/STLExtras.h" |
75 | #include "llvm/Support/Error.h" |
76 | #include "llvm/Support/FileOutputBuffer.h" |
77 | |
78 | namespace llvm { |
79 | class DiagnosticInfo; |
80 | } |
81 | |
82 | namespace lld { |
83 | |
84 | class ErrorHandler { |
85 | public: |
86 | uint64_t ErrorCount = 0; |
87 | uint64_t ErrorLimit = 20; |
88 | StringRef ErrorLimitExceededMsg = "too many errors emitted, stopping now"; |
89 | StringRef LogName = "lld"; |
90 | llvm::raw_ostream *ErrorOS = &llvm::errs(); |
91 | bool ColorDiagnostics = llvm::errs().has_colors(); |
92 | bool ExitEarly = true; |
93 | bool FatalWarnings = false; |
94 | bool Verbose = false; |
95 | |
96 | void error(const Twine &Msg); |
97 | LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) void fatal(const Twine &Msg); |
98 | void log(const Twine &Msg); |
99 | void message(const Twine &Msg); |
100 | void warn(const Twine &Msg); |
101 | |
102 | std::unique_ptr<llvm::FileOutputBuffer> OutputBuffer; |
103 | |
104 | private: |
105 | void print(StringRef S, raw_ostream::Colors C); |
106 | }; |
107 | |
108 | /// Returns the default error handler. |
109 | ErrorHandler &errorHandler(); |
110 | |
111 | inline void error(const Twine &Msg) { errorHandler().error(Msg); } |
112 | inline LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) void fatal(const Twine &Msg) { |
113 | errorHandler().fatal(Msg); |
114 | } |
115 | inline void log(const Twine &Msg) { errorHandler().log(Msg); } |
116 | inline void message(const Twine &Msg) { errorHandler().message(Msg); } |
117 | inline void warn(const Twine &Msg) { errorHandler().warn(Msg); } |
118 | inline uint64_t errorCount() { return errorHandler().ErrorCount; } |
119 | |
120 | LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) void exitLld(int Val); |
121 | |
122 | void diagnosticHandler(const llvm::DiagnosticInfo &DI); |
123 | void checkError(Error E); |
124 | |
125 | // check functions are convenient functions to strip errors |
126 | // from error-or-value objects. |
127 | template <class T> T check(ErrorOr<T> E) { |
128 | if (auto EC = E.getError()) |
129 | fatal(EC.message()); |
130 | return std::move(*E); |
131 | } |
132 | |
133 | template <class T> T check(Expected<T> E) { |
134 | if (!E) |
135 | fatal(llvm::toString(E.takeError())); |
136 | return std::move(*E); |
137 | } |
138 | |
139 | template <class T> |
140 | T check2(ErrorOr<T> E, llvm::function_ref<std::string()> Prefix) { |
141 | if (auto EC = E.getError()) |
142 | fatal(Prefix() + ": " + EC.message()); |
143 | return std::move(*E); |
144 | } |
145 | |
146 | template <class T> |
147 | T check2(Expected<T> E, llvm::function_ref<std::string()> Prefix) { |
148 | if (!E) |
149 | fatal(Prefix() + ": " + toString(E.takeError())); |
150 | return std::move(*E); |
151 | } |
152 | |
153 | inline std::string toString(const Twine &S) { return S.str(); } |
154 | |
155 | // To evaluate the second argument lazily, we use C macro. |
156 | #define CHECK(E, S)check2((E), [&] { return toString(S); }) check2((E), [&] { return toString(S); }) |
157 | |
158 | } // namespace lld |
159 | |
160 | #endif |
1 | //===- llvm/Support/Error.h - Recoverable error handling --------*- C++ -*-===// | |||
2 | // | |||
3 | // The LLVM Compiler Infrastructure | |||
4 | // | |||
5 | // This file is distributed under the University of Illinois Open Source | |||
6 | // License. See LICENSE.TXT for details. | |||
7 | // | |||
8 | //===----------------------------------------------------------------------===// | |||
9 | // | |||
10 | // This file defines an API used to report recoverable errors. | |||
11 | // | |||
12 | //===----------------------------------------------------------------------===// | |||
13 | ||||
14 | #ifndef LLVM_SUPPORT_ERROR_H | |||
15 | #define LLVM_SUPPORT_ERROR_H | |||
16 | ||||
17 | #include "llvm-c/Error.h" | |||
18 | #include "llvm/ADT/STLExtras.h" | |||
19 | #include "llvm/ADT/SmallVector.h" | |||
20 | #include "llvm/ADT/StringExtras.h" | |||
21 | #include "llvm/ADT/Twine.h" | |||
22 | #include "llvm/Config/abi-breaking.h" | |||
23 | #include "llvm/Support/AlignOf.h" | |||
24 | #include "llvm/Support/Compiler.h" | |||
25 | #include "llvm/Support/Debug.h" | |||
26 | #include "llvm/Support/ErrorHandling.h" | |||
27 | #include "llvm/Support/ErrorOr.h" | |||
28 | #include "llvm/Support/Format.h" | |||
29 | #include "llvm/Support/raw_ostream.h" | |||
30 | #include <algorithm> | |||
31 | #include <cassert> | |||
32 | #include <cstdint> | |||
33 | #include <cstdlib> | |||
34 | #include <functional> | |||
35 | #include <memory> | |||
36 | #include <new> | |||
37 | #include <string> | |||
38 | #include <system_error> | |||
39 | #include <type_traits> | |||
40 | #include <utility> | |||
41 | #include <vector> | |||
42 | ||||
43 | namespace llvm { | |||
44 | ||||
45 | class ErrorSuccess; | |||
46 | ||||
47 | /// Base class for error info classes. Do not extend this directly: Extend | |||
48 | /// the ErrorInfo template subclass instead. | |||
49 | class ErrorInfoBase { | |||
50 | public: | |||
51 | virtual ~ErrorInfoBase() = default; | |||
52 | ||||
53 | /// Print an error message to an output stream. | |||
54 | virtual void log(raw_ostream &OS) const = 0; | |||
55 | ||||
56 | /// Return the error message as a string. | |||
57 | virtual std::string message() const { | |||
58 | std::string Msg; | |||
59 | raw_string_ostream OS(Msg); | |||
60 | log(OS); | |||
61 | return OS.str(); | |||
62 | } | |||
63 | ||||
64 | /// Convert this error to a std::error_code. | |||
65 | /// | |||
66 | /// This is a temporary crutch to enable interaction with code still | |||
67 | /// using std::error_code. It will be removed in the future. | |||
68 | virtual std::error_code convertToErrorCode() const = 0; | |||
69 | ||||
70 | // Returns the class ID for this type. | |||
71 | static const void *classID() { return &ID; } | |||
72 | ||||
73 | // Returns the class ID for the dynamic type of this ErrorInfoBase instance. | |||
74 | virtual const void *dynamicClassID() const = 0; | |||
75 | ||||
76 | // Check whether this instance is a subclass of the class identified by | |||
77 | // ClassID. | |||
78 | virtual bool isA(const void *const ClassID) const { | |||
79 | return ClassID == classID(); | |||
80 | } | |||
81 | ||||
82 | // Check whether this instance is a subclass of ErrorInfoT. | |||
83 | template <typename ErrorInfoT> bool isA() const { | |||
84 | return isA(ErrorInfoT::classID()); | |||
85 | } | |||
86 | ||||
87 | private: | |||
88 | virtual void anchor(); | |||
89 | ||||
90 | static char ID; | |||
91 | }; | |||
92 | ||||
93 | /// Lightweight error class with error context and mandatory checking. | |||
94 | /// | |||
95 | /// Instances of this class wrap a ErrorInfoBase pointer. Failure states | |||
96 | /// are represented by setting the pointer to a ErrorInfoBase subclass | |||
97 | /// instance containing information describing the failure. Success is | |||
98 | /// represented by a null pointer value. | |||
99 | /// | |||
100 | /// Instances of Error also contains a 'Checked' flag, which must be set | |||
101 | /// before the destructor is called, otherwise the destructor will trigger a | |||
102 | /// runtime error. This enforces at runtime the requirement that all Error | |||
103 | /// instances be checked or returned to the caller. | |||
104 | /// | |||
105 | /// There are two ways to set the checked flag, depending on what state the | |||
106 | /// Error instance is in. For Error instances indicating success, it | |||
107 | /// is sufficient to invoke the boolean conversion operator. E.g.: | |||
108 | /// | |||
109 | /// @code{.cpp} | |||
110 | /// Error foo(<...>); | |||
111 | /// | |||
112 | /// if (auto E = foo(<...>)) | |||
113 | /// return E; // <- Return E if it is in the error state. | |||
114 | /// // We have verified that E was in the success state. It can now be safely | |||
115 | /// // destroyed. | |||
116 | /// @endcode | |||
117 | /// | |||
118 | /// A success value *can not* be dropped. For example, just calling 'foo(<...>)' | |||
119 | /// without testing the return value will raise a runtime error, even if foo | |||
120 | /// returns success. | |||
121 | /// | |||
122 | /// For Error instances representing failure, you must use either the | |||
123 | /// handleErrors or handleAllErrors function with a typed handler. E.g.: | |||
124 | /// | |||
125 | /// @code{.cpp} | |||
126 | /// class MyErrorInfo : public ErrorInfo<MyErrorInfo> { | |||
127 | /// // Custom error info. | |||
128 | /// }; | |||
129 | /// | |||
130 | /// Error foo(<...>) { return make_error<MyErrorInfo>(...); } | |||
131 | /// | |||
132 | /// auto E = foo(<...>); // <- foo returns failure with MyErrorInfo. | |||
133 | /// auto NewE = | |||
134 | /// handleErrors(E, | |||
135 | /// [](const MyErrorInfo &M) { | |||
136 | /// // Deal with the error. | |||
137 | /// }, | |||
138 | /// [](std::unique_ptr<OtherError> M) -> Error { | |||
139 | /// if (canHandle(*M)) { | |||
140 | /// // handle error. | |||
141 | /// return Error::success(); | |||
142 | /// } | |||
143 | /// // Couldn't handle this error instance. Pass it up the stack. | |||
144 | /// return Error(std::move(M)); | |||
145 | /// ); | |||
146 | /// // Note - we must check or return NewE in case any of the handlers | |||
147 | /// // returned a new error. | |||
148 | /// @endcode | |||
149 | /// | |||
150 | /// The handleAllErrors function is identical to handleErrors, except | |||
151 | /// that it has a void return type, and requires all errors to be handled and | |||
152 | /// no new errors be returned. It prevents errors (assuming they can all be | |||
153 | /// handled) from having to be bubbled all the way to the top-level. | |||
154 | /// | |||
155 | /// *All* Error instances must be checked before destruction, even if | |||
156 | /// they're moved-assigned or constructed from Success values that have already | |||
157 | /// been checked. This enforces checking through all levels of the call stack. | |||
158 | class LLVM_NODISCARD[[clang::warn_unused_result]] Error { | |||
159 | // Both ErrorList and FileError need to be able to yank ErrorInfoBase | |||
160 | // pointers out of this class to add to the error list. | |||
161 | friend class ErrorList; | |||
162 | friend class FileError; | |||
163 | ||||
164 | // handleErrors needs to be able to set the Checked flag. | |||
165 | template <typename... HandlerTs> | |||
166 | friend Error handleErrors(Error E, HandlerTs &&... Handlers); | |||
167 | ||||
168 | // Expected<T> needs to be able to steal the payload when constructed from an | |||
169 | // error. | |||
170 | template <typename T> friend class Expected; | |||
171 | ||||
172 | // wrap needs to be able to steal the payload. | |||
173 | friend LLVMErrorRef wrap(Error); | |||
174 | ||||
175 | protected: | |||
176 | /// Create a success value. Prefer using 'Error::success()' for readability | |||
177 | Error() { | |||
178 | setPtr(nullptr); | |||
179 | setChecked(false); | |||
180 | } | |||
181 | ||||
182 | public: | |||
183 | /// Create a success value. | |||
184 | static ErrorSuccess success(); | |||
185 | ||||
186 | // Errors are not copy-constructable. | |||
187 | Error(const Error &Other) = delete; | |||
188 | ||||
189 | /// Move-construct an error value. The newly constructed error is considered | |||
190 | /// unchecked, even if the source error had been checked. The original error | |||
191 | /// becomes a checked Success value, regardless of its original state. | |||
192 | Error(Error &&Other) { | |||
193 | setChecked(true); | |||
194 | *this = std::move(Other); | |||
195 | } | |||
196 | ||||
197 | /// Create an error value. Prefer using the 'make_error' function, but | |||
198 | /// this constructor can be useful when "re-throwing" errors from handlers. | |||
199 | Error(std::unique_ptr<ErrorInfoBase> Payload) { | |||
200 | setPtr(Payload.release()); | |||
201 | setChecked(false); | |||
| ||||
202 | } | |||
203 | ||||
204 | // Errors are not copy-assignable. | |||
205 | Error &operator=(const Error &Other) = delete; | |||
206 | ||||
207 | /// Move-assign an error value. The current error must represent success, you | |||
208 | /// you cannot overwrite an unhandled error. The current error is then | |||
209 | /// considered unchecked. The source error becomes a checked success value, | |||
210 | /// regardless of its original state. | |||
211 | Error &operator=(Error &&Other) { | |||
212 | // Don't allow overwriting of unchecked values. | |||
213 | assertIsChecked(); | |||
214 | setPtr(Other.getPtr()); | |||
215 | ||||
216 | // This Error is unchecked, even if the source error was checked. | |||
217 | setChecked(false); | |||
218 | ||||
219 | // Null out Other's payload and set its checked bit. | |||
220 | Other.setPtr(nullptr); | |||
221 | Other.setChecked(true); | |||
222 | ||||
223 | return *this; | |||
224 | } | |||
225 | ||||
226 | /// Destroy a Error. Fails with a call to abort() if the error is | |||
227 | /// unchecked. | |||
228 | ~Error() { | |||
229 | assertIsChecked(); | |||
230 | delete getPtr(); | |||
231 | } | |||
232 | ||||
233 | /// Bool conversion. Returns true if this Error is in a failure state, | |||
234 | /// and false if it is in an accept state. If the error is in a Success state | |||
235 | /// it will be considered checked. | |||
236 | explicit operator bool() { | |||
237 | setChecked(getPtr() == nullptr); | |||
238 | return getPtr() != nullptr; | |||
239 | } | |||
240 | ||||
241 | /// Check whether one error is a subclass of another. | |||
242 | template <typename ErrT> bool isA() const { | |||
243 | return getPtr() && getPtr()->isA(ErrT::classID()); | |||
244 | } | |||
245 | ||||
246 | /// Returns the dynamic class id of this error, or null if this is a success | |||
247 | /// value. | |||
248 | const void* dynamicClassID() const { | |||
249 | if (!getPtr()) | |||
250 | return nullptr; | |||
251 | return getPtr()->dynamicClassID(); | |||
252 | } | |||
253 | ||||
254 | private: | |||
255 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 | |||
256 | // assertIsChecked() happens very frequently, but under normal circumstances | |||
257 | // is supposed to be a no-op. So we want it to be inlined, but having a bunch | |||
258 | // of debug prints can cause the function to be too large for inlining. So | |||
259 | // it's important that we define this function out of line so that it can't be | |||
260 | // inlined. | |||
261 | LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) | |||
262 | void fatalUncheckedError() const; | |||
263 | #endif | |||
264 | ||||
265 | void assertIsChecked() { | |||
266 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 | |||
267 | if (LLVM_UNLIKELY(!getChecked() || getPtr())__builtin_expect((bool)(!getChecked() || getPtr()), false)) | |||
268 | fatalUncheckedError(); | |||
269 | #endif | |||
270 | } | |||
271 | ||||
272 | ErrorInfoBase *getPtr() const { | |||
273 | return reinterpret_cast<ErrorInfoBase*>( | |||
274 | reinterpret_cast<uintptr_t>(Payload) & | |||
275 | ~static_cast<uintptr_t>(0x1)); | |||
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 | Payload = reinterpret_cast<ErrorInfoBase*>( | |||
299 | (reinterpret_cast<uintptr_t>(Payload) & | |||
300 | ~static_cast<uintptr_t>(0x1)) | | |||
301 | (V ? 0 : 1)); | |||
302 | } | |||
303 | ||||
304 | std::unique_ptr<ErrorInfoBase> takePayload() { | |||
305 | std::unique_ptr<ErrorInfoBase> Tmp(getPtr()); | |||
306 | setPtr(nullptr); | |||
307 | setChecked(true); | |||
308 | return Tmp; | |||
309 | } | |||
310 | ||||
311 | friend raw_ostream &operator<<(raw_ostream &OS, const Error &E) { | |||
312 | if (auto P = E.getPtr()) | |||
313 | P->log(OS); | |||
314 | else | |||
315 | OS << "success"; | |||
316 | return OS; | |||
317 | } | |||
318 | ||||
319 | ErrorInfoBase *Payload = nullptr; | |||
320 | }; | |||
321 | ||||
322 | /// Subclass of Error for the sole purpose of identifying the success path in | |||
323 | /// the type system. This allows to catch invalid conversion to Expected<T> at | |||
324 | /// compile time. | |||
325 | class ErrorSuccess final : public Error {}; | |||
326 | ||||
327 | inline ErrorSuccess Error::success() { return ErrorSuccess(); } | |||
328 | ||||
329 | /// Make a Error instance representing failure using the given error info | |||
330 | /// type. | |||
331 | template <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) { | |||
332 | return Error(llvm::make_unique<ErrT>(std::forward<ArgTs>(Args)...)); | |||
333 | } | |||
334 | ||||
335 | /// Base class for user error types. Users should declare their error types | |||
336 | /// like: | |||
337 | /// | |||
338 | /// class MyError : public ErrorInfo<MyError> { | |||
339 | /// .... | |||
340 | /// }; | |||
341 | /// | |||
342 | /// This class provides an implementation of the ErrorInfoBase::kind | |||
343 | /// method, which is used by the Error RTTI system. | |||
344 | template <typename ThisErrT, typename ParentErrT = ErrorInfoBase> | |||
345 | class ErrorInfo : public ParentErrT { | |||
346 | public: | |||
347 | using ParentErrT::ParentErrT; // inherit constructors | |||
348 | ||||
349 | static const void *classID() { return &ThisErrT::ID; } | |||
350 | ||||
351 | const void *dynamicClassID() const override { return &ThisErrT::ID; } | |||
352 | ||||
353 | bool isA(const void *const ClassID) const override { | |||
354 | return ClassID == classID() || ParentErrT::isA(ClassID); | |||
355 | } | |||
356 | }; | |||
357 | ||||
358 | /// Special ErrorInfo subclass representing a list of ErrorInfos. | |||
359 | /// Instances of this class are constructed by joinError. | |||
360 | class ErrorList final : public ErrorInfo<ErrorList> { | |||
361 | // handleErrors needs to be able to iterate the payload list of an | |||
362 | // ErrorList. | |||
363 | template <typename... HandlerTs> | |||
364 | friend Error handleErrors(Error E, HandlerTs &&... Handlers); | |||
365 | ||||
366 | // joinErrors is implemented in terms of join. | |||
367 | friend Error joinErrors(Error, Error); | |||
368 | ||||
369 | public: | |||
370 | void log(raw_ostream &OS) const override { | |||
371 | OS << "Multiple errors:\n"; | |||
372 | for (auto &ErrPayload : Payloads) { | |||
373 | ErrPayload->log(OS); | |||
374 | OS << "\n"; | |||
375 | } | |||
376 | } | |||
377 | ||||
378 | std::error_code convertToErrorCode() const override; | |||
379 | ||||
380 | // Used by ErrorInfo::classID. | |||
381 | static char ID; | |||
382 | ||||
383 | private: | |||
384 | ErrorList(std::unique_ptr<ErrorInfoBase> Payload1, | |||
385 | std::unique_ptr<ErrorInfoBase> Payload2) { | |||
386 | assert(!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() &&((!Payload1->isA<ErrorList>() && !Payload2-> isA<ErrorList>() && "ErrorList constructor payloads should be singleton errors" ) ? static_cast<void> (0) : __assert_fail ("!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() && \"ErrorList constructor payloads should be singleton errors\"" , "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h" , 387, __PRETTY_FUNCTION__)) | |||
387 | "ErrorList constructor payloads should be singleton errors")((!Payload1->isA<ErrorList>() && !Payload2-> isA<ErrorList>() && "ErrorList constructor payloads should be singleton errors" ) ? static_cast<void> (0) : __assert_fail ("!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() && \"ErrorList constructor payloads should be singleton errors\"" , "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h" , 387, __PRETTY_FUNCTION__)); | |||
388 | Payloads.push_back(std::move(Payload1)); | |||
389 | Payloads.push_back(std::move(Payload2)); | |||
390 | } | |||
391 | ||||
392 | static Error join(Error E1, Error E2) { | |||
393 | if (!E1) | |||
394 | return E2; | |||
395 | if (!E2) | |||
396 | return E1; | |||
397 | if (E1.isA<ErrorList>()) { | |||
398 | auto &E1List = static_cast<ErrorList &>(*E1.getPtr()); | |||
399 | if (E2.isA<ErrorList>()) { | |||
400 | auto E2Payload = E2.takePayload(); | |||
401 | auto &E2List = static_cast<ErrorList &>(*E2Payload); | |||
402 | for (auto &Payload : E2List.Payloads) | |||
403 | E1List.Payloads.push_back(std::move(Payload)); | |||
404 | } else | |||
405 | E1List.Payloads.push_back(E2.takePayload()); | |||
406 | ||||
407 | return E1; | |||
408 | } | |||
409 | if (E2.isA<ErrorList>()) { | |||
410 | auto &E2List = static_cast<ErrorList &>(*E2.getPtr()); | |||
411 | E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload()); | |||
412 | return E2; | |||
413 | } | |||
414 | return Error(std::unique_ptr<ErrorList>( | |||
415 | new ErrorList(E1.takePayload(), E2.takePayload()))); | |||
416 | } | |||
417 | ||||
418 | std::vector<std::unique_ptr<ErrorInfoBase>> Payloads; | |||
419 | }; | |||
420 | ||||
421 | /// Concatenate errors. The resulting Error is unchecked, and contains the | |||
422 | /// ErrorInfo(s), if any, contained in E1, followed by the | |||
423 | /// ErrorInfo(s), if any, contained in E2. | |||
424 | inline Error joinErrors(Error E1, Error E2) { | |||
425 | return ErrorList::join(std::move(E1), std::move(E2)); | |||
426 | } | |||
427 | ||||
428 | /// Tagged union holding either a T or a Error. | |||
429 | /// | |||
430 | /// This class parallels ErrorOr, but replaces error_code with Error. Since | |||
431 | /// Error cannot be copied, this class replaces getError() with | |||
432 | /// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the | |||
433 | /// error class type. | |||
434 | template <class T> class LLVM_NODISCARD[[clang::warn_unused_result]] Expected { | |||
435 | template <class T1> friend class ExpectedAsOutParameter; | |||
436 | template <class OtherT> friend class Expected; | |||
437 | ||||
438 | static const bool isRef = std::is_reference<T>::value; | |||
439 | ||||
440 | using wrap = std::reference_wrapper<typename std::remove_reference<T>::type>; | |||
441 | ||||
442 | using error_type = std::unique_ptr<ErrorInfoBase>; | |||
443 | ||||
444 | public: | |||
445 | using storage_type = typename std::conditional<isRef, wrap, T>::type; | |||
446 | using value_type = T; | |||
447 | ||||
448 | private: | |||
449 | using reference = typename std::remove_reference<T>::type &; | |||
450 | using const_reference = const typename std::remove_reference<T>::type &; | |||
451 | using pointer = typename std::remove_reference<T>::type *; | |||
452 | using const_pointer = const typename std::remove_reference<T>::type *; | |||
453 | ||||
454 | public: | |||
455 | /// Create an Expected<T> error value from the given Error. | |||
456 | Expected(Error Err) | |||
457 | : HasError(true) | |||
458 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 | |||
459 | // Expected is unchecked upon construction in Debug builds. | |||
460 | , Unchecked(true) | |||
461 | #endif | |||
462 | { | |||
463 | assert(Err && "Cannot create Expected<T> from Error success value.")((Err && "Cannot create Expected<T> from Error success value." ) ? static_cast<void> (0) : __assert_fail ("Err && \"Cannot create Expected<T> from Error success value.\"" , "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h" , 463, __PRETTY_FUNCTION__)); | |||
464 | new (getErrorStorage()) error_type(Err.takePayload()); | |||
465 | } | |||
466 | ||||
467 | /// Forbid to convert from Error::success() implicitly, this avoids having | |||
468 | /// Expected<T> foo() { return Error::success(); } which compiles otherwise | |||
469 | /// but triggers the assertion above. | |||
470 | Expected(ErrorSuccess) = delete; | |||
471 | ||||
472 | /// Create an Expected<T> success value from the given OtherT value, which | |||
473 | /// must be convertible to T. | |||
474 | template <typename OtherT> | |||
475 | Expected(OtherT &&Val, | |||
476 | typename std::enable_if<std::is_convertible<OtherT, T>::value>::type | |||
477 | * = nullptr) | |||
478 | : HasError(false) | |||
479 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 | |||
480 | // Expected is unchecked upon construction in Debug builds. | |||
481 | , Unchecked(true) | |||
482 | #endif | |||
483 | { | |||
484 | new (getStorage()) storage_type(std::forward<OtherT>(Val)); | |||
485 | } | |||
486 | ||||
487 | /// Move construct an Expected<T> value. | |||
488 | Expected(Expected &&Other) { moveConstruct(std::move(Other)); } | |||
489 | ||||
490 | /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT | |||
491 | /// must be convertible to T. | |||
492 | template <class OtherT> | |||
493 | Expected(Expected<OtherT> &&Other, | |||
494 | typename std::enable_if<std::is_convertible<OtherT, T>::value>::type | |||
495 | * = nullptr) { | |||
496 | moveConstruct(std::move(Other)); | |||
497 | } | |||
498 | ||||
499 | /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT | |||
500 | /// isn't convertible to T. | |||
501 | template <class OtherT> | |||
502 | explicit Expected( | |||
503 | Expected<OtherT> &&Other, | |||
504 | typename std::enable_if<!std::is_convertible<OtherT, T>::value>::type * = | |||
505 | nullptr) { | |||
506 | moveConstruct(std::move(Other)); | |||
507 | } | |||
508 | ||||
509 | /// Move-assign from another Expected<T>. | |||
510 | Expected &operator=(Expected &&Other) { | |||
511 | moveAssign(std::move(Other)); | |||
512 | return *this; | |||
513 | } | |||
514 | ||||
515 | /// Destroy an Expected<T>. | |||
516 | ~Expected() { | |||
517 | assertIsChecked(); | |||
518 | if (!HasError) | |||
519 | getStorage()->~storage_type(); | |||
520 | else | |||
521 | getErrorStorage()->~error_type(); | |||
522 | } | |||
523 | ||||
524 | /// Return false if there is an error. | |||
525 | explicit operator bool() { | |||
526 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 | |||
527 | Unchecked = HasError; | |||
528 | #endif | |||
529 | return !HasError; | |||
530 | } | |||
531 | ||||
532 | /// Returns a reference to the stored T value. | |||
533 | reference get() { | |||
534 | assertIsChecked(); | |||
535 | return *getStorage(); | |||
536 | } | |||
537 | ||||
538 | /// Returns a const reference to the stored T value. | |||
539 | const_reference get() const { | |||
540 | assertIsChecked(); | |||
541 | return const_cast<Expected<T> *>(this)->get(); | |||
542 | } | |||
543 | ||||
544 | /// Check that this Expected<T> is an error of type ErrT. | |||
545 | template <typename ErrT> bool errorIsA() const { | |||
546 | return HasError && (*getErrorStorage())->template isA<ErrT>(); | |||
547 | } | |||
548 | ||||
549 | /// Take ownership of the stored error. | |||
550 | /// After calling this the Expected<T> is in an indeterminate state that can | |||
551 | /// only be safely destructed. No further calls (beside the destructor) should | |||
552 | /// be made on the Expected<T> vaule. | |||
553 | Error takeError() { | |||
554 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 | |||
555 | Unchecked = false; | |||
556 | #endif | |||
557 | return HasError ? Error(std::move(*getErrorStorage())) : Error::success(); | |||
558 | } | |||
559 | ||||
560 | /// Returns a pointer to the stored T value. | |||
561 | pointer operator->() { | |||
562 | assertIsChecked(); | |||
563 | return toPointer(getStorage()); | |||
564 | } | |||
565 | ||||
566 | /// Returns a const pointer to the stored T value. | |||
567 | const_pointer operator->() const { | |||
568 | assertIsChecked(); | |||
569 | return toPointer(getStorage()); | |||
570 | } | |||
571 | ||||
572 | /// Returns a reference to the stored T value. | |||
573 | reference operator*() { | |||
574 | assertIsChecked(); | |||
575 | return *getStorage(); | |||
576 | } | |||
577 | ||||
578 | /// Returns a const reference to the stored T value. | |||
579 | const_reference operator*() const { | |||
580 | assertIsChecked(); | |||
581 | return *getStorage(); | |||
582 | } | |||
583 | ||||
584 | private: | |||
585 | template <class T1> | |||
586 | static bool compareThisIfSameType(const T1 &a, const T1 &b) { | |||
587 | return &a == &b; | |||
588 | } | |||
589 | ||||
590 | template <class T1, class T2> | |||
591 | static bool compareThisIfSameType(const T1 &a, const T2 &b) { | |||
592 | return false; | |||
593 | } | |||
594 | ||||
595 | template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) { | |||
596 | HasError = Other.HasError; | |||
597 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 | |||
598 | Unchecked = true; | |||
599 | Other.Unchecked = false; | |||
600 | #endif | |||
601 | ||||
602 | if (!HasError) | |||
603 | new (getStorage()) storage_type(std::move(*Other.getStorage())); | |||
604 | else | |||
605 | new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage())); | |||
606 | } | |||
607 | ||||
608 | template <class OtherT> void moveAssign(Expected<OtherT> &&Other) { | |||
609 | assertIsChecked(); | |||
610 | ||||
611 | if (compareThisIfSameType(*this, Other)) | |||
612 | return; | |||
613 | ||||
614 | this->~Expected(); | |||
615 | new (this) Expected(std::move(Other)); | |||
616 | } | |||
617 | ||||
618 | pointer toPointer(pointer Val) { return Val; } | |||
619 | ||||
620 | const_pointer toPointer(const_pointer Val) const { return Val; } | |||
621 | ||||
622 | pointer toPointer(wrap *Val) { return &Val->get(); } | |||
623 | ||||
624 | const_pointer toPointer(const wrap *Val) const { return &Val->get(); } | |||
625 | ||||
626 | storage_type *getStorage() { | |||
627 | assert(!HasError && "Cannot get value when an error exists!")((!HasError && "Cannot get value when an error exists!" ) ? static_cast<void> (0) : __assert_fail ("!HasError && \"Cannot get value when an error exists!\"" , "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h" , 627, __PRETTY_FUNCTION__)); | |||
628 | return reinterpret_cast<storage_type *>(TStorage.buffer); | |||
629 | } | |||
630 | ||||
631 | const storage_type *getStorage() const { | |||
632 | assert(!HasError && "Cannot get value when an error exists!")((!HasError && "Cannot get value when an error exists!" ) ? static_cast<void> (0) : __assert_fail ("!HasError && \"Cannot get value when an error exists!\"" , "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h" , 632, __PRETTY_FUNCTION__)); | |||
633 | return reinterpret_cast<const storage_type *>(TStorage.buffer); | |||
634 | } | |||
635 | ||||
636 | error_type *getErrorStorage() { | |||
637 | assert(HasError && "Cannot get error when a value exists!")((HasError && "Cannot get error when a value exists!" ) ? static_cast<void> (0) : __assert_fail ("HasError && \"Cannot get error when a value exists!\"" , "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h" , 637, __PRETTY_FUNCTION__)); | |||
638 | return reinterpret_cast<error_type *>(ErrorStorage.buffer); | |||
639 | } | |||
640 | ||||
641 | const error_type *getErrorStorage() const { | |||
642 | assert(HasError && "Cannot get error when a value exists!")((HasError && "Cannot get error when a value exists!" ) ? static_cast<void> (0) : __assert_fail ("HasError && \"Cannot get error when a value exists!\"" , "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h" , 642, __PRETTY_FUNCTION__)); | |||
643 | return reinterpret_cast<const error_type *>(ErrorStorage.buffer); | |||
644 | } | |||
645 | ||||
646 | // Used by ExpectedAsOutParameter to reset the checked flag. | |||
647 | void setUnchecked() { | |||
648 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 | |||
649 | Unchecked = true; | |||
650 | #endif | |||
651 | } | |||
652 | ||||
653 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 | |||
654 | LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) | |||
655 | LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) | |||
656 | void fatalUncheckedExpected() const { | |||
657 | dbgs() << "Expected<T> must be checked before access or destruction.\n"; | |||
658 | if (HasError) { | |||
659 | dbgs() << "Unchecked Expected<T> contained error:\n"; | |||
660 | (*getErrorStorage())->log(dbgs()); | |||
661 | } else | |||
662 | dbgs() << "Expected<T> value was in success state. (Note: Expected<T> " | |||
663 | "values in success mode must still be checked prior to being " | |||
664 | "destroyed).\n"; | |||
665 | abort(); | |||
666 | } | |||
667 | #endif | |||
668 | ||||
669 | void assertIsChecked() { | |||
670 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 | |||
671 | if (LLVM_UNLIKELY(Unchecked)__builtin_expect((bool)(Unchecked), false)) | |||
672 | fatalUncheckedExpected(); | |||
673 | #endif | |||
674 | } | |||
675 | ||||
676 | union { | |||
677 | AlignedCharArrayUnion<storage_type> TStorage; | |||
678 | AlignedCharArrayUnion<error_type> ErrorStorage; | |||
679 | }; | |||
680 | bool HasError : 1; | |||
681 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 | |||
682 | bool Unchecked : 1; | |||
683 | #endif | |||
684 | }; | |||
685 | ||||
686 | /// Report a serious error, calling any installed error handler. See | |||
687 | /// ErrorHandling.h. | |||
688 | LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) void report_fatal_error(Error Err, | |||
689 | bool gen_crash_diag = true); | |||
690 | ||||
691 | /// Report a fatal error if Err is a failure value. | |||
692 | /// | |||
693 | /// This function can be used to wrap calls to fallible functions ONLY when it | |||
694 | /// is known that the Error will always be a success value. E.g. | |||
695 | /// | |||
696 | /// @code{.cpp} | |||
697 | /// // foo only attempts the fallible operation if DoFallibleOperation is | |||
698 | /// // true. If DoFallibleOperation is false then foo always returns | |||
699 | /// // Error::success(). | |||
700 | /// Error foo(bool DoFallibleOperation); | |||
701 | /// | |||
702 | /// cantFail(foo(false)); | |||
703 | /// @endcode | |||
704 | inline void cantFail(Error Err, const char *Msg = nullptr) { | |||
705 | if (Err) { | |||
706 | if (!Msg) | |||
707 | Msg = "Failure value returned from cantFail wrapped call"; | |||
708 | llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h" , 708); | |||
709 | } | |||
710 | } | |||
711 | ||||
712 | /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and | |||
713 | /// returns the contained value. | |||
714 | /// | |||
715 | /// This function can be used to wrap calls to fallible functions ONLY when it | |||
716 | /// is known that the Error will always be a success value. E.g. | |||
717 | /// | |||
718 | /// @code{.cpp} | |||
719 | /// // foo only attempts the fallible operation if DoFallibleOperation is | |||
720 | /// // true. If DoFallibleOperation is false then foo always returns an int. | |||
721 | /// Expected<int> foo(bool DoFallibleOperation); | |||
722 | /// | |||
723 | /// int X = cantFail(foo(false)); | |||
724 | /// @endcode | |||
725 | template <typename T> | |||
726 | T cantFail(Expected<T> ValOrErr, const char *Msg = nullptr) { | |||
727 | if (ValOrErr) | |||
728 | return std::move(*ValOrErr); | |||
729 | else { | |||
730 | if (!Msg) | |||
731 | Msg = "Failure value returned from cantFail wrapped call"; | |||
732 | llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h" , 732); | |||
733 | } | |||
734 | } | |||
735 | ||||
736 | /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and | |||
737 | /// returns the contained reference. | |||
738 | /// | |||
739 | /// This function can be used to wrap calls to fallible functions ONLY when it | |||
740 | /// is known that the Error will always be a success value. E.g. | |||
741 | /// | |||
742 | /// @code{.cpp} | |||
743 | /// // foo only attempts the fallible operation if DoFallibleOperation is | |||
744 | /// // true. If DoFallibleOperation is false then foo always returns a Bar&. | |||
745 | /// Expected<Bar&> foo(bool DoFallibleOperation); | |||
746 | /// | |||
747 | /// Bar &X = cantFail(foo(false)); | |||
748 | /// @endcode | |||
749 | template <typename T> | |||
750 | T& cantFail(Expected<T&> ValOrErr, const char *Msg = nullptr) { | |||
751 | if (ValOrErr) | |||
752 | return *ValOrErr; | |||
753 | else { | |||
754 | if (!Msg) | |||
755 | Msg = "Failure value returned from cantFail wrapped call"; | |||
756 | llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h" , 756); | |||
757 | } | |||
758 | } | |||
759 | ||||
760 | /// Helper for testing applicability of, and applying, handlers for | |||
761 | /// ErrorInfo types. | |||
762 | template <typename HandlerT> | |||
763 | class ErrorHandlerTraits | |||
764 | : public ErrorHandlerTraits<decltype( | |||
765 | &std::remove_reference<HandlerT>::type::operator())> {}; | |||
766 | ||||
767 | // Specialization functions of the form 'Error (const ErrT&)'. | |||
768 | template <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> { | |||
769 | public: | |||
770 | static bool appliesTo(const ErrorInfoBase &E) { | |||
771 | return E.template isA<ErrT>(); | |||
772 | } | |||
773 | ||||
774 | template <typename HandlerT> | |||
775 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { | |||
776 | assert(appliesTo(*E) && "Applying incorrect handler")((appliesTo(*E) && "Applying incorrect handler") ? static_cast <void> (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\"" , "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h" , 776, __PRETTY_FUNCTION__)); | |||
777 | return H(static_cast<ErrT &>(*E)); | |||
778 | } | |||
779 | }; | |||
780 | ||||
781 | // Specialization functions of the form 'void (const ErrT&)'. | |||
782 | template <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> { | |||
783 | public: | |||
784 | static bool appliesTo(const ErrorInfoBase &E) { | |||
785 | return E.template isA<ErrT>(); | |||
786 | } | |||
787 | ||||
788 | template <typename HandlerT> | |||
789 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { | |||
790 | assert(appliesTo(*E) && "Applying incorrect handler")((appliesTo(*E) && "Applying incorrect handler") ? static_cast <void> (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\"" , "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h" , 790, __PRETTY_FUNCTION__)); | |||
791 | H(static_cast<ErrT &>(*E)); | |||
792 | return Error::success(); | |||
793 | } | |||
794 | }; | |||
795 | ||||
796 | /// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'. | |||
797 | template <typename ErrT> | |||
798 | class ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> { | |||
799 | public: | |||
800 | static bool appliesTo(const ErrorInfoBase &E) { | |||
801 | return E.template isA<ErrT>(); | |||
802 | } | |||
803 | ||||
804 | template <typename HandlerT> | |||
805 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { | |||
806 | assert(appliesTo(*E) && "Applying incorrect handler")((appliesTo(*E) && "Applying incorrect handler") ? static_cast <void> (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\"" , "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h" , 806, __PRETTY_FUNCTION__)); | |||
807 | std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release())); | |||
808 | return H(std::move(SubE)); | |||
809 | } | |||
810 | }; | |||
811 | ||||
812 | /// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'. | |||
813 | template <typename ErrT> | |||
814 | class ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> { | |||
815 | public: | |||
816 | static bool appliesTo(const ErrorInfoBase &E) { | |||
817 | return E.template isA<ErrT>(); | |||
818 | } | |||
819 | ||||
820 | template <typename HandlerT> | |||
821 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { | |||
822 | assert(appliesTo(*E) && "Applying incorrect handler")((appliesTo(*E) && "Applying incorrect handler") ? static_cast <void> (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\"" , "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h" , 822, __PRETTY_FUNCTION__)); | |||
823 | std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release())); | |||
824 | H(std::move(SubE)); | |||
825 | return Error::success(); | |||
826 | } | |||
827 | }; | |||
828 | ||||
829 | // Specialization for member functions of the form 'RetT (const ErrT&)'. | |||
830 | template <typename C, typename RetT, typename ErrT> | |||
831 | class ErrorHandlerTraits<RetT (C::*)(ErrT &)> | |||
832 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; | |||
833 | ||||
834 | // Specialization for member functions of the form 'RetT (const ErrT&) const'. | |||
835 | template <typename C, typename RetT, typename ErrT> | |||
836 | class ErrorHandlerTraits<RetT (C::*)(ErrT &) const> | |||
837 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; | |||
838 | ||||
839 | // Specialization for member functions of the form 'RetT (const ErrT&)'. | |||
840 | template <typename C, typename RetT, typename ErrT> | |||
841 | class ErrorHandlerTraits<RetT (C::*)(const ErrT &)> | |||
842 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; | |||
843 | ||||
844 | // Specialization for member functions of the form 'RetT (const ErrT&) const'. | |||
845 | template <typename C, typename RetT, typename ErrT> | |||
846 | class ErrorHandlerTraits<RetT (C::*)(const ErrT &) const> | |||
847 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; | |||
848 | ||||
849 | /// Specialization for member functions of the form | |||
850 | /// 'RetT (std::unique_ptr<ErrT>)'. | |||
851 | template <typename C, typename RetT, typename ErrT> | |||
852 | class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>)> | |||
853 | : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {}; | |||
854 | ||||
855 | /// Specialization for member functions of the form | |||
856 | /// 'RetT (std::unique_ptr<ErrT>) const'. | |||
857 | template <typename C, typename RetT, typename ErrT> | |||
858 | class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>) const> | |||
859 | : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {}; | |||
860 | ||||
861 | inline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) { | |||
862 | return Error(std::move(Payload)); | |||
863 | } | |||
864 | ||||
865 | template <typename HandlerT, typename... HandlerTs> | |||
866 | Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload, | |||
867 | HandlerT &&Handler, HandlerTs &&... Handlers) { | |||
868 | if (ErrorHandlerTraits<HandlerT>::appliesTo(*Payload)) | |||
869 | return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler), | |||
870 | std::move(Payload)); | |||
871 | return handleErrorImpl(std::move(Payload), | |||
872 | std::forward<HandlerTs>(Handlers)...); | |||
873 | } | |||
874 | ||||
875 | /// Pass the ErrorInfo(s) contained in E to their respective handlers. Any | |||
876 | /// unhandled errors (or Errors returned by handlers) are re-concatenated and | |||
877 | /// returned. | |||
878 | /// Because this function returns an error, its result must also be checked | |||
879 | /// or returned. If you intend to handle all errors use handleAllErrors | |||
880 | /// (which returns void, and will abort() on unhandled errors) instead. | |||
881 | template <typename... HandlerTs> | |||
882 | Error handleErrors(Error E, HandlerTs &&... Hs) { | |||
883 | if (!E) | |||
884 | return Error::success(); | |||
885 | ||||
886 | std::unique_ptr<ErrorInfoBase> Payload = E.takePayload(); | |||
887 | ||||
888 | if (Payload->isA<ErrorList>()) { | |||
889 | ErrorList &List = static_cast<ErrorList &>(*Payload); | |||
890 | Error R; | |||
891 | for (auto &P : List.Payloads) | |||
892 | R = ErrorList::join( | |||
893 | std::move(R), | |||
894 | handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...)); | |||
895 | return R; | |||
896 | } | |||
897 | ||||
898 | return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...); | |||
899 | } | |||
900 | ||||
901 | /// Behaves the same as handleErrors, except that by contract all errors | |||
902 | /// *must* be handled by the given handlers (i.e. there must be no remaining | |||
903 | /// errors after running the handlers, or llvm_unreachable is called). | |||
904 | template <typename... HandlerTs> | |||
905 | void handleAllErrors(Error E, HandlerTs &&... Handlers) { | |||
906 | cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...)); | |||
907 | } | |||
908 | ||||
909 | /// Check that E is a non-error, then drop it. | |||
910 | /// If E is an error, llvm_unreachable will be called. | |||
911 | inline void handleAllErrors(Error E) { | |||
912 | cantFail(std::move(E)); | |||
913 | } | |||
914 | ||||
915 | /// Handle any errors (if present) in an Expected<T>, then try a recovery path. | |||
916 | /// | |||
917 | /// If the incoming value is a success value it is returned unmodified. If it | |||
918 | /// is a failure value then it the contained error is passed to handleErrors. | |||
919 | /// If handleErrors is able to handle the error then the RecoveryPath functor | |||
920 | /// is called to supply the final result. If handleErrors is not able to | |||
921 | /// handle all errors then the unhandled errors are returned. | |||
922 | /// | |||
923 | /// This utility enables the follow pattern: | |||
924 | /// | |||
925 | /// @code{.cpp} | |||
926 | /// enum FooStrategy { Aggressive, Conservative }; | |||
927 | /// Expected<Foo> foo(FooStrategy S); | |||
928 | /// | |||
929 | /// auto ResultOrErr = | |||
930 | /// handleExpected( | |||
931 | /// foo(Aggressive), | |||
932 | /// []() { return foo(Conservative); }, | |||
933 | /// [](AggressiveStrategyError&) { | |||
934 | /// // Implicitly conusme this - we'll recover by using a conservative | |||
935 | /// // strategy. | |||
936 | /// }); | |||
937 | /// | |||
938 | /// @endcode | |||
939 | template <typename T, typename RecoveryFtor, typename... HandlerTs> | |||
940 | Expected<T> handleExpected(Expected<T> ValOrErr, RecoveryFtor &&RecoveryPath, | |||
941 | HandlerTs &&... Handlers) { | |||
942 | if (ValOrErr) | |||
943 | return ValOrErr; | |||
944 | ||||
945 | if (auto Err = handleErrors(ValOrErr.takeError(), | |||
946 | std::forward<HandlerTs>(Handlers)...)) | |||
947 | return std::move(Err); | |||
948 | ||||
949 | return RecoveryPath(); | |||
950 | } | |||
951 | ||||
952 | /// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner | |||
953 | /// will be printed before the first one is logged. A newline will be printed | |||
954 | /// after each error. | |||
955 | /// | |||
956 | /// This is useful in the base level of your program to allow clean termination | |||
957 | /// (allowing clean deallocation of resources, etc.), while reporting error | |||
958 | /// information to the user. | |||
959 | void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner); | |||
960 | ||||
961 | /// Write all error messages (if any) in E to a string. The newline character | |||
962 | /// is used to separate error messages. | |||
963 | inline std::string toString(Error E) { | |||
964 | SmallVector<std::string, 2> Errors; | |||
965 | handleAllErrors(std::move(E), [&Errors](const ErrorInfoBase &EI) { | |||
966 | Errors.push_back(EI.message()); | |||
967 | }); | |||
968 | return join(Errors.begin(), Errors.end(), "\n"); | |||
969 | } | |||
970 | ||||
971 | /// Consume a Error without doing anything. This method should be used | |||
972 | /// only where an error can be considered a reasonable and expected return | |||
973 | /// value. | |||
974 | /// | |||
975 | /// Uses of this method are potentially indicative of design problems: If it's | |||
976 | /// legitimate to do nothing while processing an "error", the error-producer | |||
977 | /// might be more clearly refactored to return an Optional<T>. | |||
978 | inline void consumeError(Error Err) { | |||
979 | handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {}); | |||
980 | } | |||
981 | ||||
982 | /// Helper for converting an Error to a bool. | |||
983 | /// | |||
984 | /// This method returns true if Err is in an error state, or false if it is | |||
985 | /// in a success state. Puts Err in a checked state in both cases (unlike | |||
986 | /// Error::operator bool(), which only does this for success states). | |||
987 | inline bool errorToBool(Error Err) { | |||
988 | bool IsError = static_cast<bool>(Err); | |||
989 | if (IsError) | |||
990 | consumeError(std::move(Err)); | |||
991 | return IsError; | |||
992 | } | |||
993 | ||||
994 | /// Helper for Errors used as out-parameters. | |||
995 | /// | |||
996 | /// This helper is for use with the Error-as-out-parameter idiom, where an error | |||
997 | /// is passed to a function or method by reference, rather than being returned. | |||
998 | /// In such cases it is helpful to set the checked bit on entry to the function | |||
999 | /// so that the error can be written to (unchecked Errors abort on assignment) | |||
1000 | /// and clear the checked bit on exit so that clients cannot accidentally forget | |||
1001 | /// to check the result. This helper performs these actions automatically using | |||
1002 | /// RAII: | |||
1003 | /// | |||
1004 | /// @code{.cpp} | |||
1005 | /// Result foo(Error &Err) { | |||
1006 | /// ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set | |||
1007 | /// // <body of foo> | |||
1008 | /// // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed. | |||
1009 | /// } | |||
1010 | /// @endcode | |||
1011 | /// | |||
1012 | /// ErrorAsOutParameter takes an Error* rather than Error& so that it can be | |||
1013 | /// used with optional Errors (Error pointers that are allowed to be null). If | |||
1014 | /// ErrorAsOutParameter took an Error reference, an instance would have to be | |||
1015 | /// created inside every condition that verified that Error was non-null. By | |||
1016 | /// taking an Error pointer we can just create one instance at the top of the | |||
1017 | /// function. | |||
1018 | class ErrorAsOutParameter { | |||
1019 | public: | |||
1020 | ErrorAsOutParameter(Error *Err) : Err(Err) { | |||
1021 | // Raise the checked bit if Err is success. | |||
1022 | if (Err) | |||
1023 | (void)!!*Err; | |||
1024 | } | |||
1025 | ||||
1026 | ~ErrorAsOutParameter() { | |||
1027 | // Clear the checked bit. | |||
1028 | if (Err && !*Err) | |||
1029 | *Err = Error::success(); | |||
1030 | } | |||
1031 | ||||
1032 | private: | |||
1033 | Error *Err; | |||
1034 | }; | |||
1035 | ||||
1036 | /// Helper for Expected<T>s used as out-parameters. | |||
1037 | /// | |||
1038 | /// See ErrorAsOutParameter. | |||
1039 | template <typename T> | |||
1040 | class ExpectedAsOutParameter { | |||
1041 | public: | |||
1042 | ExpectedAsOutParameter(Expected<T> *ValOrErr) | |||
1043 | : ValOrErr(ValOrErr) { | |||
1044 | if (ValOrErr) | |||
1045 | (void)!!*ValOrErr; | |||
1046 | } | |||
1047 | ||||
1048 | ~ExpectedAsOutParameter() { | |||
1049 | if (ValOrErr) | |||
1050 | ValOrErr->setUnchecked(); | |||
1051 | } | |||
1052 | ||||
1053 | private: | |||
1054 | Expected<T> *ValOrErr; | |||
1055 | }; | |||
1056 | ||||
1057 | /// This class wraps a std::error_code in a Error. | |||
1058 | /// | |||
1059 | /// This is useful if you're writing an interface that returns a Error | |||
1060 | /// (or Expected) and you want to call code that still returns | |||
1061 | /// std::error_codes. | |||
1062 | class ECError : public ErrorInfo<ECError> { | |||
1063 | friend Error errorCodeToError(std::error_code); | |||
1064 | ||||
1065 | public: | |||
1066 | void setErrorCode(std::error_code EC) { this->EC = EC; } | |||
1067 | std::error_code convertToErrorCode() const override { return EC; } | |||
1068 | void log(raw_ostream &OS) const override { OS << EC.message(); } | |||
1069 | ||||
1070 | // Used by ErrorInfo::classID. | |||
1071 | static char ID; | |||
1072 | ||||
1073 | protected: | |||
1074 | ECError() = default; | |||
1075 | ECError(std::error_code EC) : EC(EC) {} | |||
1076 | ||||
1077 | std::error_code EC; | |||
1078 | }; | |||
1079 | ||||
1080 | /// The value returned by this function can be returned from convertToErrorCode | |||
1081 | /// for Error values where no sensible translation to std::error_code exists. | |||
1082 | /// It should only be used in this situation, and should never be used where a | |||
1083 | /// sensible conversion to std::error_code is available, as attempts to convert | |||
1084 | /// to/from this error will result in a fatal error. (i.e. it is a programmatic | |||
1085 | ///error to try to convert such a value). | |||
1086 | std::error_code inconvertibleErrorCode(); | |||
1087 | ||||
1088 | /// Helper for converting an std::error_code to a Error. | |||
1089 | Error errorCodeToError(std::error_code EC); | |||
1090 | ||||
1091 | /// Helper for converting an ECError to a std::error_code. | |||
1092 | /// | |||
1093 | /// This method requires that Err be Error() or an ECError, otherwise it | |||
1094 | /// will trigger a call to abort(). | |||
1095 | std::error_code errorToErrorCode(Error Err); | |||
1096 | ||||
1097 | /// Convert an ErrorOr<T> to an Expected<T>. | |||
1098 | template <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) { | |||
1099 | if (auto EC = EO.getError()) | |||
1100 | return errorCodeToError(EC); | |||
1101 | return std::move(*EO); | |||
1102 | } | |||
1103 | ||||
1104 | /// Convert an Expected<T> to an ErrorOr<T>. | |||
1105 | template <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) { | |||
1106 | if (auto Err = E.takeError()) | |||
1107 | return errorToErrorCode(std::move(Err)); | |||
1108 | return std::move(*E); | |||
1109 | } | |||
1110 | ||||
1111 | /// This class wraps a string in an Error. | |||
1112 | /// | |||
1113 | /// StringError is useful in cases where the client is not expected to be able | |||
1114 | /// to consume the specific error message programmatically (for example, if the | |||
1115 | /// error message is to be presented to the user). | |||
1116 | /// | |||
1117 | /// StringError can also be used when additional information is to be printed | |||
1118 | /// along with a error_code message. Depending on the constructor called, this | |||
1119 | /// class can either display: | |||
1120 | /// 1. the error_code message (ECError behavior) | |||
1121 | /// 2. a string | |||
1122 | /// 3. the error_code message and a string | |||
1123 | /// | |||
1124 | /// These behaviors are useful when subtyping is required; for example, when a | |||
1125 | /// specific library needs an explicit error type. In the example below, | |||
1126 | /// PDBError is derived from StringError: | |||
1127 | /// | |||
1128 | /// @code{.cpp} | |||
1129 | /// Expected<int> foo() { | |||
1130 | /// return llvm::make_error<PDBError>(pdb_error_code::dia_failed_loading, | |||
1131 | /// "Additional information"); | |||
1132 | /// } | |||
1133 | /// @endcode | |||
1134 | /// | |||
1135 | class StringError : public ErrorInfo<StringError> { | |||
1136 | public: | |||
1137 | static char ID; | |||
1138 | ||||
1139 | // Prints EC + S and converts to EC | |||
1140 | StringError(std::error_code EC, const Twine &S = Twine()); | |||
1141 | ||||
1142 | // Prints S and converts to EC | |||
1143 | StringError(const Twine &S, std::error_code EC); | |||
1144 | ||||
1145 | void log(raw_ostream &OS) const override; | |||
1146 | std::error_code convertToErrorCode() const override; | |||
1147 | ||||
1148 | const std::string &getMessage() const { return Msg; } | |||
1149 | ||||
1150 | private: | |||
1151 | std::string Msg; | |||
1152 | std::error_code EC; | |||
1153 | const bool PrintMsgOnly = false; | |||
1154 | }; | |||
1155 | ||||
1156 | /// Create formatted StringError object. | |||
1157 | template <typename... Ts> | |||
1158 | Error createStringError(std::error_code EC, char const *Fmt, | |||
1159 | const Ts &... Vals) { | |||
1160 | std::string Buffer; | |||
1161 | raw_string_ostream Stream(Buffer); | |||
1162 | Stream << format(Fmt, Vals...); | |||
1163 | return make_error<StringError>(Stream.str(), EC); | |||
1164 | } | |||
1165 | ||||
1166 | Error createStringError(std::error_code EC, char const *Msg); | |||
1167 | ||||
1168 | /// This class wraps a filename and another Error. | |||
1169 | /// | |||
1170 | /// In some cases, an error needs to live along a 'source' name, in order to | |||
1171 | /// show more detailed information to the user. | |||
1172 | class FileError final : public ErrorInfo<FileError> { | |||
1173 | ||||
1174 | friend Error createFileError(std::string, Error); | |||
1175 | ||||
1176 | public: | |||
1177 | void log(raw_ostream &OS) const override { | |||
1178 | assert(Err && !FileName.empty() && "Trying to log after takeError().")((Err && !FileName.empty() && "Trying to log after takeError()." ) ? static_cast<void> (0) : __assert_fail ("Err && !FileName.empty() && \"Trying to log after takeError().\"" , "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h" , 1178, __PRETTY_FUNCTION__)); | |||
1179 | OS << "'" << FileName << "': "; | |||
1180 | Err->log(OS); | |||
1181 | } | |||
1182 | ||||
1183 | Error takeError() { return Error(std::move(Err)); } | |||
1184 | ||||
1185 | std::error_code convertToErrorCode() const override; | |||
1186 | ||||
1187 | // Used by ErrorInfo::classID. | |||
1188 | static char ID; | |||
1189 | ||||
1190 | private: | |||
1191 | FileError(std::string F, std::unique_ptr<ErrorInfoBase> E) { | |||
1192 | assert(E && "Cannot create FileError from Error success value.")((E && "Cannot create FileError from Error success value." ) ? static_cast<void> (0) : __assert_fail ("E && \"Cannot create FileError from Error success value.\"" , "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h" , 1192, __PRETTY_FUNCTION__)); | |||
1193 | assert(!F.empty() &&((!F.empty() && "The file name provided to FileError must not be empty." ) ? static_cast<void> (0) : __assert_fail ("!F.empty() && \"The file name provided to FileError must not be empty.\"" , "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h" , 1194, __PRETTY_FUNCTION__)) | |||
1194 | "The file name provided to FileError must not be empty.")((!F.empty() && "The file name provided to FileError must not be empty." ) ? static_cast<void> (0) : __assert_fail ("!F.empty() && \"The file name provided to FileError must not be empty.\"" , "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h" , 1194, __PRETTY_FUNCTION__)); | |||
1195 | FileName = F; | |||
1196 | Err = std::move(E); | |||
1197 | } | |||
1198 | ||||
1199 | static Error build(std::string F, Error E) { | |||
1200 | return Error(std::unique_ptr<FileError>(new FileError(F, E.takePayload()))); | |||
1201 | } | |||
1202 | ||||
1203 | std::string FileName; | |||
1204 | std::unique_ptr<ErrorInfoBase> Err; | |||
1205 | }; | |||
1206 | ||||
1207 | /// Concatenate a source file path and/or name with an Error. The resulting | |||
1208 | /// Error is unchecked. | |||
1209 | inline Error createFileError(std::string F, Error E) { | |||
1210 | return FileError::build(F, std::move(E)); | |||
1211 | } | |||
1212 | ||||
1213 | Error createFileError(std::string F, ErrorSuccess) = delete; | |||
1214 | ||||
1215 | /// Helper for check-and-exit error handling. | |||
1216 | /// | |||
1217 | /// For tool use only. NOT FOR USE IN LIBRARY CODE. | |||
1218 | /// | |||
1219 | class ExitOnError { | |||
1220 | public: | |||
1221 | /// Create an error on exit helper. | |||
1222 | ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1) | |||
1223 | : Banner(std::move(Banner)), | |||
1224 | GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {} | |||
1225 | ||||
1226 | /// Set the banner string for any errors caught by operator(). | |||
1227 | void setBanner(std::string Banner) { this->Banner = std::move(Banner); } | |||
1228 | ||||
1229 | /// Set the exit-code mapper function. | |||
1230 | void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) { | |||
1231 | this->GetExitCode = std::move(GetExitCode); | |||
1232 | } | |||
1233 | ||||
1234 | /// Check Err. If it's in a failure state log the error(s) and exit. | |||
1235 | void operator()(Error Err) const { checkError(std::move(Err)); } | |||
1236 | ||||
1237 | /// Check E. If it's in a success state then return the contained value. If | |||
1238 | /// it's in a failure state log the error(s) and exit. | |||
1239 | template <typename T> T operator()(Expected<T> &&E) const { | |||
1240 | checkError(E.takeError()); | |||
1241 | return std::move(*E); | |||
1242 | } | |||
1243 | ||||
1244 | /// Check E. If it's in a success state then return the contained reference. If | |||
1245 | /// it's in a failure state log the error(s) and exit. | |||
1246 | template <typename T> T& operator()(Expected<T&> &&E) const { | |||
1247 | checkError(E.takeError()); | |||
1248 | return *E; | |||
1249 | } | |||
1250 | ||||
1251 | private: | |||
1252 | void checkError(Error Err) const { | |||
1253 | if (Err) { | |||
1254 | int ExitCode = GetExitCode(Err); | |||
1255 | logAllUnhandledErrors(std::move(Err), errs(), Banner); | |||
1256 | exit(ExitCode); | |||
1257 | } | |||
1258 | } | |||
1259 | ||||
1260 | std::string Banner; | |||
1261 | std::function<int(const Error &)> GetExitCode; | |||
1262 | }; | |||
1263 | ||||
1264 | /// Conversion from Error to LLVMErrorRef for C error bindings. | |||
1265 | inline LLVMErrorRef wrap(Error Err) { | |||
1266 | return reinterpret_cast<LLVMErrorRef>(Err.takePayload().release()); | |||
1267 | } | |||
1268 | ||||
1269 | /// Conversion from LLVMErrorRef to Error for C error bindings. | |||
1270 | inline Error unwrap(LLVMErrorRef ErrRef) { | |||
1271 | return Error(std::unique_ptr<ErrorInfoBase>( | |||
1272 | reinterpret_cast<ErrorInfoBase *>(ErrRef))); | |||
1273 | } | |||
1274 | ||||
1275 | } // end namespace llvm | |||
1276 | ||||
1277 | #endif // LLVM_SUPPORT_ERROR_H |