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