1 //===-- CommandObjectProcess.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 "CommandObjectProcess.h" 10 #include "CommandObjectTrace.h" 11 #include "CommandOptionsProcessLaunch.h" 12 #include "lldb/Breakpoint/Breakpoint.h" 13 #include "lldb/Breakpoint/BreakpointLocation.h" 14 #include "lldb/Breakpoint/BreakpointSite.h" 15 #include "lldb/Core/Module.h" 16 #include "lldb/Core/PluginManager.h" 17 #include "lldb/Host/OptionParser.h" 18 #include "lldb/Interpreter/CommandInterpreter.h" 19 #include "lldb/Interpreter/CommandReturnObject.h" 20 #include "lldb/Interpreter/OptionArgParser.h" 21 #include "lldb/Interpreter/OptionGroupPythonClassWithDict.h" 22 #include "lldb/Interpreter/Options.h" 23 #include "lldb/Target/Platform.h" 24 #include "lldb/Target/Process.h" 25 #include "lldb/Target/StopInfo.h" 26 #include "lldb/Target/Target.h" 27 #include "lldb/Target/Thread.h" 28 #include "lldb/Target/UnixSignals.h" 29 #include "lldb/Utility/Args.h" 30 #include "lldb/Utility/State.h" 31 32 #include <bitset> 33 34 using namespace lldb; 35 using namespace lldb_private; 36 37 class CommandObjectProcessLaunchOrAttach : public CommandObjectParsed { 38 public: 39 CommandObjectProcessLaunchOrAttach(CommandInterpreter &interpreter, 40 const char *name, const char *help, 41 const char *syntax, uint32_t flags, 42 const char *new_process_action) 43 : CommandObjectParsed(interpreter, name, help, syntax, flags), 44 m_new_process_action(new_process_action) {} 45 46 ~CommandObjectProcessLaunchOrAttach() override = default; 47 48 protected: 49 bool StopProcessIfNecessary(Process *process, StateType &state, 50 CommandReturnObject &result) { 51 state = eStateInvalid; 52 if (process) { 53 state = process->GetState(); 54 55 if (process->IsAlive() && state != eStateConnected) { 56 std::string message; 57 if (process->GetState() == eStateAttaching) 58 message = 59 llvm::formatv("There is a pending attach, abort it and {0}?", 60 m_new_process_action); 61 else if (process->GetShouldDetach()) 62 message = llvm::formatv( 63 "There is a running process, detach from it and {0}?", 64 m_new_process_action); 65 else 66 message = 67 llvm::formatv("There is a running process, kill it and {0}?", 68 m_new_process_action); 69 70 if (!m_interpreter.Confirm(message, true)) { 71 result.SetStatus(eReturnStatusFailed); 72 return false; 73 } else { 74 if (process->GetShouldDetach()) { 75 bool keep_stopped = false; 76 Status detach_error(process->Detach(keep_stopped)); 77 if (detach_error.Success()) { 78 result.SetStatus(eReturnStatusSuccessFinishResult); 79 process = nullptr; 80 } else { 81 result.AppendErrorWithFormat( 82 "Failed to detach from process: %s\n", 83 detach_error.AsCString()); 84 } 85 } else { 86 Status destroy_error(process->Destroy(false)); 87 if (destroy_error.Success()) { 88 result.SetStatus(eReturnStatusSuccessFinishResult); 89 process = nullptr; 90 } else { 91 result.AppendErrorWithFormat("Failed to kill process: %s\n", 92 destroy_error.AsCString()); 93 } 94 } 95 } 96 } 97 } 98 return result.Succeeded(); 99 } 100 101 std::string m_new_process_action; 102 }; 103 104 // CommandObjectProcessLaunch 105 #pragma mark CommandObjectProcessLaunch 106 class CommandObjectProcessLaunch : public CommandObjectProcessLaunchOrAttach { 107 public: 108 CommandObjectProcessLaunch(CommandInterpreter &interpreter) 109 : CommandObjectProcessLaunchOrAttach( 110 interpreter, "process launch", 111 "Launch the executable in the debugger.", nullptr, 112 eCommandRequiresTarget, "restart"), 113 m_options(), 114 m_class_options("scripted process", true, 'C', 'k', 'v', 0), 115 m_all_options() { 116 m_all_options.Append(&m_options); 117 m_all_options.Append(&m_class_options, LLDB_OPT_SET_1 | LLDB_OPT_SET_2, 118 LLDB_OPT_SET_ALL); 119 m_all_options.Finalize(); 120 121 CommandArgumentEntry arg; 122 CommandArgumentData run_args_arg; 123 124 // Define the first (and only) variant of this arg. 125 run_args_arg.arg_type = eArgTypeRunArgs; 126 run_args_arg.arg_repetition = eArgRepeatOptional; 127 128 // There is only one variant this argument could be; put it into the 129 // argument entry. 130 arg.push_back(run_args_arg); 131 132 // Push the data for the first argument into the m_arguments vector. 133 m_arguments.push_back(arg); 134 } 135 136 ~CommandObjectProcessLaunch() override = default; 137 138 void 139 HandleArgumentCompletion(CompletionRequest &request, 140 OptionElementVector &opt_element_vector) override { 141 142 CommandCompletions::InvokeCommonCompletionCallbacks( 143 GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion, 144 request, nullptr); 145 } 146 147 Options *GetOptions() override { return &m_all_options; } 148 149 const char *GetRepeatCommand(Args ¤t_command_args, 150 uint32_t index) override { 151 // No repeat for "process launch"... 152 return ""; 153 } 154 155 protected: 156 bool DoExecute(Args &launch_args, CommandReturnObject &result) override { 157 Debugger &debugger = GetDebugger(); 158 Target *target = debugger.GetSelectedTarget().get(); 159 // If our listener is nullptr, users aren't allows to launch 160 ModuleSP exe_module_sp = target->GetExecutableModule(); 161 162 if (exe_module_sp == nullptr) { 163 result.AppendError("no file in target, create a debug target using the " 164 "'target create' command"); 165 return false; 166 } 167 168 StateType state = eStateInvalid; 169 170 if (!StopProcessIfNecessary(m_exe_ctx.GetProcessPtr(), state, result)) 171 return false; 172 173 // Determine whether we will disable ASLR or leave it in the default state 174 // (i.e. enabled if the platform supports it). First check if the process 175 // launch options explicitly turn on/off 176 // disabling ASLR. If so, use that setting; 177 // otherwise, use the 'settings target.disable-aslr' setting. 178 bool disable_aslr = false; 179 if (m_options.disable_aslr != eLazyBoolCalculate) { 180 // The user specified an explicit setting on the process launch line. 181 // Use it. 182 disable_aslr = (m_options.disable_aslr == eLazyBoolYes); 183 } else { 184 // The user did not explicitly specify whether to disable ASLR. Fall 185 // back to the target.disable-aslr setting. 186 disable_aslr = target->GetDisableASLR(); 187 } 188 189 if (!m_class_options.GetName().empty()) { 190 m_options.launch_info.SetProcessPluginName("ScriptedProcess"); 191 m_options.launch_info.SetScriptedProcessClassName( 192 m_class_options.GetName()); 193 m_options.launch_info.SetScriptedProcessDictionarySP( 194 m_class_options.GetStructuredData()); 195 target->SetProcessLaunchInfo(m_options.launch_info); 196 } 197 198 if (disable_aslr) 199 m_options.launch_info.GetFlags().Set(eLaunchFlagDisableASLR); 200 else 201 m_options.launch_info.GetFlags().Clear(eLaunchFlagDisableASLR); 202 203 if (target->GetInheritTCC()) 204 m_options.launch_info.GetFlags().Set(eLaunchFlagInheritTCCFromParent); 205 206 if (target->GetDetachOnError()) 207 m_options.launch_info.GetFlags().Set(eLaunchFlagDetachOnError); 208 209 if (target->GetDisableSTDIO()) 210 m_options.launch_info.GetFlags().Set(eLaunchFlagDisableSTDIO); 211 212 // Merge the launch info environment with the target environment. 213 Environment target_env = target->GetEnvironment(); 214 m_options.launch_info.GetEnvironment().insert(target_env.begin(), 215 target_env.end()); 216 217 llvm::StringRef target_settings_argv0 = target->GetArg0(); 218 219 if (!target_settings_argv0.empty()) { 220 m_options.launch_info.GetArguments().AppendArgument( 221 target_settings_argv0); 222 m_options.launch_info.SetExecutableFile( 223 exe_module_sp->GetPlatformFileSpec(), false); 224 } else { 225 m_options.launch_info.SetExecutableFile( 226 exe_module_sp->GetPlatformFileSpec(), true); 227 } 228 229 if (launch_args.GetArgumentCount() == 0) { 230 m_options.launch_info.GetArguments().AppendArguments( 231 target->GetProcessLaunchInfo().GetArguments()); 232 } else { 233 m_options.launch_info.GetArguments().AppendArguments(launch_args); 234 // Save the arguments for subsequent runs in the current target. 235 target->SetRunArguments(launch_args); 236 } 237 238 StreamString stream; 239 Status error = target->Launch(m_options.launch_info, &stream); 240 241 if (error.Success()) { 242 ProcessSP process_sp(target->GetProcessSP()); 243 if (process_sp) { 244 // There is a race condition where this thread will return up the call 245 // stack to the main command handler and show an (lldb) prompt before 246 // HandlePrivateEvent (from PrivateStateThread) has a chance to call 247 // PushProcessIOHandler(). 248 process_sp->SyncIOHandler(0, std::chrono::seconds(2)); 249 250 llvm::StringRef data = stream.GetString(); 251 if (!data.empty()) 252 result.AppendMessage(data); 253 const char *archname = 254 exe_module_sp->GetArchitecture().GetArchitectureName(); 255 result.AppendMessageWithFormat( 256 "Process %" PRIu64 " launched: '%s' (%s)\n", process_sp->GetID(), 257 exe_module_sp->GetFileSpec().GetPath().c_str(), archname); 258 result.SetStatus(eReturnStatusSuccessFinishResult); 259 result.SetDidChangeProcessState(true); 260 } else { 261 result.AppendError( 262 "no error returned from Target::Launch, and target has no process"); 263 } 264 } else { 265 result.AppendError(error.AsCString()); 266 } 267 return result.Succeeded(); 268 } 269 270 CommandOptionsProcessLaunch m_options; 271 OptionGroupPythonClassWithDict m_class_options; 272 OptionGroupOptions m_all_options; 273 }; 274 275 #define LLDB_OPTIONS_process_attach 276 #include "CommandOptions.inc" 277 278 #pragma mark CommandObjectProcessAttach 279 class CommandObjectProcessAttach : public CommandObjectProcessLaunchOrAttach { 280 public: 281 class CommandOptions : public Options { 282 public: 283 CommandOptions() : Options() { 284 // Keep default values of all options in one place: OptionParsingStarting 285 // () 286 OptionParsingStarting(nullptr); 287 } 288 289 ~CommandOptions() override = default; 290 291 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, 292 ExecutionContext *execution_context) override { 293 Status error; 294 const int short_option = m_getopt_table[option_idx].val; 295 switch (short_option) { 296 case 'c': 297 attach_info.SetContinueOnceAttached(true); 298 break; 299 300 case 'p': { 301 lldb::pid_t pid; 302 if (option_arg.getAsInteger(0, pid)) { 303 error.SetErrorStringWithFormat("invalid process ID '%s'", 304 option_arg.str().c_str()); 305 } else { 306 attach_info.SetProcessID(pid); 307 } 308 } break; 309 310 case 'P': 311 attach_info.SetProcessPluginName(option_arg); 312 break; 313 314 case 'n': 315 attach_info.GetExecutableFile().SetFile(option_arg, 316 FileSpec::Style::native); 317 break; 318 319 case 'w': 320 attach_info.SetWaitForLaunch(true); 321 break; 322 323 case 'i': 324 attach_info.SetIgnoreExisting(false); 325 break; 326 327 default: 328 llvm_unreachable("Unimplemented option"); 329 } 330 return error; 331 } 332 333 void OptionParsingStarting(ExecutionContext *execution_context) override { 334 attach_info.Clear(); 335 } 336 337 llvm::ArrayRef<OptionDefinition> GetDefinitions() override { 338 return llvm::makeArrayRef(g_process_attach_options); 339 } 340 341 ProcessAttachInfo attach_info; 342 }; 343 344 CommandObjectProcessAttach(CommandInterpreter &interpreter) 345 : CommandObjectProcessLaunchOrAttach( 346 interpreter, "process attach", "Attach to a process.", 347 "process attach <cmd-options>", 0, "attach"), 348 m_options() {} 349 350 ~CommandObjectProcessAttach() override = default; 351 352 Options *GetOptions() override { return &m_options; } 353 354 protected: 355 bool DoExecute(Args &command, CommandReturnObject &result) override { 356 PlatformSP platform_sp( 357 GetDebugger().GetPlatformList().GetSelectedPlatform()); 358 359 Target *target = GetDebugger().GetSelectedTarget().get(); 360 // N.B. The attach should be synchronous. It doesn't help much to get the 361 // prompt back between initiating the attach and the target actually 362 // stopping. So even if the interpreter is set to be asynchronous, we wait 363 // for the stop ourselves here. 364 365 StateType state = eStateInvalid; 366 Process *process = m_exe_ctx.GetProcessPtr(); 367 368 if (!StopProcessIfNecessary(process, state, result)) 369 return false; 370 371 if (target == nullptr) { 372 // If there isn't a current target create one. 373 TargetSP new_target_sp; 374 Status error; 375 376 error = GetDebugger().GetTargetList().CreateTarget( 377 GetDebugger(), "", "", eLoadDependentsNo, 378 nullptr, // No platform options 379 new_target_sp); 380 target = new_target_sp.get(); 381 if (target == nullptr || error.Fail()) { 382 result.AppendError(error.AsCString("Error creating target")); 383 return false; 384 } 385 } 386 387 // Record the old executable module, we want to issue a warning if the 388 // process of attaching changed the current executable (like somebody said 389 // "file foo" then attached to a PID whose executable was bar.) 390 391 ModuleSP old_exec_module_sp = target->GetExecutableModule(); 392 ArchSpec old_arch_spec = target->GetArchitecture(); 393 394 if (command.GetArgumentCount()) { 395 result.AppendErrorWithFormat("Invalid arguments for '%s'.\nUsage: %s\n", 396 m_cmd_name.c_str(), m_cmd_syntax.c_str()); 397 return false; 398 } 399 400 StreamString stream; 401 ProcessSP process_sp; 402 const auto error = target->Attach(m_options.attach_info, &stream); 403 if (error.Success()) { 404 process_sp = target->GetProcessSP(); 405 if (process_sp) { 406 result.AppendMessage(stream.GetString()); 407 result.SetStatus(eReturnStatusSuccessFinishNoResult); 408 result.SetDidChangeProcessState(true); 409 } else { 410 result.AppendError( 411 "no error returned from Target::Attach, and target has no process"); 412 } 413 } else { 414 result.AppendErrorWithFormat("attach failed: %s\n", error.AsCString()); 415 } 416 417 if (!result.Succeeded()) 418 return false; 419 420 // Okay, we're done. Last step is to warn if the executable module has 421 // changed: 422 char new_path[PATH_MAX]; 423 ModuleSP new_exec_module_sp(target->GetExecutableModule()); 424 if (!old_exec_module_sp) { 425 // We might not have a module if we attached to a raw pid... 426 if (new_exec_module_sp) { 427 new_exec_module_sp->GetFileSpec().GetPath(new_path, PATH_MAX); 428 result.AppendMessageWithFormat("Executable module set to \"%s\".\n", 429 new_path); 430 } 431 } else if (old_exec_module_sp->GetFileSpec() != 432 new_exec_module_sp->GetFileSpec()) { 433 char old_path[PATH_MAX]; 434 435 old_exec_module_sp->GetFileSpec().GetPath(old_path, PATH_MAX); 436 new_exec_module_sp->GetFileSpec().GetPath(new_path, PATH_MAX); 437 438 result.AppendWarningWithFormat( 439 "Executable module changed from \"%s\" to \"%s\".\n", old_path, 440 new_path); 441 } 442 443 if (!old_arch_spec.IsValid()) { 444 result.AppendMessageWithFormat( 445 "Architecture set to: %s.\n", 446 target->GetArchitecture().GetTriple().getTriple().c_str()); 447 } else if (!old_arch_spec.IsExactMatch(target->GetArchitecture())) { 448 result.AppendWarningWithFormat( 449 "Architecture changed from %s to %s.\n", 450 old_arch_spec.GetTriple().getTriple().c_str(), 451 target->GetArchitecture().GetTriple().getTriple().c_str()); 452 } 453 454 // This supports the use-case scenario of immediately continuing the 455 // process once attached. 456 if (m_options.attach_info.GetContinueOnceAttached()) { 457 // We have made a process but haven't told the interpreter about it yet, 458 // so CheckRequirements will fail for "process continue". Set the override 459 // here: 460 ExecutionContext exe_ctx(process_sp); 461 m_interpreter.HandleCommand("process continue", eLazyBoolNo, exe_ctx, result); 462 } 463 464 return result.Succeeded(); 465 } 466 467 CommandOptions m_options; 468 }; 469 470 // CommandObjectProcessContinue 471 472 #define LLDB_OPTIONS_process_continue 473 #include "CommandOptions.inc" 474 475 #pragma mark CommandObjectProcessContinue 476 477 class CommandObjectProcessContinue : public CommandObjectParsed { 478 public: 479 CommandObjectProcessContinue(CommandInterpreter &interpreter) 480 : CommandObjectParsed( 481 interpreter, "process continue", 482 "Continue execution of all threads in the current process.", 483 "process continue", 484 eCommandRequiresProcess | eCommandTryTargetAPILock | 485 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused), 486 m_options() {} 487 488 ~CommandObjectProcessContinue() override = default; 489 490 protected: 491 class CommandOptions : public Options { 492 public: 493 CommandOptions() : Options() { 494 // Keep default values of all options in one place: OptionParsingStarting 495 // () 496 OptionParsingStarting(nullptr); 497 } 498 499 ~CommandOptions() override = default; 500 501 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, 502 ExecutionContext *execution_context) override { 503 Status error; 504 const int short_option = m_getopt_table[option_idx].val; 505 switch (short_option) { 506 case 'i': 507 if (option_arg.getAsInteger(0, m_ignore)) 508 error.SetErrorStringWithFormat( 509 "invalid value for ignore option: \"%s\", should be a number.", 510 option_arg.str().c_str()); 511 break; 512 513 default: 514 llvm_unreachable("Unimplemented option"); 515 } 516 return error; 517 } 518 519 void OptionParsingStarting(ExecutionContext *execution_context) override { 520 m_ignore = 0; 521 } 522 523 llvm::ArrayRef<OptionDefinition> GetDefinitions() override { 524 return llvm::makeArrayRef(g_process_continue_options); 525 } 526 527 uint32_t m_ignore; 528 }; 529 530 bool DoExecute(Args &command, CommandReturnObject &result) override { 531 Process *process = m_exe_ctx.GetProcessPtr(); 532 bool synchronous_execution = m_interpreter.GetSynchronous(); 533 StateType state = process->GetState(); 534 if (state == eStateStopped) { 535 if (command.GetArgumentCount() != 0) { 536 result.AppendErrorWithFormat( 537 "The '%s' command does not take any arguments.\n", 538 m_cmd_name.c_str()); 539 return false; 540 } 541 542 if (m_options.m_ignore > 0) { 543 ThreadSP sel_thread_sp(GetDefaultThread()->shared_from_this()); 544 if (sel_thread_sp) { 545 StopInfoSP stop_info_sp = sel_thread_sp->GetStopInfo(); 546 if (stop_info_sp && 547 stop_info_sp->GetStopReason() == eStopReasonBreakpoint) { 548 lldb::break_id_t bp_site_id = 549 (lldb::break_id_t)stop_info_sp->GetValue(); 550 BreakpointSiteSP bp_site_sp( 551 process->GetBreakpointSiteList().FindByID(bp_site_id)); 552 if (bp_site_sp) { 553 const size_t num_owners = bp_site_sp->GetNumberOfOwners(); 554 for (size_t i = 0; i < num_owners; i++) { 555 Breakpoint &bp_ref = 556 bp_site_sp->GetOwnerAtIndex(i)->GetBreakpoint(); 557 if (!bp_ref.IsInternal()) { 558 bp_ref.SetIgnoreCount(m_options.m_ignore); 559 } 560 } 561 } 562 } 563 } 564 } 565 566 { // Scope for thread list mutex: 567 std::lock_guard<std::recursive_mutex> guard( 568 process->GetThreadList().GetMutex()); 569 const uint32_t num_threads = process->GetThreadList().GetSize(); 570 571 // Set the actions that the threads should each take when resuming 572 for (uint32_t idx = 0; idx < num_threads; ++idx) { 573 const bool override_suspend = false; 574 process->GetThreadList().GetThreadAtIndex(idx)->SetResumeState( 575 eStateRunning, override_suspend); 576 } 577 } 578 579 const uint32_t iohandler_id = process->GetIOHandlerID(); 580 581 StreamString stream; 582 Status error; 583 if (synchronous_execution) 584 error = process->ResumeSynchronous(&stream); 585 else 586 error = process->Resume(); 587 588 if (error.Success()) { 589 // There is a race condition where this thread will return up the call 590 // stack to the main command handler and show an (lldb) prompt before 591 // HandlePrivateEvent (from PrivateStateThread) has a chance to call 592 // PushProcessIOHandler(). 593 process->SyncIOHandler(iohandler_id, std::chrono::seconds(2)); 594 595 result.AppendMessageWithFormat("Process %" PRIu64 " resuming\n", 596 process->GetID()); 597 if (synchronous_execution) { 598 // If any state changed events had anything to say, add that to the 599 // result 600 result.AppendMessage(stream.GetString()); 601 602 result.SetDidChangeProcessState(true); 603 result.SetStatus(eReturnStatusSuccessFinishNoResult); 604 } else { 605 result.SetStatus(eReturnStatusSuccessContinuingNoResult); 606 } 607 } else { 608 result.AppendErrorWithFormat("Failed to resume process: %s.\n", 609 error.AsCString()); 610 } 611 } else { 612 result.AppendErrorWithFormat( 613 "Process cannot be continued from its current state (%s).\n", 614 StateAsCString(state)); 615 } 616 return result.Succeeded(); 617 } 618 619 Options *GetOptions() override { return &m_options; } 620 621 CommandOptions m_options; 622 }; 623 624 // CommandObjectProcessDetach 625 #define LLDB_OPTIONS_process_detach 626 #include "CommandOptions.inc" 627 628 #pragma mark CommandObjectProcessDetach 629 630 class CommandObjectProcessDetach : public CommandObjectParsed { 631 public: 632 class CommandOptions : public Options { 633 public: 634 CommandOptions() : Options() { OptionParsingStarting(nullptr); } 635 636 ~CommandOptions() override = default; 637 638 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, 639 ExecutionContext *execution_context) override { 640 Status error; 641 const int short_option = m_getopt_table[option_idx].val; 642 643 switch (short_option) { 644 case 's': 645 bool tmp_result; 646 bool success; 647 tmp_result = OptionArgParser::ToBoolean(option_arg, false, &success); 648 if (!success) 649 error.SetErrorStringWithFormat("invalid boolean option: \"%s\"", 650 option_arg.str().c_str()); 651 else { 652 if (tmp_result) 653 m_keep_stopped = eLazyBoolYes; 654 else 655 m_keep_stopped = eLazyBoolNo; 656 } 657 break; 658 default: 659 llvm_unreachable("Unimplemented option"); 660 } 661 return error; 662 } 663 664 void OptionParsingStarting(ExecutionContext *execution_context) override { 665 m_keep_stopped = eLazyBoolCalculate; 666 } 667 668 llvm::ArrayRef<OptionDefinition> GetDefinitions() override { 669 return llvm::makeArrayRef(g_process_detach_options); 670 } 671 672 // Instance variables to hold the values for command options. 673 LazyBool m_keep_stopped; 674 }; 675 676 CommandObjectProcessDetach(CommandInterpreter &interpreter) 677 : CommandObjectParsed(interpreter, "process detach", 678 "Detach from the current target process.", 679 "process detach", 680 eCommandRequiresProcess | eCommandTryTargetAPILock | 681 eCommandProcessMustBeLaunched), 682 m_options() {} 683 684 ~CommandObjectProcessDetach() override = default; 685 686 Options *GetOptions() override { return &m_options; } 687 688 protected: 689 bool DoExecute(Args &command, CommandReturnObject &result) override { 690 Process *process = m_exe_ctx.GetProcessPtr(); 691 // FIXME: This will be a Command Option: 692 bool keep_stopped; 693 if (m_options.m_keep_stopped == eLazyBoolCalculate) { 694 // Check the process default: 695 keep_stopped = process->GetDetachKeepsStopped(); 696 } else if (m_options.m_keep_stopped == eLazyBoolYes) 697 keep_stopped = true; 698 else 699 keep_stopped = false; 700 701 Status error(process->Detach(keep_stopped)); 702 if (error.Success()) { 703 result.SetStatus(eReturnStatusSuccessFinishResult); 704 } else { 705 result.AppendErrorWithFormat("Detach failed: %s\n", error.AsCString()); 706 return false; 707 } 708 return result.Succeeded(); 709 } 710 711 CommandOptions m_options; 712 }; 713 714 // CommandObjectProcessConnect 715 #define LLDB_OPTIONS_process_connect 716 #include "CommandOptions.inc" 717 718 #pragma mark CommandObjectProcessConnect 719 720 class CommandObjectProcessConnect : public CommandObjectParsed { 721 public: 722 class CommandOptions : public Options { 723 public: 724 CommandOptions() : Options() { 725 // Keep default values of all options in one place: OptionParsingStarting 726 // () 727 OptionParsingStarting(nullptr); 728 } 729 730 ~CommandOptions() override = default; 731 732 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, 733 ExecutionContext *execution_context) override { 734 Status error; 735 const int short_option = m_getopt_table[option_idx].val; 736 737 switch (short_option) { 738 case 'p': 739 plugin_name.assign(std::string(option_arg)); 740 break; 741 742 default: 743 llvm_unreachable("Unimplemented option"); 744 } 745 return error; 746 } 747 748 void OptionParsingStarting(ExecutionContext *execution_context) override { 749 plugin_name.clear(); 750 } 751 752 llvm::ArrayRef<OptionDefinition> GetDefinitions() override { 753 return llvm::makeArrayRef(g_process_connect_options); 754 } 755 756 // Instance variables to hold the values for command options. 757 758 std::string plugin_name; 759 }; 760 761 CommandObjectProcessConnect(CommandInterpreter &interpreter) 762 : CommandObjectParsed(interpreter, "process connect", 763 "Connect to a remote debug service.", 764 "process connect <remote-url>", 0), 765 m_options() {} 766 767 ~CommandObjectProcessConnect() override = default; 768 769 Options *GetOptions() override { return &m_options; } 770 771 protected: 772 bool DoExecute(Args &command, CommandReturnObject &result) override { 773 if (command.GetArgumentCount() != 1) { 774 result.AppendErrorWithFormat( 775 "'%s' takes exactly one argument:\nUsage: %s\n", m_cmd_name.c_str(), 776 m_cmd_syntax.c_str()); 777 return false; 778 } 779 780 Process *process = m_exe_ctx.GetProcessPtr(); 781 if (process && process->IsAlive()) { 782 result.AppendErrorWithFormat( 783 "Process %" PRIu64 784 " is currently being debugged, kill the process before connecting.\n", 785 process->GetID()); 786 return false; 787 } 788 789 const char *plugin_name = nullptr; 790 if (!m_options.plugin_name.empty()) 791 plugin_name = m_options.plugin_name.c_str(); 792 793 Status error; 794 Debugger &debugger = GetDebugger(); 795 PlatformSP platform_sp = m_interpreter.GetPlatform(true); 796 ProcessSP process_sp = 797 debugger.GetAsyncExecution() 798 ? platform_sp->ConnectProcess( 799 command.GetArgumentAtIndex(0), plugin_name, debugger, 800 debugger.GetSelectedTarget().get(), error) 801 : platform_sp->ConnectProcessSynchronous( 802 command.GetArgumentAtIndex(0), plugin_name, debugger, 803 result.GetOutputStream(), debugger.GetSelectedTarget().get(), 804 error); 805 if (error.Fail() || process_sp == nullptr) { 806 result.AppendError(error.AsCString("Error connecting to the process")); 807 return false; 808 } 809 return true; 810 } 811 812 CommandOptions m_options; 813 }; 814 815 // CommandObjectProcessPlugin 816 #pragma mark CommandObjectProcessPlugin 817 818 class CommandObjectProcessPlugin : public CommandObjectProxy { 819 public: 820 CommandObjectProcessPlugin(CommandInterpreter &interpreter) 821 : CommandObjectProxy( 822 interpreter, "process plugin", 823 "Send a custom command to the current target process plug-in.", 824 "process plugin <args>", 0) {} 825 826 ~CommandObjectProcessPlugin() override = default; 827 828 CommandObject *GetProxyCommandObject() override { 829 Process *process = m_interpreter.GetExecutionContext().GetProcessPtr(); 830 if (process) 831 return process->GetPluginCommandObject(); 832 return nullptr; 833 } 834 }; 835 836 // CommandObjectProcessLoad 837 #define LLDB_OPTIONS_process_load 838 #include "CommandOptions.inc" 839 840 #pragma mark CommandObjectProcessLoad 841 842 class CommandObjectProcessLoad : public CommandObjectParsed { 843 public: 844 class CommandOptions : public Options { 845 public: 846 CommandOptions() : Options() { 847 // Keep default values of all options in one place: OptionParsingStarting 848 // () 849 OptionParsingStarting(nullptr); 850 } 851 852 ~CommandOptions() override = default; 853 854 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, 855 ExecutionContext *execution_context) override { 856 Status error; 857 const int short_option = m_getopt_table[option_idx].val; 858 switch (short_option) { 859 case 'i': 860 do_install = true; 861 if (!option_arg.empty()) 862 install_path.SetFile(option_arg, FileSpec::Style::native); 863 break; 864 default: 865 llvm_unreachable("Unimplemented option"); 866 } 867 return error; 868 } 869 870 void OptionParsingStarting(ExecutionContext *execution_context) override { 871 do_install = false; 872 install_path.Clear(); 873 } 874 875 llvm::ArrayRef<OptionDefinition> GetDefinitions() override { 876 return llvm::makeArrayRef(g_process_load_options); 877 } 878 879 // Instance variables to hold the values for command options. 880 bool do_install; 881 FileSpec install_path; 882 }; 883 884 CommandObjectProcessLoad(CommandInterpreter &interpreter) 885 : CommandObjectParsed(interpreter, "process load", 886 "Load a shared library into the current process.", 887 "process load <filename> [<filename> ...]", 888 eCommandRequiresProcess | eCommandTryTargetAPILock | 889 eCommandProcessMustBeLaunched | 890 eCommandProcessMustBePaused), 891 m_options() {} 892 893 ~CommandObjectProcessLoad() override = default; 894 895 void 896 HandleArgumentCompletion(CompletionRequest &request, 897 OptionElementVector &opt_element_vector) override { 898 if (!m_exe_ctx.HasProcessScope()) 899 return; 900 901 CommandCompletions::InvokeCommonCompletionCallbacks( 902 GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion, 903 request, nullptr); 904 } 905 906 Options *GetOptions() override { return &m_options; } 907 908 protected: 909 bool DoExecute(Args &command, CommandReturnObject &result) override { 910 Process *process = m_exe_ctx.GetProcessPtr(); 911 912 for (auto &entry : command.entries()) { 913 Status error; 914 PlatformSP platform = process->GetTarget().GetPlatform(); 915 llvm::StringRef image_path = entry.ref(); 916 uint32_t image_token = LLDB_INVALID_IMAGE_TOKEN; 917 918 if (!m_options.do_install) { 919 FileSpec image_spec(image_path); 920 platform->ResolveRemotePath(image_spec, image_spec); 921 image_token = 922 platform->LoadImage(process, FileSpec(), image_spec, error); 923 } else if (m_options.install_path) { 924 FileSpec image_spec(image_path); 925 FileSystem::Instance().Resolve(image_spec); 926 platform->ResolveRemotePath(m_options.install_path, 927 m_options.install_path); 928 image_token = platform->LoadImage(process, image_spec, 929 m_options.install_path, error); 930 } else { 931 FileSpec image_spec(image_path); 932 FileSystem::Instance().Resolve(image_spec); 933 image_token = 934 platform->LoadImage(process, image_spec, FileSpec(), error); 935 } 936 937 if (image_token != LLDB_INVALID_IMAGE_TOKEN) { 938 result.AppendMessageWithFormat( 939 "Loading \"%s\"...ok\nImage %u loaded.\n", image_path.str().c_str(), 940 image_token); 941 result.SetStatus(eReturnStatusSuccessFinishResult); 942 } else { 943 result.AppendErrorWithFormat("failed to load '%s': %s", 944 image_path.str().c_str(), 945 error.AsCString()); 946 } 947 } 948 return result.Succeeded(); 949 } 950 951 CommandOptions m_options; 952 }; 953 954 // CommandObjectProcessUnload 955 #pragma mark CommandObjectProcessUnload 956 957 class CommandObjectProcessUnload : public CommandObjectParsed { 958 public: 959 CommandObjectProcessUnload(CommandInterpreter &interpreter) 960 : CommandObjectParsed( 961 interpreter, "process unload", 962 "Unload a shared library from the current process using the index " 963 "returned by a previous call to \"process load\".", 964 "process unload <index>", 965 eCommandRequiresProcess | eCommandTryTargetAPILock | 966 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {} 967 968 ~CommandObjectProcessUnload() override = default; 969 970 void 971 HandleArgumentCompletion(CompletionRequest &request, 972 OptionElementVector &opt_element_vector) override { 973 974 if (request.GetCursorIndex() || !m_exe_ctx.HasProcessScope()) 975 return; 976 977 Process *process = m_exe_ctx.GetProcessPtr(); 978 979 const std::vector<lldb::addr_t> &tokens = process->GetImageTokens(); 980 const size_t token_num = tokens.size(); 981 for (size_t i = 0; i < token_num; ++i) { 982 if (tokens[i] == LLDB_INVALID_IMAGE_TOKEN) 983 continue; 984 request.TryCompleteCurrentArg(std::to_string(i)); 985 } 986 } 987 988 protected: 989 bool DoExecute(Args &command, CommandReturnObject &result) override { 990 Process *process = m_exe_ctx.GetProcessPtr(); 991 992 for (auto &entry : command.entries()) { 993 uint32_t image_token; 994 if (entry.ref().getAsInteger(0, image_token)) { 995 result.AppendErrorWithFormat("invalid image index argument '%s'", 996 entry.ref().str().c_str()); 997 break; 998 } else { 999 Status error(process->GetTarget().GetPlatform()->UnloadImage( 1000 process, image_token)); 1001 if (error.Success()) { 1002 result.AppendMessageWithFormat( 1003 "Unloading shared library with index %u...ok\n", image_token); 1004 result.SetStatus(eReturnStatusSuccessFinishResult); 1005 } else { 1006 result.AppendErrorWithFormat("failed to unload image: %s", 1007 error.AsCString()); 1008 break; 1009 } 1010 } 1011 } 1012 return result.Succeeded(); 1013 } 1014 }; 1015 1016 // CommandObjectProcessSignal 1017 #pragma mark CommandObjectProcessSignal 1018 1019 class CommandObjectProcessSignal : public CommandObjectParsed { 1020 public: 1021 CommandObjectProcessSignal(CommandInterpreter &interpreter) 1022 : CommandObjectParsed( 1023 interpreter, "process signal", 1024 "Send a UNIX signal to the current target process.", nullptr, 1025 eCommandRequiresProcess | eCommandTryTargetAPILock) { 1026 CommandArgumentEntry arg; 1027 CommandArgumentData signal_arg; 1028 1029 // Define the first (and only) variant of this arg. 1030 signal_arg.arg_type = eArgTypeUnixSignal; 1031 signal_arg.arg_repetition = eArgRepeatPlain; 1032 1033 // There is only one variant this argument could be; put it into the 1034 // argument entry. 1035 arg.push_back(signal_arg); 1036 1037 // Push the data for the first argument into the m_arguments vector. 1038 m_arguments.push_back(arg); 1039 } 1040 1041 ~CommandObjectProcessSignal() override = default; 1042 1043 void 1044 HandleArgumentCompletion(CompletionRequest &request, 1045 OptionElementVector &opt_element_vector) override { 1046 if (!m_exe_ctx.HasProcessScope() || request.GetCursorIndex() != 0) 1047 return; 1048 1049 UnixSignalsSP signals = m_exe_ctx.GetProcessPtr()->GetUnixSignals(); 1050 int signo = signals->GetFirstSignalNumber(); 1051 while (signo != LLDB_INVALID_SIGNAL_NUMBER) { 1052 request.TryCompleteCurrentArg(signals->GetSignalAsCString(signo)); 1053 signo = signals->GetNextSignalNumber(signo); 1054 } 1055 } 1056 1057 protected: 1058 bool DoExecute(Args &command, CommandReturnObject &result) override { 1059 Process *process = m_exe_ctx.GetProcessPtr(); 1060 1061 if (command.GetArgumentCount() == 1) { 1062 int signo = LLDB_INVALID_SIGNAL_NUMBER; 1063 1064 const char *signal_name = command.GetArgumentAtIndex(0); 1065 if (::isxdigit(signal_name[0])) { 1066 if (!llvm::to_integer(signal_name, signo)) 1067 signo = LLDB_INVALID_SIGNAL_NUMBER; 1068 } else 1069 signo = process->GetUnixSignals()->GetSignalNumberFromName(signal_name); 1070 1071 if (signo == LLDB_INVALID_SIGNAL_NUMBER) { 1072 result.AppendErrorWithFormat("Invalid signal argument '%s'.\n", 1073 command.GetArgumentAtIndex(0)); 1074 } else { 1075 Status error(process->Signal(signo)); 1076 if (error.Success()) { 1077 result.SetStatus(eReturnStatusSuccessFinishResult); 1078 } else { 1079 result.AppendErrorWithFormat("Failed to send signal %i: %s\n", signo, 1080 error.AsCString()); 1081 } 1082 } 1083 } else { 1084 result.AppendErrorWithFormat( 1085 "'%s' takes exactly one signal number argument:\nUsage: %s\n", 1086 m_cmd_name.c_str(), m_cmd_syntax.c_str()); 1087 } 1088 return result.Succeeded(); 1089 } 1090 }; 1091 1092 // CommandObjectProcessInterrupt 1093 #pragma mark CommandObjectProcessInterrupt 1094 1095 class CommandObjectProcessInterrupt : public CommandObjectParsed { 1096 public: 1097 CommandObjectProcessInterrupt(CommandInterpreter &interpreter) 1098 : CommandObjectParsed(interpreter, "process interrupt", 1099 "Interrupt the current target process.", 1100 "process interrupt", 1101 eCommandRequiresProcess | eCommandTryTargetAPILock | 1102 eCommandProcessMustBeLaunched) {} 1103 1104 ~CommandObjectProcessInterrupt() override = default; 1105 1106 protected: 1107 bool DoExecute(Args &command, CommandReturnObject &result) override { 1108 Process *process = m_exe_ctx.GetProcessPtr(); 1109 if (process == nullptr) { 1110 result.AppendError("no process to halt"); 1111 return false; 1112 } 1113 1114 if (command.GetArgumentCount() == 0) { 1115 bool clear_thread_plans = true; 1116 Status error(process->Halt(clear_thread_plans)); 1117 if (error.Success()) { 1118 result.SetStatus(eReturnStatusSuccessFinishResult); 1119 } else { 1120 result.AppendErrorWithFormat("Failed to halt process: %s\n", 1121 error.AsCString()); 1122 } 1123 } else { 1124 result.AppendErrorWithFormat("'%s' takes no arguments:\nUsage: %s\n", 1125 m_cmd_name.c_str(), m_cmd_syntax.c_str()); 1126 } 1127 return result.Succeeded(); 1128 } 1129 }; 1130 1131 // CommandObjectProcessKill 1132 #pragma mark CommandObjectProcessKill 1133 1134 class CommandObjectProcessKill : public CommandObjectParsed { 1135 public: 1136 CommandObjectProcessKill(CommandInterpreter &interpreter) 1137 : CommandObjectParsed(interpreter, "process kill", 1138 "Terminate the current target process.", 1139 "process kill", 1140 eCommandRequiresProcess | eCommandTryTargetAPILock | 1141 eCommandProcessMustBeLaunched) {} 1142 1143 ~CommandObjectProcessKill() override = default; 1144 1145 protected: 1146 bool DoExecute(Args &command, CommandReturnObject &result) override { 1147 Process *process = m_exe_ctx.GetProcessPtr(); 1148 if (process == nullptr) { 1149 result.AppendError("no process to kill"); 1150 return false; 1151 } 1152 1153 if (command.GetArgumentCount() == 0) { 1154 Status error(process->Destroy(true)); 1155 if (error.Success()) { 1156 result.SetStatus(eReturnStatusSuccessFinishResult); 1157 } else { 1158 result.AppendErrorWithFormat("Failed to kill process: %s\n", 1159 error.AsCString()); 1160 } 1161 } else { 1162 result.AppendErrorWithFormat("'%s' takes no arguments:\nUsage: %s\n", 1163 m_cmd_name.c_str(), m_cmd_syntax.c_str()); 1164 } 1165 return result.Succeeded(); 1166 } 1167 }; 1168 1169 // CommandObjectProcessSaveCore 1170 #pragma mark CommandObjectProcessSaveCore 1171 1172 static constexpr OptionEnumValueElement g_corefile_save_style[] = { 1173 {eSaveCoreFull, "full", "Create a core file with all memory saved"}, 1174 {eSaveCoreDirtyOnly, "modified-memory", 1175 "Create a corefile with only modified memory saved"}, 1176 {eSaveCoreStackOnly, "stack", 1177 "Create a corefile with only stack memory saved"}}; 1178 1179 static constexpr OptionEnumValues SaveCoreStyles() { 1180 return OptionEnumValues(g_corefile_save_style); 1181 } 1182 1183 #define LLDB_OPTIONS_process_save_core 1184 #include "CommandOptions.inc" 1185 1186 class CommandObjectProcessSaveCore : public CommandObjectParsed { 1187 public: 1188 CommandObjectProcessSaveCore(CommandInterpreter &interpreter) 1189 : CommandObjectParsed( 1190 interpreter, "process save-core", 1191 "Save the current process as a core file using an " 1192 "appropriate file type.", 1193 "process save-core [-s corefile-style -p plugin-name] FILE", 1194 eCommandRequiresProcess | eCommandTryTargetAPILock | 1195 eCommandProcessMustBeLaunched) {} 1196 1197 ~CommandObjectProcessSaveCore() override = default; 1198 1199 Options *GetOptions() override { return &m_options; } 1200 1201 class CommandOptions : public Options { 1202 public: 1203 CommandOptions() 1204 : Options(), m_requested_save_core_style(eSaveCoreUnspecified) {} 1205 1206 ~CommandOptions() override = default; 1207 1208 llvm::ArrayRef<OptionDefinition> GetDefinitions() override { 1209 return llvm::makeArrayRef(g_process_save_core_options); 1210 } 1211 1212 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, 1213 ExecutionContext *execution_context) override { 1214 const int short_option = m_getopt_table[option_idx].val; 1215 Status error; 1216 1217 switch (short_option) { 1218 case 'p': 1219 m_requested_plugin_name = option_arg.str(); 1220 break; 1221 case 's': 1222 m_requested_save_core_style = 1223 (lldb::SaveCoreStyle)OptionArgParser::ToOptionEnum( 1224 option_arg, GetDefinitions()[option_idx].enum_values, 1225 eSaveCoreUnspecified, error); 1226 break; 1227 default: 1228 llvm_unreachable("Unimplemented option"); 1229 } 1230 1231 return {}; 1232 } 1233 1234 void OptionParsingStarting(ExecutionContext *execution_context) override { 1235 m_requested_save_core_style = eSaveCoreUnspecified; 1236 m_requested_plugin_name.clear(); 1237 } 1238 1239 // Instance variables to hold the values for command options. 1240 SaveCoreStyle m_requested_save_core_style; 1241 std::string m_requested_plugin_name; 1242 }; 1243 1244 protected: 1245 bool DoExecute(Args &command, CommandReturnObject &result) override { 1246 ProcessSP process_sp = m_exe_ctx.GetProcessSP(); 1247 if (process_sp) { 1248 if (command.GetArgumentCount() == 1) { 1249 FileSpec output_file(command.GetArgumentAtIndex(0)); 1250 SaveCoreStyle corefile_style = m_options.m_requested_save_core_style; 1251 Status error = 1252 PluginManager::SaveCore(process_sp, output_file, corefile_style, 1253 m_options.m_requested_plugin_name); 1254 if (error.Success()) { 1255 if (corefile_style == SaveCoreStyle::eSaveCoreDirtyOnly || 1256 corefile_style == SaveCoreStyle::eSaveCoreStackOnly) { 1257 result.AppendMessageWithFormat( 1258 "\nModified-memory or stack-memory only corefile " 1259 "created. This corefile may \n" 1260 "not show library/framework/app binaries " 1261 "on a different system, or when \n" 1262 "those binaries have " 1263 "been updated/modified. Copies are not included\n" 1264 "in this corefile. Use --style full to include all " 1265 "process memory.\n"); 1266 } 1267 result.SetStatus(eReturnStatusSuccessFinishResult); 1268 } else { 1269 result.AppendErrorWithFormat( 1270 "Failed to save core file for process: %s\n", error.AsCString()); 1271 } 1272 } else { 1273 result.AppendErrorWithFormat("'%s' takes one arguments:\nUsage: %s\n", 1274 m_cmd_name.c_str(), m_cmd_syntax.c_str()); 1275 } 1276 } else { 1277 result.AppendError("invalid process"); 1278 return false; 1279 } 1280 1281 return result.Succeeded(); 1282 } 1283 1284 CommandOptions m_options; 1285 }; 1286 1287 // CommandObjectProcessStatus 1288 #pragma mark CommandObjectProcessStatus 1289 #define LLDB_OPTIONS_process_status 1290 #include "CommandOptions.inc" 1291 1292 class CommandObjectProcessStatus : public CommandObjectParsed { 1293 public: 1294 CommandObjectProcessStatus(CommandInterpreter &interpreter) 1295 : CommandObjectParsed( 1296 interpreter, "process status", 1297 "Show status and stop location for the current target process.", 1298 "process status", 1299 eCommandRequiresProcess | eCommandTryTargetAPILock), 1300 m_options() {} 1301 1302 ~CommandObjectProcessStatus() override = default; 1303 1304 Options *GetOptions() override { return &m_options; } 1305 1306 class CommandOptions : public Options { 1307 public: 1308 CommandOptions() : Options() {} 1309 1310 ~CommandOptions() override = default; 1311 1312 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, 1313 ExecutionContext *execution_context) override { 1314 const int short_option = m_getopt_table[option_idx].val; 1315 1316 switch (short_option) { 1317 case 'v': 1318 m_verbose = true; 1319 break; 1320 default: 1321 llvm_unreachable("Unimplemented option"); 1322 } 1323 1324 return {}; 1325 } 1326 1327 void OptionParsingStarting(ExecutionContext *execution_context) override { 1328 m_verbose = false; 1329 } 1330 1331 llvm::ArrayRef<OptionDefinition> GetDefinitions() override { 1332 return llvm::makeArrayRef(g_process_status_options); 1333 } 1334 1335 // Instance variables to hold the values for command options. 1336 bool m_verbose = false; 1337 }; 1338 1339 protected: 1340 bool DoExecute(Args &command, CommandReturnObject &result) override { 1341 Stream &strm = result.GetOutputStream(); 1342 result.SetStatus(eReturnStatusSuccessFinishNoResult); 1343 1344 if (command.GetArgumentCount()) { 1345 result.AppendError("'process status' takes no arguments"); 1346 return result.Succeeded(); 1347 } 1348 1349 // No need to check "process" for validity as eCommandRequiresProcess 1350 // ensures it is valid 1351 Process *process = m_exe_ctx.GetProcessPtr(); 1352 const bool only_threads_with_stop_reason = true; 1353 const uint32_t start_frame = 0; 1354 const uint32_t num_frames = 1; 1355 const uint32_t num_frames_with_source = 1; 1356 const bool stop_format = true; 1357 process->GetStatus(strm); 1358 process->GetThreadStatus(strm, only_threads_with_stop_reason, start_frame, 1359 num_frames, num_frames_with_source, stop_format); 1360 1361 if (m_options.m_verbose) { 1362 addr_t code_mask = process->GetCodeAddressMask(); 1363 addr_t data_mask = process->GetDataAddressMask(); 1364 if (code_mask != 0) { 1365 int bits = std::bitset<64>(~code_mask).count(); 1366 result.AppendMessageWithFormat( 1367 "Addressable code address mask: 0x%" PRIx64 "\n", code_mask); 1368 result.AppendMessageWithFormat( 1369 "Addressable data address mask: 0x%" PRIx64 "\n", data_mask); 1370 result.AppendMessageWithFormat( 1371 "Number of bits used in addressing (code): %d\n", bits); 1372 } 1373 1374 PlatformSP platform_sp = process->GetTarget().GetPlatform(); 1375 if (!platform_sp) { 1376 result.AppendError("Couldn'retrieve the target's platform"); 1377 return result.Succeeded(); 1378 } 1379 1380 auto expected_crash_info = 1381 platform_sp->FetchExtendedCrashInformation(*process); 1382 1383 if (!expected_crash_info) { 1384 result.AppendError(llvm::toString(expected_crash_info.takeError())); 1385 return result.Succeeded(); 1386 } 1387 1388 StructuredData::DictionarySP crash_info_sp = *expected_crash_info; 1389 1390 if (crash_info_sp) { 1391 strm.PutCString("Extended Crash Information:\n"); 1392 crash_info_sp->Dump(strm); 1393 } 1394 } 1395 1396 return result.Succeeded(); 1397 } 1398 1399 private: 1400 CommandOptions m_options; 1401 }; 1402 1403 // CommandObjectProcessHandle 1404 #define LLDB_OPTIONS_process_handle 1405 #include "CommandOptions.inc" 1406 1407 #pragma mark CommandObjectProcessHandle 1408 1409 class CommandObjectProcessHandle : public CommandObjectParsed { 1410 public: 1411 class CommandOptions : public Options { 1412 public: 1413 CommandOptions() : Options() { OptionParsingStarting(nullptr); } 1414 1415 ~CommandOptions() override = default; 1416 1417 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, 1418 ExecutionContext *execution_context) override { 1419 Status error; 1420 const int short_option = m_getopt_table[option_idx].val; 1421 1422 switch (short_option) { 1423 case 's': 1424 stop = std::string(option_arg); 1425 break; 1426 case 'n': 1427 notify = std::string(option_arg); 1428 break; 1429 case 'p': 1430 pass = std::string(option_arg); 1431 break; 1432 default: 1433 llvm_unreachable("Unimplemented option"); 1434 } 1435 return error; 1436 } 1437 1438 void OptionParsingStarting(ExecutionContext *execution_context) override { 1439 stop.clear(); 1440 notify.clear(); 1441 pass.clear(); 1442 } 1443 1444 llvm::ArrayRef<OptionDefinition> GetDefinitions() override { 1445 return llvm::makeArrayRef(g_process_handle_options); 1446 } 1447 1448 // Instance variables to hold the values for command options. 1449 1450 std::string stop; 1451 std::string notify; 1452 std::string pass; 1453 }; 1454 1455 CommandObjectProcessHandle(CommandInterpreter &interpreter) 1456 : CommandObjectParsed(interpreter, "process handle", 1457 "Manage LLDB handling of OS signals for the " 1458 "current target process. Defaults to showing " 1459 "current policy.", 1460 nullptr, eCommandRequiresTarget), 1461 m_options() { 1462 SetHelpLong("\nIf no signals are specified, update them all. If no update " 1463 "option is specified, list the current values."); 1464 CommandArgumentEntry arg; 1465 CommandArgumentData signal_arg; 1466 1467 signal_arg.arg_type = eArgTypeUnixSignal; 1468 signal_arg.arg_repetition = eArgRepeatStar; 1469 1470 arg.push_back(signal_arg); 1471 1472 m_arguments.push_back(arg); 1473 } 1474 1475 ~CommandObjectProcessHandle() override = default; 1476 1477 Options *GetOptions() override { return &m_options; } 1478 1479 bool VerifyCommandOptionValue(const std::string &option, int &real_value) { 1480 bool okay = true; 1481 bool success = false; 1482 bool tmp_value = OptionArgParser::ToBoolean(option, false, &success); 1483 1484 if (success && tmp_value) 1485 real_value = 1; 1486 else if (success && !tmp_value) 1487 real_value = 0; 1488 else { 1489 // If the value isn't 'true' or 'false', it had better be 0 or 1. 1490 if (!llvm::to_integer(option, real_value)) 1491 real_value = 3; 1492 if (real_value != 0 && real_value != 1) 1493 okay = false; 1494 } 1495 1496 return okay; 1497 } 1498 1499 void PrintSignalHeader(Stream &str) { 1500 str.Printf("NAME PASS STOP NOTIFY\n"); 1501 str.Printf("=========== ===== ===== ======\n"); 1502 } 1503 1504 void PrintSignal(Stream &str, int32_t signo, const char *sig_name, 1505 const UnixSignalsSP &signals_sp) { 1506 bool stop; 1507 bool suppress; 1508 bool notify; 1509 1510 str.Printf("%-11s ", sig_name); 1511 if (signals_sp->GetSignalInfo(signo, suppress, stop, notify)) { 1512 bool pass = !suppress; 1513 str.Printf("%s %s %s", (pass ? "true " : "false"), 1514 (stop ? "true " : "false"), (notify ? "true " : "false")); 1515 } 1516 str.Printf("\n"); 1517 } 1518 1519 void PrintSignalInformation(Stream &str, Args &signal_args, 1520 int num_valid_signals, 1521 const UnixSignalsSP &signals_sp) { 1522 PrintSignalHeader(str); 1523 1524 if (num_valid_signals > 0) { 1525 size_t num_args = signal_args.GetArgumentCount(); 1526 for (size_t i = 0; i < num_args; ++i) { 1527 int32_t signo = signals_sp->GetSignalNumberFromName( 1528 signal_args.GetArgumentAtIndex(i)); 1529 if (signo != LLDB_INVALID_SIGNAL_NUMBER) 1530 PrintSignal(str, signo, signal_args.GetArgumentAtIndex(i), 1531 signals_sp); 1532 } 1533 } else // Print info for ALL signals 1534 { 1535 int32_t signo = signals_sp->GetFirstSignalNumber(); 1536 while (signo != LLDB_INVALID_SIGNAL_NUMBER) { 1537 PrintSignal(str, signo, signals_sp->GetSignalAsCString(signo), 1538 signals_sp); 1539 signo = signals_sp->GetNextSignalNumber(signo); 1540 } 1541 } 1542 } 1543 1544 protected: 1545 bool DoExecute(Args &signal_args, CommandReturnObject &result) override { 1546 Target *target_sp = &GetSelectedTarget(); 1547 1548 ProcessSP process_sp = target_sp->GetProcessSP(); 1549 1550 if (!process_sp) { 1551 result.AppendError("No current process; cannot handle signals until you " 1552 "have a valid process.\n"); 1553 return false; 1554 } 1555 1556 int stop_action = -1; // -1 means leave the current setting alone 1557 int pass_action = -1; // -1 means leave the current setting alone 1558 int notify_action = -1; // -1 means leave the current setting alone 1559 1560 if (!m_options.stop.empty() && 1561 !VerifyCommandOptionValue(m_options.stop, stop_action)) { 1562 result.AppendError("Invalid argument for command option --stop; must be " 1563 "true or false.\n"); 1564 return false; 1565 } 1566 1567 if (!m_options.notify.empty() && 1568 !VerifyCommandOptionValue(m_options.notify, notify_action)) { 1569 result.AppendError("Invalid argument for command option --notify; must " 1570 "be true or false.\n"); 1571 return false; 1572 } 1573 1574 if (!m_options.pass.empty() && 1575 !VerifyCommandOptionValue(m_options.pass, pass_action)) { 1576 result.AppendError("Invalid argument for command option --pass; must be " 1577 "true or false.\n"); 1578 return false; 1579 } 1580 1581 size_t num_args = signal_args.GetArgumentCount(); 1582 UnixSignalsSP signals_sp = process_sp->GetUnixSignals(); 1583 int num_signals_set = 0; 1584 1585 if (num_args > 0) { 1586 for (const auto &arg : signal_args) { 1587 int32_t signo = signals_sp->GetSignalNumberFromName(arg.c_str()); 1588 if (signo != LLDB_INVALID_SIGNAL_NUMBER) { 1589 // Casting the actions as bools here should be okay, because 1590 // VerifyCommandOptionValue guarantees the value is either 0 or 1. 1591 if (stop_action != -1) 1592 signals_sp->SetShouldStop(signo, stop_action); 1593 if (pass_action != -1) { 1594 bool suppress = !pass_action; 1595 signals_sp->SetShouldSuppress(signo, suppress); 1596 } 1597 if (notify_action != -1) 1598 signals_sp->SetShouldNotify(signo, notify_action); 1599 ++num_signals_set; 1600 } else { 1601 result.AppendErrorWithFormat("Invalid signal name '%s'\n", 1602 arg.c_str()); 1603 } 1604 } 1605 } else { 1606 // No signal specified, if any command options were specified, update ALL 1607 // signals. 1608 if ((notify_action != -1) || (stop_action != -1) || (pass_action != -1)) { 1609 if (m_interpreter.Confirm( 1610 "Do you really want to update all the signals?", false)) { 1611 int32_t signo = signals_sp->GetFirstSignalNumber(); 1612 while (signo != LLDB_INVALID_SIGNAL_NUMBER) { 1613 if (notify_action != -1) 1614 signals_sp->SetShouldNotify(signo, notify_action); 1615 if (stop_action != -1) 1616 signals_sp->SetShouldStop(signo, stop_action); 1617 if (pass_action != -1) { 1618 bool suppress = !pass_action; 1619 signals_sp->SetShouldSuppress(signo, suppress); 1620 } 1621 signo = signals_sp->GetNextSignalNumber(signo); 1622 } 1623 } 1624 } 1625 } 1626 1627 PrintSignalInformation(result.GetOutputStream(), signal_args, 1628 num_signals_set, signals_sp); 1629 1630 if (num_signals_set > 0) 1631 result.SetStatus(eReturnStatusSuccessFinishNoResult); 1632 else 1633 result.SetStatus(eReturnStatusFailed); 1634 1635 return result.Succeeded(); 1636 } 1637 1638 CommandOptions m_options; 1639 }; 1640 1641 // Next are the subcommands of CommandObjectMultiwordProcessTrace 1642 1643 // CommandObjectProcessTraceStart 1644 class CommandObjectProcessTraceStart : public CommandObjectTraceProxy { 1645 public: 1646 CommandObjectProcessTraceStart(CommandInterpreter &interpreter) 1647 : CommandObjectTraceProxy( 1648 /*live_debug_session_only*/ true, interpreter, 1649 "process trace start", 1650 "Start tracing this process with the corresponding trace " 1651 "plug-in.", 1652 "process trace start [<trace-options>]") {} 1653 1654 protected: 1655 lldb::CommandObjectSP GetDelegateCommand(Trace &trace) override { 1656 return trace.GetProcessTraceStartCommand(m_interpreter); 1657 } 1658 }; 1659 1660 // CommandObjectProcessTraceSave 1661 #define LLDB_OPTIONS_process_trace_save 1662 #include "CommandOptions.inc" 1663 1664 #pragma mark CommandObjectProcessTraceSave 1665 1666 class CommandObjectProcessTraceSave : public CommandObjectParsed { 1667 public: 1668 class CommandOptions : public Options { 1669 public: 1670 CommandOptions() : Options() { OptionParsingStarting(nullptr); } 1671 1672 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, 1673 ExecutionContext *execution_context) override { 1674 Status error; 1675 const int short_option = m_getopt_table[option_idx].val; 1676 1677 switch (short_option) { 1678 1679 case 'd': { 1680 m_directory.SetFile(option_arg, FileSpec::Style::native); 1681 FileSystem::Instance().Resolve(m_directory); 1682 break; 1683 } 1684 default: 1685 llvm_unreachable("Unimplemented option"); 1686 } 1687 return error; 1688 } 1689 1690 void OptionParsingStarting(ExecutionContext *execution_context) override{}; 1691 1692 llvm::ArrayRef<OptionDefinition> GetDefinitions() override { 1693 return llvm::makeArrayRef(g_process_trace_save_options); 1694 }; 1695 1696 FileSpec m_directory; 1697 }; 1698 1699 Options *GetOptions() override { return &m_options; } 1700 CommandObjectProcessTraceSave(CommandInterpreter &interpreter) 1701 : CommandObjectParsed( 1702 interpreter, "process trace save", 1703 "Save the trace of the current process in the specified directory. " 1704 "The directory will be created if needed. " 1705 "This will also create a file <directory>/trace.json with the main " 1706 "properties of the trace session, along with others files which " 1707 "contain the actual trace data. The trace.json file can be used " 1708 "later as input for the \"trace load\" command to load the trace " 1709 "in LLDB", 1710 "process trace save [<cmd-options>]", 1711 eCommandRequiresProcess | eCommandTryTargetAPILock | 1712 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused | 1713 eCommandProcessMustBeTraced) {} 1714 1715 ~CommandObjectProcessTraceSave() override = default; 1716 1717 protected: 1718 bool DoExecute(Args &command, CommandReturnObject &result) override { 1719 ProcessSP process_sp = m_exe_ctx.GetProcessSP(); 1720 1721 TraceSP trace_sp = process_sp->GetTarget().GetTrace(); 1722 1723 if (llvm::Error err = trace_sp->SaveLiveTraceToDisk(m_options.m_directory)) 1724 result.AppendError(toString(std::move(err))); 1725 else 1726 result.SetStatus(eReturnStatusSuccessFinishResult); 1727 1728 return result.Succeeded(); 1729 } 1730 1731 CommandOptions m_options; 1732 }; 1733 1734 // CommandObjectProcessTraceStop 1735 class CommandObjectProcessTraceStop : public CommandObjectParsed { 1736 public: 1737 CommandObjectProcessTraceStop(CommandInterpreter &interpreter) 1738 : CommandObjectParsed(interpreter, "process trace stop", 1739 "Stop tracing this process. This does not affect " 1740 "traces started with the " 1741 "\"thread trace start\" command.", 1742 "process trace stop", 1743 eCommandRequiresProcess | eCommandTryTargetAPILock | 1744 eCommandProcessMustBeLaunched | 1745 eCommandProcessMustBePaused | 1746 eCommandProcessMustBeTraced) {} 1747 1748 ~CommandObjectProcessTraceStop() override = default; 1749 1750 bool DoExecute(Args &command, CommandReturnObject &result) override { 1751 ProcessSP process_sp = m_exe_ctx.GetProcessSP(); 1752 1753 TraceSP trace_sp = process_sp->GetTarget().GetTrace(); 1754 1755 if (llvm::Error err = trace_sp->Stop()) 1756 result.AppendError(toString(std::move(err))); 1757 else 1758 result.SetStatus(eReturnStatusSuccessFinishResult); 1759 1760 return result.Succeeded(); 1761 } 1762 }; 1763 1764 // CommandObjectMultiwordProcessTrace 1765 class CommandObjectMultiwordProcessTrace : public CommandObjectMultiword { 1766 public: 1767 CommandObjectMultiwordProcessTrace(CommandInterpreter &interpreter) 1768 : CommandObjectMultiword( 1769 interpreter, "trace", "Commands for tracing the current process.", 1770 "process trace <subcommand> [<subcommand objects>]") { 1771 LoadSubCommand("save", CommandObjectSP( 1772 new CommandObjectProcessTraceSave(interpreter))); 1773 LoadSubCommand("start", CommandObjectSP(new CommandObjectProcessTraceStart( 1774 interpreter))); 1775 LoadSubCommand("stop", CommandObjectSP( 1776 new CommandObjectProcessTraceStop(interpreter))); 1777 } 1778 1779 ~CommandObjectMultiwordProcessTrace() override = default; 1780 }; 1781 1782 // CommandObjectMultiwordProcess 1783 1784 CommandObjectMultiwordProcess::CommandObjectMultiwordProcess( 1785 CommandInterpreter &interpreter) 1786 : CommandObjectMultiword( 1787 interpreter, "process", 1788 "Commands for interacting with processes on the current platform.", 1789 "process <subcommand> [<subcommand-options>]") { 1790 LoadSubCommand("attach", 1791 CommandObjectSP(new CommandObjectProcessAttach(interpreter))); 1792 LoadSubCommand("launch", 1793 CommandObjectSP(new CommandObjectProcessLaunch(interpreter))); 1794 LoadSubCommand("continue", CommandObjectSP(new CommandObjectProcessContinue( 1795 interpreter))); 1796 LoadSubCommand("connect", 1797 CommandObjectSP(new CommandObjectProcessConnect(interpreter))); 1798 LoadSubCommand("detach", 1799 CommandObjectSP(new CommandObjectProcessDetach(interpreter))); 1800 LoadSubCommand("load", 1801 CommandObjectSP(new CommandObjectProcessLoad(interpreter))); 1802 LoadSubCommand("unload", 1803 CommandObjectSP(new CommandObjectProcessUnload(interpreter))); 1804 LoadSubCommand("signal", 1805 CommandObjectSP(new CommandObjectProcessSignal(interpreter))); 1806 LoadSubCommand("handle", 1807 CommandObjectSP(new CommandObjectProcessHandle(interpreter))); 1808 LoadSubCommand("status", 1809 CommandObjectSP(new CommandObjectProcessStatus(interpreter))); 1810 LoadSubCommand("interrupt", CommandObjectSP(new CommandObjectProcessInterrupt( 1811 interpreter))); 1812 LoadSubCommand("kill", 1813 CommandObjectSP(new CommandObjectProcessKill(interpreter))); 1814 LoadSubCommand("plugin", 1815 CommandObjectSP(new CommandObjectProcessPlugin(interpreter))); 1816 LoadSubCommand("save-core", CommandObjectSP(new CommandObjectProcessSaveCore( 1817 interpreter))); 1818 LoadSubCommand( 1819 "trace", 1820 CommandObjectSP(new CommandObjectMultiwordProcessTrace(interpreter))); 1821 } 1822 1823 CommandObjectMultiwordProcess::~CommandObjectMultiwordProcess() = default; 1824