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