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