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 // We want to separate multi-line messages with a newline. `sep` is "\n"
33 // if the last messages was multi-line. Otherwise "".
34 static StringRef sep;
35 
36 static StringRef getSeparator(const Twine &msg) {
37   if (StringRef(msg.str()).contains('\n'))
38     return "\n";
39   return "";
40 }
41 
42 ErrorHandler &lld::errorHandler() {
43   static ErrorHandler handler;
44   return handler;
45 }
46 
47 void lld::enableColors(bool enable) {
48   errorHandler().errorOS->enable_colors(enable);
49 }
50 
51 void lld::exitLld(int val) {
52   // Delete any temporary file, while keeping the memory mapping open.
53   if (errorHandler().outputBuffer)
54     errorHandler().outputBuffer->discard();
55 
56   // Dealloc/destroy ManagedStatic variables before calling
57   // _exit(). In a non-LTO build, this is a nop. In an LTO
58   // build allows us to get the output of -time-passes.
59   llvm_shutdown();
60 
61   outs().flush();
62   errs().flush();
63   _exit(val);
64 }
65 
66 void lld::diagnosticHandler(const DiagnosticInfo &di) {
67   SmallString<128> s;
68   raw_svector_ostream os(s);
69   DiagnosticPrinterRawOStream dp(os);
70   di.print(dp);
71   switch (di.getSeverity()) {
72   case DS_Error:
73     error(s);
74     break;
75   case DS_Warning:
76     warn(s);
77     break;
78   case DS_Remark:
79   case DS_Note:
80     message(s);
81     break;
82   }
83 }
84 
85 void lld::checkError(Error e) {
86   handleAllErrors(std::move(e),
87                   [&](ErrorInfoBase &eib) { error(eib.message()); });
88 }
89 
90 // This is for --vs-diagnostics.
91 //
92 // Normally, lld's error message starts with argv[0]. Therefore, it usually
93 // looks like this:
94 //
95 //   ld.lld: error: ...
96 //
97 // This error message style is unfortunately unfriendly to Visual Studio
98 // IDE. VS interprets the first word of the first line as an error location
99 // and make it clickable, thus "ld.lld" in the above message would become a
100 // clickable text. When you click it, VS opens "ld.lld" executable file with
101 // a binary editor.
102 //
103 // As a workaround, we print out an error location instead of "ld.lld" if
104 // lld is running in VS diagnostics mode. As a result, error message will
105 // look like this:
106 //
107 //   src/foo.c(35): error: ...
108 //
109 // This function returns an error location string. An error location is
110 // extracted from an error message using regexps.
111 std::string ErrorHandler::getLocation(const Twine &msg) {
112   if (!vsDiagnostics)
113     return logName;
114 
115   static std::regex regexes[] = {
116       std::regex(
117           R"(^undefined (?:\S+ )?symbol:.*\n>>> referenced by (\S+):(\d+)\n.*)"),
118       std::regex(R"(^undefined symbol:.*\n>>> referenced by (.*):)"),
119       std::regex(
120           R"(^duplicate symbol: .*\n>>> defined in (\S+)\n>>> defined in.*)"),
121       std::regex(R"(^duplicate symbol: .*\n>>> defined at (\S+):(\d+).*)"),
122       std::regex(R"(.*\n>>> defined in .*\n>>> referenced by (\S+):(\d+))"),
123       std::regex(R"((\S+):(\d+): unclosed quote)"),
124   };
125 
126   std::string str = msg.str();
127   for (std::regex &re : regexes) {
128     std::smatch m;
129     if (!std::regex_search(str, m, re))
130       continue;
131 
132     assert(m.size() == 2 || m.size() == 3);
133     if (m.size() == 2)
134       return m.str(1);
135     return m.str(1) + "(" + m.str(2) + ")";
136   }
137 
138   return logName;
139 }
140 
141 void ErrorHandler::log(const Twine &msg) {
142   if (!verbose)
143     return;
144   std::lock_guard<std::mutex> lock(mu);
145   *errorOS << logName << ": " << msg << "\n";
146 }
147 
148 void ErrorHandler::message(const Twine &msg) {
149   std::lock_guard<std::mutex> lock(mu);
150   outs() << msg << "\n";
151   outs().flush();
152 }
153 
154 void ErrorHandler::warn(const Twine &msg) {
155   if (fatalWarnings) {
156     error(msg);
157     return;
158   }
159 
160   std::lock_guard<std::mutex> lock(mu);
161   *errorOS << sep << getLocation(msg) << ": " << Colors::MAGENTA
162            << "warning: " << Colors::RESET << msg << "\n";
163   sep = getSeparator(msg);
164 }
165 
166 void ErrorHandler::error(const Twine &msg) {
167   // If Visual Studio-style error message mode is enabled,
168   // this particular error is printed out as two errors.
169   if (vsDiagnostics) {
170     static std::regex re(R"(^(duplicate symbol: .*))"
171                          R"((\n>>> defined at \S+:\d+.*\n>>>.*))"
172                          R"((\n>>> defined at \S+:\d+.*\n>>>.*))");
173     std::string str = msg.str();
174     std::smatch m;
175 
176     if (std::regex_match(str, m, re)) {
177       error(m.str(1) + m.str(2));
178       error(m.str(1) + m.str(3));
179       return;
180     }
181   }
182 
183   std::lock_guard<std::mutex> lock(mu);
184 
185   if (errorLimit == 0 || errorCount < errorLimit) {
186     *errorOS << sep << getLocation(msg) << ": " << Colors::RED
187              << "error: " << Colors::RESET << msg << "\n";
188   } else if (errorCount == errorLimit) {
189     *errorOS << sep << getLocation(msg) << ": " << Colors::RED
190              << "error: " << Colors::RESET << errorLimitExceededMsg << "\n";
191     if (exitEarly)
192       exitLld(1);
193   }
194 
195   sep = getSeparator(msg);
196   ++errorCount;
197 }
198 
199 void ErrorHandler::fatal(const Twine &msg) {
200   error(msg);
201   exitLld(1);
202 }
203