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