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