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