Benjamin Kramer | bb1cdb6 | 2017-02-07 10:28:20 +0000 | [diff] [blame] | 1 | //===--- 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" |
Kadir Cetinkaya | 689bf93 | 2018-08-24 13:09:41 +0000 | [diff] [blame^] | 11 | #include "Cancellation.h" |
Benjamin Kramer | bb1cdb6 | 2017-02-07 10:28:20 +0000 | [diff] [blame] | 12 | #include "ProtocolHandlers.h" |
Sam McCall | 8567cb3 | 2017-11-02 09:21:51 +0000 | [diff] [blame] | 13 | #include "Trace.h" |
Benjamin Kramer | bb1cdb6 | 2017-02-07 10:28:20 +0000 | [diff] [blame] | 14 | #include "llvm/ADT/SmallString.h" |
Sam McCall | 94362c6 | 2017-11-07 14:45:31 +0000 | [diff] [blame] | 15 | #include "llvm/ADT/StringExtras.h" |
Sam McCall | a90f257 | 2018-02-16 16:41:42 +0000 | [diff] [blame] | 16 | #include "llvm/Support/Chrono.h" |
Sam McCall | 27a07cf | 2018-06-05 09:34:46 +0000 | [diff] [blame] | 17 | #include "llvm/Support/Errno.h" |
Sam McCall | bed5885 | 2018-07-11 10:35:11 +0000 | [diff] [blame] | 18 | #include "llvm/Support/FormatVariadic.h" |
Sam McCall | d20d798 | 2018-07-09 14:25:59 +0000 | [diff] [blame] | 19 | #include "llvm/Support/JSON.h" |
Benjamin Kramer | bb1cdb6 | 2017-02-07 10:28:20 +0000 | [diff] [blame] | 20 | #include "llvm/Support/SourceMgr.h" |
Ilya Biryukov | 687b92a | 2017-05-16 15:23:55 +0000 | [diff] [blame] | 21 | #include <istream> |
| 22 | |
Sam McCall | d20d798 | 2018-07-09 14:25:59 +0000 | [diff] [blame] | 23 | using namespace llvm; |
Benjamin Kramer | bb1cdb6 | 2017-02-07 10:28:20 +0000 | [diff] [blame] | 24 | using namespace clang; |
| 25 | using namespace clangd; |
| 26 | |
Ilya Biryukov | 940901e | 2017-12-13 12:51:22 +0000 | [diff] [blame] | 27 | namespace { |
Sam McCall | d20d798 | 2018-07-09 14:25:59 +0000 | [diff] [blame] | 28 | static Key<json::Value> RequestID; |
Ilya Biryukov | 940901e | 2017-12-13 12:51:22 +0000 | [diff] [blame] | 29 | static Key<JSONOutput *> RequestOut; |
Sam McCall | 1b475a1 | 2018-01-26 09:00:30 +0000 | [diff] [blame] | 30 | |
| 31 | // When tracing, we trace a request and attach the repsonse in reply(). |
| 32 | // Because the Span isn't available, we find the current request using Context. |
| 33 | class RequestSpan { |
Sam McCall | d20d798 | 2018-07-09 14:25:59 +0000 | [diff] [blame] | 34 | RequestSpan(llvm::json::Object *Args) : Args(Args) {} |
Sam McCall | 1b475a1 | 2018-01-26 09:00:30 +0000 | [diff] [blame] | 35 | std::mutex Mu; |
Sam McCall | d20d798 | 2018-07-09 14:25:59 +0000 | [diff] [blame] | 36 | llvm::json::Object *Args; |
Sam McCall | 24f0fa3 | 2018-01-26 11:23:33 +0000 | [diff] [blame] | 37 | static Key<std::unique_ptr<RequestSpan>> RSKey; |
Sam McCall | 1b475a1 | 2018-01-26 09:00:30 +0000 | [diff] [blame] | 38 | |
| 39 | public: |
| 40 | // Return a context that's aware of the enclosing request, identified by Span. |
| 41 | static Context stash(const trace::Span &Span) { |
Sam McCall | d1a7a37 | 2018-01-31 13:40:48 +0000 | [diff] [blame] | 42 | return Context::current().derive( |
| 43 | RSKey, std::unique_ptr<RequestSpan>(new RequestSpan(Span.Args))); |
Sam McCall | 1b475a1 | 2018-01-26 09:00:30 +0000 | [diff] [blame] | 44 | } |
| 45 | |
| 46 | // If there's an enclosing request and the tracer is interested, calls \p F |
Sam McCall | d20d798 | 2018-07-09 14:25:59 +0000 | [diff] [blame] | 47 | // with a json::Object where request info can be added. |
Sam McCall | d1a7a37 | 2018-01-31 13:40:48 +0000 | [diff] [blame] | 48 | template <typename Func> static void attach(Func &&F) { |
| 49 | auto *RequestArgs = Context::current().get(RSKey); |
Sam McCall | 1b475a1 | 2018-01-26 09:00:30 +0000 | [diff] [blame] | 50 | if (!RequestArgs || !*RequestArgs || !(*RequestArgs)->Args) |
| 51 | return; |
| 52 | std::lock_guard<std::mutex> Lock((*RequestArgs)->Mu); |
| 53 | F(*(*RequestArgs)->Args); |
| 54 | } |
| 55 | }; |
Sam McCall | 24f0fa3 | 2018-01-26 11:23:33 +0000 | [diff] [blame] | 56 | Key<std::unique_ptr<RequestSpan>> RequestSpan::RSKey; |
Ilya Biryukov | 940901e | 2017-12-13 12:51:22 +0000 | [diff] [blame] | 57 | } // namespace |
| 58 | |
Sam McCall | d20d798 | 2018-07-09 14:25:59 +0000 | [diff] [blame] | 59 | void JSONOutput::writeMessage(const json::Value &Message) { |
Sam McCall | dd0566b | 2017-11-06 15:40:30 +0000 | [diff] [blame] | 60 | std::string S; |
| 61 | llvm::raw_string_ostream OS(S); |
| 62 | if (Pretty) |
| 63 | OS << llvm::formatv("{0:2}", Message); |
| 64 | else |
| 65 | OS << Message; |
| 66 | OS.flush(); |
Benjamin Kramer | bb1cdb6 | 2017-02-07 10:28:20 +0000 | [diff] [blame] | 67 | |
Sam McCall | a90f257 | 2018-02-16 16:41:42 +0000 | [diff] [blame] | 68 | { |
| 69 | std::lock_guard<std::mutex> Guard(StreamMutex); |
| 70 | Outs << "Content-Length: " << S.size() << "\r\n\r\n" << S; |
| 71 | Outs.flush(); |
| 72 | } |
Sam McCall | 8d7760c | 2018-07-12 11:52:18 +0000 | [diff] [blame] | 73 | vlog(">>> {0}\n", S); |
Benjamin Kramer | bb1cdb6 | 2017-02-07 10:28:20 +0000 | [diff] [blame] | 74 | } |
| 75 | |
Sam McCall | bed5885 | 2018-07-11 10:35:11 +0000 | [diff] [blame] | 76 | void JSONOutput::log(Logger::Level Level, |
| 77 | const llvm::formatv_object_base &Message) { |
| 78 | if (Level < MinLevel) |
| 79 | return; |
Sam McCall | a90f257 | 2018-02-16 16:41:42 +0000 | [diff] [blame] | 80 | llvm::sys::TimePoint<> Timestamp = std::chrono::system_clock::now(); |
Sam McCall | d1a7a37 | 2018-01-31 13:40:48 +0000 | [diff] [blame] | 81 | trace::log(Message); |
Benjamin Kramer | e14bd42 | 2017-02-15 16:44:11 +0000 | [diff] [blame] | 82 | std::lock_guard<std::mutex> Guard(StreamMutex); |
Sam McCall | bed5885 | 2018-07-11 10:35:11 +0000 | [diff] [blame] | 83 | Logs << llvm::formatv("{0}[{1:%H:%M:%S.%L}] {2}\n", indicator(Level), |
| 84 | Timestamp, Message); |
Benjamin Kramer | e14bd42 | 2017-02-15 16:44:11 +0000 | [diff] [blame] | 85 | Logs.flush(); |
| 86 | } |
| 87 | |
Ilya Biryukov | e6dbb58 | 2017-10-10 09:08:47 +0000 | [diff] [blame] | 88 | void JSONOutput::mirrorInput(const Twine &Message) { |
| 89 | if (!InputMirror) |
| 90 | return; |
| 91 | |
| 92 | *InputMirror << Message; |
| 93 | InputMirror->flush(); |
| 94 | } |
| 95 | |
Sam McCall | d20d798 | 2018-07-09 14:25:59 +0000 | [diff] [blame] | 96 | void clangd::reply(json::Value &&Result) { |
Kadir Cetinkaya | 689bf93 | 2018-08-24 13:09:41 +0000 | [diff] [blame^] | 97 | auto ID = getRequestId(); |
Sam McCall | dd0566b | 2017-11-06 15:40:30 +0000 | [diff] [blame] | 98 | if (!ID) { |
Sam McCall | bed5885 | 2018-07-11 10:35:11 +0000 | [diff] [blame] | 99 | elog("Attempted to reply to a notification!"); |
Sam McCall | 8a5dded | 2017-10-12 13:29:58 +0000 | [diff] [blame] | 100 | return; |
| 101 | } |
Sam McCall | d20d798 | 2018-07-09 14:25:59 +0000 | [diff] [blame] | 102 | RequestSpan::attach([&](json::Object &Args) { Args["Reply"] = Result; }); |
Sam McCall | 8d7760c | 2018-07-12 11:52:18 +0000 | [diff] [blame] | 103 | log("--> reply({0})", *ID); |
Sam McCall | d1a7a37 | 2018-01-31 13:40:48 +0000 | [diff] [blame] | 104 | Context::current() |
| 105 | .getExisting(RequestOut) |
Sam McCall | d20d798 | 2018-07-09 14:25:59 +0000 | [diff] [blame] | 106 | ->writeMessage(json::Object{ |
Ilya Biryukov | 940901e | 2017-12-13 12:51:22 +0000 | [diff] [blame] | 107 | {"jsonrpc", "2.0"}, |
| 108 | {"id", *ID}, |
| 109 | {"result", std::move(Result)}, |
| 110 | }); |
Benjamin Kramer | bb1cdb6 | 2017-02-07 10:28:20 +0000 | [diff] [blame] | 111 | } |
| 112 | |
Ilya Biryukov | 74f2655 | 2018-07-26 12:05:31 +0000 | [diff] [blame] | 113 | void clangd::replyError(ErrorCode Code, const llvm::StringRef &Message) { |
| 114 | elog("Error {0}: {1}", static_cast<int>(Code), Message); |
Sam McCall | d20d798 | 2018-07-09 14:25:59 +0000 | [diff] [blame] | 115 | RequestSpan::attach([&](json::Object &Args) { |
Ilya Biryukov | 74f2655 | 2018-07-26 12:05:31 +0000 | [diff] [blame] | 116 | Args["Error"] = json::Object{{"code", static_cast<int>(Code)}, |
Sam McCall | d20d798 | 2018-07-09 14:25:59 +0000 | [diff] [blame] | 117 | {"message", Message.str()}}; |
Sam McCall | 1b475a1 | 2018-01-26 09:00:30 +0000 | [diff] [blame] | 118 | }); |
Ilya Biryukov | 940901e | 2017-12-13 12:51:22 +0000 | [diff] [blame] | 119 | |
Kadir Cetinkaya | 689bf93 | 2018-08-24 13:09:41 +0000 | [diff] [blame^] | 120 | if (auto ID = getRequestId()) { |
Sam McCall | 8d7760c | 2018-07-12 11:52:18 +0000 | [diff] [blame] | 121 | log("--> reply({0}) error: {1}", *ID, Message); |
Sam McCall | d1a7a37 | 2018-01-31 13:40:48 +0000 | [diff] [blame] | 122 | Context::current() |
| 123 | .getExisting(RequestOut) |
Sam McCall | d20d798 | 2018-07-09 14:25:59 +0000 | [diff] [blame] | 124 | ->writeMessage(json::Object{ |
Ilya Biryukov | 940901e | 2017-12-13 12:51:22 +0000 | [diff] [blame] | 125 | {"jsonrpc", "2.0"}, |
| 126 | {"id", *ID}, |
Ilya Biryukov | 74f2655 | 2018-07-26 12:05:31 +0000 | [diff] [blame] | 127 | {"error", json::Object{{"code", static_cast<int>(Code)}, |
Sam McCall | d20d798 | 2018-07-09 14:25:59 +0000 | [diff] [blame] | 128 | {"message", Message}}}, |
Ilya Biryukov | 940901e | 2017-12-13 12:51:22 +0000 | [diff] [blame] | 129 | }); |
Sam McCall | 8a5dded | 2017-10-12 13:29:58 +0000 | [diff] [blame] | 130 | } |
Benjamin Kramer | bb1cdb6 | 2017-02-07 10:28:20 +0000 | [diff] [blame] | 131 | } |
| 132 | |
Kadir Cetinkaya | 689bf93 | 2018-08-24 13:09:41 +0000 | [diff] [blame^] | 133 | void clangd::replyError(Error E) { |
| 134 | handleAllErrors(std::move(E), |
| 135 | [](const CancelledError &TCE) { |
| 136 | replyError(ErrorCode::RequestCancelled, TCE.message()); |
| 137 | }, |
| 138 | [](const ErrorInfoBase &EIB) { |
| 139 | replyError(ErrorCode::InvalidParams, EIB.message()); |
| 140 | }); |
| 141 | } |
| 142 | |
Sam McCall | d20d798 | 2018-07-09 14:25:59 +0000 | [diff] [blame] | 143 | void clangd::call(StringRef Method, json::Value &&Params) { |
Sam McCall | d20d798 | 2018-07-09 14:25:59 +0000 | [diff] [blame] | 144 | RequestSpan::attach([&](json::Object &Args) { |
| 145 | Args["Call"] = json::Object{{"method", Method.str()}, {"params", Params}}; |
Sam McCall | 1b475a1 | 2018-01-26 09:00:30 +0000 | [diff] [blame] | 146 | }); |
Sam McCall | 8d7760c | 2018-07-12 11:52:18 +0000 | [diff] [blame] | 147 | // FIXME: Generate/Increment IDs for every request so that we can get proper |
| 148 | // replies once we need to. |
| 149 | auto ID = 1; |
| 150 | log("--> {0}({1})", Method, ID); |
Sam McCall | d1a7a37 | 2018-01-31 13:40:48 +0000 | [diff] [blame] | 151 | Context::current() |
| 152 | .getExisting(RequestOut) |
Sam McCall | d20d798 | 2018-07-09 14:25:59 +0000 | [diff] [blame] | 153 | ->writeMessage(json::Object{ |
Ilya Biryukov | 940901e | 2017-12-13 12:51:22 +0000 | [diff] [blame] | 154 | {"jsonrpc", "2.0"}, |
Sam McCall | 8d7760c | 2018-07-12 11:52:18 +0000 | [diff] [blame] | 155 | {"id", ID}, |
Ilya Biryukov | 940901e | 2017-12-13 12:51:22 +0000 | [diff] [blame] | 156 | {"method", Method}, |
| 157 | {"params", std::move(Params)}, |
| 158 | }); |
Marc-Andre Laperle | e7ec16a | 2017-11-03 13:39:15 +0000 | [diff] [blame] | 159 | } |
| 160 | |
Sam McCall | 8a5dded | 2017-10-12 13:29:58 +0000 | [diff] [blame] | 161 | void JSONRPCDispatcher::registerHandler(StringRef Method, Handler H) { |
Benjamin Kramer | bb1cdb6 | 2017-02-07 10:28:20 +0000 | [diff] [blame] | 162 | assert(!Handlers.count(Method) && "Handler already registered!"); |
| 163 | Handlers[Method] = std::move(H); |
| 164 | } |
| 165 | |
Sam McCall | 8d7760c | 2018-07-12 11:52:18 +0000 | [diff] [blame] | 166 | static void logIncomingMessage(const llvm::Optional<json::Value> &ID, |
| 167 | llvm::Optional<StringRef> Method, |
| 168 | const json::Object *Error) { |
| 169 | if (Method) { // incoming request |
| 170 | if (ID) // call |
| 171 | log("<-- {0}({1})", *Method, *ID); |
| 172 | else // notification |
| 173 | log("<-- {0}", *Method); |
| 174 | } else if (ID) { // response, ID must be provided |
| 175 | if (Error) |
| 176 | log("<-- reply({0}) error: {1}", *ID, |
| 177 | Error->getString("message").getValueOr("<no message>")); |
| 178 | else |
| 179 | log("<-- reply({0})", *ID); |
| 180 | } |
| 181 | } |
| 182 | |
Sam McCall | d20d798 | 2018-07-09 14:25:59 +0000 | [diff] [blame] | 183 | bool JSONRPCDispatcher::call(const json::Value &Message, |
| 184 | JSONOutput &Out) const { |
Sam McCall | ec10902 | 2017-11-28 09:37:43 +0000 | [diff] [blame] | 185 | // Message must be an object with "jsonrpc":"2.0". |
Sam McCall | d20d798 | 2018-07-09 14:25:59 +0000 | [diff] [blame] | 186 | auto *Object = Message.getAsObject(); |
Sam McCall | ec10902 | 2017-11-28 09:37:43 +0000 | [diff] [blame] | 187 | if (!Object || Object->getString("jsonrpc") != Optional<StringRef>("2.0")) |
Benjamin Kramer | bb1cdb6 | 2017-02-07 10:28:20 +0000 | [diff] [blame] | 188 | return false; |
Sam McCall | ec10902 | 2017-11-28 09:37:43 +0000 | [diff] [blame] | 189 | // ID may be any JSON value. If absent, this is a notification. |
Sam McCall | d20d798 | 2018-07-09 14:25:59 +0000 | [diff] [blame] | 190 | llvm::Optional<json::Value> ID; |
Sam McCall | ec10902 | 2017-11-28 09:37:43 +0000 | [diff] [blame] | 191 | if (auto *I = Object->get("id")) |
| 192 | ID = std::move(*I); |
Sam McCall | ec10902 | 2017-11-28 09:37:43 +0000 | [diff] [blame] | 193 | auto Method = Object->getString("method"); |
Sam McCall | 8d7760c | 2018-07-12 11:52:18 +0000 | [diff] [blame] | 194 | logIncomingMessage(ID, Method, Object->getObject("error")); |
| 195 | if (!Method) // We only handle incoming requests, and ignore responses. |
Benjamin Kramer | bb1cdb6 | 2017-02-07 10:28:20 +0000 | [diff] [blame] | 196 | return false; |
Sam McCall | ec10902 | 2017-11-28 09:37:43 +0000 | [diff] [blame] | 197 | // Params should be given, use null if not. |
Sam McCall | d20d798 | 2018-07-09 14:25:59 +0000 | [diff] [blame] | 198 | json::Value Params = nullptr; |
Sam McCall | ec10902 | 2017-11-28 09:37:43 +0000 | [diff] [blame] | 199 | if (auto *P = Object->get("params")) |
| 200 | Params = std::move(*P); |
Benjamin Kramer | bb1cdb6 | 2017-02-07 10:28:20 +0000 | [diff] [blame] | 201 | |
Sam McCall | ec10902 | 2017-11-28 09:37:43 +0000 | [diff] [blame] | 202 | auto I = Handlers.find(*Method); |
| 203 | auto &Handler = I != Handlers.end() ? I->second : UnknownHandler; |
Ilya Biryukov | 940901e | 2017-12-13 12:51:22 +0000 | [diff] [blame] | 204 | |
Ilya Biryukov | ee27d2e | 2017-12-14 15:04:59 +0000 | [diff] [blame] | 205 | // Create a Context that contains request information. |
Sam McCall | d1a7a37 | 2018-01-31 13:40:48 +0000 | [diff] [blame] | 206 | WithContextValue WithRequestOut(RequestOut, &Out); |
| 207 | llvm::Optional<WithContextValue> WithID; |
Ilya Biryukov | ee27d2e | 2017-12-14 15:04:59 +0000 | [diff] [blame] | 208 | if (ID) |
Sam McCall | d1a7a37 | 2018-01-31 13:40:48 +0000 | [diff] [blame] | 209 | WithID.emplace(RequestID, *ID); |
Ilya Biryukov | ee27d2e | 2017-12-14 15:04:59 +0000 | [diff] [blame] | 210 | |
| 211 | // Create a tracing Span covering the whole request lifetime. |
Sam McCall | d1a7a37 | 2018-01-31 13:40:48 +0000 | [diff] [blame] | 212 | trace::Span Tracer(*Method); |
Ilya Biryukov | 940901e | 2017-12-13 12:51:22 +0000 | [diff] [blame] | 213 | if (ID) |
Sam McCall | 1b475a1 | 2018-01-26 09:00:30 +0000 | [diff] [blame] | 214 | SPAN_ATTACH(Tracer, "ID", *ID); |
| 215 | SPAN_ATTACH(Tracer, "Params", Params); |
Ilya Biryukov | 940901e | 2017-12-13 12:51:22 +0000 | [diff] [blame] | 216 | |
Sam McCall | 1b475a1 | 2018-01-26 09:00:30 +0000 | [diff] [blame] | 217 | // Stash a reference to the span args, so later calls can add metadata. |
Sam McCall | d1a7a37 | 2018-01-31 13:40:48 +0000 | [diff] [blame] | 218 | WithContext WithRequestSpan(RequestSpan::stash(Tracer)); |
| 219 | Handler(std::move(Params)); |
Benjamin Kramer | bb1cdb6 | 2017-02-07 10:28:20 +0000 | [diff] [blame] | 220 | return true; |
| 221 | } |
Ilya Biryukov | afb5554 | 2017-05-16 14:40:30 +0000 | [diff] [blame] | 222 | |
Sam McCall | 27a07cf | 2018-06-05 09:34:46 +0000 | [diff] [blame] | 223 | // Tries to read a line up to and including \n. |
| 224 | // If failing, feof() or ferror() will be set. |
| 225 | static bool readLine(std::FILE *In, std::string &Out) { |
| 226 | static constexpr int BufSize = 1024; |
| 227 | size_t Size = 0; |
| 228 | Out.clear(); |
| 229 | for (;;) { |
| 230 | Out.resize(Size + BufSize); |
| 231 | // Handle EINTR which is sent when a debugger attaches on some platforms. |
| 232 | if (!llvm::sys::RetryAfterSignal(nullptr, ::fgets, &Out[Size], BufSize, In)) |
| 233 | return false; |
| 234 | clearerr(In); |
| 235 | // If the line contained null bytes, anything after it (including \n) will |
| 236 | // be ignored. Fortunately this is not a legal header or JSON. |
| 237 | size_t Read = std::strlen(&Out[Size]); |
| 238 | if (Read > 0 && Out[Size + Read - 1] == '\n') { |
| 239 | Out.resize(Size + Read); |
| 240 | return true; |
| 241 | } |
| 242 | Size += Read; |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | // Returns None when: |
| 247 | // - ferror() or feof() are set. |
| 248 | // - Content-Length is missing or empty (protocol error) |
| 249 | static llvm::Optional<std::string> readStandardMessage(std::FILE *In, |
Sam McCall | 5ed599e | 2018-02-06 10:47:30 +0000 | [diff] [blame] | 250 | JSONOutput &Out) { |
| 251 | // A Language Server Protocol message starts with a set of HTTP headers, |
| 252 | // delimited by \r\n, and terminated by an empty line (\r\n). |
| 253 | unsigned long long ContentLength = 0; |
Sam McCall | 27a07cf | 2018-06-05 09:34:46 +0000 | [diff] [blame] | 254 | std::string Line; |
| 255 | while (true) { |
| 256 | if (feof(In) || ferror(In) || !readLine(In, Line)) |
| 257 | return llvm::None; |
Benjamin Kramer | 1d05379 | 2017-10-27 17:06:41 +0000 | [diff] [blame] | 258 | |
Sam McCall | 5ed599e | 2018-02-06 10:47:30 +0000 | [diff] [blame] | 259 | Out.mirrorInput(Line); |
Sam McCall | 5ed599e | 2018-02-06 10:47:30 +0000 | [diff] [blame] | 260 | llvm::StringRef LineRef(Line); |
Sam McCall | 8567cb3 | 2017-11-02 09:21:51 +0000 | [diff] [blame] | 261 | |
Sam McCall | 5ed599e | 2018-02-06 10:47:30 +0000 | [diff] [blame] | 262 | // We allow comments in headers. Technically this isn't part |
| 263 | // of the LSP specification, but makes writing tests easier. |
| 264 | if (LineRef.startswith("#")) |
| 265 | continue; |
| 266 | |
Sam McCall | 27a07cf | 2018-06-05 09:34:46 +0000 | [diff] [blame] | 267 | // Content-Length is a mandatory header, and the only one we handle. |
Sam McCall | 5ed599e | 2018-02-06 10:47:30 +0000 | [diff] [blame] | 268 | if (LineRef.consume_front("Content-Length: ")) { |
| 269 | if (ContentLength != 0) { |
Sam McCall | bed5885 | 2018-07-11 10:35:11 +0000 | [diff] [blame] | 270 | elog("Warning: Duplicate Content-Length header received. " |
| 271 | "The previous value for this message ({0}) was ignored.", |
| 272 | ContentLength); |
Ilya Biryukov | 1fab4f8 | 2017-09-04 12:28:15 +0000 | [diff] [blame] | 273 | } |
Sam McCall | 5ed599e | 2018-02-06 10:47:30 +0000 | [diff] [blame] | 274 | llvm::getAsUnsignedInteger(LineRef.trim(), 0, ContentLength); |
| 275 | continue; |
| 276 | } else if (!LineRef.trim().empty()) { |
| 277 | // It's another header, ignore it. |
| 278 | continue; |
| 279 | } else { |
| 280 | // An empty line indicates the end of headers. |
| 281 | // Go ahead and read the JSON. |
| 282 | break; |
| 283 | } |
| 284 | } |
| 285 | |
Sam McCall | 27a07cf | 2018-06-05 09:34:46 +0000 | [diff] [blame] | 286 | // The fuzzer likes crashing us by sending "Content-Length: 9999999999999999" |
Sam McCall | 5ed599e | 2018-02-06 10:47:30 +0000 | [diff] [blame] | 287 | if (ContentLength > 1 << 30) { // 1024M |
Sam McCall | bed5885 | 2018-07-11 10:35:11 +0000 | [diff] [blame] | 288 | elog("Refusing to read message with long Content-Length: {0}. " |
| 289 | "Expect protocol errors", |
| 290 | ContentLength); |
Sam McCall | 27a07cf | 2018-06-05 09:34:46 +0000 | [diff] [blame] | 291 | return llvm::None; |
| 292 | } |
| 293 | if (ContentLength == 0) { |
| 294 | log("Warning: Missing Content-Length header, or zero-length message."); |
Sam McCall | 5ed599e | 2018-02-06 10:47:30 +0000 | [diff] [blame] | 295 | return llvm::None; |
| 296 | } |
| 297 | |
Sam McCall | 27a07cf | 2018-06-05 09:34:46 +0000 | [diff] [blame] | 298 | std::string JSON(ContentLength, '\0'); |
| 299 | for (size_t Pos = 0, Read; Pos < ContentLength; Pos += Read) { |
| 300 | // Handle EINTR which is sent when a debugger attaches on some platforms. |
| 301 | Read = llvm::sys::RetryAfterSignal(0u, ::fread, &JSON[Pos], 1, |
| 302 | ContentLength - Pos, In); |
| 303 | Out.mirrorInput(StringRef(&JSON[Pos], Read)); |
| 304 | if (Read == 0) { |
Sam McCall | bed5885 | 2018-07-11 10:35:11 +0000 | [diff] [blame] | 305 | elog("Input was aborted. Read only {0} bytes of expected {1}.", Pos, |
| 306 | ContentLength); |
Sam McCall | 5ed599e | 2018-02-06 10:47:30 +0000 | [diff] [blame] | 307 | return llvm::None; |
| 308 | } |
Sam McCall | 27a07cf | 2018-06-05 09:34:46 +0000 | [diff] [blame] | 309 | clearerr(In); // If we're done, the error was transient. If we're not done, |
| 310 | // either it was transient or we'll see it again on retry. |
| 311 | Pos += Read; |
Sam McCall | 5ed599e | 2018-02-06 10:47:30 +0000 | [diff] [blame] | 312 | } |
Sam McCall | 27a07cf | 2018-06-05 09:34:46 +0000 | [diff] [blame] | 313 | return std::move(JSON); |
Sam McCall | 5ed599e | 2018-02-06 10:47:30 +0000 | [diff] [blame] | 314 | } |
| 315 | |
| 316 | // For lit tests we support a simplified syntax: |
| 317 | // - messages are delimited by '---' on a line by itself |
| 318 | // - lines starting with # are ignored. |
| 319 | // This is a testing path, so favor simplicity over performance here. |
Sam McCall | 27a07cf | 2018-06-05 09:34:46 +0000 | [diff] [blame] | 320 | // When returning None, feof() or ferror() will be set. |
| 321 | static llvm::Optional<std::string> readDelimitedMessage(std::FILE *In, |
Sam McCall | 5ed599e | 2018-02-06 10:47:30 +0000 | [diff] [blame] | 322 | JSONOutput &Out) { |
| 323 | std::string JSON; |
| 324 | std::string Line; |
Sam McCall | 27a07cf | 2018-06-05 09:34:46 +0000 | [diff] [blame] | 325 | while (readLine(In, Line)) { |
Sam McCall | 5ed599e | 2018-02-06 10:47:30 +0000 | [diff] [blame] | 326 | auto LineRef = llvm::StringRef(Line).trim(); |
| 327 | if (LineRef.startswith("#")) // comment |
| 328 | continue; |
| 329 | |
Jan Korous | 6243515 | 2018-04-23 15:55:07 +0000 | [diff] [blame] | 330 | // found a delimiter |
Jan Korous | 1bc528c | 2018-04-23 15:58:42 +0000 | [diff] [blame] | 331 | if (LineRef.rtrim() == "---") |
Jan Korous | 6243515 | 2018-04-23 15:55:07 +0000 | [diff] [blame] | 332 | break; |
| 333 | |
| 334 | JSON += Line; |
Sam McCall | 5ed599e | 2018-02-06 10:47:30 +0000 | [diff] [blame] | 335 | } |
| 336 | |
Sam McCall | 27a07cf | 2018-06-05 09:34:46 +0000 | [diff] [blame] | 337 | if (ferror(In)) { |
Sam McCall | bed5885 | 2018-07-11 10:35:11 +0000 | [diff] [blame] | 338 | elog("Input error while reading message!"); |
Sam McCall | 5ed599e | 2018-02-06 10:47:30 +0000 | [diff] [blame] | 339 | return llvm::None; |
Sam McCall | 27a07cf | 2018-06-05 09:34:46 +0000 | [diff] [blame] | 340 | } else { // Including EOF |
Jan Korous | 6243515 | 2018-04-23 15:55:07 +0000 | [diff] [blame] | 341 | Out.mirrorInput( |
| 342 | llvm::formatv("Content-Length: {0}\r\n\r\n{1}", JSON.size(), JSON)); |
Sam McCall | 5ed599e | 2018-02-06 10:47:30 +0000 | [diff] [blame] | 343 | return std::move(JSON); |
| 344 | } |
| 345 | } |
| 346 | |
Sam McCall | 27a07cf | 2018-06-05 09:34:46 +0000 | [diff] [blame] | 347 | // The use of C-style std::FILE* IO deserves some explanation. |
| 348 | // Previously, std::istream was used. When a debugger attached on MacOS, the |
| 349 | // process received EINTR, the stream went bad, and clangd exited. |
| 350 | // A retry-on-EINTR loop around reads solved this problem, but caused clangd to |
| 351 | // sometimes hang rather than exit on other OSes. The interaction between |
| 352 | // istreams and signals isn't well-specified, so it's hard to get this right. |
| 353 | // The C APIs seem to be clearer in this respect. |
| 354 | void clangd::runLanguageServerLoop(std::FILE *In, JSONOutput &Out, |
Sam McCall | 5ed599e | 2018-02-06 10:47:30 +0000 | [diff] [blame] | 355 | JSONStreamStyle InputStyle, |
| 356 | JSONRPCDispatcher &Dispatcher, |
| 357 | bool &IsDone) { |
| 358 | auto &ReadMessage = |
| 359 | (InputStyle == Delimited) ? readDelimitedMessage : readStandardMessage; |
Sam McCall | 27a07cf | 2018-06-05 09:34:46 +0000 | [diff] [blame] | 360 | while (!IsDone && !feof(In)) { |
| 361 | if (ferror(In)) { |
Sam McCall | bed5885 | 2018-07-11 10:35:11 +0000 | [diff] [blame] | 362 | elog("IO error: {0}", llvm::sys::StrError()); |
Sam McCall | 27a07cf | 2018-06-05 09:34:46 +0000 | [diff] [blame] | 363 | return; |
| 364 | } |
Sam McCall | 5ed599e | 2018-02-06 10:47:30 +0000 | [diff] [blame] | 365 | if (auto JSON = ReadMessage(In, Out)) { |
| 366 | if (auto Doc = json::parse(*JSON)) { |
Sam McCall | ec10902 | 2017-11-28 09:37:43 +0000 | [diff] [blame] | 367 | // Log the formatted message. |
Sam McCall | 8d7760c | 2018-07-12 11:52:18 +0000 | [diff] [blame] | 368 | vlog(Out.Pretty ? "<<< {0:2}\n" : "<<< {0}\n", *Doc); |
Sam McCall | ec10902 | 2017-11-28 09:37:43 +0000 | [diff] [blame] | 369 | // Finally, execute the action for this JSON message. |
| 370 | if (!Dispatcher.call(*Doc, Out)) |
Sam McCall | bed5885 | 2018-07-11 10:35:11 +0000 | [diff] [blame] | 371 | elog("JSON dispatch failed!"); |
Sam McCall | ec10902 | 2017-11-28 09:37:43 +0000 | [diff] [blame] | 372 | } else { |
| 373 | // Parse error. Log the raw message. |
Sam McCall | 8d7760c | 2018-07-12 11:52:18 +0000 | [diff] [blame] | 374 | vlog("<<< {0}\n", *JSON); |
Sam McCall | bed5885 | 2018-07-11 10:35:11 +0000 | [diff] [blame] | 375 | elog("JSON parse error: {0}", llvm::toString(Doc.takeError())); |
Sam McCall | ec10902 | 2017-11-28 09:37:43 +0000 | [diff] [blame] | 376 | } |
Ilya Biryukov | afb5554 | 2017-05-16 14:40:30 +0000 | [diff] [blame] | 377 | } |
| 378 | } |
| 379 | } |
Kadir Cetinkaya | 689bf93 | 2018-08-24 13:09:41 +0000 | [diff] [blame^] | 380 | |
| 381 | const json::Value *clangd::getRequestId() { |
| 382 | return Context::current().get(RequestID); |
| 383 | } |