[Lldb-commits] [PATCH] D120972: [lldb] Show progress events in the command line driver

2022-03-04 Thread Jonas Devlieghere via Phabricator via lldb-commits
JDevlieghere updated this revision to Diff 413058.
JDevlieghere added a comment.

- Reduce flickering by not printing the last status message when the the 
progress is complete
- Add `...` as suggested by Adrian offline
- Make ANSI (vt100) escape codes a requirement in order to show progress to 
simplify the code


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

https://reviews.llvm.org/D120972

Files:
  lldb/include/lldb/API/SBCommandInterpreterRunOptions.h
  lldb/include/lldb/Core/Debugger.h
  lldb/include/lldb/Interpreter/CommandInterpreter.h
  lldb/source/API/SBCommandInterpreterRunOptions.cpp
  lldb/source/Core/CoreProperties.td
  lldb/source/Core/Debugger.cpp
  lldb/source/Interpreter/CommandInterpreter.cpp
  lldb/source/Symbol/LocateSymbolFile.cpp
  lldb/tools/driver/Driver.cpp

Index: lldb/tools/driver/Driver.cpp
===
--- lldb/tools/driver/Driver.cpp
+++ lldb/tools/driver/Driver.cpp
@@ -565,6 +565,7 @@
 m_debugger.SetAsync(false);
 
 SBCommandInterpreterRunOptions options;
+options.SetShowProgress(true);
 options.SetAutoHandleEvents(true);
 options.SetSpawnThread(false);
 options.SetStopOnError(true);
Index: lldb/source/Symbol/LocateSymbolFile.cpp
===
--- lldb/source/Symbol/LocateSymbolFile.cpp
+++ lldb/source/Symbol/LocateSymbolFile.cpp
@@ -10,6 +10,7 @@
 
 #include "lldb/Core/ModuleList.h"
 #include "lldb/Core/ModuleSpec.h"
+#include "lldb/Core/Progress.h"
 #include "lldb/Host/FileSystem.h"
 #include "lldb/Symbol/ObjectFile.h"
 #include "lldb/Utility/ArchSpec.h"
@@ -262,6 +263,10 @@
   FileSystem::Instance().Exists(symbol_file_spec))
 return symbol_file_spec;
 
+  Progress progress(llvm::formatv(
+  "Locating external symbol file for {0}",
+  module_spec.GetFileSpec().GetFilename().AsCString("")));
+
   FileSpecList debug_file_search_paths = default_search_paths;
 
   // Add module directory.
Index: lldb/source/Interpreter/CommandInterpreter.cpp
===
--- lldb/source/Interpreter/CommandInterpreter.cpp
+++ lldb/source/Interpreter/CommandInterpreter.cpp
@@ -3283,6 +3283,9 @@
 
 CommandInterpreterRunResult CommandInterpreter::RunCommandInterpreter(
 CommandInterpreterRunOptions &options) {
+  if (options.GetShowProgress())
+m_debugger.StartProgressHandlerThread();
+
   // Always re-create the command interpreter when we run it in case any file
   // handles have changed.
   bool force_create = true;
Index: lldb/source/Core/Debugger.cpp
===
--- lldb/source/Core/Debugger.cpp
+++ lldb/source/Core/Debugger.cpp
@@ -378,6 +378,12 @@
   return ret;
 }
 
