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