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/Interpreter/Args.h" 17 #include "lldb/Interpreter/Options.h" 18 #include "lldb/Core/State.h" 19 #include "lldb/Interpreter/CommandInterpreter.h" 20 #include "lldb/Interpreter/CommandReturnObject.h" 21 #include "./CommandObjectThread.h" 22 #include "lldb/Target/Process.h" 23 #include "lldb/Target/Target.h" 24 #include "lldb/Target/Thread.h" 25 26 using namespace lldb; 27 using namespace lldb_private; 28 29 //------------------------------------------------------------------------- 30 // CommandObjectProcessLaunch 31 //------------------------------------------------------------------------- 32 33 class CommandObjectProcessLaunch : public CommandObject 34 { 35 public: 36 37 class CommandOptions : public Options 38 { 39 public: 40 41 CommandOptions () : 42 Options() 43 { 44 // Keep default values of all options in one place: ResetOptionValues () 45 ResetOptionValues (); 46 } 47 48 ~CommandOptions () 49 { 50 } 51 52 Error 53 SetOptionValue (int option_idx, const char *option_arg) 54 { 55 Error error; 56 char short_option = (char) m_getopt_table[option_idx].val; 57 58 switch (short_option) 59 { 60 case 's': stop_at_entry = true; break; 61 case 'e': stderr_path = option_arg; break; 62 case 'i': stdin_path = option_arg; break; 63 case 'o': stdout_path = option_arg; break; 64 case 'p': plugin_name = option_arg; break; 65 case 't': 66 if (option_arg && option_arg[0]) 67 tty_name.assign (option_arg); 68 in_new_tty = true; 69 break; 70 default: 71 error.SetErrorStringWithFormat("Invalid short option character '%c'.\n", short_option); 72 break; 73 74 } 75 return error; 76 } 77 78 void 79 ResetOptionValues () 80 { 81 Options::ResetOptionValues(); 82 stop_at_entry = false; 83 in_new_tty = false; 84 tty_name.clear(); 85 stdin_path.clear(); 86 stdout_path.clear(); 87 stderr_path.clear(); 88 plugin_name.clear(); 89 } 90 91 const lldb::OptionDefinition* 92 GetDefinitions () 93 { 94 return g_option_table; 95 } 96 97 // Options table: Required for subclasses of Options. 98 99 static lldb::OptionDefinition g_option_table[]; 100 101 // Instance variables to hold the values for command options. 102 103 bool stop_at_entry; 104 bool in_new_tty; 105 std::string tty_name; 106 std::string stderr_path; 107 std::string stdin_path; 108 std::string stdout_path; 109 std::string plugin_name; 110 111 }; 112 113 CommandObjectProcessLaunch (CommandInterpreter &interpreter) : 114 CommandObject (interpreter, 115 "process launch", 116 "Launch the executable in the debugger.", 117 NULL) 118 { 119 CommandArgumentEntry arg; 120 CommandArgumentData run_args_arg; 121 122 // Define the first (and only) variant of this arg. 123 run_args_arg.arg_type = eArgTypeRunArgs; 124 run_args_arg.arg_repetition = eArgRepeatOptional; 125 126 // There is only one variant this argument could be; put it into the argument entry. 127 arg.push_back (run_args_arg); 128 129 // Push the data for the first argument into the m_arguments vector. 130 m_arguments.push_back (arg); 131 } 132 133 134 ~CommandObjectProcessLaunch () 135 { 136 } 137 138 Options * 139 GetOptions () 140 { 141 return &m_options; 142 } 143 144 bool 145 Execute (Args& launch_args, CommandReturnObject &result) 146 { 147 Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); 148 149 if (target == NULL) 150 { 151 result.AppendError ("invalid target, set executable file using 'file' command"); 152 result.SetStatus (eReturnStatusFailed); 153 return false; 154 } 155 156 // If our listener is NULL, users aren't allows to launch 157 char filename[PATH_MAX]; 158 const Module *exe_module = target->GetExecutableModule().get(); 159 exe_module->GetFileSpec().GetPath(filename, sizeof(filename)); 160 161 Process *process = m_interpreter.GetDebugger().GetExecutionContext().process; 162 if (process && process->IsAlive()) 163 { 164 result.AppendErrorWithFormat ("Process %u is currently being debugged, kill the process before running again.\n", 165 process->GetID()); 166 result.SetStatus (eReturnStatusFailed); 167 return false; 168 } 169 170 const char *plugin_name; 171 if (!m_options.plugin_name.empty()) 172 plugin_name = m_options.plugin_name.c_str(); 173 else 174 plugin_name = NULL; 175 176 process = target->CreateProcess (m_interpreter.GetDebugger().GetListener(), plugin_name).get(); 177 178 if (process == NULL) 179 { 180 result.AppendErrorWithFormat ("Failed to find a process plugin for executable.\n"); 181 result.SetStatus (eReturnStatusFailed); 182 return false; 183 } 184 185 // If no launch args were given on the command line, then use any that 186 // might have been set using the "run-args" set variable. 187 if (launch_args.GetArgumentCount() == 0) 188 { 189 if (process->GetRunArguments().GetArgumentCount() > 0) 190 launch_args = process->GetRunArguments(); 191 } 192 193 if (m_options.in_new_tty) 194 { 195 char exec_file_path[PATH_MAX]; 196 if (exe_module->GetFileSpec().GetPath(exec_file_path, sizeof(exec_file_path))) 197 { 198 launch_args.InsertArgumentAtIndex(0, exec_file_path); 199 } 200 else 201 { 202 result.AppendError("invalid executable"); 203 result.SetStatus (eReturnStatusFailed); 204 return false; 205 } 206 } 207 208 Args environment; 209 210 process->GetEnvironmentAsArgs (environment); 211 212 uint32_t launch_flags = eLaunchFlagNone; 213 214 if (process->GetDisableASLR()) 215 launch_flags |= eLaunchFlagDisableASLR; 216 217 const char **inferior_argv = launch_args.GetArgumentCount() ? launch_args.GetConstArgumentVector() : NULL; 218 const char **inferior_envp = environment.GetArgumentCount() ? environment.GetConstArgumentVector() : NULL; 219 220 Error error; 221 222 if (m_options.in_new_tty) 223 { 224 225 lldb::pid_t pid = Host::LaunchInNewTerminal (m_options.tty_name.c_str(), 226 inferior_argv, 227 inferior_envp, 228 &exe_module->GetArchitecture(), 229 true, 230 process->GetDisableASLR()); 231 232 if (pid != LLDB_INVALID_PROCESS_ID) 233 error = process->Attach (pid); 234 } 235 else 236 { 237 const char * stdin_path = NULL; 238 const char * stdout_path = NULL; 239 const char * stderr_path = NULL; 240 241 // Were any standard input/output/error paths given on the command line? 242 if (m_options.stdin_path.empty() && 243 m_options.stdout_path.empty() && 244 m_options.stderr_path.empty()) 245 { 246 // No standard file handles were given on the command line, check 247 // with the process object in case they were give using "set settings" 248 stdin_path = process->GetStandardInputPath(); 249 stdout_path = process->GetStandardOutputPath(); 250 stderr_path = process->GetStandardErrorPath(); 251 } 252 else 253 { 254 stdin_path = m_options.stdin_path.empty() ? NULL : m_options.stdin_path.c_str(); 255 stdout_path = m_options.stdout_path.empty() ? NULL : m_options.stdout_path.c_str(); 256 stderr_path = m_options.stderr_path.empty() ? NULL : m_options.stderr_path.c_str(); 257 } 258 259 if (stdin_path == NULL) 260 stdin_path = "/dev/null"; 261 if (stdout_path == NULL) 262 stdout_path = "/dev/null"; 263 if (stderr_path == NULL) 264 stderr_path = "/dev/null"; 265 266 error = process->Launch (inferior_argv, 267 inferior_envp, 268 launch_flags, 269 stdin_path, 270 stdout_path, 271 stderr_path); 272 } 273 274 if (error.Success()) 275 { 276 const char *archname = exe_module->GetArchitecture().AsCString(); 277 278 result.AppendMessageWithFormat ("Process %i launched: '%s' (%s)\n", process->GetID(), filename, archname); 279 result.SetDidChangeProcessState (true); 280 if (m_options.stop_at_entry == false) 281 { 282 result.SetStatus (eReturnStatusSuccessContinuingNoResult); 283 StateType state = process->WaitForProcessToStop (NULL); 284 285 if (state == eStateStopped) 286 { 287 error = process->Resume(); 288 if (error.Success()) 289 { 290 bool synchronous_execution = m_interpreter.GetSynchronous (); 291 if (synchronous_execution) 292 { 293 state = process->WaitForProcessToStop (NULL); 294 result.SetDidChangeProcessState (true); 295 result.SetStatus (eReturnStatusSuccessFinishResult); 296 } 297 else 298 { 299 result.SetStatus (eReturnStatusSuccessContinuingNoResult); 300 } 301 } 302 } 303 } 304 } 305 306 return result.Succeeded(); 307 } 308 309 virtual const char *GetRepeatCommand (Args ¤t_command_args, uint32_t index) 310 { 311 // No repeat for "process launch"... 312 return ""; 313 } 314 315 protected: 316 317 CommandOptions m_options; 318 }; 319 320 321 #define SET1 LLDB_OPT_SET_1 322 #define SET2 LLDB_OPT_SET_2 323 324 lldb::OptionDefinition 325 CommandObjectProcessLaunch::CommandOptions::g_option_table[] = 326 { 327 { SET1 | SET2, false, "stop-at-entry", 's', no_argument, NULL, 0, eArgTypeNone, "Stop at the entry point of the program when launching a process."}, 328 { SET1 , false, "stdin", 'i', required_argument, NULL, 0, eArgTypePath, "Redirect stdin for the process to <path>."}, 329 { SET1 , false, "stdout", 'o', required_argument, NULL, 0, eArgTypePath, "Redirect stdout for the process to <path>."}, 330 { SET1 , false, "stderr", 'e', required_argument, NULL, 0, eArgTypePath, "Redirect stderr for the process to <path>."}, 331 { SET1 | SET2, false, "plugin", 'p', required_argument, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."}, 332 { SET2, false, "tty", 't', optional_argument, NULL, 0, eArgTypePath, "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."}, 333 { 0, false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL } 334 }; 335 336 #undef SET1 337 #undef SET2 338 339 //------------------------------------------------------------------------- 340 // CommandObjectProcessAttach 341 //------------------------------------------------------------------------- 342 343 class CommandObjectProcessAttach : public CommandObject 344 { 345 public: 346 347 class CommandOptions : public Options 348 { 349 public: 350 351 CommandOptions () : 352 Options() 353 { 354 // Keep default values of all options in one place: ResetOptionValues () 355 ResetOptionValues (); 356 } 357 358 ~CommandOptions () 359 { 360 } 361 362 Error 363 SetOptionValue (int option_idx, const char *option_arg) 364 { 365 Error error; 366 char short_option = (char) m_getopt_table[option_idx].val; 367 bool success = false; 368 switch (short_option) 369 { 370 case 'p': 371 pid = Args::StringToUInt32 (option_arg, LLDB_INVALID_PROCESS_ID, 0, &success); 372 if (!success || pid == LLDB_INVALID_PROCESS_ID) 373 { 374 error.SetErrorStringWithFormat("Invalid process ID '%s'.\n", option_arg); 375 } 376 break; 377 378 case 'P': 379 plugin_name = option_arg; 380 break; 381 382 case 'n': 383 name.assign(option_arg); 384 break; 385 386 case 'w': 387 waitfor = true; 388 break; 389 390 default: 391 error.SetErrorStringWithFormat("Invalid short option character '%c'.\n", short_option); 392 break; 393 } 394 return error; 395 } 396 397 void 398 ResetOptionValues () 399 { 400 Options::ResetOptionValues(); 401 pid = LLDB_INVALID_PROCESS_ID; 402 name.clear(); 403 waitfor = false; 404 } 405 406 const lldb::OptionDefinition* 407 GetDefinitions () 408 { 409 return g_option_table; 410 } 411 412 virtual bool 413 HandleOptionArgumentCompletion (CommandInterpreter &interpeter, 414 Args &input, 415 int cursor_index, 416 int char_pos, 417 OptionElementVector &opt_element_vector, 418 int opt_element_index, 419 int match_start_point, 420 int max_return_elements, 421 bool &word_complete, 422 StringList &matches) 423 { 424 int opt_arg_pos = opt_element_vector[opt_element_index].opt_arg_pos; 425 int opt_defs_index = opt_element_vector[opt_element_index].opt_defs_index; 426 427 // We are only completing the name option for now... 428 429 const lldb::OptionDefinition *opt_defs = GetDefinitions(); 430 if (opt_defs[opt_defs_index].short_option == 'n') 431 { 432 // Are we in the name? 433 434 // Look to see if there is a -P argument provided, and if so use that plugin, otherwise 435 // use the default plugin. 436 Process *process = interpeter.GetDebugger().GetExecutionContext().process; 437 bool need_to_delete_process = false; 438 439 const char *partial_name = NULL; 440 partial_name = input.GetArgumentAtIndex(opt_arg_pos); 441 442 if (process && process->IsAlive()) 443 return true; 444 445 Target *target = interpeter.GetDebugger().GetSelectedTarget().get(); 446 if (target == NULL) 447 { 448 // No target has been set yet, for now do host completion. Otherwise I don't know how we would 449 // figure out what the right target to use is... 450 std::vector<lldb::pid_t> pids; 451 Host::ListProcessesMatchingName (partial_name, matches, pids); 452 return true; 453 } 454 if (!process) 455 { 456 process = target->CreateProcess (interpeter.GetDebugger().GetListener(), partial_name).get(); 457 need_to_delete_process = true; 458 } 459 460 if (process) 461 { 462 matches.Clear(); 463 std::vector<lldb::pid_t> pids; 464 process->ListProcessesMatchingName (NULL, matches, pids); 465 if (need_to_delete_process) 466 target->DeleteCurrentProcess(); 467 return true; 468 } 469 } 470 471 return false; 472 } 473 474 // Options table: Required for subclasses of Options. 475 476 static lldb::OptionDefinition g_option_table[]; 477 478 // Instance variables to hold the values for command options. 479 480 lldb::pid_t pid; 481 std::string plugin_name; 482 std::string name; 483 bool waitfor; 484 }; 485 486 CommandObjectProcessAttach (CommandInterpreter &interpreter) : 487 CommandObject (interpreter, 488 "process attach", 489 "Attach to a process.", 490 "process attach <cmd-options>") 491 { 492 } 493 494 ~CommandObjectProcessAttach () 495 { 496 } 497 498 bool 499 Execute (Args& command, 500 CommandReturnObject &result) 501 { 502 Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); 503 504 Process *process = m_interpreter.GetDebugger().GetExecutionContext().process; 505 if (process) 506 { 507 if (process->IsAlive()) 508 { 509 result.AppendErrorWithFormat ("Process %u is currently being debugged, kill the process before attaching.\n", 510 process->GetID()); 511 result.SetStatus (eReturnStatusFailed); 512 return false; 513 } 514 } 515 516 if (target == NULL) 517 { 518 // If there isn't a current target create one. 519 TargetSP new_target_sp; 520 FileSpec emptyFileSpec; 521 ArchSpec emptyArchSpec; 522 Error error; 523 524 error = m_interpreter.GetDebugger().GetTargetList().CreateTarget (m_interpreter.GetDebugger(), 525 emptyFileSpec, 526 emptyArchSpec, 527 NULL, 528 false, 529 new_target_sp); 530 target = new_target_sp.get(); 531 if (target == NULL || error.Fail()) 532 { 533 result.AppendError(error.AsCString("Error creating empty target")); 534 return false; 535 } 536 m_interpreter.GetDebugger().GetTargetList().SetSelectedTarget(target); 537 } 538 539 // Record the old executable module, we want to issue a warning if the process of attaching changed the 540 // current executable (like somebody said "file foo" then attached to a PID whose executable was bar.) 541 542 ModuleSP old_exec_module_sp = target->GetExecutableModule(); 543 ArchSpec old_arch_spec = target->GetArchitecture(); 544 545 if (command.GetArgumentCount()) 546 { 547 result.AppendErrorWithFormat("Invalid arguments for '%s'.\nUsage: \n", m_cmd_name.c_str(), m_cmd_syntax.c_str()); 548 result.SetStatus (eReturnStatusFailed); 549 } 550 else 551 { 552 const char *plugin_name = NULL; 553 554 if (!m_options.plugin_name.empty()) 555 plugin_name = m_options.plugin_name.c_str(); 556 557 process = target->CreateProcess (m_interpreter.GetDebugger().GetListener(), plugin_name).get(); 558 559 if (process) 560 { 561 Error error; 562 int attach_pid = m_options.pid; 563 564 const char *wait_name = NULL; 565 566 if (m_options.name.empty()) 567 { 568 if (old_exec_module_sp) 569 { 570 wait_name = old_exec_module_sp->GetFileSpec().GetFilename().AsCString(); 571 } 572 } 573 else 574 { 575 wait_name = m_options.name.c_str(); 576 } 577 578 // If we are waiting for a process with this name to show up, do that first. 579 if (m_options.waitfor) 580 { 581 582 if (wait_name == NULL) 583 { 584 result.AppendError("Invalid arguments: must have a file loaded or supply a process name with the waitfor option.\n"); 585 result.SetStatus (eReturnStatusFailed); 586 return false; 587 } 588 589 m_interpreter.GetDebugger().GetOutputStream().Printf("Waiting to attach to a process named \"%s\".\n", wait_name); 590 error = process->Attach (wait_name, m_options.waitfor); 591 if (error.Success()) 592 { 593 result.SetStatus (eReturnStatusSuccessContinuingNoResult); 594 } 595 else 596 { 597 result.AppendErrorWithFormat ("Waiting for a process to launch named '%s': %s\n", 598 wait_name, 599 error.AsCString()); 600 result.SetStatus (eReturnStatusFailed); 601 return false; 602 } 603 } 604 else 605 { 606 // If the process was specified by name look it up, so we can warn if there are multiple 607 // processes with this pid. 608 609 if (attach_pid == LLDB_INVALID_PROCESS_ID && wait_name != NULL) 610 { 611 std::vector<lldb::pid_t> pids; 612 StringList matches; 613 614 process->ListProcessesMatchingName(wait_name, matches, pids); 615 if (matches.GetSize() > 1) 616 { 617 result.AppendErrorWithFormat("More than one process named %s\n", wait_name); 618 result.SetStatus (eReturnStatusFailed); 619 return false; 620 } 621 else if (matches.GetSize() == 0) 622 { 623 result.AppendErrorWithFormat("Could not find a process named %s\n", wait_name); 624 result.SetStatus (eReturnStatusFailed); 625 return false; 626 } 627 else 628 { 629 attach_pid = pids[0]; 630 } 631 632 } 633 634 if (attach_pid != LLDB_INVALID_PROCESS_ID) 635 { 636 error = process->Attach (attach_pid); 637 if (error.Success()) 638 { 639 result.SetStatus (eReturnStatusSuccessContinuingNoResult); 640 } 641 else 642 { 643 result.AppendErrorWithFormat ("Attaching to process %i failed: %s.\n", 644 attach_pid, 645 error.AsCString()); 646 result.SetStatus (eReturnStatusFailed); 647 } 648 } 649 else 650 { 651 result.AppendErrorWithFormat ("No PID specified for attach\n", 652 attach_pid, 653 error.AsCString()); 654 result.SetStatus (eReturnStatusFailed); 655 656 } 657 } 658 } 659 } 660 661 if (result.Succeeded()) 662 { 663 // Okay, we're done. Last step is to warn if the executable module has changed: 664 if (!old_exec_module_sp) 665 { 666 char new_path[PATH_MAX + 1]; 667 target->GetExecutableModule()->GetFileSpec().GetPath(new_path, PATH_MAX); 668 669 result.AppendMessageWithFormat("Executable module set to \"%s\".\n", 670 new_path); 671 } 672 else if (old_exec_module_sp->GetFileSpec() != target->GetExecutableModule()->GetFileSpec()) 673 { 674 char old_path[PATH_MAX + 1]; 675 char new_path[PATH_MAX + 1]; 676 677 old_exec_module_sp->GetFileSpec().GetPath(old_path, PATH_MAX); 678 target->GetExecutableModule()->GetFileSpec().GetPath (new_path, PATH_MAX); 679 680 result.AppendWarningWithFormat("Executable module changed from \"%s\" to \"%s\".\n", 681 old_path, new_path); 682 } 683 684 if (!old_arch_spec.IsValid()) 685 { 686 result.AppendMessageWithFormat ("Architecture set to: %s.\n", target->GetArchitecture().AsCString()); 687 } 688 else if (old_arch_spec != target->GetArchitecture()) 689 { 690 result.AppendWarningWithFormat("Architecture changed from %s to %s.\n", 691 old_arch_spec.AsCString(), target->GetArchitecture().AsCString()); 692 } 693 } 694 return result.Succeeded(); 695 } 696 697 Options * 698 GetOptions () 699 { 700 return &m_options; 701 } 702 703 protected: 704 705 CommandOptions m_options; 706 }; 707 708 709 lldb::OptionDefinition 710 CommandObjectProcessAttach::CommandOptions::g_option_table[] = 711 { 712 { LLDB_OPT_SET_ALL, false, "plugin", 'P', required_argument, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."}, 713 { LLDB_OPT_SET_1, false, "pid", 'p', required_argument, NULL, 0, eArgTypePid, "The process ID of an existing process to attach to."}, 714 { LLDB_OPT_SET_2, false, "name", 'n', required_argument, NULL, 0, eArgTypeProcessName, "The name of the process to attach to."}, 715 { LLDB_OPT_SET_2, false, "waitfor",'w', no_argument, NULL, 0, eArgTypeNone, "Wait for the the process with <process-name> to launch."}, 716 { 0, false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL } 717 }; 718 719 //------------------------------------------------------------------------- 720 // CommandObjectProcessContinue 721 //------------------------------------------------------------------------- 722 723 class CommandObjectProcessContinue : public CommandObject 724 { 725 public: 726 727 CommandObjectProcessContinue (CommandInterpreter &interpreter) : 728 CommandObject (interpreter, 729 "process continue", 730 "Continue execution of all threads in the current process.", 731 "process continue", 732 eFlagProcessMustBeLaunched | eFlagProcessMustBePaused) 733 { 734 } 735 736 737 ~CommandObjectProcessContinue () 738 { 739 } 740 741 bool 742 Execute (Args& command, 743 CommandReturnObject &result) 744 { 745 Process *process = m_interpreter.GetDebugger().GetExecutionContext().process; 746 bool synchronous_execution = m_interpreter.GetSynchronous (); 747 748 if (process == NULL) 749 { 750 result.AppendError ("no process to continue"); 751 result.SetStatus (eReturnStatusFailed); 752 return false; 753 } 754 755 StateType state = process->GetState(); 756 if (state == eStateStopped) 757 { 758 if (command.GetArgumentCount() != 0) 759 { 760 result.AppendErrorWithFormat ("The '%s' command does not take any arguments.\n", m_cmd_name.c_str()); 761 result.SetStatus (eReturnStatusFailed); 762 return false; 763 } 764 765 const uint32_t num_threads = process->GetThreadList().GetSize(); 766 767 // Set the actions that the threads should each take when resuming 768 for (uint32_t idx=0; idx<num_threads; ++idx) 769 { 770 process->GetThreadList().GetThreadAtIndex(idx)->SetResumeState (eStateRunning); 771 } 772 773 Error error(process->Resume()); 774 if (error.Success()) 775 { 776 result.AppendMessageWithFormat ("Process %i resuming\n", process->GetID()); 777 if (synchronous_execution) 778 { 779 state = process->WaitForProcessToStop (NULL); 780 781 result.SetDidChangeProcessState (true); 782 result.AppendMessageWithFormat ("Process %i %s\n", process->GetID(), StateAsCString (state)); 783 result.SetStatus (eReturnStatusSuccessFinishNoResult); 784 } 785 else 786 { 787 result.SetStatus (eReturnStatusSuccessContinuingNoResult); 788 } 789 } 790 else 791 { 792 result.AppendErrorWithFormat("Failed to resume process: %s.\n", error.AsCString()); 793 result.SetStatus (eReturnStatusFailed); 794 } 795 } 796 else 797 { 798 result.AppendErrorWithFormat ("Process cannot be continued from its current state (%s).\n", 799 StateAsCString(state)); 800 result.SetStatus (eReturnStatusFailed); 801 } 802 return result.Succeeded(); 803 } 804 }; 805 806 //------------------------------------------------------------------------- 807 // CommandObjectProcessDetach 808 //------------------------------------------------------------------------- 809 810 class CommandObjectProcessDetach : public CommandObject 811 { 812 public: 813 814 CommandObjectProcessDetach (CommandInterpreter &interpreter) : 815 CommandObject (interpreter, 816 "process detach", 817 "Detach from the current process being debugged.", 818 "process detach", 819 eFlagProcessMustBeLaunched) 820 { 821 } 822 823 ~CommandObjectProcessDetach () 824 { 825 } 826 827 bool 828 Execute (Args& command, 829 CommandReturnObject &result) 830 { 831 Process *process = m_interpreter.GetDebugger().GetExecutionContext().process; 832 if (process == NULL) 833 { 834 result.AppendError ("must have a valid process in order to detach"); 835 result.SetStatus (eReturnStatusFailed); 836 return false; 837 } 838 839 result.AppendMessageWithFormat ("Detaching from process %i\n", process->GetID()); 840 Error error (process->Detach()); 841 if (error.Success()) 842 { 843 result.SetStatus (eReturnStatusSuccessFinishResult); 844 } 845 else 846 { 847 result.AppendErrorWithFormat ("Detach failed: %s\n", error.AsCString()); 848 result.SetStatus (eReturnStatusFailed); 849 return false; 850 } 851 return result.Succeeded(); 852 } 853 }; 854 855 //------------------------------------------------------------------------- 856 // CommandObjectProcessSignal 857 //------------------------------------------------------------------------- 858 859 class CommandObjectProcessSignal : public CommandObject 860 { 861 public: 862 863 CommandObjectProcessSignal (CommandInterpreter &interpreter) : 864 CommandObject (interpreter, 865 "process signal", 866 "Send a UNIX signal to the current process being debugged.", 867 NULL) 868 { 869 CommandArgumentEntry arg; 870 CommandArgumentData signal_arg; 871 872 // Define the first (and only) variant of this arg. 873 signal_arg.arg_type = eArgTypeUnixSignal; 874 signal_arg.arg_repetition = eArgRepeatPlain; 875 876 // There is only one variant this argument could be; put it into the argument entry. 877 arg.push_back (signal_arg); 878 879 // Push the data for the first argument into the m_arguments vector. 880 m_arguments.push_back (arg); 881 } 882 883 ~CommandObjectProcessSignal () 884 { 885 } 886 887 bool 888 Execute (Args& command, 889 CommandReturnObject &result) 890 { 891 Process *process = m_interpreter.GetDebugger().GetExecutionContext().process; 892 if (process == NULL) 893 { 894 result.AppendError ("no process to signal"); 895 result.SetStatus (eReturnStatusFailed); 896 return false; 897 } 898 899 if (command.GetArgumentCount() == 1) 900 { 901 int signo = LLDB_INVALID_SIGNAL_NUMBER; 902 903 const char *signal_name = command.GetArgumentAtIndex(0); 904 if (::isxdigit (signal_name[0])) 905 signo = Args::StringToSInt32(signal_name, LLDB_INVALID_SIGNAL_NUMBER, 0); 906 else 907 signo = process->GetUnixSignals().GetSignalNumberFromName (signal_name); 908 909 if (signo == LLDB_INVALID_SIGNAL_NUMBER) 910 { 911 result.AppendErrorWithFormat ("Invalid signal argument '%s'.\n", command.GetArgumentAtIndex(0)); 912 result.SetStatus (eReturnStatusFailed); 913 } 914 else 915 { 916 Error error (process->Signal (signo)); 917 if (error.Success()) 918 { 919 result.SetStatus (eReturnStatusSuccessFinishResult); 920 } 921 else 922 { 923 result.AppendErrorWithFormat ("Failed to send signal %i: %s\n", signo, error.AsCString()); 924 result.SetStatus (eReturnStatusFailed); 925 } 926 } 927 } 928 else 929 { 930 result.AppendErrorWithFormat("'%s' takes exactly one signal number argument:\nUsage: \n", m_cmd_name.c_str(), 931 m_cmd_syntax.c_str()); 932 result.SetStatus (eReturnStatusFailed); 933 } 934 return result.Succeeded(); 935 } 936 }; 937 938 939 //------------------------------------------------------------------------- 940 // CommandObjectProcessInterrupt 941 //------------------------------------------------------------------------- 942 943 class CommandObjectProcessInterrupt : public CommandObject 944 { 945 public: 946 947 948 CommandObjectProcessInterrupt (CommandInterpreter &interpreter) : 949 CommandObject (interpreter, 950 "process interrupt", 951 "Interrupt the current process being debugged.", 952 "process interrupt", 953 eFlagProcessMustBeLaunched) 954 { 955 } 956 957 ~CommandObjectProcessInterrupt () 958 { 959 } 960 961 bool 962 Execute (Args& command, 963 CommandReturnObject &result) 964 { 965 Process *process = m_interpreter.GetDebugger().GetExecutionContext().process; 966 if (process == NULL) 967 { 968 result.AppendError ("no process to halt"); 969 result.SetStatus (eReturnStatusFailed); 970 return false; 971 } 972 973 if (command.GetArgumentCount() == 0) 974 { 975 Error error(process->Halt ()); 976 if (error.Success()) 977 { 978 result.SetStatus (eReturnStatusSuccessFinishResult); 979 980 // Maybe we should add a "SuspendThreadPlans so we 981 // can halt, and keep in place all the current thread plans. 982 process->GetThreadList().DiscardThreadPlans(); 983 } 984 else 985 { 986 result.AppendErrorWithFormat ("Failed to halt process: %s\n", error.AsCString()); 987 result.SetStatus (eReturnStatusFailed); 988 } 989 } 990 else 991 { 992 result.AppendErrorWithFormat("'%s' takes no arguments:\nUsage: \n", 993 m_cmd_name.c_str(), 994 m_cmd_syntax.c_str()); 995 result.SetStatus (eReturnStatusFailed); 996 } 997 return result.Succeeded(); 998 } 999 }; 1000 1001 //------------------------------------------------------------------------- 1002 // CommandObjectProcessKill 1003 //------------------------------------------------------------------------- 1004 1005 class CommandObjectProcessKill : public CommandObject 1006 { 1007 public: 1008 1009 CommandObjectProcessKill (CommandInterpreter &interpreter) : 1010 CommandObject (interpreter, 1011 "process kill", 1012 "Terminate the current process being debugged.", 1013 "process kill", 1014 eFlagProcessMustBeLaunched) 1015 { 1016 } 1017 1018 ~CommandObjectProcessKill () 1019 { 1020 } 1021 1022 bool 1023 Execute (Args& command, 1024 CommandReturnObject &result) 1025 { 1026 Process *process = m_interpreter.GetDebugger().GetExecutionContext().process; 1027 if (process == NULL) 1028 { 1029 result.AppendError ("no process to kill"); 1030 result.SetStatus (eReturnStatusFailed); 1031 return false; 1032 } 1033 1034 if (command.GetArgumentCount() == 0) 1035 { 1036 Error error (process->Destroy()); 1037 if (error.Success()) 1038 { 1039 result.SetStatus (eReturnStatusSuccessFinishResult); 1040 } 1041 else 1042 { 1043 result.AppendErrorWithFormat ("Failed to kill process: %s\n", error.AsCString()); 1044 result.SetStatus (eReturnStatusFailed); 1045 } 1046 } 1047 else 1048 { 1049 result.AppendErrorWithFormat("'%s' takes no arguments:\nUsage: \n", 1050 m_cmd_name.c_str(), 1051 m_cmd_syntax.c_str()); 1052 result.SetStatus (eReturnStatusFailed); 1053 } 1054 return result.Succeeded(); 1055 } 1056 }; 1057 1058 //------------------------------------------------------------------------- 1059 // CommandObjectProcessStatus 1060 //------------------------------------------------------------------------- 1061 class CommandObjectProcessStatus : public CommandObject 1062 { 1063 public: 1064 CommandObjectProcessStatus (CommandInterpreter &interpreter) : 1065 CommandObject (interpreter, 1066 "process status", 1067 "Show the current status and location of executing process.", 1068 "process status", 1069 0) 1070 { 1071 } 1072 1073 ~CommandObjectProcessStatus() 1074 { 1075 } 1076 1077 1078 bool 1079 Execute 1080 ( 1081 Args& command, 1082 CommandReturnObject &result 1083 ) 1084 { 1085 StreamString &output_stream = result.GetOutputStream(); 1086 result.SetStatus (eReturnStatusSuccessFinishNoResult); 1087 ExecutionContext exe_ctx(m_interpreter.GetDebugger().GetExecutionContext()); 1088 if (exe_ctx.process) 1089 { 1090 const StateType state = exe_ctx.process->GetState(); 1091 if (StateIsStoppedState(state)) 1092 { 1093 if (state == eStateExited) 1094 { 1095 int exit_status = exe_ctx.process->GetExitStatus(); 1096 const char *exit_description = exe_ctx.process->GetExitDescription(); 1097 output_stream.Printf ("Process %d exited with status = %i (0x%8.8x) %s\n", 1098 exe_ctx.process->GetID(), 1099 exit_status, 1100 exit_status, 1101 exit_description ? exit_description : ""); 1102 } 1103 else 1104 { 1105 output_stream.Printf ("Process %d %s\n", exe_ctx.process->GetID(), StateAsCString (state)); 1106 if (exe_ctx.thread == NULL) 1107 exe_ctx.thread = exe_ctx.process->GetThreadList().GetThreadAtIndex(0).get(); 1108 if (exe_ctx.thread != NULL) 1109 { 1110 DisplayThreadsInfo (m_interpreter, &exe_ctx, result, true, true); 1111 } 1112 else 1113 { 1114 result.AppendError ("No valid thread found in current process."); 1115 result.SetStatus (eReturnStatusFailed); 1116 } 1117 } 1118 } 1119 else 1120 { 1121 output_stream.Printf ("Process %d is running.\n", 1122 exe_ctx.process->GetID()); 1123 } 1124 } 1125 else 1126 { 1127 result.AppendError ("No current location or status available."); 1128 result.SetStatus (eReturnStatusFailed); 1129 } 1130 return result.Succeeded(); 1131 } 1132 }; 1133 1134 //------------------------------------------------------------------------- 1135 // CommandObjectProcessHandle 1136 //------------------------------------------------------------------------- 1137 1138 class CommandObjectProcessHandle : public CommandObject 1139 { 1140 public: 1141 1142 class CommandOptions : public Options 1143 { 1144 public: 1145 1146 CommandOptions () : 1147 Options () 1148 { 1149 ResetOptionValues (); 1150 } 1151 1152 ~CommandOptions () 1153 { 1154 } 1155 1156 Error 1157 SetOptionValue (int option_idx, const char *option_arg) 1158 { 1159 Error error; 1160 char short_option = (char) m_getopt_table[option_idx].val; 1161 1162 switch (short_option) 1163 { 1164 case 's': 1165 stop = option_arg; 1166 break; 1167 case 'n': 1168 notify = option_arg; 1169 break; 1170 case 'p': 1171 pass = option_arg; 1172 break; 1173 default: 1174 error.SetErrorStringWithFormat("Invalid short option character '%c'.\n", short_option); 1175 break; 1176 } 1177 return error; 1178 } 1179 1180 void 1181 ResetOptionValues () 1182 { 1183 Options::ResetOptionValues(); 1184 stop.clear(); 1185 notify.clear(); 1186 pass.clear(); 1187 } 1188 1189 const lldb::OptionDefinition* 1190 GetDefinitions () 1191 { 1192 return g_option_table; 1193 } 1194 1195 // Options table: Required for subclasses of Options. 1196 1197 static lldb::OptionDefinition g_option_table[]; 1198 1199 // Instance variables to hold the values for command options. 1200 1201 std::string stop; 1202 std::string notify; 1203 std::string pass; 1204 }; 1205 1206 1207 CommandObjectProcessHandle (CommandInterpreter &interpreter) : 1208 CommandObject (interpreter, 1209 "process handle", 1210 "Show or update what the process and debugger should do with various signals received from the OS.", 1211 NULL) 1212 { 1213 SetHelpLong ("If no signals are specified, update them all. If no update option is specified, list the current values.\n"); 1214 CommandArgumentEntry arg; 1215 CommandArgumentData signal_arg; 1216 1217 signal_arg.arg_type = eArgTypeUnixSignal; 1218 signal_arg.arg_repetition = eArgRepeatStar; 1219 1220 arg.push_back (signal_arg); 1221 1222 m_arguments.push_back (arg); 1223 } 1224 1225 ~CommandObjectProcessHandle () 1226 { 1227 } 1228 1229 Options * 1230 GetOptions () 1231 { 1232 return &m_options; 1233 } 1234 1235 bool 1236 VerifyCommandOptionValue (const std::string &option, int &real_value) 1237 { 1238 bool okay = true; 1239 1240 bool success = false; 1241 bool tmp_value = Args::StringToBoolean (option.c_str(), false, &success); 1242 1243 if (success && tmp_value) 1244 real_value = 1; 1245 else if (success && !tmp_value) 1246 real_value = 0; 1247 else 1248 { 1249 // If the value isn't 'true' or 'false', it had better be 0 or 1. 1250 real_value = Args::StringToUInt32 (option.c_str(), 3); 1251 if (real_value != 0 && real_value != 1) 1252 okay = false; 1253 } 1254 1255 return okay; 1256 } 1257 1258 void 1259 PrintSignalHeader (Stream &str) 1260 { 1261 str.Printf ("NAME PASS STOP NOTIFY\n"); 1262 str.Printf ("========== ===== ===== ======\n"); 1263 } 1264 1265 void 1266 PrintSignal (Stream &str, int32_t signo, const char *sig_name, UnixSignals &signals) 1267 { 1268 bool stop; 1269 bool suppress; 1270 bool notify; 1271 1272 str.Printf ("%-10s ", sig_name); 1273 if (signals.GetSignalInfo (signo, suppress, stop, notify)) 1274 { 1275 bool pass = !suppress; 1276 str.Printf ("%s %s %s", 1277 (pass ? "true " : "false"), 1278 (stop ? "true " : "false"), 1279 (notify ? "true " : "false")); 1280 } 1281 str.Printf ("\n"); 1282 } 1283 1284 void 1285 PrintSignalInformation (Stream &str, Args &signal_args, int num_valid_signals, UnixSignals &signals) 1286 { 1287 PrintSignalHeader (str); 1288 1289 if (num_valid_signals > 0) 1290 { 1291 size_t num_args = signal_args.GetArgumentCount(); 1292 for (size_t i = 0; i < num_args; ++i) 1293 { 1294 int32_t signo = signals.GetSignalNumberFromName (signal_args.GetArgumentAtIndex (i)); 1295 if (signo != LLDB_INVALID_SIGNAL_NUMBER) 1296 PrintSignal (str, signo, signal_args.GetArgumentAtIndex (i), signals); 1297 } 1298 } 1299 else // Print info for ALL signals 1300 { 1301 int32_t signo = signals.GetFirstSignalNumber(); 1302 while (signo != LLDB_INVALID_SIGNAL_NUMBER) 1303 { 1304 PrintSignal (str, signo, signals.GetSignalAsCString (signo), signals); 1305 signo = signals.GetNextSignalNumber (signo); 1306 } 1307 } 1308 } 1309 1310 bool 1311 Execute (Args &signal_args, CommandReturnObject &result) 1312 { 1313 TargetSP target_sp = m_interpreter.GetDebugger().GetSelectedTarget(); 1314 1315 if (!target_sp) 1316 { 1317 result.AppendError ("No current target;" 1318 " cannot handle signals until you have a valid target and process.\n"); 1319 result.SetStatus (eReturnStatusFailed); 1320 return false; 1321 } 1322 1323 ProcessSP process_sp = target_sp->GetProcessSP(); 1324 1325 if (!process_sp) 1326 { 1327 result.AppendError ("No current process; cannot handle signals until you have a valid process.\n"); 1328 result.SetStatus (eReturnStatusFailed); 1329 return false; 1330 } 1331 1332 int stop_action = -1; // -1 means leave the current setting alone 1333 int pass_action = -1; // -1 means leave the current setting alone 1334 int notify_action = -1; // -1 means leave the current setting alone 1335 1336 if (! m_options.stop.empty() 1337 && ! VerifyCommandOptionValue (m_options.stop, stop_action)) 1338 { 1339 result.AppendError ("Invalid argument for command option --stop; must be true or false.\n"); 1340 result.SetStatus (eReturnStatusFailed); 1341 return false; 1342 } 1343 1344 if (! m_options.notify.empty() 1345 && ! VerifyCommandOptionValue (m_options.notify, notify_action)) 1346 { 1347 result.AppendError ("Invalid argument for command option --notify; must be true or false.\n"); 1348 result.SetStatus (eReturnStatusFailed); 1349 return false; 1350 } 1351 1352 if (! m_options.pass.empty() 1353 && ! VerifyCommandOptionValue (m_options.pass, pass_action)) 1354 { 1355 result.AppendError ("Invalid argument for command option --pass; must be true or false.\n"); 1356 result.SetStatus (eReturnStatusFailed); 1357 return false; 1358 } 1359 1360 size_t num_args = signal_args.GetArgumentCount(); 1361 UnixSignals &signals = process_sp->GetUnixSignals(); 1362 int num_signals_set = 0; 1363 1364 if (num_args > 0) 1365 { 1366 for (size_t i = 0; i < num_args; ++i) 1367 { 1368 int32_t signo = signals.GetSignalNumberFromName (signal_args.GetArgumentAtIndex (i)); 1369 if (signo != LLDB_INVALID_SIGNAL_NUMBER) 1370 { 1371 // Casting the actions as bools here should be okay, because VerifyCommandOptionValue guarantees 1372 // the value is either 0 or 1. 1373 if (stop_action != -1) 1374 signals.SetShouldStop (signo, (bool) stop_action); 1375 if (pass_action != -1) 1376 { 1377 bool suppress = ! ((bool) pass_action); 1378 signals.SetShouldSuppress (signo, suppress); 1379 } 1380 if (notify_action != -1) 1381 signals.SetShouldNotify (signo, (bool) notify_action); 1382 ++num_signals_set; 1383 } 1384 else 1385 { 1386 result.AppendErrorWithFormat ("Invalid signal name '%s'\n", signal_args.GetArgumentAtIndex (i)); 1387 } 1388 } 1389 } 1390 else 1391 { 1392 // No signal specified, if any command options were specified, update ALL signals. 1393 if ((notify_action != -1) || (stop_action != -1) || (pass_action != -1)) 1394 { 1395 if (m_interpreter.Confirm ("Do you really want to update all the signals?", false)) 1396 { 1397 int32_t signo = signals.GetFirstSignalNumber(); 1398 while (signo != LLDB_INVALID_SIGNAL_NUMBER) 1399 { 1400 if (notify_action != -1) 1401 signals.SetShouldNotify (signo, (bool) notify_action); 1402 if (stop_action != -1) 1403 signals.SetShouldStop (signo, (bool) stop_action); 1404 if (pass_action != -1) 1405 { 1406 bool suppress = ! ((bool) pass_action); 1407 signals.SetShouldSuppress (signo, suppress); 1408 } 1409 signo = signals.GetNextSignalNumber (signo); 1410 } 1411 } 1412 } 1413 } 1414 1415 PrintSignalInformation (result.GetOutputStream(), signal_args, num_signals_set, signals); 1416 1417 if (num_signals_set > 0) 1418 result.SetStatus (eReturnStatusSuccessFinishNoResult); 1419 else 1420 result.SetStatus (eReturnStatusFailed); 1421 1422 return result.Succeeded(); 1423 } 1424 1425 protected: 1426 1427 CommandOptions m_options; 1428 }; 1429 1430 lldb::OptionDefinition 1431 CommandObjectProcessHandle::CommandOptions::g_option_table[] = 1432 { 1433 { LLDB_OPT_SET_1, false, "stop", 's', required_argument, NULL, 0, eArgTypeBoolean, "Whether or not the process should be stopped if the signal is received." }, 1434 { LLDB_OPT_SET_1, false, "notify", 'n', required_argument, NULL, 0, eArgTypeBoolean, "Whether or not the debugger should notify the user if the signal is received." }, 1435 { LLDB_OPT_SET_1, false, "pass", 'p', required_argument, NULL, 0, eArgTypeBoolean, "Whether or not the signal should be passed to the process." }, 1436 { 0, false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL } 1437 }; 1438 1439 //------------------------------------------------------------------------- 1440 // CommandObjectMultiwordProcess 1441 //------------------------------------------------------------------------- 1442 1443 CommandObjectMultiwordProcess::CommandObjectMultiwordProcess (CommandInterpreter &interpreter) : 1444 CommandObjectMultiword (interpreter, 1445 "process", 1446 "A set of commands for operating on a process.", 1447 "process <subcommand> [<subcommand-options>]") 1448 { 1449 LoadSubCommand ("attach", CommandObjectSP (new CommandObjectProcessAttach (interpreter))); 1450 LoadSubCommand ("launch", CommandObjectSP (new CommandObjectProcessLaunch (interpreter))); 1451 LoadSubCommand ("continue", CommandObjectSP (new CommandObjectProcessContinue (interpreter))); 1452 LoadSubCommand ("detach", CommandObjectSP (new CommandObjectProcessDetach (interpreter))); 1453 LoadSubCommand ("signal", CommandObjectSP (new CommandObjectProcessSignal (interpreter))); 1454 LoadSubCommand ("handle", CommandObjectSP (new CommandObjectProcessHandle (interpreter))); 1455 LoadSubCommand ("status", CommandObjectSP (new CommandObjectProcessStatus (interpreter))); 1456 LoadSubCommand ("interrupt", CommandObjectSP (new CommandObjectProcessInterrupt (interpreter))); 1457 LoadSubCommand ("kill", CommandObjectSP (new CommandObjectProcessKill (interpreter))); 1458 } 1459 1460 CommandObjectMultiwordProcess::~CommandObjectMultiwordProcess () 1461 { 1462 } 1463 1464