+bool Debugger::GetShowProgress() const {
+  const uint32_t idx = ePropertyShowProgress;
+  return m_collection_sp->GetPropertyAtIndexAsBoolean(
+  nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
+}
+
 bool Debugger::GetUseAutosuggestion() const {
   const uint32_t idx = ePropertyShowAutosuggestion;
   return m_collection_sp->GetPropertyAtIndexAsBoolean(
@@ -1719,6 +1725,75 @@
   return {};
 }
 
+lldb::thread_result_t Debugger::ProgressHandlerThread() {
+  // Only report progress if nobody else is listening for it.
+  if (GetBroadcaster().EventTypeHasListeners(Debugger::eBroadcastBitProgress))
+return {};
+
+  ListenerSP listener_sp = Listener::MakeListener("lldb.progress.listener");
+  listener_sp->StartListeningForEvents(&m_broadcaster,
+   Debugger::eBroadcastBitProgress);
+
+  // Only handle one kind of event at the same time. Ignore events that come in
+  // in while the current event hasn't completed
+  llvm::Optional CurrentEventID;
+  while (true) {
+lldb::EventSP event_sp;
+if (listener_sp->GetEvent(event_sp, llvm::None)) {
+  if (!event_sp)
+continue;
+
+  auto *data =
+  Debugger::ProgressEventData::GetEventDataFromEvent(event_sp.get());
+  if (!data)
+continue;
+
+  // Do some bookkeeping for the current event, regardless of whether we're
+  // going to show the progress.
+  uint64_t id = data->GetID();
+  if (CurrentEventID) {
+if (id != *CurrentEventID)
+  continue;
+if (data->GetCompleted())
+  CurrentEventID.reset();
+  } else {
+CurrentEventID = id;
+  }
+
+  // Decide whether we actually are going to show the progress. This
+  // decision can change between iterations so check it inside the loop.
+  File &output = GetOutputFile();
+  if (!output.GetIsTerminalWithColors() || !GetShowProgress())
+continue;
+
+  // If we're done, just clear the current line.
+  if (data->GetCompleted()) {
+output.Printf("\33[2K\r");
+continue;
+  }
+
+  // Print over previous line, if any.
+  output.Printf("\r");
+
+  

[Lldb-commits] [PATCH] D120969: [lldb/Plugins] Add ability to load modules to Scripted Processes

2022-03-04 Thread Jonas Devlieghere via Phabricator via lldb-commits
JDevlieghere added inline comments.



Comment at: lldb/source/Plugins/Process/scripted/ScriptedProcess.cpp:413-416
+if (!has_path && !has_uuid)
+  return error_with_message("Dictionary should have key 'path' or 'uuid'");
+if (!dict->HasKey("load_addr"))
+  return error_with_message("Dictionary is missing field 'load_addr'");

Nit: you're calling it a key in the first error message, but `field` in the 
second. Let's pick one and be consistent. 



Comment at: 
lldb/test/API/functionalities/scripted_process/stack_core_scripted_process.py:45
+
+lib_load_addr = 0x0001001e
+self.loaded_images.append({"path": self.lib_path,

What exactly is this value? Shouldn't we get the load address from the core 
file and report that? 


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

https://reviews.llvm.org/D120969

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


[Lldb-commits] [PATCH] D120972: [lldb] Show progress events in the command line driver

2022-03-04 Thread Pavel Labath via Phabricator via lldb-commits
labath added a comment.

I like the feature, but why does it need to have a thread of it's own? Could 
this be done from inside the regular event handler thread? The event handler 
thread also prints to stdout, and it seems like a bad idea to have two threads 
trying to do the same...


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

https://reviews.llvm.org/D120972

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


[Lldb-commits] [PATCH] D120969: [lldb/Plugins] Add ability to load modules to Scripted Processes

2022-03-04 Thread Med Ismail Bennani via Phabricator via lldb-commits
mib added inline comments.



Comment at: 
lldb/test/API/functionalities/scripted_process/stack_core_scripted_process.py:45
+
+lib_load_addr = 0x0001001e
+self.loaded_images.append({"path": self.lib_path,

JDevlieghere wrote:
> What exactly is this value? Shouldn't we get the load address from the core 
> file and report that? 
You're right, I missed that.


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

https://reviews.llvm.org/D120969

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


[Lldb-commits] [PATCH] D120969: [lldb/Plugins] Add ability to load modules to Scripted Processes

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

Address @JDevlieghere comments:

- Fix error message
- Use corefile module load address for scripted process module


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

https://reviews.llvm.org/D120969

Files:
  lldb/examples/python/scripted_process/scripted_process.py
  lldb/include/lldb/Interpreter/ScriptedProcessInterface.h
  lldb/source/Plugins/Process/scripted/ScriptedProcess.cpp
  lldb/source/Plugins/Process/scripted/ScriptedProcess.h
  
lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.cpp
  lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.h
  lldb/test/API/functionalities/scripted_process/Makefile
  lldb/test/API/functionalities/scripted_process/TestStackCoreScriptedProcess.py
  lldb/test/API/functionalities/scripted_process/baz.c
  lldb/test/API/functionalities/scripted_process/baz.h
  lldb/test/API/functionalities/scripted_process/main.cpp
  lldb/test/API/functionalities/scripted_process/stack_core_scripted_process.py

Index: lldb/test/API/functionalities/scripted_process/stack_core_scripted_process.py
===
--- lldb/test/API/functionalities/scripted_process/stack_core_scripted_process.py
+++ lldb/test/API/functionalities/scripted_process/stack_core_scripted_process.py
@@ -7,13 +7,19 @@
 from lldb.plugins.scripted_process import ScriptedThread
 
 class StackCoreScriptedProcess(ScriptedProcess):
+def get_module_with_name(self, target, name):
+for module in target.modules:
+if name in module.GetFileSpec().GetFilename():
+return module
+return None
+
 def __init__(self, target: lldb.SBTarget, args : lldb.SBStructuredData):
 super().__init__(target, args)
 
-self.backing_target_idx = args.GetValueForKey("backing_target_idx")
-
 self.corefile_target = None
 self.corefile_process = None
+
+self.backing_target_idx = args.GetValueForKey("backing_target_idx")
 if (self.backing_target_idx and self.backing_target_idx.IsValid()):
 if self.backing_target_idx.GetType() == lldb.eStructuredDataTypeInteger:
 idx = self.backing_target_idx.GetIntegerValue(42)
@@ -30,9 +36,22 @@
 
 self.threads[corefile_thread.GetThreadID()] = StackCoreScriptedThread(self, structured_data)
 
-if len(self.threads) == 3:
+if len(self.threads) == 2:
 self.threads[len(self.threads) - 1].is_stopped = True
 
+corefile_module = self.get_module_with_name(self.corefile_target,
+"libbaz.dylib")
+if not corefile_module or not corefile_module.IsValid():
+return
+module_path = os.path.join(corefile_module.GetFileSpec().GetDirectory(),
+   corefile_module.GetFileSpec().GetFilename())
+if not os.path.exists(module_path):
+return
+module_load_addr = corefile_module.GetObjectFileHeaderAddress().GetLoadAddress(self.corefile_target)
+
+self.loaded_images.append({"path": module_path,
+   "load_addr": module_load_addr})
+
 def get_memory_region_containing_address(self, addr: int) -> lldb.SBMemoryRegionInfo:
 mem_region = lldb.SBMemoryRegionInfo()
 error = self.corefile_process.GetMemoryRegionInfo(addr, mem_region)
@@ -61,8 +80,6 @@
 return data
 
 def get_loaded_images(self):
-# TODO: Iterate over corefile_target modules and build a data structure
-# from it.
 return self.loaded_images
 
 def get_process_id(self) -> int:
Index: lldb/test/API/functionalities/scripted_process/main.cpp
===
--- lldb/test/API/functionalities/scripted_process/main.cpp
+++ lldb/test/API/functionalities/scripted_process/main.cpp
@@ -2,16 +2,20 @@
 #include 
 #include 
 
+extern "C" {
+int baz(int);
+}
+
 int bar(int i) {
   int j = i * i;
-  return j; // break here
+  return j;
 }
 
 int foo(int i) { return bar(i); }
 
 void call_and_wait(int &n) {
   std::cout << "waiting for computation!" << std::endl;
-  while (n != 42 * 42)
+  while (baz(n) != 42)
 ;
   std::cout << "finished computation!" << std::endl;
 }
Index: lldb/test/API/functionalities/scripted_process/baz.h
===
--- /dev/null
+++ lldb/test/API/functionalities/scripted_process/baz.h
@@ -0,0 +1,3 @@
+#pragma once
+
+int baz(int j);
Index: lldb/test/API/functionalities/scripted_process/baz.c
===
--- /dev/null
+++ lldb/test/API/functionalities/scripted_process/baz.c
@@ -0,0 +1,8 @@
+#include "baz.h"
+
+#include 
+
+int baz(int j) {
+  int k = sqrt(j);
+  return k; // break here
+}
Index: lldb/test/API/functionalities/scripted

[Lldb-commits] [PATCH] D120969: [lldb/Plugins] Add ability to load modules to Scripted Processes

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

LGTM


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

https://reviews.llvm.org/D120969

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


[Lldb-commits] [PATCH] D120595: [WIP][trace][intelpt] Add TSC to Nanosecond conversion for IntelPT traces

2022-03-04 Thread walter erquinigo via Phabricator via lldb-commits
wallace added a comment.

Thanks @davidca and @labath for chiming in.
@jj10306, please rename IntelPTManager to IntelPTCollector for clarity.




Comment at: lldb/docs/lldb-gdb-remote.txt:469
+//
+//tsc_rate: {
+//  kind: "perf",

davidca wrote:
> why is all this called tsc rate? there is also offset in this conversion. 
> What about something like tsc_conversion_params or tsc_conv
tsc_conversion_params seems like a good idea



Comment at: lldb/include/lldb/Utility/TraceIntelPTGDBRemotePackets.h:44
+/// TSC to nanosecond conversion.
+class TimestampCounterRate {
+  public:

davidca wrote:
> nit, Intel documentation and kernel refers this as TSC, not TimestampCounter, 
> in order to differentiate this awful name from everywhere else that 
> "Timestamp" and "Counter" is used. Perhaps embrace TSC to make it easier to 
> google info?
Ahh!! Then let's do what David says. Let's call it tsc everywhere



Comment at: lldb/include/lldb/Utility/TraceIntelPTGDBRemotePackets.h:74
+struct TraceIntelPTGetStateResponse : TraceGetStateResponse {
+  /// `nullptr` if no tsc conversion rate exists.
+  llvm::Optional tsc_rate;

labath wrote:
> wallace wrote:
> > avoid using nullptr when you have an Optional. 
> Ideally this would be a plain `TimestampCounterRateSP` variable and nullptr 
> would denote emptyness. Since (shared) pointers already have a natural empty 
> state, it's best to use that. Adding an extra Optional layer just creates 
> ambiguity.
Good idea



Comment at: lldb/include/lldb/Utility/TraceIntelPTGDBRemotePackets.h:78-80
+bool fromJSON(const llvm::json::Value &value, TimestampCounterRateSP 
&tsc_converter, llvm::json::Path path);
+
+bool fromJSON(const llvm::json::Value &value, TraceIntelPTGetStateResponse 
&packet, llvm::json::Path path);

davidca wrote:
> should this two be static factory methods?
That's just the pattern most json conversion utils follow. It helps with some 
templating stuff



Comment at: lldb/source/Plugins/Process/Linux/IntelPTManager.cpp:257
 
+  IntelPTManager::GetPerfTscRate(*m_mmap_meta);
+

davidca wrote:
> wallace wrote:
> > sadly you can't put this here. If you do this, then GetState() will only 
> > work correctly if StartTrace() was invoked first. What if in the future we 
> > have a different flow in which lldb-server uses an additional tracing 
> > function besides StartTrace() and that new function forgets to set the 
> > tsc_rate?
> > This is called coupling and should be avoided.
> > 
> > What you should do instead is to create a new static function called 
> > `llvm::OptionalGetTscRate()` that will perform the 
> > perf_event request or reuse a previously saved value. It should work 
> > regardless of when it's invoked.
> 1) this is not a Get* method. This is populating a global. Get* are 
> inexpensive methods that return a value.
> 
> 2) if the TSC conversion parameters will be stored in a global, why not to 
> use the Singleton pattern?
> 
> 3) TSC parameters change over time. I really think that should be stored 
> within IntelPTManager. Obtaining this parameters is a ~10 microseconds 
> operation, so it's fine if they need to be read next time an IntelPTManager 
> is created.
Can tsc frequency rates change even in modern cpus?. In this case, it's no 
brainer we need to calculate this number all the time.

I also agree with point number 1. 



Comment at: lldb/source/Plugins/Process/Linux/IntelPTManager.h:211
   static bool IsSupported();
+  static void GetPerfTscRate(perf_event_mmap_page &mmap_meta);
+

davidca wrote:
> wallace wrote:
> > don't forget to add documentation here
> how is ti
@davidca, i think you didn't finish your comment


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

https://reviews.llvm.org/D120595

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


[Lldb-commits] [PATCH] D120972: [lldb] Show progress events in the command line driver

2022-03-04 Thread Jonas Devlieghere via Phabricator via lldb-commits
JDevlieghere updated this revision to Diff 413108.
JDevlieghere added a comment.

- Move progress event handling in the regular event handler thread


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

https://reviews.llvm.org/D120972

Files:
  lldb/include/lldb/Core/Debugger.h
  lldb/include/lldb/Interpreter/CommandInterpreter.h
  lldb/source/Core/CoreProperties.td
  lldb/source/Core/Debugger.cpp
  lldb/source/Symbol/LocateSymbolFile.cpp

Index: lldb/source/Symbol/LocateSymbolFile.cpp
===
--- lldb/source/Symbol/LocateSymbolFile.cpp
+++ lldb/source/Symbol/LocateSymbolFile.cpp
@@ -10,6 +10,7 @@
 
 #include "lldb/Core/ModuleList.h"
 #include "lldb/Core/ModuleSpec.h"
+#include "lldb/Core/Progress.h"
 #include "lldb/Host/FileSystem.h"
 #include "lldb/Symbol/ObjectFile.h"
 #include "lldb/Utility/ArchSpec.h"
@@ -262,6 +263,10 @@
   FileSystem::Instance().Exists(symbol_file_spec))
 return symbol_file_spec;
 
+  Progress progress(llvm::formatv(
+  "Locating external symbol file for {0}",
+  module_spec.GetFileSpec().GetFilename().AsCString("")));
+
   FileSpecList debug_file_search_paths = default_search_paths;
 
   // Add module directory.
Index: lldb/source/Core/Debugger.cpp
===
--- lldb/source/Core/Debugger.cpp
+++ lldb/source/Core/Debugger.cpp
@@ -378,6 +378,12 @@
   return ret;
 }
 
+bool Debugger::GetShowProgress() const {
+  const uint32_t idx = ePropertyShowProgress;
+  return m_collection_sp->GetPropertyAtIndexAsBoolean(
+  nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
+}
+
 bool Debugger::GetUseAutosuggestion() const {
   const uint32_t idx = ePropertyShowAutosuggestion;
   return m_collection_sp->GetPropertyAtIndexAsBoolean(
@@ -1605,6 +1611,11 @@
   CommandInterpreter::eBroadcastBitAsynchronousOutputData |
   CommandInterpreter::eBroadcastBitAsynchronousErrorData);
 
+  if (!m_broadcaster.EventTypeHasListeners(Debugger::eBroadcastBitProgress)) {
+listener_sp->StartListeningForEvents(&m_broadcaster,
+ Debugger::eBroadcastBitProgress);
+  }
+
   // Let the thread that spawned us know that we have started up and that we
   // are now listening to all required events so no events get missed
   m_sync_broadcaster.BroadcastEvent(eBroadcastBitEventThreadIsListening);
@@ -1654,6 +1665,9 @@
 }
   }
 }
+  } else if (broadcaster == &m_broadcaster) {
+if (event_type & Debugger::eBroadcastBitProgress)
+  HandleProgressEvent(event_sp);
   }
 }
 
@@ -1719,6 +1733,55 @@
   return {};
 }
 
+void Debugger::HandleProgressEvent(const lldb::EventSP &event_sp) {
+  auto *data =
+  Debugger::ProgressEventData::GetEventDataFromEvent(event_sp.get());
+  if (!data)
+return;
+
+  // Do some bookkeeping for the current event, regardless of whether we're
+  // going to show the progress.
+  const uint64_t id = data->GetID();
+  if (m_current_event_id) {
+if (id != *m_current_event_id)
+  return;
+if (data->GetCompleted())
+  m_current_event_id.reset();
+  } else {
+m_current_event_id = id;
+  }
+
+  // Decide whether we actually are going to show the progress. This
+  // decision can change between iterations so check it inside the loop.
+  File &output = GetOutputFile();
+  if (!output.GetIsTerminalWithColors() || !GetShowProgress())
+return;
+
+  // If we're done, just clear the current line.
+  if (data->GetCompleted()) {
+output.Printf("\33[2K\r");
+return;
+  }
+
+  // Print over previous line, if any.
+  output.Printf("\r");
+
+  // Print the progress message.
+  std::string message = data->GetMessage();
+  if (data->GetTotal() != UINT64_MAX) {
+output.Printf("[%llu/%llu] %s...", data->GetCompleted(), data->GetTotal(),
+  message.c_str());
+  } else {
+output.Printf("%s...", message.c_str());
+  }
+
+  // Clear until the end of the line.
+  output.Printf("\x1B[K");
+
+  // Flush the output.
+  output.Flush();
+}
+
 bool Debugger::HasIOHandlerThread() { return m_io_handler_thread.IsJoinable(); }
 
 bool Debugger::StartIOHandlerThread() {
Index: lldb/source/Core/CoreProperties.td
===
--- lldb/source/Core/CoreProperties.td
+++ lldb/source/Core/CoreProperties.td
@@ -131,6 +131,10 @@
 Global,
 DefaultTrue,
 Desc<"Whether to use Ansi color codes or not.">;
+  def ShowProgress: Property<"show-progress", "Boolean">,
+Global,
+DefaultTrue,
+Desc<"Whether to show progress or not.">;
   def UseSourceCache: Property<"use-source-cache", "Boolean">,
 Global,
 DefaultTrue,
Index: lldb/include/lldb/Interpreter/CommandInterpreter.h
===
--- lldb/include/lldb/Interpreter/CommandInterpreter.h
+++ l

[Lldb-commits] [PATCH] D120972: [lldb] Show progress events in the command line driver

2022-03-04 Thread Jonas Devlieghere via Phabricator via lldb-commits
JDevlieghere updated this revision to Diff 413110.
JDevlieghere added a comment.

- Unstage `lldb/include/lldb/Interpreter/CommandInterpreter.h`.


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

https://reviews.llvm.org/D120972

Files:
  lldb/include/lldb/Core/Debugger.h
  lldb/source/Core/CoreProperties.td
  lldb/source/Core/Debugger.cpp
  lldb/source/Symbol/LocateSymbolFile.cpp

Index: lldb/source/Symbol/LocateSymbolFile.cpp
===
--- lldb/source/Symbol/LocateSymbolFile.cpp
+++ lldb/source/Symbol/LocateSymbolFile.cpp
@@ -10,6 +10,7 @@
 
 #include "lldb/Core/ModuleList.h"
 #include "lldb/Core/ModuleSpec.h"
+#include "lldb/Core/Progress.h"
 #include "lldb/Host/FileSystem.h"
 #include "lldb/Symbol/ObjectFile.h"
 #include "lldb/Utility/ArchSpec.h"
@@ -262,6 +263,10 @@
   FileSystem::Instance().Exists(symbol_file_spec))
 return symbol_file_spec;
 
+  Progress progress(llvm::formatv(
+  "Locating external symbol file for {0}",
+  module_spec.GetFileSpec().GetFilename().AsCString("")));
+
   FileSpecList debug_file_search_paths = default_search_paths;
 
   // Add module directory.
Index: lldb/source/Core/Debugger.cpp
===
--- lldb/source/Core/Debugger.cpp
+++ lldb/source/Core/Debugger.cpp
@@ -378,6 +378,12 @@
   return ret;
 }
 
+bool Debugger::GetShowProgress() const {
+  const uint32_t idx = ePropertyShowProgress;
+  return m_collection_sp->GetPropertyAtIndexAsBoolean(
+  nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
+}
+
 bool Debugger::GetUseAutosuggestion() const {
   const uint32_t idx = ePropertyShowAutosuggestion;
   return m_collection_sp->GetPropertyAtIndexAsBoolean(
@@ -1605,6 +1611,11 @@
   CommandInterpreter::eBroadcastBitAsynchronousOutputData |
   CommandInterpreter::eBroadcastBitAsynchronousErrorData);
 
+  if (!m_broadcaster.EventTypeHasListeners(Debugger::eBroadcastBitProgress)) {
+listener_sp->StartListeningForEvents(&m_broadcaster,
+ Debugger::eBroadcastBitProgress);
+  }
+
   // Let the thread that spawned us know that we have started up and that we
   // are now listening to all required events so no events get missed
   m_sync_broadcaster.BroadcastEvent(eBroadcastBitEventThreadIsListening);
@@ -1654,6 +1665,9 @@
 }
   }
 }
+  } else if (broadcaster == &m_broadcaster) {
+if (event_type & Debugger::eBroadcastBitProgress)
+  HandleProgressEvent(event_sp);
   }
 }
 
@@ -1719,6 +1733,55 @@
   return {};
 }
 
