1 //===-- JSONUtils.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 <algorithm> 10 11 #include "llvm/ADT/Optional.h" 12 #include "llvm/Support/FormatAdapters.h" 13 #include "llvm/Support/Path.h" 14 #include "llvm/Support/ScopedPrinter.h" 15 16 #include "lldb/API/SBBreakpoint.h" 17 #include "lldb/API/SBBreakpointLocation.h" 18 #include "lldb/API/SBValue.h" 19 #include "lldb/Host/PosixApi.h" 20 21 #include "ExceptionBreakpoint.h" 22 #include "JSONUtils.h" 23 #include "LLDBUtils.h" 24 #include "VSCode.h" 25 26 namespace lldb_vscode { 27 28 void EmplaceSafeString(llvm::json::Object &obj, llvm::StringRef key, 29 llvm::StringRef str) { 30 if (LLVM_LIKELY(llvm::json::isUTF8(str))) 31 obj.try_emplace(key, str.str()); 32 else 33 obj.try_emplace(key, llvm::json::fixUTF8(str)); 34 } 35 36 llvm::StringRef GetAsString(const llvm::json::Value &value) { 37 if (auto s = value.getAsString()) 38 return *s; 39 return llvm::StringRef(); 40 } 41 42 // Gets a string from a JSON object using the key, or returns an empty string. 43 llvm::StringRef GetString(const llvm::json::Object &obj, llvm::StringRef key) { 44 if (llvm::Optional<llvm::StringRef> value = obj.getString(key)) 45 return *value; 46 return llvm::StringRef(); 47 } 48 49 llvm::StringRef GetString(const llvm::json::Object *obj, llvm::StringRef key) { 50 if (obj == nullptr) 51 return llvm::StringRef(); 52 return GetString(*obj, key); 53 } 54 55 // Gets an unsigned integer from a JSON object using the key, or returns the 56 // specified fail value. 57 uint64_t GetUnsigned(const llvm::json::Object &obj, llvm::StringRef key, 58 uint64_t fail_value) { 59 if (auto value = obj.getInteger(key)) 60 return (uint64_t)*value; 61 return fail_value; 62 } 63 64 uint64_t GetUnsigned(const llvm::json::Object *obj, llvm::StringRef key, 65 uint64_t fail_value) { 66 if (obj == nullptr) 67 return fail_value; 68 return GetUnsigned(*obj, key, fail_value); 69 } 70 71 bool GetBoolean(const llvm::json::Object &obj, llvm::StringRef key, 72 bool fail_value) { 73 if (auto value = obj.getBoolean(key)) 74 return *value; 75 if (auto value = obj.getInteger(key)) 76 return *value != 0; 77 return fail_value; 78 } 79 80 bool GetBoolean(const llvm::json::Object *obj, llvm::StringRef key, 81 bool fail_value) { 82 if (obj == nullptr) 83 return fail_value; 84 return GetBoolean(*obj, key, fail_value); 85 } 86 87 int64_t GetSigned(const llvm::json::Object &obj, llvm::StringRef key, 88 int64_t fail_value) { 89 if (auto value = obj.getInteger(key)) 90 return *value; 91 return fail_value; 92 } 93 94 int64_t GetSigned(const llvm::json::Object *obj, llvm::StringRef key, 95 int64_t fail_value) { 96 if (obj == nullptr) 97 return fail_value; 98 return GetSigned(*obj, key, fail_value); 99 } 100 101 bool ObjectContainsKey(const llvm::json::Object &obj, llvm::StringRef key) { 102 return obj.find(key) != obj.end(); 103 } 104 105 std::vector<std::string> GetStrings(const llvm::json::Object *obj, 106 llvm::StringRef key) { 107 std::vector<std::string> strs; 108 auto json_array = obj->getArray(key); 109 if (!json_array) 110 return strs; 111 for (const auto &value : *json_array) { 112 switch (value.kind()) { 113 case llvm::json::Value::String: 114 strs.push_back(value.getAsString()->str()); 115 break; 116 case llvm::json::Value::Number: 117 case llvm::json::Value::Boolean: 118 strs.push_back(llvm::to_string(value)); 119 break; 120 case llvm::json::Value::Null: 121 case llvm::json::Value::Object: 122 case llvm::json::Value::Array: 123 break; 124 } 125 } 126 return strs; 127 } 128 129 void SetValueForKey(lldb::SBValue &v, llvm::json::Object &object, 130 llvm::StringRef key) { 131 132 llvm::StringRef value = v.GetValue(); 133 llvm::StringRef summary = v.GetSummary(); 134 llvm::StringRef type_name = v.GetType().GetDisplayTypeName(); 135 136 std::string result; 137 llvm::raw_string_ostream strm(result); 138 if (!value.empty()) { 139 strm << value; 140 if (!summary.empty()) 141 strm << ' ' << summary; 142 } else if (!summary.empty()) { 143 strm << ' ' << summary; 144 } else if (!type_name.empty()) { 145 strm << type_name; 146 lldb::addr_t address = v.GetLoadAddress(); 147 if (address != LLDB_INVALID_ADDRESS) 148 strm << " @ " << llvm::format_hex(address, 0); 149 } 150 strm.flush(); 151 EmplaceSafeString(object, key, result); 152 } 153 154 void FillResponse(const llvm::json::Object &request, 155 llvm::json::Object &response) { 156 // Fill in all of the needed response fields to a "request" and set "success" 157 // to true by default. 158 response.try_emplace("type", "response"); 159 response.try_emplace("seq", (int64_t)0); 160 EmplaceSafeString(response, "command", GetString(request, "command")); 161 const int64_t seq = GetSigned(request, "seq", 0); 162 response.try_emplace("request_seq", seq); 163 response.try_emplace("success", true); 164 } 165 166 // "Scope": { 167 // "type": "object", 168 // "description": "A Scope is a named container for variables. Optionally 169 // a scope can map to a source or a range within a source.", 170 // "properties": { 171 // "name": { 172 // "type": "string", 173 // "description": "Name of the scope such as 'Arguments', 'Locals'." 174 // }, 175 // "variablesReference": { 176 // "type": "integer", 177 // "description": "The variables of this scope can be retrieved by 178 // passing the value of variablesReference to the 179 // VariablesRequest." 180 // }, 181 // "namedVariables": { 182 // "type": "integer", 183 // "description": "The number of named variables in this scope. The 184 // client can use this optional information to present 185 // the variables in a paged UI and fetch them in chunks." 186 // }, 187 // "indexedVariables": { 188 // "type": "integer", 189 // "description": "The number of indexed variables in this scope. The 190 // client can use this optional information to present 191 // the variables in a paged UI and fetch them in chunks." 192 // }, 193 // "expensive": { 194 // "type": "boolean", 195 // "description": "If true, the number of variables in this scope is 196 // large or expensive to retrieve." 197 // }, 198 // "source": { 199 // "$ref": "#/definitions/Source", 200 // "description": "Optional source for this scope." 201 // }, 202 // "line": { 203 // "type": "integer", 204 // "description": "Optional start line of the range covered by this 205 // scope." 206 // }, 207 // "column": { 208 // "type": "integer", 209 // "description": "Optional start column of the range covered by this 210 // scope." 211 // }, 212 // "endLine": { 213 // "type": "integer", 214 // "description": "Optional end line of the range covered by this scope." 215 // }, 216 // "endColumn": { 217 // "type": "integer", 218 // "description": "Optional end column of the range covered by this 219 // scope." 220 // } 221 // }, 222 // "required": [ "name", "variablesReference", "expensive" ] 223 // } 224 llvm::json::Value CreateScope(const llvm::StringRef name, 225 int64_t variablesReference, 226 int64_t namedVariables, bool expensive) { 227 llvm::json::Object object; 228 EmplaceSafeString(object, "name", name.str()); 229 object.try_emplace("variablesReference", variablesReference); 230 object.try_emplace("expensive", expensive); 231 object.try_emplace("namedVariables", namedVariables); 232 return llvm::json::Value(std::move(object)); 233 } 234 235 // "Breakpoint": { 236 // "type": "object", 237 // "description": "Information about a Breakpoint created in setBreakpoints 238 // or setFunctionBreakpoints.", 239 // "properties": { 240 // "id": { 241 // "type": "integer", 242 // "description": "An optional unique identifier for the breakpoint." 243 // }, 244 // "verified": { 245 // "type": "boolean", 246 // "description": "If true breakpoint could be set (but not necessarily 247 // at the desired location)." 248 // }, 249 // "message": { 250 // "type": "string", 251 // "description": "An optional message about the state of the breakpoint. 252 // This is shown to the user and can be used to explain 253 // why a breakpoint could not be verified." 254 // }, 255 // "source": { 256 // "$ref": "#/definitions/Source", 257 // "description": "The source where the breakpoint is located." 258 // }, 259 // "line": { 260 // "type": "integer", 261 // "description": "The start line of the actual range covered by the 262 // breakpoint." 263 // }, 264 // "column": { 265 // "type": "integer", 266 // "description": "An optional start column of the actual range covered 267 // by the breakpoint." 268 // }, 269 // "endLine": { 270 // "type": "integer", 271 // "description": "An optional end line of the actual range covered by 272 // the breakpoint." 273 // }, 274 // "endColumn": { 275 // "type": "integer", 276 // "description": "An optional end column of the actual range covered by 277 // the breakpoint. If no end line is given, then the end 278 // column is assumed to be in the start line." 279 // } 280 // }, 281 // "required": [ "verified" ] 282 // } 283 llvm::json::Value CreateBreakpoint(lldb::SBBreakpoint &bp, 284 llvm::Optional<llvm::StringRef> request_path, 285 llvm::Optional<uint32_t> request_line) { 286 // Each breakpoint location is treated as a separate breakpoint for VS code. 287 // They don't have the notion of a single breakpoint with multiple locations. 288 llvm::json::Object object; 289 if (!bp.IsValid()) 290 return llvm::json::Value(std::move(object)); 291 292 object.try_emplace("verified", bp.GetNumResolvedLocations() > 0); 293 object.try_emplace("id", bp.GetID()); 294 // VS Code DAP doesn't currently allow one breakpoint to have multiple 295 // locations so we just report the first one. If we report all locations 296 // then the IDE starts showing the wrong line numbers and locations for 297 // other source file and line breakpoints in the same file. 298 299 // Below we search for the first resolved location in a breakpoint and report 300 // this as the breakpoint location since it will have a complete location 301 // that is at least loaded in the current process. 302 lldb::SBBreakpointLocation bp_loc; 303 const auto num_locs = bp.GetNumLocations(); 304 for (size_t i = 0; i < num_locs; ++i) { 305 bp_loc = bp.GetLocationAtIndex(i); 306 if (bp_loc.IsResolved()) 307 break; 308 } 309 // If not locations are resolved, use the first location. 310 if (!bp_loc.IsResolved()) 311 bp_loc = bp.GetLocationAtIndex(0); 312 auto bp_addr = bp_loc.GetAddress(); 313 314 if (request_path) 315 object.try_emplace("source", CreateSource(*request_path)); 316 317 if (bp_addr.IsValid()) { 318 auto line_entry = bp_addr.GetLineEntry(); 319 const auto line = line_entry.GetLine(); 320 if (line != UINT32_MAX) 321 object.try_emplace("line", line); 322 object.try_emplace("source", CreateSource(line_entry)); 323 } 324 // We try to add request_line as a fallback 325 if (request_line) 326 object.try_emplace("line", *request_line); 327 return llvm::json::Value(std::move(object)); 328 } 329 330 llvm::json::Value CreateModule(lldb::SBModule &module) { 331 llvm::json::Object object; 332 if (!module.IsValid()) 333 return llvm::json::Value(std::move(object)); 334 object.try_emplace("id", std::string(module.GetUUIDString())); 335 object.try_emplace("name", std::string(module.GetFileSpec().GetFilename())); 336 char module_path_arr[PATH_MAX]; 337 module.GetFileSpec().GetPath(module_path_arr, sizeof(module_path_arr)); 338 std::string module_path(module_path_arr); 339 object.try_emplace("path", module_path); 340 if (module.GetNumCompileUnits() > 0) { 341 object.try_emplace("symbolStatus", "Symbols loaded."); 342 char symbol_path_arr[PATH_MAX]; 343 module.GetSymbolFileSpec().GetPath(symbol_path_arr, sizeof(symbol_path_arr)); 344 std::string symbol_path(symbol_path_arr); 345 object.try_emplace("symbolFilePath", symbol_path); 346 } else { 347 object.try_emplace("symbolStatus", "Symbols not found."); 348 } 349 std::string loaded_addr = std::to_string( 350 module.GetObjectFileHeaderAddress().GetLoadAddress(g_vsc.target)); 351 object.try_emplace("addressRange", loaded_addr); 352 std::string version_str; 353 uint32_t version_nums[3]; 354 uint32_t num_versions = module.GetVersion(version_nums, sizeof(version_nums)/sizeof(uint32_t)); 355 for (uint32_t i=0; i<num_versions; ++i) { 356 if (!version_str.empty()) 357 version_str += "."; 358 version_str += std::to_string(version_nums[i]); 359 } 360 if (!version_str.empty()) 361 object.try_emplace("version", version_str); 362 return llvm::json::Value(std::move(object)); 363 } 364 365 void AppendBreakpoint(lldb::SBBreakpoint &bp, llvm::json::Array &breakpoints, 366 llvm::Optional<llvm::StringRef> request_path, 367 llvm::Optional<uint32_t> request_line) { 368 breakpoints.emplace_back(CreateBreakpoint(bp, request_path, request_line)); 369 } 370 371 // "Event": { 372 // "allOf": [ { "$ref": "#/definitions/ProtocolMessage" }, { 373 // "type": "object", 374 // "description": "Server-initiated event.", 375 // "properties": { 376 // "type": { 377 // "type": "string", 378 // "enum": [ "event" ] 379 // }, 380 // "event": { 381 // "type": "string", 382 // "description": "Type of event." 383 // }, 384 // "body": { 385 // "type": [ "array", "boolean", "integer", "null", "number" , 386 // "object", "string" ], 387 // "description": "Event-specific information." 388 // } 389 // }, 390 // "required": [ "type", "event" ] 391 // }] 392 // }, 393 // "ProtocolMessage": { 394 // "type": "object", 395 // "description": "Base class of requests, responses, and events.", 396 // "properties": { 397 // "seq": { 398 // "type": "integer", 399 // "description": "Sequence number." 400 // }, 401 // "type": { 402 // "type": "string", 403 // "description": "Message type.", 404 // "_enum": [ "request", "response", "event" ] 405 // } 406 // }, 407 // "required": [ "seq", "type" ] 408 // } 409 llvm::json::Object CreateEventObject(const llvm::StringRef event_name) { 410 llvm::json::Object event; 411 event.try_emplace("seq", 0); 412 event.try_emplace("type", "event"); 413 EmplaceSafeString(event, "event", event_name); 414 return event; 415 } 416 417 // "ExceptionBreakpointsFilter": { 418 // "type": "object", 419 // "description": "An ExceptionBreakpointsFilter is shown in the UI as an 420 // option for configuring how exceptions are dealt with.", 421 // "properties": { 422 // "filter": { 423 // "type": "string", 424 // "description": "The internal ID of the filter. This value is passed 425 // to the setExceptionBreakpoints request." 426 // }, 427 // "label": { 428 // "type": "string", 429 // "description": "The name of the filter. This will be shown in the UI." 430 // }, 431 // "default": { 432 // "type": "boolean", 433 // "description": "Initial value of the filter. If not specified a value 434 // 'false' is assumed." 435 // } 436 // }, 437 // "required": [ "filter", "label" ] 438 // } 439 llvm::json::Value 440 CreateExceptionBreakpointFilter(const ExceptionBreakpoint &bp) { 441 llvm::json::Object object; 442 EmplaceSafeString(object, "filter", bp.filter); 443 EmplaceSafeString(object, "label", bp.label); 444 object.try_emplace("default", bp.default_value); 445 return llvm::json::Value(std::move(object)); 446 } 447 448 // "Source": { 449 // "type": "object", 450 // "description": "A Source is a descriptor for source code. It is returned 451 // from the debug adapter as part of a StackFrame and it is 452 // used by clients when specifying breakpoints.", 453 // "properties": { 454 // "name": { 455 // "type": "string", 456 // "description": "The short name of the source. Every source returned 457 // from the debug adapter has a name. When sending a 458 // source to the debug adapter this name is optional." 459 // }, 460 // "path": { 461 // "type": "string", 462 // "description": "The path of the source to be shown in the UI. It is 463 // only used to locate and load the content of the 464 // source if no sourceReference is specified (or its 465 // value is 0)." 466 // }, 467 // "sourceReference": { 468 // "type": "number", 469 // "description": "If sourceReference > 0 the contents of the source must 470 // be retrieved through the SourceRequest (even if a path 471 // is specified). A sourceReference is only valid for a 472 // session, so it must not be used to persist a source." 473 // }, 474 // "presentationHint": { 475 // "type": "string", 476 // "description": "An optional hint for how to present the source in the 477 // UI. A value of 'deemphasize' can be used to indicate 478 // that the source is not available or that it is 479 // skipped on stepping.", 480 // "enum": [ "normal", "emphasize", "deemphasize" ] 481 // }, 482 // "origin": { 483 // "type": "string", 484 // "description": "The (optional) origin of this source: possible values 485 // 'internal module', 'inlined content from source map', 486 // etc." 487 // }, 488 // "sources": { 489 // "type": "array", 490 // "items": { 491 // "$ref": "#/definitions/Source" 492 // }, 493 // "description": "An optional list of sources that are related to this 494 // source. These may be the source that generated this 495 // source." 496 // }, 497 // "adapterData": { 498 // "type":["array","boolean","integer","null","number","object","string"], 499 // "description": "Optional data that a debug adapter might want to loop 500 // through the client. The client should leave the data 501 // intact and persist it across sessions. The client 502 // should not interpret the data." 503 // }, 504 // "checksums": { 505 // "type": "array", 506 // "items": { 507 // "$ref": "#/definitions/Checksum" 508 // }, 509 // "description": "The checksums associated with this file." 510 // } 511 // } 512 // } 513 llvm::json::Value CreateSource(lldb::SBLineEntry &line_entry) { 514 llvm::json::Object object; 515 lldb::SBFileSpec file = line_entry.GetFileSpec(); 516 if (file.IsValid()) { 517 const char *name = file.GetFilename(); 518 if (name) 519 EmplaceSafeString(object, "name", name); 520 char path[PATH_MAX] = ""; 521 file.GetPath(path, sizeof(path)); 522 if (path[0]) { 523 EmplaceSafeString(object, "path", std::string(path)); 524 } 525 } 526 return llvm::json::Value(std::move(object)); 527 } 528 529 llvm::json::Value CreateSource(llvm::StringRef source_path) { 530 llvm::json::Object source; 531 llvm::StringRef name = llvm::sys::path::filename(source_path); 532 EmplaceSafeString(source, "name", name); 533 EmplaceSafeString(source, "path", source_path); 534 return llvm::json::Value(std::move(source)); 535 } 536 537 llvm::json::Value CreateSource(lldb::SBFrame &frame, int64_t &disasm_line) { 538 disasm_line = 0; 539 auto line_entry = frame.GetLineEntry(); 540 if (line_entry.GetFileSpec().IsValid()) 541 return CreateSource(line_entry); 542 543 llvm::json::Object object; 544 const auto pc = frame.GetPC(); 545 546 lldb::SBInstructionList insts; 547 lldb::SBFunction function = frame.GetFunction(); 548 lldb::addr_t low_pc = LLDB_INVALID_ADDRESS; 549 if (function.IsValid()) { 550 low_pc = function.GetStartAddress().GetLoadAddress(g_vsc.target); 551 auto addr_srcref = g_vsc.addr_to_source_ref.find(low_pc); 552 if (addr_srcref != g_vsc.addr_to_source_ref.end()) { 553 // We have this disassembly cached already, return the existing 554 // sourceReference 555 object.try_emplace("sourceReference", addr_srcref->second); 556 disasm_line = g_vsc.GetLineForPC(addr_srcref->second, pc); 557 } else { 558 insts = function.GetInstructions(g_vsc.target); 559 } 560 } else { 561 lldb::SBSymbol symbol = frame.GetSymbol(); 562 if (symbol.IsValid()) { 563 low_pc = symbol.GetStartAddress().GetLoadAddress(g_vsc.target); 564 auto addr_srcref = g_vsc.addr_to_source_ref.find(low_pc); 565 if (addr_srcref != g_vsc.addr_to_source_ref.end()) { 566 // We have this disassembly cached already, return the existing 567 // sourceReference 568 object.try_emplace("sourceReference", addr_srcref->second); 569 disasm_line = g_vsc.GetLineForPC(addr_srcref->second, pc); 570 } else { 571 insts = symbol.GetInstructions(g_vsc.target); 572 } 573 } 574 } 575 const auto num_insts = insts.GetSize(); 576 if (low_pc != LLDB_INVALID_ADDRESS && num_insts > 0) { 577 EmplaceSafeString(object, "name", frame.GetFunctionName()); 578 SourceReference source; 579 llvm::raw_string_ostream src_strm(source.content); 580 std::string line; 581 for (size_t i = 0; i < num_insts; ++i) { 582 lldb::SBInstruction inst = insts.GetInstructionAtIndex(i); 583 const auto inst_addr = inst.GetAddress().GetLoadAddress(g_vsc.target); 584 const char *m = inst.GetMnemonic(g_vsc.target); 585 const char *o = inst.GetOperands(g_vsc.target); 586 const char *c = inst.GetComment(g_vsc.target); 587 if (pc == inst_addr) 588 disasm_line = i + 1; 589 const auto inst_offset = inst_addr - low_pc; 590 int spaces = 0; 591 if (inst_offset < 10) 592 spaces = 3; 593 else if (inst_offset < 100) 594 spaces = 2; 595 else if (inst_offset < 1000) 596 spaces = 1; 597 line.clear(); 598 llvm::raw_string_ostream line_strm(line); 599 line_strm << llvm::formatv("{0:X+}: <{1}> {2} {3,12} {4}", inst_addr, 600 inst_offset, llvm::fmt_repeat(' ', spaces), m, 601 o); 602 603 // If there is a comment append it starting at column 60 or after one 604 // space past the last char 605 const uint32_t comment_row = std::max(line_strm.str().size(), (size_t)60); 606 if (c && c[0]) { 607 if (line.size() < comment_row) 608 line_strm.indent(comment_row - line_strm.str().size()); 609 line_strm << " # " << c; 610 } 611 src_strm << line_strm.str() << "\n"; 612 source.addr_to_line[inst_addr] = i + 1; 613 } 614 // Flush the source stream 615 src_strm.str(); 616 auto sourceReference = VSCode::GetNextSourceReference(); 617 g_vsc.source_map[sourceReference] = std::move(source); 618 g_vsc.addr_to_source_ref[low_pc] = sourceReference; 619 object.try_emplace("sourceReference", sourceReference); 620 } 621 return llvm::json::Value(std::move(object)); 622 } 623 624 // "StackFrame": { 625 // "type": "object", 626 // "description": "A Stackframe contains the source location.", 627 // "properties": { 628 // "id": { 629 // "type": "integer", 630 // "description": "An identifier for the stack frame. It must be unique 631 // across all threads. This id can be used to retrieve 632 // the scopes of the frame with the 'scopesRequest' or 633 // to restart the execution of a stackframe." 634 // }, 635 // "name": { 636 // "type": "string", 637 // "description": "The name of the stack frame, typically a method name." 638 // }, 639 // "source": { 640 // "$ref": "#/definitions/Source", 641 // "description": "The optional source of the frame." 642 // }, 643 // "line": { 644 // "type": "integer", 645 // "description": "The line within the file of the frame. If source is 646 // null or doesn't exist, line is 0 and must be ignored." 647 // }, 648 // "column": { 649 // "type": "integer", 650 // "description": "The column within the line. If source is null or 651 // doesn't exist, column is 0 and must be ignored." 652 // }, 653 // "endLine": { 654 // "type": "integer", 655 // "description": "An optional end line of the range covered by the 656 // stack frame." 657 // }, 658 // "endColumn": { 659 // "type": "integer", 660 // "description": "An optional end column of the range covered by the 661 // stack frame." 662 // }, 663 // "moduleId": { 664 // "type": ["integer", "string"], 665 // "description": "The module associated with this frame, if any." 666 // }, 667 // "presentationHint": { 668 // "type": "string", 669 // "enum": [ "normal", "label", "subtle" ], 670 // "description": "An optional hint for how to present this frame in 671 // the UI. A value of 'label' can be used to indicate 672 // that the frame is an artificial frame that is used 673 // as a visual label or separator. A value of 'subtle' 674 // can be used to change the appearance of a frame in 675 // a 'subtle' way." 676 // } 677 // }, 678 // "required": [ "id", "name", "line", "column" ] 679 // } 680 llvm::json::Value CreateStackFrame(lldb::SBFrame &frame) { 681 llvm::json::Object object; 682 int64_t frame_id = MakeVSCodeFrameID(frame); 683 object.try_emplace("id", frame_id); 684 EmplaceSafeString(object, "name", frame.GetFunctionName()); 685 int64_t disasm_line = 0; 686 object.try_emplace("source", CreateSource(frame, disasm_line)); 687 688 auto line_entry = frame.GetLineEntry(); 689 if (disasm_line > 0) { 690 object.try_emplace("line", disasm_line); 691 } else { 692 auto line = line_entry.GetLine(); 693 if (line == UINT32_MAX) 694 line = 0; 695 object.try_emplace("line", line); 696 } 697 object.try_emplace("column", line_entry.GetColumn()); 698 return llvm::json::Value(std::move(object)); 699 } 700 701 // "Thread": { 702 // "type": "object", 703 // "description": "A Thread", 704 // "properties": { 705 // "id": { 706 // "type": "integer", 707 // "description": "Unique identifier for the thread." 708 // }, 709 // "name": { 710 // "type": "string", 711 // "description": "A name of the thread." 712 // } 713 // }, 714 // "required": [ "id", "name" ] 715 // } 716 llvm::json::Value CreateThread(lldb::SBThread &thread) { 717 llvm::json::Object object; 718 object.try_emplace("id", (int64_t)thread.GetThreadID()); 719 char thread_str[64]; 720 snprintf(thread_str, sizeof(thread_str), "Thread #%u", thread.GetIndexID()); 721 const char *name = thread.GetName(); 722 if (name) { 723 std::string thread_with_name(thread_str); 724 thread_with_name += ' '; 725 thread_with_name += name; 726 EmplaceSafeString(object, "name", thread_with_name); 727 } else { 728 EmplaceSafeString(object, "name", std::string(thread_str)); 729 } 730 return llvm::json::Value(std::move(object)); 731 } 732 733 // "StoppedEvent": { 734 // "allOf": [ { "$ref": "#/definitions/Event" }, { 735 // "type": "object", 736 // "description": "Event message for 'stopped' event type. The event 737 // indicates that the execution of the debuggee has stopped 738 // due to some condition. This can be caused by a break 739 // point previously set, a stepping action has completed, 740 // by executing a debugger statement etc.", 741 // "properties": { 742 // "event": { 743 // "type": "string", 744 // "enum": [ "stopped" ] 745 // }, 746 // "body": { 747 // "type": "object", 748 // "properties": { 749 // "reason": { 750 // "type": "string", 751 // "description": "The reason for the event. For backward 752 // compatibility this string is shown in the UI if 753 // the 'description' attribute is missing (but it 754 // must not be translated).", 755 // "_enum": [ "step", "breakpoint", "exception", "pause", "entry" ] 756 // }, 757 // "description": { 758 // "type": "string", 759 // "description": "The full reason for the event, e.g. 'Paused 760 // on exception'. This string is shown in the UI 761 // as is." 762 // }, 763 // "threadId": { 764 // "type": "integer", 765 // "description": "The thread which was stopped." 766 // }, 767 // "text": { 768 // "type": "string", 769 // "description": "Additional information. E.g. if reason is 770 // 'exception', text contains the exception name. 771 // This string is shown in the UI." 772 // }, 773 // "allThreadsStopped": { 774 // "type": "boolean", 775 // "description": "If allThreadsStopped is true, a debug adapter 776 // can announce that all threads have stopped. 777 // The client should use this information to 778 // enable that all threads can be expanded to 779 // access their stacktraces. If the attribute 780 // is missing or false, only the thread with the 781 // given threadId can be expanded." 782 // } 783 // }, 784 // "required": [ "reason" ] 785 // } 786 // }, 787 // "required": [ "event", "body" ] 788 // }] 789 // } 790 llvm::json::Value CreateThreadStopped(lldb::SBThread &thread, 791 uint32_t stop_id) { 792 llvm::json::Object event(CreateEventObject("stopped")); 793 llvm::json::Object body; 794 switch (thread.GetStopReason()) { 795 case lldb::eStopReasonTrace: 796 case lldb::eStopReasonPlanComplete: 797 body.try_emplace("reason", "step"); 798 break; 799 case lldb::eStopReasonBreakpoint: { 800 ExceptionBreakpoint *exc_bp = g_vsc.GetExceptionBPFromStopReason(thread); 801 if (exc_bp) { 802 body.try_emplace("reason", "exception"); 803 EmplaceSafeString(body, "description", exc_bp->label); 804 } else { 805 body.try_emplace("reason", "breakpoint"); 806 char desc_str[64]; 807 uint64_t bp_id = thread.GetStopReasonDataAtIndex(0); 808 uint64_t bp_loc_id = thread.GetStopReasonDataAtIndex(1); 809 snprintf(desc_str, sizeof(desc_str), "breakpoint %" PRIu64 ".%" PRIu64, 810 bp_id, bp_loc_id); 811 EmplaceSafeString(body, "description", desc_str); 812 } 813 } break; 814 case lldb::eStopReasonWatchpoint: 815 case lldb::eStopReasonInstrumentation: 816 body.try_emplace("reason", "breakpoint"); 817 break; 818 case lldb::eStopReasonSignal: 819 body.try_emplace("reason", "exception"); 820 break; 821 case lldb::eStopReasonException: 822 body.try_emplace("reason", "exception"); 823 break; 824 case lldb::eStopReasonExec: 825 body.try_emplace("reason", "entry"); 826 break; 827 case lldb::eStopReasonThreadExiting: 828 case lldb::eStopReasonInvalid: 829 case lldb::eStopReasonNone: 830 break; 831 } 832 if (stop_id == 0) 833 body.try_emplace("reason", "entry"); 834 const lldb::tid_t tid = thread.GetThreadID(); 835 body.try_emplace("threadId", (int64_t)tid); 836 // If no description has been set, then set it to the default thread stopped 837 // description. If we have breakpoints that get hit and shouldn't be reported 838 // as breakpoints, then they will set the description above. 839 if (ObjectContainsKey(body, "description")) { 840 char description[1024]; 841 if (thread.GetStopDescription(description, sizeof(description))) { 842 EmplaceSafeString(body, "description", std::string(description)); 843 } 844 } 845 if (tid == g_vsc.focus_tid) { 846 body.try_emplace("threadCausedFocus", true); 847 } 848 body.try_emplace("preserveFocusHint", tid != g_vsc.focus_tid); 849 body.try_emplace("allThreadsStopped", true); 850 event.try_emplace("body", std::move(body)); 851 return llvm::json::Value(std::move(event)); 852 } 853 854 // "Variable": { 855 // "type": "object", 856 // "description": "A Variable is a name/value pair. Optionally a variable 857 // can have a 'type' that is shown if space permits or when 858 // hovering over the variable's name. An optional 'kind' is 859 // used to render additional properties of the variable, 860 // e.g. different icons can be used to indicate that a 861 // variable is public or private. If the value is 862 // structured (has children), a handle is provided to 863 // retrieve the children with the VariablesRequest. If 864 // the number of named or indexed children is large, the 865 // numbers should be returned via the optional 866 // 'namedVariables' and 'indexedVariables' attributes. The 867 // client can use this optional information to present the 868 // children in a paged UI and fetch them in chunks.", 869 // "properties": { 870 // "name": { 871 // "type": "string", 872 // "description": "The variable's name." 873 // }, 874 // "value": { 875 // "type": "string", 876 // "description": "The variable's value. This can be a multi-line text, 877 // e.g. for a function the body of a function." 878 // }, 879 // "type": { 880 // "type": "string", 881 // "description": "The type of the variable's value. Typically shown in 882 // the UI when hovering over the value." 883 // }, 884 // "presentationHint": { 885 // "$ref": "#/definitions/VariablePresentationHint", 886 // "description": "Properties of a variable that can be used to determine 887 // how to render the variable in the UI." 888 // }, 889 // "evaluateName": { 890 // "type": "string", 891 // "description": "Optional evaluatable name of this variable which can 892 // be passed to the 'EvaluateRequest' to fetch the 893 // variable's value." 894 // }, 895 // "variablesReference": { 896 // "type": "integer", 897 // "description": "If variablesReference is > 0, the variable is 898 // structured and its children can be retrieved by 899 // passing variablesReference to the VariablesRequest." 900 // }, 901 // "namedVariables": { 902 // "type": "integer", 903 // "description": "The number of named child variables. The client can 904 // use this optional information to present the children 905 // in a paged UI and fetch them in chunks." 906 // }, 907 // "indexedVariables": { 908 // "type": "integer", 909 // "description": "The number of indexed child variables. The client 910 // can use this optional information to present the 911 // children in a paged UI and fetch them in chunks." 912 // } 913 // }, 914 // "required": [ "name", "value", "variablesReference" ] 915 // } 916 llvm::json::Value CreateVariable(lldb::SBValue v, int64_t variablesReference, 917 int64_t varID, bool format_hex) { 918 llvm::json::Object object; 919 auto name = v.GetName(); 920 EmplaceSafeString(object, "name", name ? name : "<null>"); 921 if (format_hex) 922 v.SetFormat(lldb::eFormatHex); 923 SetValueForKey(v, object, "value"); 924 auto type_cstr = v.GetType().GetDisplayTypeName(); 925 EmplaceSafeString(object, "type", type_cstr ? type_cstr : NO_TYPENAME); 926 if (varID != INT64_MAX) 927 object.try_emplace("id", varID); 928 if (v.MightHaveChildren()) 929 object.try_emplace("variablesReference", variablesReference); 930 else 931 object.try_emplace("variablesReference", (int64_t)0); 932 lldb::SBStream evaluateStream; 933 v.GetExpressionPath(evaluateStream); 934 const char *evaluateName = evaluateStream.GetData(); 935 if (evaluateName && evaluateName[0]) 936 EmplaceSafeString(object, "evaluateName", std::string(evaluateName)); 937 return llvm::json::Value(std::move(object)); 938 } 939 940 llvm::json::Value CreateCompileUnit(lldb::SBCompileUnit unit) { 941 llvm::json::Object object; 942 char unit_path_arr[PATH_MAX]; 943 unit.GetFileSpec().GetPath(unit_path_arr, sizeof(unit_path_arr)); 944 std::string unit_path(unit_path_arr); 945 object.try_emplace("compileUnitPath", unit_path); 946 return llvm::json::Value(std::move(object)); 947 } 948 949 } // namespace lldb_vscode 950