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