1 //===-- CommandObjectReproducer.cpp ---------------------------------------===// 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 "CommandObjectReproducer.h" 10 11 #include "lldb/Host/HostInfo.h" 12 #include "lldb/Host/OptionParser.h" 13 #include "lldb/Interpreter/CommandInterpreter.h" 14 #include "lldb/Interpreter/CommandReturnObject.h" 15 #include "lldb/Interpreter/OptionArgParser.h" 16 #include "lldb/Utility/GDBRemote.h" 17 #include "lldb/Utility/ProcessInfo.h" 18 #include "lldb/Utility/Reproducer.h" 19 20 #include <csignal> 21 22 using namespace lldb; 23 using namespace llvm; 24 using namespace lldb_private; 25 using namespace lldb_private::repro; 26 27 enum ReproducerProvider { 28 eReproducerProviderCommands, 29 eReproducerProviderFiles, 30 eReproducerProviderSymbolFiles, 31 eReproducerProviderGDB, 32 eReproducerProviderProcessInfo, 33 eReproducerProviderVersion, 34 eReproducerProviderWorkingDirectory, 35 eReproducerProviderHomeDirectory, 36 eReproducerProviderNone 37 }; 38 39 static constexpr OptionEnumValueElement g_reproducer_provider_type[] = { 40 { 41 eReproducerProviderCommands, 42 "commands", 43 "Command Interpreter Commands", 44 }, 45 { 46 eReproducerProviderFiles, 47 "files", 48 "Files", 49 }, 50 { 51 eReproducerProviderSymbolFiles, 52 "symbol-files", 53 "Symbol Files", 54 }, 55 { 56 eReproducerProviderGDB, 57 "gdb", 58 "GDB Remote Packets", 59 }, 60 { 61 eReproducerProviderProcessInfo, 62 "processes", 63 "Process Info", 64 }, 65 { 66 eReproducerProviderVersion, 67 "version", 68 "Version", 69 }, 70 { 71 eReproducerProviderWorkingDirectory, 72 "cwd", 73 "Working Directory", 74 }, 75 { 76 eReproducerProviderHomeDirectory, 77 "home", 78 "Home Directory", 79 }, 80 { 81 eReproducerProviderNone, 82 "none", 83 "None", 84 }, 85 }; 86 87 static constexpr OptionEnumValues ReproducerProviderType() { 88 return OptionEnumValues(g_reproducer_provider_type); 89 } 90 91 #define LLDB_OPTIONS_reproducer_dump 92 #include "CommandOptions.inc" 93 94 enum ReproducerCrashSignal { 95 eReproducerCrashSigill, 96 eReproducerCrashSigsegv, 97 }; 98 99 static constexpr OptionEnumValueElement g_reproducer_signaltype[] = { 100 { 101 eReproducerCrashSigill, 102 "SIGILL", 103 "Illegal instruction", 104 }, 105 { 106 eReproducerCrashSigsegv, 107 "SIGSEGV", 108 "Segmentation fault", 109 }, 110 }; 111 112 static constexpr OptionEnumValues ReproducerSignalType() { 113 return OptionEnumValues(g_reproducer_signaltype); 114 } 115 116 #define LLDB_OPTIONS_reproducer_xcrash 117 #include "CommandOptions.inc" 118 119 #define LLDB_OPTIONS_reproducer_verify 120 #include "CommandOptions.inc" 121 122 template <typename T> 123 llvm::Expected<T> static ReadFromYAML(StringRef filename) { 124 auto error_or_file = MemoryBuffer::getFile(filename); 125 if (auto err = error_or_file.getError()) { 126 return errorCodeToError(err); 127 } 128 129 T t; 130 yaml::Input yin((*error_or_file)->getBuffer()); 131 yin >> t; 132 133 if (auto err = yin.error()) { 134 return errorCodeToError(err); 135 } 136 137 return t; 138 } 139 140 static void SetError(CommandReturnObject &result, Error err) { 141 result.AppendError(toString(std::move(err))); 142 } 143 144 /// Create a loader from the given path if specified. Otherwise use the current 145 /// loader used for replay. 146 static Loader * 147 GetLoaderFromPathOrCurrent(llvm::Optional<Loader> &loader_storage, 148 CommandReturnObject &result, 149 FileSpec reproducer_path) { 150 if (reproducer_path) { 151 loader_storage.emplace(reproducer_path); 152 Loader *loader = &(*loader_storage); 153 if (Error err = loader->LoadIndex()) { 154 // This is a hard error and will set the result to eReturnStatusFailed. 155 SetError(result, std::move(err)); 156 return nullptr; 157 } 158 return loader; 159 } 160 161 if (Loader *loader = Reproducer::Instance().GetLoader()) 162 return loader; 163 164 // This is a soft error because this is expected to fail during capture. 165 result.AppendError( 166 "Not specifying a reproducer is only support during replay."); 167 result.SetStatus(eReturnStatusSuccessFinishNoResult); 168 return nullptr; 169 } 170 171 class CommandObjectReproducerGenerate : public CommandObjectParsed { 172 public: 173 CommandObjectReproducerGenerate(CommandInterpreter &interpreter) 174 : CommandObjectParsed( 175 interpreter, "reproducer generate", 176 "Generate reproducer on disk. When the debugger is in capture " 177 "mode, this command will output the reproducer to a directory on " 178 "disk and quit. In replay mode this command in a no-op.", 179 nullptr) {} 180 181 ~CommandObjectReproducerGenerate() override = default; 182 183 protected: 184 bool DoExecute(Args &command, CommandReturnObject &result) override { 185 if (!command.empty()) { 186 result.AppendErrorWithFormat("'%s' takes no arguments", 187 m_cmd_name.c_str()); 188 return false; 189 } 190 191 auto &r = Reproducer::Instance(); 192 if (auto generator = r.GetGenerator()) { 193 generator->Keep(); 194 } else { 195 result.AppendErrorWithFormat("Unable to get the reproducer generator"); 196 return false; 197 } 198 199 result.GetOutputStream() 200 << "Reproducer written to '" << r.GetReproducerPath() << "'\n"; 201 result.GetOutputStream() 202 << "Please have a look at the directory to assess if you're willing to " 203 "share the contained information.\n"; 204 205 m_interpreter.BroadcastEvent( 206 CommandInterpreter::eBroadcastBitQuitCommandReceived); 207 result.SetStatus(eReturnStatusQuit); 208 return result.Succeeded(); 209 } 210 }; 211 212 class CommandObjectReproducerXCrash : public CommandObjectParsed { 213 public: 214 CommandObjectReproducerXCrash(CommandInterpreter &interpreter) 215 : CommandObjectParsed(interpreter, "reproducer xcrash", 216 "Intentionally force the debugger to crash in " 217 "order to trigger and test reproducer generation.", 218 nullptr) {} 219 220 ~CommandObjectReproducerXCrash() override = default; 221 222 Options *GetOptions() override { return &m_options; } 223 224 class CommandOptions : public Options { 225 public: 226 CommandOptions() = default; 227 228 ~CommandOptions() override = default; 229 230 Status SetOptionValue(uint32_t option_idx, StringRef option_arg, 231 ExecutionContext *execution_context) override { 232 Status error; 233 const int short_option = m_getopt_table[option_idx].val; 234 235 switch (short_option) { 236 case 's': 237 signal = (ReproducerCrashSignal)OptionArgParser::ToOptionEnum( 238 option_arg, GetDefinitions()[option_idx].enum_values, 0, error); 239 if (!error.Success()) 240 error.SetErrorStringWithFormat("unrecognized value for signal '%s'", 241 option_arg.str().c_str()); 242 break; 243 default: 244 llvm_unreachable("Unimplemented option"); 245 } 246 247 return error; 248 } 249 250 void OptionParsingStarting(ExecutionContext *execution_context) override { 251 signal = eReproducerCrashSigsegv; 252 } 253 254 ArrayRef<OptionDefinition> GetDefinitions() override { 255 return makeArrayRef(g_reproducer_xcrash_options); 256 } 257 258 ReproducerCrashSignal signal = eReproducerCrashSigsegv; 259 }; 260 261 protected: 262 bool DoExecute(Args &command, CommandReturnObject &result) override { 263 if (!command.empty()) { 264 result.AppendErrorWithFormat("'%s' takes no arguments", 265 m_cmd_name.c_str()); 266 return false; 267 } 268 269 auto &r = Reproducer::Instance(); 270 271 if (!r.IsCapturing()) { 272 result.AppendError( 273 "forcing a crash is only supported when capturing a reproducer."); 274 result.SetStatus(eReturnStatusSuccessFinishNoResult); 275 return false; 276 } 277 278 switch (m_options.signal) { 279 case eReproducerCrashSigill: 280 std::raise(SIGILL); 281 break; 282 case eReproducerCrashSigsegv: 283 std::raise(SIGSEGV); 284 break; 285 } 286 287 result.SetStatus(eReturnStatusQuit); 288 return result.Succeeded(); 289 } 290 291 private: 292 CommandOptions m_options; 293 }; 294 295 class CommandObjectReproducerStatus : public CommandObjectParsed { 296 public: 297 CommandObjectReproducerStatus(CommandInterpreter &interpreter) 298 : CommandObjectParsed( 299 interpreter, "reproducer status", 300 "Show the current reproducer status. In capture mode the " 301 "debugger " 302 "is collecting all the information it needs to create a " 303 "reproducer. In replay mode the reproducer is replaying a " 304 "reproducer. When the reproducers are off, no data is collected " 305 "and no reproducer can be generated.", 306 nullptr) {} 307 308 ~CommandObjectReproducerStatus() override = default; 309 310 protected: 311 bool DoExecute(Args &command, CommandReturnObject &result) override { 312 if (!command.empty()) { 313 result.AppendErrorWithFormat("'%s' takes no arguments", 314 m_cmd_name.c_str()); 315 return false; 316 } 317 318 auto &r = Reproducer::Instance(); 319 if (r.IsCapturing()) { 320 result.GetOutputStream() << "Reproducer is in capture mode.\n"; 321 result.GetOutputStream() 322 << "Path: " << r.GetReproducerPath().GetPath() << '\n'; 323 } else { 324 result.GetOutputStream() << "Reproducer is off.\n"; 325 } 326 327 // Auto generate is hidden unless enabled because this is mostly for 328 // development and testing. 329 if (Generator *g = r.GetGenerator()) { 330 if (g->IsAutoGenerate()) 331 result.GetOutputStream() << "Auto generate: on\n"; 332 } 333 334 result.SetStatus(eReturnStatusSuccessFinishResult); 335 return result.Succeeded(); 336 } 337 }; 338 339 class CommandObjectReproducerDump : public CommandObjectParsed { 340 public: 341 CommandObjectReproducerDump(CommandInterpreter &interpreter) 342 : CommandObjectParsed(interpreter, "reproducer dump", 343 "Dump the information contained in a reproducer. " 344 "If no reproducer is specified during replay, it " 345 "dumps the content of the current reproducer.", 346 nullptr) {} 347 348 ~CommandObjectReproducerDump() override = default; 349 350 Options *GetOptions() override { return &m_options; } 351 352 class CommandOptions : public Options { 353 public: 354 CommandOptions() = default; 355 356 ~CommandOptions() override = default; 357 358 Status SetOptionValue(uint32_t option_idx, StringRef option_arg, 359 ExecutionContext *execution_context) override { 360 Status error; 361 const int short_option = m_getopt_table[option_idx].val; 362 363 switch (short_option) { 364 case 'f': 365 file.SetFile(option_arg, FileSpec::Style::native); 366 FileSystem::Instance().Resolve(file); 367 break; 368 case 'p': 369 provider = (ReproducerProvider)OptionArgParser::ToOptionEnum( 370 option_arg, GetDefinitions()[option_idx].enum_values, 0, error); 371 if (!error.Success()) 372 error.SetErrorStringWithFormat("unrecognized value for provider '%s'", 373 option_arg.str().c_str()); 374 break; 375 default: 376 llvm_unreachable("Unimplemented option"); 377 } 378 379 return error; 380 } 381 382 void OptionParsingStarting(ExecutionContext *execution_context) override { 383 file.Clear(); 384 provider = eReproducerProviderNone; 385 } 386 387 ArrayRef<OptionDefinition> GetDefinitions() override { 388 return makeArrayRef(g_reproducer_dump_options); 389 } 390 391 FileSpec file; 392 ReproducerProvider provider = eReproducerProviderNone; 393 }; 394 395 protected: 396 bool DoExecute(Args &command, CommandReturnObject &result) override { 397 if (!command.empty()) { 398 result.AppendErrorWithFormat("'%s' takes no arguments", 399 m_cmd_name.c_str()); 400 return false; 401 } 402 403 llvm::Optional<Loader> loader_storage; 404 Loader *loader = 405 GetLoaderFromPathOrCurrent(loader_storage, result, m_options.file); 406 if (!loader) 407 return false; 408 409 switch (m_options.provider) { 410 case eReproducerProviderFiles: { 411 FileSpec vfs_mapping = loader->GetFile<FileProvider::Info>(); 412 413 // Read the VFS mapping. 414 ErrorOr<std::unique_ptr<MemoryBuffer>> buffer = 415 vfs::getRealFileSystem()->getBufferForFile(vfs_mapping.GetPath()); 416 if (!buffer) { 417 SetError(result, errorCodeToError(buffer.getError())); 418 return false; 419 } 420 421 // Initialize a VFS from the given mapping. 422 IntrusiveRefCntPtr<vfs::FileSystem> vfs = vfs::getVFSFromYAML( 423 std::move(buffer.get()), nullptr, vfs_mapping.GetPath()); 424 425 // Dump the VFS to a buffer. 426 std::string str; 427 raw_string_ostream os(str); 428 static_cast<vfs::RedirectingFileSystem &>(*vfs).print(os); 429 os.flush(); 430 431 // Return the string. 432 result.AppendMessage(str); 433 result.SetStatus(eReturnStatusSuccessFinishResult); 434 return true; 435 } 436 case eReproducerProviderSymbolFiles: { 437 Expected<std::string> symbol_files = 438 loader->LoadBuffer<SymbolFileProvider>(); 439 if (!symbol_files) { 440 SetError(result, symbol_files.takeError()); 441 return false; 442 } 443 444 std::vector<SymbolFileProvider::Entry> entries; 445 llvm::yaml::Input yin(*symbol_files); 446 yin >> entries; 447 448 for (const auto &entry : entries) { 449 result.AppendMessageWithFormat("- uuid: %s\n", 450 entry.uuid.c_str()); 451 result.AppendMessageWithFormat(" module path: %s\n", 452 entry.module_path.c_str()); 453 result.AppendMessageWithFormat(" symbol path: %s\n", 454 entry.symbol_path.c_str()); 455 } 456 result.SetStatus(eReturnStatusSuccessFinishResult); 457 return true; 458 } 459 case eReproducerProviderVersion: { 460 Expected<std::string> version = loader->LoadBuffer<VersionProvider>(); 461 if (!version) { 462 SetError(result, version.takeError()); 463 return false; 464 } 465 result.AppendMessage(*version); 466 result.SetStatus(eReturnStatusSuccessFinishResult); 467 return true; 468 } 469 case eReproducerProviderWorkingDirectory: { 470 Expected<std::string> cwd = 471 repro::GetDirectoryFrom<WorkingDirectoryProvider>(loader); 472 if (!cwd) { 473 SetError(result, cwd.takeError()); 474 return false; 475 } 476 result.AppendMessage(*cwd); 477 result.SetStatus(eReturnStatusSuccessFinishResult); 478 return true; 479 } 480 case eReproducerProviderHomeDirectory: { 481 Expected<std::string> home = 482 repro::GetDirectoryFrom<HomeDirectoryProvider>(loader); 483 if (!home) { 484 SetError(result, home.takeError()); 485 return false; 486 } 487 result.AppendMessage(*home); 488 result.SetStatus(eReturnStatusSuccessFinishResult); 489 return true; 490 } 491 case eReproducerProviderCommands: { 492 std::unique_ptr<repro::MultiLoader<repro::CommandProvider>> multi_loader = 493 repro::MultiLoader<repro::CommandProvider>::Create(loader); 494 if (!multi_loader) { 495 SetError(result, 496 make_error<StringError>("Unable to create command loader.", 497 llvm::inconvertibleErrorCode())); 498 return false; 499 } 500 501 // Iterate over the command files and dump them. 502 llvm::Optional<std::string> command_file; 503 while ((command_file = multi_loader->GetNextFile())) { 504 if (!command_file) 505 break; 506 507 auto command_buffer = llvm::MemoryBuffer::getFile(*command_file); 508 if (auto err = command_buffer.getError()) { 509 SetError(result, errorCodeToError(err)); 510 return false; 511 } 512 result.AppendMessage((*command_buffer)->getBuffer()); 513 } 514 515 result.SetStatus(eReturnStatusSuccessFinishResult); 516 return true; 517 } 518 case eReproducerProviderGDB: { 519 std::unique_ptr<repro::MultiLoader<repro::GDBRemoteProvider>> 520 multi_loader = 521 repro::MultiLoader<repro::GDBRemoteProvider>::Create(loader); 522 523 if (!multi_loader) { 524 SetError(result, 525 make_error<StringError>("Unable to create GDB loader.", 526 llvm::inconvertibleErrorCode())); 527 return false; 528 } 529 530 llvm::Optional<std::string> gdb_file; 531 while ((gdb_file = multi_loader->GetNextFile())) { 532 if (llvm::Expected<std::vector<GDBRemotePacket>> packets = 533 ReadFromYAML<std::vector<GDBRemotePacket>>(*gdb_file)) { 534 for (GDBRemotePacket &packet : *packets) { 535 packet.Dump(result.GetOutputStream()); 536 } 537 } else { 538 SetError(result, packets.takeError()); 539 return false; 540 } 541 } 542 543 result.SetStatus(eReturnStatusSuccessFinishResult); 544 return true; 545 } 546 case eReproducerProviderProcessInfo: { 547 std::unique_ptr<repro::MultiLoader<repro::ProcessInfoProvider>> 548 multi_loader = 549 repro::MultiLoader<repro::ProcessInfoProvider>::Create(loader); 550 551 if (!multi_loader) { 552 SetError(result, make_error<StringError>( 553 llvm::inconvertibleErrorCode(), 554 "Unable to create process info loader.")); 555 return false; 556 } 557 558 llvm::Optional<std::string> process_file; 559 while ((process_file = multi_loader->GetNextFile())) { 560 if (llvm::Expected<ProcessInstanceInfoList> infos = 561 ReadFromYAML<ProcessInstanceInfoList>(*process_file)) { 562 for (ProcessInstanceInfo info : *infos) 563 info.Dump(result.GetOutputStream(), HostInfo::GetUserIDResolver()); 564 } else { 565 SetError(result, infos.takeError()); 566 return false; 567 } 568 } 569 570 result.SetStatus(eReturnStatusSuccessFinishResult); 571 return true; 572 } 573 case eReproducerProviderNone: 574 result.AppendError("No valid provider specified."); 575 return false; 576 } 577 578 result.SetStatus(eReturnStatusSuccessFinishNoResult); 579 return result.Succeeded(); 580 } 581 582 private: 583 CommandOptions m_options; 584 }; 585 586 CommandObjectReproducer::CommandObjectReproducer( 587 CommandInterpreter &interpreter) 588 : CommandObjectMultiword( 589 interpreter, "reproducer", 590 "Commands for manipulating reproducers. Reproducers make it " 591 "possible " 592 "to capture full debug sessions with all its dependencies. The " 593 "resulting reproducer is used to replay the debug session while " 594 "debugging the debugger.\n" 595 "Because reproducers need the whole the debug session from " 596 "beginning to end, you need to launch the debugger in capture or " 597 "replay mode, commonly though the command line driver.\n" 598 "Reproducers are unrelated record-replay debugging, as you cannot " 599 "interact with the debugger during replay.\n", 600 "reproducer <subcommand> [<subcommand-options>]") { 601 LoadSubCommand( 602 "generate", 603 CommandObjectSP(new CommandObjectReproducerGenerate(interpreter))); 604 LoadSubCommand("status", CommandObjectSP( 605 new CommandObjectReproducerStatus(interpreter))); 606 LoadSubCommand("dump", 607 CommandObjectSP(new CommandObjectReproducerDump(interpreter))); 608 LoadSubCommand("xcrash", CommandObjectSP( 609 new CommandObjectReproducerXCrash(interpreter))); 610 } 611 612 CommandObjectReproducer::~CommandObjectReproducer() = default; 613