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