[Lldb-commits] [lldb] [lldb] enhance colorize process for image lookup command (PR #76112)

José Lira Junior via lldb-commits lldb-commits at lists.llvm.org
Thu Jan 18 15:04:44 PST 2024


https://github.com/junior-jl updated https://github.com/llvm/llvm-project/pull/76112

>From fb2383f3e6e2124e4f14e8e0f6a04df4bed15f65 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jos=C3=A9=20L=2E=20Junior?= <jljuniorpb at gmail.com>
Date: Thu, 18 Jan 2024 20:03:25 -0300
Subject: [PATCH] refactor PutCStringColorHighlight | add struct to store
 highlight settings

---
 lldb/include/lldb/Core/Address.h             |  4 +-
 lldb/include/lldb/Symbol/Symbol.h            |  4 +-
 lldb/include/lldb/Symbol/SymbolContext.h     |  7 +++-
 lldb/include/lldb/Utility/Stream.h           | 18 +++++++--
 lldb/source/Commands/CommandObjectTarget.cpp | 39 ++++++++++++--------
 lldb/source/Core/Address.cpp                 | 22 +++++------
 lldb/source/Symbol/Symbol.cpp                | 11 +++---
 lldb/source/Symbol/SymbolContext.cpp         | 36 +++++++-----------
 lldb/source/Utility/Stream.cpp               | 17 ++++-----
 9 files changed, 85 insertions(+), 73 deletions(-)

diff --git a/lldb/include/lldb/Core/Address.h b/lldb/include/lldb/Core/Address.h
index 725b5d9f91d3d5..f11ece414eec83 100644
--- a/lldb/include/lldb/Core/Address.h
+++ b/lldb/include/lldb/Core/Address.h
@@ -9,6 +9,7 @@
 #ifndef LLDB_CORE_ADDRESS_H
 #define LLDB_CORE_ADDRESS_H
 
+#include "lldb/Utility/Stream.h"
 #include "lldb/lldb-defines.h"
 #include "lldb/lldb-forward.h"
 #include "lldb/lldb-private-enumerations.h"
@@ -255,7 +256,8 @@ class Address {
   bool Dump(Stream *s, ExecutionContextScope *exe_scope, DumpStyle style,
             DumpStyle fallback_style = DumpStyleInvalid,
             uint32_t addr_byte_size = UINT32_MAX, bool all_ranges = false,
-            llvm::StringRef pattern = "") const;
+            std::optional<Stream::HighlightSettings> pattern_info =
+                std::nullopt) const;
 
   AddressClass GetAddressClass() const;
 
diff --git a/lldb/include/lldb/Symbol/Symbol.h b/lldb/include/lldb/Symbol/Symbol.h
index e6c0b495bcf28c..0da431f5ccf5da 100644
--- a/lldb/include/lldb/Symbol/Symbol.h
+++ b/lldb/include/lldb/Symbol/Symbol.h
@@ -13,6 +13,7 @@
 #include "lldb/Core/Mangled.h"
 #include "lldb/Core/Section.h"
 #include "lldb/Symbol/SymbolContextScope.h"
+#include "lldb/Utility/Stream.h"
 #include "lldb/Utility/UserID.h"
 #include "lldb/lldb-private.h"
 #include "llvm/Support/JSON.h"
@@ -175,7 +176,8 @@ class Symbol : public SymbolContextScope {
   void SetFlags(uint32_t flags) { m_flags = flags; }
 
   void GetDescription(Stream *s, lldb::DescriptionLevel level, Target *target,
-                      llvm::StringRef pattern = "") const;
+                      std::optional<Stream::HighlightSettings> pattern_info =
+                          std::nullopt) const;
 
   bool IsSynthetic() const { return m_is_synthetic; }
 
diff --git a/lldb/include/lldb/Symbol/SymbolContext.h b/lldb/include/lldb/Symbol/SymbolContext.h
index 26f3bac09a9626..a089e93863a75d 100644
--- a/lldb/include/lldb/Symbol/SymbolContext.h
+++ b/lldb/include/lldb/Symbol/SymbolContext.h
@@ -17,6 +17,7 @@
 #include "lldb/Core/Mangled.h"
 #include "lldb/Symbol/LineEntry.h"
 #include "lldb/Utility/Iterable.h"
+#include "lldb/Utility/Stream.h"
 #include "lldb/lldb-private.h"
 
 namespace lldb_private {
@@ -157,7 +158,8 @@ class SymbolContext {
                        const Address &so_addr, bool show_fullpaths,
                        bool show_module, bool show_inlined_frames,
                        bool show_function_arguments, bool show_function_name,
-                       llvm::StringRef pattern = "") const;
+                       std::optional<Stream::HighlightSettings> pattern_info =
+                           std::nullopt) const;
 
   /// Get the address range contained within a symbol context.
   ///
@@ -224,7 +226,8 @@ class SymbolContext {
   const Symbol *FindBestGlobalDataSymbol(ConstString name, Status &error);
 
   void GetDescription(Stream *s, lldb::DescriptionLevel level, Target *target,
-                      llvm::StringRef pattern = "") const;
+                      std::optional<Stream::HighlightSettings> pattern_info =
+                          std::nullopt) const;
 
   uint32_t GetResolvedMask() const;
 
diff --git a/lldb/include/lldb/Utility/Stream.h b/lldb/include/lldb/Utility/Stream.h
index 20c55ac4597ae6..f2666a749d5fa1 100644
--- a/lldb/include/lldb/Utility/Stream.h
+++ b/lldb/include/lldb/Utility/Stream.h
@@ -33,6 +33,17 @@ class Stream {
                        /// string mode.
   };
 
+  /// Struct to store information for color highlighting in the stream.
+  struct HighlightSettings {
+    llvm::StringRef pattern; ///< Regex pattern for highlighting.
+    llvm::StringRef prefix;  ///< ANSI color code to start colorization.
+    llvm::StringRef suffix;  ///< ANSI color code to end colorization.
+
+    HighlightSettings(llvm::StringRef p, llvm::StringRef pre,
+                      llvm::StringRef suf)
+        : pattern(p), prefix(pre), suffix(suf) {}
+  };
+
   /// Utility class for counting the bytes that were written to a stream in a
   /// certain time span.
   ///
@@ -260,10 +271,9 @@ class Stream {
   ///     The ANSI color code to end colorization. This is
   ///     environment-dependent.
 
-  void PutCStringColorHighlighted(llvm::StringRef text,
-                                  llvm::StringRef pattern = "",
-                                  llvm::StringRef prefix = "",
-                                  llvm::StringRef suffix = "");
+  void PutCStringColorHighlighted(
+      llvm::StringRef text,
+      std::optional<HighlightSettings> pattern_info = std::nullopt);
 
   /// Output and End of Line character to the stream.
   size_t EOL();
diff --git a/lldb/source/Commands/CommandObjectTarget.cpp b/lldb/source/Commands/CommandObjectTarget.cpp
index bc8bc51356c8ca..45f93e5684373f 100644
--- a/lldb/source/Commands/CommandObjectTarget.cpp
+++ b/lldb/source/Commands/CommandObjectTarget.cpp
@@ -53,6 +53,7 @@
 #include "lldb/Utility/FileSpec.h"
 #include "lldb/Utility/LLDBLog.h"
 #include "lldb/Utility/State.h"
+#include "lldb/Utility/Stream.h"
 #include "lldb/Utility/StructuredData.h"
 #include "lldb/Utility/Timer.h"
 #include "lldb/lldb-enumerations.h"
@@ -1531,9 +1532,10 @@ static void DumpOsoFilesTable(Stream &strm,
   });
 }
 
