[Lldb-commits] [PATCH] D145240: [lldb][TypeSystemClang][NFC] Factor out l/r-value reference logic for IsXXXType APIs

2023-03-03 Thread Michael Buch via Phabricator via lldb-commits
Michael137 created this revision.
Michael137 added a reviewer: aprantl.
Herald added a project: All.
Michael137 requested review of this revision.
Herald added a project: LLDB.
Herald added a subscriber: lldb-commits.

This will be useful as we add more `IsXXXType` APIs for different
function types.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D145240

Files:
  lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
  lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h

Index: lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
===
--- lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
+++ lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
@@ -1147,6 +1147,9 @@
   const clang::ClassTemplateSpecializationDecl *
   GetAsTemplateSpecialization(lldb::opaque_compiler_type_t type);
 
+  bool IsTypeImpl(lldb::opaque_compiler_type_t type,
+  llvm::function_ref predicate) const;
+
   // Classes that inherit from TypeSystemClang can see and modify these
   std::string m_target_triple;
   std::unique_ptr m_ast_up;
Index: lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
===
--- lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
+++ lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
@@ -3050,28 +3050,11 @@
 }
 
 bool TypeSystemClang::IsFunctionType(lldb::opaque_compiler_type_t type) {
-  if (type) {
-clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
-
-if (qual_type->isFunctionType()) {
-  return true;
-}
+  auto isFunctionType = [&](clang::QualType qual_type) {
+return qual_type->isFunctionType();
+  };
 
-const clang::Type::TypeClass type_class = qual_type->getTypeClass();
-switch (type_class) {
-default:
-  break;
-case clang::Type::LValueReference:
-case clang::Type::RValueReference: {
-  const clang::ReferenceType *reference_type =
-  llvm::cast(qual_type.getTypePtr());
-  if (reference_type)
-return IsFunctionType(
-reference_type->getPointeeType().getAsOpaquePtr());
-} break;
-}
-  }
-  return false;
+  return IsTypeImpl(type, isFunctionType);
 }
 
 // Used to detect "Homogeneous Floating-point Aggregates"
@@ -3185,11 +3168,13 @@
   return CompilerType();
 }
 
-bool TypeSystemClang::IsFunctionPointerType(lldb::opaque_compiler_type_t type) {
+bool TypeSystemClang::IsTypeImpl(
+lldb::opaque_compiler_type_t type,
+llvm::function_ref predicate) const {
   if (type) {
 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
 
-if (qual_type->isFunctionPointerType())
+if (predicate(qual_type))
   return true;
 
 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
@@ -3202,20 +3187,25 @@
   const clang::ReferenceType *reference_type =
   llvm::cast(qual_type.getTypePtr());
   if (reference_type)
-return IsFunctionPointerType(
-reference_type->getPointeeType().getAsOpaquePtr());
+return IsTypeImpl(reference_type->getPointeeType().getAsOpaquePtr(), predicate);
 } break;
 }
   }
   return false;
 }
 
+bool TypeSystemClang::IsFunctionPointerType(lldb::opaque_compiler_type_t type) {
+  auto isFunctionPointerType = [](clang::QualType qual_type) {
+return qual_type->isFunctionPointerType();
+  };
+
+  return IsTypeImpl(type, isFunctionPointerType);
+}
+
 bool TypeSystemClang::IsBlockPointerType(
 lldb::opaque_compiler_type_t type,
 CompilerType *function_pointer_type_ptr) {
-  if (type) {
-clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
-
+  auto isBlockPointerType = [&](clang::QualType qual_type) {
 if (qual_type->isBlockPointerType()) {
   if (function_pointer_type_ptr) {
 const clang::BlockPointerType *block_pointer_type =
@@ -3228,23 +3218,10 @@
   return true;
 }
 
-const clang::Type::TypeClass type_class = qual_type->getTypeClass();
-switch (type_class) {
-default:
-  break;
+return false;
+  };
 
-case clang::Type::LValueReference:
-case clang::Type::RValueReference: {
-  const clang::ReferenceType *reference_type =
-  llvm::cast(qual_type.getTypePtr());
-  if (reference_type)
-return IsBlockPointerType(
-reference_type->getPointeeType().getAsOpaquePtr(),
-function_pointer_type_ptr);
-} break;
-}
-  }
-  return false;
+  return IsTypeImpl(type, isBlockPointerType);
 }
 
 bool TypeSystemClang::IsIntegerType(lldb::opaque_compiler_type_t type,
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D145241: [lldb][TypeSystemClang] Format pointers to member functions as eFormatHex

2023-03-03 Thread Michael Buch via Phabricator via lldb-commits
Michael137 created this revision.
Michael137 added a reviewer: aprantl.
Herald added a project: All.
Michael137 requested review of this revision.
Herald added a project: LLDB.
Herald added a subscriber: lldb-commits.

Before this patch, LLDB used to format pointers to members, such as,

  void (Foo::*pointer_to_member_func)() = &Foo::member_func;

as `eFormatBytes`. E.g.,

  (lldb) v pointer_to_member_func
  (void (Foo::*)()) $1 = 94 3f 00 00 01 00 00 00 00 00 00 00 00 00 00 00

This patch makes sure we format pointers to member functions the same
way we do regular function pointers.

After this patch we format member pointers as:

  (lldb) v pointer_to_member_func
  (void (Foo::*)()) ::pointer_to_member_func = 
0x00013f94


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D145241

Files:
  lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
  
lldb/test/API/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py
  lldb/test/API/functionalities/data-formatter/data-formatter-cpp/main.cpp


Index: lldb/test/API/functionalities/data-formatter/data-formatter-cpp/main.cpp
===
--- lldb/test/API/functionalities/data-formatter/data-formatter-cpp/main.cpp
+++ lldb/test/API/functionalities/data-formatter/data-formatter-cpp/main.cpp
@@ -57,6 +57,8 @@
 {
const char* pointer;
IUseCharStar() : pointer("Hello world") {}
+
+char const *member_func(int) { return ""; }
 };
 
 int main (int argc, const char * argv[])
@@ -106,7 +108,12 @@
 char* strptr = "Hello world!";
 
 i_am_cooler the_coolest_guy(1,2,3.14,6.28,'E','G');
-
+
+const char *IUseCharStar::*member_ptr = &IUseCharStar::pointer;
+const char *(IUseCharStar::*member_func_ptr)(int) =
+&IUseCharStar::member_func;
+auto &ref_to_member_func_ptr = member_func_ptr;
+
 return 0; // Set break point at this line.
 }
 
Index: 
lldb/test/API/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py
===
--- 
lldb/test/API/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py
+++ 
lldb/test/API/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py
@@ -285,3 +285,14 @@
 matching=False,
 substrs=['(int) iAmInt = 0x0001'])
 self.expect("frame variable iAmInt", substrs=['(int) iAmInt = 1'])
+
+# Check that pointer to members are correctly formatted
+self.expect(
+"frame variable member_ptr",
+substrs=['member_ptr = 0x'])
+self.expect(
+"frame variable member_func_ptr",
+substrs=['member_func_ptr = 0x'])
+self.expect(
+"frame variable ref_to_member_func_ptr",
+substrs=['ref_to_member_func_ptr = 0x'])
Index: lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
===
--- lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
+++ lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
@@ -5277,7 +5277,7 @@
   case clang::Type::RValueReference:
 return lldb::eFormatHex;
   case clang::Type::MemberPointer:
-break;
+return lldb::eFormatHex;
   case clang::Type::Complex: {
 if (qual_type->isComplexType())
   return lldb::eFormatComplex;


Index: lldb/test/API/functionalities/data-formatter/data-formatter-cpp/main.cpp
===
--- lldb/test/API/functionalities/data-formatter/data-formatter-cpp/main.cpp
+++ lldb/test/API/functionalities/data-formatter/data-formatter-cpp/main.cpp
@@ -57,6 +57,8 @@
 {
 	const char* pointer;
 	IUseCharStar() : pointer("Hello world") {}
+
+char const *member_func(int) { return ""; }
 };
 
 int main (int argc, const char * argv[])
@@ -106,7 +108,12 @@
 char* strptr = "Hello world!";
 
 i_am_cooler the_coolest_guy(1,2,3.14,6.28,'E','G');
-
+
+const char *IUseCharStar::*member_ptr = &IUseCharStar::pointer;
+const char *(IUseCharStar::*member_func_ptr)(int) =
+&IUseCharStar::member_func;
+auto &ref_to_member_func_ptr = member_func_ptr;
+
 return 0; // Set break point at this line.
 }
 
Index: lldb/test/API/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py
===
--- lldb/test/API/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py
+++ lldb/test/API/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py
@@ -285,3 +285,14 @@
 matching=False,
 substrs=['(int) iAmInt = 0x0001'])
 self.expect("frame variable iAmInt", substrs=['(int) iAmInt = 1'])
+
+# Check that pointer to members are correctly formatted
+self.expect(
+"frame variable

[Lldb-commits] [PATCH] D145242: [lldb][TypeSystemClang] Use the CXXFunctionPointerSummaryProvider for member-function pointers

2023-03-03 Thread Michael Buch via Phabricator via lldb-commits
Michael137 created this revision.
Michael137 added a reviewer: aprantl.
Herald added a project: All.
Michael137 requested review of this revision.
Herald added a project: LLDB.
Herald added a subscriber: lldb-commits.

With this patch member-function pointers are formatted using
`CXXFunctionPointerSummaryProvider`.

This turns,

  (lldb) v pointer_to_member_func
  (void (Foo::*)()) ::pointer_to_member_func = 
0x00013f94

into

  (lldb) v pointer_to_member_func
  (void (Foo::*)()) ::pointer_to_member_func = 
0x00013f94 (a.out`Foo::member_func() at main.cpp:3)


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D145242

Files:
  lldb/include/lldb/Symbol/CompilerType.h
  lldb/include/lldb/Symbol/TypeSystem.h
  lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp
  lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
  lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
  lldb/source/Symbol/CompilerType.cpp
  
lldb/test/API/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py

Index: lldb/test/API/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py
===
--- lldb/test/API/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py
+++ lldb/test/API/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py
@@ -292,7 +292,9 @@
 substrs=['member_ptr = 0x'])
 self.expect(
 "frame variable member_func_ptr",
-substrs=['member_func_ptr = 0x'])
+substrs=['member_func_ptr = 0x',
+ '(a.out`IUseCharStar::member_func(int) at main.cpp:61)'])
 self.expect(
 "frame variable ref_to_member_func_ptr",
-substrs=['ref_to_member_func_ptr = 0x'])
+substrs=['ref_to_member_func_ptr = 0x',
+ '(a.out`IUseCharStar::member_func(int) at main.cpp:61)'])
Index: lldb/source/Symbol/CompilerType.cpp
===
--- lldb/source/Symbol/CompilerType.cpp
+++ lldb/source/Symbol/CompilerType.cpp
@@ -154,6 +154,13 @@
   return false;
 }
 
+bool CompilerType::IsMemberFunctionPointerType() const {
+  if (IsValid())
+if (auto type_system_sp = GetTypeSystem())
+  return type_system_sp->IsMemberFunctionPointerType(m_type);
+  return false;
+}
+
 bool CompilerType::IsBlockPointerType(
 CompilerType *function_pointer_type_ptr) const {
   if (IsValid())
Index: lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
===
--- lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
+++ lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
@@ -658,6 +658,8 @@
 
   bool IsFunctionPointerType(lldb::opaque_compiler_type_t type) override;
 
+  bool IsMemberFunctionPointerType(lldb::opaque_compiler_type_t type) override;
+
   bool IsBlockPointerType(lldb::opaque_compiler_type_t type,
   CompilerType *function_pointer_type_ptr) override;
 
Index: lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
===
--- lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
+++ lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
@@ -3194,6 +3194,15 @@
   return false;
 }
 
+bool TypeSystemClang::IsMemberFunctionPointerType(
+lldb::opaque_compiler_type_t type) {
+  auto isMemberFunctionPointerType = [](clang::QualType qual_type) {
+return qual_type->isMemberFunctionPointerType();
+  };
+
+  return IsTypeImpl(type, isMemberFunctionPointerType);
+}
+
 bool TypeSystemClang::IsFunctionPointerType(lldb::opaque_compiler_type_t type) {
   auto isFunctionPointerType = [](clang::QualType qual_type) {
 return qual_type->isFunctionPointerType();
Index: lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp
===
--- lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp
+++ lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp
@@ -1390,7 +1390,8 @@
   TypeSummaryImpl::Flags(),
   lldb_private::formatters::CXXFunctionPointerSummaryProvider,
   "Function pointer summary provider"));
