diff options
Diffstat (limited to 'lldb/source')
24 files changed, 12 insertions, 3882 deletions
diff --git a/lldb/source/API/CMakeLists.txt b/lldb/source/API/CMakeLists.txt index 3dba1b08703..8e9e1fb2278 100644 --- a/lldb/source/API/CMakeLists.txt +++ b/lldb/source/API/CMakeLists.txt @@ -47,7 +47,6 @@ add_lldb_library(liblldb SHARED SBSourceManager.cpp SBStream.cpp SBStringList.cpp - SBStructuredData.cpp SBSymbol.cpp SBSymbolContext.cpp SBSymbolContextList.cpp diff --git a/lldb/source/API/SBDebugger.cpp b/lldb/source/API/SBDebugger.cpp index cc55230d8b3..3493ad507a7 100644 --- a/lldb/source/API/SBDebugger.cpp +++ b/lldb/source/API/SBDebugger.cpp @@ -491,7 +491,7 @@ SBDebugger::HandleProcessEvent (const SBProcess &process, const SBEvent &event, if (err != nullptr) ::fwrite (stdio_buffer, 1, len, err); } - + if (event_type & Process::eBroadcastBitStateChanged) { StateType event_state = SBProcess::GetStateFromEvent (event); diff --git a/lldb/source/API/SBProcess.cpp b/lldb/source/API/SBProcess.cpp index 9b8ac8461ac..50211bfde32 100644 --- a/lldb/source/API/SBProcess.cpp +++ b/lldb/source/API/SBProcess.cpp @@ -39,7 +39,6 @@ #include "lldb/API/SBFileSpec.h" #include "lldb/API/SBMemoryRegionInfo.h" #include "lldb/API/SBMemoryRegionInfoList.h" -#include "lldb/API/SBStructuredData.h" #include "lldb/API/SBThread.h" #include "lldb/API/SBThreadCollection.h" #include "lldb/API/SBStream.h" @@ -1030,16 +1029,8 @@ SBProcess::GetRestartedReasonAtIndexFromEvent (const lldb::SBEvent &event, size_ SBProcess SBProcess::GetProcessFromEvent (const SBEvent &event) { - ProcessSP process_sp = - Process::ProcessEventData::GetProcessFromEvent (event.get()); - if (!process_sp) - { - // StructuredData events also know the process they come from. - // Try that. - process_sp = EventDataStructuredData::GetProcessFromEvent(event.get()); - } - - return SBProcess(process_sp); + SBProcess process(Process::ProcessEventData::GetProcessFromEvent (event.get())); + return process; } bool @@ -1048,26 +1039,10 @@ SBProcess::GetInterruptedFromEvent (const SBEvent &event) return Process::ProcessEventData::GetInterruptedFromEvent(event.get()); } -lldb::SBStructuredData -SBProcess::GetStructuredDataFromEvent (const lldb::SBEvent &event) -{ - return SBStructuredData(event.GetSP()); -} - bool SBProcess::EventIsProcessEvent (const SBEvent &event) { - return (event.GetBroadcasterClass() == SBProcess::GetBroadcasterClass()) && - !EventIsStructuredDataEvent (event); -} - -bool -SBProcess::EventIsStructuredDataEvent (const lldb::SBEvent &event) -{ - EventSP event_sp = event.GetSP(); - EventData *event_data = event_sp ? event_sp->GetData() : nullptr; - return event_data && - (event_data->GetFlavor() == EventDataStructuredData::GetFlavorString()); + return event.GetBroadcasterClass() == SBProcess::GetBroadcasterClass(); } SBBroadcaster diff --git a/lldb/source/API/SBStructuredData.cpp b/lldb/source/API/SBStructuredData.cpp deleted file mode 100644 index 5e4417484f0..00000000000 --- a/lldb/source/API/SBStructuredData.cpp +++ /dev/null @@ -1,165 +0,0 @@ -//===-- SBStructuredData.cpp ------------------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#include "lldb/API/SBStructuredData.h" - -#include "lldb/API/SBStream.h" -#include "lldb/Core/Error.h" -#include "lldb/Core/Event.h" -#include "lldb/Core/Stream.h" -#include "lldb/Core/StructuredData.h" -#include "lldb/Target/StructuredDataPlugin.h" - -using namespace lldb; -using namespace lldb_private; - -#pragma mark -- -#pragma mark Impl - -class SBStructuredData::Impl -{ -public: - - Impl() : - m_plugin_wp(), - m_data_sp() - { - } - - Impl(const Impl &rhs) = default; - - Impl(const EventSP &event_sp) : - m_plugin_wp(EventDataStructuredData::GetPluginFromEvent(event_sp.get())), - m_data_sp(EventDataStructuredData::GetObjectFromEvent(event_sp.get())) - { - } - - ~Impl() = default; - - Impl& - operator =(const Impl &rhs) = default; - - bool - IsValid() const - { - return m_data_sp.get() != nullptr; - } - - void - Clear() - { - m_plugin_wp.reset(); - m_data_sp.reset(); - } - - SBError - GetAsJSON(lldb::SBStream &stream) const - { - SBError sb_error; - - if (!m_data_sp) - { - sb_error.SetErrorString("No structured data."); - return sb_error; - } - - m_data_sp->Dump(stream.ref()); - return sb_error; - } - - lldb::SBError - GetDescription(lldb::SBStream &stream) const - { - SBError sb_error; - - if (!m_data_sp) - { - sb_error.SetErrorString("Cannot pretty print structured data: " - "no data to print."); - return sb_error; - } - - // Grab the plugin. - auto plugin_sp = StructuredDataPluginSP(m_plugin_wp); - if (!plugin_sp) - { - sb_error.SetErrorString("Cannot pretty print structured data: " - "plugin doesn't exist."); - return sb_error; - } - - // Get the data's description. - auto error = plugin_sp->GetDescription(m_data_sp, stream.ref()); - if (!error.Success()) - sb_error.SetError(error); - - return sb_error; - } - -private: - - StructuredDataPluginWP m_plugin_wp; - StructuredData::ObjectSP m_data_sp; - -}; - -#pragma mark -- -#pragma mark SBStructuredData - - -SBStructuredData::SBStructuredData() : - m_impl_up(new Impl()) -{ -} - -SBStructuredData::SBStructuredData(const lldb::SBStructuredData &rhs) : - m_impl_up(new Impl(*rhs.m_impl_up.get())) -{ -} - -SBStructuredData::SBStructuredData(const lldb::EventSP &event_sp) : - m_impl_up(new Impl(event_sp)) -{ -} - -SBStructuredData::~SBStructuredData() -{ -} - -SBStructuredData & -SBStructuredData::operator =(const lldb::SBStructuredData &rhs) -{ - *m_impl_up = *rhs.m_impl_up; - return *this; -} - -bool -SBStructuredData::IsValid() const -{ - return m_impl_up->IsValid(); -} - -void -SBStructuredData::Clear() -{ - m_impl_up->Clear(); -} - -SBError -SBStructuredData::GetAsJSON(lldb::SBStream &stream) const -{ - return m_impl_up->GetAsJSON(stream); -} - -lldb::SBError -SBStructuredData::GetDescription(lldb::SBStream &stream) const -{ - return m_impl_up->GetDescription(stream); -} - diff --git a/lldb/source/API/SystemInitializerFull.cpp b/lldb/source/API/SystemInitializerFull.cpp index 00cbb5dee75..8644757229c 100644 --- a/lldb/source/API/SystemInitializerFull.cpp +++ b/lldb/source/API/SystemInitializerFull.cpp @@ -100,7 +100,6 @@ #include "Plugins/Process/mach-core/ProcessMachCore.h" #include "Plugins/SymbolVendor/MacOSX/SymbolVendorMacOSX.h" #endif -#include "Plugins/StructuredData/DarwinLog/StructuredDataDarwinLog.h" #if defined(__FreeBSD__) #include "Plugins/Process/FreeBSD/ProcessFreeBSD.h" @@ -382,11 +381,6 @@ SystemInitializerFull::Initialize() PlatformRemoteAppleWatch::Initialize(); DynamicLoaderDarwinKernel::Initialize(); #endif - - // This plugin is valid on any host that talks to a Darwin remote. - // It shouldn't be limited to __APPLE__. - StructuredDataDarwinLog::Initialize(); - //---------------------------------------------------------------------- // Platform agnostic plugins //---------------------------------------------------------------------- @@ -519,8 +513,6 @@ SystemInitializerFull::Terminate() platform_gdb_server::PlatformRemoteGDBServer::Terminate(); process_gdb_remote::ProcessGDBRemote::Terminate(); - StructuredDataDarwinLog::Terminate(); - DynamicLoaderMacOSXDYLD::Terminate(); DynamicLoaderMacOS::Terminate(); DynamicLoaderPOSIXDYLD::Terminate(); diff --git a/lldb/source/Core/Debugger.cpp b/lldb/source/Core/Debugger.cpp index 200fa1a5a23..a30ce674f3a 100644 --- a/lldb/source/Core/Debugger.cpp +++ b/lldb/source/Core/Debugger.cpp @@ -56,7 +56,6 @@ #include "lldb/Target/RegisterContext.h" #include "lldb/Target/SectionLoadList.h" #include "lldb/Target/StopInfo.h" -#include "lldb/Target/StructuredDataPlugin.h" #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #include "lldb/Utility/AnsiTerminal.h" @@ -1477,15 +1476,14 @@ Debugger::GetProcessSTDERR (Process *process, Stream *stream) return total_bytes; } + // This function handles events that were broadcast by the process. void Debugger::HandleProcessEvent (const EventSP &event_sp) { using namespace lldb; const uint32_t event_type = event_sp->GetType(); - ProcessSP process_sp = (event_type == Process::eBroadcastBitStructuredData) - ? EventDataStructuredData::GetProcessFromEvent(event_sp.get()) - : Process::ProcessEventData::GetProcessFromEvent(event_sp.get()); + ProcessSP process_sp = Process::ProcessEventData::GetProcessFromEvent(event_sp.get()); StreamSP output_stream_sp = GetAsyncOutputStream(); StreamSP error_stream_sp = GetAsyncErrorStream(); @@ -1500,9 +1498,6 @@ Debugger::HandleProcessEvent (const EventSP &event_sp) const bool got_state_changed = (event_type & Process::eBroadcastBitStateChanged) != 0; const bool got_stdout = (event_type & Process::eBroadcastBitSTDOUT) != 0; const bool got_stderr = (event_type & Process::eBroadcastBitSTDERR) != 0; - const bool got_structured_data = (event_type & - Process::eBroadcastBitStructuredData) != 0; - if (got_state_changed) { StateType event_state = Process::ProcessEventData::GetStateFromEvent (event_sp.get()); @@ -1527,45 +1522,6 @@ Debugger::HandleProcessEvent (const EventSP &event_sp) GetProcessSTDERR (process_sp.get(), error_stream_sp.get()); } - // Give structured data events an opportunity to display. - if (got_structured_data) - { - StructuredDataPluginSP plugin_sp = - EventDataStructuredData::GetPluginFromEvent(event_sp.get()); - if (plugin_sp) - { - auto structured_data_sp = - EventDataStructuredData::GetObjectFromEvent(event_sp.get()); - if (output_stream_sp) - { - StreamString content_stream; - Error error = plugin_sp->GetDescription(structured_data_sp, - content_stream); - if (error.Success()) - { - if (!content_stream.GetString().empty()) - { - // Add newline. - content_stream.PutChar('\n'); - content_stream.Flush(); - - // Print it. - output_stream_sp->PutCString(content_stream - .GetString().c_str()); - } - } - else - { - error_stream_sp->Printf("Failed to print structured " - "data with plugin %s: %s", - plugin_sp->GetPluginName() - .AsCString(), - error.AsCString()); - } - } - } - } - // Now display any stopped state changes after any STDIO if (got_state_changed && state_is_stopped) { @@ -1630,8 +1586,7 @@ Debugger::DefaultEventHandler() BroadcastEventSpec process_event_spec (broadcaster_class_process, Process::eBroadcastBitStateChanged | Process::eBroadcastBitSTDOUT | - Process::eBroadcastBitSTDERR | - Process::eBroadcastBitStructuredData); + Process::eBroadcastBitSTDERR); BroadcastEventSpec thread_event_spec (broadcaster_class_thread, Thread::eBroadcastBitStackChanged | diff --git a/lldb/source/Core/Event.cpp b/lldb/source/Core/Event.cpp index 96c1c56b10f..6b07e4d9198 100644 --- a/lldb/source/Core/Event.cpp +++ b/lldb/source/Core/Event.cpp @@ -25,13 +25,6 @@ using namespace lldb; using namespace lldb_private; -#pragma mark - -#pragma mark Event - -//------------------------------------------------------------------ -// Event functions -//------------------------------------------------------------------ - Event::Event (Broadcaster *broadcaster, uint32_t event_type, EventData *data) : m_broadcaster_wp(broadcaster->GetBroadcasterImpl()), m_type(event_type), @@ -108,13 +101,6 @@ Event::DoOnRemoval () m_data_sp->DoOnRemoval (this); } -#pragma mark - -#pragma mark EventData - -//------------------------------------------------------------------ -// EventData functions -//------------------------------------------------------------------ - EventData::EventData() = default; EventData::~EventData() = default; @@ -125,14 +111,6 @@ EventData::Dump (Stream *s) const s->PutCString ("Generic Event Data"); } -#pragma mark - -#pragma mark EventDataBytes - -//------------------------------------------------------------------ -// EventDataBytes functions -//------------------------------------------------------------------ - - EventDataBytes::EventDataBytes () : m_bytes() { @@ -246,150 +224,3 @@ EventDataBytes::SwapBytes (std::string &new_bytes) { m_bytes.swap (new_bytes); } - -#pragma mark - -#pragma mark EventStructuredData - -//------------------------------------------------------------------ -// EventDataStructuredData definitions -//------------------------------------------------------------------ - -EventDataStructuredData::EventDataStructuredData() : - EventData(), - m_process_sp(), - m_object_sp(), - m_plugin_sp() -{ -} - -EventDataStructuredData::EventDataStructuredData(const ProcessSP &process_sp, - const StructuredData::ObjectSP - &object_sp, - const - lldb::StructuredDataPluginSP - &plugin_sp) : - EventData(), - m_process_sp(process_sp), - m_object_sp(object_sp), - m_plugin_sp(plugin_sp) -{ -} - -EventDataStructuredData::~EventDataStructuredData() -{ -} - -//------------------------------------------------------------------ -// EventDataStructuredData member functions -//------------------------------------------------------------------ - -const ConstString & -EventDataStructuredData::GetFlavor() const -{ - return EventDataStructuredData::GetFlavorString(); -} - -void -EventDataStructuredData::Dump(Stream *s) const -{ - if (!s) - return; - - if (m_object_sp) - m_object_sp->Dump(*s); -} - -const ProcessSP& -EventDataStructuredData::GetProcess() const -{ - return m_process_sp; -} - -const StructuredData::ObjectSP& -EventDataStructuredData::GetObject() const -{ - return m_object_sp; -} - -const lldb::StructuredDataPluginSP& -EventDataStructuredData::GetStructuredDataPlugin() const -{ - return m_plugin_sp; -} - -void -EventDataStructuredData::SetProcess(const ProcessSP &process_sp) -{ - m_process_sp = process_sp; -} - -void -EventDataStructuredData::SetObject(const StructuredData::ObjectSP &object_sp) -{ - m_object_sp = object_sp; -} - -void -EventDataStructuredData::SetStructuredDataPlugin(const - lldb::StructuredDataPluginSP - &plugin_sp) -{ - m_plugin_sp = plugin_sp; -} - -//------------------------------------------------------------------ -// EventDataStructuredData static functions -//------------------------------------------------------------------ - -const EventDataStructuredData* -EventDataStructuredData::GetEventDataFromEvent(const Event *event_ptr) -{ - if (event_ptr == nullptr) - return nullptr; - - const EventData *event_data = event_ptr->GetData(); - if (!event_data || event_data->GetFlavor() != - EventDataStructuredData::GetFlavorString()) - return nullptr; - - return static_cast<const EventDataStructuredData*>(event_data); -} - -ProcessSP -EventDataStructuredData::GetProcessFromEvent(const Event *event_ptr) -{ - auto event_data = EventDataStructuredData::GetEventDataFromEvent(event_ptr); - if (event_data) - return event_data->GetProcess(); - else - return ProcessSP(); -} - -StructuredData::ObjectSP -EventDataStructuredData::GetObjectFromEvent(const Event *event_ptr) -{ - auto event_data = EventDataStructuredData::GetEventDataFromEvent(event_ptr); - if (event_data) - return event_data->GetObject(); - else - return StructuredData::ObjectSP(); -} - -lldb::StructuredDataPluginSP -EventDataStructuredData::GetPluginFromEvent(const Event *event_ptr) -{ - auto event_data = EventDataStructuredData::GetEventDataFromEvent(event_ptr); - if (event_data) - return event_data->GetStructuredDataPlugin(); - else - return StructuredDataPluginSP(); -} - -const ConstString & -EventDataStructuredData::GetFlavorString () -{ - static ConstString s_flavor("EventDataStructuredData"); - return s_flavor; -} - - diff --git a/lldb/source/Core/PluginManager.cpp b/lldb/source/Core/PluginManager.cpp index eb8b3f1ffb2..500b08b73e9 100644 --- a/lldb/source/Core/PluginManager.cpp +++ b/lldb/source/Core/PluginManager.cpp @@ -1917,146 +1917,6 @@ PluginManager::GetScriptInterpreterForLanguage(lldb::ScriptLanguage script_lang, return none_instance(interpreter); } -#pragma mark - -#pragma mark StructuredDataPlugin - -// ----------------------------------------------------------------------------- -// StructuredDataPlugin -// ----------------------------------------------------------------------------- - -struct StructuredDataPluginInstance -{ - StructuredDataPluginInstance() : - name(), - description(), - create_callback(nullptr), - debugger_init_callback(nullptr), - filter_callback(nullptr) - { - } - - ConstString name; - std::string description; - StructuredDataPluginCreateInstance create_callback; - DebuggerInitializeCallback debugger_init_callback; - StructuredDataFilterLaunchInfo filter_callback; -}; - -typedef std::vector<StructuredDataPluginInstance> StructuredDataPluginInstances; - -static std::recursive_mutex & -GetStructuredDataPluginMutex() -{ - static std::recursive_mutex g_instances_mutex; - return g_instances_mutex; -} - -static StructuredDataPluginInstances & -GetStructuredDataPluginInstances () -{ - static StructuredDataPluginInstances g_instances; - return g_instances; -} - -bool -PluginManager::RegisterPlugin(const ConstString &name, - const char *description, - StructuredDataPluginCreateInstance - create_callback, - DebuggerInitializeCallback debugger_init_callback, - StructuredDataFilterLaunchInfo filter_callback) -{ - if (create_callback) - { - StructuredDataPluginInstance instance; - assert((bool)name); - instance.name = name; - if (description && description[0]) - instance.description = description; - instance.create_callback = create_callback; - instance.debugger_init_callback = debugger_init_callback; - instance.filter_callback = filter_callback; - std::lock_guard<std::recursive_mutex> guard( - GetStructuredDataPluginMutex()); - GetStructuredDataPluginInstances().push_back(instance); - } - return false; -} - -bool -PluginManager::UnregisterPlugin(StructuredDataPluginCreateInstance create_callback) -{ - if (create_callback) - { - std::lock_guard<std::recursive_mutex> guard( - GetStructuredDataPluginMutex()); - StructuredDataPluginInstances &instances = - GetStructuredDataPluginInstances(); - - StructuredDataPluginInstances::iterator pos, end = instances.end(); - for (pos = instances.begin(); pos != end; ++ pos) - { - if (pos->create_callback == create_callback) - { - instances.erase(pos); - return true; - } - } - } - return false; -} - -StructuredDataPluginCreateInstance -PluginManager::GetStructuredDataPluginCreateCallbackAtIndex(uint32_t idx) -{ - std::lock_guard<std::recursive_mutex> guard(GetStructuredDataPluginMutex()); - StructuredDataPluginInstances &instances = - GetStructuredDataPluginInstances(); - if (idx < instances.size()) - return instances[idx].create_callback; - return nullptr; -} - -StructuredDataPluginCreateInstance -PluginManager::GetStructuredDataPluginCreateCallbackForPluginName( - const ConstString &name) -{ - if (name) - { - std::lock_guard<std::recursive_mutex> guard( - GetStructuredDataPluginMutex()); - StructuredDataPluginInstances &instances = - GetStructuredDataPluginInstances(); - - StructuredDataPluginInstances::iterator pos, end = instances.end(); - for (pos = instances.begin(); pos != end; ++ pos) - { - if (name == pos->name) - return pos->create_callback; - } - } - return nullptr; -} - -StructuredDataFilterLaunchInfo -PluginManager::GetStructuredDataFilterCallbackAtIndex(uint32_t idx, - bool &iteration_complete) -{ - std::lock_guard<std::recursive_mutex> guard(GetStructuredDataPluginMutex()); - StructuredDataPluginInstances &instances = - GetStructuredDataPluginInstances(); - if (idx < instances.size()) - { - iteration_complete = false; - return instances[idx].filter_callback; - } - else - { - iteration_complete = true; - } - return nullptr; -} - #pragma mark SymbolFile struct SymbolFileInstance @@ -2912,17 +2772,6 @@ PluginManager::DebuggerInitialize (Debugger &debugger) os.debugger_init_callback(debugger); } } - - // Initialize the StructuredDataPlugin plugins - { - std::lock_guard<std::recursive_mutex> - guard(GetStructuredDataPluginMutex()); - for (auto &plugin: GetStructuredDataPluginInstances()) - { - if (plugin.debugger_init_callback) - plugin.debugger_init_callback(debugger); - } - } } // This is the preferred new way to register plugin specific settings. e.g. @@ -3056,7 +2905,6 @@ const char* kPlatformPluginName("platform"); const char* kProcessPluginName("process"); const char* kSymbolFilePluginName("symbol-file"); const char* kJITLoaderPluginName("jit-loader"); -const char* kStructuredDataPluginName("structured-data"); } // anonymous namespace @@ -3201,24 +3049,3 @@ PluginManager::CreateSettingForOperatingSystemPlugin(Debugger &debugger, } return false; } - -lldb::OptionValuePropertiesSP -PluginManager::GetSettingForStructuredDataPlugin(Debugger &debugger, - const ConstString &setting_name) -{ - return GetSettingForPlugin(debugger, setting_name, ConstString(kStructuredDataPluginName)); -} - -bool -PluginManager::CreateSettingForStructuredDataPlugin(Debugger &debugger, - const lldb::OptionValuePropertiesSP &properties_sp, - const ConstString &description, - bool is_global_property) -{ - return CreateSettingForPlugin(debugger, - ConstString(kStructuredDataPluginName), - ConstString("Settings for structured data plug-ins"), - properties_sp, - description, - is_global_property); -} diff --git a/lldb/source/Interpreter/Args.cpp b/lldb/source/Interpreter/Args.cpp index 8ddc91bb109..3e5b55a482a 100644 --- a/lldb/source/Interpreter/Args.cpp +++ b/lldb/source/Interpreter/Args.cpp @@ -1170,48 +1170,8 @@ Args::LongestCommonPrefix (std::string &common_prefix) } } -void -Args::AddOrReplaceEnvironmentVariable(const char *env_var_name, - const char *new_value) -{ - if (!env_var_name || !new_value) - return; - - // Build the new entry. - StreamString stream; - stream << env_var_name; - stream << '='; - stream << new_value; - stream.Flush(); - - // Find the environment variable if present and replace it. - for (size_t i = 0; i < GetArgumentCount(); ++i) - { - // Get the env var value. - const char *arg_value = GetArgumentAtIndex(i); - if (!arg_value) - continue; - - // Find the name of the env var: before the first =. - auto equal_p = strchr(arg_value, '='); - if (!equal_p) - continue; - - // Check if the name matches the given env_var_name. - if (strncmp(env_var_name, arg_value, equal_p - arg_value) == 0) - { - ReplaceArgumentAtIndex(i, stream.GetString().c_str()); - return; - } - } - - // We didn't find it. Append it instead. - AppendArgument(stream.GetString().c_str()); -} - bool -Args::ContainsEnvironmentVariable(const char *env_var_name, - size_t *argument_index) const +Args::ContainsEnvironmentVariable(const char *env_var_name) const { // Validate args. if (!env_var_name) @@ -1233,8 +1193,6 @@ Args::ContainsEnvironmentVariable(const char *env_var_name, equal_p - argument_value) == 0) { // We matched. - if (argument_index) - *argument_index = i; return true; } } @@ -1244,8 +1202,6 @@ Args::ContainsEnvironmentVariable(const char *env_var_name, if (strcmp(argument_value, env_var_name) == 0) { // We matched. - if (argument_index) - *argument_index = i; return true; } } diff --git a/lldb/source/Plugins/Process/gdb-remote/GDBRemoteClientBase.cpp b/lldb/source/Plugins/Process/gdb-remote/GDBRemoteClientBase.cpp index fde38037d9a..786d80176c6 100644 --- a/lldb/source/Plugins/Process/gdb-remote/GDBRemoteClientBase.cpp +++ b/lldb/source/Plugins/Process/gdb-remote/GDBRemoteClientBase.cpp @@ -11,7 +11,6 @@ #include "llvm/ADT/StringExtras.h" -#include "lldb/Target/Process.h" #include "lldb/Target/UnixSignals.h" #include "lldb/Utility/LLDBAssert.h" @@ -101,41 +100,6 @@ GDBRemoteClientBase::SendContinuePacketAndWaitForResponse(ContinueDelegate &dele case 'A': delegate.HandleAsyncMisc(llvm::StringRef(response.GetStringRef()).substr(1)); break; - - case 'J': - // Asynchronous JSON packet, destined for a - // StructuredDataPlugin. - { - // Parse the content into a StructuredData instance. - auto payload_index = strlen("JSON-async:"); - StructuredData::ObjectSP json_sp = - StructuredData::ParseJSON(response.GetStringRef() - .substr(payload_index)); - if (log) - { - if (json_sp) - log->Printf( - "GDBRemoteCommmunicationClientBase::%s() " - "received Async StructuredData packet: %s", - __FUNCTION__, - response.GetStringRef(). - substr(payload_index).c_str()); - else - log->Printf("GDBRemoteCommmunicationClientBase::%s" - "() received StructuredData packet:" - " parse failure", __FUNCTION__); - } - - // Pass the data to the process to route to the - // appropriate plugin. The plugin controls what happens - // to it from there. - bool routed = delegate.HandleAsyncStructuredData(json_sp); - if (log) - log->Printf("GDBRemoteCommmunicationClientBase::%s()" - " packet %s", __FUNCTION__, - routed ? "handled" : "not handled"); - break; - } case 'T': case 'S': // Do this with the continue lock held. diff --git a/lldb/source/Plugins/Process/gdb-remote/GDBRemoteClientBase.h b/lldb/source/Plugins/Process/gdb-remote/GDBRemoteClientBase.h index 684ef3e80d1..9cfba4b8394 100644 --- a/lldb/source/Plugins/Process/gdb-remote/GDBRemoteClientBase.h +++ b/lldb/source/Plugins/Process/gdb-remote/GDBRemoteClientBase.h @@ -31,16 +31,6 @@ public: HandleAsyncMisc(llvm::StringRef data) = 0; virtual void HandleStopReply() = 0; - - // - /// Processes async structured data. - /// - /// @return - /// true if the data was handled; otherwise, false. - // - virtual bool - HandleAsyncStructuredData(const StructuredData::ObjectSP - &object_sp) = 0; }; GDBRemoteClientBase(const char *comm_name, const char *listener_name); diff --git a/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.cpp b/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.cpp index d893b868e75..00357dd54e3 100644 --- a/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.cpp +++ b/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.cpp @@ -30,8 +30,6 @@ #include "lldb/Interpreter/Args.h" #include "lldb/Symbol/Symbol.h" #include "lldb/Target/MemoryRegionInfo.h" -#include "lldb/Target/UnixSignals.h" -#include "lldb/Utility/LLDBAssert.h" #include "lldb/Target/Target.h" // Project includes @@ -116,10 +114,7 @@ GDBRemoteCommunicationClient::GDBRemoteCommunicationClient() m_gdb_server_name(), m_gdb_server_version(UINT32_MAX), m_default_packet_timeout(0), - m_max_packet_size(0), - m_qSupported_response(), - m_supported_async_json_packets_is_valid(false), - m_supported_async_json_packets_sp() + m_max_packet_size(0) { } @@ -383,9 +378,6 @@ GDBRemoteCommunicationClient::ResetDiscoverableSettings (bool did_exec) m_gdb_server_version = UINT32_MAX; m_default_packet_timeout = 0; m_max_packet_size = 0; - m_qSupported_response.clear(); - m_supported_async_json_packets_is_valid = false; - m_supported_async_json_packets_sp.reset(); } // These flags should be reset when we first connect to a GDB server @@ -421,12 +413,6 @@ GDBRemoteCommunicationClient::GetRemoteQSupported () /*send_async=*/false) == PacketResult::Success) { const char *response_cstr = response.GetStringRef().c_str(); - - // Hang on to the qSupported packet, so that platforms can do custom - // configuration of the transport before attaching/launching the - // process. - m_qSupported_response = response_cstr; - if (::strstr (response_cstr, "qXfer:auxv:read+")) m_supports_qXfer_auxv_read = eLazyBoolYes; if (::strstr (response_cstr, "qXfer:libraries-svr4:read+")) @@ -3920,126 +3906,6 @@ GDBRemoteCommunicationClient::ServeSymbolLookups(lldb_private::Process *process) } } -StructuredData::Array* -GDBRemoteCommunicationClient::GetSupportedStructuredDataPlugins() -{ - if (!m_supported_async_json_packets_is_valid) - { - // Query the server for the array of supported asynchronous JSON - // packets. - m_supported_async_json_packets_is_valid = true; - - Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet( - GDBR_LOG_PROCESS)); - - // Poll it now. - StringExtractorGDBRemote response; - const bool send_async = false; - if (SendPacketAndWaitForResponse("qStructuredDataPlugins", response, - send_async) == PacketResult::Success) - { - m_supported_async_json_packets_sp = StructuredData::ParseJSON( - response.GetStringRef()); - if (m_supported_async_json_packets_sp && - !m_supported_async_json_packets_sp->GetAsArray()) - { - // We were returned something other than a JSON array. This - // is invalid. Clear it out. - if (log) - log->Printf("GDBRemoteCommunicationClient::%s(): " - "QSupportedAsyncJSONPackets returned invalid " - "result: %s", __FUNCTION__, - response.GetStringRef().c_str()); - m_supported_async_json_packets_sp.reset(); - } - } - else - { - if (log) - log->Printf("GDBRemoteCommunicationClient::%s(): " - "QSupportedAsyncJSONPackets unsupported", - __FUNCTION__); - } - - if (log && m_supported_async_json_packets_is_valid) - { - StreamString stream; - m_supported_async_json_packets_sp->Dump(stream); - log->Printf("GDBRemoteCommunicationClient::%s(): supported async " - "JSON packets: %s", __FUNCTION__, - stream.GetString().c_str()); - } - } - - return m_supported_async_json_packets_sp - ? m_supported_async_json_packets_sp->GetAsArray() - : nullptr; -} - -Error -GDBRemoteCommunicationClient::ConfigureRemoteStructuredData( - const ConstString &type_name, - const StructuredData::ObjectSP &config_sp) -{ - Error error; - - if (type_name.GetLength() == 0) - { - error.SetErrorString("invalid type_name argument"); - return error; - } - - // Build command: Configure{type_name}: serialized config - // data. - StreamGDBRemote stream; - stream.PutCString("QConfigure"); - stream.PutCString(type_name.AsCString()); - stream.PutChar(':'); - if (config_sp) - { - // Gather the plain-text version of the configuration data. - StreamString unescaped_stream; - config_sp->Dump(unescaped_stream); - unescaped_stream.Flush(); - - // Add it to the stream in escaped fashion. - stream.PutEscapedBytes(unescaped_stream.GetData(), - unescaped_stream.GetSize()); - } - stream.Flush(); - - // Send the packet. - const bool send_async = false; - StringExtractorGDBRemote response; - auto result = SendPacketAndWaitForResponse(stream.GetString().c_str(), - response, send_async); - if (result == PacketResult::Success) - { - // We failed if the config result comes back other than OK. - if (strcmp(response.GetStringRef().c_str(), "OK") == 0) - { - // Okay! - error.Clear(); - } - else - { - error.SetErrorStringWithFormat("configuring StructuredData feature " - "%s failed with error %s", - type_name.AsCString(), - response.GetStringRef().c_str()); - } - } - else - { - // Can we get more data here on the failure? - error.SetErrorStringWithFormat("configuring StructuredData feature %s " - "failed when sending packet: " - "PacketResult=%d", type_name.AsCString(), - result); - } - return error; -} - void GDBRemoteCommunicationClient::OnRunPacketSent(bool first) { diff --git a/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.h b/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.h index 54e70792175..b041ecbf3da 100644 --- a/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.h +++ b/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.h @@ -547,53 +547,6 @@ public: void ServeSymbolLookups(lldb_private::Process *process); - //------------------------------------------------------------------ - /// Return the feature set supported by the gdb-remote server. - /// - /// This method returns the remote side's response to the qSupported - /// packet. The response is the complete string payload returned - /// to the client. - /// - /// @return - /// The string returned by the server to the qSupported query. - //------------------------------------------------------------------ - const std::string& - GetServerSupportedFeatures() const - { - return m_qSupported_response; - } - - //------------------------------------------------------------------ - /// Return the array of async JSON packet types supported by the remote. - /// - /// This method returns the remote side's array of supported JSON - /// packet types as a list of type names. Each of the results are - /// expected to have an Enable{type_name} command to enable and configure - /// the related feature. Each type_name for an enabled feature will - /// possibly send async-style packets that contain a payload of a - /// binhex-encoded JSON dictionary. The dictionary will have a - /// string field named 'type', that contains the type_name of the - /// supported packet type. - /// - /// There is a Plugin category called structured-data plugins. - /// A plugin indicates whether it knows how to handle a type_name. - /// If so, it can be used to process the async JSON packet. - /// - /// @return - /// The string returned by the server to the qSupported query. - //------------------------------------------------------------------ - lldb_private::StructuredData::Array* - GetSupportedStructuredDataPlugins(); - - //------------------------------------------------------------------ - /// Configure a StructuredData feature on the remote end. - /// - /// @see \b Process::ConfigureStructuredData(...) for details. - //------------------------------------------------------------------ - Error - ConfigureRemoteStructuredData(const ConstString &type_name, - const StructuredData::ObjectSP &config_sp); - protected: LazyBool m_supports_not_sending_acks; LazyBool m_supports_thread_suffix; @@ -664,10 +617,6 @@ protected: uint32_t m_gdb_server_version; // from reply to qGDBServerVersion, zero if qGDBServerVersion is not supported uint32_t m_default_packet_timeout; uint64_t m_max_packet_size; // as returned by qSupported - std::string m_qSupported_response; // the complete response to qSupported - - bool m_supported_async_json_packets_is_valid; - lldb_private::StructuredData::ObjectSP m_supported_async_json_packets_sp; bool GetCurrentProcessInfo (bool allow_lazy_pid = true); diff --git a/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp b/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp index be5c3b552c8..1fa78fe155f 100644 --- a/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp +++ b/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp @@ -1175,7 +1175,7 @@ ProcessGDBRemote::DidLaunchOrAttach (ArchSpec& process_arch) { Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); if (log) - log->Printf ("ProcessGDBRemote::%s()", __FUNCTION__); + log->Printf ("ProcessGDBRemote::DidLaunch()"); if (GetID() != LLDB_INVALID_PROCESS_ID) { BuildDynamicRegisterInfo (false); @@ -1271,13 +1271,6 @@ ProcessGDBRemote::DidLaunchOrAttach (ArchSpec& process_arch) GetTarget().SetArchitecture (process_arch); } } - - // Find out which StructuredDataPlugins are supported by the - // debug monitor. These plugins transmit data over async $J packets. - auto supported_packets_array = - m_gdb_comm.GetSupportedStructuredDataPlugins(); - if (supported_packets_array) - MapSupportedStructuredDataPlugins(*supported_packets_array); } } @@ -4349,13 +4342,6 @@ ProcessGDBRemote::GetSharedCacheInfo () return object_sp; } -Error -ProcessGDBRemote::ConfigureStructuredData(const ConstString &type_name, - const StructuredData::ObjectSP - &config_sp) -{ - return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp); -} // Establish the largest memory read/write payloads we should use. // If the remote stub has a max packet size, stay under that size. @@ -5249,13 +5235,6 @@ ProcessGDBRemote::HandleStopReply() BuildDynamicRegisterInfo(true); } -bool -ProcessGDBRemote::HandleAsyncStructuredData(const StructuredData::ObjectSP - &object_sp) -{ - return RouteAsyncStructuredData(object_sp); -} - class CommandObjectProcessGDBRemoteSpeedTest: public CommandObjectParsed { public: diff --git a/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h b/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h index 3a0dd2f7235..0f41a2149ea 100644 --- a/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h +++ b/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h @@ -261,10 +261,6 @@ public: StructuredData::ObjectSP GetLoadedDynamicLibrariesInfos (lldb::addr_t image_list_address, lldb::addr_t image_count) override; - Error - ConfigureStructuredData(const ConstString &type_name, - const StructuredData::ObjectSP &config_sp) override; - StructuredData::ObjectSP GetLoadedDynamicLibrariesInfos () override; @@ -510,9 +506,6 @@ private: HandleAsyncMisc(llvm::StringRef data) override; void HandleStopReply() override; - bool - HandleAsyncStructuredData(const StructuredData::ObjectSP - &object_sp) override; DISALLOW_COPY_AND_ASSIGN (ProcessGDBRemote); }; diff --git a/lldb/source/Plugins/StructuredData/CMakeLists.txt b/lldb/source/Plugins/StructuredData/CMakeLists.txt deleted file mode 100644 index 40d64558482..00000000000 --- a/lldb/source/Plugins/StructuredData/CMakeLists.txt +++ /dev/null @@ -1,2 +0,0 @@ -add_subdirectory(DarwinLog) - diff --git a/lldb/source/Plugins/StructuredData/DarwinLog/CMakeLists.txt b/lldb/source/Plugins/StructuredData/DarwinLog/CMakeLists.txt deleted file mode 100644 index ce0e21b4ed3..00000000000 --- a/lldb/source/Plugins/StructuredData/DarwinLog/CMakeLists.txt +++ /dev/null @@ -1,5 +0,0 @@ -list(APPEND SOURCES - StructuredDataDarwinLog.cpp - ) - -add_lldb_library(lldbPluginStructuredDataDarwinLog ${SOURCES}) diff --git a/lldb/source/Plugins/StructuredData/DarwinLog/StructuredDataDarwinLog.cpp b/lldb/source/Plugins/StructuredData/DarwinLog/StructuredDataDarwinLog.cpp deleted file mode 100644 index 7e0f080dca8..00000000000 --- a/lldb/source/Plugins/StructuredData/DarwinLog/StructuredDataDarwinLog.cpp +++ /dev/null @@ -1,2420 +0,0 @@ -//===-- StructuredDataDarwinLog.cpp -----------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#include "StructuredDataDarwinLog.h" - -// C includes -#include <string.h> - -// C++ includes -#include <sstream> - -#include "lldb/Breakpoint/StoppointCallbackContext.h" -#include "lldb/Core/Debugger.h" -#include "lldb/Core/Log.h" -#include "lldb/Core/Module.h" -#include "lldb/Core/PluginManager.h" -#include "lldb/Core/RegularExpression.h" -#include "lldb/Interpreter/CommandInterpreter.h" -#include "lldb/Interpreter/CommandObjectMultiword.h" -#include "lldb/Interpreter/CommandReturnObject.h" -#include "lldb/Interpreter/OptionValueProperties.h" -#include "lldb/Interpreter/OptionValueString.h" -#include "lldb/Interpreter/Property.h" -#include "lldb/Target/Process.h" -#include "lldb/Target/Target.h" -#include "lldb/Target/ThreadPlanCallOnFunctionExit.h" - -#define DARWIN_LOG_TYPE_VALUE "DarwinLog" - -using namespace lldb; -using namespace lldb_private; - -#pragma mark - -#pragma mark Anonymous Namespace - -// ----------------------------------------------------------------------------- -// Anonymous namespace -// ----------------------------------------------------------------------------- - -namespace sddarwinlog_private -{ - const uint64_t NANOS_PER_MICRO = 1000; - const uint64_t NANOS_PER_MILLI = NANOS_PER_MICRO * 1000; - const uint64_t NANOS_PER_SECOND = NANOS_PER_MILLI * 1000; - const uint64_t NANOS_PER_MINUTE = NANOS_PER_SECOND * 60; - const uint64_t NANOS_PER_HOUR = NANOS_PER_MINUTE * 60; - - static bool DEFAULT_FILTER_FALLTHROUGH_ACCEPTS = true; - - //------------------------------------------------------------------ - /// Global, sticky enable switch. If true, the user has explicitly - /// run the enable command. When a process launches or is attached to, - /// we will enable DarwinLog if either the settings for auto-enable is - /// on, or if the user had explicitly run enable at some point prior - /// to the launch/attach. - //------------------------------------------------------------------ - static bool s_is_explicitly_enabled; - - class EnableOptions; - using EnableOptionsSP = std::shared_ptr<EnableOptions>; - - using OptionsMap = std::map<DebuggerWP, EnableOptionsSP, - std::owner_less<DebuggerWP>>; - - static OptionsMap& - GetGlobalOptionsMap() - { - static OptionsMap s_options_map; - return s_options_map; - } - - static std::mutex& - GetGlobalOptionsMapLock() - { - static std::mutex s_options_map_lock; - return s_options_map_lock; - } - - EnableOptionsSP - GetGlobalEnableOptions(const DebuggerSP &debugger_sp) - { - if (!debugger_sp) - return EnableOptionsSP(); - - std::lock_guard<std::mutex> locker(GetGlobalOptionsMapLock()); - OptionsMap &options_map = GetGlobalOptionsMap(); - DebuggerWP debugger_wp(debugger_sp); - auto find_it = options_map.find(debugger_wp); - if (find_it != options_map.end()) - return find_it->second; - else - return EnableOptionsSP(); - } - - void - SetGlobalEnableOptions(const DebuggerSP &debugger_sp, - const EnableOptionsSP &options_sp) - { - std::lock_guard<std::mutex> locker(GetGlobalOptionsMapLock()); - OptionsMap &options_map = GetGlobalOptionsMap(); - DebuggerWP debugger_wp(debugger_sp); - auto find_it = options_map.find(debugger_wp); - if (find_it != options_map.end()) - find_it->second = options_sp; - else - options_map.insert(std::make_pair(debugger_wp, options_sp)); - } - -#pragma mark - -#pragma mark Settings Handling - - //------------------------------------------------------------------ - /// Code to handle the StructuredDataDarwinLog settings - //------------------------------------------------------------------ - - static PropertyDefinition - g_properties[] = - { - { - "enable-on-startup" , // name - OptionValue::eTypeBoolean, // type - true, // global - false, // default uint value - nullptr, // default cstring value - nullptr, // enum values - "Enable Darwin os_log collection when debugged process is launched " - "or attached." // description - }, - { - "auto-enable-options" , // name - OptionValue::eTypeString, // type - true, // global - 0, // default uint value - "", // default cstring value - nullptr, // enum values - "Specify the options to 'plugin structured-data darwin-log enable' " - "that should be applied when automatically enabling logging on " - "startup/attach." // description - }, - // Last entry sentinel. - { - nullptr, - OptionValue::eTypeInvalid, - false, - 0 , - nullptr, - nullptr, - nullptr - } - }; - - enum { - ePropertyEnableOnStartup = 0, - ePropertyAutoEnableOptions = 1 - }; - - class StructuredDataDarwinLogProperties : public Properties - { - public: - - static ConstString & - GetSettingName () - { - static ConstString g_setting_name("darwin-log"); - return g_setting_name; - } - - StructuredDataDarwinLogProperties() : - Properties () - { - m_collection_sp.reset(new OptionValueProperties(GetSettingName())); - m_collection_sp->Initialize(g_properties); - } - - virtual - ~StructuredDataDarwinLogProperties() - { - } - - bool - GetEnableOnStartup() const - { - const uint32_t idx = ePropertyEnableOnStartup; - return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, - g_properties[idx].default_uint_value != 0); - } - - const char* - GetAutoEnableOptions() const - { - const uint32_t idx = ePropertyAutoEnableOptions; - return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, - g_properties[idx].default_cstr_value); - } - - const char* - GetLoggingModuleName() const - { - return "libsystem_trace.dylib"; - } - }; - - using StructuredDataDarwinLogPropertiesSP = - std::shared_ptr<StructuredDataDarwinLogProperties>; - - static const StructuredDataDarwinLogPropertiesSP& - GetGlobalProperties() - { - static StructuredDataDarwinLogPropertiesSP g_settings_sp; - if (!g_settings_sp) - g_settings_sp.reset(new StructuredDataDarwinLogProperties()); - return g_settings_sp; - } - - const char *const s_filter_attributes[] = - { - "activity", // current activity - "activity-chain", // entire activity chain, each level separated by ':' - "category", // category of the log message - "message", // message contents, fully expanded - "subsystem" // subsystem of the log message - - // Consider impelmenting this action as it would be cheaper to filter. - // "message" requires always formatting the message, which is a waste - // of cycles if it ends up being rejected. - // "format", // format string used to format message text - }; - - static const ConstString& - GetDarwinLogTypeName() - { - static const ConstString s_key_name("DarwinLog"); - return s_key_name; - } - - static const ConstString& - GetLogEventType() - { - static const ConstString s_event_type("log"); - return s_event_type; - } - - class FilterRule; - using FilterRuleSP = std::shared_ptr<FilterRule>; - - class FilterRule - { - public: - - virtual - ~FilterRule() - { - } - - using OperationCreationFunc = - std::function<FilterRuleSP(bool accept, - size_t attribute_index, - const std::string &op_arg, - Error &error)>; - - static void - RegisterOperation(const ConstString &operation, - const OperationCreationFunc &creation_func) - { - GetCreationFuncMap().insert(std::make_pair(operation, - creation_func)); - } - - static - FilterRuleSP CreateRule(bool match_accepts, size_t attribute, - const ConstString &operation, - const std::string &op_arg, Error &error) - { - // Find the creation func for this type of filter rule. - auto map = GetCreationFuncMap(); - auto find_it = map.find(operation); - if (find_it == map.end()) - { - error.SetErrorStringWithFormat("unknown filter operation \"" - "%s\"", - operation.GetCString()); - return FilterRuleSP(); - } - - return find_it->second(match_accepts, attribute, op_arg, error); - } - - StructuredData::ObjectSP Serialize() const - { - StructuredData::Dictionary *dict_p = - new StructuredData::Dictionary(); - - // Indicate whether this is an accept or reject rule. - dict_p->AddBooleanItem("accept", m_accept); - - // Indicate which attribute of the message this filter references. - // This can drop into the rule-specific DoSerialization if we get - // to the point where not all FilterRule derived classes work on - // an attribute. (e.g. logical and/or and other compound - // operations). - dict_p->AddStringItem("attribute", - s_filter_attributes[m_attribute_index]); - - // Indicate the type of the rule. - dict_p->AddStringItem("type", GetOperationType().GetCString()); - - // Let the rule add its own specific details here. - DoSerialization(*dict_p); - - return StructuredData::ObjectSP(dict_p); - } - - virtual void - Dump(Stream &stream) const = 0; - - const ConstString& - GetOperationType() const - { - return m_operation; - } - - protected: - - FilterRule(bool accept, size_t attribute_index, - const ConstString &operation) : - m_accept(accept), - m_attribute_index(attribute_index), - m_operation(operation) - { - } - - virtual void - DoSerialization(StructuredData::Dictionary &dict) const = 0; - - bool - GetMatchAccepts() const - { - return m_accept; - } - - const char* - GetFilterAttribute() const - { - return s_filter_attributes[m_attribute_index]; - } - - private: - - using CreationFuncMap = std::map<ConstString, OperationCreationFunc>; - - static CreationFuncMap& - GetCreationFuncMap() - { - static CreationFuncMap s_map; - return s_map; - } - - const bool m_accept; - const size_t m_attribute_index; - const ConstString m_operation; - - }; - - using FilterRules = std::vector<FilterRuleSP>; - - class RegexFilterRule : public FilterRule - { - public: - - static void - RegisterOperation() - { - FilterRule::RegisterOperation(StaticGetOperation(), - CreateOperation); - } - - void - Dump(Stream &stream) const override - { - stream.Printf("%s %s regex %s", - GetMatchAccepts() ? "accept" : "reject", - GetFilterAttribute(), m_regex_text.c_str()); - } - - protected: - - void - DoSerialization(StructuredData::Dictionary &dict) const override - { - dict.AddStringItem("regex", m_regex_text); - } - - private: - - static FilterRuleSP - CreateOperation(bool accept, size_t attribute_index, - const std::string &op_arg, Error &error) - { - // We treat the op_arg as a regex. Validate it. - if (op_arg.empty()) - { - error.SetErrorString("regex filter type requires a regex " - "argument"); - return FilterRuleSP(); - } - - // Instantiate the regex so we can report any errors. - auto regex = RegularExpression(op_arg.c_str()); - if (!regex.IsValid()) - { - char error_text[256]; - error_text[0] = '\0'; - regex.GetErrorAsCString(error_text, sizeof(error_text)); - error.SetErrorString(error_text); - return FilterRuleSP(); - } - - // We passed all our checks, this appears fine. - error.Clear(); - return FilterRuleSP(new RegexFilterRule(accept, attribute_index, - op_arg)); - } - - static const ConstString & - StaticGetOperation() - { - static ConstString s_operation("regex"); - return s_operation; - } - - RegexFilterRule(bool accept, size_t attribute_index, - const std::string ®ex_text) : - FilterRule(accept, attribute_index, StaticGetOperation()), - m_regex_text(regex_text) - { - } - - const std::string m_regex_text; - }; - - class ExactMatchFilterRule : public FilterRule - { - public: - - static void - RegisterOperation() - { - FilterRule::RegisterOperation(StaticGetOperation(), - CreateOperation); - } - - void - Dump(Stream &stream) const override - { - stream.Printf("%s %s match %s", - GetMatchAccepts() ? "accept" : "reject", - GetFilterAttribute(), m_match_text.c_str()); - } - - protected: - - void - DoSerialization(StructuredData::Dictionary &dict) const override - { - dict.AddStringItem("exact_text", m_match_text); - } - - private: - - static FilterRuleSP - CreateOperation(bool accept, size_t attribute_index, - const std::string &op_arg, Error &error) - { - if (op_arg.empty()) - { - error.SetErrorString("exact match filter type requires an " - "argument containing the text that must " - "match the specified message attribute."); - return FilterRuleSP(); - } - - error.Clear(); - return FilterRuleSP(new ExactMatchFilterRule(accept, - attribute_index, - op_arg)); - } - - static const ConstString & - StaticGetOperation() - { - static ConstString s_operation("match"); - return s_operation; - } - - ExactMatchFilterRule(bool accept, size_t attribute_index, - const std::string &match_text) : - FilterRule(accept, attribute_index, StaticGetOperation()), - m_match_text(match_text) - { - } - - const std::string m_match_text; - }; - - static void - RegisterFilterOperations() - { - ExactMatchFilterRule::RegisterOperation(); - RegexFilterRule::RegisterOperation(); - } - - // ========================================================================= - // Commands - // ========================================================================= - - // ------------------------------------------------------------------------- - /// Provides the main on-off switch for enabling darwin logging. - /// - /// It is valid to run the enable command when logging is already enabled. - /// This resets the logging with whatever settings are currently set. - // ------------------------------------------------------------------------- - class EnableOptions : public Options - { - public: - - EnableOptions() : - Options(), - m_include_debug_level(false), - m_include_info_level(false), - m_include_any_process(false), - m_filter_fall_through_accepts(DEFAULT_FILTER_FALLTHROUGH_ACCEPTS), - m_echo_to_stderr(false), - m_display_timestamp_relative(false), - m_display_subsystem(false), - m_display_category(false), - m_display_activity_chain(false), - m_broadcast_events(true), - m_live_stream(true), - m_filter_rules() - { - } - - void - OptionParsingStarting (ExecutionContext *execution_context) override - { - m_include_debug_level = false; - m_include_info_level = false; - m_include_any_process = false; - m_filter_fall_through_accepts = DEFAULT_FILTER_FALLTHROUGH_ACCEPTS; - m_echo_to_stderr = false; - m_display_timestamp_relative = false; - m_display_subsystem = false; - m_display_category = false; - m_display_activity_chain = false; - m_broadcast_events = true; - m_live_stream = true; - m_filter_rules.clear(); - } - - Error - SetOptionValue (uint32_t option_idx, const char *option_arg, - ExecutionContext *execution_context) override - { - Error error; - - const int short_option = m_getopt_table[option_idx].val; - switch (short_option) - { - case 'a': - m_include_any_process = true; - break; - - case 'A': - m_display_timestamp_relative = true; - m_display_category = true; - m_display_subsystem = true; - m_display_activity_chain = true; - break; - - case 'b': - m_broadcast_events = - Args::StringToBoolean(option_arg, true, nullptr); - break; - - case 'c': - m_display_category = true; - break; - - case 'C': - m_display_activity_chain = true; - break; - - case 'd': - m_include_debug_level = true; - break; - - case 'e': - m_echo_to_stderr = - Args::StringToBoolean(option_arg, false, nullptr); - break; - - case 'f': - return ParseFilterRule(option_arg); - - case 'i': - m_include_info_level = true; - break; - - case 'l': - m_live_stream = - Args::StringToBoolean(option_arg, false, nullptr); - break; - - case 'n': - m_filter_fall_through_accepts = - Args::StringToBoolean(option_arg, true, nullptr); - break; - - case 'r': - m_display_timestamp_relative = true; - break; - - case 's': - m_display_subsystem = true; - break; - - default: - error.SetErrorStringWithFormat("unsupported option '%c'", - short_option); - } - return error; - } - - const OptionDefinition* - GetDefinitions () override - { - return g_enable_option_table; - } - - StructuredData::DictionarySP - BuildConfigurationData(bool enabled) - { - StructuredData::DictionarySP config_sp(new StructuredData:: - Dictionary()); - - // Set the basic enabled state. - config_sp->AddBooleanItem("enabled", enabled); - - // If we're disabled, there's nothing more to add. - if (!enabled) - return config_sp; - - // Handle source stream flags. - auto source_flags_sp = - StructuredData::DictionarySP(new StructuredData::Dictionary()); - config_sp->AddItem("source-flags", source_flags_sp); - - source_flags_sp->AddBooleanItem("any-process", - m_include_any_process); - source_flags_sp->AddBooleanItem("debug-level", - m_include_debug_level); - // The debug-level flag, if set, implies info-level. - source_flags_sp->AddBooleanItem("info-level", - m_include_info_level || - m_include_debug_level); - source_flags_sp->AddBooleanItem("live-stream", - m_live_stream); - - // Specify default filter rule (the fall-through) - config_sp->AddBooleanItem("filter-fall-through-accepts", - m_filter_fall_through_accepts); - - - // Handle filter rules - if (!m_filter_rules.empty()) - { - auto json_filter_rules_sp = - StructuredData::ArraySP(new StructuredData::Array); - config_sp->AddItem("filter-rules", - json_filter_rules_sp); - for (auto &rule_sp : m_filter_rules) - { - if (!rule_sp) - continue; - json_filter_rules_sp->AddItem(rule_sp->Serialize()); - } - } - return config_sp; - } - - bool - GetIncludeDebugLevel() const - { - return m_include_debug_level; - } - - bool - GetIncludeInfoLevel() const - { - // Specifying debug level implies info level. - return m_include_info_level || m_include_debug_level; - } - - const FilterRules& - GetFilterRules() const - { - return m_filter_rules; - } - - bool - GetFallthroughAccepts() const - { - return m_filter_fall_through_accepts; - } - - bool - GetEchoToStdErr() const - { - return m_echo_to_stderr; - } - - bool - GetDisplayTimestampRelative() const - { - return m_display_timestamp_relative; - } - - bool - GetDisplaySubsystem() const - { - return m_display_subsystem; - } - bool - GetDisplayCategory() const - { - return m_display_category; - } - bool - GetDisplayActivityChain() const - { - return m_display_activity_chain; - } - - bool - GetDisplayAnyHeaderFields() const - { - return - m_display_timestamp_relative || - m_display_activity_chain || - m_display_subsystem || - m_display_category; - } - - bool - GetBroadcastEvents() const - { - return m_broadcast_events; - } - - private: - - Error - ParseFilterRule(const char *rule_text_cstr) - { - Error error; - - if (!rule_text_cstr || !rule_text_cstr[0]) - { - error.SetErrorString("invalid rule_text"); - return error; - } - - // filter spec format: - // - // {action} {attribute} {op} - // - // {action} := - // accept | - // reject - // - // {attribute} := - // category | - // subsystem | - // activity | - // activity-chain | - // message | - // format - // - // {op} := - // match {exact-match-text} | - // regex {search-regex} - - const std::string rule_text(rule_text_cstr); - - // Parse action. - auto action_end_pos = rule_text.find(" "); - if (action_end_pos == std::string::npos) - { - error.SetErrorStringWithFormat("could not parse filter rule " - "action from \"%s\"", - rule_text_cstr); - return error; - } - auto action = rule_text.substr(0, action_end_pos); - bool accept; - if (action == "accept") - accept = true; - else if (action == "reject") - accept = false; - else - { - error.SetErrorString("filter action must be \"accept\" or " - "\"deny\""); - return error; - } - - // parse attribute - auto attribute_end_pos = rule_text.find(" ", action_end_pos + 1); - if (attribute_end_pos == std::string::npos) - { - error.SetErrorStringWithFormat("could not parse filter rule " - "attribute from \"%s\"", - rule_text_cstr); - return error; - } - auto attribute = - rule_text.substr(action_end_pos + 1, - attribute_end_pos - (action_end_pos + 1)); - auto attribute_index = MatchAttributeIndex(attribute); - if (attribute_index < 0) - { - error.SetErrorStringWithFormat("filter rule attribute unknown: " - "%s", attribute.c_str()); - return error; - } - - // parse operation - auto operation_end_pos = rule_text.find(" ", attribute_end_pos + 1); - auto operation = - rule_text.substr(attribute_end_pos + 1, - operation_end_pos - (attribute_end_pos + 1)); - - // add filter spec - auto rule_sp = - FilterRule::CreateRule(accept, attribute_index, - ConstString(operation), - rule_text.substr(operation_end_pos + 1), - error); - - if (rule_sp && error.Success()) - m_filter_rules.push_back(rule_sp); - - return error; - } - - int - MatchAttributeIndex(const std::string &attribute_name) - { - auto attribute_count = - sizeof(s_filter_attributes) / sizeof(s_filter_attributes[0]); - for (size_t i = 0; i < attribute_count; ++i) - { - if (attribute_name == s_filter_attributes[i]) - return static_cast<int>(i); - } - - // We didn't match anything. - return -1; - } - - static OptionDefinition g_enable_option_table[]; - - bool m_include_debug_level; - bool m_include_info_level; - bool m_include_any_process; - bool m_filter_fall_through_accepts; - bool m_echo_to_stderr; - bool m_display_timestamp_relative; - bool m_display_subsystem; - bool m_display_category; - bool m_display_activity_chain; - bool m_broadcast_events; - bool m_live_stream; - FilterRules m_filter_rules; - }; - - OptionDefinition - EnableOptions::g_enable_option_table[] = - { - // Source stream include/exclude options (the first-level filter). - // This one should be made as small as possible as everything that - // goes through here must be processed by the process monitor. - { LLDB_OPT_SET_ALL, false, "any-process", 'a', - OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, - "Specifies log messages from other related processes should be " - "included." }, - { LLDB_OPT_SET_ALL, false, "debug", 'd', OptionParser::eNoArgument, - nullptr, nullptr, 0, eArgTypeNone, - "Specifies debug-level log messages should be included. Specifying" - " --debug implies --info."}, - { LLDB_OPT_SET_ALL, false, "info", 'i', OptionParser::eNoArgument, - nullptr, nullptr, 0, eArgTypeNone, - "Specifies info-level log messages should be included." }, - { LLDB_OPT_SET_ALL, false, "filter", 'f', - OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgRawInput, - // There doesn't appear to be a great way for me to have these - // multi-line, formatted tables in help. This looks mostly right - // but there are extra linefeeds added at seemingly random spots, - // and indentation isn't handled properly on those lines. - "Appends a filter rule to the log message filter chain. Multiple " - "rules may be added by specifying this option multiple times, " - "once per filter rule. Filter rules are processed in the order " - "they are specified, with the --no-match-accepts setting used " - "for any message that doesn't match one of the rules.\n" - "\n" - " Filter spec format:\n" - "\n" - " --filter \"{action} {attribute} {op}\"\n" - "\n" - " {action} :=\n" - " accept |\n" - " reject\n" - "\n" - " {attribute} :=\n" - " activity | // message's most-derived activity\n" - " activity-chain | // message's {parent}:{child} activity\n" - " category | // message's category\n" - " message | // message's expanded contents\n" - " subsystem | // message's subsystem\n" - "\n" - " {op} :=\n" - " match {exact-match-text} |\n" - " regex {search-regex}\n" - "\n" - "The regex flavor used is the C++ std::regex ECMAScript format. " - "Prefer character classes like [[:digit:]] to \\d and the like, as " - "getting the backslashes escaped through properly is error-prone." - }, - { LLDB_OPT_SET_ALL, false, "live-stream", 'l', - OptionParser::eRequiredArgument, nullptr, nullptr, 0, - eArgTypeBoolean, - "Specify whether logging events are live-streamed or buffered. " - "True indicates live streaming, false indicates buffered. The " - "default is true (live streaming). Live streaming will deliver " - "log messages with less delay, but buffered capture mode has less " - "of an observer effect." }, - { LLDB_OPT_SET_ALL, false, "no-match-accepts", 'n', - OptionParser::eRequiredArgument, nullptr, nullptr, 0, - eArgTypeBoolean, - "Specify whether a log message that doesn't match any filter rule " - "is accepted or rejected, where true indicates accept. The " - "default is true." }, - { LLDB_OPT_SET_ALL, false, "echo-to-stderr", 'e', - OptionParser::eRequiredArgument, nullptr, nullptr, 0, - eArgTypeBoolean, - "Specify whether os_log()/NSLog() messages are echoed to the " - "target program's stderr. When DarwinLog is enabled, we shut off " - "the mirroring of os_log()/NSLog() to the program's stderr. " - "Setting this flag to true will restore the stderr mirroring." - "The default is false." }, - { LLDB_OPT_SET_ALL, false, "broadcast-events", 'b', - OptionParser::eRequiredArgument, nullptr, nullptr, 0, - eArgTypeBoolean, - "Specify if the plugin should broadcast events. Broadcasting " - "log events is a requirement for displaying the log entries in " - "LLDB command-line. It is also required if LLDB clients want to " - "process log events. The default is true." }, - // Message formatting options - { LLDB_OPT_SET_ALL, false, "timestamp-relative", 'r', - OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, - "Include timestamp in the message header when printing a log " - "message. The timestamp is relative to the first displayed " - "message." }, - { LLDB_OPT_SET_ALL, false, "subsystem", 's', - OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, - "Include the subsystem in the the message header when displaying " - "a log message." }, - { LLDB_OPT_SET_ALL, false, "category", 'c', - OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, - "Include the category in the the message header when displaying " - "a log message." }, - { LLDB_OPT_SET_ALL, false, "activity-chain", 'C', - OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, - "Include the activity parent-child chain in the the message header " - "when displaying a log message. The activity hierarchy is " - "displayed as {grandparent-activity}:" - "{parent-activity}:{activity}[:...]."}, - { LLDB_OPT_SET_ALL, false, "all-fields", 'A', - OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, - "Shortcut to specify that all header fields should be displayed." }, - - // Tail sentinel entry - { 0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr } - }; - - class EnableCommand : public CommandObjectParsed - { - public: - - EnableCommand(CommandInterpreter &interpreter, bool enable, - const char *name, const char *help, - const char *syntax) : - CommandObjectParsed(interpreter, name, help, syntax), - m_enable(enable), - m_options_sp(enable ? new EnableOptions() : nullptr) - { - } - - protected: - - void - AppendStrictSourcesWarning(CommandReturnObject &result, - const char *source_name) - { - if (!source_name) - return; - - // Check if we're *not* using strict sources. If not, - // then the user is going to get debug-level info - // anyways, probably not what they're expecting. - // Unfortunately we can only fix this by adding an - // env var, which would have had to have happened - // already. Thus, a warning is the best we can do here. - StreamString stream; - stream.Printf("darwin-log source settings specify to exclude " - "%s messages, but setting " - "'plugin.structured-data.darwin-log." - "strict-sources' is disabled. This process will " - "automatically have %s messages included. Enable" - " the property and relaunch the target binary to have" - " these messages excluded.", source_name, - source_name); - result.AppendWarning(stream.GetString().c_str()); - } - - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - // First off, set the global sticky state of enable/disable - // based on this command execution. - s_is_explicitly_enabled = m_enable; - - // Next, if this is an enable, save off the option data. - // We will need it later if a process hasn't been launched or - // attached yet. - if (m_enable) - { - // Save off enabled configuration so we can apply these parsed - // options the next time an attach or launch occurs. - DebuggerSP debugger_sp = - GetCommandInterpreter().GetDebugger().shared_from_this(); - SetGlobalEnableOptions(debugger_sp, m_options_sp); - } - - // Now check if we have a running process. If so, we should - // instruct the process monitor to enable/disable DarwinLog support - // now. - Target *target = GetSelectedOrDummyTarget(); - if (!target) - { - // No target, so there is nothing more to do right now. - result.SetStatus(eReturnStatusSuccessFinishNoResult); - return true; - } - - // Grab the active process. - auto process_sp = target->GetProcessSP(); - if (!process_sp) - { - // No active process, so there is nothing more to do right - // now. - result.SetStatus(eReturnStatusSuccessFinishNoResult); - return true; - } - - // If the process is no longer alive, we can't do this now. - // We'll catch it the next time the process is started up. - if (!process_sp->IsAlive()) - { - result.SetStatus(eReturnStatusSuccessFinishNoResult); - return true; - } - - // Get the plugin for the process. - auto plugin_sp = - process_sp->GetStructuredDataPlugin(GetDarwinLogTypeName()); - if (!plugin_sp || - (plugin_sp->GetPluginName() != - StructuredDataDarwinLog::GetStaticPluginName())) - { - result.AppendError("failed to get StructuredDataPlugin for " - "the process"); - result.SetStatus(eReturnStatusFailed); - } - StructuredDataDarwinLog &plugin = - *static_cast<StructuredDataDarwinLog*>(plugin_sp.get()); - - if (m_enable) - { - // To do this next part right, we need to track whether we - // added the proper environment variable at launch time. - // It is incorrect to assume that we're enabling after launch, - // and that therefore if we needed the env var set to properly - // handle the options, that it is set incorrectly. The env var - // could have been added if this is a re-enable using different - // arguments. This is a bit tricky as the point where we - // have to set the env var, we don't yet have a process or the - // associated darwin-log plugin instance, and thus don't have a - // great place to stick this knowledge. -#if 0 - // Check if we're attempting to disable debug-level or - // info-level content but we haven't launched with the magic - // env var that suppresses the "always add" of those. In - // that scenario, the user is asking *not* to see debug or - // info level messages, but will see them anyway. Warn and - // show how to correct it. - if (!m_options_sp->GetIncludeDebugLevel() && - !GetGlobalProperties()->GetUseStrictSources()) - { - AppendStrictSourcesWarning(result, "debug-level"); - } - - if (!m_options_sp->GetIncludeInfoLevel() && - !GetGlobalProperties()->GetUseStrictSources()) - { - AppendStrictSourcesWarning(result, "info-level"); - } -#endif - - // Hook up the breakpoint for the process that detects when - // libtrace has been sufficiently initialized to really start - // the os_log stream. This is insurance to assure us that - // logging is really enabled. Requesting that logging be - // enabled for a process before libtrace is initialized - // results in a scenario where no errors occur, but no logging - // is captured, either. This step is to eliminate that - // possibility. - plugin.AddInitCompletionHook(*process_sp.get()); - } - - // Send configuration to the feature by way of the process. - // Construct the options we will use. - auto config_sp = m_options_sp->BuildConfigurationData(m_enable); - const Error error = - process_sp->ConfigureStructuredData(GetDarwinLogTypeName(), - config_sp); - - // Report results. - if (!error.Success()) - { - result.AppendError(error.AsCString()); - result.SetStatus(eReturnStatusFailed); - // Our configuration failed, so we're definitely disabled. - plugin.SetEnabled(false); - } - else - { - result.SetStatus(eReturnStatusSuccessFinishNoResult); - // Our configuration succeeeded, so we're enabled/disabled - // per whichever one this command is setup to do. - plugin.SetEnabled(m_enable); - } - return result.Succeeded(); - } - - Options* - GetOptions () override - { - // We don't have options when this represents disable. - return m_enable ? m_options_sp.get() : nullptr; - } - - private: - const bool m_enable; - EnableOptionsSP m_options_sp; - }; - - // ------------------------------------------------------------------------- - /// Provides the status command. - // ------------------------------------------------------------------------- - class StatusCommand : public CommandObjectParsed - { - public: - - StatusCommand(CommandInterpreter &interpreter) : - CommandObjectParsed(interpreter, "status", - "Show whether Darwin log supported is available" - " and enabled.", - "plugin structured-data darwin-log status") - { - } - - protected: - - bool - DoExecute (Args& command, CommandReturnObject &result) override - { - auto &stream = result.GetOutputStream(); - - // Figure out if we've got a process. If so, we can tell if - // DarwinLog is available for that process. - Target *target = GetSelectedOrDummyTarget(); - auto process_sp = target ? target->GetProcessSP() : ProcessSP(); - if (!target || !process_sp) - { - stream.PutCString("Availability: unknown (requires process)\n"); - stream.PutCString("Enabled: not applicable " - "(requires process)\n"); - } - else - { - auto plugin_sp = - process_sp->GetStructuredDataPlugin(GetDarwinLogTypeName()); - stream.Printf("Availability: %s\n", plugin_sp ? "available" : - "unavailable"); - auto &plugin_name = - StructuredDataDarwinLog::GetStaticPluginName(); - const bool enabled = plugin_sp ? - plugin_sp->GetEnabled(plugin_name) : false; - stream.Printf("Enabled: %s\n", enabled ? "true" : - "false"); - } - - // Display filter settings. - DebuggerSP debugger_sp = - GetCommandInterpreter().GetDebugger().shared_from_this(); - auto options_sp = GetGlobalEnableOptions(debugger_sp); - if (!options_sp) - { - // Nothing more to do. - result.SetStatus(eReturnStatusSuccessFinishResult); - return true; - } - - // Print filter rules - stream.PutCString("DarwinLog filter rules:\n"); - - stream.IndentMore(); - - if (options_sp->GetFilterRules().empty()) - { - stream.Indent(); - stream.PutCString("none\n"); - } - else - { - // Print each of the filter rules. - int rule_number = 0; - for (auto rule_sp : options_sp->GetFilterRules()) - { - ++rule_number; - if (!rule_sp) - continue; - - stream.Indent(); - stream.Printf("%02d: ", rule_number); - rule_sp->Dump(stream); - stream.PutChar('\n'); - } - } - stream.IndentLess(); - - // Print no-match handling. - stream.Indent(); - stream.Printf("no-match behavior: %s\n", - options_sp->GetFallthroughAccepts() ? "accept" : - "reject"); - - result.SetStatus(eReturnStatusSuccessFinishResult); - return true; - } - }; - - // ------------------------------------------------------------------------- - /// Provides the darwin-log base command - // ------------------------------------------------------------------------- - class BaseCommand : public CommandObjectMultiword - { - public: - BaseCommand(CommandInterpreter &interpreter) : - CommandObjectMultiword(interpreter, - "plugin structured-data darwin-log", - "Commands for configuring Darwin os_log " - "support.", - "") - { - // enable - auto enable_help = "Enable Darwin log collection, or re-enable " - "with modified configuration."; - auto enable_syntax = "plugin structured-data darwin-log enable"; - auto enable_cmd_sp = - CommandObjectSP(new EnableCommand(interpreter, - true, // enable - "enable", - enable_help, - enable_syntax)); - LoadSubCommand("enable", enable_cmd_sp); - - // disable - auto disable_help = "Disable Darwin log collection."; - auto disable_syntax = "plugin structured-data darwin-log disable"; - auto disable_cmd_sp = - CommandObjectSP(new EnableCommand(interpreter, - false, // disable - "disable", - disable_help, - disable_syntax)); - LoadSubCommand("disable", disable_cmd_sp); - - // status - auto status_cmd_sp = - CommandObjectSP(new StatusCommand(interpreter)); - LoadSubCommand("status", status_cmd_sp); - } - }; - - EnableOptionsSP - ParseAutoEnableOptions(Error &error, Debugger &debugger) - { - // We are abusing the options data model here so that we can parse - // options without requiring the Debugger instance. - - // We have an empty execution context at this point. We only want - // to parse options, and we don't need any context to do this here. - // In fact, we want to be able to parse the enable options before having - // any context. - ExecutionContext exe_ctx; - - EnableOptionsSP options_sp(new EnableOptions()); - options_sp->NotifyOptionParsingStarting(&exe_ctx); - - CommandReturnObject result; - - // Parse the arguments. - auto options_property_sp = - debugger.GetPropertyValue(nullptr, - "plugin.structured-data.darwin-log." - "auto-enable-options", - false, - error); - if (!error.Success()) - return EnableOptionsSP(); - if (!options_property_sp) - { - error.SetErrorString("failed to find option setting for " - "plugin.structured-data.darwin-log."); - return EnableOptionsSP(); - } - - const char *enable_options = options_property_sp->GetAsString()->GetCurrentValue(); - Args args(enable_options); - if (args.GetArgumentCount() > 0) - { - // Eliminate the initial '--' that would be required to set the - // settings that themselves include '-' and/or '--'. - const char *first_arg = args.GetArgumentAtIndex(0); - if (first_arg && (strcmp(first_arg, "--") == 0)) - args.Shift(); - } - - // ParseOptions calls getopt_long_only, which always skips the zero'th item in the array and starts at position 1, - // so we need to push a dummy value into position zero. - args.Unshift("dummy_string"); - bool require_validation = false; - error = args.ParseOptions(*options_sp.get(), &exe_ctx, PlatformSP(), - require_validation); - if (!error.Success()) - return EnableOptionsSP(); - - if (!options_sp->VerifyOptions(result)) - return EnableOptionsSP(); - - // We successfully parsed and validated the options. - return options_sp; - } - - bool - RunEnableCommand(CommandInterpreter &interpreter) - { - StreamString command_stream; - - command_stream << "plugin structured-data darwin-log enable"; - auto enable_options = GetGlobalProperties()->GetAutoEnableOptions(); - if (enable_options && (strlen(enable_options) > 0)) - { - command_stream << ' '; - command_stream << enable_options; - } - - // Run the command. - CommandReturnObject return_object; - interpreter.HandleCommand(command_stream.GetString().c_str(), - eLazyBoolNo, - return_object); - return return_object.Succeeded(); - } -} -using namespace sddarwinlog_private; - -#pragma mark - -#pragma mark Public static API - -// ----------------------------------------------------------------------------- -// Public static API -// ----------------------------------------------------------------------------- - -void -StructuredDataDarwinLog::Initialize() -{ - RegisterFilterOperations(); - PluginManager::RegisterPlugin(GetStaticPluginName(), - "Darwin os_log() and os_activity() support", - &CreateInstance, - &DebuggerInitialize, - &FilterLaunchInfo); -} - -void -StructuredDataDarwinLog::Terminate() -{ - PluginManager::UnregisterPlugin(&CreateInstance); -} - -const ConstString& -StructuredDataDarwinLog::GetStaticPluginName() -{ - static ConstString s_plugin_name("darwin-log"); - return s_plugin_name; -} - -#pragma mark - -#pragma mark PluginInterface API - -// ----------------------------------------------------------------------------- -// PluginInterface API -// ----------------------------------------------------------------------------- - -ConstString -StructuredDataDarwinLog::GetPluginName() -{ - return GetStaticPluginName(); -} - -uint32_t -StructuredDataDarwinLog::GetPluginVersion() -{ - return 1; -} - -#pragma mark - -#pragma mark StructuredDataPlugin API - -// ----------------------------------------------------------------------------- -// StructuredDataPlugin API -// ----------------------------------------------------------------------------- - -bool -StructuredDataDarwinLog::SupportsStructuredDataType( - const ConstString &type_name) -{ - return type_name == GetDarwinLogTypeName(); -} - -void -StructuredDataDarwinLog::HandleArrivalOfStructuredData(Process &process, - const ConstString - &type_name, - const - StructuredData::ObjectSP - &object_sp) -{ - Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); - if (log) - { - StreamString json_stream; - if (object_sp) - object_sp->Dump(json_stream); - else - json_stream.PutCString("<null>"); - log->Printf("StructuredDataDarwinLog::%s() called with json: %s", - __FUNCTION__, json_stream.GetString().c_str()); - } - - // Ignore empty structured data. - if (!object_sp) - { - if (log) - log->Printf("StructuredDataDarwinLog::%s() StructuredData object " - "is null", __FUNCTION__); - return; - } - - // Ignore any data that isn't for us. - if (type_name != GetDarwinLogTypeName()) - { - if (log) - log->Printf("StructuredDataDarwinLog::%s() StructuredData type " - "expected to be %s but was %s, ignoring", __FUNCTION__, - GetDarwinLogTypeName().AsCString(), - type_name.AsCString()); - return; - } - - // Broadcast the structured data event if we have that enabled. - // This is the way that the outside world (all clients) get access - // to this data. This plugin sets policy as to whether we do that. - DebuggerSP debugger_sp = - process.GetTarget().GetDebugger().shared_from_this(); - auto options_sp = GetGlobalEnableOptions(debugger_sp); - if (options_sp && options_sp->GetBroadcastEvents()) - { - if (log) - log->Printf("StructuredDataDarwinLog::%s() broadcasting event", - __FUNCTION__); - process.BroadcastStructuredData(object_sp, shared_from_this()); - } - - // Later, hang on to a configurable amount of these and allow commands - // to inspect, including showing backtraces. -} - -static void -SetErrorWithJSON(Error &error, const char *message, - StructuredData::Object &object) -{ - if (!message) - { - error.SetErrorString("Internal error: message not set."); - return; - } - - StreamString object_stream; - object.Dump(object_stream); - object_stream.Flush(); - - error.SetErrorStringWithFormat("%s: %s", message, - object_stream.GetString().c_str()); -} - -Error -StructuredDataDarwinLog::GetDescription(const StructuredData::ObjectSP - &object_sp, - lldb_private::Stream &stream) -{ - Error error; - - if (!object_sp) - { - error.SetErrorString("No structured data."); - return error; - } - - // Log message payload objects will be dictionaries. - const StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary(); - if (!dictionary) - { - SetErrorWithJSON(error, "Structured data should have been a dictionary " - "but wasn't", *object_sp); - return error; - } - - // Validate this is really a message for our plugin. - ConstString type_name; - if (!dictionary->GetValueForKeyAsString("type", type_name)) - { - SetErrorWithJSON(error, "Structured data doesn't contain mandatory " - "type field", *object_sp); - return error; - } - - if (type_name != GetDarwinLogTypeName()) - { - // This is okay - it simply means the data we received is not a log - // message. We'll just format it as is. - object_sp->Dump(stream); - return error; - } - - // DarwinLog dictionaries store their data - // in an array with key name "events". - StructuredData::Array *events = nullptr; - if (!dictionary->GetValueForKeyAsArray("events", events) || - !events) - { - SetErrorWithJSON(error, "Log structured data is missing mandatory " - "'events' field, expected to be an array", *object_sp); - return error; - } - - events->ForEach([&stream, &error, &object_sp, this] - (StructuredData::Object *object) - { - if (!object) - { - // Invalid. Stop iterating. - SetErrorWithJSON(error, "Log event entry is null", *object_sp); - return false; - } - - auto event = object->GetAsDictionary(); - if (!event) - { - // Invalid, stop iterating. - SetErrorWithJSON(error, "Log event is not a dictionary", - *object_sp); - return false; - } - - // If we haven't already grabbed the first timestamp - // value, do that now. - if (!m_recorded_first_timestamp) - { - uint64_t timestamp = 0; - if (event->GetValueForKeyAsInteger("timestamp", - timestamp)) - { - m_first_timestamp_seen = timestamp; - m_recorded_first_timestamp = true; - } - } - - HandleDisplayOfEvent(*event, stream); - return true; - }); - - stream.Flush(); - return error; -} - -bool -StructuredDataDarwinLog::GetEnabled(const ConstString &type_name) const -{ - if (type_name == GetStaticPluginName()) - return m_is_enabled; - else - return false; -} - -void -StructuredDataDarwinLog::SetEnabled(bool enabled) -{ - m_is_enabled = enabled; -} - -void -StructuredDataDarwinLog::ModulesDidLoad(Process &process, - ModuleList &module_list) -{ - Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); - if (log) - log->Printf("StructuredDataDarwinLog::%s called (process uid %u)", - __FUNCTION__, process.GetUniqueID()); - - // Check if we should enable the darwin log support on startup/attach. - if (!GetGlobalProperties()->GetEnableOnStartup() && - !s_is_explicitly_enabled) - { - // We're neither auto-enabled or explicitly enabled, so we shouldn't - // try to enable here. - if (log) - log->Printf("StructuredDataDarwinLog::%s not applicable, we're not " - "enabled (process uid %u)", __FUNCTION__, - process.GetUniqueID()); - return; - } - - // If we already added the breakpoint, we've got nothing left to do. - { - std::lock_guard<std::mutex> locker(m_added_breakpoint_mutex); - if (m_added_breakpoint) - { - if (log) - log->Printf("StructuredDataDarwinLog::%s process uid %u's " - "post-libtrace-init breakpoint is already set", - __FUNCTION__, process.GetUniqueID()); - return; - } - } - - // The logging support module name, specifies the name of - // the image name that must be loaded into the debugged process before - // we can try to enable logging. - const char *logging_module_cstr = - GetGlobalProperties()->GetLoggingModuleName(); - if (!logging_module_cstr || (logging_module_cstr[0] == 0)) - { - // We need this. Bail. - if (log) - log->Printf("StructuredDataDarwinLog::%s no logging module name " - "specified, we don't know where to set a breakpoint " - "(process uid %u)", __FUNCTION__, - process.GetUniqueID()); - return; - } - - const ConstString logging_module_name = - ConstString(logging_module_cstr); - - // We need to see libtrace in the list of modules before we can enable - // tracing for the target process. - bool found_logging_support_module = false; - for (size_t i = 0; i < module_list.GetSize(); ++i) - { - auto module_sp = module_list.GetModuleAtIndex(i); - if (!module_sp) - continue; - - auto &file_spec = module_sp->GetFileSpec(); - found_logging_support_module = - (file_spec.GetLastPathComponent() == logging_module_name); - if (found_logging_support_module) - break; - } - - if (!found_logging_support_module) - { - if (log) - log->Printf("StructuredDataDarwinLog::%s logging module %s " - "has not yet been loaded, can't set a breakpoint " - "yet (process uid %u)", __FUNCTION__, - logging_module_name.AsCString(), - process.GetUniqueID()); - return; - } - - // Time to enqueue the breakpoint so we can wait for logging support - // to be initialized before we try to tap the libtrace stream. - AddInitCompletionHook(process); - if (log) - log->Printf("StructuredDataDarwinLog::%s post-init hook breakpoint " - "set for logging module %s (process uid %u)", __FUNCTION__, - logging_module_name.AsCString(), - process.GetUniqueID()); - - // We need to try the enable here as well, which will succeed - // in the event that we're attaching to (rather than launching) the - // process and the process is already past initialization time. In that - // case, the completion breakpoint will never get hit and therefore won't - // start that way. It doesn't hurt much beyond a bit of bandwidth - // if we end up doing this twice. It hurts much more if we don't get - // the logging enabled when the user expects it. - EnableNow(); -} - -#pragma mark - -#pragma mark Private instance methods - -// ----------------------------------------------------------------------------- -// Private constructors -// ----------------------------------------------------------------------------- - -StructuredDataDarwinLog::StructuredDataDarwinLog(const ProcessWP &process_wp) : - StructuredDataPlugin(process_wp), - m_recorded_first_timestamp(false), - m_first_timestamp_seen(0), - m_is_enabled(false), - m_added_breakpoint_mutex(), - m_added_breakpoint() -{ -} - -// ----------------------------------------------------------------------------- -// Private static methods -// ----------------------------------------------------------------------------- - -StructuredDataPluginSP -StructuredDataDarwinLog::CreateInstance(Process &process) -{ - // Currently only Apple targets support the os_log/os_activity - // protocol. - if (process.GetTarget().GetArchitecture().GetTriple().getVendor() == - llvm::Triple::VendorType::Apple) - { - auto process_wp = ProcessWP(process.shared_from_this()); - return StructuredDataPluginSP(new StructuredDataDarwinLog(process_wp)); - } - else - { - return StructuredDataPluginSP(); - } -} - -void -StructuredDataDarwinLog::DebuggerInitialize(Debugger &debugger) -{ - // Setup parent class first. - StructuredDataPlugin::InitializeBasePluginForDebugger(debugger); - - // Get parent command. - auto &interpreter = debugger.GetCommandInterpreter(); - std::string parent_command_text = "plugin structured-data"; - auto parent_command = - interpreter.GetCommandObjectForCommand(parent_command_text); - if (!parent_command) - { - // Ut oh, parent failed to create parent command. - // TODO log - return; - } - - auto command_name = "darwin-log"; - auto command_sp = CommandObjectSP(new BaseCommand(interpreter)); - bool result = parent_command->LoadSubCommand(command_name, command_sp); - if (!result) - { - // TODO log it once we setup structured data logging - } - - if (!PluginManager::GetSettingForPlatformPlugin(debugger, - StructuredDataDarwinLogProperties::GetSettingName())) - { - const bool is_global_setting = true; - PluginManager::CreateSettingForStructuredDataPlugin(debugger, - GetGlobalProperties()->GetValueProperties(), - ConstString ("Properties for the darwin-log" - " plug-in."), - is_global_setting); - } - -} - -Error -StructuredDataDarwinLog::FilterLaunchInfo(ProcessLaunchInfo &launch_info, - Target *target) -{ - Error error; - - // If we're not debugging this launched process, there's nothing for us - // to do here. - if (!launch_info.GetFlags().AnySet(eLaunchFlagDebug)) - return error; - - // Darwin os_log() support automatically adds debug-level and info-level - // messages when a debugger is attached to a process. However, with - // integrated suppport for debugging built into the command-line LLDB, - // the user may specifically set to *not* include debug-level and info-level - // content. When the user is using the integrated log support, we want - // to put the kabosh on that automatic adding of info and debug level. - // This is done by adding an environment variable to the process on launch. - // (This also means it is not possible to suppress this behavior if - // attaching to an already-running app). - // Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM)); - - // If the target architecture is not one that supports DarwinLog, we have - // nothing to do here. - auto &triple = target ? target->GetArchitecture().GetTriple() : - launch_info.GetArchitecture().GetTriple(); - if (triple.getVendor() != - llvm::Triple::Apple) - { - return error; - } - - // If DarwinLog is not enabled (either by explicit user command or via - // the auto-enable option), then we have nothing to do. - if (!GetGlobalProperties()->GetEnableOnStartup() && - !s_is_explicitly_enabled) - { - // Nothing to do, DarwinLog is not enabled. - return error; - } - - // If we don't have parsed configuration info, that implies we have - // enable-on-startup set up, but we haven't yet attempted to run the - // enable command. - if (!target) - { - // We really can't do this without a target. We need to be able - // to get to the debugger to get the proper options to do this right. - // TODO log. - error.SetErrorString("requires a target to auto-enable DarwinLog."); - return error; - } - - DebuggerSP debugger_sp = target->GetDebugger().shared_from_this(); - auto options_sp = GetGlobalEnableOptions(debugger_sp); - if (!options_sp && debugger_sp) - { - options_sp = ParseAutoEnableOptions(error, *debugger_sp.get()); - if (!options_sp || !error.Success()) - return error; - - // We already parsed the options, save them now so we don't generate - // them again until the user runs the command manually. - SetGlobalEnableOptions(debugger_sp, options_sp); - } - - auto &env_vars = launch_info.GetEnvironmentEntries(); - if (!options_sp->GetEchoToStdErr()) - { - // The user doesn't want to see os_log/NSLog messages echo to stderr. - // That mechanism is entirely separate from the DarwinLog support. - // By default we don't want to get it via stderr, because that would - // be in duplicate of the explicit log support here. - - // Here we need to strip out any OS_ACTIVITY_DT_MODE setting to prevent - // echoing of os_log()/NSLog() to stderr in the target program. - size_t argument_index; - if (env_vars.ContainsEnvironmentVariable("OS_ACTIVITY_DT_MODE", - &argument_index)) - env_vars.DeleteArgumentAtIndex(argument_index); - - // We will also set the env var that tells any downstream launcher - // from adding OS_ACTIVITY_DT_MODE. - env_vars.AddOrReplaceEnvironmentVariable( - "IDE_DISABLED_OS_ACTIVITY_DT_MODE", "1"); - } - - // Set the OS_ACTIVITY_MODE env var appropriately to enable/disable - // debug and info level messages. - const char *env_var_value; - if (options_sp->GetIncludeDebugLevel()) - env_var_value = "debug"; - else if (options_sp->GetIncludeInfoLevel()) - env_var_value = "info"; - else - env_var_value = ""; - - if (env_var_value) - { - const char *env_var_name = "OS_ACTIVITY_MODE"; - launch_info.GetEnvironmentEntries() - .AddOrReplaceEnvironmentVariable(env_var_name, env_var_value); - } - - return error; -} - -bool -StructuredDataDarwinLog::InitCompletionHookCallback(void *baton, - StoppointCallbackContext *context, - lldb::user_id_t break_id, - lldb::user_id_t break_loc_id) -{ - // We hit the init function. We now want to enqueue our new thread plan, - // which will in turn enqueue a StepOut thread plan. When the StepOut - // finishes and control returns to our new thread plan, that is the time - // when we can execute our logic to enable the logging support. - - Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); - if (log) - log->Printf("StructuredDataDarwinLog::%s() called", __FUNCTION__); - - // Get the current thread. - if (!context) - { - if (log) - log->Printf("StructuredDataDarwinLog::%s() warning: no context, " - "ignoring", __FUNCTION__); - return false; - } - - // Get the plugin from the process. - auto process_sp = context->exe_ctx_ref.GetProcessSP(); - if (!process_sp) - { - if (log) - log->Printf("StructuredDataDarwinLog::%s() warning: invalid " - "process in context, ignoring", __FUNCTION__); - return false; - } - if (log) - log->Printf("StructuredDataDarwinLog::%s() call is for process uid %d", - __FUNCTION__, process_sp->GetUniqueID()); - - auto plugin_sp = - process_sp->GetStructuredDataPlugin(GetDarwinLogTypeName()); - if (!plugin_sp) - { - if (log) - log->Printf("StructuredDataDarwinLog::%s() warning: no plugin for " - "feature %s in process uid %u", - __FUNCTION__, GetDarwinLogTypeName().AsCString(), - process_sp->GetUniqueID()); - return false; - } - - // Create the callback for when the thread plan completes. - bool called_enable_method = false; - const auto process_uid = process_sp->GetUniqueID(); - - std::weak_ptr<StructuredDataPlugin> plugin_wp(plugin_sp); - ThreadPlanCallOnFunctionExit::Callback callback = - [plugin_wp, &called_enable_method, log, process_uid]() { - if (log) - log->Printf("StructuredDataDarwinLog::post-init callback: " - "called (process uid %u)", process_uid); - - auto strong_plugin_sp = plugin_wp.lock(); - if (!strong_plugin_sp) - { - if (log) - log->Printf("StructuredDataDarwinLog::post-init callback: " - "plugin no longer exists, ignoring (process " - "uid %u)", process_uid); - return; - } - // Make sure we only call it once, just in case the - // thread plan hits the breakpoint twice. - if (!called_enable_method) - { - if (log) - log->Printf("StructuredDataDarwinLog::post-init callback: " - "calling EnableNow() (process uid %u)", - process_uid); - static_cast<StructuredDataDarwinLog*>(strong_plugin_sp.get()) - ->EnableNow(); - called_enable_method = true; - } - else - { - // Our breakpoint was hit more than once. Unexpected but - // no harm done. Log it. - if (log) - log->Printf("StructuredDataDarwinLog::post-init callback: " - "skipping EnableNow(), already called by " - "callback [we hit this more than once] " - "(process uid %u)", process_uid); - } - }; - - // Grab the current thread. - auto thread_sp = context->exe_ctx_ref.GetThreadSP(); - if (!thread_sp) - { - if (log) - log->Printf("StructuredDataDarwinLog::%s() warning: failed to " - "retrieve the current thread from the execution " - "context, nowhere to run the thread plan (process uid " - "%u)", __FUNCTION__, process_sp->GetUniqueID()); - return false; - } - - // Queue the thread plan. - auto thread_plan_sp - = ThreadPlanSP(new ThreadPlanCallOnFunctionExit(*thread_sp.get(), - callback)); - const bool abort_other_plans = false; - thread_sp->QueueThreadPlan(thread_plan_sp, abort_other_plans); - if (log) - log->Printf("StructuredDataDarwinLog::%s() queuing thread plan on " - "trace library init method entry (process uid %u)", - __FUNCTION__, process_sp->GetUniqueID()); - - // We return false here to indicate that it isn't a public stop. - return false; -} - -void -StructuredDataDarwinLog::AddInitCompletionHook(Process &process) -{ - Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); - if (log) - log->Printf("StructuredDataDarwinLog::%s() called (process uid %u)", - __FUNCTION__, process.GetUniqueID()); - - // Make sure we haven't already done this. - { - std::lock_guard<std::mutex> locker(m_added_breakpoint_mutex); - if (m_added_breakpoint) - { - if (log) - log->Printf("StructuredDataDarwinLog::%s() ignoring request, " - "breakpoint already set (process uid %u)", - __FUNCTION__, process.GetUniqueID()); - return; - } - - // We're about to do this, don't let anybody else try to do it. - m_added_breakpoint = true; - } - - // Set a breakpoint for the process that will kick in when libtrace - // has finished its initialization. - Target &target = process.GetTarget(); - - // Build up the module list. - FileSpecList module_spec_list; - auto module_file_spec = - FileSpec(GetGlobalProperties()->GetLoggingModuleName(), false); - module_spec_list.Append(module_file_spec); - - // We aren't specifying a source file set. - FileSpecList *source_spec_list = nullptr; - - const char *func_name = "_libtrace_init"; - const lldb::addr_t offset = 0; - const LazyBool skip_prologue = eLazyBoolCalculate; - // This is an internal breakpoint - the user shouldn't see it. - const bool internal = true; - const bool hardware = false; - - auto breakpoint_sp = - target.CreateBreakpoint(&module_spec_list, source_spec_list, func_name, - eFunctionNameTypeFull, eLanguageTypeC, offset, - skip_prologue, internal, hardware); - if (!breakpoint_sp) - { - // Huh? Bail here. - if (log) - log->Printf("StructuredDataDarwinLog::%s() failed to set " - "breakpoint in module %s, function %s (process uid %u)", - __FUNCTION__, - GetGlobalProperties()->GetLoggingModuleName(), - func_name, process.GetUniqueID()); - return; - } - - // Set our callback. - breakpoint_sp->SetCallback(InitCompletionHookCallback, nullptr); - if (log) - log->Printf("StructuredDataDarwinLog::%s() breakpoint set in module %s," - "function %s (process uid %u)", - __FUNCTION__, - GetGlobalProperties()->GetLoggingModuleName(), - func_name, process.GetUniqueID()); -} - -void -StructuredDataDarwinLog::DumpTimestamp(Stream &stream, uint64_t timestamp) -{ - const uint64_t delta_nanos = timestamp - m_first_timestamp_seen; - - const uint64_t hours = delta_nanos / NANOS_PER_HOUR; - uint64_t nanos_remaining = delta_nanos % NANOS_PER_HOUR; - - const uint64_t minutes = nanos_remaining / NANOS_PER_MINUTE; - nanos_remaining = nanos_remaining % NANOS_PER_MINUTE; - - const uint64_t seconds = nanos_remaining / NANOS_PER_SECOND; - nanos_remaining = nanos_remaining % NANOS_PER_SECOND; - - stream.Printf("%02" PRIu64 ":%02" PRIu64 ":%02" PRIu64 ".%09" PRIu64, - hours, minutes, seconds, nanos_remaining); -} - -size_t -StructuredDataDarwinLog::DumpHeader(Stream &output_stream, - const StructuredData::Dictionary &event) -{ - StreamString stream; - - ProcessSP process_sp = GetProcess(); - if (!process_sp) - { - // TODO log - return 0; - } - - DebuggerSP debugger_sp = - process_sp->GetTarget().GetDebugger().shared_from_this(); - if (!debugger_sp) - { - // TODO log - return 0; - } - - auto options_sp = GetGlobalEnableOptions(debugger_sp); - if (!options_sp) - { - // TODO log - return 0; - } - - // Check if we should even display a header. - if (!options_sp->GetDisplayAnyHeaderFields()) - return 0; - - stream.PutChar('['); - - int header_count = 0; - if (options_sp->GetDisplayTimestampRelative()) - { - uint64_t timestamp = 0; - if (event.GetValueForKeyAsInteger("timestamp", timestamp)) - { - DumpTimestamp(stream, timestamp); - ++header_count; - } - } - - if (options_sp->GetDisplayActivityChain()) - { - std::string activity_chain; - if (event.GetValueForKeyAsString("activity-chain", activity_chain) && - !activity_chain.empty()) - { - if (header_count > 0) - stream.PutChar(','); - - // Switch over to the #if 0 branch once we figure out - // how we want to present settings for the tri-state of - // no-activity, activity (most derived only), or activity-chain. -#if 1 - // Display the activity chain, from parent-most to child-most - // activity, separated by a colon (:). - stream.PutCString("activity-chain="); - stream.PutCString(activity_chain.c_str()); -#else - if (GetGlobalProperties()->GetDisplayActivityChain()) - { - // Display the activity chain, from parent-most to child-most - // activity, separated by a colon (:). - stream.PutCString("activity-chain="); - stream.PutCString(activity_chain.c_str()); - } - else - { - // We're only displaying the child-most activity. - stream.PutCString("activity="); - auto pos = activity_chain.find_last_of(':'); - if (pos == std::string::npos) - { - // The activity chain only has one level, use the whole - // thing. - stream.PutCString(activity_chain.c_str()); - } - else - { - // Display everything after the final ':'. - stream.PutCString(activity_chain.substr(pos+1).c_str()); - } - } -#endif - ++header_count; - } - } - - if (options_sp->GetDisplaySubsystem()) - { - std::string subsystem; - if (event.GetValueForKeyAsString("subsystem", - subsystem) && - !subsystem.empty()) - { - if (header_count > 0) - stream.PutChar(','); - stream.PutCString("subsystem="); - stream.PutCString(subsystem.c_str()); - ++header_count; - } - } - - if (options_sp->GetDisplayCategory()) - { - std::string category; - if (event.GetValueForKeyAsString("category", - category) && - !category.empty()) - { - if (header_count > 0) - stream.PutChar(','); - stream.PutCString("category="); - stream.PutCString(category.c_str()); - ++header_count; - } - } - stream.PutCString("] "); - - auto &result = stream.GetString(); - output_stream.PutCString(result.c_str()); - - return result.size(); -} - -size_t -StructuredDataDarwinLog::HandleDisplayOfEvent(const StructuredData::Dictionary - &event, Stream &stream) -{ - // Check the type of the event. - ConstString event_type; - if (!event.GetValueForKeyAsString("type", event_type)) - { - // Hmm, we expected to get events that describe - // what they are. Continue anyway. - return 0; - } - - if (event_type != GetLogEventType()) - return 0; - - size_t total_bytes = 0; - - // Grab the message content. - std::string message; - if (!event.GetValueForKeyAsString("message", message)) - return true; - - // Display the log entry. - const auto len = message.length(); - - total_bytes += DumpHeader(stream, event); - - stream.Write(message.c_str(), len); - total_bytes += len; - - // Add an end of line. - stream.PutChar('\n'); - total_bytes += sizeof(char); - - return total_bytes; -} - -void -StructuredDataDarwinLog::EnableNow() -{ - Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); - if (log) - log->Printf("StructuredDataDarwinLog::%s() called", __FUNCTION__); - - // Run the enable command. - auto process_sp = GetProcess(); - if (!process_sp) - { - // Nothing to do. - if (log) - log->Printf("StructuredDataDarwinLog::%s() warning: failed to get " - "valid process, skipping", __FUNCTION__); - return; - } - if (log) - log->Printf("StructuredDataDarwinLog::%s() call is for process uid %u", - __FUNCTION__, process_sp->GetUniqueID()); - - // If we have configuration data, we can directly enable it now. - // Otherwise, we need to run through the command interpreter to parse - // the auto-run options (which is the only way we get here without having - // already-parsed configuration data). - DebuggerSP debugger_sp = - process_sp->GetTarget().GetDebugger().shared_from_this(); - if (!debugger_sp) - { - if (log) - log->Printf("StructuredDataDarwinLog::%s() warning: failed to get " - "debugger shared pointer, skipping (process uid %u)", - __FUNCTION__, process_sp->GetUniqueID()); - return; - } - - auto options_sp = GetGlobalEnableOptions(debugger_sp); - if (!options_sp) - { - // We haven't run the enable command yet. Just do that now, it'll - // take care of the rest. - auto &interpreter = debugger_sp->GetCommandInterpreter(); - const bool success = RunEnableCommand(interpreter); - if (log) - { - if (success) - log->Printf("StructuredDataDarwinLog::%s() ran enable command " - "successfully for (process uid %u)", - __FUNCTION__, process_sp->GetUniqueID()); - else - log->Printf("StructuredDataDarwinLog::%s() error: running " - "enable command failed (process uid %u)", - __FUNCTION__, process_sp->GetUniqueID()); - } - // Report failures to the debugger error stream. - auto error_stream_sp = debugger_sp->GetAsyncErrorStream(); - if (error_stream_sp) - { - error_stream_sp->Printf("failed to configure DarwinLog " - "support\n"); - error_stream_sp->Flush(); - } - return; - } - - // We've previously been enabled. We will re-enable now with the - // previously specified options. - auto config_sp = options_sp->BuildConfigurationData(true); - if (!config_sp) - { - if (log) - log->Printf("StructuredDataDarwinLog::%s() warning: failed to " - "build configuration data for enable options, skipping " - "(process uid %u)", __FUNCTION__, - process_sp->GetUniqueID()); - return; - } - - // We can run it directly. - // Send configuration to the feature by way of the process. - const Error error = - process_sp->ConfigureStructuredData(GetDarwinLogTypeName(), - config_sp); - - // Report results. - if (!error.Success()) - { - if (log) - log->Printf("StructuredDataDarwinLog::%s() " - "ConfigureStructuredData() call failed " - "(process uid %u): %s", - __FUNCTION__, process_sp->GetUniqueID(), - error.AsCString()); - auto error_stream_sp = debugger_sp->GetAsyncErrorStream(); - if (error_stream_sp) - { - error_stream_sp->Printf("failed to configure DarwinLog " - "support: %s\n", error.AsCString()); - error_stream_sp->Flush(); - } - m_is_enabled = false; - } - else - { - m_is_enabled = true; - if (log) - log->Printf("StructuredDataDarwinLog::%s() success via direct " - "configuration (process uid %u)", __FUNCTION__, - process_sp->GetUniqueID()); - } -} diff --git a/lldb/source/Plugins/StructuredData/DarwinLog/StructuredDataDarwinLog.h b/lldb/source/Plugins/StructuredData/DarwinLog/StructuredDataDarwinLog.h deleted file mode 100644 index 5dcb37b04ea..00000000000 --- a/lldb/source/Plugins/StructuredData/DarwinLog/StructuredDataDarwinLog.h +++ /dev/null @@ -1,164 +0,0 @@ -//===-- StructuredDataDarwinLog.h -------------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - - -#ifndef StructuredDataDarwinLog_h -#define StructuredDataDarwinLog_h - -#include "lldb/Target/StructuredDataPlugin.h" - -#include <mutex> - -// Forward declarations -namespace sddarwinlog_private -{ - class EnableCommand; -} - -namespace lldb_private -{ - -class StructuredDataDarwinLog : public StructuredDataPlugin -{ - friend sddarwinlog_private::EnableCommand; - -public: - - // ------------------------------------------------------------------------- - // Public static API - // ------------------------------------------------------------------------- - - static void - Initialize(); - - static void - Terminate(); - - static const ConstString& - GetStaticPluginName(); - - // ------------------------------------------------------------------------- - /// Return whether the DarwinLog functionality is enabled. - /// - /// The DarwinLog functionality is enabled if the user expicitly enabled - /// it with the enable command, or if the user has the setting set - /// that controls if we always enable it for newly created/attached - /// processes. - /// - /// @return - /// True if DarwinLog support is/will be enabled for existing or - /// newly launched/attached processes. - // ------------------------------------------------------------------------- - static bool - IsEnabled(); - - // ------------------------------------------------------------------------- - // PluginInterface API - // ------------------------------------------------------------------------- - - ConstString - GetPluginName() override; - - uint32_t - GetPluginVersion() override; - - // ------------------------------------------------------------------------- - // StructuredDataPlugin API - // ------------------------------------------------------------------------- - - bool - SupportsStructuredDataType(const ConstString &type_name) override; - - void - HandleArrivalOfStructuredData(Process &process, - const ConstString &type_name, - const StructuredData::ObjectSP - &object_sp) override; - - Error - GetDescription(const StructuredData::ObjectSP &object_sp, - lldb_private::Stream &stream) override; - - - bool - GetEnabled(const ConstString &type_name) const override; - - void - ModulesDidLoad(Process &process, ModuleList &module_list) override; - -private: - - // ------------------------------------------------------------------------- - // Private constructors - // ------------------------------------------------------------------------- - - StructuredDataDarwinLog(const lldb::ProcessWP &process_wp); - - // ------------------------------------------------------------------------- - // Private static methods - // ------------------------------------------------------------------------- - - static lldb::StructuredDataPluginSP - CreateInstance(Process &process); - - static void - DebuggerInitialize(Debugger &debugger); - - static bool - InitCompletionHookCallback(void *baton, StoppointCallbackContext *context, - lldb::user_id_t break_id, - lldb::user_id_t break_loc_id); - - static Error - FilterLaunchInfo(ProcessLaunchInfo &launch_info, Target *target); - - // ------------------------------------------------------------------------- - // Internal helper methods used by friend classes - // ------------------------------------------------------------------------- - void - SetEnabled(bool enabled); - - void - AddInitCompletionHook(Process &process); - - // ------------------------------------------------------------------------- - // Private methods - // ------------------------------------------------------------------------- - - void - DumpTimestamp(Stream &stream, uint64_t timestamp); - - size_t - DumpHeader(Stream &stream, const StructuredData::Dictionary &event); - - size_t - HandleDisplayOfEvent(const StructuredData::Dictionary &event, - Stream &stream); - - // ------------------------------------------------------------------------- - /// Call the enable command again, using whatever settings were initially - /// made. - // ------------------------------------------------------------------------- - - void - EnableNow(); - - // ------------------------------------------------------------------------- - // Private data - // ------------------------------------------------------------------------- - bool m_recorded_first_timestamp; - uint64_t m_first_timestamp_seen; - bool m_is_enabled; - std::mutex m_added_breakpoint_mutex; - bool m_added_breakpoint; -}; - -} - -#endif /* StructuredDataPluginDarwinLog_hpp */ diff --git a/lldb/source/Target/CMakeLists.txt b/lldb/source/Target/CMakeLists.txt index cdb047a6640..f1c2a7e9800 100644 --- a/lldb/source/Target/CMakeLists.txt +++ b/lldb/source/Target/CMakeLists.txt @@ -30,7 +30,6 @@ add_lldb_library(lldbTarget StackFrameList.cpp StackID.cpp StopInfo.cpp - StructuredDataPlugin.cpp SystemRuntime.cpp Target.cpp TargetList.cpp @@ -41,7 +40,6 @@ add_lldb_library(lldbTarget ThreadPlanBase.cpp ThreadPlanCallFunction.cpp ThreadPlanCallFunctionUsingABI.cpp - ThreadPlanCallOnFunctionExit.cpp ThreadPlanCallUserExpression.cpp ThreadPlanPython.cpp ThreadPlanRunToAddress.cpp diff --git a/lldb/source/Target/Platform.cpp b/lldb/source/Target/Platform.cpp index 884c9b2cbcd..2abff2b9e95 100644 --- a/lldb/source/Target/Platform.cpp +++ b/lldb/source/Target/Platform.cpp @@ -1314,34 +1314,7 @@ Platform::DebugProcess (ProcessLaunchInfo &launch_info, // group, since then we can handle ^C interrupts ourselves w/o having to worry // about the target getting them as well. launch_info.SetLaunchInSeparateProcessGroup(true); - - // Allow any StructuredData process-bound plugins to adjust the launch info - // if needed - size_t i = 0; - bool iteration_complete = false; - // Note iteration can't simply go until a nullptr callback is returned, as - // it is valid for a plugin to not supply a filter. - auto get_filter_func = - PluginManager::GetStructuredDataFilterCallbackAtIndex; - for (auto filter_callback = get_filter_func(i, iteration_complete); - !iteration_complete; - filter_callback = get_filter_func(++i, iteration_complete)) - { - if (filter_callback) - { - // Give this ProcessLaunchInfo filter a chance to adjust the launch - // info. - error = (*filter_callback)(launch_info, target); - if (!error.Success()) - { - if (log) - log->Printf("Platform::%s() StructuredDataPlugin launch " - "filter failed.", __FUNCTION__); - return process_sp; - } - } - } - + error = LaunchProcess (launch_info); if (error.Success()) { diff --git a/lldb/source/Target/Process.cpp b/lldb/source/Target/Process.cpp index c4f20d7d465..e95c8ee7f25 100644 --- a/lldb/source/Target/Process.cpp +++ b/lldb/source/Target/Process.cpp @@ -54,7 +54,6 @@ #include "lldb/Target/Process.h" #include "lldb/Target/RegisterContext.h" #include "lldb/Target/StopInfo.h" -#include "lldb/Target/StructuredDataPlugin.h" #include "lldb/Target/SystemRuntime.h" #include "lldb/Target/Target.h" #include "lldb/Target/TargetList.h" @@ -798,7 +797,6 @@ Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp, const UnixSig SetEventName(eBroadcastBitSTDOUT, "stdout-available"); SetEventName(eBroadcastBitSTDERR, "stderr-available"); SetEventName(eBroadcastBitProfileData, "profile-data-available"); - SetEventName(eBroadcastBitStructuredData, "structured-data-available"); m_private_state_control_broadcaster.SetEventName(eBroadcastInternalStateControlStop, "control-stop"); m_private_state_control_broadcaster.SetEventName(eBroadcastInternalStateControlPause, "control-pause"); @@ -806,8 +804,7 @@ Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp, const UnixSig m_listener_sp->StartListeningForEvents(this, eBroadcastBitStateChanged | eBroadcastBitInterrupt | eBroadcastBitSTDOUT | eBroadcastBitSTDERR | - eBroadcastBitProfileData | - eBroadcastBitStructuredData); + eBroadcastBitProfileData); m_private_state_listener_sp->StartListeningForEvents(&m_private_state_broadcaster, eBroadcastBitStateChanged | eBroadcastBitInterrupt); @@ -4798,25 +4795,6 @@ Process::BroadcastAsyncProfileData(const std::string &one_profile_data) BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState())); } -void -Process::BroadcastStructuredData(const StructuredData::ObjectSP &object_sp, - const StructuredDataPluginSP &plugin_sp) -{ - BroadcastEvent(eBroadcastBitStructuredData, - new EventDataStructuredData(shared_from_this(), - object_sp, plugin_sp)); -} - -StructuredDataPluginSP -Process::GetStructuredDataPlugin(const ConstString &type_name) const -{ - auto find_it = m_structured_data_plugin_map.find(type_name); - if (find_it != m_structured_data_plugin_map.end()) - return find_it->second; - else - return StructuredDataPluginSP(); -} - size_t Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error) { @@ -6403,13 +6381,6 @@ Process::ModulesDidLoad (ModuleList &module_list) // loading shared libraries might cause a new one to try and load if (!m_os_ap) LoadOperatingSystemPlugin(false); - - // Give structured-data plugins a chance to see the modified modules. - for (auto pair : m_structured_data_plugin_map) - { - if (pair.second) - pair.second->ModulesDidLoad(*this, module_list); - } } void @@ -6627,129 +6598,5 @@ Process::GetMemoryRegions (std::vector<lldb::MemoryRegionInfoSP>& region_list) } while (range_end != LLDB_INVALID_ADDRESS); return error; -} - -Error -Process::ConfigureStructuredData(const ConstString &type_name, - const StructuredData::ObjectSP &config_sp) -{ - // If you get this, the Process-derived class needs to implement a method - // to enable an already-reported asynchronous structured data feature. - // See ProcessGDBRemote for an example implementation over gdb-remote. - return Error("unimplemented"); -} - -void -Process::MapSupportedStructuredDataPlugins(const StructuredData::Array - &supported_type_names) -{ - Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); - - // Bail out early if there are no type names to map. - if (supported_type_names.GetSize() == 0) - { - if (log) - log->Printf("Process::%s(): no structured data types supported", - __FUNCTION__); - return; - } - - // Convert StructuredData type names to ConstString instances. - std::set<ConstString> const_type_names; - - if (log) - log->Printf("Process::%s(): the process supports the following async " - "structured data types:", __FUNCTION__); - - supported_type_names.ForEach([&const_type_names, &log] - (StructuredData::Object *object) { - if (!object) - { - // Invalid - shouldn't be null objects in the array. - return false; - } - - auto type_name = object->GetAsString(); - if (!type_name) - { - // Invalid format - all type names should be strings. - return false; - } - - const_type_names.insert(ConstString(type_name->GetValue())); - if (log) - log->Printf("- %s", type_name->GetValue().c_str()); - return true; - }); - - // For each StructuredDataPlugin, if the plugin handles any of the - // types in the supported_type_names, map that type name to that plugin. - uint32_t plugin_index = 0; - for (auto create_instance = - PluginManager::GetStructuredDataPluginCreateCallbackAtIndex(plugin_index); - create_instance && !const_type_names.empty(); - ++plugin_index) - { - // Create the plugin. - StructuredDataPluginSP plugin_sp = (*create_instance)(*this); - if (!plugin_sp) - { - // This plugin doesn't think it can work with the process. - // Move on to the next. - continue; - } - - // For any of the remaining type names, map any that this plugin - // supports. - std::vector<ConstString> names_to_remove; - for (auto &type_name : const_type_names) - { - if (plugin_sp->SupportsStructuredDataType(type_name)) - { - m_structured_data_plugin_map.insert(std::make_pair(type_name, - plugin_sp)); - names_to_remove.push_back(type_name); - if (log) - log->Printf("Process::%s(): using plugin %s for type name " - "%s", __FUNCTION__, - plugin_sp->GetPluginName().GetCString(), - type_name.GetCString()); - } - } - // Remove the type names that were consumed by this plugin. - for (auto &type_name : names_to_remove) - const_type_names.erase(type_name); - } -} - -bool -Process::RouteAsyncStructuredData(const StructuredData::ObjectSP object_sp) -{ - // Nothing to do if there's no data. - if (!object_sp) - return false; - - // The contract is this must be a dictionary, so we can look up the - // routing key via the top-level 'type' string value within the dictionary. - StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary(); - if (!dictionary) - return false; - - // Grab the async structured type name (i.e. the feature/plugin name). - ConstString type_name; - if (!dictionary->GetValueForKeyAsString("type", type_name)) - return false; - - // Check if there's a plugin registered for this type name. - auto find_it = m_structured_data_plugin_map.find(type_name); - if (find_it == m_structured_data_plugin_map.end()) - { - // We don't have a mapping for this structured data type. - return false; - } - - // Route the structured data to the plugin. - find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp); - return true; } diff --git a/lldb/source/Target/StructuredDataPlugin.cpp b/lldb/source/Target/StructuredDataPlugin.cpp deleted file mode 100644 index 8930af2dac6..00000000000 --- a/lldb/source/Target/StructuredDataPlugin.cpp +++ /dev/null @@ -1,89 +0,0 @@ -//===-- StructuredDataPlugin.cpp --------------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#include "lldb/Target/StructuredDataPlugin.h" - -#include "lldb/Core/Debugger.h" -#include "lldb/Interpreter/CommandInterpreter.h" -#include "lldb/Interpreter/CommandObjectMultiword.h" - -using namespace lldb; -using namespace lldb_private; - -namespace -{ - class CommandStructuredData : public CommandObjectMultiword - { - public: - CommandStructuredData(CommandInterpreter &interpreter) : - CommandObjectMultiword(interpreter, - "structured-data", - "Parent for per-plugin structured data commands", - "plugin structured-data <plugin>") - { - } - - ~CommandStructuredData() - { - } - }; -} - -StructuredDataPlugin::StructuredDataPlugin(const ProcessWP &process_wp) : - PluginInterface(), - m_process_wp(process_wp) -{ -} - -StructuredDataPlugin::~StructuredDataPlugin() -{ -} - -bool -StructuredDataPlugin::GetEnabled(const ConstString &type_name) const -{ - // By default, plugins are always enabled. Plugin authors should override - // this if there is an enabled/disabled state for their plugin. -} - -ProcessSP -StructuredDataPlugin::GetProcess() const -{ - return m_process_wp.lock(); -} - -void -StructuredDataPlugin::InitializeBasePluginForDebugger(Debugger &debugger) -{ - // Create our mutliword command anchor if it doesn't already exist. - auto &interpreter = debugger.GetCommandInterpreter(); - if (!interpreter.GetCommandObject("plugin structured-data")) - { - // Find the parent command. - auto parent_command = - debugger.GetCommandInterpreter().GetCommandObject("plugin"); - if (!parent_command) - return; - - // Create the structured-data ommand object. - auto command_name = "structured-data"; - auto command_sp = - CommandObjectSP(new CommandStructuredData(interpreter)); - - // Hook it up under the top-level plugin command. - parent_command->LoadSubCommand(command_name, - command_sp); - } -} - -void -StructuredDataPlugin::ModulesDidLoad(Process &process, ModuleList &module_list) -{ - // Default implementation does nothing. -} diff --git a/lldb/source/Target/ThreadPlanCallOnFunctionExit.cpp b/lldb/source/Target/ThreadPlanCallOnFunctionExit.cpp deleted file mode 100644 index b2383e4f122..00000000000 --- a/lldb/source/Target/ThreadPlanCallOnFunctionExit.cpp +++ /dev/null @@ -1,119 +0,0 @@ -//===-- ThreadPlanCallOnFunctionExit.cpp ------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#include "lldb/Target/ThreadPlanCallOnFunctionExit.h" - -using namespace lldb; -using namespace lldb_private; - -ThreadPlanCallOnFunctionExit::ThreadPlanCallOnFunctionExit(Thread &thread, - const Callback - &callback) : - ThreadPlan(ThreadPlanKind::eKindGeneric, "CallOnFunctionExit", - thread, - eVoteNoOpinion, eVoteNoOpinion // TODO check with Jim on these - ), - m_callback(callback) -{ - // We are not a user-generated plan. - SetIsMasterPlan(false); -} - -void -ThreadPlanCallOnFunctionExit::DidPush() -{ - // We now want to queue the "step out" thread plan so it executes - // and completes. - - // Set stop vote to eVoteNo. - m_step_out_threadplan_sp = GetThread() - .QueueThreadPlanForStepOut(false, // abort other plans - nullptr, // addr_context - true, // first instruction - true, // stop other threads - eVoteNo, // do not say "we're stopping" - eVoteNoOpinion, // don't care about - // run state broadcasting - 0, // frame_idx - eLazyBoolCalculate // avoid code w/o debinfo - ); -} - -// ------------------------------------------------------------------------- -// ThreadPlan API -// ------------------------------------------------------------------------- - -void -ThreadPlanCallOnFunctionExit::GetDescription(Stream *s, lldb::DescriptionLevel - level) -{ - if (!s) - return; - s->Printf("Running until completion of current function, then making " - "callback."); -} - -bool -ThreadPlanCallOnFunctionExit::ValidatePlan(Stream *error) -{ - // We'll say we're always good since I don't know what would make this - // invalid. - return true; -} - -bool -ThreadPlanCallOnFunctionExit::ShouldStop(Event *event_ptr) -{ - // If this is where we find out that an internal stop came in, then: - // Check if the step-out plan completed. If it did, then we want to - // run the callback here (our reason for living...) - if (m_step_out_threadplan_sp && - m_step_out_threadplan_sp->IsPlanComplete()) - { - m_callback(); - - // We no longer need the pointer to the step-out thread plan. - m_step_out_threadplan_sp.reset(); - - // Indicate that this plan is done and can be discarded. - SetPlanComplete(); - - // We're done now, but we want to return false so that we - // don't cause the thread to really stop. - } - - return false; -} - -bool -ThreadPlanCallOnFunctionExit::WillStop() -{ - // The code looks like the return value is ignored via ThreadList:: - // ShouldStop(). - // This is called when we really are going to stop. We don't care - // and don't need to do anything here. - return false; -} - -bool -ThreadPlanCallOnFunctionExit::DoPlanExplainsStop (Event *event_ptr) -{ - // We don't ever explain a stop. The only stop that is relevant - // to us directly is the step_out plan we added to do the heavy lifting - // of getting us past the current method. - return false; -} - -lldb::StateType -ThreadPlanCallOnFunctionExit::GetPlanRunState() -{ - // This value doesn't matter - we'll never be the top thread plan, so - // nobody will ask us this question. - return eStateRunning; -} |