blob: f81af3d1dda7e4719c8d1d0eeb492af39bf2eaa2 [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 McCalld20d7982018-07-09 14:25:59 +000017#include "llvm/Support/JSON.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
Sam McCalld20d7982018-07-09 14:25:59 +000021using namespace llvm;
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000022using namespace clang;
23using namespace clangd;
24
Ilya Biryukov940901e2017-12-13 12:51:22 +000025namespace {
Sam McCalld20d7982018-07-09 14:25:59 +000026static Key<json::Value> RequestID;
Ilya Biryukov940901e2017-12-13 12:51:22 +000027static Key<JSONOutput *> RequestOut;
Sam McCall1b475a12018-01-26 09:00:30 +000028
29// When tracing, we trace a request and attach the repsonse in reply().
30// Because the Span isn't available, we find the current request using Context.
31class RequestSpan {
Sam McCalld20d7982018-07-09 14:25:59 +000032 RequestSpan(llvm::json::Object *Args) : Args(Args) {}
Sam McCall1b475a12018-01-26 09:00:30 +000033 std::mutex Mu;
Sam McCalld20d7982018-07-09 14:25:59 +000034 llvm::json::Object *Args;
Sam McCall24f0fa32018-01-26 11:23:33 +000035 static Key<std::unique_ptr<RequestSpan>> RSKey;
Sam McCall1b475a12018-01-26 09:00:30 +000036
37public:
38 // Return a context that's aware of the enclosing request, identified by Span.
39 static Context stash(const trace::Span &Span) {
Sam McCalld1a7a372018-01-31 13:40:48 +000040 return Context::current().derive(
41 RSKey, std::unique_ptr<RequestSpan>(new RequestSpan(Span.Args)));
Sam McCall1b475a12018-01-26 09:00:30 +000042 }
43
44 // If there's an enclosing request and the tracer is interested, calls \p F
Sam McCalld20d7982018-07-09 14:25:59 +000045 // with a json::Object where request info can be added.
Sam McCalld1a7a372018-01-31 13:40:48 +000046 template <typename Func> static void attach(Func &&F) {
47 auto *RequestArgs = Context::current().get(RSKey);
Sam McCall1b475a12018-01-26 09:00:30 +000048 if (!RequestArgs || !*RequestArgs || !(*RequestArgs)->Args)
49 return;
50 std::lock_guard<std::mutex> Lock((*RequestArgs)->Mu);
51 F(*(*RequestArgs)->Args);
52 }
53};
Sam McCall24f0fa32018-01-26 11:23:33 +000054Key<std::unique_ptr<RequestSpan>> RequestSpan::RSKey;
Ilya Biryukov940901e2017-12-13 12:51:22 +000055} // namespace
56
Sam McCalld20d7982018-07-09 14:25:59 +000057void JSONOutput::writeMessage(const json::Value &Message) {
Sam McCalldd0566b2017-11-06 15:40:30 +000058 std::string S;
59 llvm::raw_string_ostream OS(S);
60 if (Pretty)
61 OS << llvm::formatv("{0:2}", Message);
62 else
63 OS << Message;
64 OS.flush();
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000065
Sam McCalla90f2572018-02-16 16:41:42 +000066 {
67 std::lock_guard<std::mutex> Guard(StreamMutex);
68 Outs << "Content-Length: " << S.size() << "\r\n\r\n" << S;
69 Outs.flush();
70 }
Sam McCall27a07cf2018-06-05 09:34:46 +000071 log(llvm::Twine("--> ") + S + "\n");
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +000072}
73
Sam McCalld1a7a372018-01-31 13:40:48 +000074void JSONOutput::log(const Twine &Message) {
Sam McCalla90f2572018-02-16 16:41:42 +000075 llvm::sys::TimePoint<> Timestamp = std::chrono::system_clock::now();
Sam McCalld1a7a372018-01-31 13:40:48 +000076 trace::log(Message);
Benjamin Kramere14bd422017-02-15 16:44:11 +000077 std::lock_guard<std::mutex> Guard(StreamMutex);
Sam McCalla90f2572018-02-16 16:41:42 +000078 Logs << llvm::formatv("[{0:%H:%M:%S.%L}] {1}\n", Timestamp, Message);
Benjamin Kramere14bd422017-02-15 16:44:11 +000079 Logs.flush();
80}
81
Ilya Biryukove6dbb582017-10-10 09:08:47 +000082void JSONOutput::mirrorInput(const Twine &Message) {
83 if (!InputMirror)
84 return;
85
86 *InputMirror << Message;
87 InputMirror->flush();
88}
89
Sam McCalld20d7982018-07-09 14:25:59 +000090void clangd::reply(json::Value &&Result) {
Sam McCalld1a7a372018-01-31 13:40:48 +000091 auto ID = Context::current().get(RequestID);
Sam McCalldd0566b2017-11-06 15:40:30 +000092 if (!ID) {
Sam McCalld1a7a372018-01-31 13:40:48 +000093 log("Attempted to reply to a notification!");
Sam McCall8a5dded2017-10-12 13:29:58 +000094 return;
95 }
Sam McCalld20d7982018-07-09 14:25:59 +000096 RequestSpan::attach([&](json::Object &Args) { Args["Reply"] = Result; });
Sam McCalld1a7a372018-01-31 13:40:48 +000097 Context::current()
98 .getExisting(RequestOut)
Sam McCalld20d7982018-07-09 14:25:59 +000099 ->writeMessage(json::Object{
Ilya Biryukov940901e2017-12-13 12:51:22 +0000100 {"jsonrpc", "2.0"},
101 {"id", *ID},
102 {"result", std::move(Result)},
103 });
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000104}
105
Sam McCalld1a7a372018-01-31 13:40:48 +0000106void clangd::replyError(ErrorCode code, const llvm::StringRef &Message) {
107 log("Error " + Twine(static_cast<int>(code)) + ": " + Message);
Sam McCalld20d7982018-07-09 14:25:59 +0000108 RequestSpan::attach([&](json::Object &Args) {
109 Args["Error"] = json::Object{{"code", static_cast<int>(code)},
110 {"message", Message.str()}};
Sam McCall1b475a12018-01-26 09:00:30 +0000111 });
Ilya Biryukov940901e2017-12-13 12:51:22 +0000112
Sam McCalld1a7a372018-01-31 13:40:48 +0000113 if (auto ID = Context::current().get(RequestID)) {
114 Context::current()
115 .getExisting(RequestOut)
Sam McCalld20d7982018-07-09 14:25:59 +0000116 ->writeMessage(json::Object{
Ilya Biryukov940901e2017-12-13 12:51:22 +0000117 {"jsonrpc", "2.0"},
118 {"id", *ID},
Sam McCalld20d7982018-07-09 14:25:59 +0000119 {"error", json::Object{{"code", static_cast<int>(code)},
120 {"message", Message}}},
Ilya Biryukov940901e2017-12-13 12:51:22 +0000121 });
Sam McCall8a5dded2017-10-12 13:29:58 +0000122 }
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000123}
124
Sam McCalld20d7982018-07-09 14:25:59 +0000125void clangd::call(StringRef Method, json::Value &&Params) {
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000126 // FIXME: Generate/Increment IDs for every request so that we can get proper
127 // replies once we need to.
Sam McCalld20d7982018-07-09 14:25:59 +0000128 RequestSpan::attach([&](json::Object &Args) {
129 Args["Call"] = json::Object{{"method", Method.str()}, {"params", Params}};
Sam McCall1b475a12018-01-26 09:00:30 +0000130 });
Sam McCalld1a7a372018-01-31 13:40:48 +0000131 Context::current()
132 .getExisting(RequestOut)
Sam McCalld20d7982018-07-09 14:25:59 +0000133 ->writeMessage(json::Object{
Ilya Biryukov940901e2017-12-13 12:51:22 +0000134 {"jsonrpc", "2.0"},
135 {"id", 1},
136 {"method", Method},
137 {"params", std::move(Params)},
138 });
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000139}
140
Sam McCall8a5dded2017-10-12 13:29:58 +0000141void JSONRPCDispatcher::registerHandler(StringRef Method, Handler H) {
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000142 assert(!Handlers.count(Method) && "Handler already registered!");
143 Handlers[Method] = std::move(H);
144}
145
Sam McCalld20d7982018-07-09 14:25:59 +0000146bool JSONRPCDispatcher::call(const json::Value &Message,
147 JSONOutput &Out) const {
Sam McCallec109022017-11-28 09:37:43 +0000148 // Message must be an object with "jsonrpc":"2.0".
Sam McCalld20d7982018-07-09 14:25:59 +0000149 auto *Object = Message.getAsObject();
Sam McCallec109022017-11-28 09:37:43 +0000150 if (!Object || Object->getString("jsonrpc") != Optional<StringRef>("2.0"))
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000151 return false;
Sam McCallec109022017-11-28 09:37:43 +0000152 // ID may be any JSON value. If absent, this is a notification.
Sam McCalld20d7982018-07-09 14:25:59 +0000153 llvm::Optional<json::Value> ID;
Sam McCallec109022017-11-28 09:37:43 +0000154 if (auto *I = Object->get("id"))
155 ID = std::move(*I);
156 // Method must be given.
157 auto Method = Object->getString("method");
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000158 if (!Method)
159 return false;
Sam McCallec109022017-11-28 09:37:43 +0000160 // Params should be given, use null if not.
Sam McCalld20d7982018-07-09 14:25:59 +0000161 json::Value Params = nullptr;
Sam McCallec109022017-11-28 09:37:43 +0000162 if (auto *P = Object->get("params"))
163 Params = std::move(*P);
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000164
Sam McCallec109022017-11-28 09:37:43 +0000165 auto I = Handlers.find(*Method);
166 auto &Handler = I != Handlers.end() ? I->second : UnknownHandler;
Ilya Biryukov940901e2017-12-13 12:51:22 +0000167
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000168 // Create a Context that contains request information.
Sam McCalld1a7a372018-01-31 13:40:48 +0000169 WithContextValue WithRequestOut(RequestOut, &Out);
170 llvm::Optional<WithContextValue> WithID;
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000171 if (ID)
Sam McCalld1a7a372018-01-31 13:40:48 +0000172 WithID.emplace(RequestID, *ID);
Ilya Biryukovee27d2e2017-12-14 15:04:59 +0000173
174 // Create a tracing Span covering the whole request lifetime.
Sam McCalld1a7a372018-01-31 13:40:48 +0000175 trace::Span Tracer(*Method);
Ilya Biryukov940901e2017-12-13 12:51:22 +0000176 if (ID)
Sam McCall1b475a12018-01-26 09:00:30 +0000177 SPAN_ATTACH(Tracer, "ID", *ID);
178 SPAN_ATTACH(Tracer, "Params", Params);
Ilya Biryukov940901e2017-12-13 12:51:22 +0000179
Sam McCall1b475a12018-01-26 09:00:30 +0000180 // Stash a reference to the span args, so later calls can add metadata.
Sam McCalld1a7a372018-01-31 13:40:48 +0000181 WithContext WithRequestSpan(RequestSpan::stash(Tracer));
182 Handler(std::move(Params));
Benjamin Kramerbb1cdb62017-02-07 10:28:20 +0000183 return true;
184}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000185
Sam McCall27a07cf2018-06-05 09:34:46 +0000186// Tries to read a line up to and including \n.
187// If failing, feof() or ferror() will be set.
188static bool readLine(std::FILE *In, std::string &Out) {
189 static constexpr int BufSize = 1024;
190 size_t Size = 0;
191 Out.clear();
192 for (;;) {
193 Out.resize(Size + BufSize);
194 // Handle EINTR which is sent when a debugger attaches on some platforms.
195 if (!llvm::sys::RetryAfterSignal(nullptr, ::fgets, &Out[Size], BufSize, In))
196 return false;
197 clearerr(In);
198 // If the line contained null bytes, anything after it (including \n) will
199 // be ignored. Fortunately this is not a legal header or JSON.
200 size_t Read = std::strlen(&Out[Size]);
201 if (Read > 0 && Out[Size + Read - 1] == '\n') {
202 Out.resize(Size + Read);
203 return true;
204 }
205 Size += Read;
206 }
207}
208
209// Returns None when:
210// - ferror() or feof() are set.
211// - Content-Length is missing or empty (protocol error)
212static llvm::Optional<std::string> readStandardMessage(std::FILE *In,
Sam McCall5ed599e2018-02-06 10:47:30 +0000213 JSONOutput &Out) {
214 // A Language Server Protocol message starts with a set of HTTP headers,
215 // delimited by \r\n, and terminated by an empty line (\r\n).
216 unsigned long long ContentLength = 0;
Sam McCall27a07cf2018-06-05 09:34:46 +0000217 std::string Line;
218 while (true) {
219 if (feof(In) || ferror(In) || !readLine(In, Line))
220 return llvm::None;
Benjamin Kramer1d053792017-10-27 17:06:41 +0000221
Sam McCall5ed599e2018-02-06 10:47:30 +0000222 Out.mirrorInput(Line);
Sam McCall5ed599e2018-02-06 10:47:30 +0000223 llvm::StringRef LineRef(Line);
Sam McCall8567cb32017-11-02 09:21:51 +0000224
Sam McCall5ed599e2018-02-06 10:47:30 +0000225 // We allow comments in headers. Technically this isn't part
226 // of the LSP specification, but makes writing tests easier.
227 if (LineRef.startswith("#"))
228 continue;
229
Sam McCall27a07cf2018-06-05 09:34:46 +0000230 // Content-Length is a mandatory header, and the only one we handle.
Sam McCall5ed599e2018-02-06 10:47:30 +0000231 if (LineRef.consume_front("Content-Length: ")) {
232 if (ContentLength != 0) {
233 log("Warning: Duplicate Content-Length header received. "
234 "The previous value for this message (" +
Sam McCall27a07cf2018-06-05 09:34:46 +0000235 llvm::Twine(ContentLength) + ") was ignored.");
Ilya Biryukov1fab4f82017-09-04 12:28:15 +0000236 }
Sam McCall5ed599e2018-02-06 10:47:30 +0000237 llvm::getAsUnsignedInteger(LineRef.trim(), 0, ContentLength);
238 continue;
239 } else if (!LineRef.trim().empty()) {
240 // It's another header, ignore it.
241 continue;
242 } else {
243 // An empty line indicates the end of headers.
244 // Go ahead and read the JSON.
245 break;
246 }
247 }
248
Sam McCall27a07cf2018-06-05 09:34:46 +0000249 // The fuzzer likes crashing us by sending "Content-Length: 9999999999999999"
Sam McCall5ed599e2018-02-06 10:47:30 +0000250 if (ContentLength > 1 << 30) { // 1024M
Sam McCall27a07cf2018-06-05 09:34:46 +0000251 log("Refusing to read message with long Content-Length: " +
252 Twine(ContentLength) + ". Expect protocol errors.");
253 return llvm::None;
254 }
255 if (ContentLength == 0) {
256 log("Warning: Missing Content-Length header, or zero-length message.");
Sam McCall5ed599e2018-02-06 10:47:30 +0000257 return llvm::None;
258 }
259
Sam McCall27a07cf2018-06-05 09:34:46 +0000260 std::string JSON(ContentLength, '\0');
261 for (size_t Pos = 0, Read; Pos < ContentLength; Pos += Read) {
262 // Handle EINTR which is sent when a debugger attaches on some platforms.
263 Read = llvm::sys::RetryAfterSignal(0u, ::fread, &JSON[Pos], 1,
264 ContentLength - Pos, In);
265 Out.mirrorInput(StringRef(&JSON[Pos], Read));
266 if (Read == 0) {
267 log("Input was aborted. Read only " + llvm::Twine(Pos) +
268 " bytes of expected " + llvm::Twine(ContentLength) + ".");
Sam McCall5ed599e2018-02-06 10:47:30 +0000269 return llvm::None;
270 }
Sam McCall27a07cf2018-06-05 09:34:46 +0000271 clearerr(In); // If we're done, the error was transient. If we're not done,
272 // either it was transient or we'll see it again on retry.
273 Pos += Read;
Sam McCall5ed599e2018-02-06 10:47:30 +0000274 }
Sam McCall27a07cf2018-06-05 09:34:46 +0000275 return std::move(JSON);
Sam McCall5ed599e2018-02-06 10:47:30 +0000276}
277
278// For lit tests we support a simplified syntax:
279// - messages are delimited by '---' on a line by itself
280// - lines starting with # are ignored.
281// This is a testing path, so favor simplicity over performance here.
Sam McCall27a07cf2018-06-05 09:34:46 +0000282// When returning None, feof() or ferror() will be set.
283static llvm::Optional<std::string> readDelimitedMessage(std::FILE *In,
Sam McCall5ed599e2018-02-06 10:47:30 +0000284 JSONOutput &Out) {
285 std::string JSON;
286 std::string Line;
Sam McCall27a07cf2018-06-05 09:34:46 +0000287 while (readLine(In, Line)) {
Sam McCall5ed599e2018-02-06 10:47:30 +0000288 auto LineRef = llvm::StringRef(Line).trim();
289 if (LineRef.startswith("#")) // comment
290 continue;
291
Jan Korous62435152018-04-23 15:55:07 +0000292 // found a delimiter
Jan Korous1bc528c2018-04-23 15:58:42 +0000293 if (LineRef.rtrim() == "---")
Jan Korous62435152018-04-23 15:55:07 +0000294 break;
295
296 JSON += Line;
Sam McCall5ed599e2018-02-06 10:47:30 +0000297 }
298
Sam McCall27a07cf2018-06-05 09:34:46 +0000299 if (ferror(In)) {
Sam McCall5ed599e2018-02-06 10:47:30 +0000300 log("Input error while reading message!");
301 return llvm::None;
Sam McCall27a07cf2018-06-05 09:34:46 +0000302 } else { // Including EOF
Jan Korous62435152018-04-23 15:55:07 +0000303 Out.mirrorInput(
304 llvm::formatv("Content-Length: {0}\r\n\r\n{1}", JSON.size(), JSON));
Sam McCall5ed599e2018-02-06 10:47:30 +0000305 return std::move(JSON);
306 }
307}
308
Sam McCall27a07cf2018-06-05 09:34:46 +0000309// The use of C-style std::FILE* IO deserves some explanation.
310// Previously, std::istream was used. When a debugger attached on MacOS, the
311// process received EINTR, the stream went bad, and clangd exited.
312// A retry-on-EINTR loop around reads solved this problem, but caused clangd to
313// sometimes hang rather than exit on other OSes. The interaction between
314// istreams and signals isn't well-specified, so it's hard to get this right.
315// The C APIs seem to be clearer in this respect.
316void clangd::runLanguageServerLoop(std::FILE *In, JSONOutput &Out,
Sam McCall5ed599e2018-02-06 10:47:30 +0000317 JSONStreamStyle InputStyle,
318 JSONRPCDispatcher &Dispatcher,
319 bool &IsDone) {
320 auto &ReadMessage =
321 (InputStyle == Delimited) ? readDelimitedMessage : readStandardMessage;
Sam McCall27a07cf2018-06-05 09:34:46 +0000322 while (!IsDone && !feof(In)) {
323 if (ferror(In)) {
324 log("IO error: " + llvm::sys::StrError());
325 return;
326 }
Sam McCall5ed599e2018-02-06 10:47:30 +0000327 if (auto JSON = ReadMessage(In, Out)) {
328 if (auto Doc = json::parse(*JSON)) {
Sam McCallec109022017-11-28 09:37:43 +0000329 // Log the formatted message.
Sam McCalld1a7a372018-01-31 13:40:48 +0000330 log(llvm::formatv(Out.Pretty ? "<-- {0:2}\n" : "<-- {0}\n", *Doc));
Sam McCallec109022017-11-28 09:37:43 +0000331 // Finally, execute the action for this JSON message.
332 if (!Dispatcher.call(*Doc, Out))
Sam McCall27a07cf2018-06-05 09:34:46 +0000333 log("JSON dispatch failed!");
Sam McCallec109022017-11-28 09:37:43 +0000334 } else {
335 // Parse error. Log the raw message.
Sam McCall5ed599e2018-02-06 10:47:30 +0000336 log(llvm::formatv("<-- {0}\n" , *JSON));
Sam McCalld1a7a372018-01-31 13:40:48 +0000337 log(llvm::Twine("JSON parse error: ") +
Sam McCall27a07cf2018-06-05 09:34:46 +0000338 llvm::toString(Doc.takeError()));
Sam McCallec109022017-11-28 09:37:43 +0000339 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000340 }
341 }
342}