-  if (valobj.GetCompilerType().IsFunctionPointerType()) {
+  if (CompilerType CT = valobj.GetCompilerType();
+  CT.IsFunctionPointerType() || CT.IsMemberFunctionPointerType()) {
 return formatter_sp;
   }
   return nullptr;
Index: lldb/include/lldb/Symbol/TypeSystem.h
===
--- lldb/include/lldb/Symbol/TypeSystem.h
+++ lldb/include/lldb/Symbol/TypeSystem.h
@@ -169,6 +169,9 @@
 
   virtual bool IsFunctionPointerType(lldb::opaque_compiler_type_t type) = 0;
 
+  virtual bool
+  IsMemberFunctionP

[Lldb-commits] [PATCH] D145245: [lldb] Ignore libcxx std::ranges global variables in frame var

2023-03-03 Thread Michael Buch via Phabricator via lldb-commits
Michael137 created this revision.
Michael137 added a reviewer: aprantl.
Herald added a project: All.
Michael137 requested review of this revision.
Herald added a project: LLDB.
Herald added a subscriber: lldb-commits.

The motivation is to avoid cluttering LLDB's global variable view for
std::ranges users.

Before:

  (lldb) frame var -g
  ...
  (const std::ranges::__end::__fn) std::__1::ranges::__cpo::end = {}
  (const std::ranges::views::__all::__fn) std::__1::ranges::views::__cpo::all = 
{}
  (const std::ranges::__begin::__fn) std::__1::ranges::__cpo::begin = {}
  (const std::ranges::views::__take::__fn) std::__1::ranges::views::__cpo::take 
= {}
  (const std::ranges::__max_element::__fn) std::__1::ranges::__cpo::max_element 
= {}
  (const std::ranges::__size::__fn) std::__1::ranges::__cpo::size = {}
  (const std::ranges::__data::__fn) std::__1::ranges::__cpo::data = {}

After this patch none of these __cpo variables would show up.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D145245

Files:
  lldb/include/lldb/Target/LanguageRuntime.h
  lldb/source/Core/ValueObject.cpp
  lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.cpp
  lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.h
  lldb/test/API/lang/cpp/hide_global_ranges_vars/Makefile
  lldb/test/API/lang/cpp/hide_global_ranges_vars/TestHideGlobalRangesVars.py
  lldb/test/API/lang/cpp/hide_global_ranges_vars/main.cpp

Index: lldb/test/API/lang/cpp/hide_global_ranges_vars/main.cpp
===
--- /dev/null
+++ lldb/test/API/lang/cpp/hide_global_ranges_vars/main.cpp
@@ -0,0 +1,9 @@
+#include 
+
+int main(int argc, char const *argv[]) {
+  int arr[3] = {1, 2, 3};
+  auto arr_view = std::ranges::views::all(arr);
+  auto arr_max = std::ranges::max_element(arr);
+
+  return 0;
+}
Index: lldb/test/API/lang/cpp/hide_global_ranges_vars/TestHideGlobalRangesVars.py
===
--- /dev/null
+++ lldb/test/API/lang/cpp/hide_global_ranges_vars/TestHideGlobalRangesVars.py
@@ -0,0 +1,27 @@
+"""Test that frame var and target var hide
+the global function objects in the libc++
+ranges implementation"""
+
+from lldbsuite.test.decorators import *
+from lldbsuite.test.lldbtest import *
+from lldbsuite.test import lldbutil
+
+class HideGlobalRangesVarsTestCase(TestBase):
+
+@add_test_categories(["libc++"])
+@skipIf(compiler=no_match("clang"))
+@skipIf(compiler="clang", compiler_version=['<', '16.0'])
+def test(self):
+self.build()
+
+lldbutil.run_to_source_breakpoint(self, "return", lldb.SBFileSpec('main.cpp', False))
+
+self.expect("frame variable --show-globals",
+substrs=["::ranges::views::__cpo",
+ "::ranges::__cpo"],
+matching=False)
+
+self.expect("target variable",
+substrs=["::ranges::views::__cpo",
+ "::ranges::__cpo"],
+matching=False)
Index: lldb/test/API/lang/cpp/hide_global_ranges_vars/Makefile
===
--- /dev/null
+++ lldb/test/API/lang/cpp/hide_global_ranges_vars/Makefile
@@ -0,0 +1,4 @@
+CXX_SOURCES := main.cpp
+CXXFLAGS_EXTRAS := -std=c++20
+
+include Makefile.rules
Index: lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.h
===
--- lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.h
+++ lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.h
@@ -77,6 +77,8 @@
   lldb::ThreadPlanSP GetStepThroughTrampolinePlan(Thread &thread,
   bool stop_others) override;
 
+  bool ShouldHideVariable(llvm::StringRef name) const override;
+
   bool IsAllowedRuntimeValue(ConstString name) override;
 protected:
   // Classes that inherit from CPPLanguageRuntime can see and modify these
Index: lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.cpp
===
--- lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.cpp
+++ lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.cpp
@@ -28,6 +28,7 @@
 #include "lldb/Target/StackFrame.h"
 #include "lldb/Target/ThreadPlanRunToAddress.h"
 #include "lldb/Target/ThreadPlanStepInRange.h"
+#include "lldb/Utility/RegularExpression.h"
 #include "lldb/Utility/Timer.h"
 
 using namespace lldb;
@@ -40,6 +41,18 @@
 CPPLanguageRuntime::CPPLanguageRuntime(Process *process)
 : LanguageRuntime(process) {}
 
+bool CPPLanguageRuntime::ShouldHideVariable(llvm::StringRef name) const {
+  // Matches the global function objects in std::ranges/std::ranges::views
+  // E.g.,
+  //   std::__1::ranges::views::__cpo::take
+  //   std::__1::ranges::__cpo::max_element
+  static RegularExpression ignore_globale_range

[Lldb-commits] [PATCH] D145245: [lldb] Ignore libcxx std::ranges global variables in frame var

2023-03-03 Thread Michael Buch via Phabricator via lldb-commits
Michael137 added a comment.
Herald added a subscriber: JDevlieghere.

Alternative to https://reviews.llvm.org/D142993

The other option would be introducing a new clang attribute that indicates "we 
don't want the debugger to display this but still keep the debug-info". This is 
what artificial does for inline-functions. So we could extend the attribute to 
handle variable declarations.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D145245/new/

https://reviews.llvm.org/D145245

___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D145245: [lldb] Ignore libcxx std::ranges global variables in frame var

2023-03-03 Thread Michael Buch via Phabricator via lldb-commits
Michael137 added a comment.

Alternative to https://reviews.llvm.org/D142993

The other option would be introducing a new clang attribute that indicates "we 
don't want the debugger to display this but still keep the debug-info". This is 
what artificial does for inline-functions. So we could extend the attribute to 
handle variable declarations.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D145245/new/

https://reviews.llvm.org/D145245

___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D145245: [lldb] Ignore libcxx std::ranges global variables in frame var

2023-03-03 Thread Michael Buch via Phabricator via lldb-commits
Michael137 updated this revision to Diff 502126.
Michael137 added a comment.

- Remove leftover debug code


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D145245/new/

https://reviews.llvm.org/D145245

Files:
  lldb/include/lldb/Target/LanguageRuntime.h
  lldb/source/Core/ValueObject.cpp
  lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.cpp
  lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.h
  lldb/test/API/lang/cpp/hide_global_ranges_vars/Makefile
  lldb/test/API/lang/cpp/hide_global_ranges_vars/TestHideGlobalRangesVars.py
  lldb/test/API/lang/cpp/hide_global_ranges_vars/main.cpp

Index: lldb/test/API/lang/cpp/hide_global_ranges_vars/main.cpp
===
--- /dev/null
+++ lldb/test/API/lang/cpp/hide_global_ranges_vars/main.cpp
@@ -0,0 +1,9 @@
+#include 
+
+int main(int argc, char const *argv[]) {
+  int arr[3] = {1, 2, 3};
+  auto arr_view = std::ranges::views::all(arr);
+  auto arr_max = std::ranges::max_element(arr);
+
+  return 0;
+}
Index: lldb/test/API/lang/cpp/hide_global_ranges_vars/TestHideGlobalRangesVars.py
===
--- /dev/null
+++ lldb/test/API/lang/cpp/hide_global_ranges_vars/TestHideGlobalRangesVars.py
@@ -0,0 +1,27 @@
+"""Test that frame var and target var hide
+the global function objects in the libc++
+ranges implementation"""
+
+from lldbsuite.test.decorators import *
+from lldbsuite.test.lldbtest import *
+from lldbsuite.test import lldbutil
+
+class HideGlobalRangesVarsTestCase(TestBase):
+
+@add_test_categories(["libc++"])
+@skipIf(compiler=no_match("clang"))
+@skipIf(compiler="clang", compiler_version=['<', '16.0'])
+def test(self):
+self.build()
+
+lldbutil.run_to_source_breakpoint(self, "return", lldb.SBFileSpec('main.cpp', False))
+
+self.expect("frame variable --show-globals",
+substrs=["::ranges::views::__cpo",
+ "::ranges::__cpo"],
+matching=False)
+
+self.expect("target variable",
+substrs=["::ranges::views::__cpo",
+ "::ranges::__cpo"],
+matching=False)
Index: lldb/test/API/lang/cpp/hide_global_ranges_vars/Makefile
===
--- /dev/null
+++ lldb/test/API/lang/cpp/hide_global_ranges_vars/Makefile
@@ -0,0 +1,4 @@
+CXX_SOURCES := main.cpp
+CXXFLAGS_EXTRAS := -std=c++20
+
+include Makefile.rules
Index: lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.h
===
--- lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.h
+++ lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.h
@@ -77,6 +77,8 @@
   lldb::ThreadPlanSP GetStepThroughTrampolinePlan(Thread &thread,
   bool stop_others) override;
 
+  bool ShouldHideVariable(llvm::StringRef name) const override;
+
   bool IsAllowedRuntimeValue(ConstString name) override;
 protected:
   // Classes that inherit from CPPLanguageRuntime can see and modify these
Index: lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.cpp
===
--- lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.cpp
+++ lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.cpp
@@ -28,6 +28,7 @@
 #include "lldb/Target/StackFrame.h"
 #include "lldb/Target/ThreadPlanRunToAddress.h"
 #include "lldb/Target/ThreadPlanStepInRange.h"
+#include "lldb/Utility/RegularExpression.h"
 #include "lldb/Utility/Timer.h"
 
 using namespace lldb;
@@ -40,6 +41,17 @@
 CPPLanguageRuntime::CPPLanguageRuntime(Process *process)
 : LanguageRuntime(process) {}
 
+bool CPPLanguageRuntime::ShouldHideVariable(llvm::StringRef name) const {
+  // Matches the global function objects in std::ranges/std::ranges::views
+  // E.g.,
+  //   std::__1::ranges::views::__cpo::take
+  //   std::__1::ranges::__cpo::max_element
+  static RegularExpression ignore_globale_ranges_pattern(
+  "std::__[[:alnum:]]+::ranges(::views)*::__cpo");
+
+  return ignore_globale_ranges_pattern.Execute(name);
+}
+
 bool CPPLanguageRuntime::IsAllowedRuntimeValue(ConstString name) {
   return name == g_this;
 }
Index: lldb/source/Core/ValueObject.cpp
===
--- lldb/source/Core/ValueObject.cpp
+++ lldb/source/Core/ValueObject.cpp
@@ -1589,12 +1589,20 @@
   if (!process)
 return false;
 
+  if (!GetVariable())
+return false;
+
+  auto *runtime = process->GetLanguageRuntime(GetVariable()->GetLanguage());
+  if (runtime)
+if (runtime->ShouldHideVariable(GetName().GetStringRef()))
+  return true;
+
   // We trust that the compiler did the right thing and marked runtime support
 

[Lldb-commits] [PATCH] D145242: [lldb][TypeSystemClang] Use the CXXFunctionPointerSummaryProvider for member-function pointers

2023-03-03 Thread Adrian Prantl via Phabricator via lldb-commits
aprantl accepted this revision.
aprantl added a comment.
This revision is now accepted and ready to land.

Nice.




Comment at: lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp:1394
+  if (CompilerType CT = valobj.GetCompilerType();
+  CT.IsFunctionPointerType() || CT.IsMemberFunctionPointerType()) {
 return formatter_sp;

The more often you are using this construct the more comfortable I'm getting 
with it :-)


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D145242/new/

https://reviews.llvm.org/D145242

___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D145245: [lldb] Ignore libcxx std::ranges global variables in frame var

2023-03-03 Thread Adrian Prantl via Phabricator via lldb-commits
aprantl accepted this revision.
aprantl added a comment.
This revision is now accepted and ready to land.

I think this is fine. It's concise, adds useful plugin functionality and we're 
already hardcoding all sorts of special knowledge about libc++.




Comment at: lldb/include/lldb/Target/LanguageRuntime.h:154
 
+  virtual bool ShouldHideVariable(llvm::StringRef name) const { return false; }
+

Can you add a doxygen comment about the effects here?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D145245/new/

https://reviews.llvm.org/D145245

___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D145241: [lldb][TypeSystemClang] Format pointers to member functions as eFormatHex

2023-03-03 Thread Adrian Prantl via Phabricator via lldb-commits
aprantl accepted this revision.
aprantl added inline comments.
This revision is now accepted and ready to land.



Comment at: lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp:5280
   case clang::Type::MemberPointer:
-break;
+return lldb::eFormatHex;
   case clang::Type::Complex: {

Are there any other suspicious `break;`s here?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D145241/new/

https://reviews.llvm.org/D145241

___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D145245: [lldb] Ignore libcxx std::ranges global variables in frame var

2023-03-03 Thread Michael Buch via Phabricator via lldb-commits
Michael137 updated this revision to Diff 502164.
Michael137 added a comment.

- Fix typo
- Add doxygen comment


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D145245/new/

https://reviews.llvm.org/D145245

Files:
  lldb/include/lldb/Target/LanguageRuntime.h
  lldb/source/Core/ValueObject.cpp
  lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.cpp
  lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.h
  lldb/test/API/lang/cpp/hide_global_ranges_vars/Makefile
  lldb/test/API/lang/cpp/hide_global_ranges_vars/TestHideGlobalRangesVars.py
  lldb/test/API/lang/cpp/hide_global_ranges_vars/main.cpp

Index: lldb/test/API/lang/cpp/hide_global_ranges_vars/main.cpp
===
--- /dev/null
+++ lldb/test/API/lang/cpp/hide_global_ranges_vars/main.cpp
@@ -0,0 +1,9 @@
+#include 
+
+int main(int argc, char const *argv[]) {
+  int arr[3] = {1, 2, 3};
+  auto arr_view = std::ranges::views::all(arr);
+  auto arr_max = std::ranges::max_element(arr);
+
+  return 0;
+}
Index: lldb/test/API/lang/cpp/hide_global_ranges_vars/TestHideGlobalRangesVars.py
===
--- /dev/null
+++ lldb/test/API/lang/cpp/hide_global_ranges_vars/TestHideGlobalRangesVars.py
@@ -0,0 +1,27 @@
+"""Test that frame var and target var hide
+the global function objects in the libc++
+ranges implementation"""
+
+from lldbsuite.test.decorators import *
+from lldbsuite.test.lldbtest import *
+from lldbsuite.test import lldbutil
+
+class HideGlobalRangesVarsTestCase(TestBase):
+
+@add_test_categories(["libc++"])
+@skipIf(compiler=no_match("clang"))
+@skipIf(compiler="clang", compiler_version=['<', '16.0'])
+def test(self):
+self.build()
+
+lldbutil.run_to_source_breakpoint(self, "return", lldb.SBFileSpec('main.cpp', False))
+
+self.expect("frame variable --show-globals",
+substrs=["::ranges::views::__cpo",
+ "::ranges::__cpo"],
+matching=False)
+
+self.expect("target variable",
+substrs=["::ranges::views::__cpo",
+ "::ranges::__cpo"],
+matching=False)
Index: lldb/test/API/lang/cpp/hide_global_ranges_vars/Makefile
===
--- /dev/null
+++ lldb/test/API/lang/cpp/hide_global_ranges_vars/Makefile
@@ -0,0 +1,4 @@
+CXX_SOURCES := main.cpp
+CXXFLAGS_EXTRAS := -std=c++20
+
+include Makefile.rules
Index: lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.h
===
--- lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.h
+++ lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.h
@@ -77,6 +77,8 @@
   lldb::ThreadPlanSP GetStepThroughTrampolinePlan(Thread &thread,
   bool stop_others) override;
 
+  bool ShouldHideVariable(llvm::StringRef name) const override;
+
   bool IsAllowedRuntimeValue(ConstString name) override;
 protected:
   // Classes that inherit from CPPLanguageRuntime can see and modify these
Index: lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.cpp
===
--- lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.cpp
+++ lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.cpp
@@ -28,6 +28,7 @@
 #include "lldb/Target/StackFrame.h"
 #include "lldb/Target/ThreadPlanRunToAddress.h"
 #include "lldb/Target/ThreadPlanStepInRange.h"
+#include "lldb/Utility/RegularExpression.h"
 #include "lldb/Utility/Timer.h"
 
 using namespace lldb;
@@ -40,6 +41,17 @@
 CPPLanguageRuntime::CPPLanguageRuntime(Process *process)
 : LanguageRuntime(process) {}
 
+bool CPPLanguageRuntime::ShouldHideVariable(llvm::StringRef name) const {
+  // Matches the global function objects in std::ranges/std::ranges::views
+  // E.g.,
+  //   std::__1::ranges::views::__cpo::take
+  //   std::__1::ranges::__cpo::max_element
+  static RegularExpression ignore_global_ranges_pattern(
+  "std::__[[:alnum:]]+::ranges(::views)*::__cpo");
+
+  return ignore_globale_ranges_pattern.Execute(name);
+}
+
 bool CPPLanguageRuntime::IsAllowedRuntimeValue(ConstString name) {
   return name == g_this;
 }
Index: lldb/source/Core/ValueObject.cpp
===
--- lldb/source/Core/ValueObject.cpp
+++ lldb/source/Core/ValueObject.cpp
@@ -1589,12 +1589,20 @@
   if (!process)
 return false;
 
+  if (!GetVariable())
+return false;
+
+  auto *runtime = process->GetLanguageRuntime(GetVariable()->GetLanguage());
+  if (runtime)
+if (runtime->ShouldHideVariable(GetName().GetStringRef()))
+  return true;
+
   // We trust that the compiler did the right thing and marked runtime suppor

[Lldb-commits] [lldb] de10c1a - [lldb] Ignore libcxx std::ranges global variables in frame var

2023-03-03 Thread Michael Buch via lldb-commits

Author: Michael Buch
Date: 2023-03-03T17:36:43Z
New Revision: de10c1a824405833a0f49b22e7fa3f32a1393cc3

URL: 
https://github.com/llvm/llvm-project/commit/de10c1a824405833a0f49b22e7fa3f32a1393cc3
DIFF: 
https://github.com/llvm/llvm-project/commit/de10c1a824405833a0f49b22e7fa3f32a1393cc3.diff

LOG: [lldb] Ignore libcxx std::ranges global variables in frame var

The motivation is to avoid cluttering LLDB's global variable view for
std::ranges users.

Before:
```
(lldb) frame var -g
...
(const std::ranges::__end::__fn) std::__1::ranges::__cpo::end = {}
(const std::ranges::views::__all::__fn) std::__1::ranges::views::__cpo::all = {}
(const std::ranges::__begin::__fn) std::__1::ranges::__cpo::begin = {}
(const std::ranges::views::__take::__fn) std::__1::ranges::views::__cpo::take = 
{}
(const std::ranges::__max_element::__fn) std::__1::ranges::__cpo::max_element = 
{}
(const std::ranges::__size::__fn) std::__1::ranges::__cpo::size = {}
(const std::ranges::__data::__fn) std::__1::ranges::__cpo::data = {}
```

After this patch none of these __cpo variables would show up.

Differential Revision: https://reviews.llvm.org/D145245

Added: 
lldb/test/API/lang/cpp/hide_global_ranges_vars/Makefile
lldb/test/API/lang/cpp/hide_global_ranges_vars/TestHideGlobalRangesVars.py
lldb/test/API/lang/cpp/hide_global_ranges_vars/main.cpp

Modified: 
lldb/include/lldb/Target/LanguageRuntime.h
lldb/source/Core/ValueObject.cpp
lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.cpp
lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.h

Removed: 




diff  --git a/lldb/include/lldb/Target/LanguageRuntime.h 
b/lldb/include/lldb/Target/LanguageRuntime.h
index 9cc79dc976c4d..34f0fdb9cfbc9 100644
--- a/lldb/include/lldb/Target/LanguageRuntime.h
+++ b/lldb/include/lldb/Target/LanguageRuntime.h
@@ -151,6 +151,11 @@ class LanguageRuntime : public Runtime, public 
PluginInterface {
   /// from the user interface.
   virtual bool IsAllowedRuntimeValue(ConstString name) { return false; }
 
+  /// Returns 'true' if we the variable with the specified 'name'
+  /// should be hidden from variable views (e.g., when listing variables in
+  /// 'frame variable' or 'target variable')
+  virtual bool ShouldHideVariable(llvm::StringRef name) const { return false; }
+
   virtual std::optional GetRuntimeType(CompilerType base_type) {
 return std::nullopt;
   }

diff  --git a/lldb/source/Core/ValueObject.cpp 
b/lldb/source/Core/ValueObject.cpp
index 6e79a04d024e5..f3ca16781e9ad 100644
--- a/lldb/source/Core/ValueObject.cpp
+++ b/lldb/source/Core/ValueObject.cpp
@@ -1600,12 +1600,20 @@ bool ValueObject::IsRuntimeSupportValue() {
   if (!process)
 return false;
 
+  if (!GetVariable())
+return false;
+
+  auto *runtime = process->GetLanguageRuntime(GetVariable()->GetLanguage());
+  if (runtime)
+if (runtime->ShouldHideVariable(GetName().GetStringRef()))
+  return true;
+
   // We trust that the compiler did the right thing and marked runtime support
   // values as artificial.
-  if (!GetVariable() || !GetVariable()->IsArtificial())
+  if (!GetVariable()->IsArtificial())
 return false;
 
-  if (auto *runtime = 
process->GetLanguageRuntime(GetVariable()->GetLanguage()))
+  if (runtime)
 if (runtime->IsAllowedRuntimeValue(GetName()))
   return false;
 

diff  --git 
a/lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.cpp 
b/lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.cpp
index 0028a51412873..5945c57e5aa74 100644
--- a/lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.cpp
+++ b/lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.cpp
@@ -28,6 +28,7 @@
 #include "lldb/Target/StackFrame.h"
 #include "lldb/Target/ThreadPlanRunToAddress.h"
 #include "lldb/Target/ThreadPlanStepInRange.h"
+#include "lldb/Utility/RegularExpression.h"
 #include "lldb/Utility/Timer.h"
 
 using namespace lldb;
@@ -40,6 +41,17 @@ char CPPLanguageRuntime::ID = 0;
 CPPLanguageRuntime::CPPLanguageRuntime(Process *process)
 : LanguageRuntime(process) {}
 
+bool CPPLanguageRuntime::ShouldHideVariable(llvm::StringRef name) const {
+  // Matches the global function objects in std::ranges/std::ranges::views
+  // E.g.,
+  //   std::__1::ranges::views::__cpo::take
+  //   std::__1::ranges::__cpo::max_element
+  static RegularExpression ignore_global_ranges_pattern(
+  "std::__[[:alnum:]]+::ranges(::views)*::__cpo");
+
+  return ignore_globale_ranges_pattern.Execute(name);
+}
+
 bool CPPLanguageRuntime::IsAllowedRuntimeValue(ConstString name) {
   return name == g_this;
 }

diff  --git 
a/lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.h 
b/lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.h
index 1be58b7bf9ea9..097d1da6e909a 100644
--- a/lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.h
+++ b/lldb/source/Plugins/La

[Lldb-commits] [PATCH] D145245: [lldb] Ignore libcxx std::ranges global variables in frame var

2023-03-03 Thread Michael Buch via Phabricator via lldb-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGde10c1a82440: [lldb] Ignore libcxx std::ranges global 
variables in frame var (authored by Michael137).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D145245/new/

https://reviews.llvm.org/D145245

Files:
  lldb/include/lldb/Target/LanguageRuntime.h
  lldb/source/Core/ValueObject.cpp
  lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.cpp
  lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.h
  lldb/test/API/lang/cpp/hide_global_ranges_vars/Makefile
  lldb/test/API/lang/cpp/hide_global_ranges_vars/TestHideGlobalRangesVars.py
  lldb/test/API/lang/cpp/hide_global_ranges_vars/main.cpp

Index: lldb/test/API/lang/cpp/hide_global_ranges_vars/main.cpp
===
--- /dev/null
+++ lldb/test/API/lang/cpp/hide_global_ranges_vars/main.cpp
@@ -0,0 +1,9 @@
+#include 
+
+int main(int argc, char const *argv[]) {
+  int arr[3] = {1, 2, 3};
+  auto arr_view = std::ranges::views::all(arr);
+  auto arr_max = std::ranges::max_element(arr);
+
+  return 0;
+}
Index: lldb/test/API/lang/cpp/hide_global_ranges_vars/TestHideGlobalRangesVars.py
===
--- /dev/null
+++ lldb/test/API/lang/cpp/hide_global_ranges_vars/TestHideGlobalRangesVars.py
@@ -0,0 +1,27 @@
+"""Test that frame var and target var hide
+the global function objects in the libc++
+ranges implementation"""
+
+from lldbsuite.test.decorators import *
+from lldbsuite.test.lldbtest import *
+from lldbsuite.test import lldbutil
+
+class HideGlobalRangesVarsTestCase(TestBase):
+
+@add_test_categories(["libc++"])
+@skipIf(compiler=no_match("clang"))
+@skipIf(compiler="clang", compiler_version=['<', '16.0'])
+def test(self):
+self.build()
+
+lldbutil.run_to_source_breakpoint(self, "return", lldb.SBFileSpec('main.cpp', False))
+
+self.expect("frame variable --show-globals",
+substrs=["::ranges::views::__cpo",
+ "::ranges::__cpo"],
+matching=False)
+
+self.expect("target variable",
+substrs=["::ranges::views::__cpo",
+ "::ranges::__cpo"],
+matching=False)
Index: lldb/test/API/lang/cpp/hide_global_ranges_vars/Makefile
===
--- /dev/null
+++ lldb/test/API/lang/cpp/hide_global_ranges_vars/Makefile
@@ -0,0 +1,4 @@
+CXX_SOURCES := main.cpp
+CXXFLAGS_EXTRAS := -std=c++20
+
+include Makefile.rules
Index: lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.h
===
--- lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.h
+++ lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.h
@@ -77,6 +77,8 @@
   lldb::ThreadPlanSP GetStepThroughTrampolinePlan(Thread &thread,
   bool stop_others) override;
 
+  bool ShouldHideVariable(llvm::StringRef name) const override;
+
   bool IsAllowedRuntimeValue(ConstString name) override;
 protected:
   // Classes that inherit from CPPLanguageRuntime can see and modify these
Index: lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.cpp
===
--- lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.cpp
+++ lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.cpp
@@ -28,6 +28,7 @@
 #include "lldb/Target/StackFrame.h"
 #include "lldb/Target/ThreadPlanRunToAddress.h"
 #include "lldb/Target/ThreadPlanStepInRange.h"
+#include "lldb/Utility/RegularExpression.h"
 #include "lldb/Utility/Timer.h"
 
 using namespace lldb;
@@ -40,6 +41,17 @@
 CPPLanguageRuntime::CPPLanguageRuntime(Process *process)
 : LanguageRuntime(process) {}
 
+bool CPPLanguageRuntime::ShouldHideVariable(llvm::StringRef name) const {
+  // Matches the global function objects in std::ranges/std::ranges::views
+  // E.g.,
+  //   std::__1::ranges::views::__cpo::take
+  //   std::__1::ranges::__cpo::max_element
+  static RegularExpression ignore_global_ranges_pattern(
+  "std::__[[:alnum:]]+::ranges(::views)*::__cpo");
+
+  return ignore_globale_ranges_pattern.Execute(name);
+}
+
 bool CPPLanguageRuntime::IsAllowedRuntimeValue(ConstString name) {
   return name == g_this;
 }
Index: lldb/source/Core/ValueObject.cpp
===
--- lldb/source/Core/ValueObject.cpp
+++ lldb/source/Core/ValueObject.cpp
@@ -1600,12 +1600,20 @@
   if (!process)
 return false;
 
+  if (!GetVariable())
+return false;
+
+  auto *runtime = process->GetLanguageRuntime(GetVariable()->GetLanguage());
+  if (runtime)
+if (runtime->Shoul

[Lldb-commits] [lldb] 4d909c5 - [lldb] Build fix: variable name typo

2023-03-03 Thread Michael Buch via lldb-commits

Author: Michael Buch
Date: 2023-03-03T17:41:32Z
New Revision: 4d909c556e2caa8e150b892384fe8d42e774f8b0

URL: 
https://github.com/llvm/llvm-project/commit/4d909c556e2caa8e150b892384fe8d42e774f8b0
DIFF: 
https://github.com/llvm/llvm-project/commit/4d909c556e2caa8e150b892384fe8d42e774f8b0.diff

LOG: [lldb] Build fix: variable name typo

Build failure introduced in `de10c1a824405833a0f49b22e7fa3f32a1393cc3`

Added: 


Modified: 
lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.cpp

Removed: 




diff  --git 
a/lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.cpp 
b/lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.cpp
index 5945c57e5aa7..91c5283e5b45 100644
--- a/lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.cpp
+++ b/lldb/source/Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.cpp
@@ -49,7 +49,7 @@ bool CPPLanguageRuntime::ShouldHideVariable(llvm::StringRef 
name) const {
   static RegularExpression ignore_global_ranges_pattern(
   "std::__[[:alnum:]]+::ranges(::views)*::__cpo");
 
-  return ignore_globale_ranges_pattern.Execute(name);
+  return ignore_global_ranges_pattern.Execute(name);
 }
 
 bool CPPLanguageRuntime::IsAllowedRuntimeValue(ConstString name) {



___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D145245: [lldb] Ignore libcxx std::ranges global variables in frame var

2023-03-03 Thread Michael Buch via Phabricator via lldb-commits
Michael137 added a comment.

Whoops, last second variable name change broke the build bot. Fixed in 
`4d909c556e2caa8e150b892384fe8d42e774f8b0`


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D145245/new/

https://reviews.llvm.org/D145245

___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] b642fd5 - [lldb][TypeSystemClang] Format pointers to member functions as eFormatHex

2023-03-03 Thread Michael Buch via lldb-commits

Author: Michael Buch
Date: 2023-03-03T17:44:36Z
New Revision: b642fd5ee250247ccefb38099169b4ee8ac4112b

URL: 
https://github.com/llvm/llvm-project/commit/b642fd5ee250247ccefb38099169b4ee8ac4112b
DIFF: 
https://github.com/llvm/llvm-project/commit/b642fd5ee250247ccefb38099169b4ee8ac4112b.diff

LOG: [lldb][TypeSystemClang] Format pointers to member functions as eFormatHex

Before this patch, LLDB used to format pointers to members, such as,
```
void (Foo::*pointer_to_member_func)() = &Foo::member_func;
```
as `eFormatBytes`. E.g.,
```
(lldb) v pointer_to_member_func
(void (Foo::*)()) $1 = 94 3f 00 00 01 00 00 00 00 00 00 00 00 00 00 00
```

This patch makes sure we format pointers to member functions the same
way we do regular function pointers.

After this patch we format member pointers as:
```
(lldb) v pointer_to_member_func
(void (Foo::*)()) ::pointer_to_member_func = 0x00013f94
```

Differential Revision: https://reviews.llvm.org/D145241

Added: 


Modified: 
lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp

lldb/test/API/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py
lldb/test/API/functionalities/data-formatter/data-formatter-cpp/main.cpp

Removed: 




diff  --git a/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp 
b/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
index 388c3675dacc5..e08e7bcd96e38 100644
--- a/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
+++ b/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
@@ -5277,7 +5277,7 @@ lldb::Format 
TypeSystemClang::GetFormat(lldb::opaque_compiler_type_t type) {
   case clang::Type::RValueReference:
 return lldb::eFormatHex;
   case clang::Type::MemberPointer:
-break;
+return lldb::eFormatHex;
   case clang::Type::Complex: {
 if (qual_type->isComplexType())
   return lldb::eFormatComplex;

diff  --git 
a/lldb/test/API/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py
 
b/lldb/test/API/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py
index fa9a3f5093d05..fb79d1463e5e1 100644
--- 
a/lldb/test/API/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py
+++ 
b/lldb/test/API/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py
@@ -285,3 +285,14 @@ def cleanup():
 matching=False,
 substrs=['(int) iAmInt = 0x0001'])
 self.expect("frame variable iAmInt", substrs=['(int) iAmInt = 1'])
+
+# Check that pointer to members are correctly formatted
+self.expect(
+"frame variable member_ptr",
+substrs=['member_ptr = 0x'])
+self.expect(
+"frame variable member_func_ptr",
+substrs=['member_func_ptr = 0x'])
+self.expect(
+"frame variable ref_to_member_func_ptr",
+substrs=['ref_to_member_func_ptr = 0x'])

diff  --git 
a/lldb/test/API/functionalities/data-formatter/data-formatter-cpp/main.cpp 
b/lldb/test/API/functionalities/data-formatter/data-formatter-cpp/main.cpp
index c81a68fd2094a..f1cf507e47f87 100644
--- a/lldb/test/API/functionalities/data-formatter/data-formatter-cpp/main.cpp
+++ b/lldb/test/API/functionalities/data-formatter/data-formatter-cpp/main.cpp
@@ -57,6 +57,8 @@ struct IUseCharStar
 {
const char* pointer;
IUseCharStar() : pointer("Hello world") {}
+
+char const *member_func(int) { return ""; }
 };
 
 int main (int argc, const char * argv[])
@@ -106,7 +108,12 @@ int main (int argc, const char * argv[])
 char* strptr = "Hello world!";
 
 i_am_cooler the_coolest_guy(1,2,3.14,6.28,'E','G');
-
+
+const char *IUseCharStar::*member_ptr = &IUseCharStar::pointer;
+const char *(IUseCharStar::*member_func_ptr)(int) =
+&IUseCharStar::member_func;
+auto &ref_to_member_func_ptr = member_func_ptr;
+
 return 0; // Set break point at this line.
 }
 



___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] d84117d - [lldb][TypeSystemClang][NFC] Factor out l/r-value reference logic for IsXXXType APIs

2023-03-03 Thread Michael Buch via lldb-commits

Author: Michael Buch
Date: 2023-03-03T17:44:35Z
New Revision: d84117d0ef5fe818990ec2a5199f4b8ceee927b5

URL: 
https://github.com/llvm/llvm-project/commit/d84117d0ef5fe818990ec2a5199f4b8ceee927b5
DIFF: 
https://github.com/llvm/llvm-project/commit/d84117d0ef5fe818990ec2a5199f4b8ceee927b5.diff

LOG: [lldb][TypeSystemClang][NFC] Factor out l/r-value reference logic for 
IsXXXType APIs

This will be useful as we add more `IsXXXType` APIs for different
function types.

Differential Revision: https://reviews.llvm.org/D145240

Added: 


Modified: 
lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h

Removed: 




diff  --git a/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp 
b/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
index bf0dcc3a92576..388c3675dacc5 100644
--- a/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
+++ b/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
@@ -3050,28 +3050,11 @@ bool 
TypeSystemClang::IsCStringType(lldb::opaque_compiler_type_t type,
 }
 
 bool TypeSystemClang::IsFunctionType(lldb::opaque_compiler_type_t type) {
-  if (type) {
-clang::QualType qual_type = 
RemoveWrappingTypes(GetCanonicalQualType(type));
-
-if (qual_type->isFunctionType()) {
-  return true;
-}
+  auto isFunctionType = [&](clang::QualType qual_type) {
+return qual_type->isFunctionType();
+  };
 
-const clang::Type::TypeClass type_class = qual_type->getTypeClass();
-switch (type_class) {
-default:
-  break;
-case clang::Type::LValueReference:
-case clang::Type::RValueReference: {
-  const clang::ReferenceType *reference_type =
-  llvm::cast(qual_type.getTypePtr());
-  if (reference_type)
-return IsFunctionType(
-reference_type->getPointeeType().getAsOpaquePtr());
-} break;
-}
-  }
-  return false;
+  return IsTypeImpl(type, isFunctionType);
 }
 
 // Used to detect "Homogeneous Floating-point Aggregates"
@@ -3185,11 +3168,13 @@ 
TypeSystemClang::GetFunctionArgumentAtIndex(lldb::opaque_compiler_type_t type,
   return CompilerType();
 }
 
-bool TypeSystemClang::IsFunctionPointerType(lldb::opaque_compiler_type_t type) 
{
+bool TypeSystemClang::IsTypeImpl(
+lldb::opaque_compiler_type_t type,
+llvm::function_ref predicate) const {
   if (type) {
 clang::QualType qual_type = 
RemoveWrappingTypes(GetCanonicalQualType(type));
 
-if (qual_type->isFunctionPointerType())
+if (predicate(qual_type))
   return true;
 
 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
@@ -3202,20 +3187,25 @@ bool 
TypeSystemClang::IsFunctionPointerType(lldb::opaque_compiler_type_t type) {
   const clang::ReferenceType *reference_type =
   llvm::cast(qual_type.getTypePtr());
   if (reference_type)
-return IsFunctionPointerType(
-reference_type->getPointeeType().getAsOpaquePtr());
+return IsTypeImpl(reference_type->getPointeeType().getAsOpaquePtr(), 
predicate);
 } break;
 }
   }
   return false;
 }
 
+bool TypeSystemClang::IsFunctionPointerType(lldb::opaque_compiler_type_t type) 
{
+  auto isFunctionPointerType = [](clang::QualType qual_type) {
+return qual_type->isFunctionPointerType();
+  };
+
+  return IsTypeImpl(type, isFunctionPointerType);
+}
+
 bool TypeSystemClang::IsBlockPointerType(
 lldb::opaque_compiler_type_t type,
 CompilerType *function_pointer_type_ptr) {
-  if (type) {
-clang::QualType qual_type = 
RemoveWrappingTypes(GetCanonicalQualType(type));
-
+  auto isBlockPointerType = [&](clang::QualType qual_type) {
 if (qual_type->isBlockPointerType()) {
   if (function_pointer_type_ptr) {
 const clang::BlockPointerType *block_pointer_type =
@@ -3228,23 +3218,10 @@ bool TypeSystemClang::IsBlockPointerType(
   return true;
 }
 
-const clang::Type::TypeClass type_class = qual_type->getTypeClass();
-switch (type_class) {
-default:
-  break;
+return false;
+  };
 
-case clang::Type::LValueReference:
-case clang::Type::RValueReference: {
-  const clang::ReferenceType *reference_type =
-  llvm::cast(qual_type.getTypePtr());
-  if (reference_type)
-return IsBlockPointerType(
-reference_type->getPointeeType().getAsOpaquePtr(),
-function_pointer_type_ptr);
-} break;
-}
-  }
-  return false;
+  return IsTypeImpl(type, isBlockPointerType);
 }
 
 bool TypeSystemClang::IsIntegerType(lldb::opaque_compiler_type_t type,

diff  --git a/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h 
b/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
index 14c4a2f864bcf..9751c0de3a50d 100644
--- a/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
+++ b/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
@@ -1147,6 +1147,9 @@ class TypeSystemClang : public Ty

[Lldb-commits] [lldb] 6bd46e7 - [lldb][TypeSystemClang] Use the CXXFunctionPointerSummaryProvider for member-function pointers

2023-03-03 Thread Michael Buch via lldb-commits

Author: Michael Buch
Date: 2023-03-03T17:44:36Z
New Revision: 6bd46e713c6d8deda7bdae8b1efadb99c88b4443

URL: 
https://github.com/llvm/llvm-project/commit/6bd46e713c6d8deda7bdae8b1efadb99c88b4443
DIFF: 
https://github.com/llvm/llvm-project/commit/6bd46e713c6d8deda7bdae8b1efadb99c88b4443.diff

LOG: [lldb][TypeSystemClang] Use the CXXFunctionPointerSummaryProvider for 
member-function pointers

With this patch member-function pointers are formatted using
`CXXFunctionPointerSummaryProvider`.

This turns,
```
(lldb) v pointer_to_member_func
(void (Foo::*)()) ::pointer_to_member_func = 0x00013f94
```
into
```
(lldb) v pointer_to_member_func
(void (Foo::*)()) ::pointer_to_member_func = 0x00013f94 
(a.out`Foo::member_func() at main.cpp:3)
```

Differential Revision: https://reviews.llvm.org/D145242

Added: 


Modified: 
lldb/include/lldb/Symbol/CompilerType.h
lldb/include/lldb/Symbol/TypeSystem.h
lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp
lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
lldb/source/Symbol/CompilerType.cpp

lldb/test/API/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py

Removed: 




diff  --git a/lldb/include/lldb/Symbol/CompilerType.h 
b/lldb/include/lldb/Symbol/CompilerType.h
index c96fc5a2b6886..50587f4aab827 100644
--- a/lldb/include/lldb/Symbol/CompilerType.h
+++ b/lldb/include/lldb/Symbol/CompilerType.h
@@ -164,6 +164,8 @@ class CompilerType {
 
   bool IsFunctionPointerType() const;
 
+  bool IsMemberFunctionPointerType() const;
+
   bool
   IsBlockPointerType(CompilerType *function_pointer_type_ptr = nullptr) const;
 

diff  --git a/lldb/include/lldb/Symbol/TypeSystem.h 
b/lldb/include/lldb/Symbol/TypeSystem.h
index a358d6fb13ad4..9c27fd92906a6 100644
--- a/lldb/include/lldb/Symbol/TypeSystem.h
+++ b/lldb/include/lldb/Symbol/TypeSystem.h
@@ -169,6 +169,9 @@ class TypeSystem : public PluginInterface,
 
   virtual bool IsFunctionPointerType(lldb::opaque_compiler_type_t type) = 0;
 
+  virtual bool
+  IsMemberFunctionPointerType(lldb::opaque_compiler_type_t type) = 0;
+
   virtual bool IsBlockPointerType(lldb::opaque_compiler_type_t type,
   CompilerType *function_pointer_type_ptr) = 0;
 

diff  --git a/lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp 
b/lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp
index 1b152c16eac2a..0dfaa92ac99f4 100644
--- a/lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp
+++ b/lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp
@@ -1390,7 +1390,8 @@ CPlusPlusLanguage::GetHardcodedSummaries() {
   TypeSummaryImpl::Flags(),
   lldb_private::formatters::CXXFunctionPointerSummaryProvider,
   "Function pointer summary provider"));
-  if (valobj.GetCompilerType().IsFunctionPointerType()) {
+  if (CompilerType CT = valobj.GetCompilerType();
+  CT.IsFunctionPointerType() || CT.IsMemberFunctionPointerType()) {
 return formatter_sp;
   }
   return nullptr;

diff  --git a/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp 
b/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
index e08e7bcd96e38..aefc67ba10b37 100644
--- a/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
+++ b/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
@@ -3194,6 +3194,15 @@ bool TypeSystemClang::IsTypeImpl(
   return false;
 }
 
+bool TypeSystemClang::IsMemberFunctionPointerType(
+lldb::opaque_compiler_type_t type) {
+  auto isMemberFunctionPointerType = [](clang::QualType qual_type) {
+return qual_type->isMemberFunctionPointerType();
+  };
+
+  return IsTypeImpl(type, isMemberFunctionPointerType);
+}
+
 bool TypeSystemClang::IsFunctionPointerType(lldb::opaque_compiler_type_t type) 
{
   auto isFunctionPointerType = [](clang::QualType qual_type) {
 return qual_type->isFunctionPointerType();

diff  --git a/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h 
b/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
index 9751c0de3a50d..d6c09cf3725f3 100644
--- a/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
+++ b/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
@@ -658,6 +658,8 @@ class TypeSystemClang : public TypeSystem {
 
   bool IsFunctionPointerType(lldb::opaque_compiler_type_t type) override;
 
+  bool IsMemberFunctionPointerType(lldb::opaque_compiler_type_t type) override;
+
   bool IsBlockPointerType(lldb::opaque_compiler_type_t type,
   CompilerType *function_pointer_type_ptr) override;
 

diff  --git a/lldb/source/Symbol/CompilerType.cpp 
b/lldb/source/Symbol/CompilerType.cpp
index 11a7d09680d3f..d6dc43c05d1bd 100644
--- a/lldb/source/Symbol/CompilerType.cpp
+++ b/lldb/so

[Lldb-commits] [PATCH] D145240: [lldb][TypeSystemClang][NFC] Factor out l/r-value reference logic for IsXXXType APIs

2023-03-03 Thread Michael Buch via Phabricator via lldb-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGd84117d0ef5f: [lldb][TypeSystemClang][NFC] Factor out 
l/r-value reference logic for IsXXXType… (authored by Michael137).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D145240/new/

https://reviews.llvm.org/D145240

Files:
  lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
  lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h

Index: lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
===
--- lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
+++ lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
@@ -1147,6 +1147,9 @@
   const clang::ClassTemplateSpecializationDecl *
   GetAsTemplateSpecialization(lldb::opaque_compiler_type_t type);
 
+  bool IsTypeImpl(lldb::opaque_compiler_type_t type,
+  llvm::function_ref predicate) const;
+
   // Classes that inherit from TypeSystemClang can see and modify these
   std::string m_target_triple;
   std::unique_ptr m_ast_up;
Index: lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
===
--- lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
+++ lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
@@ -3050,28 +3050,11 @@
 }
 
 bool TypeSystemClang::IsFunctionType(lldb::opaque_compiler_type_t type) {
-  if (type) {
-clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
-
-if (qual_type->isFunctionType()) {
-  return true;
-}
+  auto isFunctionType = [&](clang::QualType qual_type) {
+return qual_type->isFunctionType();
+  };
 
-const clang::Type::TypeClass type_class = qual_type->getTypeClass();
-switch (type_class) {
-default:
-  break;
-case clang::Type::LValueReference:
-case clang::Type::RValueReference: {
-  const clang::ReferenceType *reference_type =
-  llvm::cast(qual_type.getTypePtr());
-  if (reference_type)
-return IsFunctionType(
-reference_type->getPointeeType().getAsOpaquePtr());
-} break;
-}
-  }
-  return false;
+  return IsTypeImpl(type, isFunctionType);
 }
 
 // Used to detect "Homogeneous Floating-point Aggregates"
@@ -3185,11 +3168,13 @@
   return CompilerType();
 }
 
-bool TypeSystemClang::IsFunctionPointerType(lldb::opaque_compiler_type_t type) {
+bool TypeSystemClang::IsTypeImpl(
+lldb::opaque_compiler_type_t type,
+llvm::function_ref predicate) const {
   if (type) {
 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
 
-if (qual_type->isFunctionPointerType())
+if (predicate(qual_type))
   return true;
 
 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
@@ -3202,20 +3187,25 @@
   const clang::ReferenceType *reference_type =
   llvm::cast(qual_type.getTypePtr());
   if (reference_type)
-return IsFunctionPointerType(
-reference_type->getPointeeType().getAsOpaquePtr());
+return IsTypeImpl(reference_type->getPointeeType().getAsOpaquePtr(), predicate);
 } break;
 }
   }
   return false;
 }
 
+bool TypeSystemClang::IsFunctionPointerType(lldb::opaque_compiler_type_t type) {
+  auto isFunctionPointerType = [](clang::QualType qual_type) {
+return qual_type->isFunctionPointerType();
+  };
+
+  return IsTypeImpl(type, isFunctionPointerType);
+}
+
 bool TypeSystemClang::IsBlockPointerType(
 lldb::opaque_compiler_type_t type,
 CompilerType *function_pointer_type_ptr) {
-  if (type) {
-clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
-
+  auto isBlockPointerType = [&](clang::QualType qual_type) {
 if (qual_type->isBlockPointerType()) {
   if (function_pointer_type_ptr) {
 const clang::BlockPointerType *block_pointer_type =
@@ -3228,23 +3218,10 @@
   return true;
 }
 
-const clang::Type::TypeClass type_class = qual_type->getTypeClass();
-switch (type_class) {
-default:
-  break;
+return false;
+  };
 
-case clang::Type::LValueReference:
-case clang::Type::RValueReference: {
-  const clang::ReferenceType *reference_type =
-  llvm::cast(qual_type.getTypePtr());
-  if (reference_type)
-return IsBlockPointerType(
-reference_type->getPointeeType().getAsOpaquePtr(),
-function_pointer_type_ptr);
-} break;
-}
-  }
-  return false;
+  return IsTypeImpl(type, isBlockPointerType);
 }
 
 bool TypeSystemClang::IsIntegerType(lldb::opaque_compiler_type_t type,
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D145241: [lldb][TypeSystemClang] Format pointers to member functions as eFormatHex

2023-03-03 Thread Michael Buch via Phabricator via lldb-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb642fd5ee250: [lldb][TypeSystemClang] Format pointers to 
member functions as eFormatHex (authored by Michael137).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D145241/new/

https://reviews.llvm.org/D145241

Files:
  lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
  
lldb/test/API/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py
  lldb/test/API/functionalities/data-formatter/data-formatter-cpp/main.cpp


Index: lldb/test/API/functionalities/data-formatter/data-formatter-cpp/main.cpp
===
--- lldb/test/API/functionalities/data-formatter/data-formatter-cpp/main.cpp
+++ lldb/test/API/functionalities/data-formatter/data-formatter-cpp/main.cpp
@@ -57,6 +57,8 @@
 {
const char* pointer;
IUseCharStar() : pointer("Hello world") {}
+
+char const *member_func(int) { return ""; }
 };
 
 int main (int argc, const char * argv[])
@@ -106,7 +108,12 @@
 char* strptr = "Hello world!";
 
 i_am_cooler the_coolest_guy(1,2,3.14,6.28,'E','G');
-
+
+const char *IUseCharStar::*member_ptr = &IUseCharStar::pointer;
+const char *(IUseCharStar::*member_func_ptr)(int) =
+&IUseCharStar::member_func;
+auto &ref_to_member_func_ptr = member_func_ptr;
+
 return 0; // Set break point at this line.
 }
 
Index: 
lldb/test/API/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py
===
--- 
lldb/test/API/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py
+++ 
lldb/test/API/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py
@@ -285,3 +285,14 @@
 matching=False,
 substrs=['(int) iAmInt = 0x0001'])
 self.expect("frame variable iAmInt", substrs=['(int) iAmInt = 1'])
+
+# Check that pointer to members are correctly formatted
+self.expect(
+"frame variable member_ptr",
+substrs=['member_ptr = 0x'])
+self.expect(
+"frame variable member_func_ptr",
+substrs=['member_func_ptr = 0x'])
+self.expect(
+"frame variable ref_to_member_func_ptr",
+substrs=['ref_to_member_func_ptr = 0x'])
Index: lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
===
--- lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
+++ lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
@@ -5277,7 +5277,7 @@
   case clang::Type::RValueReference:
 return lldb::eFormatHex;
   case clang::Type::MemberPointer:
-break;
+return lldb::eFormatHex;
   case clang::Type::Complex: {
 if (qual_type->isComplexType())
   return lldb::eFormatComplex;


Index: lldb/test/API/functionalities/data-formatter/data-formatter-cpp/main.cpp
===
--- lldb/test/API/functionalities/data-formatter/data-formatter-cpp/main.cpp
+++ lldb/test/API/functionalities/data-formatter/data-formatter-cpp/main.cpp
@@ -57,6 +57,8 @@
 {
 	const char* pointer;
 	IUseCharStar() : pointer("Hello world") {}
+
+char const *member_func(int) { return ""; }
 };
 
 int main (int argc, const char * argv[])
@@ -106,7 +108,12 @@
 char* strptr = "Hello world!";
 
 i_am_cooler the_coolest_guy(1,2,3.14,6.28,'E','G');
-
+
+const char *IUseCharStar::*member_ptr = &IUseCharStar::pointer;
+const char *(IUseCharStar::*member_func_ptr)(int) =
+&IUseCharStar::member_func;
+auto &ref_to_member_func_ptr = member_func_ptr;
+
 return 0; // Set break point at this line.
 }
 
Index: lldb/test/API/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py
===
--- lldb/test/API/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py
+++ lldb/test/API/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py
@@ -285,3 +285,14 @@
 matching=False,
 substrs=['(int) iAmInt = 0x0001'])
 self.expect("frame variable iAmInt", substrs=['(int) iAmInt = 1'])
+
+# Check that pointer to members are correctly formatted
+self.expect(
+"frame variable member_ptr",
+substrs=['member_ptr = 0x'])
+self.expect(
+"frame variable member_func_ptr",
+substrs=['member_func_ptr = 0x'])
+self.expect(
+"frame variable ref_to_member_func_ptr",
+substrs=['ref_to_member_func_ptr = 0x'])
Index: lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
===
--- lldb/source/Plugins/TypeSystem/Clang/TypeSyste

[Lldb-commits] [PATCH] D145242: [lldb][TypeSystemClang] Use the CXXFunctionPointerSummaryProvider for member-function pointers

2023-03-03 Thread Michael Buch via Phabricator via lldb-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG6bd46e713c6d: [lldb][TypeSystemClang] Use the 
CXXFunctionPointerSummaryProvider for member… (authored by Michael137).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D145242/new/

https://reviews.llvm.org/D145242

Files:
  lldb/include/lldb/Symbol/CompilerType.h
  lldb/include/lldb/Symbol/TypeSystem.h
  lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp
  lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
  lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
  lldb/source/Symbol/CompilerType.cpp
  
lldb/test/API/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py

Index: lldb/test/API/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py
===
--- lldb/test/API/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py
+++ lldb/test/API/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py
@@ -292,7 +292,9 @@
 substrs=['member_ptr = 0x'])
 self.expect(
 "frame variable member_func_ptr",
-substrs=['member_func_ptr = 0x'])
+substrs=['member_func_ptr = 0x',
+ '(a.out`IUseCharStar::member_func(int) at main.cpp:61)'])
 self.expect(
 "frame variable ref_to_member_func_ptr",
-substrs=['ref_to_member_func_ptr = 0x'])
+substrs=['ref_to_member_func_ptr = 0x',
+ '(a.out`IUseCharStar::member_func(int) at main.cpp:61)'])
Index: lldb/source/Symbol/CompilerType.cpp
===
--- lldb/source/Symbol/CompilerType.cpp
+++ lldb/source/Symbol/CompilerType.cpp
@@ -154,6 +154,13 @@
   return false;
 }
 
+bool CompilerType::IsMemberFunctionPointerType() const {
+  if (IsValid())
+if (auto type_system_sp = GetTypeSystem())
+  return type_system_sp->IsMemberFunctionPointerType(m_type);
+  return false;
+}
+
 bool CompilerType::IsBlockPointerType(
 CompilerType *function_pointer_type_ptr) const {
   if (IsValid())
Index: lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
===
--- lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
+++ lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
@@ -658,6 +658,8 @@
 
   bool IsFunctionPointerType(lldb::opaque_compiler_type_t type) override;
 
+  bool IsMemberFunctionPointerType(lldb::opaque_compiler_type_t type) override;
+
   bool IsBlockPointerType(lldb::opaque_compiler_type_t type,
   CompilerType *function_pointer_type_ptr) override;
 
Index: lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
===
--- lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
+++ lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
@@ -3194,6 +3194,15 @@
   return false;
 }
 
+bool TypeSystemClang::IsMemberFunctionPointerType(
+lldb::opaque_compiler_type_t type) {
+  auto isMemberFunctionPointerType = [](clang::QualType qual_type) {
+return qual_type->isMemberFunctionPointerType();
+  };
+
+  return IsTypeImpl(type, isMemberFunctionPointerType);
+}
+
 bool TypeSystemClang::IsFunctionPointerType(lldb::opaque_compiler_type_t type) {
   auto isFunctionPointerType = [](clang::QualType qual_type) {
 return qual_type->isFunctionPointerType();
Index: lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp
===
--- lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp
+++ lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp
@@ -1390,7 +1390,8 @@
   TypeSummaryImpl::Flags(),
   lldb_private::formatters::CXXFunctionPointerSummaryProvider,
   "Function pointer summary provider"));
-  if (valobj.GetCompilerType().IsFunctionPointerType()) {
+  if (CompilerType CT = valobj.GetCompilerType();
+  CT.IsFunctionPointerType() || CT.IsMemberFunctionPointerType()) {
 return formatter_sp;
   }
   return nullptr;
Index: lldb/include/lldb/Symbol/TypeSystem.h
===
--- lldb/include/lldb/Symbol/TypeSystem.h
+++ lldb/include/lldb/Symbol/TypeSystem.h
@@ -169,6 +169,9 @@
 
   virtual bool IsFunctionPointerType(lldb::opaque_compiler_type_t type) = 0;
 
+  virtual bool
+  IsMemberFunctionPointerType(lldb::opaque_compiler_type_t type) = 0;
+
   virtual bool IsBlockPointerType(lldb::opaque_compiler_type_t type,
   CompilerType *function_pointer_type_ptr) = 0;
 
Index: lldb/include/lldb/Symbol/CompilerType.h
==

[Lldb-commits] [lldb] 83263ae - Add HitCount into Breakpoint statistics

2023-03-03 Thread Jeffrey Tan via lldb-commits

Author: Jeffrey Tan
Date: 2023-03-03T10:28:56-08:00
New Revision: 83263aeceb8e89709a5da417db753a02bb5a0fbd

URL: 
https://github.com/llvm/llvm-project/commit/83263aeceb8e89709a5da417db753a02bb5a0fbd
DIFF: 
https://github.com/llvm/llvm-project/commit/83263aeceb8e89709a5da417db753a02bb5a0fbd.diff

LOG: Add HitCount into Breakpoint statistics

Turns out breakpoint statistics is missing hitCount.
This patches adds the hitCount field.

Differential Revision: https://reviews.llvm.org/D145203

Added: 


Modified: 
lldb/source/Breakpoint/Breakpoint.cpp

lldb/test/API/functionalities/breakpoint/breakpoint_command/TestBreakpointCommand.py

Removed: 




diff  --git a/lldb/source/Breakpoint/Breakpoint.cpp 
b/lldb/source/Breakpoint/Breakpoint.cpp
index aad01a2e6fb67..bdaf3c905d042 100644
--- a/lldb/source/Breakpoint/Breakpoint.cpp
+++ b/lldb/source/Breakpoint/Breakpoint.cpp
@@ -532,12 +532,12 @@ void Breakpoint::ModulesChanged(ModuleList &module_list, 
bool load,
   locations_with_no_section.Add(break_loc_sp);
   continue;
 }
-  
+
 if (!break_loc_sp->IsEnabled())
   continue;
-
+
 SectionSP section_sp(section_addr.GetSection());
-
+
 // If we don't have a Section, that means this location is a raw
 // address that we haven't resolved to a section yet.  So we'll have to
 // look in all the new modules to resolve this location. Otherwise, if
@@ -554,9 +554,9 @@ void Breakpoint::ModulesChanged(ModuleList &module_list, 
bool load,
   }
 }
   }
-  
+
   size_t num_to_delete = locations_with_no_section.GetSize();
-  
+
   for (size_t i = 0; i < num_to_delete; i++)
 m_locations.RemoveLocation(locations_with_no_section.GetByIndex(i));
 
@@ -1132,12 +1132,13 @@ json::Value Breakpoint::GetStatistics() {
   bp.try_emplace("resolveTime", m_resolve_time.get().count());
   bp.try_emplace("numLocations", (int64_t)GetNumLocations());
   bp.try_emplace("numResolvedLocations", (int64_t)GetNumResolvedLocations());
+  bp.try_emplace("hitCount", (int64_t)GetHitCount());
   bp.try_emplace("internal", IsInternal());
   if (!m_kind_description.empty())
 bp.try_emplace("kindDescription", m_kind_description);
   // Put the full structured data for reproducing this breakpoint in a 
key/value
   // pair named "details". This allows the breakpoint's details to be visible
-  // in the stats in case we need to reproduce a breakpoint that has long 
+  // in the stats in case we need to reproduce a breakpoint that has long
   // resolve times
   StructuredData::ObjectSP bp_data_sp = SerializeToStructuredData();
   if (bp_data_sp) {

diff  --git 
a/lldb/test/API/functionalities/breakpoint/breakpoint_command/TestBreakpointCommand.py
 
b/lldb/test/API/functionalities/breakpoint/breakpoint_command/TestBreakpointCommand.py
index 36860ecb29482..95d2a633d24e5 100644
--- 
a/lldb/test/API/functionalities/breakpoint/breakpoint_command/TestBreakpointCommand.py
+++ 
b/lldb/test/API/functionalities/breakpoint/breakpoint_command/TestBreakpointCommand.py
@@ -423,7 +423,6 @@ def test_add_commands_by_breakpoint_name(self):
 patterns=["bktptcmd.function"])
 
 
-
 def test_breakpoint_delete_disabled(self):
 """Test 'break delete --disabled' works"""
 self.build()
@@ -548,3 +547,26 @@ def test_breakpoints_auto_source_map_relative(self):
 
 source_map_json = self.get_source_map_json()
 self.assertEquals(len(source_map_json), 0, "source map should not be 
deduced")
+
+
+def test_breakpoint_statistics_hitcount(self):
+"""Test breakpoints statistics have hitCount field."""
+self.build()
+target = self.createTestTarget()
+
+lldbutil.run_break_set_by_file_and_line(
+self, "main.c", self.line, num_expected_locations=1, 
loc_exact=True)
+
+stream = lldb.SBStream()
+res = target.GetStatistics().GetAsJSON(stream)
+self.assertTrue(res.Success())
+debug_stats = json.loads(stream.GetData())
+self.assertEqual('targets' in debug_stats, True,
+'Make sure the "targets" key in in target.GetStatistics()')
+target_stats = debug_stats['targets'][0]
+self.assertNotEqual(target_stats, None)
+
+breakpoints_stats = target_stats['breakpoints']
+self.assertNotEqual(breakpoints_stats, None)
+for breakpoint_stats in breakpoints_stats:
+self.assertIn("hitCount", breakpoint_stats)



___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D145203: Add HitCount into Breakpoint statistics

2023-03-03 Thread jeffrey tan via Phabricator via lldb-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG83263aeceb8e: Add HitCount into Breakpoint statistics 
(authored by yinghuitan).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D145203/new/

https://reviews.llvm.org/D145203

Files:
  lldb/source/Breakpoint/Breakpoint.cpp
  
lldb/test/API/functionalities/breakpoint/breakpoint_command/TestBreakpointCommand.py


Index: 
lldb/test/API/functionalities/breakpoint/breakpoint_command/TestBreakpointCommand.py
===
--- 
lldb/test/API/functionalities/breakpoint/breakpoint_command/TestBreakpointCommand.py
+++ 
lldb/test/API/functionalities/breakpoint/breakpoint_command/TestBreakpointCommand.py
@@ -423,7 +423,6 @@
 patterns=["bktptcmd.function"])
 
 
-
 def test_breakpoint_delete_disabled(self):
 """Test 'break delete --disabled' works"""
 self.build()
@@ -548,3 +547,26 @@
 
 source_map_json = self.get_source_map_json()
 self.assertEquals(len(source_map_json), 0, "source map should not be 
deduced")
+
+
+def test_breakpoint_statistics_hitcount(self):
+"""Test breakpoints statistics have hitCount field."""
+self.build()
+target = self.createTestTarget()
+
+lldbutil.run_break_set_by_file_and_line(
+self, "main.c", self.line, num_expected_locations=1, 
loc_exact=True)
+
+stream = lldb.SBStream()
+res = target.GetStatistics().GetAsJSON(stream)
+self.assertTrue(res.Success())
+debug_stats = json.loads(stream.GetData())
+self.assertEqual('targets' in debug_stats, True,
+'Make sure the "targets" key in in target.GetStatistics()')
+target_stats = debug_stats['targets'][0]
+self.assertNotEqual(target_stats, None)
+
+breakpoints_stats = target_stats['breakpoints']
+self.assertNotEqual(breakpoints_stats, None)
+for breakpoint_stats in breakpoints_stats:
+self.assertIn("hitCount", breakpoint_stats)
Index: lldb/source/Breakpoint/Breakpoint.cpp
===
--- lldb/source/Breakpoint/Breakpoint.cpp
+++ lldb/source/Breakpoint/Breakpoint.cpp
@@ -532,12 +532,12 @@
   locations_with_no_section.Add(break_loc_sp);
   continue;
 }
-  
+
 if (!break_loc_sp->IsEnabled())
   continue;
-
+
 SectionSP section_sp(section_addr.GetSection());
-
+
 // If we don't have a Section, that means this location is a raw
 // address that we haven't resolved to a section yet.  So we'll have to
 // look in all the new modules to resolve this location. Otherwise, if
@@ -554,9 +554,9 @@
   }
 }
   }
-  
+
   size_t num_to_delete = locations_with_no_section.GetSize();
-  
+
   for (size_t i = 0; i < num_to_delete; i++)
 m_locations.RemoveLocation(locations_with_no_section.GetByIndex(i));
 
@@ -1132,12 +1132,13 @@
   bp.try_emplace("resolveTime", m_resolve_time.get().count());
   bp.try_emplace("numLocations", (int64_t)GetNumLocations());
   bp.try_emplace("numResolvedLocations", (int64_t)GetNumResolvedLocations());
+  bp.try_emplace("hitCount", (int64_t)GetHitCount());
   bp.try_emplace("internal", IsInternal());
   if (!m_kind_description.empty())
 bp.try_emplace("kindDescription", m_kind_description);
   // Put the full structured data for reproducing this breakpoint in a 
key/value
   // pair named "details". This allows the breakpoint's details to be visible
-  // in the stats in case we need to reproduce a breakpoint that has long 
+  // in the stats in case we need to reproduce a breakpoint that has long
   // resolve times
   StructuredData::ObjectSP bp_data_sp = SerializeToStructuredData();
   if (bp_data_sp) {


Index: lldb/test/API/functionalities/breakpoint/breakpoint_command/TestBreakpointCommand.py
===
--- lldb/test/API/functionalities/breakpoint/breakpoint_command/TestBreakpointCommand.py
+++ lldb/test/API/functionalities/breakpoint/breakpoint_command/TestBreakpointCommand.py
@@ -423,7 +423,6 @@
 patterns=["bktptcmd.function"])
 
 
-
 def test_breakpoint_delete_disabled(self):
 """Test 'break delete --disabled' works"""
 self.build()
@@ -548,3 +547,26 @@
 
 source_map_json = self.get_source_map_json()
 self.assertEquals(len(source_map_json), 0, "source map should not be deduced")
+
+
+def test_breakpoint_statistics_hitcount(self):
+"""Test breakpoints statistics have hitCount field."""
+self.build()
+target = self.createTestTarget()
+
+lldbutil.run_break_set_by_file_and_line(
+self, "main.c", self.line, num_expected_locations=1, loc_exact=True)
+
+stream = lldb.SBS

[Lldb-commits] [PATCH] D145180: [lldb] Introduce new SymbolFileJSON and ObjectFileJSON

2023-03-03 Thread Jonas Devlieghere via Phabricator via lldb-commits
JDevlieghere marked 4 inline comments as done.
JDevlieghere added a comment.

Thanks for the feedback Greg, they're all great suggestions.

In D145180#4166302 , @clayborg wrote:

> From reading this it looks like your main use case is to supply additional 
> symbols to an existing stripped binary. Is that correct?

That's one use case, the other one being the interactive crashlogs. I went into 
a bit a bit more detail in the summary.

> Are you aware that each dSYM file has a full copy of the unstripped symbol 
> table already? It removes the debug map entries, but each dSYM copies all non 
> debug map symbols inside of it already. So the same thing from this patch can 
> already be accomplished by stripping a dSYM file of all debug info sections 
> and leaving the symbol table alone, and then using this this minimal dSYM 
> file just to get the symbols.

Yup and for the strip scenario I described above, we wouldn't even have to go 
through a dSYM, we could just have `llvm-strip` emit a Mach-O with only the 
unstripped symbol table and that should work out of the box in LLDB (similar to 
how you can add the unstripped binary with `target symbols add`). But for the 
crashlog use case where we only have an address and a symbol, it would be 
really tedious to have to build the whole symbol table. I really like the idea 
of a textual format for this and it's easy to read and modify. The barrier is 
super low and even if you had nothing but the textual output of `nm` you could 
create one of these JSON files and symbolicate your binary in LLDB.

> Any idea on where the JSON file will live if it is just a companion file for 
> another mach-o or ELF executable? Will it always be next to the mach-o 
> executable? Will we enable a Spotlight importer to find it like we do for 
> dSYM files?

For now I have no plans to have LLDB pick these files up automatically, but 
that's definitely something we could explore in the future.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D145180/new/

https://reviews.llvm.org/D145180

___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D145241: [lldb][TypeSystemClang] Format pointers to member functions as eFormatHex

2023-03-03 Thread Michael Buch via Phabricator via lldb-commits
Michael137 added a comment.

Looks like this is causing windows tests to fail: 
https://lab.llvm.org/buildbot#builders/219/builds/1013

Investigating...


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D145241/new/

https://reviews.llvm.org/D145241

___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D145260: [lldb/swig] Fix ref counting issue in SBProcess::GetScriptedImplementation

2023-03-03 Thread Med Ismail Bennani via Phabricator via lldb-commits
mib created this revision.
mib added reviewers: bulbazord, JDevlieghere.
mib added a project: LLDB.
Herald added a project: All.
mib requested review of this revision.
Herald added a subscriber: lldb-commits.

When using SBProcess::GetScriptedImplementation in python, if the
process has a valid implementation, we returned a reference of the
object without incrementing the reference counting. That causes the
interpreter to crash after accessing the reference several times.

This patch address this by incrementing the reference count when passing
the valid object reference.

Signed-off-by: Med Ismail Bennani 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D145260

Files:
  lldb/bindings/python/python-typemaps.swig


Index: lldb/bindings/python/python-typemaps.swig
===
--- lldb/bindings/python/python-typemaps.swig
+++ lldb/bindings/python/python-typemaps.swig
@@ -61,6 +61,8 @@
   if (!$result) {
 $result = Py_None;
 Py_INCREF(Py_None);
+  } else {
+Py_INCREF($result);
   }
 }
 


