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