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