Index: lldb/bindings/python/python-typemaps.swig
===
--- lldb/bindings/python/python-typemaps.swig
+++ lldb/bindings/python/python-typemaps.swig
@@ -61,6 +61,8 @@
   if (!$result) {
 $result = Py_None;
 Py_INCREF(Py_None);
+  } else {
+Py_INCREF($result);
   }
 }
 
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D145260: [lldb/swig] Fix ref counting issue in SBProcess::GetScriptedImplementation

2023-03-03 Thread Jonas Devlieghere via Phabricator via lldb-commits
JDevlieghere accepted this revision.
JDevlieghere added a comment.
This revision is now accepted and ready to land.

LGTM. Can we turn that crash into a small test case?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D145260/new/

https://reviews.llvm.org/D145260

___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D145260: [lldb/swig] Fix ref counting issue in SBProcess::GetScriptedImplementation

2023-03-03 Thread Med Ismail Bennani via Phabricator via lldb-commits
mib updated this revision to Diff 50.
mib added a comment.

Add test


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D145260/new/

https://reviews.llvm.org/D145260

Files:
  lldb/bindings/python/python-typemaps.swig
  lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py


Index: lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
===
--- lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
+++ lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
@@ -80,6 +80,15 @@
 self.assertEqual(process.GetProcessID(), 666)
 self.assertEqual(process.GetNumThreads(), 0)
 
