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