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