+impl = process.GetScriptedImplementation()
+self.assertTrue(impl)
+impl = process.GetScriptedImplementation()
+self.assertTrue(impl)
+impl = process.GetScriptedImplementation()
+self.assertTrue(impl)
+impl = process.GetScriptedImplementation()
+self.assertTrue(impl)
+
 addr = 0x5
 buff = process.ReadMemory(addr, 4, error)
 self.assertEqual(buff, None)
Index: lldb/bindings/python/python-typemaps.swig
===
--- lldb/bindings/python/python-typemaps.swig
+++ lldb/bindings/python/python-typemaps.swig
@@ -61,6 +61,8 @@
   if (!$result) {
 $result = Py_None;
 Py_INCREF(Py_None);
+  } else {
+Py_INCREF($result);
   }
 }
 


Index: lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
===
--- lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
+++ lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
@@ -80,6 +80,15 @@
 self.assertEqual(process.GetProcessID(), 666)
 self.assertEqual(process.GetNumThreads(), 0)
 
+impl = process.GetScriptedImplementation()
+self.assertTrue(impl)
+impl = process.GetScriptedImplementation()
+self.assertTrue(impl)
+impl = process.GetScriptedImplementation()
+self.assertTrue(impl)
+impl = process.GetScriptedImplementation()
+self.assertTrue(impl)
+
 addr = 0x5
 buff = process.ReadMemory(addr, 4, error)
 self.assertEqual(buff, None)
Index: lldb/bindings/python/python-typemaps.swig
===
--- lldb/bindings/python/python-typemaps.swig
+++ lldb/bindings/python/python-typemaps.swig
@@ -61,6 +61,8 @@
   if (!$result) {
 $result = Py_None;
 Py_INCREF(Py_None);
+  } else {
+Py_INCREF($result);
   }
 }
 
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] 96e39fd - [lldb][test] NativePDB/ast-types: fix expected pointer format

2023-03-03 Thread Michael Buch via lldb-commits

Author: Michael Buch
Date: 2023-03-03T21:41:18Z
New Revision: 96e39fdbb90b26191fc79b6226f299e3c10e559b

URL: 
https://github.com/llvm/llvm-project/commit/96e39fdbb90b26191fc79b6226f299e3c10e559b
DIFF: 
https://github.com/llvm/llvm-project/commit/96e39fdbb90b26191fc79b6226f299e3c10e559b.diff

LOG: [lldb][test] NativePDB/ast-types: fix expected pointer format

Format changed in `b642fd5ee250247ccefb38099169b4ee8ac4112b`

Differential Revision: https://reviews.llvm.org/D145241

Added: 


Modified: 
lldb/test/Shell/SymbolFile/NativePDB/ast-types.cpp

Removed: 




diff  --git a/lldb/test/Shell/SymbolFile/NativePDB/ast-types.cpp 
b/lldb/test/Shell/SymbolFile/NativePDB/ast-types.cpp
index a210ce0451047..5554881716184 100644
--- a/lldb/test/Shell/SymbolFile/NativePDB/ast-types.cpp
+++ b/lldb/test/Shell/SymbolFile/NativePDB/ast-types.cpp
@@ -131,15 +131,15 @@ int SI::*mp9 = nullptr;
 // CHECK: (Anonymous) AnonInt = (AnonymousMember = 0)
 // CHECK: (Anonymous>) AnonABCVoid = (AnonymousMember = 0)
 // CHECK: (Anonymous>::D) AnonABCVoidD = (AnonymousDMember = 0)
-// CHECK: (void (SI::*)()) mp1 = 00 00 00 00 00 00 00 00
-// CHECK: (void (MI::*)()) mp2 = 00 00 00 00 00 00 00 00
-// CHECK: (void (MI2::*)()) mp3 = 00 00 00 00 00 00 00 00
-// CHECK: (void (VI::*)()) mp4 = 00 00 00 00 00 00 00 00
-// CHECK: (void (VI2::*)()) mp5 = 00 00 00 00 00 00 00 00
-// CHECK: (void (UI::*)()) mp6 = 00 00 00 00 00 00 00 00
+// CHECK: (void (SI::*)()) mp1 = 0x
+// CHECK: (void (MI::*)()) mp2 = 0x
+// CHECK: (void (MI2::*)()) mp3 = 0x
+// CHECK: (void (VI::*)()) mp4 = 0x
+// CHECK: (void (VI2::*)()) mp5 = 0x
+// CHECK: (void (UI::*)()) mp6 = 0x
 // CHECK: (void (MI::**)()) mp7 = 0x
 // CHECK: (void (VI2::**)()) mp8 = 0x
-// CHECK: (int SI::*) mp9 = ff ff ff ff
+// CHECK: (int SI::*) mp9 = 0x
 // CHECK: Dumping clang ast for 1 modules.
 // CHECK: TranslationUnitDecl {{.*}}
 // CHECK: |-CXXRecordDecl {{.*}} class TrivialC definition



___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D139945: [lldb] Add scripted process launch/attach option to platform commands

2023-03-03 Thread Med Ismail Bennani via Phabricator via lldb-commits
mib updated this revision to Diff 502259.
mib added a comment.

Fix build failures after rebase


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D139945/new/

https://reviews.llvm.org/D139945

Files:
  lldb/include/lldb/API/SBAttachInfo.h
  lldb/include/lldb/API/SBStructuredData.h
  lldb/include/lldb/Target/Process.h
  lldb/source/API/SBAttachInfo.cpp
  lldb/source/Commands/CMakeLists.txt
  lldb/source/Commands/CommandObjectPlatform.cpp
  lldb/source/Commands/CommandObjectProcess.cpp
  lldb/source/Commands/CommandOptionsProcessAttach.cpp
  lldb/source/Commands/CommandOptionsProcessAttach.h

Index: lldb/source/Commands/CommandOptionsProcessAttach.h
===
--- /dev/null
+++ lldb/source/Commands/CommandOptionsProcessAttach.h
@@ -0,0 +1,47 @@
+//===-- CommandOptionsProcessAttach.h ---*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLDB_SOURCE_COMMANDS_COMMANDOPTIONSPROCESSATTACH_H
+#define LLDB_SOURCE_COMMANDS_COMMANDOPTIONSPROCESSATTACH_H
+
+#include "lldb/Interpreter/Options.h"
+#include "lldb/Target/Process.h"
+
+namespace lldb_private {
+
+// CommandOptionsProcessAttach
+
+class CommandOptionsProcessAttach : public lldb_private::OptionGroup {
+public:
+  CommandOptionsProcessAttach() {
+// Keep default values of all options in one place: OptionParsingStarting
+// ()
+OptionParsingStarting(nullptr);
+  }
+
+  ~CommandOptionsProcessAttach() override = default;
+
+  lldb_private::Status
+  SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
+ lldb_private::ExecutionContext *execution_context) override;
+
+  void OptionParsingStarting(
+  lldb_private::ExecutionContext *execution_context) override {
+attach_info.Clear();
+  }
+
+  llvm::ArrayRef GetDefinitions() override;
+
+  // Instance variables to hold the values for command options.
+
+  lldb_private::ProcessAttachInfo attach_info;
+}; // CommandOptionsProcessAttach
+
+} // namespace lldb_private
+
+#endif // LLDB_SOURCE_COMMANDS_COMMANDOPTIONSPROCESSATTACH_H
Index: lldb/source/Commands/CommandOptionsProcessAttach.cpp
===
--- /dev/null
+++ lldb/source/Commands/CommandOptionsProcessAttach.cpp
@@ -0,0 +1,76 @@
+//===-- CommandOptionsProcessAttach.cpp ---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "CommandOptionsProcessAttach.h"
+
+#include "lldb/Host/FileSystem.h"
+#include "lldb/Host/HostInfo.h"
+#include "lldb/Host/OptionParser.h"
+#include "lldb/Interpreter/CommandCompletions.h"
+#include "lldb/Interpreter/CommandObject.h"
+#include "lldb/Interpreter/CommandOptionArgumentTable.h"
+#include "lldb/Interpreter/OptionArgParser.h"
+#include "lldb/Target/ExecutionContext.h"
+#include "lldb/Target/Platform.h"
+#include "lldb/Target/Target.h"
+
+#include "llvm/ADT/ArrayRef.h"
+
+using namespace llvm;
+using namespace lldb;
+using namespace lldb_private;
+
+#define LLDB_OPTIONS_process_attach
+#include "CommandOptions.inc"
+
+Status CommandOptionsProcessAttach::SetOptionValue(
+uint32_t option_idx, llvm::StringRef option_arg,
+ExecutionContext *execution_context) {
+  Status error;
+  const int short_option = g_process_attach_options[option_idx].short_option;
+  switch (short_option) {
+  case 'c':
+attach_info.SetContinueOnceAttached(true);
+break;
+
+  case 'p': {
+lldb::pid_t pid;
+if (option_arg.getAsInteger(0, pid)) {
+  error.SetErrorStringWithFormat("invalid process ID '%s'",
+ option_arg.str().c_str());
+} else {
+  attach_info.SetProcessID(pid);
+}
+  } break;
+
+  case 'P':
+attach_info.SetProcessPluginName(option_arg);
+break;
+
+  case 'n':
+attach_info.GetExecutableFile().SetFile(option_arg,
+FileSpec::Style::native);
+break;
+
+  case 'w':
+attach_info.SetWaitForLaunch(true);
+break;
+
+  case 'i':
+attach_info.SetIgnoreExisting(false);
+break;
+
+  default:
+llvm_unreachable("Unimplemented option");
+  }
+  return error;
+}
+
+llvm::ArrayRef CommandOptionsProcessAttach::GetDefinitions() {
+  return llvm::makeArrayRef(g_process_attach_options);
+}
Index: lldb/source/Commands/CommandObjectProcess.cpp
===
--- lldb/source/Commands/CommandObjectProcess.cpp
+++ lldb/source/Comm

[Lldb-commits] [PATCH] D143104: [lldb/Plugins] Add Attach capabilities to ScriptedProcess

2023-03-03 Thread Med Ismail Bennani via Phabricator via lldb-commits
mib updated this revision to Diff 502265.
mib edited the summary of this revision.
mib added a comment.

- Address @bulbazord comment about only being able to assign the Scripted 
Metadata attributes once.
- Add necessary SWIG wrappers to convert the internal type into SB counterpart 
and back.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D143104/new/

https://reviews.llvm.org/D143104

Files:
  lldb/bindings/python/python-swigsafecast.swig
  lldb/bindings/python/python-wrapper.swig
  lldb/examples/python/scripted_process/scripted_process.py
  lldb/include/lldb/API/SBAttachInfo.h
  lldb/include/lldb/API/SBLaunchInfo.h
  lldb/include/lldb/Host/ProcessLaunchInfo.h
  lldb/include/lldb/Interpreter/ScriptInterpreter.h
  lldb/include/lldb/Interpreter/ScriptedMetadata.h
  lldb/include/lldb/Interpreter/ScriptedProcessInterface.h
  lldb/include/lldb/Target/Process.h
  lldb/include/lldb/Target/Target.h
  lldb/include/lldb/Utility/ProcessInfo.h
  lldb/include/lldb/lldb-forward.h
  lldb/source/API/SBAttachInfo.cpp
  lldb/source/API/SBLaunchInfo.cpp
  lldb/source/API/SBTarget.cpp
  lldb/source/Commands/CommandObjectPlatform.cpp
  lldb/source/Commands/CommandObjectProcess.cpp
  lldb/source/Host/common/ProcessLaunchInfo.cpp
  lldb/source/Interpreter/ScriptInterpreter.cpp
  lldb/source/Plugins/Process/scripted/ScriptedProcess.cpp
  lldb/source/Plugins/Process/scripted/ScriptedProcess.h
  lldb/source/Plugins/ScriptInterpreter/Python/SWIGPythonBridge.h
  
lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.cpp
  lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.h
  lldb/source/Plugins/ScriptInterpreter/Python/ScriptedPythonInterface.cpp
  lldb/source/Plugins/ScriptInterpreter/Python/ScriptedPythonInterface.h
  lldb/source/Target/Target.cpp
  lldb/source/Utility/ProcessInfo.cpp
  lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
  lldb/unittests/ScriptInterpreter/Python/PythonTestSuite.cpp

Index: lldb/unittests/ScriptInterpreter/Python/PythonTestSuite.cpp
===
--- lldb/unittests/ScriptInterpreter/Python/PythonTestSuite.cpp
+++ lldb/unittests/ScriptInterpreter/Python/PythonTestSuite.cpp
@@ -139,6 +139,14 @@
   return nullptr;
 }
 
+void *lldb_private::LLDBSWIGPython_CastPyObjectToSBAttachInfo(PyObject *data) {
+  return nullptr;
+}
+
+void *lldb_private::LLDBSWIGPython_CastPyObjectToSBLaunchInfo(PyObject *data) {
+  return nullptr;
+}
+
 void *lldb_private::LLDBSWIGPython_CastPyObjectToSBError(PyObject *data) {
   return nullptr;
 }
Index: lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
===
--- lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
+++ lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
@@ -137,8 +137,14 @@
 
 target_1 = self.dbg.CreateTarget(self.getBuildArtifact("a.out"))
 self.assertTrue(target_1, VALID_TARGET)
+
+# We still need to specify a PID when attaching even for scripted processes
+attach_info = lldb.SBAttachInfo(42)
+attach_info.SetProcessPluginName("ScriptedProcess")
+attach_info.SetScriptedProcessClassName("dummy_scripted_process.DummyScriptedProcess")
+
 error = lldb.SBError()
-process_1 = target_1.Launch(launch_info, error)
+process_1 = target_1.Attach(attach_info, error)
 self.assertTrue(process_1 and process_1.IsValid(), PROCESS_IS_VALID)
 self.assertEqual(process_1.GetProcessID(), 42)
 self.assertEqual(process_1.GetNumThreads(), 1)
Index: lldb/source/Utility/ProcessInfo.cpp
===
--- lldb/source/Utility/ProcessInfo.cpp
+++ lldb/source/Utility/ProcessInfo.cpp
@@ -8,6 +8,7 @@
 
 #include "lldb/Utility/ProcessInfo.h"
 
+#include "lldb/Interpreter/ScriptedMetadata.h"
 #include "lldb/Utility/ArchSpec.h"
 #include "lldb/Utility/Stream.h"
 #include "lldb/Utility/StreamString.h"
