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