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