@@ -36,6 +37,7 @@
   m_gid = UINT32_MAX;
   m_arch.Clear();
   m_pid = LLDB_INVALID_PROCESS_ID;
+  m_scripted_metadata_sp.reset();
 }
 
 const char *ProcessInfo::GetName() const {
@@ -109,6 +111,10 @@
   }
 }
 
+bool ProcessInfo::IsScriptedProcess() const {
+  return m_scripted_metadata_sp && *m_scripted_metadata_sp;
+}
+
 void ProcessInstanceInfo::Dump(Stream &s, UserIDResolver &resolver) const {
   if (m_pid != LLDB_INVALID_PROCESS_ID)
 s.Printf("pid = %" PRIu64 "\n", m_pid);
Index: lldb/source/Target/Target.cpp
===
--- lldb/source/Target/Target.cpp
+++ lldb/source/Target/Target.cpp
@@ -3079,6 +3079,17 @@
 
 void Target::ClearAllLoadedSections() { m_section_load_history.Clear(); }
 
+void Target::SaveScriptedLaunchInfo(lldb_private::ProcessInfo &process_info) {
+  if (process_info.IsScriptedProcess()) {
+// Only copy scripted process l

[Lldb-commits] [PATCH] D143104: [lldb/Plugins] Add Attach capabilities to ScriptedProcess

2023-03-03 Thread Alex Langford via Phabricator via lldb-commits
bulbazord added a comment.

I still think it's a little weird that you can create LaunchInfo or AttachInfo, 
call SetScriptedProcessDictionary, and still have the ScriptedMetadata be 
"invalid", but I suppose it makes no sense if there is no class name anyway.

Just a few small things. Everything else looks fine to me.




Comment at: lldb/source/API/SBAttachInfo.cpp:272
 void SBAttachInfo::SetScriptedProcessClassName(const char *class_name) {
   LLDB_INSTRUMENT_VA(this, class_name);
+  ScriptedMetadataSP metadata_sp = m_opaque_sp->GetScriptedMetadata();

Add a new line after the instrument macro



Comment at: lldb/source/Plugins/Process/scripted/ScriptedProcess.cpp:203-208
+  SetPrivateState(eStateRunning);
+
+  if (error.Fail())
+return error;
+
+  SetPrivateState(eStateStopped);

mib wrote:
> bulbazord wrote:
> > I'm not sure I understand what the point of setting the state to `Running` 
> > is and only setting it to `Stopped` if the attach failed? Should we be 
> > mucking with state at all if the attach failed?
> I guess we can do it subsequently
I'm not sure this was addressed and maybe I don't understand something but why 
do we check to see if the error failed only after setting the state to running? 
If we actually did fail to attach, does it make sense to think of the 
ScriptedProcess as "running"?


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D143104/new/

https://reviews.llvm.org/D143104

___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D143104: [lldb/Plugins] Add Attach capabilities to ScriptedProcess

2023-03-03 Thread Med Ismail Bennani via Phabricator via lldb-commits
mib updated this revision to Diff 502270.
mib added a comment.

- Address last feedbacks
- Fix unittest


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D143104/new/

https://reviews.llvm.org/D143104

Files:
  lldb/bindings/python/python-swigsafecast.swig
  lldb/bindings/python/python-wrapper.swig
  lldb/examples/python/scripted_process/scripted_process.py
  lldb/include/lldb/API/SBAttachInfo.h
  lldb/include/lldb/API/SBLaunchInfo.h
  lldb/include/lldb/Host/ProcessLaunchInfo.h
  lldb/include/lldb/Interpreter/ScriptInterpreter.h
  lldb/include/lldb/Interpreter/ScriptedMetadata.h
  lldb/include/lldb/Interpreter/ScriptedProcessInterface.h
  lldb/include/lldb/Target/Process.h
  lldb/include/lldb/Target/Target.h
  lldb/include/lldb/Utility/ProcessInfo.h
  lldb/include/lldb/lldb-forward.h
  lldb/source/API/SBAttachInfo.cpp
  lldb/source/API/SBLaunchInfo.cpp
  lldb/source/API/SBTarget.cpp
  lldb/source/Commands/CommandObjectPlatform.cpp
  lldb/source/Commands/CommandObjectProcess.cpp
  lldb/source/Host/common/ProcessLaunchInfo.cpp
  lldb/source/Interpreter/ScriptInterpreter.cpp
  lldb/source/Plugins/Process/scripted/ScriptedProcess.cpp
  lldb/source/Plugins/Process/scripted/ScriptedProcess.h
  lldb/source/Plugins/ScriptInterpreter/Python/SWIGPythonBridge.h
  
lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.cpp
  lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.h
  lldb/source/Plugins/ScriptInterpreter/Python/ScriptedPythonInterface.cpp
  lldb/source/Plugins/ScriptInterpreter/Python/ScriptedPythonInterface.h
  lldb/source/Target/Target.cpp
  lldb/source/Utility/ProcessInfo.cpp
  lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
  lldb/unittests/ScriptInterpreter/Python/PythonTestSuite.cpp

Index: lldb/unittests/ScriptInterpreter/Python/PythonTestSuite.cpp
===
--- lldb/unittests/ScriptInterpreter/Python/PythonTestSuite.cpp
+++ lldb/unittests/ScriptInterpreter/Python/PythonTestSuite.cpp
@@ -139,6 +139,14 @@
   return nullptr;
 }
 
+void *lldb_private::LLDBSWIGPython_CastPyObjectToSBAttachInfo(PyObject *data) {
+  return nullptr;
+}
+
+void *lldb_private::LLDBSWIGPython_CastPyObjectToSBLaunchInfo(PyObject *data) {
+  return nullptr;
+}
+
 void *lldb_private::LLDBSWIGPython_CastPyObjectToSBError(PyObject *data) {
   return nullptr;
 }
@@ -268,3 +276,13 @@
 python::PythonObject lldb_private::python::ToSWIGWrapper(const Status &status) {
   return python::PythonObject();
 }
+
+python::PythonObject
+lldb_private::python::ToSWIGWrapper(lldb::ProcessAttachInfoSP) {
+  return python::PythonObject();
+}
+
+python::PythonObject
+lldb_private::python::ToSWIGWrapper(lldb::ProcessLaunchInfoSP) {
+  return python::PythonObject();
+}
Index: lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
===
--- lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
+++ lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
@@ -137,8 +137,14 @@
 
 target_1 = self.dbg.CreateTarget(self.getBuildArtifact("a.out"))
 self.assertTrue(target_1, VALID_TARGET)
+
+# We still need to specify a PID when attaching even for scripted processes
+attach_info = lldb.SBAttachInfo(42)
+attach_info.SetProcessPluginName("ScriptedProcess")
+attach_info.SetScriptedProcessClassName("dummy_scripted_process.DummyScriptedProcess")
+
 error = lldb.SBError()
-process_1 = target_1.Launch(launch_info, error)
+process_1 = target_1.Attach(attach_info, error)
 self.assertTrue(process_1 and process_1.IsValid(), PROCESS_IS_VALID)
 self.assertEqual(process_1.GetProcessID(), 42)
 self.assertEqual(process_1.GetNumThreads(), 1)
Index: lldb/source/Utility/ProcessInfo.cpp
===
--- lldb/source/Utility/ProcessInfo.cpp
+++ lldb/source/Utility/ProcessInfo.cpp
@@ -8,6 +8,7 @@
 
 #include "lldb/Utility/ProcessInfo.h"
 
+#include "lldb/Interpreter/ScriptedMetadata.h"
 #include "lldb/Utility/ArchSpec.h"
 #include "lldb/Utility/Stream.h"
 #include "lldb/Utility/StreamString.h"
@@ -36,6 +37,7 @@
   m_gid = UINT32_MAX;
   m_arch.Clear();
   m_pid = LLDB_INVALID_PROCESS_ID;
+  m_scripted_metadata_sp.reset();
 }
 
 const char *ProcessInfo::GetName() const {
@@ -109,6 +111,10 @@
   }
 }
 
+bool ProcessInfo::IsScriptedProcess() const {
+  return m_scripted_metadata_sp && *m_scripted_metadata_sp;
+}
+
 void ProcessInstanceInfo::Dump(Stream &s, UserIDResolver &resolver) const {
   if (m_pid != LLDB_INVALID_PROCESS_ID)
 s.Printf("pid = %" PRIu64 "\n", m_pid);
Index: lldb/source/Target/Target.cpp
===
--- lldb/source/Target/Target.cpp
+++ lldb/source/Target/Target.cpp
@@ -3079,6 +3079,17 @@
 
 void Target::ClearAllLoadedSectio

[Lldb-commits] [PATCH] D139945: [lldb] Add scripted process launch/attach option to {, platform }process commands

2023-03-03 Thread Jonas Devlieghere via Phabricator via lldb-commits
JDevlieghere accepted this revision.
JDevlieghere added a comment.
This revision is now accepted and ready to land.

LGTM modulo inline comments.




Comment at: lldb/include/lldb/Target/Process.h:235-239
+  std::string m_scripted_process_class_name; // The name of the class that will
+ // manage a scripted process.
+  StructuredData::DictionarySP
+  m_scripted_process_dictionary_sp; // A dictionary that holds key/value
+// pairs passed to the scripted 
process.

I know you're just doing this for consistency but please use Doxygen style 
comments `///` on the line before. Bonus points if you fix the ones above as 
well.



Comment at: lldb/source/Commands/CommandOptionsProcessAttach.h:17
+
+// CommandOptionsProcessAttach
+

Let's stop cargo culting these frankly useless comments.



Comment at: lldb/source/Commands/CommandOptionsProcessAttach.h:40
+
+  // Instance variables to hold the values for command options.
+

Remove



Comment at: lldb/source/Commands/CommandOptionsProcessAttach.h:43
+  lldb_private::ProcessAttachInfo attach_info;
+}; // CommandOptionsProcessAttach
+




CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D139945/new/

https://reviews.llvm.org/D139945

___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D143104: [lldb/Plugins] Add Attach capabilities to ScriptedProcess

2023-03-03 Thread Jonas Devlieghere via Phabricator via lldb-commits
JDevlieghere accepted this revision.
JDevlieghere added a comment.
This revision is now accepted and ready to land.

LGTM


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D143104/new/

https://reviews.llvm.org/D143104

___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D144237: [lldb/Plugins] Add memory writing capabilities to Scripted Process

2023-03-03 Thread Med Ismail Bennani via Phabricator via lldb-commits
mib updated this revision to Diff 502319.
mib added a comment.

Rebase


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D144237/new/

https://reviews.llvm.org/D144237

Files:
  lldb/bindings/python/python-swigsafecast.swig
  lldb/examples/python/scripted_process/scripted_process.py
  lldb/include/lldb/Interpreter/ScriptedProcessInterface.h
  lldb/source/Plugins/Process/scripted/ScriptedProcess.cpp
  lldb/source/Plugins/Process/scripted/ScriptedProcess.h
  lldb/source/Plugins/ScriptInterpreter/Python/SWIGPythonBridge.h
  
lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.cpp
  lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.h
  lldb/source/Plugins/ScriptInterpreter/Python/ScriptedPythonInterface.h
  lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
  lldb/test/API/functionalities/scripted_process/dummy_scripted_process.py
  lldb/unittests/ScriptInterpreter/Python/PythonTestSuite.cpp

Index: lldb/unittests/ScriptInterpreter/Python/PythonTestSuite.cpp
===
--- lldb/unittests/ScriptInterpreter/Python/PythonTestSuite.cpp
+++ lldb/unittests/ScriptInterpreter/Python/PythonTestSuite.cpp
@@ -286,3 +286,8 @@
 lldb_private::python::ToSWIGWrapper(lldb::ProcessLaunchInfoSP) {
   return python::PythonObject();
 }
+
+python::PythonObject
+lldb_private::python::ToSWIGWrapper(lldb::DataExtractorSP) {
+  return python::PythonObject();
+}
Index: lldb/test/API/functionalities/scripted_process/dummy_scripted_process.py
===
--- lldb/test/API/functionalities/scripted_process/dummy_scripted_process.py
+++ lldb/test/API/functionalities/scripted_process/dummy_scripted_process.py
@@ -7,20 +7,29 @@
 from lldb.plugins.scripted_process import ScriptedThread
 
 class DummyScriptedProcess(ScriptedProcess):
+memory = None
+
 def __init__(self, exe_ctx: lldb.SBExecutionContext, args : lldb.SBStructuredData):
 super().__init__(exe_ctx, args)
 self.threads[0] = DummyScriptedThread(self, None)
-
-def read_memory_at_address(self, addr: int, size: int, error: lldb.SBError) -> lldb.SBData:
+self.memory = {}
+addr = 0x5
 debugger = self.target.GetDebugger()
 index = debugger.GetIndexOfTarget(self.target)
+self.memory[addr] = "Hello, target " + str(index)
+
+def read_memory_at_address(self, addr: int, size: int, error: lldb.SBError) -> lldb.SBData:
 data = lldb.SBData().CreateDataFromCString(
 self.target.GetByteOrder(),
 self.target.GetCodeByteSize(),
-"Hello, target " + str(index))
+self.memory[addr])
 
 return data
 
+def write_memory_at_address(self, addr, data, error):
+self.memory[addr] = data.GetString(error, 0)
+return len(self.memory[addr])
+
 def get_loaded_images(self):
 return self.loaded_images
 
Index: lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
===
--- lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
+++ lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
@@ -150,7 +150,6 @@
 self.assertEqual(process_1.GetNumThreads(), 1)
 
 # ... then try reading from target #1 process ...
-addr = 0x5
 message = "Hello, target 1"
 buff = process_1.ReadCStringFromMemory(addr, len(message) + 1, error)
 self.assertSuccess(error)
@@ -158,12 +157,22 @@
 
 # ... now, reading again from target #0 process to make sure the call
 # gets dispatched to the right target.
-addr = 0x5
 message = "Hello, target 0"
 buff = process_0.ReadCStringFromMemory(addr, len(message) + 1, error)
 self.assertSuccess(error)
 self.assertEqual(buff, message)
 
+# Let's write some memory.
+message = "Hello, world!"
+bytes_written = process_0.WriteCStringToMemory(addr, message, error)
+self.assertSuccess(error)
+self.assertEqual(bytes_written, len(message) + 1)
+
+# ... and check if that memory was saved properly.
+buff = process_0.ReadCStringFromMemory(addr, len(message) + 1, error)
+self.assertSuccess(error)
+self.assertEqual(buff, message)
+
 thread = process_0.GetSelectedThread()
 self.assertTrue(thread, "Invalid thread.")
 self.assertEqual(thread.GetThreadID(), 0x19)
Index: lldb/source/Plugins/ScriptInterpreter/Python/ScriptedPythonInterface.h
===
--- lldb/source/Plugins/ScriptInterpreter/Python/ScriptedPythonInterface.h
+++ lldb/source/Plugins/ScriptInterpreter/Python/ScriptedPythonInterface.h
@@ -125,6 +

[Lldb-commits] [PATCH] D145180: [lldb] Introduce new SymbolFileJSON and ObjectFileJSON

2023-03-03 Thread Jonas Devlieghere via Phabricator via lldb-commits
JDevlieghere updated this revision to Diff 502330.
JDevlieghere marked 3 inline comments as done.
JDevlieghere added a comment.

Address Greg's feedback


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D145180/new/

https://reviews.llvm.org/D145180

Files:
  lldb/include/lldb/Symbol/Symbol.h
  lldb/source/Plugins/ObjectFile/CMakeLists.txt
  lldb/source/Plugins/ObjectFile/JSON/CMakeLists.txt
  lldb/source/Plugins/ObjectFile/JSON/ObjectFileJSON.cpp
  lldb/source/Plugins/ObjectFile/JSON/ObjectFileJSON.h
  lldb/source/Plugins/SymbolFile/CMakeLists.txt
  lldb/source/Plugins/SymbolFile/JSON/CMakeLists.txt
  lldb/source/Plugins/SymbolFile/JSON/SymbolFileJSON.cpp
  lldb/source/Plugins/SymbolFile/JSON/SymbolFileJSON.h
  lldb/source/Symbol/Symbol.cpp
  lldb/test/API/macosx/symbols/Makefile
  lldb/test/API/macosx/symbols/TestSymbolFileJSON.py
  lldb/test/API/macosx/symbols/main.c

Index: lldb/test/API/macosx/symbols/main.c
===
--- /dev/null
+++ lldb/test/API/macosx/symbols/main.c
@@ -0,0 +1,2 @@
+int foo() { return 1; }
+int main() { return foo(); }
Index: lldb/test/API/macosx/symbols/TestSymbolFileJSON.py
===
--- /dev/null
+++ lldb/test/API/macosx/symbols/TestSymbolFileJSON.py
@@ -0,0 +1,82 @@
+""" Testing symbol loading via JSON file. """
+import lldb
+from lldbsuite.test.decorators import *
+from lldbsuite.test.lldbtest import *
+from lldbsuite.test import lldbutil
+
+
+class TargetSymbolsFileJSON(TestBase):
+
+def setUp(self):
+TestBase.setUp(self)
+self.source = 'main.c'
+
+@no_debug_info_test  # Prevent the genaration of the dwarf version of this test
+def test_symbol_file_json(self):
+"""Test that 'target symbols add' can load the symbols from a JSON file."""
+
+self.build()
+stripped = self.getBuildArtifact("stripped.out")
+unstripped = self.getBuildArtifact("a.out")
+
+# Create a JSON symbol file from the unstripped target.
+unstripped_target = self.dbg.CreateTarget(unstripped)
+self.assertTrue(unstripped_target, VALID_TARGET)
+
+unstripped_module = unstripped_target.GetModuleAtIndex(0)
+main_symbol = unstripped_module.FindSymbol("main")
+foo_symbol = unstripped_module.FindSymbol("foo")
+
+data = {
+"triple": unstripped_module.GetTriple(),
+"uuid": unstripped_module.GetUUIDString(),
+"symbols": list()
+}
+data['symbols'].append({
+"name": "main",
+"type": "code",
+"size": main_symbol.GetSize(),
+"value": main_symbol.addr.GetFileAddress(),
+})
+data['symbols'].append({
+"name": "foo",
+"type": "code",
+"size": foo_symbol.GetSize(),
+"value": foo_symbol.addr.GetFileAddress(),
+})
+
+json_object = json.dumps(data, indent=4)
+json_symbol_file = self.getBuildArtifact("a.json")
+with open(json_symbol_file, "w") as outfile:
+outfile.write(json_object)
+
+# Create a stripped target.
+stripped_target = self.dbg.CreateTarget(stripped)
+self.assertTrue(stripped_target, VALID_TARGET)
+
+# Ensure there's no symbol for main and foo.
+stripped_module = stripped_target.GetModuleAtIndex(0)
+self.assertFalse(stripped_module.FindSymbol("main").IsValid())
+self.assertFalse(stripped_module.FindSymbol("foo").IsValid())
+
+main_bp = stripped_target.BreakpointCreateByName(
+"main", "stripped.out")
+self.assertTrue(main_bp, VALID_BREAKPOINT)
+self.assertEqual(main_bp.num_locations, 0)
+
+# Load the JSON symbol file.
+self.runCmd("target symbols add -s %s %s" %
+(stripped, self.getBuildArtifact("a.json")))
+
+# Ensure main and foo are available now.
+self.assertTrue(stripped_module.FindSymbol("main").IsValid())
+self.assertTrue(stripped_module.FindSymbol("foo").IsValid())
+self.assertEqual(main_bp.num_locations, 1)
+
+# Ensure the file address matches between the stripped and unstripped target.
+self.assertEqual(
+stripped_module.FindSymbol("main").addr.GetFileAddress(),
+unstripped_module.FindSymbol("main").addr.GetFileAddress())
+self.assertEqual(
+stripped_module.FindSymbol("foo").addr.GetFileAddress(),
+unstripped_module.FindSymbol("foo").addr.GetFileAddress())
Index: lldb/test/API/macosx/symbols/Makefile
===
--- /dev/null
+++ lldb/test/API/macosx/symbols/Makefile
@@ -0,0 +1,8 @@
+C_SOURCES := main.c
+
+all: stripped.out
+
+stripped.out : a.out
+	strip a.out -o stripped.out
+
+include Makefile.rules
Index: lldb/source/Symbol/Symbol.cpp
===

[Lldb-commits] [PATCH] D144224: [lldb] Extend SWIG SBProcess interface with WriteMemoryAsCString method

2023-03-03 Thread Med Ismail Bennani via Phabricator via lldb-commits
mib updated this revision to Diff 502332.
mib added a comment.

Handle empty string case and add tests


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D144224/new/

https://reviews.llvm.org/D144224

Files:
  lldb/bindings/interface/SBProcessExtensions.i
  lldb/test/API/python_api/process/TestProcessAPI.py


Index: lldb/test/API/python_api/process/TestProcessAPI.py
===
--- lldb/test/API/python_api/process/TestProcessAPI.py
+++ lldb/test/API/python_api/process/TestProcessAPI.py
@@ -186,6 +186,32 @@
 exe=False,
 startstr=b'a')
 
+# Get the SBValue for the global variable 'my_cstring'.
+val = frame.FindValue("my_cstring", lldb.eValueTypeVariableGlobal)
+self.DebugSBValue(val)
+
+addr = val.AddressOf().GetValueAsUnsigned()
+
+# Write an empty string to memory
+bytes_written = process.WriteMemoryAsCString(addr, "", error)
+self.assertEqual(bytes_written, 0)
+if not error.Success():
+self.fail("SBProcess.WriteMemoryAsCString() failed")
+
+message = "Hello!"
+bytes_written = process.WriteMemoryAsCString(addr, message, error)
+self.assertEqual(bytes_written, len(message) + 1)
+if not error.Success():
+self.fail("SBProcess.WriteMemoryAsCString() failed")
+
+cstring = process.ReadCStringFromMemory(
+val.AddressOf().GetValueAsUnsigned(), 256, error)
+if not error.Success():
+self.fail("SBProcess.ReadCStringFromMemory() failed")
+
+self.assertEqual(cstring, message)
+
+
 def test_access_my_int(self):
 """Test access 'my_int' using Python SBProcess.GetByteOrder() and 
other APIs."""
 self.build()
