[Lldb-commits] [PATCH] D133366: [lldb] Fix SBFileSpec.fullpath for Windows

2022-11-15 Thread Pavel Labath via Phabricator via lldb-commits
labath added a comment.

The real problem here is that the `__get_fullpath__` implementation does not 
use the path style information from within the FileSpec object. Hardcoding it 
to use the host os path style (instead of posix style) just changes the set of 
bugs.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133366

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


[Lldb-commits] [PATCH] D137873: [LLDB][Minidump] Set abi environment for windows.

2022-11-15 Thread Pavel Labath via Phabricator via lldb-commits
labath added a comment.

This dual environment thing is tricky.. MSVC is probably a better default, but 
it would still mean that the same bugs will appear if the situation is reversed 
(we assume MSVC environ, but the binary actually uses GNU). Have you looked at 
how this interacts with https://reviews.llvm.org/D127048 (and the setting 
introduced there) and whether you can achieve the same effect by changing that 
setting?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137873

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


[Lldb-commits] [PATCH] D135631: [lldb] Copy log files into diagnostic directory

2022-11-15 Thread Pavel Labath via Phabricator via lldb-commits
labath added inline comments.



Comment at: lldb/source/Core/Debugger.cpp:815
+Diagnostics::Instance().AddCallback(
+[&](const FileSpec &dir) -> llvm::Error {
+  for (auto &entry : m_stream_handlers) {

A default reference capture is dangerous when the lambda is supposed to run 
after the enclosing function returns. I guess you really wanted to capture 
`this` (?)
Also, I would expect that means that you need to disable the callback in the 
Debugger destructor.



Comment at: lldb/test/Shell/Diagnostics/TestCopyLogs.test:3
+# RUN: mkdir -p %t
+# The "ll''db" below is not a typo but a way to prevent lit from substituting 
'lldb'.
+# RUN: %lldb -o 'log enable ll''db commands -f %t/commands.log' -o 
'diagnostics dump -d %t/diags'

JDevlieghere wrote:
> labath wrote:
> > That's cute, but I suspect windows will have a problem with that. `-s %s` 
> > (and putting the commands in this file) would be safer.
> I thought about that, but I still need `%t` to be expanded. I guess I could 
> put `log enable lldb commands -f ` in a file and append `%t/commands.log` to 
> it. 
hm.. the %t substitution makes it tricky, but I don't think this is better than 
what we had before. It still has nested quotes, which is the thing that causes 
problems on windows. I think you could work around this by creating an alias in 
a command file (say `command alias logcommands log enable lldb commands`) and 
then invoking it from the command line (`-o "logcommands -f %t/commands.log"`).


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

https://reviews.llvm.org/D135631

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


[Lldb-commits] [PATCH] D136650: Make CompilerType safe [Was: Add a check for TypeSystem use-after-free problems]

2022-11-15 Thread Pavel Labath via Phabricator via lldb-commits
labath added inline comments.



Comment at: lldb/include/lldb/Symbol/CompilerType.h:58
+template  TypeSystemType *dyn_cast_or_null() {
+  return llvm::dyn_cast_or_null(m_typesystem_sp.get());
+}

Maybe do something like this instead:
```
template  std::shared_ptr 
dyn_cast_or_null() {
  if (llvm::isa(m_typesystem_sp.get()))
return std::shared_ptr(m_typesystem_sp, 
llvm::cast(m_typesystem_sp.get()));
  return nullptr;
}
```

That said, `llvm::dyn_cast` supports custom casts for smart pointers (it 
already has them for std::unique_ptr), so it should be possible to completely 
avoid this wrapper class by implementing this logic inside llvm.
Although, then we'd have to answer awkward questions like "why are you using a 
shared_ptr in the first place".



Comment at: lldb/include/lldb/Symbol/CompilerType.h:60
+}
+operator bool() const { return static_cast(m_typesystem_sp); }
+bool operator==(const TypeSystemSPWrapper &other) const;

add `explicit`



Comment at: lldb/include/lldb/Symbol/TypeSystem.h:517-520
+  /// Only to be used by TypeSystemMap and various unit tests.
+  void SetCanonicalWeakPtr(lldb::TypeSystemWP wp) { m_canonical_wp = wp; }
 protected:
+  lldb::TypeSystemWP m_canonical_wp;

Can this be replaced by inheriting from `std::enable_shared_from_this`?



Comment at: lldb/source/Core/DumpDataExtractor.cpp:322
size_t byte_size) {
-  if (target_sp) {
-if (auto type_system_or_err =
-target_sp->GetScratchTypeSystemForLanguage(eLanguageTypeC))
-  return type_system_or_err->GetFloatTypeSemantics(byte_size);
-else
+  while (target_sp) {
+auto type_system_or_err =

why?


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

https://reviews.llvm.org/D136650

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


[Lldb-commits] [PATCH] D137247: [lldb] Allow plugins to extend DWARF expression parsing for vendor extensions

2022-11-15 Thread Philip Pfaffe via Phabricator via lldb-commits
pfaffe updated this revision to Diff 475399.
pfaffe added a comment.

Stray change.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137247

Files:
  lldb/include/lldb/Expression/DWARFExpression.h
  lldb/source/Expression/DWARFExpression.cpp
  lldb/source/Expression/DWARFExpressionList.cpp
  lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp
  lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.h
  lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARFDwo.h
  lldb/unittests/Expression/DWARFExpressionTest.cpp

Index: lldb/unittests/Expression/DWARFExpressionTest.cpp
===
--- lldb/unittests/Expression/DWARFExpressionTest.cpp
+++ lldb/unittests/Expression/DWARFExpressionTest.cpp
@@ -9,9 +9,11 @@
 #include "lldb/Expression/DWARFExpression.h"
 #include "Plugins/Platform/Linux/PlatformLinux.h"
 #include "Plugins/SymbolFile/DWARF/DWARFDebugInfo.h"
+#include "Plugins/SymbolFile/DWARF/SymbolFileDWARFDwo.h"
 #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
 #include "TestingSupport/Symbol/YAMLModuleTester.h"
 #include "lldb/Core/Debugger.h"
+#include "lldb/Core/PluginManager.h"
 #include "lldb/Core/Value.h"
 #include "lldb/Core/dwarf.h"
 #include "lldb/Host/HostInfo.h"
@@ -514,3 +516,242 @@
   ASSERT_EQ(result.GetValueType(), Value::ValueType::LoadAddress);
   ASSERT_EQ(result.GetScalar().UInt(), 0x5678u);
 }
+
+class CustomSymbolFileDWARF : public SymbolFileDWARF {
+  static char ID;
+
+public:
+  using SymbolFileDWARF::SymbolFileDWARF;
+
+  bool isA(const void *ClassID) const override {
+return ClassID == &ID || SymbolFile::isA(ClassID);
+  }
+  static bool classof(const SymbolFile *obj) { return obj->isA(&ID); }
+
+  static llvm::StringRef GetPluginNameStatic() { return "custom_dwarf"; }
+
+  static llvm::StringRef GetPluginDescriptionStatic() {
+return "Symbol file reader with expression extensions.";
+  }
+
+  static void Initialize() {
+PluginManager::RegisterPlugin(GetPluginNameStatic(),
+  GetPluginDescriptionStatic(), CreateInstance,
+  SymbolFileDWARF::DebuggerInitialize);
+  }
+
+  static void Terminate() { PluginManager::UnregisterPlugin(CreateInstance); }
+
+  static lldb_private::SymbolFile *
+  CreateInstance(lldb::ObjectFileSP objfile_sp) {
+return new CustomSymbolFileDWARF(std::move(objfile_sp),
+ /*dwo_section_list*/ nullptr);
+  }
+
+  lldb::offset_t
+  GetVendorDWARFOpcodeSize(const lldb_private::DataExtractor &data,
+   const lldb::offset_t data_offset,
+   const uint8_t op) const final {
+auto offset = data_offset;
+if (op != DW_OP_WASM_location) {
+  return LLDB_INVALID_OFFSET;
+}
+
+// DW_OP_WASM_location WASM_GLOBAL:0x03 index:u32
+// Called with "arguments" 0x03 and 0x04
+// Location type:
+if (data.GetU8(&offset) != /* global */ 0x03) {
+  return LLDB_INVALID_OFFSET;
+}
+
+// Index
+if (data.GetU32(&offset) != 0x04) {
+  return LLDB_INVALID_OFFSET;
+}
+
+// Report the skipped distance:
+return offset - data_offset;
+  }
+
+  bool
+  ParseVendorDWARFOpcode(uint8_t op, const lldb_private::DataExtractor &opcodes,
+ lldb::offset_t &offset,
+ std::vector &stack) const final {
+if (op != DW_OP_WASM_location) {
+  return false;
+}
+
+// DW_OP_WASM_location WASM_GLOBAL:0x03 index:u32
+// Called with "arguments" 0x03 and  0x04
+// Location type:
+if (opcodes.GetU8(&offset) != /* global */ 0x03) {
+  return false;
+}
+
+// Index:
+if (opcodes.GetU32(&offset) != 0x04) {
+  return false;
+}
+
+// Return some value:
+stack.push_back({GetScalar(32, 42, false)});
+return true;
+  }
+};
+
+char CustomSymbolFileDWARF::ID;
+
+static auto testExpressionVendorExtensions(lldb::ModuleSP module_sp,
+   DWARFUnit &dwarf_unit) {
+  // Test that expression extensions can be evaluated, for example
+  // DW_OP_WASM_location which is not currently handled by DWARFExpression:
+  EXPECT_THAT_EXPECTED(Evaluate({DW_OP_WASM_location, 0x03, // WASM_GLOBAL:0x03
+ 0x04, 0x00, 0x00,  // index:u32
+ 0x00, DW_OP_stack_value},
+module_sp, &dwarf_unit),
+   llvm::HasValue(GetScalar(32, 42, false)));
+
+  // Test that searches for opcodes work in the presence of extensions:
+  uint8_t expr[] = {DW_OP_WASM_location,   0x03, 0x04, 0x00, 0x00, 0x00,
+DW_OP_form_tls_address};
+  DataExtractor extractor(expr, sizeof(expr), lldb::eByteOrderLittle,
+  /*addr_size*/ 4);
+  DWARFExpression dwarf_expr(extractor);
+  ASSERT_TRUE(dwarf_expr.ContainsTh

[Lldb-commits] [PATCH] D137983: [lldb] Disable looking at pointee types to find synthetic value for non-ObjC

2022-11-15 Thread David Blaikie via Phabricator via lldb-commits
dblaikie added inline comments.



Comment at: lldb/source/Core/ValueObject.cpp:2676-2677
 if (!m_deref_valobj) {
-  if (HasSyntheticValue()) {
+  // FIXME: C++ stdlib formatters break with incomplete types (e.g.
+  // `std::vector &`). Remove ObjC restriction once that's resolved.
+  if (Language::LanguageIsObjC(GetPreferredDisplayLanguage()) &&

Maybe worth filing a bug and referencing it here?

Is this limitation still necessary if the incomplete type has template 
parameter DIEs? (I guess probably yes, because it'll be missing member 
descriptions, etc)

& does this path get hit if the type is declared in one CU but defined in 
another? (& does the inf recurse/crash loop still get hit in that case, without 
this patch?)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137983

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


[Lldb-commits] [PATCH] D134066: [LLDB][NativePDB] Forcefully complete a record type if it has empty debug info and is required to have complete type.

2022-11-15 Thread Zequan Wu via Phabricator via lldb-commits
zequanwu updated this revision to Diff 475517.
zequanwu marked 2 inline comments as done.
zequanwu added a comment.
Herald added a reviewer: shafik.

Move RequireCompleteType to TypeSystemClang.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134066

Files:
  lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParserClang.cpp
  lldb/source/Plugins/SymbolFile/NativePDB/UdtRecordCompleter.cpp
  lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
  lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
  lldb/test/Shell/SymbolFile/NativePDB/Inputs/incomplete-tag-type.cpp
  lldb/test/Shell/SymbolFile/NativePDB/incomplete-tag-type.cpp

Index: lldb/test/Shell/SymbolFile/NativePDB/incomplete-tag-type.cpp
===
--- /dev/null
+++ lldb/test/Shell/SymbolFile/NativePDB/incomplete-tag-type.cpp
@@ -0,0 +1,48 @@
+// clang-format off
+// REQUIRES: lld, x86
+
+// RUN: %clang_cl --target=x86_64-windows-msvc -c /Fo%t1.obj -- %p/Inputs/incomplete-tag-type.cpp
+// RUN: %clang_cl --target=x86_64-windows-msvc /O1 /Z7 -c /Fo%t2.obj -- %s
+// RUN: lld-link /debug:full /nodefaultlib /entry:main %t1.obj %t2.obj /out:%t.exe /pdb:%t.pdb
+// RUN: env LLDB_USE_NATIVE_PDB_READER=1 %lldb -f %t.exe -o \
+// RUN:   "settings set interpreter.stop-command-source-on-error false" \
+// RUN:   -o "p b" -o "p d" -o "p static_e_ref" -o "exit" 2>&1 | FileCheck %s
+
+// CHECK: (lldb) p b
+// CHECK: (B) $0 = {}
+// CHECK: (lldb) p d
+// CHECK: (D) $1 = {}
+// CHECK: (lldb) p static_e_ref
+// CHECK: error: expression failed to parse:
+// CHECK: error: {{.*}}: incomplete type 'E' where a complete type is required
+// CHECK: static_e_ref
+// CHECK: ^
+
+// Complete base class.
+struct A { int x; A(); };
+struct B : A {};
+B b;
+
+// Complete data member.
+struct C {
+  C();
+};
+
+struct D {
+  C c;
+};
+D d;
+
+// Incomplete static data member should return error.
+struct E {
+  E();
+};
+
+struct F {
+  static E static_e;
+};
+
+E F::static_e = E();
+E& static_e_ref = F::static_e;
+
+int main(){}
Index: lldb/test/Shell/SymbolFile/NativePDB/Inputs/incomplete-tag-type.cpp
===
--- /dev/null
+++ lldb/test/Shell/SymbolFile/NativePDB/Inputs/incomplete-tag-type.cpp
@@ -0,0 +1,15 @@
+struct A {
+  int x;
+  A();
+};
+A::A() : x(47) {}
+
+struct C {
+  C();
+};
+C::C() = default;
+
+struct E {
+  E();
+};
+E::E() = default;
Index: lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
===
--- lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
+++ lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
@@ -1045,6 +1045,8 @@
 return m_source_manager_up.get();
   }
 
+  static void RequireCompleteType(CompilerType type);
+
 private:
   /// Returns the PrintingPolicy used when generating the internal type names.
   /// These type names are mostly used for the formatter selection.
Index: lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
===
--- lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
+++ lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
@@ -9813,6 +9813,33 @@
   return nullptr;
 }
 
+/// Complete a type from debug info, or mark it as forcefully completed if
+/// there is no definition of the type in the current Module. Call this function
+/// in contexts where the usual C++ rules require a type to be complete (base
+/// class, member, etc.).
+void TypeSystemClang::RequireCompleteType(CompilerType type) {
+  // Technically, enums can be incomplete too, but we don't handle those as they
+  // are emitted even under -flimit-debug-info.
+  if (!TypeSystemClang::IsCXXClassType(type))
+return;
+
+  if (type.GetCompleteType())
+return;
+
+  // No complete definition in this module.  Mark the class as complete to
+  // satisfy local ast invariants, but make a note of the fact that
+  // it is not _really_ complete so we can later search for a definition in a
+  // different module.
+  // Since we provide layout assistance, layouts of types containing this class
+  // will be correct even if we  are not able to find the definition elsewhere.
+  bool started = TypeSystemClang::StartTagDeclarationDefinition(type);
+  lldbassert(started && "Unable to start a class type definition.");
+  TypeSystemClang::CompleteTagDeclarationDefinition(type);
+  const clang::TagDecl *td = ClangUtil::GetAsTagDecl(type);
+  auto &ts = llvm::cast(*type.GetTypeSystem());
+  ts.GetMetadata(td)->SetIsForcefullyCompleted();
+}
+
 namespace {
 /// A specialized scratch AST used within ScratchTypeSystemClang.
 /// These are the ASTs backing the different IsolatedASTKinds. They behave
Index: lldb/source/Plugins/SymbolFile/NativePDB/UdtRecordCompleter.cpp
===
--- l

[Lldb-commits] [PATCH] D137873: [LLDB][Minidump] Set abi environment for windows.

2022-11-15 Thread Zequan Wu via Phabricator via lldb-commits
zequanwu abandoned this revision.
zequanwu added a comment.

In D137873#3926821 , @labath wrote:

> This dual environment thing is tricky.. MSVC is probably a better default, 
> but it would still mean that the same bugs will appear if the situation is 
> reversed (we assume MSVC environ, but the binary actually uses GNU). Have you 
> looked at how this interacts with https://reviews.llvm.org/D127048 (and the 
> setting introduced there) and whether you can achieve the same effect by 
> changing that setting?

Thanks, I didn't realize the existence of this setting.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137873

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


[Lldb-commits] [PATCH] D137873: [LLDB][Minidump] Set abi environment for windows.

2022-11-15 Thread Zequan Wu via Phabricator via lldb-commits
zequanwu reclaimed this revision.
zequanwu added a comment.

Oh, they are not the same. I will work on a similar setting for minidump.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137873

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


[Lldb-commits] [PATCH] D137217: [LTO][COFF] Use bitcode file names in lto native object file names.

2022-11-15 Thread Zequan Wu via Phabricator via lldb-commits
zequanwu updated this revision to Diff 475538.
zequanwu marked 2 inline comments as done.
zequanwu added a comment.

Update.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137217

Files:
  clang/lib/CodeGen/BackendUtil.cpp
  clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
  lld/COFF/LTO.cpp
  lld/COFF/LTO.h
  lld/ELF/LTO.cpp
  lld/MachO/LTO.cpp
  lld/test/COFF/lto-obj-path.ll
  lld/test/COFF/pdb-thinlto.ll
  lld/test/COFF/thinlto.ll
  lld/wasm/LTO.cpp
  lldb/source/Core/DataFileCache.cpp
  llvm/include/llvm/Support/Caching.h
  llvm/lib/Debuginfod/Debuginfod.cpp
  llvm/lib/LTO/LTO.cpp
  llvm/lib/LTO/LTOBackend.cpp
  llvm/lib/LTO/LTOCodeGenerator.cpp
  llvm/lib/Support/Caching.cpp
  llvm/tools/llvm-lto/llvm-lto.cpp
  llvm/tools/llvm-lto2/llvm-lto2.cpp

Index: llvm/tools/llvm-lto2/llvm-lto2.cpp
===
--- llvm/tools/llvm-lto2/llvm-lto2.cpp
+++ llvm/tools/llvm-lto2/llvm-lto2.cpp
@@ -411,7 +411,8 @@
   if (HasErrors)
 return 1;
 
-  auto AddStream = [&](size_t Task) -> std::unique_ptr {
+  auto AddStream = [&](size_t Task,
+   Twine ModuleName) -> std::unique_ptr {
 std::string Path = OutputFilename + "." + utostr(Task);
 
 std::error_code EC;
@@ -420,8 +421,9 @@
 return std::make_unique(std::move(S), Path);
   };
 
-  auto AddBuffer = [&](size_t Task, std::unique_ptr MB) {
-*AddStream(Task)->OS << MB->getBuffer();
+  auto AddBuffer = [&](size_t Task, Twine ModuleName,
+   std::unique_ptr MB) {
+*AddStream(Task, ModuleName)->OS << MB->getBuffer();
   };
 
   FileCache Cache;
Index: llvm/tools/llvm-lto/llvm-lto.cpp
===
--- llvm/tools/llvm-lto/llvm-lto.cpp
+++ llvm/tools/llvm-lto/llvm-lto.cpp
@@ -317,11 +317,11 @@
   if (!CurrentActivity.empty())
 OS << ' ' << CurrentActivity;
   OS << ": ";
-  
+
   DiagnosticPrinterRawOStream DP(OS);
   DI.print(DP);
   OS << '\n';
-  
+
   if (DI.getSeverity() == DS_Error)
 exit(1);
   return true;
@@ -1099,7 +1099,9 @@
 error("writing merged module failed.");
 }
 
-auto AddStream = [&](size_t Task) -> std::unique_ptr {
+auto AddStream =
+[&](size_t Task,
+Twine ModuleName) -> std::unique_ptr {
   std::string PartFilename = OutputFilename;
   if (Parallelism != 1)
 PartFilename += "." + utostr(Task);
Index: llvm/lib/Support/Caching.cpp
===
--- llvm/lib/Support/Caching.cpp
+++ llvm/lib/Support/Caching.cpp
@@ -37,7 +37,8 @@
   TempFilePrefixRef.toVector(TempFilePrefix);
   CacheDirectoryPathRef.toVector(CacheDirectoryPath);
 
-  return [=](unsigned Task, StringRef Key) -> Expected {
+  return [=](unsigned Task, StringRef Key,
+ Twine ModuleName) -> Expected {
 // This choice of file name allows the cache to be pruned (see pruneCache()
 // in include/llvm/Support/CachePruning.h).
 SmallString<64> EntryPath;
@@ -54,7 +55,7 @@
 /*RequiresNullTerminator=*/false);
   sys::fs::closeFile(*FDOrErr);
   if (MBOrErr) {
-AddBuffer(Task, std::move(*MBOrErr));
+AddBuffer(Task, ModuleName, std::move(*MBOrErr));
 return AddStreamFn();
   }
   EC = MBOrErr.getError();
@@ -77,14 +78,15 @@
 struct CacheStream : CachedFileStream {
   AddBufferFn AddBuffer;
   sys::fs::TempFile TempFile;
+  std::string ModuleName;
   unsigned Task;
 
   CacheStream(std::unique_ptr OS, AddBufferFn AddBuffer,
   sys::fs::TempFile TempFile, std::string EntryPath,
-  unsigned Task)
+  std::string ModuleName, unsigned Task)
   : CachedFileStream(std::move(OS), std::move(EntryPath)),
 AddBuffer(std::move(AddBuffer)), TempFile(std::move(TempFile)),
-Task(Task) {}
+ModuleName(ModuleName), Task(Task) {}
 
   ~CacheStream() {
 // TODO: Manually commit rather than using non-trivial destructor,
@@ -133,11 +135,12 @@
  TempFile.TmpName + " to " + ObjectPathName + ": " +
  toString(std::move(E)) + "\n");
 
-AddBuffer(Task, std::move(*MBOrErr));
+AddBuffer(Task, ModuleName, std::move(*MBOrErr));
   }
 };
 
-return [=](size_t Task) -> Expected> {
+return [=](size_t Task, Twine ModuleName)
+   -> Expected> {
   // Create the cache directory if not already done. Doing this lazily
   // ensures the filesystem isn't mutated until the cache is.
   if (std::error_code EC = sys::fs::create_directories(
@@ -158,7 +161,8 @@
   // This CacheStream will move the temporary file into the cache when done.
   return std::make_unique(
   std::make_unique(Tem

[Lldb-commits] [PATCH] D138060: Improve error logging when xcrun fails to execute successfully

2022-11-15 Thread Adrian Prantl via Phabricator via lldb-commits
aprantl created this revision.
aprantl added reviewers: JDevlieghere, kastiglione.
Herald added a project: All.
aprantl requested review of this revision.

Because Host::RunShellCommand runs commands through `$SHELL` there is an 
opportunity for this to fail spectacularly on systems that use custom shells 
with odd behaviors. This patch makes these situations easier to debug by at 
least logging the result of the failed xcrun invocation.

rdar://102107430


https://reviews.llvm.org/D138060

Files:
  lldb/source/Host/macosx/objcxx/HostInfoMacOSX.mm
  lldb/unittests/Host/HostTest.cpp


Index: lldb/unittests/Host/HostTest.cpp
===
--- lldb/unittests/Host/HostTest.cpp
+++ lldb/unittests/Host/HostTest.cpp
@@ -25,3 +25,16 @@
   ASSERT_EQ("Host::GetEnvironment",
 Host::GetEnvironment().lookup("LLDB_TEST_ENVIRONMENT_VAR"));
 }
+
+#if defined(LLVM_ON_UNIX)
+TEST(Host, RunShellCommand) {
+  std::string shell = "SHELL=" + getenv("SHELL");
+  putenv(const_cast("SHELL=/bin/LLDB_TEST_this-file-does-not-exist"));
+  int status;
+  std::string out;
+  Status error =
+  Host::RunShellCommand("/usr/bin/true", FileSpec(), &status, &signo, 
&out);
+  ASSERT_TRUE(error.Fail());
+  putenv(shell);
+}
+#endif
Index: lldb/source/Host/macosx/objcxx/HostInfoMacOSX.mm
===
--- lldb/source/Host/macosx/objcxx/HostInfoMacOSX.mm
+++ lldb/source/Host/macosx/objcxx/HostInfoMacOSX.mm
@@ -381,7 +381,7 @@
 args.AppendArgument("--sdk");
 args.AppendArgument(sdk);
 
-Log *log = GetLog(LLDBLog::Host);
+Log *log = GetLog(LLDBLog::Host | LLDBLog::Types);
 if (log) {
   std::string cmdstr;
   args.GetCommandString(cmdstr);
@@ -393,11 +393,21 @@
 std::string output_str;
 lldb_private::Status error =
 Host::RunShellCommand(args, FileSpec(), &status, &signo, &output_str,
-  std::chrono::seconds(15));
+  std::chrono::seconds(30));
 
-// Check that xcrun return something useful.
-if (status != 0 || output_str.empty())
+// Check that xcrun returned something useful.
+if (error.Fail()) {
+  LLDB_LOG(log, "xcrun failed to execute: %s", error.AsCString());
+  return {};
+}
+if (status != 0) {
+  LLDB_LOG(log, "xcrun returned exit code %d", status);
   return {};
+}
+if (output_str.empty()) {
+  LLDB_LOG(log, "xcrun returned no results");
+  return {};
+}
 
 // Convert to a StringRef so we can manipulate the string without modifying
 // the underlying data.


Index: lldb/unittests/Host/HostTest.cpp
===
--- lldb/unittests/Host/HostTest.cpp
+++ lldb/unittests/Host/HostTest.cpp
@@ -25,3 +25,16 @@
   ASSERT_EQ("Host::GetEnvironment",
 Host::GetEnvironment().lookup("LLDB_TEST_ENVIRONMENT_VAR"));
 }
+
+#if defined(LLVM_ON_UNIX)
+TEST(Host, RunShellCommand) {
+  std::string shell = "SHELL=" + getenv("SHELL");
+  putenv(const_cast("SHELL=/bin/LLDB_TEST_this-file-does-not-exist"));
+  int status;
+  std::string out;
+  Status error =
+  Host::RunShellCommand("/usr/bin/true", FileSpec(), &status, &signo, &out);
+  ASSERT_TRUE(error.Fail());
+  putenv(shell);
+}
+#endif
Index: lldb/source/Host/macosx/objcxx/HostInfoMacOSX.mm
===
--- lldb/source/Host/macosx/objcxx/HostInfoMacOSX.mm
+++ lldb/source/Host/macosx/objcxx/HostInfoMacOSX.mm
@@ -381,7 +381,7 @@
 args.AppendArgument("--sdk");
 args.AppendArgument(sdk);
 
-Log *log = GetLog(LLDBLog::Host);
+Log *log = GetLog(LLDBLog::Host | LLDBLog::Types);
 if (log) {
   std::string cmdstr;
   args.GetCommandString(cmdstr);
@@ -393,11 +393,21 @@
 std::string output_str;
 lldb_private::Status error =
 Host::RunShellCommand(args, FileSpec(), &status, &signo, &output_str,
-  std::chrono::seconds(15));
+  std::chrono::seconds(30));
 
-// Check that xcrun return something useful.
-if (status != 0 || output_str.empty())
+// Check that xcrun returned something useful.
+if (error.Fail()) {
+  LLDB_LOG(log, "xcrun failed to execute: %s", error.AsCString());
+  return {};
+}
+if (status != 0) {
+  LLDB_LOG(log, "xcrun returned exit code %d", status);
   return {};
+}
+if (output_str.empty()) {
+  LLDB_LOG(log, "xcrun returned no results");
+  return {};
+}
 
 // Convert to a StringRef so we can manipulate the string without modifying
 // the underlying data.
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D134066: [LLDB][NativePDB] Forcefully complete a record type if it has empty debug info and is required to have complete type.

2022-11-15 Thread Reid Kleckner via Phabricator via lldb-commits
rnk added a comment.

Following the direction of the DWARF plugin sounds good to me.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134066

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


[Lldb-commits] [PATCH] D138060: Improve error logging when xcrun fails to execute successfully

2022-11-15 Thread Dave Lee via Phabricator via lldb-commits
kastiglione added inline comments.



Comment at: lldb/source/Host/macosx/objcxx/HostInfoMacOSX.mm:384
 
-Log *log = GetLog(LLDBLog::Host);
+Log *log = GetLog(LLDBLog::Host | LLDBLog::Types);
 if (log) {

Maybe a comment explaining how this is useful in the Types category.



Comment at: lldb/source/Host/macosx/objcxx/HostInfoMacOSX.mm:396
 Host::RunShellCommand(args, FileSpec(), &status, &signo, &output_str,
-  std::chrono::seconds(15));
+  std::chrono::seconds(30));
 

Why is the timeout increased?



Comment at: lldb/source/Host/macosx/objcxx/HostInfoMacOSX.mm:399-406
+if (error.Fail()) {
+  LLDB_LOG(log, "xcrun failed to execute: %s", error.AsCString());
+  return {};
+}
+if (status != 0) {
+  LLDB_LOG(log, "xcrun returned exit code %d", status);
   return {};

Should this produce a diagnostic? Seems like failure here should be surfaced to 
the user.


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

https://reviews.llvm.org/D138060

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


[Lldb-commits] [lldb] 8d41609 - [lldb/test] Fix app_specific_backtrace_crashlog.test (NFC)

2022-11-15 Thread Med Ismail Bennani via lldb-commits

Author: Med Ismail Bennani
Date: 2022-11-15T14:25:52-08:00
New Revision: 8d416099240a2c090bd461f99c3014bac828cf98

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

LOG: [lldb/test] Fix app_specific_backtrace_crashlog.test (NFC)

This patch changes app_specific_backtrace_crashlog.test's crashlog file
extension from `ips` to `txt. This should prevent the test from opening
Console.app when being run.

This should also fix a test failure caused by missing symbols.

Signed-off-by: Med Ismail Bennani 

Added: 

lldb/test/Shell/ScriptInterpreter/Python/Crashlog/Inputs/application_specific_info/asi.txt

Modified: 

lldb/test/Shell/ScriptInterpreter/Python/Crashlog/app_specific_backtrace_crashlog.test

Removed: 

lldb/test/Shell/ScriptInterpreter/Python/Crashlog/Inputs/application_specific_info/asi.ips



diff  --git 
a/lldb/test/Shell/ScriptInterpreter/Python/Crashlog/Inputs/application_specific_info/asi.ips
 
b/lldb/test/Shell/ScriptInterpreter/Python/Crashlog/Inputs/application_specific_info/asi.txt
similarity index 100%
rename from 
lldb/test/Shell/ScriptInterpreter/Python/Crashlog/Inputs/application_specific_info/asi.ips
rename to 
lldb/test/Shell/ScriptInterpreter/Python/Crashlog/Inputs/application_specific_info/asi.txt

diff  --git 
a/lldb/test/Shell/ScriptInterpreter/Python/Crashlog/app_specific_backtrace_crashlog.test
 
b/lldb/test/Shell/ScriptInterpreter/Python/Crashlog/app_specific_backtrace_crashlog.test
index 5ca5c51a3125c..c57cefdaf32d2 100644
--- 
a/lldb/test/Shell/ScriptInterpreter/Python/Crashlog/app_specific_backtrace_crashlog.test
+++ 
b/lldb/test/Shell/ScriptInterpreter/Python/Crashlog/app_specific_backtrace_crashlog.test
@@ -3,7 +3,7 @@
 # RUN: mkdir -p %t.dir
 # RUN: yaml2obj %S/Inputs/application_specific_info/asi.yaml > %t.dir/asi
 # RUN: %lldb -o 'command script import lldb.macosx.crashlog' \
-# RUN: -o 'crashlog -a -i -t %t.dir/asi 
%S/Inputs/application_specific_info/asi.ips' \
+# RUN: -o 'crashlog -a -i -t %t.dir/asi 
%S/Inputs/application_specific_info/asi.txt' \
 # RUN: -o "thread list" -o "bt all" 2>&1 | FileCheck %s
 
 # CHECK: "crashlog" {{.*}} commands have been installed, use the "--help" 
options on these commands
@@ -44,7 +44,7 @@
 # CHECK-NEXT: frame #3: 0x0001a0b46af3{{.*}}
 # CHECK-NEXT: frame #4: 0x0001a09a12a3{{.*}}
 # CHECK-NEXT: frame #5: 0x0001047e3ecf asi`main{{.*}}
-# CHECK-NEXT: frame #6: 0x0001a05d3e4f dyld`start{{.*}}
+# CHECK-NEXT: frame #6: 0x0001a05d3e4f
 
 
 # CHECK: (lldb) thread list



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


[Lldb-commits] [lldb] 0869a69 - NFC test if rosetta debugserver exists before testing rosetta

2022-11-15 Thread Jason Molenda via lldb-commits

Author: Jason Molenda
Date: 2022-11-15T14:35:02-08:00
New Revision: 0869a699173f6d92949153e5301e6cfadf33201c

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

LOG: NFC test if rosetta debugserver exists before testing rosetta

A fresh install of macOS does not have Rosetta 2 installed by
default; the CI bots are often in this state, resulting in a
test failure.  debugserver already hardcodes the filepath of
the Rosetta 2 debugserver; test if that file exists before
running the Rosetta test.

Added: 


Modified: 
lldb/test/API/macosx/rosetta/TestRosetta.py

Removed: 




diff  --git a/lldb/test/API/macosx/rosetta/TestRosetta.py 
b/lldb/test/API/macosx/rosetta/TestRosetta.py
index 8836db9db73dc..4146fc3dbe929 100644
--- a/lldb/test/API/macosx/rosetta/TestRosetta.py
+++ b/lldb/test/API/macosx/rosetta/TestRosetta.py
@@ -3,6 +3,7 @@
 import lldbsuite.test.lldbutil as lldbutil
 from lldbsuite.test.lldbtest import *
 from lldbsuite.test.decorators import *
+from os.path import exists
 
 
 def get_os_version():
@@ -16,6 +17,8 @@ def get_os_version():
 return m.group(1)
 return None
 
+def rosetta_debugserver_installed():
+return exists("/Library/Apple/usr/libexec/oah/debugserver")
 
 def has_rosetta_shared_cache(os_version):
 if not os_version:
@@ -41,16 +44,17 @@ def test_rosetta(self):
 self.build()
 self.main_source_file = lldb.SBFileSpec("main.c")
 
-broadcaster = self.dbg.GetBroadcaster()
-listener = lldbutil.start_listening_from(
-broadcaster, lldb.SBDebugger.eBroadcastBitWarning)
+if rosetta_debugserver_installed():
+  broadcaster = self.dbg.GetBroadcaster()
+  listener = lldbutil.start_listening_from(
+  broadcaster, lldb.SBDebugger.eBroadcastBitWarning)
 
-target, process, thread, bkpt = lldbutil.run_to_source_breakpoint(
-self, "Set a breakpoint here", self.main_source_file)
+  target, process, thread, bkpt = lldbutil.run_to_source_breakpoint(
+  self, "Set a breakpoint here", self.main_source_file)
 
-event = lldb.SBEvent()
-os_version = get_os_version()
-if not has_rosetta_shared_cache(os_version):
-self.assertTrue(listener.GetNextEvent(event))
-else:
-self.assertFalse(listener.GetNextEvent(event))
+  event = lldb.SBEvent()
+  os_version = get_os_version()
+  if not has_rosetta_shared_cache(os_version):
+  self.assertTrue(listener.GetNextEvent(event))
+  else:
+  self.assertFalse(listener.GetNextEvent(event))



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


[Lldb-commits] [lldb] 1447ea0 - NFC test if rosetta is installed before running x86 binary on AS

2022-11-15 Thread Jason Molenda via lldb-commits

Author: Jason Molenda
Date: 2022-11-15T14:44:35-08:00
New Revision: 1447ea059b4ac0995418950c1146fd936d57fee6

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

LOG: NFC test if rosetta is installed before running x86 binary on AS

Rosetta 2 is not installed by default in a fresh macOS installation
on Apple Silicon, so x86 binaries cannot be run.  CI bots are often
in this state.  Update this test to check for the rosetta debugserver,
which our debugserver also hardcodes the path of, before trying to
run an x86 process on AS systems.

Added: 


Modified: 
lldb/test/API/macosx/posix_spawn/TestLaunchProcessPosixSpawn.py

Removed: 




diff  --git a/lldb/test/API/macosx/posix_spawn/TestLaunchProcessPosixSpawn.py 
b/lldb/test/API/macosx/posix_spawn/TestLaunchProcessPosixSpawn.py
index 1c25dc02e5ea3..166b4dfa50b28 100644
--- a/lldb/test/API/macosx/posix_spawn/TestLaunchProcessPosixSpawn.py
+++ b/lldb/test/API/macosx/posix_spawn/TestLaunchProcessPosixSpawn.py
@@ -1,5 +1,6 @@
 import contextlib
 import os
+from os.path import exists
 import lldb
 from lldbsuite.test.decorators import *
 from lldbsuite.test.lldbtest import *
@@ -16,6 +17,9 @@ def apple_silicon():
 return "Apple M" in features.decode('utf-8')
 
 
+def rosetta_debugserver_installed():
+return exists("/Library/Apple/usr/libexec/oah/debugserver")
+
 class TestLaunchProcessPosixSpawn(TestBase):
 NO_DEBUG_INFO_TESTCASE = True
 
@@ -56,5 +60,6 @@ def test_haswell(self):
 def test_apple_silicon(self):
 self.build()
 exe = self.getBuildArtifact("fat.out")
-self.run_arch(exe, 'x86_64')
+if rosetta_debugserver_installed():
+self.run_arch(exe, 'x86_64')
 self.run_arch(exe, 'arm64')



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


[Lldb-commits] [PATCH] D137583: [lldb] Fix simple template names and template params with scope qualifiers

2022-11-15 Thread David Blaikie via Phabricator via lldb-commits
dblaikie accepted this revision.
dblaikie added a comment.
This revision is now accepted and ready to land.

Awesome!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137583

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


[Lldb-commits] [lldb] 4bc86ae - [lldb-vscode] Send Selected Statistics Dump in Terminated Event

2022-11-15 Thread Wanyi Ye via lldb-commits

Author: Wanyi Ye
Date: 2022-11-15T15:24:36-08:00
New Revision: 4bc86ae83e956cd6d5b9e5fdbec6a85ccc579fc9

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

LOG: [lldb-vscode] Send Selected Statistics Dump in Terminated Event

This patch will gather debug info & breakpoint info from the statistics dump 
(from `(SBTarget.GetStatistics())` func) and send to DAP in terminated event.

The statistics content can be huge (especially the `modules`) and dumping in 
full JSON can create delay in the IDE's debugging UI. (For more details, please 
read: 
https://github.com/llvm/llvm-project/commit/7bbd0fba986c241162b77b7e424ad82bc7e17b41
 ). Hence, we will filter out large contents before returning it in terminated 
event.

It will keep all the metadata fields (those starts with "total"). For large 
contents, it uses the opt-out strategy. Currently it only removes the "modules" 
field. This way every time a new top-level field being added, we will be able 
to capture them from DAP log without changing lldb-vscode.

The DAP terminated event should look like
```
{
  "event":"terminated",
  "seq":0,
  "statistics": {
"memory": 
"targets": , // it's a JSON array, breakpoints info included 
in each target
 // pairs
  },
  "type":"event"
}
```

All the info above will be append to statistics field in the terminated event

Test Plan

Debugged a simple hello world program from VSCode. Exit debug session in two 
ways: 1) run to program exit; 2) user initiated debug session end (quit 
debugging before program exit).
Check DAP log and see both debug sessions have statistics returned in 
terminated event.

Here's an example when debugging the test program:

```
{"event":"terminated","seq":0,"statistics":{"memory":"{\"strings\":{\"bytesTotal\":1843200,\"bytesUnused\":897741,\"bytesUsed\":945459}}","targets":"[{\"breakpoints\":[{\"details\":{\"Breakpoint\":{\"BKPTOptions\":{\"AutoContinue\":false,\"ConditionText\":\"\",\"EnabledState\":true,\"IgnoreCount\":0,\"OneShotState\":false},\"BKPTResolver\":{\"Options\":{\"NameMask\":[56],\"Offset\":0,\"SkipPrologue\":true,\"SymbolNames\":[\"foo\"]},\"Type\":\"SymbolName\"},\"Hardware\":false,\"Names\":[\"vscode\"],\"SearchFilter\":{\"Options\":{},\"Type\":\"Unconstrained\"}}},\"id\":1,\"internal\":false,\"numLocations\":1,\"numResolvedLocations\":1,\"resolveTime\":0.002232},{\"details\":{\"Breakpoint\":{\"BKPTOptions\":{\"AutoContinue\":false,\"ConditionText\":\"\",\"EnabledState\":true,\"IgnoreCount\":0,\"OneShotState\":false},\"BKPTResolver\":{\"Options\":{\"Column\":0,\"Exact\":false,\"FileName\":\"/data/users/wanyi/llvm-sand/external/llvm-project/lldb/test/API/tools/lldb-vscode/terminated-event/main.cpp\",\"Inlines\":true,\"LineNumber\":5,\"Offset\":0,\"SkipPrologue\":true},\"Type\":\"FileAndLine\"},\"Hardware\":false,\"Names\":[\"vscode\"],\"SearchFilter\":{\"Options\":{},\"Type\":\"Unconstrained\"}}},\"id\":2,\"internal\":false,\"numLocations\":0,\"numResolvedLocations\":0,\"resolveTime\":0.232037999},{\"details\":{\"Breakpoint\":{\"BKPTOptions\":{\"AutoContinue\":false,\"ConditionText\":\"\",\"EnabledState\":true,\"IgnoreCount\":0,\"OneShotState\":false},\"BKPTResolver\":{\"Options\":{\"Language\":\"c\",\"NameMask\":[4,4,4,4,4,4],\"Offset\":0,\"SkipPrologue\":false,\"SymbolNames\":[\"_dl_debug_state\",\"rtld_db_dlactivity\",\"__dl_rtld_db_dlactivity\",\"r_debug_state\",\"_r_debug_state\",\"_rtld_debug_state\"]},\"Type\":\"SymbolName\"},\"Hardware\":false,\"SearchFilter\":{\"Options\":{\"ModuleList\":[\"/usr/lib64/ld-2.28.so\"]},\"Type\":\"Modules\"}}},\"id\":-1,\"internal\":true,\"kindDescription\":\"shared-library-event\",\"numLocations\":1,\"numResolvedLocations\":1,\"resolveTime\":0.00026698}],\"expressionEvaluation\":{\"failures\":0,\"successes\":0},\"firstStopTime\":0.0874589744,\"frameVariable\":{\"failures\":0,\"successes\":0},\"launchOrAttachTime\":0.0529531618,\"moduleIdentifiers\":[94554748126576,94554747837792,94554747149216,139800112130176,139800112161056,139800112206064,139800112340224,139800112509552,139800112236528],\"signals\":[{\"SIGSTOP\":1}],\"sourceMapDeduceCount\":0,\"stopCount\":8,\"targetCreateTime\":0.00057704,\"totalBreakpointResolveTime\":0.234537}]","totalDebugInfoByteSize":1668056,"totalDebugInfoEnabled":3,"totalDebugInfoIndexLoadedFromCache":0,"totalDebugInfoIndexSavedToCache":0,"totalDebugInfoIndexTime":0.0279630002,"totalDebugInfoParseTime":0.343548002,"totalModuleCount":10,"totalModuleCountHasDebugInfo":3,"totalSymbolTableIndexTime":0.056053,"totalSymbolTableParseTime":0.23931,"totalSymbolTableStripped":0,"totalSymbolTablesLoadedFromCache":0,"totalSymbolTablesSavedToCache":0},"type":"event"}
```

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

Added: 
lldb/test/API/tools/lldb-vscode/terminated-event/Make

[Lldb-commits] [PATCH] D137665: [lldb-vscode] Send Selected Statistics Dump in Terminated Event

2022-11-15 Thread Wanyi Ye via Phabricator via lldb-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG4bc86ae83e95: [lldb-vscode] Send Selected Statistics Dump in 
Terminated Event (authored by kusmour).
Herald added a project: LLDB.
Herald added a subscriber: lldb-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137665

Files:
  lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py
  lldb/test/API/tools/lldb-vscode/terminated-event/Makefile
  lldb/test/API/tools/lldb-vscode/terminated-event/TestVSCode_terminatedEvent.py
  lldb/test/API/tools/lldb-vscode/terminated-event/foo.cpp
  lldb/test/API/tools/lldb-vscode/terminated-event/foo.h
  lldb/test/API/tools/lldb-vscode/terminated-event/main.cpp
  lldb/tools/lldb-vscode/JSONUtils.cpp
  lldb/tools/lldb-vscode/JSONUtils.h
  lldb/tools/lldb-vscode/lldb-vscode.cpp

Index: lldb/tools/lldb-vscode/lldb-vscode.cpp
===
--- lldb/tools/lldb-vscode/lldb-vscode.cpp
+++ lldb/tools/lldb-vscode/lldb-vscode.cpp
@@ -204,7 +204,7 @@
 g_vsc.sent_terminated_event = true;
 g_vsc.RunTerminateCommands();
 // Send a "terminated" event
-llvm::json::Object event(CreateEventObject("terminated"));
+llvm::json::Object event(CreateTerminatedEventObject());
 g_vsc.SendJSON(llvm::json::Value(std::move(event)));
   }
 }
@@ -2949,7 +2949,7 @@
   const uint32_t addr_size = g_vsc.target.GetProcess().GetAddressByteSize();
   lldb::SBValue reg_set = g_vsc.variables.registers.GetValueAtIndex(0);
   const uint32_t num_regs = reg_set.GetNumChildren();
-  for (uint32_t reg_idx=0; reg_idx pairs
+void FilterAndGetValueForKey(const lldb::SBStructuredData data, const char *key,
+ llvm::json::Object &out) {
+  lldb::SBStructuredData value = data.GetValueForKey(key);
+  std::string key_utf8 = llvm::json::fixUTF8(key);
+  if (strcmp(key, "modules") == 0)
+return;
+  switch (value.GetType()) {
+  case lldb::eStructuredDataTypeFloat:
+out.try_emplace(key_utf8, value.GetFloatValue());
+break;
+  case lldb::eStructuredDataTypeInteger:
+out.try_emplace(key_utf8, value.GetIntegerValue());
+break;
+  case lldb::eStructuredDataTypeArray: {
+lldb::SBStream contents;
+value.GetAsJSON(contents);
+out.try_emplace(key_utf8, llvm::json::fixUTF8(contents.GetData()));
+  } break;
+  case lldb::eStructuredDataTypeBoolean:
+out.try_emplace(key_utf8, value.GetBooleanValue());
+break;
+  case lldb::eStructuredDataTypeString: {
+// Get the string size before reading
+const size_t str_length = value.GetStringValue(nullptr, 0);
+std::string str(str_length + 1, 0);
+value.GetStringValue(&str[0], str_length);
+out.try_emplace(key_utf8, llvm::json::fixUTF8(str));
+  } break;
+  case lldb::eStructuredDataTypeDictionary: {
+lldb::SBStream contents;
+value.GetAsJSON(contents);
+out.try_emplace(key_utf8, llvm::json::fixUTF8(contents.GetData()));
+  } break;
+  case lldb::eStructuredDataTypeNull:
+  case lldb::eStructuredDataTypeGeneric:
+  case lldb::eStructuredDataTypeInvalid:
+break;
+  }
+}
+
+void addStatistic(llvm::json::Object &event) {
+  lldb::SBStructuredData statistics = g_vsc.target.GetStatistics();
+  bool is_dictionary =
+  statistics.GetType() == lldb::eStructuredDataTypeDictionary;
+  if (!is_dictionary)
+return;
+  llvm::json::Object stats_body;
+
+  lldb::SBStringList keys;
+  if (!statistics.GetKeys(keys))
+return;
+  for (size_t i = 0; i < keys.GetSize(); i++) {
+const char *key = keys.GetStringAtIndex(i);
+FilterAndGetValueForKey(statistics, key, stats_body);
+  }
+  event.try_emplace("statistics", std::move(stats_body));
+}
+
+llvm::json::Object CreateTerminatedEventObject() {
+  llvm::json::Object event(CreateEventObject("terminated"));
+  addStatistic(event);
+  return event;
+}
+
 std::string JSONToString(const llvm::json::Value &json) {
   std::string data;
   llvm::raw_string_ostream os(data);
Index: lldb/test/API/tools/lldb-vscode/terminated-event/main.cpp
===
--- /dev/null
+++ lldb/test/API/tools/lldb-vscode/terminated-event/main.cpp
@@ -0,0 +1,8 @@
+#include 
+#include "foo.h"
+
+int main(int argc, char const *argv[]) {
+  std::cout << "Hello World!" << std::endl; // main breakpoint 1
+  foo();
+  return 0;
+}
Index: lldb/test/API/tools/lldb-vscode/terminated-event/foo.h
===
--- /dev/null
+++ lldb/test/API/tools/lldb-vscode/terminated-event/foo.h
@@ -0,0 +1 @@
+int foo();
Index: lldb/test/API/tools/lldb-vscode/terminated-event/foo.cpp
===
--- /dev/null
+++ lldb/test/API/tools/lldb-vscode/terminated-event/foo.cpp
@@ -0,0 +1,3 @@
+int foo() {
+return 12;
+}
Index: lldb/test/API/tools/lldb-vscode/termin

[Lldb-commits] [PATCH] D138077: Send statistics in initialized event

2022-11-15 Thread Yubo Hu via Phabricator via lldb-commits
GeorgeHuyubo created this revision.
Herald added a project: All.
GeorgeHuyubo requested review of this revision.
Herald added a project: LLDB.
Herald added a subscriber: lldb-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D138077

Files:
  lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py
  lldb/test/API/tools/lldb-vscode/eventStatistic/Makefile
  lldb/test/API/tools/lldb-vscode/eventStatistic/TestVSCode_eventStatistic.py
  lldb/test/API/tools/lldb-vscode/eventStatistic/foo.cpp
  lldb/test/API/tools/lldb-vscode/eventStatistic/foo.h
  lldb/test/API/tools/lldb-vscode/eventStatistic/main.cpp
  lldb/test/API/tools/lldb-vscode/terminated-event/Makefile
  lldb/test/API/tools/lldb-vscode/terminated-event/TestVSCode_terminatedEvent.py
  lldb/test/API/tools/lldb-vscode/terminated-event/foo.cpp
  lldb/test/API/tools/lldb-vscode/terminated-event/foo.h
  lldb/test/API/tools/lldb-vscode/terminated-event/main.cpp
  lldb/tools/lldb-vscode/JSONUtils.cpp
  lldb/tools/lldb-vscode/JSONUtils.h
  lldb/tools/lldb-vscode/lldb-vscode.cpp

Index: lldb/tools/lldb-vscode/lldb-vscode.cpp
===
--- lldb/tools/lldb-vscode/lldb-vscode.cpp
+++ lldb/tools/lldb-vscode/lldb-vscode.cpp
@@ -687,7 +687,7 @@
   g_vsc.SendJSON(llvm::json::Value(std::move(response)));
   if (error.Success()) {
 SendProcessEvent(Attach);
-g_vsc.SendJSON(CreateEventObject("initialized"));
+g_vsc.SendJSON(CreateInitializedEventObject());
   }
 }
 
@@ -1754,7 +1754,7 @@
 SendProcessEvent(Attach); // this happens when doing runInTerminal
   else
 SendProcessEvent(Launch);
-  g_vsc.SendJSON(llvm::json::Value(CreateEventObject("initialized")));
+  g_vsc.SendJSON(CreateInitializedEventObject());
 }
 
 // "NextRequest": {
Index: lldb/tools/lldb-vscode/JSONUtils.h
===
--- lldb/tools/lldb-vscode/JSONUtils.h
+++ lldb/tools/lldb-vscode/JSONUtils.h
@@ -491,6 +491,12 @@
 /// A body JSON object with debug info and breakpoint info
 llvm::json::Object CreateTerminatedEventObject();
 
+/// Create a "Initialized" JSON object that contains statistics
+///
+/// \return
+/// A body JSON object with debug info
+llvm::json::Object CreateInitializedEventObject();
+
 /// Convert a given JSON object to a string.
 std::string JSONToString(const llvm::json::Value &json);
 
Index: lldb/tools/lldb-vscode/JSONUtils.cpp
===
--- lldb/tools/lldb-vscode/JSONUtils.cpp
+++ lldb/tools/lldb-vscode/JSONUtils.cpp
@@ -1209,6 +1209,12 @@
   return event;
 }
 
+llvm::json::Object CreateInitializedEventObject() {
+  llvm::json::Object event(CreateEventObject("initialized"));
+  addStatistic(event);
+  return event;
+}
+
 std::string JSONToString(const llvm::json::Value &json) {
   std::string data;
   llvm::raw_string_ostream os(data);
Index: lldb/test/API/tools/lldb-vscode/terminated-event/main.cpp
===
--- /dev/null
+++ lldb/test/API/tools/lldb-vscode/terminated-event/main.cpp
@@ -1,8 +0,0 @@
-#include 
-#include "foo.h"
-
-int main(int argc, char const *argv[]) {
-  std::cout << "Hello World!" << std::endl; // main breakpoint 1
-  foo();
-  return 0;
-}
Index: lldb/test/API/tools/lldb-vscode/terminated-event/foo.h
===
--- /dev/null
+++ lldb/test/API/tools/lldb-vscode/terminated-event/foo.h
@@ -1 +0,0 @@
-int foo();
Index: lldb/test/API/tools/lldb-vscode/terminated-event/foo.cpp
===
--- /dev/null
+++ lldb/test/API/tools/lldb-vscode/terminated-event/foo.cpp
@@ -1,3 +0,0 @@
-int foo() {
-return 12;
-}
Index: lldb/test/API/tools/lldb-vscode/eventStatistic/TestVSCode_eventStatistic.py
===
--- lldb/test/API/tools/lldb-vscode/eventStatistic/TestVSCode_eventStatistic.py
+++ lldb/test/API/tools/lldb-vscode/eventStatistic/TestVSCode_eventStatistic.py
@@ -10,7 +10,27 @@
 import re
 import json
 
-class TestVSCode_terminatedEvent(lldbvscode_testcase.VSCodeTestCaseBase):
+class TestVSCode_eventStatistic(lldbvscode_testcase.VSCodeTestCaseBase):
+
+def check_statistic(self, statistics):
+self.assertTrue(statistics['totalDebugInfoByteSize'] > 0)
+self.assertTrue(statistics['totalDebugInfoEnabled'] > 0)
+self.assertTrue(statistics['totalModuleCountHasDebugInfo'] > 0)
+
+self.assertIsNotNone(statistics['memory'])
+self.assertNotIn('modules', statistics.keys())
+
+def check_target(self, statistics):
+# lldb-vscode debugs one target at a time
+target = json.loads(statistics['targets'])[0]
+self.assertTrue(target['totalBreakpointResolveTime'] > 0)
+
+breakpoints = target['breakpoints']
+self.assertIn('foo',
+  br

[Lldb-commits] [PATCH] D137983: [lldb] Disable looking at pointee types to find synthetic value for non-ObjC

2022-11-15 Thread Arthur Eubanks via Phabricator via lldb-commits
aeubanks updated this revision to Diff 475627.
aeubanks added a comment.

add bug


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137983

Files:
  lldb/source/Core/ValueObject.cpp


Index: lldb/source/Core/ValueObject.cpp
===
--- lldb/source/Core/ValueObject.cpp
+++ lldb/source/Core/ValueObject.cpp
@@ -2673,7 +2673,10 @@
 // In case of incomplete child compiler type, use the pointee type and try
 // to recreate a new ValueObjectChild using it.
 if (!m_deref_valobj) {
-  if (HasSyntheticValue()) {
+  // FIXME(#59012): C++ stdlib formatters break with incomplete types (e.g.
+  // `std::vector &`). Remove ObjC restriction once that's resolved.
+  if (Language::LanguageIsObjC(GetPreferredDisplayLanguage()) &&
+  HasSyntheticValue()) {
 child_compiler_type = compiler_type.GetPointeeType();
 
 if (child_compiler_type) {


Index: lldb/source/Core/ValueObject.cpp
===
--- lldb/source/Core/ValueObject.cpp
+++ lldb/source/Core/ValueObject.cpp
@@ -2673,7 +2673,10 @@
 // In case of incomplete child compiler type, use the pointee type and try
 // to recreate a new ValueObjectChild using it.
 if (!m_deref_valobj) {
-  if (HasSyntheticValue()) {
+  // FIXME(#59012): C++ stdlib formatters break with incomplete types (e.g.
+  // `std::vector &`). Remove ObjC restriction once that's resolved.
+  if (Language::LanguageIsObjC(GetPreferredDisplayLanguage()) &&
+  HasSyntheticValue()) {
 child_compiler_type = compiler_type.GetPointeeType();
 
 if (child_compiler_type) {
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D137873: [LLDB][Minidump] Set abi environment for windows.

2022-11-15 Thread Zequan Wu via Phabricator via lldb-commits
zequanwu updated this revision to Diff 475628.
zequanwu added a comment.
Herald added subscribers: llvm-commits, mstorsjo.
Herald added a project: LLVM.

Add `settings set plugin.process.minidump.abi msvc/gnu` to override minidump 
abi triple.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137873

Files:
  lldb/source/Plugins/Process/minidump/CMakeLists.txt
  lldb/source/Plugins/Process/minidump/ProcessMinidump.cpp
  lldb/source/Plugins/Process/minidump/ProcessMinidump.h
  lldb/source/Plugins/Process/minidump/ProcessMinidumpProperties.td
  lldb/test/Shell/Minidump/Windows/find-module.test
  llvm/utils/gn/secondary/lldb/source/Plugins/Process/minidump/BUILD.gn

Index: llvm/utils/gn/secondary/lldb/source/Plugins/Process/minidump/BUILD.gn
===
--- llvm/utils/gn/secondary/lldb/source/Plugins/Process/minidump/BUILD.gn
+++ llvm/utils/gn/secondary/lldb/source/Plugins/Process/minidump/BUILD.gn
@@ -1,7 +1,20 @@
+import("//lldb/utils/TableGen/lldb_tablegen.gni")
+
+lldb_tablegen("ProcessMinidumpProperties") {
+  args = [ "-gen-lldb-property-defs" ]
+}
+
+lldb_tablegen("ProcessMinidumpPropertiesEnum") {
+  args = [ "-gen-lldb-property-enum-defs" ]
+  td_file = "ProcessMinidumpProperties.td"
+}
+
 static_library("minidump") {
   output_name = "lldbPluginProcessMinidump"
   configs += [ "//llvm/utils/gn/build:lldb_code" ]
   deps = [
+":ProcessMinidumpProperties",
+":ProcessMinidumpPropertiesEnum",
 "//lldb/source/Core",
 "//lldb/source/Plugins/Process/Utility",
 "//lldb/source/Plugins/Process/elf-core",
Index: lldb/test/Shell/Minidump/Windows/find-module.test
===
--- lldb/test/Shell/Minidump/Windows/find-module.test
+++ lldb/test/Shell/Minidump/Windows/find-module.test
@@ -4,7 +4,21 @@
 RUN: yaml2obj %S/Inputs/find-module.exe.yaml -o %T/find-module.exe
 RUN: yaml2obj %S/Inputs/find-module.dmp.yaml -o %T/find-module.dmp
 RUN: %lldb -O "settings set target.exec-search-paths %T" \
-RUN:   -c %T/find-module.dmp -o "image dump objfile" -o exit | FileCheck %s
+RUN:   -c %T/find-module.dmp -o "image dump objfile" -o "target list" -o exit \
+RUN:   | FileCheck -DABI=msvc -DFILENAME=%basename_t.tmp %s
+
+RUN: %lldb -O "settings set plugin.process.minidump.abi msvc" \
+RUN:   -O "settings set target.exec-search-paths %T" \
+RUN:   -c %T/find-module.dmp -o "image dump objfile" -o "target list" -o exit \
+RUN:   | FileCheck -DABI=msvc -DFILENAME=%basename_t.tmp %s
+
+RUN: %lldb -O "settings set plugin.process.minidump.abi gnu" \
+RUN:   -O "settings set target.exec-search-paths %T" \
+RUN:   -c %T/find-module.dmp -o "image dump objfile" -o "target list" -o exit \
+RUN:   | FileCheck -DABI=gnu -DFILENAME=%basename_t.tmp %s
 
 CHECK-LABEL: image dump objfile
 CHECK: ObjectFilePECOFF, file = '{{.*}}find-module.exe', arch = i386
+
+CHECK-LABEL: target list
+CHECK: arch=i386-pc-windows-[[ABI]]
Index: lldb/source/Plugins/Process/minidump/ProcessMinidumpProperties.td
===
--- /dev/null
+++ lldb/source/Plugins/Process/minidump/ProcessMinidumpProperties.td
@@ -0,0 +1,9 @@
+include "../../../../include/lldb/Core/PropertiesBase.td"
+
+let Definition = "processminidump" in {
+  def ABI: Property<"abi", "Enum">,
+Global,
+DefaultEnumValue<"llvm::Triple::UnknownEnvironment">,
+EnumValues<"OptionEnumValues(g_abi_enums)">,
+Desc<"ABI to use when loading a Windows minidump. This configures the C++ ABI used, which affects things like the handling of class layout. Accepted values are: `msvc` for the MSVC ABI, `gnu` for the MinGW / Itanium ABI, and `default` to follow the default target if it is a Windows triple or use the MSVC ABI by default.">;
+}
Index: lldb/source/Plugins/Process/minidump/ProcessMinidump.h
===
--- lldb/source/Plugins/Process/minidump/ProcessMinidump.h
+++ lldb/source/Plugins/Process/minidump/ProcessMinidump.h
@@ -35,6 +35,8 @@
 
   static void Initialize();
 
+  static void DebuggerInitialize(Debugger &debugger);
+
   static void Terminate();
 
   static llvm::StringRef GetPluginNameStatic() { return "minidump"; }
Index: lldb/source/Plugins/Process/minidump/ProcessMinidump.cpp
===
--- lldb/source/Plugins/Process/minidump/ProcessMinidump.cpp
+++ lldb/source/Plugins/Process/minidump/ProcessMinidump.cpp
@@ -21,6 +21,7 @@
 #include "lldb/Interpreter/CommandReturnObject.h"
 #include "lldb/Interpreter/OptionArgParser.h"
 #include "lldb/Interpreter/OptionGroupBoolean.h"
+#include "lldb/Interpreter/OptionValueProperties.h"
 #include "lldb/Target/JITLoaderList.h"
 #include "lldb/Target/MemoryRegionInfo.h"
 #include "lldb/Target/SectionLoadList.h"
@@ -46,6 +47,55 @@
 
 namespace {
 
+static constexpr Optio

[Lldb-commits] [PATCH] D137983: [lldb] Disable looking at pointee types to find synthetic value for non-ObjC

2022-11-15 Thread Arthur Eubanks via Phabricator via lldb-commits
aeubanks added inline comments.



Comment at: lldb/source/Core/ValueObject.cpp:2676-2677
 if (!m_deref_valobj) {
-  if (HasSyntheticValue()) {
+  // FIXME: C++ stdlib formatters break with incomplete types (e.g.
+  // `std::vector &`). Remove ObjC restriction once that's resolved.
+  if (Language::LanguageIsObjC(GetPreferredDisplayLanguage()) &&

dblaikie wrote:
> Maybe worth filing a bug and referencing it here?
> 
> Is this limitation still necessary if the incomplete type has template 
> parameter DIEs? (I guess probably yes, because it'll be missing member 
> descriptions, etc)
> 
> & does this path get hit if the type is declared in one CU but defined in 
> another? (& does the inf recurse/crash loop still get hit in that case, 
> without this patch?)
> Maybe worth filing a bug and referencing it here?
Filed https://github.com/llvm/llvm-project/issues/59012, added here

> Is this limitation still necessary if the incomplete type has template 
> parameter DIEs? (I guess probably yes, because it'll be missing member 
> descriptions, etc)
yes (I incorrectly mentioned in person that this works with 
`-gsimple-template-names`, it actually still infinite recurses)

> & does this path get hit if the type is declared in one CU but defined in 
> another? (& does the inf recurse/crash loop still get hit in that case, 
> without this patch?)
if the declaration is in a shared library and the main binary has the 
definition, we hit this
if we have two CUs, one with a declaration, one with a definition, but both 
linked into the same binary, we don't hit the issue
AFAICT lldb restricts looking up debug info to the binary/shared library, but 
otherwise prefers definitions over declarations?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137983

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


[Lldb-commits] [PATCH] D138060: Improve error logging when xcrun fails to execute successfully

2022-11-15 Thread Adrian Prantl via Phabricator via lldb-commits
aprantl updated this revision to Diff 475630.
aprantl edited the summary of this revision.
aprantl added a comment.

Implemented error handling of sorts. Because the computation result is cached 
and most uses are nested deep in places that have no proper error handling 
themselves I'm logging to the global error stream.


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

https://reviews.llvm.org/D138060

Files:
  lldb/source/Host/macosx/objcxx/HostInfoMacOSX.mm
  lldb/unittests/Host/CMakeLists.txt
  lldb/unittests/Host/HostTest.cpp

Index: lldb/unittests/Host/HostTest.cpp
===
--- lldb/unittests/Host/HostTest.cpp
+++ lldb/unittests/Host/HostTest.cpp
@@ -7,6 +7,8 @@
 //===--===//
 
 #include "lldb/Host/Host.h"
+#include "lldb/Host/FileSystem.h"
+#include "lldb/Host/HostInfoBase.h"
 #include "gtest/gtest.h"
 
 using namespace lldb_private;
@@ -25,3 +27,25 @@
   ASSERT_EQ("Host::GetEnvironment",
 Host::GetEnvironment().lookup("LLDB_TEST_ENVIRONMENT_VAR"));
 }
+
+#if defined(LLVM_ON_UNIX)
+TEST(Host, RunShellCommand) {
+  HostInfoBase::Initialize();
+  FileSystem::Initialize();
+  std::string shell = std::string("SHELL=") + getenv("SHELL");
+  putenv(const_cast("SHELL=/bin/LLDB_TEST_this-file-does-not-exist"));
+  int status, signo;
+  std::string out;
+  auto timeout = std::chrono::seconds(60);
+  Status error = Host::RunShellCommand("/usr/bin/true", FileSpec(), &status,
+   &signo, &out, timeout);
+  ASSERT_TRUE(error.Fail());
+  putenv(const_cast(shell.c_str()));
+
+  error = Host::RunShellCommand("/usr/bin/false", FileSpec(), &status, &signo,
+&out, timeout);
+  ASSERT_FALSE(error.Fail());
+  HostInfoBase::Terminate();
+  FileSystem::Terminate();
+}
+#endif
Index: lldb/unittests/Host/CMakeLists.txt
===
--- lldb/unittests/Host/CMakeLists.txt
+++ lldb/unittests/Host/CMakeLists.txt
@@ -32,6 +32,7 @@
   ${FILES}
   LINK_LIBS
 lldbHost
+lldbCore
 lldbUtilityHelpers
 lldbHostHelpers
 LLVMTestingSupport
Index: lldb/source/Host/macosx/objcxx/HostInfoMacOSX.mm
===
--- lldb/source/Host/macosx/objcxx/HostInfoMacOSX.mm
+++ lldb/source/Host/macosx/objcxx/HostInfoMacOSX.mm
@@ -10,6 +10,7 @@
 #include "lldb/Host/Host.h"
 #include "lldb/Host/HostInfo.h"
 #include "lldb/Host/macosx/HostInfoMacOSX.h"
+#include "lldb/Core/Debugger.h"
 #include "lldb/Utility/Args.h"
 #include "lldb/Utility/LLDBLog.h"
 #include "lldb/Utility/Log.h"
@@ -365,12 +366,14 @@
   return g_developer_directory;
 }
 
-static std::string GetXcodeSDK(XcodeSDK sdk) {
+llvm::Expected GetXcodeSDK(XcodeSDK sdk) {
   XcodeSDK::Info info = sdk.Parse();
   std::string sdk_name = XcodeSDK::GetCanonicalName(info);
+  Log *log = GetLog(LLDBLog::Host);
 
   auto xcrun = [](const std::string &sdk,
-  llvm::StringRef developer_dir = "") -> std::string {
+  llvm::StringRef developer_dir =
+  "") -> llvm::Expected {
 Args args;
 if (!developer_dir.empty()) {
   args.AppendArgument("/usr/bin/env");
@@ -391,13 +394,25 @@
 int status = 0;
 int signo = 0;
 std::string output_str;
-lldb_private::Status error =
-Host::RunShellCommand(args, FileSpec(), &status, &signo, &output_str,
-  std::chrono::seconds(15));
-
-// Check that xcrun return something useful.
-if (status != 0 || output_str.empty())
-  return {};
+// The first time after Xcode was updated or freshly installed,
+// xcrun can take surprisingly long to build up its database.
+auto timeout = std::chrono::seconds(60);
+lldb_private::Status error = Host::RunShellCommand(
+args, FileSpec(), &status, &signo, &output_str, timeout);
+
+// Check that xcrun returned something useful.
+if (error.Fail()) {
+  LLDB_LOG(log, "xcrun failed to execute: %s", error.AsCString());
+  return error.ToError();
+}
+if (status != 0) {
+  LLDB_LOG(log, "xcrun returned exit code %d", status);
+  return "";
+}
+if (output_str.empty()) {
+  LLDB_LOG(log, "xcrun returned no results");
+  return "";
+}
 
 // Convert to a StringRef so we can manipulate the string without modifying
 // the underlying data.
@@ -414,7 +429,8 @@
 return output.str();
   };
 
-  auto find_sdk = [&xcrun](const std::string &sdk_name) -> std::string {
+  auto find_sdk =
+  [&xcrun](const std::string &sdk_name) -> llvm::Expected {
 // Invoke xcrun with the developer dir specified in the environment.
 std::string developer_dir = GetEnvDeveloperDir();
 if (!developer_dir.empty()) {
@@ -430,8 +446,10 @@
 llvm::StringRef shlib_developer_dir =
 llvm::sys::pat

[Lldb-commits] [lldb] cb0ffa5 - [lldb] Fix simple template names and template params with scope qualifiers

2022-11-15 Thread Arthur Eubanks via lldb-commits

Author: Arthur Eubanks
Date: 2022-11-15T16:52:34-08:00
New Revision: cb0ffa529a0f7f907fd89587fc2ab4f6ffd57cf5

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

LOG: [lldb] Fix simple template names and template params with scope qualifiers

Followup to D134378.

With PrintingPolicy::SuppressScope, we'd also not print the scope in template 
params. The intention was only to skip the scope for the class because we 
expect template params to be fully qualified when comparing them for simple 
template names.

Instead, use `NamedDecl::getNameForDiagnostic` if we're dealing with a tag, 
which is what we actually use when emitting debug info in clang. That already 
has an option to suppress the scope on the base name.

Reviewed By: dblaikie

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

Added: 


Modified: 
lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
lldb/test/API/lang/cpp/unique-types2/TestUniqueTypes2.py
lldb/test/API/lang/cpp/unique-types2/main.cpp

Removed: 




diff  --git a/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp 
b/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
index cd142b73ab824..a868abb46a73a 100644
--- a/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
+++ b/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
@@ -2131,11 +2131,12 @@ PrintingPolicy TypeSystemClang::GetTypePrintingPolicy() 
{
   return printing_policy;
 }
 
-std::string TypeSystemClang::GetTypeNameForDecl(const NamedDecl *named_decl) {
+std::string TypeSystemClang::GetTypeNameForDecl(const NamedDecl *named_decl,
+bool qualified) {
   clang::PrintingPolicy printing_policy = GetTypePrintingPolicy();
   std::string result;
   llvm::raw_string_ostream os(result);
-  named_decl->printQualifiedName(os, printing_policy);
+  named_decl->getNameForDiagnostic(os, printing_policy, qualified);
   return result;
 }
 
@@ -3768,7 +3769,7 @@ bool 
TypeSystemClang::GetCompleteType(lldb::opaque_compiler_type_t type) {
 }
 
 ConstString TypeSystemClang::GetTypeName(lldb::opaque_compiler_type_t type,
- bool BaseOnly) {
+ bool base_only) {
   if (!type)
 return ConstString();
 
@@ -3790,9 +3791,13 @@ ConstString 
TypeSystemClang::GetTypeName(lldb::opaque_compiler_type_t type,
 return ConstString(GetTypeNameForDecl(typedef_decl));
   }
 
-  clang::PrintingPolicy printing_policy(GetTypePrintingPolicy());
-  printing_policy.SuppressScope = BaseOnly;
-  return ConstString(qual_type.getAsString(printing_policy));
+  // For consistency, this follows the same code path that clang uses to emit
+  // debug info. This also handles when we don't want any scopes preceding the
+  // name.
+  if (auto *named_decl = qual_type->getAsTagDecl())
+return ConstString(GetTypeNameForDecl(named_decl, !base_only));
+
+  return ConstString(qual_type.getAsString(GetTypePrintingPolicy()));
 }
 
 ConstString

diff  --git a/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h 
b/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
index a56c5f27850c7..1c0e120aadbfe 100644
--- a/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
+++ b/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
@@ -644,7 +644,7 @@ class TypeSystemClang : public TypeSystem {
   // Accessors
 
   ConstString GetTypeName(lldb::opaque_compiler_type_t type,
-  bool BaseOnly) override;
+  bool base_only) override;
 
   ConstString GetDisplayTypeName(lldb::opaque_compiler_type_t type) override;
 
@@ -1051,7 +1051,8 @@ class TypeSystemClang : public TypeSystem {
   clang::PrintingPolicy GetTypePrintingPolicy();
   /// Returns the internal type name for the given NamedDecl using the
   /// type printing policy.
-  std::string GetTypeNameForDecl(const clang::NamedDecl *named_decl);
+  std::string GetTypeNameForDecl(const clang::NamedDecl *named_decl,
+ bool qualified = true);
 
   const clang::ClassTemplateSpecializationDecl *
   GetAsTemplateSpecialization(lldb::opaque_compiler_type_t type);

diff  --git a/lldb/test/API/lang/cpp/unique-types2/TestUniqueTypes2.py 
b/lldb/test/API/lang/cpp/unique-types2/TestUniqueTypes2.py
index 0fe078b2d1e3a..b0105a3994f89 100644
--- a/lldb/test/API/lang/cpp/unique-types2/TestUniqueTypes2.py
+++ b/lldb/test/API/lang/cpp/unique-types2/TestUniqueTypes2.py
@@ -36,6 +36,7 @@ def do_test(self, debug_flags):
 self.expect("image lookup -A -t 'Foo::Nested'", 
DATA_TYPES_DISPLAYED_CORRECTLY, error=True)
 self.expect("image lookup -A -t 'Nested'", 
DATA_TYPES_DISPLAYED_CORRECTLY, substrs=["1 match fo

[Lldb-commits] [PATCH] D137583: [lldb] Fix simple template names and template params with scope qualifiers

2022-11-15 Thread Arthur Eubanks via Phabricator via lldb-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGcb0ffa529a0f: [lldb] Fix simple template names and template 
params with scope qualifiers (authored by aeubanks).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137583

Files:
  lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
  lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
  lldb/test/API/lang/cpp/unique-types2/TestUniqueTypes2.py
  lldb/test/API/lang/cpp/unique-types2/main.cpp

Index: lldb/test/API/lang/cpp/unique-types2/main.cpp
===
--- lldb/test/API/lang/cpp/unique-types2/main.cpp
+++ lldb/test/API/lang/cpp/unique-types2/main.cpp
@@ -1,3 +1,7 @@
+namespace ns {
+struct Bar {};
+} // namespace ns
+
 template  struct Foo {
   T t;
   template  class Nested {
@@ -23,5 +27,6 @@
   FooPack p7;
 
   Foo::Nested n1;
+  Foo::Nested n2;
   // Set breakpoint here
 }
Index: lldb/test/API/lang/cpp/unique-types2/TestUniqueTypes2.py
===
--- lldb/test/API/lang/cpp/unique-types2/TestUniqueTypes2.py
+++ lldb/test/API/lang/cpp/unique-types2/TestUniqueTypes2.py
@@ -36,6 +36,7 @@
 self.expect("image lookup -A -t 'Foo::Nested'", DATA_TYPES_DISPLAYED_CORRECTLY, error=True)
 self.expect("image lookup -A -t 'Nested'", DATA_TYPES_DISPLAYED_CORRECTLY, substrs=["1 match found"])
 self.expect("image lookup -A -t '::Nested'", DATA_TYPES_DISPLAYED_CORRECTLY, error=True)
+self.expect("image lookup -A -t 'Foo::Nested'", DATA_TYPES_DISPLAYED_CORRECTLY, substrs=["1 match found"])
 
 self.expect_expr("t1", result_type="Foo")
 self.expect_expr("t1", result_type="Foo")
@@ -49,6 +50,7 @@
 self.expect_expr("p6", result_type="FooPack")
 self.expect_expr("p7", result_type="FooPack")
 self.expect_expr("n1", result_type="Foo::Nested")
+self.expect_expr("n2", result_type="Foo::Nested")
 
 @skipIf(compiler=no_match("clang"))
 @skipIf(compiler_version=["<", "15.0"])
Index: lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
===
--- lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
+++ lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
@@ -644,7 +644,7 @@
   // Accessors
 
   ConstString GetTypeName(lldb::opaque_compiler_type_t type,
-  bool BaseOnly) override;
+  bool base_only) override;
 
   ConstString GetDisplayTypeName(lldb::opaque_compiler_type_t type) override;
 
@@ -1051,7 +1051,8 @@
   clang::PrintingPolicy GetTypePrintingPolicy();
   /// Returns the internal type name for the given NamedDecl using the
   /// type printing policy.
-  std::string GetTypeNameForDecl(const clang::NamedDecl *named_decl);
+  std::string GetTypeNameForDecl(const clang::NamedDecl *named_decl,
+ bool qualified = true);
 
   const clang::ClassTemplateSpecializationDecl *
   GetAsTemplateSpecialization(lldb::opaque_compiler_type_t type);
Index: lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
===
--- lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
+++ lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
@@ -2131,11 +2131,12 @@
   return printing_policy;
 }
 
-std::string TypeSystemClang::GetTypeNameForDecl(const NamedDecl *named_decl) {
+std::string TypeSystemClang::GetTypeNameForDecl(const NamedDecl *named_decl,
+bool qualified) {
   clang::PrintingPolicy printing_policy = GetTypePrintingPolicy();
   std::string result;
   llvm::raw_string_ostream os(result);
-  named_decl->printQualifiedName(os, printing_policy);
+  named_decl->getNameForDiagnostic(os, printing_policy, qualified);
   return result;
 }
 
@@ -3768,7 +3769,7 @@
 }
 
 ConstString TypeSystemClang::GetTypeName(lldb::opaque_compiler_type_t type,
- bool BaseOnly) {
+ bool base_only) {
   if (!type)
 return ConstString();
 
@@ -3790,9 +3791,13 @@
 return ConstString(GetTypeNameForDecl(typedef_decl));
   }
 
-  clang::PrintingPolicy printing_policy(GetTypePrintingPolicy());
-  printing_policy.SuppressScope = BaseOnly;
-  return ConstString(qual_type.getAsString(printing_policy));
+  // For consistency, this follows the same code path that clang uses to emit
+  // debug info. This also handles when we don't want any scopes preceding the
+  // name.
+  if (auto *named_decl = qual_type->getAsTagDecl())
+return ConstString(GetTypeNameForDecl(named_decl, !base_only));
+
+  return ConstString(qual_type.getAsString(GetTypePrintingPolicy()));
 }
 
 ConstString
___
lldb-commits mailing list
lld

[Lldb-commits] [PATCH] D136650: Make CompilerType safe [Was: Add a check for TypeSystem use-after-free problems]

2022-11-15 Thread Adrian Prantl via Phabricator via lldb-commits
aprantl added inline comments.



Comment at: lldb/include/lldb/Symbol/CompilerType.h:58
+template  TypeSystemType *dyn_cast_or_null() {
+  return llvm::dyn_cast_or_null(m_typesystem_sp.get());
+}

labath wrote:
> Maybe do something like this instead:
> ```
> template  std::shared_ptr 
> dyn_cast_or_null() {
>   if (llvm::isa(m_typesystem_sp.get()))
> return std::shared_ptr(m_typesystem_sp, 
> llvm::cast(m_typesystem_sp.get()));
>   return nullptr;
> }
> ```
> 
> That said, `llvm::dyn_cast` supports custom casts for smart pointers (it 
> already has them for std::unique_ptr), so it should be possible to completely 
> avoid this wrapper class by implementing this logic inside llvm.
> Although, then we'd have to answer awkward questions like "why are you using 
> a shared_ptr in the first place".
I think that's a good idea. Based on the assumption that we are going to rework 
the ownership model in LLDB to move away from shared pointers towards contexts 
at some point in the future, I'm not going to extend casting support in Support 
now.


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

https://reviews.llvm.org/D136650

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


[Lldb-commits] [PATCH] D138060: Improve error logging when xcrun fails to execute successfully

2022-11-15 Thread Jonas Devlieghere via Phabricator via lldb-commits
JDevlieghere requested changes to this revision.
JDevlieghere added inline comments.
This revision now requires changes to proceed.



Comment at: lldb/source/Host/macosx/objcxx/HostInfoMacOSX.mm:410
+  LLDB_LOG(log, "xcrun returned exit code %d", status);
+  return "";
+}

Why not return an Error?



Comment at: lldb/source/Host/macosx/objcxx/HostInfoMacOSX.mm:414
+  LLDB_LOG(log, "xcrun returned no results");
+  return "";
+}

Same question.



Comment at: lldb/source/Host/macosx/objcxx/HostInfoMacOSX.mm:495
 LLDB_LOGF(log, "Couldn't find any matching SDK on host");
-return {};
+return "";
   }

Here too, why not return a `StringError` with the log message from the live 
above?


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

https://reviews.llvm.org/D138060

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


[Lldb-commits] [lldb] 7fe3586 - Send statistics in initialized event

2022-11-15 Thread George Hu via lldb-commits

Author: George Hu
Date: 2022-11-15T19:09:05-08:00
New Revision: 7fe3586cda5b683766ec6b6d5ca2d98c2baaf162

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

LOG: Send statistics in initialized event

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

Added: 
lldb/test/API/tools/lldb-vscode/eventStatistic/Makefile
lldb/test/API/tools/lldb-vscode/eventStatistic/TestVSCode_eventStatistic.py
lldb/test/API/tools/lldb-vscode/eventStatistic/foo.cpp
lldb/test/API/tools/lldb-vscode/eventStatistic/foo.h
lldb/test/API/tools/lldb-vscode/eventStatistic/main.cpp

Modified: 
lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py
lldb/tools/lldb-vscode/JSONUtils.cpp
lldb/tools/lldb-vscode/JSONUtils.h
lldb/tools/lldb-vscode/lldb-vscode.cpp

Removed: 
lldb/test/API/tools/lldb-vscode/terminated-event/Makefile

lldb/test/API/tools/lldb-vscode/terminated-event/TestVSCode_terminatedEvent.py
lldb/test/API/tools/lldb-vscode/terminated-event/foo.cpp
lldb/test/API/tools/lldb-vscode/terminated-event/foo.h
lldb/test/API/tools/lldb-vscode/terminated-event/main.cpp



diff  --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py 
b/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py
index c2de4ad5c7d9a..49f268ae28793 100644
--- a/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py
+++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py
@@ -134,6 +134,7 @@ def __init__(self, recv, send, init_commands, 
log_file=None):
 self.configuration_done_sent = False
 self.frame_scopes = {}
 self.init_commands = init_commands
+self.initialized_event = None
 
 @classmethod
 def encode_content(cls, s):
@@ -231,6 +232,8 @@ def handle_recv_packet(self, packet):
 self._process_stopped()
 tid = body['threadId']
 self.thread_stop_reasons[tid] = body
+elif event == 'initialized':
+self.initialized_event = packet
 elif event == 'breakpoint':
 # Breakpoint events come in when a breakpoint has locations
 # added or removed. Keep track of them so we can look for them

diff  --git a/lldb/test/API/tools/lldb-vscode/terminated-event/Makefile 
b/lldb/test/API/tools/lldb-vscode/eventStatistic/Makefile
similarity index 100%
rename from lldb/test/API/tools/lldb-vscode/terminated-event/Makefile
rename to lldb/test/API/tools/lldb-vscode/eventStatistic/Makefile

diff  --git 
a/lldb/test/API/tools/lldb-vscode/terminated-event/TestVSCode_terminatedEvent.py
 b/lldb/test/API/tools/lldb-vscode/eventStatistic/TestVSCode_eventStatistic.py
similarity index 64%
rename from 
lldb/test/API/tools/lldb-vscode/terminated-event/TestVSCode_terminatedEvent.py
rename to 
lldb/test/API/tools/lldb-vscode/eventStatistic/TestVSCode_eventStatistic.py
index ae364a5fe1f0d..b70e21ef7d9da 100644
--- 
a/lldb/test/API/tools/lldb-vscode/terminated-event/TestVSCode_terminatedEvent.py
+++ 
b/lldb/test/API/tools/lldb-vscode/eventStatistic/TestVSCode_eventStatistic.py
@@ -10,7 +10,27 @@
 import re
 import json
 
-class TestVSCode_terminatedEvent(lldbvscode_testcase.VSCodeTestCaseBase):
+class TestVSCode_eventStatistic(lldbvscode_testcase.VSCodeTestCaseBase):
+
+def check_statistic(self, statistics):
+self.assertTrue(statistics['totalDebugInfoByteSize'] > 0)
+self.assertTrue(statistics['totalDebugInfoEnabled'] > 0)
+self.assertTrue(statistics['totalModuleCountHasDebugInfo'] > 0)
+
+self.assertIsNotNone(statistics['memory'])
+self.assertNotIn('modules', statistics.keys())
+
+def check_target(self, statistics):
+# lldb-vscode debugs one target at a time
+target = json.loads(statistics['targets'])[0]
+self.assertTrue(target['totalBreakpointResolveTime'] > 0)
+
+breakpoints = target['breakpoints']
+self.assertIn('foo',
+  
breakpoints[0]['details']['Breakpoint']['BKPTResolver']['Options']['SymbolNames'],
+  'foo is a symbol breakpoint')
+
self.assertTrue(breakpoints[1]['details']['Breakpoint']['BKPTResolver']['Options']['FileName'].endswith('main.cpp'),
+'target has source line breakpoint in main.cpp')
 
 @skipIfWindows
 @skipIfRemote
@@ -45,20 +65,33 @@ def test_terminated_event(self):
 self.continue_to_exit()
 
 statistics = self.vscode.wait_for_terminated()['statistics']
-self.assertTrue(statistics['totalDebugInfoByteSize'] > 0)
-self.assertTrue(statistics['totalDebugInfoEnabled'] > 0)
-self.assertTrue(statistics['totalModuleCountHasDebugInfo'] > 0)
+self.check_statistic(statistics)
+self.ch

[Lldb-commits] [PATCH] D138077: Send statistics in initialized event

2022-11-15 Thread Yubo Hu via Phabricator via lldb-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG7fe3586cda5b: Send statistics in initialized event (authored 
by GeorgeHuyubo).

Changed prior to commit:
  https://reviews.llvm.org/D138077?vs=475624&id=475662#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138077

Files:
  lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py
  lldb/test/API/tools/lldb-vscode/eventStatistic/Makefile
  lldb/test/API/tools/lldb-vscode/eventStatistic/TestVSCode_eventStatistic.py
  lldb/test/API/tools/lldb-vscode/eventStatistic/foo.cpp
  lldb/test/API/tools/lldb-vscode/eventStatistic/foo.h
  lldb/test/API/tools/lldb-vscode/eventStatistic/main.cpp
  lldb/test/API/tools/lldb-vscode/terminated-event/Makefile
  lldb/test/API/tools/lldb-vscode/terminated-event/TestVSCode_terminatedEvent.py
  lldb/test/API/tools/lldb-vscode/terminated-event/foo.cpp
  lldb/test/API/tools/lldb-vscode/terminated-event/foo.h
  lldb/test/API/tools/lldb-vscode/terminated-event/main.cpp
  lldb/tools/lldb-vscode/JSONUtils.cpp
  lldb/tools/lldb-vscode/JSONUtils.h
  lldb/tools/lldb-vscode/lldb-vscode.cpp

Index: lldb/tools/lldb-vscode/lldb-vscode.cpp
===
--- lldb/tools/lldb-vscode/lldb-vscode.cpp
+++ lldb/tools/lldb-vscode/lldb-vscode.cpp
@@ -687,7 +687,7 @@
   g_vsc.SendJSON(llvm::json::Value(std::move(response)));
   if (error.Success()) {
 SendProcessEvent(Attach);
-g_vsc.SendJSON(CreateEventObject("initialized"));
+g_vsc.SendJSON(CreateInitializedEventObject());
   }
 }
 
@@ -1754,7 +1754,7 @@
 SendProcessEvent(Attach); // this happens when doing runInTerminal
   else
 SendProcessEvent(Launch);
-  g_vsc.SendJSON(llvm::json::Value(CreateEventObject("initialized")));
+  g_vsc.SendJSON(CreateInitializedEventObject());
 }
 
 // "NextRequest": {
Index: lldb/tools/lldb-vscode/JSONUtils.h
===
--- lldb/tools/lldb-vscode/JSONUtils.h
+++ lldb/tools/lldb-vscode/JSONUtils.h
@@ -491,6 +491,12 @@
 /// A body JSON object with debug info and breakpoint info
 llvm::json::Object CreateTerminatedEventObject();
 
+/// Create a "Initialized" JSON object that contains statistics
+///
+/// \return
+/// A body JSON object with debug info
+llvm::json::Object CreateInitializedEventObject();
+
 /// Convert a given JSON object to a string.
 std::string JSONToString(const llvm::json::Value &json);
 
Index: lldb/tools/lldb-vscode/JSONUtils.cpp
===
--- lldb/tools/lldb-vscode/JSONUtils.cpp
+++ lldb/tools/lldb-vscode/JSONUtils.cpp
@@ -1209,6 +1209,12 @@
   return event;
 }
 
+llvm::json::Object CreateInitializedEventObject() {
+  llvm::json::Object event(CreateEventObject("initialized"));
+  addStatistic(event);
+  return event;
+}
+
 std::string JSONToString(const llvm::json::Value &json) {
   std::string data;
   llvm::raw_string_ostream os(data);
Index: lldb/test/API/tools/lldb-vscode/eventStatistic/TestVSCode_eventStatistic.py
===
--- lldb/test/API/tools/lldb-vscode/eventStatistic/TestVSCode_eventStatistic.py
+++ lldb/test/API/tools/lldb-vscode/eventStatistic/TestVSCode_eventStatistic.py
@@ -10,7 +10,27 @@
 import re
 import json
 
-class TestVSCode_terminatedEvent(lldbvscode_testcase.VSCodeTestCaseBase):
+class TestVSCode_eventStatistic(lldbvscode_testcase.VSCodeTestCaseBase):
+
+def check_statistic(self, statistics):
+self.assertTrue(statistics['totalDebugInfoByteSize'] > 0)
+self.assertTrue(statistics['totalDebugInfoEnabled'] > 0)
+self.assertTrue(statistics['totalModuleCountHasDebugInfo'] > 0)
+
+self.assertIsNotNone(statistics['memory'])
+self.assertNotIn('modules', statistics.keys())
+
+def check_target(self, statistics):
+# lldb-vscode debugs one target at a time
+target = json.loads(statistics['targets'])[0]
+self.assertTrue(target['totalBreakpointResolveTime'] > 0)
+
+breakpoints = target['breakpoints']
+self.assertIn('foo',
+  breakpoints[0]['details']['Breakpoint']['BKPTResolver']['Options']['SymbolNames'],
+  'foo is a symbol breakpoint')
+self.assertTrue(breakpoints[1]['details']['Breakpoint']['BKPTResolver']['Options']['FileName'].endswith('main.cpp'),
+'target has source line breakpoint in main.cpp')
 
 @skipIfWindows
 @skipIfRemote
@@ -45,20 +65,33 @@
 self.continue_to_exit()
 
 statistics = self.vscode.wait_for_terminated()['statistics']
-self.assertTrue(statistics['totalDebugInfoByteSize'] > 0)
-self.assertTrue(statistics['totalDebugInfoEnabled'] > 0)
-self.assertTrue(statistics['totalModuleCountHasDebugInfo'] > 0)
+self.check_statist

[Lldb-commits] [PATCH] D137217: [LTO][COFF] Use bitcode file names in lto native object file names.

2022-11-15 Thread Fangrui Song via Phabricator via lldb-commits
MaskRay added a comment.

In D137217#3926601 , @tejohnson wrote:

> @MaskRay wondering if this is a good change to make for ELF as well, wdyt?

Yes, I think this is a good idea and improves debuggability. The change is 
non-trivial so so this patch focusing on the COFF part is good.




Comment at: lld/COFF/LTO.cpp:238
+  sys::path::append(path, directory,
+outputFileBaseName + ".lto." + baseName);
+  sys::path::remove_dots(path, true);

What if two input bitcode files have the same basename, e.g. `dir1/a.obj` and 
`dir2/a.obj`?



Comment at: lld/COFF/LTO.cpp:229
+StringRef ltoObjName;
+if (bitcodeFilePath == "ld-temp.o") {
+  ltoObjName =

tejohnson wrote:
> zequanwu wrote:
> > tejohnson wrote:
> > > This case should always be i==0 I think?
> > IIUC, "ld-temp.o" is the name of combined module. Do you mean there will be 
> > only 1 combined module and it will always be the first task?
> Yes. So you don't need the handling for i==0 in the name in this case (you 
> could probably assert that i==0).
This looks like a hack. `assert(i == 0)` will fail with 
`-opt:lldltopartitions=2`: `buf[1]` will be called `ld-temp.o` as well.

In addition, if an input bitcode file is called `ld-temp.o` (for some reason 
they don't use `.obj`, just `ld-temp.o`), `assert(i == 0)` will fail as well.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137217

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


[Lldb-commits] [PATCH] D137217: [LTO][COFF] Use bitcode file names in lto native object file names.

2022-11-15 Thread Fangrui Song via Phabricator via lldb-commits
MaskRay added inline comments.



Comment at: lld/COFF/LTO.cpp:229
+StringRef ltoObjName;
+if (bitcodeFilePath == "ld-temp.o") {
+  ltoObjName =

MaskRay wrote:
> tejohnson wrote:
> > zequanwu wrote:
> > > tejohnson wrote:
> > > > This case should always be i==0 I think?
> > > IIUC, "ld-temp.o" is the name of combined module. Do you mean there will 
> > > be only 1 combined module and it will always be the first task?
> > Yes. So you don't need the handling for i==0 in the name in this case (you 
> > could probably assert that i==0).
> This looks like a hack. `assert(i == 0)` will fail with 
> `-opt:lldltopartitions=2`: `buf[1]` will be called `ld-temp.o` as well.
> 
> In addition, if an input bitcode file is called `ld-temp.o` (for some reason 
> they don't use `.obj`, just `ld-temp.o`), `assert(i == 0)` will fail as well.
I guess `if (i < config->ltoPartitions)` may fix the issue.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137217

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


[Lldb-commits] [PATCH] D138077: Send statistics in initialized event

2022-11-15 Thread Muhammad Omair Javaid via Phabricator via lldb-commits
omjavaid added a comment.

This test fails on Arm/AArch64 Linux. I have marked it as an XFAIL.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138077

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


[Lldb-commits] [lldb] d599ac4 - [LLDB] Xfail TestVSCode_eventStatistic.py on Arm/AArch64 Linux

2022-11-15 Thread Muhammad Omair Javaid via lldb-commits

Author: Muhammad Omair Javaid
Date: 2022-11-16T10:45:24+04:00
New Revision: d599ac41aabddeb2442db7b31faacf143d63abe4

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

LOG: [LLDB] Xfail TestVSCode_eventStatistic.py on Arm/AArch64 Linux

This patch marks TestVSCode_eventStatistic.py as xfail on Arm/AArch64
Linux platform. test_initialized_event testcase is failing. See buildbot
logs below:

https://lab.llvm.org/buildbot/#/builders/17/builds/30199
https://lab.llvm.org/buildbot/#/builders/96/builds/31528

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

Added: 


Modified: 
lldb/test/API/tools/lldb-vscode/eventStatistic/TestVSCode_eventStatistic.py

Removed: 




diff  --git 
a/lldb/test/API/tools/lldb-vscode/eventStatistic/TestVSCode_eventStatistic.py 
b/lldb/test/API/tools/lldb-vscode/eventStatistic/TestVSCode_eventStatistic.py
index b70e21ef7d9d..2b7630795dca 100644
--- 
a/lldb/test/API/tools/lldb-vscode/eventStatistic/TestVSCode_eventStatistic.py
+++ 
b/lldb/test/API/tools/lldb-vscode/eventStatistic/TestVSCode_eventStatistic.py
@@ -70,6 +70,7 @@ def test_terminated_event(self):
 
 @skipIfWindows
 @skipIfRemote
+@expectedFailureAll(oslist=['linux'], archs=['arm', 'aarch64'])
 def test_initialized_event(self):
 '''
 Initialized Event



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


[Lldb-commits] [PATCH] D136809: [CMake] Ensure `CLANG_RESOURCE_DIR` is respected

2022-11-15 Thread LJC via Phabricator via lldb-commits
paperchalice updated this revision to Diff 475696.

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

https://reviews.llvm.org/D136809

Files:
  clang/lib/Headers/CMakeLists.txt
  clang/lib/Tooling/CMakeLists.txt
  clang/runtime/CMakeLists.txt
  cmake/Modules/GetClangResourceDir.cmake
  compiler-rt/cmake/base-config-ix.cmake
  lldb/source/Plugins/ExpressionParser/Clang/ClangHost.cpp
  lldb/unittests/Expression/ClangParserTest.cpp
  llvm/cmake/modules/LLVMExternalProjectUtils.cmake
  openmp/CMakeLists.txt

Index: openmp/CMakeLists.txt
===
--- openmp/CMakeLists.txt
+++ openmp/CMakeLists.txt
@@ -79,8 +79,8 @@
 if(${OPENMP_STANDALONE_BUILD})
   set(LIBOMP_HEADERS_INSTALL_PATH "${CMAKE_INSTALL_INCLUDEDIR}")
 else()
-  string(REGEX MATCH "[0-9]+\\.[0-9]+(\\.[0-9]+)?" CLANG_VERSION ${PACKAGE_VERSION})
-  set(LIBOMP_HEADERS_INSTALL_PATH "${OPENMP_INSTALL_LIBDIR}/clang/${CLANG_VERSION}/include")
+  include(GetClangResourceDir)
+  get_clang_resource_dir(LIBOMP_HEADERS_INSTALL_PATH SUBDIR include)
 endif()
 
 # Build host runtime library, after LIBOMPTARGET variables are set since they are needed
Index: llvm/cmake/modules/LLVMExternalProjectUtils.cmake
===
--- llvm/cmake/modules/LLVMExternalProjectUtils.cmake
+++ llvm/cmake/modules/LLVMExternalProjectUtils.cmake
@@ -257,7 +257,11 @@
 if(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
   string(REGEX MATCH "^[0-9]+" CLANG_VERSION_MAJOR
  ${PACKAGE_VERSION})
-  set(resource_dir "${LLVM_LIBRARY_DIR}/clang/${CLANG_VERSION_MAJOR}")
+  if(DEFINED CLANG_RESOURCE_DIR AND NOT CLANG_RESOURCE_DIR STREQUAL "")
+set(resource_dir ${LLVM_TOOLS_BINARY_DIR}/${CLANG_RESOURCE_DIR})
+  else()
+set(resource_dir "${LLVM_LIBRARY_DIR}/clang/${CLANG_VERSION_MAJOR}")
+  endif()
   set(flag_types ASM C CXX MODULE_LINKER SHARED_LINKER EXE_LINKER)
   foreach(type ${flag_types})
 set(${type}_flag -DCMAKE_${type}_FLAGS=-resource-dir=${resource_dir})
Index: lldb/unittests/Expression/ClangParserTest.cpp
===
--- lldb/unittests/Expression/ClangParserTest.cpp
+++ lldb/unittests/Expression/ClangParserTest.cpp
@@ -7,6 +7,7 @@
 //===--===//
 
 #include "clang/Basic/Version.h"
+#include "clang/Config/config.h"
 
 #include "Plugins/ExpressionParser/Clang/ClangHost.h"
 #include "TestingSupport/SubsystemRAII.h"
@@ -37,12 +38,16 @@
 TEST_F(ClangHostTest, ComputeClangResourceDirectory) {
 #if !defined(_WIN32)
   std::string path_to_liblldb = "/foo/bar/lib/";
-  std::string path_to_clang_dir =
-  "/foo/bar/" LLDB_INSTALL_LIBDIR_BASENAME "/clang/" CLANG_VERSION_MAJOR_STRING;
+  std::string path_to_clang_dir = CLANG_RESOURCE_DIR[0]
+  ? "/foo/bar/bin/" CLANG_RESOURCE_DIR
+  : "/foo/bar/" LLDB_INSTALL_LIBDIR_BASENAME
+"/clang/" CLANG_VERSION_MAJOR_STRING;
 #else
   std::string path_to_liblldb = "C:\\foo\\bar\\lib";
   std::string path_to_clang_dir =
-  "C:\\foo\\bar\\lib\\clang\\" CLANG_VERSION_MAJOR_STRING;
+  CLANG_RESOURCE_DIR[0]
+  ? "C:\\foo\\bar\\bin\\" CLANG_RESOURCE_DIR
+  : "C:\\foo\\bar\\lib\\clang\\" CLANG_VERSION_MAJOR_STRING;
 #endif
   EXPECT_EQ(ComputeClangResourceDir(path_to_liblldb), path_to_clang_dir);
 
Index: lldb/source/Plugins/ExpressionParser/Clang/ClangHost.cpp
===
--- lldb/source/Plugins/ExpressionParser/Clang/ClangHost.cpp
+++ lldb/source/Plugins/ExpressionParser/Clang/ClangHost.cpp
@@ -54,8 +54,11 @@
 
   static const llvm::StringRef kResourceDirSuffixes[] = {
   // LLVM.org's build of LLDB uses the clang resource directory placed
-  // in $install_dir/lib{,64}/clang/$clang_version.
-  CLANG_INSTALL_LIBDIR_BASENAME "/clang/" CLANG_VERSION_MAJOR_STRING,
+  // in $install_dir/lib{,64}/clang/$clang_version or
+  // $install_dir/bin/$CLANG_RESOURCE_DIR
+  CLANG_RESOURCE_DIR[0] ? "bin/" CLANG_RESOURCE_DIR
+: CLANG_INSTALL_LIBDIR_BASENAME
+  "/clang/" CLANG_VERSION_MAJOR_STRING,
   // swift-lldb uses the clang resource directory copied from swift, which
   // by default is placed in $install_dir/lib{,64}/lldb/clang. LLDB places
   // it there, so we use LLDB_INSTALL_LIBDIR_BASENAME.
Index: compiler-rt/cmake/base-config-ix.cmake
===
--- compiler-rt/cmake/base-config-ix.cmake
+++ compiler-rt/cmake/base-config-ix.cmake
@@ -7,6 +7,7 @@
 include(CheckIncludeFile)
 include(CheckCXXSourceCompiles)
 include(GNUInstallDirs)
+include(GetClangResourceDir)
 include(ExtendPath)
 
 check_include_file(unwind.h HAVE_UNWIND_H)
@@ -43,9 +44,9 @@