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