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