-static void DumpAddress(ExecutionContextScope *exe_scope,
-                        const Address &so_addr, bool verbose, bool all_ranges,
-                        Stream &strm, llvm::StringRef pattern = "") {
+static void DumpAddress(
+    ExecutionContextScope *exe_scope, const Address &so_addr, bool verbose,
+    bool all_ranges, Stream &strm,
+    std::optional<Stream::HighlightSettings> pattern_info = std::nullopt) {
   strm.IndentMore();
   strm.Indent("    Address: ");
   so_addr.Dump(&strm, exe_scope, Address::DumpStyleModuleWithFileAddress);
@@ -1544,13 +1546,14 @@ static void DumpAddress(ExecutionContextScope *exe_scope,
   const uint32_t save_indent = strm.GetIndentLevel();
   strm.SetIndentLevel(save_indent + 13);
   so_addr.Dump(&strm, exe_scope, Address::DumpStyleResolvedDescription,
-               Address::DumpStyleInvalid, UINT32_MAX, false, pattern);
+               Address::DumpStyleInvalid, UINT32_MAX, false, pattern_info);
   strm.SetIndentLevel(save_indent);
   // Print out detailed address information when verbose is enabled
   if (verbose) {
     strm.EOL();
     so_addr.Dump(&strm, exe_scope, Address::DumpStyleDetailedSymbolContext,
-                 Address::DumpStyleInvalid, UINT32_MAX, all_ranges, pattern);
+                 Address::DumpStyleInvalid, UINT32_MAX, all_ranges,
+                 pattern_info);
   }
   strm.IndentLess();
 }
