blob: d273577e28f740cc5f75abcddd28ff5f8c7a950a [file] [log] [blame]
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +00001//===--- JSONRPCDispatcher.cpp - Main JSON parser entry point -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "JSONRPCDispatcher.h"
11#include "ProtocolHandlers.h"
Sam McCall8567cb32017-11-02 09:21:51 +000012#include "Trace.h"
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000013#include "llvm/ADT/SmallString.h"
Sam McCall94362c62017-11-07 14:45:31 +000014#include "llvm/ADT/StringExtras.h"
Sam McCalla90f2572018-02-16 16:41:42 +000015#include "llvm/Support/Chrono.h"
Sam McCall27a07cf2018-06-05 09:34:46 +000016#include "llvm/Support/Errno.h"
Sam McCallbed58852018-07-11 10:35:11 +000017#include "llvm/Support/FormatVariadic.h"
Sam McCalld20d7982018-07-09 14:25:59 +000018#include "llvm/Support/JSON.h"
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000019#include "llvm/Support/SourceMgr.h"
Ilya Biryukov687b92a2017-05-16 15:23:55 +000020#include <istream>
21
Sam McCalld20d7982018-07-09 14:25:59 +000022using namespace llvm;
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000023using namespace clang;
24using namespace clangd;
25
Ilya Biryukov940901e2017-12-13 12:51:22 +000026namespace {
Sam McCalld20d7982018-07-09 14:25:59 +000027static Key<json::Value> RequestID;
Ilya Biryukov940901e2017-12-13 12:51:22 +000028static Key<JSONOutput *> RequestOut;
Sam McCall1b475a12018-01-26 09:00:30 +000029
30// When tracing, we trace a request and attach the repsonse in reply().
31// Because the Span isn't available, we find the current request using Context.
32class RequestSpan {
Sam McCalld20d7982018-07-09 14:25:59 +000033 RequestSpan(llvm::json::Object *Args) : Args(Args) {}
Sam McCall1b475a12018-01-26 09:00:30 +000034 std::mutex Mu;
Sam McCalld20d7982018-07-09 14:25:59 +000035 llvm::json::Object *Args;
Sam McCall24f0fa32018-01-26 11:23:33 +000036 static Key<std::unique_ptr<RequestSpan>> RSKey;
Sam McCall1b475a12018-01-26 09:00:30 +000037
38public:
39 // Return a context that's aware of the enclosing request, identified by Span.
40 static Context stash(const trace::Span &Span) {
Sam McCalld1a7a372018-01-31 13:40:48 +000041 return Context::current().derive(
42 RSKey, std::unique_ptr<RequestSpan>(new RequestSpan(Span.Args)));
Sam McCall1b475a12018-01-26 09:00:30 +000043 }
44
45 // If there's an enclosing request and the tracer is interested, calls \p F
Sam McCalld20d7982018-07-09 14:25:59 +000046 // with a json::Object where request info can be added.
Sam McCalld1a7a372018-01-31 13:40:48 +000047 template <typename Func> static void attach(Func &&F) {
48 auto *RequestArgs = Context::current().get(RSKey);
Sam McCall1b475a12018-01-26 09:00:30 +000049 if (!RequestArgs || !*RequestArgs || !(*RequestArgs)->Args)
50 return;
51 std::lock_guard<std::mutex> Lock((*RequestArgs)->Mu);
52 F(*(*RequestArgs)->Args);
53 }
54};
Sam McCall24f0fa32018-01-26 11:23:33 +000055Key<std::unique_ptr<RequestSpan>> RequestSpan::RSKey;
Ilya Biryukov940901e2017-12-13 12:51:22 +000056} // namespace
57
Sam McCalld20d7982018-07-09 14:25:59 +000058void JSONOutput::writeMessage(const json::Value &Message) {
Sam McCalldd0566b2017-11-06 15:40:30 +000059 std::string S;
60 llvm::raw_string_ostream OS(S);
61 if (Pretty)
62 OS << llvm::formatv("{0:2}", Message);
63 else
64 OS << Message;
65 OS.flush();
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000066
Sam McCalla90f2572018-02-16 16:41:42 +000067 {
68 std::lock_guard<std::mutex> Guard(StreamMutex);
69 Outs << "Content-Length: " << S.size() << "\r\n\r\n" << S;
70 Outs.flush();
71 }
Sam McCallbed58852018-07-11 10:35:11 +000072 vlog("--> {0}\n", S);
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000073}
74
Sam McCallbed58852018-07-11 10:35:11 +000075void JSONOutput::log(Logger::Level Level,
76 const llvm::formatv_object_base &Message) {
77 if (Level < MinLevel)
78 return;
Sam McCalla90f2572018-02-16 16:41:42 +000079 llvm::sys::TimePoint<> Timestamp = std::chrono::system_clock::now();
Sam McCalld1a7a372018-01-31 13:40:48 +000080 trace::log(Message);
Benjamin Kramere14bd422017-02-15 16:44:11 +000081 std::lock_guard<std::mutex> Guard(StreamMutex);
Sam McCallbed58852018-07-11 10:35:11 +000082 Logs << llvm::formatv("{0}[{1:%H:%M:%S.%L}] {2}\n", indicator(Level),
83 Timestamp, Message);
Benjamin Kramere14bd422017-02-15 16:44:11 +000084 Logs.flush();
85}
86
Ilya Biryukove6dbb582017-10-10 09:08:47 +000087void JSONOutput::mirrorInput(const Twine &Message) {
88 if (!InputMirror)
89 return;
90
91 *InputMirror << Message;
92 InputMirror->flush();
93}
94
Sam McCalld20d7982018-07-09 14:25:59 +000095void clangd::reply(json::Value &&Result) {
Sam McCalld1a7a372018-01-31 13:40:48 +000096 auto ID = Context::current().get(RequestID);
Sam McCalldd0566b2017-11-06 15:40:30 +000097 if (!ID) {
Sam McCallbed58852018-07-11 10:35:11 +000098 elog("Attempted to reply to a notification!");
Sam McCall8a5dded2017-10-12 13:29:58 +000099 return;
100 }
Sam McCalld20d7982018-07-09 14:25:59 +0000101 RequestSpan::attach([&](json::Object &Args) { Args["Reply"] = Result; });
Sam McCalld1a7a372018-01-31 13:40:48 +0000102 Context::current()
103 .getExisting(RequestOut)
Sam McCalld20d7982018-07-09 14:25:59 +0000104 ->writeMessage(json::Object{
Ilya Biryukov940901e2017-12-13 12:51:22 +0000105 {"jsonrpc", "2.0"},
106 {"id", *ID},
107 {"result", std::move(Result)},
108 });
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000109}
110
Sam McCalld1a7a372018-01-31 13:40:48 +0000111void clangd::replyError(ErrorCode code, const llvm::StringRef &Message) {
Sam McCallbed58852018-07-11 10:35:11 +0000112 elog("Error {0}: {1}", static_cast<int>(code), Message);
Sam McCalld20d7982018-07-09 14:25:59 +0000113 RequestSpan::attach([&](json::Object &Args) {
114 Args["Error"] = json::Object{{"code", static_cast<int>(code)},
115 {"message", Message.str()}};
Sam McCall1b475a12018-01-26 09:00:30 +0000116 });
Ilya Biryukov940901e2017-12-13 12:51:22 +0000117
Sam McCalld1a7a372018-01-31 13:40:48 +0000118 if (auto ID = Context::current().get(RequestID)) {
119 Context::current()
120 .getExisting(RequestOut)
Sam McCalld20d7982018-07-09 14:25:59 +0000121 ->writeMessage(json::Object{
Ilya Biryukov940901e2017-12-13 12:51:22 +0000122 {"jsonrpc", "2.0"},
123 {"id", *ID},
Sam McCalld20d7982018-07-09 14:25:59 +0000124 {"error", json::Object{{"code", static_cast<int>(code)},
125 {"message", Message}}},
Ilya Biryukov940901e2017-12-13 12:51:22 +0000126 });
Sam McCall8a5dded2017-10-12 13:29:58 +0000127 }
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000128}
129
Sam McCalld20d7982018-07-09 14:25:59 +0000130void clangd::call(StringRef Method, json::Value &&Params) {
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000131 // FIXME: Generate/Increment IDs for every request so that we can get proper
132 // replies once we need to.
Sam McCalld20d7982018-07-09 14:25:59 +0000133 RequestSpan::attach([&](json::Object &Args) {
134 Args["Call"] = json::Object{{"method", Method.str()}, {"params", Params}};
Sam McCall1b475a12018-01-26 09:00:30 +0000135 });
Sam McCalld1a7a372018-01-31 13:40:48 +0000136 Context::current()
137 .getExisting(RequestOut)
Sam McCalld20d7982018-07-09 14:25:59 +0000138 ->writeMessage(json::Object{
Ilya Biryukov940901e2017-12-13 12:51:22 +0000139 {"jsonrpc", "2.0"},
140 {"id", 1},
141 {"method", Method},
142 {"params", std::move(Params)},
143 });
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000144}
145
Sam McCall8a5dded2017-10-12 13:29:58 +0000146void JSONRPCDispatcher::registerHandler(StringRef Method, Handler H) {
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000147 assert(!Handlers.count(Method) && "Handler already registered!");
148 Handlers[Method] = std::move(H);
149}
150
Sam McCalld20d7982018-07-09 14:25:59 +0000151bool JSONRPCDispatcher::call(const json::Value &Message,
152 JSONOutput &Out) const {
Sam McCallec109022017-11-28 09:37:43 +0000153 // Message must be an object with "jsonrpc":"2.0".
Sam McCalld20d7982018-07-09 14:25:59 +0000154 auto *Object = Message.getAsObject();
Sam McCallec109022017-11-28 09:37:43 +0000155 if (!Object || Object->getString("jsonrpc") != Optional<StringRef>("2.0"))
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000156 return false;
Sam McCallec109022017-11-28 09:37:43 +0000157 // ID may be any JSON value. If absent, this is a notification.
Sam McCalld20d7982018-07-09 14:25:59 +0000158 llvm::Optional<json::Value> ID;
Sam McCallec109022017-11-28 09:37:43 +0000159 if (auto *I = Object->get("id"))
160 ID = std::move(*I);
161 // Method must be given.
162 auto Method = Object->getString("method");
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000163 if (!Method)
164 return false;
Sam McCallec109022017-11-28 09:37:43 +0000165 // Params should be given, use null if not.
Sam McCalld20d7982018-07-09 14:25:59 +0000166 json::Value Params = nullptr;
Sam McCallec109022017-11-28 09:37:43 +0000167 if (auto *P = Object->get("params"))
168 Params = std::move(*P);
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000169
Sam McCallec109022017-11-28 09:37:43 +0000170 auto I = Handlers.find(*Method);
171 auto &Handler = I != Handlers.end() ? I->second : UnknownHandler;
Ilya Biryukov940901e2017-12-13 12:51:22 +0000172
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000173 // Create a Context that contains request information.
Sam McCalld1a7a372018-01-31 13:40:48 +0000174 WithContextValue WithRequestOut(RequestOut, &Out);
175 llvm::Optional<WithContextValue> WithID;
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000176 if (ID)
Sam McCalld1a7a372018-01-31 13:40:48 +0000177 WithID.emplace(RequestID, *ID);
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000178
179 // Create a tracing Span covering the whole request lifetime.
Sam McCalld1a7a372018-01-31 13:40:48 +0000180 trace::Span Tracer(*Method);
Ilya Biryukov940901e2017-12-13 12:51:22 +0000181 if (ID)
Sam McCall1b475a12018-01-26 09:00:30 +0000182 SPAN_ATTACH(Tracer, "ID", *ID);
183 SPAN_ATTACH(Tracer, "Params", Params);
Ilya Biryukov940901e2017-12-13 12:51:22 +0000184
Sam McCall1b475a12018-01-26 09:00:30 +0000185 // Stash a reference to the span args, so later calls can add metadata.
Sam McCalld1a7a372018-01-31 13:40:48 +0000186 WithContext WithRequestSpan(RequestSpan::stash(Tracer));
187 Handler(std::move(Params));
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000188 return true;
189}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000190
Sam McCall27a07cf2018-06-05 09:34:46 +0000191// Tries to read a line up to and including \n.
192// If failing, feof() or ferror() will be set.
193static bool readLine(std::FILE *In, std::string &Out) {
194 static constexpr int BufSize = 1024;
195 size_t Size = 0;
196 Out.clear();
197 for (;;) {
198 Out.resize(Size + BufSize);
199 // Handle EINTR which is sent when a debugger attaches on some platforms.
200 if (!llvm::sys::RetryAfterSignal(nullptr, ::fgets, &Out[Size], BufSize, In))
201 return false;
202 clearerr(In);
203 // If the line contained null bytes, anything after it (including \n) will
204 // be ignored. Fortunately this is not a legal header or JSON.
205 size_t Read = std::strlen(&Out[Size]);
206 if (Read > 0 && Out[Size + Read - 1] == '\n') {
207 Out.resize(Size + Read);
208 return true;
209 }
210 Size += Read;
211 }
212}
213
214// Returns None when:
215// - ferror() or feof() are set.
216// - Content-Length is missing or empty (protocol error)
217static llvm::Optional<std::string> readStandardMessage(std::FILE *In,
Sam McCall5ed599e2018-02-06 10:47:30 +0000218 JSONOutput &Out) {
219 // A Language Server Protocol message starts with a set of HTTP headers,
220 // delimited by \r\n, and terminated by an empty line (\r\n).
221 unsigned long long ContentLength = 0;
Sam McCall27a07cf2018-06-05 09:34:46 +0000222 std::string Line;
223 while (true) {
224 if (feof(In) || ferror(In) || !readLine(In, Line))
225 return llvm::None;
Benjamin Kramer1d053792017-10-27 17:06:41 +0000226
Sam McCall5ed599e2018-02-06 10:47:30 +0000227 Out.mirrorInput(Line);
Sam McCall5ed599e2018-02-06 10:47:30 +0000228 llvm::StringRef LineRef(Line);
Sam McCall8567cb32017-11-02 09:21:51 +0000229
Sam McCall5ed599e2018-02-06 10:47:30 +0000230 // We allow comments in headers. Technically this isn't part
231 // of the LSP specification, but makes writing tests easier.
232 if (LineRef.startswith("#"))
233 continue;
234
Sam McCall27a07cf2018-06-05 09:34:46 +0000235 // Content-Length is a mandatory header, and the only one we handle.
Sam McCall5ed599e2018-02-06 10:47:30 +0000236 if (LineRef.consume_front("Content-Length: ")) {
237 if (ContentLength != 0) {
Sam McCallbed58852018-07-11 10:35:11 +0000238 elog("Warning: Duplicate Content-Length header received. "
239 "The previous value for this message ({0}) was ignored.",
240 ContentLength);
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000241 }
Sam McCall5ed599e2018-02-06 10:47:30 +0000242 llvm::getAsUnsignedInteger(LineRef.trim(), 0, ContentLength);
243 continue;
244 } else if (!LineRef.trim().empty()) {
245 // It's another header, ignore it.
246 continue;
247 } else {
248 // An empty line indicates the end of headers.
249 // Go ahead and read the JSON.
250 break;
251 }
252 }
253
Sam McCall27a07cf2018-06-05 09:34:46 +0000254 // The fuzzer likes crashing us by sending "Content-Length: 9999999999999999"
Sam McCall5ed599e2018-02-06 10:47:30 +0000255 if (ContentLength > 1 << 30) { // 1024M
Sam McCallbed58852018-07-11 10:35:11 +0000256 elog("Refusing to read message with long Content-Length: {0}. "
257 "Expect protocol errors",
258 ContentLength);
Sam McCall27a07cf2018-06-05 09:34:46 +0000259 return llvm::None;
260 }
261 if (ContentLength == 0) {
262 log("Warning: Missing Content-Length header, or zero-length message.");
Sam McCall5ed599e2018-02-06 10:47:30 +0000263 return llvm::None;
264 }
265
Sam McCall27a07cf2018-06-05 09:34:46 +0000266 std::string JSON(ContentLength, '\0');
267 for (size_t Pos = 0, Read; Pos < ContentLength; Pos += Read) {
268 // Handle EINTR which is sent when a debugger attaches on some platforms.
269 Read = llvm::sys::RetryAfterSignal(0u, ::fread, &JSON[Pos], 1,
270 ContentLength - Pos, In);
271 Out.mirrorInput(StringRef(&JSON[Pos], Read));
272 if (Read == 0) {
Sam McCallbed58852018-07-11 10:35:11 +0000273 elog("Input was aborted. Read only {0} bytes of expected {1}.", Pos,
274 ContentLength);
Sam McCall5ed599e2018-02-06 10:47:30 +0000275 return llvm::None;
276 }
Sam McCall27a07cf2018-06-05 09:34:46 +0000277 clearerr(In); // If we're done, the error was transient. If we're not done,
278 // either it was transient or we'll see it again on retry.
279 Pos += Read;
Sam McCall5ed599e2018-02-06 10:47:30 +0000280 }
Sam McCall27a07cf2018-06-05 09:34:46 +0000281 return std::move(JSON);
Sam McCall5ed599e2018-02-06 10:47:30 +0000282}
283
284// For lit tests we support a simplified syntax:
285// - messages are delimited by '---' on a line by itself
286// - lines starting with # are ignored.
287// This is a testing path, so favor simplicity over performance here.
Sam McCall27a07cf2018-06-05 09:34:46 +0000288// When returning None, feof() or ferror() will be set.
289static llvm::Optional<std::string> readDelimitedMessage(std::FILE *In,
Sam McCall5ed599e2018-02-06 10:47:30 +0000290 JSONOutput &Out) {
291 std::string JSON;
292 std::string Line;
Sam McCall27a07cf2018-06-05 09:34:46 +0000293 while (readLine(In, Line)) {
Sam McCall5ed599e2018-02-06 10:47:30 +0000294 auto LineRef = llvm::StringRef(Line).trim();
295 if (LineRef.startswith("#")) // comment
296 continue;
297
Jan Korous62435152018-04-23 15:55:07 +0000298 // found a delimiter
Jan Korous1bc528c2018-04-23 15:58:42 +0000299 if (LineRef.rtrim() == "---")
Jan Korous62435152018-04-23 15:55:07 +0000300 break;
301
302 JSON += Line;
Sam McCall5ed599e2018-02-06 10:47:30 +0000303 }
304
Sam McCall27a07cf2018-06-05 09:34:46 +0000305 if (ferror(In)) {
Sam McCallbed58852018-07-11 10:35:11 +0000306 elog("Input error while reading message!");
Sam McCall5ed599e2018-02-06 10:47:30 +0000307 return llvm::None;
Sam McCall27a07cf2018-06-05 09:34:46 +0000308 } else { // Including EOF
Jan Korous62435152018-04-23 15:55:07 +0000309 Out.mirrorInput(
310 llvm::formatv("Content-Length: {0}\r\n\r\n{1}", JSON.size(), JSON));
Sam McCall5ed599e2018-02-06 10:47:30 +0000311 return std::move(JSON);
312 }
313}
314
Sam McCall27a07cf2018-06-05 09:34:46 +0000315// The use of C-style std::FILE* IO deserves some explanation.
316// Previously, std::istream was used. When a debugger attached on MacOS, the
317// process received EINTR, the stream went bad, and clangd exited.
318// A retry-on-EINTR loop around reads solved this problem, but caused clangd to
319// sometimes hang rather than exit on other OSes. The interaction between
320// istreams and signals isn't well-specified, so it's hard to get this right.
321// The C APIs seem to be clearer in this respect.
322void clangd::runLanguageServerLoop(std::FILE *In, JSONOutput &Out,
Sam McCall5ed599e2018-02-06 10:47:30 +0000323 JSONStreamStyle InputStyle,
324 JSONRPCDispatcher &Dispatcher,
325 bool &IsDone) {
326 auto &ReadMessage =
327 (InputStyle == Delimited) ? readDelimitedMessage : readStandardMessage;
Sam McCall27a07cf2018-06-05 09:34:46 +0000328 while (!IsDone && !feof(In)) {
329 if (ferror(In)) {
Sam McCallbed58852018-07-11 10:35:11 +0000330 elog("IO error: {0}", llvm::sys::StrError());
Sam McCall27a07cf2018-06-05 09:34:46 +0000331 return;
332 }
Sam McCall5ed599e2018-02-06 10:47:30 +0000333 if (auto JSON = ReadMessage(In, Out)) {
334 if (auto Doc = json::parse(*JSON)) {
Sam McCallec109022017-11-28 09:37:43 +0000335 // Log the formatted message.
Sam McCallbed58852018-07-11 10:35:11 +0000336 vlog(Out.Pretty ? "<-- {0:2}\n" : "<-- {0}\n", *Doc);
Sam McCallec109022017-11-28 09:37:43 +0000337 // Finally, execute the action for this JSON message.
338 if (!Dispatcher.call(*Doc, Out))
Sam McCallbed58852018-07-11 10:35:11 +0000339 elog("JSON dispatch failed!");
Sam McCallec109022017-11-28 09:37:43 +0000340 } else {
341 // Parse error. Log the raw message.
Sam McCallbed58852018-07-11 10:35:11 +0000342 vlog("<-- {0}\n", *JSON);
343 elog("JSON parse error: {0}", llvm::toString(Doc.takeError()));
Sam McCallec109022017-11-28 09:37:43 +0000344 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000345 }
346 }
347}