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