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