@@ -1618,22 +1621,25 @@ static uint32_t LookupSymbolInModule(CommandInterpreter &interpreter,
     for (uint32_t i = 0; i < num_matches; ++i) {
       Symbol *symbol = symtab->SymbolAtIndex(match_indexes[i]);
       if (symbol) {
+        Stream::HighlightSettings pattern_info(
+            name, interpreter.GetDebugger().GetRegexMatchAnsiPrefix(),
+            interpreter.GetDebugger().GetRegexMatchAnsiSuffix());
         if (symbol->ValueIsAddress()) {
           DumpAddress(
               interpreter.GetExecutionContext().GetBestExecutionContextScope(),
               symbol->GetAddressRef(), verbose, all_ranges, strm,
-              use_color && name_is_regex ? name : nullptr);
+              use_color && name_is_regex
+                  ? std::optional<Stream::HighlightSettings>{pattern_info}
+                  : std::nullopt);
           strm.EOL();
         } else {
           strm.IndentMore();
           strm.Indent("    Name: ");
-          llvm::StringRef ansi_prefix =
-              interpreter.GetDebugger().GetRegexMatchAnsiPrefix();
-          llvm::StringRef ansi_suffix =
-              interpreter.GetDebugger().GetRegexMatchAnsiSuffix();
           strm.PutCStringColorHighlighted(
               symbol->GetDisplayName().GetStringRef(),
-              use_color ? name : nullptr, ansi_prefix, ansi_suffix);
+              use_color && name_is_regex
+                  ? std::optional<Stream::HighlightSettings>{pattern_info}
+                  : std::nullopt);
           strm.EOL();
           strm.Indent("    Value: ");
           strm.Printf("0x%16.16" PRIx64 "\n", symbol->GetRawValue());
@@ -1650,10 +1656,10 @@ static uint32_t LookupSymbolInModule(CommandInterpreter &interpreter,
   return num_matches;
 }
 
-static void DumpSymbolContextList(ExecutionContextScope *exe_scope,
-                                  Stream &strm,
-                                  const SymbolContextList &sc_list,
-                                  bool verbose, bool all_ranges) {
+static void DumpSymbolContextList(
+    ExecutionContextScope *exe_scope, Stream &strm,
+    const SymbolContextList &sc_list, bool verbose, bool all_ranges,
+    std::optional<Stream::HighlightSettings> pattern_info = std::nullopt) {
   strm.IndentMore();
   bool first_module = true;
   for (const SymbolContext &sc : sc_list) {
@@ -1664,7 +1670,8 @@ static void DumpSymbolContextList(ExecutionContextScope *exe_scope,
 
     sc.GetAddressRange(eSymbolContextEverything, 0, true, range);
 
-    DumpAddress(exe_scope, range.GetBaseAddress(), verbose, all_ranges, strm);
+    DumpAddress(exe_scope, range.GetBaseAddress(), verbose, all_ranges, strm,
+                pattern_info);
     first_module = false;
   }
   strm.IndentLess();
diff --git a/lldb/source/Core/Address.cpp b/lldb/source/Core/Address.cpp
index 19d34db44ea55c..848827f52fb5b6 100644
--- a/lldb/source/Core/Address.cpp
+++ b/lldb/source/Core/Address.cpp
@@ -405,9 +405,10 @@ bool Address::GetDescription(Stream &s, Target &target,
   return false;
 }
 
-bool Address::Dump(Stream *s, ExecutionContextScope *exe_scope, DumpStyle style,
-                   DumpStyle fallback_style, uint32_t addr_size,
-                   bool all_ranges, llvm::StringRef pattern) const {
+bool Address::Dump(
+    Stream *s, ExecutionContextScope *exe_scope, DumpStyle style,
+    DumpStyle fallback_style, uint32_t addr_size, bool all_ranges,
+    std::optional<Stream::HighlightSettings> pattern_info) const {
   // If the section was nullptr, only load address is going to work unless we
   // are trying to deref a pointer
   SectionSP section_sp(GetSection());
@@ -524,8 +525,7 @@ bool Address::Dump(Stream *s, ExecutionContextScope *exe_scope, DumpStyle style,
                     ansi_suffix =
                         target->GetDebugger().GetRegexMatchAnsiSuffix();
                   }
-                  s->PutCStringColorHighlighted(symbol_name, pattern,
-                                                ansi_prefix, ansi_suffix);
+                  s->PutCStringColorHighlighted(symbol_name, pattern_info);
                   addr_t delta =
                       file_Addr - symbol->GetAddressRef().GetFileAddress();
                   if (delta)
@@ -653,7 +653,7 @@ bool Address::Dump(Stream *s, ExecutionContextScope *exe_scope, DumpStyle style,
                     pointer_sc.symbol != nullptr) {
                   s->PutCString(": ");
                   pointer_sc.DumpStopContext(s, exe_scope, so_addr, true, false,
-                                             false, true, true, pattern);
+                                             false, true, true, pattern_info);
                 }
               }
             }
@@ -693,13 +693,13 @@ bool Address::Dump(Stream *s, ExecutionContextScope *exe_scope, DumpStyle style,
               sc.DumpStopContext(s, exe_scope, *this, show_fullpaths,
                                  show_module, show_inlined_frames,
                                  show_function_arguments, show_function_name,
-                                 pattern);
+                                 pattern_info);
             } else {
               // We found a symbol but it was in a different section so it
               // isn't the symbol we should be showing, just show the section
               // name + offset
               Dump(s, exe_scope, DumpStyleSectionNameOffset, DumpStyleInvalid,
-                   UINT32_MAX, false, pattern);
+                   UINT32_MAX, false, pattern_info);
             }
           }
         }
@@ -707,7 +707,7 @@ bool Address::Dump(Stream *s, ExecutionContextScope *exe_scope, DumpStyle style,
     } else {
       if (fallback_style != DumpStyleInvalid)
         return Dump(s, exe_scope, fallback_style, DumpStyleInvalid, addr_size,
-                    false, pattern);
+                    false, pattern_info);
       return false;
     }
     break;
@@ -728,7 +728,7 @@ bool Address::Dump(Stream *s, ExecutionContextScope *exe_scope, DumpStyle style,
               sc.symbol->GetAddressRef().GetSection() != GetSection())
             sc.symbol = nullptr;
         }
-        sc.GetDescription(s, eDescriptionLevelBrief, target, pattern);
+        sc.GetDescription(s, eDescriptionLevelBrief, target, pattern_info);
 
         if (sc.block) {
           bool can_create = true;
@@ -777,7 +777,7 @@ bool Address::Dump(Stream *s, ExecutionContextScope *exe_scope, DumpStyle style,
     } else {
       if (fallback_style != DumpStyleInvalid)
         return Dump(s, exe_scope, fallback_style, DumpStyleInvalid, addr_size,
-                    false, pattern);
+                    false, pattern_info);
       return false;
     }
     break;
diff --git a/lldb/source/Symbol/Symbol.cpp b/lldb/source/Symbol/Symbol.cpp
index 08900a3ef34914..af461bf8325e18 100644
--- a/lldb/source/Symbol/Symbol.cpp
+++ b/lldb/source/Symbol/Symbol.cpp
@@ -226,8 +226,9 @@ bool Symbol::IsTrampoline() const { return m_type == eSymbolTypeTrampoline; }
 
 bool Symbol::IsIndirect() const { return m_type == eSymbolTypeResolver; }
 