Index: lldb/bindings/interface/SBProcessExtensions.i
===
--- lldb/bindings/interface/SBProcessExtensions.i
+++ lldb/bindings/interface/SBProcessExtensions.i
@@ -2,6 +2,18 @@
 %extend lldb::SBProcess {
 #ifdef SWIGPYTHON
 %pythoncode %{
+def WriteMemoryAsCString(self, addr, str, error):
+'''
+  WriteMemoryAsCString(self, addr, str, error):
+This functions the same as `WriteMemory` except a 
null-terminator is appended
+to the end of the buffer if it is not there already.
+'''
+if not str or len(str) == 0:
+return 0
+if not str[-1] == '\0':
+str += '\0'
+return self.WriteMemory(addr, str, error)
+
 def __get_is_alive__(self):
 '''Returns "True" if the process is currently alive, "False" 
otherwise'''
 s = self.GetState()


Index: lldb/test/API/python_api/process/TestProcessAPI.py
===
--- lldb/test/API/python_api/process/TestProcessAPI.py
+++ lldb/test/API/python_api/process/TestProcessAPI.py
@@ -186,6 +186,32 @@
 exe=False,
 startstr=b'a')
 
+# Get the SBValue for the global variable 'my_cstring'.
+val = frame.FindValue("my_cstring", lldb.eValueTypeVariableGlobal)
+self.DebugSBValue(val)
+
+addr = val.AddressOf().GetValueAsUnsigned()
+
+# Write an empty string to memory
+bytes_written = process.WriteMemoryAsCString(addr, "", error)
+self.assertEqual(bytes_written, 0)
+if not error.Success():
+self.fail("SBProcess.WriteMemoryAsCString() failed")
+
+message = "Hello!"
+bytes_written = process.WriteMemoryAsCString(addr, message, error)
+self.assertEqual(bytes_written, len(message) + 1)
+if not error.Success():
+self.fail("SBProcess.WriteMemoryAsCString() failed")
+
+cstring = process.ReadCStringFromMemory(
+val.AddressOf().GetValueAsUnsigned(), 256, error)
+if not error.Success():
+self.fail("SBProcess.ReadCStringFromMemory() failed")
+
+self.assertEqual(cstring, message)
+
+
 def test_access_my_int(self):
 """Test access 'my_int' using Python SBProcess.GetByteOrder() and other APIs."""
 self.build()
Index: lldb/bindings/interface/SBProcessExtensions.i
===
--- lldb/bindings/interface/SBProcessExtensions.i
+++ lldb/bindings/interface/SBProcessExtensions.i
@@ -2,6 +2,18 @@
 %extend lldb::SBProcess {
 #ifdef SWIGPYTHON
 %pythoncode %{
+def WriteMemoryAsCString(self, addr, str, error):
+'''
+  WriteMemoryAsCString(self, addr, str, error):
+This functions the same as `WriteMemory` except a null-terminator is appended
+to the end of the buffer if it is not there already.
+'''
+if not str or len(str) == 0:
+return 0
+if not str[-1] == '\0':
+str += '\0'
+ 

[Lldb-commits] [PATCH] D144224: [lldb] Extend SWIG SBProcess interface with WriteMemoryAsCString method

2023-03-03 Thread Alex Langford via Phabricator via lldb-commits
bulbazord accepted this revision.
bulbazord added a comment.
This revision is now accepted and ready to land.

Thanks for adding those tests.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D144224/new/

https://reviews.llvm.org/D144224

___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] 2d5348b - [lldb/Plugins] Add ScriptedProcess::GetCapabilities affordance (NFC)

2023-03-03 Thread Med Ismail Bennani via lldb-commits

Author: Med Ismail Bennani
Date: 2023-03-03T19:33:02-08:00
New Revision: 2d5348be2561402e284e26a9adf3a2e28e70c1f5

URL: 
https://github.com/llvm/llvm-project/commit/2d5348be2561402e284e26a9adf3a2e28e70c1f5
DIFF: 
https://github.com/llvm/llvm-project/commit/2d5348be2561402e284e26a9adf3a2e28e70c1f5.diff

LOG: [lldb/Plugins] Add ScriptedProcess::GetCapabilities affordance (NFC)

This patch introduces a new method to the Scripted Process interface,
GetCapabilities.

This returns a dictionary that contains a list of flags that the
ScriptedProcess instance supports. This can be used for instance, to
force symbol lookup, when loading dynamic libraries in the scripted process.

Differential Revision: https://reviews.llvm.org/D142059

Signed-off-by: Med Ismail Bennani 

Added: 


Modified: 
lldb/examples/python/scripted_process/scripted_process.py
lldb/include/lldb/Interpreter/ScriptedProcessInterface.h

lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.cpp

lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.h

Removed: 




diff  --git a/lldb/examples/python/scripted_process/scripted_process.py 
b/lldb/examples/python/scripted_process/scripted_process.py
index 758d0a47d115..db77e125817e 100644
--- a/lldb/examples/python/scripted_process/scripted_process.py
+++ b/lldb/examples/python/scripted_process/scripted_process.py
@@ -14,6 +14,7 @@ class ScriptedProcess(metaclass=ABCMeta):
 THE METHODS EXPOSED MIGHT CHANGE IN THE FUTURE.
 """
 
+capabilities = None
 memory_regions = None
 loaded_images = None
 threads = None
@@ -45,6 +46,17 @@ def __init__(self, exe_ctx, args):
 self.threads = {}
 self.loaded_images = []
 self.metadata = {}
+self.capabilities = {}
+
+def get_capabilities(self):
+""" Get a dictionary containing the process capabilities.
+
+Returns:
+Dict[str:bool]: The dictionary of capability, with the capability
+name as the key and a boolean flag as the value.
+The dictionary can be empty.
+"""
+return self.capabilities
 
 @abstractmethod
 def get_memory_region_containing_address(self, addr):

diff  --git a/lldb/include/lldb/Interpreter/ScriptedProcessInterface.h 
b/lldb/include/lldb/Interpreter/ScriptedProcessInterface.h
index 6d1860aa310a..0dffa71a873d 100644
--- a/lldb/include/lldb/Interpreter/ScriptedProcessInterface.h
+++ b/lldb/include/lldb/Interpreter/ScriptedProcessInterface.h
@@ -28,6 +28,8 @@ class ScriptedProcessInterface : virtual public 
ScriptedInterface {
 return {};
   }
 
+  virtual StructuredData::DictionarySP GetCapabilities() { return {}; }
+
   virtual Status Launch() { return Status("ScriptedProcess did not launch"); }
 
   virtual Status Resume() { return Status("ScriptedProcess did not resume"); }

diff  --git 
a/lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.cpp
 
b/lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.cpp
index 6f087e8390ce..3a1db7f35b15 100644
--- 
a/lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.cpp
+++ 
b/lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.cpp
@@ -56,6 +56,17 @@ StructuredData::GenericSP 
ScriptedProcessPythonInterface::CreatePluginObject(
   return m_object_instance_sp;
 }
 
+StructuredData::DictionarySP ScriptedProcessPythonInterface::GetCapabilities() 
{
+  Status error;
+  StructuredData::DictionarySP dict =
+  Dispatch("get_capabilities", error);
+
+  if (!CheckStructuredDataObject(LLVM_PRETTY_FUNCTION, dict, error))
+return {};
+
+  return dict;
+}
+
 Status ScriptedProcessPythonInterface::Launch() {
   return GetStatusFromMethod("launch");
 }
@@ -140,14 +151,8 @@ StructuredData::ArraySP 
ScriptedProcessPythonInterface::GetLoadedImages() {
   StructuredData::ArraySP array =
   Dispatch("get_loaded_images", error);
 
-  if (!array || !array->IsValid() || error.Fail()) {
-return ScriptedInterface::ErrorWithMessage(
-LLVM_PRETTY_FUNCTION,
-llvm::Twine("Null or invalid object (" +
-llvm::Twine(error.AsCString()) + llvm::Twine(")."))
-.str(),
-error);
-  }
+  if (!CheckStructuredDataObject(LLVM_PRETTY_FUNCTION, array, error))
+return {};
 
   return array;
 }

diff  --git 
a/lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.h 
b/lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.h
index 6b4ee3021cfa..6358f9cabffd 100644
--- 
a/lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.h
+++ 
b/lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.h
@@ -29,6 +29,8 @@ class ScriptedProcessPythonInterface : public 
ScriptedProcessInterface,
  StructuredData::Di

[Lldb-commits] [lldb] 3014a1c - [lldb] Add scripted process launch/attach option to {, platform }process commands

2023-03-03 Thread Med Ismail Bennani via lldb-commits

Author: Med Ismail Bennani
Date: 2023-03-03T19:33:02-08:00
New Revision: 3014a1c5a130daeb73f6d3b7280c5ceaeadc66a8

URL: 
https://github.com/llvm/llvm-project/commit/3014a1c5a130daeb73f6d3b7280c5ceaeadc66a8
DIFF: 
https://github.com/llvm/llvm-project/commit/3014a1c5a130daeb73f6d3b7280c5ceaeadc66a8.diff

LOG: [lldb] Add scripted process launch/attach option to {,platform }process 
commands

This patch does several things:

First, it refactors the `CommandObject{,Platform}ProcessObject` command
option class into a separate `CommandOptionsProcessAttach` option group.

This will make sure both the `platform process attach` and `process attach`
command options will always stay in sync without having with duplicate
them each time. But more importantly, making this class an `OptionGroup`
allows us to combine with a `OptionGroupPythonClassWithDict` to add
support for the scripted process managing class name and user-provided
dictionary options.

This patch also improves feature parity between `ProcessLaunchInfo` and
`ProcessAttachInfo` with regard to ScriptedProcesses, by exposing the
various getters and setters necessary to use them through the SBAPI.

This is foundation work for adding support to "attach" to a process from
the scripted platform.

Differential Revision: https://reviews.llvm.org/D139945

Signed-off-by: Med Ismail Bennani 

Added: 
lldb/source/Commands/CommandOptionsProcessAttach.cpp
lldb/source/Commands/CommandOptionsProcessAttach.h

Modified: 
lldb/include/lldb/API/SBAttachInfo.h
lldb/include/lldb/API/SBStructuredData.h
lldb/include/lldb/Target/Process.h
lldb/source/API/SBAttachInfo.cpp
lldb/source/Commands/CMakeLists.txt
lldb/source/Commands/CommandObjectPlatform.cpp
lldb/source/Commands/CommandObjectProcess.cpp

Removed: 




diff  --git a/lldb/include/lldb/API/SBAttachInfo.h 
b/lldb/include/lldb/API/SBAttachInfo.h
index 9b211d0f74bd..e296956c0a19 100644
--- a/lldb/include/lldb/API/SBAttachInfo.h
+++ b/lldb/include/lldb/API/SBAttachInfo.h
@@ -164,6 +164,14 @@ class LLDB_API SBAttachInfo {
   /// allows a 
diff erent listener to be used to listen for process events.
   void SetListener(SBListener &listener);
 
+  const char *GetScriptedProcessClassName() const;
+
+  void SetScriptedProcessClassName(const char *class_name);
+
+  lldb::SBStructuredData GetScriptedProcessDictionary() const;
+
+  void SetScriptedProcessDictionary(lldb::SBStructuredData dict);
+
 protected:
   friend class SBTarget;
 

diff  --git a/lldb/include/lldb/API/SBStructuredData.h 
b/lldb/include/lldb/API/SBStructuredData.h
index 9cf55ad002e0..13dfca6b38c2 100644
--- a/lldb/include/lldb/API/SBStructuredData.h
+++ b/lldb/include/lldb/API/SBStructuredData.h
@@ -92,6 +92,7 @@ class SBStructuredData {
   size_t GetStringValue(char *dst, size_t dst_len) const;
 
 protected:
+  friend class SBAttachInfo;
   friend class SBLaunchInfo;
   friend class SBDebugger;
   friend class SBTarget;

diff  --git a/lldb/include/lldb/Target/Process.h 
b/lldb/include/lldb/Target/Process.h
index 3ffacb52299b..ff2a62a09def 100644
--- a/lldb/include/lldb/Target/Process.h
+++ b/lldb/include/lldb/Target/Process.h
@@ -193,6 +193,28 @@ class ProcessAttachInfo : public ProcessInstanceInfo {
 
   lldb::ListenerSP GetListenerForProcess(Debugger &debugger);
 
+  bool IsScriptedProcess() const {
+return !m_scripted_process_class_name.empty();
+  }
+
+  std::string GetScriptedProcessClassName() const {
+return m_scripted_process_class_name;
+  }
+
+  void SetScriptedProcessClassName(std::string name) {
+m_scripted_process_class_name = name;
+  }
+
+  lldb_private::StructuredData::DictionarySP
+  GetScriptedProcessDictionarySP() const {
+return m_scripted_process_dictionary_sp;
+  }
+
+  void SetScriptedProcessDictionarySP(
+  lldb_private::StructuredData::DictionarySP dictionary_sp) {
+m_scripted_process_dictionary_sp = dictionary_sp;
+  }
+
 protected:
   lldb::ListenerSP m_listener_sp;
   lldb::ListenerSP m_hijack_listener_sp;
@@ -210,6 +232,11 @@ class ProcessAttachInfo : public ProcessInstanceInfo {
   false; // Use an async attach where we start the attach and return
  // immediately (used by GUI programs with --waitfor so they can
  // call SBProcess::Stop() to cancel attach)
+  std::string m_scripted_process_class_name; // The name of the class that will
+ // manage a scripted process.
+  StructuredData::DictionarySP
+  m_scripted_process_dictionary_sp; // A dictionary that holds key/value
+// pairs passed to the scripted 
process.
 };
 
 // This class tracks the Modification state of the process.  Things that can

diff  --git a/lldb/source/API/SBAttachInfo.cpp 
b/lldb/source/API/SBAttachInfo.cpp
index edb4f7104d41..cb66566270b2 100644
--- a/lldb/source/API/SBAttachInfo.cpp
+++ b/lldb/source/API/S

[Lldb-commits] [lldb] e6cac17 - [lldb] Extend SWIG SBProcess interface with WriteMemoryAsCString method

2023-03-03 Thread Med Ismail Bennani via lldb-commits

Author: Med Ismail Bennani
Date: 2023-03-03T19:33:01-08:00
New Revision: e6cac17b563f2e2bc7d04347b0b40a9fe12334c9

URL: 
https://github.com/llvm/llvm-project/commit/e6cac17b563f2e2bc7d04347b0b40a9fe12334c9
DIFF: 
https://github.com/llvm/llvm-project/commit/e6cac17b563f2e2bc7d04347b0b40a9fe12334c9.diff

LOG: [lldb] Extend SWIG SBProcess interface with WriteMemoryAsCString method

This patch tries to address an interoperability issue when writing
python string into the process memory.

Since the python string is not null-terminated, it would still be
written to memory however, when trying to read it again with
`SBProcess::ReadCStringFromMemory`, the memory read would fail, since
the read string doens't contain a null-terminator, and therefore is not
a valid C string.

To address that, this patch extends the `SBProcess` SWIG interface to
expose a new `WriteMemoryAsCString` method that is only exposed to the
SWIG target language. That method checks that the buffer to write is
null-terminated and otherwise, it appends a null byte at the end of it.

Signed-off-by: Med Ismail Bennani 

Added: 


Modified: 
lldb/bindings/interface/SBProcessExtensions.i
lldb/test/API/python_api/process/TestProcessAPI.py

Removed: 




diff  --git a/lldb/bindings/interface/SBProcessExtensions.i 
b/lldb/bindings/interface/SBProcessExtensions.i
index c6660d7f42e1..fe9e6415b618 100644
--- a/lldb/bindings/interface/SBProcessExtensions.i
+++ b/lldb/bindings/interface/SBProcessExtensions.i
@@ -2,6 +2,18 @@ STRING_EXTENSION_OUTSIDE(SBProcess)
 %extend lldb::SBProcess {
 #ifdef SWIGPYTHON
 %pythoncode %{
+def WriteMemoryAsCString(self, addr, str, error):
+'''
+  WriteMemoryAsCString(self, addr, str, error):
+This functions the same as `WriteMemory` except a 
null-terminator is appended
+to the end of the buffer if it is not there already.
+'''
+if not str or len(str) == 0:
+return 0
+if not str[-1] == '\0':
+str += '\0'
+return self.WriteMemory(addr, str, error)
+
 def __get_is_alive__(self):
 '''Returns "True" if the process is currently alive, "False" 
otherwise'''
 s = self.GetState()

diff  --git a/lldb/test/API/python_api/process/TestProcessAPI.py 
b/lldb/test/API/python_api/process/TestProcessAPI.py
index c56053dad0cf..edb507057283 100644
--- a/lldb/test/API/python_api/process/TestProcessAPI.py
+++ b/lldb/test/API/python_api/process/TestProcessAPI.py
@@ -186,6 +186,32 @@ def test_write_memory(self):
 exe=False,
 startstr=b'a')
 
+# Get the SBValue for the global variable 'my_cstring'.
+val = frame.FindValue("my_cstring", lldb.eValueTypeVariableGlobal)
+self.DebugSBValue(val)
+
+addr = val.AddressOf().GetValueAsUnsigned()
+
+# Write an empty string to memory
+bytes_written = process.WriteMemoryAsCString(addr, "", error)
+self.assertEqual(bytes_written, 0)
+if not error.Success():
+self.fail("SBProcess.WriteMemoryAsCString() failed")
+
+message = "Hello!"
+bytes_written = process.WriteMemoryAsCString(addr, message, error)
+self.assertEqual(bytes_written, len(message) + 1)
+if not error.Success():
+self.fail("SBProcess.WriteMemoryAsCString() failed")
+
+cstring = process.ReadCStringFromMemory(
+val.AddressOf().GetValueAsUnsigned(), 256, error)
+if not error.Success():
+self.fail("SBProcess.ReadCStringFromMemory() failed")
+
+self.assertEqual(cstring, message)
+
+
 def test_access_my_int(self):
 """Test access 'my_int' using Python SBProcess.GetByteOrder() and 
other APIs."""
 self.build()



___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] e02a355 - [lldb/Plugins] Clean-up Scripted Process interface requirements (NFC)

2023-03-03 Thread Med Ismail Bennani via lldb-commits

Author: Med Ismail Bennani
Date: 2023-03-03T19:33:02-08:00
New Revision: e02a355f9846d5ec9cd64b086674770ecc795c26

URL: 
https://github.com/llvm/llvm-project/commit/e02a355f9846d5ec9cd64b086674770ecc795c26
DIFF: 
https://github.com/llvm/llvm-project/commit/e02a355f9846d5ec9cd64b086674770ecc795c26.diff

LOG: [lldb/Plugins] Clean-up Scripted Process interface requirements (NFC)

The goal of the simple patch is to clean-up the scripted process
interface by removing methods that were introduced with the interface
originally, but that were never really implemented (get_thread_with_id &
get_registers_for_thread).

This patch also changes `get_memory_region_containing_address` to have a
base implementation (that retunrs `None`), instead of forcing the user
to override it in their derived class.

Signed-off-by: Med Ismail Bennani 

Added: 


Modified: 
lldb/examples/python/scripted_process/crashlog_scripted_process.py
lldb/examples/python/scripted_process/scripted_process.py
lldb/include/lldb/Interpreter/ScriptedProcessInterface.h

lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.cpp

lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.h
lldb/test/API/functionalities/scripted_process/dummy_scripted_process.py
lldb/test/API/functionalities/scripted_process/invalid_scripted_process.py

lldb/test/API/functionalities/scripted_process/stack_core_scripted_process.py

Removed: 




diff  --git 
a/lldb/examples/python/scripted_process/crashlog_scripted_process.py 
b/lldb/examples/python/scripted_process/crashlog_scripted_process.py
index dfb32aae6d3f..8c32b40d8c8a 100644
--- a/lldb/examples/python/scripted_process/crashlog_scripted_process.py
+++ b/lldb/examples/python/scripted_process/crashlog_scripted_process.py
@@ -94,15 +94,6 @@ def __init__(self, exe_ctx: lldb.SBExecutionContext, args : 
lldb.SBStructuredDat
 self.extended_thread_info = None
 self.parse_crashlog()
 
-def get_memory_region_containing_address(self, addr: int) -> 
lldb.SBMemoryRegionInfo:
-return None
-
-def get_thread_with_id(self, tid: int):
-return {}
-
-def get_registers_for_thread(self, tid: int):
-return {}
-
 def read_memory_at_address(self, addr: int, size: int, error: 
lldb.SBError) -> lldb.SBData:
 # NOTE: CrashLogs don't contain any memory.
 return lldb.SBData()

diff  --git a/lldb/examples/python/scripted_process/scripted_process.py 
b/lldb/examples/python/scripted_process/scripted_process.py
index 8f896fc5acce..60b65fc4b4c9 100644
--- a/lldb/examples/python/scripted_process/scripted_process.py
+++ b/lldb/examples/python/scripted_process/scripted_process.py
@@ -58,7 +58,6 @@ def get_capabilities(self):
 """
 return self.capabilities
 
-@abstractmethod
 def get_memory_region_containing_address(self, addr):
 """ Get the memory region for the scripted process, containing a
 specific address.
@@ -71,7 +70,7 @@ def get_memory_region_containing_address(self, addr):
 lldb.SBMemoryRegionInfo: The memory region containing the address.
 None if out of bounds.
 """
-pass
+return None
 
 def get_threads_info(self):
 """ Get the dictionary describing the process' Scripted Threads.
@@ -83,35 +82,6 @@ def get_threads_info(self):
 """
 return self.threads
 
-@abstractmethod
-def get_thread_with_id(self, tid):
-""" Get the scripted process thread with a specific ID.
-
-Args:
-tid (int): Thread ID to look for in the scripted process.
-
-Returns:
-Dict: The thread represented as a dictionary, with the
-tid thread ID. None if tid doesn't match any of the scripted
-process threads.
-"""
-pass
-
-@abstractmethod
-def get_registers_for_thread(self, tid):
-""" Get the register context dictionary for a certain thread of
-the scripted process.
-
-Args:
-tid (int): Thread ID for the thread's register context.
-
-Returns:
-Dict: The register context represented as a dictionary, for the
-tid thread. None if tid doesn't match any of the scripted
-process threads.
-"""
-pass
-
 @abstractmethod
 def read_memory_at_address(self, addr, size, error):
 """ Get a memory buffer from the scripted process at a certain address,

diff  --git a/lldb/include/lldb/Interpreter/ScriptedProcessInterface.h 
b/lldb/include/lldb/Interpreter/ScriptedProcessInterface.h
index 1fdac762e51e..ec0d7deac01b 100644
--- a/lldb/include/lldb/Interpreter/ScriptedProcessInterface.h
+++ b/lldb/include/lldb/Interpreter/ScriptedProcessInterface.h
@@ -50,14 +50,6 @@ class ScriptedProcessInterface : virtual public 
Sc

[Lldb-commits] [lldb] b9d4c94 - [lldb/Plugins] Add Attach capabilities to ScriptedProcess

2023-03-03 Thread Med Ismail Bennani via lldb-commits

Author: Med Ismail Bennani
Date: 2023-03-03T19:33:02-08:00
New Revision: b9d4c94a603d3cc1f44ab7dd1d4f3ae9c80da98b

URL: 
https://github.com/llvm/llvm-project/commit/b9d4c94a603d3cc1f44ab7dd1d4f3ae9c80da98b
DIFF: 
https://github.com/llvm/llvm-project/commit/b9d4c94a603d3cc1f44ab7dd1d4f3ae9c80da98b.diff

LOG: [lldb/Plugins] Add Attach capabilities to ScriptedProcess

This patch adds process attach capabilities to the ScriptedProcess
plugin. This doesn't really expects a PID or process name, since the
process state is already script, however, this allows to create a
scripted process without requiring to have an executuble in the target.

In order to do so, this patch also turns the scripted process related
getters and setters from the `ProcessLaunchInfo` and
`ProcessAttachInfo` classes to a `ScriptedMetadata` instance and moves
it in the `ProcessInfo` class, so it can be accessed interchangeably.

This also adds the necessary SWIG wrappers to convert the internal
`Process{Attach,Launch}InfoSP` into a `SB{Attach,Launch}Info` to pass it
as argument the scripted process python implementation and convert it
back to the internal representation.

rdar://104577406

Differential Revision: https://reviews.llvm.org/D143104

Signed-off-by: Med Ismail Bennani 

Added: 


Modified: 
lldb/bindings/python/python-swigsafecast.swig
lldb/bindings/python/python-wrapper.swig
lldb/examples/python/scripted_process/scripted_process.py
lldb/include/lldb/API/SBAttachInfo.h
lldb/include/lldb/API/SBLaunchInfo.h
lldb/include/lldb/Host/ProcessLaunchInfo.h
lldb/include/lldb/Interpreter/ScriptInterpreter.h
lldb/include/lldb/Interpreter/ScriptedMetadata.h
lldb/include/lldb/Interpreter/ScriptedProcessInterface.h
lldb/include/lldb/Target/Process.h
lldb/include/lldb/Target/Target.h
lldb/include/lldb/Utility/ProcessInfo.h
lldb/include/lldb/lldb-forward.h
lldb/source/API/SBAttachInfo.cpp
lldb/source/API/SBLaunchInfo.cpp
lldb/source/API/SBTarget.cpp
lldb/source/Commands/CommandObjectPlatform.cpp
lldb/source/Commands/CommandObjectProcess.cpp
lldb/source/Host/common/ProcessLaunchInfo.cpp
lldb/source/Interpreter/ScriptInterpreter.cpp
lldb/source/Plugins/Process/scripted/ScriptedProcess.cpp
lldb/source/Plugins/Process/scripted/ScriptedProcess.h
lldb/source/Plugins/ScriptInterpreter/Python/SWIGPythonBridge.h

lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.cpp

lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.h
lldb/source/Plugins/ScriptInterpreter/Python/ScriptedPythonInterface.cpp
lldb/source/Plugins/ScriptInterpreter/Python/ScriptedPythonInterface.h
lldb/source/Target/Target.cpp
lldb/source/Utility/ProcessInfo.cpp
lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
lldb/unittests/ScriptInterpreter/Python/PythonTestSuite.cpp

Removed: 




diff  --git a/lldb/bindings/python/python-swigsafecast.swig 
b/lldb/bindings/python/python-swigsafecast.swig
index a1e883b3b19d..ae562c26518c 100644
--- a/lldb/bindings/python/python-swigsafecast.swig
+++ b/lldb/bindings/python/python-swigsafecast.swig
@@ -93,6 +93,16 @@ PythonObject ToSWIGWrapper(const SymbolContext &sym_ctx) {
   SWIGTYPE_p_lldb__SBSymbolContext);
 }
 
+PythonObject ToSWIGWrapper(lldb::ProcessLaunchInfoSP launch_info_sp) {
+   return ToSWIGHelper(new 
lldb::ProcessLaunchInfoSP(std::move(launch_info_sp)),
+   SWIGTYPE_p_lldb__SBLaunchInfo);
+ }
+
+ PythonObject ToSWIGWrapper(lldb::ProcessAttachInfoSP attach_info_sp) {
+   return ToSWIGHelper(new 
lldb::ProcessAttachInfoSP(std::move(attach_info_sp)),
+   SWIGTYPE_p_lldb__SBAttachInfo);
+ }
+
 ScopedPythonObject
 ToSWIGWrapper(CommandReturnObject &cmd_retobj) {
   return ScopedPythonObject(

diff  --git a/lldb/bindings/python/python-wrapper.swig 
b/lldb/bindings/python/python-wrapper.swig
index 9a08c3000b79..26f79266538a 100644
--- a/lldb/bindings/python/python-wrapper.swig
+++ b/lldb/bindings/python/python-wrapper.swig
@@ -716,6 +716,30 @@ void 
*lldb_private::LLDBSWIGPython_CastPyObjectToSBData(PyObject * data) {
   return sb_ptr;
 }
 
+void *lldb_private::LLDBSWIGPython_CastPyObjectToSBAttachInfo(PyObject * data) 
{
+  lldb::SBAttachInfo *sb_ptr = nullptr;
+
+  int valid_cast =
+  SWIG_ConvertPtr(data, (void **)&sb_ptr, SWIGTYPE_p_lldb__SBAttachInfo, 
0);
+
+  if (valid_cast == -1)
+return NULL;
+
+  return sb_ptr;
+}
+
+void *lldb_private::LLDBSWIGPython_CastPyObjectToSBLaunchInfo(PyObject * data) 
{
+  lldb::SBLaunchInfo *sb_ptr = nullptr;
+
+  int valid_cast =
+  SWIG_ConvertPtr(data, (void **)&sb_ptr, SWIGTYPE_p_lldb__SBLaunchInfo, 
0);
+
+  if (valid_cast == -1)
+return NULL;
+
+  return sb_ptr;
+}
+
 void *lldb_private::LLDBSWIGPython_CastPyObjectToSBError(PyObject * data) {
   lldb::

[Lldb-commits] [PATCH] D142059: [lldb/Plugins] Add ScriptedProcess::GetCapabilities affordance (NFC)

2023-03-03 Thread Med Ismail Bennani via Phabricator via lldb-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG2d5348be2561: [lldb/Plugins] Add 
ScriptedProcess::GetCapabilities affordance (NFC) (authored by mib).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D142059/new/

https://reviews.llvm.org/D142059

Files:
  lldb/examples/python/scripted_process/scripted_process.py
  lldb/include/lldb/Interpreter/ScriptedProcessInterface.h
  
lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.cpp
  lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.h


Index: 
lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.h
===
--- 
lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.h
+++ 
lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.h
@@ -29,6 +29,8 @@
  StructuredData::DictionarySP args_sp,
  StructuredData::Generic *script_obj = nullptr) override;
 
+  StructuredData::DictionarySP GetCapabilities() override;
+
   Status Launch() override;
 
   Status Resume() override;
Index: 
lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.cpp
===
--- 
lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.cpp
+++ 
lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.cpp
@@ -56,6 +56,17 @@
   return m_object_instance_sp;
 }
 
+StructuredData::DictionarySP ScriptedProcessPythonInterface::GetCapabilities() 
{
+  Status error;
+  StructuredData::DictionarySP dict =
+  Dispatch("get_capabilities", error);
+
+  if (!CheckStructuredDataObject(LLVM_PRETTY_FUNCTION, dict, error))
+return {};
+
+  return dict;
+}
+
 Status ScriptedProcessPythonInterface::Launch() {
   return GetStatusFromMethod("launch");
 }
@@ -140,14 +151,8 @@
   StructuredData::ArraySP array =
   Dispatch("get_loaded_images", error);
 
-  if (!array || !array->IsValid() || error.Fail()) {
-return ScriptedInterface::ErrorWithMessage(
-LLVM_PRETTY_FUNCTION,
-llvm::Twine("Null or invalid object (" +
-llvm::Twine(error.AsCString()) + llvm::Twine(")."))
-.str(),
-error);
-  }
+  if (!CheckStructuredDataObject(LLVM_PRETTY_FUNCTION, array, error))
+return {};
 
   return array;
 }
Index: lldb/include/lldb/Interpreter/ScriptedProcessInterface.h
===
--- lldb/include/lldb/Interpreter/ScriptedProcessInterface.h
+++ lldb/include/lldb/Interpreter/ScriptedProcessInterface.h
@@ -28,6 +28,8 @@
 return {};
   }
 
+  virtual StructuredData::DictionarySP GetCapabilities() { return {}; }
+
   virtual Status Launch() { return Status("ScriptedProcess did not launch"); }
 
   virtual Status Resume() { return Status("ScriptedProcess did not resume"); }
Index: lldb/examples/python/scripted_process/scripted_process.py
===
--- lldb/examples/python/scripted_process/scripted_process.py
+++ lldb/examples/python/scripted_process/scripted_process.py
@@ -14,6 +14,7 @@
 THE METHODS EXPOSED MIGHT CHANGE IN THE FUTURE.
 """
 
+capabilities = None
 memory_regions = None
 loaded_images = None
 threads = None
@@ -45,6 +46,17 @@
 self.threads = {}
 self.loaded_images = []
 self.metadata = {}
+self.capabilities = {}
+
+def get_capabilities(self):
+""" Get a dictionary containing the process capabilities.
+
+Returns:
+Dict[str:bool]: The dictionary of capability, with the capability
+name as the key and a boolean flag as the value.
+The dictionary can be empty.
+"""
+return self.capabilities
 
 @abstractmethod
 def get_memory_region_containing_address(self, addr):


Index: lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.h
===
--- lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.h
+++ lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.h
@@ -29,6 +29,8 @@
  StructuredData::DictionarySP args_sp,
  StructuredData::Generic *script_obj = nullptr) override;
 
+  StructuredData::DictionarySP GetCapabilities() override;
+
   Status Launch() override;
 
   Status Resume() override;
Index: lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.cpp
===
--- lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.cpp
+++ lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.cpp
@@ -56,6 +

[Lldb-commits] [lldb] f190ec6 - [lldb/Plugins] Add memory writing capabilities to Scripted Process

2023-03-03 Thread Med Ismail Bennani via lldb-commits

Author: Med Ismail Bennani
Date: 2023-03-03T19:33:02-08:00
New Revision: f190ec6882706d30c606e62986512371925288a9

URL: 
https://github.com/llvm/llvm-project/commit/f190ec6882706d30c606e62986512371925288a9
DIFF: 
https://github.com/llvm/llvm-project/commit/f190ec6882706d30c606e62986512371925288a9.diff

LOG: [lldb/Plugins] Add memory writing capabilities to Scripted Process

This patch adds memory writing capabilities to the Scripted Process plugin.

This allows to user to get a target address and a memory buffer on the
python scripted process implementation that the user can make processing
on before performing the actual write.

This will also be used to write trap instruction to a real process
memory to set a breakpoint.

Signed-off-by: Med Ismail Bennani 

Added: 


Modified: 
lldb/bindings/python/python-swigsafecast.swig
lldb/examples/python/scripted_process/scripted_process.py
lldb/include/lldb/Interpreter/ScriptedProcessInterface.h
lldb/source/Plugins/Process/scripted/ScriptedProcess.cpp
lldb/source/Plugins/Process/scripted/ScriptedProcess.h
lldb/source/Plugins/ScriptInterpreter/Python/SWIGPythonBridge.h

lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.cpp

lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.h
lldb/source/Plugins/ScriptInterpreter/Python/ScriptedPythonInterface.h
lldb/source/Target/Memory.cpp
lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
lldb/test/API/functionalities/scripted_process/dummy_scripted_process.py
lldb/unittests/ScriptInterpreter/Python/PythonTestSuite.cpp

Removed: 




diff  --git a/lldb/bindings/python/python-swigsafecast.swig 
b/lldb/bindings/python/python-swigsafecast.swig
index ae562c26518c..f7e78bb419bd 100644
--- a/lldb/bindings/python/python-swigsafecast.swig
+++ b/lldb/bindings/python/python-swigsafecast.swig
@@ -103,6 +103,11 @@ PythonObject ToSWIGWrapper(lldb::ProcessLaunchInfoSP 
launch_info_sp) {
SWIGTYPE_p_lldb__SBAttachInfo);
  }
 
