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