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