1 //===-- lldb-vscode.cpp -----------------------------------------*- C++ -*-===//
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 <assert.h>
10 #include <limits.h>
11 #include <stdarg.h>
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <sys/stat.h>
16 #include <sys/types.h>
17 #if defined(_WIN32)
18 // We need to #define NOMINMAX in order to skip `min()` and `max()` macro
19 // definitions that conflict with other system headers.
20 // We also need to #undef GetObject (which is defined to GetObjectW) because
21 // the JSON code we use also has methods named `GetObject()` and we conflict
22 // against these.
23 #define NOMINMAX
24 #include <windows.h>
25 #undef GetObject
26 #include <io.h>
27 #else
28 #include <netinet/in.h>
29 #include <sys/socket.h>
30 #include <unistd.h>
31 #endif
32 
33 #include <algorithm>
34 #include <chrono>
35 #include <fstream>
36 #include <map>
37 #include <memory>
38 #include <mutex>
39 #include <set>
40 #include <sstream>
41 #include <thread>
42 #include <vector>
43 
44 #include "llvm/ADT/ArrayRef.h"
45 #include "llvm/Option/Arg.h"
46 #include "llvm/Option/ArgList.h"
47 #include "llvm/Option/Option.h"
48 #include "llvm/Support/Errno.h"
49 #include "llvm/Support/FileSystem.h"
50 #include "llvm/Support/Path.h"
51 #include "llvm/Support/raw_ostream.h"
52 
53 #include "JSONUtils.h"
54 #include "LLDBUtils.h"
55 #include "VSCode.h"
56 
57 #if defined(_WIN32)
58 #ifndef PATH_MAX
59 #define PATH_MAX MAX_PATH
60 #endif
61 typedef int socklen_t;
62 constexpr const char *dev_null_path = "nul";
63 
64 #else
65 constexpr const char *dev_null_path = "/dev/null";
66 
67 #endif
68 
69 using namespace lldb_vscode;
70 
71 namespace {
72 enum ID {
73   OPT_INVALID = 0, // This is not an option ID.
74 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
75                HELPTEXT, METAVAR, VALUES)                                      \
76   OPT_##ID,
77 #include "Options.inc"
78 #undef OPTION
79 };
80 
81 #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
82 #include "Options.inc"
83 #undef PREFIX
84 
85 static const llvm::opt::OptTable::Info InfoTable[] = {
86 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
87                HELPTEXT, METAVAR, VALUES)                                      \
88   {PREFIX,      NAME,      HELPTEXT,                                           \
89    METAVAR,     OPT_##ID,  llvm::opt::Option::KIND##Class,                     \
90    PARAM,       FLAGS,     OPT_##GROUP,                                        \
91    OPT_##ALIAS, ALIASARGS, VALUES},
92 #include "Options.inc"
93 #undef OPTION
94 };
95 class LLDBVSCodeOptTable : public llvm::opt::OptTable {
96 public:
97   LLDBVSCodeOptTable() : OptTable(InfoTable, true) {}
98 };
99 
100 typedef void (*RequestCallback)(const llvm::json::Object &command);
101 
102 enum LaunchMethod { Launch, Attach, AttachForSuspendedLaunch };
103 
104 SOCKET AcceptConnection(int portno) {
105   // Accept a socket connection from any host on "portno".
106   SOCKET newsockfd = -1;
107   struct sockaddr_in serv_addr, cli_addr;
108   SOCKET sockfd = socket(AF_INET, SOCK_STREAM, 0);
109   if (sockfd < 0) {
110     if (g_vsc.log)
111       *g_vsc.log << "error: opening socket (" << strerror(errno) << ")"
112                  << std::endl;
113   } else {
114     memset((char *)&serv_addr, 0, sizeof(serv_addr));
115     serv_addr.sin_family = AF_INET;
116     // serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
117     serv_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
118     serv_addr.sin_port = htons(portno);
119     if (bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
120       if (g_vsc.log)
121         *g_vsc.log << "error: binding socket (" << strerror(errno) << ")"
122                    << std::endl;
123     } else {
124       listen(sockfd, 5);
125       socklen_t clilen = sizeof(cli_addr);
126       newsockfd =
127           llvm::sys::RetryAfterSignal(static_cast<SOCKET>(-1), accept, sockfd,
128                                       (struct sockaddr *)&cli_addr, &clilen);
129       if (newsockfd < 0)
130         if (g_vsc.log)
131           *g_vsc.log << "error: accept (" << strerror(errno) << ")"
132                      << std::endl;
133     }
134 #if defined(_WIN32)
135     closesocket(sockfd);
136 #else
137     close(sockfd);
138 #endif
139   }
140   return newsockfd;
141 }
142 
143 std::vector<const char *> MakeArgv(const llvm::ArrayRef<std::string> &strs) {
144   // Create and return an array of "const char *", one for each C string in
145   // "strs" and terminate the list with a NULL. This can be used for argument
146   // vectors (argv) or environment vectors (envp) like those passed to the
147   // "main" function in C programs.
148   std::vector<const char *> argv;
149   for (const auto &s : strs)
150     argv.push_back(s.c_str());
151   argv.push_back(nullptr);
152   return argv;
153 }
154 
155 // Send a "exited" event to indicate the process has exited.
156 void SendProcessExitedEvent(lldb::SBProcess &process) {
157   llvm::json::Object event(CreateEventObject("exited"));
158   llvm::json::Object body;
159   body.try_emplace("exitCode", (int64_t)process.GetExitStatus());
160   event.try_emplace("body", std::move(body));
161   g_vsc.SendJSON(llvm::json::Value(std::move(event)));
162 }
163 
164 void SendThreadExitedEvent(lldb::tid_t tid) {
165   llvm::json::Object event(CreateEventObject("thread"));
166   llvm::json::Object body;
167   body.try_emplace("reason", "exited");
168   body.try_emplace("threadId", (int64_t)tid);
169   event.try_emplace("body", std::move(body));
170   g_vsc.SendJSON(llvm::json::Value(std::move(event)));
171 }
172 
173 // Send a "terminated" event to indicate the process is done being
174 // debugged.
175 void SendTerminatedEvent() {
176   if (!g_vsc.sent_terminated_event) {
177     g_vsc.sent_terminated_event = true;
178     g_vsc.RunTerminateCommands();
179     // Send a "terminated" event
180     llvm::json::Object event(CreateEventObject("terminated"));
181     g_vsc.SendJSON(llvm::json::Value(std::move(event)));
182   }
183 }
184 
185 // Send a thread stopped event for all threads as long as the process
186 // is stopped.
187 void SendThreadStoppedEvent() {
188   lldb::SBProcess process = g_vsc.target.GetProcess();
189   if (process.IsValid()) {
190     auto state = process.GetState();
191     if (state == lldb::eStateStopped) {
192       llvm::DenseSet<lldb::tid_t> old_thread_ids;
193       old_thread_ids.swap(g_vsc.thread_ids);
194       uint32_t stop_id = process.GetStopID();
195       const uint32_t num_threads = process.GetNumThreads();
196 
197       // First make a pass through the threads to see if the focused thread
198       // has a stop reason. In case the focus thread doesn't have a stop
199       // reason, remember the first thread that has a stop reason so we can
200       // set it as the focus thread if below if needed.
201       lldb::tid_t first_tid_with_reason = LLDB_INVALID_THREAD_ID;
202       uint32_t num_threads_with_reason = 0;
203       for (uint32_t thread_idx = 0; thread_idx < num_threads; ++thread_idx) {
204         lldb::SBThread thread = process.GetThreadAtIndex(thread_idx);
205         const lldb::tid_t tid = thread.GetThreadID();
206         const bool has_reason = ThreadHasStopReason(thread);
207         // If the focus thread doesn't have a stop reason, clear the thread ID
208         if (tid == g_vsc.focus_tid && !has_reason)
209           g_vsc.focus_tid = LLDB_INVALID_THREAD_ID;
210         if (has_reason) {
211           ++num_threads_with_reason;
212           if (first_tid_with_reason == LLDB_INVALID_THREAD_ID)
213             first_tid_with_reason = tid;
214         }
215       }
216 
217       // We will have cleared g_vsc.focus_tid if he focus thread doesn't
218       // have a stop reason, so if it was cleared, or wasn't set, then set the
219       // focus thread to the first thread with a stop reason.
220       if (g_vsc.focus_tid == LLDB_INVALID_THREAD_ID)
221         g_vsc.focus_tid = first_tid_with_reason;
222 
223       // If no threads stopped with a reason, then report the first one so
224       // we at least let the UI know we stopped.
225       if (num_threads_with_reason == 0) {
226         lldb::SBThread thread = process.GetThreadAtIndex(0);
227         g_vsc.SendJSON(CreateThreadStopped(thread, stop_id));
228       } else {
229         for (uint32_t thread_idx = 0; thread_idx < num_threads; ++thread_idx) {
230           lldb::SBThread thread = process.GetThreadAtIndex(thread_idx);
231           g_vsc.thread_ids.insert(thread.GetThreadID());
232           if (ThreadHasStopReason(thread)) {
233             g_vsc.SendJSON(CreateThreadStopped(thread, stop_id));
234           }
235         }
236       }
237 
238       for (auto tid : old_thread_ids) {
239         auto end = g_vsc.thread_ids.end();
240         auto pos = g_vsc.thread_ids.find(tid);
241         if (pos == end)
242           SendThreadExitedEvent(tid);
243       }
244     } else {
245       if (g_vsc.log)
246         *g_vsc.log << "error: SendThreadStoppedEvent() when process"
247                       " isn't stopped ("
248                    << lldb::SBDebugger::StateAsCString(state) << ')'
249                    << std::endl;
250     }
251   } else {
252     if (g_vsc.log)
253       *g_vsc.log << "error: SendThreadStoppedEvent() invalid process"
254                  << std::endl;
255   }
256   g_vsc.RunStopCommands();
257 }
258 
259 // "ProcessEvent": {
260 //   "allOf": [
261 //     { "$ref": "#/definitions/Event" },
262 //     {
263 //       "type": "object",
264 //       "description": "Event message for 'process' event type. The event
265 //                       indicates that the debugger has begun debugging a
266 //                       new process. Either one that it has launched, or one
267 //                       that it has attached to.",
268 //       "properties": {
269 //         "event": {
270 //           "type": "string",
271 //           "enum": [ "process" ]
272 //         },
273 //         "body": {
274 //           "type": "object",
275 //           "properties": {
276 //             "name": {
277 //               "type": "string",
278 //               "description": "The logical name of the process. This is
279 //                               usually the full path to process's executable
280 //                               file. Example: /home/myproj/program.js."
281 //             },
282 //             "systemProcessId": {
283 //               "type": "integer",
284 //               "description": "The system process id of the debugged process.
285 //                               This property will be missing for non-system
286 //                               processes."
287 //             },
288 //             "isLocalProcess": {
289 //               "type": "boolean",
290 //               "description": "If true, the process is running on the same
291 //                               computer as the debug adapter."
292 //             },
293 //             "startMethod": {
294 //               "type": "string",
295 //               "enum": [ "launch", "attach", "attachForSuspendedLaunch" ],
296 //               "description": "Describes how the debug engine started
297 //                               debugging this process.",
298 //               "enumDescriptions": [
299 //                 "Process was launched under the debugger.",
300 //                 "Debugger attached to an existing process.",
301 //                 "A project launcher component has launched a new process in
302 //                  a suspended state and then asked the debugger to attach."
303 //               ]
304 //             }
305 //           },
306 //           "required": [ "name" ]
307 //         }
308 //       },
309 //       "required": [ "event", "body" ]
310 //     }
311 //   ]
312 // }
313 void SendProcessEvent(LaunchMethod launch_method) {
314   lldb::SBFileSpec exe_fspec = g_vsc.target.GetExecutable();
315   char exe_path[PATH_MAX];
316   exe_fspec.GetPath(exe_path, sizeof(exe_path));
317   llvm::json::Object event(CreateEventObject("process"));
318   llvm::json::Object body;
319   EmplaceSafeString(body, "name", std::string(exe_path));
320   const auto pid = g_vsc.target.GetProcess().GetProcessID();
321   body.try_emplace("systemProcessId", (int64_t)pid);
322   body.try_emplace("isLocalProcess", true);
323   const char *startMethod = nullptr;
324   switch (launch_method) {
325   case Launch:
326     startMethod = "launch";
327     break;
328   case Attach:
329     startMethod = "attach";
330     break;
331   case AttachForSuspendedLaunch:
332     startMethod = "attachForSuspendedLaunch";
333     break;
334   }
335   body.try_emplace("startMethod", startMethod);
336   event.try_emplace("body", std::move(body));
337   g_vsc.SendJSON(llvm::json::Value(std::move(event)));
338 }
339 
340 // Grab any STDOUT and STDERR from the process and send it up to VS Code
341 // via an "output" event to the "stdout" and "stderr" categories.
342 void SendStdOutStdErr(lldb::SBProcess &process) {
343   char buffer[1024];
344   size_t count;
345   while ((count = process.GetSTDOUT(buffer, sizeof(buffer))) > 0)
346     g_vsc.SendOutput(OutputType::Stdout, llvm::StringRef(buffer, count));
347   while ((count = process.GetSTDERR(buffer, sizeof(buffer))) > 0)
348     g_vsc.SendOutput(OutputType::Stderr, llvm::StringRef(buffer, count));
349 }
350 
351 // All events from the debugger, target, process, thread and frames are
352 // received in this function that runs in its own thread. We are using a
353 // "FILE *" to output packets back to VS Code and they have mutexes in them
354 // them prevent multiple threads from writing simultaneously so no locking
355 // is required.
356 void EventThreadFunction() {
357   lldb::SBEvent event;
358   lldb::SBListener listener = g_vsc.debugger.GetListener();
359   bool done = false;
360   while (!done) {
361     if (listener.WaitForEvent(1, event)) {
362       const auto event_mask = event.GetType();
363       if (lldb::SBProcess::EventIsProcessEvent(event)) {
364         lldb::SBProcess process = lldb::SBProcess::GetProcessFromEvent(event);
365         if (event_mask & lldb::SBProcess::eBroadcastBitStateChanged) {
366           auto state = lldb::SBProcess::GetStateFromEvent(event);
367           switch (state) {
368           case lldb::eStateInvalid:
369             // Not a state event
370             break;
371           case lldb::eStateUnloaded:
372             break;
373           case lldb::eStateConnected:
374             break;
375           case lldb::eStateAttaching:
376             break;
377           case lldb::eStateLaunching:
378             break;
379           case lldb::eStateStepping:
380             break;
381           case lldb::eStateCrashed:
382             break;
383           case lldb::eStateDetached:
384             break;
385           case lldb::eStateSuspended:
386             break;
387           case lldb::eStateStopped:
388             // Only report a stopped event if the process was not restarted.
389             if (!lldb::SBProcess::GetRestartedFromEvent(event)) {
390               SendStdOutStdErr(process);
391               SendThreadStoppedEvent();
392             }
393             break;
394           case lldb::eStateRunning:
395             break;
396           case lldb::eStateExited: {
397             // Run any exit LLDB commands the user specified in the
398             // launch.json
399             g_vsc.RunExitCommands();
400             SendProcessExitedEvent(process);
401             SendTerminatedEvent();
402             done = true;
403           } break;
404           }
405         } else if ((event_mask & lldb::SBProcess::eBroadcastBitSTDOUT) ||
406                    (event_mask & lldb::SBProcess::eBroadcastBitSTDERR)) {
407           SendStdOutStdErr(process);
408         }
409       } else if (lldb::SBBreakpoint::EventIsBreakpointEvent(event)) {
410         if (event_mask & lldb::SBTarget::eBroadcastBitBreakpointChanged) {
411           auto event_type =
412               lldb::SBBreakpoint::GetBreakpointEventTypeFromEvent(event);
413           auto bp = lldb::SBBreakpoint::GetBreakpointFromEvent(event);
414           // If the breakpoint was originated from the IDE, it will have the
415           // BreakpointBase::GetBreakpointLabel() label attached. Regardless
416           // of wether the locations were added or removed, the breakpoint
417           // ins't going away, so we the reason is always "changed".
418           if ((event_type & lldb::eBreakpointEventTypeLocationsAdded ||
419                event_type & lldb::eBreakpointEventTypeLocationsRemoved) &&
420               bp.MatchesName(BreakpointBase::GetBreakpointLabel())) {
421             auto bp_event = CreateEventObject("breakpoint");
422             llvm::json::Object body;
423             // As VSCode already knows the path of this breakpoint, we don't
424             // need to send it back as part of a "changed" event. This
425             // prevent us from sending to VSCode paths that should be source
426             // mapped. Note that CreateBreakpoint doesn't apply source mapping.
427             // Besides, the current implementation of VSCode ignores the
428             // "source" element of breakpoint events.
429             llvm::json::Value source_bp = CreateBreakpoint(bp);
430             source_bp.getAsObject()->erase("source");
431 
432             body.try_emplace("breakpoint", source_bp);
433             body.try_emplace("reason", "changed");
434             bp_event.try_emplace("body", std::move(body));
435             g_vsc.SendJSON(llvm::json::Value(std::move(bp_event)));
436           }
437         }
438       } else if (lldb::SBTarget::EventIsTargetEvent(event)) {
439         if (event_mask & lldb::SBTarget::eBroadcastBitModulesLoaded ||
440             event_mask & lldb::SBTarget::eBroadcastBitModulesUnloaded ||
441             event_mask & lldb::SBTarget::eBroadcastBitSymbolsLoaded) {
442           int num_modules = lldb::SBTarget::GetNumModulesFromEvent(event);
443           for (int i = 0; i < num_modules; i++) {
444             auto module = lldb::SBTarget::GetModuleAtIndexFromEvent(i, event);
445             auto module_event = CreateEventObject("module");
446             llvm::json::Value module_value = CreateModule(module);
447             llvm::json::Object body;
448             if (event_mask & lldb::SBTarget::eBroadcastBitModulesLoaded) {
449               body.try_emplace("reason", "new");
450             } else if (event_mask &
451                        lldb::SBTarget::eBroadcastBitModulesUnloaded) {
452               body.try_emplace("reason", "removed");
453             } else if (event_mask &
454                        lldb::SBTarget::eBroadcastBitSymbolsLoaded) {
455               body.try_emplace("reason", "changed");
456             }
457             body.try_emplace("module", module_value);
458             module_event.try_emplace("body", std::move(body));
459             g_vsc.SendJSON(llvm::json::Value(std::move(module_event)));
460           }
461         }
462       } else if (event.BroadcasterMatchesRef(g_vsc.broadcaster)) {
463         if (event_mask & eBroadcastBitStopEventThread) {
464           done = true;
465         }
466       }
467     }
468   }
469 }
470 
471 // Both attach and launch take a either a sourcePath or sourceMap
472 // argument (or neither), from which we need to set the target.source-map.
473 void SetSourceMapFromArguments(const llvm::json::Object &arguments) {
474   const char *sourceMapHelp =
475       "source must be be an array of two-element arrays, "
476       "each containing a source and replacement path string.\n";
477 
478   std::string sourceMapCommand;
479   llvm::raw_string_ostream strm(sourceMapCommand);
480   strm << "settings set target.source-map ";
481   auto sourcePath = GetString(arguments, "sourcePath");
482 
483   // sourceMap is the new, more general form of sourcePath and overrides it.
484   auto sourceMap = arguments.getArray("sourceMap");
485   if (sourceMap) {
486     for (const auto &value : *sourceMap) {
487       auto mapping = value.getAsArray();
488       if (mapping == nullptr || mapping->size() != 2 ||
489           (*mapping)[0].kind() != llvm::json::Value::String ||
490           (*mapping)[1].kind() != llvm::json::Value::String) {
491         g_vsc.SendOutput(OutputType::Console, llvm::StringRef(sourceMapHelp));
492         return;
493       }
494       auto mapFrom = GetAsString((*mapping)[0]);
495       auto mapTo = GetAsString((*mapping)[1]);
496       strm << "\"" << mapFrom << "\" \"" << mapTo << "\" ";
497     }
498   } else {
499     if (ObjectContainsKey(arguments, "sourceMap")) {
500       g_vsc.SendOutput(OutputType::Console, llvm::StringRef(sourceMapHelp));
501       return;
502     }
503     if (sourcePath.empty())
504       return;
505     // Do any source remapping needed before we create our targets
506     strm << "\".\" \"" << sourcePath << "\"";
507   }
508   strm.flush();
509   if (!sourceMapCommand.empty()) {
510     g_vsc.RunLLDBCommands("Setting source map:", {sourceMapCommand});
511   }
512 }
513 
514 // "AttachRequest": {
515 //   "allOf": [ { "$ref": "#/definitions/Request" }, {
516 //     "type": "object",
517 //     "description": "Attach request; value of command field is 'attach'.",
518 //     "properties": {
519 //       "command": {
520 //         "type": "string",
521 //         "enum": [ "attach" ]
522 //       },
523 //       "arguments": {
524 //         "$ref": "#/definitions/AttachRequestArguments"
525 //       }
526 //     },
527 //     "required": [ "command", "arguments" ]
528 //   }]
529 // },
530 // "AttachRequestArguments": {
531 //   "type": "object",
532 //   "description": "Arguments for 'attach' request.\nThe attach request has no
533 //   standardized attributes."
534 // },
535 // "AttachResponse": {
536 //   "allOf": [ { "$ref": "#/definitions/Response" }, {
537 //     "type": "object",
538 //     "description": "Response to 'attach' request. This is just an
539 //     acknowledgement, so no body field is required."
540 //   }]
541 // }
542 void request_attach(const llvm::json::Object &request) {
543   g_vsc.is_attach = true;
544   llvm::json::Object response;
545   lldb::SBError error;
546   FillResponse(request, response);
547   lldb::SBAttachInfo attach_info;
548   auto arguments = request.getObject("arguments");
549   const lldb::pid_t pid =
550       GetUnsigned(arguments, "pid", LLDB_INVALID_PROCESS_ID);
551   if (pid != LLDB_INVALID_PROCESS_ID)
552     attach_info.SetProcessID(pid);
553   const auto wait_for = GetBoolean(arguments, "waitFor", false);
554   attach_info.SetWaitForLaunch(wait_for, false /*async*/);
555   g_vsc.init_commands = GetStrings(arguments, "initCommands");
556   g_vsc.pre_run_commands = GetStrings(arguments, "preRunCommands");
557   g_vsc.stop_commands = GetStrings(arguments, "stopCommands");
558   g_vsc.exit_commands = GetStrings(arguments, "exitCommands");
559   g_vsc.terminate_commands = GetStrings(arguments, "terminateCommands");
560   auto attachCommands = GetStrings(arguments, "attachCommands");
561   llvm::StringRef core_file = GetString(arguments, "coreFile");
562   g_vsc.stop_at_entry =
563       core_file.empty() ? GetBoolean(arguments, "stopOnEntry", false) : true;
564   const llvm::StringRef debuggerRoot = GetString(arguments, "debuggerRoot");
565 
566   // This is a hack for loading DWARF in .o files on Mac where the .o files
567   // in the debug map of the main executable have relative paths which require
568   // the lldb-vscode binary to have its working directory set to that relative
569   // root for the .o files in order to be able to load debug info.
570   if (!debuggerRoot.empty())
571     llvm::sys::fs::set_current_path(debuggerRoot);
572 
573   // Run any initialize LLDB commands the user specified in the launch.json
574   g_vsc.RunInitCommands();
575 
576   lldb::SBError status;
577   g_vsc.SetTarget(g_vsc.CreateTargetFromArguments(*arguments, status));
578   if (status.Fail()) {
579     response["success"] = llvm::json::Value(false);
580     EmplaceSafeString(response, "message", status.GetCString());
581     g_vsc.SendJSON(llvm::json::Value(std::move(response)));
582     return;
583   }
584 
585   // Run any pre run LLDB commands the user specified in the launch.json
586   g_vsc.RunPreRunCommands();
587 
588   if (pid == LLDB_INVALID_PROCESS_ID && wait_for) {
589     char attach_msg[256];
590     auto attach_msg_len = snprintf(attach_msg, sizeof(attach_msg),
591                                    "Waiting to attach to \"%s\"...",
592                                    g_vsc.target.GetExecutable().GetFilename());
593     g_vsc.SendOutput(OutputType::Console,
594                      llvm::StringRef(attach_msg, attach_msg_len));
595   }
596   if (attachCommands.empty()) {
597     // No "attachCommands", just attach normally.
598     // Disable async events so the attach will be successful when we return from
599     // the launch call and the launch will happen synchronously
600     g_vsc.debugger.SetAsync(false);
601     if (core_file.empty())
602       g_vsc.target.Attach(attach_info, error);
603     else
604       g_vsc.target.LoadCore(core_file.data(), error);
605     // Reenable async events
606     g_vsc.debugger.SetAsync(true);
607   } else {
608     // We have "attachCommands" that are a set of commands that are expected
609     // to execute the commands after which a process should be created. If there
610     // is no valid process after running these commands, we have failed.
611     g_vsc.RunLLDBCommands("Running attachCommands:", attachCommands);
612     // The custom commands might have created a new target so we should use the
613     // selected target after these commands are run.
614     g_vsc.target = g_vsc.debugger.GetSelectedTarget();
615   }
616 
617   SetSourceMapFromArguments(*arguments);
618 
619   if (error.Success() && core_file.empty()) {
620     auto attached_pid = g_vsc.target.GetProcess().GetProcessID();
621     if (attached_pid == LLDB_INVALID_PROCESS_ID) {
622       if (attachCommands.empty())
623         error.SetErrorString("failed to attach to a process");
624       else
625         error.SetErrorString("attachCommands failed to attach to a process");
626     }
627   }
628 
629   if (error.Fail()) {
630     response["success"] = llvm::json::Value(false);
631     EmplaceSafeString(response, "message", std::string(error.GetCString()));
632   }
633   g_vsc.SendJSON(llvm::json::Value(std::move(response)));
634   if (error.Success()) {
635     SendProcessEvent(Attach);
636     g_vsc.SendJSON(CreateEventObject("initialized"));
637     // SendThreadStoppedEvent();
638   }
639 }
640 
641 // "ContinueRequest": {
642 //   "allOf": [ { "$ref": "#/definitions/Request" }, {
643 //     "type": "object",
644 //     "description": "Continue request; value of command field is 'continue'.
645 //                     The request starts the debuggee to run again.",
646 //     "properties": {
647 //       "command": {
648 //         "type": "string",
649 //         "enum": [ "continue" ]
650 //       },
651 //       "arguments": {
652 //         "$ref": "#/definitions/ContinueArguments"
653 //       }
654 //     },
655 //     "required": [ "command", "arguments"  ]
656 //   }]
657 // },
658 // "ContinueArguments": {
659 //   "type": "object",
660 //   "description": "Arguments for 'continue' request.",
661 //   "properties": {
662 //     "threadId": {
663 //       "type": "integer",
664 //       "description": "Continue execution for the specified thread (if
665 //                       possible). If the backend cannot continue on a single
666 //                       thread but will continue on all threads, it should
667 //                       set the allThreadsContinued attribute in the response
668 //                       to true."
669 //     }
670 //   },
671 //   "required": [ "threadId" ]
672 // },
673 // "ContinueResponse": {
674 //   "allOf": [ { "$ref": "#/definitions/Response" }, {
675 //     "type": "object",
676 //     "description": "Response to 'continue' request.",
677 //     "properties": {
678 //       "body": {
679 //         "type": "object",
680 //         "properties": {
681 //           "allThreadsContinued": {
682 //             "type": "boolean",
683 //             "description": "If true, the continue request has ignored the
684 //                             specified thread and continued all threads
685 //                             instead. If this attribute is missing a value
686 //                             of 'true' is assumed for backward
687 //                             compatibility."
688 //           }
689 //         }
690 //       }
691 //     },
692 //     "required": [ "body" ]
693 //   }]
694 // }
695 void request_continue(const llvm::json::Object &request) {
696   llvm::json::Object response;
697   FillResponse(request, response);
698   lldb::SBProcess process = g_vsc.target.GetProcess();
699   auto arguments = request.getObject("arguments");
700   // Remember the thread ID that caused the resume so we can set the
701   // "threadCausedFocus" boolean value in the "stopped" events.
702   g_vsc.focus_tid = GetUnsigned(arguments, "threadId", LLDB_INVALID_THREAD_ID);
703   lldb::SBError error = process.Continue();
704   llvm::json::Object body;
705   body.try_emplace("allThreadsContinued", true);
706   response.try_emplace("body", std::move(body));
707   g_vsc.SendJSON(llvm::json::Value(std::move(response)));
708 }
709 
710 // "ConfigurationDoneRequest": {
711 //   "allOf": [ { "$ref": "#/definitions/Request" }, {
712 //             "type": "object",
713 //             "description": "ConfigurationDone request; value of command field
714 //             is 'configurationDone'.\nThe client of the debug protocol must
715 //             send this request at the end of the sequence of configuration
716 //             requests (which was started by the InitializedEvent).",
717 //             "properties": {
718 //             "command": {
719 //             "type": "string",
720 //             "enum": [ "configurationDone" ]
721 //             },
722 //             "arguments": {
723 //             "$ref": "#/definitions/ConfigurationDoneArguments"
724 //             }
725 //             },
726 //             "required": [ "command" ]
727 //             }]
728 // },
729 // "ConfigurationDoneArguments": {
730 //   "type": "object",
731 //   "description": "Arguments for 'configurationDone' request.\nThe
732 //   configurationDone request has no standardized attributes."
733 // },
734 // "ConfigurationDoneResponse": {
735 //   "allOf": [ { "$ref": "#/definitions/Response" }, {
736 //             "type": "object",
737 //             "description": "Response to 'configurationDone' request. This is
738 //             just an acknowledgement, so no body field is required."
739 //             }]
740 // },
741 void request_configurationDone(const llvm::json::Object &request) {
742   llvm::json::Object response;
743   FillResponse(request, response);
744   g_vsc.SendJSON(llvm::json::Value(std::move(response)));
745   if (g_vsc.stop_at_entry)
746     SendThreadStoppedEvent();
747   else
748     g_vsc.target.GetProcess().Continue();
749 }
750 
751 // "DisconnectRequest": {
752 //   "allOf": [ { "$ref": "#/definitions/Request" }, {
753 //     "type": "object",
754 //     "description": "Disconnect request; value of command field is
755 //                     'disconnect'.",
756 //     "properties": {
757 //       "command": {
758 //         "type": "string",
759 //         "enum": [ "disconnect" ]
760 //       },
761 //       "arguments": {
762 //         "$ref": "#/definitions/DisconnectArguments"
763 //       }
764 //     },
765 //     "required": [ "command" ]
766 //   }]
767 // },
768 // "DisconnectArguments": {
769 //   "type": "object",
770 //   "description": "Arguments for 'disconnect' request.",
771 //   "properties": {
772 //     "terminateDebuggee": {
773 //       "type": "boolean",
774 //       "description": "Indicates whether the debuggee should be terminated
775 //                       when the debugger is disconnected. If unspecified,
776 //                       the debug adapter is free to do whatever it thinks
777 //                       is best. A client can only rely on this attribute
778 //                       being properly honored if a debug adapter returns
779 //                       true for the 'supportTerminateDebuggee' capability."
780 //     },
781 //     "restart": {
782 //       "type": "boolean",
783 //       "description": "Indicates whether the debuggee should be restart
784 //                       the process."
785 //     }
786 //   }
787 // },
788 // "DisconnectResponse": {
789 //   "allOf": [ { "$ref": "#/definitions/Response" }, {
790 //     "type": "object",
791 //     "description": "Response to 'disconnect' request. This is just an
792 //                     acknowledgement, so no body field is required."
793 //   }]
794 // }
795 void request_disconnect(const llvm::json::Object &request) {
796   llvm::json::Object response;
797   FillResponse(request, response);
798   auto arguments = request.getObject("arguments");
799 
800   bool defaultTerminateDebuggee = g_vsc.is_attach ? false : true;
801   bool terminateDebuggee =
802       GetBoolean(arguments, "terminateDebuggee", defaultTerminateDebuggee);
803   lldb::SBProcess process = g_vsc.target.GetProcess();
804   auto state = process.GetState();
805   switch (state) {
806   case lldb::eStateInvalid:
807   case lldb::eStateUnloaded:
808   case lldb::eStateDetached:
809   case lldb::eStateExited:
810     break;
811   case lldb::eStateConnected:
812   case lldb::eStateAttaching:
813   case lldb::eStateLaunching:
814   case lldb::eStateStepping:
815   case lldb::eStateCrashed:
816   case lldb::eStateSuspended:
817   case lldb::eStateStopped:
818   case lldb::eStateRunning:
819     g_vsc.debugger.SetAsync(false);
820     lldb::SBError error = terminateDebuggee ? process.Kill() : process.Detach();
821     if (!error.Success())
822       response.try_emplace("error", error.GetCString());
823     g_vsc.debugger.SetAsync(true);
824     break;
825   }
826   SendTerminatedEvent();
827   g_vsc.SendJSON(llvm::json::Value(std::move(response)));
828   if (g_vsc.event_thread.joinable()) {
829     g_vsc.broadcaster.BroadcastEventByType(eBroadcastBitStopEventThread);
830     g_vsc.event_thread.join();
831   }
832 }
833 
834 void request_exceptionInfo(const llvm::json::Object &request) {
835   llvm::json::Object response;
836   FillResponse(request, response);
837   auto arguments = request.getObject("arguments");
838   llvm::json::Object body;
839   lldb::SBThread thread = g_vsc.GetLLDBThread(*arguments);
840   if (thread.IsValid()) {
841     auto stopReason = thread.GetStopReason();
842     if (stopReason == lldb::eStopReasonSignal)
843       body.try_emplace("exceptionId", "signal");
844     else if (stopReason == lldb::eStopReasonBreakpoint) {
845       ExceptionBreakpoint *exc_bp = g_vsc.GetExceptionBPFromStopReason(thread);
846       if (exc_bp) {
847         EmplaceSafeString(body, "exceptionId", exc_bp->filter);
848         EmplaceSafeString(body, "description", exc_bp->label);
849       } else {
850         body.try_emplace("exceptionId", "exception");
851       }
852     } else {
853       body.try_emplace("exceptionId", "exception");
854     }
855     if (!ObjectContainsKey(body, "description")) {
856       char description[1024];
857       if (thread.GetStopDescription(description, sizeof(description))) {
858         EmplaceSafeString(body, "description", std::string(description));
859       }
860     }
861     body.try_emplace("breakMode", "always");
862     // auto excInfoCount = thread.GetStopReasonDataCount();
863     // for (auto i=0; i<excInfoCount; ++i) {
864     //   uint64_t exc_data = thread.GetStopReasonDataAtIndex(i);
865     // }
866   } else {
867     response["success"] = llvm::json::Value(false);
868   }
869   response.try_emplace("body", std::move(body));
870   g_vsc.SendJSON(llvm::json::Value(std::move(response)));
871 }
872 
873 // "CompletionsRequest": {
874 //   "allOf": [ { "$ref": "#/definitions/Request" }, {
875 //     "type": "object",
876 //     "description": "Returns a list of possible completions for a given caret
877 //     position and text.\nThe CompletionsRequest may only be called if the
878 //     'supportsCompletionsRequest' capability exists and is true.",
879 //     "properties": {
880 //       "command": {
881 //         "type": "string",
882 //         "enum": [ "completions" ]
883 //       },
884 //       "arguments": {
885 //         "$ref": "#/definitions/CompletionsArguments"
886 //       }
887 //     },
888 //     "required": [ "command", "arguments"  ]
889 //   }]
890 // },
891 // "CompletionsArguments": {
892 //   "type": "object",
893 //   "description": "Arguments for 'completions' request.",
894 //   "properties": {
895 //     "frameId": {
896 //       "type": "integer",
897 //       "description": "Returns completions in the scope of this stack frame.
898 //       If not specified, the completions are returned for the global scope."
899 //     },
900 //     "text": {
901 //       "type": "string",
902 //       "description": "One or more source lines. Typically this is the text a
903 //       user has typed into the debug console before he asked for completion."
904 //     },
905 //     "column": {
906 //       "type": "integer",
907 //       "description": "The character position for which to determine the
908 //       completion proposals."
909 //     },
910 //     "line": {
911 //       "type": "integer",
912 //       "description": "An optional line for which to determine the completion
913 //       proposals. If missing the first line of the text is assumed."
914 //     }
915 //   },
916 //   "required": [ "text", "column" ]
917 // },
918 // "CompletionsResponse": {
919 //   "allOf": [ { "$ref": "#/definitions/Response" }, {
920 //     "type": "object",
921 //     "description": "Response to 'completions' request.",
922 //     "properties": {
923 //       "body": {
924 //         "type": "object",
925 //         "properties": {
926 //           "targets": {
927 //             "type": "array",
928 //             "items": {
929 //               "$ref": "#/definitions/CompletionItem"
930 //             },
931 //             "description": "The possible completions for ."
932 //           }
933 //         },
934 //         "required": [ "targets" ]
935 //       }
936 //     },
937 //     "required": [ "body" ]
938 //   }]
939 // },
940 // "CompletionItem": {
941 //   "type": "object",
942 //   "description": "CompletionItems are the suggestions returned from the
943 //   CompletionsRequest.", "properties": {
944 //     "label": {
945 //       "type": "string",
946 //       "description": "The label of this completion item. By default this is
947 //       also the text that is inserted when selecting this completion."
948 //     },
949 //     "text": {
950 //       "type": "string",
951 //       "description": "If text is not falsy then it is inserted instead of the
952 //       label."
953 //     },
954 //     "sortText": {
955 //       "type": "string",
956 //       "description": "A string that should be used when comparing this item
957 //       with other items. When `falsy` the label is used."
958 //     },
959 //     "type": {
960 //       "$ref": "#/definitions/CompletionItemType",
961 //       "description": "The item's type. Typically the client uses this
962 //       information to render the item in the UI with an icon."
963 //     },
964 //     "start": {
965 //       "type": "integer",
966 //       "description": "This value determines the location (in the
967 //       CompletionsRequest's 'text' attribute) where the completion text is
968 //       added.\nIf missing the text is added at the location specified by the
969 //       CompletionsRequest's 'column' attribute."
970 //     },
971 //     "length": {
972 //       "type": "integer",
973 //       "description": "This value determines how many characters are
974 //       overwritten by the completion text.\nIf missing the value 0 is assumed
975 //       which results in the completion text being inserted."
976 //     }
977 //   },
978 //   "required": [ "label" ]
979 // },
980 // "CompletionItemType": {
981 //   "type": "string",
982 //   "description": "Some predefined types for the CompletionItem. Please note
983 //   that not all clients have specific icons for all of them.", "enum": [
984 //   "method", "function", "constructor", "field", "variable", "class",
985 //   "interface", "module", "property", "unit", "value", "enum", "keyword",
986 //   "snippet", "text", "color", "file", "reference", "customcolor" ]
987 // }
988 void request_completions(const llvm::json::Object &request) {
989   llvm::json::Object response;
990   FillResponse(request, response);
991   llvm::json::Object body;
992   auto arguments = request.getObject("arguments");
993   std::string text = std::string(GetString(arguments, "text"));
994   auto original_column = GetSigned(arguments, "column", text.size());
995   auto actual_column = original_column - 1;
996   llvm::json::Array targets;
997   // NOTE: the 'line' argument is not needed, as multiline expressions
998   // work well already
999   // TODO: support frameID. Currently
1000   // g_vsc.debugger.GetCommandInterpreter().HandleCompletionWithDescriptions
1001   // is frame-unaware.
1002 
1003   if (!text.empty() && text[0] == '`') {
1004     text = text.substr(1);
1005     actual_column--;
1006   } else {
1007     text = "p " + text;
1008     actual_column += 2;
1009   }
1010   lldb::SBStringList matches;
1011   lldb::SBStringList descriptions;
1012   g_vsc.debugger.GetCommandInterpreter().HandleCompletionWithDescriptions(
1013       text.c_str(), actual_column, 0, -1, matches, descriptions);
1014   size_t count = std::min((uint32_t)100, matches.GetSize());
1015   targets.reserve(count);
1016   for (size_t i = 0; i < count; i++) {
1017     std::string match = matches.GetStringAtIndex(i);
1018     std::string description = descriptions.GetStringAtIndex(i);
1019 
1020     llvm::json::Object item;
1021 
1022     llvm::StringRef match_ref = match;
1023     for (llvm::StringRef commit_point : {".", "->"}) {
1024       if (match_ref.contains(commit_point)) {
1025         match_ref = match_ref.rsplit(commit_point).second;
1026       }
1027     }
1028     EmplaceSafeString(item, "text", match_ref);
1029 
1030     if (description.empty())
1031       EmplaceSafeString(item, "label", match);
1032     else
1033       EmplaceSafeString(item, "label", match + " -- " + description);
1034 
1035     targets.emplace_back(std::move(item));
1036   }
1037 
1038   body.try_emplace("targets", std::move(targets));
1039   response.try_emplace("body", std::move(body));
1040   g_vsc.SendJSON(llvm::json::Value(std::move(response)));
1041 }
1042 
1043 //  "EvaluateRequest": {
1044 //    "allOf": [ { "$ref": "#/definitions/Request" }, {
1045 //      "type": "object",
1046 //      "description": "Evaluate request; value of command field is 'evaluate'.
1047 //                      Evaluates the given expression in the context of the
1048 //                      top most stack frame. The expression has access to any
1049 //                      variables and arguments that are in scope.",
1050 //      "properties": {
1051 //        "command": {
1052 //          "type": "string",
1053 //          "enum": [ "evaluate" ]
1054 //        },
1055 //        "arguments": {
1056 //          "$ref": "#/definitions/EvaluateArguments"
1057 //        }
1058 //      },
1059 //      "required": [ "command", "arguments"  ]
1060 //    }]
1061 //  },
1062 //  "EvaluateArguments": {
1063 //    "type": "object",
1064 //    "description": "Arguments for 'evaluate' request.",
1065 //    "properties": {
1066 //      "expression": {
1067 //        "type": "string",
1068 //        "description": "The expression to evaluate."
1069 //      },
1070 //      "frameId": {
1071 //        "type": "integer",
1072 //        "description": "Evaluate the expression in the scope of this stack
1073 //                        frame. If not specified, the expression is evaluated
1074 //                        in the global scope."
1075 //      },
1076 //      "context": {
1077 //        "type": "string",
1078 //        "_enum": [ "watch", "repl", "hover" ],
1079 //        "enumDescriptions": [
1080 //          "evaluate is run in a watch.",
1081 //          "evaluate is run from REPL console.",
1082 //          "evaluate is run from a data hover."
1083 //        ],
1084 //        "description": "The context in which the evaluate request is run."
1085 //      },
1086 //      "format": {
1087 //        "$ref": "#/definitions/ValueFormat",
1088 //        "description": "Specifies details on how to format the Evaluate
1089 //                        result."
1090 //      }
1091 //    },
1092 //    "required": [ "expression" ]
1093 //  },
1094 //  "EvaluateResponse": {
1095 //    "allOf": [ { "$ref": "#/definitions/Response" }, {
1096 //      "type": "object",
1097 //      "description": "Response to 'evaluate' request.",
1098 //      "properties": {
1099 //        "body": {
1100 //          "type": "object",
1101 //          "properties": {
1102 //            "result": {
1103 //              "type": "string",
1104 //              "description": "The result of the evaluate request."
1105 //            },
1106 //            "type": {
1107 //              "type": "string",
1108 //              "description": "The optional type of the evaluate result."
1109 //            },
1110 //            "presentationHint": {
1111 //              "$ref": "#/definitions/VariablePresentationHint",
1112 //              "description": "Properties of a evaluate result that can be
1113 //                              used to determine how to render the result in
1114 //                              the UI."
1115 //            },
1116 //            "variablesReference": {
1117 //              "type": "number",
1118 //              "description": "If variablesReference is > 0, the evaluate
1119 //                              result is structured and its children can be
1120 //                              retrieved by passing variablesReference to the
1121 //                              VariablesRequest."
1122 //            },
1123 //            "namedVariables": {
1124 //              "type": "number",
1125 //              "description": "The number of named child variables. The
1126 //                              client can use this optional information to
1127 //                              present the variables in a paged UI and fetch
1128 //                              them in chunks."
1129 //            },
1130 //            "indexedVariables": {
1131 //              "type": "number",
1132 //              "description": "The number of indexed child variables. The
1133 //                              client can use this optional information to
1134 //                              present the variables in a paged UI and fetch
1135 //                              them in chunks."
1136 //            }
1137 //          },
1138 //          "required": [ "result", "variablesReference" ]
1139 //        }
1140 //      },
1141 //      "required": [ "body" ]
1142 //    }]
1143 //  }
1144 void request_evaluate(const llvm::json::Object &request) {
1145   llvm::json::Object response;
1146   FillResponse(request, response);
1147   llvm::json::Object body;
1148   auto arguments = request.getObject("arguments");
1149   lldb::SBFrame frame = g_vsc.GetLLDBFrame(*arguments);
1150   const auto expression = GetString(arguments, "expression");
1151 
1152   if (!expression.empty() && expression[0] == '`') {
1153     auto result =
1154         RunLLDBCommands(llvm::StringRef(), {std::string(expression.substr(1))});
1155     EmplaceSafeString(body, "result", result);
1156     body.try_emplace("variablesReference", (int64_t)0);
1157   } else {
1158     // Always try to get the answer from the local variables if possible. If
1159     // this fails, then actually evaluate an expression using the expression
1160     // parser. "frame variable" is more reliable than the expression parser in
1161     // many cases and it is faster.
1162     lldb::SBValue value = frame.GetValueForVariablePath(
1163         expression.data(), lldb::eDynamicDontRunTarget);
1164     if (value.GetError().Fail())
1165       value = frame.EvaluateExpression(expression.data());
1166     if (value.GetError().Fail()) {
1167       response["success"] = llvm::json::Value(false);
1168       // This error object must live until we're done with the pointer returned
1169       // by GetCString().
1170       lldb::SBError error = value.GetError();
1171       const char *error_cstr = error.GetCString();
1172       if (error_cstr && error_cstr[0])
1173         EmplaceSafeString(response, "message", std::string(error_cstr));
1174       else
1175         EmplaceSafeString(response, "message", "evaluate failed");
1176     } else {
1177       SetValueForKey(value, body, "result");
1178       auto value_typename = value.GetType().GetDisplayTypeName();
1179       EmplaceSafeString(body, "type",
1180                         value_typename ? value_typename : NO_TYPENAME);
1181       if (value.MightHaveChildren()) {
1182         auto variablesReference = VARIDX_TO_VARREF(g_vsc.variables.GetSize());
1183         g_vsc.variables.Append(value);
1184         body.try_emplace("variablesReference", variablesReference);
1185       } else {
1186         body.try_emplace("variablesReference", (int64_t)0);
1187       }
1188     }
1189   }
1190   response.try_emplace("body", std::move(body));
1191   g_vsc.SendJSON(llvm::json::Value(std::move(response)));
1192 }
1193 
1194 // "getCompileUnitsRequest": {
1195 //   "allOf": [ { "$ref": "#/definitions/Request" }, {
1196 //     "type": "object",
1197 //     "description": "Compile Unit request; value of command field is
1198 //                     'getCompileUnits'.",
1199 //     "properties": {
1200 //       "command": {
1201 //         "type": "string",
1202 //         "enum": [ "getCompileUnits" ]
1203 //       },
1204 //       "arguments": {
1205 //         "$ref": "#/definitions/getCompileUnitRequestArguments"
1206 //       }
1207 //     },
1208 //     "required": [ "command", "arguments" ]
1209 //   }]
1210 // },
1211 // "getCompileUnitsRequestArguments": {
1212 //   "type": "object",
1213 //   "description": "Arguments for 'getCompileUnits' request.",
1214 //   "properties": {
1215 //     "moduleId": {
1216 //       "type": "string",
1217 //       "description": "The ID of the module."
1218 //     }
1219 //   },
1220 //   "required": [ "moduleId" ]
1221 // },
1222 // "getCompileUnitsResponse": {
1223 //   "allOf": [ { "$ref": "#/definitions/Response" }, {
1224 //     "type": "object",
1225 //     "description": "Response to 'getCompileUnits' request.",
1226 //     "properties": {
1227 //       "body": {
1228 //         "description": "Response to 'getCompileUnits' request. Array of
1229 //                         paths of compile units."
1230 //       }
1231 //     }
1232 //   }]
1233 // }
1234 
1235 void request_getCompileUnits(const llvm::json::Object &request) {
1236   llvm::json::Object response;
1237   FillResponse(request, response);
1238   lldb::SBProcess process = g_vsc.target.GetProcess();
1239   llvm::json::Object body;
1240   llvm::json::Array units;
1241   auto arguments = request.getObject("arguments");
1242   std::string module_id = std::string(GetString(arguments, "moduleId"));
1243   int num_modules = g_vsc.target.GetNumModules();
1244   for (int i = 0; i < num_modules; i++) {
1245     auto curr_module = g_vsc.target.GetModuleAtIndex(i);
1246     if (module_id == curr_module.GetUUIDString()) {
1247       int num_units = curr_module.GetNumCompileUnits();
1248       for (int j = 0; j < num_units; j++) {
1249         auto curr_unit = curr_module.GetCompileUnitAtIndex(j);
1250         units.emplace_back(CreateCompileUnit(curr_unit));
1251       }
1252       body.try_emplace("compileUnits", std::move(units));
1253       break;
1254     }
1255   }
1256   response.try_emplace("body", std::move(body));
1257   g_vsc.SendJSON(llvm::json::Value(std::move(response)));
1258 }
1259 
1260 // "InitializeRequest": {
1261 //   "allOf": [ { "$ref": "#/definitions/Request" }, {
1262 //     "type": "object",
1263 //     "description": "Initialize request; value of command field is
1264 //                     'initialize'.",
1265 //     "properties": {
1266 //       "command": {
1267 //         "type": "string",
1268 //         "enum": [ "initialize" ]
1269 //       },
1270 //       "arguments": {
1271 //         "$ref": "#/definitions/InitializeRequestArguments"
1272 //       }
1273 //     },
1274 //     "required": [ "command", "arguments" ]
1275 //   }]
1276 // },
1277 // "InitializeRequestArguments": {
1278 //   "type": "object",
1279 //   "description": "Arguments for 'initialize' request.",
1280 //   "properties": {
1281 //     "clientID": {
1282 //       "type": "string",
1283 //       "description": "The ID of the (frontend) client using this adapter."
1284 //     },
1285 //     "adapterID": {
1286 //       "type": "string",
1287 //       "description": "The ID of the debug adapter."
1288 //     },
1289 //     "locale": {
1290 //       "type": "string",
1291 //       "description": "The ISO-639 locale of the (frontend) client using
1292 //                       this adapter, e.g. en-US or de-CH."
1293 //     },
1294 //     "linesStartAt1": {
1295 //       "type": "boolean",
1296 //       "description": "If true all line numbers are 1-based (default)."
1297 //     },
1298 //     "columnsStartAt1": {
1299 //       "type": "boolean",
1300 //       "description": "If true all column numbers are 1-based (default)."
1301 //     },
1302 //     "pathFormat": {
1303 //       "type": "string",
1304 //       "_enum": [ "path", "uri" ],
1305 //       "description": "Determines in what format paths are specified. The
1306 //                       default is 'path', which is the native format."
1307 //     },
1308 //     "supportsVariableType": {
1309 //       "type": "boolean",
1310 //       "description": "Client supports the optional type attribute for
1311 //                       variables."
1312 //     },
1313 //     "supportsVariablePaging": {
1314 //       "type": "boolean",
1315 //       "description": "Client supports the paging of variables."
1316 //     },
1317 //     "supportsRunInTerminalRequest": {
1318 //       "type": "boolean",
1319 //       "description": "Client supports the runInTerminal request."
1320 //     }
1321 //   },
1322 //   "required": [ "adapterID" ]
1323 // },
1324 // "InitializeResponse": {
1325 //   "allOf": [ { "$ref": "#/definitions/Response" }, {
1326 //     "type": "object",
1327 //     "description": "Response to 'initialize' request.",
1328 //     "properties": {
1329 //       "body": {
1330 //         "$ref": "#/definitions/Capabilities",
1331 //         "description": "The capabilities of this debug adapter."
1332 //       }
1333 //     }
1334 //   }]
1335 // }
1336 void request_initialize(const llvm::json::Object &request) {
1337   g_vsc.debugger = lldb::SBDebugger::Create(true /*source_init_files*/);
1338   // Create an empty target right away since we might get breakpoint requests
1339   // before we are given an executable to launch in a "launch" request, or a
1340   // executable when attaching to a process by process ID in a "attach"
1341   // request.
1342   FILE *out = llvm::sys::RetryAfterSignal(nullptr, fopen, dev_null_path, "w");
1343   if (out) {
1344     // Set the output and error file handles to redirect into nothing otherwise
1345     // if any code in LLDB prints to the debugger file handles, the output and
1346     // error file handles are initialized to STDOUT and STDERR and any output
1347     // will kill our debug session.
1348     g_vsc.debugger.SetOutputFileHandle(out, true);
1349     g_vsc.debugger.SetErrorFileHandle(out, false);
1350   }
1351 
1352   // Start our event thread so we can receive events from the debugger, target,
1353   // process and more.
1354   g_vsc.event_thread = std::thread(EventThreadFunction);
1355 
1356   llvm::json::Object response;
1357   FillResponse(request, response);
1358   llvm::json::Object body;
1359   // The debug adapter supports the configurationDoneRequest.
1360   body.try_emplace("supportsConfigurationDoneRequest", true);
1361   // The debug adapter supports function breakpoints.
1362   body.try_emplace("supportsFunctionBreakpoints", true);
1363   // The debug adapter supports conditional breakpoints.
1364   body.try_emplace("supportsConditionalBreakpoints", true);
1365   // The debug adapter supports breakpoints that break execution after a
1366   // specified number of hits.
1367   body.try_emplace("supportsHitConditionalBreakpoints", true);
1368   // The debug adapter supports a (side effect free) evaluate request for
1369   // data hovers.
1370   body.try_emplace("supportsEvaluateForHovers", true);
1371   // Available filters or options for the setExceptionBreakpoints request.
1372   llvm::json::Array filters;
1373   for (const auto &exc_bp : g_vsc.exception_breakpoints) {
1374     filters.emplace_back(CreateExceptionBreakpointFilter(exc_bp));
1375   }
1376   body.try_emplace("exceptionBreakpointFilters", std::move(filters));
1377   // The debug adapter supports stepping back via the stepBack and
1378   // reverseContinue requests.
1379   body.try_emplace("supportsStepBack", false);
1380   // The debug adapter supports setting a variable to a value.
1381   body.try_emplace("supportsSetVariable", true);
1382   // The debug adapter supports restarting a frame.
1383   body.try_emplace("supportsRestartFrame", false);
1384   // The debug adapter supports the gotoTargetsRequest.
1385   body.try_emplace("supportsGotoTargetsRequest", false);
1386   // The debug adapter supports the stepInTargetsRequest.
1387   body.try_emplace("supportsStepInTargetsRequest", false);
1388   // We need to improve the current implementation of completions in order to
1389   // enable it again. For some context, this is how VSCode works:
1390   // - VSCode sends a completion request whenever chars are added, the user
1391   //   triggers completion manually via CTRL-space or similar mechanisms, but
1392   //   not when there's a deletion. Besides, VSCode doesn't let us know which
1393   //   of these events we are handling. What is more, the use can paste or cut
1394   //   sections of the text arbitrarily.
1395   //   https://github.com/microsoft/vscode/issues/89531 tracks part of the
1396   //   issue just mentioned.
1397   // This behavior causes many problems with the current way completion is
1398   // implemented in lldb-vscode, as these requests could be really expensive,
1399   // blocking the debugger, and there could be many concurrent requests unless
1400   // the user types very slowly... We need to address this specific issue, or
1401   // at least trigger completion only when the user explicitly wants it, which
1402   // is the behavior of LLDB CLI, that expects a TAB.
1403   body.try_emplace("supportsCompletionsRequest", false);
1404   // The debug adapter supports the modules request.
1405   body.try_emplace("supportsModulesRequest", false);
1406   // The set of additional module information exposed by the debug adapter.
1407   //   body.try_emplace("additionalModuleColumns"] = ColumnDescriptor
1408   // Checksum algorithms supported by the debug adapter.
1409   //   body.try_emplace("supportedChecksumAlgorithms"] = ChecksumAlgorithm
1410   // The debug adapter supports the RestartRequest. In this case a client
1411   // should not implement 'restart' by terminating and relaunching the adapter
1412   // but by calling the RestartRequest.
1413   body.try_emplace("supportsRestartRequest", false);
1414   // The debug adapter supports 'exceptionOptions' on the
1415   // setExceptionBreakpoints request.
1416   body.try_emplace("supportsExceptionOptions", true);
1417   // The debug adapter supports a 'format' attribute on the stackTraceRequest,
1418   // variablesRequest, and evaluateRequest.
1419   body.try_emplace("supportsValueFormattingOptions", true);
1420   // The debug adapter supports the exceptionInfo request.
1421   body.try_emplace("supportsExceptionInfoRequest", true);
1422   // The debug adapter supports the 'terminateDebuggee' attribute on the
1423   // 'disconnect' request.
1424   body.try_emplace("supportTerminateDebuggee", true);
1425   // The debug adapter supports the delayed loading of parts of the stack,
1426   // which requires that both the 'startFrame' and 'levels' arguments and the
1427   // 'totalFrames' result of the 'StackTrace' request are supported.
1428   body.try_emplace("supportsDelayedStackTraceLoading", true);
1429   // The debug adapter supports the 'loadedSources' request.
1430   body.try_emplace("supportsLoadedSourcesRequest", false);
1431 
1432   response.try_emplace("body", std::move(body));
1433   g_vsc.SendJSON(llvm::json::Value(std::move(response)));
1434 }
1435 
1436 // "LaunchRequest": {
1437 //   "allOf": [ { "$ref": "#/definitions/Request" }, {
1438 //     "type": "object",
1439 //     "description": "Launch request; value of command field is 'launch'.",
1440 //     "properties": {
1441 //       "command": {
1442 //         "type": "string",
1443 //         "enum": [ "launch" ]
1444 //       },
1445 //       "arguments": {
1446 //         "$ref": "#/definitions/LaunchRequestArguments"
1447 //       }
1448 //     },
1449 //     "required": [ "command", "arguments"  ]
1450 //   }]
1451 // },
1452 // "LaunchRequestArguments": {
1453 //   "type": "object",
1454 //   "description": "Arguments for 'launch' request.",
1455 //   "properties": {
1456 //     "noDebug": {
1457 //       "type": "boolean",
1458 //       "description": "If noDebug is true the launch request should launch
1459 //                       the program without enabling debugging."
1460 //     }
1461 //   }
1462 // },
1463 // "LaunchResponse": {
1464 //   "allOf": [ { "$ref": "#/definitions/Response" }, {
1465 //     "type": "object",
1466 //     "description": "Response to 'launch' request. This is just an
1467 //                     acknowledgement, so no body field is required."
1468 //   }]
1469 // }
1470 void request_launch(const llvm::json::Object &request) {
1471   g_vsc.is_attach = false;
1472   llvm::json::Object response;
1473   lldb::SBError error;
1474   FillResponse(request, response);
1475   auto arguments = request.getObject("arguments");
1476   g_vsc.init_commands = GetStrings(arguments, "initCommands");
1477   g_vsc.pre_run_commands = GetStrings(arguments, "preRunCommands");
1478   g_vsc.stop_commands = GetStrings(arguments, "stopCommands");
1479   g_vsc.exit_commands = GetStrings(arguments, "exitCommands");
1480   g_vsc.terminate_commands = GetStrings(arguments, "terminateCommands");
1481   auto launchCommands = GetStrings(arguments, "launchCommands");
1482   g_vsc.stop_at_entry = GetBoolean(arguments, "stopOnEntry", false);
1483   const llvm::StringRef debuggerRoot = GetString(arguments, "debuggerRoot");
1484 
1485   // This is a hack for loading DWARF in .o files on Mac where the .o files
1486   // in the debug map of the main executable have relative paths which require
1487   // the lldb-vscode binary to have its working directory set to that relative
1488   // root for the .o files in order to be able to load debug info.
1489   if (!debuggerRoot.empty())
1490     llvm::sys::fs::set_current_path(debuggerRoot);
1491 
1492   // Run any initialize LLDB commands the user specified in the launch.json.
1493   // This is run before target is created, so commands can't do anything with
1494   // the targets - preRunCommands are run with the target.
1495   g_vsc.RunInitCommands();
1496 
1497   SetSourceMapFromArguments(*arguments);
1498 
1499   lldb::SBError status;
1500   g_vsc.SetTarget(g_vsc.CreateTargetFromArguments(*arguments, status));
1501   if (status.Fail()) {
1502     response["success"] = llvm::json::Value(false);
1503     EmplaceSafeString(response, "message", status.GetCString());
1504     g_vsc.SendJSON(llvm::json::Value(std::move(response)));
1505     return;
1506   }
1507 
1508   // Instantiate a launch info instance for the target.
1509   auto launch_info = g_vsc.target.GetLaunchInfo();
1510 
1511   // Grab the current working directory if there is one and set it in the
1512   // launch info.
1513   const auto cwd = GetString(arguments, "cwd");
1514   if (!cwd.empty())
1515     launch_info.SetWorkingDirectory(cwd.data());
1516 
1517   // Extract any extra arguments and append them to our program arguments for
1518   // when we launch
1519   auto args = GetStrings(arguments, "args");
1520   if (!args.empty())
1521     launch_info.SetArguments(MakeArgv(args).data(), true);
1522 
1523   // Pass any environment variables along that the user specified.
1524   auto envs = GetStrings(arguments, "env");
1525   if (!envs.empty())
1526     launch_info.SetEnvironmentEntries(MakeArgv(envs).data(), true);
1527 
1528   auto flags = launch_info.GetLaunchFlags();
1529 
1530   if (GetBoolean(arguments, "disableASLR", true))
1531     flags |= lldb::eLaunchFlagDisableASLR;
1532   if (GetBoolean(arguments, "disableSTDIO", false))
1533     flags |= lldb::eLaunchFlagDisableSTDIO;
1534   if (GetBoolean(arguments, "shellExpandArguments", false))
1535     flags |= lldb::eLaunchFlagShellExpandArguments;
1536   const bool detatchOnError = GetBoolean(arguments, "detachOnError", false);
1537   launch_info.SetDetachOnError(detatchOnError);
1538   launch_info.SetLaunchFlags(flags | lldb::eLaunchFlagDebug |
1539                              lldb::eLaunchFlagStopAtEntry);
1540 
1541   // Run any pre run LLDB commands the user specified in the launch.json
1542   g_vsc.RunPreRunCommands();
1543   if (launchCommands.empty()) {
1544     // Disable async events so the launch will be successful when we return from
1545     // the launch call and the launch will happen synchronously
1546     g_vsc.debugger.SetAsync(false);
1547     g_vsc.target.Launch(launch_info, error);
1548     g_vsc.debugger.SetAsync(true);
1549   } else {
1550     g_vsc.RunLLDBCommands("Running launchCommands:", launchCommands);
1551     // The custom commands might have created a new target so we should use the
1552     // selected target after these commands are run.
1553     g_vsc.target = g_vsc.debugger.GetSelectedTarget();
1554   }
1555 
1556   if (error.Fail()) {
1557     response["success"] = llvm::json::Value(false);
1558     EmplaceSafeString(response, "message", std::string(error.GetCString()));
1559   }
1560   g_vsc.SendJSON(llvm::json::Value(std::move(response)));
1561 
1562   SendProcessEvent(Launch);
1563   g_vsc.SendJSON(llvm::json::Value(CreateEventObject("initialized")));
1564   // Reenable async events and start the event thread to catch async events.
1565   // g_vsc.debugger.SetAsync(true);
1566 }
1567 
1568 // "NextRequest": {
1569 //   "allOf": [ { "$ref": "#/definitions/Request" }, {
1570 //     "type": "object",
1571 //     "description": "Next request; value of command field is 'next'. The
1572 //                     request starts the debuggee to run again for one step.
1573 //                     The debug adapter first sends the NextResponse and then
1574 //                     a StoppedEvent (event type 'step') after the step has
1575 //                     completed.",
1576 //     "properties": {
1577 //       "command": {
1578 //         "type": "string",
1579 //         "enum": [ "next" ]
1580 //       },
1581 //       "arguments": {
1582 //         "$ref": "#/definitions/NextArguments"
1583 //       }
1584 //     },
1585 //     "required": [ "command", "arguments"  ]
1586 //   }]
1587 // },
1588 // "NextArguments": {
1589 //   "type": "object",
1590 //   "description": "Arguments for 'next' request.",
1591 //   "properties": {
1592 //     "threadId": {
1593 //       "type": "integer",
1594 //       "description": "Execute 'next' for this thread."
1595 //     }
1596 //   },
1597 //   "required": [ "threadId" ]
1598 // },
1599 // "NextResponse": {
1600 //   "allOf": [ { "$ref": "#/definitions/Response" }, {
1601 //     "type": "object",
1602 //     "description": "Response to 'next' request. This is just an
1603 //                     acknowledgement, so no body field is required."
1604 //   }]
1605 // }
1606 void request_next(const llvm::json::Object &request) {
1607   llvm::json::Object response;
1608   FillResponse(request, response);
1609   auto arguments = request.getObject("arguments");
1610   lldb::SBThread thread = g_vsc.GetLLDBThread(*arguments);
1611   if (thread.IsValid()) {
1612     // Remember the thread ID that caused the resume so we can set the
1613     // "threadCausedFocus" boolean value in the "stopped" events.
1614     g_vsc.focus_tid = thread.GetThreadID();
1615     thread.StepOver();
1616   } else {
1617     response["success"] = llvm::json::Value(false);
1618   }
1619   g_vsc.SendJSON(llvm::json::Value(std::move(response)));
1620 }
1621 
1622 // "PauseRequest": {
1623 //   "allOf": [ { "$ref": "#/definitions/Request" }, {
1624 //     "type": "object",
1625 //     "description": "Pause request; value of command field is 'pause'. The
1626 //     request suspenses the debuggee. The debug adapter first sends the
1627 //     PauseResponse and then a StoppedEvent (event type 'pause') after the
1628 //     thread has been paused successfully.", "properties": {
1629 //       "command": {
1630 //         "type": "string",
1631 //         "enum": [ "pause" ]
1632 //       },
1633 //       "arguments": {
1634 //         "$ref": "#/definitions/PauseArguments"
1635 //       }
1636 //     },
1637 //     "required": [ "command", "arguments"  ]
1638 //   }]
1639 // },
1640 // "PauseArguments": {
1641 //   "type": "object",
1642 //   "description": "Arguments for 'pause' request.",
1643 //   "properties": {
1644 //     "threadId": {
1645 //       "type": "integer",
1646 //       "description": "Pause execution for this thread."
1647 //     }
1648 //   },
1649 //   "required": [ "threadId" ]
1650 // },
1651 // "PauseResponse": {
1652 //   "allOf": [ { "$ref": "#/definitions/Response" }, {
1653 //     "type": "object",
1654 //     "description": "Response to 'pause' request. This is just an
1655 //     acknowledgement, so no body field is required."
1656 //   }]
1657 // }
1658 void request_pause(const llvm::json::Object &request) {
1659   llvm::json::Object response;
1660   FillResponse(request, response);
1661   lldb::SBProcess process = g_vsc.target.GetProcess();
1662   lldb::SBError error = process.Stop();
1663   g_vsc.SendJSON(llvm::json::Value(std::move(response)));
1664 }
1665 
1666 // "ScopesRequest": {
1667 //   "allOf": [ { "$ref": "#/definitions/Request" }, {
1668 //     "type": "object",
1669 //     "description": "Scopes request; value of command field is 'scopes'. The
1670 //     request returns the variable scopes for a given stackframe ID.",
1671 //     "properties": {
1672 //       "command": {
1673 //         "type": "string",
1674 //         "enum": [ "scopes" ]
1675 //       },
1676 //       "arguments": {
1677 //         "$ref": "#/definitions/ScopesArguments"
1678 //       }
1679 //     },
1680 //     "required": [ "command", "arguments"  ]
1681 //   }]
1682 // },
1683 // "ScopesArguments": {
1684 //   "type": "object",
1685 //   "description": "Arguments for 'scopes' request.",
1686 //   "properties": {
1687 //     "frameId": {
1688 //       "type": "integer",
1689 //       "description": "Retrieve the scopes for this stackframe."
1690 //     }
1691 //   },
1692 //   "required": [ "frameId" ]
1693 // },
1694 // "ScopesResponse": {
1695 //   "allOf": [ { "$ref": "#/definitions/Response" }, {
1696 //     "type": "object",
1697 //     "description": "Response to 'scopes' request.",
1698 //     "properties": {
1699 //       "body": {
1700 //         "type": "object",
1701 //         "properties": {
1702 //           "scopes": {
1703 //             "type": "array",
1704 //             "items": {
1705 //               "$ref": "#/definitions/Scope"
1706 //             },
1707 //             "description": "The scopes of the stackframe. If the array has
1708 //             length zero, there are no scopes available."
1709 //           }
1710 //         },
1711 //         "required": [ "scopes" ]
1712 //       }
1713 //     },
1714 //     "required": [ "body" ]
1715 //   }]
1716 // }
1717 void request_scopes(const llvm::json::Object &request) {
1718   llvm::json::Object response;
1719   FillResponse(request, response);
1720   llvm::json::Object body;
1721   auto arguments = request.getObject("arguments");
1722   lldb::SBFrame frame = g_vsc.GetLLDBFrame(*arguments);
1723   // As the user selects different stack frames in the GUI, a "scopes" request
1724   // will be sent to the DAP. This is the only way we know that the user has
1725   // selected a frame in a thread. There are no other notifications that are
1726   // sent and VS code doesn't allow multiple frames to show variables
1727   // concurrently. If we select the thread and frame as the "scopes" requests
1728   // are sent, this allows users to type commands in the debugger console
1729   // with a backtick character to run lldb commands and these lldb commands
1730   // will now have the right context selected as they are run. If the user
1731   // types "`bt" into the debugger console and we had another thread selected
1732   // in the LLDB library, we would show the wrong thing to the user. If the
1733   // users switches threads with a lldb command like "`thread select 14", the
1734   // GUI will not update as there are no "event" notification packets that
1735   // allow us to change the currently selected thread or frame in the GUI that
1736   // I am aware of.
1737   if (frame.IsValid()) {
1738     frame.GetThread().GetProcess().SetSelectedThread(frame.GetThread());
1739     frame.GetThread().SetSelectedFrame(frame.GetFrameID());
1740   }
1741   g_vsc.variables.Clear();
1742   g_vsc.variables.Append(frame.GetVariables(true,   // arguments
1743                                             true,   // locals
1744                                             false,  // statics
1745                                             true)); // in_scope_only
1746   g_vsc.num_locals = g_vsc.variables.GetSize();
1747   g_vsc.variables.Append(frame.GetVariables(false,  // arguments
1748                                             false,  // locals
1749                                             true,   // statics
1750                                             true)); // in_scope_only
1751   g_vsc.num_globals = g_vsc.variables.GetSize() - (g_vsc.num_locals);
1752   g_vsc.variables.Append(frame.GetRegisters());
1753   g_vsc.num_regs =
1754       g_vsc.variables.GetSize() - (g_vsc.num_locals + g_vsc.num_globals);
1755   body.try_emplace("scopes", g_vsc.CreateTopLevelScopes());
1756   response.try_emplace("body", std::move(body));
1757   g_vsc.SendJSON(llvm::json::Value(std::move(response)));
1758 }
1759 
1760 // "SetBreakpointsRequest": {
1761 //   "allOf": [ { "$ref": "#/definitions/Request" }, {
1762 //     "type": "object",
1763 //     "description": "SetBreakpoints request; value of command field is
1764 //     'setBreakpoints'. Sets multiple breakpoints for a single source and
1765 //     clears all previous breakpoints in that source. To clear all breakpoint
1766 //     for a source, specify an empty array. When a breakpoint is hit, a
1767 //     StoppedEvent (event type 'breakpoint') is generated.", "properties": {
1768 //       "command": {
1769 //         "type": "string",
1770 //         "enum": [ "setBreakpoints" ]
1771 //       },
1772 //       "arguments": {
1773 //         "$ref": "#/definitions/SetBreakpointsArguments"
1774 //       }
1775 //     },
1776 //     "required": [ "command", "arguments"  ]
1777 //   }]
1778 // },
1779 // "SetBreakpointsArguments": {
1780 //   "type": "object",
1781 //   "description": "Arguments for 'setBreakpoints' request.",
1782 //   "properties": {
1783 //     "source": {
1784 //       "$ref": "#/definitions/Source",
1785 //       "description": "The source location of the breakpoints; either
1786 //       source.path or source.reference must be specified."
1787 //     },
1788 //     "breakpoints": {
1789 //       "type": "array",
1790 //       "items": {
1791 //         "$ref": "#/definitions/SourceBreakpoint"
1792 //       },
1793 //       "description": "The code locations of the breakpoints."
1794 //     },
1795 //     "lines": {
1796 //       "type": "array",
1797 //       "items": {
1798 //         "type": "integer"
1799 //       },
1800 //       "description": "Deprecated: The code locations of the breakpoints."
1801 //     },
1802 //     "sourceModified": {
1803 //       "type": "boolean",
1804 //       "description": "A value of true indicates that the underlying source
1805 //       has been modified which results in new breakpoint locations."
1806 //     }
1807 //   },
1808 //   "required": [ "source" ]
1809 // },
1810 // "SetBreakpointsResponse": {
1811 //   "allOf": [ { "$ref": "#/definitions/Response" }, {
1812 //     "type": "object",
1813 //     "description": "Response to 'setBreakpoints' request. Returned is
1814 //     information about each breakpoint created by this request. This includes
1815 //     the actual code location and whether the breakpoint could be verified.
1816 //     The breakpoints returned are in the same order as the elements of the
1817 //     'breakpoints' (or the deprecated 'lines') in the
1818 //     SetBreakpointsArguments.", "properties": {
1819 //       "body": {
1820 //         "type": "object",
1821 //         "properties": {
1822 //           "breakpoints": {
1823 //             "type": "array",
1824 //             "items": {
1825 //               "$ref": "#/definitions/Breakpoint"
1826 //             },
1827 //             "description": "Information about the breakpoints. The array
1828 //             elements are in the same order as the elements of the
1829 //             'breakpoints' (or the deprecated 'lines') in the
1830 //             SetBreakpointsArguments."
1831 //           }
1832 //         },
1833 //         "required": [ "breakpoints" ]
1834 //       }
1835 //     },
1836 //     "required": [ "body" ]
1837 //   }]
1838 // },
1839 // "SourceBreakpoint": {
1840 //   "type": "object",
1841 //   "description": "Properties of a breakpoint or logpoint passed to the
1842 //   setBreakpoints request.", "properties": {
1843 //     "line": {
1844 //       "type": "integer",
1845 //       "description": "The source line of the breakpoint or logpoint."
1846 //     },
1847 //     "column": {
1848 //       "type": "integer",
1849 //       "description": "An optional source column of the breakpoint."
1850 //     },
1851 //     "condition": {
1852 //       "type": "string",
1853 //       "description": "An optional expression for conditional breakpoints."
1854 //     },
1855 //     "hitCondition": {
1856 //       "type": "string",
1857 //       "description": "An optional expression that controls how many hits of
1858 //       the breakpoint are ignored. The backend is expected to interpret the
1859 //       expression as needed."
1860 //     },
1861 //     "logMessage": {
1862 //       "type": "string",
1863 //       "description": "If this attribute exists and is non-empty, the backend
1864 //       must not 'break' (stop) but log the message instead. Expressions within
1865 //       {} are interpolated."
1866 //     }
1867 //   },
1868 //   "required": [ "line" ]
1869 // }
1870 void request_setBreakpoints(const llvm::json::Object &request) {
1871   llvm::json::Object response;
1872   lldb::SBError error;
1873   FillResponse(request, response);
1874   auto arguments = request.getObject("arguments");
1875   auto source = arguments->getObject("source");
1876   const auto path = GetString(source, "path");
1877   auto breakpoints = arguments->getArray("breakpoints");
1878   llvm::json::Array response_breakpoints;
1879 
1880   // Decode the source breakpoint infos for this "setBreakpoints" request
1881   SourceBreakpointMap request_bps;
1882   for (const auto &bp : *breakpoints) {
1883     auto bp_obj = bp.getAsObject();
1884     if (bp_obj) {
1885       SourceBreakpoint src_bp(*bp_obj);
1886       request_bps[src_bp.line] = src_bp;
1887 
1888       // We check if this breakpoint already exists to update it
1889       auto existing_source_bps = g_vsc.source_breakpoints.find(path);
1890       if (existing_source_bps != g_vsc.source_breakpoints.end()) {
1891         const auto &existing_bp = existing_source_bps->second.find(src_bp.line);
1892         if (existing_bp != existing_source_bps->second.end()) {
1893           existing_bp->second.UpdateBreakpoint(src_bp);
1894           AppendBreakpoint(existing_bp->second.bp, response_breakpoints, path,
1895                            src_bp.line);
1896           continue;
1897         }
1898       }
1899       // At this point the breakpoint is new
1900       src_bp.SetBreakpoint(path.data());
1901       AppendBreakpoint(src_bp.bp, response_breakpoints, path, src_bp.line);
1902       g_vsc.source_breakpoints[path][src_bp.line] = std::move(src_bp);
1903     }
1904   }
1905 
1906   // Delete any breakpoints in this source file that aren't in the
1907   // request_bps set. There is no call to remove breakpoints other than
1908   // calling this function with a smaller or empty "breakpoints" list.
1909   auto old_src_bp_pos = g_vsc.source_breakpoints.find(path);
1910   if (old_src_bp_pos != g_vsc.source_breakpoints.end()) {
1911     for (auto &old_bp : old_src_bp_pos->second) {
1912       auto request_pos = request_bps.find(old_bp.first);
1913       if (request_pos == request_bps.end()) {
1914         // This breakpoint no longer exists in this source file, delete it
1915         g_vsc.target.BreakpointDelete(old_bp.second.bp.GetID());
1916         old_src_bp_pos->second.erase(old_bp.first);
1917       }
1918     }
1919   }
1920 
1921   llvm::json::Object body;
1922   body.try_emplace("breakpoints", std::move(response_breakpoints));
1923   response.try_emplace("body", std::move(body));
1924   g_vsc.SendJSON(llvm::json::Value(std::move(response)));
1925 }
1926 
1927 // "SetExceptionBreakpointsRequest": {
1928 //   "allOf": [ { "$ref": "#/definitions/Request" }, {
1929 //     "type": "object",
1930 //     "description": "SetExceptionBreakpoints request; value of command field
1931 //     is 'setExceptionBreakpoints'. The request configures the debuggers
1932 //     response to thrown exceptions. If an exception is configured to break, a
1933 //     StoppedEvent is fired (event type 'exception').", "properties": {
1934 //       "command": {
1935 //         "type": "string",
1936 //         "enum": [ "setExceptionBreakpoints" ]
1937 //       },
1938 //       "arguments": {
1939 //         "$ref": "#/definitions/SetExceptionBreakpointsArguments"
1940 //       }
1941 //     },
1942 //     "required": [ "command", "arguments"  ]
1943 //   }]
1944 // },
1945 // "SetExceptionBreakpointsArguments": {
1946 //   "type": "object",
1947 //   "description": "Arguments for 'setExceptionBreakpoints' request.",
1948 //   "properties": {
1949 //     "filters": {
1950 //       "type": "array",
1951 //       "items": {
1952 //         "type": "string"
1953 //       },
1954 //       "description": "IDs of checked exception options. The set of IDs is
1955 //       returned via the 'exceptionBreakpointFilters' capability."
1956 //     },
1957 //     "exceptionOptions": {
1958 //       "type": "array",
1959 //       "items": {
1960 //         "$ref": "#/definitions/ExceptionOptions"
1961 //       },
1962 //       "description": "Configuration options for selected exceptions."
1963 //     }
1964 //   },
1965 //   "required": [ "filters" ]
1966 // },
1967 // "SetExceptionBreakpointsResponse": {
1968 //   "allOf": [ { "$ref": "#/definitions/Response" }, {
1969 //     "type": "object",
1970 //     "description": "Response to 'setExceptionBreakpoints' request. This is
1971 //     just an acknowledgement, so no body field is required."
1972 //   }]
1973 // }
1974 void request_setExceptionBreakpoints(const llvm::json::Object &request) {
1975   llvm::json::Object response;
1976   lldb::SBError error;
1977   FillResponse(request, response);
1978   auto arguments = request.getObject("arguments");
1979   auto filters = arguments->getArray("filters");
1980   // Keep a list of any exception breakpoint filter names that weren't set
1981   // so we can clear any exception breakpoints if needed.
1982   std::set<std::string> unset_filters;
1983   for (const auto &bp : g_vsc.exception_breakpoints)
1984     unset_filters.insert(bp.filter);
1985 
1986   for (const auto &value : *filters) {
1987     const auto filter = GetAsString(value);
1988     auto exc_bp = g_vsc.GetExceptionBreakpoint(std::string(filter));
1989     if (exc_bp) {
1990       exc_bp->SetBreakpoint();
1991       unset_filters.erase(std::string(filter));
1992     }
1993   }
1994   for (const auto &filter : unset_filters) {
1995     auto exc_bp = g_vsc.GetExceptionBreakpoint(filter);
1996     if (exc_bp)
1997       exc_bp->ClearBreakpoint();
1998   }
1999   g_vsc.SendJSON(llvm::json::Value(std::move(response)));
2000 }
2001 
2002 // "SetFunctionBreakpointsRequest": {
2003 //   "allOf": [ { "$ref": "#/definitions/Request" }, {
2004 //     "type": "object",
2005 //     "description": "SetFunctionBreakpoints request; value of command field is
2006 //     'setFunctionBreakpoints'. Sets multiple function breakpoints and clears
2007 //     all previous function breakpoints. To clear all function breakpoint,
2008 //     specify an empty array. When a function breakpoint is hit, a StoppedEvent
2009 //     (event type 'function breakpoint') is generated.", "properties": {
2010 //       "command": {
2011 //         "type": "string",
2012 //         "enum": [ "setFunctionBreakpoints" ]
2013 //       },
2014 //       "arguments": {
2015 //         "$ref": "#/definitions/SetFunctionBreakpointsArguments"
2016 //       }
2017 //     },
2018 //     "required": [ "command", "arguments"  ]
2019 //   }]
2020 // },
2021 // "SetFunctionBreakpointsArguments": {
2022 //   "type": "object",
2023 //   "description": "Arguments for 'setFunctionBreakpoints' request.",
2024 //   "properties": {
2025 //     "breakpoints": {
2026 //       "type": "array",
2027 //       "items": {
2028 //         "$ref": "#/definitions/FunctionBreakpoint"
2029 //       },
2030 //       "description": "The function names of the breakpoints."
2031 //     }
2032 //   },
2033 //   "required": [ "breakpoints" ]
2034 // },
2035 // "FunctionBreakpoint": {
2036 //   "type": "object",
2037 //   "description": "Properties of a breakpoint passed to the
2038 //   setFunctionBreakpoints request.", "properties": {
2039 //     "name": {
2040 //       "type": "string",
2041 //       "description": "The name of the function."
2042 //     },
2043 //     "condition": {
2044 //       "type": "string",
2045 //       "description": "An optional expression for conditional breakpoints."
2046 //     },
2047 //     "hitCondition": {
2048 //       "type": "string",
2049 //       "description": "An optional expression that controls how many hits of
2050 //       the breakpoint are ignored. The backend is expected to interpret the
2051 //       expression as needed."
2052 //     }
2053 //   },
2054 //   "required": [ "name" ]
2055 // },
2056 // "SetFunctionBreakpointsResponse": {
2057 //   "allOf": [ { "$ref": "#/definitions/Response" }, {
2058 //     "type": "object",
2059 //     "description": "Response to 'setFunctionBreakpoints' request. Returned is
2060 //     information about each breakpoint created by this request.",
2061 //     "properties": {
2062 //       "body": {
2063 //         "type": "object",
2064 //         "properties": {
2065 //           "breakpoints": {
2066 //             "type": "array",
2067 //             "items": {
2068 //               "$ref": "#/definitions/Breakpoint"
2069 //             },
2070 //             "description": "Information about the breakpoints. The array
2071 //             elements correspond to the elements of the 'breakpoints' array."
2072 //           }
2073 //         },
2074 //         "required": [ "breakpoints" ]
2075 //       }
2076 //     },
2077 //     "required": [ "body" ]
2078 //   }]
2079 // }
2080 void request_setFunctionBreakpoints(const llvm::json::Object &request) {
2081   llvm::json::Object response;
2082   lldb::SBError error;
2083   FillResponse(request, response);
2084   auto arguments = request.getObject("arguments");
2085   auto breakpoints = arguments->getArray("breakpoints");
2086   FunctionBreakpointMap request_bps;
2087   llvm::json::Array response_breakpoints;
2088   for (const auto &value : *breakpoints) {
2089     auto bp_obj = value.getAsObject();
2090     if (bp_obj == nullptr)
2091       continue;
2092     FunctionBreakpoint func_bp(*bp_obj);
2093     request_bps[func_bp.functionName] = std::move(func_bp);
2094   }
2095 
2096   std::vector<llvm::StringRef> remove_names;
2097   // Disable any function breakpoints that aren't in the request_bps.
2098   // There is no call to remove function breakpoints other than calling this
2099   // function with a smaller or empty "breakpoints" list.
2100   for (auto &pair : g_vsc.function_breakpoints) {
2101     auto request_pos = request_bps.find(pair.first());
2102     if (request_pos == request_bps.end()) {
2103       // This function breakpoint no longer exists delete it from LLDB
2104       g_vsc.target.BreakpointDelete(pair.second.bp.GetID());
2105       remove_names.push_back(pair.first());
2106     } else {
2107       // Update the existing breakpoint as any setting withing the function
2108       // breakpoint might have changed.
2109       pair.second.UpdateBreakpoint(request_pos->second);
2110       // Remove this breakpoint from the request breakpoints since we have
2111       // handled it here and we don't need to set a new breakpoint below.
2112       request_bps.erase(request_pos);
2113       // Add this breakpoint info to the response
2114       AppendBreakpoint(pair.second.bp, response_breakpoints);
2115     }
2116   }
2117   // Remove any breakpoints that are no longer in our list
2118   for (const auto &name : remove_names)
2119     g_vsc.function_breakpoints.erase(name);
2120 
2121   // Any breakpoints that are left in "request_bps" are breakpoints that
2122   // need to be set.
2123   for (auto &pair : request_bps) {
2124     pair.second.SetBreakpoint();
2125     // Add this breakpoint info to the response
2126     AppendBreakpoint(pair.second.bp, response_breakpoints);
2127     g_vsc.function_breakpoints[pair.first()] = std::move(pair.second);
2128   }
2129 
2130   llvm::json::Object body;
2131   body.try_emplace("breakpoints", std::move(response_breakpoints));
2132   response.try_emplace("body", std::move(body));
2133   g_vsc.SendJSON(llvm::json::Value(std::move(response)));
2134 }
2135 
2136 // "SourceRequest": {
2137 //   "allOf": [ { "$ref": "#/definitions/Request" }, {
2138 //     "type": "object",
2139 //     "description": "Source request; value of command field is 'source'. The
2140 //     request retrieves the source code for a given source reference.",
2141 //     "properties": {
2142 //       "command": {
2143 //         "type": "string",
2144 //         "enum": [ "source" ]
2145 //       },
2146 //       "arguments": {
2147 //         "$ref": "#/definitions/SourceArguments"
2148 //       }
2149 //     },
2150 //     "required": [ "command", "arguments"  ]
2151 //   }]
2152 // },
2153 // "SourceArguments": {
2154 //   "type": "object",
2155 //   "description": "Arguments for 'source' request.",
2156 //   "properties": {
2157 //     "source": {
2158 //       "$ref": "#/definitions/Source",
2159 //       "description": "Specifies the source content to load. Either
2160 //       source.path or source.sourceReference must be specified."
2161 //     },
2162 //     "sourceReference": {
2163 //       "type": "integer",
2164 //       "description": "The reference to the source. This is the same as
2165 //       source.sourceReference. This is provided for backward compatibility
2166 //       since old backends do not understand the 'source' attribute."
2167 //     }
2168 //   },
2169 //   "required": [ "sourceReference" ]
2170 // },
2171 // "SourceResponse": {
2172 //   "allOf": [ { "$ref": "#/definitions/Response" }, {
2173 //     "type": "object",
2174 //     "description": "Response to 'source' request.",
2175 //     "properties": {
2176 //       "body": {
2177 //         "type": "object",
2178 //         "properties": {
2179 //           "content": {
2180 //             "type": "string",
2181 //             "description": "Content of the source reference."
2182 //           },
2183 //           "mimeType": {
2184 //             "type": "string",
2185 //             "description": "Optional content type (mime type) of the source."
2186 //           }
2187 //         },
2188 //         "required": [ "content" ]
2189 //       }
2190 //     },
2191 //     "required": [ "body" ]
2192 //   }]
2193 // }
2194 void request_source(const llvm::json::Object &request) {
2195   llvm::json::Object response;
2196   FillResponse(request, response);
2197   llvm::json::Object body;
2198 
2199   auto arguments = request.getObject("arguments");
2200   auto source = arguments->getObject("source");
2201   auto sourceReference = GetSigned(source, "sourceReference", -1);
2202   auto pos = g_vsc.source_map.find((lldb::addr_t)sourceReference);
2203   if (pos != g_vsc.source_map.end()) {
2204     EmplaceSafeString(body, "content", pos->second.content);
2205   } else {
2206     response["success"] = llvm::json::Value(false);
2207   }
2208   EmplaceSafeString(body, "mimeType", "text/x-lldb.disassembly");
2209   response.try_emplace("body", std::move(body));
2210   g_vsc.SendJSON(llvm::json::Value(std::move(response)));
2211 }
2212 
2213 // "StackTraceRequest": {
2214 //   "allOf": [ { "$ref": "#/definitions/Request" }, {
2215 //     "type": "object",
2216 //     "description": "StackTrace request; value of command field is
2217 //     'stackTrace'. The request returns a stacktrace from the current execution
2218 //     state.", "properties": {
2219 //       "command": {
2220 //         "type": "string",
2221 //         "enum": [ "stackTrace" ]
2222 //       },
2223 //       "arguments": {
2224 //         "$ref": "#/definitions/StackTraceArguments"
2225 //       }
2226 //     },
2227 //     "required": [ "command", "arguments"  ]
2228 //   }]
2229 // },
2230 // "StackTraceArguments": {
2231 //   "type": "object",
2232 //   "description": "Arguments for 'stackTrace' request.",
2233 //   "properties": {
2234 //     "threadId": {
2235 //       "type": "integer",
2236 //       "description": "Retrieve the stacktrace for this thread."
2237 //     },
2238 //     "startFrame": {
2239 //       "type": "integer",
2240 //       "description": "The index of the first frame to return; if omitted
2241 //       frames start at 0."
2242 //     },
2243 //     "levels": {
2244 //       "type": "integer",
2245 //       "description": "The maximum number of frames to return. If levels is
2246 //       not specified or 0, all frames are returned."
2247 //     },
2248 //     "format": {
2249 //       "$ref": "#/definitions/StackFrameFormat",
2250 //       "description": "Specifies details on how to format the stack frames."
2251 //     }
2252 //  },
2253 //   "required": [ "threadId" ]
2254 // },
2255 // "StackTraceResponse": {
2256 //   "allOf": [ { "$ref": "#/definitions/Response" }, {
2257 //     "type": "object",
2258 //     "description": "Response to 'stackTrace' request.",
2259 //     "properties": {
2260 //       "body": {
2261 //         "type": "object",
2262 //         "properties": {
2263 //           "stackFrames": {
2264 //             "type": "array",
2265 //             "items": {
2266 //               "$ref": "#/definitions/StackFrame"
2267 //             },
2268 //             "description": "The frames of the stackframe. If the array has
2269 //             length zero, there are no stackframes available. This means that
2270 //             there is no location information available."
2271 //           },
2272 //           "totalFrames": {
2273 //             "type": "integer",
2274 //             "description": "The total number of frames available."
2275 //           }
2276 //         },
2277 //         "required": [ "stackFrames" ]
2278 //       }
2279 //     },
2280 //     "required": [ "body" ]
2281 //   }]
2282 // }
2283 void request_stackTrace(const llvm::json::Object &request) {
2284   llvm::json::Object response;
2285   FillResponse(request, response);
2286   lldb::SBError error;
2287   auto arguments = request.getObject("arguments");
2288   lldb::SBThread thread = g_vsc.GetLLDBThread(*arguments);
2289   llvm::json::Array stackFrames;
2290   llvm::json::Object body;
2291 
2292   if (thread.IsValid()) {
2293     const auto startFrame = GetUnsigned(arguments, "startFrame", 0);
2294     const auto levels = GetUnsigned(arguments, "levels", 0);
2295     const auto endFrame = (levels == 0) ? INT64_MAX : (startFrame + levels);
2296     for (uint32_t i = startFrame; i < endFrame; ++i) {
2297       auto frame = thread.GetFrameAtIndex(i);
2298       if (!frame.IsValid())
2299         break;
2300       stackFrames.emplace_back(CreateStackFrame(frame));
2301     }
2302     const auto totalFrames = thread.GetNumFrames();
2303     body.try_emplace("totalFrames", totalFrames);
2304   }
2305   body.try_emplace("stackFrames", std::move(stackFrames));
2306   response.try_emplace("body", std::move(body));
2307   g_vsc.SendJSON(llvm::json::Value(std::move(response)));
2308 }
2309 
2310 // "StepInRequest": {
2311 //   "allOf": [ { "$ref": "#/definitions/Request" }, {
2312 //     "type": "object",
2313 //     "description": "StepIn request; value of command field is 'stepIn'. The
2314 //     request starts the debuggee to step into a function/method if possible.
2315 //     If it cannot step into a target, 'stepIn' behaves like 'next'. The debug
2316 //     adapter first sends the StepInResponse and then a StoppedEvent (event
2317 //     type 'step') after the step has completed. If there are multiple
2318 //     function/method calls (or other targets) on the source line, the optional
2319 //     argument 'targetId' can be used to control into which target the 'stepIn'
2320 //     should occur. The list of possible targets for a given source line can be
2321 //     retrieved via the 'stepInTargets' request.", "properties": {
2322 //       "command": {
2323 //         "type": "string",
2324 //         "enum": [ "stepIn" ]
2325 //       },
2326 //       "arguments": {
2327 //         "$ref": "#/definitions/StepInArguments"
2328 //       }
2329 //     },
2330 //     "required": [ "command", "arguments"  ]
2331 //   }]
2332 // },
2333 // "StepInArguments": {
2334 //   "type": "object",
2335 //   "description": "Arguments for 'stepIn' request.",
2336 //   "properties": {
2337 //     "threadId": {
2338 //       "type": "integer",
2339 //       "description": "Execute 'stepIn' for this thread."
2340 //     },
2341 //     "targetId": {
2342 //       "type": "integer",
2343 //       "description": "Optional id of the target to step into."
2344 //     }
2345 //   },
2346 //   "required": [ "threadId" ]
2347 // },
2348 // "StepInResponse": {
2349 //   "allOf": [ { "$ref": "#/definitions/Response" }, {
2350 //     "type": "object",
2351 //     "description": "Response to 'stepIn' request. This is just an
2352 //     acknowledgement, so no body field is required."
2353 //   }]
2354 // }
2355 void request_stepIn(const llvm::json::Object &request) {
2356   llvm::json::Object response;
2357   FillResponse(request, response);
2358   auto arguments = request.getObject("arguments");
2359   lldb::SBThread thread = g_vsc.GetLLDBThread(*arguments);
2360   if (thread.IsValid()) {
2361     // Remember the thread ID that caused the resume so we can set the
2362     // "threadCausedFocus" boolean value in the "stopped" events.
2363     g_vsc.focus_tid = thread.GetThreadID();
2364     thread.StepInto();
2365   } else {
2366     response["success"] = llvm::json::Value(false);
2367   }
2368   g_vsc.SendJSON(llvm::json::Value(std::move(response)));
2369 }
2370 
2371 // "StepOutRequest": {
2372 //   "allOf": [ { "$ref": "#/definitions/Request" }, {
2373 //     "type": "object",
2374 //     "description": "StepOut request; value of command field is 'stepOut'. The
2375 //     request starts the debuggee to run again for one step. The debug adapter
2376 //     first sends the StepOutResponse and then a StoppedEvent (event type
2377 //     'step') after the step has completed.", "properties": {
2378 //       "command": {
2379 //         "type": "string",
2380 //         "enum": [ "stepOut" ]
2381 //       },
2382 //       "arguments": {
2383 //         "$ref": "#/definitions/StepOutArguments"
2384 //       }
2385 //     },
2386 //     "required": [ "command", "arguments"  ]
2387 //   }]
2388 // },
2389 // "StepOutArguments": {
2390 //   "type": "object",
2391 //   "description": "Arguments for 'stepOut' request.",
2392 //   "properties": {
2393 //     "threadId": {
2394 //       "type": "integer",
2395 //       "description": "Execute 'stepOut' for this thread."
2396 //     }
2397 //   },
2398 //   "required": [ "threadId" ]
2399 // },
2400 // "StepOutResponse": {
2401 //   "allOf": [ { "$ref": "#/definitions/Response" }, {
2402 //     "type": "object",
2403 //     "description": "Response to 'stepOut' request. This is just an
2404 //     acknowledgement, so no body field is required."
2405 //   }]
2406 // }
2407 void request_stepOut(const llvm::json::Object &request) {
2408   llvm::json::Object response;
2409   FillResponse(request, response);
2410   auto arguments = request.getObject("arguments");
2411   lldb::SBThread thread = g_vsc.GetLLDBThread(*arguments);
2412   if (thread.IsValid()) {
2413     // Remember the thread ID that caused the resume so we can set the
2414     // "threadCausedFocus" boolean value in the "stopped" events.
2415     g_vsc.focus_tid = thread.GetThreadID();
2416     thread.StepOut();
2417   } else {
2418     response["success"] = llvm::json::Value(false);
2419   }
2420   g_vsc.SendJSON(llvm::json::Value(std::move(response)));
2421 }
2422 
2423 // "ThreadsRequest": {
2424 //   "allOf": [ { "$ref": "#/definitions/Request" }, {
2425 //     "type": "object",
2426 //     "description": "Thread request; value of command field is 'threads'. The
2427 //     request retrieves a list of all threads.", "properties": {
2428 //       "command": {
2429 //         "type": "string",
2430 //         "enum": [ "threads" ]
2431 //       }
2432 //     },
2433 //     "required": [ "command" ]
2434 //   }]
2435 // },
2436 // "ThreadsResponse": {
2437 //   "allOf": [ { "$ref": "#/definitions/Response" }, {
2438 //     "type": "object",
2439 //     "description": "Response to 'threads' request.",
2440 //     "properties": {
2441 //       "body": {
2442 //         "type": "object",
2443 //         "properties": {
2444 //           "threads": {
2445 //             "type": "array",
2446 //             "items": {
2447 //               "$ref": "#/definitions/Thread"
2448 //             },
2449 //             "description": "All threads."
2450 //           }
2451 //         },
2452 //         "required": [ "threads" ]
2453 //       }
2454 //     },
2455 //     "required": [ "body" ]
2456 //   }]
2457 // }
2458 void request_threads(const llvm::json::Object &request) {
2459 
2460   lldb::SBProcess process = g_vsc.target.GetProcess();
2461   llvm::json::Object response;
2462   FillResponse(request, response);
2463 
2464   const uint32_t num_threads = process.GetNumThreads();
2465   llvm::json::Array threads;
2466   for (uint32_t thread_idx = 0; thread_idx < num_threads; ++thread_idx) {
2467     lldb::SBThread thread = process.GetThreadAtIndex(thread_idx);
2468     threads.emplace_back(CreateThread(thread));
2469   }
2470   if (threads.size() == 0) {
2471     response["success"] = llvm::json::Value(false);
2472   }
2473   llvm::json::Object body;
2474   body.try_emplace("threads", std::move(threads));
2475   response.try_emplace("body", std::move(body));
2476   g_vsc.SendJSON(llvm::json::Value(std::move(response)));
2477 }
2478 
2479 // "SetVariableRequest": {
2480 //   "allOf": [ { "$ref": "#/definitions/Request" }, {
2481 //     "type": "object",
2482 //     "description": "setVariable request; value of command field is
2483 //     'setVariable'. Set the variable with the given name in the variable
2484 //     container to a new value.", "properties": {
2485 //       "command": {
2486 //         "type": "string",
2487 //         "enum": [ "setVariable" ]
2488 //       },
2489 //       "arguments": {
2490 //         "$ref": "#/definitions/SetVariableArguments"
2491 //       }
2492 //     },
2493 //     "required": [ "command", "arguments"  ]
2494 //   }]
2495 // },
2496 // "SetVariableArguments": {
2497 //   "type": "object",
2498 //   "description": "Arguments for 'setVariable' request.",
2499 //   "properties": {
2500 //     "variablesReference": {
2501 //       "type": "integer",
2502 //       "description": "The reference of the variable container."
2503 //     },
2504 //     "name": {
2505 //       "type": "string",
2506 //       "description": "The name of the variable."
2507 //     },
2508 //     "value": {
2509 //       "type": "string",
2510 //       "description": "The value of the variable."
2511 //     },
2512 //     "format": {
2513 //       "$ref": "#/definitions/ValueFormat",
2514 //       "description": "Specifies details on how to format the response value."
2515 //     }
2516 //   },
2517 //   "required": [ "variablesReference", "name", "value" ]
2518 // },
2519 // "SetVariableResponse": {
2520 //   "allOf": [ { "$ref": "#/definitions/Response" }, {
2521 //     "type": "object",
2522 //     "description": "Response to 'setVariable' request.",
2523 //     "properties": {
2524 //       "body": {
2525 //         "type": "object",
2526 //         "properties": {
2527 //           "value": {
2528 //             "type": "string",
2529 //             "description": "The new value of the variable."
2530 //           },
2531 //           "type": {
2532 //             "type": "string",
2533 //             "description": "The type of the new value. Typically shown in the
2534 //             UI when hovering over the value."
2535 //           },
2536 //           "variablesReference": {
2537 //             "type": "number",
2538 //             "description": "If variablesReference is > 0, the new value is
2539 //             structured and its children can be retrieved by passing
2540 //             variablesReference to the VariablesRequest."
2541 //           },
2542 //           "namedVariables": {
2543 //             "type": "number",
2544 //             "description": "The number of named child variables. The client
2545 //             can use this optional information to present the variables in a
2546 //             paged UI and fetch them in chunks."
2547 //           },
2548 //           "indexedVariables": {
2549 //             "type": "number",
2550 //             "description": "The number of indexed child variables. The client
2551 //             can use this optional information to present the variables in a
2552 //             paged UI and fetch them in chunks."
2553 //           }
2554 //         },
2555 //         "required": [ "value" ]
2556 //       }
2557 //     },
2558 //     "required": [ "body" ]
2559 //   }]
2560 // }
2561 void request_setVariable(const llvm::json::Object &request) {
2562   llvm::json::Object response;
2563   FillResponse(request, response);
2564   llvm::json::Array variables;
2565   llvm::json::Object body;
2566   auto arguments = request.getObject("arguments");
2567   // This is a reference to the containing variable/scope
2568   const auto variablesReference =
2569       GetUnsigned(arguments, "variablesReference", 0);
2570   const auto name = GetString(arguments, "name");
2571   const auto value = GetString(arguments, "value");
2572   // Set success to false just in case we don't find the variable by name
2573   response.try_emplace("success", false);
2574 
2575   lldb::SBValue variable;
2576   int64_t newVariablesReference = 0;
2577 
2578   // The "id" is the unique integer ID that is unique within the enclosing
2579   // variablesReference. It is optionally added to any "interface Variable"
2580   // objects to uniquely identify a variable within an enclosing
2581   // variablesReference. It helps to disambiguate between two variables that
2582   // have the same name within the same scope since the "setVariables" request
2583   // only specifies the variable reference of the enclosing scope/variable, and
2584   // the name of the variable. We could have two shadowed variables with the
2585   // same name in "Locals" or "Globals". In our case the "id" absolute index
2586   // of the variable within the g_vsc.variables list.
2587   const auto id_value = GetUnsigned(arguments, "id", UINT64_MAX);
2588   if (id_value != UINT64_MAX) {
2589     variable = g_vsc.variables.GetValueAtIndex(id_value);
2590   } else if (VARREF_IS_SCOPE(variablesReference)) {
2591     // variablesReference is one of our scopes, not an actual variable it is
2592     // asking for a variable in locals or globals or registers
2593     int64_t start_idx = 0;
2594     int64_t end_idx = 0;
2595     switch (variablesReference) {
2596     case VARREF_LOCALS:
2597       start_idx = 0;
2598       end_idx = start_idx + g_vsc.num_locals;
2599       break;
2600     case VARREF_GLOBALS:
2601       start_idx = g_vsc.num_locals;
2602       end_idx = start_idx + g_vsc.num_globals;
2603       break;
2604     case VARREF_REGS:
2605       start_idx = g_vsc.num_locals + g_vsc.num_globals;
2606       end_idx = start_idx + g_vsc.num_regs;
2607       break;
2608     default:
2609       break;
2610     }
2611 
2612     // Find the variable by name in the correct scope and hope we don't have
2613     // multiple variables with the same name. We search backwards because
2614     // the list of variables has the top most variables first and variables
2615     // in deeper scopes are last. This means we will catch the deepest
2616     // variable whose name matches which is probably what the user wants.
2617     for (int64_t i = end_idx - 1; i >= start_idx; --i) {
2618       auto curr_variable = g_vsc.variables.GetValueAtIndex(i);
2619       llvm::StringRef variable_name(curr_variable.GetName());
2620       if (variable_name == name) {
2621         variable = curr_variable;
2622         if (curr_variable.MightHaveChildren())
2623           newVariablesReference = i;
2624         break;
2625       }
2626     }
2627   } else {
2628     // We have a named item within an actual variable so we need to find it
2629     // withing the container variable by name.
2630     const int64_t var_idx = VARREF_TO_VARIDX(variablesReference);
2631     lldb::SBValue container = g_vsc.variables.GetValueAtIndex(var_idx);
2632     variable = container.GetChildMemberWithName(name.data());
2633     if (!variable.IsValid()) {
2634       if (name.startswith("[")) {
2635         llvm::StringRef index_str(name.drop_front(1));
2636         uint64_t index = 0;
2637         if (!index_str.consumeInteger(0, index)) {
2638           if (index_str == "]")
2639             variable = container.GetChildAtIndex(index);
2640         }
2641       }
2642     }
2643 
2644     // We don't know the index of the variable in our g_vsc.variables
2645     if (variable.IsValid()) {
2646       if (variable.MightHaveChildren()) {
2647         newVariablesReference = VARIDX_TO_VARREF(g_vsc.variables.GetSize());
2648         g_vsc.variables.Append(variable);
2649       }
2650     }
2651   }
2652 
2653   if (variable.IsValid()) {
2654     lldb::SBError error;
2655     bool success = variable.SetValueFromCString(value.data(), error);
2656     if (success) {
2657       SetValueForKey(variable, body, "value");
2658       EmplaceSafeString(body, "type", variable.GetType().GetDisplayTypeName());
2659       body.try_emplace("variablesReference", newVariablesReference);
2660     } else {
2661       EmplaceSafeString(body, "message", std::string(error.GetCString()));
2662     }
2663     response["success"] = llvm::json::Value(success);
2664   }
2665 
2666   response.try_emplace("body", std::move(body));
2667   g_vsc.SendJSON(llvm::json::Value(std::move(response)));
2668 }
2669 
2670 // "VariablesRequest": {
2671 //   "allOf": [ { "$ref": "#/definitions/Request" }, {
2672 //     "type": "object",
2673 //     "description": "Variables request; value of command field is 'variables'.
2674 //     Retrieves all child variables for the given variable reference. An
2675 //     optional filter can be used to limit the fetched children to either named
2676 //     or indexed children.", "properties": {
2677 //       "command": {
2678 //         "type": "string",
2679 //         "enum": [ "variables" ]
2680 //       },
2681 //       "arguments": {
2682 //         "$ref": "#/definitions/VariablesArguments"
2683 //       }
2684 //     },
2685 //     "required": [ "command", "arguments"  ]
2686 //   }]
2687 // },
2688 // "VariablesArguments": {
2689 //   "type": "object",
2690 //   "description": "Arguments for 'variables' request.",
2691 //   "properties": {
2692 //     "variablesReference": {
2693 //       "type": "integer",
2694 //       "description": "The Variable reference."
2695 //     },
2696 //     "filter": {
2697 //       "type": "string",
2698 //       "enum": [ "indexed", "named" ],
2699 //       "description": "Optional filter to limit the child variables to either
2700 //       named or indexed. If ommited, both types are fetched."
2701 //     },
2702 //     "start": {
2703 //       "type": "integer",
2704 //       "description": "The index of the first variable to return; if omitted
2705 //       children start at 0."
2706 //     },
2707 //     "count": {
2708 //       "type": "integer",
2709 //       "description": "The number of variables to return. If count is missing
2710 //       or 0, all variables are returned."
2711 //     },
2712 //     "format": {
2713 //       "$ref": "#/definitions/ValueFormat",
2714 //       "description": "Specifies details on how to format the Variable
2715 //       values."
2716 //     }
2717 //   },
2718 //   "required": [ "variablesReference" ]
2719 // },
2720 // "VariablesResponse": {
2721 //   "allOf": [ { "$ref": "#/definitions/Response" }, {
2722 //     "type": "object",
2723 //     "description": "Response to 'variables' request.",
2724 //     "properties": {
2725 //       "body": {
2726 //         "type": "object",
2727 //         "properties": {
2728 //           "variables": {
2729 //             "type": "array",
2730 //             "items": {
2731 //               "$ref": "#/definitions/Variable"
2732 //             },
2733 //             "description": "All (or a range) of variables for the given
2734 //             variable reference."
2735 //           }
2736 //         },
2737 //         "required": [ "variables" ]
2738 //       }
2739 //     },
2740 //     "required": [ "body" ]
2741 //   }]
2742 // }
2743 void request_variables(const llvm::json::Object &request) {
2744   llvm::json::Object response;
2745   FillResponse(request, response);
2746   llvm::json::Array variables;
2747   auto arguments = request.getObject("arguments");
2748   const auto variablesReference =
2749       GetUnsigned(arguments, "variablesReference", 0);
2750   const int64_t start = GetSigned(arguments, "start", 0);
2751   const int64_t count = GetSigned(arguments, "count", 0);
2752   bool hex = false;
2753   auto format = arguments->getObject("format");
2754   if (format)
2755     hex = GetBoolean(format, "hex", false);
2756 
2757   if (VARREF_IS_SCOPE(variablesReference)) {
2758     // variablesReference is one of our scopes, not an actual variable it is
2759     // asking for the list of args, locals or globals.
2760     int64_t start_idx = 0;
2761     int64_t num_children = 0;
2762     switch (variablesReference) {
2763     case VARREF_LOCALS:
2764       start_idx = start;
2765       num_children = g_vsc.num_locals;
2766       break;
2767     case VARREF_GLOBALS:
2768       start_idx = start + g_vsc.num_locals + start;
2769       num_children = g_vsc.num_globals;
2770       break;
2771     case VARREF_REGS:
2772       start_idx = start + g_vsc.num_locals + g_vsc.num_globals;
2773       num_children = g_vsc.num_regs;
2774       break;
2775     default:
2776       break;
2777     }
2778     const int64_t end_idx = start_idx + ((count == 0) ? num_children : count);
2779     for (auto i = start_idx; i < end_idx; ++i) {
2780       lldb::SBValue variable = g_vsc.variables.GetValueAtIndex(i);
2781       if (!variable.IsValid())
2782         break;
2783       variables.emplace_back(
2784           CreateVariable(variable, VARIDX_TO_VARREF(i), i, hex));
2785     }
2786   } else {
2787     // We are expanding a variable that has children, so we will return its
2788     // children.
2789     const int64_t var_idx = VARREF_TO_VARIDX(variablesReference);
2790     lldb::SBValue variable = g_vsc.variables.GetValueAtIndex(var_idx);
2791     if (variable.IsValid()) {
2792       const auto num_children = variable.GetNumChildren();
2793       const int64_t end_idx = start + ((count == 0) ? num_children : count);
2794       for (auto i = start; i < end_idx; ++i) {
2795         lldb::SBValue child = variable.GetChildAtIndex(i);
2796         if (!child.IsValid())
2797           break;
2798         if (child.MightHaveChildren()) {
2799           const int64_t var_idx = g_vsc.variables.GetSize();
2800           auto childVariablesReferences = VARIDX_TO_VARREF(var_idx);
2801           variables.emplace_back(
2802               CreateVariable(child, childVariablesReferences, var_idx, hex));
2803           g_vsc.variables.Append(child);
2804         } else {
2805           variables.emplace_back(CreateVariable(child, 0, INT64_MAX, hex));
2806         }
2807       }
2808     }
2809   }
2810   llvm::json::Object body;
2811   body.try_emplace("variables", std::move(variables));
2812   response.try_emplace("body", std::move(body));
2813   g_vsc.SendJSON(llvm::json::Value(std::move(response)));
2814 }
2815 
2816 // A request used in testing to get the details on all breakpoints that are
2817 // currently set in the target. This helps us to test "setBreakpoints" and
2818 // "setFunctionBreakpoints" requests to verify we have the correct set of
2819 // breakpoints currently set in LLDB.
2820 void request__testGetTargetBreakpoints(const llvm::json::Object &request) {
2821   llvm::json::Object response;
2822   FillResponse(request, response);
2823   llvm::json::Array response_breakpoints;
2824   for (uint32_t i = 0; g_vsc.target.GetBreakpointAtIndex(i).IsValid(); ++i) {
2825     auto bp = g_vsc.target.GetBreakpointAtIndex(i);
2826     AppendBreakpoint(bp, response_breakpoints);
2827   }
2828   llvm::json::Object body;
2829   body.try_emplace("breakpoints", std::move(response_breakpoints));
2830   response.try_emplace("body", std::move(body));
2831   g_vsc.SendJSON(llvm::json::Value(std::move(response)));
2832 }
2833 
2834 const std::map<std::string, RequestCallback> &GetRequestHandlers() {
2835 #define REQUEST_CALLBACK(name)                                                 \
2836   { #name, request_##name }
2837   static std::map<std::string, RequestCallback> g_request_handlers = {
2838       // VSCode Debug Adaptor requests
2839       REQUEST_CALLBACK(attach),
2840       REQUEST_CALLBACK(completions),
2841       REQUEST_CALLBACK(continue),
2842       REQUEST_CALLBACK(configurationDone),
2843       REQUEST_CALLBACK(disconnect),
2844       REQUEST_CALLBACK(evaluate),
2845       REQUEST_CALLBACK(exceptionInfo),
2846       REQUEST_CALLBACK(getCompileUnits),
2847       REQUEST_CALLBACK(initialize),
2848       REQUEST_CALLBACK(launch),
2849       REQUEST_CALLBACK(next),
2850       REQUEST_CALLBACK(pause),
2851       REQUEST_CALLBACK(scopes),
2852       REQUEST_CALLBACK(setBreakpoints),
2853       REQUEST_CALLBACK(setExceptionBreakpoints),
2854       REQUEST_CALLBACK(setFunctionBreakpoints),
2855       REQUEST_CALLBACK(setVariable),
2856       REQUEST_CALLBACK(source),
2857       REQUEST_CALLBACK(stackTrace),
2858       REQUEST_CALLBACK(stepIn),
2859       REQUEST_CALLBACK(stepOut),
2860       REQUEST_CALLBACK(threads),
2861       REQUEST_CALLBACK(variables),
2862       // Testing requests
2863       REQUEST_CALLBACK(_testGetTargetBreakpoints),
2864   };
2865 #undef REQUEST_CALLBACK
2866   return g_request_handlers;
2867 }
2868 
2869 } // anonymous namespace
2870 
2871 static void printHelp(LLDBVSCodeOptTable &table, llvm::StringRef tool_name) {
2872   std::string usage_str = tool_name.str() + " options";
2873   table.PrintHelp(llvm::outs(), usage_str.c_str(), "LLDB VSCode", false);
2874 
2875   std::string examples = R"___(
2876 EXAMPLES:
2877   The debug adapter can be started in two modes.
2878 
2879   Running lldb-vscode without any arguments will start communicating with the
2880   parent over stdio. Passing a port number causes lldb-vscode to start listening
2881   for connections on that port.
2882 
2883     lldb-vscode -p <port>
2884 
2885   Passing --wait-for-debugger will pause the process at startup and wait for a
2886   debugger to attach to the process.
2887 
2888     lldb-vscode -g
2889   )___";
2890   llvm::outs() << examples;
2891 }
2892 
2893 int main(int argc, char *argv[]) {
2894 
2895   // Initialize LLDB first before we do anything.
2896   lldb::SBDebugger::Initialize();
2897 
2898   int portno = -1;
2899 
2900   LLDBVSCodeOptTable T;
2901   unsigned MAI, MAC;
2902   llvm::ArrayRef<const char *> ArgsArr = llvm::makeArrayRef(argv + 1, argc);
2903   llvm::opt::InputArgList input_args = T.ParseArgs(ArgsArr, MAI, MAC);
2904 
2905   if (input_args.hasArg(OPT_help)) {
2906     printHelp(T, llvm::sys::path::filename(argv[0]));
2907     return 0;
2908   }
2909 
2910   if (auto *arg = input_args.getLastArg(OPT_port)) {
2911     auto optarg = arg->getValue();
2912     char *remainder;
2913     portno = strtol(optarg, &remainder, 0);
2914     if (remainder == optarg || *remainder != '\0') {
2915       fprintf(stderr, "'%s' is not a valid port number.\n", optarg);
2916       exit(1);
2917     }
2918   }
2919 
2920 #if !defined(_WIN32)
2921   if (input_args.hasArg(OPT_wait_for_debugger)) {
2922     printf("Paused waiting for debugger to attach (pid = %i)...\n", getpid());
2923     pause();
2924   }
2925 #endif
2926   if (portno != -1) {
2927     printf("Listening on port %i...\n", portno);
2928     SOCKET socket_fd = AcceptConnection(portno);
2929     if (socket_fd >= 0) {
2930       g_vsc.input.descriptor = StreamDescriptor::from_socket(socket_fd, true);
2931       g_vsc.output.descriptor = StreamDescriptor::from_socket(socket_fd, false);
2932     } else {
2933       exit(1);
2934     }
2935   } else {
2936     g_vsc.input.descriptor = StreamDescriptor::from_file(fileno(stdin), false);
2937     g_vsc.output.descriptor =
2938         StreamDescriptor::from_file(fileno(stdout), false);
2939   }
2940   auto request_handlers = GetRequestHandlers();
2941   uint32_t packet_idx = 0;
2942   while (!g_vsc.sent_terminated_event) {
2943     std::string json = g_vsc.ReadJSON();
2944     if (json.empty())
2945       break;
2946 
2947     llvm::StringRef json_sref(json);
2948     llvm::Expected<llvm::json::Value> json_value = llvm::json::parse(json_sref);
2949     if (!json_value) {
2950       auto error = json_value.takeError();
2951       if (g_vsc.log) {
2952         std::string error_str;
2953         llvm::raw_string_ostream strm(error_str);
2954         strm << error;
2955         strm.flush();
2956 
2957         *g_vsc.log << "error: failed to parse JSON: " << error_str << std::endl
2958                    << json << std::endl;
2959       }
2960       return 1;
2961     }
2962 
2963     auto object = json_value->getAsObject();
2964     if (!object) {
2965       if (g_vsc.log)
2966         *g_vsc.log << "error: json packet isn't a object" << std::endl;
2967       return 1;
2968     }
2969 
2970     const auto packet_type = GetString(object, "type");
2971     if (packet_type == "request") {
2972       const auto command = GetString(object, "command");
2973       auto handler_pos = request_handlers.find(std::string(command));
2974       if (handler_pos != request_handlers.end()) {
2975         handler_pos->second(*object);
2976       } else {
2977         if (g_vsc.log)
2978           *g_vsc.log << "error: unhandled command \"" << command.data()
2979                      << std::endl;
2980         return 1;
2981       }
2982     }
2983     ++packet_idx;
2984   }
2985 
2986   // We must terminate the debugger in a thread before the C++ destructor
2987   // chain messes everything up.
2988   lldb::SBDebugger::Terminate();
2989   return 0;
2990 }
2991