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