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