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