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