blob: f441edecda6c52965550e1be33826add9f34d327 [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"
Sam McCalldd0566b2017-11-06 15:40:30 +000011#include "JSONExpr.h"
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000012#include "ProtocolHandlers.h"
Sam McCall8567cb32017-11-02 09:21:51 +000013#include "Trace.h"
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000014#include "llvm/ADT/SmallString.h"
Sam McCall94362c62017-11-07 14:45:31 +000015#include "llvm/ADT/StringExtras.h"
Sam McCalla90f2572018-02-16 16:41:42 +000016#include "llvm/Support/Chrono.h"
Sam McCall27a07cf2018-06-05 09:34:46 +000017#include "llvm/Support/Errno.h"
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000018#include "llvm/Support/SourceMgr.h"
Ilya Biryukov687b92a2017-05-16 15:23:55 +000019#include <istream>
20
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000021using namespace clang;
22using namespace clangd;
23
Ilya Biryukov940901e2017-12-13 12:51:22 +000024namespace {
Ilya Biryukov940901e2017-12-13 12:51:22 +000025static Key<json::Expr> RequestID;
26static Key<JSONOutput *> RequestOut;
Sam McCall1b475a12018-01-26 09:00:30 +000027
28// When tracing, we trace a request and attach the repsonse in reply().
29// Because the Span isn't available, we find the current request using Context.
30class RequestSpan {
31 RequestSpan(json::obj *Args) : Args(Args) {}
32 std::mutex Mu;
33 json::obj *Args;
Sam McCall24f0fa32018-01-26 11:23:33 +000034 static Key<std::unique_ptr<RequestSpan>> RSKey;
Sam McCall1b475a12018-01-26 09:00:30 +000035
36public:
37 // Return a context that's aware of the enclosing request, identified by Span.
38 static Context stash(const trace::Span &Span) {
Sam McCalld1a7a372018-01-31 13:40:48 +000039 return Context::current().derive(
40 RSKey, std::unique_ptr<RequestSpan>(new RequestSpan(Span.Args)));
Sam McCall1b475a12018-01-26 09:00:30 +000041 }
42
43 // If there's an enclosing request and the tracer is interested, calls \p F
44 // with a json::obj where request info can be added.
Sam McCalld1a7a372018-01-31 13:40:48 +000045 template <typename Func> static void attach(Func &&F) {
46 auto *RequestArgs = Context::current().get(RSKey);
Sam McCall1b475a12018-01-26 09:00:30 +000047 if (!RequestArgs || !*RequestArgs || !(*RequestArgs)->Args)
48 return;
49 std::lock_guard<std::mutex> Lock((*RequestArgs)->Mu);
50 F(*(*RequestArgs)->Args);
51 }
52};
Sam McCall24f0fa32018-01-26 11:23:33 +000053Key<std::unique_ptr<RequestSpan>> RequestSpan::RSKey;
Ilya Biryukov940901e2017-12-13 12:51:22 +000054} // namespace
55
Sam McCalldd0566b2017-11-06 15:40:30 +000056void JSONOutput::writeMessage(const json::Expr &Message) {
57 std::string S;
58 llvm::raw_string_ostream OS(S);
59 if (Pretty)
60 OS << llvm::formatv("{0:2}", Message);
61 else
62 OS << Message;
63 OS.flush();
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000064
Sam McCalla90f2572018-02-16 16:41:42 +000065 {
66 std::lock_guard<std::mutex> Guard(StreamMutex);
67 Outs << "Content-Length: " << S.size() << "\r\n\r\n" << S;
68 Outs.flush();
69 }
Sam McCall27a07cf2018-06-05 09:34:46 +000070 log(llvm::Twine("--> ") + S + "\n");
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000071}
72
Sam McCalld1a7a372018-01-31 13:40:48 +000073void JSONOutput::log(const Twine &Message) {
Sam McCalla90f2572018-02-16 16:41:42 +000074 llvm::sys::TimePoint<> Timestamp = std::chrono::system_clock::now();
Sam McCalld1a7a372018-01-31 13:40:48 +000075 trace::log(Message);
Benjamin Kramere14bd422017-02-15 16:44:11 +000076 std::lock_guard<std::mutex> Guard(StreamMutex);
Sam McCalla90f2572018-02-16 16:41:42 +000077 Logs << llvm::formatv("[{0:%H:%M:%S.%L}] {1}\n", Timestamp, Message);
Benjamin Kramere14bd422017-02-15 16:44:11 +000078 Logs.flush();
79}
80
Ilya Biryukove6dbb582017-10-10 09:08:47 +000081void JSONOutput::mirrorInput(const Twine &Message) {
82 if (!InputMirror)
83 return;
84
85 *InputMirror << Message;
86 InputMirror->flush();
87}
88
Sam McCalld1a7a372018-01-31 13:40:48 +000089void clangd::reply(json::Expr &&Result) {
90 auto ID = Context::current().get(RequestID);
Sam McCalldd0566b2017-11-06 15:40:30 +000091 if (!ID) {
Sam McCalld1a7a372018-01-31 13:40:48 +000092 log("Attempted to reply to a notification!");
Sam McCall8a5dded2017-10-12 13:29:58 +000093 return;
94 }
Sam McCalld1a7a372018-01-31 13:40:48 +000095 RequestSpan::attach([&](json::obj &Args) { Args["Reply"] = Result; });
96 Context::current()
97 .getExisting(RequestOut)
Ilya Biryukov940901e2017-12-13 12:51:22 +000098 ->writeMessage(json::obj{
99 {"jsonrpc", "2.0"},
100 {"id", *ID},
101 {"result", std::move(Result)},
102 });
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000103}
104
Sam McCalld1a7a372018-01-31 13:40:48 +0000105void clangd::replyError(ErrorCode code, const llvm::StringRef &Message) {
106 log("Error " + Twine(static_cast<int>(code)) + ": " + Message);
107 RequestSpan::attach([&](json::obj &Args) {
Sam McCall1b475a12018-01-26 09:00:30 +0000108 Args["Error"] =
109 json::obj{{"code", static_cast<int>(code)}, {"message", Message.str()}};
110 });
Ilya Biryukov940901e2017-12-13 12:51:22 +0000111
Sam McCalld1a7a372018-01-31 13:40:48 +0000112 if (auto ID = Context::current().get(RequestID)) {
113 Context::current()
114 .getExisting(RequestOut)
Ilya Biryukov940901e2017-12-13 12:51:22 +0000115 ->writeMessage(json::obj{
116 {"jsonrpc", "2.0"},
117 {"id", *ID},
118 {"error",
119 json::obj{{"code", static_cast<int>(code)}, {"message", Message}}},
120 });
Sam McCall8a5dded2017-10-12 13:29:58 +0000121 }
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000122}
123
Sam McCalld1a7a372018-01-31 13:40:48 +0000124void clangd::call(StringRef Method, json::Expr &&Params) {
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000125 // FIXME: Generate/Increment IDs for every request so that we can get proper
126 // replies once we need to.
Sam McCalld1a7a372018-01-31 13:40:48 +0000127 RequestSpan::attach([&](json::obj &Args) {
Sam McCall1b475a12018-01-26 09:00:30 +0000128 Args["Call"] = json::obj{{"method", Method.str()}, {"params", Params}};
129 });
Sam McCalld1a7a372018-01-31 13:40:48 +0000130 Context::current()
131 .getExisting(RequestOut)
Ilya Biryukov940901e2017-12-13 12:51:22 +0000132 ->writeMessage(json::obj{
133 {"jsonrpc", "2.0"},
134 {"id", 1},
135 {"method", Method},
136 {"params", std::move(Params)},
137 });
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000138}
139
Sam McCall8a5dded2017-10-12 13:29:58 +0000140void JSONRPCDispatcher::registerHandler(StringRef Method, Handler H) {
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000141 assert(!Handlers.count(Method) && "Handler already registered!");
142 Handlers[Method] = std::move(H);
143}
144
Sam McCallec109022017-11-28 09:37:43 +0000145bool JSONRPCDispatcher::call(const json::Expr &Message, JSONOutput &Out) const {
146 // Message must be an object with "jsonrpc":"2.0".
147 auto *Object = Message.asObject();
148 if (!Object || Object->getString("jsonrpc") != Optional<StringRef>("2.0"))
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000149 return false;
Sam McCallec109022017-11-28 09:37:43 +0000150 // ID may be any JSON value. If absent, this is a notification.
Sam McCalldd0566b2017-11-06 15:40:30 +0000151 llvm::Optional<json::Expr> ID;
Sam McCallec109022017-11-28 09:37:43 +0000152 if (auto *I = Object->get("id"))
153 ID = std::move(*I);
154 // Method must be given.
155 auto Method = Object->getString("method");
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000156 if (!Method)
157 return false;
Sam McCallec109022017-11-28 09:37:43 +0000158 // Params should be given, use null if not.
159 json::Expr Params = nullptr;
160 if (auto *P = Object->get("params"))
161 Params = std::move(*P);
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000162
Sam McCallec109022017-11-28 09:37:43 +0000163 auto I = Handlers.find(*Method);
164 auto &Handler = I != Handlers.end() ? I->second : UnknownHandler;
Ilya Biryukov940901e2017-12-13 12:51:22 +0000165
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000166 // Create a Context that contains request information.
Sam McCalld1a7a372018-01-31 13:40:48 +0000167 WithContextValue WithRequestOut(RequestOut, &Out);
168 llvm::Optional<WithContextValue> WithID;
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000169 if (ID)
Sam McCalld1a7a372018-01-31 13:40:48 +0000170 WithID.emplace(RequestID, *ID);
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000171
172 // Create a tracing Span covering the whole request lifetime.
Sam McCalld1a7a372018-01-31 13:40:48 +0000173 trace::Span Tracer(*Method);
Ilya Biryukov940901e2017-12-13 12:51:22 +0000174 if (ID)
Sam McCall1b475a12018-01-26 09:00:30 +0000175 SPAN_ATTACH(Tracer, "ID", *ID);
176 SPAN_ATTACH(Tracer, "Params", Params);
Ilya Biryukov940901e2017-12-13 12:51:22 +0000177
Sam McCall1b475a12018-01-26 09:00:30 +0000178 // Stash a reference to the span args, so later calls can add metadata.
Sam McCalld1a7a372018-01-31 13:40:48 +0000179 WithContext WithRequestSpan(RequestSpan::stash(Tracer));
180 Handler(std::move(Params));
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000181 return true;
182}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000183
Sam McCall27a07cf2018-06-05 09:34:46 +0000184// Tries to read a line up to and including \n.
185// If failing, feof() or ferror() will be set.
186static bool readLine(std::FILE *In, std::string &Out) {
187 static constexpr int BufSize = 1024;
188 size_t Size = 0;
189 Out.clear();
190 for (;;) {
191 Out.resize(Size + BufSize);
192 // Handle EINTR which is sent when a debugger attaches on some platforms.
193 if (!llvm::sys::RetryAfterSignal(nullptr, ::fgets, &Out[Size], BufSize, In))
194 return false;
195 clearerr(In);
196 // If the line contained null bytes, anything after it (including \n) will
197 // be ignored. Fortunately this is not a legal header or JSON.
198 size_t Read = std::strlen(&Out[Size]);
199 if (Read > 0 && Out[Size + Read - 1] == '\n') {
200 Out.resize(Size + Read);
201 return true;
202 }
203 Size += Read;
204 }
205}
206
207// Returns None when:
208// - ferror() or feof() are set.
209// - Content-Length is missing or empty (protocol error)
210static llvm::Optional<std::string> readStandardMessage(std::FILE *In,
Sam McCall5ed599e2018-02-06 10:47:30 +0000211 JSONOutput &Out) {
212 // A Language Server Protocol message starts with a set of HTTP headers,
213 // delimited by \r\n, and terminated by an empty line (\r\n).
214 unsigned long long ContentLength = 0;
Sam McCall27a07cf2018-06-05 09:34:46 +0000215 std::string Line;
216 while (true) {
217 if (feof(In) || ferror(In) || !readLine(In, Line))
218 return llvm::None;
Benjamin Kramer1d053792017-10-27 17:06:41 +0000219
Sam McCall5ed599e2018-02-06 10:47:30 +0000220 Out.mirrorInput(Line);
Sam McCall5ed599e2018-02-06 10:47:30 +0000221 llvm::StringRef LineRef(Line);
Sam McCall8567cb32017-11-02 09:21:51 +0000222
Sam McCall5ed599e2018-02-06 10:47:30 +0000223 // We allow comments in headers. Technically this isn't part
224 // of the LSP specification, but makes writing tests easier.
225 if (LineRef.startswith("#"))
226 continue;
227
Sam McCall27a07cf2018-06-05 09:34:46 +0000228 // Content-Length is a mandatory header, and the only one we handle.
Sam McCall5ed599e2018-02-06 10:47:30 +0000229 if (LineRef.consume_front("Content-Length: ")) {
230 if (ContentLength != 0) {
231 log("Warning: Duplicate Content-Length header received. "
232 "The previous value for this message (" +
Sam McCall27a07cf2018-06-05 09:34:46 +0000233 llvm::Twine(ContentLength) + ") was ignored.");
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000234 }
Sam McCall5ed599e2018-02-06 10:47:30 +0000235 llvm::getAsUnsignedInteger(LineRef.trim(), 0, ContentLength);
236 continue;
237 } else if (!LineRef.trim().empty()) {
238 // It's another header, ignore it.
239 continue;
240 } else {
241 // An empty line indicates the end of headers.
242 // Go ahead and read the JSON.
243 break;
244 }
245 }
246
Sam McCall27a07cf2018-06-05 09:34:46 +0000247 // The fuzzer likes crashing us by sending "Content-Length: 9999999999999999"
Sam McCall5ed599e2018-02-06 10:47:30 +0000248 if (ContentLength > 1 << 30) { // 1024M
Sam McCall27a07cf2018-06-05 09:34:46 +0000249 log("Refusing to read message with long Content-Length: " +
250 Twine(ContentLength) + ". Expect protocol errors.");
251 return llvm::None;
252 }
253 if (ContentLength == 0) {
254 log("Warning: Missing Content-Length header, or zero-length message.");
Sam McCall5ed599e2018-02-06 10:47:30 +0000255 return llvm::None;
256 }
257
Sam McCall27a07cf2018-06-05 09:34:46 +0000258 std::string JSON(ContentLength, '\0');
259 for (size_t Pos = 0, Read; Pos < ContentLength; Pos += Read) {
260 // Handle EINTR which is sent when a debugger attaches on some platforms.
261 Read = llvm::sys::RetryAfterSignal(0u, ::fread, &JSON[Pos], 1,
262 ContentLength - Pos, In);
263 Out.mirrorInput(StringRef(&JSON[Pos], Read));
264 if (Read == 0) {
265 log("Input was aborted. Read only " + llvm::Twine(Pos) +
266 " bytes of expected " + llvm::Twine(ContentLength) + ".");
Sam McCall5ed599e2018-02-06 10:47:30 +0000267 return llvm::None;
268 }
Sam McCall27a07cf2018-06-05 09:34:46 +0000269 clearerr(In); // If we're done, the error was transient. If we're not done,
270 // either it was transient or we'll see it again on retry.
271 Pos += Read;
Sam McCall5ed599e2018-02-06 10:47:30 +0000272 }
Sam McCall27a07cf2018-06-05 09:34:46 +0000273 return std::move(JSON);
Sam McCall5ed599e2018-02-06 10:47:30 +0000274}
275
276// For lit tests we support a simplified syntax:
277// - messages are delimited by '---' on a line by itself
278// - lines starting with # are ignored.
279// This is a testing path, so favor simplicity over performance here.
Sam McCall27a07cf2018-06-05 09:34:46 +0000280// When returning None, feof() or ferror() will be set.
281static llvm::Optional<std::string> readDelimitedMessage(std::FILE *In,
Sam McCall5ed599e2018-02-06 10:47:30 +0000282 JSONOutput &Out) {
283 std::string JSON;
284 std::string Line;
Sam McCall27a07cf2018-06-05 09:34:46 +0000285 while (readLine(In, Line)) {
Sam McCall5ed599e2018-02-06 10:47:30 +0000286 auto LineRef = llvm::StringRef(Line).trim();
287 if (LineRef.startswith("#")) // comment
288 continue;
289
Jan Korous62435152018-04-23 15:55:07 +0000290 // found a delimiter
Jan Korous1bc528c2018-04-23 15:58:42 +0000291 if (LineRef.rtrim() == "---")
Jan Korous62435152018-04-23 15:55:07 +0000292 break;
293
294 JSON += Line;
Sam McCall5ed599e2018-02-06 10:47:30 +0000295 }
296
Sam McCall27a07cf2018-06-05 09:34:46 +0000297 if (ferror(In)) {
Sam McCall5ed599e2018-02-06 10:47:30 +0000298 log("Input error while reading message!");
299 return llvm::None;
Sam McCall27a07cf2018-06-05 09:34:46 +0000300 } else { // Including EOF
Jan Korous62435152018-04-23 15:55:07 +0000301 Out.mirrorInput(
302 llvm::formatv("Content-Length: {0}\r\n\r\n{1}", JSON.size(), JSON));
Sam McCall5ed599e2018-02-06 10:47:30 +0000303 return std::move(JSON);
304 }
305}
306
Sam McCall27a07cf2018-06-05 09:34:46 +0000307// The use of C-style std::FILE* IO deserves some explanation.
308// Previously, std::istream was used. When a debugger attached on MacOS, the
309// process received EINTR, the stream went bad, and clangd exited.
310// A retry-on-EINTR loop around reads solved this problem, but caused clangd to
311// sometimes hang rather than exit on other OSes. The interaction between
312// istreams and signals isn't well-specified, so it's hard to get this right.
313// The C APIs seem to be clearer in this respect.
314void clangd::runLanguageServerLoop(std::FILE *In, JSONOutput &Out,
Sam McCall5ed599e2018-02-06 10:47:30 +0000315 JSONStreamStyle InputStyle,
316 JSONRPCDispatcher &Dispatcher,
317 bool &IsDone) {
318 auto &ReadMessage =
319 (InputStyle == Delimited) ? readDelimitedMessage : readStandardMessage;
Sam McCall27a07cf2018-06-05 09:34:46 +0000320 while (!IsDone && !feof(In)) {
321 if (ferror(In)) {
322 log("IO error: " + llvm::sys::StrError());
323 return;
324 }
Sam McCall5ed599e2018-02-06 10:47:30 +0000325 if (auto JSON = ReadMessage(In, Out)) {
326 if (auto Doc = json::parse(*JSON)) {
Sam McCallec109022017-11-28 09:37:43 +0000327 // Log the formatted message.
Sam McCalld1a7a372018-01-31 13:40:48 +0000328 log(llvm::formatv(Out.Pretty ? "<-- {0:2}\n" : "<-- {0}\n", *Doc));
Sam McCallec109022017-11-28 09:37:43 +0000329 // Finally, execute the action for this JSON message.
330 if (!Dispatcher.call(*Doc, Out))
Sam McCall27a07cf2018-06-05 09:34:46 +0000331 log("JSON dispatch failed!");
Sam McCallec109022017-11-28 09:37:43 +0000332 } else {
333 // Parse error. Log the raw message.
Sam McCall5ed599e2018-02-06 10:47:30 +0000334 log(llvm::formatv("<-- {0}\n" , *JSON));
Sam McCalld1a7a372018-01-31 13:40:48 +0000335 log(llvm::Twine("JSON parse error: ") +
Sam McCall27a07cf2018-06-05 09:34:46 +0000336 llvm::toString(Doc.takeError()));
Sam McCallec109022017-11-28 09:37:43 +0000337 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000338 }
339 }
340}