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 class CommandOptions : public Options 1178 { 1179 public: 1180 CommandOptions (CommandInterpreter &interpreter) : 1181 Options(interpreter) 1182 { 1183 // Keep default values of all options in one place: OptionParsingStarting () 1184 OptionParsingStarting (); 1185 } 1186 1187 ~CommandOptions () override = default; 1188 1189 Error 1190 SetOptionValue (uint32_t option_idx, const char *option_arg) override 1191 { 1192 Error error; 1193 const int short_option = m_getopt_table[option_idx].val; 1194 switch (short_option) 1195 { 1196 case 'i': 1197 do_install = true; 1198 if (option_arg && option_arg[0]) 1199 install_path.SetFile(option_arg, false); 1200 break; 1201 default: 1202 error.SetErrorStringWithFormat("invalid short option character '%c'", short_option); 1203 break; 1204 } 1205 return error; 1206 } 1207 1208 void 1209 OptionParsingStarting () override 1210 { 1211 do_install = false; 1212 install_path.Clear(); 1213 } 1214 1215 const OptionDefinition* 1216 GetDefinitions () override 1217 { 1218 return g_option_table; 1219 } 1220 1221 // Options table: Required for subclasses of Options. 1222 static OptionDefinition g_option_table[]; 1223 1224 // Instance variables to hold the values for command options. 1225 bool do_install; 1226 FileSpec install_path; 1227 }; 1228 1229 CommandObjectProcessLoad (CommandInterpreter &interpreter) : 1230 CommandObjectParsed (interpreter, 1231 "process load", 1232 "Load a shared library into the current process.", 1233 "process load <filename> [<filename> ...]", 1234 eCommandRequiresProcess | 1235 eCommandTryTargetAPILock | 1236 eCommandProcessMustBeLaunched | 1237 eCommandProcessMustBePaused ), 1238 m_options (interpreter) 1239 { 1240 } 1241 1242 ~CommandObjectProcessLoad () override = default; 1243 1244 Options * 1245 GetOptions () override 1246 { 1247 return &m_options; 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 for (uint32_t i=0; i<argc; ++i) 1258 { 1259 Error error; 1260 PlatformSP platform = process->GetTarget().GetPlatform(); 1261 const char *image_path = command.GetArgumentAtIndex(i); 1262 uint32_t image_token = LLDB_INVALID_IMAGE_TOKEN; 1263 1264 if (!m_options.do_install) 1265 { 1266 FileSpec image_spec (image_path, false); 1267 platform->ResolveRemotePath(image_spec, image_spec); 1268 image_token = platform->LoadImage(process, FileSpec(), image_spec, error); 1269 } 1270 else if (m_options.install_path) 1271 { 1272 FileSpec image_spec (image_path, true); 1273 platform->ResolveRemotePath(m_options.install_path, m_options.install_path); 1274 image_token = platform->LoadImage(process, image_spec, m_options.install_path, error); 1275 } 1276 else 1277 { 1278 FileSpec image_spec (image_path, true); 1279 image_token = platform->LoadImage(process, image_spec, FileSpec(), error); 1280 } 1281 1282 if (image_token != LLDB_INVALID_IMAGE_TOKEN) 1283 { 1284 result.AppendMessageWithFormat ("Loading \"%s\"...ok\nImage %u loaded.\n", image_path, image_token); 1285 result.SetStatus (eReturnStatusSuccessFinishResult); 1286 } 1287 else 1288 { 1289 result.AppendErrorWithFormat ("failed to load '%s': %s", image_path, error.AsCString()); 1290 result.SetStatus (eReturnStatusFailed); 1291 } 1292 } 1293 return result.Succeeded(); 1294 } 1295 1296 CommandOptions m_options; 1297 }; 1298 1299 OptionDefinition 1300 CommandObjectProcessLoad::CommandOptions::g_option_table[] = 1301 { 1302 { LLDB_OPT_SET_ALL, false, "install", 'i', OptionParser::eOptionalArgument, nullptr, nullptr, 0, eArgTypePath, "Install the shared library to the target. If specified without an argument then the library will installed in the current working directory."}, 1303 { 0, false, nullptr, 0 , 0, nullptr, nullptr, 0, eArgTypeNone, nullptr } 1304 }; 1305 1306 //------------------------------------------------------------------------- 1307 // CommandObjectProcessUnload 1308 //------------------------------------------------------------------------- 1309 #pragma mark CommandObjectProcessUnload 1310 1311 class CommandObjectProcessUnload : public CommandObjectParsed 1312 { 1313 public: 1314 1315 CommandObjectProcessUnload (CommandInterpreter &interpreter) : 1316 CommandObjectParsed (interpreter, 1317 "process unload", 1318 "Unload a shared library from the current process using the index returned by a previous call to \"process load\".", 1319 "process unload <index>", 1320 eCommandRequiresProcess | 1321 eCommandTryTargetAPILock | 1322 eCommandProcessMustBeLaunched | 1323 eCommandProcessMustBePaused ) 1324 { 1325 } 1326 1327 ~CommandObjectProcessUnload () override 1328 { 1329 } 1330 1331 protected: 1332 bool 1333 DoExecute (Args& command, CommandReturnObject &result) override 1334 { 1335 Process *process = m_exe_ctx.GetProcessPtr(); 1336 1337 const size_t argc = command.GetArgumentCount(); 1338 1339 for (uint32_t i=0; i<argc; ++i) 1340 { 1341 const char *image_token_cstr = command.GetArgumentAtIndex(i); 1342 uint32_t image_token = StringConvert::ToUInt32(image_token_cstr, LLDB_INVALID_IMAGE_TOKEN, 0); 1343 if (image_token == LLDB_INVALID_IMAGE_TOKEN) 1344 { 1345 result.AppendErrorWithFormat ("invalid image index argument '%s'", image_token_cstr); 1346 result.SetStatus (eReturnStatusFailed); 1347 break; 1348 } 1349 else 1350 { 1351 Error error (process->GetTarget().GetPlatform()->UnloadImage(process, image_token)); 1352 if (error.Success()) 1353 { 1354 result.AppendMessageWithFormat ("Unloading shared library with index %u...ok\n", image_token); 1355 result.SetStatus (eReturnStatusSuccessFinishResult); 1356 } 1357 else 1358 { 1359 result.AppendErrorWithFormat ("failed to unload image: %s", error.AsCString()); 1360 result.SetStatus (eReturnStatusFailed); 1361 break; 1362 } 1363 } 1364 } 1365 return result.Succeeded(); 1366 } 1367 }; 1368 1369 //------------------------------------------------------------------------- 1370 // CommandObjectProcessSignal 1371 //------------------------------------------------------------------------- 1372 #pragma mark CommandObjectProcessSignal 1373 1374 class CommandObjectProcessSignal : public CommandObjectParsed 1375 { 1376 public: 1377 1378 CommandObjectProcessSignal (CommandInterpreter &interpreter) : 1379 CommandObjectParsed (interpreter, 1380 "process signal", 1381 "Send a UNIX signal to the current process being debugged.", 1382 NULL, 1383 eCommandRequiresProcess | eCommandTryTargetAPILock) 1384 { 1385 CommandArgumentEntry arg; 1386 CommandArgumentData signal_arg; 1387 1388 // Define the first (and only) variant of this arg. 1389 signal_arg.arg_type = eArgTypeUnixSignal; 1390 signal_arg.arg_repetition = eArgRepeatPlain; 1391 1392 // There is only one variant this argument could be; put it into the argument entry. 1393 arg.push_back (signal_arg); 1394 1395 // Push the data for the first argument into the m_arguments vector. 1396 m_arguments.push_back (arg); 1397 } 1398 1399 ~CommandObjectProcessSignal () override 1400 { 1401 } 1402 1403 protected: 1404 bool 1405 DoExecute (Args& command, CommandReturnObject &result) override 1406 { 1407 Process *process = m_exe_ctx.GetProcessPtr(); 1408 1409 if (command.GetArgumentCount() == 1) 1410 { 1411 int signo = LLDB_INVALID_SIGNAL_NUMBER; 1412 1413 const char *signal_name = command.GetArgumentAtIndex(0); 1414 if (::isxdigit (signal_name[0])) 1415 signo = StringConvert::ToSInt32(signal_name, LLDB_INVALID_SIGNAL_NUMBER, 0); 1416 else 1417 signo = process->GetUnixSignals()->GetSignalNumberFromName(signal_name); 1418 1419 if (signo == LLDB_INVALID_SIGNAL_NUMBER) 1420 { 1421 result.AppendErrorWithFormat ("Invalid signal argument '%s'.\n", command.GetArgumentAtIndex(0)); 1422 result.SetStatus (eReturnStatusFailed); 1423 } 1424 else 1425 { 1426 Error error (process->Signal (signo)); 1427 if (error.Success()) 1428 { 1429 result.SetStatus (eReturnStatusSuccessFinishResult); 1430 } 1431 else 1432 { 1433 result.AppendErrorWithFormat ("Failed to send signal %i: %s\n", signo, error.AsCString()); 1434 result.SetStatus (eReturnStatusFailed); 1435 } 1436 } 1437 } 1438 else 1439 { 1440 result.AppendErrorWithFormat("'%s' takes exactly one signal number argument:\nUsage: %s\n", m_cmd_name.c_str(), 1441 m_cmd_syntax.c_str()); 1442 result.SetStatus (eReturnStatusFailed); 1443 } 1444 return result.Succeeded(); 1445 } 1446 }; 1447 1448 1449 //------------------------------------------------------------------------- 1450 // CommandObjectProcessInterrupt 1451 //------------------------------------------------------------------------- 1452 #pragma mark CommandObjectProcessInterrupt 1453 1454 class CommandObjectProcessInterrupt : public CommandObjectParsed 1455 { 1456 public: 1457 1458 1459 CommandObjectProcessInterrupt (CommandInterpreter &interpreter) : 1460 CommandObjectParsed (interpreter, 1461 "process interrupt", 1462 "Interrupt the current process being debugged.", 1463 "process interrupt", 1464 eCommandRequiresProcess | 1465 eCommandTryTargetAPILock | 1466 eCommandProcessMustBeLaunched) 1467 { 1468 } 1469 1470 ~CommandObjectProcessInterrupt () override 1471 { 1472 } 1473 1474 protected: 1475 bool 1476 DoExecute (Args& command, CommandReturnObject &result) override 1477 { 1478 Process *process = m_exe_ctx.GetProcessPtr(); 1479 if (process == NULL) 1480 { 1481 result.AppendError ("no process to halt"); 1482 result.SetStatus (eReturnStatusFailed); 1483 return false; 1484 } 1485 1486 if (command.GetArgumentCount() == 0) 1487 { 1488 bool clear_thread_plans = true; 1489 Error error(process->Halt (clear_thread_plans)); 1490 if (error.Success()) 1491 { 1492 result.SetStatus (eReturnStatusSuccessFinishResult); 1493 } 1494 else 1495 { 1496 result.AppendErrorWithFormat ("Failed to halt process: %s\n", error.AsCString()); 1497 result.SetStatus (eReturnStatusFailed); 1498 } 1499 } 1500 else 1501 { 1502 result.AppendErrorWithFormat("'%s' takes no arguments:\nUsage: %s\n", 1503 m_cmd_name.c_str(), 1504 m_cmd_syntax.c_str()); 1505 result.SetStatus (eReturnStatusFailed); 1506 } 1507 return result.Succeeded(); 1508 } 1509 }; 1510 1511 //------------------------------------------------------------------------- 1512 // CommandObjectProcessKill 1513 //------------------------------------------------------------------------- 1514 #pragma mark CommandObjectProcessKill 1515 1516 class CommandObjectProcessKill : public CommandObjectParsed 1517 { 1518 public: 1519 1520 CommandObjectProcessKill (CommandInterpreter &interpreter) : 1521 CommandObjectParsed (interpreter, 1522 "process kill", 1523 "Terminate the current process being debugged.", 1524 "process kill", 1525 eCommandRequiresProcess | 1526 eCommandTryTargetAPILock | 1527 eCommandProcessMustBeLaunched) 1528 { 1529 } 1530 1531 ~CommandObjectProcessKill () override 1532 { 1533 } 1534 1535 protected: 1536 bool 1537 DoExecute (Args& command, CommandReturnObject &result) override 1538 { 1539 Process *process = m_exe_ctx.GetProcessPtr(); 1540 if (process == NULL) 1541 { 1542 result.AppendError ("no process to kill"); 1543 result.SetStatus (eReturnStatusFailed); 1544 return false; 1545 } 1546 1547 if (command.GetArgumentCount() == 0) 1548 { 1549 Error error (process->Destroy(true)); 1550 if (error.Success()) 1551 { 1552 result.SetStatus (eReturnStatusSuccessFinishResult); 1553 } 1554 else 1555 { 1556 result.AppendErrorWithFormat ("Failed to kill process: %s\n", error.AsCString()); 1557 result.SetStatus (eReturnStatusFailed); 1558 } 1559 } 1560 else 1561 { 1562 result.AppendErrorWithFormat("'%s' takes no arguments:\nUsage: %s\n", 1563 m_cmd_name.c_str(), 1564 m_cmd_syntax.c_str()); 1565 result.SetStatus (eReturnStatusFailed); 1566 } 1567 return result.Succeeded(); 1568 } 1569 }; 1570 1571 //------------------------------------------------------------------------- 1572 // CommandObjectProcessSaveCore 1573 //------------------------------------------------------------------------- 1574 #pragma mark CommandObjectProcessSaveCore 1575 1576 class CommandObjectProcessSaveCore : public CommandObjectParsed 1577 { 1578 public: 1579 1580 CommandObjectProcessSaveCore (CommandInterpreter &interpreter) : 1581 CommandObjectParsed (interpreter, 1582 "process save-core", 1583 "Save the current process as a core file using an appropriate file type.", 1584 "process save-core FILE", 1585 eCommandRequiresProcess | 1586 eCommandTryTargetAPILock | 1587 eCommandProcessMustBeLaunched) 1588 { 1589 } 1590 1591 ~CommandObjectProcessSaveCore () override 1592 { 1593 } 1594 1595 protected: 1596 bool 1597 DoExecute (Args& command, 1598 CommandReturnObject &result) override 1599 { 1600 ProcessSP process_sp = m_exe_ctx.GetProcessSP(); 1601 if (process_sp) 1602 { 1603 if (command.GetArgumentCount() == 1) 1604 { 1605 FileSpec output_file(command.GetArgumentAtIndex(0), false); 1606 Error error = PluginManager::SaveCore(process_sp, output_file); 1607 if (error.Success()) 1608 { 1609 result.SetStatus (eReturnStatusSuccessFinishResult); 1610 } 1611 else 1612 { 1613 result.AppendErrorWithFormat ("Failed to save core file for process: %s\n", error.AsCString()); 1614 result.SetStatus (eReturnStatusFailed); 1615 } 1616 } 1617 else 1618 { 1619 result.AppendErrorWithFormat ("'%s' takes one arguments:\nUsage: %s\n", 1620 m_cmd_name.c_str(), 1621 m_cmd_syntax.c_str()); 1622 result.SetStatus (eReturnStatusFailed); 1623 } 1624 } 1625 else 1626 { 1627 result.AppendError ("invalid process"); 1628 result.SetStatus (eReturnStatusFailed); 1629 return false; 1630 } 1631 1632 return result.Succeeded(); 1633 } 1634 }; 1635 1636 //------------------------------------------------------------------------- 1637 // CommandObjectProcessStatus 1638 //------------------------------------------------------------------------- 1639 #pragma mark CommandObjectProcessStatus 1640 1641 class CommandObjectProcessStatus : public CommandObjectParsed 1642 { 1643 public: 1644 CommandObjectProcessStatus (CommandInterpreter &interpreter) : 1645 CommandObjectParsed (interpreter, 1646 "process status", 1647 "Show the current status and location of executing process.", 1648 "process status", 1649 eCommandRequiresProcess | eCommandTryTargetAPILock) 1650 { 1651 } 1652 1653 ~CommandObjectProcessStatus() override 1654 { 1655 } 1656 1657 1658 bool 1659 DoExecute (Args& command, CommandReturnObject &result) override 1660 { 1661 Stream &strm = result.GetOutputStream(); 1662 result.SetStatus (eReturnStatusSuccessFinishNoResult); 1663 // No need to check "process" for validity as eCommandRequiresProcess ensures it is valid 1664 Process *process = m_exe_ctx.GetProcessPtr(); 1665 const bool only_threads_with_stop_reason = true; 1666 const uint32_t start_frame = 0; 1667 const uint32_t num_frames = 1; 1668 const uint32_t num_frames_with_source = 1; 1669 process->GetStatus(strm); 1670 process->GetThreadStatus (strm, 1671 only_threads_with_stop_reason, 1672 start_frame, 1673 num_frames, 1674 num_frames_with_source); 1675 return result.Succeeded(); 1676 } 1677 }; 1678 1679 //------------------------------------------------------------------------- 1680 // CommandObjectProcessHandle 1681 //------------------------------------------------------------------------- 1682 #pragma mark CommandObjectProcessHandle 1683 1684 class CommandObjectProcessHandle : public CommandObjectParsed 1685 { 1686 public: 1687 1688 class CommandOptions : public Options 1689 { 1690 public: 1691 1692 CommandOptions (CommandInterpreter &interpreter) : 1693 Options (interpreter) 1694 { 1695 OptionParsingStarting (); 1696 } 1697 1698 ~CommandOptions () override 1699 { 1700 } 1701 1702 Error 1703 SetOptionValue (uint32_t option_idx, const char *option_arg) override 1704 { 1705 Error error; 1706 const int short_option = m_getopt_table[option_idx].val; 1707 1708 switch (short_option) 1709 { 1710 case 's': 1711 stop = option_arg; 1712 break; 1713 case 'n': 1714 notify = option_arg; 1715 break; 1716 case 'p': 1717 pass = option_arg; 1718 break; 1719 default: 1720 error.SetErrorStringWithFormat("invalid short option character '%c'", short_option); 1721 break; 1722 } 1723 return error; 1724 } 1725 1726 void 1727 OptionParsingStarting () override 1728 { 1729 stop.clear(); 1730 notify.clear(); 1731 pass.clear(); 1732 } 1733 1734 const OptionDefinition* 1735 GetDefinitions () override 1736 { 1737 return g_option_table; 1738 } 1739 1740 // Options table: Required for subclasses of Options. 1741 1742 static OptionDefinition g_option_table[]; 1743 1744 // Instance variables to hold the values for command options. 1745 1746 std::string stop; 1747 std::string notify; 1748 std::string pass; 1749 }; 1750 1751 1752 CommandObjectProcessHandle (CommandInterpreter &interpreter) : 1753 CommandObjectParsed (interpreter, 1754 "process handle", 1755 "Show or update what the process and debugger should do with various signals received from the OS.", 1756 NULL), 1757 m_options (interpreter) 1758 { 1759 SetHelpLong ("\nIf no signals are specified, update them all. If no update " 1760 "option is specified, list the current values."); 1761 CommandArgumentEntry arg; 1762 CommandArgumentData signal_arg; 1763 1764 signal_arg.arg_type = eArgTypeUnixSignal; 1765 signal_arg.arg_repetition = eArgRepeatStar; 1766 1767 arg.push_back (signal_arg); 1768 1769 m_arguments.push_back (arg); 1770 } 1771 1772 ~CommandObjectProcessHandle () override 1773 { 1774 } 1775 1776 Options * 1777 GetOptions () override 1778 { 1779 return &m_options; 1780 } 1781 1782 bool 1783 VerifyCommandOptionValue (const std::string &option, int &real_value) 1784 { 1785 bool okay = true; 1786 1787 bool success = false; 1788 bool tmp_value = Args::StringToBoolean (option.c_str(), false, &success); 1789 1790 if (success && tmp_value) 1791 real_value = 1; 1792 else if (success && !tmp_value) 1793 real_value = 0; 1794 else 1795 { 1796 // If the value isn't 'true' or 'false', it had better be 0 or 1. 1797 real_value = StringConvert::ToUInt32 (option.c_str(), 3); 1798 if (real_value != 0 && real_value != 1) 1799 okay = false; 1800 } 1801 1802 return okay; 1803 } 1804 1805 void 1806 PrintSignalHeader (Stream &str) 1807 { 1808 str.Printf ("NAME PASS STOP NOTIFY\n"); 1809 str.Printf ("=========== ===== ===== ======\n"); 1810 } 1811 1812 void 1813 PrintSignal(Stream &str, int32_t signo, const char *sig_name, const UnixSignalsSP &signals_sp) 1814 { 1815 bool stop; 1816 bool suppress; 1817 bool notify; 1818 1819 str.Printf ("%-11s ", sig_name); 1820 if (signals_sp->GetSignalInfo(signo, suppress, stop, notify)) 1821 { 1822 bool pass = !suppress; 1823 str.Printf ("%s %s %s", 1824 (pass ? "true " : "false"), 1825 (stop ? "true " : "false"), 1826 (notify ? "true " : "false")); 1827 } 1828 str.Printf ("\n"); 1829 } 1830 1831 void 1832 PrintSignalInformation(Stream &str, Args &signal_args, int num_valid_signals, const UnixSignalsSP &signals_sp) 1833 { 1834 PrintSignalHeader (str); 1835 1836 if (num_valid_signals > 0) 1837 { 1838 size_t num_args = signal_args.GetArgumentCount(); 1839 for (size_t i = 0; i < num_args; ++i) 1840 { 1841 int32_t signo = signals_sp->GetSignalNumberFromName(signal_args.GetArgumentAtIndex(i)); 1842 if (signo != LLDB_INVALID_SIGNAL_NUMBER) 1843 PrintSignal (str, signo, signal_args.GetArgumentAtIndex (i), signals_sp); 1844 } 1845 } 1846 else // Print info for ALL signals 1847 { 1848 int32_t signo = signals_sp->GetFirstSignalNumber(); 1849 while (signo != LLDB_INVALID_SIGNAL_NUMBER) 1850 { 1851 PrintSignal(str, signo, signals_sp->GetSignalAsCString(signo), signals_sp); 1852 signo = signals_sp->GetNextSignalNumber(signo); 1853 } 1854 } 1855 } 1856 1857 protected: 1858 bool 1859 DoExecute (Args &signal_args, CommandReturnObject &result) override 1860 { 1861 TargetSP target_sp = m_interpreter.GetDebugger().GetSelectedTarget(); 1862 1863 if (!target_sp) 1864 { 1865 result.AppendError ("No current target;" 1866 " cannot handle signals until you have a valid target and process.\n"); 1867 result.SetStatus (eReturnStatusFailed); 1868 return false; 1869 } 1870 1871 ProcessSP process_sp = target_sp->GetProcessSP(); 1872 1873 if (!process_sp) 1874 { 1875 result.AppendError ("No current process; cannot handle signals until you have a valid process.\n"); 1876 result.SetStatus (eReturnStatusFailed); 1877 return false; 1878 } 1879 1880 int stop_action = -1; // -1 means leave the current setting alone 1881 int pass_action = -1; // -1 means leave the current setting alone 1882 int notify_action = -1; // -1 means leave the current setting alone 1883 1884 if (! m_options.stop.empty() 1885 && ! VerifyCommandOptionValue (m_options.stop, stop_action)) 1886 { 1887 result.AppendError ("Invalid argument for command option --stop; must be true or false.\n"); 1888 result.SetStatus (eReturnStatusFailed); 1889 return false; 1890 } 1891 1892 if (! m_options.notify.empty() 1893 && ! VerifyCommandOptionValue (m_options.notify, notify_action)) 1894 { 1895 result.AppendError ("Invalid argument for command option --notify; must be true or false.\n"); 1896 result.SetStatus (eReturnStatusFailed); 1897 return false; 1898 } 1899 1900 if (! m_options.pass.empty() 1901 && ! VerifyCommandOptionValue (m_options.pass, pass_action)) 1902 { 1903 result.AppendError ("Invalid argument for command option --pass; must be true or false.\n"); 1904 result.SetStatus (eReturnStatusFailed); 1905 return false; 1906 } 1907 1908 size_t num_args = signal_args.GetArgumentCount(); 1909 UnixSignalsSP signals_sp = process_sp->GetUnixSignals(); 1910 int num_signals_set = 0; 1911 1912 if (num_args > 0) 1913 { 1914 for (size_t i = 0; i < num_args; ++i) 1915 { 1916 int32_t signo = signals_sp->GetSignalNumberFromName(signal_args.GetArgumentAtIndex(i)); 1917 if (signo != LLDB_INVALID_SIGNAL_NUMBER) 1918 { 1919 // Casting the actions as bools here should be okay, because VerifyCommandOptionValue guarantees 1920 // the value is either 0 or 1. 1921 if (stop_action != -1) 1922 signals_sp->SetShouldStop(signo, stop_action); 1923 if (pass_action != -1) 1924 { 1925 bool suppress = !pass_action; 1926 signals_sp->SetShouldSuppress(signo, suppress); 1927 } 1928 if (notify_action != -1) 1929 signals_sp->SetShouldNotify(signo, notify_action); 1930 ++num_signals_set; 1931 } 1932 else 1933 { 1934 result.AppendErrorWithFormat ("Invalid signal name '%s'\n", signal_args.GetArgumentAtIndex (i)); 1935 } 1936 } 1937 } 1938 else 1939 { 1940 // No signal specified, if any command options were specified, update ALL signals. 1941 if ((notify_action != -1) || (stop_action != -1) || (pass_action != -1)) 1942 { 1943 if (m_interpreter.Confirm ("Do you really want to update all the signals?", false)) 1944 { 1945 int32_t signo = signals_sp->GetFirstSignalNumber(); 1946 while (signo != LLDB_INVALID_SIGNAL_NUMBER) 1947 { 1948 if (notify_action != -1) 1949 signals_sp->SetShouldNotify(signo, notify_action); 1950 if (stop_action != -1) 1951 signals_sp->SetShouldStop(signo, stop_action); 1952 if (pass_action != -1) 1953 { 1954 bool suppress = !pass_action; 1955 signals_sp->SetShouldSuppress(signo, suppress); 1956 } 1957 signo = signals_sp->GetNextSignalNumber(signo); 1958 } 1959 } 1960 } 1961 } 1962 1963 PrintSignalInformation (result.GetOutputStream(), signal_args, num_signals_set, signals_sp); 1964 1965 if (num_signals_set > 0) 1966 result.SetStatus (eReturnStatusSuccessFinishNoResult); 1967 else 1968 result.SetStatus (eReturnStatusFailed); 1969 1970 return result.Succeeded(); 1971 } 1972 1973 CommandOptions m_options; 1974 }; 1975 1976 OptionDefinition 1977 CommandObjectProcessHandle::CommandOptions::g_option_table[] = 1978 { 1979 { 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." }, 1980 { 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." }, 1981 { LLDB_OPT_SET_1, false, "pass", 'p', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeBoolean, "Whether or not the signal should be passed to the process." }, 1982 { 0, false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL } 1983 }; 1984 1985 //------------------------------------------------------------------------- 1986 // CommandObjectMultiwordProcess 1987 //------------------------------------------------------------------------- 1988 1989 CommandObjectMultiwordProcess::CommandObjectMultiwordProcess (CommandInterpreter &interpreter) : 1990 CommandObjectMultiword (interpreter, 1991 "process", 1992 "A set of commands for operating on a process.", 1993 "process <subcommand> [<subcommand-options>]") 1994 { 1995 LoadSubCommand ("attach", CommandObjectSP (new CommandObjectProcessAttach (interpreter))); 1996 LoadSubCommand ("launch", CommandObjectSP (new CommandObjectProcessLaunch (interpreter))); 1997 LoadSubCommand ("continue", CommandObjectSP (new CommandObjectProcessContinue (interpreter))); 1998 LoadSubCommand ("connect", CommandObjectSP (new CommandObjectProcessConnect (interpreter))); 1999 LoadSubCommand ("detach", CommandObjectSP (new CommandObjectProcessDetach (interpreter))); 2000 LoadSubCommand ("load", CommandObjectSP (new CommandObjectProcessLoad (interpreter))); 2001 LoadSubCommand ("unload", CommandObjectSP (new CommandObjectProcessUnload (interpreter))); 2002 LoadSubCommand ("signal", CommandObjectSP (new CommandObjectProcessSignal (interpreter))); 2003 LoadSubCommand ("handle", CommandObjectSP (new CommandObjectProcessHandle (interpreter))); 2004 LoadSubCommand ("status", CommandObjectSP (new CommandObjectProcessStatus (interpreter))); 2005 LoadSubCommand ("interrupt", CommandObjectSP (new CommandObjectProcessInterrupt (interpreter))); 2006 LoadSubCommand ("kill", CommandObjectSP (new CommandObjectProcessKill (interpreter))); 2007 LoadSubCommand ("plugin", CommandObjectSP (new CommandObjectProcessPlugin (interpreter))); 2008 LoadSubCommand ("save-core", CommandObjectSP (new CommandObjectProcessSaveCore (interpreter))); 2009 } 2010 2011 CommandObjectMultiwordProcess::~CommandObjectMultiwordProcess () 2012 { 2013 } 2014 2015