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