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