[Lldb-commits] [lldb] [lldb/Target] Unify frame provider descriptor and chain IDs (PR #190712)

via lldb-commits lldb-commits at lists.llvm.org
Mon Apr 6 16:56:29 PDT 2026


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-lldb

Author: Med Ismail Bennani (medismailben)

<details>
<summary>Changes</summary>

Replace the two separate ID systems for frame providers — hash-based
descriptor IDs in Target and sequential chain IDs in Thread — with a
single monotonic counter in Target.

Provider IDs are now assigned by Target::AddScriptedFrameProviderDescriptor
and used directly as the chain ID in Thread, so RegisterScriptedFrameProvider
returns the same ID used by 'bt --provider'. Also add duplicate detection to
reject registering a provider with the same class name and arguments twice.

---

Patch is 57.81 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/190712.diff


18 Files Affected:

- (modified) lldb/include/lldb/Interpreter/CommandOptionArgumentTable.h (+1) 
- (modified) lldb/include/lldb/Target/SyntheticFrameProvider.h (+15-4) 
- (modified) lldb/include/lldb/Target/Target.h (+7-4) 
- (modified) lldb/include/lldb/Target/Thread.h (+19-4) 
- (modified) lldb/include/lldb/lldb-enumerations.h (+1) 
- (modified) lldb/source/Commands/CommandObjectTarget.cpp (+1-1) 
- (modified) lldb/source/Commands/CommandObjectThread.cpp (+188-5) 
- (modified) lldb/source/Commands/Options.td (+9) 
- (modified) lldb/source/Interpreter/CommandInterpreter.cpp (+9) 
- (modified) lldb/source/Target/SyntheticFrameProvider.cpp (+11-1) 
- (modified) lldb/source/Target/Target.cpp (+19-7) 
- (modified) lldb/source/Target/Thread.cpp (+30-20) 
- (modified) lldb/test/API/functionalities/scripted_frame_provider/pass_through_prefix/TestFrameProviderPassThroughPrefix.py (+402-12) 
- (modified) lldb/test/API/functionalities/scripted_frame_provider/pass_through_prefix/frame_provider.py (+65-8) 
- (added) lldb/test/API/functionalities/scripted_frame_provider/thread_filter/Makefile (+3) 
- (added) lldb/test/API/functionalities/scripted_frame_provider/thread_filter/TestFrameProviderThreadFilter.py (+94) 
- (added) lldb/test/API/functionalities/scripted_frame_provider/thread_filter/frame_provider.py (+110) 
- (added) lldb/test/API/functionalities/scripted_frame_provider/thread_filter/main.cpp (+18) 


``````````diff
diff --git a/lldb/include/lldb/Interpreter/CommandOptionArgumentTable.h b/lldb/include/lldb/Interpreter/CommandOptionArgumentTable.h
index 701491b71fb27..600b9639c4d4d 100644
--- a/lldb/include/lldb/Interpreter/CommandOptionArgumentTable.h
+++ b/lldb/include/lldb/Interpreter/CommandOptionArgumentTable.h
@@ -258,6 +258,7 @@ static constexpr CommandObject::ArgumentTableEntry g_argument_table[] = {
     { lldb::eArgTypeFilename, "filename", lldb::eDiskFileCompletion, {}, { nullptr, false }, "The name of a file (can include path)." },
     { lldb::eArgTypeFormat, "format", lldb::CompletionType::eNoCompletion, {}, { FormatHelpTextCallback, true }, nullptr },
     { lldb::eArgTypeFrameIndex, "frame-index", lldb::eFrameIndexCompletion, {}, { nullptr, false }, "Index into a thread's list of frames." },
+    { lldb::eArgTypeFrameProviderIDRange, "frame-provider-id-range", lldb::CompletionType::eNoCompletion, {}, { nullptr, false }, "A single frame provider ID, a range of IDs (e.g., '0', '0-2', '0 to 2'), or '*'/'all' to show every provider. ID 0 is the base unwinder, 1+ are synthetic providers." },
     { lldb::eArgTypeFullName, "fullname", lldb::CompletionType::eNoCompletion, {}, { nullptr, false }, "Help text goes here." },
     { lldb::eArgTypeFunctionName, "function-name", lldb::CompletionType::eNoCompletion, {}, { nullptr, false }, "The name of a function." },
     { lldb::eArgTypeFunctionOrSymbol, "function-or-symbol", lldb::CompletionType::eNoCompletion, {}, { nullptr, false }, "The name of a function or symbol." },
diff --git a/lldb/include/lldb/Target/SyntheticFrameProvider.h b/lldb/include/lldb/Target/SyntheticFrameProvider.h
index bbd52b144412d..249a9bb714ff6 100644
--- a/lldb/include/lldb/Target/SyntheticFrameProvider.h
+++ b/lldb/include/lldb/Target/SyntheticFrameProvider.h
@@ -36,6 +36,10 @@ struct ScriptedFrameProviderDescriptor {
   /// satisfies ANY of the specs in this vector (OR logic).
   std::vector<ThreadSpec> thread_specs;
 
+  /// Monotonic ID assigned by Target when this descriptor is registered.
+  /// Zero means no ID has been assigned yet.
+  uint32_t m_id = 0;
+
   ScriptedFrameProviderDescriptor() = default;
 
   ScriptedFrameProviderDescriptor(lldb::ScriptedMetadataSP metadata_sp)
@@ -83,12 +87,19 @@ struct ScriptedFrameProviderDescriptor {
   /// Check if this descriptor has valid metadata for script-based providers.
   bool IsValid() const { return scripted_metadata_sp != nullptr; }
 
-  /// Get a unique identifier for this descriptor based on its contents.
-  /// The ID is computed from the class name and arguments dictionary,
-  /// not from the pointer address, so two descriptors with the same
-  /// contents will have the same ID.
+  /// Get a unique identifier for this descriptor.
+  /// Returns the monotonic ID assigned by Target if set (non-zero),
+  /// otherwise falls back to the content-based hash from ScriptedMetadata.
   uint32_t GetID() const;
 
+  /// Set the monotonic ID for this descriptor. Called by Target when
+  /// the descriptor is registered.
+  void SetID(uint32_t id) { m_id = id; }
+
+  /// Get the content-based hash from ScriptedMetadata.
+  /// Used for duplicate detection (same class name + args).
+  uint32_t GetArgumentsHash() const;
+
   /// Dump a description of this descriptor to the given stream.
   void Dump(Stream *s) const;
 };
diff --git a/lldb/include/lldb/Target/Target.h b/lldb/include/lldb/Target/Target.h
index 2e9ee1de3c456..ab317d0d686b8 100644
--- a/lldb/include/lldb/Target/Target.h
+++ b/lldb/include/lldb/Target/Target.h
@@ -41,6 +41,7 @@
 #include "lldb/Utility/StructuredData.h"
 #include "lldb/Utility/Timeout.h"
 #include "lldb/lldb-public.h"
+#include "llvm/ADT/MapVector.h"
 #include "llvm/ADT/StringRef.h"
 
 namespace lldb_private {
@@ -798,7 +799,7 @@ class Target : public std::enable_shared_from_this<Target>,
   void ClearScriptedFrameProviderDescriptors();
 
   /// Get all scripted frame provider descriptors for this target.
-  const llvm::DenseMap<uint32_t, ScriptedFrameProviderDescriptor> &
+  const llvm::MapVector<uint32_t, ScriptedFrameProviderDescriptor> &
   GetScriptedFrameProviderDescriptors() const;
 
 protected:
@@ -1806,11 +1807,13 @@ class Target : public std::enable_shared_from_this<Target>,
   TypeSystemMap m_scratch_type_system_map;
 
   /// Map of scripted frame provider descriptors for this target.
-  /// Keys are the provider descriptors ids, values are the descriptors.
-  /// Used to initialize frame providers for new threads.
-  llvm::DenseMap<uint32_t, ScriptedFrameProviderDescriptor>
+  /// Keys are the provider descriptor IDs, values are the descriptors.
+  /// Insertion order is preserved so that equal-priority providers chain
+  /// in registration order.
+  llvm::MapVector<uint32_t, ScriptedFrameProviderDescriptor>
       m_frame_provider_descriptors;
   mutable std::recursive_mutex m_frame_provider_descriptors_mutex;
+  uint32_t m_next_frame_provider_id = 1;
 
   typedef std::map<lldb::LanguageType, lldb::REPLSP> REPLMap;
   REPLMap m_repl_map;
diff --git a/lldb/include/lldb/Target/Thread.h b/lldb/include/lldb/Target/Thread.h
index c698dd8015885..4353725ca47f6 100644
--- a/lldb/include/lldb/Target/Thread.h
+++ b/lldb/include/lldb/Target/Thread.h
@@ -1324,6 +1324,25 @@ class Thread : public std::enable_shared_from_this<Thread>,
   /// Returns true if any host thread is currently inside a provider.
   bool IsAnyProviderActive();
 
+  /// Get the ordered chain of provider descriptors and their frame list IDs.
+  ///
+  /// Each element is a pair of:
+  ///   - \b ScriptedFrameProviderDescriptor: metadata for the provider
+  ///     (class name, description, priority, thread specs).
+  ///   - \b frame_list_id_t: the sequential frame list identifier assigned
+  ///     to that provider in the chain (1 for the first provider, 2 for the
+  ///     second, etc.). ID 0 is reserved for the base unwinder and is never
+  ///     present in this vector.
+  ///
+  /// The vector is ordered by provider chain position (registration order
+  /// adjusted by priority). It persists across \c ClearStackFrames() so that
+  /// provider IDs remain stable for the lifetime of the thread.
+  const std::vector<
+      std::pair<ScriptedFrameProviderDescriptor, lldb::frame_list_id_t>> &
+  GetProviderChainIds() const {
+    return m_provider_chain_ids;
+  }
+
 protected:
   friend class ThreadPlan;
   friend class ThreadList;
@@ -1458,10 +1477,6 @@ class Thread : public std::enable_shared_from_this<Thread>,
   mutable llvm::DenseMap<lldb::frame_list_id_t, lldb::StackFrameListWP>
       m_frame_lists_by_id;
 
-  /// Counter for assigning unique provider IDs. Starts at 1 since 0 is
-  /// reserved for normal unwinder frames. Persists across ClearStackFrames.
-  lldb::frame_list_id_t m_next_provider_id = 1;
-
 private:
   bool m_extended_info_fetched; // Have we tried to retrieve the m_extended_info
                                 // for this thread?
diff --git a/lldb/include/lldb/lldb-enumerations.h b/lldb/include/lldb/lldb-enumerations.h
index 11b7808bb1b61..4d31c4db5c20b 100644
--- a/lldb/include/lldb/lldb-enumerations.h
+++ b/lldb/include/lldb/lldb-enumerations.h
@@ -596,6 +596,7 @@ enum CommandArgumentType {
   eArgTypeFilename,
   eArgTypeFormat,
   eArgTypeFrameIndex,
+  eArgTypeFrameProviderIDRange,
   eArgTypeFullName,
   eArgTypeFunctionName,
   eArgTypeFunctionOrSymbol,
diff --git a/lldb/source/Commands/CommandObjectTarget.cpp b/lldb/source/Commands/CommandObjectTarget.cpp
index 7ed40bff3a985..7415a5370af84 100644
--- a/lldb/source/Commands/CommandObjectTarget.cpp
+++ b/lldb/source/Commands/CommandObjectTarget.cpp
@@ -5472,7 +5472,7 @@ class CommandObjectTargetFrameProviderList : public CommandObjectParsed {
       return;
     }
 
-    result.AppendMessageWithFormat("%u frame provider(s) registered:\n\n",
+    result.AppendMessageWithFormat("%zu frame provider(s) registered:\n\n",
                                    descriptors.size());
 
     for (const auto &entry : descriptors) {
diff --git a/lldb/source/Commands/CommandObjectThread.cpp b/lldb/source/Commands/CommandObjectThread.cpp
index 6786741cd04b6..87dd28445365d 100644
--- a/lldb/source/Commands/CommandObjectThread.cpp
+++ b/lldb/source/Commands/CommandObjectThread.cpp
@@ -92,6 +92,76 @@ class CommandObjectThreadBacktrace : public CommandObjectIterateOverThreads {
       case 'u':
         m_filtered_backtrace = false;
         break;
+      case 'p': {
+        // Parse provider range using same format as breakpoint IDs.
+        // Supports: "N", "N-M", "N to M", "*", "all".
+        llvm::StringRef trimmed = option_arg.trim();
+        if (trimmed == "*" || trimmed.equals_insensitive("all")) {
+          m_show_all_providers = true;
+          m_provider_specific_backtrace = true;
+          break;
+        }
+
+        std::string option_lower = option_arg.lower();
+        static constexpr llvm::StringLiteral range_specifiers[] = {"-", "to"};
+
+        llvm::StringRef range_from;
+        llvm::StringRef range_to;
+        bool is_range = false;
+
+        // Try to find a range specifier.
+        for (auto specifier : range_specifiers) {
+          size_t idx = option_lower.find(specifier);
+          if (idx == std::string::npos)
+            continue;
+
+          range_from = llvm::StringRef(option_lower).take_front(idx).trim();
+          range_to = llvm::StringRef(option_lower)
+                         .drop_front(idx + specifier.size())
+                         .trim();
+
+          if (!range_from.empty() && !range_to.empty()) {
+            is_range = true;
+            break;
+          }
+        }
+
+        if (is_range) {
+          // Parse both start and end IDs.
+          if (range_from.getAsInteger(0, m_provider_start_id)) {
+            error = Status::FromErrorStringWithFormat(
+                "invalid start provider ID for option '%c': %s", short_option,
+                range_from.data());
+            break;
+          }
+          if (range_to.getAsInteger(0, m_provider_end_id)) {
+            error = Status::FromErrorStringWithFormat(
+                "invalid end provider ID for option '%c': %s", short_option,
+                range_to.data());
+            break;
+          }
+
+          // Validate range.
+          if (m_provider_start_id > m_provider_end_id) {
+            error = Status::FromErrorStringWithFormat(
+                "invalid provider range for option '%c': start ID %u > end "
+                "ID %u",
+                short_option, m_provider_start_id, m_provider_end_id);
+            break;
+          }
+        } else {
+          // Single provider ID.
+          if (option_arg.getAsInteger(0, m_provider_start_id)) {
+            error = Status::FromErrorStringWithFormat(
+                "invalid provider ID for option '%c': %s", short_option,
+                option_arg.data());
+            break;
+          }
+          m_provider_end_id = m_provider_start_id;
+        }
+
+        m_provider_specific_backtrace = true;
+      } break;
       default:
         llvm_unreachable("Unimplemented option");
       }
@@ -103,10 +173,14 @@ class CommandObjectThreadBacktrace : public CommandObjectIterateOverThreads {
       m_start = 0;
       m_extended_backtrace = false;
       m_filtered_backtrace = true;
+      m_provider_start_id = 0;
+      m_provider_end_id = 0;
+      m_provider_specific_backtrace = false;
+      m_show_all_providers = false;
     }
 
     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
-      return llvm::ArrayRef(g_thread_backtrace_options);
+      return g_thread_backtrace_options;
     }
 
     // Instance variables to hold the values for command options.
@@ -114,6 +188,10 @@ class CommandObjectThreadBacktrace : public CommandObjectIterateOverThreads {
     uint32_t m_start;
     bool m_extended_backtrace;
     bool m_filtered_backtrace;
+    lldb::frame_list_id_t m_provider_start_id;
+    lldb::frame_list_id_t m_provider_end_id;
+    bool m_provider_specific_backtrace;
+    bool m_show_all_providers;
   };
 
   CommandObjectThreadBacktrace(CommandInterpreter &interpreter)
@@ -124,6 +202,9 @@ class CommandObjectThreadBacktrace : public CommandObjectIterateOverThreads {
             "Use the thread-index \"all\" to see all threads.\n"
             "Use the thread-index \"unique\" to see threads grouped by unique "
             "call stacks.\n"
+            "Use '--provider <id>' or '--provider <start>-<end>' to view "
+            "synthetic frame providers (0=base unwinder, 1+=synthetic). "
+            "Range specifiers '-', 'to', 'To', 'TO' are supported.\n"
             "Use 'settings set frame-format' to customize the printing of "
             "frames in the backtrace and 'settings set thread-format' to "
             "customize the thread header.\n"
@@ -227,13 +308,115 @@ class CommandObjectThreadBacktrace : public CommandObjectIterateOverThreads {
     }
 
     Thread *thread = thread_sp.get();
-
     Stream &strm = result.GetOutputStream();
 
-    // Only dump stack info if we processing unique stacks.
-    const bool only_stacks = m_unique_stacks;
+    // Check if provider filtering is requested.
+    if (m_options.m_provider_specific_backtrace) {
+      // Disallow 'bt --provider' from within a scripted frame provider.
+      // A provider's get_frame_at_index running 'bt --provider' would
+      // try to evaluate the very provider that is mid-construction,
+      // leading to infinite recursion.
+      if (thread->IsAnyProviderActive()) {
+        result.AppendErrorWithFormat(
+            "cannot use '--provider' option while a scripted frame provider is "
+            "being constructed on this thread\n");
+        return false;
+      }
+
+      // Print thread status header, like regular bt. This also ensures the
+      // frame list is initialized and any providers are loaded.
+      thread->GetStatus(strm, /*start_frame=*/0, /*num_frames=*/0,
+                        /*num_frames_with_source=*/0, /*stop_format=*/true,
+                        /*show_hidden=*/false, /*only_stacks=*/false);
+
+      if (m_options.m_show_all_providers) {
+        // Show all providers: unwinder (0) through the last in the chain.
+        m_options.m_provider_start_id = 0;
+        const auto &chain = thread->GetProviderChainIds();
+        m_options.m_provider_end_id = chain.empty() ? 0 : chain.back().second;
+      }
+
+      // Provider filter mode: show sequential views for each provider in range.
+      bool first_provider = true;
+      for (lldb::frame_list_id_t provider_id = m_options.m_provider_start_id;
+           provider_id <= m_options.m_provider_end_id; ++provider_id) {
+
+        // Get the frame list for this provider.
+        lldb::StackFrameListSP frame_list_sp =
+            thread->GetFrameListByIdentifier(provider_id);
+
+        if (!frame_list_sp) {
+          // Provider doesn't exist - skip silently.
+          continue;
+        }
+
+        // Add blank line between providers for readability.
+        if (!first_provider)
+          strm.PutChar('\n');
+        first_provider = false;
+
+        // Print provider header.
+        strm.Printf("=== Provider %u", provider_id);
+
+        // Get provider metadata for header.
+        if (provider_id == 0) {
+          strm.Printf(": Base Unwinder ===\n");
+        } else {
+          // Find the descriptor in the provider chain.
+          const auto &provider_chain = thread->GetProviderChainIds();
+          std::string provider_name = "Unknown";
+          std::string provider_desc;
+          std::optional<uint32_t> provider_priority;
+
+          for (const auto &[descriptor, id] : provider_chain) {
+            if (id == provider_id) {
+              provider_name = descriptor.GetName().str();
+              provider_desc = descriptor.GetDescription();
+              provider_priority = descriptor.GetPriority();
+              break;
+            }
+          }
+
+          strm.Printf(": %s", provider_name.c_str());
+          if (provider_priority.has_value()) {
+            strm.Printf(" (priority: %u)", *provider_priority);
+          }
+          strm.Printf(" ===\n");
+
+          if (!provider_desc.empty()) {
+            strm.Printf("Description: %s\n", provider_desc.c_str());
+          }
+        }
+
+        // Print the backtrace for this provider.
+        const uint32_t num_frames_with_source = 0;
+        const StackFrameSP selected_frame_sp =
+            thread->GetSelectedFrame(DoNoSelectMostRelevantFrame);
+        const char *selected_frame_marker = selected_frame_sp ? "->" : nullptr;
+
+        size_t num_frames = frame_list_sp->GetStatus(
+            strm, m_options.m_start, m_options.m_count,
+            /*show_frame_info=*/true, num_frames_with_source,
+            /*show_unique=*/false,
+            /*show_hidden=*/!m_options.m_filtered_backtrace,
+            selected_frame_marker);
+
+        if (num_frames == 0) {
+          strm.Printf("(No frames available)\n");
+        }
+      }
 
-    // Don't show source context when doing backtraces.
+      if (first_provider) {
+        result.AppendErrorWithFormat("no provider found in range %u-%u\n",
+                                     m_options.m_provider_start_id,
+                                     m_options.m_provider_end_id);
+        return false;
+      }
+      return true;
+    }
+
+    // Original behavior: show default backtrace.
+    const bool only_stacks = m_unique_stacks;
     const uint32_t num_frames_with_source = 0;
     const bool stop_format = true;
     if (!thread->GetStatus(strm, m_options.m_start, m_options.m_count,
diff --git a/lldb/source/Commands/Options.td b/lldb/source/Commands/Options.td
index 78bde66199659..54e9f022880c4 100644
--- a/lldb/source/Commands/Options.td
+++ b/lldb/source/Commands/Options.td
@@ -1919,6 +1919,15 @@ let Command = "thread backtrace" in {
                                     Group<1>,
                                     Desc<"Do not filter out frames according "
                                          "to installed frame recognizers">;
+  def thread_backtrace_provider
+      : Option<"provider", "p">,
+        Group<1>,
+        Arg<"FrameProviderIDRange">,
+        Desc<"Show backtrace from specific frame provider(s). "
+             "Use a single ID (e.g., '2') for one provider, "
+             "a range (e.g., '0-2', '0 to 2') for multiple, "
+             "or '*'/'all' to show every provider. "
+             "ID 0 is the base unwinder, 1+ are synthetic providers.">;
 }
 
 let Command = "thread step scope" in {
diff --git a/lldb/source/Interpreter/CommandInterpreter.cpp b/lldb/source/Interpreter/CommandInterpreter.cpp
index eeb1ae0ff3eb8..6218591b3a20b 100644
--- a/lldb/source/Interpreter/CommandInterpreter.cpp
+++ b/lldb/source/Interpreter/CommandInterpreter.cpp
@@ -424,6 +424,15 @@ void CommandInterpreter::Initialize() {
   if (cmd_obj_sp)
     AddAlias("bt", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
 
+  cmd_obj_sp = GetCommandSPExact("thread backtrace");
+  if (cmd_obj_sp) {
+    if (auto *sys_bt = AddAlias("sys_bt", cmd_obj_sp, "--provider 0")) {
+      sys_bt->SetHelp("Show the base unwinder backtrace (without frame "
+                      "providers). Equivalent to 'thread backtrace "
+                      "--provider 0'.");
+    }
+  }
+
   cmd_obj_sp = GetCommandSPExact("target create");
   if (cmd_obj_sp)
     AddAlias("file", cmd_obj_sp);
diff --git a/lldb/source/Target/SyntheticFrameProvider.cpp b/lldb/source/Target/SyntheticFrameProvider.cpp
index 0e4408eaad480..df59e62ee7bbf 100644
--- a/lldb/source/Target/SyntheticFrameProvider.cpp
+++ b/lldb/source/Target/SyntheticFrameProvider.cpp
@@ -27,7 +27,7 @@ void ScriptedFrameProviderDescriptor::Dump(Stream *s) const {
   if (!s)
     return;
 
-  s->Format("  ID: {0:x}\n", GetID());
+  s->Format("  ID: {0}\n", GetID());
   s->Printf("  Name: %s\n", GetName().str().c_str());
 
   std::string description = GetDescription();
@@ -56,6 +56,16 @@ void ScriptedFrameProviderDescriptor::Dump(Stream *s) const {
 }
 
 uint32_t ScriptedFrameProviderDescriptor::GetID() const {
+  if (m_id != 0)
+    return m_id;
+
+  if (!scripted_metadata_sp)
+    return 0;
+
+  return scripted_metadata_sp->GetID();
+}
+
+uint32_t ScriptedFrameProviderDescriptor::GetArgumentsHash() const {
   if (!scripted_metadata_sp)
     return 0;
 
diff --git a/lldb/source/Target/Target.cpp b/lldb/source/Tar...
[truncated]

``````````

</details>


https://github.com/llvm/llvm-project/pull/190712


More information about the lldb-commits mailing list