1 //===- ErrorHandler.cpp ---------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "lld/Common/ErrorHandler.h"
10 
11 #include "lld/Common/Threads.h"
12 
13 #include "llvm/ADT/Twine.h"
14 #include "llvm/IR/DiagnosticInfo.h"
15 #include "llvm/IR/DiagnosticPrinter.h"
16 #include "llvm/Support/ManagedStatic.h"
17 #include "llvm/Support/raw_ostream.h"
18 #include <mutex>
19 #include <regex>
20 
21 #if !defined(_MSC_VER) && !defined(__MINGW32__)
22 #include <unistd.h>
23 #endif
24 
25 using namespace llvm;
26 using namespace lld;
27 
28 // The functions defined in this file can be called from multiple threads,
29 // but outs() or errs() are not thread-safe. We protect them using a mutex.
30 static std::mutex mu;
31 
32 // Prints "\n" or does nothing, depending on Msg contents of
33 // the previous call of this function.
34 static void newline(raw_ostream *errorOS, const Twine &msg) {
35   // True if the previous error message contained "\n".
36   // We want to separate multi-line error messages with a newline.
37   static bool flag;
38 
39   if (flag)
40     *errorOS << "\n";
41   flag = StringRef(msg.str()).contains('\n');
42 }
43 
44 ErrorHandler &lld::errorHandler() {
45   static ErrorHandler handler;
46   return handler;
47 }
48 
49 void lld::exitLld(int val) {
50   // Delete any temporary file, while keeping the memory mapping open.
51   if (errorHandler().outputBuffer)
52     errorHandler().outputBuffer->discard();
53 
54   // Dealloc/destroy ManagedStatic variables before calling
55   // _exit(). In a non-LTO build, this is a nop. In an LTO
56   // build allows us to get the output of -time-passes.
57   llvm_shutdown();
58 
59   outs().flush();
60   errs().flush();
61   _exit(val);
62 }
63 
64 void lld::diagnosticHandler(const DiagnosticInfo &di) {
65   SmallString<128> s;
66   raw_svector_ostream os(s);
67   DiagnosticPrinterRawOStream dp(os);
68   di.print(dp);
69   switch (di.getSeverity()) {
70   case DS_Error:
71     error(s);
72     break;
73   case DS_Warning:
74     warn(s);
75     break;
76   case DS_Remark:
77   case DS_Note:
78     message(s);
79     break;
80   }
81 }
82 
83 void lld::checkError(Error e) {
84   handleAllErrors(std::move(e),
85                   [&](ErrorInfoBase &eib) { error(eib.message()); });
86 }
87 
88 // This is for --vs-diagnostics.
89 //
90 // Normally, lld's error message starts with argv[0]. Therefore, it usually
91 // looks like this:
92 //
93 //   ld.lld: error: ...
94 //
95 // This error message style is unfortunately unfriendly to Visual Studio
96 // IDE. VS interprets the first word of the first line as an error location
97 // and make it clickable, thus "ld.lld" in the above message would become a
98 // clickable text. When you click it, VS opens "ld.lld" executable file with
99 // a binary editor.
100 //
101 // As a workaround, we print out an error location instead of "ld.lld" if
102 // lld is running in VS diagnostics mode. As a result, error message will
103 // look like this:
104 //
105 //   src/foo.c(35): error: ...
106 //
107 // This function returns an error location string. An error location is
108 // extracted from an error message using regexps.
109 std::string ErrorHandler::getLocation(const Twine &msg) {
110   if (!vsDiagnostics)
111     return logName;
112 
113   static std::regex regexes[] = {
114       std::regex(
115           R"(^undefined (?:\S+ )?symbol:.*\n>>> referenced by (\S+):(\d+)\n.*)"),
116       std::regex(R"(^undefined symbol:.*\n>>> referenced by (.*):)"),
117       std::regex(
118           R"(^duplicate symbol: .*\n>>> defined in (\S+)\n>>> defined in.*)"),
119       std::regex(R"(^duplicate symbol: .*\n>>> defined at (\S+):(\d+).*)"),
120       std::regex(R"(.*\n>>> defined in .*\n>>> referenced by (\S+):(\d+))"),
121       std::regex(R"((\S+):(\d+): unclosed quote)"),
122   };
123 
124   std::string str = msg.str();
125 
126   for (std::regex &re : regexes) {
127     std::smatch m;
128     if (!std::regex_search(str, m, re))
129       continue;
130     assert(m.size() == 2 || m.size() == 3);
131 
132     if (m.size() == 2)
133       return m.str(1);
134     return m.str(1) + "(" + m.str(2) + ")";
135   }
136 
137   return logName;
138 }
139 
140 void ErrorHandler::log(const Twine &msg) {
141   if (!verbose)
142     return;
143   std::lock_guard<std::mutex> lock(mu);
144   *errorOS << logName << ": " << msg << "\n";
145 }
146 
147 void ErrorHandler::message(const Twine &msg) {
148   std::lock_guard<std::mutex> lock(mu);
149   outs() << msg << "\n";
150   outs().flush();
151 }
152 
153 void ErrorHandler::warn(const Twine &msg) {
154   if (fatalWarnings) {
155     error(msg);
156     return;
157   }
158 
159   std::lock_guard<std::mutex> lock(mu);
160   newline(errorOS, msg);
161   *errorOS << getLocation(msg) << ": " << Color::MAGENTA
162            << "warning: " << Color::RESET << msg << "\n";
163 }
164 
165 void ErrorHandler::error(const Twine &msg) {
166   // If Microsoft Visual Studio-style error message mode is enabled,
167   // this particular error is printed out as two errors.
168   if (vsDiagnostics) {
169     static std::regex re(R"(^(duplicate symbol: .*))"
170                          R"((\n>>> defined at \S+:\d+\n>>>.*))"
171                          R"((\n>>> defined at \S+:\d+\n>>>.*))");
172     std::string str = msg.str();
173     std::smatch m;
174 
175     if (std::regex_match(str, m, re)) {
176       error(m.str(1) + m.str(2));
177       error(m.str(1) + m.str(3));
178       return;
179     }
180   }
181 
182   std::lock_guard<std::mutex> lock(mu);
183 
184   if (errorLimit == 0 || errorCount < errorLimit) {
185     newline(errorOS, msg);
186     *errorOS << getLocation(msg) << ": " << Color::RED
187              << "error: " << Color::RESET << msg << "\n";
188   } else if (errorCount == errorLimit) {
189     newline(errorOS, msg);
190     *errorOS << getLocation(msg) << ": " << Color::RED
191              << "error: " << Color::RESET << errorLimitExceededMsg << "\n";
192     if (exitEarly)
193       exitLld(1);
194   }
195 
196   ++errorCount;
197 }
198 
199 void ErrorHandler::fatal(const Twine &msg) {
200   error(msg);
201   exitLld(1);
202 }
203