[Lldb-commits] [lldb] [lldb] Add support for disabling frame recognizers (PR #109219)

2024-09-19 Thread via lldb-commits


@@ -957,53 +962,43 @@ PrintRecognizerDetails(Stream &strm, const std::string 
&name,
   llvm::interleaveComma(symbols, strm);
 }
 
-class CommandObjectFrameRecognizerDelete : public CommandObjectParsed {
-public:
-  CommandObjectFrameRecognizerDelete(CommandInterpreter &interpreter)
-  : CommandObjectParsed(interpreter, "frame recognizer delete",
-"Delete an existing frame recognizer by id.",
-nullptr) {
-AddSimpleArgumentList(eArgTypeRecognizerID);
-  }
-
-  ~CommandObjectFrameRecognizerDelete() override = default;
+// Base class for commands which accept a single frame recognizer as an 
argument
+class CommandObjectWithFrameRecognizerArg : public CommandObjectParsed {
+  public:
+CommandObjectWithFrameRecognizerArg(CommandInterpreter &interpreter,
+const char *name,
+const char *help = nullptr,
+const char *syntax = nullptr,
+uint32_t flags = 0)
+: CommandObjectParsed(interpreter, name, help, syntax, flags) {
+  AddSimpleArgumentList(eArgTypeRecognizerID);
+}
 
   void
   HandleArgumentCompletion(CompletionRequest &request,
OptionElementVector &opt_element_vector) override {
+std::cerr << request.GetCursorIndex() << std::endl;
 if (request.GetCursorIndex() != 0)
   return;
 
 GetTarget().GetFrameRecognizerManager().ForEach(
-[&request](uint32_t rid, std::string rname, std::string module,
+[&request](uint32_t rid, bool enabled, std::string rname, std::string 
module,
llvm::ArrayRef symbols,
Mangled::NamePreference symbol_mangling, bool regexp) {
   StreamString strm;
   if (rname.empty())
 rname = "(internal)";
 
-  PrintRecognizerDetails(strm, rname, module, symbols, symbol_mangling,
- regexp);
+  PrintRecognizerDetails(strm, rname, enabled, module, symbols,
+ symbol_mangling, regexp);
 
   request.TryCompleteCurrentArg(std::to_string(rid), strm.GetString());
 });
   }
 
-protected:
-  void DoExecute(Args &command, CommandReturnObject &result) override {
-if (command.GetArgumentCount() == 0) {
-  if (!m_interpreter.Confirm(
-  "About to delete all frame recognizers, do you want to do that?",
-  true)) {
-result.AppendMessage("Operation cancelled...");
-return;
-  }
-
-  GetTarget().GetFrameRecognizerManager().RemoveAllRecognizers();
-  result.SetStatus(eReturnStatusSuccessFinishResult);
-  return;
-}
+  virtual void DoExecuteWithId(CommandReturnObject &result, uint32_t 
recognizer_id) = 0;
 
+  void DoExecute(Args &command, CommandReturnObject &result) override {
 if (command.GetArgumentCount() != 1) {

jimingham wrote:

You didn't add this part, so feel free to ignore this comment, but if you pass 
`eArgRepeatOptional` to defaulted second parameter to AddSimpleArgumentList, 
you shouldn't need to do this check here.

https://github.com/llvm/llvm-project/pull/109219
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [lldb] Add support for disabling frame recognizers (PR #109219)

2024-09-19 Thread via lldb-commits

jimingham wrote:

This looks good to me so far, but of course it needs tests.

https://github.com/llvm/llvm-project/pull/109219
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] Improve type and namespace lookup using parent chain (PR #108907)

2024-09-19 Thread via lldb-commits


@@ -374,25 +377,40 @@ void DebugNamesDWARFIndex::GetFullyQualifiedType(
   m_fallback.GetFullyQualifiedType(context, callback);
 }
 
+bool DebugNamesDWARFIndex::SameAsEntryATName(
+llvm::StringRef query_name, const DebugNames::Entry &entry) const {
+  auto maybe_dieoffset = entry.getDIEUnitOffset();
+  if (!maybe_dieoffset)
+return false;
+
+  // [Optimization] instead of parsing the entry from dwo file, we simply
+  // check if the query_name can point to an entry of the same DIE offset.
+  // This greatly reduced number of dwo file parsed and thus improved the
+  // performance.
+  for (const DebugNames::Entry &query_entry :
+   entry.getNameIndex()->equal_range(query_name)) {
+auto query_dieoffset = query_entry.getDIEUnitOffset();
+if (!query_dieoffset)
+  continue;
+
+if (*query_dieoffset == *maybe_dieoffset) {
+  return true;
+} else if (*query_dieoffset > *maybe_dieoffset) {
+  // The pool entries of the same name are sequentially cluttered together
+  // so if the query name from `query_name` is after the target entry, this
+  // is definitely not the correct one, we can stop searching.
+  return false;
+}
+  }
+  return false;
+}
+
 bool DebugNamesDWARFIndex::SameParentChain(
 llvm::ArrayRef parent_names,
 llvm::ArrayRef parent_entries) const {
-
   if (parent_entries.size() != parent_names.size())
 return false;
 
-  auto SameAsEntryATName = [this](llvm::StringRef name,
-  const DebugNames::Entry &entry) {
-// Peek at the AT_name of `entry` and test equality to `name`.
-auto maybe_dieoffset = entry.getDIEUnitOffset();
-if (!maybe_dieoffset)
-  return false;
-DWARFUnit *unit = GetNonSkeletonUnit(entry);
-if (!unit)
-  return false;
-return name == unit->PeekDIEName(unit->GetOffset() + *maybe_dieoffset);

jeffreytan81 wrote:

@felipepiovezan , I am having trouble finding a context without split dwarf to 
measure the performance. Our target is way too big to build without split dwarf 
(linker error). I am trying to debug clang++ per your benchmark, but the 
evaluation is very fast `293ms` which I do not think it is slow enough to 
measure perf. How do you get 5~6 seconds from this? 

```
devbig623:~/llvm-sand/build/Debug/fbcode-x86_64/toolchain$ lldb -o "b 
CodeGenFunction::GenerateCode" -o r -o "timeit expr Fn" --  
~/llvm-sand/build/Debug/fbcode-x86_64/toolchain/bin/clang++ -std=c++17 -pthread 
-glldb -c ~/personal/main.cpp -o ~/personal/a
(lldb) target create 
"/home/jeffreytan/llvm-sand/build/Debug/fbcode-x86_64/toolchain/bin/clang++"
Current executable set to 
'/home/jeffreytan/llvm-sand/build/Debug/fbcode-x86_64/toolchain/bin/clang++' 
(x86_64).
(lldb) settings set -- target.run-args  "-std=c++17" "-pthread" "-glldb" "-c" 
"/home/jeffreytan/personal/main.cpp" "-o" "/home/jeffreytan/personal/a"
(lldb) b CodeGenFunction::GenerateCode
Breakpoint 1: where = 
clang++`clang::CodeGen::CodeGenFunction::GenerateCode(clang::GlobalDecl, 
llvm::Function*, clang::CodeGen::CGFunctionInfo const&) + 59 at 
CodeGenFunction.cpp:1440:3, address = 0x083c507b
(lldb) r
Process 233320 launched: 
'/home/jeffreytan/llvm-sand/build/Debug/fbcode-x86_64/toolchain/bin/clang++' 
(x86_64)
Process 233320 stopped
* thread #1, name = 'clang++', stop reason = breakpoint 1.1
frame #0: 0x5d91907b 
clang++`clang::CodeGen::CodeGenFunction::GenerateCode(this=0x7fff5bb0, 
GD=GlobalDecl @ 0x7fff5b48, Fn=0x02921787f228, 
FnInfo=0x029218308200) at CodeGenFunction.cpp:1440:3
   1437
   1438 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
   1439const CGFunctionInfo &FnInfo) {
-> 1440   assert(Fn && "generating code for null Function");
   1441   const FunctionDecl *FD = cast(GD.getDecl());
   1442   CurGD = GD;
   1443
(lldb) timeit expr Fn
(llvm::Function *) $0 = 0x02921787f228

time: 0m0.293s
```

https://github.com/llvm/llvm-project/pull/108907
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [lldb/Interpreter] Introduce `ScriptedStopHook{, Python}Interface` & make use of it (PR #105449)

2024-09-19 Thread Med Ismail Bennani via lldb-commits

https://github.com/medismailben updated 
https://github.com/llvm/llvm-project/pull/105449

>From 3387de37a8c0da9174653062b0804494d8ebf53e Mon Sep 17 00:00:00 2001
From: Med Ismail Bennani 
Date: Thu, 19 Sep 2024 23:29:13 -0700
Subject: [PATCH 1/3] [lldb/Interpreter] Create
 ScriptedStopHook{,Python}Interface (NFC)

This patch introduces a new scripted interface for ScriptedStopHooks.

This will be used in a follow-up patch to call into the script methods.

Signed-off-by: Med Ismail Bennani 
---
 .../Interfaces/ScriptedStopHookInterface.h| 33 
 .../lldb/Interpreter/ScriptInterpreter.h  |  4 +
 lldb/include/lldb/lldb-forward.h  |  3 +
 .../Python/Interfaces/CMakeLists.txt  |  1 +
 .../ScriptInterpreterPythonInterfaces.cpp |  2 +
 .../ScriptInterpreterPythonInterfaces.h   |  1 +
 .../ScriptedStopHookPythonInterface.cpp   | 75 +++
 .../ScriptedStopHookPythonInterface.h | 51 +
 .../Python/ScriptInterpreterPython.cpp|  5 ++
 .../Python/ScriptInterpreterPythonImpl.h  |  2 +
 10 files changed, 177 insertions(+)
 create mode 100644 
lldb/include/lldb/Interpreter/Interfaces/ScriptedStopHookInterface.h
 create mode 100644 
lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/ScriptedStopHookPythonInterface.cpp
 create mode 100644 
lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/ScriptedStopHookPythonInterface.h

diff --git 
a/lldb/include/lldb/Interpreter/Interfaces/ScriptedStopHookInterface.h 
b/lldb/include/lldb/Interpreter/Interfaces/ScriptedStopHookInterface.h
new file mode 100644
index 00..125e7f2077b543
--- /dev/null
+++ b/lldb/include/lldb/Interpreter/Interfaces/ScriptedStopHookInterface.h
@@ -0,0 +1,33 @@
+//===-- ScriptedStopHookInterface.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_INTERPRETER_INTERFACES_SCRIPTEDSTOPHOOKINTERFACE_H
+#define LLDB_INTERPRETER_INTERFACES_SCRIPTEDSTOPHOOKINTERFACE_H
+
+#include "lldb/lldb-private.h"
+
+#include "ScriptedInterface.h"
+
+namespace lldb_private {
+class ScriptedStopHookInterface : public ScriptedInterface {
+public:
+  virtual llvm::Expected
+  CreatePluginObject(llvm::StringRef class_name, lldb::TargetSP target_sp,
+ const StructuredDataImpl &args_sp) = 0;
+
+  /// "handle_stop" will return a bool with the meaning "should_stop"...
+  /// If nothing is returned, we'll assume we are going to stop.
+  /// Also any errors should return true, since we should stop on error.
+  virtual llvm::Expected HandleStop(ExecutionContext &exe_ctx,
+  lldb::StreamSP output_sp) {
+return true;
+  }
+};
+} // namespace lldb_private
+
+#endif // LLDB_INTERPRETER_INTERFACES_SCRIPTEDSTOPHOOKINTERFACE_H
diff --git a/lldb/include/lldb/Interpreter/ScriptInterpreter.h 
b/lldb/include/lldb/Interpreter/ScriptInterpreter.h
index addb1394ab5652..8fabe6f250b084 100644
--- a/lldb/include/lldb/Interpreter/ScriptInterpreter.h
+++ b/lldb/include/lldb/Interpreter/ScriptInterpreter.h
@@ -561,6 +561,10 @@ class ScriptInterpreter : public PluginInterface {
 return {};
   }
 
+  virtual lldb::ScriptedStopHookInterfaceSP CreateScriptedStopHookInterface() {
+return {};
+  }
+
   virtual StructuredData::ObjectSP
   CreateStructuredDataFromScriptObject(ScriptObject obj) {
 return {};
diff --git a/lldb/include/lldb/lldb-forward.h b/lldb/include/lldb/lldb-forward.h
index 5fb288ad43af48..d09edeeccaff1a 100644
--- a/lldb/include/lldb/lldb-forward.h
+++ b/lldb/include/lldb/lldb-forward.h
@@ -190,6 +190,7 @@ class ScriptInterpreterLocker;
 class ScriptedMetadata;
 class ScriptedPlatformInterface;
 class ScriptedProcessInterface;
+class ScriptedStopHookInterface;
 class ScriptedThreadInterface;
 class ScriptedThreadPlanInterface;
 class ScriptedSyntheticChildren;
@@ -408,6 +409,8 @@ typedef 
std::unique_ptr
 ScriptedPlatformInterfaceUP;
 typedef std::unique_ptr
 ScriptedProcessInterfaceUP;
+typedef std::shared_ptr
+ScriptedStopHookInterfaceSP;
 typedef std::shared_ptr
 ScriptedThreadInterfaceSP;
 typedef std::shared_ptr
diff --git 
a/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/CMakeLists.txt 
b/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/CMakeLists.txt
index 6ba714ed1c263e..ee5e48ad5cdc37 100644
--- a/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/CMakeLists.txt
+++ b/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/CMakeLists.txt
@@ -25,6 +25,7 @@ add_lldb_library(lldbPluginScriptInterpreterPythonInterfaces 
PLUGIN
   ScriptedPlatformPythonInterface.cpp
   ScriptedProcessPythonInterface.cpp
   ScriptedPythonInterface.cpp
+  ScriptedStopHookPythonInterface.cp

[Lldb-commits] [lldb] 1e131dd - [lldb/Interpreter] Introduce `ScriptedStopHook{, Python}Interface` & make use of it (#105449)

2024-09-19 Thread via lldb-commits

Author: Med Ismail Bennani
Date: 2024-09-19T23:35:34-07:00
New Revision: 1e131ddfa8f1d7b18c85c6e4079458be8b419421

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

LOG: [lldb/Interpreter] Introduce `ScriptedStopHook{,Python}Interface` & make 
use of it (#105449)

This patch introduces new `ScriptedStopHook{,Python}Interface` classes
that make use of the Scripted Interface infrastructure and makes use of
it in `StopHookScripted`.

It also relax the requirement on the number of argument for initializing
scripting extension if the size of the interface parameter pack contains
1 less element than the extension maximum number of positional arguments
for this initializer.
This addresses the cases where the embedded interpreter session
dictionary is passed to the extension initializer which is not used most
of the time.

-

Signed-off-by: Med Ismail Bennani 

Added: 
lldb/include/lldb/Interpreter/Interfaces/ScriptedStopHookInterface.h

lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/ScriptedStopHookPythonInterface.cpp

lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/ScriptedStopHookPythonInterface.h

Modified: 
lldb/bindings/python/python-wrapper.swig
lldb/include/lldb/API/SBExecutionContext.h
lldb/include/lldb/Interpreter/ScriptInterpreter.h
lldb/include/lldb/Target/Target.h
lldb/include/lldb/lldb-forward.h
lldb/source/Interpreter/ScriptInterpreter.cpp
lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/CMakeLists.txt

lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/ScriptInterpreterPythonInterfaces.cpp

lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/ScriptInterpreterPythonInterfaces.h

lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/ScriptedPythonInterface.cpp

lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/ScriptedPythonInterface.h
lldb/source/Plugins/ScriptInterpreter/Python/SWIGPythonBridge.h
lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp
lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPythonImpl.h
lldb/source/Target/Target.cpp
lldb/test/API/commands/target/stop-hooks/TestStopHookScripted.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-wrapper.swig 
b/lldb/bindings/python/python-wrapper.swig
index 810673aaec5d19..961fb2d1a76178 100644
--- a/lldb/bindings/python/python-wrapper.swig
+++ b/lldb/bindings/python/python-wrapper.swig
@@ -301,104 +301,6 @@ unsigned int 
lldb_private::python::SWIGBridge::LLDBSwigPythonCallBreakpointResol
   return ret_val;
 }
 
-PythonObject 
lldb_private::python::SWIGBridge::LLDBSwigPythonCreateScriptedStopHook(
-lldb::TargetSP target_sp, const char *python_class_name,
-const char *session_dictionary_name, const StructuredDataImpl &args_impl,
-Status &error) {
-  if (python_class_name == NULL || python_class_name[0] == '\0') {
-error = Status::FromErrorString("Empty class name.");
-return PythonObject();
-  }
-  if (!session_dictionary_name) {
-error = Status::FromErrorString("No session dictionary");
-return PythonObject();
-  }
-
-  PyErr_Cleaner py_err_cleaner(true);
-
-  auto dict = PythonModule::MainModule().ResolveName(
-  session_dictionary_name);
-  auto pfunc = PythonObject::ResolveNameWithDictionary(
-  python_class_name, dict);
-
-  if (!pfunc.IsAllocated()) {
-error = Status::FromErrorStringWithFormat("Could not find class: %s.",
-   python_class_name);
-return PythonObject();
-  }
-
-  PythonObject result =
-  pfunc(SWIGBridge::ToSWIGWrapper(target_sp), 
SWIGBridge::ToSWIGWrapper(args_impl), dict);
-
-  if (result.IsAllocated()) {
-// Check that the handle_stop callback is defined:
-auto callback_func = result.ResolveName("handle_stop");
-if (callback_func.IsAllocated()) {
-  if (auto args_info = callback_func.GetArgInfo()) {
-size_t num_args = (*args_info).max_positional_args;
-if (num_args != 2) {
-  error = Status::FromErrorStringWithFormat(
-  "Wrong number of args for "
-  "handle_stop callback, should be 2 (excluding self), got: %zu",
-  num_args);
-  return PythonObject();
-} else
-  return result;
-  } else {
-error = Status::FromErrorString(
-"Couldn't get num arguments for handle_stop "
-"callback.");
-return PythonObject();
-  }
-  return result;
-} else {
-  error = Status::FromErrorStringWithFormat(
-  "Class \"%s\" is missing the required "
-  "handle_stop cal

[Lldb-commits] [lldb] [lldb/Interpreter] Introduce `ScriptedStopHook{, Python}Interface` & make use of it (PR #105449)

2024-09-19 Thread Med Ismail Bennani via lldb-commits

https://github.com/medismailben closed 
https://github.com/llvm/llvm-project/pull/105449
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [lldb] Inline expression evaluator error visualization (PR #106470)

2024-09-19 Thread Adrian Prantl via lldb-commits

https://github.com/adrian-prantl updated 
https://github.com/llvm/llvm-project/pull/106470

>From 8c682fc70bff5c6dff43c4601c14e5e61d11a08f Mon Sep 17 00:00:00 2001
From: Adrian Prantl 
Date: Wed, 28 Aug 2024 10:04:33 -0700
Subject: [PATCH 1/2] [lldb] Store expression evaluator diagnostics in an
 llvm::Error (NFC)

This patch is a reworking of Pete Lawrence's (@PortalPete) proposal
for better expression evaluator error messages:
https://github.com/llvm/llvm-project/pull/80938

This patch is preparatory patch for improving the rendering of
expression evaluator diagnostics. Currently diagnostics are rendered
into a string and the command interpreter layer then textually parses
words like "error:" to (sometimes) color the output accordingly. In
order to enable user interfaces to do better with diagnostics, we need
to store them in a machine-readable fromat. This patch does this by
adding a new llvm::Error kind wrapping a DiagnosticDetail struct that
is used when the error type is eErrorTypeExpression. Multiple
diagnostics are modeled using llvm::ErrorList.

Right now the extra information is not used by the CommandInterpreter,
this will be added in a follow-up patch!
---
 .../lldb/Expression/DiagnosticManager.h   | 91 +-
 lldb/include/lldb/Utility/Status.h|  5 +-
 lldb/source/Breakpoint/BreakpointLocation.cpp | 10 +-
 lldb/source/Expression/DiagnosticManager.cpp  | 94 +++
 lldb/source/Expression/ExpressionParser.cpp   |  5 +-
 lldb/source/Expression/UserExpression.cpp | 32 ---
 lldb/source/Expression/UtilityFunction.cpp| 16 ++--
 .../ExpressionParser/Clang/ClangDiagnostic.h  |  5 +-
 .../Clang/ClangExpressionParser.cpp   | 69 ++
 .../Clang/ClangUserExpression.h   |  2 +
 .../Plugins/Platform/POSIX/PlatformPOSIX.cpp  | 10 +-
 .../Platform/Windows/PlatformWindows.cpp  | 10 +-
 lldb/source/Target/Target.cpp |  2 +-
 lldb/source/Utility/Status.cpp|  8 ++
 .../TestModulesCompileError.py|  2 +-
 .../Expression/DiagnosticManagerTest.cpp  | 22 +++--
 lldb/unittests/Utility/StatusTest.cpp |  2 +-
 17 files changed, 267 insertions(+), 118 deletions(-)

diff --git a/lldb/include/lldb/Expression/DiagnosticManager.h 
b/lldb/include/lldb/Expression/DiagnosticManager.h
index d49b7c99b114fb..1c0763eea92f05 100644
--- a/lldb/include/lldb/Expression/DiagnosticManager.h
+++ b/lldb/include/lldb/Expression/DiagnosticManager.h
@@ -12,6 +12,9 @@
 #include "lldb/lldb-defines.h"
 #include "lldb/lldb-types.h"
 
+#include "lldb/Utility/FileSpec.h"
+#include "lldb/Utility/Status.h"
+
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringRef.h"
 
@@ -20,6 +23,52 @@
 
 namespace lldb_private {
 
+/// A compiler-independent representation of a Diagnostic. Expression
+/// evaluation failures often have more than one diagnostic that a UI
+/// layer might want to render differently, for example to colorize
+/// it.
+///
+/// Running example:
+///   (lldb) expr 1+foo
+///   error: :1:3: use of undeclared identifier 'foo'
+///   1+foo
+/// ^
+struct DiagnosticDetail {
+  struct SourceLocation {
+FileSpec file;
+unsigned line = 0;
+uint16_t column = 0;
+uint16_t length = 0;
+bool in_user_input = false;
+  };
+  /// Contains {{}, 1, 3, 3, true} in the example above.
+  std::optional source_location;
+  /// Contains eSeverityError in the example above.
+  lldb::Severity severity = lldb::eSeverityInfo;
+  /// Contains "use of undeclared identifier 'x'" in the example above.
+  std::string message;
+  /// Contains the fully rendered error message.
+  std::string rendered;
+};
+
+/// An llvm::Error used to communicate diagnostics in Status. Multiple
+/// diagnostics may be chained in an llvm::ErrorList.
+class DetailedExpressionError
+: public llvm::ErrorInfo {
+  DiagnosticDetail m_detail;
+
+public:
+  using llvm::ErrorInfo::ErrorInfo;
+  DetailedExpressionError(DiagnosticDetail detail) : m_detail(detail) {}
+  std::string message() const override;
+  DiagnosticDetail GetDetail() const { return m_detail; }
+  std::error_code convertToErrorCode() const override;
+  void log(llvm::raw_ostream &OS) const override;
+  std::unique_ptr Clone() const override;
+
+  static char ID;
+};
+
 enum DiagnosticOrigin {
   eDiagnosticOriginUnknown = 0,
   eDiagnosticOriginLLDB,
@@ -49,37 +98,28 @@ class Diagnostic {
 }
   }
 
-  Diagnostic(llvm::StringRef message, lldb::Severity severity,
- DiagnosticOrigin origin, uint32_t compiler_id)
-  : m_message(message), m_severity(severity), m_origin(origin),
-m_compiler_id(compiler_id) {}
-
-  Diagnostic(const Diagnostic &rhs)
-  : m_message(rhs.m_message), m_severity(rhs.m_severity),
-m_origin(rhs.m_origin), m_compiler_id(rhs.m_compiler_id) {}
+  Diagnostic(DiagnosticOrigin origin, uint32_t compiler_id,
+ DiagnosticDetail detail)
+  : m_origin(origin), m_compiler_id(compiler_id), 

[Lldb-commits] [lldb] [lldb] Inline expression evaluator error visualization (PR #106470)

2024-09-19 Thread Adrian Prantl via lldb-commits

https://github.com/adrian-prantl ready_for_review 
https://github.com/llvm/llvm-project/pull/106470
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [lldb] Inline expression evaluator error visualization (PR #106470)

2024-09-19 Thread Adrian Prantl via lldb-commits

https://github.com/adrian-prantl updated 
https://github.com/llvm/llvm-project/pull/106470

>From 8c682fc70bff5c6dff43c4601c14e5e61d11a08f Mon Sep 17 00:00:00 2001
From: Adrian Prantl 
Date: Wed, 28 Aug 2024 10:04:33 -0700
Subject: [PATCH 1/2] [lldb] Store expression evaluator diagnostics in an
 llvm::Error (NFC)

This patch is a reworking of Pete Lawrence's (@PortalPete) proposal
for better expression evaluator error messages:
https://github.com/llvm/llvm-project/pull/80938

This patch is preparatory patch for improving the rendering of
expression evaluator diagnostics. Currently diagnostics are rendered
into a string and the command interpreter layer then textually parses
words like "error:" to (sometimes) color the output accordingly. In
order to enable user interfaces to do better with diagnostics, we need
to store them in a machine-readable fromat. This patch does this by
adding a new llvm::Error kind wrapping a DiagnosticDetail struct that
is used when the error type is eErrorTypeExpression. Multiple
diagnostics are modeled using llvm::ErrorList.

Right now the extra information is not used by the CommandInterpreter,
this will be added in a follow-up patch!
---
 .../lldb/Expression/DiagnosticManager.h   | 91 +-
 lldb/include/lldb/Utility/Status.h|  5 +-
 lldb/source/Breakpoint/BreakpointLocation.cpp | 10 +-
 lldb/source/Expression/DiagnosticManager.cpp  | 94 +++
 lldb/source/Expression/ExpressionParser.cpp   |  5 +-
 lldb/source/Expression/UserExpression.cpp | 32 ---
 lldb/source/Expression/UtilityFunction.cpp| 16 ++--
 .../ExpressionParser/Clang/ClangDiagnostic.h  |  5 +-
 .../Clang/ClangExpressionParser.cpp   | 69 ++
 .../Clang/ClangUserExpression.h   |  2 +
 .../Plugins/Platform/POSIX/PlatformPOSIX.cpp  | 10 +-
 .../Platform/Windows/PlatformWindows.cpp  | 10 +-
 lldb/source/Target/Target.cpp |  2 +-
 lldb/source/Utility/Status.cpp|  8 ++
 .../TestModulesCompileError.py|  2 +-
 .../Expression/DiagnosticManagerTest.cpp  | 22 +++--
 lldb/unittests/Utility/StatusTest.cpp |  2 +-
 17 files changed, 267 insertions(+), 118 deletions(-)

diff --git a/lldb/include/lldb/Expression/DiagnosticManager.h 
b/lldb/include/lldb/Expression/DiagnosticManager.h
index d49b7c99b114fb..1c0763eea92f05 100644
--- a/lldb/include/lldb/Expression/DiagnosticManager.h
+++ b/lldb/include/lldb/Expression/DiagnosticManager.h
@@ -12,6 +12,9 @@
 #include "lldb/lldb-defines.h"
 #include "lldb/lldb-types.h"
 
+#include "lldb/Utility/FileSpec.h"
+#include "lldb/Utility/Status.h"
+
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringRef.h"
 
@@ -20,6 +23,52 @@
 
 namespace lldb_private {
 
+/// A compiler-independent representation of a Diagnostic. Expression
+/// evaluation failures often have more than one diagnostic that a UI
+/// layer might want to render differently, for example to colorize
+/// it.
+///
+/// Running example:
+///   (lldb) expr 1+foo
+///   error: :1:3: use of undeclared identifier 'foo'
+///   1+foo
+/// ^
+struct DiagnosticDetail {
+  struct SourceLocation {
+FileSpec file;
+unsigned line = 0;
+uint16_t column = 0;
+uint16_t length = 0;
+bool in_user_input = false;
+  };
+  /// Contains {{}, 1, 3, 3, true} in the example above.
+  std::optional source_location;
+  /// Contains eSeverityError in the example above.
+  lldb::Severity severity = lldb::eSeverityInfo;
+  /// Contains "use of undeclared identifier 'x'" in the example above.
+  std::string message;
+  /// Contains the fully rendered error message.
+  std::string rendered;
+};
+
+/// An llvm::Error used to communicate diagnostics in Status. Multiple
+/// diagnostics may be chained in an llvm::ErrorList.
+class DetailedExpressionError
+: public llvm::ErrorInfo {
+  DiagnosticDetail m_detail;
+
+public:
+  using llvm::ErrorInfo::ErrorInfo;
+  DetailedExpressionError(DiagnosticDetail detail) : m_detail(detail) {}
+  std::string message() const override;
+  DiagnosticDetail GetDetail() const { return m_detail; }
+  std::error_code convertToErrorCode() const override;
+  void log(llvm::raw_ostream &OS) const override;
+  std::unique_ptr Clone() const override;
+
+  static char ID;
+};
+
 enum DiagnosticOrigin {
   eDiagnosticOriginUnknown = 0,
   eDiagnosticOriginLLDB,
@@ -49,37 +98,28 @@ class Diagnostic {
 }
   }
 
-  Diagnostic(llvm::StringRef message, lldb::Severity severity,
- DiagnosticOrigin origin, uint32_t compiler_id)
-  : m_message(message), m_severity(severity), m_origin(origin),
-m_compiler_id(compiler_id) {}
-
-  Diagnostic(const Diagnostic &rhs)
-  : m_message(rhs.m_message), m_severity(rhs.m_severity),
-m_origin(rhs.m_origin), m_compiler_id(rhs.m_compiler_id) {}
+  Diagnostic(DiagnosticOrigin origin, uint32_t compiler_id,
+ DiagnosticDetail detail)
+  : m_origin(origin), m_compiler_id(compiler_id), 

[Lldb-commits] [lldb] [lldb] Inline expression evaluator error visualization (PR #106470)

2024-09-19 Thread Adrian Prantl via lldb-commits

https://github.com/adrian-prantl updated 
https://github.com/llvm/llvm-project/pull/106470

>From 8c682fc70bff5c6dff43c4601c14e5e61d11a08f Mon Sep 17 00:00:00 2001
From: Adrian Prantl 
Date: Wed, 28 Aug 2024 10:04:33 -0700
Subject: [PATCH 1/2] [lldb] Store expression evaluator diagnostics in an
 llvm::Error (NFC)

This patch is a reworking of Pete Lawrence's (@PortalPete) proposal
for better expression evaluator error messages:
https://github.com/llvm/llvm-project/pull/80938

This patch is preparatory patch for improving the rendering of
expression evaluator diagnostics. Currently diagnostics are rendered
into a string and the command interpreter layer then textually parses
words like "error:" to (sometimes) color the output accordingly. In
order to enable user interfaces to do better with diagnostics, we need
to store them in a machine-readable fromat. This patch does this by
adding a new llvm::Error kind wrapping a DiagnosticDetail struct that
is used when the error type is eErrorTypeExpression. Multiple
diagnostics are modeled using llvm::ErrorList.

Right now the extra information is not used by the CommandInterpreter,
this will be added in a follow-up patch!
---
 .../lldb/Expression/DiagnosticManager.h   | 91 +-
 lldb/include/lldb/Utility/Status.h|  5 +-
 lldb/source/Breakpoint/BreakpointLocation.cpp | 10 +-
 lldb/source/Expression/DiagnosticManager.cpp  | 94 +++
 lldb/source/Expression/ExpressionParser.cpp   |  5 +-
 lldb/source/Expression/UserExpression.cpp | 32 ---
 lldb/source/Expression/UtilityFunction.cpp| 16 ++--
 .../ExpressionParser/Clang/ClangDiagnostic.h  |  5 +-
 .../Clang/ClangExpressionParser.cpp   | 69 ++
 .../Clang/ClangUserExpression.h   |  2 +
 .../Plugins/Platform/POSIX/PlatformPOSIX.cpp  | 10 +-
 .../Platform/Windows/PlatformWindows.cpp  | 10 +-
 lldb/source/Target/Target.cpp |  2 +-
 lldb/source/Utility/Status.cpp|  8 ++
 .../TestModulesCompileError.py|  2 +-
 .../Expression/DiagnosticManagerTest.cpp  | 22 +++--
 lldb/unittests/Utility/StatusTest.cpp |  2 +-
 17 files changed, 267 insertions(+), 118 deletions(-)

diff --git a/lldb/include/lldb/Expression/DiagnosticManager.h 
b/lldb/include/lldb/Expression/DiagnosticManager.h
index d49b7c99b114fb..1c0763eea92f05 100644
--- a/lldb/include/lldb/Expression/DiagnosticManager.h
+++ b/lldb/include/lldb/Expression/DiagnosticManager.h
@@ -12,6 +12,9 @@
 #include "lldb/lldb-defines.h"
 #include "lldb/lldb-types.h"
 
+#include "lldb/Utility/FileSpec.h"
+#include "lldb/Utility/Status.h"
+
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringRef.h"
 
@@ -20,6 +23,52 @@
 
 namespace lldb_private {
 
+/// A compiler-independent representation of a Diagnostic. Expression
+/// evaluation failures often have more than one diagnostic that a UI
+/// layer might want to render differently, for example to colorize
+/// it.
+///
+/// Running example:
+///   (lldb) expr 1+foo
+///   error: :1:3: use of undeclared identifier 'foo'
+///   1+foo
+/// ^
+struct DiagnosticDetail {
+  struct SourceLocation {
+FileSpec file;
+unsigned line = 0;
+uint16_t column = 0;
+uint16_t length = 0;
+bool in_user_input = false;
+  };
+  /// Contains {{}, 1, 3, 3, true} in the example above.
+  std::optional source_location;
+  /// Contains eSeverityError in the example above.
+  lldb::Severity severity = lldb::eSeverityInfo;
+  /// Contains "use of undeclared identifier 'x'" in the example above.
+  std::string message;
+  /// Contains the fully rendered error message.
+  std::string rendered;
+};
+
+/// An llvm::Error used to communicate diagnostics in Status. Multiple
+/// diagnostics may be chained in an llvm::ErrorList.
+class DetailedExpressionError
+: public llvm::ErrorInfo {
+  DiagnosticDetail m_detail;
+
+public:
+  using llvm::ErrorInfo::ErrorInfo;
+  DetailedExpressionError(DiagnosticDetail detail) : m_detail(detail) {}
+  std::string message() const override;
+  DiagnosticDetail GetDetail() const { return m_detail; }
+  std::error_code convertToErrorCode() const override;
+  void log(llvm::raw_ostream &OS) const override;
+  std::unique_ptr Clone() const override;
+
+  static char ID;
+};
+
 enum DiagnosticOrigin {
   eDiagnosticOriginUnknown = 0,
   eDiagnosticOriginLLDB,
@@ -49,37 +98,28 @@ class Diagnostic {
 }
   }
 
-  Diagnostic(llvm::StringRef message, lldb::Severity severity,
- DiagnosticOrigin origin, uint32_t compiler_id)
-  : m_message(message), m_severity(severity), m_origin(origin),
-m_compiler_id(compiler_id) {}
-
-  Diagnostic(const Diagnostic &rhs)
-  : m_message(rhs.m_message), m_severity(rhs.m_severity),
-m_origin(rhs.m_origin), m_compiler_id(rhs.m_compiler_id) {}
+  Diagnostic(DiagnosticOrigin origin, uint32_t compiler_id,
+ DiagnosticDetail detail)
+  : m_origin(origin), m_compiler_id(compiler_id), 

[Lldb-commits] [lldb] [lldb/Interpreter] Introduce `ScriptedStopHook{, Python}Interface` & make use of it (PR #105449)

2024-09-19 Thread Med Ismail Bennani via lldb-commits

https://github.com/medismailben updated 
https://github.com/llvm/llvm-project/pull/105449

>From 897dd358d3b15ec59e63068f7e328e914db49495 Mon Sep 17 00:00:00 2001
From: Med Ismail Bennani 
Date: Thu, 19 Sep 2024 13:25:06 -0700
Subject: [PATCH] [lldb/Interpreter] Add requirements to Scripted Interface
 abstract methods

This patch adds new requirements to the Scripted Interface abstract
method checker to check the minimum number of argument for abstract
methods.

This check is done when creating the interface object so the object is
not created if the user implementation doesn't match the abstract method
requirement.

Signed-off-by: Med Ismail Bennani 
---
 .../Interfaces/ScriptedInterface.h|  17 +-
 .../OperatingSystemPythonInterface.h  |   5 +-
 .../ScriptedPlatformPythonInterface.h |  11 +-
 .../ScriptedProcessPythonInterface.h  |   9 +-
 .../Interfaces/ScriptedPythonInterface.h  | 160 +-
 .../ScriptedThreadPlanPythonInterface.h   |   3 +-
 .../ScriptedThreadPythonInterface.h   |   7 +-
 7 files changed, 158 insertions(+), 54 deletions(-)

diff --git a/lldb/include/lldb/Interpreter/Interfaces/ScriptedInterface.h 
b/lldb/include/lldb/Interpreter/Interfaces/ScriptedInterface.h
index 89c0b36d6fc2a1..a3dc52c435561f 100644
--- a/lldb/include/lldb/Interpreter/Interfaces/ScriptedInterface.h
+++ b/lldb/include/lldb/Interpreter/Interfaces/ScriptedInterface.h
@@ -31,7 +31,22 @@ class ScriptedInterface {
 return m_object_instance_sp;
   }
 
-  virtual llvm::SmallVector GetAbstractMethods() const = 
0;
+  struct AbstractMethodRequirement {
+llvm::StringLiteral name;
+size_t min_arg_count = 0;
+  };
+
+  virtual llvm::SmallVector
+  GetAbstractMethodRequirements() const = 0;
+
+  llvm::SmallVector const GetAbstractMethods() const {
+llvm::SmallVector abstract_methods;
+llvm::transform(GetAbstractMethodRequirements(), abstract_methods.begin(),
+[](const AbstractMethodRequirement &requirement) {
+  return requirement.name;
+});
+return abstract_methods;
+  }
 
   template 
   static Ret ErrorWithMessage(llvm::StringRef caller_name,
diff --git 
a/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/OperatingSystemPythonInterface.h
 
b/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/OperatingSystemPythonInterface.h
index 92358ac6c34f7e..102c3c39537686 100644
--- 
a/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/OperatingSystemPythonInterface.h
+++ 
b/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/OperatingSystemPythonInterface.h
@@ -31,8 +31,9 @@ class OperatingSystemPythonInterface
  StructuredData::DictionarySP args_sp,
  StructuredData::Generic *script_obj = nullptr) override;
 
-  llvm::SmallVector GetAbstractMethods() const override {
-return llvm::SmallVector({"get_thread_info"});
+  llvm::SmallVector
+  GetAbstractMethodRequirements() const override {
+return llvm::SmallVector({{"get_thread_info"}});
   }
 
   StructuredData::DictionarySP CreateThread(lldb::tid_t tid,
diff --git 
a/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/ScriptedPlatformPythonInterface.h
 
b/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/ScriptedPlatformPythonInterface.h
index 36a219a656993b..a0da1bbc31c70f 100644
--- 
a/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/ScriptedPlatformPythonInterface.h
+++ 
b/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/ScriptedPlatformPythonInterface.h
@@ -29,10 +29,13 @@ class ScriptedPlatformPythonInterface : public 
ScriptedPlatformInterface,
  StructuredData::DictionarySP args_sp,
  StructuredData::Generic *script_obj = nullptr) override;
 
-  llvm::SmallVector GetAbstractMethods() const override {
-return llvm::SmallVector(
-{"list_processes", "attach_to_process", "launch_process",
- "kill_process"});
+  llvm::SmallVector
+  GetAbstractMethodRequirements() const override {
+return llvm::SmallVector(
+{{"list_processes"},
+ {"attach_to_process", 2},
+ {"launch_process", 2},
+ {"kill_process", 2}});
   }
 
   StructuredData::DictionarySP ListProcesses() override;
diff --git 
a/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/ScriptedProcessPythonInterface.h
 
b/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/ScriptedProcessPythonInterface.h
index 1535d573e72f43..703b942fe5647c 100644
--- 
a/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/ScriptedProcessPythonInterface.h
+++ 
b/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/ScriptedProcessPythonInterface.h
@@ -31,9 +31,12 @@ class ScriptedProcessPythonInterface : public 
ScriptedProcessInterface,
  StructuredData::DictionarySP args_sp,
  StructuredData::Generic *script_obj = nullptr) override;
 
-  llvm::SmallVector GetAbstractM

[Lldb-commits] [lldb] 2102607 - [lldb/Interpreter] Add requirements to Scripted Interface abstract methods (#109063)

2024-09-19 Thread via lldb-commits

Author: Med Ismail Bennani
Date: 2024-09-19T13:55:41-07:00
New Revision: 21026073e3b0583caf0c81564c4d7ebf002fe67b

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

LOG: [lldb/Interpreter] Add requirements to Scripted Interface abstract methods 
(#109063)

This patch adds new requirements to the Scripted Interface abstract
method checker to check the minimum number of argument for abstract
methods.

This check is done when creating the interface object so the object is
not created if the user implementation doesn't match the abstract method
requirement.

Signed-off-by: Med Ismail Bennani 

Added: 


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

lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/OperatingSystemPythonInterface.h

lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/ScriptedPlatformPythonInterface.h

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

lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/ScriptedPythonInterface.h

lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/ScriptedThreadPlanPythonInterface.h

lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/ScriptedThreadPythonInterface.h

Removed: 




diff  --git a/lldb/include/lldb/Interpreter/Interfaces/ScriptedInterface.h 
b/lldb/include/lldb/Interpreter/Interfaces/ScriptedInterface.h
index 89c0b36d6fc2a1..a3dc52c435561f 100644
--- a/lldb/include/lldb/Interpreter/Interfaces/ScriptedInterface.h
+++ b/lldb/include/lldb/Interpreter/Interfaces/ScriptedInterface.h
@@ -31,7 +31,22 @@ class ScriptedInterface {
 return m_object_instance_sp;
   }
 
-  virtual llvm::SmallVector GetAbstractMethods() const = 
0;
+  struct AbstractMethodRequirement {
+llvm::StringLiteral name;
+size_t min_arg_count = 0;
+  };
+
+  virtual llvm::SmallVector
+  GetAbstractMethodRequirements() const = 0;
+
+  llvm::SmallVector const GetAbstractMethods() const {
+llvm::SmallVector abstract_methods;
+llvm::transform(GetAbstractMethodRequirements(), abstract_methods.begin(),
+[](const AbstractMethodRequirement &requirement) {
+  return requirement.name;
+});
+return abstract_methods;
+  }
 
   template 
   static Ret ErrorWithMessage(llvm::StringRef caller_name,

diff  --git 
a/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/OperatingSystemPythonInterface.h
 
b/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/OperatingSystemPythonInterface.h
index 92358ac6c34f7e..102c3c39537686 100644
--- 
a/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/OperatingSystemPythonInterface.h
+++ 
b/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/OperatingSystemPythonInterface.h
@@ -31,8 +31,9 @@ class OperatingSystemPythonInterface
  StructuredData::DictionarySP args_sp,
  StructuredData::Generic *script_obj = nullptr) override;
 
-  llvm::SmallVector GetAbstractMethods() const override {
-return llvm::SmallVector({"get_thread_info"});
+  llvm::SmallVector
+  GetAbstractMethodRequirements() const override {
+return llvm::SmallVector({{"get_thread_info"}});
   }
 
   StructuredData::DictionarySP CreateThread(lldb::tid_t tid,

diff  --git 
a/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/ScriptedPlatformPythonInterface.h
 
b/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/ScriptedPlatformPythonInterface.h
index 36a219a656993b..a0da1bbc31c70f 100644
--- 
a/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/ScriptedPlatformPythonInterface.h
+++ 
b/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/ScriptedPlatformPythonInterface.h
@@ -29,10 +29,13 @@ class ScriptedPlatformPythonInterface : public 
ScriptedPlatformInterface,
  StructuredData::DictionarySP args_sp,
  StructuredData::Generic *script_obj = nullptr) override;
 
-  llvm::SmallVector GetAbstractMethods() const override {
-return llvm::SmallVector(
-{"list_processes", "attach_to_process", "launch_process",
- "kill_process"});
+  llvm::SmallVector
+  GetAbstractMethodRequirements() const override {
+return llvm::SmallVector(
+{{"list_processes"},
+ {"attach_to_process", 2},
+ {"launch_process", 2},
+ {"kill_process", 2}});
   }
 
   StructuredData::DictionarySP ListProcesses() override;

diff  --git 
a/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/ScriptedProcessPythonInterface.h
 
b/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/ScriptedProcessPythonInterface.h
index 1535d573e72f43..703b942fe5647c 100644
--- 
a/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/ScriptedProcessPythonInterfac

[Lldb-commits] [lldb] [lldb/Interpreter] Add requirements to Scripted Interface abstract methods (PR #109063)

2024-09-19 Thread Med Ismail Bennani via lldb-commits

https://github.com/medismailben closed 
https://github.com/llvm/llvm-project/pull/109063
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [lldb] Inline expression evaluator error visualization (PR #106470)

2024-09-19 Thread Adrian Prantl via lldb-commits

adrian-prantl wrote:

This is now ready for review. Out of scope for this PR, but the obvious next 
step: `dwim-print` / `p` support.

https://github.com/llvm/llvm-project/pull/106470
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [lldb] Store expression evaluator diagnostics in an llvm::Error (NFC) (PR #106442)

2024-09-19 Thread Adrian Prantl via lldb-commits


@@ -254,14 +255,46 @@ class ClangDiagnosticManagerAdapter : public 
clang::DiagnosticConsumer {
   std::string stripped_output =
   std::string(llvm::StringRef(m_output).trim());
 
-  auto new_diagnostic = std::make_unique(
-  stripped_output, severity, Info.getID());
+  // Translate the source location.
+  if (Info.hasSourceManager()) {
+DiagnosticDetail::SourceLocation loc;
+clang::SourceManager &sm = Info.getSourceManager();
+const clang::SourceLocation sloc = Info.getLocation();
+if (sloc.isValid()) {
+  const clang::FullSourceLoc fsloc(sloc, sm);
+  clang::PresumedLoc PLoc = fsloc.getPresumedLoc(true);
+  StringRef filename =
+  PLoc.isValid() ? PLoc.getFilename() : StringRef{};
+  loc.file = FileSpec(filename);
+  loc.line = fsloc.getSpellingLineNumber();
+  loc.column = fsloc.getSpellingColumnNumber();
+  // A heuristic detecting the #line 1 "".
+  loc.in_user_input = filename.starts_with("https://github.com/llvm/llvm-project/pull/106470

https://github.com/llvm/llvm-project/pull/106442
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [lldb/Interpreter] Add requirements to Scripted Interface abstract methods (PR #109063)

2024-09-19 Thread Med Ismail Bennani via lldb-commits

https://github.com/medismailben updated 
https://github.com/llvm/llvm-project/pull/109063

>From 897dd358d3b15ec59e63068f7e328e914db49495 Mon Sep 17 00:00:00 2001
From: Med Ismail Bennani 
Date: Thu, 19 Sep 2024 13:25:06 -0700
Subject: [PATCH] [lldb/Interpreter] Add requirements to Scripted Interface
 abstract methods

This patch adds new requirements to the Scripted Interface abstract
method checker to check the minimum number of argument for abstract
methods.

This check is done when creating the interface object so the object is
not created if the user implementation doesn't match the abstract method
requirement.

Signed-off-by: Med Ismail Bennani 
---
 .../Interfaces/ScriptedInterface.h|  17 +-
 .../OperatingSystemPythonInterface.h  |   5 +-
 .../ScriptedPlatformPythonInterface.h |  11 +-
 .../ScriptedProcessPythonInterface.h  |   9 +-
 .../Interfaces/ScriptedPythonInterface.h  | 160 +-
 .../ScriptedThreadPlanPythonInterface.h   |   3 +-
 .../ScriptedThreadPythonInterface.h   |   7 +-
 7 files changed, 158 insertions(+), 54 deletions(-)

diff --git a/lldb/include/lldb/Interpreter/Interfaces/ScriptedInterface.h 
b/lldb/include/lldb/Interpreter/Interfaces/ScriptedInterface.h
index 89c0b36d6fc2a1..a3dc52c435561f 100644
--- a/lldb/include/lldb/Interpreter/Interfaces/ScriptedInterface.h
+++ b/lldb/include/lldb/Interpreter/Interfaces/ScriptedInterface.h
@@ -31,7 +31,22 @@ class ScriptedInterface {
 return m_object_instance_sp;
   }
 
-  virtual llvm::SmallVector GetAbstractMethods() const = 
0;
+  struct AbstractMethodRequirement {
+llvm::StringLiteral name;
+size_t min_arg_count = 0;
+  };
+
+  virtual llvm::SmallVector
+  GetAbstractMethodRequirements() const = 0;
+
+  llvm::SmallVector const GetAbstractMethods() const {
+llvm::SmallVector abstract_methods;
+llvm::transform(GetAbstractMethodRequirements(), abstract_methods.begin(),
+[](const AbstractMethodRequirement &requirement) {
+  return requirement.name;
+});
+return abstract_methods;
+  }
 
   template 
   static Ret ErrorWithMessage(llvm::StringRef caller_name,
diff --git 
a/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/OperatingSystemPythonInterface.h
 
b/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/OperatingSystemPythonInterface.h
index 92358ac6c34f7e..102c3c39537686 100644
--- 
a/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/OperatingSystemPythonInterface.h
+++ 
b/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/OperatingSystemPythonInterface.h
@@ -31,8 +31,9 @@ class OperatingSystemPythonInterface
  StructuredData::DictionarySP args_sp,
  StructuredData::Generic *script_obj = nullptr) override;
 
-  llvm::SmallVector GetAbstractMethods() const override {
-return llvm::SmallVector({"get_thread_info"});
+  llvm::SmallVector
+  GetAbstractMethodRequirements() const override {
+return llvm::SmallVector({{"get_thread_info"}});
   }
 
   StructuredData::DictionarySP CreateThread(lldb::tid_t tid,
diff --git 
a/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/ScriptedPlatformPythonInterface.h
 
b/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/ScriptedPlatformPythonInterface.h
index 36a219a656993b..a0da1bbc31c70f 100644
--- 
a/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/ScriptedPlatformPythonInterface.h
+++ 
b/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/ScriptedPlatformPythonInterface.h
@@ -29,10 +29,13 @@ class ScriptedPlatformPythonInterface : public 
ScriptedPlatformInterface,
  StructuredData::DictionarySP args_sp,
  StructuredData::Generic *script_obj = nullptr) override;
 
-  llvm::SmallVector GetAbstractMethods() const override {
-return llvm::SmallVector(
-{"list_processes", "attach_to_process", "launch_process",
- "kill_process"});
+  llvm::SmallVector
+  GetAbstractMethodRequirements() const override {
+return llvm::SmallVector(
+{{"list_processes"},
+ {"attach_to_process", 2},
+ {"launch_process", 2},
+ {"kill_process", 2}});
   }
 
   StructuredData::DictionarySP ListProcesses() override;
diff --git 
a/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/ScriptedProcessPythonInterface.h
 
b/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/ScriptedProcessPythonInterface.h
index 1535d573e72f43..703b942fe5647c 100644
--- 
a/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/ScriptedProcessPythonInterface.h
+++ 
b/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/ScriptedProcessPythonInterface.h
@@ -31,9 +31,12 @@ class ScriptedProcessPythonInterface : public 
ScriptedProcessInterface,
  StructuredData::DictionarySP args_sp,
  StructuredData::Generic *script_obj = nullptr) override;
 
-  llvm::SmallVector GetAbstractM

[Lldb-commits] [lldb] Improve type and namespace lookup using parent chain (PR #108907)

2024-09-19 Thread via lldb-commits

https://github.com/jeffreytan81 edited 
https://github.com/llvm/llvm-project/pull/108907
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] Improve type and namespace lookup using parent chain (PR #108907)

2024-09-19 Thread via lldb-commits

jeffreytan81 wrote:

> I'm also not sure where's the " NameEntry> mapping table" 
> you mention in the description. Could you point me to it?

@labath, that is the first prototype I tried, but benchmark shows it did not 
improve any performance because the time to build this mapping offsets any 
query gain later so this PR did not use it and uses the second idea by 
searching parent entry's matching names which is implemented in this PR.



https://github.com/llvm/llvm-project/pull/108907
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] Add the ability to define custom completers to the parsed_cmd template. (PR #109062)

2024-09-19 Thread Med Ismail Bennani via lldb-commits


@@ -587,8 +587,150 @@ say
 SBCommandReturnObject and SBStream both support this file-like behavior by
 providing write() and flush() calls at the Python layer.
 
+The commands that are added using this Class definition are what lldb calls
+"raw" commands.  The command interpreter doesn't attempt to parse the command,
+doesn't handle option values, neither generating help for them, or their
+completion.  Raw commands are useful when the arguments passed to the command
+are unstructured, and having to protect them against lldb command parsing would
+be onerous.  For instance, "expr" is a raw command.
+
+You can also add scripted commands that implement the "parsed command", where
+the options and their types are specified, as well as the argument and argument
+types.  These commands look and act like the majority of lldb commands, and you
+can also add custom completions for the options and/or the arguments if you 
have
+special needs.
+
+The easiest way to do this is to derive your new command from the 
lldb.ParsedCommand
+class.  That responds in the same way to the help & repeat command interfaces, 
and
+provides some convenience methods, and most importantly an 
LLDBOptionValueParser,
+accessed throught lldb.ParsedCommand.get_parser().  The parser is used to set
+your command definitions, and to retrieve option values in the __call__ method.
+
+To set the command definition, implement the ParsedCommand abstract method:
+
+::
+
+   def setup_command_definition(self):
+
+This is called when your command is added to lldb.  In this method you add the
+options and their types, the option help strings, etc. to the command using 
the API:
+
+::
+
+def add_option(self, short_option, long_option, help, default,
+   dest = None, required=False, groups = None,
+   value_type=lldb.eArgTypeNone, completion_type=None,
+   enum_values=None):
+"""
+short_option: one character, must be unique, not required
+long_option:  no spaces, must be unique, required
+help: a usage string for this option, will print in the 
command help
+default:  the initial value for this option (if it has a value)
+dest: the name of the property that gives you access to the 
value for
+  this value.  Defaults to the long option if not provided.
+required: if true, this option must be provided or the command will 
error out
+groups: Which "option groups" does this option belong to.  This can 
either be
+a simple list (e.g. [1, 3, 4, 5]) or you can specify ranges by 
sublists:
+so [1, [3,5]] is the same as [1, 3, 4, 5].
+value_type: one of the lldb.eArgType enum values.  Some of the common 
arg
+types also have default completers, which will be applied 
automatically.
+completion_type: currently these are values form the 
lldb.CompletionType enum. If
+ you need custom completions, implement
handle_option_argument_completion.
+enum_values: An array of duples: ["element_name", "element_help"].  If 
provided,
+ only one of the enum elements is allowed.  The value will 
be the
+ element_name for the chosen enum element as a string.
+"""
+
+Similarly, you can add argument types to the command:
+
+::
+
+def make_argument_element(self, arg_type, repeat = "optional", groups = 
None):
+"""
+   arg_type: The argument type, one of the lldb.eArgType enum values.
+   repeat: Choose from the following options:
+   "plain" - one value
+   "optional" - zero or more values
+   "plus" - one or more values
+   groups: As with add_option.
+"""
+
+Then implement the body of the command by defining:
+
+::
+
+def __call__(self, debugger, args_array, exe_ctx, result):
+"""This is the command callback.  The option values are
+provided by the 'dest' properties on the parser.
+
+args_array: This is the list of arguments provided.
+exe_ctx: Gives the SBExecutionContext on which the
+ command should operate.
+result:  Any results of the command should be
+ written into this SBCommandReturnObject.
+"""
+
+This differs from the "raw" command's __call__ in that the arguments are 
already
+parsed into the args_array, and the option values are set in the parser, and
+can be accessed using their property name.  The LLDBOptionValueParser class has
+a couple of other handy methods:
+
+::
+def was_set(self, long_option_name):
+
+returns True if the option was specified on the command line.
+
+::
+def dest_for_option(self, long_option_name):
+"""
+This will return the value of the dest variable you defined for opt_name.
+Mostly useful for handle_completion where you get passed the long option.

[Lldb-commits] [lldb] Add the ability to define custom completers to the parsed_cmd template. (PR #109062)

2024-09-19 Thread Med Ismail Bennani via lldb-commits


@@ -587,8 +587,150 @@ say
 SBCommandReturnObject and SBStream both support this file-like behavior by
 providing write() and flush() calls at the Python layer.
 
+The commands that are added using this Class definition are what lldb calls
+"raw" commands.  The command interpreter doesn't attempt to parse the command,
+doesn't handle option values, neither generating help for them, or their
+completion.  Raw commands are useful when the arguments passed to the command
+are unstructured, and having to protect them against lldb command parsing would
+be onerous.  For instance, "expr" is a raw command.
+
+You can also add scripted commands that implement the "parsed command", where
+the options and their types are specified, as well as the argument and argument
+types.  These commands look and act like the majority of lldb commands, and you
+can also add custom completions for the options and/or the arguments if you 
have
+special needs.
+
+The easiest way to do this is to derive your new command from the 
lldb.ParsedCommand
+class.  That responds in the same way to the help & repeat command interfaces, 
and
+provides some convenience methods, and most importantly an 
LLDBOptionValueParser,
+accessed throught lldb.ParsedCommand.get_parser().  The parser is used to set
+your command definitions, and to retrieve option values in the __call__ method.
+
+To set the command definition, implement the ParsedCommand abstract method:
+
+::
+
+   def setup_command_definition(self):
+
+This is called when your command is added to lldb.  In this method you add the
+options and their types, the option help strings, etc. to the command using 
the API:
+
+::
+
+def add_option(self, short_option, long_option, help, default,
+   dest = None, required=False, groups = None,
+   value_type=lldb.eArgTypeNone, completion_type=None,
+   enum_values=None):
+"""
+short_option: one character, must be unique, not required
+long_option:  no spaces, must be unique, required
+help: a usage string for this option, will print in the 
command help
+default:  the initial value for this option (if it has a value)
+dest: the name of the property that gives you access to the 
value for
+  this value.  Defaults to the long option if not provided.
+required: if true, this option must be provided or the command will 
error out
+groups: Which "option groups" does this option belong to.  This can 
either be
+a simple list (e.g. [1, 3, 4, 5]) or you can specify ranges by 
sublists:
+so [1, [3,5]] is the same as [1, 3, 4, 5].
+value_type: one of the lldb.eArgType enum values.  Some of the common 
arg
+types also have default completers, which will be applied 
automatically.
+completion_type: currently these are values form the 
lldb.CompletionType enum. If
+ you need custom completions, implement
handle_option_argument_completion.
+enum_values: An array of duples: ["element_name", "element_help"].  If 
provided,
+ only one of the enum elements is allowed.  The value will 
be the
+ element_name for the chosen enum element as a string.
+"""
+
+Similarly, you can add argument types to the command:
+
+::
+
+def make_argument_element(self, arg_type, repeat = "optional", groups = 
None):
+"""
+   arg_type: The argument type, one of the lldb.eArgType enum values.
+   repeat: Choose from the following options:
+   "plain" - one value
+   "optional" - zero or more values
+   "plus" - one or more values
+   groups: As with add_option.
+"""
+
+Then implement the body of the command by defining:
+
+::
+
+def __call__(self, debugger, args_array, exe_ctx, result):
+"""This is the command callback.  The option values are
+provided by the 'dest' properties on the parser.
+
+args_array: This is the list of arguments provided.
+exe_ctx: Gives the SBExecutionContext on which the
+ command should operate.
+result:  Any results of the command should be
+ written into this SBCommandReturnObject.
+"""
+
+This differs from the "raw" command's __call__ in that the arguments are 
already
+parsed into the args_array, and the option values are set in the parser, and
+can be accessed using their property name.  The LLDBOptionValueParser class has
+a couple of other handy methods:
+
+::
+def was_set(self, long_option_name):
+
+returns True if the option was specified on the command line.
+
+::
+def dest_for_option(self, long_option_name):
+"""
+This will return the value of the dest variable you defined for opt_name.
+Mostly useful for handle_completion where you get passed the long option.

[Lldb-commits] [lldb] Add the ability to define custom completers to the parsed_cmd template. (PR #109062)

2024-09-19 Thread Med Ismail Bennani via lldb-commits


@@ -43,7 +43,65 @@ def __call__(self, debugger, args_list, exe_ctx, result):
 will return True if the user set this option, and False if it was left at its 
default
 value.
 
-There are example commands in the lldb testsuite at:
+Custom Completions:
+
+You can also implement custom completers for your custom command, either for 
the
+arguments to your command or to the option values in your command.  If you use 
enum
+values or if your option/argument uses is one of the types we have completers 
for,
+you should not need to do this.  But if you have your own completeable types, 
or if
+you want completion of one option to be conditioned by other options on the 
command
+line, you can use this interface to take over the completion.  
+
+You can choose to add a completion for the option values defined for your 
command,
+or for the arguments, separately.  For the option values, define:
+
+def handle_option_argument_completion(self, long_option, cursor_pos):
+

medismailben wrote:

Use `.. code-block:: python`  so this gets rendered differently on the website

```suggestion

.. code-block:: python

def handle_option_argument_completion(self, long_option, 
cursor_pos):

```

https://github.com/llvm/llvm-project/pull/109062
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] Add the ability to define custom completers to the parsed_cmd template. (PR #109062)

2024-09-19 Thread Med Ismail Bennani via lldb-commits

https://github.com/medismailben edited 
https://github.com/llvm/llvm-project/pull/109062
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [lldb/Interpreter] Add requirements to Scripted Interface abstract methods (PR #109063)

2024-09-19 Thread Alex Langford via lldb-commits

https://github.com/bulbazord approved this pull request.


https://github.com/llvm/llvm-project/pull/109063
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [lldb] Inline expression evaluator error visualization (PR #106470)

2024-09-19 Thread Adrian Prantl via lldb-commits

https://github.com/adrian-prantl updated 
https://github.com/llvm/llvm-project/pull/106470

>From 8c682fc70bff5c6dff43c4601c14e5e61d11a08f Mon Sep 17 00:00:00 2001
From: Adrian Prantl 
Date: Wed, 28 Aug 2024 10:04:33 -0700
Subject: [PATCH 1/2] [lldb] Store expression evaluator diagnostics in an
 llvm::Error (NFC)

This patch is a reworking of Pete Lawrence's (@PortalPete) proposal
for better expression evaluator error messages:
https://github.com/llvm/llvm-project/pull/80938

This patch is preparatory patch for improving the rendering of
expression evaluator diagnostics. Currently diagnostics are rendered
into a string and the command interpreter layer then textually parses
words like "error:" to (sometimes) color the output accordingly. In
order to enable user interfaces to do better with diagnostics, we need
to store them in a machine-readable fromat. This patch does this by
adding a new llvm::Error kind wrapping a DiagnosticDetail struct that
is used when the error type is eErrorTypeExpression. Multiple
diagnostics are modeled using llvm::ErrorList.

Right now the extra information is not used by the CommandInterpreter,
this will be added in a follow-up patch!
---
 .../lldb/Expression/DiagnosticManager.h   | 91 +-
 lldb/include/lldb/Utility/Status.h|  5 +-
 lldb/source/Breakpoint/BreakpointLocation.cpp | 10 +-
 lldb/source/Expression/DiagnosticManager.cpp  | 94 +++
 lldb/source/Expression/ExpressionParser.cpp   |  5 +-
 lldb/source/Expression/UserExpression.cpp | 32 ---
 lldb/source/Expression/UtilityFunction.cpp| 16 ++--
 .../ExpressionParser/Clang/ClangDiagnostic.h  |  5 +-
 .../Clang/ClangExpressionParser.cpp   | 69 ++
 .../Clang/ClangUserExpression.h   |  2 +
 .../Plugins/Platform/POSIX/PlatformPOSIX.cpp  | 10 +-
 .../Platform/Windows/PlatformWindows.cpp  | 10 +-
 lldb/source/Target/Target.cpp |  2 +-
 lldb/source/Utility/Status.cpp|  8 ++
 .../TestModulesCompileError.py|  2 +-
 .../Expression/DiagnosticManagerTest.cpp  | 22 +++--
 lldb/unittests/Utility/StatusTest.cpp |  2 +-
 17 files changed, 267 insertions(+), 118 deletions(-)

diff --git a/lldb/include/lldb/Expression/DiagnosticManager.h 
b/lldb/include/lldb/Expression/DiagnosticManager.h
index d49b7c99b114fb..1c0763eea92f05 100644
--- a/lldb/include/lldb/Expression/DiagnosticManager.h
+++ b/lldb/include/lldb/Expression/DiagnosticManager.h
@@ -12,6 +12,9 @@
 #include "lldb/lldb-defines.h"
 #include "lldb/lldb-types.h"
 
+#include "lldb/Utility/FileSpec.h"
+#include "lldb/Utility/Status.h"
+
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringRef.h"
 
@@ -20,6 +23,52 @@
 
 namespace lldb_private {
 
+/// A compiler-independent representation of a Diagnostic. Expression
+/// evaluation failures often have more than one diagnostic that a UI
+/// layer might want to render differently, for example to colorize
+/// it.
+///
+/// Running example:
+///   (lldb) expr 1+foo
+///   error: :1:3: use of undeclared identifier 'foo'
+///   1+foo
+/// ^
+struct DiagnosticDetail {
+  struct SourceLocation {
+FileSpec file;
+unsigned line = 0;
+uint16_t column = 0;
+uint16_t length = 0;
+bool in_user_input = false;
+  };
+  /// Contains {{}, 1, 3, 3, true} in the example above.
+  std::optional source_location;
+  /// Contains eSeverityError in the example above.
+  lldb::Severity severity = lldb::eSeverityInfo;
+  /// Contains "use of undeclared identifier 'x'" in the example above.
+  std::string message;
+  /// Contains the fully rendered error message.
+  std::string rendered;
+};
+
+/// An llvm::Error used to communicate diagnostics in Status. Multiple
+/// diagnostics may be chained in an llvm::ErrorList.
+class DetailedExpressionError
+: public llvm::ErrorInfo {
+  DiagnosticDetail m_detail;
+
+public:
+  using llvm::ErrorInfo::ErrorInfo;
+  DetailedExpressionError(DiagnosticDetail detail) : m_detail(detail) {}
+  std::string message() const override;
+  DiagnosticDetail GetDetail() const { return m_detail; }
+  std::error_code convertToErrorCode() const override;
+  void log(llvm::raw_ostream &OS) const override;
+  std::unique_ptr Clone() const override;
+
+  static char ID;
+};
+
 enum DiagnosticOrigin {
   eDiagnosticOriginUnknown = 0,
   eDiagnosticOriginLLDB,
@@ -49,37 +98,28 @@ class Diagnostic {
 }
   }
 
-  Diagnostic(llvm::StringRef message, lldb::Severity severity,
- DiagnosticOrigin origin, uint32_t compiler_id)
-  : m_message(message), m_severity(severity), m_origin(origin),
-m_compiler_id(compiler_id) {}
-
-  Diagnostic(const Diagnostic &rhs)
-  : m_message(rhs.m_message), m_severity(rhs.m_severity),
-m_origin(rhs.m_origin), m_compiler_id(rhs.m_compiler_id) {}
+  Diagnostic(DiagnosticOrigin origin, uint32_t compiler_id,
+ DiagnosticDetail detail)
+  : m_origin(origin), m_compiler_id(compiler_id), 

[Lldb-commits] [lldb] Improve type and namespace lookup using parent chain (PR #108907)

2024-09-19 Thread via lldb-commits


@@ -126,3 +126,62 @@ bool DWARFIndex::GetFullyQualifiedTypeImpl(
 return callback(die);
   return true;
 }
+
+void DWARFIndex::GetNamespacesWithParents(
+ConstString name, llvm::ArrayRef parent_names,
+llvm::function_ref callback) {
+  GetNamespaces(name, [&](DWARFDIE die) {
+return ProcessDieMatchParentNames(name, parent_names, die, callback);
+  });
+}
+
+void DWARFIndex::GetTypesWithParents(
+ConstString name, llvm::ArrayRef parent_names,
+llvm::function_ref callback) {
+  GetTypes(name, [&](DWARFDIE die) {
+return ProcessDieMatchParentNames(name, parent_names, die, callback);
+  });
+}
+
+bool DWARFIndex::ProcessDieMatchParentNames(
+ConstString name, llvm::ArrayRef query_parent_names,
+DWARFDIE die, llvm::function_ref callback) {
+  std::vector type_context =
+  die.GetTypeLookupContext();
+  if (type_context.empty()) {
+// If both type_context and query_parent_names and empty we have a match.
+// Otherwise, this one does not match and we keep on searching.
+if (query_parent_names.empty())
+  return callback(die);
+return true;
+  }
+
+  // Type lookup context includes the current DIE as the last element.
+  // so revert it for easy matching.
+  std::reverse(type_context.begin(), type_context.end());
+
+  // type_context includes the name of the current DIE while query_parent_names

jeffreytan81 wrote:

@Michael137 , @clayborg, yep, the algorithm is similar. I tried to reuse 
`TypeQuery::ContextMatches` from `DebugNamesDWARFIndex` before, but then find 
it hard because, as Greg pointed out, the `CompilerContext` is parsed out from 
.debug_names parent chain, which is lazily searched in the new algorithm. 

However, I should be able to reuse `TypeQuery::ContextMatches` in this base 
implementation. Let me give a try. 

https://github.com/llvm/llvm-project/pull/108907
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] Improve type and namespace lookup using parent chain (PR #108907)

2024-09-19 Thread Greg Clayton via lldb-commits


@@ -126,3 +126,62 @@ bool DWARFIndex::GetFullyQualifiedTypeImpl(
 return callback(die);
   return true;
 }
+
+void DWARFIndex::GetNamespacesWithParents(
+ConstString name, llvm::ArrayRef parent_names,
+llvm::function_ref callback) {
+  GetNamespaces(name, [&](DWARFDIE die) {
+return ProcessDieMatchParentNames(name, parent_names, die, callback);
+  });
+}
+
+void DWARFIndex::GetTypesWithParents(
+ConstString name, llvm::ArrayRef parent_names,
+llvm::function_ref callback) {
+  GetTypes(name, [&](DWARFDIE die) {
+return ProcessDieMatchParentNames(name, parent_names, die, callback);
+  });
+}
+
+bool DWARFIndex::ProcessDieMatchParentNames(
+ConstString name, llvm::ArrayRef query_parent_names,
+DWARFDIE die, llvm::function_ref callback) {
+  std::vector type_context =
+  die.GetTypeLookupContext();
+  if (type_context.empty()) {
+// If both type_context and query_parent_names and empty we have a match.
+// Otherwise, this one does not match and we keep on searching.
+if (query_parent_names.empty())
+  return callback(die);
+return true;
+  }
+
+  // Type lookup context includes the current DIE as the last element.
+  // so revert it for easy matching.
+  std::reverse(type_context.begin(), type_context.end());
+
+  // type_context includes the name of the current DIE while query_parent_names

clayborg wrote:

The .debug_names search is what returns results to `TypeQuery::ContextMatches`, 
but we should have functions that can do the same matching. The difference here 
in .debug_names is we are trying to live off only the contents of .debug_names 
without using and DIEs. `TypeQuery::ContextMatches` uses DIEs. So we might be 
able to unify some of the context matching once the context has been extracted 
from the .debug_names or from the DWARF, but that is about as far as we should 
go.

https://github.com/llvm/llvm-project/pull/108907
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] Improve type and namespace lookup using parent chain (PR #108907)

2024-09-19 Thread Greg Clayton via lldb-commits


@@ -126,3 +126,62 @@ bool DWARFIndex::GetFullyQualifiedTypeImpl(
 return callback(die);
   return true;
 }
+
+void DWARFIndex::GetNamespacesWithParents(
+ConstString name, llvm::ArrayRef parent_names,
+llvm::function_ref callback) {
+  GetNamespaces(name, [&](DWARFDIE die) {
+return ProcessDieMatchParentNames(name, parent_names, die, callback);
+  });
+}
+
+void DWARFIndex::GetTypesWithParents(
+ConstString name, llvm::ArrayRef parent_names,
+llvm::function_ref callback) {
+  GetTypes(name, [&](DWARFDIE die) {
+return ProcessDieMatchParentNames(name, parent_names, die, callback);
+  });
+}
+
+bool DWARFIndex::ProcessDieMatchParentNames(
+ConstString name, llvm::ArrayRef query_parent_names,

clayborg wrote:

Same here, replace `llvm::ArrayRef` parent_names with 
`llvm::ArrayRef`

https://github.com/llvm/llvm-project/pull/108907
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] Improve type and namespace lookup using parent chain (PR #108907)

2024-09-19 Thread Greg Clayton via lldb-commits


@@ -126,3 +126,62 @@ bool DWARFIndex::GetFullyQualifiedTypeImpl(
 return callback(die);
   return true;
 }
+
+void DWARFIndex::GetNamespacesWithParents(
+ConstString name, llvm::ArrayRef parent_names,
+llvm::function_ref callback) {
+  GetNamespaces(name, [&](DWARFDIE die) {
+return ProcessDieMatchParentNames(name, parent_names, die, callback);
+  });
+}
+
+void DWARFIndex::GetTypesWithParents(
+ConstString name, llvm::ArrayRef parent_names,

clayborg wrote:

Same here, replace `llvm::ArrayRef parent_names` with 
`llvm::ArrayRef`

https://github.com/llvm/llvm-project/pull/108907
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] Improve type and namespace lookup using parent chain (PR #108907)

2024-09-19 Thread Greg Clayton via lldb-commits


@@ -126,3 +126,62 @@ bool DWARFIndex::GetFullyQualifiedTypeImpl(
 return callback(die);
   return true;
 }
+
+void DWARFIndex::GetNamespacesWithParents(
+ConstString name, llvm::ArrayRef parent_names,

clayborg wrote:

Instead of just an array of names, we should try to use the 
`llvm::ArrayRef`. The .debug_names table has the DW_TAG in 
each entry and we can further reduce the number of things and possibly not even 
need to check the name if the DW_TAG_ doesn't match of the CompilerContext type 
isn't set to Any.

https://github.com/llvm/llvm-project/pull/108907
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [lldb-dap] Add feature to remember last non-empty expression. (PR #107485)

2024-09-19 Thread via lldb-commits

https://github.com/cmtice updated 
https://github.com/llvm/llvm-project/pull/107485

>From 15541f354decf80586d590db9f9cb353be04b122 Mon Sep 17 00:00:00 2001
From: Caroline Tice 
Date: Thu, 5 Sep 2024 15:51:35 -0700
Subject: [PATCH 1/9] [lldb-dap] Add feature to remember last non-empty
 expression.

Update lldb-dap so if the user just presses return, which sends an
empty expression, it re-evaluates the most recent non-empty
expression/command. Also udpated test to test this case.
---
 lldb/test/API/tools/lldb-dap/evaluate/TestDAP_evaluate.py | 3 +++
 lldb/tools/lldb-dap/lldb-dap.cpp  | 8 
 2 files changed, 11 insertions(+)

diff --git a/lldb/test/API/tools/lldb-dap/evaluate/TestDAP_evaluate.py 
b/lldb/test/API/tools/lldb-dap/evaluate/TestDAP_evaluate.py
index 29548a835c6919..9ed0fc564268a7 100644
--- a/lldb/test/API/tools/lldb-dap/evaluate/TestDAP_evaluate.py
+++ b/lldb/test/API/tools/lldb-dap/evaluate/TestDAP_evaluate.py
@@ -60,7 +60,10 @@ def run_test_evaluate_expressions(
 
 # Expressions at breakpoint 1, which is in main
 self.assertEvaluate("var1", "20")
+# Empty expression should equate to the previous expression.
+self.assertEvaluate("", "20")
 self.assertEvaluate("var2", "21")
+self.assertEvaluate("", "21")
 self.assertEvaluate("static_int", "42")
 self.assertEvaluate("non_static_int", "43")
 self.assertEvaluate("struct1.foo", "15")
diff --git a/lldb/tools/lldb-dap/lldb-dap.cpp b/lldb/tools/lldb-dap/lldb-dap.cpp
index c5c4b09f15622b..a6a701dc2219fa 100644
--- a/lldb/tools/lldb-dap/lldb-dap.cpp
+++ b/lldb/tools/lldb-dap/lldb-dap.cpp
@@ -1363,6 +1363,14 @@ void request_evaluate(const llvm::json::Object &request) 
{
   lldb::SBFrame frame = g_dap.GetLLDBFrame(*arguments);
   std::string expression = GetString(arguments, "expression").str();
   llvm::StringRef context = GetString(arguments, "context");
+  static std::string last_nonempty_expression;
+
+  // Remember the last non-empty expression from the user, and use that if
+  // the current expression is empty (i.e. the user hit plain 'return').
+  if (!expression.empty())
+last_nonempty_expression = expression;
+  else
+expression = last_nonempty_expression;
 
   if (context == "repl" && g_dap.DetectExpressionContext(frame, expression) ==
ExpressionContext::Command) {

>From e35928e08f792163dd4886e797bc6de3d16ea6e6 Mon Sep 17 00:00:00 2001
From: Caroline Tice 
Date: Fri, 6 Sep 2024 10:02:18 -0700
Subject: [PATCH 2/9] [lldb] Add feature to remember last non-empty expression

Make last_nonempty_spression part of DAP struct rather than a
static variable.
---
 lldb/tools/lldb-dap/DAP.h| 1 +
 lldb/tools/lldb-dap/lldb-dap.cpp | 5 ++---
 2 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/lldb/tools/lldb-dap/DAP.h b/lldb/tools/lldb-dap/DAP.h
index f4fdec6e895ad1..4220c15d3ae70d 100644
--- a/lldb/tools/lldb-dap/DAP.h
+++ b/lldb/tools/lldb-dap/DAP.h
@@ -205,6 +205,7 @@ struct DAP {
   std::string command_escape_prefix = "`";
   lldb::SBFormat frame_format;
   lldb::SBFormat thread_format;
+  std::string last_nonempty_expression;
 
   DAP();
   ~DAP();
diff --git a/lldb/tools/lldb-dap/lldb-dap.cpp b/lldb/tools/lldb-dap/lldb-dap.cpp
index a6a701dc2219fa..d3728df9183aa1 100644
--- a/lldb/tools/lldb-dap/lldb-dap.cpp
+++ b/lldb/tools/lldb-dap/lldb-dap.cpp
@@ -1363,14 +1363,13 @@ void request_evaluate(const llvm::json::Object 
&request) {
   lldb::SBFrame frame = g_dap.GetLLDBFrame(*arguments);
   std::string expression = GetString(arguments, "expression").str();
   llvm::StringRef context = GetString(arguments, "context");
-  static std::string last_nonempty_expression;
 
   // Remember the last non-empty expression from the user, and use that if
   // the current expression is empty (i.e. the user hit plain 'return').
   if (!expression.empty())
-last_nonempty_expression = expression;
+g_dap.last_nonempty_expression = expression;
   else
-expression = last_nonempty_expression;
+expression = g_dap.last_nonempty_expression;
 
   if (context == "repl" && g_dap.DetectExpressionContext(frame, expression) ==
ExpressionContext::Command) {

>From 616017152f3f0611462e9863273754036b52f7eb Mon Sep 17 00:00:00 2001
From: Caroline Tice 
Date: Thu, 12 Sep 2024 10:52:32 -0700
Subject: [PATCH 3/9] [lldb-dap] Add feature to remember last non-empty
 expression

Update to handle commands & variables separately: empty command
expressions are passed to the CommandIntepreter to handle as it
normally does; empty variable expressions are updated to use the last
non-empty variable expression, if the last expression was a variable (not
a command).  Also updated the test case to test these cases properly, and
added a 'memory read' followed by an empty expression, to make sure it
handles that sequence correctly.
---
 .../lldb-dap/evaluate/TestDAP_evaluate.py | 16 +++--
 ...

[Lldb-commits] [lldb] [lldb-dap] Add feature to remember last non-empty expression. (PR #107485)

2024-09-19 Thread via lldb-commits


@@ -54,13 +54,20 @@ def run_test_evaluate_expressions(
 line_number(source, "// breakpoint 5"),
 line_number(source, "// breakpoint 6"),
 line_number(source, "// breakpoint 7"),
+line_number(source, "// breakpoint 8"),
 ],
 )
 self.continue_to_next_stop()
 
 # Expressions at breakpoint 1, which is in main
 self.assertEvaluate("var1", "20")
+# Empty expression should equate to the previous expression.
+if context == "repl":
+self.assertEvaluate("", "20")

cmtice wrote:

Done

https://github.com/llvm/llvm-project/pull/107485
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] Add the ability to define custom completers to the parsed_cmd template. (PR #109062)

2024-09-19 Thread Med Ismail Bennani via lldb-commits


@@ -43,7 +43,65 @@ def __call__(self, debugger, args_list, exe_ctx, result):
 will return True if the user set this option, and False if it was left at its 
default
 value.
 
-There are example commands in the lldb testsuite at:
+Custom Completions:
+
+You can also implement custom completers for your custom command, either for 
the
+arguments to your command or to the option values in your command.  If you use 
enum
+values or if your option/argument uses is one of the types we have completers 
for,
+you should not need to do this.  But if you have your own completeable types, 
or if
+you want completion of one option to be conditioned by other options on the 
command
+line, you can use this interface to take over the completion.  
+
+You can choose to add a completion for the option values defined for your 
command,
+or for the arguments, separately.  For the option values, define:
+
+def handle_option_argument_completion(self, long_option, cursor_pos):
+
+The line to be completed will be parsed up to the option containint the cursor 
position, 
+and the values will be set in the OptionValue parser object.  long_option will 
be
+the option name containing the cursor, and cursor_pos will be the position of 
the cursor
+in that option's value.  You can call the 
OVParser.dest_for_option(long_option) to get the
+value for that option.  The other options that came before the cursor in the 
command
+line will also be set in the OV Parser when the completion handler is called.

medismailben wrote:

```suggestion
in that option's value.  You can call the 
`OVParser.dest_for_option(long_option)` to get the
value for that option.  The other options that came before the cursor in the 
command
line will also be set in the `OVParser` when the completion handler is called.
```

https://github.com/llvm/llvm-project/pull/109062
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] Add the ability to define custom completers to the parsed_cmd template. (PR #109062)

2024-09-19 Thread Med Ismail Bennani via lldb-commits


@@ -587,8 +587,150 @@ say
 SBCommandReturnObject and SBStream both support this file-like behavior by
 providing write() and flush() calls at the Python layer.
 
+The commands that are added using this Class definition are what lldb calls

medismailben wrote:

```suggestion
The commands that are added using this class definition are what lldb calls
```

https://github.com/llvm/llvm-project/pull/109062
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] Add the ability to define custom completers to the parsed_cmd template. (PR #109062)

2024-09-19 Thread Med Ismail Bennani via lldb-commits


@@ -587,8 +587,150 @@ say
 SBCommandReturnObject and SBStream both support this file-like behavior by
 providing write() and flush() calls at the Python layer.
 
+The commands that are added using this Class definition are what lldb calls
+"raw" commands.  The command interpreter doesn't attempt to parse the command,
+doesn't handle option values, neither generating help for them, or their
+completion.  Raw commands are useful when the arguments passed to the command
+are unstructured, and having to protect them against lldb command parsing would
+be onerous.  For instance, "expr" is a raw command.
+
+You can also add scripted commands that implement the "parsed command", where
+the options and their types are specified, as well as the argument and argument
+types.  These commands look and act like the majority of lldb commands, and you
+can also add custom completions for the options and/or the arguments if you 
have
+special needs.
+
+The easiest way to do this is to derive your new command from the 
lldb.ParsedCommand
+class.  That responds in the same way to the help & repeat command interfaces, 
and
+provides some convenience methods, and most importantly an 
LLDBOptionValueParser,
+accessed throught lldb.ParsedCommand.get_parser().  The parser is used to set
+your command definitions, and to retrieve option values in the __call__ method.
+
+To set the command definition, implement the ParsedCommand abstract method:
+
+::
+
+   def setup_command_definition(self):
+
+This is called when your command is added to lldb.  In this method you add the
+options and their types, the option help strings, etc. to the command using 
the API:
+
+::
+
+def add_option(self, short_option, long_option, help, default,
+   dest = None, required=False, groups = None,
+   value_type=lldb.eArgTypeNone, completion_type=None,
+   enum_values=None):
+"""
+short_option: one character, must be unique, not required
+long_option:  no spaces, must be unique, required
+help: a usage string for this option, will print in the 
command help
+default:  the initial value for this option (if it has a value)
+dest: the name of the property that gives you access to the 
value for
+  this value.  Defaults to the long option if not provided.
+required: if true, this option must be provided or the command will 
error out
+groups: Which "option groups" does this option belong to.  This can 
either be
+a simple list (e.g. [1, 3, 4, 5]) or you can specify ranges by 
sublists:
+so [1, [3,5]] is the same as [1, 3, 4, 5].
+value_type: one of the lldb.eArgType enum values.  Some of the common 
arg
+types also have default completers, which will be applied 
automatically.
+completion_type: currently these are values form the 
lldb.CompletionType enum. If
+ you need custom completions, implement
handle_option_argument_completion.
+enum_values: An array of duples: ["element_name", "element_help"].  If 
provided,
+ only one of the enum elements is allowed.  The value will 
be the
+ element_name for the chosen enum element as a string.
+"""
+
+Similarly, you can add argument types to the command:
+
+::
+
+def make_argument_element(self, arg_type, repeat = "optional", groups = 
None):
+"""
+   arg_type: The argument type, one of the lldb.eArgType enum values.
+   repeat: Choose from the following options:
+   "plain" - one value
+   "optional" - zero or more values
+   "plus" - one or more values
+   groups: As with add_option.
+"""
+
+Then implement the body of the command by defining:
+
+::
+
+def __call__(self, debugger, args_array, exe_ctx, result):
+"""This is the command callback.  The option values are
+provided by the 'dest' properties on the parser.
+
+args_array: This is the list of arguments provided.
+exe_ctx: Gives the SBExecutionContext on which the
+ command should operate.
+result:  Any results of the command should be
+ written into this SBCommandReturnObject.
+"""
+
+This differs from the "raw" command's __call__ in that the arguments are 
already
+parsed into the args_array, and the option values are set in the parser, and
+can be accessed using their property name.  The LLDBOptionValueParser class has
+a couple of other handy methods:
+
+::
+def was_set(self, long_option_name):
+
+returns True if the option was specified on the command line.
+
+::
+def dest_for_option(self, long_option_name):
+"""
+This will return the value of the dest variable you defined for opt_name.
+Mostly useful for handle_completion where you get passed the long option.

[Lldb-commits] [lldb] Add the ability to define custom completers to the parsed_cmd template. (PR #109062)

2024-09-19 Thread Med Ismail Bennani via lldb-commits


@@ -587,8 +587,150 @@ say
 SBCommandReturnObject and SBStream both support this file-like behavior by
 providing write() and flush() calls at the Python layer.
 
+The commands that are added using this Class definition are what lldb calls
+"raw" commands.  The command interpreter doesn't attempt to parse the command,
+doesn't handle option values, neither generating help for them, or their
+completion.  Raw commands are useful when the arguments passed to the command
+are unstructured, and having to protect them against lldb command parsing would
+be onerous.  For instance, "expr" is a raw command.
+
+You can also add scripted commands that implement the "parsed command", where
+the options and their types are specified, as well as the argument and argument
+types.  These commands look and act like the majority of lldb commands, and you
+can also add custom completions for the options and/or the arguments if you 
have
+special needs.
+
+The easiest way to do this is to derive your new command from the 
lldb.ParsedCommand
+class.  That responds in the same way to the help & repeat command interfaces, 
and
+provides some convenience methods, and most importantly an 
LLDBOptionValueParser,
+accessed throught lldb.ParsedCommand.get_parser().  The parser is used to set
+your command definitions, and to retrieve option values in the __call__ method.
+
+To set the command definition, implement the ParsedCommand abstract method:

medismailben wrote:

Are we missing a word here ?

```suggestion
To set up the command definition, implement the ParsedCommand abstract method:
```

https://github.com/llvm/llvm-project/pull/109062
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] Add the ability to define custom completers to the parsed_cmd template. (PR #109062)

2024-09-19 Thread Med Ismail Bennani via lldb-commits


@@ -587,8 +587,150 @@ say
 SBCommandReturnObject and SBStream both support this file-like behavior by
 providing write() and flush() calls at the Python layer.
 
+The commands that are added using this Class definition are what lldb calls
+"raw" commands.  The command interpreter doesn't attempt to parse the command,
+doesn't handle option values, neither generating help for them, or their
+completion.  Raw commands are useful when the arguments passed to the command
+are unstructured, and having to protect them against lldb command parsing would
+be onerous.  For instance, "expr" is a raw command.
+
+You can also add scripted commands that implement the "parsed command", where
+the options and their types are specified, as well as the argument and argument
+types.  These commands look and act like the majority of lldb commands, and you
+can also add custom completions for the options and/or the arguments if you 
have
+special needs.
+
+The easiest way to do this is to derive your new command from the 
lldb.ParsedCommand
+class.  That responds in the same way to the help & repeat command interfaces, 
and
+provides some convenience methods, and most importantly an 
LLDBOptionValueParser,
+accessed throught lldb.ParsedCommand.get_parser().  The parser is used to set
+your command definitions, and to retrieve option values in the __call__ method.
+
+To set the command definition, implement the ParsedCommand abstract method:
+
+::
+
+   def setup_command_definition(self):
+
+This is called when your command is added to lldb.  In this method you add the
+options and their types, the option help strings, etc. to the command using 
the API:
+
+::
+
+def add_option(self, short_option, long_option, help, default,
+   dest = None, required=False, groups = None,
+   value_type=lldb.eArgTypeNone, completion_type=None,
+   enum_values=None):
+"""
+short_option: one character, must be unique, not required
+long_option:  no spaces, must be unique, required
+help: a usage string for this option, will print in the 
command help
+default:  the initial value for this option (if it has a value)
+dest: the name of the property that gives you access to the 
value for
+  this value.  Defaults to the long option if not provided.
+required: if true, this option must be provided or the command will 
error out
+groups: Which "option groups" does this option belong to.  This can 
either be
+a simple list (e.g. [1, 3, 4, 5]) or you can specify ranges by 
sublists:
+so [1, [3,5]] is the same as [1, 3, 4, 5].
+value_type: one of the lldb.eArgType enum values.  Some of the common 
arg
+types also have default completers, which will be applied 
automatically.
+completion_type: currently these are values form the 
lldb.CompletionType enum. If
+ you need custom completions, implement
handle_option_argument_completion.
+enum_values: An array of duples: ["element_name", "element_help"].  If 
provided,
+ only one of the enum elements is allowed.  The value will 
be the
+ element_name for the chosen enum element as a string.
+"""
+
+Similarly, you can add argument types to the command:
+
+::
+
+def make_argument_element(self, arg_type, repeat = "optional", groups = 
None):
+"""
+   arg_type: The argument type, one of the lldb.eArgType enum values.
+   repeat: Choose from the following options:
+   "plain" - one value
+   "optional" - zero or more values
+   "plus" - one or more values
+   groups: As with add_option.
+"""
+
+Then implement the body of the command by defining:
+
+::
+
+def __call__(self, debugger, args_array, exe_ctx, result):
+"""This is the command callback.  The option values are
+provided by the 'dest' properties on the parser.
+
+args_array: This is the list of arguments provided.
+exe_ctx: Gives the SBExecutionContext on which the
+ command should operate.
+result:  Any results of the command should be
+ written into this SBCommandReturnObject.
+"""
+
+This differs from the "raw" command's __call__ in that the arguments are 
already
+parsed into the args_array, and the option values are set in the parser, and
+can be accessed using their property name.  The LLDBOptionValueParser class has
+a couple of other handy methods:
+
+::
+def was_set(self, long_option_name):
+
+returns True if the option was specified on the command line.
+
+::
+def dest_for_option(self, long_option_name):
+"""
+This will return the value of the dest variable you defined for opt_name.
+Mostly useful for handle_completion where you get passed the long option.

[Lldb-commits] [lldb] Add the ability to define custom completers to the parsed_cmd template. (PR #109062)

2024-09-19 Thread Med Ismail Bennani via lldb-commits


@@ -1637,6 +1637,129 @@ class CommandObjectScriptingObjectParsed : public 
CommandObjectParsed {
 
 size_t GetNumOptions() { return m_num_options; }
 
+void PrepareOptionsForCompletion(CompletionRequest &request,
+ OptionElementVector &option_vec,
+ ExecutionContext *exe_ctx) {
+  // I'm not sure if we'll get into trouble doing an option parsing start
+  // and end in this context.  If so, then I'll have to directly tell the
+  // scripter to do this.
+  OptionParsingStarting(exe_ctx);
+  auto opt_defs = GetDefinitions();
+
+  // Iterate through the options we found so far, and push them into
+  // the scripted side.
+  for (auto option_elem : option_vec) {
+int cur_defs_index = option_elem.opt_defs_index;
+// If we don't recognize this option we can't set it.
+if (cur_defs_index == OptionArgElement::eUnrecognizedArg ||
+cur_defs_index == OptionArgElement::eBareDash ||
+cur_defs_index == OptionArgElement::eBareDoubleDash)
+  continue;
+bool option_has_arg = opt_defs[cur_defs_index].option_has_arg;
+llvm::StringRef cur_arg_value;
+if (option_has_arg) {
+  int cur_arg_pos = option_elem.opt_arg_pos;
+  if (cur_arg_pos != OptionArgElement::eUnrecognizedArg &&
+  cur_arg_pos != OptionArgElement::eBareDash &&
+  cur_arg_pos != OptionArgElement::eBareDoubleDash) {
+cur_arg_value =
+request.GetParsedLine().GetArgumentAtIndex(cur_arg_pos);
+  }
+}
+SetOptionValue(cur_defs_index, cur_arg_value, exe_ctx);
+  }
+  OptionParsingFinished(exe_ctx);
+}
+
+void
+ProcessCompletionDict(CompletionRequest &request,
+  StructuredData::DictionarySP &completion_dict_sp) {
+  // We don't know how to process an empty completion dict, our callers 
have
+  // to do that.
+  assert(completion_dict_sp && "Must have valid completion dict");
+  // First handle the case of a single completion:
+  llvm::StringRef completion;
+  // If the dictionary has one element "no-completion" then we return here
+  if (completion_dict_sp->GetValueForKeyAsString("no-completion",
+ completion))
+return;
+
+  if (completion_dict_sp->GetValueForKeyAsString("completion",
+ completion)) {
+llvm::StringRef mode_str;
+CompletionMode mode = CompletionMode::Normal;
+if (completion_dict_sp->GetValueForKeyAsString("mode", mode_str)) {
+  if (mode_str == "complete")
+mode = CompletionMode::Normal;
+  else if (mode_str == "partial")
+mode = CompletionMode::Partial;
+  else {
+// FIXME - how do I report errors here?
+return;
+  }
+}
+request.AddCompletion(completion, "", mode);
+return;
+  }
+  // The completions are required, the descriptions are not:
+  StructuredData::Array *completions;
+  StructuredData::Array *descriptions;
+  if (completion_dict_sp->GetValueForKeyAsArray("values", completions)) {
+completion_dict_sp->GetValueForKeyAsArray("descriptions", 
descriptions);
+size_t num_completions = completions->GetSize();
+for (size_t idx = 0; idx < num_completions; idx++) {
+  auto val = completions->GetItemAtIndexAsString(idx);
+  if (!val)
+// FIXME: How do I report this error?

medismailben wrote:

todo ?

https://github.com/llvm/llvm-project/pull/109062
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] Add the ability to define custom completers to the parsed_cmd template. (PR #109062)

2024-09-19 Thread Med Ismail Bennani via lldb-commits

https://github.com/medismailben commented:

Overall, this looks fine. It would be nice to surround the keywords with 
backticks and the function definition with a `.. code-block:: python` so it 
gets rendered properly on the website.

https://github.com/llvm/llvm-project/pull/109062
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] Add the ability to define custom completers to the parsed_cmd template. (PR #109062)

2024-09-19 Thread Med Ismail Bennani via lldb-commits


@@ -43,7 +43,65 @@ def __call__(self, debugger, args_list, exe_ctx, result):
 will return True if the user set this option, and False if it was left at its 
default
 value.
 
-There are example commands in the lldb testsuite at:
+Custom Completions:
+
+You can also implement custom completers for your custom command, either for 
the
+arguments to your command or to the option values in your command.  If you use 
enum
+values or if your option/argument uses is one of the types we have completers 
for,
+you should not need to do this.  But if you have your own completeable types, 
or if
+you want completion of one option to be conditioned by other options on the 
command
+line, you can use this interface to take over the completion.  
+
+You can choose to add a completion for the option values defined for your 
command,
+or for the arguments, separately.  For the option values, define:
+
+def handle_option_argument_completion(self, long_option, cursor_pos):
+
+The line to be completed will be parsed up to the option containint the cursor 
position, 
+and the values will be set in the OptionValue parser object.  long_option will 
be
+the option name containing the cursor, and cursor_pos will be the position of 
the cursor
+in that option's value.  You can call the 
OVParser.dest_for_option(long_option) to get the
+value for that option.  The other options that came before the cursor in the 
command
+line will also be set in the OV Parser when the completion handler is called.
+
+For argument values, define:
+
+def handle_argument_completion(self, args, arg_pos, cursor_pos):
+

medismailben wrote:

ditto

https://github.com/llvm/llvm-project/pull/109062
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [lldb/Interpreter] Introduce `ScriptedStopHook{, Python}Interface` & make use of it (PR #105449)

2024-09-19 Thread Med Ismail Bennani via lldb-commits

https://github.com/medismailben updated 
https://github.com/llvm/llvm-project/pull/105449

>From 89ed41f52916bdc67d244488e5ee1d7da7c7bb90 Mon Sep 17 00:00:00 2001
From: Med Ismail Bennani 
Date: Tue, 20 Aug 2024 16:13:54 -0700
Subject: [PATCH 1/3] [lldb/Interpreter] Create
 ScriptedStopHook{,Python}Interface (NFC)

This patch introduces a new scripted interface for ScriptedStopHooks.

This will be used in a follow-up patch to call into the script methods.

Signed-off-by: Med Ismail Bennani 
---
 .../Interfaces/ScriptedStopHookInterface.h| 33 
 .../lldb/Interpreter/ScriptInterpreter.h  |  4 +
 lldb/include/lldb/lldb-forward.h  |  3 +
 .../Python/Interfaces/CMakeLists.txt  |  1 +
 .../ScriptInterpreterPythonInterfaces.cpp |  2 +
 .../ScriptInterpreterPythonInterfaces.h   |  1 +
 .../ScriptedStopHookPythonInterface.cpp   | 75 +++
 .../ScriptedStopHookPythonInterface.h | 50 +
 .../Python/ScriptInterpreterPython.cpp|  5 ++
 .../Python/ScriptInterpreterPythonImpl.h  |  2 +
 10 files changed, 176 insertions(+)
 create mode 100644 
lldb/include/lldb/Interpreter/Interfaces/ScriptedStopHookInterface.h
 create mode 100644 
lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/ScriptedStopHookPythonInterface.cpp
 create mode 100644 
lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/ScriptedStopHookPythonInterface.h

diff --git 
a/lldb/include/lldb/Interpreter/Interfaces/ScriptedStopHookInterface.h 
b/lldb/include/lldb/Interpreter/Interfaces/ScriptedStopHookInterface.h
new file mode 100644
index 00..125e7f2077b543
--- /dev/null
+++ b/lldb/include/lldb/Interpreter/Interfaces/ScriptedStopHookInterface.h
@@ -0,0 +1,33 @@
+//===-- ScriptedStopHookInterface.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_INTERPRETER_INTERFACES_SCRIPTEDSTOPHOOKINTERFACE_H
+#define LLDB_INTERPRETER_INTERFACES_SCRIPTEDSTOPHOOKINTERFACE_H
+
+#include "lldb/lldb-private.h"
+
+#include "ScriptedInterface.h"
+
+namespace lldb_private {
+class ScriptedStopHookInterface : public ScriptedInterface {
+public:
+  virtual llvm::Expected
+  CreatePluginObject(llvm::StringRef class_name, lldb::TargetSP target_sp,
+ const StructuredDataImpl &args_sp) = 0;
+
+  /// "handle_stop" will return a bool with the meaning "should_stop"...
+  /// If nothing is returned, we'll assume we are going to stop.
+  /// Also any errors should return true, since we should stop on error.
+  virtual llvm::Expected HandleStop(ExecutionContext &exe_ctx,
+  lldb::StreamSP output_sp) {
+return true;
+  }
+};
+} // namespace lldb_private
+
+#endif // LLDB_INTERPRETER_INTERFACES_SCRIPTEDSTOPHOOKINTERFACE_H
diff --git a/lldb/include/lldb/Interpreter/ScriptInterpreter.h 
b/lldb/include/lldb/Interpreter/ScriptInterpreter.h
index addb1394ab5652..8fabe6f250b084 100644
--- a/lldb/include/lldb/Interpreter/ScriptInterpreter.h
+++ b/lldb/include/lldb/Interpreter/ScriptInterpreter.h
@@ -561,6 +561,10 @@ class ScriptInterpreter : public PluginInterface {
 return {};
   }
 
+  virtual lldb::ScriptedStopHookInterfaceSP CreateScriptedStopHookInterface() {
+return {};
+  }
+
   virtual StructuredData::ObjectSP
   CreateStructuredDataFromScriptObject(ScriptObject obj) {
 return {};
diff --git a/lldb/include/lldb/lldb-forward.h b/lldb/include/lldb/lldb-forward.h
index 5fb288ad43af48..d09edeeccaff1a 100644
--- a/lldb/include/lldb/lldb-forward.h
+++ b/lldb/include/lldb/lldb-forward.h
@@ -190,6 +190,7 @@ class ScriptInterpreterLocker;
 class ScriptedMetadata;
 class ScriptedPlatformInterface;
 class ScriptedProcessInterface;
+class ScriptedStopHookInterface;
 class ScriptedThreadInterface;
 class ScriptedThreadPlanInterface;
 class ScriptedSyntheticChildren;
@@ -408,6 +409,8 @@ typedef 
std::unique_ptr
 ScriptedPlatformInterfaceUP;
 typedef std::unique_ptr
 ScriptedProcessInterfaceUP;
+typedef std::shared_ptr
+ScriptedStopHookInterfaceSP;
 typedef std::shared_ptr
 ScriptedThreadInterfaceSP;
 typedef std::shared_ptr
diff --git 
a/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/CMakeLists.txt 
b/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/CMakeLists.txt
index 6ba714ed1c263e..ee5e48ad5cdc37 100644
--- a/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/CMakeLists.txt
+++ b/lldb/source/Plugins/ScriptInterpreter/Python/Interfaces/CMakeLists.txt
@@ -25,6 +25,7 @@ add_lldb_library(lldbPluginScriptInterpreterPythonInterfaces 
PLUGIN
   ScriptedPlatformPythonInterface.cpp
   ScriptedProcessPythonInterface.cpp
   ScriptedPythonInterface.cpp
+  ScriptedStopHookPythonInterface.cp

[Lldb-commits] [lldb] Improve type and namespace lookup using parent chain (PR #108907)

2024-09-19 Thread via lldb-commits


@@ -374,25 +377,40 @@ void DebugNamesDWARFIndex::GetFullyQualifiedType(
   m_fallback.GetFullyQualifiedType(context, callback);
 }
 
+bool DebugNamesDWARFIndex::SameAsEntryATName(
+llvm::StringRef query_name, const DebugNames::Entry &entry) const {
+  auto maybe_dieoffset = entry.getDIEUnitOffset();
+  if (!maybe_dieoffset)
+return false;
+
+  // [Optimization] instead of parsing the entry from dwo file, we simply
+  // check if the query_name can point to an entry of the same DIE offset.
+  // This greatly reduced number of dwo file parsed and thus improved the
+  // performance.
+  for (const DebugNames::Entry &query_entry :
+   entry.getNameIndex()->equal_range(query_name)) {
+auto query_dieoffset = query_entry.getDIEUnitOffset();
+if (!query_dieoffset)
+  continue;
+
+if (*query_dieoffset == *maybe_dieoffset) {
+  return true;
+} else if (*query_dieoffset > *maybe_dieoffset) {
+  // The pool entries of the same name are sequentially cluttered together
+  // so if the query name from `query_name` is after the target entry, this
+  // is definitely not the correct one, we can stop searching.
+  return false;
+}
+  }
+  return false;
+}
+
 bool DebugNamesDWARFIndex::SameParentChain(
 llvm::ArrayRef parent_names,
 llvm::ArrayRef parent_entries) const {
-
   if (parent_entries.size() != parent_names.size())
 return false;
 
-  auto SameAsEntryATName = [this](llvm::StringRef name,
-  const DebugNames::Entry &entry) {
-// Peek at the AT_name of `entry` and test equality to `name`.
-auto maybe_dieoffset = entry.getDIEUnitOffset();
-if (!maybe_dieoffset)
-  return false;
-DWARFUnit *unit = GetNonSkeletonUnit(entry);
-if (!unit)
-  return false;
-return name == unit->PeekDIEName(unit->GetOffset() + *maybe_dieoffset);

jeffreytan81 wrote:

Sounds good. Let me try to build a target with split dwarf disable and measure 
the perf (not sure if I can use the same target because I might get debug_info 
or debug_str overflow). 

https://github.com/llvm/llvm-project/pull/108907
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] Improve type and namespace lookup using parent chain (PR #108907)

2024-09-19 Thread via lldb-commits


@@ -444,6 +492,98 @@ void DebugNamesDWARFIndex::GetNamespaces(
   m_fallback.GetNamespaces(name, callback);
 }
 
+void DebugNamesDWARFIndex::GetNamespacesWithParents(
+ConstString name, llvm::ArrayRef parent_names,
+llvm::function_ref callback) {
+  Progress progress("Get namespace from index for %s", name.GetCString());
+  for (const DebugNames::Entry &entry :
+   m_debug_names_up->equal_range(name.GetStringRef())) {
+lldb_private::dwarf::Tag entry_tag = entry.tag();
+if (entry_tag == DW_TAG_namespace ||
+entry_tag == DW_TAG_imported_declaration) {
+  std::optional> parent_chain =
+  getParentChain(entry);
+  if (!parent_chain) {
+// Fallback: use the base class implementation.
+if (!ProcessEntry(entry, [&](DWARFDIE die) {
+  return ProcessDieMatchParentNames(name, parent_names, die, 
callback);
+}))
+  return;
+continue;
+  }
+
+  if (parent_chain->size() < parent_names.size())
+continue;
+  else if (parent_chain->size() == parent_names.size()) {

jeffreytan81 wrote:

Sounds good. To make sure I understand, are you suggesting we always call 
`WithinParentChain()` from here, and `WithinParentChain()`'s implementation 
should dispatch to `SameParentChain()` if the entries are of same size? 

https://github.com/llvm/llvm-project/pull/108907
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] Improve type and namespace lookup using parent chain (PR #108907)

2024-09-19 Thread via lldb-commits


@@ -374,25 +377,40 @@ void DebugNamesDWARFIndex::GetFullyQualifiedType(
   m_fallback.GetFullyQualifiedType(context, callback);
 }
 
+bool DebugNamesDWARFIndex::SameAsEntryATName(
+llvm::StringRef query_name, const DebugNames::Entry &entry) const {
+  auto maybe_dieoffset = entry.getDIEUnitOffset();
+  if (!maybe_dieoffset)
+return false;
+
+  // [Optimization] instead of parsing the entry from dwo file, we simply
+  // check if the query_name can point to an entry of the same DIE offset.
+  // This greatly reduced number of dwo file parsed and thus improved the
+  // performance.
+  for (const DebugNames::Entry &query_entry :
+   entry.getNameIndex()->equal_range(query_name)) {
+auto query_dieoffset = query_entry.getDIEUnitOffset();
+if (!query_dieoffset)
+  continue;
+
+if (*query_dieoffset == *maybe_dieoffset) {
+  return true;
+} else if (*query_dieoffset > *maybe_dieoffset) {
+  // The pool entries of the same name are sequentially cluttered together
+  // so if the query name from `query_name` is after the target entry, this
+  // is definitely not the correct one, we can stop searching.

jeffreytan81 wrote:

@labath, @felipepiovezan, this assumption (pool entries of the same name are 
sequentially cluttered together) is actually guaranteed by dwarf5 specification:

Page 141:
```
The entry pool contains all the index entries, grouped by name. The second 
column of the name list points to the first index entry for the name, and all 
the index entries for that name are placed one after the other.
```

Also in `6.1.1.4.8 Entry Pool`:

```
Gaps are not allowed between entries in a series (that is, the entries for a 
single
10 name must all be contiguous), but there may be gaps between series.
```

I can add quoting of these sections in the comment if you think will make it 
clear. 


https://github.com/llvm/llvm-project/pull/108907
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] Improve type and namespace lookup using parent chain (PR #108907)

2024-09-19 Thread via lldb-commits


@@ -402,6 +420,36 @@ bool DebugNamesDWARFIndex::SameParentChain(
   return true;
 }
 
+bool DebugNamesDWARFIndex::WithinParentChain(
+llvm::ArrayRef query_parent_names,
+llvm::ArrayRef parent_chain) const {
+  if (parent_chain.size() < query_parent_names.size())
+return false;
+
+  size_t query_idx = 0, chain_idx = 0;
+  while (query_idx < query_parent_names.size() &&
+ chain_idx < parent_chain.size()) {
+if (SameAsEntryATName(query_parent_names[query_idx],
+  parent_chain[chain_idx])) {
+  ++query_idx;
+  ++chain_idx;
+} else {
+  // Name does not match, try next parent_chain entry if the current entry
+  // is namespace because the current one can be an inline namespace.

jeffreytan81 wrote:

Yeah, I would love to but I do not think .debug_names tag has information to 
filter it out. It simply encodes `DW_TAG_namespace` tag:
```
   Name 1748 {
  Hash: 0xB3EF34A4
  String: 0xae01 "inline_ns"
  Entry @ 0xb2d9 {
Abbrev: 0x5
Tag: DW_TAG_namespace
DW_IDX_die_offset: 0x00015df7
DW_IDX_parent: Entry @ 0xbab8
  }
}
```
I guess we could try to PeekDieName() to parse this DIE from dwo files to check 
if it is an inline vs non-inline namespace but that is the expensive code path 
this PR wants to avoid.

https://github.com/llvm/llvm-project/pull/108907
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] Improve type and namespace lookup using parent chain (PR #108907)

2024-09-19 Thread via lldb-commits


@@ -374,25 +377,40 @@ void DebugNamesDWARFIndex::GetFullyQualifiedType(
   m_fallback.GetFullyQualifiedType(context, callback);
 }
 
+bool DebugNamesDWARFIndex::SameAsEntryATName(
+llvm::StringRef query_name, const DebugNames::Entry &entry) const {
+  auto maybe_dieoffset = entry.getDIEUnitOffset();
+  if (!maybe_dieoffset)
+return false;
+
+  // [Optimization] instead of parsing the entry from dwo file, we simply
+  // check if the query_name can point to an entry of the same DIE offset.
+  // This greatly reduced number of dwo file parsed and thus improved the
+  // performance.
+  for (const DebugNames::Entry &query_entry :
+   entry.getNameIndex()->equal_range(query_name)) {
+auto query_dieoffset = query_entry.getDIEUnitOffset();
+if (!query_dieoffset)
+  continue;
+
+if (*query_dieoffset == *maybe_dieoffset) {
+  return true;
+} else if (*query_dieoffset > *maybe_dieoffset) {
+  // The pool entries of the same name are sequentially cluttered together
+  // so if the query name from `query_name` is after the target entry, this
+  // is definitely not the correct one, we can stop searching.
+  return false;
+}
+  }
+  return false;
+}
+
 bool DebugNamesDWARFIndex::SameParentChain(
 llvm::ArrayRef parent_names,
 llvm::ArrayRef parent_entries) const {
-
   if (parent_entries.size() != parent_names.size())
 return false;
 
-  auto SameAsEntryATName = [this](llvm::StringRef name,
-  const DebugNames::Entry &entry) {
-// Peek at the AT_name of `entry` and test equality to `name`.
-auto maybe_dieoffset = entry.getDIEUnitOffset();
-if (!maybe_dieoffset)
-  return false;
-DWARFUnit *unit = GetNonSkeletonUnit(entry);
-if (!unit)
-  return false;
-return name == unit->PeekDIEName(unit->GetOffset() + *maybe_dieoffset);

jeffreytan81 wrote:

Nevermind, I manually strip down the internal target debug info from 7GB => 
400MB so that it can be linked without split dwarf. 

Tested with `PeekDIEName()` vs this PR in two different code paths:
```
In the first path: 
PeekDIEName  1.2s 
This PR: 1.4s

In the second path:
PeekDIEName  1.999s
This PR: 1.720s
```

So they are about the same if not using split dwarf. And majority of the saving 
comes from split dwarf which avoiding parsing dwo files really matters. 

https://github.com/llvm/llvm-project/pull/108907
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [lldb/Interpreter] Introduce `ScriptedStopHook{, Python}Interface` & make use of it (PR #105449)

2024-09-19 Thread LLVM Continuous Integration via lldb-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder `lldb-x86_64-debian` 
running on `lldb-x86_64-debian` while building `lldb` at step 6 "test".

Full details are available at: 
https://lab.llvm.org/buildbot/#/builders/162/builds/6721


Here is the relevant piece of the build log for the reference

```
Step 6 (test) failure: build (failure)
...
6.835 [127/72/61] Building CXX object 
tools/lldb/unittests/Core/CMakeFiles/LLDBCoreTests.dir/ModuleSpecTest.cpp.o
6.844 [126/72/62] Building CXX object 
tools/lldb/unittests/Interpreter/CMakeFiles/InterpreterTests.dir/TestCompletion.cpp.o
7.045 [125/72/63] Building CXX object 
tools/lldb/unittests/Process/Linux/CMakeFiles/ProcessLinuxTests.dir/PerfTests.cpp.o
7.212 [124/72/64] Building CXX object 
tools/lldb/unittests/Core/CMakeFiles/LLDBCoreTests.dir/DiagnosticEventTest.cpp.o
7.396 [123/72/65] Building CXX object 
tools/lldb/unittests/Symbol/CMakeFiles/SymbolTests.dir/MangledTest.cpp.o
7.487 [122/72/66] Building CXX object 
tools/lldb/unittests/Core/CMakeFiles/LLDBCoreTests.dir/MangledTest.cpp.o
7.541 [121/72/67] Building CXX object 
tools/lldb/unittests/DataFormatter/CMakeFiles/LLDBFormatterTests.dir/FormatManagerTests.cpp.o
7.550 [120/72/68] Building CXX object 
tools/lldb/unittests/Core/CMakeFiles/LLDBCoreTests.dir/ProgressReportTest.cpp.o
7.575 [119/72/69] Building CXX object 
tools/lldb/unittests/Platform/CMakeFiles/LLDBPlatformTests.dir/PlatformAppleSimulatorTest.cpp.o
7.581 [118/72/70] Building CXX object 
tools/lldb/unittests/ScriptInterpreter/Python/CMakeFiles/ScriptInterpreterPythonTests.dir/PythonTestSuite.cpp.o
FAILED: 
tools/lldb/unittests/ScriptInterpreter/Python/CMakeFiles/ScriptInterpreterPythonTests.dir/PythonTestSuite.cpp.o
 
/usr/bin/clang++ -DGTEST_HAS_RTTI=0 -DHAVE_ROUND -DLLVM_BUILD_STATIC -D_DEBUG 
-D_GLIBCXX_ASSERTIONS -D_GNU_SOURCE -D__STDC_CONSTANT_MACROS 
-D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS 
-I/home/worker/2.0.1/lldb-x86_64-debian/build/tools/lldb/unittests/ScriptInterpreter/Python
 
-I/home/worker/2.0.1/lldb-x86_64-debian/llvm-project/lldb/unittests/ScriptInterpreter/Python
 -I/home/worker/2.0.1/lldb-x86_64-debian/llvm-project/lldb/include 
-I/home/worker/2.0.1/lldb-x86_64-debian/build/tools/lldb/include 
-I/home/worker/2.0.1/lldb-x86_64-debian/build/include 
-I/home/worker/2.0.1/lldb-x86_64-debian/llvm-project/llvm/include 
-I/usr/include/python3.11 
-I/home/worker/2.0.1/lldb-x86_64-debian/llvm-project/llvm/../clang/include 
-I/home/worker/2.0.1/lldb-x86_64-debian/build/tools/lldb/../clang/include 
-I/home/worker/2.0.1/lldb-x86_64-debian/llvm-project/lldb/source 
-I/home/worker/2.0.1/lldb-x86_64-debian/llvm-project/lldb/unittests 
-I/home/worker/2.0.1/lldb-x86_64-debian/llvm-project/third-party/unittest/googletest/include
 
-I/home/worker/2.0.1/lldb-x86_64-debian/llvm-project/third-party/unittest/googlemock/include
 -isystem /usr/include/libxml2 -fPIC -fno-semantic-interposition 
-fvisibility-inlines-hidden -Werror=date-time 
-Werror=unguarded-availability-new -Wall -Wextra -Wno-unused-parameter 
-Wwrite-strings -Wcast-qual -Wmissing-field-initializers -pedantic 
-Wno-long-long -Wc++98-compat-extra-semi -Wimplicit-fallthrough 
-Wcovered-switch-default -Wno-noexcept-type -Wnon-virtual-dtor 
-Wdelete-non-virtual-dtor -Wsuggest-override -Wstring-conversion 
-Wmisleading-indentation -Wctad-maybe-unsupported -fdiagnostics-color 
-ffunction-sections -fdata-sections -Wno-deprecated-declarations 
-Wno-unknown-pragmas -Wno-strict-aliasing -Wno-deprecated-register 
-Wno-vla-extension -O3 -DNDEBUG  -Wno-variadic-macros 
-Wno-gnu-zero-variadic-macro-arguments -fno-exceptions -funwind-tables 
-fno-rtti -UNDEBUG -Wno-suggest-override -std=c++17 -MD -MT 
tools/lldb/unittests/ScriptInterpreter/Python/CMakeFiles/ScriptInterpreterPythonTests.dir/PythonTestSuite.cpp.o
 -MF 
tools/lldb/unittests/ScriptInterpreter/Python/CMakeFiles/ScriptInterpreterPythonTests.dir/PythonTestSuite.cpp.o.d
 -o 
tools/lldb/unittests/ScriptInterpreter/Python/CMakeFiles/ScriptInterpreterPythonTests.dir/PythonTestSuite.cpp.o
 -c 
/home/worker/2.0.1/lldb-x86_64-debian/llvm-project/lldb/unittests/ScriptInterpreter/Python/PythonTestSuite.cpp
/home/worker/2.0.1/lldb-x86_64-debian/llvm-project/lldb/unittests/ScriptInterpreter/Python/PythonTestSuite.cpp:277:35:
 error: out-of-line definition of 'ToSWIGWrapper' does not match any 
declaration in 'lldb_private::python::SWIGBridge'
lldb_private::python::SWIGBridge::ToSWIGWrapper(const Status &status) {
  ^
/home/worker/2.0.1/lldb-x86_64-debian/llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/SWIGPythonBridge.h:89:37:
 note: type of 1st parameter of member declaration does not match definition 
('lldb_private::Status' vs 'const lldb_private::Status &')
  static PythonObject ToSWIGWrapper(Status status);
^
1 error generated.
7.626 [118/71/71] Building CXX object 
tools/lldb/unittests/Platform/CMakeFiles/LLDBPlatformTests.dir/

[Lldb-commits] [lldb] [lldb/DWARF] Downgrade the "parent of variable is not CU" error (PR #108806)

2024-09-19 Thread Pavel Labath via lldb-commits

https://github.com/labath closed 
https://github.com/llvm/llvm-project/pull/108806
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [lldb-dap] Add feature to remember last non-empty expression. (PR #107485)

2024-09-19 Thread Pavel Labath via lldb-commits

https://github.com/labath commented:

This works for me. Walter?

https://github.com/llvm/llvm-project/pull/107485
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [lldb-dap] Add feature to remember last non-empty expression. (PR #107485)

2024-09-19 Thread Pavel Labath via lldb-commits


@@ -45,7 +45,8 @@ bool RunLLDBCommands(llvm::StringRef prefix,
   // RunTerminateCommands.
   static std::mutex handle_command_mutex;
   std::lock_guard locker(handle_command_mutex);
-  interp.HandleCommand(command.str().c_str(), result);
+  interp.HandleCommand(command.str().c_str(), result,
+   /* add_to_history */ true);

labath wrote:

Okay, I see now. The comment threw me off, as I though this code handles 
commands which run during termination.

https://github.com/llvm/llvm-project/pull/107485
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [lldb-dap] Add feature to remember last non-empty expression. (PR #107485)

2024-09-19 Thread Pavel Labath via lldb-commits


@@ -54,13 +54,20 @@ def run_test_evaluate_expressions(
 line_number(source, "// breakpoint 5"),
 line_number(source, "// breakpoint 6"),
 line_number(source, "// breakpoint 7"),
+line_number(source, "// breakpoint 8"),
 ],
 )
 self.continue_to_next_stop()
 
 # Expressions at breakpoint 1, which is in main
 self.assertEvaluate("var1", "20")
+# Empty expression should equate to the previous expression.
+if context == "repl":
+self.assertEvaluate("", "20")

labath wrote:

```suggestion
self.assertEvaluate("", "20")
else:
self.assertEvaluateFailure("")
```
.. or something along those lines (I haven't checked whether this works) -- 
basically to check that the empty string does not repeat in non-repl contexts.

https://github.com/llvm/llvm-project/pull/107485
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [lldb-dap] Add feature to remember last non-empty expression. (PR #107485)

2024-09-19 Thread Pavel Labath via lldb-commits

https://github.com/labath edited 
https://github.com/llvm/llvm-project/pull/107485
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [lldb] refactor Target::Install function (PR #108996)

2024-09-19 Thread David Spickett via lldb-commits


@@ -76,6 +76,79 @@
 using namespace lldb;
 using namespace lldb_private;
 
+namespace {
+
+struct ExecutableInstaller {
+
+  ExecutableInstaller(PlatformSP platform, ModuleSP module)
+  : m_platform{platform}, m_module{module},
+m_local_file{m_module->GetFileSpec()},
+m_remote_file{m_module->GetRemoteInstallFileSpec()} {}
+
+  void setRemoteFile() const { m_module->SetPlatformFileSpec(m_remote_file); }
+
+  PlatformSP m_platform;
+  ModuleSP m_module;
+  const FileSpec m_local_file;
+  const FileSpec m_remote_file;
+};
+
+struct MainExecutableInstaller {
+
+  MainExecutableInstaller(PlatformSP platform, TargetSP target, ModuleSP 
module,
+  ProcessLaunchInfo *launch_info)
+  : m_platform{platform},  m_module{module},
+m_local_file{m_module->GetFileSpec()},
+m_remote_file{
+getRemoteFileSpec(m_platform, target, m_module, m_local_file)},
+m_launch_info{launch_info} {}
+
+  void setRemoteFile() const {
+m_module->SetPlatformFileSpec(m_remote_file);
+m_launch_info->SetExecutableFile(m_remote_file,
+ false /*add_exe_file_as_first_arg*/);
+m_platform->SetFilePermissions(m_remote_file, 0700 /*-rwx--*/);
+  }
+
+  PlatformSP m_platform;
+  ModuleSP m_module;
+  const FileSpec m_local_file;
+  const FileSpec m_remote_file;
+  ProcessLaunchInfo *m_launch_info;

DavidSpickett wrote:

Anything here that's not used outside the class should be private. I see local 
and remote file used not sure about the other ones.

https://github.com/llvm/llvm-project/pull/108996
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [lldb] refactor Target::Install function (PR #108996)

2024-09-19 Thread David Spickett via lldb-commits


@@ -76,6 +76,79 @@
 using namespace lldb;
 using namespace lldb_private;
 
+namespace {
+
+struct ExecutableInstaller {
+
+  ExecutableInstaller(PlatformSP platform, ModuleSP module)
+  : m_platform{platform}, m_module{module},
+m_local_file{m_module->GetFileSpec()},
+m_remote_file{m_module->GetRemoteInstallFileSpec()} {}
+
+  void setRemoteFile() const { m_module->SetPlatformFileSpec(m_remote_file); }
+
+  PlatformSP m_platform;
+  ModuleSP m_module;
+  const FileSpec m_local_file;
+  const FileSpec m_remote_file;
+};
+
+struct MainExecutableInstaller {
+
+  MainExecutableInstaller(PlatformSP platform, TargetSP target, ModuleSP 
module,
+  ProcessLaunchInfo *launch_info)
+  : m_platform{platform},  m_module{module},
+m_local_file{m_module->GetFileSpec()},
+m_remote_file{
+getRemoteFileSpec(m_platform, target, m_module, m_local_file)},
+m_launch_info{launch_info} {}
+
+  void setRemoteFile() const {
+m_module->SetPlatformFileSpec(m_remote_file);
+m_launch_info->SetExecutableFile(m_remote_file,
+ false /*add_exe_file_as_first_arg*/);
+m_platform->SetFilePermissions(m_remote_file, 0700 /*-rwx--*/);
+  }
+
+  PlatformSP m_platform;
+  ModuleSP m_module;
+  const FileSpec m_local_file;
+  const FileSpec m_remote_file;
+  ProcessLaunchInfo *m_launch_info;
+
+private:
+  static FileSpec getRemoteFileSpec(PlatformSP platform, TargetSP target,
+ModuleSP module,
+const FileSpec &local_file) {
+FileSpec remote_file = module->GetRemoteInstallFileSpec();
+if (remote_file || !target->GetAutoInstallMainExecutable())
+  return remote_file;
+
+if (!local_file)
+  return {};
+
+remote_file = platform->GetRemoteWorkingDirectory();
+remote_file.AppendPathComponent(local_file.GetFilename().GetCString());
+
+return remote_file;
+  }
+};
+} // namespace
+
+template 
+static Status installExecutable(const Installer &installer) {
+  if (!installer.m_local_file || !installer.m_remote_file)
+return Status();

DavidSpickett wrote:

This seems like it should be a failure, was it in the original code?

I guess this is saying that if we have a local file that does not need to be 
copied to a remote, or a file that exists on the remote already but not 
locally, there is no work to be done.

https://github.com/llvm/llvm-project/pull/108996
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [lldb] refactor Target::Install function (PR #108996)

2024-09-19 Thread David Spickett via lldb-commits


@@ -76,6 +76,79 @@
 using namespace lldb;
 using namespace lldb_private;
 
+namespace {
+
+struct ExecutableInstaller {
+
+  ExecutableInstaller(PlatformSP platform, ModuleSP module)
+  : m_platform{platform}, m_module{module},
+m_local_file{m_module->GetFileSpec()},
+m_remote_file{m_module->GetRemoteInstallFileSpec()} {}
+
+  void setRemoteFile() const { m_module->SetPlatformFileSpec(m_remote_file); }
+
+  PlatformSP m_platform;
+  ModuleSP m_module;
+  const FileSpec m_local_file;
+  const FileSpec m_remote_file;
+};
+
+struct MainExecutableInstaller {
+
+  MainExecutableInstaller(PlatformSP platform, TargetSP target, ModuleSP 
module,
+  ProcessLaunchInfo *launch_info)
+  : m_platform{platform},  m_module{module},
+m_local_file{m_module->GetFileSpec()},
+m_remote_file{
+getRemoteFileSpec(m_platform, target, m_module, m_local_file)},
+m_launch_info{launch_info} {}
+
+  void setRemoteFile() const {
+m_module->SetPlatformFileSpec(m_remote_file);
+m_launch_info->SetExecutableFile(m_remote_file,
+ false /*add_exe_file_as_first_arg*/);
+m_platform->SetFilePermissions(m_remote_file, 0700 /*-rwx--*/);
+  }
+
+  PlatformSP m_platform;
+  ModuleSP m_module;
+  const FileSpec m_local_file;
+  const FileSpec m_remote_file;
+  ProcessLaunchInfo *m_launch_info;
+
+private:
+  static FileSpec getRemoteFileSpec(PlatformSP platform, TargetSP target,
+ModuleSP module,
+const FileSpec &local_file) {
+FileSpec remote_file = module->GetRemoteInstallFileSpec();
+if (remote_file || !target->GetAutoInstallMainExecutable())
+  return remote_file;
+
+if (!local_file)
+  return {};
+
+remote_file = platform->GetRemoteWorkingDirectory();
+remote_file.AppendPathComponent(local_file.GetFilename().GetCString());
+
+return remote_file;
+  }
+};
+} // namespace
+
+template 

DavidSpickett wrote:

What's the reason to use a template function here, instead of making a base 
class with this as a method? Just avoiding the need for a vtable?

https://github.com/llvm/llvm-project/pull/108996
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [lldb] refactor Target::Install function (PR #108996)

2024-09-19 Thread David Spickett via lldb-commits


@@ -76,6 +76,79 @@
 using namespace lldb;
 using namespace lldb_private;
 
+namespace {
+
+struct ExecutableInstaller {
+
+  ExecutableInstaller(PlatformSP platform, ModuleSP module)
+  : m_platform{platform}, m_module{module},
+m_local_file{m_module->GetFileSpec()},
+m_remote_file{m_module->GetRemoteInstallFileSpec()} {}
+
+  void setRemoteFile() const { m_module->SetPlatformFileSpec(m_remote_file); }
+
+  PlatformSP m_platform;
+  ModuleSP m_module;
+  const FileSpec m_local_file;
+  const FileSpec m_remote_file;
+};
+
+struct MainExecutableInstaller {
+
+  MainExecutableInstaller(PlatformSP platform, TargetSP target, ModuleSP 
module,
+  ProcessLaunchInfo *launch_info)
+  : m_platform{platform},  m_module{module},
+m_local_file{m_module->GetFileSpec()},
+m_remote_file{
+getRemoteFileSpec(m_platform, target, m_module, m_local_file)},
+m_launch_info{launch_info} {}
+
+  void setRemoteFile() const {

DavidSpickett wrote:

Perhaps `setupRemoteFile(` instead? setRemoteFile looks like a member 
assignment method, but this doesn't have any arguments. And `setup` implies 
some work is being done, which it is but within the module and launch info in 
this case.

https://github.com/llvm/llvm-project/pull/108996
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [lldb] refactor Target::Install function (PR #108996)

2024-09-19 Thread David Spickett via lldb-commits


@@ -76,6 +76,79 @@
 using namespace lldb;
 using namespace lldb_private;
 
+namespace {
+
+struct ExecutableInstaller {
+
+  ExecutableInstaller(PlatformSP platform, ModuleSP module)
+  : m_platform{platform}, m_module{module},
+m_local_file{m_module->GetFileSpec()},
+m_remote_file{m_module->GetRemoteInstallFileSpec()} {}
+
+  void setRemoteFile() const { m_module->SetPlatformFileSpec(m_remote_file); }
+
+  PlatformSP m_platform;
+  ModuleSP m_module;
+  const FileSpec m_local_file;
+  const FileSpec m_remote_file;
+};
+
+struct MainExecutableInstaller {
+
+  MainExecutableInstaller(PlatformSP platform, TargetSP target, ModuleSP 
module,

DavidSpickett wrote:

I would put platform and module first, in the same order as 
ExecutableInstaller, then target and launch info. So that it's more clear what 
the extra parameters are.

https://github.com/llvm/llvm-project/pull/108996
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [lldb] refactor Target::Install function (PR #108996)

2024-09-19 Thread David Spickett via lldb-commits


@@ -76,6 +76,79 @@
 using namespace lldb;
 using namespace lldb_private;
 
+namespace {
+
+struct ExecutableInstaller {
+
+  ExecutableInstaller(PlatformSP platform, ModuleSP module)
+  : m_platform{platform}, m_module{module},
+m_local_file{m_module->GetFileSpec()},
+m_remote_file{m_module->GetRemoteInstallFileSpec()} {}
+
+  void setRemoteFile() const { m_module->SetPlatformFileSpec(m_remote_file); }
+
+  PlatformSP m_platform;
+  ModuleSP m_module;
+  const FileSpec m_local_file;
+  const FileSpec m_remote_file;
+};
+
+struct MainExecutableInstaller {
+
+  MainExecutableInstaller(PlatformSP platform, TargetSP target, ModuleSP 
module,
+  ProcessLaunchInfo *launch_info)
+  : m_platform{platform},  m_module{module},
+m_local_file{m_module->GetFileSpec()},
+m_remote_file{
+getRemoteFileSpec(m_platform, target, m_module, m_local_file)},
+m_launch_info{launch_info} {}
+
+  void setRemoteFile() const {
+m_module->SetPlatformFileSpec(m_remote_file);
+m_launch_info->SetExecutableFile(m_remote_file,
+ false /*add_exe_file_as_first_arg*/);

DavidSpickett wrote:

I like the comment but use the form `/*add_exe_file_as_first_arg=*/`. That 
enables clang-tidy to check the name matches the one in the caller.

https://github.com/llvm/llvm-project/pull/108996
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [lldb] refactor Target::Install function (PR #108996)

2024-09-19 Thread David Spickett via lldb-commits


@@ -76,6 +76,79 @@
 using namespace lldb;
 using namespace lldb_private;
 
+namespace {
+
+struct ExecutableInstaller {
+
+  ExecutableInstaller(PlatformSP platform, ModuleSP module)
+  : m_platform{platform}, m_module{module},
+m_local_file{m_module->GetFileSpec()},
+m_remote_file{m_module->GetRemoteInstallFileSpec()} {}
+
+  void setRemoteFile() const { m_module->SetPlatformFileSpec(m_remote_file); }
+
+  PlatformSP m_platform;
+  ModuleSP m_module;
+  const FileSpec m_local_file;
+  const FileSpec m_remote_file;
+};
+
+struct MainExecutableInstaller {
+
+  MainExecutableInstaller(PlatformSP platform, TargetSP target, ModuleSP 
module,
+  ProcessLaunchInfo *launch_info)

DavidSpickett wrote:

Could all these launch_info uses be references? Everything assumes that the 
pointer is not null.

https://github.com/llvm/llvm-project/pull/108996
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [lldb-dap][docs] Improve README (PR #109266)

2024-09-19 Thread Adrian Vogelsgesang via lldb-commits

https://github.com/vogelsgesang created 
https://github.com/llvm/llvm-project/pull/109266

* Document how to procure and configure the `lldb-dap` binary
* Improve documentation for `launch.json`:
   * Show the examples before the reference. Most new users just want to get 
going, and will only need the reference later on
   * Deduplicate the list of "launch" and "attach" config settings
   * Remove the `stopOnEntry` setting from "attach", since this is a 
launch-only setting
   * Document the previously undocumented settings `sourcePath`, 
`commandEscapePrefix`, `custom{Frame,Thread}Format`, `runInTerminal`
   * Add the settings `debuggerRoot` and `sourceMap` to the common section. So 
far they were documented as launch-only settings.
* Document that the Debug Console prints variables / expressions by default and 
that LLDB commands need to be escaped.

>From 02cd59cda789abbed42a26408cf05767cb2f8512 Mon Sep 17 00:00:00 2001
From: Adrian Vogelsgesang 
Date: Thu, 19 Sep 2024 11:45:29 +0200
Subject: [PATCH] [lldb-dap][docs] Improve README

* Document how to procure and configure the `lldb-dap` binary
* Improve documentation for `launch.json`:
   * Show the examples before the reference. Most new users just want to
 get going, and will only need the reference later on
   * Deduplicate the list of "launch" and "attach" config settings
   * Remove the `stopOnEntry` setting from "attach", since this is a
 launch-only setting
   * Document the previously undocumented settings `sourcePath`,
 `commandEscapePrefix`, `custom{Frame,Thread}Format`,
 `runInTerminal`
   * Add the settings `debuggerRoot` and `sourceMap` to the common
 section. So far they were documented as launch-only settings.
* Document that the Debug Console prints variables / expressions by
  default and that LLDB commands need to be escaped.
---
 lldb/tools/lldb-dap/README.md | 141 +++---
 1 file changed, 80 insertions(+), 61 deletions(-)

diff --git a/lldb/tools/lldb-dap/README.md b/lldb/tools/lldb-dap/README.md
index 11a14d29ab51e2..eddeab469d9345 100644
--- a/lldb/tools/lldb-dap/README.md
+++ b/lldb/tools/lldb-dap/README.md
@@ -1,71 +1,30 @@
 # LLDB DAP
 
-## `lldb-dap` Configurations
+## Procuring the `lldb-dap` binary
 
-The extension requires the `lldb-dap` (formerly `lldb-vscode`) binary. It is a
-command line tool that implements the [Debug Adapter
-Protocol](https://microsoft.github.io/debug-adapter-protocol/). It is used to 
power the Visual Studio Code extension but can also be used with other IDEs and 
editors that support DAP.
-The protocol is easy to run remotely and also can allow other tools and IDEs to
-get a full featured debugger with a well defined protocol.
+The extension requires the `lldb-dap` (formerly `lldb-vscode`) binary.
+This binary is not currently packaged with the VS-Code extension. 
 
-## Launching & Attaching Configuration
+There are multiple ways to obtain this binary:
+* build it from source (see [LLDB's build 
instructions](https://lldb.llvm.org/resources/build.html))
+* download it one of the relase packages from the [LLVM release 
page](https://github.com/llvm/llvm-project/releases/). The 
`LLVM-19.1.0-{operating_system}.tar.xz` packages contain a prebuilt `lldb-dap` 
binary.
+* contact your toolchain vendor
 
-Launching to attaching require you to create a [launch 
configuration](https://code.visualstudio.com/Docs/editor/debugging#_launch-configurations).
-This file defines arguments that get passed to `lldb-dap` and the 
configuration settings control how the launch or attach happens.
+By default, the VS-Code extension will expect to find `lldb-dap` in your 
`PATH`.
+Alternatively, you can explictly specify the location of the `lldb-dap` binary 
using the `lldb-dap.executable-path` setting.
 
-### Launch Configuration Settings
+### Usage with other editors
 
-When you launch a program with Visual Studio Code you will need to create a 
[launch.json](https://code.visualstudio.com/Docs/editor/debugging#_launch-configurations)
-file that defines how your program will be run. The JSON configuration file 
can contain the following `lldb-dap` specific launch key/value pairs:
+The `lldb-dap` binary is a command line tool that implements the [Debug 
Adapter Protocol](https://microsoft.github.io/debug-adapter-protocol/).
+It is used to power the Visual Studio Code extension but can also be used with 
other IDEs and editors that support DAP.
+The protocol is easy to run remotely and also can allow other tools and IDEs 
to get a full featured debugger with a well defined protocol.
 
-|parameter  |type|req | |
-|---||:--:|-|
-|**name**   |string|Y| A configuration name that will be displayed in 
the IDE.
-|**type**   |string|Y| Must be "lldb-dap".
-|**request**|string|Y| Must be "launch".
-|**program**|string|Y| Path to the executable to launch.
-|**args**   |[string]|| An array of command li

[Lldb-commits] [lldb] [lldb-dap][docs] Improve README (PR #109266)

2024-09-19 Thread via lldb-commits

llvmbot wrote:




@llvm/pr-subscribers-lldb

Author: Adrian Vogelsgesang (vogelsgesang)


Changes

* Document how to procure and configure the `lldb-dap` binary
* Improve documentation for `launch.json`:
   * Show the examples before the reference. Most new users just want to get 
going, and will only need the reference later on
   * Deduplicate the list of "launch" and "attach" config settings
   * Remove the `stopOnEntry` setting from "attach", since this is a 
launch-only setting
   * Document the previously undocumented settings `sourcePath`, 
`commandEscapePrefix`, `custom{Frame,Thread}Format`, `runInTerminal`
   * Add the settings `debuggerRoot` and `sourceMap` to the common section. So 
far they were documented as launch-only settings.
* Document that the Debug Console prints variables / expressions by default and 
that LLDB commands need to be escaped.

---
Full diff: https://github.com/llvm/llvm-project/pull/109266.diff


1 Files Affected:

- (modified) lldb/tools/lldb-dap/README.md (+80-61) 


``diff
diff --git a/lldb/tools/lldb-dap/README.md b/lldb/tools/lldb-dap/README.md
index 11a14d29ab51e2..eddeab469d9345 100644
--- a/lldb/tools/lldb-dap/README.md
+++ b/lldb/tools/lldb-dap/README.md
@@ -1,71 +1,30 @@
 # LLDB DAP
 
-## `lldb-dap` Configurations
+## Procuring the `lldb-dap` binary
 
-The extension requires the `lldb-dap` (formerly `lldb-vscode`) binary. It is a
-command line tool that implements the [Debug Adapter
-Protocol](https://microsoft.github.io/debug-adapter-protocol/). It is used to 
power the Visual Studio Code extension but can also be used with other IDEs and 
editors that support DAP.
-The protocol is easy to run remotely and also can allow other tools and IDEs to
-get a full featured debugger with a well defined protocol.
+The extension requires the `lldb-dap` (formerly `lldb-vscode`) binary.
+This binary is not currently packaged with the VS-Code extension. 
 
-## Launching & Attaching Configuration
+There are multiple ways to obtain this binary:
+* build it from source (see [LLDB's build 
instructions](https://lldb.llvm.org/resources/build.html))
+* download it one of the relase packages from the [LLVM release 
page](https://github.com/llvm/llvm-project/releases/). The 
`LLVM-19.1.0-{operating_system}.tar.xz` packages contain a prebuilt `lldb-dap` 
binary.
+* contact your toolchain vendor
 
-Launching to attaching require you to create a [launch 
configuration](https://code.visualstudio.com/Docs/editor/debugging#_launch-configurations).
-This file defines arguments that get passed to `lldb-dap` and the 
configuration settings control how the launch or attach happens.
+By default, the VS-Code extension will expect to find `lldb-dap` in your 
`PATH`.
+Alternatively, you can explictly specify the location of the `lldb-dap` binary 
using the `lldb-dap.executable-path` setting.
 
-### Launch Configuration Settings
+### Usage with other editors
 
-When you launch a program with Visual Studio Code you will need to create a 
[launch.json](https://code.visualstudio.com/Docs/editor/debugging#_launch-configurations)
-file that defines how your program will be run. The JSON configuration file 
can contain the following `lldb-dap` specific launch key/value pairs:
+The `lldb-dap` binary is a command line tool that implements the [Debug 
Adapter Protocol](https://microsoft.github.io/debug-adapter-protocol/).
+It is used to power the Visual Studio Code extension but can also be used with 
other IDEs and editors that support DAP.
+The protocol is easy to run remotely and also can allow other tools and IDEs 
to get a full featured debugger with a well defined protocol.
 
-|parameter  |type|req | |
-|---||:--:|-|
-|**name**   |string|Y| A configuration name that will be displayed in 
the IDE.
-|**type**   |string|Y| Must be "lldb-dap".
-|**request**|string|Y| Must be "launch".
-|**program**|string|Y| Path to the executable to launch.
-|**args**   |[string]|| An array of command line argument strings to 
be passed to the program being launched.
-|**cwd**|string| | The program working directory.
-|**env**|dictionary| | Environment variables to set when launching 
the program. The format of each environment variable string is "VAR=VALUE" for 
environment variables with values or just "VAR" for environment variables with 
no values.
-|**stopOnEntry**|boolean| | Whether to stop program immediately after 
launching.
-|**initCommands**   |[string]| | LLDB commands executed upon debugger startup 
prior to creating the LLDB target. Commands and command output will be sent to 
the debugger console when they are executed.
-|**preRunCommands** |[string]| | LLDB commands executed just before launching 
after the LLDB target has been created. Commands and command output will be 
sent to the debugger console when they are executed.
-|**stopCommands**   |[string]| | LLDB commands executed jus

[Lldb-commits] [lldb] [lldb-dap][docs] Improve README (PR #109266)

2024-09-19 Thread Adrian Vogelsgesang via lldb-commits

https://github.com/vogelsgesang updated 
https://github.com/llvm/llvm-project/pull/109266

>From 006f7cbe4aa1621b9490ae534ea6e17f56e3f6af Mon Sep 17 00:00:00 2001
From: Adrian Vogelsgesang 
Date: Thu, 19 Sep 2024 11:45:29 +0200
Subject: [PATCH] [lldb-dap][docs] Improve README

* Document how to procure and configure the `lldb-dap` binary
* Improve documentation for `launch.json`:
   * Show the examples before the reference. Most new users just want to
 get going, and will only need the reference later on
   * Deduplicate the list of "launch" and "attach" config settings
   * Remove the `stopOnEntry` setting from "attach", since this is a
 launch-only setting
   * Document the previously undocumented settings `sourcePath`,
 `commandEscapePrefix`, `custom{Frame,Thread}Format`,
 `runInTerminal`
   * Add the settings `debuggerRoot` and `sourceMap` to the common
 section. So far they were documented as launch-only settings.
* Document that the Debug Console prints variables / expressions by
  default and that LLDB commands need to be escaped.
---
 lldb/tools/lldb-dap/README.md | 150 +++---
 1 file changed, 86 insertions(+), 64 deletions(-)

diff --git a/lldb/tools/lldb-dap/README.md b/lldb/tools/lldb-dap/README.md
index 11a14d29ab51e2..f757c25fa3ab2c 100644
--- a/lldb/tools/lldb-dap/README.md
+++ b/lldb/tools/lldb-dap/README.md
@@ -1,71 +1,30 @@
 # LLDB DAP
 
-## `lldb-dap` Configurations
+## Procuring the `lldb-dap` binary
 
-The extension requires the `lldb-dap` (formerly `lldb-vscode`) binary. It is a
-command line tool that implements the [Debug Adapter
-Protocol](https://microsoft.github.io/debug-adapter-protocol/). It is used to 
power the Visual Studio Code extension but can also be used with other IDEs and 
editors that support DAP.
-The protocol is easy to run remotely and also can allow other tools and IDEs to
-get a full featured debugger with a well defined protocol.
+The extension requires the `lldb-dap` (formerly `lldb-vscode`) binary.
+This binary is not currently packaged with the VS-Code extension. 
 
-## Launching & Attaching Configuration
+There are multiple ways to obtain this binary:
+* build it from source (see [LLDB's build 
instructions](https://lldb.llvm.org/resources/build.html))
+* download it one of the relase packages from the [LLVM release 
page](https://github.com/llvm/llvm-project/releases/). The 
`LLVM-19.1.0-{operating_system}.tar.xz` packages contain a prebuilt `lldb-dap` 
binary.
+* contact your toolchain vendor
 
-Launching to attaching require you to create a [launch 
configuration](https://code.visualstudio.com/Docs/editor/debugging#_launch-configurations).
-This file defines arguments that get passed to `lldb-dap` and the 
configuration settings control how the launch or attach happens.
-
-### Launch Configuration Settings
-
-When you launch a program with Visual Studio Code you will need to create a 
[launch.json](https://code.visualstudio.com/Docs/editor/debugging#_launch-configurations)
-file that defines how your program will be run. The JSON configuration file 
can contain the following `lldb-dap` specific launch key/value pairs:
-
-|parameter  |type|req | |
-|---||:--:|-|
-|**name**   |string|Y| A configuration name that will be displayed in 
the IDE.
-|**type**   |string|Y| Must be "lldb-dap".
-|**request**|string|Y| Must be "launch".
-|**program**|string|Y| Path to the executable to launch.
-|**args**   |[string]|| An array of command line argument strings to 
be passed to the program being launched.
-|**cwd**|string| | The program working directory.
-|**env**|dictionary| | Environment variables to set when launching 
the program. The format of each environment variable string is "VAR=VALUE" for 
environment variables with values or just "VAR" for environment variables with 
no values.
-|**stopOnEntry**|boolean| | Whether to stop program immediately after 
launching.
-|**initCommands**   |[string]| | LLDB commands executed upon debugger startup 
prior to creating the LLDB target. Commands and command output will be sent to 
the debugger console when they are executed.
-|**preRunCommands** |[string]| | LLDB commands executed just before launching 
after the LLDB target has been created. Commands and command output will be 
sent to the debugger console when they are executed.
-|**stopCommands**   |[string]| | LLDB commands executed just after each stop. 
Commands and command output will be sent to the debugger console when they are 
executed.
-|**launchCommands** |[string]| | LLDB commands executed to launch the program. 
Commands and command output will be sent to the debugger console when they are 
executed.
-|**exitCommands**   |[string]| | LLDB commands executed when the program 
exits. Commands and command output will be sent to the debugger console when 
they are executed.
-|**terminateCommands** |[str

[Lldb-commits] [lldb] [lldb-dap] Support inspecting memory (PR #104317)

2024-09-19 Thread Pavel Labath via lldb-commits

https://github.com/labath commented:

Sorry for being late to the party. I don't usually follow lldb-dap patches, but 
the mention of memory reads and windows errors intrigued me.

I don't think this is a good approach to reading memory. You shouldn't trust 
GetMemoryRegionInfo over ReadMemory. The data returned by the first may not be 
always there, and (in case of linux, at least), it will return the memory 
permissions in effect for the debugged application. The debugger can bypass 
(most of) those restrictions and also access memory that's unreadable to the 
debugged process.

The method I'd recommend is to call `ReadMemory`, and then if (and only if) it 
returns a partial (or no) result, consult the memory region info, to find the 
size of the unreadable region (by querying for the memory region containing the 
first byte that could not be read).

It's possible you had to do it this way, since before #106532 (and it looks 
like you started this patch before that), truncated reads did not work (on 
linux, at least), but it should be possible to do it now.

That should also avoid all of the business with being limited to a single 
memory region, since crossing from one readable region to another would be 
handled inside ReadMemory.

https://github.com/llvm/llvm-project/pull/104317
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] Improve type and namespace lookup using parent chain (PR #108907)

2024-09-19 Thread Pavel Labath via lldb-commits

https://github.com/labath commented:

> Ping, anyone wants to review this? Thanks

The usual ping time is one week, and this is definitely one of the more nuanced 
patches, which usually take a longer time to review.

This isn't really a review, just noting something that caught my eye.

I'm also not sure where's the " NameEntry> mapping table" 
you mention in the description. Could you point me to it?

https://github.com/llvm/llvm-project/pull/108907
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] Improve type and namespace lookup using parent chain (PR #108907)

2024-09-19 Thread Pavel Labath via lldb-commits


@@ -374,25 +377,40 @@ void DebugNamesDWARFIndex::GetFullyQualifiedType(
   m_fallback.GetFullyQualifiedType(context, callback);
 }
 
+bool DebugNamesDWARFIndex::SameAsEntryATName(
+llvm::StringRef query_name, const DebugNames::Entry &entry) const {
+  auto maybe_dieoffset = entry.getDIEUnitOffset();
+  if (!maybe_dieoffset)
+return false;
+
+  // [Optimization] instead of parsing the entry from dwo file, we simply
+  // check if the query_name can point to an entry of the same DIE offset.
+  // This greatly reduced number of dwo file parsed and thus improved the
+  // performance.
+  for (const DebugNames::Entry &query_entry :
+   entry.getNameIndex()->equal_range(query_name)) {
+auto query_dieoffset = query_entry.getDIEUnitOffset();
+if (!query_dieoffset)
+  continue;
+
+if (*query_dieoffset == *maybe_dieoffset) {
+  return true;
+} else if (*query_dieoffset > *maybe_dieoffset) {
+  // The pool entries of the same name are sequentially cluttered together
+  // so if the query name from `query_name` is after the target entry, this
+  // is definitely not the correct one, we can stop searching.

labath wrote:

That may be the case for clang, but I don't think anything guarantees that. 
This sounds like the kind of thing that we could communicate through the 
augmentation string of the debug_names table though... 

I.e. I think we shouldn't do this unconditionally, but only if the producer 
signals this through the augmentation string. We could possibly even retcon the 
LLVM0700 string which has been emitted by llvm/clang from the beginning of time 
(if indeed the output has been sorted the whole time).

We should probably also add some tests/comments/etc. to the producer code to 
make sure they realize we're relying on that.

https://github.com/llvm/llvm-project/pull/108907
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] Improve type and namespace lookup using parent chain (PR #108907)

2024-09-19 Thread Pavel Labath via lldb-commits

https://github.com/labath edited 
https://github.com/llvm/llvm-project/pull/108907
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [llvm] [lldb][RISCV] function calls support in lldb expressions (PR #99336)

2024-09-19 Thread Michael Buch via lldb-commits

https://github.com/Michael137 approved this pull request.

LGTM too

But please wait a bit for @lhames to chime in about the `RuntimeDyld` changes 
in case he has any comments/ideas for testing those

https://github.com/llvm/llvm-project/pull/99336
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [lldb] Store expression evaluator diagnostics in an llvm::Error (NFC) (PR #106442)

2024-09-19 Thread Pavel Labath via lldb-commits




labath wrote:

Any chance of a test case for the Diagnostic->DetailedExpressionError 
conversion?

https://github.com/llvm/llvm-project/pull/106442
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [lldb] Store expression evaluator diagnostics in an llvm::Error (NFC) (PR #106442)

2024-09-19 Thread Pavel Labath via lldb-commits


@@ -328,18 +328,20 @@ UserExpression::Evaluate(ExecutionContext &exe_ctx,
 }
 
 if (!parse_success) {
-  std::string msg;
-  {
-llvm::raw_string_ostream os(msg);
-if (!diagnostic_manager.Diagnostics().empty())
-  os << diagnostic_manager.GetString();
-else
-  os << "expression failed to parse (no further compiler diagnostics)";
-if (target->GetEnableNotifyAboutFixIts() && fixed_expression &&
-!fixed_expression->empty())
-  os << "\nfixed expression suggested:\n  " << *fixed_expression;
+  if (target->GetEnableNotifyAboutFixIts() && fixed_expression &&
+  !fixed_expression->empty()) {
+std::string fixit =
+"fixed expression suggested:\n  " + *fixed_expression;
+diagnostic_manager.AddDiagnostic(fixit, lldb::eSeverityInfo,
+ eDiagnosticOriginLLDB);
   }
-  error = Status::FromExpressionError(execution_results, msg);
+  if (!diagnostic_manager.Diagnostics().size())

labath wrote:

```suggestion
  if (diagnostic_manager.Diagnostics().empty())
```

https://github.com/llvm/llvm-project/pull/106442
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [lldb] Store expression evaluator diagnostics in an llvm::Error (NFC) (PR #106442)

2024-09-19 Thread Pavel Labath via lldb-commits


@@ -254,14 +255,46 @@ class ClangDiagnosticManagerAdapter : public 
clang::DiagnosticConsumer {
   std::string stripped_output =
   std::string(llvm::StringRef(m_output).trim());
 
-  auto new_diagnostic = std::make_unique(
-  stripped_output, severity, Info.getID());
+  // Translate the source location.
+  if (Info.hasSourceManager()) {
+DiagnosticDetail::SourceLocation loc;
+clang::SourceManager &sm = Info.getSourceManager();
+const clang::SourceLocation sloc = Info.getLocation();
+if (sloc.isValid()) {
+  const clang::FullSourceLoc fsloc(sloc, sm);
+  clang::PresumedLoc PLoc = fsloc.getPresumedLoc(true);
+  StringRef filename =
+  PLoc.isValid() ? PLoc.getFilename() : StringRef{};
+  loc.file = FileSpec(filename);
+  loc.line = fsloc.getSpellingLineNumber();
+  loc.column = fsloc.getSpellingColumnNumber();
+  // A heuristic detecting the #line 1 "".
+  loc.in_user_input = filename.starts_with(" T FOO(T x) { return x/2; }
(lldb) expr -- FOO(4.0)
(double) $0 = 2
(lldb) expr -- FOO("")
error: :1:43: invalid operands to binary expression ('const 
char *' and 'int')
1 | template T FOO(T x) { return x/2; }
  |  ~^~
:1:1: in instantiation of function template specialization 
'FOO' requested here
1 | FOO("")
  | ^
```
Which one of these diagnostics should have `in_user_input` set?

https://github.com/llvm/llvm-project/pull/106442
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [llvm] [lldb][RISCV] function calls support in lldb expressions (PR #99336)

2024-09-19 Thread via lldb-commits


@@ -279,6 +279,9 @@ void IRExecutionUnit::GetRunnableInfo(Status &error, 
lldb::addr_t &func_addr,
   .setMCJITMemoryManager(std::make_unique(*this))
   .setOptLevel(llvm::CodeGenOptLevel::Less);
 
+  if (triple.isRISCV64())

dlav-sc wrote:

addressed

https://github.com/llvm/llvm-project/pull/99336
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [llvm] [lldb][RISCV] function calls support in lldb expressions (PR #99336)

2024-09-19 Thread via lldb-commits

https://github.com/dlav-sc edited 
https://github.com/llvm/llvm-project/pull/99336
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [clang] [lldb] [llvm] [mlir] [APInt] Assert correct values in APInt constructor (PR #80309)

2024-09-19 Thread Nikita Popov via lldb-commits

https://github.com/nikic updated https://github.com/llvm/llvm-project/pull/80309

>From f47b38cd26107108f082df437196832fbe9ad78d Mon Sep 17 00:00:00 2001
From: Nikita Popov 
Date: Thu, 19 Sep 2024 17:27:13 +0200
Subject: [PATCH] apint only

---
 clang/lib/AST/ByteCode/IntegralAP.h   |   6 +-
 clang/lib/CodeGen/CGVTT.cpp   |   4 +-
 clang/lib/CodeGen/ItaniumCXXABI.cpp   |   4 +-
 clang/lib/Parse/ParseInit.cpp |   4 +-
 clang/lib/Sema/SemaExpr.cpp   |   7 +-
 clang/lib/Sema/SemaOpenMP.cpp |   4 +-
 lldb/source/Expression/DWARFExpression.cpp|   7 +-
 llvm/include/llvm/ADT/APFixedPoint.h  |   4 +-
 llvm/include/llvm/ADT/APInt.h |   2 +-
 llvm/lib/Analysis/ConstantFolding.cpp |   3 +-
 llvm/lib/Analysis/Loads.cpp   |   6 +-
 llvm/lib/Analysis/MemoryBuiltins.cpp  |   2 +
 llvm/lib/Analysis/ScalarEvolution.cpp |   2 +-
 llvm/lib/Bitcode/Reader/BitcodeReader.cpp |   3 +-
 .../lib/CodeGen/SelectionDAG/SelectionDAG.cpp |   5 +-
 .../SelectionDAG/SelectionDAGBuilder.cpp  |   3 +-
 .../CodeGen/SelectionDAG/SelectionDAGISel.cpp |   4 +-
 .../CodeGen/SelectionDAG/TargetLowering.cpp   |   8 +-
 llvm/lib/ExecutionEngine/MCJIT/MCJIT.cpp  |   2 +-
 llvm/lib/IR/Constants.cpp |   4 +-
 .../Target/AArch64/AArch64ISelLowering.cpp|  32 ++--
 llvm/lib/Target/AMDGPU/AMDGPUISelDAGToDAG.cpp |   2 +-
 .../AMDGPU/AMDGPUInstructionSelector.cpp  |   2 +-
 .../Disassembler/AMDGPUDisassembler.cpp   |   2 +-
 .../MCTargetDesc/AMDGPUMCTargetDesc.cpp   |   2 +-
 llvm/lib/Target/AMDGPU/SIInstrInfo.cpp|  13 +-
 .../Target/AMDGPU/SIShrinkInstructions.cpp|   4 +-
 .../lib/Target/ARM/AsmParser/ARMAsmParser.cpp |   4 +-
 .../Hexagon/HexagonConstPropagation.cpp   |   3 +-
 llvm/lib/Target/Hexagon/HexagonGenExtract.cpp |   2 +-
 llvm/lib/Target/RISCV/RISCVISelLowering.cpp   |   4 +-
 llvm/lib/Target/X86/X86ISelLowering.cpp   |   6 +-
 llvm/lib/Transforms/IPO/ArgumentPromotion.cpp |   3 +-
 llvm/lib/Transforms/Utils/SimplifyCFG.cpp |   2 +-
 llvm/unittests/ADT/APFixedPointTest.cpp   |   9 +-
 llvm/unittests/ADT/APIntTest.cpp  | 180 +-
 llvm/unittests/ADT/APSIntTest.cpp |   8 +-
 llvm/unittests/ADT/StringExtrasTest.cpp   |  10 +-
 .../Analysis/ScalarEvolutionTest.cpp  |   2 +-
 llvm/unittests/IR/MetadataTest.cpp|  22 ++-
 .../Support/DivisionByConstantTest.cpp|   2 +-
 mlir/include/mlir/IR/BuiltinAttributes.td |   4 +-
 mlir/include/mlir/IR/OpImplementation.h   |   3 +-
 .../Conversion/TosaToArith/TosaToArith.cpp|   2 +-
 .../Dialect/ControlFlow/IR/ControlFlowOps.cpp |   2 +-
 mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp|   2 +-
 mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp  |   2 +-
 mlir/lib/IR/Builders.cpp  |  16 +-
 .../SPIRV/Deserialization/Deserializer.cpp|   6 +-
 .../Dialect/SPIRV/SerializationTest.cpp   |   2 +-
 50 files changed, 246 insertions(+), 191 deletions(-)

diff --git a/clang/lib/AST/ByteCode/IntegralAP.h 
b/clang/lib/AST/ByteCode/IntegralAP.h
index a4d656433344b7..6ab3d09ec85d5b 100644
--- a/clang/lib/AST/ByteCode/IntegralAP.h
+++ b/clang/lib/AST/ByteCode/IntegralAP.h
@@ -61,7 +61,7 @@ template  class IntegralAP final {
 
   IntegralAP(APInt V) : V(V) {}
   /// Arbitrary value for uninitialized variables.
-  IntegralAP() : IntegralAP(-1, 3) {}
+  IntegralAP() : IntegralAP(Signed ? -1 : 7, 3) {}
 
   IntegralAP operator-() const { return IntegralAP(-V); }
   IntegralAP operator-(const IntegralAP &Other) const {
@@ -112,7 +112,9 @@ template  class IntegralAP final {
 
   template 
   static IntegralAP from(Integral I, unsigned BitWidth) {
-APInt Copy = APInt(BitWidth, static_cast(I), InputSigned);
+// TODO: Avoid implicit trunc?
+APInt Copy = APInt(BitWidth, static_cast(I), InputSigned,
+   /*implicitTrunc=*/true);
 
 return IntegralAP(Copy);
   }
diff --git a/clang/lib/CodeGen/CGVTT.cpp b/clang/lib/CodeGen/CGVTT.cpp
index 20bd2c2fc2c642..c861e1f9203058 100644
--- a/clang/lib/CodeGen/CGVTT.cpp
+++ b/clang/lib/CodeGen/CGVTT.cpp
@@ -85,8 +85,8 @@ CodeGenVTables::EmitVTTDefinition(llvm::GlobalVariable *VTT,
  cast(VTable->getValueType())
  ->getElementType(AddressPoint.VTableIndex));
  unsigned Offset = ComponentSize * AddressPoint.AddressPointIndex;
- llvm::ConstantRange InRange(llvm::APInt(32, -Offset, true),
- llvm::APInt(32, VTableSize - Offset, true));
+ llvm::ConstantRange InRange(llvm::APInt(32, -Offset),
+ llvm::APInt(32, VTableSize - Offset));
  llvm::Constant *Init = llvm::ConstantExpr::getGetElementPtr(
  VTable->getValueType(), VTable, Idxs, /*InBounds=*/true, InRange);
 
diff --git a/clang/lib/CodeGen/ItaniumCXXABI.cpp 
b/clang/lib/CodeGen/ItaniumCXX

[Lldb-commits] [lldb] 104b249 - [lldb] Change the implementation of Status to store an llvm::Error (NFC) (#106774)

2024-09-19 Thread Adrian Prantl via lldb-commits

Author: Adrian Prantl
Date: 2024-09-19T10:07:13-07:00
New Revision: 104b249c236578d298384416c495ff7310b97f4d

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

LOG: [lldb] Change the implementation of Status to store an llvm::Error (NFC) 
(#106774)

(based on a conversation I had with @labath yesterday in
https://github.com/llvm/llvm-project/pull/106442)

Most APIs that currently vend a Status would be better served by
returning llvm::Expected<> instead. If possibles APIs should be
refactored to avoid Status. The only legitimate long-term uses of Status
are objects that need to store an error for a long time (which should be
questioned as a design decision, too).

This patch makes the transition to llvm::Error easier by making the
places that cannot switch to llvm::Error explicit: They are marked with
a call to Status::clone(). Every other API can and should be refactored
to use llvm::Expected. In the end Status should only be used in very few
places.

Whenever an unchecked Error is dropped by Status it logs this to the
verbose API channel.

Implementation notes:

This patch introduces two new kinds of error_category as well as new
llvm::Error types. Here is the mapping of lldb::ErrorType to
llvm::Errors:
```
   (eErrorTypeInvalid)
   eErrorTypeGeneric  llvm::StringError
   eErrorTypePOSIXllvm::ECError
   eErrorTypeMachKernel   MachKernelError
   eErrorTypeExpression   llvm::ErrorList
   eErrorTypeWin32Win32Error
```

Relanding with built-in cloning support for llvm::ECError.

Added: 


Modified: 
lldb/include/lldb/Utility/Status.h
lldb/source/Plugins/ScriptInterpreter/Python/PythonDataObjects.cpp
lldb/source/Utility/Status.cpp
lldb/unittests/Utility/StatusTest.cpp

Removed: 




diff  --git a/lldb/include/lldb/Utility/Status.h 
b/lldb/include/lldb/Utility/Status.h
index 795c830b965173..084ce4afb8cefd 100644
--- a/lldb/include/lldb/Utility/Status.h
+++ b/lldb/include/lldb/Utility/Status.h
@@ -28,6 +28,67 @@ namespace lldb_private {
 
 const char *ExpressionResultAsCString(lldb::ExpressionResults result);
 
+/// Going a bit against the spirit of llvm::Error,
+/// lldb_private::Status need to store errors long-term and sometimes
+/// copy them. This base class defines an interface for this
+/// operation.
+class CloneableError
+: public llvm::ErrorInfo {
+public:
+  using llvm::ErrorInfo::ErrorInfo;
+  CloneableError() : ErrorInfo() {}
+  virtual std::unique_ptr Clone() const = 0;
+  static char ID;
+};
+
+/// Common base class for all error-code errors.
+class CloneableECError
+: public llvm::ErrorInfo {
+public:
+  using llvm::ErrorInfo::ErrorInfo;
+  std::error_code convertToErrorCode() const override { return EC; }
+  void log(llvm::raw_ostream &OS) const override { OS << EC.message(); }
+  static char ID;
+
+protected:
+  CloneableECError() = delete;
+  CloneableECError(std::error_code ec) : ErrorInfo(), EC(ec) {}
+  std::error_code EC;
+};
+/// FIXME: Move these declarations closer to where they're used.
+class MachKernelError
+: public llvm::ErrorInfo {
+public:
+  using llvm::ErrorInfo::ErrorInfo;
+  MachKernelError(std::error_code ec) : ErrorInfo(ec) {}
+  std::string message() const override;
+  std::unique_ptr Clone() const override;
+  static char ID;
+};
+
+class Win32Error : public llvm::ErrorInfo {
+public:
+  using llvm::ErrorInfo::ErrorInfo;
+  Win32Error(std::error_code ec, const llvm::Twine &msg = {}) : ErrorInfo(ec) 
{}
+  std::string message() const override;
+  std::unique_ptr Clone() const override;
+  static char ID;
+};
+
+class ExpressionError
+: public llvm::ErrorInfo {
+public:
+  using llvm::ErrorInfo::ErrorInfo;
+  ExpressionError(std::error_code ec, std::string msg = {})
+  : ErrorInfo(ec), m_string(msg) {}
+  std::unique_ptr Clone() const override;
+  std::string message() const override { return m_string; }
+  static char ID;
+
+protected:
+  std::string m_string;
+};
+
 /// \class Status Status.h "lldb/Utility/Status.h" An error handling class.
 ///
 /// This class is designed to be able to hold any error code that can be
@@ -100,9 +161,7 @@ class Status {
   }
 
   static Status FromExpressionError(lldb::ExpressionResults result,
-std::string msg) {
-return Status(result, lldb::eErrorTypeExpression, msg);
-  }
+std::string msg);
 
   /// Set the current error to errno.
   ///
@@ -115,6 +174,7 @@ class Status {
   const Status &operator=(Status &&);
   /// Avoid using this in new code. Migrate APIs to llvm::Expected instead.
   static Status FromError(llvm::Error error);
+
   /// FIXME: Replace this with a takeError() method.
   llvm::Error ToError() const;
   /// Don't call this function in new code. Instead, redesign th

[Lldb-commits] [lldb] 1f8a328 - [lldb] Only send "posix" error codes through the gdb-remote protocol

2024-09-19 Thread Adrian Prantl via lldb-commits

Author: Pavel Labath
Date: 2024-09-19T10:07:13-07:00
New Revision: 1f8a3286e065b8cb82628db0d335b3e82b9373fd

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

LOG: [lldb] Only send "posix" error codes through the gdb-remote protocol

The other side has no way of telling which namespace do these codes
belong to, so mashing them all together is not very helpful.

I'm mainly doing this to simplify some code in a pending patch
,
and I've picked the posix error category semi-randomly. If we wanted to
be serious about assigning meaning to these error codes, we should
create a special error category for "gdb errors".

Added: 


Modified: 
lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServer.cpp
lldb/unittests/Process/gdb-remote/GDBRemoteCommunicationServerTest.cpp

Removed: 




diff  --git 
a/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServer.cpp 
b/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServer.cpp
index 9b72cb00352821..d4aa90b2c7731a 100644
--- a/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServer.cpp
+++ b/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServer.cpp
@@ -103,13 +103,14 @@ GDBRemoteCommunicationServer::SendErrorResponse(uint8_t 
err) {
 
 GDBRemoteCommunication::PacketResult
 GDBRemoteCommunicationServer::SendErrorResponse(const Status &error) {
+  uint8_t code = error.GetType() == eErrorTypePOSIX ? error.GetError() : 0xff;
   if (m_send_error_strings) {
 lldb_private::StreamString packet;
-packet.Printf("E%2.2x;", static_cast(error.GetError()));
+packet.Printf("E%2.2x;", code);
 packet.PutStringAsRawHex8(error.AsCString());
 return SendPacketNoLock(packet.GetString());
-  } else
-return SendErrorResponse(error.GetError());
+  }
+  return SendErrorResponse(code);
 }
 
 GDBRemoteCommunication::PacketResult

diff  --git 
a/lldb/unittests/Process/gdb-remote/GDBRemoteCommunicationServerTest.cpp 
b/lldb/unittests/Process/gdb-remote/GDBRemoteCommunicationServerTest.cpp
index 69ca1720c04fc9..ba9ca6ea73e3be 100644
--- a/lldb/unittests/Process/gdb-remote/GDBRemoteCommunicationServerTest.cpp
+++ b/lldb/unittests/Process/gdb-remote/GDBRemoteCommunicationServerTest.cpp
@@ -12,6 +12,7 @@
 #include "Plugins/Process/gdb-remote/GDBRemoteCommunicationServer.h"
 #include "lldb/Utility/Connection.h"
 #include "lldb/Utility/UnimplementedError.h"
+#include "lldb/lldb-enumerations.h"
 
 namespace lldb_private {
 namespace process_gdb_remote {
@@ -25,7 +26,7 @@ TEST(GDBRemoteCommunicationServerTest, 
SendErrorResponse_ErrorNumber) {
 
 TEST(GDBRemoteCommunicationServerTest, SendErrorResponse_Status) {
   MockServerWithMockConnection server;
-  Status status(0x42, lldb::eErrorTypeGeneric, "Test error message");
+  Status status(0x42, lldb::eErrorTypePOSIX, "Test error message");
   server.SendErrorResponse(status);
 
   EXPECT_THAT(



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


[Lldb-commits] [lldb] [lldb/Interpreter] Add requirements to Scripted Interface abstract methods (PR #109063)

2024-09-19 Thread Alex Langford via lldb-commits


@@ -186,36 +210,49 @@ class ScriptedPythonInterface : virtual public 
ScriptedInterface {
 if (!checker_or_err)
   return checker_or_err.takeError();
 
+llvm::Error abstract_method_errors = llvm::Error::success();
 for (const auto &method_checker : *checker_or_err)
   switch (method_checker.second) {
   case AbstractMethodCheckerCases::eNotImplemented:
-LLDB_LOG(GetLog(LLDBLog::Script),
- "Abstract method {0}.{1} not implemented.",
- obj_class_name.GetString(), method_checker.first);
+abstract_method_errors = llvm::joinErrors(
+std::move(abstract_method_errors),
+std::move(create_error("Abstract method {0}.{1} not implemented.",
+   obj_class_name.GetString(),
+   method_checker.first)));
 break;
   case AbstractMethodCheckerCases::eNotAllocated:
-LLDB_LOG(GetLog(LLDBLog::Script),
- "Abstract method {0}.{1} not allocated.",
- obj_class_name.GetString(), method_checker.first);
+abstract_method_errors = llvm::joinErrors(
+std::move(abstract_method_errors),
+std::move(create_error("Abstract method {0}.{1} not allocated.",
+   obj_class_name.GetString(),
+   method_checker.first)));
 break;
   case AbstractMethodCheckerCases::eNotCallable:
-LLDB_LOG(GetLog(LLDBLog::Script),
- "Abstract method {0}.{1} not callable.",
- obj_class_name.GetString(), method_checker.first);
+abstract_method_errors = llvm::joinErrors(
+std::move(abstract_method_errors),
+std::move(create_error("Abstract method {0}.{1} not callable.",
+   obj_class_name.GetString(),
+   method_checker.first)));
+break;
+  case AbstractMethodCheckerCases::eInvalidArgumentCount:
+abstract_method_errors = llvm::joinErrors(
+std::move(abstract_method_errors),
+std::move(create_error(
+"Abstract method {0}.{1} has unexpected argument count.",

bulbazord wrote:

I don't think this error is actionable as-is. Is there a way you can include 
the argument count and the minimum number of arguments?

https://github.com/llvm/llvm-project/pull/109063
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [lldb/Interpreter] Add requirements to Scripted Interface abstract methods (PR #109063)

2024-09-19 Thread Med Ismail Bennani via lldb-commits


@@ -186,36 +210,49 @@ class ScriptedPythonInterface : virtual public 
ScriptedInterface {
 if (!checker_or_err)
   return checker_or_err.takeError();
 
+llvm::Error abstract_method_errors = llvm::Error::success();
 for (const auto &method_checker : *checker_or_err)
   switch (method_checker.second) {
   case AbstractMethodCheckerCases::eNotImplemented:
-LLDB_LOG(GetLog(LLDBLog::Script),
- "Abstract method {0}.{1} not implemented.",
- obj_class_name.GetString(), method_checker.first);
+abstract_method_errors = llvm::joinErrors(
+std::move(abstract_method_errors),
+std::move(create_error("Abstract method {0}.{1} not implemented.",
+   obj_class_name.GetString(),
+   method_checker.first)));
 break;
   case AbstractMethodCheckerCases::eNotAllocated:
-LLDB_LOG(GetLog(LLDBLog::Script),
- "Abstract method {0}.{1} not allocated.",
- obj_class_name.GetString(), method_checker.first);
+abstract_method_errors = llvm::joinErrors(
+std::move(abstract_method_errors),
+std::move(create_error("Abstract method {0}.{1} not allocated.",
+   obj_class_name.GetString(),
+   method_checker.first)));
 break;
   case AbstractMethodCheckerCases::eNotCallable:
-LLDB_LOG(GetLog(LLDBLog::Script),
- "Abstract method {0}.{1} not callable.",
- obj_class_name.GetString(), method_checker.first);
+abstract_method_errors = llvm::joinErrors(
+std::move(abstract_method_errors),
+std::move(create_error("Abstract method {0}.{1} not callable.",
+   obj_class_name.GetString(),
+   method_checker.first)));
+break;
+  case AbstractMethodCheckerCases::eInvalidArgumentCount:
+abstract_method_errors = llvm::joinErrors(
+std::move(abstract_method_errors),
+std::move(create_error(
+"Abstract method {0}.{1} has unexpected argument count.",

medismailben wrote:

Yeah, it would just require more plumbing.

https://github.com/llvm/llvm-project/pull/109063
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [lldb] Removed gdbserver ports map from lldb-server (PR #104238)

2024-09-19 Thread Dmitry Vasilyev via lldb-commits

https://github.com/slydiman updated 
https://github.com/llvm/llvm-project/pull/104238

>From 792cb17f05ded47b152408ac7f4d1de6c986013f Mon Sep 17 00:00:00 2001
From: Dmitry Vasilyev 
Date: Fri, 6 Sep 2024 16:12:50 +0400
Subject: [PATCH 1/3] [lldb] Removed gdbserver ports map from lldb-server

Listen to gdbserver-port, accept the connection and run lldb-server gdbserver 
--fd on all platforms.
Parameters --min-gdbserver-port and --max-gdbserver-port are deprecated now.

This is the part 2 of #101283.

Fixes #97537, fixes #101475.
---
 lldb/docs/man/lldb-server.rst |  11 +-
 lldb/docs/resources/qemu-testing.rst  |  19 +-
 .../GDBRemoteCommunicationServerPlatform.cpp  | 287 +
 .../GDBRemoteCommunicationServerPlatform.h|  82 +---
 .../TestPlatformLaunchGDBServer.py|  12 +-
 .../Shell/lldb-server/TestGdbserverPort.test  |   4 -
 lldb/tools/lldb-server/Acceptor.cpp   |  98 -
 lldb/tools/lldb-server/Acceptor.h |  60 ---
 lldb/tools/lldb-server/CMakeLists.txt |   1 -
 lldb/tools/lldb-server/lldb-gdbserver.cpp |  17 +-
 lldb/tools/lldb-server/lldb-platform.cpp  | 391 --
 .../Process/gdb-remote/CMakeLists.txt |   1 -
 .../Process/gdb-remote/PortMapTest.cpp| 115 --
 13 files changed, 391 insertions(+), 707 deletions(-)
 delete mode 100644 lldb/test/Shell/lldb-server/TestGdbserverPort.test
 delete mode 100644 lldb/tools/lldb-server/Acceptor.cpp
 delete mode 100644 lldb/tools/lldb-server/Acceptor.h
 delete mode 100644 lldb/unittests/Process/gdb-remote/PortMapTest.cpp

diff --git a/lldb/docs/man/lldb-server.rst b/lldb/docs/man/lldb-server.rst
index a67c00b305f6d2..31f5360df5e23e 100644
--- a/lldb/docs/man/lldb-server.rst
+++ b/lldb/docs/man/lldb-server.rst
@@ -147,15 +147,8 @@ GDB-SERVER CONNECTIONS
 
 .. option:: --gdbserver-port 
 
- Define a port to be used for gdb-server connections. Can be specified multiple
- times to allow multiple ports. Has no effect if --min-gdbserver-port
- and --max-gdbserver-port are specified.
-
-.. option:: --min-gdbserver-port 
-.. option:: --max-gdbserver-port 
-
- Specify the range of ports that can be used for gdb-server connections. Both
- options need to be specified simultaneously. Overrides --gdbserver-port.
+ Define a port to be used for gdb-server connections. This port is used for
+ multiple connections.
 
 .. option:: --port-offset 
 
diff --git a/lldb/docs/resources/qemu-testing.rst 
b/lldb/docs/resources/qemu-testing.rst
index 51a30b11717a87..e102f84a1d31f4 100644
--- a/lldb/docs/resources/qemu-testing.rst
+++ b/lldb/docs/resources/qemu-testing.rst
@@ -149,7 +149,6 @@ to the host (refer to QEMU's manuals for the specific 
options).
 * At least one to connect to the intial ``lldb-server``.
 * One more if you want to use ``lldb-server`` in ``platform mode``, and have it
   start a ``gdbserver`` instance for you.
-* A bunch more if you want to run tests against the ``lldb-server`` platform.
 
 If you are doing either of the latter 2 you should also restrict what ports
 ``lldb-server tries`` to use, otherwise it will randomly pick one that is 
almost
@@ -157,22 +156,14 @@ certainly not forwarded. An example of this is shown 
below.
 
 ::
 
-  $ lldb-server plaform --server --listen 0.0.0.0:54321 \
---min-gdbserver-port 49140 --max-gdbserver-port 49150
+  $ lldb-server plaform --server --listen 0.0.0.0:54321 --gdbserver-port 49140
 
 The result of this is that:
 
 * ``lldb-server`` platform mode listens externally on port ``54321``.
 
-* When it is asked to start a new gdbserver mode instance, it will use a port
-  in the range ``49140`` to ``49150``.
+* When it is asked to start a new gdbserver mode instance, it will use the port
+  ``49140``.
 
-Your VM configuration should have ports ``54321``, and ``49140`` to ``49150``
-forwarded for this to work.
-
-.. note::
-  These options are used to create a "port map" within ``lldb-server``.
-  Unfortunately this map is not cleaned up on Windows on connection close,
-  and across a few uses you may run out of valid ports. To work around this,
-  restart the platform every so often, especially after running a set of tests.
-  This is tracked here: https://github.com/llvm/llvm-project/issues/90923
+Your VM configuration should have ports ``54321`` and ``49140`` forwarded for
+this to work.
diff --git 
a/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerPlatform.cpp
 
b/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerPlatform.cpp
index c60a83d351ba09..647130b2984aac 100644
--- 
a/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerPlatform.cpp
+++ 
b/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerPlatform.cpp
@@ -44,79 +44,14 @@ using namespace lldb;
 using namespace lldb_private::process_gdb_remote;
 using namespace lldb_private;
 
-GDBRemoteCommunicationServerPlatform::PortMap::PortMap(uint16_t min_port,
-   

[Lldb-commits] [lldb] [lldb] Removed gdbserver ports map from lldb-server (PR #104238)

2024-09-19 Thread Dmitry Vasilyev via lldb-commits

slydiman wrote:

I have updated Socket::Create() with minimal changes. But later I used 
TCPSocket and DomainSocket constructors directly to keep Socket.cpp untouched.

https://github.com/llvm/llvm-project/pull/104238
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [lldb-dap][docs] Improve README (PR #109266)

2024-09-19 Thread via lldb-commits

https://github.com/jeffreytan81 approved this pull request.


https://github.com/llvm/llvm-project/pull/109266
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [lldb-dap][docs] Improve README (PR #109266)

2024-09-19 Thread via lldb-commits


@@ -1,71 +1,30 @@
 # LLDB DAP
 
-## `lldb-dap` Configurations
+## Procuring the `lldb-dap` binary
 
-The extension requires the `lldb-dap` (formerly `lldb-vscode`) binary. It is a
-command line tool that implements the [Debug Adapter
-Protocol](https://microsoft.github.io/debug-adapter-protocol/). It is used to 
power the Visual Studio Code extension but can also be used with other IDEs and 
editors that support DAP.
-The protocol is easy to run remotely and also can allow other tools and IDEs to
-get a full featured debugger with a well defined protocol.
+The extension requires the `lldb-dap` (formerly `lldb-vscode`) binary.
+This binary is not currently packaged with the VS-Code extension. 
 
-## Launching & Attaching Configuration
+There are multiple ways to obtain this binary:
+* build it from source (see [LLDB's build 
instructions](https://lldb.llvm.org/resources/build.html))
+* download it one of the relase packages from the [LLVM release 
page](https://github.com/llvm/llvm-project/releases/). The 
`LLVM-19.1.0-{operating_system}.tar.xz` packages contain a prebuilt `lldb-dap` 
binary.
+* contact your toolchain vendor
 
-Launching to attaching require you to create a [launch 
configuration](https://code.visualstudio.com/Docs/editor/debugging#_launch-configurations).
-This file defines arguments that get passed to `lldb-dap` and the 
configuration settings control how the launch or attach happens.
-
-### Launch Configuration Settings
-
-When you launch a program with Visual Studio Code you will need to create a 
[launch.json](https://code.visualstudio.com/Docs/editor/debugging#_launch-configurations)
-file that defines how your program will be run. The JSON configuration file 
can contain the following `lldb-dap` specific launch key/value pairs:
-
-|parameter  |type|req | |
-|---||:--:|-|
-|**name**   |string|Y| A configuration name that will be displayed in 
the IDE.
-|**type**   |string|Y| Must be "lldb-dap".
-|**request**|string|Y| Must be "launch".
-|**program**|string|Y| Path to the executable to launch.
-|**args**   |[string]|| An array of command line argument strings to 
be passed to the program being launched.
-|**cwd**|string| | The program working directory.
-|**env**|dictionary| | Environment variables to set when launching 
the program. The format of each environment variable string is "VAR=VALUE" for 
environment variables with values or just "VAR" for environment variables with 
no values.
-|**stopOnEntry**|boolean| | Whether to stop program immediately after 
launching.
-|**initCommands**   |[string]| | LLDB commands executed upon debugger startup 
prior to creating the LLDB target. Commands and command output will be sent to 
the debugger console when they are executed.
-|**preRunCommands** |[string]| | LLDB commands executed just before launching 
after the LLDB target has been created. Commands and command output will be 
sent to the debugger console when they are executed.
-|**stopCommands**   |[string]| | LLDB commands executed just after each stop. 
Commands and command output will be sent to the debugger console when they are 
executed.
-|**launchCommands** |[string]| | LLDB commands executed to launch the program. 
Commands and command output will be sent to the debugger console when they are 
executed.
-|**exitCommands**   |[string]| | LLDB commands executed when the program 
exits. Commands and command output will be sent to the debugger console when 
they are executed.
-|**terminateCommands** |[string]| | LLDB commands executed when the debugging 
session ends. Commands and command output will be sent to the debugger console 
when they are executed.
-|**sourceMap**  |[string[2]]| | Specify an array of path re-mappings. Each 
element in the array must be a two element array containing a source and 
destination pathname.
-|**debuggerRoot**   | string| |Specify a working directory to use when 
launching lldb-dap. If the debug information in your executable contains 
relative paths, this option can be used so that `lldb-dap` can find source 
files and object files that have relative paths.
-
-### Attaching Settings
-
-When attaching to a process using LLDB you can attach in a few ways
+By default, the VS-Code extension will expect to find `lldb-dap` in your 
`PATH`.
+Alternatively, you can explictly specify the location of the `lldb-dap` binary 
using the `lldb-dap.executable-path` setting.

jeffreytan81 wrote:

Is `lldb-dap.executable-path` a setting in VSCode? 

https://github.com/llvm/llvm-project/pull/109266
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [lldb-dap][docs] Improve README (PR #109266)

2024-09-19 Thread via lldb-commits


@@ -1,71 +1,30 @@
 # LLDB DAP
 
-## `lldb-dap` Configurations
+## Procuring the `lldb-dap` binary
 
-The extension requires the `lldb-dap` (formerly `lldb-vscode`) binary. It is a
-command line tool that implements the [Debug Adapter
-Protocol](https://microsoft.github.io/debug-adapter-protocol/). It is used to 
power the Visual Studio Code extension but can also be used with other IDEs and 
editors that support DAP.
-The protocol is easy to run remotely and also can allow other tools and IDEs to
-get a full featured debugger with a well defined protocol.
+The extension requires the `lldb-dap` (formerly `lldb-vscode`) binary.
+This binary is not currently packaged with the VS-Code extension. 
 
-## Launching & Attaching Configuration
+There are multiple ways to obtain this binary:
+* build it from source (see [LLDB's build 
instructions](https://lldb.llvm.org/resources/build.html))
+* download it one of the relase packages from the [LLVM release 
page](https://github.com/llvm/llvm-project/releases/). The 
`LLVM-19.1.0-{operating_system}.tar.xz` packages contain a prebuilt `lldb-dap` 
binary.
+* contact your toolchain vendor
 
-Launching to attaching require you to create a [launch 
configuration](https://code.visualstudio.com/Docs/editor/debugging#_launch-configurations).
-This file defines arguments that get passed to `lldb-dap` and the 
configuration settings control how the launch or attach happens.
-
-### Launch Configuration Settings
-
-When you launch a program with Visual Studio Code you will need to create a 
[launch.json](https://code.visualstudio.com/Docs/editor/debugging#_launch-configurations)
-file that defines how your program will be run. The JSON configuration file 
can contain the following `lldb-dap` specific launch key/value pairs:
-
-|parameter  |type|req | |
-|---||:--:|-|
-|**name**   |string|Y| A configuration name that will be displayed in 
the IDE.
-|**type**   |string|Y| Must be "lldb-dap".
-|**request**|string|Y| Must be "launch".
-|**program**|string|Y| Path to the executable to launch.
-|**args**   |[string]|| An array of command line argument strings to 
be passed to the program being launched.
-|**cwd**|string| | The program working directory.
-|**env**|dictionary| | Environment variables to set when launching 
the program. The format of each environment variable string is "VAR=VALUE" for 
environment variables with values or just "VAR" for environment variables with 
no values.
-|**stopOnEntry**|boolean| | Whether to stop program immediately after 
launching.
-|**initCommands**   |[string]| | LLDB commands executed upon debugger startup 
prior to creating the LLDB target. Commands and command output will be sent to 
the debugger console when they are executed.
-|**preRunCommands** |[string]| | LLDB commands executed just before launching 
after the LLDB target has been created. Commands and command output will be 
sent to the debugger console when they are executed.
-|**stopCommands**   |[string]| | LLDB commands executed just after each stop. 
Commands and command output will be sent to the debugger console when they are 
executed.
-|**launchCommands** |[string]| | LLDB commands executed to launch the program. 
Commands and command output will be sent to the debugger console when they are 
executed.
-|**exitCommands**   |[string]| | LLDB commands executed when the program 
exits. Commands and command output will be sent to the debugger console when 
they are executed.
-|**terminateCommands** |[string]| | LLDB commands executed when the debugging 
session ends. Commands and command output will be sent to the debugger console 
when they are executed.
-|**sourceMap**  |[string[2]]| | Specify an array of path re-mappings. Each 
element in the array must be a two element array containing a source and 
destination pathname.
-|**debuggerRoot**   | string| |Specify a working directory to use when 
launching lldb-dap. If the debug information in your executable contains 
relative paths, this option can be used so that `lldb-dap` can find source 
files and object files that have relative paths.
-
-### Attaching Settings
-
-When attaching to a process using LLDB you can attach in a few ways
+By default, the VS-Code extension will expect to find `lldb-dap` in your 
`PATH`.
+Alternatively, you can explictly specify the location of the `lldb-dap` binary 
using the `lldb-dap.executable-path` setting.
 
-1. Attach to an existing process using the process ID
-2. Attach to an existing process by name
-3. Attach by name by waiting for the next instance of a process to launch
+### Usage with other editors

jeffreytan81 wrote:

other "IDEs"?

https://github.com/llvm/llvm-project/pull/109266
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-comm

[Lldb-commits] [lldb] [lldb-dap][docs] Improve README (PR #109266)

2024-09-19 Thread Adrian Vogelsgesang via lldb-commits


@@ -1,71 +1,30 @@
 # LLDB DAP
 
-## `lldb-dap` Configurations
+## Procuring the `lldb-dap` binary
 
-The extension requires the `lldb-dap` (formerly `lldb-vscode`) binary. It is a
-command line tool that implements the [Debug Adapter
-Protocol](https://microsoft.github.io/debug-adapter-protocol/). It is used to 
power the Visual Studio Code extension but can also be used with other IDEs and 
editors that support DAP.
-The protocol is easy to run remotely and also can allow other tools and IDEs to
-get a full featured debugger with a well defined protocol.
+The extension requires the `lldb-dap` (formerly `lldb-vscode`) binary.
+This binary is not currently packaged with the VS-Code extension. 
 
-## Launching & Attaching Configuration
+There are multiple ways to obtain this binary:
+* build it from source (see [LLDB's build 
instructions](https://lldb.llvm.org/resources/build.html))
+* download it one of the relase packages from the [LLVM release 
page](https://github.com/llvm/llvm-project/releases/). The 
`LLVM-19.1.0-{operating_system}.tar.xz` packages contain a prebuilt `lldb-dap` 
binary.
+* contact your toolchain vendor
 
-Launching to attaching require you to create a [launch 
configuration](https://code.visualstudio.com/Docs/editor/debugging#_launch-configurations).
-This file defines arguments that get passed to `lldb-dap` and the 
configuration settings control how the launch or attach happens.
-
-### Launch Configuration Settings
-
-When you launch a program with Visual Studio Code you will need to create a 
[launch.json](https://code.visualstudio.com/Docs/editor/debugging#_launch-configurations)
-file that defines how your program will be run. The JSON configuration file 
can contain the following `lldb-dap` specific launch key/value pairs:
-
-|parameter  |type|req | |
-|---||:--:|-|
-|**name**   |string|Y| A configuration name that will be displayed in 
the IDE.
-|**type**   |string|Y| Must be "lldb-dap".
-|**request**|string|Y| Must be "launch".
-|**program**|string|Y| Path to the executable to launch.
-|**args**   |[string]|| An array of command line argument strings to 
be passed to the program being launched.
-|**cwd**|string| | The program working directory.
-|**env**|dictionary| | Environment variables to set when launching 
the program. The format of each environment variable string is "VAR=VALUE" for 
environment variables with values or just "VAR" for environment variables with 
no values.
-|**stopOnEntry**|boolean| | Whether to stop program immediately after 
launching.
-|**initCommands**   |[string]| | LLDB commands executed upon debugger startup 
prior to creating the LLDB target. Commands and command output will be sent to 
the debugger console when they are executed.
-|**preRunCommands** |[string]| | LLDB commands executed just before launching 
after the LLDB target has been created. Commands and command output will be 
sent to the debugger console when they are executed.
-|**stopCommands**   |[string]| | LLDB commands executed just after each stop. 
Commands and command output will be sent to the debugger console when they are 
executed.
-|**launchCommands** |[string]| | LLDB commands executed to launch the program. 
Commands and command output will be sent to the debugger console when they are 
executed.
-|**exitCommands**   |[string]| | LLDB commands executed when the program 
exits. Commands and command output will be sent to the debugger console when 
they are executed.
-|**terminateCommands** |[string]| | LLDB commands executed when the debugging 
session ends. Commands and command output will be sent to the debugger console 
when they are executed.
-|**sourceMap**  |[string[2]]| | Specify an array of path re-mappings. Each 
element in the array must be a two element array containing a source and 
destination pathname.
-|**debuggerRoot**   | string| |Specify a working directory to use when 
launching lldb-dap. If the debug information in your executable contains 
relative paths, this option can be used so that `lldb-dap` can find source 
files and object files that have relative paths.
-
-### Attaching Settings
-
-When attaching to a process using LLDB you can attach in a few ways
+By default, the VS-Code extension will expect to find `lldb-dap` in your 
`PATH`.
+Alternatively, you can explictly specify the location of the `lldb-dap` binary 
using the `lldb-dap.executable-path` setting.

vogelsgesang wrote:

yes, this is one of the VS-Code settings added by this extension

https://github.com/llvm/llvm-project/pull/109266
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] Improve type and namespace lookup using parent chain (PR #108907)

2024-09-19 Thread Felipe de Azevedo Piovezan via lldb-commits

https://github.com/felipepiovezan edited 
https://github.com/llvm/llvm-project/pull/108907
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] Improve type and namespace lookup using parent chain (PR #108907)

2024-09-19 Thread Felipe de Azevedo Piovezan via lldb-commits


@@ -402,6 +420,36 @@ bool DebugNamesDWARFIndex::SameParentChain(
   return true;
 }
 
+bool DebugNamesDWARFIndex::WithinParentChain(
+llvm::ArrayRef query_parent_names,
+llvm::ArrayRef parent_chain) const {
+  if (parent_chain.size() < query_parent_names.size())
+return false;
+
+  size_t query_idx = 0, chain_idx = 0;
+  while (query_idx < query_parent_names.size() &&
+ chain_idx < parent_chain.size()) {
+if (SameAsEntryATName(query_parent_names[query_idx],
+  parent_chain[chain_idx])) {
+  ++query_idx;
+  ++chain_idx;
+} else {
+  // Name does not match, try next parent_chain entry if the current entry
+  // is namespace because the current one can be an inline namespace.

felipepiovezan wrote:

do we have a way of guaranteeing it *is*?
If the comparison that failed to match is with a real (non inline) namespace, 
we would return a false result here.

https://github.com/llvm/llvm-project/pull/108907
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] Improve type and namespace lookup using parent chain (PR #108907)

2024-09-19 Thread Felipe de Azevedo Piovezan via lldb-commits


@@ -444,6 +492,98 @@ void DebugNamesDWARFIndex::GetNamespaces(
   m_fallback.GetNamespaces(name, callback);
 }
 
+void DebugNamesDWARFIndex::GetNamespacesWithParents(
+ConstString name, llvm::ArrayRef parent_names,
+llvm::function_ref callback) {
+  Progress progress("Get namespace from index for %s", name.GetCString());
+  for (const DebugNames::Entry &entry :
+   m_debug_names_up->equal_range(name.GetStringRef())) {
+lldb_private::dwarf::Tag entry_tag = entry.tag();
+if (entry_tag == DW_TAG_namespace ||
+entry_tag == DW_TAG_imported_declaration) {
+  std::optional> parent_chain =
+  getParentChain(entry);
+  if (!parent_chain) {
+// Fallback: use the base class implementation.
+if (!ProcessEntry(entry, [&](DWARFDIE die) {
+  return ProcessDieMatchParentNames(name, parent_names, die, 
callback);
+}))
+  return;
+continue;
+  }
+
+  if (parent_chain->size() < parent_names.size())
+continue;
+  else if (parent_chain->size() == parent_names.size()) {

felipepiovezan wrote:

I'd probably fold this optimization inside `WithinParentChain`

https://github.com/llvm/llvm-project/pull/108907
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] Improve type and namespace lookup using parent chain (PR #108907)

2024-09-19 Thread Felipe de Azevedo Piovezan via lldb-commits


@@ -374,25 +377,40 @@ void DebugNamesDWARFIndex::GetFullyQualifiedType(
   m_fallback.GetFullyQualifiedType(context, callback);
 }
 
+bool DebugNamesDWARFIndex::SameAsEntryATName(
+llvm::StringRef query_name, const DebugNames::Entry &entry) const {
+  auto maybe_dieoffset = entry.getDIEUnitOffset();
+  if (!maybe_dieoffset)
+return false;
+
+  // [Optimization] instead of parsing the entry from dwo file, we simply
+  // check if the query_name can point to an entry of the same DIE offset.
+  // This greatly reduced number of dwo file parsed and thus improved the
+  // performance.
+  for (const DebugNames::Entry &query_entry :
+   entry.getNameIndex()->equal_range(query_name)) {
+auto query_dieoffset = query_entry.getDIEUnitOffset();
+if (!query_dieoffset)
+  continue;
+
+if (*query_dieoffset == *maybe_dieoffset) {
+  return true;
+} else if (*query_dieoffset > *maybe_dieoffset) {
+  // The pool entries of the same name are sequentially cluttered together
+  // so if the query name from `query_name` is after the target entry, this
+  // is definitely not the correct one, we can stop searching.
+  return false;
+}
+  }
+  return false;
+}
+
 bool DebugNamesDWARFIndex::SameParentChain(
 llvm::ArrayRef parent_names,
 llvm::ArrayRef parent_entries) const {
-
   if (parent_entries.size() != parent_names.size())
 return false;
 
-  auto SameAsEntryATName = [this](llvm::StringRef name,
-  const DebugNames::Entry &entry) {
-// Peek at the AT_name of `entry` and test equality to `name`.
-auto maybe_dieoffset = entry.getDIEUnitOffset();
-if (!maybe_dieoffset)
-  return false;
-DWARFUnit *unit = GetNonSkeletonUnit(entry);
-if (!unit)
-  return false;
-return name == unit->PeekDIEName(unit->GetOffset() + *maybe_dieoffset);

felipepiovezan wrote:

I think this is the core of your proposal, right? In the original 
implementation that I did, the vast majority of the savings was thanks to being 
able to do `PeekDIEName`. I would strongly recommend we benchmark this new 
implementation is the non-dwo case as well.

One way to check is to build with regular object files (the non dwo case) and 
repeat the experiments I described in this reply: 
https://discourse.llvm.org/t/rfc-improve-dwarf-5-debug-names-type-lookup-parsing-speed/74151/38?u=felipe
And instrumenting this portion of the code: 
https://github.com/llvm/llvm-project/pull/75365/commits/837bc0f476820f9ee5695223420105dedfea8d79

https://github.com/llvm/llvm-project/pull/108907
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] Improve type and namespace lookup using parent chain (PR #108907)

2024-09-19 Thread Felipe de Azevedo Piovezan via lldb-commits

https://github.com/felipepiovezan commented:

Very cool work! I've left some high level thoughts and questions inline. 
Focused only on the namespace bit for now, and didn't do a _code_ review, just 
algorithm ideas

https://github.com/llvm/llvm-project/pull/108907
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] Improve type and namespace lookup using parent chain (PR #108907)

2024-09-19 Thread Felipe de Azevedo Piovezan via lldb-commits


@@ -402,6 +420,36 @@ bool DebugNamesDWARFIndex::SameParentChain(
   return true;
 }
 
+bool DebugNamesDWARFIndex::WithinParentChain(
+llvm::ArrayRef query_parent_names,
+llvm::ArrayRef parent_chain) const {
+  if (parent_chain.size() < query_parent_names.size())

felipepiovezan wrote:

this check and the one at the end of the loop can be combined into a single 
check at the start of the loop

https://github.com/llvm/llvm-project/pull/108907
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] Improve type and namespace lookup using parent chain (PR #108907)

2024-09-19 Thread Felipe de Azevedo Piovezan via lldb-commits


@@ -374,25 +377,40 @@ void DebugNamesDWARFIndex::GetFullyQualifiedType(
   m_fallback.GetFullyQualifiedType(context, callback);
 }
 
+bool DebugNamesDWARFIndex::SameAsEntryATName(
+llvm::StringRef query_name, const DebugNames::Entry &entry) const {
+  auto maybe_dieoffset = entry.getDIEUnitOffset();
+  if (!maybe_dieoffset)
+return false;
+
+  // [Optimization] instead of parsing the entry from dwo file, we simply
+  // check if the query_name can point to an entry of the same DIE offset.
+  // This greatly reduced number of dwo file parsed and thus improved the
+  // performance.
+  for (const DebugNames::Entry &query_entry :
+   entry.getNameIndex()->equal_range(query_name)) {
+auto query_dieoffset = query_entry.getDIEUnitOffset();
+if (!query_dieoffset)
+  continue;
+
+if (*query_dieoffset == *maybe_dieoffset) {
+  return true;
+} else if (*query_dieoffset > *maybe_dieoffset) {
+  // The pool entries of the same name are sequentially cluttered together
+  // so if the query name from `query_name` is after the target entry, this
+  // is definitely not the correct one, we can stop searching.
+  return false;

felipepiovezan wrote:

does the spec guarantee this sorting of DIE offsets?

https://github.com/llvm/llvm-project/pull/108907
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [clang] [clang-tools-extra] [lldb] [llvm] [SystemZ][z/OS] Propagate IsText parameter to open text files as text (PR #107906)

2024-09-19 Thread Zibi Sarbinowski via lldb-commits

https://github.com/zibi2 approved this pull request.

LGTM

https://github.com/llvm/llvm-project/pull/107906
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [lldb] Store expression evaluator diagnostics in an llvm::Error (NFC) (PR #106442)

2024-09-19 Thread Pavel Labath via lldb-commits


@@ -20,6 +23,47 @@
 
 namespace lldb_private {
 
+/// A compiler-independent representation of a Diagnostic. Expression
+/// evaluation failures often have more than one diagnostic that a UI
+/// layer might want to render differently, for example to colorize
+/// it.
+///
+/// Running example:
+///   (lldb) expr 1+foo
+///   error: :1:3: use of undeclared identifier 'foo'
+///   1+foo
+/// ^
+struct DiagnosticDetail {
+  struct SourceLocation {
+FileSpec file;
+unsigned line = 0;
+uint16_t column = 0;
+uint16_t length = 0;
+bool in_user_input = false;
+  };
+  /// Contains {{}, 1, 3, 3, true} in the example above.
+  std::optional source_location;
+  /// Contains eSeverityError in the example above.
+  lldb::Severity severity = lldb::eSeverityInfo;
+  /// Contains "use of undeclared identifier 'x'" in the example above.
+  std::string message;
+  /// Contains the fully rendered error message.
+  std::string rendered;
+};
+
+/// An llvm::Error used to communicate diagnostics in Status. Multiple
+/// diagnostics may be chained in an llvm::ErrorList.
+class DetailedExpressionError
+: public llvm::ErrorInfo {

labath wrote:

Is this really an `instanceof` ECError? e.g.:
- should it be constructible with any kind of error category/code combination?
- do you intend to support the setErrorCode ECError API?

If the answer to either of these is no, I think it'd be better to derive this 
directly from the base class.

https://github.com/llvm/llvm-project/pull/106442
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] bca5073 - [lldb][FrameRecognizer] Display the first non-std frame on verbose_trap (#108825)

2024-09-19 Thread via lldb-commits

Author: Michael Buch
Date: 2024-09-19T10:06:28+01:00
New Revision: bca507387ae1945137214ec7fb80b709927ee6e8

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

LOG: [lldb][FrameRecognizer] Display the first non-std frame on verbose_trap 
(#108825)

This attempts to improve user-experience when LLDB stops on a
verbose_trap. Currently if a `__builtin_verbose_trap` triggers, we
display the first frame above the call to the verbose_trap. So in the
newly added test case, we would've previously stopped here:
```
(lldb) run
Process 28095 launched: '/Users/michaelbuch/a.out' (arm64)
Process 28095 stopped
* thread #1, queue = 'com.apple.main-thread', stop reason = Bounds error: 
out-of-bounds access
frame #1: 0x00013f5c 
a.out`std::__1::vector::operator[](this=0x00016fdfebef size=0, 
(null)=10) at verbose_trap.cpp:6:9
   3template 
   4struct vector {
   5void operator[](unsigned) {
-> 6__builtin_verbose_trap("Bounds error", "out-of-bounds access");
   7}
   8};
```

After this patch, we would stop in the first non-`std` frame:
```
(lldb) run
Process 27843 launched: '/Users/michaelbuch/a.out' (arm64)
Process 27843 stopped
* thread #1, queue = 'com.apple.main-thread', stop reason = Bounds error: 
out-of-bounds access
frame #2: 0x00013f44 a.out`g() at verbose_trap.cpp:14:5
   11  
   12   void g() {
   13   std::vector v;
-> 14   v[10];
   15   }
   16  
```

rdar://134490328

Added: 
lldb/test/Shell/Recognizer/Inputs/verbose_trap-in-stl-callback-user-leaf.cpp
lldb/test/Shell/Recognizer/Inputs/verbose_trap-in-stl-callback.cpp
lldb/test/Shell/Recognizer/Inputs/verbose_trap-in-stl-max-depth.cpp
lldb/test/Shell/Recognizer/Inputs/verbose_trap-in-stl-nested.cpp
lldb/test/Shell/Recognizer/Inputs/verbose_trap-in-stl.cpp
lldb/test/Shell/Recognizer/verbose_trap-in-stl-callback-user-leaf.test
lldb/test/Shell/Recognizer/verbose_trap-in-stl-callback.test
lldb/test/Shell/Recognizer/verbose_trap-in-stl-max-depth.test
lldb/test/Shell/Recognizer/verbose_trap-in-stl-nested.test
lldb/test/Shell/Recognizer/verbose_trap-in-stl.test

Modified: 
lldb/source/Target/VerboseTrapFrameRecognizer.cpp

Removed: 




diff  --git a/lldb/source/Target/VerboseTrapFrameRecognizer.cpp 
b/lldb/source/Target/VerboseTrapFrameRecognizer.cpp
index de710fcda54064..03ab58b8c59a9b 100644
--- a/lldb/source/Target/VerboseTrapFrameRecognizer.cpp
+++ b/lldb/source/Target/VerboseTrapFrameRecognizer.cpp
@@ -16,6 +16,39 @@ using namespace llvm;
 using namespace lldb;
 using namespace lldb_private;
 
+/// The 0th frame is the artificial inline frame generated to store
+/// the verbose_trap message. So, starting with the current parent frame,
+/// find the first frame that's not inside of the STL.
+static StackFrameSP FindMostRelevantFrame(Thread &selected_thread) {
+  // Defensive upper-bound of when we stop walking up the frames in
+  // case we somehow ended up looking at an infinite recursion.
+  const size_t max_stack_depth = 128;
+
+  // Start at parent frame.
+  size_t stack_idx = 1;
+  StackFrameSP most_relevant_frame_sp =
+  selected_thread.GetStackFrameAtIndex(stack_idx);
+
+  while (most_relevant_frame_sp && stack_idx <= max_stack_depth) {
+auto const &sc =
+most_relevant_frame_sp->GetSymbolContext(eSymbolContextEverything);
+ConstString frame_name = sc.GetFunctionName();
+if (!frame_name)
+  return nullptr;
+
+// Found a frame outside of the `std` namespace. That's the
+// first frame in user-code that ended up triggering the
+// verbose_trap. Hence that's the one we want to display.
+if (!frame_name.GetStringRef().starts_with("std::"))
+  return most_relevant_frame_sp;
+
+++stack_idx;
+most_relevant_frame_sp = selected_thread.GetStackFrameAtIndex(stack_idx);
+  }
+
+  return nullptr;
+}
+
 VerboseTrapRecognizedStackFrame::VerboseTrapRecognizedStackFrame(
 StackFrameSP most_relevant_frame_sp, std::string stop_desc)
 : m_most_relevant_frame(most_relevant_frame_sp) {
@@ -30,7 +63,7 @@ VerboseTrapFrameRecognizer::RecognizeFrame(lldb::StackFrameSP 
frame_sp) {
   ThreadSP thread_sp = frame_sp->GetThread();
   ProcessSP process_sp = thread_sp->GetProcess();
 
-  StackFrameSP most_relevant_frame_sp = thread_sp->GetStackFrameAtIndex(1);
+  StackFrameSP most_relevant_frame_sp = FindMostRelevantFrame(*thread_sp);
 
   if (!most_relevant_frame_sp) {
 Log *log = GetLog(LLDBLog::Unwind);

diff  --git 
a/lldb/test/Shell/Recognizer/Inputs/verbose_trap-in-stl-callback-user-leaf.cpp 
b/lldb/test/Shell/Recognizer/Inputs/verbose_trap-in-stl-callback-user-leaf.cpp
new file mode 100644
index 00..6c36682626a6ef
--- /dev/null
+++ 
b/lldb/test/Shell/Recognizer/Inp

[Lldb-commits] [lldb] [lldb][FrameRecognizer] Display the first non-std frame on verbose_trap (PR #108825)

2024-09-19 Thread Michael Buch via lldb-commits

https://github.com/Michael137 closed 
https://github.com/llvm/llvm-project/pull/108825
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [lldb][FrameRecognizer] Display the first non-std frame on verbose_trap (PR #108825)

2024-09-19 Thread Michael Buch via lldb-commits

https://github.com/Michael137 updated 
https://github.com/llvm/llvm-project/pull/108825

>From 729a0f69583c2c8ac597e68622231e4b719735b8 Mon Sep 17 00:00:00 2001
From: Michael Buch 
Date: Mon, 16 Sep 2024 14:10:46 +0100
Subject: [PATCH 1/3] [lldb][FrameRecognizer] Display the first non-std frame
 on verbose_trap

---
 .../Target/VerboseTrapFrameRecognizer.cpp | 27 ++-
 .../Inputs/verbose_trap-in-stl-callback.cpp   | 22 +++
 .../Inputs/verbose_trap-in-stl-nested.cpp | 21 +++
 .../Recognizer/Inputs/verbose_trap-in-stl.cpp | 17 
 .../verbose_trap-in-stl-callback.test | 13 +
 .../verbose_trap-in-stl-nested.test   | 13 +
 .../Shell/Recognizer/verbose_trap-in-stl.test | 13 +
 7 files changed, 125 insertions(+), 1 deletion(-)
 create mode 100644 
lldb/test/Shell/Recognizer/Inputs/verbose_trap-in-stl-callback.cpp
 create mode 100644 
lldb/test/Shell/Recognizer/Inputs/verbose_trap-in-stl-nested.cpp
 create mode 100644 lldb/test/Shell/Recognizer/Inputs/verbose_trap-in-stl.cpp
 create mode 100644 lldb/test/Shell/Recognizer/verbose_trap-in-stl-callback.test
 create mode 100644 lldb/test/Shell/Recognizer/verbose_trap-in-stl-nested.test
 create mode 100644 lldb/test/Shell/Recognizer/verbose_trap-in-stl.test

diff --git a/lldb/source/Target/VerboseTrapFrameRecognizer.cpp 
b/lldb/source/Target/VerboseTrapFrameRecognizer.cpp
index de710fcda54064..530a8941c8d504 100644
--- a/lldb/source/Target/VerboseTrapFrameRecognizer.cpp
+++ b/lldb/source/Target/VerboseTrapFrameRecognizer.cpp
@@ -16,6 +16,31 @@ using namespace llvm;
 using namespace lldb;
 using namespace lldb_private;
 
+/// The 0th frame is the artificial inline frame generated to store
+/// the verbose_trap message. So, starting with the current parent frame,
+/// find the first frame that's not inside of the STL.
+static StackFrameSP FindMostRelevantFrame(Thread &selected_thread) {
+  StackFrameSP most_relevant_frame_sp = 
selected_thread.GetStackFrameAtIndex(1);
+  while (most_relevant_frame_sp) {
+auto const &sc =
+most_relevant_frame_sp->GetSymbolContext(eSymbolContextEverything);
+ConstString frame_name = sc.GetFunctionName();
+if (!frame_name)
+  return nullptr;
+
+// Found a frame outside of the `std` namespace. That's the
+// first frame in user-code that ended up triggering the
+// verbose_trap. Hence that's the one we want to display.
+if (!frame_name.GetStringRef().starts_with("std::"))
+  return most_relevant_frame_sp;
+
+most_relevant_frame_sp = selected_thread.GetStackFrameAtIndex(
+most_relevant_frame_sp->GetFrameIndex() + 1);
+  }
+
+  return nullptr;
+}
+
 VerboseTrapRecognizedStackFrame::VerboseTrapRecognizedStackFrame(
 StackFrameSP most_relevant_frame_sp, std::string stop_desc)
 : m_most_relevant_frame(most_relevant_frame_sp) {
@@ -30,7 +55,7 @@ VerboseTrapFrameRecognizer::RecognizeFrame(lldb::StackFrameSP 
frame_sp) {
   ThreadSP thread_sp = frame_sp->GetThread();
   ProcessSP process_sp = thread_sp->GetProcess();
 
-  StackFrameSP most_relevant_frame_sp = thread_sp->GetStackFrameAtIndex(1);
+  StackFrameSP most_relevant_frame_sp = FindMostRelevantFrame(*thread_sp);
 
   if (!most_relevant_frame_sp) {
 Log *log = GetLog(LLDBLog::Unwind);
diff --git a/lldb/test/Shell/Recognizer/Inputs/verbose_trap-in-stl-callback.cpp 
b/lldb/test/Shell/Recognizer/Inputs/verbose_trap-in-stl-callback.cpp
new file mode 100644
index 00..23beed4c62c3b3
--- /dev/null
+++ b/lldb/test/Shell/Recognizer/Inputs/verbose_trap-in-stl-callback.cpp
@@ -0,0 +1,22 @@
+namespace std {
+void definitely_aborts() { __builtin_verbose_trap("Failed", "Invariant 
violated"); }
+
+void aborts_soon() { definitely_aborts(); }
+} // namespace std
+
+void g() { std::aborts_soon(); }
+
+namespace std {
+namespace detail {
+void eventually_aborts() { g(); }
+} // namespace detail
+
+inline namespace __1 {
+void eventually_aborts() { detail::eventually_aborts(); }
+} // namespace __1
+} // namespace std
+
+int main() {
+  std::eventually_aborts();
+  return 0;
+}
diff --git a/lldb/test/Shell/Recognizer/Inputs/verbose_trap-in-stl-nested.cpp 
b/lldb/test/Shell/Recognizer/Inputs/verbose_trap-in-stl-nested.cpp
new file mode 100644
index 00..67fa65c9ceae22
--- /dev/null
+++ b/lldb/test/Shell/Recognizer/Inputs/verbose_trap-in-stl-nested.cpp
@@ -0,0 +1,21 @@
+namespace std {
+namespace detail {
+void function_that_aborts() { __builtin_verbose_trap("Bounds error", 
"out-of-bounds access"); }
+} // namespace detail
+
+inline namespace __1 {
+template  struct vector {
+  void operator[](unsigned) { detail::function_that_aborts(); }
+};
+} // namespace __1
+} // namespace std
+
+void g() {
+  std::vector v;
+  v[10];
+}
+
+int main() {
+  g();
+  return 0;
+}
diff --git a/lldb/test/Shell/Recognizer/Inputs/verbose_trap-in-stl.cpp 
b/lldb/test/Shell/Recognizer/Inputs/verbose_trap-in-stl.cpp
new file mode 100644
index 0

[Lldb-commits] [lldb] [llvm] [lldb][RISCV] function calls support in lldb expressions (PR #99336)

2024-09-19 Thread David Spickett via lldb-commits

DavidSpickett wrote:

Reminder to update the PR description now that the large code model has been 
implemented over in llvm.

https://github.com/llvm/llvm-project/pull/99336
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [clang] [lldb] [ASTImporter][lldb] Avoid implicit imports in VisitFieldDecl (PR #107828)

2024-09-19 Thread Michael Buch via lldb-commits

Michael137 wrote:

> > Our idea is summarized in 
> > https://discourse.llvm.org/t/rfc-lldb-more-reliable-completion-of-record-types/77442.
> >  Basically the goal is to guarantee that a call to `getDefinition`, _will_ 
> > fetch the definition. This is something that Clang already does, but we 
> > just never implement (via `CompleteRedeclChain`). You're right that the 
> > "minimal import" mode was implemented for perf. reasons. Though we should 
> > probably revisit this. I think we can make LLDB use non-minimal import for 
> > record types while keeping the number of transitive imports contained. It 
> > would still require changes to the importer to be smarter about what we 
> > import, but we wouldn't have these "complete but incomplete" types floating 
> > around.
> 
> Thanks a lot Michael. It's a lot of work to get the redesign ready, 
> considering both functional and performance requirements.
> 
> In the meantime, should we merge this patch to fix at least some current 
> problems?

Apologies, got a bit side-tracked this week. I'm slowly extracting a test-case 
out of the crash I was looking at. I'd be more comfortable making changes to 
the ASTImporter once we're sure there isn't a way of fixing this on the LLDB 
side. Hopefully I'll be able to provide some updates on this next week.

https://github.com/llvm/llvm-project/pull/107828
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [clang] [compiler-rt] [lldb] [llvm] [Support] Remove terminfo dependency (PR #92865)

2024-09-19 Thread via lldb-commits

davide-q wrote:

Is there a way to revert and rework this PR to avoid issue #101368 which this 
PR introduced?

https://github.com/llvm/llvm-project/pull/92865
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] [lldb/DWARF] Downgrade the "parent of variable is not CU" error (PR #108806)

2024-09-19 Thread Pavel Labath via lldb-commits

https://github.com/labath updated 
https://github.com/llvm/llvm-project/pull/108806

>From bb9ed8615a1ec2f53e3704136394f0be37756dfc Mon Sep 17 00:00:00 2001
From: Pavel Labath 
Date: Mon, 16 Sep 2024 10:52:00 +0200
Subject: [PATCH] [lldb/DWARF] Downgrade the "parent of variable is not CU"
 error

This can legitimately happen for static function-local variables with a
non-manual dwarf index. According to the DWARF spec, these variables
should be (and are) included in the compiler generated indexes, but they
are ignored by our manual index. Encountering them does not indicate any
sort of error.

The error message is particularly annoying due to a combination of the
fact that we don't cache negative hits (so we print it every time we
encounter it), VSCode's aggresive tab completion (which attempts a
lookup after every keypress) and the fact that some low-level libraries
(e.g. tcmalloc) have several local variables called "v". The result is a
console full of error messages everytime you type "v ".

We already have tests (e.g. find-basic-variable.cpp), which check that
these variables are not included in the result (and by extension, that
their presence does not crash lldb). It would be possible to extend it
to make sure it does *not* print this error message, but it doesn't seem
like it would be particularly useful.
---
 lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp | 7 +++
 1 file changed, 3 insertions(+), 4 deletions(-)

diff --git a/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp 
b/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp
index f721ca00fd3559..a40d6d9e37978b 100644
--- a/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp
+++ b/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp
@@ -3828,10 +3828,9 @@ void SymbolFileDWARF::ParseAndAppendGlobalVariable(
 break;
 
   default:
-GetObjectFile()->GetModule()->ReportError(
-"didn't find appropriate parent DIE for variable list for {0:x8} "
-"{1} ({2}).\n",
-die.GetID(), DW_TAG_value_to_name(die.Tag()), die.Tag());
+LLDB_LOG(GetLog(DWARFLog::Lookups),
+ "{0} '{1}' ({2:x8}) is not a global variable - ignoring", tag,
+ die.GetName(), die.GetID());
 return;
   }
 

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


[Lldb-commits] [lldb] [lldb/DWARF] Downgrade the "parent of variable is not CU" error (PR #108806)

2024-09-19 Thread Pavel Labath via lldb-commits


@@ -3828,10 +3828,8 @@ void SymbolFileDWARF::ParseAndAppendGlobalVariable(
 break;
 
   default:
-GetObjectFile()->GetModule()->ReportError(
-"didn't find appropriate parent DIE for variable list for {0:x8} "
-"{1} ({2}).\n",
-die.GetID(), DW_TAG_value_to_name(die.Tag()), die.Tag());
+LLDB_LOG(GetLog(DWARFLog::Lookups),
+ "DIE {0:x8} is not a global variable - ignoring", die.GetID());

labath wrote:

Sure, why not.

https://github.com/llvm/llvm-project/pull/108806
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [lldb] lldb: get lldb API tests working with newer Android NDKs (PR #106443)

2024-09-19 Thread Pavel Labath via lldb-commits

https://github.com/labath approved this pull request.


https://github.com/llvm/llvm-project/pull/106443
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


  1   2   >