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