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