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