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