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 error.SetErrorString("executable module does not exist"); 2524 return error; 2525 } 2526 2527 char local_exec_file_path[PATH_MAX]; 2528 char platform_exec_file_path[PATH_MAX]; 2529 exe_module->GetFileSpec().GetPath(local_exec_file_path, 2530 sizeof(local_exec_file_path)); 2531 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, 2532 sizeof(platform_exec_file_path)); 2533 if (FileSystem::Instance().Exists(exe_module->GetFileSpec())) { 2534 // Install anything that might need to be installed prior to launching. 2535 // For host systems, this will do nothing, but if we are connected to a 2536 // remote platform it will install any needed binaries 2537 error = GetTarget().Install(&launch_info); 2538 if (error.Fail()) 2539 return error; 2540 2541 if (PrivateStateThreadIsValid()) 2542 PausePrivateStateThread(); 2543 2544 error = WillLaunch(exe_module); 2545 if (error.Success()) { 2546 const bool restarted = false; 2547 SetPublicState(eStateLaunching, restarted); 2548 m_should_detach = false; 2549 2550 if (m_public_run_lock.TrySetRunning()) { 2551 // Now launch using these arguments. 2552 error = DoLaunch(exe_module, launch_info); 2553 } else { 2554 // This shouldn't happen 2555 error.SetErrorString("failed to acquire process run lock"); 2556 } 2557 2558 if (error.Fail()) { 2559 if (GetID() != LLDB_INVALID_PROCESS_ID) { 2560 SetID(LLDB_INVALID_PROCESS_ID); 2561 const char *error_string = error.AsCString(); 2562 if (error_string == nullptr) 2563 error_string = "launch failed"; 2564 SetExitStatus(-1, error_string); 2565 } 2566 } else { 2567 EventSP event_sp; 2568 2569 // Now wait for the process to launch and return control to us, and then 2570 // call DidLaunch: 2571 StateType state = WaitForProcessStopPrivate(event_sp, seconds(10)); 2572 2573 if (state == eStateInvalid || !event_sp) { 2574 // We were able to launch the process, but we failed to catch the 2575 // initial stop. 2576 error.SetErrorString("failed to catch stop after launch"); 2577 SetExitStatus(0, "failed to catch stop after launch"); 2578 Destroy(false); 2579 } else if (state == eStateStopped || state == eStateCrashed) { 2580 DidLaunch(); 2581 2582 DynamicLoader *dyld = GetDynamicLoader(); 2583 if (dyld) 2584 dyld->DidLaunch(); 2585 2586 GetJITLoaders().DidLaunch(); 2587 2588 SystemRuntime *system_runtime = GetSystemRuntime(); 2589 if (system_runtime) 2590 system_runtime->DidLaunch(); 2591 2592 if (!m_os_up) 2593 LoadOperatingSystemPlugin(false); 2594 2595 // We successfully launched the process and stopped, now it the 2596 // right time to set up signal filters before resuming. 2597 UpdateAutomaticSignalFiltering(); 2598 2599 // Note, the stop event was consumed above, but not handled. This 2600 // was done to give DidLaunch a chance to run. The target is either 2601 // stopped or crashed. Directly set the state. This is done to 2602 // prevent a stop message with a bunch of spurious output on thread 2603 // status, as well as not pop a ProcessIOHandler. 2604 SetPublicState(state, false); 2605 2606 if (PrivateStateThreadIsValid()) 2607 ResumePrivateStateThread(); 2608 else 2609 StartPrivateStateThread(); 2610 2611 // Target was stopped at entry as was intended. Need to notify the 2612 // listeners about it. 2613 if (state == eStateStopped && 2614 launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)) 2615 HandlePrivateEvent(event_sp); 2616 } else if (state == eStateExited) { 2617 // We exited while trying to launch somehow. Don't call DidLaunch 2618 // as that's not likely to work, and return an invalid pid. 2619 HandlePrivateEvent(event_sp); 2620 } 2621 } 2622 } 2623 } else { 2624 error.SetErrorStringWithFormat("file doesn't exist: '%s'", 2625 local_exec_file_path); 2626 } 2627 2628 return error; 2629 } 2630 2631 Status Process::LoadCore() { 2632 Status error = DoLoadCore(); 2633 if (error.Success()) { 2634 ListenerSP listener_sp( 2635 Listener::MakeListener("lldb.process.load_core_listener")); 2636 HijackProcessEvents(listener_sp); 2637 2638 if (PrivateStateThreadIsValid()) 2639 ResumePrivateStateThread(); 2640 else 2641 StartPrivateStateThread(); 2642 2643 DynamicLoader *dyld = GetDynamicLoader(); 2644 if (dyld) 2645 dyld->DidAttach(); 2646 2647 GetJITLoaders().DidAttach(); 2648 2649 SystemRuntime *system_runtime = GetSystemRuntime(); 2650 if (system_runtime) 2651 system_runtime->DidAttach(); 2652 2653 if (!m_os_up) 2654 LoadOperatingSystemPlugin(false); 2655 2656 // We successfully loaded a core file, now pretend we stopped so we can 2657 // show all of the threads in the core file and explore the crashed state. 2658 SetPrivateState(eStateStopped); 2659 2660 // Wait for a stopped event since we just posted one above... 2661 lldb::EventSP event_sp; 2662 StateType state = 2663 WaitForProcessToStop(seconds(10), &event_sp, true, listener_sp); 2664 2665 if (!StateIsStoppedState(state, false)) { 2666 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 2667 if (log) 2668 log->Printf("Process::Halt() failed to stop, state is: %s", 2669 StateAsCString(state)); 2670 error.SetErrorString( 2671 "Did not get stopped event after loading the core file."); 2672 } 2673 RestoreProcessEvents(); 2674 } 2675 return error; 2676 } 2677 2678 DynamicLoader *Process::GetDynamicLoader() { 2679 if (!m_dyld_up) 2680 m_dyld_up.reset(DynamicLoader::FindPlugin(this, nullptr)); 2681 return m_dyld_up.get(); 2682 } 2683 2684 const lldb::DataBufferSP Process::GetAuxvData() { return DataBufferSP(); } 2685 2686 JITLoaderList &Process::GetJITLoaders() { 2687 if (!m_jit_loaders_up) { 2688 m_jit_loaders_up.reset(new JITLoaderList()); 2689 JITLoader::LoadPlugins(this, *m_jit_loaders_up); 2690 } 2691 return *m_jit_loaders_up; 2692 } 2693 2694 SystemRuntime *Process::GetSystemRuntime() { 2695 if (!m_system_runtime_up) 2696 m_system_runtime_up.reset(SystemRuntime::FindPlugin(this)); 2697 return m_system_runtime_up.get(); 2698 } 2699 2700 Process::AttachCompletionHandler::AttachCompletionHandler(Process *process, 2701 uint32_t exec_count) 2702 : NextEventAction(process), m_exec_count(exec_count) { 2703 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 2704 if (log) 2705 log->Printf( 2706 "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32, 2707 __FUNCTION__, static_cast<void *>(process), exec_count); 2708 } 2709 2710 Process::NextEventAction::EventActionResult 2711 Process::AttachCompletionHandler::PerformAction(lldb::EventSP &event_sp) { 2712 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 2713 2714 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get()); 2715 if (log) 2716 log->Printf( 2717 "Process::AttachCompletionHandler::%s called with state %s (%d)", 2718 __FUNCTION__, StateAsCString(state), static_cast<int>(state)); 2719 2720 switch (state) { 2721 case eStateAttaching: 2722 return eEventActionSuccess; 2723 2724 case eStateRunning: 2725 case eStateConnected: 2726 return eEventActionRetry; 2727 2728 case eStateStopped: 2729 case eStateCrashed: 2730 // During attach, prior to sending the eStateStopped event, 2731 // lldb_private::Process subclasses must set the new process ID. 2732 assert(m_process->GetID() != LLDB_INVALID_PROCESS_ID); 2733 // We don't want these events to be reported, so go set the 2734 // ShouldReportStop here: 2735 m_process->GetThreadList().SetShouldReportStop(eVoteNo); 2736 2737 if (m_exec_count > 0) { 2738 --m_exec_count; 2739 2740 if (log) 2741 log->Printf("Process::AttachCompletionHandler::%s state %s: reduced " 2742 "remaining exec count to %" PRIu32 ", requesting resume", 2743 __FUNCTION__, StateAsCString(state), m_exec_count); 2744 2745 RequestResume(); 2746 return eEventActionRetry; 2747 } else { 2748 if (log) 2749 log->Printf("Process::AttachCompletionHandler::%s state %s: no more " 2750 "execs expected to start, continuing with attach", 2751 __FUNCTION__, StateAsCString(state)); 2752 2753 m_process->CompleteAttach(); 2754 return eEventActionSuccess; 2755 } 2756 break; 2757 2758 default: 2759 case eStateExited: 2760 case eStateInvalid: 2761 break; 2762 } 2763 2764 m_exit_string.assign("No valid Process"); 2765 return eEventActionExit; 2766 } 2767 2768 Process::NextEventAction::EventActionResult 2769 Process::AttachCompletionHandler::HandleBeingInterrupted() { 2770 return eEventActionSuccess; 2771 } 2772 2773 const char *Process::AttachCompletionHandler::GetExitString() { 2774 return m_exit_string.c_str(); 2775 } 2776 2777 ListenerSP ProcessAttachInfo::GetListenerForProcess(Debugger &debugger) { 2778 if (m_listener_sp) 2779 return m_listener_sp; 2780 else 2781 return debugger.GetListener(); 2782 } 2783 2784 Status Process::Attach(ProcessAttachInfo &attach_info) { 2785 m_abi_sp.reset(); 2786 m_process_input_reader.reset(); 2787 m_dyld_up.reset(); 2788 m_jit_loaders_up.reset(); 2789 m_system_runtime_up.reset(); 2790 m_os_up.reset(); 2791 2792 lldb::pid_t attach_pid = attach_info.GetProcessID(); 2793 Status error; 2794 if (attach_pid == LLDB_INVALID_PROCESS_ID) { 2795 char process_name[PATH_MAX]; 2796 2797 if (attach_info.GetExecutableFile().GetPath(process_name, 2798 sizeof(process_name))) { 2799 const bool wait_for_launch = attach_info.GetWaitForLaunch(); 2800 2801 if (wait_for_launch) { 2802 error = WillAttachToProcessWithName(process_name, wait_for_launch); 2803 if (error.Success()) { 2804 if (m_public_run_lock.TrySetRunning()) { 2805 m_should_detach = true; 2806 const bool restarted = false; 2807 SetPublicState(eStateAttaching, restarted); 2808 // Now attach using these arguments. 2809 error = DoAttachToProcessWithName(process_name, attach_info); 2810 } else { 2811 // This shouldn't happen 2812 error.SetErrorString("failed to acquire process run lock"); 2813 } 2814 2815 if (error.Fail()) { 2816 if (GetID() != LLDB_INVALID_PROCESS_ID) { 2817 SetID(LLDB_INVALID_PROCESS_ID); 2818 if (error.AsCString() == nullptr) 2819 error.SetErrorString("attach failed"); 2820 2821 SetExitStatus(-1, error.AsCString()); 2822 } 2823 } else { 2824 SetNextEventAction(new Process::AttachCompletionHandler( 2825 this, attach_info.GetResumeCount())); 2826 StartPrivateStateThread(); 2827 } 2828 return error; 2829 } 2830 } else { 2831 ProcessInstanceInfoList process_infos; 2832 PlatformSP platform_sp(GetTarget().GetPlatform()); 2833 2834 if (platform_sp) { 2835 ProcessInstanceInfoMatch match_info; 2836 match_info.GetProcessInfo() = attach_info; 2837 match_info.SetNameMatchType(NameMatch::Equals); 2838 platform_sp->FindProcesses(match_info, process_infos); 2839 const uint32_t num_matches = process_infos.GetSize(); 2840 if (num_matches == 1) { 2841 attach_pid = process_infos.GetProcessIDAtIndex(0); 2842 // Fall through and attach using the above process ID 2843 } else { 2844 match_info.GetProcessInfo().GetExecutableFile().GetPath( 2845 process_name, sizeof(process_name)); 2846 if (num_matches > 1) { 2847 StreamString s; 2848 ProcessInstanceInfo::DumpTableHeader(s, true, false); 2849 for (size_t i = 0; i < num_matches; i++) { 2850 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow( 2851 s, platform_sp->GetUserIDResolver(), true, false); 2852 } 2853 error.SetErrorStringWithFormat( 2854 "more than one process named %s:\n%s", process_name, 2855 s.GetData()); 2856 } else 2857 error.SetErrorStringWithFormat( 2858 "could not find a process named %s", process_name); 2859 } 2860 } else { 2861 error.SetErrorString( 2862 "invalid platform, can't find processes by name"); 2863 return error; 2864 } 2865 } 2866 } else { 2867 error.SetErrorString("invalid process name"); 2868 } 2869 } 2870 2871 if (attach_pid != LLDB_INVALID_PROCESS_ID) { 2872 error = WillAttachToProcessWithID(attach_pid); 2873 if (error.Success()) { 2874 2875 if (m_public_run_lock.TrySetRunning()) { 2876 // Now attach using these arguments. 2877 m_should_detach = true; 2878 const bool restarted = false; 2879 SetPublicState(eStateAttaching, restarted); 2880 error = DoAttachToProcessWithID(attach_pid, attach_info); 2881 } else { 2882 // This shouldn't happen 2883 error.SetErrorString("failed to acquire process run lock"); 2884 } 2885 2886 if (error.Success()) { 2887 SetNextEventAction(new Process::AttachCompletionHandler( 2888 this, attach_info.GetResumeCount())); 2889 StartPrivateStateThread(); 2890 } else { 2891 if (GetID() != LLDB_INVALID_PROCESS_ID) 2892 SetID(LLDB_INVALID_PROCESS_ID); 2893 2894 const char *error_string = error.AsCString(); 2895 if (error_string == nullptr) 2896 error_string = "attach failed"; 2897 2898 SetExitStatus(-1, error_string); 2899 } 2900 } 2901 } 2902 return error; 2903 } 2904 2905 void Process::CompleteAttach() { 2906 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | 2907 LIBLLDB_LOG_TARGET)); 2908 if (log) 2909 log->Printf("Process::%s()", __FUNCTION__); 2910 2911 // Let the process subclass figure out at much as it can about the process 2912 // before we go looking for a dynamic loader plug-in. 2913 ArchSpec process_arch; 2914 DidAttach(process_arch); 2915 2916 if (process_arch.IsValid()) { 2917 GetTarget().SetArchitecture(process_arch); 2918 if (log) { 2919 const char *triple_str = process_arch.GetTriple().getTriple().c_str(); 2920 log->Printf("Process::%s replacing process architecture with DidAttach() " 2921 "architecture: %s", 2922 __FUNCTION__, triple_str ? triple_str : "<null>"); 2923 } 2924 } 2925 2926 // We just attached. If we have a platform, ask it for the process 2927 // architecture, and if it isn't the same as the one we've already set, 2928 // switch architectures. 2929 PlatformSP platform_sp(GetTarget().GetPlatform()); 2930 assert(platform_sp); 2931 if (platform_sp) { 2932 const ArchSpec &target_arch = GetTarget().GetArchitecture(); 2933 if (target_arch.IsValid() && 2934 !platform_sp->IsCompatibleArchitecture(target_arch, false, nullptr)) { 2935 ArchSpec platform_arch; 2936 platform_sp = 2937 platform_sp->GetPlatformForArchitecture(target_arch, &platform_arch); 2938 if (platform_sp) { 2939 GetTarget().SetPlatform(platform_sp); 2940 GetTarget().SetArchitecture(platform_arch); 2941 if (log) 2942 log->Printf("Process::%s switching platform to %s and architecture " 2943 "to %s based on info from attach", 2944 __FUNCTION__, platform_sp->GetName().AsCString(""), 2945 platform_arch.GetTriple().getTriple().c_str()); 2946 } 2947 } else if (!process_arch.IsValid()) { 2948 ProcessInstanceInfo process_info; 2949 GetProcessInfo(process_info); 2950 const ArchSpec &process_arch = process_info.GetArchitecture(); 2951 if (process_arch.IsValid() && 2952 !GetTarget().GetArchitecture().IsExactMatch(process_arch)) { 2953 GetTarget().SetArchitecture(process_arch); 2954 if (log) 2955 log->Printf("Process::%s switching architecture to %s based on info " 2956 "the platform retrieved for pid %" PRIu64, 2957 __FUNCTION__, 2958 process_arch.GetTriple().getTriple().c_str(), GetID()); 2959 } 2960 } 2961 } 2962 2963 // We have completed the attach, now it is time to find the dynamic loader 2964 // plug-in 2965 DynamicLoader *dyld = GetDynamicLoader(); 2966 if (dyld) { 2967 dyld->DidAttach(); 2968 if (log) { 2969 ModuleSP exe_module_sp = GetTarget().GetExecutableModule(); 2970 log->Printf("Process::%s after DynamicLoader::DidAttach(), target " 2971 "executable is %s (using %s plugin)", 2972 __FUNCTION__, 2973 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str() 2974 : "<none>", 2975 dyld->GetPluginName().AsCString("<unnamed>")); 2976 } 2977 } 2978 2979 GetJITLoaders().DidAttach(); 2980 2981 SystemRuntime *system_runtime = GetSystemRuntime(); 2982 if (system_runtime) { 2983 system_runtime->DidAttach(); 2984 if (log) { 2985 ModuleSP exe_module_sp = GetTarget().GetExecutableModule(); 2986 log->Printf("Process::%s after SystemRuntime::DidAttach(), target " 2987 "executable is %s (using %s plugin)", 2988 __FUNCTION__, 2989 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str() 2990 : "<none>", 2991 system_runtime->GetPluginName().AsCString("<unnamed>")); 2992 } 2993 } 2994 2995 if (!m_os_up) 2996 LoadOperatingSystemPlugin(false); 2997 // Figure out which one is the executable, and set that in our target: 2998 const ModuleList &target_modules = GetTarget().GetImages(); 2999 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex()); 3000 size_t num_modules = target_modules.GetSize(); 3001 ModuleSP new_executable_module_sp; 3002 3003 for (size_t i = 0; i < num_modules; i++) { 3004 ModuleSP module_sp(target_modules.GetModuleAtIndexUnlocked(i)); 3005 if (module_sp && module_sp->IsExecutable()) { 3006 if (GetTarget().GetExecutableModulePointer() != module_sp.get()) 3007 new_executable_module_sp = module_sp; 3008 break; 3009 } 3010 } 3011 if (new_executable_module_sp) { 3012 GetTarget().SetExecutableModule(new_executable_module_sp, 3013 eLoadDependentsNo); 3014 if (log) { 3015 ModuleSP exe_module_sp = GetTarget().GetExecutableModule(); 3016 log->Printf( 3017 "Process::%s after looping through modules, target executable is %s", 3018 __FUNCTION__, 3019 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str() 3020 : "<none>"); 3021 } 3022 } 3023 } 3024 3025 Status Process::ConnectRemote(Stream *strm, llvm::StringRef remote_url) { 3026 m_abi_sp.reset(); 3027 m_process_input_reader.reset(); 3028 3029 // Find the process and its architecture. Make sure it matches the 3030 // architecture of the current Target, and if not adjust it. 3031 3032 Status error(DoConnectRemote(strm, remote_url)); 3033 if (error.Success()) { 3034 if (GetID() != LLDB_INVALID_PROCESS_ID) { 3035 EventSP event_sp; 3036 StateType state = WaitForProcessStopPrivate(event_sp, llvm::None); 3037 3038 if (state == eStateStopped || state == eStateCrashed) { 3039 // If we attached and actually have a process on the other end, then 3040 // this ended up being the equivalent of an attach. 3041 CompleteAttach(); 3042 3043 // This delays passing the stopped event to listeners till 3044 // CompleteAttach gets a chance to complete... 3045 HandlePrivateEvent(event_sp); 3046 } 3047 } 3048 3049 if (PrivateStateThreadIsValid()) 3050 ResumePrivateStateThread(); 3051 else 3052 StartPrivateStateThread(); 3053 } 3054 return error; 3055 } 3056 3057 Status Process::PrivateResume() { 3058 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | 3059 LIBLLDB_LOG_STEP)); 3060 if (log) 3061 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s " 3062 "private state: %s", 3063 m_mod_id.GetStopID(), StateAsCString(m_public_state.GetValue()), 3064 StateAsCString(m_private_state.GetValue())); 3065 3066 // If signals handing status changed we might want to update our signal 3067 // filters before resuming. 3068 UpdateAutomaticSignalFiltering(); 3069 3070 Status error(WillResume()); 3071 // Tell the process it is about to resume before the thread list 3072 if (error.Success()) { 3073 // Now let the thread list know we are about to resume so it can let all of 3074 // our threads know that they are about to be resumed. Threads will each be 3075 // called with Thread::WillResume(StateType) where StateType contains the 3076 // state that they are supposed to have when the process is resumed 3077 // (suspended/running/stepping). Threads should also check their resume 3078 // signal in lldb::Thread::GetResumeSignal() to see if they are supposed to 3079 // start back up with a signal. 3080 if (m_thread_list.WillResume()) { 3081 // Last thing, do the PreResumeActions. 3082 if (!RunPreResumeActions()) { 3083 error.SetErrorStringWithFormat( 3084 "Process::PrivateResume PreResumeActions failed, not resuming."); 3085 } else { 3086 m_mod_id.BumpResumeID(); 3087 error = DoResume(); 3088 if (error.Success()) { 3089 DidResume(); 3090 m_thread_list.DidResume(); 3091 if (log) 3092 log->Printf("Process thinks the process has resumed."); 3093 } else { 3094 if (log) 3095 log->Printf( 3096 "Process::PrivateResume() DoResume failed."); 3097 return error; 3098 } 3099 } 3100 } else { 3101 // Somebody wanted to run without running (e.g. we were faking a step 3102 // from one frame of a set of inlined frames that share the same PC to 3103 // another.) So generate a continue & a stopped event, and let the world 3104 // handle them. 3105 if (log) 3106 log->Printf( 3107 "Process::PrivateResume() asked to simulate a start & stop."); 3108 3109 SetPrivateState(eStateRunning); 3110 SetPrivateState(eStateStopped); 3111 } 3112 } else if (log) 3113 log->Printf("Process::PrivateResume() got an error \"%s\".", 3114 error.AsCString("<unknown error>")); 3115 return error; 3116 } 3117 3118 Status Process::Halt(bool clear_thread_plans, bool use_run_lock) { 3119 if (!StateIsRunningState(m_public_state.GetValue())) 3120 return Status("Process is not running."); 3121 3122 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if in 3123 // case it was already set and some thread plan logic calls halt on its own. 3124 m_clear_thread_plans_on_stop |= clear_thread_plans; 3125 3126 ListenerSP halt_listener_sp( 3127 Listener::MakeListener("lldb.process.halt_listener")); 3128 HijackProcessEvents(halt_listener_sp); 3129 3130 EventSP event_sp; 3131 3132 SendAsyncInterrupt(); 3133 3134 if (m_public_state.GetValue() == eStateAttaching) { 3135 // Don't hijack and eat the eStateExited as the code that was doing the 3136 // attach will be waiting for this event... 3137 RestoreProcessEvents(); 3138 SetExitStatus(SIGKILL, "Cancelled async attach."); 3139 Destroy(false); 3140 return Status(); 3141 } 3142 3143 // Wait for 10 second for the process to stop. 3144 StateType state = WaitForProcessToStop( 3145 seconds(10), &event_sp, true, halt_listener_sp, nullptr, use_run_lock); 3146 RestoreProcessEvents(); 3147 3148 if (state == eStateInvalid || !event_sp) { 3149 // We timed out and didn't get a stop event... 3150 return Status("Halt timed out. State = %s", StateAsCString(GetState())); 3151 } 3152 3153 BroadcastEvent(event_sp); 3154 3155 return Status(); 3156 } 3157 3158 Status Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp) { 3159 Status error; 3160 3161 // Check both the public & private states here. If we're hung evaluating an 3162 // expression, for instance, then the public state will be stopped, but we 3163 // still need to interrupt. 3164 if (m_public_state.GetValue() == eStateRunning || 3165 m_private_state.GetValue() == eStateRunning) { 3166 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 3167 if (log) 3168 log->Printf("Process::%s() About to stop.", __FUNCTION__); 3169 3170 ListenerSP listener_sp( 3171 Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack")); 3172 HijackProcessEvents(listener_sp); 3173 3174 SendAsyncInterrupt(); 3175 3176 // Consume the interrupt event. 3177 StateType state = 3178 WaitForProcessToStop(seconds(10), &exit_event_sp, true, listener_sp); 3179 3180 RestoreProcessEvents(); 3181 3182 // If the process exited while we were waiting for it to stop, put the 3183 // exited event into the shared pointer passed in and return. Our caller 3184 // doesn't need to do anything else, since they don't have a process 3185 // anymore... 3186 3187 if (state == eStateExited || m_private_state.GetValue() == eStateExited) { 3188 if (log) 3189 log->Printf("Process::%s() Process exited while waiting to stop.", 3190 __FUNCTION__); 3191 return error; 3192 } else 3193 exit_event_sp.reset(); // It is ok to consume any non-exit stop events 3194 3195 if (state != eStateStopped) { 3196 if (log) 3197 log->Printf("Process::%s() failed to stop, state is: %s", __FUNCTION__, 3198 StateAsCString(state)); 3199 // If we really couldn't stop the process then we should just error out 3200 // here, but if the lower levels just bobbled sending the event and we 3201 // really are stopped, then continue on. 3202 StateType private_state = m_private_state.GetValue(); 3203 if (private_state != eStateStopped) { 3204 return Status( 3205 "Attempt to stop the target in order to detach timed out. " 3206 "State = %s", 3207 StateAsCString(GetState())); 3208 } 3209 } 3210 } 3211 return error; 3212 } 3213 3214 Status Process::Detach(bool keep_stopped) { 3215 EventSP exit_event_sp; 3216 Status error; 3217 m_destroy_in_process = true; 3218 3219 error = WillDetach(); 3220 3221 if (error.Success()) { 3222 if (DetachRequiresHalt()) { 3223 error = StopForDestroyOrDetach(exit_event_sp); 3224 if (!error.Success()) { 3225 m_destroy_in_process = false; 3226 return error; 3227 } else if (exit_event_sp) { 3228 // We shouldn't need to do anything else here. There's no process left 3229 // to detach from... 3230 StopPrivateStateThread(); 3231 m_destroy_in_process = false; 3232 return error; 3233 } 3234 } 3235 3236 m_thread_list.DiscardThreadPlans(); 3237 DisableAllBreakpointSites(); 3238 3239 error = DoDetach(keep_stopped); 3240 if (error.Success()) { 3241 DidDetach(); 3242 StopPrivateStateThread(); 3243 } else { 3244 return error; 3245 } 3246 } 3247 m_destroy_in_process = false; 3248 3249 // If we exited when we were waiting for a process to stop, then forward the 3250 // event here so we don't lose the event 3251 if (exit_event_sp) { 3252 // Directly broadcast our exited event because we shut down our private 3253 // state thread above 3254 BroadcastEvent(exit_event_sp); 3255 } 3256 3257 // If we have been interrupted (to kill us) in the middle of running, we may 3258 // not end up propagating the last events through the event system, in which 3259 // case we might strand the write lock. Unlock it here so when we do to tear 3260 // down the process we don't get an error destroying the lock. 3261 3262 m_public_run_lock.SetStopped(); 3263 return error; 3264 } 3265 3266 Status Process::Destroy(bool force_kill) { 3267 3268 // Tell ourselves we are in the process of destroying the process, so that we 3269 // don't do any unnecessary work that might hinder the destruction. Remember 3270 // to set this back to false when we are done. That way if the attempt 3271 // failed and the process stays around for some reason it won't be in a 3272 // confused state. 3273 3274 if (force_kill) 3275 m_should_detach = false; 3276 3277 if (GetShouldDetach()) { 3278 // FIXME: This will have to be a process setting: 3279 bool keep_stopped = false; 3280 Detach(keep_stopped); 3281 } 3282 3283 m_destroy_in_process = true; 3284 3285 Status error(WillDestroy()); 3286 if (error.Success()) { 3287 EventSP exit_event_sp; 3288 if (DestroyRequiresHalt()) { 3289 error = StopForDestroyOrDetach(exit_event_sp); 3290 } 3291 3292 if (m_public_state.GetValue() != eStateRunning) { 3293 // Ditch all thread plans, and remove all our breakpoints: in case we 3294 // have to restart the target to kill it, we don't want it hitting a 3295 // breakpoint... Only do this if we've stopped, however, since if we 3296 // didn't manage to halt it above, then we're not going to have much luck 3297 // doing this now. 3298 m_thread_list.DiscardThreadPlans(); 3299 DisableAllBreakpointSites(); 3300 } 3301 3302 error = DoDestroy(); 3303 if (error.Success()) { 3304 DidDestroy(); 3305 StopPrivateStateThread(); 3306 } 3307 m_stdio_communication.Disconnect(); 3308 m_stdio_communication.StopReadThread(); 3309 m_stdin_forward = false; 3310 3311 if (m_process_input_reader) { 3312 m_process_input_reader->SetIsDone(true); 3313 m_process_input_reader->Cancel(); 3314 m_process_input_reader.reset(); 3315 } 3316 3317 // If we exited when we were waiting for a process to stop, then forward 3318 // the event here so we don't lose the event 3319 if (exit_event_sp) { 3320 // Directly broadcast our exited event because we shut down our private 3321 // state thread above 3322 BroadcastEvent(exit_event_sp); 3323 } 3324 3325 // If we have been interrupted (to kill us) in the middle of running, we 3326 // may not end up propagating the last events through the event system, in 3327 // which case we might strand the write lock. Unlock it here so when we do 3328 // to tear down the process we don't get an error destroying the lock. 3329 m_public_run_lock.SetStopped(); 3330 } 3331 3332 m_destroy_in_process = false; 3333 3334 return error; 3335 } 3336 3337 Status Process::Signal(int signal) { 3338 Status error(WillSignal()); 3339 if (error.Success()) { 3340 error = DoSignal(signal); 3341 if (error.Success()) 3342 DidSignal(); 3343 } 3344 return error; 3345 } 3346 3347 void Process::SetUnixSignals(UnixSignalsSP &&signals_sp) { 3348 assert(signals_sp && "null signals_sp"); 3349 m_unix_signals_sp = signals_sp; 3350 } 3351 3352 const lldb::UnixSignalsSP &Process::GetUnixSignals() { 3353 assert(m_unix_signals_sp && "null m_unix_signals_sp"); 3354 return m_unix_signals_sp; 3355 } 3356 3357 lldb::ByteOrder Process::GetByteOrder() const { 3358 return GetTarget().GetArchitecture().GetByteOrder(); 3359 } 3360 3361 uint32_t Process::GetAddressByteSize() const { 3362 return GetTarget().GetArchitecture().GetAddressByteSize(); 3363 } 3364 3365 bool Process::ShouldBroadcastEvent(Event *event_ptr) { 3366 const StateType state = 3367 Process::ProcessEventData::GetStateFromEvent(event_ptr); 3368 bool return_value = true; 3369 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | 3370 LIBLLDB_LOG_PROCESS)); 3371 3372 switch (state) { 3373 case eStateDetached: 3374 case eStateExited: 3375 case eStateUnloaded: 3376 m_stdio_communication.SynchronizeWithReadThread(); 3377 m_stdio_communication.Disconnect(); 3378 m_stdio_communication.StopReadThread(); 3379 m_stdin_forward = false; 3380 3381 LLVM_FALLTHROUGH; 3382 case eStateConnected: 3383 case eStateAttaching: 3384 case eStateLaunching: 3385 // These events indicate changes in the state of the debugging session, 3386 // always report them. 3387 return_value = true; 3388 break; 3389 case eStateInvalid: 3390 // We stopped for no apparent reason, don't report it. 3391 return_value = false; 3392 break; 3393 case eStateRunning: 3394 case eStateStepping: 3395 // If we've started the target running, we handle the cases where we are 3396 // already running and where there is a transition from stopped to running 3397 // differently. running -> running: Automatically suppress extra running 3398 // events stopped -> running: Report except when there is one or more no 3399 // votes 3400 // and no yes votes. 3401 SynchronouslyNotifyStateChanged(state); 3402 if (m_force_next_event_delivery) 3403 return_value = true; 3404 else { 3405 switch (m_last_broadcast_state) { 3406 case eStateRunning: 3407 case eStateStepping: 3408 // We always suppress multiple runnings with no PUBLIC stop in between. 3409 return_value = false; 3410 break; 3411 default: 3412 // TODO: make this work correctly. For now always report 3413 // run if we aren't running so we don't miss any running events. If I 3414 // run the lldb/test/thread/a.out file and break at main.cpp:58, run 3415 // and hit the breakpoints on multiple threads, then somehow during the 3416 // stepping over of all breakpoints no run gets reported. 3417 3418 // This is a transition from stop to run. 3419 switch (m_thread_list.ShouldReportRun(event_ptr)) { 3420 case eVoteYes: 3421 case eVoteNoOpinion: 3422 return_value = true; 3423 break; 3424 case eVoteNo: 3425 return_value = false; 3426 break; 3427 } 3428 break; 3429 } 3430 } 3431 break; 3432 case eStateStopped: 3433 case eStateCrashed: 3434 case eStateSuspended: 3435 // We've stopped. First see if we're going to restart the target. If we 3436 // are going to stop, then we always broadcast the event. If we aren't 3437 // going to stop, let the thread plans decide if we're going to report this 3438 // event. If no thread has an opinion, we don't report it. 3439 3440 m_stdio_communication.SynchronizeWithReadThread(); 3441 RefreshStateAfterStop(); 3442 if (ProcessEventData::GetInterruptedFromEvent(event_ptr)) { 3443 if (log) 3444 log->Printf("Process::ShouldBroadcastEvent (%p) stopped due to an " 3445 "interrupt, state: %s", 3446 static_cast<void *>(event_ptr), StateAsCString(state)); 3447 // Even though we know we are going to stop, we should let the threads 3448 // have a look at the stop, so they can properly set their state. 3449 m_thread_list.ShouldStop(event_ptr); 3450 return_value = true; 3451 } else { 3452 bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr); 3453 bool should_resume = false; 3454 3455 // It makes no sense to ask "ShouldStop" if we've already been 3456 // restarted... Asking the thread list is also not likely to go well, 3457 // since we are running again. So in that case just report the event. 3458 3459 if (!was_restarted) 3460 should_resume = !m_thread_list.ShouldStop(event_ptr); 3461 3462 if (was_restarted || should_resume || m_resume_requested) { 3463 Vote stop_vote = m_thread_list.ShouldReportStop(event_ptr); 3464 if (log) 3465 log->Printf("Process::ShouldBroadcastEvent: should_resume: %i state: " 3466 "%s was_restarted: %i stop_vote: %d.", 3467 should_resume, StateAsCString(state), was_restarted, 3468 stop_vote); 3469 3470 switch (stop_vote) { 3471 case eVoteYes: 3472 return_value = true; 3473 break; 3474 case eVoteNoOpinion: 3475 case eVoteNo: 3476 return_value = false; 3477 break; 3478 } 3479 3480 if (!was_restarted) { 3481 if (log) 3482 log->Printf("Process::ShouldBroadcastEvent (%p) Restarting process " 3483 "from state: %s", 3484 static_cast<void *>(event_ptr), StateAsCString(state)); 3485 ProcessEventData::SetRestartedInEvent(event_ptr, true); 3486 PrivateResume(); 3487 } 3488 } else { 3489 return_value = true; 3490 SynchronouslyNotifyStateChanged(state); 3491 } 3492 } 3493 break; 3494 } 3495 3496 // Forcing the next event delivery is a one shot deal. So reset it here. 3497 m_force_next_event_delivery = false; 3498 3499 // We do some coalescing of events (for instance two consecutive running 3500 // events get coalesced.) But we only coalesce against events we actually 3501 // broadcast. So we use m_last_broadcast_state to track that. NB - you 3502 // can't use "m_public_state.GetValue()" for that purpose, as was originally 3503 // done, because the PublicState reflects the last event pulled off the 3504 // queue, and there may be several events stacked up on the queue unserviced. 3505 // So the PublicState may not reflect the last broadcasted event yet. 3506 // m_last_broadcast_state gets updated here. 3507 3508 if (return_value) 3509 m_last_broadcast_state = state; 3510 3511 if (log) 3512 log->Printf("Process::ShouldBroadcastEvent (%p) => new state: %s, last " 3513 "broadcast state: %s - %s", 3514 static_cast<void *>(event_ptr), StateAsCString(state), 3515 StateAsCString(m_last_broadcast_state), 3516 return_value ? "YES" : "NO"); 3517 return return_value; 3518 } 3519 3520 bool Process::StartPrivateStateThread(bool is_secondary_thread) { 3521 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS)); 3522 3523 bool already_running = PrivateStateThreadIsValid(); 3524 if (log) 3525 log->Printf("Process::%s()%s ", __FUNCTION__, 3526 already_running ? " already running" 3527 : " starting private state thread"); 3528 3529 if (!is_secondary_thread && already_running) 3530 return true; 3531 3532 // Create a thread that watches our internal state and controls which events 3533 // make it to clients (into the DCProcess event queue). 3534 char thread_name[1024]; 3535 uint32_t max_len = llvm::get_max_thread_name_length(); 3536 if (max_len > 0 && max_len <= 30) { 3537 // On platforms with abbreviated thread name lengths, choose thread names 3538 // that fit within the limit. 3539 if (already_running) 3540 snprintf(thread_name, sizeof(thread_name), "intern-state-OV"); 3541 else 3542 snprintf(thread_name, sizeof(thread_name), "intern-state"); 3543 } else { 3544 if (already_running) 3545 snprintf(thread_name, sizeof(thread_name), 3546 "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", 3547 GetID()); 3548 else 3549 snprintf(thread_name, sizeof(thread_name), 3550 "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID()); 3551 } 3552 3553 // Create the private state thread, and start it running. 3554 PrivateStateThreadArgs *args_ptr = 3555 new PrivateStateThreadArgs(this, is_secondary_thread); 3556 m_private_state_thread = 3557 ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread, 3558 (void *)args_ptr, nullptr, 8 * 1024 * 1024); 3559 if (m_private_state_thread.IsJoinable()) { 3560 ResumePrivateStateThread(); 3561 return true; 3562 } else 3563 return false; 3564 } 3565 3566 void Process::PausePrivateStateThread() { 3567 ControlPrivateStateThread(eBroadcastInternalStateControlPause); 3568 } 3569 3570 void Process::ResumePrivateStateThread() { 3571 ControlPrivateStateThread(eBroadcastInternalStateControlResume); 3572 } 3573 3574 void Process::StopPrivateStateThread() { 3575 if (m_private_state_thread.IsJoinable()) 3576 ControlPrivateStateThread(eBroadcastInternalStateControlStop); 3577 else { 3578 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 3579 if (log) 3580 log->Printf( 3581 "Went to stop the private state thread, but it was already invalid."); 3582 } 3583 } 3584 3585 void Process::ControlPrivateStateThread(uint32_t signal) { 3586 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 3587 3588 assert(signal == eBroadcastInternalStateControlStop || 3589 signal == eBroadcastInternalStateControlPause || 3590 signal == eBroadcastInternalStateControlResume); 3591 3592 if (log) 3593 log->Printf("Process::%s (signal = %d)", __FUNCTION__, signal); 3594 3595 // Signal the private state thread 3596 if (m_private_state_thread.IsJoinable()) { 3597 // Broadcast the event. 3598 // It is important to do this outside of the if below, because it's 3599 // possible that the thread state is invalid but that the thread is waiting 3600 // on a control event instead of simply being on its way out (this should 3601 // not happen, but it apparently can). 3602 if (log) 3603 log->Printf("Sending control event of type: %d.", signal); 3604 std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt()); 3605 m_private_state_control_broadcaster.BroadcastEvent(signal, 3606 event_receipt_sp); 3607 3608 // Wait for the event receipt or for the private state thread to exit 3609 bool receipt_received = false; 3610 if (PrivateStateThreadIsValid()) { 3611 while (!receipt_received) { 3612 // Check for a receipt for 2 seconds and then check if the private 3613 // state thread is still around. 3614 receipt_received = 3615 event_receipt_sp->WaitForEventReceived(std::chrono::seconds(2)); 3616 if (!receipt_received) { 3617 // Check if the private state thread is still around. If it isn't 3618 // then we are done waiting 3619 if (!PrivateStateThreadIsValid()) 3620 break; // Private state thread exited or is exiting, we are done 3621 } 3622 } 3623 } 3624 3625 if (signal == eBroadcastInternalStateControlStop) { 3626 thread_result_t result = NULL; 3627 m_private_state_thread.Join(&result); 3628 m_private_state_thread.Reset(); 3629 } 3630 } else { 3631 if (log) 3632 log->Printf( 3633 "Private state thread already dead, no need to signal it to stop."); 3634 } 3635 } 3636 3637 void Process::SendAsyncInterrupt() { 3638 if (PrivateStateThreadIsValid()) 3639 m_private_state_broadcaster.BroadcastEvent(Process::eBroadcastBitInterrupt, 3640 nullptr); 3641 else 3642 BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr); 3643 } 3644 3645 void Process::HandlePrivateEvent(EventSP &event_sp) { 3646 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 3647 m_resume_requested = false; 3648 3649 const StateType new_state = 3650 Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 3651 3652 // First check to see if anybody wants a shot at this event: 3653 if (m_next_event_action_up) { 3654 NextEventAction::EventActionResult action_result = 3655 m_next_event_action_up->PerformAction(event_sp); 3656 if (log) 3657 log->Printf("Ran next event action, result was %d.", action_result); 3658 3659 switch (action_result) { 3660 case NextEventAction::eEventActionSuccess: 3661 SetNextEventAction(nullptr); 3662 break; 3663 3664 case NextEventAction::eEventActionRetry: 3665 break; 3666 3667 case NextEventAction::eEventActionExit: 3668 // Handle Exiting Here. If we already got an exited event, we should 3669 // just propagate it. Otherwise, swallow this event, and set our state 3670 // to exit so the next event will kill us. 3671 if (new_state != eStateExited) { 3672 // FIXME: should cons up an exited event, and discard this one. 3673 SetExitStatus(0, m_next_event_action_up->GetExitString()); 3674 SetNextEventAction(nullptr); 3675 return; 3676 } 3677 SetNextEventAction(nullptr); 3678 break; 3679 } 3680 } 3681 3682 // See if we should broadcast this state to external clients? 3683 const bool should_broadcast = ShouldBroadcastEvent(event_sp.get()); 3684 3685 if (should_broadcast) { 3686 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged); 3687 if (log) { 3688 log->Printf("Process::%s (pid = %" PRIu64 3689 ") broadcasting new state %s (old state %s) to %s", 3690 __FUNCTION__, GetID(), StateAsCString(new_state), 3691 StateAsCString(GetState()), 3692 is_hijacked ? "hijacked" : "public"); 3693 } 3694 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get()); 3695 if (StateIsRunningState(new_state)) { 3696 // Only push the input handler if we aren't fowarding events, as this 3697 // means the curses GUI is in use... Or don't push it if we are launching 3698 // since it will come up stopped. 3699 if (!GetTarget().GetDebugger().IsForwardingEvents() && 3700 new_state != eStateLaunching && new_state != eStateAttaching) { 3701 PushProcessIOHandler(); 3702 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue() + 1, 3703 eBroadcastAlways); 3704 if (log) 3705 log->Printf("Process::%s updated m_iohandler_sync to %d", 3706 __FUNCTION__, m_iohandler_sync.GetValue()); 3707 } 3708 } else if (StateIsStoppedState(new_state, false)) { 3709 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) { 3710 // If the lldb_private::Debugger is handling the events, we don't want 3711 // to pop the process IOHandler here, we want to do it when we receive 3712 // the stopped event so we can carefully control when the process 3713 // IOHandler is popped because when we stop we want to display some 3714 // text stating how and why we stopped, then maybe some 3715 // process/thread/frame info, and then we want the "(lldb) " prompt to 3716 // show up. If we pop the process IOHandler here, then we will cause 3717 // the command interpreter to become the top IOHandler after the 3718 // process pops off and it will update its prompt right away... See the 3719 // Debugger.cpp file where it calls the function as 3720 // "process_sp->PopProcessIOHandler()" to see where I am talking about. 3721 // Otherwise we end up getting overlapping "(lldb) " prompts and 3722 // garbled output. 3723 // 3724 // If we aren't handling the events in the debugger (which is indicated 3725 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or 3726 // we are hijacked, then we always pop the process IO handler manually. 3727 // Hijacking happens when the internal process state thread is running 3728 // thread plans, or when commands want to run in synchronous mode and 3729 // they call "process->WaitForProcessToStop()". An example of something 3730 // that will hijack the events is a simple expression: 3731 // 3732 // (lldb) expr (int)puts("hello") 3733 // 3734 // This will cause the internal process state thread to resume and halt 3735 // the process (and _it_ will hijack the eBroadcastBitStateChanged 3736 // events) and we do need the IO handler to be pushed and popped 3737 // correctly. 3738 3739 if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents()) 3740 PopProcessIOHandler(); 3741 } 3742 } 3743 3744 BroadcastEvent(event_sp); 3745 } else { 3746 if (log) { 3747 log->Printf( 3748 "Process::%s (pid = %" PRIu64 3749 ") suppressing state %s (old state %s): should_broadcast == false", 3750 __FUNCTION__, GetID(), StateAsCString(new_state), 3751 StateAsCString(GetState())); 3752 } 3753 } 3754 } 3755 3756 Status Process::HaltPrivate() { 3757 EventSP event_sp; 3758 Status error(WillHalt()); 3759 if (error.Fail()) 3760 return error; 3761 3762 // Ask the process subclass to actually halt our process 3763 bool caused_stop; 3764 error = DoHalt(caused_stop); 3765 3766 DidHalt(); 3767 return error; 3768 } 3769 3770 thread_result_t Process::PrivateStateThread(void *arg) { 3771 std::unique_ptr<PrivateStateThreadArgs> args_up( 3772 static_cast<PrivateStateThreadArgs *>(arg)); 3773 thread_result_t result = 3774 args_up->process->RunPrivateStateThread(args_up->is_secondary_thread); 3775 return result; 3776 } 3777 3778 thread_result_t Process::RunPrivateStateThread(bool is_secondary_thread) { 3779 bool control_only = true; 3780 3781 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 3782 if (log) 3783 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...", 3784 __FUNCTION__, static_cast<void *>(this), GetID()); 3785 3786 bool exit_now = false; 3787 bool interrupt_requested = false; 3788 while (!exit_now) { 3789 EventSP event_sp; 3790 GetEventsPrivate(event_sp, llvm::None, control_only); 3791 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) { 3792 if (log) 3793 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 3794 ") got a control event: %d", 3795 __FUNCTION__, static_cast<void *>(this), GetID(), 3796 event_sp->GetType()); 3797 3798 switch (event_sp->GetType()) { 3799 case eBroadcastInternalStateControlStop: 3800 exit_now = true; 3801 break; // doing any internal state management below 3802 3803 case eBroadcastInternalStateControlPause: 3804 control_only = true; 3805 break; 3806 3807 case eBroadcastInternalStateControlResume: 3808 control_only = false; 3809 break; 3810 } 3811 3812 continue; 3813 } else if (event_sp->GetType() == eBroadcastBitInterrupt) { 3814 if (m_public_state.GetValue() == eStateAttaching) { 3815 if (log) 3816 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 3817 ") woke up with an interrupt while attaching - " 3818 "forwarding interrupt.", 3819 __FUNCTION__, static_cast<void *>(this), GetID()); 3820 BroadcastEvent(eBroadcastBitInterrupt, nullptr); 3821 } else if (StateIsRunningState(m_last_broadcast_state)) { 3822 if (log) 3823 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 3824 ") woke up with an interrupt - Halting.", 3825 __FUNCTION__, static_cast<void *>(this), GetID()); 3826 Status error = HaltPrivate(); 3827 if (error.Fail() && log) 3828 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 3829 ") failed to halt the process: %s", 3830 __FUNCTION__, static_cast<void *>(this), GetID(), 3831 error.AsCString()); 3832 // Halt should generate a stopped event. Make a note of the fact that 3833 // we were doing the interrupt, so we can set the interrupted flag 3834 // after we receive the event. We deliberately set this to true even if 3835 // HaltPrivate failed, so that we can interrupt on the next natural 3836 // stop. 3837 interrupt_requested = true; 3838 } else { 3839 // This can happen when someone (e.g. Process::Halt) sees that we are 3840 // running and sends an interrupt request, but the process actually 3841 // stops before we receive it. In that case, we can just ignore the 3842 // request. We use m_last_broadcast_state, because the Stopped event 3843 // may not have been popped of the event queue yet, which is when the 3844 // public state gets updated. 3845 if (log) 3846 log->Printf( 3847 "Process::%s ignoring interrupt as we have already stopped.", 3848 __FUNCTION__); 3849 } 3850 continue; 3851 } 3852 3853 const StateType internal_state = 3854 Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 3855 3856 if (internal_state != eStateInvalid) { 3857 if (m_clear_thread_plans_on_stop && 3858 StateIsStoppedState(internal_state, true)) { 3859 m_clear_thread_plans_on_stop = false; 3860 m_thread_list.DiscardThreadPlans(); 3861 } 3862 3863 if (interrupt_requested) { 3864 if (StateIsStoppedState(internal_state, true)) { 3865 // We requested the interrupt, so mark this as such in the stop event 3866 // so clients can tell an interrupted process from a natural stop 3867 ProcessEventData::SetInterruptedInEvent(event_sp.get(), true); 3868 interrupt_requested = false; 3869 } else if (log) { 3870 log->Printf("Process::%s interrupt_requested, but a non-stopped " 3871 "state '%s' received.", 3872 __FUNCTION__, StateAsCString(internal_state)); 3873 } 3874 } 3875 3876 HandlePrivateEvent(event_sp); 3877 } 3878 3879 if (internal_state == eStateInvalid || internal_state == eStateExited || 3880 internal_state == eStateDetached) { 3881 if (log) 3882 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 3883 ") about to exit with internal state %s...", 3884 __FUNCTION__, static_cast<void *>(this), GetID(), 3885 StateAsCString(internal_state)); 3886 3887 break; 3888 } 3889 } 3890 3891 // Verify log is still enabled before attempting to write to it... 3892 if (log) 3893 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", 3894 __FUNCTION__, static_cast<void *>(this), GetID()); 3895 3896 // If we are a secondary thread, then the primary thread we are working for 3897 // will have already acquired the public_run_lock, and isn't done with what 3898 // it was doing yet, so don't try to change it on the way out. 3899 if (!is_secondary_thread) 3900 m_public_run_lock.SetStopped(); 3901 return NULL; 3902 } 3903 3904 //------------------------------------------------------------------ 3905 // Process Event Data 3906 //------------------------------------------------------------------ 3907 3908 Process::ProcessEventData::ProcessEventData() 3909 : EventData(), m_process_wp(), m_state(eStateInvalid), m_restarted(false), 3910 m_update_state(0), m_interrupted(false) {} 3911 3912 Process::ProcessEventData::ProcessEventData(const ProcessSP &process_sp, 3913 StateType state) 3914 : EventData(), m_process_wp(), m_state(state), m_restarted(false), 3915 m_update_state(0), m_interrupted(false) { 3916 if (process_sp) 3917 m_process_wp = process_sp; 3918 } 3919 3920 Process::ProcessEventData::~ProcessEventData() = default; 3921 3922 ConstString Process::ProcessEventData::GetFlavorString() { 3923 static ConstString g_flavor("Process::ProcessEventData"); 3924 return g_flavor; 3925 } 3926 3927 ConstString Process::ProcessEventData::GetFlavor() const { 3928 return ProcessEventData::GetFlavorString(); 3929 } 3930 3931 void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) { 3932 ProcessSP process_sp(m_process_wp.lock()); 3933 3934 if (!process_sp) 3935 return; 3936 3937 // This function gets called twice for each event, once when the event gets 3938 // pulled off of the private process event queue, and then any number of 3939 // times, first when it gets pulled off of the public event queue, then other 3940 // times when we're pretending that this is where we stopped at the end of 3941 // expression evaluation. m_update_state is used to distinguish these three 3942 // cases; it is 0 when we're just pulling it off for private handling, and > 3943 // 1 for expression evaluation, and we don't want to do the breakpoint 3944 // command handling then. 3945 if (m_update_state != 1) 3946 return; 3947 3948 process_sp->SetPublicState( 3949 m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr)); 3950 3951 if (m_state == eStateStopped && !m_restarted) { 3952 // Let process subclasses know we are about to do a public stop and do 3953 // anything they might need to in order to speed up register and memory 3954 // accesses. 3955 process_sp->WillPublicStop(); 3956 } 3957 3958 // If this is a halt event, even if the halt stopped with some reason other 3959 // than a plain interrupt (e.g. we had already stopped for a breakpoint when 3960 // the halt request came through) don't do the StopInfo actions, as they may 3961 // end up restarting the process. 3962 if (m_interrupted) 3963 return; 3964 3965 // If we're stopped and haven't restarted, then do the StopInfo actions here: 3966 if (m_state == eStateStopped && !m_restarted) { 3967 ThreadList &curr_thread_list = process_sp->GetThreadList(); 3968 uint32_t num_threads = curr_thread_list.GetSize(); 3969 uint32_t idx; 3970 3971 // The actions might change one of the thread's stop_info's opinions about 3972 // whether we should stop the process, so we need to query that as we go. 3973 3974 // One other complication here, is that we try to catch any case where the 3975 // target has run (except for expressions) and immediately exit, but if we 3976 // get that wrong (which is possible) then the thread list might have 3977 // changed, and that would cause our iteration here to crash. We could 3978 // make a copy of the thread list, but we'd really like to also know if it 3979 // has changed at all, so we make up a vector of the thread ID's and check 3980 // what we get back against this list & bag out if anything differs. 3981 std::vector<uint32_t> thread_index_array(num_threads); 3982 for (idx = 0; idx < num_threads; ++idx) 3983 thread_index_array[idx] = 3984 curr_thread_list.GetThreadAtIndex(idx)->GetIndexID(); 3985 3986 // Use this to track whether we should continue from here. We will only 3987 // continue the target running if no thread says we should stop. Of course 3988 // if some thread's PerformAction actually sets the target running, then it 3989 // doesn't matter what the other threads say... 3990 3991 bool still_should_stop = false; 3992 3993 // Sometimes - for instance if we have a bug in the stub we are talking to, 3994 // we stop but no thread has a valid stop reason. In that case we should 3995 // just stop, because we have no way of telling what the right thing to do 3996 // is, and it's better to let the user decide than continue behind their 3997 // backs. 3998 3999 bool does_anybody_have_an_opinion = false; 4000 4001 for (idx = 0; idx < num_threads; ++idx) { 4002 curr_thread_list = process_sp->GetThreadList(); 4003 if (curr_thread_list.GetSize() != num_threads) { 4004 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP | 4005 LIBLLDB_LOG_PROCESS)); 4006 if (log) 4007 log->Printf( 4008 "Number of threads changed from %u to %u while processing event.", 4009 num_threads, curr_thread_list.GetSize()); 4010 break; 4011 } 4012 4013 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx); 4014 4015 if (thread_sp->GetIndexID() != thread_index_array[idx]) { 4016 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP | 4017 LIBLLDB_LOG_PROCESS)); 4018 if (log) 4019 log->Printf("The thread at position %u changed from %u to %u while " 4020 "processing event.", 4021 idx, thread_index_array[idx], thread_sp->GetIndexID()); 4022 break; 4023 } 4024 4025 StopInfoSP stop_info_sp = thread_sp->GetStopInfo(); 4026 if (stop_info_sp && stop_info_sp->IsValid()) { 4027 does_anybody_have_an_opinion = true; 4028 bool this_thread_wants_to_stop; 4029 if (stop_info_sp->GetOverrideShouldStop()) { 4030 this_thread_wants_to_stop = 4031 stop_info_sp->GetOverriddenShouldStopValue(); 4032 } else { 4033 stop_info_sp->PerformAction(event_ptr); 4034 // The stop action might restart the target. If it does, then we 4035 // want to mark that in the event so that whoever is receiving it 4036 // will know to wait for the running event and reflect that state 4037 // appropriately. We also need to stop processing actions, since they 4038 // aren't expecting the target to be running. 4039 4040 // FIXME: we might have run. 4041 if (stop_info_sp->HasTargetRunSinceMe()) { 4042 SetRestarted(true); 4043 break; 4044 } 4045 4046 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr); 4047 } 4048 4049 if (!still_should_stop) 4050 still_should_stop = this_thread_wants_to_stop; 4051 } 4052 } 4053 4054 if (!GetRestarted()) { 4055 if (!still_should_stop && does_anybody_have_an_opinion) { 4056 // We've been asked to continue, so do that here. 4057 SetRestarted(true); 4058 // Use the public resume method here, since this is just extending a 4059 // public resume. 4060 process_sp->PrivateResume(); 4061 } else { 4062 bool hijacked = 4063 process_sp->IsHijackedForEvent(eBroadcastBitStateChanged) 4064 && !process_sp->StateChangedIsHijackedForSynchronousResume(); 4065 4066 if (!hijacked) { 4067 // If we didn't restart, run the Stop Hooks here. 4068 // Don't do that if state changed events aren't hooked up to the 4069 // public (or SyncResume) broadcasters. StopHooks are just for 4070 // real public stops. They might also restart the target, 4071 // so watch for that. 4072 process_sp->GetTarget().RunStopHooks(); 4073 if (process_sp->GetPrivateState() == eStateRunning) 4074 SetRestarted(true); 4075 } 4076 } 4077 } 4078 } 4079 } 4080 4081 void Process::ProcessEventData::Dump(Stream *s) const { 4082 ProcessSP process_sp(m_process_wp.lock()); 4083 4084 if (process_sp) 4085 s->Printf(" process = %p (pid = %" PRIu64 "), ", 4086 static_cast<void *>(process_sp.get()), process_sp->GetID()); 4087 else 4088 s->PutCString(" process = NULL, "); 4089 4090 s->Printf("state = %s", StateAsCString(GetState())); 4091 } 4092 4093 const Process::ProcessEventData * 4094 Process::ProcessEventData::GetEventDataFromEvent(const Event *event_ptr) { 4095 if (event_ptr) { 4096 const EventData *event_data = event_ptr->GetData(); 4097 if (event_data && 4098 event_data->GetFlavor() == ProcessEventData::GetFlavorString()) 4099 return static_cast<const ProcessEventData *>(event_ptr->GetData()); 4100 } 4101 return nullptr; 4102 } 4103 4104 ProcessSP 4105 Process::ProcessEventData::GetProcessFromEvent(const Event *event_ptr) { 4106 ProcessSP process_sp; 4107 const ProcessEventData *data = GetEventDataFromEvent(event_ptr); 4108 if (data) 4109 process_sp = data->GetProcessSP(); 4110 return process_sp; 4111 } 4112 4113 StateType Process::ProcessEventData::GetStateFromEvent(const Event *event_ptr) { 4114 const ProcessEventData *data = GetEventDataFromEvent(event_ptr); 4115 if (data == nullptr) 4116 return eStateInvalid; 4117 else 4118 return data->GetState(); 4119 } 4120 4121 bool Process::ProcessEventData::GetRestartedFromEvent(const Event *event_ptr) { 4122 const ProcessEventData *data = GetEventDataFromEvent(event_ptr); 4123 if (data == nullptr) 4124 return false; 4125 else 4126 return data->GetRestarted(); 4127 } 4128 4129 void Process::ProcessEventData::SetRestartedInEvent(Event *event_ptr, 4130 bool new_value) { 4131 ProcessEventData *data = 4132 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr)); 4133 if (data != nullptr) 4134 data->SetRestarted(new_value); 4135 } 4136 4137 size_t 4138 Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr) { 4139 ProcessEventData *data = 4140 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr)); 4141 if (data != nullptr) 4142 return data->GetNumRestartedReasons(); 4143 else 4144 return 0; 4145 } 4146 4147 const char * 4148 Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, 4149 size_t idx) { 4150 ProcessEventData *data = 4151 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr)); 4152 if (data != nullptr) 4153 return data->GetRestartedReasonAtIndex(idx); 4154 else 4155 return nullptr; 4156 } 4157 4158 void Process::ProcessEventData::AddRestartedReason(Event *event_ptr, 4159 const char *reason) { 4160 ProcessEventData *data = 4161 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr)); 4162 if (data != nullptr) 4163 data->AddRestartedReason(reason); 4164 } 4165 4166 bool Process::ProcessEventData::GetInterruptedFromEvent( 4167 const Event *event_ptr) { 4168 const ProcessEventData *data = GetEventDataFromEvent(event_ptr); 4169 if (data == nullptr) 4170 return false; 4171 else 4172 return data->GetInterrupted(); 4173 } 4174 4175 void Process::ProcessEventData::SetInterruptedInEvent(Event *event_ptr, 4176 bool new_value) { 4177 ProcessEventData *data = 4178 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr)); 4179 if (data != nullptr) 4180 data->SetInterrupted(new_value); 4181 } 4182 4183 bool Process::ProcessEventData::SetUpdateStateOnRemoval(Event *event_ptr) { 4184 ProcessEventData *data = 4185 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr)); 4186 if (data) { 4187 data->SetUpdateStateOnRemoval(); 4188 return true; 4189 } 4190 return false; 4191 } 4192 4193 lldb::TargetSP Process::CalculateTarget() { return m_target_wp.lock(); } 4194 4195 void Process::CalculateExecutionContext(ExecutionContext &exe_ctx) { 4196 exe_ctx.SetTargetPtr(&GetTarget()); 4197 exe_ctx.SetProcessPtr(this); 4198 exe_ctx.SetThreadPtr(nullptr); 4199 exe_ctx.SetFramePtr(nullptr); 4200 } 4201 4202 // uint32_t 4203 // Process::ListProcessesMatchingName (const char *name, StringList &matches, 4204 // std::vector<lldb::pid_t> &pids) 4205 //{ 4206 // return 0; 4207 //} 4208 // 4209 // ArchSpec 4210 // Process::GetArchSpecForExistingProcess (lldb::pid_t pid) 4211 //{ 4212 // return Host::GetArchSpecForExistingProcess (pid); 4213 //} 4214 // 4215 // ArchSpec 4216 // Process::GetArchSpecForExistingProcess (const char *process_name) 4217 //{ 4218 // return Host::GetArchSpecForExistingProcess (process_name); 4219 //} 4220 4221 void Process::AppendSTDOUT(const char *s, size_t len) { 4222 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex); 4223 m_stdout_data.append(s, len); 4224 BroadcastEventIfUnique(eBroadcastBitSTDOUT, 4225 new ProcessEventData(shared_from_this(), GetState())); 4226 } 4227 4228 void Process::AppendSTDERR(const char *s, size_t len) { 4229 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex); 4230 m_stderr_data.append(s, len); 4231 BroadcastEventIfUnique(eBroadcastBitSTDERR, 4232 new ProcessEventData(shared_from_this(), GetState())); 4233 } 4234 4235 void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) { 4236 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex); 4237 m_profile_data.push_back(one_profile_data); 4238 BroadcastEventIfUnique(eBroadcastBitProfileData, 4239 new ProcessEventData(shared_from_this(), GetState())); 4240 } 4241 4242 void Process::BroadcastStructuredData(const StructuredData::ObjectSP &object_sp, 4243 const StructuredDataPluginSP &plugin_sp) { 4244 BroadcastEvent( 4245 eBroadcastBitStructuredData, 4246 new EventDataStructuredData(shared_from_this(), object_sp, plugin_sp)); 4247 } 4248 4249 StructuredDataPluginSP 4250 Process::GetStructuredDataPlugin(ConstString type_name) const { 4251 auto find_it = m_structured_data_plugin_map.find(type_name); 4252 if (find_it != m_structured_data_plugin_map.end()) 4253 return find_it->second; 4254 else 4255 return StructuredDataPluginSP(); 4256 } 4257 4258 size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Status &error) { 4259 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex); 4260 if (m_profile_data.empty()) 4261 return 0; 4262 4263 std::string &one_profile_data = m_profile_data.front(); 4264 size_t bytes_available = one_profile_data.size(); 4265 if (bytes_available > 0) { 4266 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 4267 if (log) 4268 log->Printf("Process::GetProfileData (buf = %p, size = %" PRIu64 ")", 4269 static_cast<void *>(buf), static_cast<uint64_t>(buf_size)); 4270 if (bytes_available > buf_size) { 4271 memcpy(buf, one_profile_data.c_str(), buf_size); 4272 one_profile_data.erase(0, buf_size); 4273 bytes_available = buf_size; 4274 } else { 4275 memcpy(buf, one_profile_data.c_str(), bytes_available); 4276 m_profile_data.erase(m_profile_data.begin()); 4277 } 4278 } 4279 return bytes_available; 4280 } 4281 4282 //------------------------------------------------------------------ 4283 // Process STDIO 4284 //------------------------------------------------------------------ 4285 4286 size_t Process::GetSTDOUT(char *buf, size_t buf_size, Status &error) { 4287 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex); 4288 size_t bytes_available = m_stdout_data.size(); 4289 if (bytes_available > 0) { 4290 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 4291 if (log) 4292 log->Printf("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")", 4293 static_cast<void *>(buf), static_cast<uint64_t>(buf_size)); 4294 if (bytes_available > buf_size) { 4295 memcpy(buf, m_stdout_data.c_str(), buf_size); 4296 m_stdout_data.erase(0, buf_size); 4297 bytes_available = buf_size; 4298 } else { 4299 memcpy(buf, m_stdout_data.c_str(), bytes_available); 4300 m_stdout_data.clear(); 4301 } 4302 } 4303 return bytes_available; 4304 } 4305 4306 size_t Process::GetSTDERR(char *buf, size_t buf_size, Status &error) { 4307 std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex); 4308 size_t bytes_available = m_stderr_data.size(); 4309 if (bytes_available > 0) { 4310 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 4311 if (log) 4312 log->Printf("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")", 4313 static_cast<void *>(buf), static_cast<uint64_t>(buf_size)); 4314 if (bytes_available > buf_size) { 4315 memcpy(buf, m_stderr_data.c_str(), buf_size); 4316 m_stderr_data.erase(0, buf_size); 4317 bytes_available = buf_size; 4318 } else { 4319 memcpy(buf, m_stderr_data.c_str(), bytes_available); 4320 m_stderr_data.clear(); 4321 } 4322 } 4323 return bytes_available; 4324 } 4325 4326 void Process::STDIOReadThreadBytesReceived(void *baton, const void *src, 4327 size_t src_len) { 4328 Process *process = (Process *)baton; 4329 process->AppendSTDOUT(static_cast<const char *>(src), src_len); 4330 } 4331 4332 class IOHandlerProcessSTDIO : public IOHandler { 4333 public: 4334 IOHandlerProcessSTDIO(Process *process, int write_fd) 4335 : IOHandler(process->GetTarget().GetDebugger(), 4336 IOHandler::Type::ProcessIO), 4337 m_process(process), m_write_file(write_fd, false) { 4338 m_pipe.CreateNew(false); 4339 m_read_file.SetDescriptor(GetInputFD(), false); 4340 } 4341 4342 ~IOHandlerProcessSTDIO() override = default; 4343 4344 // Each IOHandler gets to run until it is done. It should read data from the 4345 // "in" and place output into "out" and "err and return when done. 4346 void Run() override { 4347 if (!m_read_file.IsValid() || !m_write_file.IsValid() || 4348 !m_pipe.CanRead() || !m_pipe.CanWrite()) { 4349 SetIsDone(true); 4350 return; 4351 } 4352 4353 SetIsDone(false); 4354 const int read_fd = m_read_file.GetDescriptor(); 4355 TerminalState terminal_state; 4356 terminal_state.Save(read_fd, false); 4357 Terminal terminal(read_fd); 4358 terminal.SetCanonical(false); 4359 terminal.SetEcho(false); 4360 // FD_ZERO, FD_SET are not supported on windows 4361 #ifndef _WIN32 4362 const int pipe_read_fd = m_pipe.GetReadFileDescriptor(); 4363 m_is_running = true; 4364 while (!GetIsDone()) { 4365 SelectHelper select_helper; 4366 select_helper.FDSetRead(read_fd); 4367 select_helper.FDSetRead(pipe_read_fd); 4368 Status error = select_helper.Select(); 4369 4370 if (error.Fail()) { 4371 SetIsDone(true); 4372 } else { 4373 char ch = 0; 4374 size_t n; 4375 if (select_helper.FDIsSetRead(read_fd)) { 4376 n = 1; 4377 if (m_read_file.Read(&ch, n).Success() && n == 1) { 4378 if (m_write_file.Write(&ch, n).Fail() || n != 1) 4379 SetIsDone(true); 4380 } else 4381 SetIsDone(true); 4382 } 4383 if (select_helper.FDIsSetRead(pipe_read_fd)) { 4384 size_t bytes_read; 4385 // Consume the interrupt byte 4386 Status error = m_pipe.Read(&ch, 1, bytes_read); 4387 if (error.Success()) { 4388 switch (ch) { 4389 case 'q': 4390 SetIsDone(true); 4391 break; 4392 case 'i': 4393 if (StateIsRunningState(m_process->GetState())) 4394 m_process->SendAsyncInterrupt(); 4395 break; 4396 } 4397 } 4398 } 4399 } 4400 } 4401 m_is_running = false; 4402 #endif 4403 terminal_state.Restore(); 4404 } 4405 4406 void Cancel() override { 4407 SetIsDone(true); 4408 // Only write to our pipe to cancel if we are in 4409 // IOHandlerProcessSTDIO::Run(). We can end up with a python command that 4410 // is being run from the command interpreter: 4411 // 4412 // (lldb) step_process_thousands_of_times 4413 // 4414 // In this case the command interpreter will be in the middle of handling 4415 // the command and if the process pushes and pops the IOHandler thousands 4416 // of times, we can end up writing to m_pipe without ever consuming the 4417 // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up 4418 // deadlocking when the pipe gets fed up and blocks until data is consumed. 4419 if (m_is_running) { 4420 char ch = 'q'; // Send 'q' for quit 4421 size_t bytes_written = 0; 4422 m_pipe.Write(&ch, 1, bytes_written); 4423 } 4424 } 4425 4426 bool Interrupt() override { 4427 // Do only things that are safe to do in an interrupt context (like in a 4428 // SIGINT handler), like write 1 byte to a file descriptor. This will 4429 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte 4430 // that was written to the pipe and then call 4431 // m_process->SendAsyncInterrupt() from a much safer location in code. 4432 if (m_active) { 4433 char ch = 'i'; // Send 'i' for interrupt 4434 size_t bytes_written = 0; 4435 Status result = m_pipe.Write(&ch, 1, bytes_written); 4436 return result.Success(); 4437 } else { 4438 // This IOHandler might be pushed on the stack, but not being run 4439 // currently so do the right thing if we aren't actively watching for 4440 // STDIN by sending the interrupt to the process. Otherwise the write to 4441 // the pipe above would do nothing. This can happen when the command 4442 // interpreter is running and gets a "expression ...". It will be on the 4443 // IOHandler thread and sending the input is complete to the delegate 4444 // which will cause the expression to run, which will push the process IO 4445 // handler, but not run it. 4446 4447 if (StateIsRunningState(m_process->GetState())) { 4448 m_process->SendAsyncInterrupt(); 4449 return true; 4450 } 4451 } 4452 return false; 4453 } 4454 4455 void GotEOF() override {} 4456 4457 protected: 4458 Process *m_process; 4459 File m_read_file; // Read from this file (usually actual STDIN for LLDB 4460 File m_write_file; // Write to this file (usually the master pty for getting 4461 // io to debuggee) 4462 Pipe m_pipe; 4463 std::atomic<bool> m_is_running{false}; 4464 }; 4465 4466 void Process::SetSTDIOFileDescriptor(int fd) { 4467 // First set up the Read Thread for reading/handling process I/O 4468 4469 std::unique_ptr<ConnectionFileDescriptor> conn_up( 4470 new ConnectionFileDescriptor(fd, true)); 4471 4472 if (conn_up) { 4473 m_stdio_communication.SetConnection(conn_up.release()); 4474 if (m_stdio_communication.IsConnected()) { 4475 m_stdio_communication.SetReadThreadBytesReceivedCallback( 4476 STDIOReadThreadBytesReceived, this); 4477 m_stdio_communication.StartReadThread(); 4478 4479 // Now read thread is set up, set up input reader. 4480 4481 if (!m_process_input_reader) 4482 m_process_input_reader = 4483 std::make_shared<IOHandlerProcessSTDIO>(this, fd); 4484 } 4485 } 4486 } 4487 4488 bool Process::ProcessIOHandlerIsActive() { 4489 IOHandlerSP io_handler_sp(m_process_input_reader); 4490 if (io_handler_sp) 4491 return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp); 4492 return false; 4493 } 4494 bool Process::PushProcessIOHandler() { 4495 IOHandlerSP io_handler_sp(m_process_input_reader); 4496 if (io_handler_sp) { 4497 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 4498 if (log) 4499 log->Printf("Process::%s pushing IO handler", __FUNCTION__); 4500 4501 io_handler_sp->SetIsDone(false); 4502 // If we evaluate an utility function, then we don't cancel the current 4503 // IOHandler. Our IOHandler is non-interactive and shouldn't disturb the 4504 // existing IOHandler that potentially provides the user interface (e.g. 4505 // the IOHandler for Editline). 4506 bool cancel_top_handler = !m_mod_id.IsRunningUtilityFunction(); 4507 GetTarget().GetDebugger().PushIOHandler(io_handler_sp, cancel_top_handler); 4508 return true; 4509 } 4510 return false; 4511 } 4512 4513 bool Process::PopProcessIOHandler() { 4514 IOHandlerSP io_handler_sp(m_process_input_reader); 4515 if (io_handler_sp) 4516 return GetTarget().GetDebugger().PopIOHandler(io_handler_sp); 4517 return false; 4518 } 4519 4520 // The process needs to know about installed plug-ins 4521 void Process::SettingsInitialize() { Thread::SettingsInitialize(); } 4522 4523 void Process::SettingsTerminate() { Thread::SettingsTerminate(); } 4524 4525 namespace { 4526 // RestorePlanState is used to record the "is private", "is master" and "okay 4527 // to discard" fields of the plan we are running, and reset it on Clean or on 4528 // destruction. It will only reset the state once, so you can call Clean and 4529 // then monkey with the state and it won't get reset on you again. 4530 4531 class RestorePlanState { 4532 public: 4533 RestorePlanState(lldb::ThreadPlanSP thread_plan_sp) 4534 : m_thread_plan_sp(thread_plan_sp), m_already_reset(false) { 4535 if (m_thread_plan_sp) { 4536 m_private = m_thread_plan_sp->GetPrivate(); 4537 m_is_master = m_thread_plan_sp->IsMasterPlan(); 4538 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard(); 4539 } 4540 } 4541 4542 ~RestorePlanState() { Clean(); } 4543 4544 void Clean() { 4545 if (!m_already_reset && m_thread_plan_sp) { 4546 m_already_reset = true; 4547 m_thread_plan_sp->SetPrivate(m_private); 4548 m_thread_plan_sp->SetIsMasterPlan(m_is_master); 4549 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard); 4550 } 4551 } 4552 4553 private: 4554 lldb::ThreadPlanSP m_thread_plan_sp; 4555 bool m_already_reset; 4556 bool m_private; 4557 bool m_is_master; 4558 bool m_okay_to_discard; 4559 }; 4560 } // anonymous namespace 4561 4562 static microseconds 4563 GetOneThreadExpressionTimeout(const EvaluateExpressionOptions &options) { 4564 const milliseconds default_one_thread_timeout(250); 4565 4566 // If the overall wait is forever, then we don't need to worry about it. 4567 if (!options.GetTimeout()) { 4568 return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout() 4569 : default_one_thread_timeout; 4570 } 4571 4572 // If the one thread timeout is set, use it. 4573 if (options.GetOneThreadTimeout()) 4574 return *options.GetOneThreadTimeout(); 4575 4576 // Otherwise use half the total timeout, bounded by the 4577 // default_one_thread_timeout. 4578 return std::min<microseconds>(default_one_thread_timeout, 4579 *options.GetTimeout() / 2); 4580 } 4581 4582 static Timeout<std::micro> 4583 GetExpressionTimeout(const EvaluateExpressionOptions &options, 4584 bool before_first_timeout) { 4585 // If we are going to run all threads the whole time, or if we are only going 4586 // to run one thread, we can just return the overall timeout. 4587 if (!options.GetStopOthers() || !options.GetTryAllThreads()) 4588 return options.GetTimeout(); 4589 4590 if (before_first_timeout) 4591 return GetOneThreadExpressionTimeout(options); 4592 4593 if (!options.GetTimeout()) 4594 return llvm::None; 4595 else 4596 return *options.GetTimeout() - GetOneThreadExpressionTimeout(options); 4597 } 4598 4599 static llvm::Optional<ExpressionResults> 4600 HandleStoppedEvent(Thread &thread, const ThreadPlanSP &thread_plan_sp, 4601 RestorePlanState &restorer, const EventSP &event_sp, 4602 EventSP &event_to_broadcast_sp, 4603 const EvaluateExpressionOptions &options, bool handle_interrupts) { 4604 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS); 4605 4606 ThreadPlanSP plan = thread.GetCompletedPlan(); 4607 if (plan == thread_plan_sp && plan->PlanSucceeded()) { 4608 LLDB_LOG(log, "execution completed successfully"); 4609 4610 // Restore the plan state so it will get reported as intended when we are 4611 // done. 4612 restorer.Clean(); 4613 return eExpressionCompleted; 4614 } 4615 4616 StopInfoSP stop_info_sp = thread.GetStopInfo(); 4617 if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint && 4618 stop_info_sp->ShouldNotify(event_sp.get())) { 4619 LLDB_LOG(log, "stopped for breakpoint: {0}.", stop_info_sp->GetDescription()); 4620 if (!options.DoesIgnoreBreakpoints()) { 4621 // Restore the plan state and then force Private to false. We are going 4622 // to stop because of this plan so we need it to become a public plan or 4623 // it won't report correctly when we continue to its termination later 4624 // on. 4625 restorer.Clean(); 4626 thread_plan_sp->SetPrivate(false); 4627 event_to_broadcast_sp = event_sp; 4628 } 4629 return eExpressionHitBreakpoint; 4630 } 4631 4632 if (!handle_interrupts && 4633 Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get())) 4634 return llvm::None; 4635 4636 LLDB_LOG(log, "thread plan did not successfully complete"); 4637 if (!options.DoesUnwindOnError()) 4638 event_to_broadcast_sp = event_sp; 4639 return eExpressionInterrupted; 4640 } 4641 4642 ExpressionResults 4643 Process::RunThreadPlan(ExecutionContext &exe_ctx, 4644 lldb::ThreadPlanSP &thread_plan_sp, 4645 const EvaluateExpressionOptions &options, 4646 DiagnosticManager &diagnostic_manager) { 4647 ExpressionResults return_value = eExpressionSetupError; 4648 4649 std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock); 4650 4651 if (!thread_plan_sp) { 4652 diagnostic_manager.PutString( 4653 eDiagnosticSeverityError, 4654 "RunThreadPlan called with empty thread plan."); 4655 return eExpressionSetupError; 4656 } 4657 4658 if (!thread_plan_sp->ValidatePlan(nullptr)) { 4659 diagnostic_manager.PutString( 4660 eDiagnosticSeverityError, 4661 "RunThreadPlan called with an invalid thread plan."); 4662 return eExpressionSetupError; 4663 } 4664 4665 if (exe_ctx.GetProcessPtr() != this) { 4666 diagnostic_manager.PutString(eDiagnosticSeverityError, 4667 "RunThreadPlan called on wrong process."); 4668 return eExpressionSetupError; 4669 } 4670 4671 Thread *thread = exe_ctx.GetThreadPtr(); 4672 if (thread == nullptr) { 4673 diagnostic_manager.PutString(eDiagnosticSeverityError, 4674 "RunThreadPlan called with invalid thread."); 4675 return eExpressionSetupError; 4676 } 4677 4678 // We need to change some of the thread plan attributes for the thread plan 4679 // runner. This will restore them when we are done: 4680 4681 RestorePlanState thread_plan_restorer(thread_plan_sp); 4682 4683 // We rely on the thread plan we are running returning "PlanCompleted" if 4684 // when it successfully completes. For that to be true the plan can't be 4685 // private - since private plans suppress themselves in the GetCompletedPlan 4686 // call. 4687 4688 thread_plan_sp->SetPrivate(false); 4689 4690 // The plans run with RunThreadPlan also need to be terminal master plans or 4691 // when they are done we will end up asking the plan above us whether we 4692 // should stop, which may give the wrong answer. 4693 4694 thread_plan_sp->SetIsMasterPlan(true); 4695 thread_plan_sp->SetOkayToDiscard(false); 4696 4697 // If we are running some utility expression for LLDB, we now have to mark 4698 // this in the ProcesModID of this process. This RAII takes care of marking 4699 // and reverting the mark it once we are done running the expression. 4700 UtilityFunctionScope util_scope(options.IsForUtilityExpr() ? this : nullptr); 4701 4702 if (m_private_state.GetValue() != eStateStopped) { 4703 diagnostic_manager.PutString( 4704 eDiagnosticSeverityError, 4705 "RunThreadPlan called while the private state was not stopped."); 4706 return eExpressionSetupError; 4707 } 4708 4709 // Save the thread & frame from the exe_ctx for restoration after we run 4710 const uint32_t thread_idx_id = thread->GetIndexID(); 4711 StackFrameSP selected_frame_sp = thread->GetSelectedFrame(); 4712 if (!selected_frame_sp) { 4713 thread->SetSelectedFrame(nullptr); 4714 selected_frame_sp = thread->GetSelectedFrame(); 4715 if (!selected_frame_sp) { 4716 diagnostic_manager.Printf( 4717 eDiagnosticSeverityError, 4718 "RunThreadPlan called without a selected frame on thread %d", 4719 thread_idx_id); 4720 return eExpressionSetupError; 4721 } 4722 } 4723 4724 // Make sure the timeout values make sense. The one thread timeout needs to 4725 // be smaller than the overall timeout. 4726 if (options.GetOneThreadTimeout() && options.GetTimeout() && 4727 *options.GetTimeout() < *options.GetOneThreadTimeout()) { 4728 diagnostic_manager.PutString(eDiagnosticSeverityError, 4729 "RunThreadPlan called with one thread " 4730 "timeout greater than total timeout"); 4731 return eExpressionSetupError; 4732 } 4733 4734 StackID ctx_frame_id = selected_frame_sp->GetStackID(); 4735 4736 // N.B. Running the target may unset the currently selected thread and frame. 4737 // We don't want to do that either, so we should arrange to reset them as 4738 // well. 4739 4740 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread(); 4741 4742 uint32_t selected_tid; 4743 StackID selected_stack_id; 4744 if (selected_thread_sp) { 4745 selected_tid = selected_thread_sp->GetIndexID(); 4746 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID(); 4747 } else { 4748 selected_tid = LLDB_INVALID_THREAD_ID; 4749 } 4750 4751 HostThread backup_private_state_thread; 4752 lldb::StateType old_state = eStateInvalid; 4753 lldb::ThreadPlanSP stopper_base_plan_sp; 4754 4755 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP | 4756 LIBLLDB_LOG_PROCESS)); 4757 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) { 4758 // Yikes, we are running on the private state thread! So we can't wait for 4759 // public events on this thread, since we are the thread that is generating 4760 // public events. The simplest thing to do is to spin up a temporary thread 4761 // to handle private state thread events while we are fielding public 4762 // events here. 4763 if (log) 4764 log->Printf("Running thread plan on private state thread, spinning up " 4765 "another state thread to handle the events."); 4766 4767 backup_private_state_thread = m_private_state_thread; 4768 4769 // One other bit of business: we want to run just this thread plan and 4770 // anything it pushes, and then stop, returning control here. But in the 4771 // normal course of things, the plan above us on the stack would be given a 4772 // shot at the stop event before deciding to stop, and we don't want that. 4773 // So we insert a "stopper" base plan on the stack before the plan we want 4774 // to run. Since base plans always stop and return control to the user, 4775 // that will do just what we want. 4776 stopper_base_plan_sp.reset(new ThreadPlanBase(*thread)); 4777 thread->QueueThreadPlan(stopper_base_plan_sp, false); 4778 // Have to make sure our public state is stopped, since otherwise the 4779 // reporting logic below doesn't work correctly. 4780 old_state = m_public_state.GetValue(); 4781 m_public_state.SetValueNoLock(eStateStopped); 4782 4783 // Now spin up the private state thread: 4784 StartPrivateStateThread(true); 4785 } 4786 4787 thread->QueueThreadPlan( 4788 thread_plan_sp, false); // This used to pass "true" does that make sense? 4789 4790 if (options.GetDebug()) { 4791 // In this case, we aren't actually going to run, we just want to stop 4792 // right away. Flush this thread so we will refetch the stacks and show the 4793 // correct backtrace. 4794 // FIXME: To make this prettier we should invent some stop reason for this, 4795 // but that 4796 // is only cosmetic, and this functionality is only of use to lldb 4797 // developers who can live with not pretty... 4798 thread->Flush(); 4799 return eExpressionStoppedForDebug; 4800 } 4801 4802 ListenerSP listener_sp( 4803 Listener::MakeListener("lldb.process.listener.run-thread-plan")); 4804 4805 lldb::EventSP event_to_broadcast_sp; 4806 4807 { 4808 // This process event hijacker Hijacks the Public events and its destructor 4809 // makes sure that the process events get restored on exit to the function. 4810 // 4811 // If the event needs to propagate beyond the hijacker (e.g., the process 4812 // exits during execution), then the event is put into 4813 // event_to_broadcast_sp for rebroadcasting. 4814 4815 ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp); 4816 4817 if (log) { 4818 StreamString s; 4819 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose); 4820 log->Printf("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 4821 " to run thread plan \"%s\".", 4822 thread->GetIndexID(), thread->GetID(), s.GetData()); 4823 } 4824 4825 bool got_event; 4826 lldb::EventSP event_sp; 4827 lldb::StateType stop_state = lldb::eStateInvalid; 4828 4829 bool before_first_timeout = true; // This is set to false the first time 4830 // that we have to halt the target. 4831 bool do_resume = true; 4832 bool handle_running_event = true; 4833 4834 // This is just for accounting: 4835 uint32_t num_resumes = 0; 4836 4837 // If we are going to run all threads the whole time, or if we are only 4838 // going to run one thread, then we don't need the first timeout. So we 4839 // pretend we are after the first timeout already. 4840 if (!options.GetStopOthers() || !options.GetTryAllThreads()) 4841 before_first_timeout = false; 4842 4843 if (log) 4844 log->Printf("Stop others: %u, try all: %u, before_first: %u.\n", 4845 options.GetStopOthers(), options.GetTryAllThreads(), 4846 before_first_timeout); 4847 4848 // This isn't going to work if there are unfetched events on the queue. Are 4849 // there cases where we might want to run the remaining events here, and 4850 // then try to call the function? That's probably being too tricky for our 4851 // own good. 4852 4853 Event *other_events = listener_sp->PeekAtNextEvent(); 4854 if (other_events != nullptr) { 4855 diagnostic_manager.PutString( 4856 eDiagnosticSeverityError, 4857 "RunThreadPlan called with pending events on the queue."); 4858 return eExpressionSetupError; 4859 } 4860 4861 // We also need to make sure that the next event is delivered. We might be 4862 // calling a function as part of a thread plan, in which case the last 4863 // delivered event could be the running event, and we don't want event 4864 // coalescing to cause us to lose OUR running event... 4865 ForceNextEventDelivery(); 4866 4867 // This while loop must exit out the bottom, there's cleanup that we need to do 4868 // when we are done. So don't call return anywhere within it. 4869 4870 #ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT 4871 // It's pretty much impossible to write test cases for things like: One 4872 // thread timeout expires, I go to halt, but the process already stopped on 4873 // the function call stop breakpoint. Turning on this define will make us 4874 // not fetch the first event till after the halt. So if you run a quick 4875 // function, it will have completed, and the completion event will be 4876 // waiting, when you interrupt for halt. The expression evaluation should 4877 // still succeed. 4878 bool miss_first_event = true; 4879 #endif 4880 while (true) { 4881 // We usually want to resume the process if we get to the top of the 4882 // loop. The only exception is if we get two running events with no 4883 // intervening stop, which can happen, we will just wait for then next 4884 // stop event. 4885 if (log) 4886 log->Printf("Top of while loop: do_resume: %i handle_running_event: %i " 4887 "before_first_timeout: %i.", 4888 do_resume, handle_running_event, before_first_timeout); 4889 4890 if (do_resume || handle_running_event) { 4891 // Do the initial resume and wait for the running event before going 4892 // further. 4893 4894 if (do_resume) { 4895 num_resumes++; 4896 Status resume_error = PrivateResume(); 4897 if (!resume_error.Success()) { 4898 diagnostic_manager.Printf( 4899 eDiagnosticSeverityError, 4900 "couldn't resume inferior the %d time: \"%s\".", num_resumes, 4901 resume_error.AsCString()); 4902 return_value = eExpressionSetupError; 4903 break; 4904 } 4905 } 4906 4907 got_event = 4908 listener_sp->GetEvent(event_sp, std::chrono::milliseconds(500)); 4909 if (!got_event) { 4910 if (log) 4911 log->Printf("Process::RunThreadPlan(): didn't get any event after " 4912 "resume %" PRIu32 ", exiting.", 4913 num_resumes); 4914 4915 diagnostic_manager.Printf(eDiagnosticSeverityError, 4916 "didn't get any event after resume %" PRIu32 4917 ", exiting.", 4918 num_resumes); 4919 return_value = eExpressionSetupError; 4920 break; 4921 } 4922 4923 stop_state = 4924 Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 4925 4926 if (stop_state != eStateRunning) { 4927 bool restarted = false; 4928 4929 if (stop_state == eStateStopped) { 4930 restarted = Process::ProcessEventData::GetRestartedFromEvent( 4931 event_sp.get()); 4932 if (log) 4933 log->Printf( 4934 "Process::RunThreadPlan(): didn't get running event after " 4935 "resume %d, got %s instead (restarted: %i, do_resume: %i, " 4936 "handle_running_event: %i).", 4937 num_resumes, StateAsCString(stop_state), restarted, do_resume, 4938 handle_running_event); 4939 } 4940 4941 if (restarted) { 4942 // This is probably an overabundance of caution, I don't think I 4943 // should ever get a stopped & restarted event here. But if I do, 4944 // the best thing is to Halt and then get out of here. 4945 const bool clear_thread_plans = false; 4946 const bool use_run_lock = false; 4947 Halt(clear_thread_plans, use_run_lock); 4948 } 4949 4950 diagnostic_manager.Printf( 4951 eDiagnosticSeverityError, 4952 "didn't get running event after initial resume, got %s instead.", 4953 StateAsCString(stop_state)); 4954 return_value = eExpressionSetupError; 4955 break; 4956 } 4957 4958 if (log) 4959 log->PutCString("Process::RunThreadPlan(): resuming succeeded."); 4960 // We need to call the function synchronously, so spin waiting for it 4961 // to return. If we get interrupted while executing, we're going to 4962 // lose our context, and won't be able to gather the result at this 4963 // point. We set the timeout AFTER the resume, since the resume takes 4964 // some time and we don't want to charge that to the timeout. 4965 } else { 4966 if (log) 4967 log->PutCString("Process::RunThreadPlan(): waiting for next event."); 4968 } 4969 4970 do_resume = true; 4971 handle_running_event = true; 4972 4973 // Now wait for the process to stop again: 4974 event_sp.reset(); 4975 4976 Timeout<std::micro> timeout = 4977 GetExpressionTimeout(options, before_first_timeout); 4978 if (log) { 4979 if (timeout) { 4980 auto now = system_clock::now(); 4981 log->Printf("Process::RunThreadPlan(): about to wait - now is %s - " 4982 "endpoint is %s", 4983 llvm::to_string(now).c_str(), 4984 llvm::to_string(now + *timeout).c_str()); 4985 } else { 4986 log->Printf("Process::RunThreadPlan(): about to wait forever."); 4987 } 4988 } 4989 4990 #ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT 4991 // See comment above... 4992 if (miss_first_event) { 4993 usleep(1000); 4994 miss_first_event = false; 4995 got_event = false; 4996 } else 4997 #endif 4998 got_event = listener_sp->GetEvent(event_sp, timeout); 4999 5000 if (got_event) { 5001 if (event_sp) { 5002 bool keep_going = false; 5003 if (event_sp->GetType() == eBroadcastBitInterrupt) { 5004 const bool clear_thread_plans = false; 5005 const bool use_run_lock = false; 5006 Halt(clear_thread_plans, use_run_lock); 5007 return_value = eExpressionInterrupted; 5008 diagnostic_manager.PutString(eDiagnosticSeverityRemark, 5009 "execution halted by user interrupt."); 5010 if (log) 5011 log->Printf("Process::RunThreadPlan(): Got interrupted by " 5012 "eBroadcastBitInterrupted, exiting."); 5013 break; 5014 } else { 5015 stop_state = 5016 Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 5017 if (log) 5018 log->Printf( 5019 "Process::RunThreadPlan(): in while loop, got event: %s.", 5020 StateAsCString(stop_state)); 5021 5022 switch (stop_state) { 5023 case lldb::eStateStopped: { 5024 // We stopped, figure out what we are going to do now. 5025 ThreadSP thread_sp = 5026 GetThreadList().FindThreadByIndexID(thread_idx_id); 5027 if (!thread_sp) { 5028 // Ooh, our thread has vanished. Unlikely that this was 5029 // successful execution... 5030 if (log) 5031 log->Printf("Process::RunThreadPlan(): execution completed " 5032 "but our thread (index-id=%u) has vanished.", 5033 thread_idx_id); 5034 return_value = eExpressionInterrupted; 5035 } else if (Process::ProcessEventData::GetRestartedFromEvent( 5036 event_sp.get())) { 5037 // If we were restarted, we just need to go back up to fetch 5038 // another event. 5039 if (log) { 5040 log->Printf("Process::RunThreadPlan(): Got a stop and " 5041 "restart, so we'll continue waiting."); 5042 } 5043 keep_going = true; 5044 do_resume = false; 5045 handle_running_event = true; 5046 } else { 5047 const bool handle_interrupts = true; 5048 return_value = *HandleStoppedEvent( 5049 *thread, thread_plan_sp, thread_plan_restorer, event_sp, 5050 event_to_broadcast_sp, options, handle_interrupts); 5051 } 5052 } break; 5053 5054 case lldb::eStateRunning: 5055 // This shouldn't really happen, but sometimes we do get two 5056 // running events without an intervening stop, and in that case 5057 // we should just go back to waiting for the stop. 5058 do_resume = false; 5059 keep_going = true; 5060 handle_running_event = false; 5061 break; 5062 5063 default: 5064 if (log) 5065 log->Printf("Process::RunThreadPlan(): execution stopped with " 5066 "unexpected state: %s.", 5067 StateAsCString(stop_state)); 5068 5069 if (stop_state == eStateExited) 5070 event_to_broadcast_sp = event_sp; 5071 5072 diagnostic_manager.PutString( 5073 eDiagnosticSeverityError, 5074 "execution stopped with unexpected state."); 5075 return_value = eExpressionInterrupted; 5076 break; 5077 } 5078 } 5079 5080 if (keep_going) 5081 continue; 5082 else 5083 break; 5084 } else { 5085 if (log) 5086 log->PutCString("Process::RunThreadPlan(): got_event was true, but " 5087 "the event pointer was null. How odd..."); 5088 return_value = eExpressionInterrupted; 5089 break; 5090 } 5091 } else { 5092 // If we didn't get an event that means we've timed out... We will 5093 // interrupt the process here. Depending on what we were asked to do 5094 // we will either exit, or try with all threads running for the same 5095 // timeout. 5096 5097 if (log) { 5098 if (options.GetTryAllThreads()) { 5099 if (before_first_timeout) { 5100 LLDB_LOG(log, 5101 "Running function with one thread timeout timed out."); 5102 } else 5103 LLDB_LOG(log, "Restarting function with all threads enabled and " 5104 "timeout: {0} timed out, abandoning execution.", 5105 timeout); 5106 } else 5107 LLDB_LOG(log, "Running function with timeout: {0} timed out, " 5108 "abandoning execution.", 5109 timeout); 5110 } 5111 5112 // It is possible that between the time we issued the Halt, and we get 5113 // around to calling Halt the target could have stopped. That's fine, 5114 // Halt will figure that out and send the appropriate Stopped event. 5115 // BUT it is also possible that we stopped & restarted (e.g. hit a 5116 // signal with "stop" set to false.) In 5117 // that case, we'll get the stopped & restarted event, and we should go 5118 // back to waiting for the Halt's stopped event. That's what this 5119 // while loop does. 5120 5121 bool back_to_top = true; 5122 uint32_t try_halt_again = 0; 5123 bool do_halt = true; 5124 const uint32_t num_retries = 5; 5125 while (try_halt_again < num_retries) { 5126 Status halt_error; 5127 if (do_halt) { 5128 if (log) 5129 log->Printf("Process::RunThreadPlan(): Running Halt."); 5130 const bool clear_thread_plans = false; 5131 const bool use_run_lock = false; 5132 Halt(clear_thread_plans, use_run_lock); 5133 } 5134 if (halt_error.Success()) { 5135 if (log) 5136 log->PutCString("Process::RunThreadPlan(): Halt succeeded."); 5137 5138 got_event = 5139 listener_sp->GetEvent(event_sp, std::chrono::milliseconds(500)); 5140 5141 if (got_event) { 5142 stop_state = 5143 Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 5144 if (log) { 5145 log->Printf("Process::RunThreadPlan(): Stopped with event: %s", 5146 StateAsCString(stop_state)); 5147 if (stop_state == lldb::eStateStopped && 5148 Process::ProcessEventData::GetInterruptedFromEvent( 5149 event_sp.get())) 5150 log->PutCString(" Event was the Halt interruption event."); 5151 } 5152 5153 if (stop_state == lldb::eStateStopped) { 5154 if (Process::ProcessEventData::GetRestartedFromEvent( 5155 event_sp.get())) { 5156 if (log) 5157 log->PutCString("Process::RunThreadPlan(): Went to halt " 5158 "but got a restarted event, there must be " 5159 "an un-restarted stopped event so try " 5160 "again... " 5161 "Exiting wait loop."); 5162 try_halt_again++; 5163 do_halt = false; 5164 continue; 5165 } 5166 5167 // Between the time we initiated the Halt and the time we 5168 // delivered it, the process could have already finished its 5169 // job. Check that here: 5170 const bool handle_interrupts = false; 5171 if (auto result = HandleStoppedEvent( 5172 *thread, thread_plan_sp, thread_plan_restorer, event_sp, 5173 event_to_broadcast_sp, options, handle_interrupts)) { 5174 return_value = *result; 5175 back_to_top = false; 5176 break; 5177 } 5178 5179 if (!options.GetTryAllThreads()) { 5180 if (log) 5181 log->PutCString("Process::RunThreadPlan(): try_all_threads " 5182 "was false, we stopped so now we're " 5183 "quitting."); 5184 return_value = eExpressionInterrupted; 5185 back_to_top = false; 5186 break; 5187 } 5188 5189 if (before_first_timeout) { 5190 // Set all the other threads to run, and return to the top of 5191 // the loop, which will continue; 5192 before_first_timeout = false; 5193 thread_plan_sp->SetStopOthers(false); 5194 if (log) 5195 log->PutCString( 5196 "Process::RunThreadPlan(): about to resume."); 5197 5198 back_to_top = true; 5199 break; 5200 } else { 5201 // Running all threads failed, so return Interrupted. 5202 if (log) 5203 log->PutCString("Process::RunThreadPlan(): running all " 5204 "threads timed out."); 5205 return_value = eExpressionInterrupted; 5206 back_to_top = false; 5207 break; 5208 } 5209 } 5210 } else { 5211 if (log) 5212 log->PutCString("Process::RunThreadPlan(): halt said it " 5213 "succeeded, but I got no event. " 5214 "I'm getting out of here passing Interrupted."); 5215 return_value = eExpressionInterrupted; 5216 back_to_top = false; 5217 break; 5218 } 5219 } else { 5220 try_halt_again++; 5221 continue; 5222 } 5223 } 5224 5225 if (!back_to_top || try_halt_again > num_retries) 5226 break; 5227 else 5228 continue; 5229 } 5230 } // END WAIT LOOP 5231 5232 // If we had to start up a temporary private state thread to run this 5233 // thread plan, shut it down now. 5234 if (backup_private_state_thread.IsJoinable()) { 5235 StopPrivateStateThread(); 5236 Status error; 5237 m_private_state_thread = backup_private_state_thread; 5238 if (stopper_base_plan_sp) { 5239 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp); 5240 } 5241 if (old_state != eStateInvalid) 5242 m_public_state.SetValueNoLock(old_state); 5243 } 5244 5245 if (return_value != eExpressionCompleted && log) { 5246 // Print a backtrace into the log so we can figure out where we are: 5247 StreamString s; 5248 s.PutCString("Thread state after unsuccessful completion: \n"); 5249 thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX); 5250 log->PutString(s.GetString()); 5251 } 5252 // Restore the thread state if we are going to discard the plan execution. 5253 // There are three cases where this could happen: 1) The execution 5254 // successfully completed 2) We hit a breakpoint, and ignore_breakpoints 5255 // was true 3) We got some other error, and discard_on_error was true 5256 bool should_unwind = (return_value == eExpressionInterrupted && 5257 options.DoesUnwindOnError()) || 5258 (return_value == eExpressionHitBreakpoint && 5259 options.DoesIgnoreBreakpoints()); 5260 5261 if (return_value == eExpressionCompleted || should_unwind) { 5262 thread_plan_sp->RestoreThreadState(); 5263 } 5264 5265 // Now do some processing on the results of the run: 5266 if (return_value == eExpressionInterrupted || 5267 return_value == eExpressionHitBreakpoint) { 5268 if (log) { 5269 StreamString s; 5270 if (event_sp) 5271 event_sp->Dump(&s); 5272 else { 5273 log->PutCString("Process::RunThreadPlan(): Stop event that " 5274 "interrupted us is NULL."); 5275 } 5276 5277 StreamString ts; 5278 5279 const char *event_explanation = nullptr; 5280 5281 do { 5282 if (!event_sp) { 5283 event_explanation = "<no event>"; 5284 break; 5285 } else if (event_sp->GetType() == eBroadcastBitInterrupt) { 5286 event_explanation = "<user interrupt>"; 5287 break; 5288 } else { 5289 const Process::ProcessEventData *event_data = 5290 Process::ProcessEventData::GetEventDataFromEvent( 5291 event_sp.get()); 5292 5293 if (!event_data) { 5294 event_explanation = "<no event data>"; 5295 break; 5296 } 5297 5298 Process *process = event_data->GetProcessSP().get(); 5299 5300 if (!process) { 5301 event_explanation = "<no process>"; 5302 break; 5303 } 5304 5305 ThreadList &thread_list = process->GetThreadList(); 5306 5307 uint32_t num_threads = thread_list.GetSize(); 5308 uint32_t thread_index; 5309 5310 ts.Printf("<%u threads> ", num_threads); 5311 5312 for (thread_index = 0; thread_index < num_threads; ++thread_index) { 5313 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get(); 5314 5315 if (!thread) { 5316 ts.Printf("<?> "); 5317 continue; 5318 } 5319 5320 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID()); 5321 RegisterContext *register_context = 5322 thread->GetRegisterContext().get(); 5323 5324 if (register_context) 5325 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC()); 5326 else 5327 ts.Printf("[ip unknown] "); 5328 5329 // Show the private stop info here, the public stop info will be 5330 // from the last natural stop. 5331 lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo(); 5332 if (stop_info_sp) { 5333 const char *stop_desc = stop_info_sp->GetDescription(); 5334 if (stop_desc) 5335 ts.PutCString(stop_desc); 5336 } 5337 ts.Printf(">"); 5338 } 5339 5340 event_explanation = ts.GetData(); 5341 } 5342 } while (0); 5343 5344 if (event_explanation) 5345 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", 5346 s.GetData(), event_explanation); 5347 else 5348 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", 5349 s.GetData()); 5350 } 5351 5352 if (should_unwind) { 5353 if (log) 5354 log->Printf("Process::RunThreadPlan: ExecutionInterrupted - " 5355 "discarding thread plans up to %p.", 5356 static_cast<void *>(thread_plan_sp.get())); 5357 thread->DiscardThreadPlansUpToPlan(thread_plan_sp); 5358 } else { 5359 if (log) 5360 log->Printf("Process::RunThreadPlan: ExecutionInterrupted - for " 5361 "plan: %p not discarding.", 5362 static_cast<void *>(thread_plan_sp.get())); 5363 } 5364 } else if (return_value == eExpressionSetupError) { 5365 if (log) 5366 log->PutCString("Process::RunThreadPlan(): execution set up error."); 5367 5368 if (options.DoesUnwindOnError()) { 5369 thread->DiscardThreadPlansUpToPlan(thread_plan_sp); 5370 } 5371 } else { 5372 if (thread->IsThreadPlanDone(thread_plan_sp.get())) { 5373 if (log) 5374 log->PutCString("Process::RunThreadPlan(): thread plan is done"); 5375 return_value = eExpressionCompleted; 5376 } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) { 5377 if (log) 5378 log->PutCString( 5379 "Process::RunThreadPlan(): thread plan was discarded"); 5380 return_value = eExpressionDiscarded; 5381 } else { 5382 if (log) 5383 log->PutCString( 5384 "Process::RunThreadPlan(): thread plan stopped in mid course"); 5385 if (options.DoesUnwindOnError() && thread_plan_sp) { 5386 if (log) 5387 log->PutCString("Process::RunThreadPlan(): discarding thread plan " 5388 "'cause unwind_on_error is set."); 5389 thread->DiscardThreadPlansUpToPlan(thread_plan_sp); 5390 } 5391 } 5392 } 5393 5394 // Thread we ran the function in may have gone away because we ran the 5395 // target Check that it's still there, and if it is put it back in the 5396 // context. Also restore the frame in the context if it is still present. 5397 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get(); 5398 if (thread) { 5399 exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id)); 5400 } 5401 5402 // Also restore the current process'es selected frame & thread, since this 5403 // function calling may be done behind the user's back. 5404 5405 if (selected_tid != LLDB_INVALID_THREAD_ID) { 5406 if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) && 5407 selected_stack_id.IsValid()) { 5408 // We were able to restore the selected thread, now restore the frame: 5409 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex()); 5410 StackFrameSP old_frame_sp = 5411 GetThreadList().GetSelectedThread()->GetFrameWithStackID( 5412 selected_stack_id); 5413 if (old_frame_sp) 5414 GetThreadList().GetSelectedThread()->SetSelectedFrame( 5415 old_frame_sp.get()); 5416 } 5417 } 5418 } 5419 5420 // If the process exited during the run of the thread plan, notify everyone. 5421 5422 if (event_to_broadcast_sp) { 5423 if (log) 5424 log->PutCString("Process::RunThreadPlan(): rebroadcasting event."); 5425 BroadcastEvent(event_to_broadcast_sp); 5426 } 5427 5428 return return_value; 5429 } 5430 5431 const char *Process::ExecutionResultAsCString(ExpressionResults result) { 5432 const char *result_name; 5433 5434 switch (result) { 5435 case eExpressionCompleted: 5436 result_name = "eExpressionCompleted"; 5437 break; 5438 case eExpressionDiscarded: 5439 result_name = "eExpressionDiscarded"; 5440 break; 5441 case eExpressionInterrupted: 5442 result_name = "eExpressionInterrupted"; 5443 break; 5444 case eExpressionHitBreakpoint: 5445 result_name = "eExpressionHitBreakpoint"; 5446 break; 5447 case eExpressionSetupError: 5448 result_name = "eExpressionSetupError"; 5449 break; 5450 case eExpressionParseError: 5451 result_name = "eExpressionParseError"; 5452 break; 5453 case eExpressionResultUnavailable: 5454 result_name = "eExpressionResultUnavailable"; 5455 break; 5456 case eExpressionTimedOut: 5457 result_name = "eExpressionTimedOut"; 5458 break; 5459 case eExpressionStoppedForDebug: 5460 result_name = "eExpressionStoppedForDebug"; 5461 break; 5462 } 5463 return result_name; 5464 } 5465 5466 void Process::GetStatus(Stream &strm) { 5467 const StateType state = GetState(); 5468 if (StateIsStoppedState(state, false)) { 5469 if (state == eStateExited) { 5470 int exit_status = GetExitStatus(); 5471 const char *exit_description = GetExitDescription(); 5472 strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n", 5473 GetID(), exit_status, exit_status, 5474 exit_description ? exit_description : ""); 5475 } else { 5476 if (state == eStateConnected) 5477 strm.Printf("Connected to remote target.\n"); 5478 else 5479 strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state)); 5480 } 5481 } else { 5482 strm.Printf("Process %" PRIu64 " is running.\n", GetID()); 5483 } 5484 } 5485 5486 size_t Process::GetThreadStatus(Stream &strm, 5487 bool only_threads_with_stop_reason, 5488 uint32_t start_frame, uint32_t num_frames, 5489 uint32_t num_frames_with_source, 5490 bool stop_format) { 5491 size_t num_thread_infos_dumped = 0; 5492 5493 // You can't hold the thread list lock while calling Thread::GetStatus. That 5494 // very well might run code (e.g. if we need it to get return values or 5495 // arguments.) For that to work the process has to be able to acquire it. 5496 // So instead copy the thread ID's, and look them up one by one: 5497 5498 uint32_t num_threads; 5499 std::vector<lldb::tid_t> thread_id_array; 5500 // Scope for thread list locker; 5501 { 5502 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex()); 5503 ThreadList &curr_thread_list = GetThreadList(); 5504 num_threads = curr_thread_list.GetSize(); 5505 uint32_t idx; 5506 thread_id_array.resize(num_threads); 5507 for (idx = 0; idx < num_threads; ++idx) 5508 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID(); 5509 } 5510 5511 for (uint32_t i = 0; i < num_threads; i++) { 5512 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i])); 5513 if (thread_sp) { 5514 if (only_threads_with_stop_reason) { 5515 StopInfoSP stop_info_sp = thread_sp->GetStopInfo(); 5516 if (!stop_info_sp || !stop_info_sp->IsValid()) 5517 continue; 5518 } 5519 thread_sp->GetStatus(strm, start_frame, num_frames, 5520 num_frames_with_source, 5521 stop_format); 5522 ++num_thread_infos_dumped; 5523 } else { 5524 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 5525 if (log) 5526 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64 5527 " vanished while running Thread::GetStatus."); 5528 } 5529 } 5530 return num_thread_infos_dumped; 5531 } 5532 5533 void Process::AddInvalidMemoryRegion(const LoadRange ®ion) { 5534 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize()); 5535 } 5536 5537 bool Process::RemoveInvalidMemoryRange(const LoadRange ®ion) { 5538 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), 5539 region.GetByteSize()); 5540 } 5541 5542 void Process::AddPreResumeAction(PreResumeActionCallback callback, 5543 void *baton) { 5544 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton)); 5545 } 5546 5547 bool Process::RunPreResumeActions() { 5548 bool result = true; 5549 while (!m_pre_resume_actions.empty()) { 5550 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back(); 5551 m_pre_resume_actions.pop_back(); 5552 bool this_result = action.callback(action.baton); 5553 if (result) 5554 result = this_result; 5555 } 5556 return result; 5557 } 5558 5559 void Process::ClearPreResumeActions() { m_pre_resume_actions.clear(); } 5560 5561 void Process::ClearPreResumeAction(PreResumeActionCallback callback, void *baton) 5562 { 5563 PreResumeCallbackAndBaton element(callback, baton); 5564 auto found_iter = std::find(m_pre_resume_actions.begin(), m_pre_resume_actions.end(), element); 5565 if (found_iter != m_pre_resume_actions.end()) 5566 { 5567 m_pre_resume_actions.erase(found_iter); 5568 } 5569 } 5570 5571 ProcessRunLock &Process::GetRunLock() { 5572 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) 5573 return m_private_run_lock; 5574 else 5575 return m_public_run_lock; 5576 } 5577 5578 void Process::Flush() { 5579 m_thread_list.Flush(); 5580 m_extended_thread_list.Flush(); 5581 m_extended_thread_stop_id = 0; 5582 m_queue_list.Clear(); 5583 m_queue_list_stop_id = 0; 5584 } 5585 5586 void Process::DidExec() { 5587 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 5588 if (log) 5589 log->Printf("Process::%s()", __FUNCTION__); 5590 5591 Target &target = GetTarget(); 5592 target.CleanupProcess(); 5593 target.ClearModules(false); 5594 m_dynamic_checkers_up.reset(); 5595 m_abi_sp.reset(); 5596 m_system_runtime_up.reset(); 5597 m_os_up.reset(); 5598 m_dyld_up.reset(); 5599 m_jit_loaders_up.reset(); 5600 m_image_tokens.clear(); 5601 m_allocated_memory_cache.Clear(); 5602 m_language_runtimes.clear(); 5603 m_instrumentation_runtimes.clear(); 5604 m_thread_list.DiscardThreadPlans(); 5605 m_memory_cache.Clear(true); 5606 DoDidExec(); 5607 CompleteAttach(); 5608 // Flush the process (threads and all stack frames) after running 5609 // CompleteAttach() in case the dynamic loader loaded things in new 5610 // locations. 5611 Flush(); 5612 5613 // After we figure out what was loaded/unloaded in CompleteAttach, we need to 5614 // let the target know so it can do any cleanup it needs to. 5615 target.DidExec(); 5616 } 5617 5618 addr_t Process::ResolveIndirectFunction(const Address *address, Status &error) { 5619 if (address == nullptr) { 5620 error.SetErrorString("Invalid address argument"); 5621 return LLDB_INVALID_ADDRESS; 5622 } 5623 5624 addr_t function_addr = LLDB_INVALID_ADDRESS; 5625 5626 addr_t addr = address->GetLoadAddress(&GetTarget()); 5627 std::map<addr_t, addr_t>::const_iterator iter = 5628 m_resolved_indirect_addresses.find(addr); 5629 if (iter != m_resolved_indirect_addresses.end()) { 5630 function_addr = (*iter).second; 5631 } else { 5632 if (!InferiorCall(this, address, function_addr)) { 5633 Symbol *symbol = address->CalculateSymbolContextSymbol(); 5634 error.SetErrorStringWithFormat( 5635 "Unable to call resolver for indirect function %s", 5636 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>"); 5637 function_addr = LLDB_INVALID_ADDRESS; 5638 } else { 5639 m_resolved_indirect_addresses.insert( 5640 std::pair<addr_t, addr_t>(addr, function_addr)); 5641 } 5642 } 5643 return function_addr; 5644 } 5645 5646 void Process::ModulesDidLoad(ModuleList &module_list) { 5647 SystemRuntime *sys_runtime = GetSystemRuntime(); 5648 if (sys_runtime) { 5649 sys_runtime->ModulesDidLoad(module_list); 5650 } 5651 5652 GetJITLoaders().ModulesDidLoad(module_list); 5653 5654 // Give runtimes a chance to be created. 5655 InstrumentationRuntime::ModulesDidLoad(module_list, this, 5656 m_instrumentation_runtimes); 5657 5658 // Tell runtimes about new modules. 5659 for (auto pos = m_instrumentation_runtimes.begin(); 5660 pos != m_instrumentation_runtimes.end(); ++pos) { 5661 InstrumentationRuntimeSP runtime = pos->second; 5662 runtime->ModulesDidLoad(module_list); 5663 } 5664 5665 // Let any language runtimes we have already created know about the modules 5666 // that loaded. 5667 5668 // Iterate over a copy of this language runtime list in case the language 5669 // runtime ModulesDidLoad somehow causes the language runtime to be 5670 // unloaded. 5671 LanguageRuntimeCollection language_runtimes(m_language_runtimes); 5672 for (const auto &pair : language_runtimes) { 5673 // We must check language_runtime_sp to make sure it is not nullptr as we 5674 // might cache the fact that we didn't have a language runtime for a 5675 // language. 5676 LanguageRuntimeSP language_runtime_sp = pair.second; 5677 if (language_runtime_sp) 5678 language_runtime_sp->ModulesDidLoad(module_list); 5679 } 5680 5681 // If we don't have an operating system plug-in, try to load one since 5682 // loading shared libraries might cause a new one to try and load 5683 if (!m_os_up) 5684 LoadOperatingSystemPlugin(false); 5685 5686 // Give structured-data plugins a chance to see the modified modules. 5687 for (auto pair : m_structured_data_plugin_map) { 5688 if (pair.second) 5689 pair.second->ModulesDidLoad(*this, module_list); 5690 } 5691 } 5692 5693 void Process::PrintWarning(uint64_t warning_type, const void *repeat_key, 5694 const char *fmt, ...) { 5695 bool print_warning = true; 5696 5697 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream(); 5698 if (!stream_sp) 5699 return; 5700 if (warning_type == eWarningsOptimization && !GetWarningsOptimization()) { 5701 return; 5702 } 5703 5704 if (repeat_key != nullptr) { 5705 WarningsCollection::iterator it = m_warnings_issued.find(warning_type); 5706 if (it == m_warnings_issued.end()) { 5707 m_warnings_issued[warning_type] = WarningsPointerSet(); 5708 m_warnings_issued[warning_type].insert(repeat_key); 5709 } else { 5710 if (it->second.find(repeat_key) != it->second.end()) { 5711 print_warning = false; 5712 } else { 5713 it->second.insert(repeat_key); 5714 } 5715 } 5716 } 5717 5718 if (print_warning) { 5719 va_list args; 5720 va_start(args, fmt); 5721 stream_sp->PrintfVarArg(fmt, args); 5722 va_end(args); 5723 } 5724 } 5725 5726 void Process::PrintWarningOptimization(const SymbolContext &sc) { 5727 if (GetWarningsOptimization() && sc.module_sp && 5728 !sc.module_sp->GetFileSpec().GetFilename().IsEmpty() && sc.function && 5729 sc.function->GetIsOptimized()) { 5730 PrintWarning(Process::Warnings::eWarningsOptimization, sc.module_sp.get(), 5731 "%s was compiled with optimization - stepping may behave " 5732 "oddly; variables may not be available.\n", 5733 sc.module_sp->GetFileSpec().GetFilename().GetCString()); 5734 } 5735 } 5736 5737 bool Process::GetProcessInfo(ProcessInstanceInfo &info) { 5738 info.Clear(); 5739 5740 PlatformSP platform_sp = GetTarget().GetPlatform(); 5741 if (!platform_sp) 5742 return false; 5743 5744 return platform_sp->GetProcessInfo(GetID(), info); 5745 } 5746 5747 ThreadCollectionSP Process::GetHistoryThreads(lldb::addr_t addr) { 5748 ThreadCollectionSP threads; 5749 5750 const MemoryHistorySP &memory_history = 5751 MemoryHistory::FindPlugin(shared_from_this()); 5752 5753 if (!memory_history) { 5754 return threads; 5755 } 5756 5757 threads = std::make_shared<ThreadCollection>( 5758 memory_history->GetHistoryThreads(addr)); 5759 5760 return threads; 5761 } 5762 5763 InstrumentationRuntimeSP 5764 Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type) { 5765 InstrumentationRuntimeCollection::iterator pos; 5766 pos = m_instrumentation_runtimes.find(type); 5767 if (pos == m_instrumentation_runtimes.end()) { 5768 return InstrumentationRuntimeSP(); 5769 } else 5770 return (*pos).second; 5771 } 5772 5773 bool Process::GetModuleSpec(const FileSpec &module_file_spec, 5774 const ArchSpec &arch, ModuleSpec &module_spec) { 5775 module_spec.Clear(); 5776 return false; 5777 } 5778 5779 size_t Process::AddImageToken(lldb::addr_t image_ptr) { 5780 m_image_tokens.push_back(image_ptr); 5781 return m_image_tokens.size() - 1; 5782 } 5783 5784 lldb::addr_t Process::GetImagePtrFromToken(size_t token) const { 5785 if (token < m_image_tokens.size()) 5786 return m_image_tokens[token]; 5787 return LLDB_INVALID_IMAGE_TOKEN; 5788 } 5789 5790 void Process::ResetImageToken(size_t token) { 5791 if (token < m_image_tokens.size()) 5792 m_image_tokens[token] = LLDB_INVALID_IMAGE_TOKEN; 5793 } 5794 5795 Address 5796 Process::AdvanceAddressToNextBranchInstruction(Address default_stop_addr, 5797 AddressRange range_bounds) { 5798 Target &target = GetTarget(); 5799 DisassemblerSP disassembler_sp; 5800 InstructionList *insn_list = nullptr; 5801 5802 Address retval = default_stop_addr; 5803 5804 if (!target.GetUseFastStepping()) 5805 return retval; 5806 if (!default_stop_addr.IsValid()) 5807 return retval; 5808 5809 ExecutionContext exe_ctx(this); 5810 const char *plugin_name = nullptr; 5811 const char *flavor = nullptr; 5812 const bool prefer_file_cache = true; 5813 disassembler_sp = Disassembler::DisassembleRange( 5814 target.GetArchitecture(), plugin_name, flavor, exe_ctx, range_bounds, 5815 prefer_file_cache); 5816 if (disassembler_sp) 5817 insn_list = &disassembler_sp->GetInstructionList(); 5818 5819 if (insn_list == nullptr) { 5820 return retval; 5821 } 5822 5823 size_t insn_offset = 5824 insn_list->GetIndexOfInstructionAtAddress(default_stop_addr); 5825 if (insn_offset == UINT32_MAX) { 5826 return retval; 5827 } 5828 5829 uint32_t branch_index = 5830 insn_list->GetIndexOfNextBranchInstruction(insn_offset, target); 5831 if (branch_index == UINT32_MAX) { 5832 return retval; 5833 } 5834 5835 if (branch_index > insn_offset) { 5836 Address next_branch_insn_address = 5837 insn_list->GetInstructionAtIndex(branch_index)->GetAddress(); 5838 if (next_branch_insn_address.IsValid() && 5839 range_bounds.ContainsFileAddress(next_branch_insn_address)) { 5840 retval = next_branch_insn_address; 5841 } 5842 } 5843 5844 return retval; 5845 } 5846 5847 Status 5848 Process::GetMemoryRegions(lldb_private::MemoryRegionInfos ®ion_list) { 5849 5850 Status error; 5851 5852 lldb::addr_t range_end = 0; 5853 5854 region_list.clear(); 5855 do { 5856 lldb_private::MemoryRegionInfo region_info; 5857 error = GetMemoryRegionInfo(range_end, region_info); 5858 // GetMemoryRegionInfo should only return an error if it is unimplemented. 5859 if (error.Fail()) { 5860 region_list.clear(); 5861 break; 5862 } 5863 5864 range_end = region_info.GetRange().GetRangeEnd(); 5865 if (region_info.GetMapped() == MemoryRegionInfo::eYes) { 5866 region_list.push_back(std::move(region_info)); 5867 } 5868 } while (range_end != LLDB_INVALID_ADDRESS); 5869 5870 return error; 5871 } 5872 5873 Status 5874 Process::ConfigureStructuredData(ConstString type_name, 5875 const StructuredData::ObjectSP &config_sp) { 5876 // If you get this, the Process-derived class needs to implement a method to 5877 // enable an already-reported asynchronous structured data feature. See 5878 // ProcessGDBRemote for an example implementation over gdb-remote. 5879 return Status("unimplemented"); 5880 } 5881 5882 void Process::MapSupportedStructuredDataPlugins( 5883 const StructuredData::Array &supported_type_names) { 5884 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 5885 5886 // Bail out early if there are no type names to map. 5887 if (supported_type_names.GetSize() == 0) { 5888 if (log) 5889 log->Printf("Process::%s(): no structured data types supported", 5890 __FUNCTION__); 5891 return; 5892 } 5893 5894 // Convert StructuredData type names to ConstString instances. 5895 std::set<ConstString> const_type_names; 5896 5897 if (log) 5898 log->Printf("Process::%s(): the process supports the following async " 5899 "structured data types:", 5900 __FUNCTION__); 5901 5902 supported_type_names.ForEach( 5903 [&const_type_names, &log](StructuredData::Object *object) { 5904 if (!object) { 5905 // Invalid - shouldn't be null objects in the array. 5906 return false; 5907 } 5908 5909 auto type_name = object->GetAsString(); 5910 if (!type_name) { 5911 // Invalid format - all type names should be strings. 5912 return false; 5913 } 5914 5915 const_type_names.insert(ConstString(type_name->GetValue())); 5916 LLDB_LOG(log, "- {0}", type_name->GetValue()); 5917 return true; 5918 }); 5919 5920 // For each StructuredDataPlugin, if the plugin handles any of the types in 5921 // the supported_type_names, map that type name to that plugin. Stop when 5922 // we've consumed all the type names. 5923 // FIXME: should we return an error if there are type names nobody 5924 // supports? 5925 for (uint32_t plugin_index = 0; !const_type_names.empty(); plugin_index++) { 5926 auto create_instance = 5927 PluginManager::GetStructuredDataPluginCreateCallbackAtIndex( 5928 plugin_index); 5929 if (!create_instance) 5930 break; 5931 5932 // Create the plugin. 5933 StructuredDataPluginSP plugin_sp = (*create_instance)(*this); 5934 if (!plugin_sp) { 5935 // This plugin doesn't think it can work with the process. Move on to the 5936 // next. 5937 continue; 5938 } 5939 5940 // For any of the remaining type names, map any that this plugin supports. 5941 std::vector<ConstString> names_to_remove; 5942 for (auto &type_name : const_type_names) { 5943 if (plugin_sp->SupportsStructuredDataType(type_name)) { 5944 m_structured_data_plugin_map.insert( 5945 std::make_pair(type_name, plugin_sp)); 5946 names_to_remove.push_back(type_name); 5947 if (log) 5948 log->Printf("Process::%s(): using plugin %s for type name " 5949 "%s", 5950 __FUNCTION__, plugin_sp->GetPluginName().GetCString(), 5951 type_name.GetCString()); 5952 } 5953 } 5954 5955 // Remove the type names that were consumed by this plugin. 5956 for (auto &type_name : names_to_remove) 5957 const_type_names.erase(type_name); 5958 } 5959 } 5960 5961 bool Process::RouteAsyncStructuredData( 5962 const StructuredData::ObjectSP object_sp) { 5963 // Nothing to do if there's no data. 5964 if (!object_sp) 5965 return false; 5966 5967 // The contract is this must be a dictionary, so we can look up the routing 5968 // key via the top-level 'type' string value within the dictionary. 5969 StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary(); 5970 if (!dictionary) 5971 return false; 5972 5973 // Grab the async structured type name (i.e. the feature/plugin name). 5974 ConstString type_name; 5975 if (!dictionary->GetValueForKeyAsString("type", type_name)) 5976 return false; 5977 5978 // Check if there's a plugin registered for this type name. 5979 auto find_it = m_structured_data_plugin_map.find(type_name); 5980 if (find_it == m_structured_data_plugin_map.end()) { 5981 // We don't have a mapping for this structured data type. 5982 return false; 5983 } 5984 5985 // Route the structured data to the plugin. 5986 find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp); 5987 return true; 5988 } 5989 5990 Status Process::UpdateAutomaticSignalFiltering() { 5991 // Default implementation does nothign. 5992 // No automatic signal filtering to speak of. 5993 return Status(); 5994 } 5995 5996 UtilityFunction *Process::GetLoadImageUtilityFunction( 5997 Platform *platform, 5998 llvm::function_ref<std::unique_ptr<UtilityFunction>()> factory) { 5999 if (platform != GetTarget().GetPlatform().get()) 6000 return nullptr; 6001 std::call_once(m_dlopen_utility_func_flag_once, 6002 [&] { m_dlopen_utility_func_up = factory(); }); 6003 return m_dlopen_utility_func_up.get(); 6004 } 6005