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 } 554 else 555 { 556 result.AppendError("no error returned from Target::Attach, and target has no process"); 557 result.SetStatus (eReturnStatusFailed); 558 } 559 } 560 else 561 { 562 result.AppendErrorWithFormat ("attach failed: %s\n", error.AsCString()); 563 result.SetStatus (eReturnStatusFailed); 564 } 565 566 if (!result.Succeeded()) 567 return false; 568 569 // Okay, we're done. Last step is to warn if the executable module has changed: 570 char new_path[PATH_MAX]; 571 ModuleSP new_exec_module_sp (target->GetExecutableModule()); 572 if (!old_exec_module_sp) 573 { 574 // We might not have a module if we attached to a raw pid... 575 if (new_exec_module_sp) 576 { 577 new_exec_module_sp->GetFileSpec().GetPath(new_path, PATH_MAX); 578 result.AppendMessageWithFormat("Executable module set to \"%s\".\n", new_path); 579 } 580 } 581 else if (old_exec_module_sp->GetFileSpec() != new_exec_module_sp->GetFileSpec()) 582 { 583 char old_path[PATH_MAX]; 584 585 old_exec_module_sp->GetFileSpec().GetPath (old_path, PATH_MAX); 586 new_exec_module_sp->GetFileSpec().GetPath (new_path, PATH_MAX); 587 588 result.AppendWarningWithFormat("Executable module changed from \"%s\" to \"%s\".\n", 589 old_path, new_path); 590 } 591 592 if (!old_arch_spec.IsValid()) 593 { 594 result.AppendMessageWithFormat ("Architecture set to: %s.\n", target->GetArchitecture().GetTriple().getTriple().c_str()); 595 } 596 else if (!old_arch_spec.IsExactMatch(target->GetArchitecture())) 597 { 598 result.AppendWarningWithFormat("Architecture changed from %s to %s.\n", 599 old_arch_spec.GetTriple().getTriple().c_str(), 600 target->GetArchitecture().GetTriple().getTriple().c_str()); 601 } 602 603 // This supports the use-case scenario of immediately continuing the process once attached. 604 if (m_options.attach_info.GetContinueOnceAttached()) 605 m_interpreter.HandleCommand("process continue", eLazyBoolNo, result); 606 607 return result.Succeeded(); 608 } 609 610 CommandOptions m_options; 611 }; 612 613 614 OptionDefinition 615 CommandObjectProcessAttach::CommandOptions::g_option_table[] = 616 { 617 { LLDB_OPT_SET_ALL, false, "continue",'c', OptionParser::eNoArgument, NULL, NULL, 0, eArgTypeNone, "Immediately continue the process once attached."}, 618 { LLDB_OPT_SET_ALL, false, "plugin", 'P', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."}, 619 { LLDB_OPT_SET_1, false, "pid", 'p', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypePid, "The process ID of an existing process to attach to."}, 620 { LLDB_OPT_SET_2, false, "name", 'n', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeProcessName, "The name of the process to attach to."}, 621 { LLDB_OPT_SET_2, false, "include-existing", 'i', OptionParser::eNoArgument, NULL, NULL, 0, eArgTypeNone, "Include existing processes when doing attach -w."}, 622 { LLDB_OPT_SET_2, false, "waitfor", 'w', OptionParser::eNoArgument, NULL, NULL, 0, eArgTypeNone, "Wait for the process with <process-name> to launch."}, 623 { 0, false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL } 624 }; 625 626 //------------------------------------------------------------------------- 627 // CommandObjectProcessContinue 628 //------------------------------------------------------------------------- 629 #pragma mark CommandObjectProcessContinue 630 631 class CommandObjectProcessContinue : public CommandObjectParsed 632 { 633 public: 634 635 CommandObjectProcessContinue (CommandInterpreter &interpreter) : 636 CommandObjectParsed (interpreter, 637 "process continue", 638 "Continue execution of all threads in the current process.", 639 "process continue", 640 eCommandRequiresProcess | 641 eCommandTryTargetAPILock | 642 eCommandProcessMustBeLaunched | 643 eCommandProcessMustBePaused ), 644 m_options(interpreter) 645 { 646 } 647 648 649 ~CommandObjectProcessContinue () override 650 { 651 } 652 653 protected: 654 655 class CommandOptions : public Options 656 { 657 public: 658 659 CommandOptions (CommandInterpreter &interpreter) : 660 Options(interpreter) 661 { 662 // Keep default values of all options in one place: OptionParsingStarting () 663 OptionParsingStarting (); 664 } 665 666 ~CommandOptions () override 667 { 668 } 669 670 Error 671 SetOptionValue (uint32_t option_idx, const char *option_arg) override 672 { 673 Error error; 674 const int short_option = m_getopt_table[option_idx].val; 675 bool success = false; 676 switch (short_option) 677 { 678 case 'i': 679 m_ignore = StringConvert::ToUInt32 (option_arg, 0, 0, &success); 680 if (!success) 681 error.SetErrorStringWithFormat ("invalid value for ignore option: \"%s\", should be a number.", option_arg); 682 break; 683 684 default: 685 error.SetErrorStringWithFormat("invalid short option character '%c'", short_option); 686 break; 687 } 688 return error; 689 } 690 691 void 692 OptionParsingStarting () override 693 { 694 m_ignore = 0; 695 } 696 697 const OptionDefinition* 698 GetDefinitions () override 699 { 700 return g_option_table; 701 } 702 703 // Options table: Required for subclasses of Options. 704 705 static OptionDefinition g_option_table[]; 706 707 uint32_t m_ignore; 708 }; 709 710 bool 711 DoExecute (Args& command, CommandReturnObject &result) override 712 { 713 Process *process = m_exe_ctx.GetProcessPtr(); 714 bool synchronous_execution = m_interpreter.GetSynchronous (); 715 StateType state = process->GetState(); 716 if (state == eStateStopped) 717 { 718 if (command.GetArgumentCount() != 0) 719 { 720 result.AppendErrorWithFormat ("The '%s' command does not take any arguments.\n", m_cmd_name.c_str()); 721 result.SetStatus (eReturnStatusFailed); 722 return false; 723 } 724 725 if (m_options.m_ignore > 0) 726 { 727 ThreadSP sel_thread_sp(process->GetThreadList().GetSelectedThread()); 728 if (sel_thread_sp) 729 { 730 StopInfoSP stop_info_sp = sel_thread_sp->GetStopInfo(); 731 if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint) 732 { 733 lldb::break_id_t bp_site_id = (lldb::break_id_t)stop_info_sp->GetValue(); 734 BreakpointSiteSP bp_site_sp(process->GetBreakpointSiteList().FindByID(bp_site_id)); 735 if (bp_site_sp) 736 { 737 const size_t num_owners = bp_site_sp->GetNumberOfOwners(); 738 for (size_t i = 0; i < num_owners; i++) 739 { 740 Breakpoint &bp_ref = bp_site_sp->GetOwnerAtIndex(i)->GetBreakpoint(); 741 if (!bp_ref.IsInternal()) 742 { 743 bp_ref.SetIgnoreCount(m_options.m_ignore); 744 } 745 } 746 } 747 } 748 } 749 } 750 751 { // Scope for thread list mutex: 752 Mutex::Locker locker (process->GetThreadList().GetMutex()); 753 const uint32_t num_threads = process->GetThreadList().GetSize(); 754 755 // Set the actions that the threads should each take when resuming 756 for (uint32_t idx=0; idx<num_threads; ++idx) 757 { 758 const bool override_suspend = false; 759 process->GetThreadList().GetThreadAtIndex(idx)->SetResumeState (eStateRunning, override_suspend); 760 } 761 } 762 763 const uint32_t iohandler_id = process->GetIOHandlerID(); 764 765 StreamString stream; 766 Error error; 767 if (synchronous_execution) 768 error = process->ResumeSynchronous (&stream); 769 else 770 error = process->Resume (); 771 772 if (error.Success()) 773 { 774 // There is a race condition where this thread will return up the call stack to the main command 775 // handler and show an (lldb) prompt before HandlePrivateEvent (from PrivateStateThread) has 776 // a chance to call PushProcessIOHandler(). 777 process->SyncIOHandler(iohandler_id, 2000); 778 779 result.AppendMessageWithFormat ("Process %" PRIu64 " resuming\n", process->GetID()); 780 if (synchronous_execution) 781 { 782 // If any state changed events had anything to say, add that to the result 783 if (stream.GetData()) 784 result.AppendMessage(stream.GetData()); 785 786 result.SetDidChangeProcessState (true); 787 result.SetStatus (eReturnStatusSuccessFinishNoResult); 788 } 789 else 790 { 791 result.SetStatus (eReturnStatusSuccessContinuingNoResult); 792 } 793 } 794 else 795 { 796 result.AppendErrorWithFormat("Failed to resume process: %s.\n", error.AsCString()); 797 result.SetStatus (eReturnStatusFailed); 798 } 799 } 800 else 801 { 802 result.AppendErrorWithFormat ("Process cannot be continued from its current state (%s).\n", 803 StateAsCString(state)); 804 result.SetStatus (eReturnStatusFailed); 805 } 806 return result.Succeeded(); 807 } 808 809 Options * 810 GetOptions () override 811 { 812 return &m_options; 813 } 814 815 CommandOptions m_options; 816 817 }; 818 819 OptionDefinition 820 CommandObjectProcessContinue::CommandOptions::g_option_table[] = 821 { 822 { LLDB_OPT_SET_ALL, false, "ignore-count",'i', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeUnsignedInteger, 823 "Ignore <N> crossings of the breakpoint (if it exists) for the currently selected thread."}, 824 { 0, false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL } 825 }; 826 827 //------------------------------------------------------------------------- 828 // CommandObjectProcessDetach 829 //------------------------------------------------------------------------- 830 #pragma mark CommandObjectProcessDetach 831 832 class CommandObjectProcessDetach : public CommandObjectParsed 833 { 834 public: 835 class CommandOptions : public Options 836 { 837 public: 838 839 CommandOptions (CommandInterpreter &interpreter) : 840 Options (interpreter) 841 { 842 OptionParsingStarting (); 843 } 844 845 ~CommandOptions () override 846 { 847 } 848 849 Error 850 SetOptionValue (uint32_t option_idx, const char *option_arg) override 851 { 852 Error error; 853 const int short_option = m_getopt_table[option_idx].val; 854 855 switch (short_option) 856 { 857 case 's': 858 bool tmp_result; 859 bool success; 860 tmp_result = Args::StringToBoolean(option_arg, false, &success); 861 if (!success) 862 error.SetErrorStringWithFormat("invalid boolean option: \"%s\"", option_arg); 863 else 864 { 865 if (tmp_result) 866 m_keep_stopped = eLazyBoolYes; 867 else 868 m_keep_stopped = eLazyBoolNo; 869 } 870 break; 871 default: 872 error.SetErrorStringWithFormat("invalid short option character '%c'", short_option); 873 break; 874 } 875 return error; 876 } 877 878 void 879 OptionParsingStarting () override 880 { 881 m_keep_stopped = eLazyBoolCalculate; 882 } 883 884 const OptionDefinition* 885 GetDefinitions () override 886 { 887 return g_option_table; 888 } 889 890 // Options table: Required for subclasses of Options. 891 892 static OptionDefinition g_option_table[]; 893 894 // Instance variables to hold the values for command options. 895 LazyBool m_keep_stopped; 896 }; 897 898 CommandObjectProcessDetach (CommandInterpreter &interpreter) : 899 CommandObjectParsed (interpreter, 900 "process detach", 901 "Detach from the current process being debugged.", 902 "process detach", 903 eCommandRequiresProcess | 904 eCommandTryTargetAPILock | 905 eCommandProcessMustBeLaunched), 906 m_options(interpreter) 907 { 908 } 909 910 ~CommandObjectProcessDetach () override 911 { 912 } 913 914 Options * 915 GetOptions () override 916 { 917 return &m_options; 918 } 919 920 921 protected: 922 bool 923 DoExecute (Args& command, CommandReturnObject &result) override 924 { 925 Process *process = m_exe_ctx.GetProcessPtr(); 926 // FIXME: This will be a Command Option: 927 bool keep_stopped; 928 if (m_options.m_keep_stopped == eLazyBoolCalculate) 929 { 930 // Check the process default: 931 if (process->GetDetachKeepsStopped()) 932 keep_stopped = true; 933 else 934 keep_stopped = false; 935 } 936 else if (m_options.m_keep_stopped == eLazyBoolYes) 937 keep_stopped = true; 938 else 939 keep_stopped = false; 940 941 Error error (process->Detach(keep_stopped)); 942 if (error.Success()) 943 { 944 result.SetStatus (eReturnStatusSuccessFinishResult); 945 } 946 else 947 { 948 result.AppendErrorWithFormat ("Detach failed: %s\n", error.AsCString()); 949 result.SetStatus (eReturnStatusFailed); 950 return false; 951 } 952 return result.Succeeded(); 953 } 954 955 CommandOptions m_options; 956 }; 957 958 OptionDefinition 959 CommandObjectProcessDetach::CommandOptions::g_option_table[] = 960 { 961 { 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)." }, 962 { 0, false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL } 963 }; 964 965 //------------------------------------------------------------------------- 966 // CommandObjectProcessConnect 967 //------------------------------------------------------------------------- 968 #pragma mark CommandObjectProcessConnect 969 970 class CommandObjectProcessConnect : public CommandObjectParsed 971 { 972 public: 973 974 class CommandOptions : public Options 975 { 976 public: 977 978 CommandOptions (CommandInterpreter &interpreter) : 979 Options(interpreter) 980 { 981 // Keep default values of all options in one place: OptionParsingStarting () 982 OptionParsingStarting (); 983 } 984 985 ~CommandOptions () override 986 { 987 } 988 989 Error 990 SetOptionValue (uint32_t option_idx, const char *option_arg) override 991 { 992 Error error; 993 const int short_option = m_getopt_table[option_idx].val; 994 995 switch (short_option) 996 { 997 case 'p': 998 plugin_name.assign (option_arg); 999 break; 1000 1001 default: 1002 error.SetErrorStringWithFormat("invalid short option character '%c'", short_option); 1003 break; 1004 } 1005 return error; 1006 } 1007 1008 void 1009 OptionParsingStarting () override 1010 { 1011 plugin_name.clear(); 1012 } 1013 1014 const OptionDefinition* 1015 GetDefinitions () override 1016 { 1017 return g_option_table; 1018 } 1019 1020 // Options table: Required for subclasses of Options. 1021 1022 static OptionDefinition g_option_table[]; 1023 1024 // Instance variables to hold the values for command options. 1025 1026 std::string plugin_name; 1027 }; 1028 1029 CommandObjectProcessConnect (CommandInterpreter &interpreter) : 1030 CommandObjectParsed (interpreter, 1031 "process connect", 1032 "Connect to a remote debug service.", 1033 "process connect <remote-url>", 1034 0), 1035 m_options (interpreter) 1036 { 1037 } 1038 1039 ~CommandObjectProcessConnect () override 1040 { 1041 } 1042 1043 1044 Options * 1045 GetOptions () override 1046 { 1047 return &m_options; 1048 } 1049 1050 protected: 1051 bool 1052 DoExecute (Args& command, CommandReturnObject &result) override 1053 { 1054 1055 TargetSP target_sp (m_interpreter.GetDebugger().GetSelectedTarget()); 1056 Error error; 1057 Process *process = m_exe_ctx.GetProcessPtr(); 1058 if (process) 1059 { 1060 if (process->IsAlive()) 1061 { 1062 result.AppendErrorWithFormat ("Process %" PRIu64 " is currently being debugged, kill the process before connecting.\n", 1063 process->GetID()); 1064 result.SetStatus (eReturnStatusFailed); 1065 return false; 1066 } 1067 } 1068 1069 if (!target_sp) 1070 { 1071 // If there isn't a current target create one. 1072 1073 error = m_interpreter.GetDebugger().GetTargetList().CreateTarget (m_interpreter.GetDebugger(), 1074 NULL, 1075 NULL, 1076 false, 1077 NULL, // No platform options 1078 target_sp); 1079 if (!target_sp || error.Fail()) 1080 { 1081 result.AppendError(error.AsCString("Error creating target")); 1082 result.SetStatus (eReturnStatusFailed); 1083 return false; 1084 } 1085 m_interpreter.GetDebugger().GetTargetList().SetSelectedTarget(target_sp.get()); 1086 } 1087 1088 if (command.GetArgumentCount() == 1) 1089 { 1090 const char *plugin_name = NULL; 1091 if (!m_options.plugin_name.empty()) 1092 plugin_name = m_options.plugin_name.c_str(); 1093 1094 const char *remote_url = command.GetArgumentAtIndex(0); 1095 process = target_sp->CreateProcess (m_interpreter.GetDebugger().GetListener(), plugin_name, NULL).get(); 1096 1097 if (process) 1098 { 1099 error = process->ConnectRemote (process->GetTarget().GetDebugger().GetOutputFile().get(), remote_url); 1100 1101 if (error.Fail()) 1102 { 1103 result.AppendError(error.AsCString("Remote connect failed")); 1104 result.SetStatus (eReturnStatusFailed); 1105 target_sp->DeleteCurrentProcess(); 1106 return false; 1107 } 1108 } 1109 else 1110 { 1111 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", 1112 remote_url); 1113 result.SetStatus (eReturnStatusFailed); 1114 } 1115 } 1116 else 1117 { 1118 result.AppendErrorWithFormat ("'%s' takes exactly one argument:\nUsage: %s\n", 1119 m_cmd_name.c_str(), 1120 m_cmd_syntax.c_str()); 1121 result.SetStatus (eReturnStatusFailed); 1122 } 1123 return result.Succeeded(); 1124 } 1125 1126 CommandOptions m_options; 1127 }; 1128 1129 OptionDefinition 1130 CommandObjectProcessConnect::CommandOptions::g_option_table[] = 1131 { 1132 { LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."}, 1133 { 0, false, NULL, 0 , 0, NULL, NULL, 0, eArgTypeNone, NULL } 1134 }; 1135 1136 //------------------------------------------------------------------------- 1137 // CommandObjectProcessPlugin 1138 //------------------------------------------------------------------------- 1139 #pragma mark CommandObjectProcessPlugin 1140 1141 class CommandObjectProcessPlugin : public CommandObjectProxy 1142 { 1143 public: 1144 1145 CommandObjectProcessPlugin (CommandInterpreter &interpreter) : 1146 CommandObjectProxy (interpreter, 1147 "process plugin", 1148 "Send a custom command to the current process plug-in.", 1149 "process plugin <args>", 1150 0) 1151 { 1152 } 1153 1154 ~CommandObjectProcessPlugin () override 1155 { 1156 } 1157 1158 CommandObject * 1159 GetProxyCommandObject() override 1160 { 1161 Process *process = m_interpreter.GetExecutionContext().GetProcessPtr(); 1162 if (process) 1163 return process->GetPluginCommandObject(); 1164 return NULL; 1165 } 1166 }; 1167 1168 1169 //------------------------------------------------------------------------- 1170 // CommandObjectProcessLoad 1171 //------------------------------------------------------------------------- 1172 #pragma mark CommandObjectProcessLoad 1173 1174 class CommandObjectProcessLoad : public CommandObjectParsed 1175 { 1176 public: 1177 1178 CommandObjectProcessLoad (CommandInterpreter &interpreter) : 1179 CommandObjectParsed (interpreter, 1180 "process load", 1181 "Load a shared library into the current process.", 1182 "process load <filename> [<filename> ...]", 1183 eCommandRequiresProcess | 1184 eCommandTryTargetAPILock | 1185 eCommandProcessMustBeLaunched | 1186 eCommandProcessMustBePaused ) 1187 { 1188 } 1189 1190 ~CommandObjectProcessLoad () override 1191 { 1192 } 1193 1194 protected: 1195 bool 1196 DoExecute (Args& command, CommandReturnObject &result) override 1197 { 1198 Process *process = m_exe_ctx.GetProcessPtr(); 1199 1200 const size_t argc = command.GetArgumentCount(); 1201 1202 for (uint32_t i=0; i<argc; ++i) 1203 { 1204 Error error; 1205 const char *image_path = command.GetArgumentAtIndex(i); 1206 FileSpec image_spec (image_path, false); 1207 process->GetTarget().GetPlatform()->ResolveRemotePath(image_spec, image_spec); 1208 uint32_t image_token = process->LoadImage(image_spec, error); 1209 if (image_token != LLDB_INVALID_IMAGE_TOKEN) 1210 { 1211 result.AppendMessageWithFormat ("Loading \"%s\"...ok\nImage %u loaded.\n", image_path, image_token); 1212 result.SetStatus (eReturnStatusSuccessFinishResult); 1213 } 1214 else 1215 { 1216 result.AppendErrorWithFormat ("failed to load '%s': %s", image_path, error.AsCString()); 1217 result.SetStatus (eReturnStatusFailed); 1218 } 1219 } 1220 return result.Succeeded(); 1221 } 1222 }; 1223 1224 1225 //------------------------------------------------------------------------- 1226 // CommandObjectProcessUnload 1227 //------------------------------------------------------------------------- 1228 #pragma mark CommandObjectProcessUnload 1229 1230 class CommandObjectProcessUnload : public CommandObjectParsed 1231 { 1232 public: 1233 1234 CommandObjectProcessUnload (CommandInterpreter &interpreter) : 1235 CommandObjectParsed (interpreter, 1236 "process unload", 1237 "Unload a shared library from the current process using the index returned by a previous call to \"process load\".", 1238 "process unload <index>", 1239 eCommandRequiresProcess | 1240 eCommandTryTargetAPILock | 1241 eCommandProcessMustBeLaunched | 1242 eCommandProcessMustBePaused ) 1243 { 1244 } 1245 1246 ~CommandObjectProcessUnload () override 1247 { 1248 } 1249 1250 protected: 1251 bool 1252 DoExecute (Args& command, CommandReturnObject &result) override 1253 { 1254 Process *process = m_exe_ctx.GetProcessPtr(); 1255 1256 const size_t argc = command.GetArgumentCount(); 1257 1258 for (uint32_t i=0; i<argc; ++i) 1259 { 1260 const char *image_token_cstr = command.GetArgumentAtIndex(i); 1261 uint32_t image_token = StringConvert::ToUInt32(image_token_cstr, LLDB_INVALID_IMAGE_TOKEN, 0); 1262 if (image_token == LLDB_INVALID_IMAGE_TOKEN) 1263 { 1264 result.AppendErrorWithFormat ("invalid image index argument '%s'", image_token_cstr); 1265 result.SetStatus (eReturnStatusFailed); 1266 break; 1267 } 1268 else 1269 { 1270 Error error (process->UnloadImage(image_token)); 1271 if (error.Success()) 1272 { 1273 result.AppendMessageWithFormat ("Unloading shared library with index %u...ok\n", image_token); 1274 result.SetStatus (eReturnStatusSuccessFinishResult); 1275 } 1276 else 1277 { 1278 result.AppendErrorWithFormat ("failed to unload image: %s", error.AsCString()); 1279 result.SetStatus (eReturnStatusFailed); 1280 break; 1281 } 1282 } 1283 } 1284 return result.Succeeded(); 1285 } 1286 }; 1287 1288 //------------------------------------------------------------------------- 1289 // CommandObjectProcessSignal 1290 //------------------------------------------------------------------------- 1291 #pragma mark CommandObjectProcessSignal 1292 1293 class CommandObjectProcessSignal : public CommandObjectParsed 1294 { 1295 public: 1296 1297 CommandObjectProcessSignal (CommandInterpreter &interpreter) : 1298 CommandObjectParsed (interpreter, 1299 "process signal", 1300 "Send a UNIX signal to the current process being debugged.", 1301 NULL, 1302 eCommandRequiresProcess | eCommandTryTargetAPILock) 1303 { 1304 CommandArgumentEntry arg; 1305 CommandArgumentData signal_arg; 1306 1307 // Define the first (and only) variant of this arg. 1308 signal_arg.arg_type = eArgTypeUnixSignal; 1309 signal_arg.arg_repetition = eArgRepeatPlain; 1310 1311 // There is only one variant this argument could be; put it into the argument entry. 1312 arg.push_back (signal_arg); 1313 1314 // Push the data for the first argument into the m_arguments vector. 1315 m_arguments.push_back (arg); 1316 } 1317 1318 ~CommandObjectProcessSignal () override 1319 { 1320 } 1321 1322 protected: 1323 bool 1324 DoExecute (Args& command, CommandReturnObject &result) override 1325 { 1326 Process *process = m_exe_ctx.GetProcessPtr(); 1327 1328 if (command.GetArgumentCount() == 1) 1329 { 1330 int signo = LLDB_INVALID_SIGNAL_NUMBER; 1331 1332 const char *signal_name = command.GetArgumentAtIndex(0); 1333 if (::isxdigit (signal_name[0])) 1334 signo = StringConvert::ToSInt32(signal_name, LLDB_INVALID_SIGNAL_NUMBER, 0); 1335 else 1336 signo = process->GetUnixSignals()->GetSignalNumberFromName(signal_name); 1337 1338 if (signo == LLDB_INVALID_SIGNAL_NUMBER) 1339 { 1340 result.AppendErrorWithFormat ("Invalid signal argument '%s'.\n", command.GetArgumentAtIndex(0)); 1341 result.SetStatus (eReturnStatusFailed); 1342 } 1343 else 1344 { 1345 Error error (process->Signal (signo)); 1346 if (error.Success()) 1347 { 1348 result.SetStatus (eReturnStatusSuccessFinishResult); 1349 } 1350 else 1351 { 1352 result.AppendErrorWithFormat ("Failed to send signal %i: %s\n", signo, error.AsCString()); 1353 result.SetStatus (eReturnStatusFailed); 1354 } 1355 } 1356 } 1357 else 1358 { 1359 result.AppendErrorWithFormat("'%s' takes exactly one signal number argument:\nUsage: %s\n", m_cmd_name.c_str(), 1360 m_cmd_syntax.c_str()); 1361 result.SetStatus (eReturnStatusFailed); 1362 } 1363 return result.Succeeded(); 1364 } 1365 }; 1366 1367 1368 //------------------------------------------------------------------------- 1369 // CommandObjectProcessInterrupt 1370 //------------------------------------------------------------------------- 1371 #pragma mark CommandObjectProcessInterrupt 1372 1373 class CommandObjectProcessInterrupt : public CommandObjectParsed 1374 { 1375 public: 1376 1377 1378 CommandObjectProcessInterrupt (CommandInterpreter &interpreter) : 1379 CommandObjectParsed (interpreter, 1380 "process interrupt", 1381 "Interrupt the current process being debugged.", 1382 "process interrupt", 1383 eCommandRequiresProcess | 1384 eCommandTryTargetAPILock | 1385 eCommandProcessMustBeLaunched) 1386 { 1387 } 1388 1389 ~CommandObjectProcessInterrupt () override 1390 { 1391 } 1392 1393 protected: 1394 bool 1395 DoExecute (Args& command, CommandReturnObject &result) override 1396 { 1397 Process *process = m_exe_ctx.GetProcessPtr(); 1398 if (process == NULL) 1399 { 1400 result.AppendError ("no process to halt"); 1401 result.SetStatus (eReturnStatusFailed); 1402 return false; 1403 } 1404 1405 if (command.GetArgumentCount() == 0) 1406 { 1407 bool clear_thread_plans = true; 1408 Error error(process->Halt (clear_thread_plans)); 1409 if (error.Success()) 1410 { 1411 result.SetStatus (eReturnStatusSuccessFinishResult); 1412 } 1413 else 1414 { 1415 result.AppendErrorWithFormat ("Failed to halt process: %s\n", error.AsCString()); 1416 result.SetStatus (eReturnStatusFailed); 1417 } 1418 } 1419 else 1420 { 1421 result.AppendErrorWithFormat("'%s' takes no arguments:\nUsage: %s\n", 1422 m_cmd_name.c_str(), 1423 m_cmd_syntax.c_str()); 1424 result.SetStatus (eReturnStatusFailed); 1425 } 1426 return result.Succeeded(); 1427 } 1428 }; 1429 1430 //------------------------------------------------------------------------- 1431 // CommandObjectProcessKill 1432 //------------------------------------------------------------------------- 1433 #pragma mark CommandObjectProcessKill 1434 1435 class CommandObjectProcessKill : public CommandObjectParsed 1436 { 1437 public: 1438 1439 CommandObjectProcessKill (CommandInterpreter &interpreter) : 1440 CommandObjectParsed (interpreter, 1441 "process kill", 1442 "Terminate the current process being debugged.", 1443 "process kill", 1444 eCommandRequiresProcess | 1445 eCommandTryTargetAPILock | 1446 eCommandProcessMustBeLaunched) 1447 { 1448 } 1449 1450 ~CommandObjectProcessKill () override 1451 { 1452 } 1453 1454 protected: 1455 bool 1456 DoExecute (Args& command, CommandReturnObject &result) override 1457 { 1458 Process *process = m_exe_ctx.GetProcessPtr(); 1459 if (process == NULL) 1460 { 1461 result.AppendError ("no process to kill"); 1462 result.SetStatus (eReturnStatusFailed); 1463 return false; 1464 } 1465 1466 if (command.GetArgumentCount() == 0) 1467 { 1468 Error error (process->Destroy(true)); 1469 if (error.Success()) 1470 { 1471 result.SetStatus (eReturnStatusSuccessFinishResult); 1472 } 1473 else 1474 { 1475 result.AppendErrorWithFormat ("Failed to kill process: %s\n", error.AsCString()); 1476 result.SetStatus (eReturnStatusFailed); 1477 } 1478 } 1479 else 1480 { 1481 result.AppendErrorWithFormat("'%s' takes no arguments:\nUsage: %s\n", 1482 m_cmd_name.c_str(), 1483 m_cmd_syntax.c_str()); 1484 result.SetStatus (eReturnStatusFailed); 1485 } 1486 return result.Succeeded(); 1487 } 1488 }; 1489 1490 //------------------------------------------------------------------------- 1491 // CommandObjectProcessSaveCore 1492 //------------------------------------------------------------------------- 1493 #pragma mark CommandObjectProcessSaveCore 1494 1495 class CommandObjectProcessSaveCore : public CommandObjectParsed 1496 { 1497 public: 1498 1499 CommandObjectProcessSaveCore (CommandInterpreter &interpreter) : 1500 CommandObjectParsed (interpreter, 1501 "process save-core", 1502 "Save the current process as a core file using an appropriate file type.", 1503 "process save-core FILE", 1504 eCommandRequiresProcess | 1505 eCommandTryTargetAPILock | 1506 eCommandProcessMustBeLaunched) 1507 { 1508 } 1509 1510 ~CommandObjectProcessSaveCore () override 1511 { 1512 } 1513 1514 protected: 1515 bool 1516 DoExecute (Args& command, 1517 CommandReturnObject &result) override 1518 { 1519 ProcessSP process_sp = m_exe_ctx.GetProcessSP(); 1520 if (process_sp) 1521 { 1522 if (command.GetArgumentCount() == 1) 1523 { 1524 FileSpec output_file(command.GetArgumentAtIndex(0), false); 1525 Error error = PluginManager::SaveCore(process_sp, output_file); 1526 if (error.Success()) 1527 { 1528 result.SetStatus (eReturnStatusSuccessFinishResult); 1529 } 1530 else 1531 { 1532 result.AppendErrorWithFormat ("Failed to save core file for process: %s\n", error.AsCString()); 1533 result.SetStatus (eReturnStatusFailed); 1534 } 1535 } 1536 else 1537 { 1538 result.AppendErrorWithFormat ("'%s' takes one arguments:\nUsage: %s\n", 1539 m_cmd_name.c_str(), 1540 m_cmd_syntax.c_str()); 1541 result.SetStatus (eReturnStatusFailed); 1542 } 1543 } 1544 else 1545 { 1546 result.AppendError ("invalid process"); 1547 result.SetStatus (eReturnStatusFailed); 1548 return false; 1549 } 1550 1551 return result.Succeeded(); 1552 } 1553 }; 1554 1555 //------------------------------------------------------------------------- 1556 // CommandObjectProcessStatus 1557 //------------------------------------------------------------------------- 1558 #pragma mark CommandObjectProcessStatus 1559 1560 class CommandObjectProcessStatus : public CommandObjectParsed 1561 { 1562 public: 1563 CommandObjectProcessStatus (CommandInterpreter &interpreter) : 1564 CommandObjectParsed (interpreter, 1565 "process status", 1566 "Show the current status and location of executing process.", 1567 "process status", 1568 eCommandRequiresProcess | eCommandTryTargetAPILock) 1569 { 1570 } 1571 1572 ~CommandObjectProcessStatus() override 1573 { 1574 } 1575 1576 1577 bool 1578 DoExecute (Args& command, CommandReturnObject &result) override 1579 { 1580 Stream &strm = result.GetOutputStream(); 1581 result.SetStatus (eReturnStatusSuccessFinishNoResult); 1582 // No need to check "process" for validity as eCommandRequiresProcess ensures it is valid 1583 Process *process = m_exe_ctx.GetProcessPtr(); 1584 const bool only_threads_with_stop_reason = true; 1585 const uint32_t start_frame = 0; 1586 const uint32_t num_frames = 1; 1587 const uint32_t num_frames_with_source = 1; 1588 process->GetStatus(strm); 1589 process->GetThreadStatus (strm, 1590 only_threads_with_stop_reason, 1591 start_frame, 1592 num_frames, 1593 num_frames_with_source); 1594 return result.Succeeded(); 1595 } 1596 }; 1597 1598 //------------------------------------------------------------------------- 1599 // CommandObjectProcessHandle 1600 //------------------------------------------------------------------------- 1601 #pragma mark CommandObjectProcessHandle 1602 1603 class CommandObjectProcessHandle : public CommandObjectParsed 1604 { 1605 public: 1606 1607 class CommandOptions : public Options 1608 { 1609 public: 1610 1611 CommandOptions (CommandInterpreter &interpreter) : 1612 Options (interpreter) 1613 { 1614 OptionParsingStarting (); 1615 } 1616 1617 ~CommandOptions () override 1618 { 1619 } 1620 1621 Error 1622 SetOptionValue (uint32_t option_idx, const char *option_arg) override 1623 { 1624 Error error; 1625 const int short_option = m_getopt_table[option_idx].val; 1626 1627 switch (short_option) 1628 { 1629 case 's': 1630 stop = option_arg; 1631 break; 1632 case 'n': 1633 notify = option_arg; 1634 break; 1635 case 'p': 1636 pass = option_arg; 1637 break; 1638 default: 1639 error.SetErrorStringWithFormat("invalid short option character '%c'", short_option); 1640 break; 1641 } 1642 return error; 1643 } 1644 1645 void 1646 OptionParsingStarting () override 1647 { 1648 stop.clear(); 1649 notify.clear(); 1650 pass.clear(); 1651 } 1652 1653 const OptionDefinition* 1654 GetDefinitions () override 1655 { 1656 return g_option_table; 1657 } 1658 1659 // Options table: Required for subclasses of Options. 1660 1661 static OptionDefinition g_option_table[]; 1662 1663 // Instance variables to hold the values for command options. 1664 1665 std::string stop; 1666 std::string notify; 1667 std::string pass; 1668 }; 1669 1670 1671 CommandObjectProcessHandle (CommandInterpreter &interpreter) : 1672 CommandObjectParsed (interpreter, 1673 "process handle", 1674 "Show or update what the process and debugger should do with various signals received from the OS.", 1675 NULL), 1676 m_options (interpreter) 1677 { 1678 SetHelpLong ("\nIf no signals are specified, update them all. If no update " 1679 "option is specified, list the current values."); 1680 CommandArgumentEntry arg; 1681 CommandArgumentData signal_arg; 1682 1683 signal_arg.arg_type = eArgTypeUnixSignal; 1684 signal_arg.arg_repetition = eArgRepeatStar; 1685 1686 arg.push_back (signal_arg); 1687 1688 m_arguments.push_back (arg); 1689 } 1690 1691 ~CommandObjectProcessHandle () override 1692 { 1693 } 1694 1695 Options * 1696 GetOptions () override 1697 { 1698 return &m_options; 1699 } 1700 1701 bool 1702 VerifyCommandOptionValue (const std::string &option, int &real_value) 1703 { 1704 bool okay = true; 1705 1706 bool success = false; 1707 bool tmp_value = Args::StringToBoolean (option.c_str(), false, &success); 1708 1709 if (success && tmp_value) 1710 real_value = 1; 1711 else if (success && !tmp_value) 1712 real_value = 0; 1713 else 1714 { 1715 // If the value isn't 'true' or 'false', it had better be 0 or 1. 1716 real_value = StringConvert::ToUInt32 (option.c_str(), 3); 1717 if (real_value != 0 && real_value != 1) 1718 okay = false; 1719 } 1720 1721 return okay; 1722 } 1723 1724 void 1725 PrintSignalHeader (Stream &str) 1726 { 1727 str.Printf ("NAME PASS STOP NOTIFY\n"); 1728 str.Printf ("=========== ===== ===== ======\n"); 1729 } 1730 1731 void 1732 PrintSignal(Stream &str, int32_t signo, const char *sig_name, const UnixSignalsSP &signals_sp) 1733 { 1734 bool stop; 1735 bool suppress; 1736 bool notify; 1737 1738 str.Printf ("%-11s ", sig_name); 1739 if (signals_sp->GetSignalInfo(signo, suppress, stop, notify)) 1740 { 1741 bool pass = !suppress; 1742 str.Printf ("%s %s %s", 1743 (pass ? "true " : "false"), 1744 (stop ? "true " : "false"), 1745 (notify ? "true " : "false")); 1746 } 1747 str.Printf ("\n"); 1748 } 1749 1750 void 1751 PrintSignalInformation(Stream &str, Args &signal_args, int num_valid_signals, const UnixSignalsSP &signals_sp) 1752 { 1753 PrintSignalHeader (str); 1754 1755 if (num_valid_signals > 0) 1756 { 1757 size_t num_args = signal_args.GetArgumentCount(); 1758 for (size_t i = 0; i < num_args; ++i) 1759 { 1760 int32_t signo = signals_sp->GetSignalNumberFromName(signal_args.GetArgumentAtIndex(i)); 1761 if (signo != LLDB_INVALID_SIGNAL_NUMBER) 1762 PrintSignal (str, signo, signal_args.GetArgumentAtIndex (i), signals_sp); 1763 } 1764 } 1765 else // Print info for ALL signals 1766 { 1767 int32_t signo = signals_sp->GetFirstSignalNumber(); 1768 while (signo != LLDB_INVALID_SIGNAL_NUMBER) 1769 { 1770 PrintSignal(str, signo, signals_sp->GetSignalAsCString(signo), signals_sp); 1771 signo = signals_sp->GetNextSignalNumber(signo); 1772 } 1773 } 1774 } 1775 1776 protected: 1777 bool 1778 DoExecute (Args &signal_args, CommandReturnObject &result) override 1779 { 1780 TargetSP target_sp = m_interpreter.GetDebugger().GetSelectedTarget(); 1781 1782 if (!target_sp) 1783 { 1784 result.AppendError ("No current target;" 1785 " cannot handle signals until you have a valid target and process.\n"); 1786 result.SetStatus (eReturnStatusFailed); 1787 return false; 1788 } 1789 1790 ProcessSP process_sp = target_sp->GetProcessSP(); 1791 1792 if (!process_sp) 1793 { 1794 result.AppendError ("No current process; cannot handle signals until you have a valid process.\n"); 1795 result.SetStatus (eReturnStatusFailed); 1796 return false; 1797 } 1798 1799 int stop_action = -1; // -1 means leave the current setting alone 1800 int pass_action = -1; // -1 means leave the current setting alone 1801 int notify_action = -1; // -1 means leave the current setting alone 1802 1803 if (! m_options.stop.empty() 1804 && ! VerifyCommandOptionValue (m_options.stop, stop_action)) 1805 { 1806 result.AppendError ("Invalid argument for command option --stop; must be true or false.\n"); 1807 result.SetStatus (eReturnStatusFailed); 1808 return false; 1809 } 1810 1811 if (! m_options.notify.empty() 1812 && ! VerifyCommandOptionValue (m_options.notify, notify_action)) 1813 { 1814 result.AppendError ("Invalid argument for command option --notify; must be true or false.\n"); 1815 result.SetStatus (eReturnStatusFailed); 1816 return false; 1817 } 1818 1819 if (! m_options.pass.empty() 1820 && ! VerifyCommandOptionValue (m_options.pass, pass_action)) 1821 { 1822 result.AppendError ("Invalid argument for command option --pass; must be true or false.\n"); 1823 result.SetStatus (eReturnStatusFailed); 1824 return false; 1825 } 1826 1827 size_t num_args = signal_args.GetArgumentCount(); 1828 UnixSignalsSP signals_sp = process_sp->GetUnixSignals(); 1829 int num_signals_set = 0; 1830 1831 if (num_args > 0) 1832 { 1833 for (size_t i = 0; i < num_args; ++i) 1834 { 1835 int32_t signo = signals_sp->GetSignalNumberFromName(signal_args.GetArgumentAtIndex(i)); 1836 if (signo != LLDB_INVALID_SIGNAL_NUMBER) 1837 { 1838 // Casting the actions as bools here should be okay, because VerifyCommandOptionValue guarantees 1839 // the value is either 0 or 1. 1840 if (stop_action != -1) 1841 signals_sp->SetShouldStop(signo, stop_action); 1842 if (pass_action != -1) 1843 { 1844 bool suppress = !pass_action; 1845 signals_sp->SetShouldSuppress(signo, suppress); 1846 } 1847 if (notify_action != -1) 1848 signals_sp->SetShouldNotify(signo, notify_action); 1849 ++num_signals_set; 1850 } 1851 else 1852 { 1853 result.AppendErrorWithFormat ("Invalid signal name '%s'\n", signal_args.GetArgumentAtIndex (i)); 1854 } 1855 } 1856 } 1857 else 1858 { 1859 // No signal specified, if any command options were specified, update ALL signals. 1860 if ((notify_action != -1) || (stop_action != -1) || (pass_action != -1)) 1861 { 1862 if (m_interpreter.Confirm ("Do you really want to update all the signals?", false)) 1863 { 1864 int32_t signo = signals_sp->GetFirstSignalNumber(); 1865 while (signo != LLDB_INVALID_SIGNAL_NUMBER) 1866 { 1867 if (notify_action != -1) 1868 signals_sp->SetShouldNotify(signo, notify_action); 1869 if (stop_action != -1) 1870 signals_sp->SetShouldStop(signo, stop_action); 1871 if (pass_action != -1) 1872 { 1873 bool suppress = !pass_action; 1874 signals_sp->SetShouldSuppress(signo, suppress); 1875 } 1876 signo = signals_sp->GetNextSignalNumber(signo); 1877 } 1878 } 1879 } 1880 } 1881 1882 PrintSignalInformation (result.GetOutputStream(), signal_args, num_signals_set, signals_sp); 1883 1884 if (num_signals_set > 0) 1885 result.SetStatus (eReturnStatusSuccessFinishNoResult); 1886 else 1887 result.SetStatus (eReturnStatusFailed); 1888 1889 return result.Succeeded(); 1890 } 1891 1892 CommandOptions m_options; 1893 }; 1894 1895 OptionDefinition 1896 CommandObjectProcessHandle::CommandOptions::g_option_table[] = 1897 { 1898 { 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." }, 1899 { 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." }, 1900 { LLDB_OPT_SET_1, false, "pass", 'p', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeBoolean, "Whether or not the signal should be passed to the process." }, 1901 { 0, false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL } 1902 }; 1903 1904 //------------------------------------------------------------------------- 1905 // CommandObjectMultiwordProcess 1906 //------------------------------------------------------------------------- 1907 1908 CommandObjectMultiwordProcess::CommandObjectMultiwordProcess (CommandInterpreter &interpreter) : 1909 CommandObjectMultiword (interpreter, 1910 "process", 1911 "A set of commands for operating on a process.", 1912 "process <subcommand> [<subcommand-options>]") 1913 { 1914 LoadSubCommand ("attach", CommandObjectSP (new CommandObjectProcessAttach (interpreter))); 1915 LoadSubCommand ("launch", CommandObjectSP (new CommandObjectProcessLaunch (interpreter))); 1916 LoadSubCommand ("continue", CommandObjectSP (new CommandObjectProcessContinue (interpreter))); 1917 LoadSubCommand ("connect", CommandObjectSP (new CommandObjectProcessConnect (interpreter))); 1918 LoadSubCommand ("detach", CommandObjectSP (new CommandObjectProcessDetach (interpreter))); 1919 LoadSubCommand ("load", CommandObjectSP (new CommandObjectProcessLoad (interpreter))); 1920 LoadSubCommand ("unload", CommandObjectSP (new CommandObjectProcessUnload (interpreter))); 1921 LoadSubCommand ("signal", CommandObjectSP (new CommandObjectProcessSignal (interpreter))); 1922 LoadSubCommand ("handle", CommandObjectSP (new CommandObjectProcessHandle (interpreter))); 1923 LoadSubCommand ("status", CommandObjectSP (new CommandObjectProcessStatus (interpreter))); 1924 LoadSubCommand ("interrupt", CommandObjectSP (new CommandObjectProcessInterrupt (interpreter))); 1925 LoadSubCommand ("kill", CommandObjectSP (new CommandObjectProcessKill (interpreter))); 1926 LoadSubCommand ("plugin", CommandObjectSP (new CommandObjectProcessPlugin (interpreter))); 1927 LoadSubCommand ("save-core", CommandObjectSP (new CommandObjectProcessSaveCore (interpreter))); 1928 } 1929 1930 CommandObjectMultiwordProcess::~CommandObjectMultiwordProcess () 1931 { 1932 } 1933 1934