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