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