1 //===-- Process.cpp ---------------------------------------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "lldb/Target/Process.h" 11 12 #include "lldb/lldb-private-log.h" 13 14 #include "lldb/Breakpoint/StoppointCallbackContext.h" 15 #include "lldb/Breakpoint/BreakpointLocation.h" 16 #include "lldb/Core/Event.h" 17 #include "lldb/Core/ConnectionFileDescriptor.h" 18 #include "lldb/Core/Debugger.h" 19 #include "lldb/Core/InputReader.h" 20 #include "lldb/Core/Log.h" 21 #include "lldb/Core/Module.h" 22 #include "lldb/Core/PluginManager.h" 23 #include "lldb/Core/State.h" 24 #include "lldb/Expression/ClangUserExpression.h" 25 #include "lldb/Interpreter/CommandInterpreter.h" 26 #include "lldb/Host/Host.h" 27 #include "lldb/Target/ABI.h" 28 #include "lldb/Target/DynamicLoader.h" 29 #include "lldb/Target/OperatingSystem.h" 30 #include "lldb/Target/LanguageRuntime.h" 31 #include "lldb/Target/CPPLanguageRuntime.h" 32 #include "lldb/Target/ObjCLanguageRuntime.h" 33 #include "lldb/Target/Platform.h" 34 #include "lldb/Target/RegisterContext.h" 35 #include "lldb/Target/StopInfo.h" 36 #include "lldb/Target/Target.h" 37 #include "lldb/Target/TargetList.h" 38 #include "lldb/Target/Thread.h" 39 #include "lldb/Target/ThreadPlan.h" 40 #include "lldb/Target/ThreadPlanBase.h" 41 42 using namespace lldb; 43 using namespace lldb_private; 44 45 46 // Comment out line below to disable memory caching, overriding the process setting 47 // target.process.disable-memory-cache 48 #define ENABLE_MEMORY_CACHING 49 50 #ifdef ENABLE_MEMORY_CACHING 51 #define DISABLE_MEM_CACHE_DEFAULT false 52 #else 53 #define DISABLE_MEM_CACHE_DEFAULT true 54 #endif 55 56 class ProcessOptionValueProperties : public OptionValueProperties 57 { 58 public: 59 ProcessOptionValueProperties (const ConstString &name) : 60 OptionValueProperties (name) 61 { 62 } 63 64 // This constructor is used when creating ProcessOptionValueProperties when it 65 // is part of a new lldb_private::Process instance. It will copy all current 66 // global property values as needed 67 ProcessOptionValueProperties (ProcessProperties *global_properties) : 68 OptionValueProperties(*global_properties->GetValueProperties()) 69 { 70 } 71 72 virtual const Property * 73 GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const 74 { 75 // When gettings the value for a key from the process options, we will always 76 // try and grab the setting from the current process if there is one. Else we just 77 // use the one from this instance. 78 if (exe_ctx) 79 { 80 Process *process = exe_ctx->GetProcessPtr(); 81 if (process) 82 { 83 ProcessOptionValueProperties *instance_properties = static_cast<ProcessOptionValueProperties *>(process->GetValueProperties().get()); 84 if (this != instance_properties) 85 return instance_properties->ProtectedGetPropertyAtIndex (idx); 86 } 87 } 88 return ProtectedGetPropertyAtIndex (idx); 89 } 90 }; 91 92 static PropertyDefinition 93 g_properties[] = 94 { 95 { "disable-memory-cache" , OptionValue::eTypeBoolean, false, DISABLE_MEM_CACHE_DEFAULT, NULL, NULL, "Disable reading and caching of memory in fixed-size units." }, 96 { "extra-startup-command", OptionValue::eTypeArray , false, OptionValue::eTypeString, NULL, NULL, "A list containing extra commands understood by the particular process plugin used." }, 97 { "python-os-plugin-path", OptionValue::eTypeFileSpec, false, 0, NULL, NULL, "A path to a python OS plug-in module file that contains a OperatingSystemPlugIn class." }, 98 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL } 99 }; 100 101 enum { 102 ePropertyDisableMemCache, 103 ePropertyExtraStartCommand, 104 ePropertyPythonOSPluginPath 105 }; 106 107 ProcessProperties::ProcessProperties (bool is_global) : 108 Properties () 109 { 110 if (is_global) 111 { 112 m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process"))); 113 m_collection_sp->Initialize(g_properties); 114 m_collection_sp->AppendProperty(ConstString("thread"), 115 ConstString("Settings specify to threads."), 116 true, 117 Thread::GetGlobalProperties()->GetValueProperties()); 118 } 119 else 120 m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get())); 121 } 122 123 ProcessProperties::~ProcessProperties() 124 { 125 } 126 127 bool 128 ProcessProperties::GetDisableMemoryCache() const 129 { 130 const uint32_t idx = ePropertyDisableMemCache; 131 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0); 132 } 133 134 Args 135 ProcessProperties::GetExtraStartupCommands () const 136 { 137 Args args; 138 const uint32_t idx = ePropertyExtraStartCommand; 139 m_collection_sp->GetPropertyAtIndexAsArgs(NULL, idx, args); 140 return args; 141 } 142 143 void 144 ProcessProperties::SetExtraStartupCommands (const Args &args) 145 { 146 const uint32_t idx = ePropertyExtraStartCommand; 147 m_collection_sp->SetPropertyAtIndexFromArgs(NULL, idx, args); 148 } 149 150 FileSpec 151 ProcessProperties::GetPythonOSPluginPath () const 152 { 153 const uint32_t idx = ePropertyPythonOSPluginPath; 154 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx); 155 } 156 157 void 158 ProcessProperties::SetPythonOSPluginPath (const FileSpec &file) 159 { 160 const uint32_t idx = ePropertyPythonOSPluginPath; 161 m_collection_sp->SetPropertyAtIndexAsFileSpec(NULL, idx, file); 162 } 163 164 void 165 ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const 166 { 167 const char *cstr; 168 if (m_pid != LLDB_INVALID_PROCESS_ID) 169 s.Printf (" pid = %llu\n", m_pid); 170 171 if (m_parent_pid != LLDB_INVALID_PROCESS_ID) 172 s.Printf (" parent = %llu\n", m_parent_pid); 173 174 if (m_executable) 175 { 176 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString()); 177 s.PutCString (" file = "); 178 m_executable.Dump(&s); 179 s.EOL(); 180 } 181 const uint32_t argc = m_arguments.GetArgumentCount(); 182 if (argc > 0) 183 { 184 for (uint32_t i=0; i<argc; i++) 185 { 186 const char *arg = m_arguments.GetArgumentAtIndex(i); 187 if (i < 10) 188 s.Printf (" arg[%u] = %s\n", i, arg); 189 else 190 s.Printf ("arg[%u] = %s\n", i, arg); 191 } 192 } 193 194 const uint32_t envc = m_environment.GetArgumentCount(); 195 if (envc > 0) 196 { 197 for (uint32_t i=0; i<envc; i++) 198 { 199 const char *env = m_environment.GetArgumentAtIndex(i); 200 if (i < 10) 201 s.Printf (" env[%u] = %s\n", i, env); 202 else 203 s.Printf ("env[%u] = %s\n", i, env); 204 } 205 } 206 207 if (m_arch.IsValid()) 208 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str()); 209 210 if (m_uid != UINT32_MAX) 211 { 212 cstr = platform->GetUserName (m_uid); 213 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : ""); 214 } 215 if (m_gid != UINT32_MAX) 216 { 217 cstr = platform->GetGroupName (m_gid); 218 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : ""); 219 } 220 if (m_euid != UINT32_MAX) 221 { 222 cstr = platform->GetUserName (m_euid); 223 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : ""); 224 } 225 if (m_egid != UINT32_MAX) 226 { 227 cstr = platform->GetGroupName (m_egid); 228 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : ""); 229 } 230 } 231 232 void 233 ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose) 234 { 235 const char *label; 236 if (show_args || verbose) 237 label = "ARGUMENTS"; 238 else 239 label = "NAME"; 240 241 if (verbose) 242 { 243 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label); 244 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n"); 245 } 246 else 247 { 248 s.Printf ("PID PARENT USER ARCH %s\n", label); 249 s.PutCString ("====== ====== ========== ======= ============================\n"); 250 } 251 } 252 253 void 254 ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const 255 { 256 if (m_pid != LLDB_INVALID_PROCESS_ID) 257 { 258 const char *cstr; 259 s.Printf ("%-6llu %-6llu ", m_pid, m_parent_pid); 260 261 262 if (verbose) 263 { 264 cstr = platform->GetUserName (m_uid); 265 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed 266 s.Printf ("%-10s ", cstr); 267 else 268 s.Printf ("%-10u ", m_uid); 269 270 cstr = platform->GetGroupName (m_gid); 271 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed 272 s.Printf ("%-10s ", cstr); 273 else 274 s.Printf ("%-10u ", m_gid); 275 276 cstr = platform->GetUserName (m_euid); 277 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed 278 s.Printf ("%-10s ", cstr); 279 else 280 s.Printf ("%-10u ", m_euid); 281 282 cstr = platform->GetGroupName (m_egid); 283 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed 284 s.Printf ("%-10s ", cstr); 285 else 286 s.Printf ("%-10u ", m_egid); 287 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : ""); 288 } 289 else 290 { 291 s.Printf ("%-10s %-7d %s ", 292 platform->GetUserName (m_euid), 293 (int)m_arch.GetTriple().getArchName().size(), 294 m_arch.GetTriple().getArchName().data()); 295 } 296 297 if (verbose || show_args) 298 { 299 const uint32_t argc = m_arguments.GetArgumentCount(); 300 if (argc > 0) 301 { 302 for (uint32_t i=0; i<argc; i++) 303 { 304 if (i > 0) 305 s.PutChar (' '); 306 s.PutCString (m_arguments.GetArgumentAtIndex(i)); 307 } 308 } 309 } 310 else 311 { 312 s.PutCString (GetName()); 313 } 314 315 s.EOL(); 316 } 317 } 318 319 320 void 321 ProcessInfo::SetArguments (char const **argv, bool first_arg_is_executable) 322 { 323 m_arguments.SetArguments (argv); 324 325 // Is the first argument the executable? 326 if (first_arg_is_executable) 327 { 328 const char *first_arg = m_arguments.GetArgumentAtIndex (0); 329 if (first_arg) 330 { 331 // Yes the first argument is an executable, set it as the executable 332 // in the launch options. Don't resolve the file path as the path 333 // could be a remote platform path 334 const bool resolve = false; 335 m_executable.SetFile(first_arg, resolve); 336 } 337 } 338 } 339 void 340 ProcessInfo::SetArguments (const Args& args, bool first_arg_is_executable) 341 { 342 // Copy all arguments 343 m_arguments = args; 344 345 // Is the first argument the executable? 346 if (first_arg_is_executable) 347 { 348 const char *first_arg = m_arguments.GetArgumentAtIndex (0); 349 if (first_arg) 350 { 351 // Yes the first argument is an executable, set it as the executable 352 // in the launch options. Don't resolve the file path as the path 353 // could be a remote platform path 354 const bool resolve = false; 355 m_executable.SetFile(first_arg, resolve); 356 } 357 } 358 } 359 360 void 361 ProcessLaunchInfo::FinalizeFileActions (Target *target, bool default_to_use_pty) 362 { 363 // If notthing was specified, then check the process for any default 364 // settings that were set with "settings set" 365 if (m_file_actions.empty()) 366 { 367 if (m_flags.Test(eLaunchFlagDisableSTDIO)) 368 { 369 AppendSuppressFileAction (STDIN_FILENO , true, false); 370 AppendSuppressFileAction (STDOUT_FILENO, false, true); 371 AppendSuppressFileAction (STDERR_FILENO, false, true); 372 } 373 else 374 { 375 // Check for any values that might have gotten set with any of: 376 // (lldb) settings set target.input-path 377 // (lldb) settings set target.output-path 378 // (lldb) settings set target.error-path 379 FileSpec in_path; 380 FileSpec out_path; 381 FileSpec err_path; 382 if (target) 383 { 384 in_path = target->GetStandardInputPath(); 385 out_path = target->GetStandardOutputPath(); 386 err_path = target->GetStandardErrorPath(); 387 } 388 389 if (in_path || out_path || err_path) 390 { 391 char path[PATH_MAX]; 392 if (in_path && in_path.GetPath(path, sizeof(path))) 393 AppendOpenFileAction(STDIN_FILENO, path, true, false); 394 395 if (out_path && out_path.GetPath(path, sizeof(path))) 396 AppendOpenFileAction(STDOUT_FILENO, path, false, true); 397 398 if (err_path && err_path.GetPath(path, sizeof(path))) 399 AppendOpenFileAction(STDERR_FILENO, path, false, true); 400 } 401 else if (default_to_use_pty) 402 { 403 if (m_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, NULL, 0)) 404 { 405 const char *slave_path = m_pty.GetSlaveName (NULL, 0); 406 AppendOpenFileAction(STDIN_FILENO, slave_path, true, false); 407 AppendOpenFileAction(STDOUT_FILENO, slave_path, false, true); 408 AppendOpenFileAction(STDERR_FILENO, slave_path, false, true); 409 } 410 } 411 } 412 } 413 } 414 415 416 bool 417 ProcessLaunchInfo::ConvertArgumentsForLaunchingInShell (Error &error, 418 bool localhost, 419 bool will_debug, 420 bool first_arg_is_full_shell_command) 421 { 422 error.Clear(); 423 424 if (GetFlags().Test (eLaunchFlagLaunchInShell)) 425 { 426 const char *shell_executable = GetShell(); 427 if (shell_executable) 428 { 429 char shell_resolved_path[PATH_MAX]; 430 431 if (localhost) 432 { 433 FileSpec shell_filespec (shell_executable, true); 434 435 if (!shell_filespec.Exists()) 436 { 437 // Resolve the path in case we just got "bash", "sh" or "tcsh" 438 if (!shell_filespec.ResolveExecutableLocation ()) 439 { 440 error.SetErrorStringWithFormat("invalid shell path '%s'", shell_executable); 441 return false; 442 } 443 } 444 shell_filespec.GetPath (shell_resolved_path, sizeof(shell_resolved_path)); 445 shell_executable = shell_resolved_path; 446 } 447 448 const char **argv = GetArguments().GetConstArgumentVector (); 449 if (argv == NULL || argv[0] == NULL) 450 return false; 451 Args shell_arguments; 452 std::string safe_arg; 453 shell_arguments.AppendArgument (shell_executable); 454 shell_arguments.AppendArgument ("-c"); 455 StreamString shell_command; 456 if (will_debug) 457 { 458 // Add a modified PATH environment variable in case argv[0] 459 // is a relative path 460 const char *argv0 = argv[0]; 461 if (argv0 && (argv0[0] != '/' && argv0[0] != '~')) 462 { 463 // We have a relative path to our executable which may not work if 464 // we just try to run "a.out" (without it being converted to "./a.out") 465 const char *working_dir = GetWorkingDirectory(); 466 std::string new_path("PATH="); 467 const size_t empty_path_len = new_path.size(); 468 469 if (working_dir && working_dir[0]) 470 { 471 new_path += working_dir; 472 } 473 else 474 { 475 char current_working_dir[PATH_MAX]; 476 const char *cwd = getcwd(current_working_dir, sizeof(current_working_dir)); 477 if (cwd && cwd[0]) 478 new_path += cwd; 479 } 480 const char *curr_path = getenv("PATH"); 481 if (curr_path) 482 { 483 if (new_path.size() > empty_path_len) 484 new_path += ':'; 485 new_path += curr_path; 486 } 487 new_path += ' '; 488 shell_command.PutCString(new_path.c_str()); 489 } 490 491 shell_command.PutCString ("exec"); 492 493 #if defined(__APPLE__) 494 // Only Apple supports /usr/bin/arch being able to specify the architecture 495 if (GetArchitecture().IsValid()) 496 { 497 shell_command.Printf(" /usr/bin/arch -arch %s", GetArchitecture().GetArchitectureName()); 498 // Set the resume count to 2: 499 // 1 - stop in shell 500 // 2 - stop in /usr/bin/arch 501 // 3 - then we will stop in our program 502 SetResumeCount(2); 503 } 504 else 505 { 506 // Set the resume count to 1: 507 // 1 - stop in shell 508 // 2 - then we will stop in our program 509 SetResumeCount(1); 510 } 511 #else 512 // Set the resume count to 1: 513 // 1 - stop in shell 514 // 2 - then we will stop in our program 515 SetResumeCount(1); 516 #endif 517 } 518 519 if (first_arg_is_full_shell_command) 520 { 521 // There should only be one argument that is the shell command itself to be used as is 522 if (argv[0] && !argv[1]) 523 shell_command.Printf("%s", argv[0]); 524 else 525 return false; 526 } 527 else 528 { 529 for (size_t i=0; argv[i] != NULL; ++i) 530 { 531 const char *arg = Args::GetShellSafeArgument (argv[i], safe_arg); 532 shell_command.Printf(" %s", arg); 533 } 534 } 535 shell_arguments.AppendArgument (shell_command.GetString().c_str()); 536 m_executable.SetFile(shell_executable, false); 537 m_arguments = shell_arguments; 538 return true; 539 } 540 else 541 { 542 error.SetErrorString ("invalid shell path"); 543 } 544 } 545 else 546 { 547 error.SetErrorString ("not launching in shell"); 548 } 549 return false; 550 } 551 552 553 bool 554 ProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write) 555 { 556 if ((read || write) && fd >= 0 && path && path[0]) 557 { 558 m_action = eFileActionOpen; 559 m_fd = fd; 560 if (read && write) 561 m_arg = O_NOCTTY | O_CREAT | O_RDWR; 562 else if (read) 563 m_arg = O_NOCTTY | O_RDONLY; 564 else 565 m_arg = O_NOCTTY | O_CREAT | O_WRONLY; 566 m_path.assign (path); 567 return true; 568 } 569 else 570 { 571 Clear(); 572 } 573 return false; 574 } 575 576 bool 577 ProcessLaunchInfo::FileAction::Close (int fd) 578 { 579 Clear(); 580 if (fd >= 0) 581 { 582 m_action = eFileActionClose; 583 m_fd = fd; 584 } 585 return m_fd >= 0; 586 } 587 588 589 bool 590 ProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd) 591 { 592 Clear(); 593 if (fd >= 0 && dup_fd >= 0) 594 { 595 m_action = eFileActionDuplicate; 596 m_fd = fd; 597 m_arg = dup_fd; 598 } 599 return m_fd >= 0; 600 } 601 602 603 604 bool 605 ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (posix_spawn_file_actions_t *file_actions, 606 const FileAction *info, 607 Log *log, 608 Error& error) 609 { 610 if (info == NULL) 611 return false; 612 613 switch (info->m_action) 614 { 615 case eFileActionNone: 616 error.Clear(); 617 break; 618 619 case eFileActionClose: 620 if (info->m_fd == -1) 621 error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)"); 622 else 623 { 624 error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd), 625 eErrorTypePOSIX); 626 if (log && (error.Fail() || log)) 627 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)", 628 file_actions, info->m_fd); 629 } 630 break; 631 632 case eFileActionDuplicate: 633 if (info->m_fd == -1) 634 error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)"); 635 else if (info->m_arg == -1) 636 error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)"); 637 else 638 { 639 error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg), 640 eErrorTypePOSIX); 641 if (log && (error.Fail() || log)) 642 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)", 643 file_actions, info->m_fd, info->m_arg); 644 } 645 break; 646 647 case eFileActionOpen: 648 if (info->m_fd == -1) 649 error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)"); 650 else 651 { 652 int oflag = info->m_arg; 653 654 mode_t mode = 0; 655 656 if (oflag & O_CREAT) 657 mode = 0640; 658 659 error.SetError (::posix_spawn_file_actions_addopen (file_actions, 660 info->m_fd, 661 info->m_path.c_str(), 662 oflag, 663 mode), 664 eErrorTypePOSIX); 665 if (error.Fail() || log) 666 error.PutToLog(log, 667 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)", 668 file_actions, info->m_fd, info->m_path.c_str(), oflag, mode); 669 } 670 break; 671 672 default: 673 error.SetErrorStringWithFormat ("invalid file action: %i", info->m_action); 674 break; 675 } 676 return error.Success(); 677 } 678 679 Error 680 ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg) 681 { 682 Error error; 683 char short_option = (char) m_getopt_table[option_idx].val; 684 685 switch (short_option) 686 { 687 case 's': // Stop at program entry point 688 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry); 689 break; 690 691 case 'i': // STDIN for read only 692 { 693 ProcessLaunchInfo::FileAction action; 694 if (action.Open (STDIN_FILENO, option_arg, true, false)) 695 launch_info.AppendFileAction (action); 696 } 697 break; 698 699 case 'o': // Open STDOUT for write only 700 { 701 ProcessLaunchInfo::FileAction action; 702 if (action.Open (STDOUT_FILENO, option_arg, false, true)) 703 launch_info.AppendFileAction (action); 704 } 705 break; 706 707 case 'e': // STDERR for write only 708 { 709 ProcessLaunchInfo::FileAction action; 710 if (action.Open (STDERR_FILENO, option_arg, false, true)) 711 launch_info.AppendFileAction (action); 712 } 713 break; 714 715 716 case 'p': // Process plug-in name 717 launch_info.SetProcessPluginName (option_arg); 718 break; 719 720 case 'n': // Disable STDIO 721 { 722 ProcessLaunchInfo::FileAction action; 723 if (action.Open (STDIN_FILENO, "/dev/null", true, false)) 724 launch_info.AppendFileAction (action); 725 if (action.Open (STDOUT_FILENO, "/dev/null", false, true)) 726 launch_info.AppendFileAction (action); 727 if (action.Open (STDERR_FILENO, "/dev/null", false, true)) 728 launch_info.AppendFileAction (action); 729 } 730 break; 731 732 case 'w': 733 launch_info.SetWorkingDirectory (option_arg); 734 break; 735 736 case 't': // Open process in new terminal window 737 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY); 738 break; 739 740 case 'a': 741 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get())) 742 launch_info.GetArchitecture().SetTriple (option_arg); 743 break; 744 745 case 'A': 746 launch_info.GetFlags().Set (eLaunchFlagDisableASLR); 747 break; 748 749 case 'c': 750 if (option_arg && option_arg[0]) 751 launch_info.SetShell (option_arg); 752 else 753 launch_info.SetShell ("/bin/bash"); 754 break; 755 756 case 'v': 757 launch_info.GetEnvironmentEntries().AppendArgument(option_arg); 758 break; 759 760 default: 761 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option); 762 break; 763 764 } 765 return error; 766 } 767 768 OptionDefinition 769 ProcessLaunchCommandOptions::g_option_table[] = 770 { 771 { LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', no_argument, NULL, 0, eArgTypeNone, "Stop at the entry point of the program when launching a process."}, 772 { LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', no_argument, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."}, 773 { LLDB_OPT_SET_ALL, false, "plugin", 'p', required_argument, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."}, 774 { LLDB_OPT_SET_ALL, false, "working-dir", 'w', required_argument, NULL, 0, eArgTypeDirectoryName, "Set the current working directory to <path> when running the inferior."}, 775 { LLDB_OPT_SET_ALL, false, "arch", 'a', required_argument, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."}, 776 { LLDB_OPT_SET_ALL, false, "environment", 'v', required_argument, NULL, 0, eArgTypeNone, "Specify an environment variable name/value stirng (--environement NAME=VALUE). Can be specified multiple times for subsequent environment entries."}, 777 { LLDB_OPT_SET_ALL, false, "shell", 'c', optional_argument, NULL, 0, eArgTypeFilename, "Run the process in a shell (not supported on all platforms)."}, 778 779 { LLDB_OPT_SET_1 , false, "stdin", 'i', required_argument, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."}, 780 { LLDB_OPT_SET_1 , false, "stdout", 'o', required_argument, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."}, 781 { LLDB_OPT_SET_1 , false, "stderr", 'e', required_argument, NULL, 0, eArgTypeFilename, "Redirect stderr for the process to <filename>."}, 782 783 { LLDB_OPT_SET_2 , false, "tty", 't', no_argument, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."}, 784 785 { LLDB_OPT_SET_3 , false, "no-stdio", 'n', no_argument, NULL, 0, eArgTypeNone, "Do not set up for terminal I/O to go to running process."}, 786 787 { 0 , false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL } 788 }; 789 790 791 792 bool 793 ProcessInstanceInfoMatch::NameMatches (const char *process_name) const 794 { 795 if (m_name_match_type == eNameMatchIgnore || process_name == NULL) 796 return true; 797 const char *match_name = m_match_info.GetName(); 798 if (!match_name) 799 return true; 800 801 return lldb_private::NameMatches (process_name, m_name_match_type, match_name); 802 } 803 804 bool 805 ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const 806 { 807 if (!NameMatches (proc_info.GetName())) 808 return false; 809 810 if (m_match_info.ProcessIDIsValid() && 811 m_match_info.GetProcessID() != proc_info.GetProcessID()) 812 return false; 813 814 if (m_match_info.ParentProcessIDIsValid() && 815 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID()) 816 return false; 817 818 if (m_match_info.UserIDIsValid () && 819 m_match_info.GetUserID() != proc_info.GetUserID()) 820 return false; 821 822 if (m_match_info.GroupIDIsValid () && 823 m_match_info.GetGroupID() != proc_info.GetGroupID()) 824 return false; 825 826 if (m_match_info.EffectiveUserIDIsValid () && 827 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID()) 828 return false; 829 830 if (m_match_info.EffectiveGroupIDIsValid () && 831 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID()) 832 return false; 833 834 if (m_match_info.GetArchitecture().IsValid() && 835 m_match_info.GetArchitecture() != proc_info.GetArchitecture()) 836 return false; 837 return true; 838 } 839 840 bool 841 ProcessInstanceInfoMatch::MatchAllProcesses () const 842 { 843 if (m_name_match_type != eNameMatchIgnore) 844 return false; 845 846 if (m_match_info.ProcessIDIsValid()) 847 return false; 848 849 if (m_match_info.ParentProcessIDIsValid()) 850 return false; 851 852 if (m_match_info.UserIDIsValid ()) 853 return false; 854 855 if (m_match_info.GroupIDIsValid ()) 856 return false; 857 858 if (m_match_info.EffectiveUserIDIsValid ()) 859 return false; 860 861 if (m_match_info.EffectiveGroupIDIsValid ()) 862 return false; 863 864 if (m_match_info.GetArchitecture().IsValid()) 865 return false; 866 867 if (m_match_all_users) 868 return false; 869 870 return true; 871 872 } 873 874 void 875 ProcessInstanceInfoMatch::Clear() 876 { 877 m_match_info.Clear(); 878 m_name_match_type = eNameMatchIgnore; 879 m_match_all_users = false; 880 } 881 882 ProcessSP 883 Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path) 884 { 885 ProcessSP process_sp; 886 ProcessCreateInstance create_callback = NULL; 887 if (plugin_name) 888 { 889 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name); 890 if (create_callback) 891 { 892 process_sp = create_callback(target, listener, crash_file_path); 893 if (process_sp) 894 { 895 if (!process_sp->CanDebug(target, true)) 896 process_sp.reset(); 897 } 898 } 899 } 900 else 901 { 902 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx) 903 { 904 process_sp = create_callback(target, listener, crash_file_path); 905 if (process_sp) 906 { 907 if (!process_sp->CanDebug(target, false)) 908 process_sp.reset(); 909 else 910 break; 911 } 912 } 913 } 914 return process_sp; 915 } 916 917 ConstString & 918 Process::GetStaticBroadcasterClass () 919 { 920 static ConstString class_name ("lldb.process"); 921 return class_name; 922 } 923 924 //---------------------------------------------------------------------- 925 // Process constructor 926 //---------------------------------------------------------------------- 927 Process::Process(Target &target, Listener &listener) : 928 ProcessProperties (false), 929 UserID (LLDB_INVALID_PROCESS_ID), 930 Broadcaster (&(target.GetDebugger()), "lldb.process"), 931 m_target (target), 932 m_public_state (eStateUnloaded), 933 m_private_state (eStateUnloaded), 934 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"), 935 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"), 936 m_private_state_listener ("lldb.process.internal_state_listener"), 937 m_private_state_control_wait(), 938 m_private_state_thread (LLDB_INVALID_HOST_THREAD), 939 m_mod_id (), 940 m_thread_index_id (0), 941 m_exit_status (-1), 942 m_exit_string (), 943 m_thread_list (this), 944 m_notifications (), 945 m_image_tokens (), 946 m_listener (listener), 947 m_breakpoint_site_list (), 948 m_dynamic_checkers_ap (), 949 m_unix_signals (), 950 m_abi_sp (), 951 m_process_input_reader (), 952 m_stdio_communication ("process.stdio"), 953 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive), 954 m_stdout_data (), 955 m_stderr_data (), 956 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive), 957 m_profile_data (), 958 m_memory_cache (*this), 959 m_allocated_memory_cache (*this), 960 m_should_detach (false), 961 m_next_event_action_ap(), 962 m_run_lock (), 963 m_currently_handling_event(false), 964 m_finalize_called(false), 965 m_can_jit(eCanJITDontKnow) 966 { 967 CheckInWithManager (); 968 969 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT)); 970 if (log) 971 log->Printf ("%p Process::Process()", this); 972 973 SetEventName (eBroadcastBitStateChanged, "state-changed"); 974 SetEventName (eBroadcastBitInterrupt, "interrupt"); 975 SetEventName (eBroadcastBitSTDOUT, "stdout-available"); 976 SetEventName (eBroadcastBitSTDERR, "stderr-available"); 977 SetEventName (eBroadcastBitProfileData, "profile-data-available"); 978 979 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" ); 980 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" ); 981 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume"); 982 983 listener.StartListeningForEvents (this, 984 eBroadcastBitStateChanged | 985 eBroadcastBitInterrupt | 986 eBroadcastBitSTDOUT | 987 eBroadcastBitSTDERR | 988 eBroadcastBitProfileData); 989 990 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster, 991 eBroadcastBitStateChanged | 992 eBroadcastBitInterrupt); 993 994 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster, 995 eBroadcastInternalStateControlStop | 996 eBroadcastInternalStateControlPause | 997 eBroadcastInternalStateControlResume); 998 } 999 1000 //---------------------------------------------------------------------- 1001 // Destructor 1002 //---------------------------------------------------------------------- 1003 Process::~Process() 1004 { 1005 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT)); 1006 if (log) 1007 log->Printf ("%p Process::~Process()", this); 1008 StopPrivateStateThread(); 1009 } 1010 1011 const ProcessPropertiesSP & 1012 Process::GetGlobalProperties() 1013 { 1014 static ProcessPropertiesSP g_settings_sp; 1015 if (!g_settings_sp) 1016 g_settings_sp.reset (new ProcessProperties (true)); 1017 return g_settings_sp; 1018 } 1019 1020 void 1021 Process::Finalize() 1022 { 1023 switch (GetPrivateState()) 1024 { 1025 case eStateConnected: 1026 case eStateAttaching: 1027 case eStateLaunching: 1028 case eStateStopped: 1029 case eStateRunning: 1030 case eStateStepping: 1031 case eStateCrashed: 1032 case eStateSuspended: 1033 if (GetShouldDetach()) 1034 Detach(); 1035 else 1036 Destroy(); 1037 break; 1038 1039 case eStateInvalid: 1040 case eStateUnloaded: 1041 case eStateDetached: 1042 case eStateExited: 1043 break; 1044 } 1045 1046 // Clear our broadcaster before we proceed with destroying 1047 Broadcaster::Clear(); 1048 1049 // Do any cleanup needed prior to being destructed... Subclasses 1050 // that override this method should call this superclass method as well. 1051 1052 // We need to destroy the loader before the derived Process class gets destroyed 1053 // since it is very likely that undoing the loader will require access to the real process. 1054 m_dynamic_checkers_ap.reset(); 1055 m_abi_sp.reset(); 1056 m_os_ap.reset(); 1057 m_dyld_ap.reset(); 1058 m_thread_list.Destroy(); 1059 std::vector<Notifications> empty_notifications; 1060 m_notifications.swap(empty_notifications); 1061 m_image_tokens.clear(); 1062 m_memory_cache.Clear(); 1063 m_allocated_memory_cache.Clear(); 1064 m_language_runtimes.clear(); 1065 m_next_event_action_ap.reset(); 1066 //#ifdef LLDB_CONFIGURATION_DEBUG 1067 // StreamFile s(stdout, false); 1068 // EventSP event_sp; 1069 // while (m_private_state_listener.GetNextEvent(event_sp)) 1070 // { 1071 // event_sp->Dump (&s); 1072 // s.EOL(); 1073 // } 1074 //#endif 1075 // We have to be very careful here as the m_private_state_listener might 1076 // contain events that have ProcessSP values in them which can keep this 1077 // process around forever. These events need to be cleared out. 1078 m_private_state_listener.Clear(); 1079 m_finalize_called = true; 1080 } 1081 1082 void 1083 Process::RegisterNotificationCallbacks (const Notifications& callbacks) 1084 { 1085 m_notifications.push_back(callbacks); 1086 if (callbacks.initialize != NULL) 1087 callbacks.initialize (callbacks.baton, this); 1088 } 1089 1090 bool 1091 Process::UnregisterNotificationCallbacks(const Notifications& callbacks) 1092 { 1093 std::vector<Notifications>::iterator pos, end = m_notifications.end(); 1094 for (pos = m_notifications.begin(); pos != end; ++pos) 1095 { 1096 if (pos->baton == callbacks.baton && 1097 pos->initialize == callbacks.initialize && 1098 pos->process_state_changed == callbacks.process_state_changed) 1099 { 1100 m_notifications.erase(pos); 1101 return true; 1102 } 1103 } 1104 return false; 1105 } 1106 1107 void 1108 Process::SynchronouslyNotifyStateChanged (StateType state) 1109 { 1110 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end(); 1111 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos) 1112 { 1113 if (notification_pos->process_state_changed) 1114 notification_pos->process_state_changed (notification_pos->baton, this, state); 1115 } 1116 } 1117 1118 // FIXME: We need to do some work on events before the general Listener sees them. 1119 // For instance if we are continuing from a breakpoint, we need to ensure that we do 1120 // the little "insert real insn, step & stop" trick. But we can't do that when the 1121 // event is delivered by the broadcaster - since that is done on the thread that is 1122 // waiting for new events, so if we needed more than one event for our handling, we would 1123 // stall. So instead we do it when we fetch the event off of the queue. 1124 // 1125 1126 StateType 1127 Process::GetNextEvent (EventSP &event_sp) 1128 { 1129 StateType state = eStateInvalid; 1130 1131 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp) 1132 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get()); 1133 1134 return state; 1135 } 1136 1137 1138 StateType 1139 Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr) 1140 { 1141 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target. 1142 // We have to actually check each event, and in the case of a stopped event check the restarted flag 1143 // on the event. 1144 if (event_sp_ptr) 1145 event_sp_ptr->reset(); 1146 StateType state = GetState(); 1147 // If we are exited or detached, we won't ever get back to any 1148 // other valid state... 1149 if (state == eStateDetached || state == eStateExited) 1150 return state; 1151 1152 while (state != eStateInvalid) 1153 { 1154 EventSP event_sp; 1155 state = WaitForStateChangedEvents (timeout, event_sp); 1156 if (event_sp_ptr && event_sp) 1157 *event_sp_ptr = event_sp; 1158 1159 switch (state) 1160 { 1161 case eStateCrashed: 1162 case eStateDetached: 1163 case eStateExited: 1164 case eStateUnloaded: 1165 return state; 1166 case eStateStopped: 1167 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) 1168 continue; 1169 else 1170 return state; 1171 default: 1172 continue; 1173 } 1174 } 1175 return state; 1176 } 1177 1178 1179 StateType 1180 Process::WaitForState 1181 ( 1182 const TimeValue *timeout, 1183 const StateType *match_states, const uint32_t num_match_states 1184 ) 1185 { 1186 EventSP event_sp; 1187 uint32_t i; 1188 StateType state = GetState(); 1189 while (state != eStateInvalid) 1190 { 1191 // If we are exited or detached, we won't ever get back to any 1192 // other valid state... 1193 if (state == eStateDetached || state == eStateExited) 1194 return state; 1195 1196 state = WaitForStateChangedEvents (timeout, event_sp); 1197 1198 for (i=0; i<num_match_states; ++i) 1199 { 1200 if (match_states[i] == state) 1201 return state; 1202 } 1203 } 1204 return state; 1205 } 1206 1207 bool 1208 Process::HijackProcessEvents (Listener *listener) 1209 { 1210 if (listener != NULL) 1211 { 1212 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt); 1213 } 1214 else 1215 return false; 1216 } 1217 1218 void 1219 Process::RestoreProcessEvents () 1220 { 1221 RestoreBroadcaster(); 1222 } 1223 1224 bool 1225 Process::HijackPrivateProcessEvents (Listener *listener) 1226 { 1227 if (listener != NULL) 1228 { 1229 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt); 1230 } 1231 else 1232 return false; 1233 } 1234 1235 void 1236 Process::RestorePrivateProcessEvents () 1237 { 1238 m_private_state_broadcaster.RestoreBroadcaster(); 1239 } 1240 1241 StateType 1242 Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp) 1243 { 1244 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 1245 1246 if (log) 1247 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout); 1248 1249 StateType state = eStateInvalid; 1250 if (m_listener.WaitForEventForBroadcasterWithType (timeout, 1251 this, 1252 eBroadcastBitStateChanged | eBroadcastBitInterrupt, 1253 event_sp)) 1254 { 1255 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged) 1256 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 1257 else if (log) 1258 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__); 1259 } 1260 1261 if (log) 1262 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", 1263 __FUNCTION__, 1264 timeout, 1265 StateAsCString(state)); 1266 return state; 1267 } 1268 1269 Event * 1270 Process::PeekAtStateChangedEvents () 1271 { 1272 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 1273 1274 if (log) 1275 log->Printf ("Process::%s...", __FUNCTION__); 1276 1277 Event *event_ptr; 1278 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this, 1279 eBroadcastBitStateChanged); 1280 if (log) 1281 { 1282 if (event_ptr) 1283 { 1284 log->Printf ("Process::%s (event_ptr) => %s", 1285 __FUNCTION__, 1286 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr))); 1287 } 1288 else 1289 { 1290 log->Printf ("Process::%s no events found", 1291 __FUNCTION__); 1292 } 1293 } 1294 return event_ptr; 1295 } 1296 1297 StateType 1298 Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp) 1299 { 1300 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 1301 1302 if (log) 1303 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout); 1304 1305 StateType state = eStateInvalid; 1306 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout, 1307 &m_private_state_broadcaster, 1308 eBroadcastBitStateChanged | eBroadcastBitInterrupt, 1309 event_sp)) 1310 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged) 1311 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 1312 1313 // This is a bit of a hack, but when we wait here we could very well return 1314 // to the command-line, and that could disable the log, which would render the 1315 // log we got above invalid. 1316 if (log) 1317 { 1318 if (state == eStateInvalid) 1319 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout); 1320 else 1321 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state)); 1322 } 1323 return state; 1324 } 1325 1326 bool 1327 Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only) 1328 { 1329 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 1330 1331 if (log) 1332 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout); 1333 1334 if (control_only) 1335 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp); 1336 else 1337 return m_private_state_listener.WaitForEvent(timeout, event_sp); 1338 } 1339 1340 bool 1341 Process::IsRunning () const 1342 { 1343 return StateIsRunningState (m_public_state.GetValue()); 1344 } 1345 1346 int 1347 Process::GetExitStatus () 1348 { 1349 if (m_public_state.GetValue() == eStateExited) 1350 return m_exit_status; 1351 return -1; 1352 } 1353 1354 1355 const char * 1356 Process::GetExitDescription () 1357 { 1358 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty()) 1359 return m_exit_string.c_str(); 1360 return NULL; 1361 } 1362 1363 bool 1364 Process::SetExitStatus (int status, const char *cstr) 1365 { 1366 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS)); 1367 if (log) 1368 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)", 1369 status, status, 1370 cstr ? "\"" : "", 1371 cstr ? cstr : "NULL", 1372 cstr ? "\"" : ""); 1373 1374 // We were already in the exited state 1375 if (m_private_state.GetValue() == eStateExited) 1376 { 1377 if (log) 1378 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited"); 1379 return false; 1380 } 1381 1382 m_exit_status = status; 1383 if (cstr) 1384 m_exit_string = cstr; 1385 else 1386 m_exit_string.clear(); 1387 1388 DidExit (); 1389 1390 SetPrivateState (eStateExited); 1391 return true; 1392 } 1393 1394 // This static callback can be used to watch for local child processes on 1395 // the current host. The the child process exits, the process will be 1396 // found in the global target list (we want to be completely sure that the 1397 // lldb_private::Process doesn't go away before we can deliver the signal. 1398 bool 1399 Process::SetProcessExitStatus (void *callback_baton, 1400 lldb::pid_t pid, 1401 bool exited, 1402 int signo, // Zero for no signal 1403 int exit_status // Exit value of process if signal is zero 1404 ) 1405 { 1406 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS)); 1407 if (log) 1408 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%llu, exited=%i, signal=%i, exit_status=%i)\n", 1409 callback_baton, 1410 pid, 1411 exited, 1412 signo, 1413 exit_status); 1414 1415 if (exited) 1416 { 1417 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid)); 1418 if (target_sp) 1419 { 1420 ProcessSP process_sp (target_sp->GetProcessSP()); 1421 if (process_sp) 1422 { 1423 const char *signal_cstr = NULL; 1424 if (signo) 1425 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo); 1426 1427 process_sp->SetExitStatus (exit_status, signal_cstr); 1428 } 1429 } 1430 return true; 1431 } 1432 return false; 1433 } 1434 1435 1436 void 1437 Process::UpdateThreadListIfNeeded () 1438 { 1439 const uint32_t stop_id = GetStopID(); 1440 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID()) 1441 { 1442 const StateType state = GetPrivateState(); 1443 if (StateIsStoppedState (state, true)) 1444 { 1445 Mutex::Locker locker (m_thread_list.GetMutex ()); 1446 // m_thread_list does have its own mutex, but we need to 1447 // hold onto the mutex between the call to UpdateThreadList(...) 1448 // and the os->UpdateThreadList(...) so it doesn't change on us 1449 ThreadList new_thread_list(this); 1450 // Always update the thread list with the protocol specific 1451 // thread list, but only update if "true" is returned 1452 if (UpdateThreadList (m_thread_list, new_thread_list)) 1453 { 1454 OperatingSystem *os = GetOperatingSystem (); 1455 if (os) 1456 os->UpdateThreadList (m_thread_list, new_thread_list); 1457 m_thread_list.Update (new_thread_list); 1458 m_thread_list.SetStopID (stop_id); 1459 } 1460 } 1461 } 1462 } 1463 1464 uint32_t 1465 Process::GetNextThreadIndexID () 1466 { 1467 return ++m_thread_index_id; 1468 } 1469 1470 StateType 1471 Process::GetState() 1472 { 1473 // If any other threads access this we will need a mutex for it 1474 return m_public_state.GetValue (); 1475 } 1476 1477 void 1478 Process::SetPublicState (StateType new_state) 1479 { 1480 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS)); 1481 if (log) 1482 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state)); 1483 const StateType old_state = m_public_state.GetValue(); 1484 m_public_state.SetValue (new_state); 1485 1486 // On the transition from Run to Stopped, we unlock the writer end of the 1487 // run lock. The lock gets locked in Resume, which is the public API 1488 // to tell the program to run. 1489 if (!IsHijackedForEvent(eBroadcastBitStateChanged)) 1490 { 1491 if (new_state == eStateDetached) 1492 { 1493 if (log) 1494 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state)); 1495 m_run_lock.WriteUnlock(); 1496 } 1497 else 1498 { 1499 const bool old_state_is_stopped = StateIsStoppedState(old_state, false); 1500 const bool new_state_is_stopped = StateIsStoppedState(new_state, false); 1501 if (old_state_is_stopped != new_state_is_stopped) 1502 { 1503 if (new_state_is_stopped) 1504 { 1505 if (log) 1506 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state)); 1507 m_run_lock.WriteUnlock(); 1508 } 1509 } 1510 } 1511 } 1512 } 1513 1514 Error 1515 Process::Resume () 1516 { 1517 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS)); 1518 if (log) 1519 log->Printf("Process::Resume -- locking run lock"); 1520 if (!m_run_lock.WriteTryLock()) 1521 { 1522 Error error("Resume request failed - process still running."); 1523 if (log) 1524 log->Printf ("Process::Resume: -- WriteTryLock failed, not resuming."); 1525 return error; 1526 } 1527 return PrivateResume(); 1528 } 1529 1530 StateType 1531 Process::GetPrivateState () 1532 { 1533 return m_private_state.GetValue(); 1534 } 1535 1536 void 1537 Process::SetPrivateState (StateType new_state) 1538 { 1539 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS)); 1540 bool state_changed = false; 1541 1542 if (log) 1543 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state)); 1544 1545 Mutex::Locker locker(m_private_state.GetMutex()); 1546 1547 const StateType old_state = m_private_state.GetValueNoLock (); 1548 state_changed = old_state != new_state; 1549 // This code is left commented out in case we ever need to control 1550 // the private process state with another run lock. Right now it doesn't 1551 // seem like we need to do this, but if we ever do, we can uncomment and 1552 // use this code. 1553 // const bool old_state_is_stopped = StateIsStoppedState(old_state, false); 1554 // const bool new_state_is_stopped = StateIsStoppedState(new_state, false); 1555 // if (old_state_is_stopped != new_state_is_stopped) 1556 // { 1557 // if (new_state_is_stopped) 1558 // m_private_run_lock.WriteUnlock(); 1559 // else 1560 // m_private_run_lock.WriteLock(); 1561 // } 1562 1563 if (state_changed) 1564 { 1565 m_private_state.SetValueNoLock (new_state); 1566 if (StateIsStoppedState(new_state, false)) 1567 { 1568 m_mod_id.BumpStopID(); 1569 m_memory_cache.Clear(); 1570 if (log) 1571 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID()); 1572 } 1573 // Use our target to get a shared pointer to ourselves... 1574 if (m_finalize_called && PrivateStateThreadIsValid() == false) 1575 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state)); 1576 else 1577 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state)); 1578 } 1579 else 1580 { 1581 if (log) 1582 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state)); 1583 } 1584 } 1585 1586 void 1587 Process::SetRunningUserExpression (bool on) 1588 { 1589 m_mod_id.SetRunningUserExpression (on); 1590 } 1591 1592 addr_t 1593 Process::GetImageInfoAddress() 1594 { 1595 return LLDB_INVALID_ADDRESS; 1596 } 1597 1598 //---------------------------------------------------------------------- 1599 // LoadImage 1600 // 1601 // This function provides a default implementation that works for most 1602 // unix variants. Any Process subclasses that need to do shared library 1603 // loading differently should override LoadImage and UnloadImage and 1604 // do what is needed. 1605 //---------------------------------------------------------------------- 1606 uint32_t 1607 Process::LoadImage (const FileSpec &image_spec, Error &error) 1608 { 1609 char path[PATH_MAX]; 1610 image_spec.GetPath(path, sizeof(path)); 1611 1612 DynamicLoader *loader = GetDynamicLoader(); 1613 if (loader) 1614 { 1615 error = loader->CanLoadImage(); 1616 if (error.Fail()) 1617 return LLDB_INVALID_IMAGE_TOKEN; 1618 } 1619 1620 if (error.Success()) 1621 { 1622 ThreadSP thread_sp(GetThreadList ().GetSelectedThread()); 1623 1624 if (thread_sp) 1625 { 1626 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0)); 1627 1628 if (frame_sp) 1629 { 1630 ExecutionContext exe_ctx; 1631 frame_sp->CalculateExecutionContext (exe_ctx); 1632 bool unwind_on_error = true; 1633 StreamString expr; 1634 expr.Printf("dlopen (\"%s\", 2)", path); 1635 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n"; 1636 lldb::ValueObjectSP result_valobj_sp; 1637 ClangUserExpression::Evaluate (exe_ctx, 1638 eExecutionPolicyAlways, 1639 lldb::eLanguageTypeUnknown, 1640 ClangUserExpression::eResultTypeAny, 1641 unwind_on_error, 1642 expr.GetData(), 1643 prefix, 1644 result_valobj_sp, 1645 true, 1646 ClangUserExpression::kDefaultTimeout); 1647 error = result_valobj_sp->GetError(); 1648 if (error.Success()) 1649 { 1650 Scalar scalar; 1651 if (result_valobj_sp->ResolveValue (scalar)) 1652 { 1653 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS); 1654 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS) 1655 { 1656 uint32_t image_token = m_image_tokens.size(); 1657 m_image_tokens.push_back (image_ptr); 1658 return image_token; 1659 } 1660 } 1661 } 1662 } 1663 } 1664 } 1665 if (!error.AsCString()) 1666 error.SetErrorStringWithFormat("unable to load '%s'", path); 1667 return LLDB_INVALID_IMAGE_TOKEN; 1668 } 1669 1670 //---------------------------------------------------------------------- 1671 // UnloadImage 1672 // 1673 // This function provides a default implementation that works for most 1674 // unix variants. Any Process subclasses that need to do shared library 1675 // loading differently should override LoadImage and UnloadImage and 1676 // do what is needed. 1677 //---------------------------------------------------------------------- 1678 Error 1679 Process::UnloadImage (uint32_t image_token) 1680 { 1681 Error error; 1682 if (image_token < m_image_tokens.size()) 1683 { 1684 const addr_t image_addr = m_image_tokens[image_token]; 1685 if (image_addr == LLDB_INVALID_ADDRESS) 1686 { 1687 error.SetErrorString("image already unloaded"); 1688 } 1689 else 1690 { 1691 DynamicLoader *loader = GetDynamicLoader(); 1692 if (loader) 1693 error = loader->CanLoadImage(); 1694 1695 if (error.Success()) 1696 { 1697 ThreadSP thread_sp(GetThreadList ().GetSelectedThread()); 1698 1699 if (thread_sp) 1700 { 1701 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0)); 1702 1703 if (frame_sp) 1704 { 1705 ExecutionContext exe_ctx; 1706 frame_sp->CalculateExecutionContext (exe_ctx); 1707 bool unwind_on_error = true; 1708 StreamString expr; 1709 expr.Printf("dlclose ((void *)0x%llx)", image_addr); 1710 const char *prefix = "extern \"C\" int dlclose(void* handle);\n"; 1711 lldb::ValueObjectSP result_valobj_sp; 1712 ClangUserExpression::Evaluate (exe_ctx, 1713 eExecutionPolicyAlways, 1714 lldb::eLanguageTypeUnknown, 1715 ClangUserExpression::eResultTypeAny, 1716 unwind_on_error, 1717 expr.GetData(), 1718 prefix, 1719 result_valobj_sp, 1720 true, 1721 ClangUserExpression::kDefaultTimeout); 1722 if (result_valobj_sp->GetError().Success()) 1723 { 1724 Scalar scalar; 1725 if (result_valobj_sp->ResolveValue (scalar)) 1726 { 1727 if (scalar.UInt(1)) 1728 { 1729 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData()); 1730 } 1731 else 1732 { 1733 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS; 1734 } 1735 } 1736 } 1737 else 1738 { 1739 error = result_valobj_sp->GetError(); 1740 } 1741 } 1742 } 1743 } 1744 } 1745 } 1746 else 1747 { 1748 error.SetErrorString("invalid image token"); 1749 } 1750 return error; 1751 } 1752 1753 const lldb::ABISP & 1754 Process::GetABI() 1755 { 1756 if (!m_abi_sp) 1757 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture()); 1758 return m_abi_sp; 1759 } 1760 1761 LanguageRuntime * 1762 Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null) 1763 { 1764 LanguageRuntimeCollection::iterator pos; 1765 pos = m_language_runtimes.find (language); 1766 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second)) 1767 { 1768 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language)); 1769 1770 m_language_runtimes[language] = runtime_sp; 1771 return runtime_sp.get(); 1772 } 1773 else 1774 return (*pos).second.get(); 1775 } 1776 1777 CPPLanguageRuntime * 1778 Process::GetCPPLanguageRuntime (bool retry_if_null) 1779 { 1780 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null); 1781 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus) 1782 return static_cast<CPPLanguageRuntime *> (runtime); 1783 return NULL; 1784 } 1785 1786 ObjCLanguageRuntime * 1787 Process::GetObjCLanguageRuntime (bool retry_if_null) 1788 { 1789 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null); 1790 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC) 1791 return static_cast<ObjCLanguageRuntime *> (runtime); 1792 return NULL; 1793 } 1794 1795 bool 1796 Process::IsPossibleDynamicValue (ValueObject& in_value) 1797 { 1798 if (in_value.IsDynamic()) 1799 return false; 1800 LanguageType known_type = in_value.GetObjectRuntimeLanguage(); 1801 1802 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC) 1803 { 1804 LanguageRuntime *runtime = GetLanguageRuntime (known_type); 1805 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false; 1806 } 1807 1808 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus); 1809 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value)) 1810 return true; 1811 1812 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC); 1813 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false; 1814 } 1815 1816 BreakpointSiteList & 1817 Process::GetBreakpointSiteList() 1818 { 1819 return m_breakpoint_site_list; 1820 } 1821 1822 const BreakpointSiteList & 1823 Process::GetBreakpointSiteList() const 1824 { 1825 return m_breakpoint_site_list; 1826 } 1827 1828 1829 void 1830 Process::DisableAllBreakpointSites () 1831 { 1832 m_breakpoint_site_list.SetEnabledForAll (false); 1833 size_t num_sites = m_breakpoint_site_list.GetSize(); 1834 for (size_t i = 0; i < num_sites; i++) 1835 { 1836 DisableBreakpoint (m_breakpoint_site_list.GetByIndex(i).get()); 1837 } 1838 } 1839 1840 Error 1841 Process::ClearBreakpointSiteByID (lldb::user_id_t break_id) 1842 { 1843 Error error (DisableBreakpointSiteByID (break_id)); 1844 1845 if (error.Success()) 1846 m_breakpoint_site_list.Remove(break_id); 1847 1848 return error; 1849 } 1850 1851 Error 1852 Process::DisableBreakpointSiteByID (lldb::user_id_t break_id) 1853 { 1854 Error error; 1855 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id); 1856 if (bp_site_sp) 1857 { 1858 if (bp_site_sp->IsEnabled()) 1859 error = DisableBreakpoint (bp_site_sp.get()); 1860 } 1861 else 1862 { 1863 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id); 1864 } 1865 1866 return error; 1867 } 1868 1869 Error 1870 Process::EnableBreakpointSiteByID (lldb::user_id_t break_id) 1871 { 1872 Error error; 1873 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id); 1874 if (bp_site_sp) 1875 { 1876 if (!bp_site_sp->IsEnabled()) 1877 error = EnableBreakpoint (bp_site_sp.get()); 1878 } 1879 else 1880 { 1881 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id); 1882 } 1883 return error; 1884 } 1885 1886 lldb::break_id_t 1887 Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware) 1888 { 1889 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target); 1890 if (load_addr != LLDB_INVALID_ADDRESS) 1891 { 1892 BreakpointSiteSP bp_site_sp; 1893 1894 // Look up this breakpoint site. If it exists, then add this new owner, otherwise 1895 // create a new breakpoint site and add it. 1896 1897 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr); 1898 1899 if (bp_site_sp) 1900 { 1901 bp_site_sp->AddOwner (owner); 1902 owner->SetBreakpointSite (bp_site_sp); 1903 return bp_site_sp->GetID(); 1904 } 1905 else 1906 { 1907 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware)); 1908 if (bp_site_sp) 1909 { 1910 if (EnableBreakpoint (bp_site_sp.get()).Success()) 1911 { 1912 owner->SetBreakpointSite (bp_site_sp); 1913 return m_breakpoint_site_list.Add (bp_site_sp); 1914 } 1915 } 1916 } 1917 } 1918 // We failed to enable the breakpoint 1919 return LLDB_INVALID_BREAK_ID; 1920 1921 } 1922 1923 void 1924 Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp) 1925 { 1926 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id); 1927 if (num_owners == 0) 1928 { 1929 DisableBreakpoint(bp_site_sp.get()); 1930 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress()); 1931 } 1932 } 1933 1934 1935 size_t 1936 Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const 1937 { 1938 size_t bytes_removed = 0; 1939 addr_t intersect_addr; 1940 size_t intersect_size; 1941 size_t opcode_offset; 1942 size_t idx; 1943 BreakpointSiteSP bp_sp; 1944 BreakpointSiteList bp_sites_in_range; 1945 1946 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range)) 1947 { 1948 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx) 1949 { 1950 if (bp_sp->GetType() == BreakpointSite::eSoftware) 1951 { 1952 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset)) 1953 { 1954 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size); 1955 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size); 1956 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize()); 1957 size_t buf_offset = intersect_addr - bp_addr; 1958 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size); 1959 } 1960 } 1961 } 1962 } 1963 return bytes_removed; 1964 } 1965 1966 1967 1968 size_t 1969 Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site) 1970 { 1971 PlatformSP platform_sp (m_target.GetPlatform()); 1972 if (platform_sp) 1973 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site); 1974 return 0; 1975 } 1976 1977 Error 1978 Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site) 1979 { 1980 Error error; 1981 assert (bp_site != NULL); 1982 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); 1983 const addr_t bp_addr = bp_site->GetLoadAddress(); 1984 if (log) 1985 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr); 1986 if (bp_site->IsEnabled()) 1987 { 1988 if (log) 1989 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr); 1990 return error; 1991 } 1992 1993 if (bp_addr == LLDB_INVALID_ADDRESS) 1994 { 1995 error.SetErrorString("BreakpointSite contains an invalid load address."); 1996 return error; 1997 } 1998 // Ask the lldb::Process subclass to fill in the correct software breakpoint 1999 // trap for the breakpoint site 2000 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site); 2001 2002 if (bp_opcode_size == 0) 2003 { 2004 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx", bp_addr); 2005 } 2006 else 2007 { 2008 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes(); 2009 2010 if (bp_opcode_bytes == NULL) 2011 { 2012 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode."); 2013 return error; 2014 } 2015 2016 // Save the original opcode by reading it 2017 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size) 2018 { 2019 // Write a software breakpoint in place of the original opcode 2020 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size) 2021 { 2022 uint8_t verify_bp_opcode_bytes[64]; 2023 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size) 2024 { 2025 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0) 2026 { 2027 bp_site->SetEnabled(true); 2028 bp_site->SetType (BreakpointSite::eSoftware); 2029 if (log) 2030 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", 2031 bp_site->GetID(), 2032 (uint64_t)bp_addr); 2033 } 2034 else 2035 error.SetErrorString("failed to verify the breakpoint trap in memory."); 2036 } 2037 else 2038 error.SetErrorString("Unable to read memory to verify breakpoint trap."); 2039 } 2040 else 2041 error.SetErrorString("Unable to write breakpoint trap to memory."); 2042 } 2043 else 2044 error.SetErrorString("Unable to read memory at breakpoint address."); 2045 } 2046 if (log && error.Fail()) 2047 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s", 2048 bp_site->GetID(), 2049 (uint64_t)bp_addr, 2050 error.AsCString()); 2051 return error; 2052 } 2053 2054 Error 2055 Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site) 2056 { 2057 Error error; 2058 assert (bp_site != NULL); 2059 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); 2060 addr_t bp_addr = bp_site->GetLoadAddress(); 2061 lldb::user_id_t breakID = bp_site->GetID(); 2062 if (log) 2063 log->Printf ("Process::DisableBreakpoint (breakID = %llu) addr = 0x%llx", breakID, (uint64_t)bp_addr); 2064 2065 if (bp_site->IsHardware()) 2066 { 2067 error.SetErrorString("Breakpoint site is a hardware breakpoint."); 2068 } 2069 else if (bp_site->IsEnabled()) 2070 { 2071 const size_t break_op_size = bp_site->GetByteSize(); 2072 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes(); 2073 if (break_op_size > 0) 2074 { 2075 // Clear a software breakoint instruction 2076 uint8_t curr_break_op[8]; 2077 assert (break_op_size <= sizeof(curr_break_op)); 2078 bool break_op_found = false; 2079 2080 // Read the breakpoint opcode 2081 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size) 2082 { 2083 bool verify = false; 2084 // Make sure we have the a breakpoint opcode exists at this address 2085 if (::memcmp (curr_break_op, break_op, break_op_size) == 0) 2086 { 2087 break_op_found = true; 2088 // We found a valid breakpoint opcode at this address, now restore 2089 // the saved opcode. 2090 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size) 2091 { 2092 verify = true; 2093 } 2094 else 2095 error.SetErrorString("Memory write failed when restoring original opcode."); 2096 } 2097 else 2098 { 2099 error.SetErrorString("Original breakpoint trap is no longer in memory."); 2100 // Set verify to true and so we can check if the original opcode has already been restored 2101 verify = true; 2102 } 2103 2104 if (verify) 2105 { 2106 uint8_t verify_opcode[8]; 2107 assert (break_op_size < sizeof(verify_opcode)); 2108 // Verify that our original opcode made it back to the inferior 2109 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size) 2110 { 2111 // compare the memory we just read with the original opcode 2112 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0) 2113 { 2114 // SUCCESS 2115 bp_site->SetEnabled(false); 2116 if (log) 2117 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr); 2118 return error; 2119 } 2120 else 2121 { 2122 if (break_op_found) 2123 error.SetErrorString("Failed to restore original opcode."); 2124 } 2125 } 2126 else 2127 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored."); 2128 } 2129 } 2130 else 2131 error.SetErrorString("Unable to read memory that should contain the breakpoint trap."); 2132 } 2133 } 2134 else 2135 { 2136 if (log) 2137 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr); 2138 return error; 2139 } 2140 2141 if (log) 2142 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s", 2143 bp_site->GetID(), 2144 (uint64_t)bp_addr, 2145 error.AsCString()); 2146 return error; 2147 2148 } 2149 2150 // Uncomment to verify memory caching works after making changes to caching code 2151 //#define VERIFY_MEMORY_READS 2152 2153 size_t 2154 Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error) 2155 { 2156 if (!GetDisableMemoryCache()) 2157 { 2158 #if defined (VERIFY_MEMORY_READS) 2159 // Memory caching is enabled, with debug verification 2160 2161 if (buf && size) 2162 { 2163 // Uncomment the line below to make sure memory caching is working. 2164 // I ran this through the test suite and got no assertions, so I am 2165 // pretty confident this is working well. If any changes are made to 2166 // memory caching, uncomment the line below and test your changes! 2167 2168 // Verify all memory reads by using the cache first, then redundantly 2169 // reading the same memory from the inferior and comparing to make sure 2170 // everything is exactly the same. 2171 std::string verify_buf (size, '\0'); 2172 assert (verify_buf.size() == size); 2173 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error); 2174 Error verify_error; 2175 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error); 2176 assert (cache_bytes_read == verify_bytes_read); 2177 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0); 2178 assert (verify_error.Success() == error.Success()); 2179 return cache_bytes_read; 2180 } 2181 return 0; 2182 #else // !defined(VERIFY_MEMORY_READS) 2183 // Memory caching is enabled, without debug verification 2184 2185 return m_memory_cache.Read (addr, buf, size, error); 2186 #endif // defined (VERIFY_MEMORY_READS) 2187 } 2188 else 2189 { 2190 // Memory caching is disabled 2191 2192 return ReadMemoryFromInferior (addr, buf, size, error); 2193 } 2194 } 2195 2196 size_t 2197 Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error) 2198 { 2199 char buf[256]; 2200 out_str.clear(); 2201 addr_t curr_addr = addr; 2202 while (1) 2203 { 2204 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error); 2205 if (length == 0) 2206 break; 2207 out_str.append(buf, length); 2208 // If we got "length - 1" bytes, we didn't get the whole C string, we 2209 // need to read some more characters 2210 if (length == sizeof(buf) - 1) 2211 curr_addr += length; 2212 else 2213 break; 2214 } 2215 return out_str.size(); 2216 } 2217 2218 2219 size_t 2220 Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error) 2221 { 2222 size_t total_cstr_len = 0; 2223 if (dst && dst_max_len) 2224 { 2225 result_error.Clear(); 2226 // NULL out everything just to be safe 2227 memset (dst, 0, dst_max_len); 2228 Error error; 2229 addr_t curr_addr = addr; 2230 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize(); 2231 size_t bytes_left = dst_max_len - 1; 2232 char *curr_dst = dst; 2233 2234 while (bytes_left > 0) 2235 { 2236 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size); 2237 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left); 2238 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error); 2239 2240 if (bytes_read == 0) 2241 { 2242 result_error = error; 2243 dst[total_cstr_len] = '\0'; 2244 break; 2245 } 2246 const size_t len = strlen(curr_dst); 2247 2248 total_cstr_len += len; 2249 2250 if (len < bytes_to_read) 2251 break; 2252 2253 curr_dst += bytes_read; 2254 curr_addr += bytes_read; 2255 bytes_left -= bytes_read; 2256 } 2257 } 2258 else 2259 { 2260 if (dst == NULL) 2261 result_error.SetErrorString("invalid arguments"); 2262 else 2263 result_error.Clear(); 2264 } 2265 return total_cstr_len; 2266 } 2267 2268 size_t 2269 Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error) 2270 { 2271 if (buf == NULL || size == 0) 2272 return 0; 2273 2274 size_t bytes_read = 0; 2275 uint8_t *bytes = (uint8_t *)buf; 2276 2277 while (bytes_read < size) 2278 { 2279 const size_t curr_size = size - bytes_read; 2280 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read, 2281 bytes + bytes_read, 2282 curr_size, 2283 error); 2284 bytes_read += curr_bytes_read; 2285 if (curr_bytes_read == curr_size || curr_bytes_read == 0) 2286 break; 2287 } 2288 2289 // Replace any software breakpoint opcodes that fall into this range back 2290 // into "buf" before we return 2291 if (bytes_read > 0) 2292 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf); 2293 return bytes_read; 2294 } 2295 2296 uint64_t 2297 Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error) 2298 { 2299 Scalar scalar; 2300 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error)) 2301 return scalar.ULongLong(fail_value); 2302 return fail_value; 2303 } 2304 2305 addr_t 2306 Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error) 2307 { 2308 Scalar scalar; 2309 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error)) 2310 return scalar.ULongLong(LLDB_INVALID_ADDRESS); 2311 return LLDB_INVALID_ADDRESS; 2312 } 2313 2314 2315 bool 2316 Process::WritePointerToMemory (lldb::addr_t vm_addr, 2317 lldb::addr_t ptr_value, 2318 Error &error) 2319 { 2320 Scalar scalar; 2321 const uint32_t addr_byte_size = GetAddressByteSize(); 2322 if (addr_byte_size <= 4) 2323 scalar = (uint32_t)ptr_value; 2324 else 2325 scalar = ptr_value; 2326 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size; 2327 } 2328 2329 size_t 2330 Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error) 2331 { 2332 size_t bytes_written = 0; 2333 const uint8_t *bytes = (const uint8_t *)buf; 2334 2335 while (bytes_written < size) 2336 { 2337 const size_t curr_size = size - bytes_written; 2338 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written, 2339 bytes + bytes_written, 2340 curr_size, 2341 error); 2342 bytes_written += curr_bytes_written; 2343 if (curr_bytes_written == curr_size || curr_bytes_written == 0) 2344 break; 2345 } 2346 return bytes_written; 2347 } 2348 2349 size_t 2350 Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error) 2351 { 2352 #if defined (ENABLE_MEMORY_CACHING) 2353 m_memory_cache.Flush (addr, size); 2354 #endif 2355 2356 if (buf == NULL || size == 0) 2357 return 0; 2358 2359 m_mod_id.BumpMemoryID(); 2360 2361 // We need to write any data that would go where any current software traps 2362 // (enabled software breakpoints) any software traps (breakpoints) that we 2363 // may have placed in our tasks memory. 2364 2365 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr); 2366 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end(); 2367 2368 if (iter == end || iter->second->GetLoadAddress() > addr + size) 2369 return WriteMemoryPrivate (addr, buf, size, error); 2370 2371 BreakpointSiteList::collection::const_iterator pos; 2372 size_t bytes_written = 0; 2373 addr_t intersect_addr = 0; 2374 size_t intersect_size = 0; 2375 size_t opcode_offset = 0; 2376 const uint8_t *ubuf = (const uint8_t *)buf; 2377 2378 for (pos = iter; pos != end; ++pos) 2379 { 2380 BreakpointSiteSP bp; 2381 bp = pos->second; 2382 2383 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset)); 2384 assert(addr <= intersect_addr && intersect_addr < addr + size); 2385 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size); 2386 assert(opcode_offset + intersect_size <= bp->GetByteSize()); 2387 2388 // Check for bytes before this breakpoint 2389 const addr_t curr_addr = addr + bytes_written; 2390 if (intersect_addr > curr_addr) 2391 { 2392 // There are some bytes before this breakpoint that we need to 2393 // just write to memory 2394 size_t curr_size = intersect_addr - curr_addr; 2395 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr, 2396 ubuf + bytes_written, 2397 curr_size, 2398 error); 2399 bytes_written += curr_bytes_written; 2400 if (curr_bytes_written != curr_size) 2401 { 2402 // We weren't able to write all of the requested bytes, we 2403 // are done looping and will return the number of bytes that 2404 // we have written so far. 2405 break; 2406 } 2407 } 2408 2409 // Now write any bytes that would cover up any software breakpoints 2410 // directly into the breakpoint opcode buffer 2411 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size); 2412 bytes_written += intersect_size; 2413 } 2414 2415 // Write any remaining bytes after the last breakpoint if we have any left 2416 if (bytes_written < size) 2417 bytes_written += WriteMemoryPrivate (addr + bytes_written, 2418 ubuf + bytes_written, 2419 size - bytes_written, 2420 error); 2421 2422 return bytes_written; 2423 } 2424 2425 size_t 2426 Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, uint32_t byte_size, Error &error) 2427 { 2428 if (byte_size == UINT32_MAX) 2429 byte_size = scalar.GetByteSize(); 2430 if (byte_size > 0) 2431 { 2432 uint8_t buf[32]; 2433 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error); 2434 if (mem_size > 0) 2435 return WriteMemory(addr, buf, mem_size, error); 2436 else 2437 error.SetErrorString ("failed to get scalar as memory data"); 2438 } 2439 else 2440 { 2441 error.SetErrorString ("invalid scalar value"); 2442 } 2443 return 0; 2444 } 2445 2446 size_t 2447 Process::ReadScalarIntegerFromMemory (addr_t addr, 2448 uint32_t byte_size, 2449 bool is_signed, 2450 Scalar &scalar, 2451 Error &error) 2452 { 2453 uint64_t uval; 2454 2455 if (byte_size <= sizeof(uval)) 2456 { 2457 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error); 2458 if (bytes_read == byte_size) 2459 { 2460 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize()); 2461 uint32_t offset = 0; 2462 if (byte_size <= 4) 2463 scalar = data.GetMaxU32 (&offset, byte_size); 2464 else 2465 scalar = data.GetMaxU64 (&offset, byte_size); 2466 2467 if (is_signed) 2468 scalar.SignExtend(byte_size * 8); 2469 return bytes_read; 2470 } 2471 } 2472 else 2473 { 2474 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size); 2475 } 2476 return 0; 2477 } 2478 2479 #define USE_ALLOCATE_MEMORY_CACHE 1 2480 addr_t 2481 Process::AllocateMemory(size_t size, uint32_t permissions, Error &error) 2482 { 2483 if (GetPrivateState() != eStateStopped) 2484 return LLDB_INVALID_ADDRESS; 2485 2486 #if defined (USE_ALLOCATE_MEMORY_CACHE) 2487 return m_allocated_memory_cache.AllocateMemory(size, permissions, error); 2488 #else 2489 addr_t allocated_addr = DoAllocateMemory (size, permissions, error); 2490 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 2491 if (log) 2492 log->Printf("Process::AllocateMemory(size=%4zu, permissions=%s) => 0x%16.16llx (m_stop_id = %u m_memory_id = %u)", 2493 size, 2494 GetPermissionsAsCString (permissions), 2495 (uint64_t)allocated_addr, 2496 m_mod_id.GetStopID(), 2497 m_mod_id.GetMemoryID()); 2498 return allocated_addr; 2499 #endif 2500 } 2501 2502 bool 2503 Process::CanJIT () 2504 { 2505 if (m_can_jit == eCanJITDontKnow) 2506 { 2507 Error err; 2508 2509 uint64_t allocated_memory = AllocateMemory(8, 2510 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable, 2511 err); 2512 2513 if (err.Success()) 2514 m_can_jit = eCanJITYes; 2515 else 2516 m_can_jit = eCanJITNo; 2517 2518 DeallocateMemory (allocated_memory); 2519 } 2520 2521 return m_can_jit == eCanJITYes; 2522 } 2523 2524 void 2525 Process::SetCanJIT (bool can_jit) 2526 { 2527 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo); 2528 } 2529 2530 Error 2531 Process::DeallocateMemory (addr_t ptr) 2532 { 2533 Error error; 2534 #if defined (USE_ALLOCATE_MEMORY_CACHE) 2535 if (!m_allocated_memory_cache.DeallocateMemory(ptr)) 2536 { 2537 error.SetErrorStringWithFormat ("deallocation of memory at 0x%llx failed.", (uint64_t)ptr); 2538 } 2539 #else 2540 error = DoDeallocateMemory (ptr); 2541 2542 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 2543 if (log) 2544 log->Printf("Process::DeallocateMemory(addr=0x%16.16llx) => err = %s (m_stop_id = %u, m_memory_id = %u)", 2545 ptr, 2546 error.AsCString("SUCCESS"), 2547 m_mod_id.GetStopID(), 2548 m_mod_id.GetMemoryID()); 2549 #endif 2550 return error; 2551 } 2552 2553 2554 ModuleSP 2555 Process::ReadModuleFromMemory (const FileSpec& file_spec, 2556 lldb::addr_t header_addr, 2557 bool add_image_to_target, 2558 bool load_sections_in_target) 2559 { 2560 ModuleSP module_sp (new Module (file_spec, ArchSpec())); 2561 if (module_sp) 2562 { 2563 Error error; 2564 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error); 2565 if (objfile) 2566 { 2567 if (add_image_to_target) 2568 { 2569 m_target.GetImages().Append(module_sp); 2570 if (load_sections_in_target) 2571 { 2572 bool changed = false; 2573 module_sp->SetLoadAddress (m_target, 0, changed); 2574 } 2575 } 2576 return module_sp; 2577 } 2578 } 2579 return ModuleSP(); 2580 } 2581 2582 Error 2583 Process::EnableWatchpoint (Watchpoint *watchpoint) 2584 { 2585 Error error; 2586 error.SetErrorString("watchpoints are not supported"); 2587 return error; 2588 } 2589 2590 Error 2591 Process::DisableWatchpoint (Watchpoint *watchpoint) 2592 { 2593 Error error; 2594 error.SetErrorString("watchpoints are not supported"); 2595 return error; 2596 } 2597 2598 StateType 2599 Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp) 2600 { 2601 StateType state; 2602 // Now wait for the process to launch and return control to us, and then 2603 // call DidLaunch: 2604 while (1) 2605 { 2606 event_sp.reset(); 2607 state = WaitForStateChangedEventsPrivate (timeout, event_sp); 2608 2609 if (StateIsStoppedState(state, false)) 2610 break; 2611 2612 // If state is invalid, then we timed out 2613 if (state == eStateInvalid) 2614 break; 2615 2616 if (event_sp) 2617 HandlePrivateEvent (event_sp); 2618 } 2619 return state; 2620 } 2621 2622 Error 2623 Process::Launch (const ProcessLaunchInfo &launch_info) 2624 { 2625 Error error; 2626 m_abi_sp.reset(); 2627 m_dyld_ap.reset(); 2628 m_os_ap.reset(); 2629 m_process_input_reader.reset(); 2630 2631 Module *exe_module = m_target.GetExecutableModulePointer(); 2632 if (exe_module) 2633 { 2634 char local_exec_file_path[PATH_MAX]; 2635 char platform_exec_file_path[PATH_MAX]; 2636 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path)); 2637 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path)); 2638 if (exe_module->GetFileSpec().Exists()) 2639 { 2640 if (PrivateStateThreadIsValid ()) 2641 PausePrivateStateThread (); 2642 2643 error = WillLaunch (exe_module); 2644 if (error.Success()) 2645 { 2646 SetPublicState (eStateLaunching); 2647 m_should_detach = false; 2648 2649 if (m_run_lock.WriteTryLock()) 2650 { 2651 // Now launch using these arguments. 2652 error = DoLaunch (exe_module, launch_info); 2653 } 2654 else 2655 { 2656 // This shouldn't happen 2657 error.SetErrorString("failed to acquire process run lock"); 2658 } 2659 2660 if (error.Fail()) 2661 { 2662 if (GetID() != LLDB_INVALID_PROCESS_ID) 2663 { 2664 SetID (LLDB_INVALID_PROCESS_ID); 2665 const char *error_string = error.AsCString(); 2666 if (error_string == NULL) 2667 error_string = "launch failed"; 2668 SetExitStatus (-1, error_string); 2669 } 2670 } 2671 else 2672 { 2673 EventSP event_sp; 2674 TimeValue timeout_time; 2675 timeout_time = TimeValue::Now(); 2676 timeout_time.OffsetWithSeconds(10); 2677 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp); 2678 2679 if (state == eStateInvalid || event_sp.get() == NULL) 2680 { 2681 // We were able to launch the process, but we failed to 2682 // catch the initial stop. 2683 SetExitStatus (0, "failed to catch stop after launch"); 2684 Destroy(); 2685 } 2686 else if (state == eStateStopped || state == eStateCrashed) 2687 { 2688 2689 DidLaunch (); 2690 2691 DynamicLoader *dyld = GetDynamicLoader (); 2692 if (dyld) 2693 dyld->DidLaunch(); 2694 2695 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL)); 2696 // This delays passing the stopped event to listeners till DidLaunch gets 2697 // a chance to complete... 2698 HandlePrivateEvent (event_sp); 2699 2700 if (PrivateStateThreadIsValid ()) 2701 ResumePrivateStateThread (); 2702 else 2703 StartPrivateStateThread (); 2704 } 2705 else if (state == eStateExited) 2706 { 2707 // We exited while trying to launch somehow. Don't call DidLaunch as that's 2708 // not likely to work, and return an invalid pid. 2709 HandlePrivateEvent (event_sp); 2710 } 2711 } 2712 } 2713 } 2714 else 2715 { 2716 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path); 2717 } 2718 } 2719 return error; 2720 } 2721 2722 2723 Error 2724 Process::LoadCore () 2725 { 2726 Error error = DoLoadCore(); 2727 if (error.Success()) 2728 { 2729 if (PrivateStateThreadIsValid ()) 2730 ResumePrivateStateThread (); 2731 else 2732 StartPrivateStateThread (); 2733 2734 DynamicLoader *dyld = GetDynamicLoader (); 2735 if (dyld) 2736 dyld->DidAttach(); 2737 2738 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL)); 2739 // We successfully loaded a core file, now pretend we stopped so we can 2740 // show all of the threads in the core file and explore the crashed 2741 // state. 2742 SetPrivateState (eStateStopped); 2743 2744 } 2745 return error; 2746 } 2747 2748 DynamicLoader * 2749 Process::GetDynamicLoader () 2750 { 2751 if (m_dyld_ap.get() == NULL) 2752 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL)); 2753 return m_dyld_ap.get(); 2754 } 2755 2756 2757 Process::NextEventAction::EventActionResult 2758 Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp) 2759 { 2760 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get()); 2761 switch (state) 2762 { 2763 case eStateRunning: 2764 case eStateConnected: 2765 return eEventActionRetry; 2766 2767 case eStateStopped: 2768 case eStateCrashed: 2769 { 2770 // During attach, prior to sending the eStateStopped event, 2771 // lldb_private::Process subclasses must set the new process ID. 2772 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID); 2773 if (m_exec_count > 0) 2774 { 2775 --m_exec_count; 2776 m_process->PrivateResume (); 2777 Process::ProcessEventData::SetRestartedInEvent (event_sp.get(), true); 2778 return eEventActionRetry; 2779 } 2780 else 2781 { 2782 m_process->CompleteAttach (); 2783 return eEventActionSuccess; 2784 } 2785 } 2786 break; 2787 2788 default: 2789 case eStateExited: 2790 case eStateInvalid: 2791 break; 2792 } 2793 2794 m_exit_string.assign ("No valid Process"); 2795 return eEventActionExit; 2796 } 2797 2798 Process::NextEventAction::EventActionResult 2799 Process::AttachCompletionHandler::HandleBeingInterrupted() 2800 { 2801 return eEventActionSuccess; 2802 } 2803 2804 const char * 2805 Process::AttachCompletionHandler::GetExitString () 2806 { 2807 return m_exit_string.c_str(); 2808 } 2809 2810 Error 2811 Process::Attach (ProcessAttachInfo &attach_info) 2812 { 2813 m_abi_sp.reset(); 2814 m_process_input_reader.reset(); 2815 m_dyld_ap.reset(); 2816 m_os_ap.reset(); 2817 2818 lldb::pid_t attach_pid = attach_info.GetProcessID(); 2819 Error error; 2820 if (attach_pid == LLDB_INVALID_PROCESS_ID) 2821 { 2822 char process_name[PATH_MAX]; 2823 2824 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name))) 2825 { 2826 const bool wait_for_launch = attach_info.GetWaitForLaunch(); 2827 2828 if (wait_for_launch) 2829 { 2830 error = WillAttachToProcessWithName(process_name, wait_for_launch); 2831 if (error.Success()) 2832 { 2833 if (m_run_lock.WriteTryLock()) 2834 { 2835 m_should_detach = true; 2836 SetPublicState (eStateAttaching); 2837 // Now attach using these arguments. 2838 error = DoAttachToProcessWithName (process_name, wait_for_launch, attach_info); 2839 } 2840 else 2841 { 2842 // This shouldn't happen 2843 error.SetErrorString("failed to acquire process run lock"); 2844 } 2845 2846 if (error.Fail()) 2847 { 2848 if (GetID() != LLDB_INVALID_PROCESS_ID) 2849 { 2850 SetID (LLDB_INVALID_PROCESS_ID); 2851 if (error.AsCString() == NULL) 2852 error.SetErrorString("attach failed"); 2853 2854 SetExitStatus(-1, error.AsCString()); 2855 } 2856 } 2857 else 2858 { 2859 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount())); 2860 StartPrivateStateThread(); 2861 } 2862 return error; 2863 } 2864 } 2865 else 2866 { 2867 ProcessInstanceInfoList process_infos; 2868 PlatformSP platform_sp (m_target.GetPlatform ()); 2869 2870 if (platform_sp) 2871 { 2872 ProcessInstanceInfoMatch match_info; 2873 match_info.GetProcessInfo() = attach_info; 2874 match_info.SetNameMatchType (eNameMatchEquals); 2875 platform_sp->FindProcesses (match_info, process_infos); 2876 const uint32_t num_matches = process_infos.GetSize(); 2877 if (num_matches == 1) 2878 { 2879 attach_pid = process_infos.GetProcessIDAtIndex(0); 2880 // Fall through and attach using the above process ID 2881 } 2882 else 2883 { 2884 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name)); 2885 if (num_matches > 1) 2886 error.SetErrorStringWithFormat ("more than one process named %s", process_name); 2887 else 2888 error.SetErrorStringWithFormat ("could not find a process named %s", process_name); 2889 } 2890 } 2891 else 2892 { 2893 error.SetErrorString ("invalid platform, can't find processes by name"); 2894 return error; 2895 } 2896 } 2897 } 2898 else 2899 { 2900 error.SetErrorString ("invalid process name"); 2901 } 2902 } 2903 2904 if (attach_pid != LLDB_INVALID_PROCESS_ID) 2905 { 2906 error = WillAttachToProcessWithID(attach_pid); 2907 if (error.Success()) 2908 { 2909 2910 if (m_run_lock.WriteTryLock()) 2911 { 2912 // Now attach using these arguments. 2913 m_should_detach = true; 2914 SetPublicState (eStateAttaching); 2915 error = DoAttachToProcessWithID (attach_pid, attach_info); 2916 } 2917 else 2918 { 2919 // This shouldn't happen 2920 error.SetErrorString("failed to acquire process run lock"); 2921 } 2922 2923 if (error.Success()) 2924 { 2925 2926 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount())); 2927 StartPrivateStateThread(); 2928 } 2929 else 2930 { 2931 if (GetID() != LLDB_INVALID_PROCESS_ID) 2932 { 2933 SetID (LLDB_INVALID_PROCESS_ID); 2934 const char *error_string = error.AsCString(); 2935 if (error_string == NULL) 2936 error_string = "attach failed"; 2937 2938 SetExitStatus(-1, error_string); 2939 } 2940 } 2941 } 2942 } 2943 return error; 2944 } 2945 2946 void 2947 Process::CompleteAttach () 2948 { 2949 // Let the process subclass figure out at much as it can about the process 2950 // before we go looking for a dynamic loader plug-in. 2951 DidAttach(); 2952 2953 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't 2954 // the same as the one we've already set, switch architectures. 2955 PlatformSP platform_sp (m_target.GetPlatform ()); 2956 assert (platform_sp.get()); 2957 if (platform_sp) 2958 { 2959 const ArchSpec &target_arch = m_target.GetArchitecture(); 2960 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch)) 2961 { 2962 ArchSpec platform_arch; 2963 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch); 2964 if (platform_sp) 2965 { 2966 m_target.SetPlatform (platform_sp); 2967 m_target.SetArchitecture(platform_arch); 2968 } 2969 } 2970 else 2971 { 2972 ProcessInstanceInfo process_info; 2973 platform_sp->GetProcessInfo (GetID(), process_info); 2974 const ArchSpec &process_arch = process_info.GetArchitecture(); 2975 if (process_arch.IsValid() && m_target.GetArchitecture() != process_arch) 2976 m_target.SetArchitecture (process_arch); 2977 } 2978 } 2979 2980 // We have completed the attach, now it is time to find the dynamic loader 2981 // plug-in 2982 DynamicLoader *dyld = GetDynamicLoader (); 2983 if (dyld) 2984 dyld->DidAttach(); 2985 2986 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL)); 2987 // Figure out which one is the executable, and set that in our target: 2988 const ModuleList &target_modules = m_target.GetImages(); 2989 Mutex::Locker modules_locker(target_modules.GetMutex()); 2990 size_t num_modules = target_modules.GetSize(); 2991 ModuleSP new_executable_module_sp; 2992 2993 for (int i = 0; i < num_modules; i++) 2994 { 2995 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i)); 2996 if (module_sp && module_sp->IsExecutable()) 2997 { 2998 if (m_target.GetExecutableModulePointer() != module_sp.get()) 2999 new_executable_module_sp = module_sp; 3000 break; 3001 } 3002 } 3003 if (new_executable_module_sp) 3004 m_target.SetExecutableModule (new_executable_module_sp, false); 3005 } 3006 3007 Error 3008 Process::ConnectRemote (Stream *strm, const char *remote_url) 3009 { 3010 m_abi_sp.reset(); 3011 m_process_input_reader.reset(); 3012 3013 // Find the process and its architecture. Make sure it matches the architecture 3014 // of the current Target, and if not adjust it. 3015 3016 Error error (DoConnectRemote (strm, remote_url)); 3017 if (error.Success()) 3018 { 3019 if (GetID() != LLDB_INVALID_PROCESS_ID) 3020 { 3021 EventSP event_sp; 3022 StateType state = WaitForProcessStopPrivate(NULL, event_sp); 3023 3024 if (state == eStateStopped || state == eStateCrashed) 3025 { 3026 // If we attached and actually have a process on the other end, then 3027 // this ended up being the equivalent of an attach. 3028 CompleteAttach (); 3029 3030 // This delays passing the stopped event to listeners till 3031 // CompleteAttach gets a chance to complete... 3032 HandlePrivateEvent (event_sp); 3033 3034 } 3035 } 3036 3037 if (PrivateStateThreadIsValid ()) 3038 ResumePrivateStateThread (); 3039 else 3040 StartPrivateStateThread (); 3041 } 3042 return error; 3043 } 3044 3045 3046 Error 3047 Process::PrivateResume () 3048 { 3049 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP)); 3050 if (log) 3051 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s", 3052 m_mod_id.GetStopID(), 3053 StateAsCString(m_public_state.GetValue()), 3054 StateAsCString(m_private_state.GetValue())); 3055 3056 Error error (WillResume()); 3057 // Tell the process it is about to resume before the thread list 3058 if (error.Success()) 3059 { 3060 // Now let the thread list know we are about to resume so it 3061 // can let all of our threads know that they are about to be 3062 // resumed. Threads will each be called with 3063 // Thread::WillResume(StateType) where StateType contains the state 3064 // that they are supposed to have when the process is resumed 3065 // (suspended/running/stepping). Threads should also check 3066 // their resume signal in lldb::Thread::GetResumeSignal() 3067 // to see if they are suppoed to start back up with a signal. 3068 if (m_thread_list.WillResume()) 3069 { 3070 // Last thing, do the PreResumeActions. 3071 if (!RunPreResumeActions()) 3072 { 3073 error.SetErrorStringWithFormat ("Process::Resume PreResumeActions failed, not resuming."); 3074 } 3075 else 3076 { 3077 m_mod_id.BumpResumeID(); 3078 error = DoResume(); 3079 if (error.Success()) 3080 { 3081 DidResume(); 3082 m_thread_list.DidResume(); 3083 if (log) 3084 log->Printf ("Process thinks the process has resumed."); 3085 } 3086 } 3087 } 3088 else 3089 { 3090 // Somebody wanted to run without running. So generate a continue & a stopped event, 3091 // and let the world handle them. 3092 if (log) 3093 log->Printf ("Process::PrivateResume() asked to simulate a start & stop."); 3094 3095 SetPrivateState(eStateRunning); 3096 SetPrivateState(eStateStopped); 3097 } 3098 } 3099 else if (log) 3100 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>")); 3101 return error; 3102 } 3103 3104 Error 3105 Process::Halt () 3106 { 3107 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since 3108 // we could just straightaway get another event. It just narrows the window... 3109 m_currently_handling_event.WaitForValueEqualTo(false); 3110 3111 3112 // Pause our private state thread so we can ensure no one else eats 3113 // the stop event out from under us. 3114 Listener halt_listener ("lldb.process.halt_listener"); 3115 HijackPrivateProcessEvents(&halt_listener); 3116 3117 EventSP event_sp; 3118 Error error (WillHalt()); 3119 3120 if (error.Success()) 3121 { 3122 3123 bool caused_stop = false; 3124 3125 // Ask the process subclass to actually halt our process 3126 error = DoHalt(caused_stop); 3127 if (error.Success()) 3128 { 3129 if (m_public_state.GetValue() == eStateAttaching) 3130 { 3131 SetExitStatus(SIGKILL, "Cancelled async attach."); 3132 Destroy (); 3133 } 3134 else 3135 { 3136 // If "caused_stop" is true, then DoHalt stopped the process. If 3137 // "caused_stop" is false, the process was already stopped. 3138 // If the DoHalt caused the process to stop, then we want to catch 3139 // this event and set the interrupted bool to true before we pass 3140 // this along so clients know that the process was interrupted by 3141 // a halt command. 3142 if (caused_stop) 3143 { 3144 // Wait for 1 second for the process to stop. 3145 TimeValue timeout_time; 3146 timeout_time = TimeValue::Now(); 3147 timeout_time.OffsetWithSeconds(1); 3148 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp); 3149 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get()); 3150 3151 if (!got_event || state == eStateInvalid) 3152 { 3153 // We timeout out and didn't get a stop event... 3154 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState())); 3155 } 3156 else 3157 { 3158 if (StateIsStoppedState (state, false)) 3159 { 3160 // We caused the process to interrupt itself, so mark this 3161 // as such in the stop event so clients can tell an interrupted 3162 // process from a natural stop 3163 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true); 3164 } 3165 else 3166 { 3167 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 3168 if (log) 3169 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state)); 3170 error.SetErrorString ("Did not get stopped event after halt."); 3171 } 3172 } 3173 } 3174 DidHalt(); 3175 } 3176 } 3177 } 3178 // Resume our private state thread before we post the event (if any) 3179 RestorePrivateProcessEvents(); 3180 3181 // Post any event we might have consumed. If all goes well, we will have 3182 // stopped the process, intercepted the event and set the interrupted 3183 // bool in the event. Post it to the private event queue and that will end up 3184 // correctly setting the state. 3185 if (event_sp) 3186 m_private_state_broadcaster.BroadcastEvent(event_sp); 3187 3188 return error; 3189 } 3190 3191 Error 3192 Process::Detach () 3193 { 3194 Error error (WillDetach()); 3195 3196 if (error.Success()) 3197 { 3198 DisableAllBreakpointSites(); 3199 error = DoDetach(); 3200 if (error.Success()) 3201 { 3202 DidDetach(); 3203 StopPrivateStateThread(); 3204 } 3205 } 3206 return error; 3207 } 3208 3209 Error 3210 Process::Destroy () 3211 { 3212 Error error (WillDestroy()); 3213 if (error.Success()) 3214 { 3215 EventSP exit_event_sp; 3216 if (m_public_state.GetValue() == eStateRunning) 3217 { 3218 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 3219 if (log) 3220 log->Printf("Process::Destroy() About to halt."); 3221 error = Halt(); 3222 if (error.Success()) 3223 { 3224 // Consume the halt event. 3225 TimeValue timeout (TimeValue::Now()); 3226 timeout.OffsetWithSeconds(1); 3227 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp); 3228 if (state != eStateExited) 3229 exit_event_sp.reset(); // It is ok to consume any non-exit stop events 3230 3231 if (state != eStateStopped) 3232 { 3233 if (log) 3234 log->Printf("Process::Destroy() Halt failed to stop, state is: %s", StateAsCString(state)); 3235 // If we really couldn't stop the process then we should just error out here, but if the 3236 // lower levels just bobbled sending the event and we really are stopped, then continue on. 3237 StateType private_state = m_private_state.GetValue(); 3238 if (private_state != eStateStopped && private_state != eStateExited) 3239 { 3240 // If we exited when we were waiting for a process to stop, then 3241 // forward the event here so we don't lose the event 3242 return error; 3243 } 3244 } 3245 } 3246 else 3247 { 3248 if (log) 3249 log->Printf("Process::Destroy() Halt got error: %s", error.AsCString()); 3250 return error; 3251 } 3252 } 3253 3254 if (m_public_state.GetValue() != eStateRunning) 3255 { 3256 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to 3257 // kill it, we don't want it hitting a breakpoint... 3258 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then 3259 // we're not going to have much luck doing this now. 3260 m_thread_list.DiscardThreadPlans(); 3261 DisableAllBreakpointSites(); 3262 } 3263 3264 error = DoDestroy(); 3265 if (error.Success()) 3266 { 3267 DidDestroy(); 3268 StopPrivateStateThread(); 3269 } 3270 m_stdio_communication.StopReadThread(); 3271 m_stdio_communication.Disconnect(); 3272 if (m_process_input_reader && m_process_input_reader->IsActive()) 3273 m_target.GetDebugger().PopInputReader (m_process_input_reader); 3274 if (m_process_input_reader) 3275 m_process_input_reader.reset(); 3276 3277 // If we exited when we were waiting for a process to stop, then 3278 // forward the event here so we don't lose the event 3279 if (exit_event_sp) 3280 { 3281 // Directly broadcast our exited event because we shut down our 3282 // private state thread above 3283 BroadcastEvent(exit_event_sp); 3284 } 3285 3286 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating 3287 // the last events through the event system, in which case we might strand the write lock. Unlock 3288 // it here so when we do to tear down the process we don't get an error destroying the lock. 3289 m_run_lock.WriteUnlock(); 3290 } 3291 return error; 3292 } 3293 3294 Error 3295 Process::Signal (int signal) 3296 { 3297 Error error (WillSignal()); 3298 if (error.Success()) 3299 { 3300 error = DoSignal(signal); 3301 if (error.Success()) 3302 DidSignal(); 3303 } 3304 return error; 3305 } 3306 3307 lldb::ByteOrder 3308 Process::GetByteOrder () const 3309 { 3310 return m_target.GetArchitecture().GetByteOrder(); 3311 } 3312 3313 uint32_t 3314 Process::GetAddressByteSize () const 3315 { 3316 return m_target.GetArchitecture().GetAddressByteSize(); 3317 } 3318 3319 3320 bool 3321 Process::ShouldBroadcastEvent (Event *event_ptr) 3322 { 3323 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr); 3324 bool return_value = true; 3325 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS)); 3326 3327 switch (state) 3328 { 3329 case eStateConnected: 3330 case eStateAttaching: 3331 case eStateLaunching: 3332 case eStateDetached: 3333 case eStateExited: 3334 case eStateUnloaded: 3335 // These events indicate changes in the state of the debugging session, always report them. 3336 return_value = true; 3337 break; 3338 case eStateInvalid: 3339 // We stopped for no apparent reason, don't report it. 3340 return_value = false; 3341 break; 3342 case eStateRunning: 3343 case eStateStepping: 3344 // If we've started the target running, we handle the cases where we 3345 // are already running and where there is a transition from stopped to 3346 // running differently. 3347 // running -> running: Automatically suppress extra running events 3348 // stopped -> running: Report except when there is one or more no votes 3349 // and no yes votes. 3350 SynchronouslyNotifyStateChanged (state); 3351 switch (m_public_state.GetValue()) 3352 { 3353 case eStateRunning: 3354 case eStateStepping: 3355 // We always suppress multiple runnings with no PUBLIC stop in between. 3356 return_value = false; 3357 break; 3358 default: 3359 // TODO: make this work correctly. For now always report 3360 // run if we aren't running so we don't miss any runnning 3361 // events. If I run the lldb/test/thread/a.out file and 3362 // break at main.cpp:58, run and hit the breakpoints on 3363 // multiple threads, then somehow during the stepping over 3364 // of all breakpoints no run gets reported. 3365 3366 // This is a transition from stop to run. 3367 switch (m_thread_list.ShouldReportRun (event_ptr)) 3368 { 3369 default: 3370 case eVoteYes: 3371 case eVoteNoOpinion: 3372 return_value = true; 3373 break; 3374 case eVoteNo: 3375 return_value = false; 3376 break; 3377 } 3378 break; 3379 } 3380 break; 3381 case eStateStopped: 3382 case eStateCrashed: 3383 case eStateSuspended: 3384 { 3385 // We've stopped. First see if we're going to restart the target. 3386 // If we are going to stop, then we always broadcast the event. 3387 // If we aren't going to stop, let the thread plans decide if we're going to report this event. 3388 // If no thread has an opinion, we don't report it. 3389 3390 RefreshStateAfterStop (); 3391 if (ProcessEventData::GetInterruptedFromEvent (event_ptr)) 3392 { 3393 if (log) 3394 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state)); 3395 return true; 3396 } 3397 else 3398 { 3399 3400 if (m_thread_list.ShouldStop (event_ptr) == false) 3401 { 3402 // ShouldStop may have restarted the target already. If so, don't 3403 // resume it twice. 3404 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr); 3405 switch (m_thread_list.ShouldReportStop (event_ptr)) 3406 { 3407 case eVoteYes: 3408 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true); 3409 // Intentional fall-through here. 3410 case eVoteNoOpinion: 3411 case eVoteNo: 3412 return_value = false; 3413 break; 3414 } 3415 3416 if (log) 3417 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state)); 3418 if (!was_restarted) 3419 PrivateResume (); 3420 } 3421 else 3422 { 3423 return_value = true; 3424 SynchronouslyNotifyStateChanged (state); 3425 } 3426 } 3427 } 3428 } 3429 3430 if (log) 3431 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s - %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO"); 3432 return return_value; 3433 } 3434 3435 3436 bool 3437 Process::StartPrivateStateThread (bool force) 3438 { 3439 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS)); 3440 3441 bool already_running = PrivateStateThreadIsValid (); 3442 if (log) 3443 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread"); 3444 3445 if (!force && already_running) 3446 return true; 3447 3448 // Create a thread that watches our internal state and controls which 3449 // events make it to clients (into the DCProcess event queue). 3450 char thread_name[1024]; 3451 if (already_running) 3452 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%llu)>", GetID()); 3453 else 3454 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%llu)>", GetID()); 3455 3456 // Create the private state thread, and start it running. 3457 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL); 3458 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread); 3459 if (success) 3460 { 3461 ResumePrivateStateThread(); 3462 return true; 3463 } 3464 else 3465 return false; 3466 } 3467 3468 void 3469 Process::PausePrivateStateThread () 3470 { 3471 ControlPrivateStateThread (eBroadcastInternalStateControlPause); 3472 } 3473 3474 void 3475 Process::ResumePrivateStateThread () 3476 { 3477 ControlPrivateStateThread (eBroadcastInternalStateControlResume); 3478 } 3479 3480 void 3481 Process::StopPrivateStateThread () 3482 { 3483 if (PrivateStateThreadIsValid ()) 3484 ControlPrivateStateThread (eBroadcastInternalStateControlStop); 3485 else 3486 { 3487 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 3488 if (log) 3489 printf ("Went to stop the private state thread, but it was already invalid."); 3490 } 3491 } 3492 3493 void 3494 Process::ControlPrivateStateThread (uint32_t signal) 3495 { 3496 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 3497 3498 assert (signal == eBroadcastInternalStateControlStop || 3499 signal == eBroadcastInternalStateControlPause || 3500 signal == eBroadcastInternalStateControlResume); 3501 3502 if (log) 3503 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal); 3504 3505 // Signal the private state thread. First we should copy this is case the 3506 // thread starts exiting since the private state thread will NULL this out 3507 // when it exits 3508 const lldb::thread_t private_state_thread = m_private_state_thread; 3509 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread)) 3510 { 3511 TimeValue timeout_time; 3512 bool timed_out; 3513 3514 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL); 3515 3516 timeout_time = TimeValue::Now(); 3517 timeout_time.OffsetWithSeconds(2); 3518 if (log) 3519 log->Printf ("Sending control event of type: %d.", signal); 3520 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out); 3521 m_private_state_control_wait.SetValue (false, eBroadcastNever); 3522 3523 if (signal == eBroadcastInternalStateControlStop) 3524 { 3525 if (timed_out) 3526 { 3527 Error error; 3528 Host::ThreadCancel (private_state_thread, &error); 3529 if (log) 3530 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString()); 3531 } 3532 else 3533 { 3534 if (log) 3535 log->Printf ("The control event killed the private state thread without having to cancel."); 3536 } 3537 3538 thread_result_t result = NULL; 3539 Host::ThreadJoin (private_state_thread, &result, NULL); 3540 m_private_state_thread = LLDB_INVALID_HOST_THREAD; 3541 } 3542 } 3543 else 3544 { 3545 if (log) 3546 log->Printf ("Private state thread already dead, no need to signal it to stop."); 3547 } 3548 } 3549 3550 void 3551 Process::SendAsyncInterrupt () 3552 { 3553 if (PrivateStateThreadIsValid()) 3554 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL); 3555 else 3556 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL); 3557 } 3558 3559 void 3560 Process::HandlePrivateEvent (EventSP &event_sp) 3561 { 3562 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 3563 m_currently_handling_event.SetValue(true, eBroadcastNever); 3564 3565 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 3566 3567 // First check to see if anybody wants a shot at this event: 3568 if (m_next_event_action_ap.get() != NULL) 3569 { 3570 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp); 3571 switch (action_result) 3572 { 3573 case NextEventAction::eEventActionSuccess: 3574 SetNextEventAction(NULL); 3575 break; 3576 3577 case NextEventAction::eEventActionRetry: 3578 break; 3579 3580 case NextEventAction::eEventActionExit: 3581 // Handle Exiting Here. If we already got an exited event, 3582 // we should just propagate it. Otherwise, swallow this event, 3583 // and set our state to exit so the next event will kill us. 3584 if (new_state != eStateExited) 3585 { 3586 // FIXME: should cons up an exited event, and discard this one. 3587 SetExitStatus(0, m_next_event_action_ap->GetExitString()); 3588 SetNextEventAction(NULL); 3589 return; 3590 } 3591 SetNextEventAction(NULL); 3592 break; 3593 } 3594 } 3595 3596 // See if we should broadcast this state to external clients? 3597 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get()); 3598 3599 if (should_broadcast) 3600 { 3601 if (log) 3602 { 3603 log->Printf ("Process::%s (pid = %llu) broadcasting new state %s (old state %s) to %s", 3604 __FUNCTION__, 3605 GetID(), 3606 StateAsCString(new_state), 3607 StateAsCString (GetState ()), 3608 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public"); 3609 } 3610 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get()); 3611 if (StateIsRunningState (new_state)) 3612 PushProcessInputReader (); 3613 else 3614 PopProcessInputReader (); 3615 3616 BroadcastEvent (event_sp); 3617 } 3618 else 3619 { 3620 if (log) 3621 { 3622 log->Printf ("Process::%s (pid = %llu) suppressing state %s (old state %s): should_broadcast == false", 3623 __FUNCTION__, 3624 GetID(), 3625 StateAsCString(new_state), 3626 StateAsCString (GetState ())); 3627 } 3628 } 3629 m_currently_handling_event.SetValue(false, eBroadcastAlways); 3630 } 3631 3632 void * 3633 Process::PrivateStateThread (void *arg) 3634 { 3635 Process *proc = static_cast<Process*> (arg); 3636 void *result = proc->RunPrivateStateThread (); 3637 return result; 3638 } 3639 3640 void * 3641 Process::RunPrivateStateThread () 3642 { 3643 bool control_only = true; 3644 m_private_state_control_wait.SetValue (false, eBroadcastNever); 3645 3646 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 3647 if (log) 3648 log->Printf ("Process::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, this, GetID()); 3649 3650 bool exit_now = false; 3651 while (!exit_now) 3652 { 3653 EventSP event_sp; 3654 WaitForEventsPrivate (NULL, event_sp, control_only); 3655 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) 3656 { 3657 if (log) 3658 log->Printf ("Process::%s (arg = %p, pid = %llu) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType()); 3659 3660 switch (event_sp->GetType()) 3661 { 3662 case eBroadcastInternalStateControlStop: 3663 exit_now = true; 3664 break; // doing any internal state managment below 3665 3666 case eBroadcastInternalStateControlPause: 3667 control_only = true; 3668 break; 3669 3670 case eBroadcastInternalStateControlResume: 3671 control_only = false; 3672 break; 3673 } 3674 3675 m_private_state_control_wait.SetValue (true, eBroadcastAlways); 3676 continue; 3677 } 3678 else if (event_sp->GetType() == eBroadcastBitInterrupt) 3679 { 3680 if (m_public_state.GetValue() == eStateAttaching) 3681 { 3682 if (log) 3683 log->Printf ("Process::%s (arg = %p, pid = %llu) woke up with an interrupt while attaching - forwarding interrupt.", __FUNCTION__, this, GetID()); 3684 BroadcastEvent (eBroadcastBitInterrupt, NULL); 3685 } 3686 else 3687 { 3688 if (log) 3689 log->Printf ("Process::%s (arg = %p, pid = %llu) woke up with an interrupt - Halting.", __FUNCTION__, this, GetID()); 3690 Halt(); 3691 } 3692 continue; 3693 } 3694 3695 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 3696 3697 if (internal_state != eStateInvalid) 3698 { 3699 HandlePrivateEvent (event_sp); 3700 } 3701 3702 if (internal_state == eStateInvalid || 3703 internal_state == eStateExited || 3704 internal_state == eStateDetached ) 3705 { 3706 if (log) 3707 log->Printf ("Process::%s (arg = %p, pid = %llu) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state)); 3708 3709 break; 3710 } 3711 } 3712 3713 // Verify log is still enabled before attempting to write to it... 3714 if (log) 3715 log->Printf ("Process::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, this, GetID()); 3716 3717 m_private_state_control_wait.SetValue (true, eBroadcastAlways); 3718 m_private_state_thread = LLDB_INVALID_HOST_THREAD; 3719 return NULL; 3720 } 3721 3722 //------------------------------------------------------------------ 3723 // Process Event Data 3724 //------------------------------------------------------------------ 3725 3726 Process::ProcessEventData::ProcessEventData () : 3727 EventData (), 3728 m_process_sp (), 3729 m_state (eStateInvalid), 3730 m_restarted (false), 3731 m_update_state (0), 3732 m_interrupted (false) 3733 { 3734 } 3735 3736 Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) : 3737 EventData (), 3738 m_process_sp (process_sp), 3739 m_state (state), 3740 m_restarted (false), 3741 m_update_state (0), 3742 m_interrupted (false) 3743 { 3744 } 3745 3746 Process::ProcessEventData::~ProcessEventData() 3747 { 3748 } 3749 3750 const ConstString & 3751 Process::ProcessEventData::GetFlavorString () 3752 { 3753 static ConstString g_flavor ("Process::ProcessEventData"); 3754 return g_flavor; 3755 } 3756 3757 const ConstString & 3758 Process::ProcessEventData::GetFlavor () const 3759 { 3760 return ProcessEventData::GetFlavorString (); 3761 } 3762 3763 void 3764 Process::ProcessEventData::DoOnRemoval (Event *event_ptr) 3765 { 3766 // This function gets called twice for each event, once when the event gets pulled 3767 // off of the private process event queue, and then any number of times, first when it gets pulled off of 3768 // the public event queue, then other times when we're pretending that this is where we stopped at the 3769 // end of expression evaluation. m_update_state is used to distinguish these 3770 // three cases; it is 0 when we're just pulling it off for private handling, 3771 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then. 3772 3773 if (m_update_state != 1) 3774 return; 3775 3776 m_process_sp->SetPublicState (m_state); 3777 3778 // If we're stopped and haven't restarted, then do the breakpoint commands here: 3779 if (m_state == eStateStopped && ! m_restarted) 3780 { 3781 ThreadList &curr_thread_list = m_process_sp->GetThreadList(); 3782 uint32_t num_threads = curr_thread_list.GetSize(); 3783 uint32_t idx; 3784 3785 // The actions might change one of the thread's stop_info's opinions about whether we should 3786 // stop the process, so we need to query that as we go. 3787 3788 // One other complication here, is that we try to catch any case where the target has run (except for expressions) 3789 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and 3790 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like 3791 // to also know if it has changed at all, so we make up a vector of the thread ID's and check what we get back 3792 // against this list & bag out if anything differs. 3793 std::vector<uint32_t> thread_index_array(num_threads); 3794 for (idx = 0; idx < num_threads; ++idx) 3795 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID(); 3796 3797 bool still_should_stop = true; 3798 3799 for (idx = 0; idx < num_threads; ++idx) 3800 { 3801 curr_thread_list = m_process_sp->GetThreadList(); 3802 if (curr_thread_list.GetSize() != num_threads) 3803 { 3804 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS)); 3805 if (log) 3806 log->Printf("Number of threads changed from %u to %u while processing event.", num_threads, curr_thread_list.GetSize()); 3807 break; 3808 } 3809 3810 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx); 3811 3812 if (thread_sp->GetIndexID() != thread_index_array[idx]) 3813 { 3814 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS)); 3815 if (log) 3816 log->Printf("The thread at position %u changed from %u to %u while processing event.", 3817 idx, 3818 thread_index_array[idx], 3819 thread_sp->GetIndexID()); 3820 break; 3821 } 3822 3823 StopInfoSP stop_info_sp = thread_sp->GetStopInfo (); 3824 if (stop_info_sp && stop_info_sp->IsValid()) 3825 { 3826 stop_info_sp->PerformAction(event_ptr); 3827 // The stop action might restart the target. If it does, then we want to mark that in the 3828 // event so that whoever is receiving it will know to wait for the running event and reflect 3829 // that state appropriately. 3830 // We also need to stop processing actions, since they aren't expecting the target to be running. 3831 3832 // FIXME: we might have run. 3833 if (stop_info_sp->HasTargetRunSinceMe()) 3834 { 3835 SetRestarted (true); 3836 break; 3837 } 3838 else if (!stop_info_sp->ShouldStop(event_ptr)) 3839 { 3840 still_should_stop = false; 3841 } 3842 } 3843 } 3844 3845 3846 if (m_process_sp->GetPrivateState() != eStateRunning) 3847 { 3848 if (!still_should_stop) 3849 { 3850 // We've been asked to continue, so do that here. 3851 SetRestarted(true); 3852 // Use the public resume method here, since this is just 3853 // extending a public resume. 3854 m_process_sp->Resume(); 3855 } 3856 else 3857 { 3858 // If we didn't restart, run the Stop Hooks here: 3859 // They might also restart the target, so watch for that. 3860 m_process_sp->GetTarget().RunStopHooks(); 3861 if (m_process_sp->GetPrivateState() == eStateRunning) 3862 SetRestarted(true); 3863 } 3864 } 3865 3866 } 3867 } 3868 3869 void 3870 Process::ProcessEventData::Dump (Stream *s) const 3871 { 3872 if (m_process_sp) 3873 s->Printf(" process = %p (pid = %llu), ", m_process_sp.get(), m_process_sp->GetID()); 3874 3875 s->Printf("state = %s", StateAsCString(GetState())); 3876 } 3877 3878 const Process::ProcessEventData * 3879 Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr) 3880 { 3881 if (event_ptr) 3882 { 3883 const EventData *event_data = event_ptr->GetData(); 3884 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString()) 3885 return static_cast <const ProcessEventData *> (event_ptr->GetData()); 3886 } 3887 return NULL; 3888 } 3889 3890 ProcessSP 3891 Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr) 3892 { 3893 ProcessSP process_sp; 3894 const ProcessEventData *data = GetEventDataFromEvent (event_ptr); 3895 if (data) 3896 process_sp = data->GetProcessSP(); 3897 return process_sp; 3898 } 3899 3900 StateType 3901 Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr) 3902 { 3903 const ProcessEventData *data = GetEventDataFromEvent (event_ptr); 3904 if (data == NULL) 3905 return eStateInvalid; 3906 else 3907 return data->GetState(); 3908 } 3909 3910 bool 3911 Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr) 3912 { 3913 const ProcessEventData *data = GetEventDataFromEvent (event_ptr); 3914 if (data == NULL) 3915 return false; 3916 else 3917 return data->GetRestarted(); 3918 } 3919 3920 void 3921 Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value) 3922 { 3923 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr)); 3924 if (data != NULL) 3925 data->SetRestarted(new_value); 3926 } 3927 3928 bool 3929 Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr) 3930 { 3931 const ProcessEventData *data = GetEventDataFromEvent (event_ptr); 3932 if (data == NULL) 3933 return false; 3934 else 3935 return data->GetInterrupted (); 3936 } 3937 3938 void 3939 Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value) 3940 { 3941 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr)); 3942 if (data != NULL) 3943 data->SetInterrupted(new_value); 3944 } 3945 3946 bool 3947 Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr) 3948 { 3949 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr)); 3950 if (data) 3951 { 3952 data->SetUpdateStateOnRemoval(); 3953 return true; 3954 } 3955 return false; 3956 } 3957 3958 lldb::TargetSP 3959 Process::CalculateTarget () 3960 { 3961 return m_target.shared_from_this(); 3962 } 3963 3964 void 3965 Process::CalculateExecutionContext (ExecutionContext &exe_ctx) 3966 { 3967 exe_ctx.SetTargetPtr (&m_target); 3968 exe_ctx.SetProcessPtr (this); 3969 exe_ctx.SetThreadPtr(NULL); 3970 exe_ctx.SetFramePtr (NULL); 3971 } 3972 3973 //uint32_t 3974 //Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids) 3975 //{ 3976 // return 0; 3977 //} 3978 // 3979 //ArchSpec 3980 //Process::GetArchSpecForExistingProcess (lldb::pid_t pid) 3981 //{ 3982 // return Host::GetArchSpecForExistingProcess (pid); 3983 //} 3984 // 3985 //ArchSpec 3986 //Process::GetArchSpecForExistingProcess (const char *process_name) 3987 //{ 3988 // return Host::GetArchSpecForExistingProcess (process_name); 3989 //} 3990 // 3991 void 3992 Process::AppendSTDOUT (const char * s, size_t len) 3993 { 3994 Mutex::Locker locker (m_stdio_communication_mutex); 3995 m_stdout_data.append (s, len); 3996 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState())); 3997 } 3998 3999 void 4000 Process::AppendSTDERR (const char * s, size_t len) 4001 { 4002 Mutex::Locker locker (m_stdio_communication_mutex); 4003 m_stderr_data.append (s, len); 4004 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState())); 4005 } 4006 4007 void 4008 Process::BroadcastAsyncProfileData(const char *s, size_t len) 4009 { 4010 Mutex::Locker locker (m_profile_data_comm_mutex); 4011 m_profile_data.append (s, len); 4012 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState())); 4013 } 4014 4015 size_t 4016 Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error) 4017 { 4018 Mutex::Locker locker(m_profile_data_comm_mutex); 4019 size_t bytes_available = m_profile_data.size(); 4020 if (bytes_available > 0) 4021 { 4022 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 4023 if (log) 4024 log->Printf ("Process::GetProfileData (buf = %p, size = %llu)", buf, (uint64_t)buf_size); 4025 if (bytes_available > buf_size) 4026 { 4027 memcpy(buf, m_profile_data.c_str(), buf_size); 4028 m_profile_data.erase(0, buf_size); 4029 bytes_available = buf_size; 4030 } 4031 else 4032 { 4033 memcpy(buf, m_profile_data.c_str(), bytes_available); 4034 m_profile_data.clear(); 4035 } 4036 } 4037 return bytes_available; 4038 } 4039 4040 4041 //------------------------------------------------------------------ 4042 // Process STDIO 4043 //------------------------------------------------------------------ 4044 4045 size_t 4046 Process::GetSTDOUT (char *buf, size_t buf_size, Error &error) 4047 { 4048 Mutex::Locker locker(m_stdio_communication_mutex); 4049 size_t bytes_available = m_stdout_data.size(); 4050 if (bytes_available > 0) 4051 { 4052 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 4053 if (log) 4054 log->Printf ("Process::GetSTDOUT (buf = %p, size = %llu)", buf, (uint64_t)buf_size); 4055 if (bytes_available > buf_size) 4056 { 4057 memcpy(buf, m_stdout_data.c_str(), buf_size); 4058 m_stdout_data.erase(0, buf_size); 4059 bytes_available = buf_size; 4060 } 4061 else 4062 { 4063 memcpy(buf, m_stdout_data.c_str(), bytes_available); 4064 m_stdout_data.clear(); 4065 } 4066 } 4067 return bytes_available; 4068 } 4069 4070 4071 size_t 4072 Process::GetSTDERR (char *buf, size_t buf_size, Error &error) 4073 { 4074 Mutex::Locker locker(m_stdio_communication_mutex); 4075 size_t bytes_available = m_stderr_data.size(); 4076 if (bytes_available > 0) 4077 { 4078 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 4079 if (log) 4080 log->Printf ("Process::GetSTDERR (buf = %p, size = %llu)", buf, (uint64_t)buf_size); 4081 if (bytes_available > buf_size) 4082 { 4083 memcpy(buf, m_stderr_data.c_str(), buf_size); 4084 m_stderr_data.erase(0, buf_size); 4085 bytes_available = buf_size; 4086 } 4087 else 4088 { 4089 memcpy(buf, m_stderr_data.c_str(), bytes_available); 4090 m_stderr_data.clear(); 4091 } 4092 } 4093 return bytes_available; 4094 } 4095 4096 void 4097 Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len) 4098 { 4099 Process *process = (Process *) baton; 4100 process->AppendSTDOUT (static_cast<const char *>(src), src_len); 4101 } 4102 4103 size_t 4104 Process::ProcessInputReaderCallback (void *baton, 4105 InputReader &reader, 4106 lldb::InputReaderAction notification, 4107 const char *bytes, 4108 size_t bytes_len) 4109 { 4110 Process *process = (Process *) baton; 4111 4112 switch (notification) 4113 { 4114 case eInputReaderActivate: 4115 break; 4116 4117 case eInputReaderDeactivate: 4118 break; 4119 4120 case eInputReaderReactivate: 4121 break; 4122 4123 case eInputReaderAsynchronousOutputWritten: 4124 break; 4125 4126 case eInputReaderGotToken: 4127 { 4128 Error error; 4129 process->PutSTDIN (bytes, bytes_len, error); 4130 } 4131 break; 4132 4133 case eInputReaderInterrupt: 4134 process->Halt (); 4135 break; 4136 4137 case eInputReaderEndOfFile: 4138 process->AppendSTDOUT ("^D", 2); 4139 break; 4140 4141 case eInputReaderDone: 4142 break; 4143 4144 } 4145 4146 return bytes_len; 4147 } 4148 4149 void 4150 Process::ResetProcessInputReader () 4151 { 4152 m_process_input_reader.reset(); 4153 } 4154 4155 void 4156 Process::SetSTDIOFileDescriptor (int file_descriptor) 4157 { 4158 // First set up the Read Thread for reading/handling process I/O 4159 4160 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true)); 4161 4162 if (conn_ap.get()) 4163 { 4164 m_stdio_communication.SetConnection (conn_ap.release()); 4165 if (m_stdio_communication.IsConnected()) 4166 { 4167 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this); 4168 m_stdio_communication.StartReadThread(); 4169 4170 // Now read thread is set up, set up input reader. 4171 4172 if (!m_process_input_reader.get()) 4173 { 4174 m_process_input_reader.reset (new InputReader(m_target.GetDebugger())); 4175 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback, 4176 this, 4177 eInputReaderGranularityByte, 4178 NULL, 4179 NULL, 4180 false)); 4181 4182 if (err.Fail()) 4183 m_process_input_reader.reset(); 4184 } 4185 } 4186 } 4187 } 4188 4189 void 4190 Process::PushProcessInputReader () 4191 { 4192 if (m_process_input_reader && !m_process_input_reader->IsActive()) 4193 m_target.GetDebugger().PushInputReader (m_process_input_reader); 4194 } 4195 4196 void 4197 Process::PopProcessInputReader () 4198 { 4199 if (m_process_input_reader && m_process_input_reader->IsActive()) 4200 m_target.GetDebugger().PopInputReader (m_process_input_reader); 4201 } 4202 4203 // The process needs to know about installed plug-ins 4204 void 4205 Process::SettingsInitialize () 4206 { 4207 // static std::vector<OptionEnumValueElement> g_plugins; 4208 // 4209 // int i=0; 4210 // const char *name; 4211 // OptionEnumValueElement option_enum; 4212 // while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL) 4213 // { 4214 // if (name) 4215 // { 4216 // option_enum.value = i; 4217 // option_enum.string_value = name; 4218 // option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i); 4219 // g_plugins.push_back (option_enum); 4220 // } 4221 // ++i; 4222 // } 4223 // option_enum.value = 0; 4224 // option_enum.string_value = NULL; 4225 // option_enum.usage = NULL; 4226 // g_plugins.push_back (option_enum); 4227 // 4228 // for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i) 4229 // { 4230 // if (::strcmp (name, "plugin") == 0) 4231 // { 4232 // SettingsController::instance_settings_table[i].enum_values = &g_plugins[0]; 4233 // break; 4234 // } 4235 // } 4236 // 4237 Thread::SettingsInitialize (); 4238 } 4239 4240 void 4241 Process::SettingsTerminate () 4242 { 4243 Thread::SettingsTerminate (); 4244 } 4245 4246 ExecutionResults 4247 Process::RunThreadPlan (ExecutionContext &exe_ctx, 4248 lldb::ThreadPlanSP &thread_plan_sp, 4249 bool stop_others, 4250 bool run_others, 4251 bool discard_on_error, 4252 uint32_t timeout_usec, 4253 Stream &errors) 4254 { 4255 ExecutionResults return_value = eExecutionSetupError; 4256 4257 if (thread_plan_sp.get() == NULL) 4258 { 4259 errors.Printf("RunThreadPlan called with empty thread plan."); 4260 return eExecutionSetupError; 4261 } 4262 4263 if (exe_ctx.GetProcessPtr() != this) 4264 { 4265 errors.Printf("RunThreadPlan called on wrong process."); 4266 return eExecutionSetupError; 4267 } 4268 4269 Thread *thread = exe_ctx.GetThreadPtr(); 4270 if (thread == NULL) 4271 { 4272 errors.Printf("RunThreadPlan called with invalid thread."); 4273 return eExecutionSetupError; 4274 } 4275 4276 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes. 4277 // For that to be true the plan can't be private - since private plans suppress themselves in the 4278 // GetCompletedPlan call. 4279 4280 bool orig_plan_private = thread_plan_sp->GetPrivate(); 4281 thread_plan_sp->SetPrivate(false); 4282 4283 if (m_private_state.GetValue() != eStateStopped) 4284 { 4285 errors.Printf ("RunThreadPlan called while the private state was not stopped."); 4286 return eExecutionSetupError; 4287 } 4288 4289 // Save the thread & frame from the exe_ctx for restoration after we run 4290 const uint32_t thread_idx_id = thread->GetIndexID(); 4291 StackID ctx_frame_id = thread->GetSelectedFrame()->GetStackID(); 4292 4293 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either, 4294 // so we should arrange to reset them as well. 4295 4296 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread(); 4297 4298 uint32_t selected_tid; 4299 StackID selected_stack_id; 4300 if (selected_thread_sp) 4301 { 4302 selected_tid = selected_thread_sp->GetIndexID(); 4303 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID(); 4304 } 4305 else 4306 { 4307 selected_tid = LLDB_INVALID_THREAD_ID; 4308 } 4309 4310 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD; 4311 lldb::StateType old_state; 4312 lldb::ThreadPlanSP stopper_base_plan_sp; 4313 4314 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS)); 4315 if (Host::GetCurrentThread() == m_private_state_thread) 4316 { 4317 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since 4318 // we are the thread that is generating public events. 4319 // The simplest thing to do is to spin up a temporary thread to handle private state thread events while 4320 // we are fielding public events here. 4321 if (log) 4322 log->Printf ("Running thread plan on private state thread, spinning up another state thread to handle the events."); 4323 4324 4325 backup_private_state_thread = m_private_state_thread; 4326 4327 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop, 4328 // returning control here. 4329 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop 4330 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack 4331 // before the plan we want to run. Since base plans always stop and return control to the user, that will 4332 // do just what we want. 4333 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread)); 4334 thread->QueueThreadPlan (stopper_base_plan_sp, false); 4335 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly. 4336 old_state = m_public_state.GetValue(); 4337 m_public_state.SetValueNoLock(eStateStopped); 4338 4339 // Now spin up the private state thread: 4340 StartPrivateStateThread(true); 4341 } 4342 4343 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense? 4344 4345 Listener listener("lldb.process.listener.run-thread-plan"); 4346 4347 lldb::EventSP event_to_broadcast_sp; 4348 4349 { 4350 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get 4351 // restored on exit to the function. 4352 // 4353 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event 4354 // is put into event_to_broadcast_sp for rebroadcasting. 4355 4356 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener); 4357 4358 if (log) 4359 { 4360 StreamString s; 4361 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose); 4362 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4llx to run thread plan \"%s\".", 4363 thread->GetIndexID(), 4364 thread->GetID(), 4365 s.GetData()); 4366 } 4367 4368 bool got_event; 4369 lldb::EventSP event_sp; 4370 lldb::StateType stop_state = lldb::eStateInvalid; 4371 4372 TimeValue* timeout_ptr = NULL; 4373 TimeValue real_timeout; 4374 4375 bool first_timeout = true; 4376 bool do_resume = true; 4377 const uint64_t default_one_thread_timeout_usec = 250000; 4378 uint64_t computed_timeout = 0; 4379 4380 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done. 4381 // So don't call return anywhere within it. 4382 4383 while (1) 4384 { 4385 // We usually want to resume the process if we get to the top of the loop. 4386 // The only exception is if we get two running events with no intervening 4387 // stop, which can happen, we will just wait for then next stop event. 4388 4389 if (do_resume) 4390 { 4391 // Do the initial resume and wait for the running event before going further. 4392 4393 Error resume_error = PrivateResume (); 4394 if (!resume_error.Success()) 4395 { 4396 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString()); 4397 return_value = eExecutionSetupError; 4398 break; 4399 } 4400 4401 real_timeout = TimeValue::Now(); 4402 real_timeout.OffsetWithMicroSeconds(500000); 4403 timeout_ptr = &real_timeout; 4404 4405 got_event = listener.WaitForEvent(timeout_ptr, event_sp); 4406 if (!got_event) 4407 { 4408 if (log) 4409 log->PutCString("Process::RunThreadPlan(): didn't get any event after initial resume, exiting."); 4410 4411 errors.Printf("Didn't get any event after initial resume, exiting."); 4412 return_value = eExecutionSetupError; 4413 break; 4414 } 4415 4416 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 4417 if (stop_state != eStateRunning) 4418 { 4419 if (log) 4420 log->Printf("Process::RunThreadPlan(): didn't get running event after " 4421 "initial resume, got %s instead.", 4422 StateAsCString(stop_state)); 4423 4424 errors.Printf("Didn't get running event after initial resume, got %s instead.", 4425 StateAsCString(stop_state)); 4426 return_value = eExecutionSetupError; 4427 break; 4428 } 4429 4430 if (log) 4431 log->PutCString ("Process::RunThreadPlan(): resuming succeeded."); 4432 // We need to call the function synchronously, so spin waiting for it to return. 4433 // If we get interrupted while executing, we're going to lose our context, and 4434 // won't be able to gather the result at this point. 4435 // We set the timeout AFTER the resume, since the resume takes some time and we 4436 // don't want to charge that to the timeout. 4437 4438 if (first_timeout) 4439 { 4440 if (run_others) 4441 { 4442 // If we are running all threads then we take half the time to run all threads, bounded by 4443 // .25 sec. 4444 if (timeout_usec == 0) 4445 computed_timeout = default_one_thread_timeout_usec; 4446 else 4447 { 4448 computed_timeout = timeout_usec / 2; 4449 if (computed_timeout > default_one_thread_timeout_usec) 4450 { 4451 computed_timeout = default_one_thread_timeout_usec; 4452 } 4453 timeout_usec -= computed_timeout; 4454 } 4455 } 4456 else 4457 { 4458 computed_timeout = timeout_usec; 4459 } 4460 } 4461 else 4462 { 4463 computed_timeout = timeout_usec; 4464 } 4465 4466 if (computed_timeout != 0) 4467 { 4468 // we have a > 0 timeout, let us set it so that we stop after the deadline 4469 real_timeout = TimeValue::Now(); 4470 real_timeout.OffsetWithMicroSeconds(computed_timeout); 4471 4472 timeout_ptr = &real_timeout; 4473 } 4474 else 4475 { 4476 timeout_ptr = NULL; 4477 } 4478 } 4479 else 4480 { 4481 if (log) 4482 log->PutCString ("Process::RunThreadPlan(): handled an extra running event."); 4483 do_resume = true; 4484 } 4485 4486 // Now wait for the process to stop again: 4487 event_sp.reset(); 4488 4489 if (log) 4490 { 4491 if (timeout_ptr) 4492 { 4493 StreamString s; 4494 s.Printf ("about to wait - timeout is:\n "); 4495 timeout_ptr->Dump (&s, 120); 4496 s.Printf ("\nNow is:\n "); 4497 TimeValue::Now().Dump (&s, 120); 4498 log->Printf ("Process::RunThreadPlan(): %s", s.GetData()); 4499 } 4500 else 4501 { 4502 log->Printf ("Process::RunThreadPlan(): about to wait forever."); 4503 } 4504 } 4505 4506 got_event = listener.WaitForEvent (timeout_ptr, event_sp); 4507 4508 if (got_event) 4509 { 4510 if (event_sp.get()) 4511 { 4512 bool keep_going = false; 4513 if (event_sp->GetType() == eBroadcastBitInterrupt) 4514 { 4515 Halt(); 4516 keep_going = false; 4517 return_value = eExecutionInterrupted; 4518 errors.Printf ("Execution halted by user interrupt."); 4519 if (log) 4520 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting."); 4521 } 4522 else 4523 { 4524 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 4525 if (log) 4526 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state)); 4527 4528 switch (stop_state) 4529 { 4530 case lldb::eStateStopped: 4531 { 4532 // Yay, we're done. Now make sure that our thread plan actually completed. 4533 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id); 4534 if (!thread_sp) 4535 { 4536 // Ooh, our thread has vanished. Unlikely that this was successful execution... 4537 if (log) 4538 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id); 4539 return_value = eExecutionInterrupted; 4540 } 4541 else 4542 { 4543 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ()); 4544 StopReason stop_reason = eStopReasonInvalid; 4545 if (stop_info_sp) 4546 stop_reason = stop_info_sp->GetStopReason(); 4547 if (stop_reason == eStopReasonPlanComplete) 4548 { 4549 if (log) 4550 log->PutCString ("Process::RunThreadPlan(): execution completed successfully."); 4551 // Now mark this plan as private so it doesn't get reported as the stop reason 4552 // after this point. 4553 if (thread_plan_sp) 4554 thread_plan_sp->SetPrivate (orig_plan_private); 4555 return_value = eExecutionCompleted; 4556 } 4557 else 4558 { 4559 if (log) 4560 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete."); 4561 4562 return_value = eExecutionInterrupted; 4563 } 4564 } 4565 } 4566 break; 4567 4568 case lldb::eStateCrashed: 4569 if (log) 4570 log->PutCString ("Process::RunThreadPlan(): execution crashed."); 4571 return_value = eExecutionInterrupted; 4572 break; 4573 4574 case lldb::eStateRunning: 4575 do_resume = false; 4576 keep_going = true; 4577 break; 4578 4579 default: 4580 if (log) 4581 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state)); 4582 4583 if (stop_state == eStateExited) 4584 event_to_broadcast_sp = event_sp; 4585 4586 errors.Printf ("Execution stopped with unexpected state.\n"); 4587 return_value = eExecutionInterrupted; 4588 break; 4589 } 4590 } 4591 4592 if (keep_going) 4593 continue; 4594 else 4595 break; 4596 } 4597 else 4598 { 4599 if (log) 4600 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd..."); 4601 return_value = eExecutionInterrupted; 4602 break; 4603 } 4604 } 4605 else 4606 { 4607 // If we didn't get an event that means we've timed out... 4608 // We will interrupt the process here. Depending on what we were asked to do we will 4609 // either exit, or try with all threads running for the same timeout. 4610 // Not really sure what to do if Halt fails here... 4611 4612 if (log) { 4613 if (run_others) 4614 { 4615 if (first_timeout) 4616 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %lld timed out, " 4617 "trying for %d usec with all threads enabled.", 4618 computed_timeout, timeout_usec); 4619 else 4620 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled " 4621 "and timeout: %d timed out, abandoning execution.", 4622 timeout_usec); 4623 } 4624 else 4625 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, " 4626 "abandoning execution.", 4627 timeout_usec); 4628 } 4629 4630 Error halt_error = Halt(); 4631 if (halt_error.Success()) 4632 { 4633 if (log) 4634 log->PutCString ("Process::RunThreadPlan(): Halt succeeded."); 4635 4636 // If halt succeeds, it always produces a stopped event. Wait for that: 4637 4638 real_timeout = TimeValue::Now(); 4639 real_timeout.OffsetWithMicroSeconds(500000); 4640 4641 got_event = listener.WaitForEvent(&real_timeout, event_sp); 4642 4643 if (got_event) 4644 { 4645 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 4646 if (log) 4647 { 4648 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state)); 4649 if (stop_state == lldb::eStateStopped 4650 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get())) 4651 log->PutCString (" Event was the Halt interruption event."); 4652 } 4653 4654 if (stop_state == lldb::eStateStopped) 4655 { 4656 // Between the time we initiated the Halt and the time we delivered it, the process could have 4657 // already finished its job. Check that here: 4658 4659 if (thread->IsThreadPlanDone (thread_plan_sp.get())) 4660 { 4661 if (log) 4662 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. " 4663 "Exiting wait loop."); 4664 return_value = eExecutionCompleted; 4665 break; 4666 } 4667 4668 if (!run_others) 4669 { 4670 if (log) 4671 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting."); 4672 return_value = eExecutionInterrupted; 4673 break; 4674 } 4675 4676 if (first_timeout) 4677 { 4678 // Set all the other threads to run, and return to the top of the loop, which will continue; 4679 first_timeout = false; 4680 thread_plan_sp->SetStopOthers (false); 4681 if (log) 4682 log->PutCString ("Process::RunThreadPlan(): about to resume."); 4683 4684 continue; 4685 } 4686 else 4687 { 4688 // Running all threads failed, so return Interrupted. 4689 if (log) 4690 log->PutCString("Process::RunThreadPlan(): running all threads timed out."); 4691 return_value = eExecutionInterrupted; 4692 break; 4693 } 4694 } 4695 } 4696 else 4697 { if (log) 4698 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. " 4699 "I'm getting out of here passing Interrupted."); 4700 return_value = eExecutionInterrupted; 4701 break; 4702 } 4703 } 4704 else 4705 { 4706 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return 4707 // an error from halt, but if you wait a bit you'll get a stopped event anyway. 4708 if (log) 4709 log->Printf ("Process::RunThreadPlan(): halt failed: error = \"%s\", I'm just going to wait a little longer and see if I get a stopped event.", 4710 halt_error.AsCString()); 4711 real_timeout = TimeValue::Now(); 4712 real_timeout.OffsetWithMicroSeconds(500000); 4713 timeout_ptr = &real_timeout; 4714 got_event = listener.WaitForEvent(&real_timeout, event_sp); 4715 if (!got_event || event_sp.get() == NULL) 4716 { 4717 // This is not going anywhere, bag out. 4718 if (log) 4719 log->PutCString ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed."); 4720 return_value = eExecutionInterrupted; 4721 break; 4722 } 4723 else 4724 { 4725 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 4726 if (log) 4727 log->PutCString ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever..."); 4728 if (stop_state == lldb::eStateStopped) 4729 { 4730 // Between the time we initiated the Halt and the time we delivered it, the process could have 4731 // already finished its job. Check that here: 4732 4733 if (thread->IsThreadPlanDone (thread_plan_sp.get())) 4734 { 4735 if (log) 4736 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. " 4737 "Exiting wait loop."); 4738 return_value = eExecutionCompleted; 4739 break; 4740 } 4741 4742 if (first_timeout) 4743 { 4744 // Set all the other threads to run, and return to the top of the loop, which will continue; 4745 first_timeout = false; 4746 thread_plan_sp->SetStopOthers (false); 4747 if (log) 4748 log->PutCString ("Process::RunThreadPlan(): About to resume."); 4749 4750 continue; 4751 } 4752 else 4753 { 4754 // Running all threads failed, so return Interrupted. 4755 if (log) 4756 log->PutCString ("Process::RunThreadPlan(): running all threads timed out."); 4757 return_value = eExecutionInterrupted; 4758 break; 4759 } 4760 } 4761 else 4762 { 4763 if (log) 4764 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get" 4765 " a stopped event, instead got %s.", StateAsCString(stop_state)); 4766 return_value = eExecutionInterrupted; 4767 break; 4768 } 4769 } 4770 } 4771 4772 } 4773 4774 } // END WAIT LOOP 4775 4776 // If we had to start up a temporary private state thread to run this thread plan, shut it down now. 4777 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread)) 4778 { 4779 StopPrivateStateThread(); 4780 Error error; 4781 m_private_state_thread = backup_private_state_thread; 4782 if (stopper_base_plan_sp) 4783 { 4784 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp); 4785 } 4786 m_public_state.SetValueNoLock(old_state); 4787 4788 } 4789 4790 // Restore the thread state if we are going to discard the plan execution. 4791 4792 if (return_value == eExecutionCompleted || discard_on_error) 4793 { 4794 thread_plan_sp->RestoreThreadState(); 4795 } 4796 4797 // Now do some processing on the results of the run: 4798 if (return_value == eExecutionInterrupted) 4799 { 4800 if (log) 4801 { 4802 StreamString s; 4803 if (event_sp) 4804 event_sp->Dump (&s); 4805 else 4806 { 4807 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL."); 4808 } 4809 4810 StreamString ts; 4811 4812 const char *event_explanation = NULL; 4813 4814 do 4815 { 4816 if (!event_sp) 4817 { 4818 event_explanation = "<no event>"; 4819 break; 4820 } 4821 else if (event_sp->GetType() == eBroadcastBitInterrupt) 4822 { 4823 event_explanation = "<user interrupt>"; 4824 break; 4825 } 4826 else 4827 { 4828 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get()); 4829 4830 if (!event_data) 4831 { 4832 event_explanation = "<no event data>"; 4833 break; 4834 } 4835 4836 Process *process = event_data->GetProcessSP().get(); 4837 4838 if (!process) 4839 { 4840 event_explanation = "<no process>"; 4841 break; 4842 } 4843 4844 ThreadList &thread_list = process->GetThreadList(); 4845 4846 uint32_t num_threads = thread_list.GetSize(); 4847 uint32_t thread_index; 4848 4849 ts.Printf("<%u threads> ", num_threads); 4850 4851 for (thread_index = 0; 4852 thread_index < num_threads; 4853 ++thread_index) 4854 { 4855 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get(); 4856 4857 if (!thread) 4858 { 4859 ts.Printf("<?> "); 4860 continue; 4861 } 4862 4863 ts.Printf("<0x%4.4llx ", thread->GetID()); 4864 RegisterContext *register_context = thread->GetRegisterContext().get(); 4865 4866 if (register_context) 4867 ts.Printf("[ip 0x%llx] ", register_context->GetPC()); 4868 else 4869 ts.Printf("[ip unknown] "); 4870 4871 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo(); 4872 if (stop_info_sp) 4873 { 4874 const char *stop_desc = stop_info_sp->GetDescription(); 4875 if (stop_desc) 4876 ts.PutCString (stop_desc); 4877 } 4878 ts.Printf(">"); 4879 } 4880 4881 event_explanation = ts.GetData(); 4882 } 4883 } while (0); 4884 4885 if (event_explanation) 4886 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation); 4887 else 4888 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData()); 4889 } 4890 4891 if (discard_on_error && thread_plan_sp) 4892 { 4893 if (log) 4894 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", thread_plan_sp.get()); 4895 thread->DiscardThreadPlansUpToPlan (thread_plan_sp); 4896 thread_plan_sp->SetPrivate (orig_plan_private); 4897 } 4898 else 4899 { 4900 if (log) 4901 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", thread_plan_sp.get()); 4902 } 4903 } 4904 else if (return_value == eExecutionSetupError) 4905 { 4906 if (log) 4907 log->PutCString("Process::RunThreadPlan(): execution set up error."); 4908 4909 if (discard_on_error && thread_plan_sp) 4910 { 4911 thread->DiscardThreadPlansUpToPlan (thread_plan_sp); 4912 thread_plan_sp->SetPrivate (orig_plan_private); 4913 } 4914 } 4915 else 4916 { 4917 if (thread->IsThreadPlanDone (thread_plan_sp.get())) 4918 { 4919 if (log) 4920 log->PutCString("Process::RunThreadPlan(): thread plan is done"); 4921 return_value = eExecutionCompleted; 4922 } 4923 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get())) 4924 { 4925 if (log) 4926 log->PutCString("Process::RunThreadPlan(): thread plan was discarded"); 4927 return_value = eExecutionDiscarded; 4928 } 4929 else 4930 { 4931 if (log) 4932 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course"); 4933 if (discard_on_error && thread_plan_sp) 4934 { 4935 if (log) 4936 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set."); 4937 thread->DiscardThreadPlansUpToPlan (thread_plan_sp); 4938 thread_plan_sp->SetPrivate (orig_plan_private); 4939 } 4940 } 4941 } 4942 4943 // Thread we ran the function in may have gone away because we ran the target 4944 // Check that it's still there, and if it is put it back in the context. Also restore the 4945 // frame in the context if it is still present. 4946 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get(); 4947 if (thread) 4948 { 4949 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id)); 4950 } 4951 4952 // Also restore the current process'es selected frame & thread, since this function calling may 4953 // be done behind the user's back. 4954 4955 if (selected_tid != LLDB_INVALID_THREAD_ID) 4956 { 4957 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid()) 4958 { 4959 // We were able to restore the selected thread, now restore the frame: 4960 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id); 4961 if (old_frame_sp) 4962 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get()); 4963 } 4964 } 4965 } 4966 4967 // If the process exited during the run of the thread plan, notify everyone. 4968 4969 if (event_to_broadcast_sp) 4970 { 4971 if (log) 4972 log->PutCString("Process::RunThreadPlan(): rebroadcasting event."); 4973 BroadcastEvent(event_to_broadcast_sp); 4974 } 4975 4976 return return_value; 4977 } 4978 4979 const char * 4980 Process::ExecutionResultAsCString (ExecutionResults result) 4981 { 4982 const char *result_name; 4983 4984 switch (result) 4985 { 4986 case eExecutionCompleted: 4987 result_name = "eExecutionCompleted"; 4988 break; 4989 case eExecutionDiscarded: 4990 result_name = "eExecutionDiscarded"; 4991 break; 4992 case eExecutionInterrupted: 4993 result_name = "eExecutionInterrupted"; 4994 break; 4995 case eExecutionSetupError: 4996 result_name = "eExecutionSetupError"; 4997 break; 4998 case eExecutionTimedOut: 4999 result_name = "eExecutionTimedOut"; 5000 break; 5001 } 5002 return result_name; 5003 } 5004 5005 void 5006 Process::GetStatus (Stream &strm) 5007 { 5008 const StateType state = GetState(); 5009 if (StateIsStoppedState(state, false)) 5010 { 5011 if (state == eStateExited) 5012 { 5013 int exit_status = GetExitStatus(); 5014 const char *exit_description = GetExitDescription(); 5015 strm.Printf ("Process %llu exited with status = %i (0x%8.8x) %s\n", 5016 GetID(), 5017 exit_status, 5018 exit_status, 5019 exit_description ? exit_description : ""); 5020 } 5021 else 5022 { 5023 if (state == eStateConnected) 5024 strm.Printf ("Connected to remote target.\n"); 5025 else 5026 strm.Printf ("Process %llu %s\n", GetID(), StateAsCString (state)); 5027 } 5028 } 5029 else 5030 { 5031 strm.Printf ("Process %llu is running.\n", GetID()); 5032 } 5033 } 5034 5035 size_t 5036 Process::GetThreadStatus (Stream &strm, 5037 bool only_threads_with_stop_reason, 5038 uint32_t start_frame, 5039 uint32_t num_frames, 5040 uint32_t num_frames_with_source) 5041 { 5042 size_t num_thread_infos_dumped = 0; 5043 5044 Mutex::Locker locker (GetThreadList().GetMutex()); 5045 const size_t num_threads = GetThreadList().GetSize(); 5046 for (uint32_t i = 0; i < num_threads; i++) 5047 { 5048 Thread *thread = GetThreadList().GetThreadAtIndex(i).get(); 5049 if (thread) 5050 { 5051 if (only_threads_with_stop_reason) 5052 { 5053 StopInfoSP stop_info_sp = thread->GetStopInfo(); 5054 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid()) 5055 continue; 5056 } 5057 thread->GetStatus (strm, 5058 start_frame, 5059 num_frames, 5060 num_frames_with_source); 5061 ++num_thread_infos_dumped; 5062 } 5063 } 5064 return num_thread_infos_dumped; 5065 } 5066 5067 void 5068 Process::AddInvalidMemoryRegion (const LoadRange ®ion) 5069 { 5070 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize()); 5071 } 5072 5073 bool 5074 Process::RemoveInvalidMemoryRange (const LoadRange ®ion) 5075 { 5076 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize()); 5077 } 5078 5079 void 5080 Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton) 5081 { 5082 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton)); 5083 } 5084 5085 bool 5086 Process::RunPreResumeActions () 5087 { 5088 bool result = true; 5089 while (!m_pre_resume_actions.empty()) 5090 { 5091 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back(); 5092 m_pre_resume_actions.pop_back(); 5093 bool this_result = action.callback (action.baton); 5094 if (result == true) result = this_result; 5095 } 5096 return result; 5097 } 5098 5099 void 5100 Process::ClearPreResumeActions () 5101 { 5102 m_pre_resume_actions.clear(); 5103 } 5104 5105 void 5106 Process::Flush () 5107 { 5108 m_thread_list.Flush(); 5109 } 5110