-void Symbol::GetDescription(Stream *s, lldb::DescriptionLevel level,
-                            Target *target, llvm::StringRef pattern) const {
+void Symbol::GetDescription(
+    Stream *s, lldb::DescriptionLevel level, Target *target,
+    std::optional<Stream::HighlightSettings> pattern_info) const {
   s->Printf("id = {0x%8.8x}", m_uid);
 
   if (m_addr_range.GetBaseAddress().GetSection()) {
@@ -262,14 +263,12 @@ void Symbol::GetDescription(Stream *s, lldb::DescriptionLevel level,
   }
   if (ConstString demangled = m_mangled.GetDemangledName()) {
     s->PutCString(", name=\"");
-    s->PutCStringColorHighlighted(demangled.GetStringRef(), pattern,
-                                  ansi_prefix, ansi_suffix);
+    s->PutCStringColorHighlighted(demangled.GetStringRef(), pattern_info);
     s->PutCString("\"");
   }
   if (ConstString mangled_name = m_mangled.GetMangledName()) {
     s->PutCString(", mangled=\"");
-    s->PutCStringColorHighlighted(mangled_name.GetStringRef(), pattern,
-                                  ansi_prefix, ansi_suffix);
+    s->PutCStringColorHighlighted(mangled_name.GetStringRef(), pattern_info);
     s->PutCString("\"");
   }
 }
diff --git a/lldb/source/Symbol/SymbolContext.cpp b/lldb/source/Symbol/SymbolContext.cpp
index d581c90cede7d3..b9ba7df098cfd0 100644
--- a/lldb/source/Symbol/SymbolContext.cpp
+++ b/lldb/source/Symbol/SymbolContext.cpp
@@ -24,6 +24,7 @@
 #include "lldb/Target/Target.h"
 #include "lldb/Utility/LLDBLog.h"
 #include "lldb/Utility/Log.h"
+#include "lldb/Utility/Stream.h"
 #include "lldb/Utility/StreamString.h"
 #include "lldb/lldb-enumerations.h"
 
@@ -68,12 +69,11 @@ void SymbolContext::Clear(bool clear_target) {
   variable = nullptr;
 }
 
-bool SymbolContext::DumpStopContext(Stream *s, ExecutionContextScope *exe_scope,
-                                    const Address &addr, bool show_fullpaths,
-                                    bool show_module, bool show_inlined_frames,
-                                    bool show_function_arguments,
-                                    bool show_function_name,
-                                    llvm::StringRef pattern) const {
+bool SymbolContext::DumpStopContext(
+    Stream *s, ExecutionContextScope *exe_scope, const Address &addr,
+    bool show_fullpaths, bool show_module, bool show_inlined_frames,
+    bool show_function_arguments, bool show_function_name,
+    std::optional<Stream::HighlightSettings> pattern_info) const {
   bool dumped_something = false;
   if (show_module && module_sp) {
     if (show_fullpaths)
@@ -95,16 +95,8 @@ bool SymbolContext::DumpStopContext(Stream *s, ExecutionContextScope *exe_scope,
         name = function->GetNameNoArguments();
       if (!name)
         name = function->GetName();
-      if (name) {
-        llvm::StringRef ansi_prefix;
-        llvm::StringRef ansi_suffix;
-        if (target_sp) {
-          ansi_prefix = target_sp->GetDebugger().GetRegexMatchAnsiPrefix();
-          ansi_suffix = target_sp->GetDebugger().GetRegexMatchAnsiSuffix();
-        }
-        s->PutCStringColorHighlighted(name.GetStringRef(), pattern, ansi_prefix,
-                                      ansi_suffix);
-      }
+      if (name)
+        s->PutCStringColorHighlighted(name.GetStringRef(), pattern_info);
     }
 
     if (addr.IsValid()) {
@@ -178,8 +170,8 @@ bool SymbolContext::DumpStopContext(Stream *s, ExecutionContextScope *exe_scope,
         ansi_prefix = target_sp->GetDebugger().GetRegexMatchAnsiPrefix();
         ansi_suffix = target_sp->GetDebugger().GetRegexMatchAnsiSuffix();
       }
-      s->PutCStringColorHighlighted(symbol->GetName().GetStringRef(), pattern,
-                                    ansi_prefix, ansi_suffix);
+      s->PutCStringColorHighlighted(symbol->GetName().GetStringRef(),
+                                    pattern_info);
     }
 
     if (addr.IsValid() && symbol->ValueIsAddress()) {
@@ -201,9 +193,9 @@ bool SymbolContext::DumpStopContext(Stream *s, ExecutionContextScope *exe_scope,
   return dumped_something;
 }
 
-void SymbolContext::GetDescription(Stream *s, lldb::DescriptionLevel level,
-                                   Target *target,
-                                   llvm::StringRef pattern) const {
+void SymbolContext::GetDescription(
+    Stream *s, lldb::DescriptionLevel level, Target *target,
+    std::optional<Stream::HighlightSettings> pattern_info) const {
   if (module_sp) {
     s->Indent("     Module: file = \"");
     module_sp->GetFileSpec().Dump(s->AsRawOstream());
@@ -263,7 +255,7 @@ void SymbolContext::GetDescription(Stream *s, lldb::DescriptionLevel level,
 
   if (symbol != nullptr) {
     s->Indent("     Symbol: ");
-    symbol->GetDescription(s, level, target, pattern);
+    symbol->GetDescription(s, level, target, pattern_info);
     s->EOL();
   }
 
diff --git a/lldb/source/Utility/Stream.cpp b/lldb/source/Utility/Stream.cpp
index 62e061e9d09c07..89dce9fb0e1f71 100644
--- a/lldb/source/Utility/Stream.cpp
+++ b/lldb/source/Utility/Stream.cpp
@@ -72,23 +72,20 @@ size_t Stream::PutCString(llvm::StringRef str) {
   return bytes_written;
 }
 
-void Stream::PutCStringColorHighlighted(llvm::StringRef text,
-                                        llvm::StringRef pattern,
-                                        llvm::StringRef prefix,
-                                        llvm::StringRef suffix) {
-  // Only apply color formatting when a pattern is present and both prefix and
-  // suffix are specified. In the absence of these conditions, output the text
-  // without color formatting.
-  if (pattern.empty() || (prefix.empty() && suffix.empty())) {
+void Stream::PutCStringColorHighlighted(
+    llvm::StringRef text, std::optional<HighlightSettings> pattern_info) {
+  // Only apply color formatting when a pattern information is specified.
+  // Otherwise, output the text without color formatting.
+  if (!pattern_info.has_value()) {
     PutCString(text);
     return;
   }
 
-  llvm::Regex reg_pattern(pattern);
+  llvm::Regex reg_pattern(pattern_info->pattern);
   llvm::SmallVector<llvm::StringRef, 1> matches;
   llvm::StringRef remaining = text;
   std::string format_str = lldb_private::ansi::FormatAnsiTerminalCodes(
-      prefix.str() + "%.*s" + suffix.str());
+      pattern_info->prefix.str() + "%.*s" + pattern_info->suffix.str());
   while (reg_pattern.match(remaining, &matches)) {
     llvm::StringRef match = matches[0];
     size_t match_start_pos = match.data() - remaining.data();



More information about the lldb-commits mailing list