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