+PythonObject ToSWIGWrapper(lldb::DataExtractorSP data_sp) {
+  return ToSWIGHelper(new lldb::DataExtractorSP(std::move(data_sp)),
+  SWIGTYPE_p_lldb__SBData);
+}
+
 ScopedPythonObject
 ToSWIGWrapper(CommandReturnObject &cmd_retobj) {
   return ScopedPythonObject(

diff  --git a/lldb/examples/python/scripted_process/scripted_process.py 
b/lldb/examples/python/scripted_process/scripted_process.py
index 60b65fc4b4c9..044aee133880 100644
--- a/lldb/examples/python/scripted_process/scripted_process.py
+++ b/lldb/examples/python/scripted_process/scripted_process.py
@@ -98,6 +98,21 @@ def read_memory_at_address(self, addr, size, error):
 """
 pass
 
+def write_memory_at_address(self, addr, data, error):
+""" Write a buffer to the scripted process memory.
+
+Args:
+addr (int): Address from which we should start reading.
+data (lldb.SBData): An `lldb.SBData` buffer to write to the
+process memory.
+error (lldb.SBError): Error object.
+
+Returns:
+size (int): Size of the memory to read.
+"""
+error.SetErrorString("%s doesn't support memory writes." % 
self.__class__.__name__)
+return 0
+
 def get_loaded_images(self):
 """ Get the list of loaded images for the scripted process.
 

diff  --git a/lldb/include/lldb/Interpreter/ScriptedProcessInterface.h 
b/lldb/include/lldb/Interpreter/ScriptedProcessInterface.h
index ec0d7deac01b..ba4743077e02 100644
--- a/lldb/include/lldb/Interpreter/ScriptedProcessInterface.h
+++ b/lldb/include/lldb/Interpreter/ScriptedProcessInterface.h
@@ -55,6 +55,12 @@ class ScriptedProcessInterface : virtual public 
ScriptedInterface {
 return {};
   }
 
+  virtual size_t WriteMemoryAtAddress(lldb::addr_t addr,
+  lldb::DataExtractorSP data_sp,
+  Status &error) {
+return LLDB_INVALID_OFFSET;
+  };
+
   virtual StructuredData::ArraySP GetLoadedImages() { return {}; }
 
   virtual lldb::pid_t GetProcessID() { return LLDB_INVALID_PROCESS_ID; }

diff  --git a/lldb/source/Plugins/Process/scripted/ScriptedProcess.cpp 
b/lldb/source/Plugins/Process/scripted/ScriptedProcess.cpp
index 84e9dea4b7be..948ee691ecbe 100644
--- a/lldb/source/Plugins/Process/scripted/ScriptedProcess.cpp
+++ b/lldb/source/Plugins/Process/scripted/ScriptedProcess.cpp
@@ -255,7 +255,31 @@ size_t ScriptedProcess::DoReadMemory(lldb::addr_t addr, 
void *buf, size_t size,
 return ScriptedInterface::ErrorWithMessage(
 LLVM_PRETTY_FUNCTION, "Failed to copy read memory to buffer.", error);
 
-  return size;
+  // FIXME: We should use the diagnostic system to report a warning if the
+  // `bytes_copied` is 
diff erent from `size`.
+
+  return bytes_copied;
+}
+
+size_t S

[Lldb-commits] [lldb] efc5236 - [lldb] Improve error reporting in ScriptedInterface

2023-03-03 Thread Med Ismail Bennani via lldb-commits

Author: Med Ismail Bennani
Date: 2023-03-03T19:33:02-08:00
New Revision: efc52361ddb7282825f1f813553f322bd119b830

URL: 
https://github.com/llvm/llvm-project/commit/efc52361ddb7282825f1f813553f322bd119b830
DIFF: 
https://github.com/llvm/llvm-project/commit/efc52361ddb7282825f1f813553f322bd119b830.diff

LOG: [lldb] Improve error reporting in ScriptedInterface

This patch improve error reporting in the Scripted Interface.

Previously, it would only log the content of the Status object and
overwrite it with the error_msg function parameter.

This patch changes that to append the Status object content to the
`error_msg` string.

Signed-off-by: Med Ismail Bennani 

Added: 


Modified: 
lldb/include/lldb/Interpreter/ScriptedInterface.h

Removed: 




diff  --git a/lldb/include/lldb/Interpreter/ScriptedInterface.h 
b/lldb/include/lldb/Interpreter/ScriptedInterface.h
index 31064de7b765..10a9f418df80 100644
--- a/lldb/include/lldb/Interpreter/ScriptedInterface.h
+++ b/lldb/include/lldb/Interpreter/ScriptedInterface.h
@@ -40,9 +40,12 @@ class ScriptedInterface {
   LLDBLog log_caterogy = LLDBLog::Process) {
 LLDB_LOGF(GetLog(log_caterogy), "%s ERROR = %s", caller_name.data(),
   error_msg.data());
-error.SetErrorString(llvm::Twine(caller_name + llvm::Twine(" ERROR = ") +
- llvm::Twine(error_msg))
- .str());
+llvm::Twine err = llvm::Twine(caller_name + llvm::Twine(" ERROR = ") +
+  llvm::Twine(error_msg));
+if (const char *detailed_error = error.AsCString())
+  err.concat(llvm::Twine(" (") + llvm::Twine(detailed_error) +
+ llvm::Twine(")"));
+error.SetErrorString(err.str());
 return {};
   }
 



___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] ebdbc26 - [lldb/swig] Fix ref counting issue in SBProcess::GetScriptedImplementation

2023-03-03 Thread Med Ismail Bennani via lldb-commits

Author: Med Ismail Bennani
Date: 2023-03-03T19:33:02-08:00
New Revision: ebdbc26a3e79e64e9b2786a8b413618a5b5c115d

URL: 
https://github.com/llvm/llvm-project/commit/ebdbc26a3e79e64e9b2786a8b413618a5b5c115d
DIFF: 
https://github.com/llvm/llvm-project/commit/ebdbc26a3e79e64e9b2786a8b413618a5b5c115d.diff

LOG: [lldb/swig] Fix ref counting issue in SBProcess::GetScriptedImplementation

When using SBProcess::GetScriptedImplementation in python, if the
process has a valid implementation, we returned a reference of the
object without incrementing the reference counting. That causes the
interpreter to crash after accessing the reference several times.

This patch address this by incrementing the reference count when passing
the valid object reference.

Differential Revision: https://reviews.llvm.org/D145260

Signed-off-by: Med Ismail Bennani 

Added: 


Modified: 
lldb/bindings/python/python-typemaps.swig
lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py

Removed: 




diff  --git a/lldb/bindings/python/python-typemaps.swig 
b/lldb/bindings/python/python-typemaps.swig
index 2057aa6b42b6..1b1f2e1fe266 100644
--- a/lldb/bindings/python/python-typemaps.swig
+++ b/lldb/bindings/python/python-typemaps.swig
@@ -61,6 +61,8 @@
   if (!$result) {
 $result = Py_None;
 Py_INCREF(Py_None);
+  } else {
+Py_INCREF($result);
   }
 }
 

diff  --git 
a/lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py 
b/lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
index 5a198cc95704..b5a14a9cd63d 100644
--- a/lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
+++ b/lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
@@ -80,6 +80,15 @@ def cleanup():
 self.assertEqual(process.GetProcessID(), 666)
 self.assertEqual(process.GetNumThreads(), 0)
 
+impl = process.GetScriptedImplementation()
+self.assertTrue(impl)
+impl = process.GetScriptedImplementation()
+self.assertTrue(impl)
+impl = process.GetScriptedImplementation()
+self.assertTrue(impl)
+impl = process.GetScriptedImplementation()
+self.assertTrue(impl)
+
 addr = 0x5
 buff = process.ReadMemory(addr, 4, error)
 self.assertEqual(buff, None)



___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D139945: [lldb] Add scripted process launch/attach option to {, platform }process commands

2023-03-03 Thread Med Ismail Bennani via Phabricator via lldb-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG3014a1c5a130: [lldb] Add scripted process launch/attach 
option to {,platform }process commands (authored by mib).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D139945/new/

https://reviews.llvm.org/D139945

Files:
  lldb/include/lldb/API/SBAttachInfo.h
  lldb/include/lldb/API/SBStructuredData.h
  lldb/include/lldb/Target/Process.h
  lldb/source/API/SBAttachInfo.cpp
  lldb/source/Commands/CMakeLists.txt
  lldb/source/Commands/CommandObjectPlatform.cpp
  lldb/source/Commands/CommandObjectProcess.cpp
  lldb/source/Commands/CommandOptionsProcessAttach.cpp
  lldb/source/Commands/CommandOptionsProcessAttach.h

Index: lldb/source/Commands/CommandOptionsProcessAttach.h
===
--- /dev/null
+++ lldb/source/Commands/CommandOptionsProcessAttach.h
@@ -0,0 +1,47 @@
+//===-- CommandOptionsProcessAttach.h ---*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLDB_SOURCE_COMMANDS_COMMANDOPTIONSPROCESSATTACH_H
+#define LLDB_SOURCE_COMMANDS_COMMANDOPTIONSPROCESSATTACH_H
+
+#include "lldb/Interpreter/Options.h"
+#include "lldb/Target/Process.h"
+
+namespace lldb_private {
+
+// CommandOptionsProcessAttach
+
+class CommandOptionsProcessAttach : public lldb_private::OptionGroup {
+public:
+  CommandOptionsProcessAttach() {
+// Keep default values of all options in one place: OptionParsingStarting
+// ()
+OptionParsingStarting(nullptr);
+  }
+
+  ~CommandOptionsProcessAttach() override = default;
+
+  lldb_private::Status
+  SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
+ lldb_private::ExecutionContext *execution_context) override;
+
+  void OptionParsingStarting(
+  lldb_private::ExecutionContext *execution_context) override {
+attach_info.Clear();
+  }
+
+  llvm::ArrayRef GetDefinitions() override;
+
+  // Instance variables to hold the values for command options.
+
+  lldb_private::ProcessAttachInfo attach_info;
+}; // CommandOptionsProcessAttach
+
+} // namespace lldb_private
+
+#endif // LLDB_SOURCE_COMMANDS_COMMANDOPTIONSPROCESSATTACH_H
Index: lldb/source/Commands/CommandOptionsProcessAttach.cpp
===
--- /dev/null
+++ lldb/source/Commands/CommandOptionsProcessAttach.cpp
@@ -0,0 +1,76 @@
+//===-- CommandOptionsProcessAttach.cpp ---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "CommandOptionsProcessAttach.h"
+
+#include "lldb/Host/FileSystem.h"
+#include "lldb/Host/HostInfo.h"
+#include "lldb/Host/OptionParser.h"
+#include "lldb/Interpreter/CommandCompletions.h"
+#include "lldb/Interpreter/CommandObject.h"
+#include "lldb/Interpreter/CommandOptionArgumentTable.h"
+#include "lldb/Interpreter/OptionArgParser.h"
+#include "lldb/Target/ExecutionContext.h"
+#include "lldb/Target/Platform.h"
+#include "lldb/Target/Target.h"
+
+#include "llvm/ADT/ArrayRef.h"
+
+using namespace llvm;
+using namespace lldb;
+using namespace lldb_private;
+
+#define LLDB_OPTIONS_process_attach
+#include "CommandOptions.inc"
+
+Status CommandOptionsProcessAttach::SetOptionValue(
+uint32_t option_idx, llvm::StringRef option_arg,
+ExecutionContext *execution_context) {
+  Status error;
+  const int short_option = g_process_attach_options[option_idx].short_option;
+  switch (short_option) {
+  case 'c':
+attach_info.SetContinueOnceAttached(true);
+break;
+
+  case 'p': {
+lldb::pid_t pid;
+if (option_arg.getAsInteger(0, pid)) {
+  error.SetErrorStringWithFormat("invalid process ID '%s'",
+ option_arg.str().c_str());
+} else {
+  attach_info.SetProcessID(pid);
+}
+  } break;
+
+  case 'P':
+attach_info.SetProcessPluginName(option_arg);
+break;
+
+  case 'n':
+attach_info.GetExecutableFile().SetFile(option_arg,
+FileSpec::Style::native);
+break;
+
+  case 'w':
+attach_info.SetWaitForLaunch(true);
+break;
+
+  case 'i':
+attach_info.SetIgnoreExisting(false);
+break;
+
+  default:
+llvm_unreachable("Unimplemented option");
+  }
+  return error;
+}
+
+llvm::ArrayRef CommandOptionsProcessAttach::GetDefinitions() {
+  return llvm::makeArrayRef(g_process_attac

[Lldb-commits] [PATCH] D143104: [lldb/Plugins] Add Attach capabilities to ScriptedProcess

2023-03-03 Thread Med Ismail Bennani via Phabricator via lldb-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb9d4c94a603d: [lldb/Plugins] Add Attach capabilities to 
ScriptedProcess (authored by mib).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D143104/new/

https://reviews.llvm.org/D143104

Files:
  lldb/bindings/python/python-swigsafecast.swig
  lldb/bindings/python/python-wrapper.swig
  lldb/examples/python/scripted_process/scripted_process.py
  lldb/include/lldb/API/SBAttachInfo.h
  lldb/include/lldb/API/SBLaunchInfo.h
  lldb/include/lldb/Host/ProcessLaunchInfo.h
  lldb/include/lldb/Interpreter/ScriptInterpreter.h
  lldb/include/lldb/Interpreter/ScriptedMetadata.h
  lldb/include/lldb/Interpreter/ScriptedProcessInterface.h
  lldb/include/lldb/Target/Process.h
  lldb/include/lldb/Target/Target.h
  lldb/include/lldb/Utility/ProcessInfo.h
  lldb/include/lldb/lldb-forward.h
  lldb/source/API/SBAttachInfo.cpp
  lldb/source/API/SBLaunchInfo.cpp
  lldb/source/API/SBTarget.cpp
  lldb/source/Commands/CommandObjectPlatform.cpp
  lldb/source/Commands/CommandObjectProcess.cpp
  lldb/source/Host/common/ProcessLaunchInfo.cpp
  lldb/source/Interpreter/ScriptInterpreter.cpp
  lldb/source/Plugins/Process/scripted/ScriptedProcess.cpp
  lldb/source/Plugins/Process/scripted/ScriptedProcess.h
  lldb/source/Plugins/ScriptInterpreter/Python/SWIGPythonBridge.h
  
lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.cpp
  lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.h
  lldb/source/Plugins/ScriptInterpreter/Python/ScriptedPythonInterface.cpp
  lldb/source/Plugins/ScriptInterpreter/Python/ScriptedPythonInterface.h
  lldb/source/Target/Target.cpp
  lldb/source/Utility/ProcessInfo.cpp
  lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
  lldb/unittests/ScriptInterpreter/Python/PythonTestSuite.cpp

Index: lldb/unittests/ScriptInterpreter/Python/PythonTestSuite.cpp
===
--- lldb/unittests/ScriptInterpreter/Python/PythonTestSuite.cpp
+++ lldb/unittests/ScriptInterpreter/Python/PythonTestSuite.cpp
@@ -139,6 +139,14 @@
   return nullptr;
 }
 
+void *lldb_private::LLDBSWIGPython_CastPyObjectToSBAttachInfo(PyObject *data) {
+  return nullptr;
+}
+
+void *lldb_private::LLDBSWIGPython_CastPyObjectToSBLaunchInfo(PyObject *data) {
+  return nullptr;
+}
+
 void *lldb_private::LLDBSWIGPython_CastPyObjectToSBError(PyObject *data) {
   return nullptr;
 }
@@ -268,3 +276,13 @@
 python::PythonObject lldb_private::python::ToSWIGWrapper(const Status &status) {
   return python::PythonObject();
 }
+
+python::PythonObject
+lldb_private::python::ToSWIGWrapper(lldb::ProcessAttachInfoSP) {
+  return python::PythonObject();
+}
+
+python::PythonObject
+lldb_private::python::ToSWIGWrapper(lldb::ProcessLaunchInfoSP) {
+  return python::PythonObject();
+}
Index: lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
===
--- lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
+++ lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
@@ -137,8 +137,14 @@
 
 target_1 = self.dbg.CreateTarget(self.getBuildArtifact("a.out"))
 self.assertTrue(target_1, VALID_TARGET)
+
+# We still need to specify a PID when attaching even for scripted processes
+attach_info = lldb.SBAttachInfo(42)
+attach_info.SetProcessPluginName("ScriptedProcess")
+attach_info.SetScriptedProcessClassName("dummy_scripted_process.DummyScriptedProcess")
+
 error = lldb.SBError()
-process_1 = target_1.Launch(launch_info, error)
+process_1 = target_1.Attach(attach_info, error)
 self.assertTrue(process_1 and process_1.IsValid(), PROCESS_IS_VALID)
 self.assertEqual(process_1.GetProcessID(), 42)
 self.assertEqual(process_1.GetNumThreads(), 1)
Index: lldb/source/Utility/ProcessInfo.cpp
===
--- lldb/source/Utility/ProcessInfo.cpp
+++ lldb/source/Utility/ProcessInfo.cpp
@@ -8,6 +8,7 @@
 
 #include "lldb/Utility/ProcessInfo.h"
 
+#include "lldb/Interpreter/ScriptedMetadata.h"
 #include "lldb/Utility/ArchSpec.h"
 #include "lldb/Utility/Stream.h"
 #include "lldb/Utility/StreamString.h"
@@ -36,6 +37,7 @@
   m_gid = UINT32_MAX;
   m_arch.Clear();
   m_pid = LLDB_INVALID_PROCESS_ID;
+  m_scripted_metadata_sp.reset();
 }
 
 const char *ProcessInfo::GetName() const {
@@ -109,6 +111,10 @@
   }
 }
 