+void Debugger::HandleProgressEvent(const lldb::EventSP &event_sp) {
+  auto *data =
+  Debugger::ProgressEventData::GetEventDataFromEvent(event_sp.get());
+  if (!data)
+return;
+
+  // Do some bookkeeping for the current event, regardless of whether we're
+  // going to show the progress.
+  const uint64_t id = data->GetID();
+  if (m_current_event_id) {
+if (id != *m_current_event_id)
+  return;
+if (data->GetCompleted())
+  m_current_event_id.reset();
+  } else {
+m_current_event_id = id;
+  }
+
+  // Decide whether we actually are going to show the progress. This
+  // decision can change between iterations so check it inside the loop.
+  File &output = GetOutputFile();
+  if (!output.GetIsTerminalWithColors() || !GetShowProgress())
+return;
+
+  // If we're done, just clear the current line.
+  if (data->GetCompleted()) {
+output.Printf("\33[2K\r");
+return;
+  }
+
+  // Print over previous line, if any.
+  output.Printf("\r");
+
+  // Print the progress message.
+  std::string message = data->GetMessage();
+  if (data->GetTotal() != UINT64_MAX) {
+output.Printf("[%llu/%llu] %s...", data->GetCompleted(), data->GetTotal(),
+  message.c_str());
+  } else {
+output.Printf("%s...", message.c_str());
+  }
+
+  // Clear until the end of the line.
+  output.Printf("\x1B[K");
+
+  // Flush the output.
+  output.Flush();
+}
+
 bool Debugger::HasIOHandlerThread() { return m_io_handler_thread.IsJoinable(); }
 
 bool Debugger::StartIOHandlerThread() {
Index: lldb/source/Core/CoreProperties.td
===
--- lldb/source/Core/CoreProperties.td
+++ lldb/source/Core/CoreProperties.td
@@ -131,6 +131,10 @@
 Global,
 DefaultTrue,
 Desc<"Whether to use Ansi color codes or not.">;
+  def ShowProgress: Property<"show-progress", "Boolean">,
+Global,
+DefaultTrue,
+Desc<"Whether to show progress or not.">;
   def UseSourceCache: Property<"use-source-cache", "Boolean">,
 Global,
 DefaultTrue,
Index: lldb/include/lldb/Core/Debugger.h
===
--- lldb/include/lldb/Core/Debugger.h
+++ lldb/include/lldb/Core/Debugger.h
@@ -329,6 +329,8 @@
 
   bool SetUseColor(bool use_color)

[Lldb-commits] [lldb] 9bd72b5 - [LLDB] Remove cases of using namespace std

2022-03-04 Thread Shafik Yaghmour via lldb-commits

Author: Shafik Yaghmour
Date: 2022-03-04T12:50:25-08:00
New Revision: 9bd72b5c258549b8743557a79c7929de38f05a6d

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

LOG: [LLDB] Remove cases of using namespace std

We had using namespace std; sprinkled around several source files and tests.

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

Added: 


Modified: 
lldb/source/Core/FileSpecList.cpp
lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugAbbrev.cpp
lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfo.cpp
lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfoEntry.cpp
lldb/source/Plugins/SymbolFile/DWARF/DWARFUnit.cpp
lldb/test/API/api/multithreaded/inferior.cpp

lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/queue/main.cpp

lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/tuple/main.cpp
lldb/test/API/functionalities/process_save_core_minidump/main.cpp
lldb/test/API/functionalities/thread/concurrent_events/main.cpp
lldb/unittests/SymbolFile/PDB/Inputs/test-pdb-types.cpp

Removed: 




diff  --git a/lldb/source/Core/FileSpecList.cpp 
b/lldb/source/Core/FileSpecList.cpp
index 1a1cf284ea07c..8eec8f499352c 100644
--- a/lldb/source/Core/FileSpecList.cpp
+++ b/lldb/source/Core/FileSpecList.cpp
@@ -16,7 +16,6 @@
 #include 
 
 using namespace lldb_private;
-using namespace std;
 
 FileSpecList::FileSpecList() : m_files() {}
 

diff  --git a/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugAbbrev.cpp 
b/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugAbbrev.cpp
index 0f0f50a645db3..d890288cdf567 100644
--- a/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugAbbrev.cpp
+++ b/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugAbbrev.cpp
@@ -12,7 +12,6 @@
 
 using namespace lldb;
 using namespace lldb_private;
-using namespace std;
 
 // DWARFAbbreviationDeclarationSet::Clear()
 void DWARFAbbreviationDeclarationSet::Clear() {

diff  --git a/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfo.cpp 
b/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfo.cpp
index b72c7406ece13..8933b0804a01c 100644
--- a/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfo.cpp
+++ b/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfo.cpp
@@ -27,7 +27,6 @@
 
 using namespace lldb;
 using namespace lldb_private;
-using namespace std;
 
 // Constructor
 DWARFDebugInfo::DWARFDebugInfo(SymbolFileDWARF &dwarf,

diff  --git a/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfoEntry.cpp 
b/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfoEntry.cpp
index 01046fb68b9d3..95c0cb6472c59 100644
--- a/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfoEntry.cpp
+++ b/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfoEntry.cpp
@@ -32,7 +32,6 @@
 
 using namespace lldb_private;
 using namespace lldb_private::dwarf;
-using namespace std;
 extern int g_verbose;
 
 // Extract a debug info entry for a given DWARFUnit from the data

diff  --git a/lldb/source/Plugins/SymbolFile/DWARF/DWARFUnit.cpp 
b/lldb/source/Plugins/SymbolFile/DWARF/DWARFUnit.cpp
index 812a8086f4875..085c9e9ce1a6e 100644
--- a/lldb/source/Plugins/SymbolFile/DWARF/DWARFUnit.cpp
+++ b/lldb/source/Plugins/SymbolFile/DWARF/DWARFUnit.cpp
@@ -26,7 +26,6 @@
 using namespace lldb;
 using namespace lldb_private;
 using namespace lldb_private::dwarf;
-using namespace std;
 
 extern int g_verbose;
 
@@ -449,7 +448,7 @@ ParseListTableHeader(const llvm::DWARFDataExtractor &data, 
uint64_t offset,
 
   uint64_t HeaderSize = llvm::DWARFListTableHeader::getHeaderSize(format);
   if (offset < HeaderSize)
-return llvm::createStringError(errc::invalid_argument,
+return llvm::createStringError(std::errc::invalid_argument,
"did not detect a valid"
" list table with base = 0x%" PRIx64 "\n",
offset);
@@ -559,10 +558,10 @@ DWARFUnit::GetRnglistTable() {
 // This function is called only for DW_FORM_rnglistx.
 llvm::Expected DWARFUnit::GetRnglistOffset(uint32_t Index) {
   if (!GetRnglistTable())
-return llvm::createStringError(errc::invalid_argument,
+return llvm::createStringError(std::errc::invalid_argument,
"missing or invalid range list table");
   if (!m_ranges_base)
-return llvm::createStringError(errc::invalid_argument,
+return llvm::createStringError(std::errc::invalid_argument,
"DW_FORM_rnglistx cannot be used without "
"DW_AT_rnglists_base for CU at 0x%8.8x",
GetOffset());
@@ -570,7 +569,7 @@ llvm::Expected 
DWARFUnit::GetRnglistOffset(uint32_t Index) {
   GetRnglistData().GetAsLLVM(), Index))
 return *off + m_ranges_

[Lldb-commits] [PATCH] D120966: Remove cases of using namespace std

2022-03-04 Thread Shafik Yaghmour via Phabricator via lldb-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG9bd72b5c2585: [LLDB] Remove cases of using namespace std 
(authored by shafik).
Herald added a project: LLDB.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120966

Files:
  lldb/source/Core/FileSpecList.cpp
  lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugAbbrev.cpp
  lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfo.cpp
  lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfoEntry.cpp
  lldb/source/Plugins/SymbolFile/DWARF/DWARFUnit.cpp
  lldb/test/API/api/multithreaded/inferior.cpp
  
lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/queue/main.cpp
  
lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/tuple/main.cpp
  lldb/test/API/functionalities/process_save_core_minidump/main.cpp
  lldb/test/API/functionalities/thread/concurrent_events/main.cpp
  lldb/unittests/SymbolFile/PDB/Inputs/test-pdb-types.cpp

Index: lldb/unittests/SymbolFile/PDB/Inputs/test-pdb-types.cpp
===
--- lldb/unittests/SymbolFile/PDB/Inputs/test-pdb-types.cpp
+++ lldb/unittests/SymbolFile/PDB/Inputs/test-pdb-types.cpp
@@ -2,8 +2,6 @@
 // Link with "link test-pdb-types.obj /debug /nodefaultlib /entry:main
 // /out:test-pdb-types.exe"
 
-using namespace std;
-
 // Sizes of builtin types
 static const int sizeof_char = sizeof(char);
 static const int sizeof_uchar = sizeof(unsigned char);
Index: lldb/test/API/functionalities/thread/concurrent_events/main.cpp
===
--- lldb/test/API/functionalities/thread/concurrent_events/main.cpp
+++ lldb/test/API/functionalities/thread/concurrent_events/main.cpp
@@ -6,7 +6,6 @@
 
 #include "pseudo_barrier.h"
 #include 
-using namespace std;
 
 #include 
 
Index: lldb/test/API/functionalities/process_save_core_minidump/main.cpp
===
--- lldb/test/API/functionalities/process_save_core_minidump/main.cpp
+++ lldb/test/API/functionalities/process_save_core_minidump/main.cpp
@@ -2,8 +2,6 @@
 #include 
 #include 
 
-using namespace std;
-
 void g() { assert(false); }
 
 void f() { g(); }
@@ -19,12 +17,12 @@
 }
 
 int main() {
-  thread t1(f);
+  std::thread t1(f);
 
   size_t x = h();
 
   t1.join();
 
-  cout << "X is " << x << "\n";
+  std::cout << "X is " << x << "\n";
   return 0;
-}
\ No newline at end of file
+}
Index: lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/tuple/main.cpp
===
--- lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/tuple/main.cpp
+++ lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/tuple/main.cpp
@@ -1,11 +1,9 @@
 #include 
 #include 
 
-using namespace std;
-
 int main() {
-  tuple<> empty;
-  tuple one_elt{47};
-  tuple three_elts{1, 47l, "foo"};
+  std::tuple<> empty;
+  std::tuple one_elt{47};
+  std::tuple three_elts{1, 47l, "foo"};
   return 0; // break here
 }
Index: lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/queue/main.cpp
===
--- lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/queue/main.cpp
+++ lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/queue/main.cpp
@@ -1,11 +1,9 @@
 #include 
 #include 
 
-using namespace std;
-
 int main() {
-  queue q1{{1,2,3,4,5}};
-  queue> q2{{1,2,3,4,5}};
+  std::queue q1{{1,2,3,4,5}};
+  std::queue> q2{{1,2,3,4,5}};
   int ret = q1.size() + q2.size(); // break here
   return ret;
 }
Index: lldb/test/API/api/multithreaded/inferior.cpp
===
--- lldb/test/API/api/multithreaded/inferior.cpp
+++ lldb/test/API/api/multithreaded/inferior.cpp
@@ -1,11 +1,11 @@
 
 #include 
 
-using namespace std;
+
 
 int next() {
   static int i = 0;
-  cout << "incrementing " << i << endl;
+  std::cout << "incrementing " << i << std::endl;
   return ++i;
 }
 
Index: lldb/source/Plugins/SymbolFile/DWARF/DWARFUnit.cpp
===
--- lldb/source/Plugins/SymbolFile/DWARF/DWARFUnit.cpp
+++ lldb/source/Plugins/SymbolFile/DWARF/DWARFUnit.cpp
@@ -26,7 +26,6 @@
 using namespace lldb;
 using namespace lldb_private;
 using namespace lldb_private::dwarf;
-using namespace std;
 
 extern int g_verbose;
 
@@ -449,7 +448,7 @@
 
   uint64_t HeaderSize = llvm::DWARFListTableHeader::getHeaderSize(format);
   if (offset < HeaderSize)
-return llvm::createStringError(errc::invalid_argument,
+return llvm::createStringError(std::errc::invalid_argument,
"did not detect a valid"
" list table with base = 0x%" PRIx64 "\n",
  

[Lldb-commits] [PATCH] D120961: [LLDB] Flush stream at the end of PrintCommandOutput

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

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120961

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


[Lldb-commits] [PATCH] D120948: Disable LLDB index cache for .o files with no UUID.

2022-03-04 Thread Greg Clayton via Phabricator via lldb-commits
clayborg updated this revision to Diff 413115.
clayborg added a comment.

Added unit tests for CacheSignature that covers:

- making sure encoding fails when we have an invalid CacheSignature
- make sure decoding of older cache files that had a previously valid signature 
fails when there is no UUID
- fix a bug in the CacheSignature encoding of object modification times


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120948

Files:
  lldb/include/lldb/Core/DataFileCache.h
  lldb/source/Core/DataFileCache.cpp
  lldb/test/API/functionalities/module_cache/bsd/TestModuleCacheBSD.py
  lldb/unittests/SymbolFile/DWARF/DWARFIndexCachingTest.cpp

Index: lldb/unittests/SymbolFile/DWARF/DWARFIndexCachingTest.cpp
===
--- lldb/unittests/SymbolFile/DWARF/DWARFIndexCachingTest.cpp
+++ lldb/unittests/SymbolFile/DWARF/DWARFIndexCachingTest.cpp
@@ -196,3 +196,75 @@
   DIERef(llvm::None, DIERef::Section::DebugInfo, ++die_offset));
   EncodeDecode(set);
 }
+
+static void EncodeDecode(const CacheSignature &object, ByteOrder byte_order,
+ bool encode_result) {
+  const uint8_t addr_size = 8;
+  DataEncoder encoder(byte_order, addr_size);
+  EXPECT_EQ(encode_result, object.Encode(encoder));
+  if (!encode_result)
+return;
+  llvm::ArrayRef bytes = encoder.GetData();
+  DataExtractor data(bytes.data(), bytes.size(), byte_order, addr_size);
+  offset_t data_offset = 0;
+  CacheSignature decoded_object;
+  EXPECT_TRUE(decoded_object.Decode(data, &data_offset));
+  EXPECT_EQ(object, decoded_object);
+}
+
+static void EncodeDecode(const CacheSignature &object, bool encode_result) {
+  EncodeDecode(object, eByteOrderLittle, encode_result);
+  EncodeDecode(object, eByteOrderBig, encode_result);
+}
+
+TEST(DWARFIndexCachingTest, CacheSignatureTests) {
+  CacheSignature sig;
+  // A cache signature is only considered valid if it has a UUID.
+  sig.m_mod_time = 0x12345678;
+  EXPECT_FALSE(sig.IsValid());
+  EncodeDecode(sig, /*encode_result=*/false);
+  sig.Clear();
+
+  sig.m_obj_mod_time = 0x12345678;
+  EXPECT_FALSE(sig.IsValid());
+  EncodeDecode(sig, /*encode_result=*/false);
+  sig.Clear();
+
+  sig.m_uuid = UUID::fromData("@\x00\x11\x22\x33\x44\x55\x66\x77", 8);
+  EXPECT_TRUE(sig.IsValid());
+  EncodeDecode(sig, /*encode_result=*/true);
+  sig.m_mod_time = 0x12345678;
+  EXPECT_TRUE(sig.IsValid());
+  EncodeDecode(sig, /*encode_result=*/true);
+  sig.m_obj_mod_time = 0x456789ab;
+  EXPECT_TRUE(sig.IsValid());
+  EncodeDecode(sig, /*encode_result=*/true);
+  sig.m_mod_time = llvm::None;
+  EXPECT_TRUE(sig.IsValid());
+  EncodeDecode(sig, /*encode_result=*/true);
+
+  // Recent changes do not allow cache signatures with only a modification time
+  // or object modification time, so make sure if we try to decode such a cache
+  // file that we fail. This verifies that if we try to load an previously
+  // valid cache file where the signature is insufficient, that we will fail to
+  // decode and load these cache files.
+  DataEncoder encoder(eByteOrderLittle, /*addr_size=*/8);
+  encoder.AppendU8(2); // eSignatureModTime
+  encoder.AppendU32(0x12345678);
+  encoder.AppendU8(255); // eSignatureEnd
+
+  llvm::ArrayRef bytes = encoder.GetData();
+  DataExtractor data(bytes.data(), bytes.size(), eByteOrderLittle,
+ /*addr_size=*/8);
+  offset_t data_offset = 0;
+
+  // Make sure we fail to decode a CacheSignature with only a mod time
+  EXPECT_FALSE(sig.Decode(data, &data_offset));
+
+  // Change the signature data to contain only a eSignatureObjectModTime and
+  // make sure decoding fails as well.
+  encoder.PutU8(/*offset=*/0, 3); // eSignatureObjectModTime
+  data_offset = 0;
+  EXPECT_FALSE(sig.Decode(data, &data_offset));
+
+}
Index: lldb/test/API/functionalities/module_cache/bsd/TestModuleCacheBSD.py
===
--- lldb/test/API/functionalities/module_cache/bsd/TestModuleCacheBSD.py
+++ lldb/test/API/functionalities/module_cache/bsd/TestModuleCacheBSD.py
@@ -41,6 +41,25 @@
 @skipUnlessDarwin
 def test(self):
 """
+This test has been modified to make sure .o files that don't have
+UUIDs are not cached after discovering build systems that play with
+modification times of .o files that the modification times are not
+unique enough to ensure the .o file within the .a file are the right
+files as this was causing older cache files to be accepted for new
+updated .o files.
+
+ELF .o files do calculate a UUID from the contents of the file,
+which is expensive, but no one loads .o files into a debug sessions
+when using ELF files. Mach-o .o files do not have UUID values and do
+no calculate one as they _are_ used during debug sessions when no
+   

[Lldb-commits] [lldb] b31a1b4 - [LLDB] Flush stream at the end of PrintCommandOutput

2022-03-04 Thread Zequan Wu via lldb-commits

Author: Zequan Wu
Date: 2022-03-04T13:06:15-08:00
New Revision: b31a1b4746c7c806bcc550e877577ec66ea407d9

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

LOG: [LLDB] Flush stream at the end of PrintCommandOutput

On Windows, lldb doesn't print any error message until exit. This fixes it.

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

Added: 


Modified: 
lldb/source/Interpreter/CommandInterpreter.cpp

Removed: 




diff  --git a/lldb/source/Interpreter/CommandInterpreter.cpp 
b/lldb/source/Interpreter/CommandInterpreter.cpp
index 8676371b963e4..edf4f59a6b7bb 100644
--- a/lldb/source/Interpreter/CommandInterpreter.cpp
+++ b/lldb/source/Interpreter/CommandInterpreter.cpp
@@ -2997,6 +2997,7 @@ void CommandInterpreter::PrintCommandOutput(Stream 
&stream,
   if (size > 0) {
 stream.Printf("\n... Interrupted.\n");
   }
+  stream.Flush();
 }
 
 bool CommandInterpreter::EchoCommandNonInteractive(



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


[Lldb-commits] [PATCH] D120961: [LLDB] Flush stream at the end of PrintCommandOutput

2022-03-04 Thread Zequan Wu via Phabricator via lldb-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb31a1b4746c7: [LLDB] Flush stream at the end of 
PrintCommandOutput (authored by zequanwu).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120961

Files:
  lldb/source/Interpreter/CommandInterpreter.cpp


Index: lldb/source/Interpreter/CommandInterpreter.cpp
===
--- lldb/source/Interpreter/CommandInterpreter.cpp
+++ lldb/source/Interpreter/CommandInterpreter.cpp
@@ -2997,6 +2997,7 @@
   if (size > 0) {
 stream.Printf("\n... Interrupted.\n");
   }
+  stream.Flush();
 }
 
 bool CommandInterpreter::EchoCommandNonInteractive(


Index: lldb/source/Interpreter/CommandInterpreter.cpp
===
--- lldb/source/Interpreter/CommandInterpreter.cpp
+++ lldb/source/Interpreter/CommandInterpreter.cpp
@@ -2997,6 +2997,7 @@
   if (size > 0) {
 stream.Printf("\n... Interrupted.\n");
   }
+  stream.Flush();
 }
 
 bool CommandInterpreter::EchoCommandNonInteractive(
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D120948: Disable LLDB index cache for .o files with no UUID.

2022-03-04 Thread jeffrey tan via Phabricator via lldb-commits
yinghuitan added inline comments.



Comment at: lldb/include/lldb/Core/DataFileCache.h:130-138
+  bool operator==(const CacheSignature &rhs) const {
 if (m_uuid != rhs.m_uuid)
-  return true;
+  return false;
 if (m_mod_time != rhs.m_mod_time)
-  return true;
+  return false;
 if (m_obj_mod_time != rhs.m_obj_mod_time)
+  return false;

Nit: I believe this can be simplified as:
```
return m_uuid == rhs.m_uuid && m_mod_time == rhs.m_mod_time && m_obj_mod_time 
== rhs.m_obj_mod_time;
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120948

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


[Lldb-commits] [PATCH] D120607: [lldb/test] Re-enable TestEvents.py on Darwin and fix crashes

2022-03-04 Thread Med Ismail Bennani via Phabricator via lldb-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG2a29c3f72e8d: [lldb/test] Re-enable TestEvents.py on Darwin 
and fix crashes (authored by mib).
Herald added a project: All.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120607

Files:
  lldb/test/API/python_api/event/TestEvents.py


Index: lldb/test/API/python_api/event/TestEvents.py
===
--- lldb/test/API/python_api/event/TestEvents.py
+++ lldb/test/API/python_api/event/TestEvents.py
@@ -13,7 +13,6 @@
 
 
 @skipIfLinux   # llvm.org/pr25924, sometimes generating SIGSEGV
-@skipIfDarwin
 class EventAPITestCase(TestBase):
 
 mydir = TestBase.compute_mydir(__file__)
@@ -171,9 +170,9 @@
 # Let's only try at most 3 times to retrieve any kind of event.
 while not count > 3:
 if listener.WaitForEvent(5, event):
-self.trace("Got a valid event:", event)
-self.trace("Event data flavor:", event.GetDataFlavor())
-self.trace("Event type:", 
lldbutil.state_type_to_str(event.GetType()))
+self.context.trace("Got a valid event:", event)
+self.context.trace("Event data flavor:", 
event.GetDataFlavor())
+self.context.trace("Event type:", 
lldbutil.state_type_to_str(event.GetType()))
 listener.Clear()
 return
 count = count + 1
@@ -187,6 +186,7 @@
 
 # Let's start the listening thread to retrieve the event.
 my_thread = MyListeningThread()
+my_thread.context = self
 my_thread.start()
 
 # Wait until the 'MyListeningThread' terminates.
@@ -256,7 +256,7 @@
 class MyListeningThread(threading.Thread):
 
 def run(self):
-self.trace("Running MyListeningThread:", self)
+self.context.trace("Running MyListeningThread:", self)
 
 # Regular expression pattern for the event description.
 pattern = re.compile("data = {.*, state = (.*)}$")
@@ -266,7 +266,7 @@
 while True:
 if listener.WaitForEvent(5, event):
 desc = lldbutil.get_description(event)
-self.trace("Event description:", desc)
+self.context.trace("Event description:", desc)
 match = pattern.search(desc)
 if not match:
 break


Index: lldb/test/API/python_api/event/TestEvents.py
===
--- lldb/test/API/python_api/event/TestEvents.py
+++ lldb/test/API/python_api/event/TestEvents.py
@@ -13,7 +13,6 @@
 
 
 @skipIfLinux   # llvm.org/pr25924, sometimes generating SIGSEGV
-@skipIfDarwin
 class EventAPITestCase(TestBase):
 
 mydir = TestBase.compute_mydir(__file__)
@@ -171,9 +170,9 @@
 # Let's only try at most 3 times to retrieve any kind of event.
 while not count > 3:
 if listener.WaitForEvent(5, event):
-self.trace("Got a valid event:", event)
-self.trace("Event data flavor:", event.GetDataFlavor())
-self.trace("Event type:", lldbutil.state_type_to_str(event.GetType()))
+self.context.trace("Got a valid event:", event)
+self.context.trace("Event data flavor:", event.GetDataFlavor())
+self.context.trace("Event type:", lldbutil.state_type_to_str(event.GetType()))
 listener.Clear()
 return
 count = count + 1
@@ -187,6 +186,7 @@
 
 # Let's start the listening thread to retrieve the event.
 my_thread = MyListeningThread()
+my_thread.context = self
 my_thread.start()
 
 # Wait until the 'MyListeningThread' terminates.
@@ -256,7 +256,7 @@
 class MyListeningThread(threading.Thread):
 
 def run(self):
-self.trace("Running MyListeningThread:", self)
+self.context.trace("Running MyListeningThread:", self)
 
 # Regular expression pattern for the event description.
 pattern = re.compile("data = {.*, state = (.*)}$")
@@ -266,7 +266,7 @@
 while True:
 if listener.WaitForEvent(5, event):
 desc = lldbutil.get_description(event)
-self.trace("Event description:", desc)
+self.context.trace("Event description:", desc)
 match = pattern.search(desc)
 if not match:
 break
___

[Lldb-commits] [lldb] 2a29c3f - [lldb/test] Re-enable TestEvents.py on Darwin and fix crashes

2022-03-04 Thread Med Ismail Bennani via lldb-commits

Author: Med Ismail Bennani
Date: 2022-03-04T13:35:07-08:00
New Revision: 2a29c3f72e8d93385be83bd24a993c3bb57ac181

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

LOG: [lldb/test] Re-enable TestEvents.py on Darwin and fix crashes

This patch re-enables TestEvents.py on Darwin and fixes some crashes
that were happening due to an undefined method.

I ran it 100 times locally with the following command and it passed
every the time:

```
for i in {1..100}; do print $i/100; ./bin/lldb-dotest -p TestEvents.py 2>&1 | 
rg PASSED; if [ "$?" -eq "1" ]; then break; fi; done
```

Let's see if it still fails non-deterministically on the bots and
eventually also re-enable it on linux.

rdar://37037235

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

Signed-off-by: Med Ismail Bennani 

Added: 


Modified: 
lldb/test/API/python_api/event/TestEvents.py

Removed: 




diff  --git a/lldb/test/API/python_api/event/TestEvents.py 
b/lldb/test/API/python_api/event/TestEvents.py
index 95cf5b28c0ca6..33650c49b850a 100644
--- a/lldb/test/API/python_api/event/TestEvents.py
+++ b/lldb/test/API/python_api/event/TestEvents.py
@@ -13,7 +13,6 @@
 
 
 @skipIfLinux   # llvm.org/pr25924, sometimes generating SIGSEGV
-@skipIfDarwin
 class EventAPITestCase(TestBase):
 
 mydir = TestBase.compute_mydir(__file__)
@@ -171,9 +170,9 @@ def run(self):
 # Let's only try at most 3 times to retrieve any kind of event.
 while not count > 3:
 if listener.WaitForEvent(5, event):
-self.trace("Got a valid event:", event)
-self.trace("Event data flavor:", event.GetDataFlavor())
-self.trace("Event type:", 
lldbutil.state_type_to_str(event.GetType()))
+self.context.trace("Got a valid event:", event)
+self.context.trace("Event data flavor:", 
event.GetDataFlavor())
+self.context.trace("Event type:", 
lldbutil.state_type_to_str(event.GetType()))
 listener.Clear()
 return
 count = count + 1
@@ -187,6 +186,7 @@ def run(self):
 
 # Let's start the listening thread to retrieve the event.
 my_thread = MyListeningThread()
+my_thread.context = self
 my_thread.start()
 
 # Wait until the 'MyListeningThread' terminates.
@@ -256,7 +256,7 @@ def test_add_listener_to_broadcaster(self):
 class MyListeningThread(threading.Thread):
 
 def run(self):
-self.trace("Running MyListeningThread:", self)
+self.context.trace("Running MyListeningThread:", self)
 
 # Regular expression pattern for the event description.
 pattern = re.compile("data = {.*, state = (.*)}$")
@@ -266,7 +266,7 @@ def run(self):
 while True:
 if listener.WaitForEvent(5, event):
 desc = lldbutil.get_description(event)
-self.trace("Event description:", desc)
+self.context.trace("Event description:", desc)
 match = pattern.search(desc)
 if not match:
 break



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


[Lldb-commits] [lldb] 6eddd98 - [lldb/Plugin] Use static ScriptedInterface::ErrorWithMessage function (NFC)

2022-03-04 Thread Med Ismail Bennani via lldb-commits

Author: Med Ismail Bennani
Date: 2022-03-04T13:35:19-08:00
New Revision: 6eddd987c9c9d2ab76ed53eea452b34145992ed9

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

LOG: [lldb/Plugin] Use static ScriptedInterface::ErrorWithMessage function (NFC)

This patch replaces the calls to ErrorWithMessage using the GetInterface
message by a call to the static method directly.

Signed-off-by: Med Ismail Bennani 

Added: 


Modified: 
lldb/source/Plugins/Process/scripted/ScriptedThread.cpp

Removed: 




diff  --git a/lldb/source/Plugins/Process/scripted/ScriptedThread.cpp 
b/lldb/source/Plugins/Process/scripted/ScriptedThread.cpp
index 8174a8bde3315..e28f66015dd59 100644
--- a/lldb/source/Plugins/Process/scripted/ScriptedThread.cpp
+++ b/lldb/source/Plugins/Process/scripted/ScriptedThread.cpp
@@ -121,7 +121,7 @@ ScriptedThread::CreateRegisterContextForFrame(StackFrame 
*frame) {
 
   llvm::Optional reg_data = GetInterface()->GetRegisterContext();
   if (!reg_data)
-return GetInterface()->ErrorWithMessage(
+return ScriptedInterface::ErrorWithMessage(
 LLVM_PRETTY_FUNCTION, "Failed to get scripted thread registers data.",
 error, LLDBLog::Thread);
 
@@ -129,7 +129,7 @@ ScriptedThread::CreateRegisterContextForFrame(StackFrame 
*frame) {
   std::make_shared(reg_data->c_str(), reg_data->size()));
 
   if (!data_sp->GetByteSize())
-return GetInterface()->ErrorWithMessage(
+return ScriptedInterface::ErrorWithMessage(
 LLVM_PRETTY_FUNCTION, "Failed to copy raw registers data.", error,
 LLDBLog::Thread);
 
@@ -137,7 +137,7 @@ ScriptedThread::CreateRegisterContextForFrame(StackFrame 
*frame) {
   std::make_shared(
   *this, 0, *GetDynamicRegisterInfo(), LLDB_INVALID_ADDRESS);
   if (!reg_ctx_memory)
-return GetInterface()->ErrorWithMessage(
+return ScriptedInterface::ErrorWithMessage(
 LLVM_PRETTY_FUNCTION, "Failed to create a register context.", error,
 LLDBLog::Thread);
 
@@ -152,13 +152,13 @@ bool ScriptedThread::LoadArtificialStackFrames() {
 
   Status error;
   if (!arr_sp)
-return GetInterface()->ErrorWithMessage(
+return ScriptedInterface::ErrorWithMessage(
 LLVM_PRETTY_FUNCTION, "Failed to get scripted thread stackframes.",
 error, LLDBLog::Thread);
 
   size_t arr_size = arr_sp->GetSize();
   if (arr_size > std::numeric_limits::max())
-return GetInterface()->ErrorWithMessage(
+return ScriptedInterface::ErrorWithMessage(
 LLVM_PRETTY_FUNCTION,
 llvm::Twine(
 "StackFrame array size (" + llvm::Twine(arr_size) +
@@ -174,7 +174,7 @@ bool ScriptedThread::LoadArtificialStackFrames() {
 StructuredData::Dictionary *dict;
 
 if (!arr_sp->GetItemAtIndexAsDictionary(idx, dict) || !dict)
-  return GetInterface()->ErrorWithMessage(
+  return ScriptedInterface::ErrorWithMessage(
   LLVM_PRETTY_FUNCTION,
   llvm::Twine(
   "Couldn't get artificial stackframe dictionary at index (" +
@@ -203,7 +203,7 @@ bool ScriptedThread::LoadArtificialStackFrames() {
 StackFrame::Kind::Artificial, behaves_like_zeroth_frame, &sc);
 
 if (!frames->SetFrameAtIndex(static_cast(idx), synth_frame_sp))
-  return GetInterface()->ErrorWithMessage(
+  return ScriptedInterface::ErrorWithMessage(
   LLVM_PRETTY_FUNCTION,
   llvm::Twine("Couldn't add frame (" + llvm::Twine(idx) +
   llvm::Twine(") to ScriptedThread StackFrameList."))
@@ -219,7 +219,7 @@ bool ScriptedThread::CalculateStopInfo() {
 
   Status error;
   if (!dict_sp)
-return GetInterface()->ErrorWithMessage(
+return ScriptedInterface::ErrorWithMessage(
 LLVM_PRETTY_FUNCTION, "Failed to get scripted thread stop info.", 
error,
 LLDBLog::Thread);
 
@@ -227,14 +227,14 @@ bool ScriptedThread::CalculateStopInfo() {
   lldb::StopReason stop_reason_type;
 
   if (!dict_sp->GetValueForKeyAsInteger("type", stop_reason_type))
-return GetInterface()->ErrorWithMessage(
+return ScriptedInterface::ErrorWithMessage(
 LLVM_PRETTY_FUNCTION,
 "Couldn't find value for key 'type' in stop reason dictionary.", error,
 LLDBLog::Thread);
 
   StructuredData::Dictionary *data_dict;
   if (!dict_sp->GetValueForKeyAsDictionary("data", data_dict))
-return GetInterface()->ErrorWithMessage(
+return ScriptedInterface::ErrorWithMessage(
 LLVM_PRETTY_FUNCTION,
 "Couldn't find value for key 'data' in stop reason dictionary.", error,
 LLDBLog::Thread);
@@ -266,7 +266,7 @@ bool ScriptedThread::CalculateStopInfo() {
 StopInfo::CreateStopReasonWithException(*this, description.data());
   } break;
   default:
-return GetInterface()->ErrorWithMessage(
+return Scr

[Lldb-commits] [lldb] 680ca7f - [lldb/Plugins] Add ability to load modules to Scripted Processes

2022-03-04 Thread Med Ismail Bennani via lldb-commits

Author: Med Ismail Bennani
Date: 2022-03-04T13:35:28-08:00
New Revision: 680ca7f21a7716698227966a9e70e7efb75cff7e

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

LOG: [lldb/Plugins] Add ability to load modules to Scripted Processes

This patch introduces a new way to load modules programatically with
Scripted Processes. To do so, the scripted process blueprint holds a
list of dictionary describing the modules to load, which their path or
uuid, load address and eventually a slide offset.

LLDB will fetch that list after launching the ScriptedProcess, and
iterate over each entry to create the module that will be loaded in the
Scripted Process' target.

The patch also refactors the StackCoreScriptedProcess test to stop
inside the `libbaz` module and make sure it's loaded correctly and that
we can fetch some variables from it.

rdar://74520238

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

Signed-off-by: Med Ismail Bennani 

Added: 
lldb/test/API/functionalities/scripted_process/baz.c
lldb/test/API/functionalities/scripted_process/baz.h

Modified: 
lldb/examples/python/scripted_process/scripted_process.py
lldb/include/lldb/Interpreter/ScriptedProcessInterface.h
lldb/source/Plugins/Process/scripted/ScriptedProcess.cpp
lldb/source/Plugins/Process/scripted/ScriptedProcess.h

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

lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.h
lldb/test/API/functionalities/scripted_process/Makefile

lldb/test/API/functionalities/scripted_process/TestStackCoreScriptedProcess.py
lldb/test/API/functionalities/scripted_process/main.cpp

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

Removed: 




diff  --git a/lldb/examples/python/scripted_process/scripted_process.py 
b/lldb/examples/python/scripted_process/scripted_process.py
index 2d3092d70e8e0..5969737c8b4bd 100644
--- a/lldb/examples/python/scripted_process/scripted_process.py
+++ b/lldb/examples/python/scripted_process/scripted_process.py
@@ -19,7 +19,7 @@ class ScriptedProcess:
 memory_regions = None
 stack_memory_dump = None
 loaded_images = None
-threads = {}
+threads = None
 
 @abstractmethod
 def __init__(self, target, args):
@@ -41,6 +41,8 @@ def __init__(self, target, args):
 self.dbg = target.GetDebugger()
 if isinstance(args, lldb.SBStructuredData) and args.IsValid():
 self.args = args
+self.threads = {}
+self.loaded_images = []
 
 @abstractmethod
 def get_memory_region_containing_address(self, addr):
@@ -116,8 +118,7 @@ def get_loaded_images(self):
 
 ```
 class ScriptedProcessImage:
-def __init__(name, file_spec, uuid, load_address):
-  self.name = name
+def __init__(file_spec, uuid, load_address):
   self.file_spec = file_spec
   self.uuid = uuid
   self.load_address = load_address

diff  --git a/lldb/include/lldb/Interpreter/ScriptedProcessInterface.h 
b/lldb/include/lldb/Interpreter/ScriptedProcessInterface.h
index 0712b3bf4a3ee..26d285b3a3e08 100644
--- a/lldb/include/lldb/Interpreter/ScriptedProcessInterface.h
+++ b/lldb/include/lldb/Interpreter/ScriptedProcessInterface.h
@@ -57,7 +57,7 @@ class ScriptedProcessInterface : virtual public 
ScriptedInterface {
 return nullptr;
   }
 
-  virtual StructuredData::DictionarySP GetLoadedImages() { return nullptr; }
+  virtual StructuredData::ArraySP GetLoadedImages() { return nullptr; }
 
   virtual lldb::pid_t GetProcessID() { return LLDB_INVALID_PROCESS_ID; }
 

diff  --git a/lldb/source/Plugins/Process/scripted/ScriptedProcess.cpp 
b/lldb/source/Plugins/Process/scripted/ScriptedProcess.cpp
index 96ae305f875ad..e36b29db0feb5 100644
--- a/lldb/source/Plugins/Process/scripted/ScriptedProcess.cpp
+++ b/lldb/source/Plugins/Process/scripted/ScriptedProcess.cpp
@@ -170,6 +170,7 @@ Status ScriptedProcess::DoLaunch(Module *exe_module,
 void ScriptedProcess::DidLaunch() {
   CheckInterpreterAndScriptObject();
   m_pid = GetInterface().GetProcessID();
+  GetLoadedDynamicLibrariesInfos();
 }
 
 Status ScriptedProcess::DoResume() {
@@ -378,6 +379,93 @@ bool ScriptedProcess::GetProcessInfo(ProcessInstanceInfo 
&info) {
   return true;
 }
 
+lldb_private::StructuredData::ObjectSP
+ScriptedProcess::GetLoadedDynamicLibrariesInfos() {
+  CheckInterpreterAndScriptObject();
+
+  Status error;
+  auto error_with_message = [&error](llvm::StringRef message) {
+return ScriptedInterface::ErrorWithMessage(LLVM_PRETTY_FUNCTION,
+ message.data(), error);
+  };
+
+  StructuredData::ArraySP loaded_images

[Lldb-commits] [PATCH] D120969: [lldb/Plugins] Add ability to load modules to Scripted Processes

2022-03-04 Thread Med Ismail Bennani via Phabricator via lldb-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG680ca7f21a77: [lldb/Plugins] Add ability to load modules to 
Scripted Processes (authored by mib).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120969

Files:
  lldb/examples/python/scripted_process/scripted_process.py
  lldb/include/lldb/Interpreter/ScriptedProcessInterface.h
  lldb/source/Plugins/Process/scripted/ScriptedProcess.cpp
  lldb/source/Plugins/Process/scripted/ScriptedProcess.h
  
lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.cpp
  lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.h
  lldb/test/API/functionalities/scripted_process/Makefile
  lldb/test/API/functionalities/scripted_process/TestStackCoreScriptedProcess.py
  lldb/test/API/functionalities/scripted_process/baz.c
  lldb/test/API/functionalities/scripted_process/baz.h
  lldb/test/API/functionalities/scripted_process/main.cpp
  lldb/test/API/functionalities/scripted_process/stack_core_scripted_process.py

Index: lldb/test/API/functionalities/scripted_process/stack_core_scripted_process.py
===
--- lldb/test/API/functionalities/scripted_process/stack_core_scripted_process.py
+++ lldb/test/API/functionalities/scripted_process/stack_core_scripted_process.py
@@ -7,13 +7,19 @@
 from lldb.plugins.scripted_process import ScriptedThread
 
 class StackCoreScriptedProcess(ScriptedProcess):
+def get_module_with_name(self, target, name):
+for module in target.modules:
+if name in module.GetFileSpec().GetFilename():
+return module
+return None
+
 def __init__(self, target: lldb.SBTarget, args : lldb.SBStructuredData):
 super().__init__(target, args)
 
-self.backing_target_idx = args.GetValueForKey("backing_target_idx")
-
 self.corefile_target = None
 self.corefile_process = None
+
+self.backing_target_idx = args.GetValueForKey("backing_target_idx")
 if (self.backing_target_idx and self.backing_target_idx.IsValid()):
 if self.backing_target_idx.GetType() == lldb.eStructuredDataTypeInteger:
 idx = self.backing_target_idx.GetIntegerValue(42)
@@ -30,9 +36,22 @@
 
 self.threads[corefile_thread.GetThreadID()] = StackCoreScriptedThread(self, structured_data)
 
-if len(self.threads) == 3:
+if len(self.threads) == 2:
 self.threads[len(self.threads) - 1].is_stopped = True
 
+corefile_module = self.get_module_with_name(self.corefile_target,
+"libbaz.dylib")
+if not corefile_module or not corefile_module.IsValid():
+return
+module_path = os.path.join(corefile_module.GetFileSpec().GetDirectory(),
+   corefile_module.GetFileSpec().GetFilename())
+if not os.path.exists(module_path):
+return
+module_load_addr = corefile_module.GetObjectFileHeaderAddress().GetLoadAddress(self.corefile_target)
+
+self.loaded_images.append({"path": module_path,
+   "load_addr": module_load_addr})
+
 def get_memory_region_containing_address(self, addr: int) -> lldb.SBMemoryRegionInfo:
 mem_region = lldb.SBMemoryRegionInfo()
 error = self.corefile_process.GetMemoryRegionInfo(addr, mem_region)
@@ -61,8 +80,6 @@
 return data
 
 def get_loaded_images(self):
-# TODO: Iterate over corefile_target modules and build a data structure
-# from it.
 return self.loaded_images
 
 def get_process_id(self) -> int:
Index: lldb/test/API/functionalities/scripted_process/main.cpp
===
--- lldb/test/API/functionalities/scripted_process/main.cpp
+++ lldb/test/API/functionalities/scripted_process/main.cpp
@@ -2,16 +2,20 @@
 #include 
 #include 
 
+extern "C" {
+int baz(int);
+}
+
 int bar(int i) {
   int j = i * i;
-  return j; // break here
+  return j;
 }
 
 int foo(int i) { return bar(i); }
 
 void call_and_wait(int &n) {
   std::cout << "waiting for computation!" << std::endl;
-  while (n != 42 * 42)
+  while (baz(n) != 42)
 ;
   std::cout << "finished computation!" << std::endl;
 }
Index: lldb/test/API/functionalities/scripted_process/baz.h
===
--- /dev/null
+++ lldb/test/API/functionalities/scripted_process/baz.h
@@ -0,0 +1,3 @@
+#pragma once
+
+int baz(int j);
Index: lldb/test/API/functionalities/scripted_process/baz.c
===
--- /dev/null
+++ lldb/test/API/functionalities/scripted_process/baz.c
@@ -0,0 +1,8 @@
+#include "baz.h"
+
+#include 
+
+int baz(int j) {
+  int k = sqrt(j);
+  return k; // break her

[Lldb-commits] [lldb] b934ed7 - revert "[lldb/Host] Fix crash in FileSystem::IsLocal"

2022-03-04 Thread Med Ismail Bennani via lldb-commits

Author: Med Ismail Bennani
Date: 2022-03-04T13:36:36-08:00
New Revision: b934ed7dd6351404d375af2f996af8a49ea36c7b

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

LOG: revert "[lldb/Host] Fix crash in FileSystem::IsLocal"

This reverts commit 2dc6e906b09deb092c15a726c06d0ecbeec1eb18 following
changes introduced in 59eb70527741594fe3c92d0a1b6704ed45111437.

Added: 


Modified: 
lldb/source/Host/common/FileSystem.cpp

Removed: 




diff  --git a/lldb/source/Host/common/FileSystem.cpp 
b/lldb/source/Host/common/FileSystem.cpp
index 2367a641e9350..358274e9d2fb1 100644
--- a/lldb/source/Host/common/FileSystem.cpp
+++ b/lldb/source/Host/common/FileSystem.cpp
@@ -171,8 +171,7 @@ bool FileSystem::IsDirectory(const FileSpec &file_spec) 
const {
 
 bool FileSystem::IsLocal(const Twine &path) const {
   bool b = false;
-  if (m_fs)
-m_fs->isLocal(path, b);
+  m_fs->isLocal(path, b);
   return b;
 }
 



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


[Lldb-commits] [lldb] b5491dd - ObjectFile: add a case for `EM_RISCV`

2022-03-04 Thread Saleem Abdulrasool via lldb-commits

Author: Saleem Abdulrasool
Date: 2022-03-04T21:54:20Z
New Revision: b5491dd30792c1ad31bfc8e2f9d1809a79205234

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

LOG: ObjectFile: add a case for `EM_RISCV`

This adds the jump slot mapping for RISCV.  This enables lldb to attach to a
remote debug server.  Although this doesn't enable debugging RISCV targets, it
is sufficient to attach, which is a slight improvement.

Tested with DebugServer2:
~~~
(lldb) gdb-remote localhost:1234
(lldb) Process 71438 stopped
* thread #1, name = 'reduced', stop reason = signal SIGTRAP
frame #0: 0x003ff7fe1b20

error: Process 71438 is currently being debugged, kill the process before 
connecting.
(lldb) register read
general:
x0 = 0x003ff7fe1b20
x1 = 0x002ae00d3a50
x2 = 0x003ff3e0
x3 = 0x002ae01566e0
x4 = 0x003fe567c7b0
x5 = 0x1000
x6 = 0x002ae00604ec
x7 = 0x03ff
x8 = 0x003fffc22db0
x9 = 0x
   x10 = 0x
   x11 = 0x002ae603b1c0
   x12 = 0x002ae6039350
   x13 = 0x
   x14 = 0x002ae6039350
   x15 = 0x002ae6039350
   x16 = 0x73642f74756f3d5f
   x17 = 0x00dd
   x18 = 0x002ae6038f08
   x19 = 0x002ae603b1c0
   x20 = 0x002b0f3d3f40
   x21 = 0x003ff0b212d0
   x22 = 0x002b0f3a2740
   x23 = 0x002b0f3de3a0
   x24 = 0x002b0f3d3f40
   x25 = 0x002ad6929850
   x26 = 0x
   x27 = 0x002ad69297c0
   x28 = 0x003fe578b364
   x29 = 0x002f
   x30 = 0x
   x31 = 0x002ae602401a
pc = 0x003ff7fe1b20
   ft0 = 0
   ft1 = 0
   ft2 = 0
   ft3 = 0
   ft4 = 0
   ft5 = 0
   ft6 = 0
   ft7 = 0
   fs0 = 0
   fs1 = 0
   fa0 = 0
   fa1 = 0
   fa2 = 0
   fa3 = 0
   fa4 = 0
   fa5 = 0
   fa6 = 0
   fa7 = 9.10304232197721e-313
   fs2 = 0
   fs3 = 1.35805727667792e-312
   fs4 = 1.35589259164679e-312
   fs5 = 1.35805727659887e-312
   fs6 = 9.10304232355822e-313
   fs7 = 0
   fs8 = 9.10304233027751e-313
   fs9 = 0
  fs10 = 9.10304232948701e-313
  fs11 = 1.35588724164707e-312
   ft8 = 0
   ft9 = 9.1372158616833e-313
  ft10 = 9.13720376537528e-313
  ft11 = 1.356808717416e-312
3 registers were unavailable.

(lldb) disassemble
error: Failed to disassemble memory at 0x3ff7fe1b2
~~~

Added: 


Modified: 
lldb/source/Plugins/ObjectFile/ELF/ELFHeader.cpp

Removed: 




diff  --git a/lldb/source/Plugins/ObjectFile/ELF/ELFHeader.cpp 
b/lldb/source/Plugins/ObjectFile/ELF/ELFHeader.cpp
index f0496beba2ef4..abda0cd0e9a38 100644
--- a/lldb/source/Plugins/ObjectFile/ELF/ELFHeader.cpp
+++ b/lldb/source/Plugins/ObjectFile/ELF/ELFHeader.cpp
@@ -208,6 +208,9 @@ unsigned ELFHeader::GetRelocationJumpSlotType() const {
   case EM_S390:
 slot = R_390_JMP_SLOT;
 break;
+  case EM_RISCV:
+slot = R_RISCV_JUMP_SLOT;
+break;
   }
 
   return slot;



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


[Lldb-commits] [lldb] 86e6030 - [lldb/Test] Disable test_scripted_process_and_scripted_thread on Windows

2022-03-04 Thread Med Ismail Bennani via lldb-commits

Author: Med Ismail Bennani
Date: 2022-03-04T14:56:20-08:00
New Revision: 86e6030ee8f8758f6e0807fc39a1aa0d8a03b68f

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

LOG: [lldb/Test] Disable test_scripted_process_and_scripted_thread on Windows

This disables TestScriptedProcess.test_scripted_process_and_scripted_thread
on Windows since the inferior binary a linked to a dylib that doesn't
build on Windows.

This should fix https://lab.llvm.org/buildbot/#/builders/83/builds/16100

Signed-off-by: Med Ismail Bennani 

Added: 


Modified: 
lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py

Removed: 




diff  --git 
a/lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py 
b/lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
index a622722cd92e1..a3b01c5c58e0c 100644
--- a/lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
+++ b/lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
@@ -80,7 +80,7 @@ def cleanup():
 
 self.assertIn("Failed to get scripted thread registers data.", log)
 
-@skipIf(archs=no_match(['x86_64', 'arm64', 'arm64e']))
+@skipUnlessDarwin
 def test_scripted_process_and_scripted_thread(self):
 """Test that we can launch an lldb scripted process using the SBAPI,
 check its process ID, read string from memory, check scripted thread



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


[Lldb-commits] [PATCH] D120972: [lldb] Show progress events in the command line driver

2022-03-04 Thread Adrian Prantl via Phabricator via lldb-commits
aprantl added a comment.

This is pretty (and) awesome.




Comment at: lldb/source/Core/Debugger.cpp:1670
+if (event_type & Debugger::eBroadcastBitProgress)
+  HandleProgressEvent(event_sp);
   }

side note: this function could benefit from some early exits.



Comment at: lldb/source/Core/Debugger.cpp:1762
+  if (data->GetCompleted()) {
+output.Printf("\33[2K\r");
+return;

I guess Colors also implies it supports \r? Sure.
Can you comment what this escape sequence does?


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

https://reviews.llvm.org/D120972

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


[Lldb-commits] [PATCH] D120972: [lldb] Show progress events in the command line driver

2022-03-04 Thread Adrian Prantl via Phabricator via lldb-commits
aprantl added inline comments.



Comment at: lldb/source/Core/Debugger.cpp:1757
+  File &output = GetOutputFile();
+  if (!output.GetIsTerminalWithColors() || !GetShowProgress())
+return;

And withColors also implies that it's an interactive TTY?


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

https://reviews.llvm.org/D120972

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


[Lldb-commits] [PATCH] D120972: [lldb] Show progress events in the command line driver

2022-03-04 Thread Jonas Devlieghere via Phabricator via lldb-commits
JDevlieghere marked 2 inline comments as done.
JDevlieghere added inline comments.



Comment at: lldb/source/Core/Debugger.cpp:1757
+  File &output = GetOutputFile();
+  if (!output.GetIsTerminalWithColors() || !GetShowProgress())
+return;

aprantl wrote:
> And withColors also implies that it's an interactive TTY?
Yup



Comment at: lldb/source/Core/Debugger.cpp:1762
+  if (data->GetCompleted()) {
+output.Printf("\33[2K\r");
+return;

aprantl wrote:
> I guess Colors also implies it supports \r? Sure.
> Can you comment what this escape sequence does?
The comment on line 1760 explains that this clears the current line. I can move 
it down to make it more obvious.


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

https://reviews.llvm.org/D120972

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


[Lldb-commits] [PATCH] D120972: [lldb] Show progress events in the command line driver

2022-03-04 Thread Jonas Devlieghere via Phabricator via lldb-commits
JDevlieghere updated this revision to Diff 413159.
JDevlieghere marked 2 inline comments as done.
JDevlieghere added a comment.

- Make sure the output is both interactive and supports colors
- Add more comments


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

https://reviews.llvm.org/D120972

Files:
  lldb/include/lldb/Core/Debugger.h
  lldb/source/Core/CoreProperties.td
  lldb/source/Core/Debugger.cpp
  lldb/source/Symbol/LocateSymbolFile.cpp

Index: lldb/source/Symbol/LocateSymbolFile.cpp
===
--- lldb/source/Symbol/LocateSymbolFile.cpp
+++ lldb/source/Symbol/LocateSymbolFile.cpp
@@ -10,6 +10,7 @@
 
 #include "lldb/Core/ModuleList.h"
 #include "lldb/Core/ModuleSpec.h"
+#include "lldb/Core/Progress.h"
 #include "lldb/Host/FileSystem.h"
 #include "lldb/Symbol/ObjectFile.h"
 #include "lldb/Utility/ArchSpec.h"
@@ -262,6 +263,10 @@
   FileSystem::Instance().Exists(symbol_file_spec))
 return symbol_file_spec;
 
+  Progress progress(llvm::formatv(
+  "Locating external symbol file for {0}",
+  module_spec.GetFileSpec().GetFilename().AsCString("")));
+
   FileSpecList debug_file_search_paths = default_search_paths;
 
   // Add module directory.
Index: lldb/source/Core/Debugger.cpp
===
--- lldb/source/Core/Debugger.cpp
+++ lldb/source/Core/Debugger.cpp
@@ -378,6 +378,12 @@
   return ret;
 }
 
+bool Debugger::GetShowProgress() const {
+  const uint32_t idx = ePropertyShowProgress;
+  return m_collection_sp->GetPropertyAtIndexAsBoolean(
+  nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
+}
+
 bool Debugger::GetUseAutosuggestion() const {
   const uint32_t idx = ePropertyShowAutosuggestion;
   return m_collection_sp->GetPropertyAtIndexAsBoolean(
@@ -1605,6 +1611,11 @@
   CommandInterpreter::eBroadcastBitAsynchronousOutputData |
   CommandInterpreter::eBroadcastBitAsynchronousErrorData);
 
+  if (!m_broadcaster.EventTypeHasListeners(Debugger::eBroadcastBitProgress)) {
+listener_sp->StartListeningForEvents(&m_broadcaster,
+ Debugger::eBroadcastBitProgress);
+  }
+
   // Let the thread that spawned us know that we have started up and that we
   // are now listening to all required events so no events get missed
   m_sync_broadcaster.BroadcastEvent(eBroadcastBitEventThreadIsListening);
@@ -1654,6 +1665,9 @@
 }
   }
 }
+  } else if (broadcaster == &m_broadcaster) {
+if (event_type & Debugger::eBroadcastBitProgress)
+  HandleProgressEvent(event_sp);
   }
 }
 
@@ -1719,6 +1733,61 @@
   return {};
 }
 
+void Debugger::HandleProgressEvent(const lldb::EventSP &event_sp) {
+  auto *data =
+  Debugger::ProgressEventData::GetEventDataFromEvent(event_sp.get());
+  if (!data)
+return;
+
+  // Do some bookkeeping for the current event, regardless of whether we're
+  // going to show the progress.
+  const uint64_t id = data->GetID();
+  if (m_current_event_id) {
+if (id != *m_current_event_id)
+  return;
+if (data->GetCompleted())
+  m_current_event_id.reset();
+  } else {
+m_current_event_id = id;
+  }
+
+  // Decide whether we actually are going to show the progress. This decision
+  // can change between iterations so check it inside the loop.
+  if (!GetShowProgress())
+return;
+
+  // Determine whether the current output file is an interactive terminal with
+  // color support. We assume that if we support ANSI escape codes we support
+  // vt100 escape codes.
+  File &output = GetOutputFile();
+  if (!output.GetIsInteractive() || !output.GetIsTerminalWithColors())
+return;
+
+  if (data->GetCompleted()) {
+// Clear the current line.
+output.Printf("\33[2K\r");
+return;
+  }
+
+  // Print over previous line, if any.
+  output.Printf("\r");
+
+  // Print the progress message.
+  std::string message = data->GetMessage();
+  if (data->GetTotal() != UINT64_MAX) {
+output.Printf("[%llu/%llu] %s...", data->GetCompleted(), data->GetTotal(),
+  message.c_str());
+  } else {
+output.Printf("%s...", message.c_str());
+  }
+
+  // Clear until the end of the line.
+  output.Printf("\x1B[K");
+
+  // Flush the output.
+  output.Flush();
+}
+
 bool Debugger::HasIOHandlerThread() { return m_io_handler_thread.IsJoinable(); }
 
 bool Debugger::StartIOHandlerThread() {
Index: lldb/source/Core/CoreProperties.td
===
--- lldb/source/Core/CoreProperties.td
+++ lldb/source/Core/CoreProperties.td
@@ -131,6 +131,10 @@
 Global,
 DefaultTrue,
 Desc<"Whether to use Ansi color codes or not.">;
+  def ShowProgress: Property<"show-progress", "Boolean">,
+Global,
+DefaultTrue,
+Desc<"Whether to show progress or not.">;
   def UseSourceCache: Property<"use-source-cache", "B

[Lldb-commits] [PATCH] D120972: [lldb] Show progress events in the command line driver

2022-03-04 Thread Jonas Devlieghere via Phabricator via lldb-commits
JDevlieghere added inline comments.



Comment at: lldb/source/Core/Debugger.cpp:1757
+  File &output = GetOutputFile();
+  if (!output.GetIsTerminalWithColors() || !GetShowProgress())
+return;

JDevlieghere wrote:
> aprantl wrote:
> > And withColors also implies that it's an interactive TTY?
> Yup
Actually, I thought it did based on the docs, but looking at the implementation 
it's tracked by two different properties. 


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

https://reviews.llvm.org/D120972

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


[Lldb-commits] [lldb] 999e754 - [lldb/Test] Fix test_launch_scripted_process_stack_frames failure

2022-03-04 Thread Med Ismail Bennani via lldb-commits

Author: Med Ismail Bennani
Date: 2022-03-04T16:22:53-08:00
New Revision: 999e75476ec22ca50cc4c309d34424fa265e244a

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

LOG: [lldb/Test] Fix test_launch_scripted_process_stack_frames failure

This should fix the test_launch_scripted_process_stack_frames GreenDragon
test failure : https://green.lab.llvm.org/green/job/lldb-cmake/41901

Signed-off-by: Med Ismail Bennani 

Added: 


Modified: 

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

Removed: 




diff  --git 
a/lldb/test/API/functionalities/scripted_process/TestStackCoreScriptedProcess.py
 
b/lldb/test/API/functionalities/scripted_process/TestStackCoreScriptedProcess.py
index b24648e80f1d8..9f1c055c7ee96 100644
--- 
a/lldb/test/API/functionalities/scripted_process/TestStackCoreScriptedProcess.py
+++ 
b/lldb/test/API/functionalities/scripted_process/TestStackCoreScriptedProcess.py
@@ -120,6 +120,9 @@ def cleanup():
 self.assertEqual(int(frame.vars.GetFirstValueByName('j').GetValue()), 
42 * 42)
 self.assertEqual(int(frame.vars.GetFirstValueByName('k').GetValue()), 
42)
 
+corefile_dylib = self.get_module_with_name(corefile_target, 
'libbaz.dylib')
+self.assertTrue(corefile_dylib, "Dynamic library libbaz.dylib not 
found.")
 scripted_dylib = self.get_module_with_name(target, 'libbaz.dylib')
 self.assertTrue(scripted_dylib, "Dynamic library libbaz.dylib not 
found.")
-
self.assertEqual(scripted_dylib.GetObjectFileHeaderAddress().GetLoadAddress(target),
 0x1001e)
+
self.assertEqual(scripted_dylib.GetObjectFileHeaderAddress().GetLoadAddress(target),
+ 
corefile_dylib.GetObjectFileHeaderAddress().GetLoadAddress(target))



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


[Lldb-commits] [PATCH] D121036: Fix target.save-jit-objects when the CWD is not writeable

2022-03-04 Thread Jim Ingham via Phabricator via lldb-commits
jingham created this revision.
jingham added reviewers: clayborg, labath, JDevlieghere.
Herald added a project: All.
jingham requested review of this revision.
Herald added a project: LLDB.
Herald added a subscriber: lldb-commits.

One of the diagnostic outputs for the expression parser is the jit objects.  
The way you used to produce these was to set "target.save-jit-objects" to true 
and the files would get dumped into the CWD.  That's not going to work if the 
CWD is not writeable (which for GUI apps on macOS is almost always true).

It's also a little annoying to dump them unconditionally in the CWD rather than 
letting the user specify a directory.

So this patch changes `target.save-jit-objects` to 
`target.save-jit-objects-dir`.  If this is empty we do nothing and if it has a 
path we put the files there.

That part seems straightforward, but I also try to validate that the path you 
provided is good.  The checking part again is easy, but there are three tricky 
bits, one of which I resolved and two of which I punted.

1. If you want to add a ValueChanged callback to a setting, you need to put the 
callback into the global properties so you can check when the setting is done 
before you have a target.  But you also need to insert it into the copy that 
the target gets, however the callback captures the TargetProperties object it 
is going to inspect, that's how it knows what to work on, so the callback has 
to be different.  That's actually fine, except that we have an assert if you 
try to overwrite a callback.   That assert has been there forever, but I don't 
know why, and in this case it is something you need to do.  So I removed the 
assert.

2. When we find an incorrect save directory I would like to inform the user 
that something is wrong.  That works for the Target's local copy, because I can 
get the Debugger and use its ErrorOutput.  But the Global copy of the 
TargetProperty objects doesn't have links back to anything that can be 
informed.  I don't have a good way to solve this currently.  You can't use the 
Debugger that caused the creation of the global properties since it might no 
longer be around.

I could add the hack of "If there's only one debugger, tell it" which would 
work for command line lldb.  I didn't do that yet in this patch but if there 
aren't any better ideas I am willing to add that.  It seem unfriendly to spray 
it across all the debuggers...

3. A better way to fix this would probably be to allow the ValueChanged 
callbacks to report an error back up to whoever it trying to change the value, 
which in the end would result in a "settings set" error.  But that's way more 
infrastructure than I can invest in right now.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D121036

Files:
  lldb/include/lldb/Interpreter/OptionValue.h
  lldb/include/lldb/Target/Target.h
  lldb/source/Expression/IRExecutionUnit.cpp
  lldb/source/Target/Target.cpp
  lldb/source/Target/TargetProperties.td
  lldb/test/API/commands/expression/save_jit_objects/TestSaveJITObjects.py

Index: lldb/test/API/commands/expression/save_jit_objects/TestSaveJITObjects.py
===
--- lldb/test/API/commands/expression/save_jit_objects/TestSaveJITObjects.py
+++ lldb/test/API/commands/expression/save_jit_objects/TestSaveJITObjects.py
@@ -38,14 +38,14 @@
 self.cleanJITFiles()
 frame.EvaluateExpression("(void*)malloc(0x1)")
 self.assertEquals(self.countJITFiles(), 0,
-"No files emitted with save-jit-objects=false")
-
-self.runCmd("settings set target.save-jit-objects true")
+"No files emitted with save-jit-objects-dir empty")
+
+self.runCmd("settings set target.save-jit-objects-dir {0}".format(self.getBuildDir()))
 frame.EvaluateExpression("(void*)malloc(0x1)")
 jit_files_count = self.countJITFiles()
 self.cleanJITFiles()
 self.assertNotEqual(jit_files_count, 0,
-"At least one file emitted with save-jit-objects=true")
+"At least one file emitted with save-jit-objects-dir set to the build dir")
 
 process.Kill()
 os.chdir(self.getSourceDir())
Index: lldb/source/Target/TargetProperties.td
===
--- lldb/source/Target/TargetProperties.td
+++ lldb/source/Target/TargetProperties.td
@@ -63,9 +63,9 @@
   def NotifyAboutFixIts: Property<"notify-about-fixits", "Boolean">,
 DefaultTrue,
 Desc<"Print the fixed expression text.">;
-  def SaveObjects: Property<"save-jit-objects", "Boolean">,
-DefaultFalse,
-Desc<"Save intermediate object files generated by the LLVM JIT">;
+  def SaveObjectsDir: Property<"save-jit-objects-dir", "FileSpec">,
+DefaultStringValue<"">,
+Desc<"If specified, the directory to save intermediate object files generated by the LLVM JIT">;
   def MaxZeroP

[Lldb-commits] [PATCH] D121036: Fix target.save-jit-objects when the CWD is not writeable

2022-03-04 Thread Jim Ingham via Phabricator via lldb-commits
jingham added a comment.

I tried emitting an error when you go to write the file, but the way this is 
layered this just comes out as a string somewhere in the middle of the 
expression output, and ended up being noisy and confusing.  I think it's better 
to validate the value on input.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121036

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


[Lldb-commits] [PATCH] D121038: [lldb/crashlog] Make interactive mode display more user-friendly

2022-03-04 Thread Med Ismail Bennani via Phabricator via lldb-commits
mib created this revision.
mib added a reviewer: JDevlieghere.
mib added a project: LLDB.
Herald added a project: All.
mib requested review of this revision.
Herald added a subscriber: lldb-commits.

This patch makes the crashlog interactive mode show the scripted process
status with the crashed scripted thread backtrace after launching it.

rdar://89634338

Signed-off-by: Med Ismail Bennani 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D121038

Files:
  lldb/examples/python/crashlog.py
  lldb/test/Shell/ScriptInterpreter/Python/Crashlog/scripted_crashlog_json.test


Index: 
lldb/test/Shell/ScriptInterpreter/Python/Crashlog/scripted_crashlog_json.test
===
--- 
lldb/test/Shell/ScriptInterpreter/Python/Crashlog/scripted_crashlog_json.test
+++ 
lldb/test/Shell/ScriptInterpreter/Python/Crashlog/scripted_crashlog_json.test
@@ -4,9 +4,17 @@
 
 # RUN: cp %S/Inputs/scripted_crashlog.ips %t.crash
 # RUN: %python %S/patch-crashlog.py --binary %t.out --crashlog %t.crash 
--offsets '{"main":20, "bar":9, "foo":16}' --json
-# RUN: %lldb %t.out -o 'command script import lldb.macosx.crashlog' -o 
'crashlog -i %t.crash' -o 'process status' 2>&1 | FileCheck %s
+# RUN: %lldb %t.out -o 'command script import lldb.macosx.crashlog' -o 
'crashlog -i %t.crash' 2>&1 | FileCheck %s
 
 # CHECK: "crashlog" {{.*}} commands have been installed, use the "--help" 
options on these commands
-# CHECK: Process 92190 stopped
-# CHECK: * thread #1, name = 'CrashLogScriptedThread.thread-0', stop reason = 
EXC_BAD_ACCESS
-# CHECK: frame #0: 0x000104a23f68 scripted_crashlog_json.test.tmp.out`foo 
at test.c:3:6 [artificial]
+# CHECK: (lldb) process status
+# CHECK-NEXT: Process 92190 stopped
+# CHECK-NEXT: * thread #1, name = 'CrashLogScriptedThread.thread-0', stop 
reason = EXC_BAD_ACCESS
+# CHECK-NEXT: frame #0: 0x000104a23f68 
scripted_crashlog_json.test.tmp.out`foo at test.c:3:6 [artificial]
+
+# CHECK: (lldb) thread backtrace
+# CHECK-NEXT: * thread #1, name = 'CrashLogScriptedThread.thread-0', stop 
reason = EXC_BAD_ACCESS
+# CHECK-NEXT: * frame #0: 0x000104a23f68 
scripted_crashlog_json.test.tmp.out`foo at test.c:3:6 [artificial]
+# CHECK-NEXT: frame #1: 0x000104a23f80 
scripted_crashlog_json.test.tmp.out`bar at test.c:6:21 [artificial]
+# CHECK-NEXT: frame #2: 0x000104a23fa0 
scripted_crashlog_json.test.tmp.out`main(argc=, 
argv=) at test.c:8:35 [artificial]
+# CHECK-NEXT: frame #3: 0x000104a6108c dyld`start(kernArgs=) at dyldMain.cpp:879:18 [opt] [artificial]
Index: lldb/examples/python/crashlog.py
===
--- lldb/examples/python/crashlog.py
+++ lldb/examples/python/crashlog.py
@@ -1017,6 +1017,29 @@
 error = lldb.SBError()
 process = target.Launch(launch_info, error)
 
+if not process or error.Fail():
+return
+
+res = lldb.SBCommandReturnObject()
+exe_ctx = lldb.SBExecutionContext(process.GetSelectedThread())
+cmd = "process status"
+ci.HandleCommand(cmd, exe_ctx, res)
+if not res.Succeeded():
+result.PutCString("error: couldn't show scripted process status")
+return
+print(debugger.GetPrompt(), cmd, sep='')
+print(res.GetOutput())
+
+res = lldb.SBCommandReturnObject()
+cmd = "thread backtrace"
+ci.HandleCommand(cmd, exe_ctx, res)
+if not res.Succeeded():
+result.PutCString("error: couldn't show scripted thread backtrace")
+return
+print(debugger.GetPrompt(), cmd, sep='')
+print(res.GetOutput())
+
+
 def CreateSymbolicateCrashLogOptions(
 command_name,
 description,


Index: lldb/test/Shell/ScriptInterpreter/Python/Crashlog/scripted_crashlog_json.test
===
--- lldb/test/Shell/ScriptInterpreter/Python/Crashlog/scripted_crashlog_json.test
+++ lldb/test/Shell/ScriptInterpreter/Python/Crashlog/scripted_crashlog_json.test
@@ -4,9 +4,17 @@
 
 # RUN: cp %S/Inputs/scripted_crashlog.ips %t.crash
 # RUN: %python %S/patch-crashlog.py --binary %t.out --crashlog %t.crash --offsets '{"main":20, "bar":9, "foo":16}' --json
-# RUN: %lldb %t.out -o 'command script import lldb.macosx.crashlog' -o 'crashlog -i %t.crash' -o 'process status' 2>&1 | FileCheck %s
+# RUN: %lldb %t.out -o 'command script import lldb.macosx.crashlog' -o 'crashlog -i %t.crash' 2>&1 | FileCheck %s
 
 # CHECK: "crashlog" {{.*}} commands have been installed, use the "--help" options on these commands
-# CHECK: Process 92190 stopped
-# CHECK: * thread #1, name = 'CrashLogScriptedThread.thread-0', stop reason = EXC_BAD_ACCESS
-# CHECK: frame #0: 0x000104a23f68 scripted_crashlog_json.test.tmp.out`foo at test.c:3:6 [artificial]
+# CHECK: (lldb) process status
+# CHECK-NEXT: Process 92190 stopped
+# CHECK-NEXT: * thread #1, name = 'CrashLogScriptedThread.thread-0', stop reason = EXC_BAD_ACCESS
+# CHECK-NEXT: frame #0: 0x000104a23f68 s

[Lldb-commits] [PATCH] D121036: Fix target.save-jit-objects when the CWD is not writeable

2022-03-04 Thread Jim Ingham via Phabricator via lldb-commits
jingham updated this revision to Diff 413185.
jingham added a comment.

I added the if there's only one debugger hack, so this will work fine in the 
driver.


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

https://reviews.llvm.org/D121036

Files:
  lldb/include/lldb/Interpreter/OptionValue.h
  lldb/include/lldb/Target/Target.h
  lldb/source/Expression/IRExecutionUnit.cpp
  lldb/source/Target/Target.cpp
  lldb/source/Target/TargetProperties.td
  lldb/test/API/commands/expression/save_jit_objects/TestSaveJITObjects.py

Index: lldb/test/API/commands/expression/save_jit_objects/TestSaveJITObjects.py
===
--- lldb/test/API/commands/expression/save_jit_objects/TestSaveJITObjects.py
+++ lldb/test/API/commands/expression/save_jit_objects/TestSaveJITObjects.py
@@ -38,14 +38,14 @@
 self.cleanJITFiles()
 frame.EvaluateExpression("(void*)malloc(0x1)")
 self.assertEquals(self.countJITFiles(), 0,
-"No files emitted with save-jit-objects=false")
-
-self.runCmd("settings set target.save-jit-objects true")
+"No files emitted with save-jit-objects-dir empty")
+
+self.runCmd("settings set target.save-jit-objects-dir {0}".format(self.getBuildDir()))
 frame.EvaluateExpression("(void*)malloc(0x1)")
 jit_files_count = self.countJITFiles()
 self.cleanJITFiles()
 self.assertNotEqual(jit_files_count, 0,
-"At least one file emitted with save-jit-objects=true")
+"At least one file emitted with save-jit-objects-dir set to the build dir")
 
 process.Kill()
 os.chdir(self.getSourceDir())
Index: lldb/source/Target/TargetProperties.td
===
--- lldb/source/Target/TargetProperties.td
+++ lldb/source/Target/TargetProperties.td
@@ -63,9 +63,9 @@
   def NotifyAboutFixIts: Property<"notify-about-fixits", "Boolean">,
 DefaultTrue,
 Desc<"Print the fixed expression text.">;
-  def SaveObjects: Property<"save-jit-objects", "Boolean">,
-DefaultFalse,
-Desc<"Save intermediate object files generated by the LLVM JIT">;
+  def SaveObjectsDir: Property<"save-jit-objects-dir", "FileSpec">,
+DefaultStringValue<"">,
+Desc<"If specified, the directory to save intermediate object files generated by the LLVM JIT">;
   def MaxZeroPaddingInFloatFormat: Property<"max-zero-padding-in-float-format", "UInt64">,
 DefaultUnsignedValue<6>,
 Desc<"The maximum number of zeroes to insert when displaying a very small float before falling back to scientific notation.">;
Index: lldb/source/Target/Target.cpp
===
--- lldb/source/Target/Target.cpp
+++ lldb/source/Target/Target.cpp
@@ -3814,6 +3814,8 @@
 m_collection_sp->SetValueChangedCallback(
 ePropertyDisableSTDIO, [this] { DisableSTDIOValueChangedCallback(); });
 
+m_collection_sp->SetValueChangedCallback(
+ePropertySaveObjectsDir, [this] { CheckJITObjectsDir(); });
 m_experimental_properties_up =
 std::make_unique();
 m_collection_sp->AppendProperty(
@@ -3835,6 +3837,8 @@
 m_collection_sp->AppendProperty(
 ConstString("process"), ConstString("Settings specific to processes."),
 true, Process::GetGlobalProperties().GetValueProperties());
+m_collection_sp->SetValueChangedCallback(
+ePropertySaveObjectsDir, [this] { CheckJITObjectsDir(); });
   }
 }
 
@@ -4164,10 +4168,41 @@
   nullptr, idx, g_target_properties[idx].default_uint_value != 0);
 }
 
-bool TargetProperties::GetEnableSaveObjects() const {
-  const uint32_t idx = ePropertySaveObjects;
-  return m_collection_sp->GetPropertyAtIndexAsBoolean(
-  nullptr, idx, g_target_properties[idx].default_uint_value != 0);
+FileSpec TargetProperties::GetSaveJITObjectsDir() const {
+  const uint32_t idx = ePropertySaveObjectsDir;
+  return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
+}
+
+void TargetProperties::CheckJITObjectsDir() {
+  const uint32_t idx = ePropertySaveObjectsDir;
+  FileSpec new_dir = GetSaveJITObjectsDir();
+  const FileSystem &instance = FileSystem::Instance();
+  bool exists = instance.Exists(new_dir);
+  bool is_directory = instance.IsDirectory(new_dir);
+  std::string path = new_dir.GetPath(true);
+  bool writable = llvm::sys::fs::can_write(path);
+  if (!exists || ! is_directory || !writable) {
+m_collection_sp->GetPropertyAtIndex(nullptr, true, idx)->GetValue()
+->Clear();
+StreamSP error_strm_sp;
+if (m_target) {
+  // FIXME: How can I warn the user when setting this on the Debugger?
+  error_strm_sp = m_target->GetDebugger().GetAsyncErrorStream();
+} else if (Debugger::GetNumDebuggers() == 1) {
+  error_strm_sp = Debugger::GetDebuggerAtIndex(0)->GetAsyncErrorStream();
+}
+if (error_strm_sp