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