+bool ProcessInfo::IsScriptedProcess() const {
+  return m_scripted_metadata_sp && *m_scripted_metadata_sp;
+}
+
 void ProcessInstanceInfo::Dump(Stream &s, UserIDResolver &resolver) const {
   if (m_pid != LLDB_INVALID_PROCESS_ID)
 s.Printf("pid = %" PRIu64 "\n", m_pid);
Index: lldb/source/Target/Target.cpp

[Lldb-commits] [PATCH] D145260: [lldb/swig] Fix ref counting issue in SBProcess::GetScriptedImplementation

2023-03-03 Thread Med Ismail Bennani via Phabricator via lldb-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGebdbc26a3e79: [lldb/swig] Fix ref counting issue in 
SBProcess::GetScriptedImplementation (authored by mib).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D145260/new/

https://reviews.llvm.org/D145260

Files:
  lldb/bindings/python/python-typemaps.swig
  lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py


Index: lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
===
--- lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
+++ lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
@@ -80,6 +80,15 @@
 self.assertEqual(process.GetProcessID(), 666)
 self.assertEqual(process.GetNumThreads(), 0)
 
+impl = process.GetScriptedImplementation()
+self.assertTrue(impl)
+impl = process.GetScriptedImplementation()
+self.assertTrue(impl)
+impl = process.GetScriptedImplementation()
+self.assertTrue(impl)
+impl = process.GetScriptedImplementation()
+self.assertTrue(impl)
+
 addr = 0x5
 buff = process.ReadMemory(addr, 4, error)
 self.assertEqual(buff, None)
Index: lldb/bindings/python/python-typemaps.swig
===
--- lldb/bindings/python/python-typemaps.swig
+++ lldb/bindings/python/python-typemaps.swig
@@ -61,6 +61,8 @@
   if (!$result) {
 $result = Py_None;
 Py_INCREF(Py_None);
+  } else {
+Py_INCREF($result);
   }
 }
 


Index: lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
===
--- lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
+++ lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
@@ -80,6 +80,15 @@
 self.assertEqual(process.GetProcessID(), 666)
 self.assertEqual(process.GetNumThreads(), 0)
 
+impl = process.GetScriptedImplementation()
+self.assertTrue(impl)
+impl = process.GetScriptedImplementation()
+self.assertTrue(impl)
+impl = process.GetScriptedImplementation()
+self.assertTrue(impl)
+impl = process.GetScriptedImplementation()
+self.assertTrue(impl)
+
 addr = 0x5
 buff = process.ReadMemory(addr, 4, error)
 self.assertEqual(buff, None)
Index: lldb/bindings/python/python-typemaps.swig
===
--- lldb/bindings/python/python-typemaps.swig
+++ lldb/bindings/python/python-typemaps.swig
@@ -61,6 +61,8 @@
   if (!$result) {
 $result = Py_None;
 Py_INCREF(Py_None);
+  } else {
+Py_INCREF($result);
   }
 }
 
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D144237: [lldb/Plugins] Add memory writing capabilities to Scripted Process

2023-03-03 Thread Med Ismail Bennani via Phabricator via lldb-commits
mib closed this revision.
mib added a comment.

Landed in f190ec688270 



CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D144237/new/

https://reviews.llvm.org/D144237

___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D144224: [lldb] Extend SWIG SBProcess interface with WriteMemoryAsCString method

2023-03-03 Thread Med Ismail Bennani via Phabricator via lldb-commits
mib closed this revision.
mib added a comment.

Landed in e6cac17b563f 



CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D144224/new/

https://reviews.llvm.org/D144224

___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] c0b4ca1 - [lldb] Simplify error string in ScriptedInterface (NFC)

2023-03-03 Thread Med Ismail Bennani via lldb-commits

Author: Med Ismail Bennani
Date: 2023-03-03T20:18:28-08:00
New Revision: c0b4ca107a3b605f810bd60642907e6a77f7c6d3

URL: 
https://github.com/llvm/llvm-project/commit/c0b4ca107a3b605f810bd60642907e6a77f7c6d3
DIFF: 
https://github.com/llvm/llvm-project/commit/c0b4ca107a3b605f810bd60642907e6a77f7c6d3.diff

LOG: [lldb] Simplify error string in ScriptedInterface (NFC)

Signed-off-by: Med Ismail Bennani 

Added: 


Modified: 
lldb/include/lldb/Interpreter/ScriptedInterface.h

Removed: 




diff  --git a/lldb/include/lldb/Interpreter/ScriptedInterface.h 
b/lldb/include/lldb/Interpreter/ScriptedInterface.h
index 10a9f418df80..8785e31f7b93 100644
--- a/lldb/include/lldb/Interpreter/ScriptedInterface.h
+++ b/lldb/include/lldb/Interpreter/ScriptedInterface.h
@@ -51,22 +51,13 @@ class ScriptedInterface {
 
   template 
   bool CheckStructuredDataObject(llvm::StringRef caller, T obj, Status &error) 
{
-if (!obj) {
-  return ErrorWithMessage(caller,
-llvm::Twine("Null StructuredData object (" 
+
-llvm::Twine(error.AsCString()) 
+
-llvm::Twine(")."))
-.str(),
+if (!obj)
+  return ErrorWithMessage(caller, "Null Structured Data object",
 error);
-}
 
 if (!obj->IsValid()) {
-  return ErrorWithMessage(
-  caller,
-  llvm::Twine("Invalid StructuredData object (" +
-  llvm::Twine(error.AsCString()) + llvm::Twine(")."))
-  .str(),
-  error);
+  return ErrorWithMessage(caller, "Invalid StructuredData object",
+error);
 }
 
 if (error.Fail())



___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D145294: [lldb/API] Introduce SBProcess::ForceScriptedState method

2023-03-03 Thread Med Ismail Bennani via Phabricator via lldb-commits
mib created this revision.
mib added reviewers: bulbazord, JDevlieghere, jingham.
mib added a project: LLDB.
Herald added a project: All.
mib requested review of this revision.
Herald added a subscriber: lldb-commits.

This patch introduces a new method to the SBProcess API called
ForceScriptedState. As the name suggests, this affordance will allow the
user to alter the private state of the scripted process programatically.

This is necessary to update the scripted process state when perform
interactive debugging.

Signed-off-by: Med Ismail Bennani 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D145294

Files:
  lldb/include/lldb/API/SBProcess.h
  lldb/include/lldb/Target/Process.h
  lldb/source/API/SBProcess.cpp
  lldb/source/Plugins/Process/scripted/ScriptedProcess.h


Index: lldb/source/Plugins/Process/scripted/ScriptedProcess.h
===
--- lldb/source/Plugins/Process/scripted/ScriptedProcess.h
+++ lldb/source/Plugins/Process/scripted/ScriptedProcess.h
@@ -88,6 +88,10 @@
 
   void *GetImplementation() override;
 
+  void ForceScriptedState(lldb::StateType state) override {
+SetPrivateState(state);
+  }
+
 protected:
   ScriptedProcess(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp,
   const ScriptedMetadata &scripted_metadata, Status &error);
Index: lldb/source/API/SBProcess.cpp
===
--- lldb/source/API/SBProcess.cpp
+++ lldb/source/API/SBProcess.cpp
@@ -466,6 +466,16 @@
   return sb_event;
 }
 
+void SBProcess::ForceScriptedState(StateType new_state) {
+  LLDB_INSTRUMENT_VA(this, new_state);
+
+  if (ProcessSP process_sp = GetSP()) {
+std::lock_guard guard(
+process_sp->GetTarget().GetAPIMutex());
+process_sp->ForceScriptedState(new_state);
+  }
+}
+
 StateType SBProcess::GetState() {
   LLDB_INSTRUMENT_VA(this);
 
Index: lldb/include/lldb/Target/Process.h
===
--- lldb/include/lldb/Target/Process.h
+++ lldb/include/lldb/Target/Process.h
@@ -2544,6 +2544,8 @@
 
   virtual void *GetImplementation() { return nullptr; }
 
+  virtual void ForceScriptedState(lldb::StateType state) {}
+
 protected:
   friend class Trace;
 
Index: lldb/include/lldb/API/SBProcess.h
===
--- lldb/include/lldb/API/SBProcess.h
+++ lldb/include/lldb/API/SBProcess.h
@@ -187,6 +187,14 @@
   ///   The stop event corresponding to stop ID.
   lldb::SBEvent GetStopEventForStopID(uint32_t stop_id);
 
+  /// If the process is a scripted process, changes its private state.
+  /// No-op otherwise.
+  ///
+  /// \param [in] new_state
+  ///   The new private state that the scripted process should be set to.
+  ///
+  void ForceScriptedState(StateType new_state);
+
   size_t ReadMemory(addr_t addr, void *buf, size_t size, lldb::SBError &error);
 
   size_t WriteMemory(addr_t addr, const void *buf, size_t size,


Index: lldb/source/Plugins/Process/scripted/ScriptedProcess.h
===
--- lldb/source/Plugins/Process/scripted/ScriptedProcess.h
+++ lldb/source/Plugins/Process/scripted/ScriptedProcess.h
@@ -88,6 +88,10 @@
 
   void *GetImplementation() override;
 
+  void ForceScriptedState(lldb::StateType state) override {
+SetPrivateState(state);
+  }
+
 protected:
   ScriptedProcess(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp,
   const ScriptedMetadata &scripted_metadata, Status &error);
Index: lldb/source/API/SBProcess.cpp
===
--- lldb/source/API/SBProcess.cpp
+++ lldb/source/API/SBProcess.cpp
@@ -466,6 +466,16 @@
   return sb_event;
 }
 
+void SBProcess::ForceScriptedState(StateType new_state) {
+  LLDB_INSTRUMENT_VA(this, new_state);
+
+  if (ProcessSP process_sp = GetSP()) {
+std::lock_guard guard(
+process_sp->GetTarget().GetAPIMutex());
+process_sp->ForceScriptedState(new_state);
+  }
+}
+
 StateType SBProcess::GetState() {
   LLDB_INSTRUMENT_VA(this);
 
Index: lldb/include/lldb/Target/Process.h
===
--- lldb/include/lldb/Target/Process.h
+++ lldb/include/lldb/Target/Process.h
@@ -2544,6 +2544,8 @@
 
   virtual void *GetImplementation() { return nullptr; }
 
+  virtual void ForceScriptedState(lldb::StateType state) {}
+
 protected:
   friend class Trace;
 
Index: lldb/include/lldb/API/SBProcess.h
===
--- lldb/include/lldb/API/SBProcess.h
+++ lldb/include/lldb/API/SBProcess.h
@@ -187,6 +187,14 @@
   ///   The stop event corresponding to stop ID.
   lldb::SBEvent GetStopEventForStopID(uint32_t stop_id);
 
+  /// If the process is a scripted process, changes its private state.
+  /// No-op otherwise.
+  ///
+  /// \param [in] new_state
+  ///  

[Lldb-commits] [PATCH] D145295: [lldb] Move ScriptedProcess private state update to implementation

2023-03-03 Thread Med Ismail Bennani via Phabricator via lldb-commits
mib created this revision.
mib added reviewers: JDevlieghere, bulbazord.
mib added a project: LLDB.
Herald added a project: All.
mib requested review of this revision.
Herald added a subscriber: lldb-commits.

While debugging a Scripted Process, in order to update its state and
work nicely with lldb's execution model, it needs to toggle its private
state from running to stopped, which will result in broadcasting a
process state changed event to the debugger listener.

Originally, this state update was done systematically in the Scripted
Process C++ plugin, however in order to make scripted process
interactive, we need to be able to update their state dynamically.

This patch makes use of the recent addition of the
`SBProcess::ForceScriptedState` to programatically, and moves the
process private state update to the python implementation of the `resume`
method instead of doing it in `ScriptedProcess::DoResume`.

This patch also removes the unused `ShouldStop` & `Stop` scripted
process APIs, and adds new ScriptedInterface transform methods for
boolean arguments. This allow the user to programmatically decide if
after running the process, we should stop it (which is the default setting).

Signed-off-by: Med Ismail Bennani 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D145295

Files:
  lldb/examples/python/scripted_process/scripted_process.py
  lldb/include/lldb/Interpreter/ScriptedProcessInterface.h
  lldb/source/Plugins/Process/scripted/ScriptedProcess.cpp
  lldb/source/Plugins/Process/scripted/ScriptedProcess.h
  lldb/source/Plugins/ScriptInterpreter/Python/PythonDataObjects.h
  
lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.cpp
  lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.h
  lldb/source/Plugins/ScriptInterpreter/Python/ScriptedPythonInterface.h

Index: lldb/source/Plugins/ScriptInterpreter/Python/ScriptedPythonInterface.h
===
--- lldb/source/Plugins/ScriptInterpreter/Python/ScriptedPythonInterface.h
+++ lldb/source/Plugins/ScriptInterpreter/Python/ScriptedPythonInterface.h
@@ -113,6 +113,11 @@
 return {object};
   }
 
+  python::PythonObject Transform(bool arg) {
+// Boolean arguments need to be turned into python objects.
+return python::PythonBoolean(arg);
+  }
+
   python::PythonObject Transform(Status arg) {
 return python::ToSWIGWrapper(arg);
   }
@@ -141,6 +146,15 @@
 original_arg = ExtractValueFromPythonObject(transformed_arg, error);
   }
 
+  template <>
+  void ReverseTransform(bool &original_arg,
+python::PythonObject transformed_arg, Status &error) {
+python::PythonBoolean boolean_arg = python::PythonBoolean(
+python::PyRefType::Borrowed, transformed_arg.get());
+if (boolean_arg.IsValid())
+  original_arg = boolean_arg.GetValue();
+  }
+
   template 
   auto TransformTuple(const std::tuple &args,
   std::index_sequence) {
Index: lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.h
===
--- lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.h
+++ lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.h
@@ -37,10 +37,6 @@
 
   Status Resume() override;
 
-  bool ShouldStop() override;
-
-  Status Stop() override;
-
   std::optional
   GetMemoryRegionContainingAddress(lldb::addr_t address,
Status &error) override;
Index: lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.cpp
===
--- lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.cpp
+++ lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.cpp
@@ -80,21 +80,8 @@
 }
 
 Status ScriptedProcessPythonInterface::Resume() {
-  return GetStatusFromMethod("resume");
-}
-
-bool ScriptedProcessPythonInterface::ShouldStop() {
-  Status error;
-  StructuredData::ObjectSP obj = Dispatch("is_alive", error);
-
-  if (!CheckStructuredDataObject(LLVM_PRETTY_FUNCTION, obj, error))
-return {};
-
-  return obj->GetBooleanValue();
-}
-
-Status ScriptedProcessPythonInterface::Stop() {
-  return GetStatusFromMethod("stop");
+  // When calling ScriptedProcess.Resume from lldb we should always stop.
+  return GetStatusFromMethod("resume", /*should_stop=*/true);
 }
 
 std::optional
Index: lldb/source/Plugins/ScriptInterpreter/Python/PythonDataObjects.h
===
--- lldb/source/Plugins/ScriptInterpreter/Python/PythonDataObjects.h
+++ lldb/source/Plugins/ScriptInterpreter/Python/PythonDataObjects.h
@@ -201,6 +201,7 @@
 template <>
 struct PythonFormat : PassthroughFormat {};
 template <> struct PythonFormat : PassthroughFormat {};
+template <> struct PythonFormat : PassthroughFormat

[Lldb-commits] [PATCH] D145296: [lldb/Plugin] Add breakpoint setting support to ScriptedProcesses.

2023-03-03 Thread Med Ismail Bennani via Phabricator via lldb-commits
mib created this revision.
mib added reviewers: JDevlieghere, jingham.
mib added a project: LLDB.
Herald added a project: All.
mib requested review of this revision.
Herald added a subscriber: lldb-commits.

This patch adds support for breakpoint setting to Scripted Processes.

For now, Scripted Processes only support setting software breakpoints.

When doing interactive scripted process debugging, it makes use of the
memory writing capability to write the trap opcodes in the memory of the
driving process. However the real process' target doesn't keep track of
the breakpoints that got added by the scripted process. This is a design
that we might need to change in the future, since we'll probably need to
do some book keeping to handle breakpoints that were set by different
scripted processes.

Signed-off-by: Med Ismail Bennani 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D145296

Files:
  lldb/source/Plugins/Process/scripted/ScriptedProcess.cpp
  lldb/source/Plugins/Process/scripted/ScriptedProcess.h


Index: lldb/source/Plugins/Process/scripted/ScriptedProcess.h
===
--- lldb/source/Plugins/Process/scripted/ScriptedProcess.h
+++ lldb/source/Plugins/Process/scripted/ScriptedProcess.h
@@ -72,6 +72,8 @@
   size_t DoWriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
Status &error) override;
 
+  Status EnableBreakpointSite(BreakpointSite *bp_site) override;
+
   ArchSpec GetArchitecture();
 
   Status
Index: lldb/source/Plugins/Process/scripted/ScriptedProcess.cpp
===
--- lldb/source/Plugins/Process/scripted/ScriptedProcess.cpp
+++ lldb/source/Plugins/Process/scripted/ScriptedProcess.cpp
@@ -267,6 +267,20 @@
   return bytes_written;
 }
 
+Status ScriptedProcess::EnableBreakpointSite(BreakpointSite *bp_site) {
+  assert(bp_site != nullptr);
+
+  if (bp_site->IsEnabled()) {
+return {};
+  }
+
+  if (bp_site->HardwareRequired()) {
+return Status("Scripted Processes don't support hardware breakpoints");
+  }
+
+  return EnableSoftwareBreakpoint(bp_site);
+}
+
 ArchSpec ScriptedProcess::GetArchitecture() {
   return GetTarget().GetArchitecture();
 }


Index: lldb/source/Plugins/Process/scripted/ScriptedProcess.h
===
--- lldb/source/Plugins/Process/scripted/ScriptedProcess.h
+++ lldb/source/Plugins/Process/scripted/ScriptedProcess.h
@@ -72,6 +72,8 @@
   size_t DoWriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
Status &error) override;
 
+  Status EnableBreakpointSite(BreakpointSite *bp_site) override;
+
   ArchSpec GetArchitecture();
 
   Status
Index: lldb/source/Plugins/Process/scripted/ScriptedProcess.cpp
===
--- lldb/source/Plugins/Process/scripted/ScriptedProcess.cpp
+++ lldb/source/Plugins/Process/scripted/ScriptedProcess.cpp
@@ -267,6 +267,20 @@
   return bytes_written;
 }
 
+Status ScriptedProcess::EnableBreakpointSite(BreakpointSite *bp_site) {
+  assert(bp_site != nullptr);
+
+  if (bp_site->IsEnabled()) {
+return {};
+  }
+
+  if (bp_site->HardwareRequired()) {
+return Status("Scripted Processes don't support hardware breakpoints");
+  }
+
+  return EnableSoftwareBreakpoint(bp_site);
+}
+
 ArchSpec ScriptedProcess::GetArchitecture() {
   return GetTarget().GetArchitecture();
 }
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D145297: [lldb] Add an example of interactive scripted process debugging (NFC)

2023-03-03 Thread Med Ismail Bennani via Phabricator via lldb-commits
mib created this revision.
mib added reviewers: labath, JDevlieghere, jingham.
mib added a project: LLDB.
Herald added a project: All.
mib requested review of this revision.
Herald added a subscriber: lldb-commits.

This patch is a proof of concept that shows how a scripted process could
be used with real process to perform interactive debugging.

In this example, we run a process that spawns 10 threads. Then, we
create a intermediary scripted process who's job will be to wrap the
real process while intercepting it's process events and dispatching them
back either to the real process or to other child scripted processes.

In this example, we have 2 child scripted processes, with even and odd
thread indices. The goal is to be able to do thread filtering and
explore the various interactive debugging approaches, by letting a child
process running when stopping the other process and inspecting it.
Another approach would be to have the child processes execution in-sync
to force running every child process when one of them starts running.

Signed-off-by: Med Ismail Bennani 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D145297

Files:
  lldb/test/API/functionalities/interactive_scripted_process/Makefile
  
lldb/test/API/functionalities/interactive_scripted_process/interactive_scripted_process.py
  lldb/test/API/functionalities/interactive_scripted_process/main.cpp

Index: lldb/test/API/functionalities/interactive_scripted_process/main.cpp
===
--- /dev/null
+++ lldb/test/API/functionalities/interactive_scripted_process/main.cpp
@@ -0,0 +1,35 @@
+#include 
+#include 
+#include 
+#include 
+#include 
+
+void spawn_thread(int index) {
+  std::string name = "I'm thread " + std::to_string(index) + " !";
+  bool done = false;
+  std::string state = "Started execution!";
+  while (true) {
+if (done) // also break here
+  break;
+  }
+
+  state = "Stopped execution!";
+}
+
+int main() {
+  size_t num_threads = 10;
+  std::vector threads;
+
+  for (size_t i = 0; i < num_threads; i++) {
+threads.push_back(std::thread(spawn_thread, i));
+  }
+
+  std::cout << "Spawned " << threads.size() << " threads!"; // Break here
+
+  for (auto &t : threads) {
+if (t.joinable())
+  t.join();
+  }
+
+  return 0;
+}
Index: lldb/test/API/functionalities/interactive_scripted_process/interactive_scripted_process.py
===
--- /dev/null
+++ lldb/test/API/functionalities/interactive_scripted_process/interactive_scripted_process.py
@@ -0,0 +1,349 @@
+# Usage:
+# ./bin/lldb $LLVM/lldb/test/API/functionalities/interactive_scripted_process/main \
+#   -o "br set -p 'Break here'" -o "run" \
+#   -o "command script import
+#   $LLVM/lldb/test/API/functionalities/interactive_scripted_process/interactive_scripted_process.py" \
+#   -o "br set -p 'also break here'" -o 'continue'
+
+import os,json,struct,signal
+
+from threading import Thread
+from typing import Any, Dict
+
+import lldb
+from lldb.plugins.scripted_process import ScriptedProcess
+from lldb.plugins.scripted_process import ScriptedThread
+
+class PassthruScriptedProcess(ScriptedProcess):
+driving_target = None
+driving_process = None
+
+def __init__(self, exe_ctx: lldb.SBExecutionContext, args : lldb.SBStructuredData):
+super().__init__(exe_ctx, args)
+
+self.driving_target = None
+self.driving_process = None
+
+self.driving_target_idx = args.GetValueForKey("driving_target_idx")
+if (self.driving_target_idx and self.driving_target_idx.IsValid()):
+if self.driving_target_idx.GetType() == lldb.eStructuredDataTypeInteger:
+idx = self.driving_target_idx.GetIntegerValue(42)
+if self.driving_target_idx.GetType() == lldb.eStructuredDataTypeString:
+idx = int(self.driving_target_idx.GetStringValue(100))
+self.driving_target = self.target.GetDebugger().GetTargetAtIndex(idx)
+self.driving_process = self.driving_target.GetProcess()
+for driving_thread in self.driving_process:
+structured_data = lldb.SBStructuredData()
+structured_data.SetFromJSON(json.dumps({
+"driving_target_idx" : idx,
+"thread_idx" : driving_thread.GetIndexID()
+}))
+
+self.threads[driving_thread.GetThreadID()] = PassthruScriptedThread(self, structured_data)
+
+for module in self.driving_target.modules:
+path = module.file.fullpath
+load_addr = module.GetObjectFileHeaderAddress().GetLoadAddress(self.driving_target)
+self.loaded_images.append({"path": path, "load_addr": load_addr})
+
+def get_memory_region_containing_address(self, addr: int) -> lldb.SBMemoryRegionInfo:
+mem_region = lldb.SBMemoryRegionInfo()
+error = self.driving_process.GetMemoryR

[Lldb-commits] [PATCH] D145297: [lldb] Add an example of interactive scripted process debugging (NFC)

2023-03-03 Thread Med Ismail Bennani via Phabricator via lldb-commits
mib added a comment.

This depends on D145294 , D145295 
 & D145296  
so make sure you take a look at those diffs :)


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D145297/new/

https://reviews.llvm.org/D145297

___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits