[Lldb-commits] [PATCH] D58257: Disable ExecControl/StopHook/stop-hook-threads.test on Linux

2019-02-14 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe created this revision.
jgorbe added reviewers: labath, zturner.
Herald added a subscriber: jdoerfert.

ExecControl/StopHook/stop-hook-threads.test is flaky on Linux (it's 
consistently failing on my machine, but doesn't fail on a co-worker's). I'm 
seeing the following assertion failure:

  CommandObject.cpp:145: bool 
lldb_private::CommandObject::CheckRequirements(lldb_private::CommandReturnObject&):
 Assertion `m_exe_ctx.GetTargetPtr() == NULL' failed.

Interestingly, this doesn't happen when typing the same commands in interactive 
mode. The cause seems to be that, in synchronous execution mode `continue` 
waits until the process stops again, and that includes running any stop-hooks 
for that later stop, so we end with a stack trace like this (lots of frames 
omitted for clarity):

  abort()
  CommandObject::CheckRequirements() <-- this is again the same instance of 
CommandObjectProcessContinue, fails assertion because the previous continue 
command hasn't finished.
  Target::RunStopHooks()
  CommandObjectProcessContinue::DoExecute()
  Target::RunStopHooks()

In general, it seems like using process control commands inside stop-hooks does 
not have very well defined semantics. You don't even need multiple threads to 
make that assertion fail, you can build

  #include 
  int main() {
printf("1\n");  // break1
printf("2\n");  // break2
  }

and then on lldb

  target stop-hook add -o continue
  break set -f stop-hook-simple.cpp -p "break1"
  break set -f stop-hook-simple.cpp -p "break2"
  run

In this case it's even worse because the presence of multiple threads makes it 
prone to race conditions. In some tests I ran with a simpler version of this 
test case, I was hitting either the previous assertion failure or the following 
issue:

1. Two threads reach a breakpoint
2. First stop-hook does a `process continue`
3. Threads end
4. Second stop-hook runs, complains about process not existing.

This change disables the test on Linux. It's already marked as XFAIL on 
Windows, so maybe we should just delete it until it's clear what should be the 
expected behavior in these cases. Or maybe try to come up with a way to write a 
similar multithreaded test without calling `continue` from a stop hook, I don't 
know.


https://reviews.llvm.org/D58257

Files:
  lldb/lit/ExecControl/StopHook/stop-hook-threads.test


Index: lldb/lit/ExecControl/StopHook/stop-hook-threads.test
===
--- lldb/lit/ExecControl/StopHook/stop-hook-threads.test
+++ lldb/lit/ExecControl/StopHook/stop-hook-threads.test
@@ -4,6 +4,7 @@
 # RUN: %lldb -b -s %p/Inputs/stop-hook-threads-2.lldbinit -s %s -f %t \
 # RUN: | FileCheck --check-prefix=CHECK --check-prefix=CHECK-FILTER %s
 # XFAIL: system-windows
+# UNSUPPORTED: linux
 
 thread list
 break set -f stop-hook-threads.cpp -p "Set break point at this line"


Index: lldb/lit/ExecControl/StopHook/stop-hook-threads.test
===
--- lldb/lit/ExecControl/StopHook/stop-hook-threads.test
+++ lldb/lit/ExecControl/StopHook/stop-hook-threads.test
@@ -4,6 +4,7 @@
 # RUN: %lldb -b -s %p/Inputs/stop-hook-threads-2.lldbinit -s %s -f %t \
 # RUN: | FileCheck --check-prefix=CHECK --check-prefix=CHECK-FILTER %s
 # XFAIL: system-windows
+# UNSUPPORTED: linux
 
 thread list
 break set -f stop-hook-threads.cpp -p "Set break point at this line"
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D58257: Disable ExecControl/StopHook/stop-hook-threads.test on Linux

2019-02-15 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL354149: Disable stop-hook-threads.test on Linux (authored by 
jgorbe, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D58257?vs=186890&id=187033#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D58257

Files:
  lldb/trunk/lit/ExecControl/StopHook/stop-hook-threads.test


Index: lldb/trunk/lit/ExecControl/StopHook/stop-hook-threads.test
===
--- lldb/trunk/lit/ExecControl/StopHook/stop-hook-threads.test
+++ lldb/trunk/lit/ExecControl/StopHook/stop-hook-threads.test
@@ -4,6 +4,7 @@
 # RUN: %lldb -b -s %p/Inputs/stop-hook-threads-2.lldbinit -s %s -f %t \
 # RUN: | FileCheck --check-prefix=CHECK --check-prefix=CHECK-FILTER %s
 # XFAIL: system-windows
+# UNSUPPORTED: linux
 
 thread list
 break set -f stop-hook-threads.cpp -p "Set break point at this line"


Index: lldb/trunk/lit/ExecControl/StopHook/stop-hook-threads.test
===
--- lldb/trunk/lit/ExecControl/StopHook/stop-hook-threads.test
+++ lldb/trunk/lit/ExecControl/StopHook/stop-hook-threads.test
@@ -4,6 +4,7 @@
 # RUN: %lldb -b -s %p/Inputs/stop-hook-threads-2.lldbinit -s %s -f %t \
 # RUN: | FileCheck --check-prefix=CHECK --check-prefix=CHECK-FILTER %s
 # XFAIL: system-windows
+# UNSUPPORTED: linux
 
 thread list
 break set -f stop-hook-threads.cpp -p "Set break point at this line"
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D59340: [lldb-vscode] Don't try to launch an invalid program.

2019-03-13 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe created this revision.
jgorbe added a reviewer: zturner.
Herald added a project: LLDB.

If an invalid program is specified, lldb-vscode will send back a
response with `"success": false`, but then will continue executing the
rest of `request_launch()`, try to launch the program anyway and try to
send another response (possibly using the `response` object after it was
moved).

This change adds a return statement so we stop executing the handler
after producing the first failing response.


Repository:
  rLLDB LLDB

https://reviews.llvm.org/D59340

Files:
  lldb/tools/lldb-vscode/lldb-vscode.cpp


Index: lldb/tools/lldb-vscode/lldb-vscode.cpp
===
--- lldb/tools/lldb-vscode/lldb-vscode.cpp
+++ lldb/tools/lldb-vscode/lldb-vscode.cpp
@@ -1245,6 +1245,7 @@
   response, "message",
   llvm::formatv("Could not load program '{0}'.", program).str());
   g_vsc.SendJSON(llvm::json::Value(std::move(response)));
+  return;
 }
   }
 


Index: lldb/tools/lldb-vscode/lldb-vscode.cpp
===
--- lldb/tools/lldb-vscode/lldb-vscode.cpp
+++ lldb/tools/lldb-vscode/lldb-vscode.cpp
@@ -1245,6 +1245,7 @@
   response, "message",
   llvm::formatv("Could not load program '{0}'.", program).str());
   g_vsc.SendJSON(llvm::json::Value(std::move(response)));
+  return;
 }
   }
 
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D59340: [lldb-vscode] Don't try to launch an invalid program.

2019-03-13 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rLLDB356110: [lldb-vscode] Don't try to launch an invalid 
program. (authored by jgorbe, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D59340?vs=190535&id=190542#toc

Repository:
  rLLDB LLDB

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

https://reviews.llvm.org/D59340

Files:
  tools/lldb-vscode/lldb-vscode.cpp


Index: tools/lldb-vscode/lldb-vscode.cpp
===
--- tools/lldb-vscode/lldb-vscode.cpp
+++ tools/lldb-vscode/lldb-vscode.cpp
@@ -1245,6 +1245,7 @@
   response, "message",
   llvm::formatv("Could not load program '{0}'.", program).str());
   g_vsc.SendJSON(llvm::json::Value(std::move(response)));
+  return;
 }
   }
 


Index: tools/lldb-vscode/lldb-vscode.cpp
===
--- tools/lldb-vscode/lldb-vscode.cpp
+++ tools/lldb-vscode/lldb-vscode.cpp
@@ -1245,6 +1245,7 @@
   response, "message",
   llvm::formatv("Could not load program '{0}'.", program).str());
   g_vsc.SendJSON(llvm::json::Value(std::move(response)));
+  return;
 }
   }
 
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D59400: [lldb-vscode] Fix dangling pointer in request_evaluate.

2019-03-14 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe created this revision.
jgorbe added reviewers: zturner, clayborg.
Herald added a project: LLDB.

SBError::GetCString() returns a pointer to a string owned by the SBError
object. The code here was calling GetCString on a temporary and using
the returned pointer after the temporary was destroyed.


Repository:
  rLLDB LLDB

https://reviews.llvm.org/D59400

Files:
  lldb/tools/lldb-vscode/lldb-vscode.cpp


Index: lldb/tools/lldb-vscode/lldb-vscode.cpp
===
--- lldb/tools/lldb-vscode/lldb-vscode.cpp
+++ lldb/tools/lldb-vscode/lldb-vscode.cpp
@@ -965,7 +965,10 @@
   value = frame.EvaluateExpression(expression.data());
 if (value.GetError().Fail()) {
   response["success"] = llvm::json::Value(false);
-  const char *error_cstr = value.GetError().GetCString();
+  // This error object must live until we're done with the pointer returned
+  // by GetCString().
+  lldb::SBError error = value.GetError();
+  const char *error_cstr = error.GetCString();
   if (error_cstr && error_cstr[0])
 EmplaceSafeString(response, "message", std::string(error_cstr));
   else


Index: lldb/tools/lldb-vscode/lldb-vscode.cpp
===
--- lldb/tools/lldb-vscode/lldb-vscode.cpp
+++ lldb/tools/lldb-vscode/lldb-vscode.cpp
@@ -965,7 +965,10 @@
   value = frame.EvaluateExpression(expression.data());
 if (value.GetError().Fail()) {
   response["success"] = llvm::json::Value(false);
-  const char *error_cstr = value.GetError().GetCString();
+  // This error object must live until we're done with the pointer returned
+  // by GetCString().
+  lldb::SBError error = value.GetError();
+  const char *error_cstr = error.GetCString();
   if (error_cstr && error_cstr[0])
 EmplaceSafeString(response, "message", std::string(error_cstr));
   else
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D59400: [lldb-vscode] Fix dangling pointer in request_evaluate.

2019-03-14 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe added a comment.

I considered assigning it to a `std::string`, but `GetCString()` can return a 
null pointer and I'm not sure you can construct a `std::string` directly from 
that.


Repository:
  rLLDB LLDB

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

https://reviews.llvm.org/D59400



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


[Lldb-commits] [PATCH] D59400: [lldb-vscode] Fix dangling pointer in request_evaluate.

2019-03-14 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rLLDB356227: [lldb-vscode] Fix dangling pointer in 
request_evaluate. (authored by jgorbe, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D59400?vs=190764&id=190769#toc

Repository:
  rLLDB LLDB

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

https://reviews.llvm.org/D59400

Files:
  tools/lldb-vscode/lldb-vscode.cpp


Index: tools/lldb-vscode/lldb-vscode.cpp
===
--- tools/lldb-vscode/lldb-vscode.cpp
+++ tools/lldb-vscode/lldb-vscode.cpp
@@ -965,7 +965,10 @@
   value = frame.EvaluateExpression(expression.data());
 if (value.GetError().Fail()) {
   response["success"] = llvm::json::Value(false);
-  const char *error_cstr = value.GetError().GetCString();
+  // This error object must live until we're done with the pointer returned
+  // by GetCString().
+  lldb::SBError error = value.GetError();
+  const char *error_cstr = error.GetCString();
   if (error_cstr && error_cstr[0])
 EmplaceSafeString(response, "message", std::string(error_cstr));
   else


Index: tools/lldb-vscode/lldb-vscode.cpp
===
--- tools/lldb-vscode/lldb-vscode.cpp
+++ tools/lldb-vscode/lldb-vscode.cpp
@@ -965,7 +965,10 @@
   value = frame.EvaluateExpression(expression.data());
 if (value.GetError().Fail()) {
   response["success"] = llvm::json::Value(false);
-  const char *error_cstr = value.GetError().GetCString();
+  // This error object must live until we're done with the pointer returned
+  // by GetCString().
+  lldb::SBError error = value.GetError();
+  const char *error_cstr = error.GetCString();
   if (error_cstr && error_cstr[0])
 EmplaceSafeString(response, "message", std::string(error_cstr));
   else
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D59828: Add lldb-vscode as a dependency of lldb tests.

2019-03-26 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe created this revision.
jgorbe added a reviewer: clayborg.
Herald added a subscriber: mgorny.
Herald added a project: LLDB.

In the current state, 'ninja check-lldb' runs the lldb-vscode tests, but it
won't rebuild lldb-vscode if any of its sources has changed. This is very
confusing when you fix something and the tests keep failing, or vice versa.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D59828

Files:
  lldb/CMakeLists.txt


Index: lldb/CMakeLists.txt
===
--- lldb/CMakeLists.txt
+++ lldb/CMakeLists.txt
@@ -91,6 +91,10 @@
 list(APPEND LLDB_TEST_DEPS lldb-mi)
   endif()
 
+  if(TARGET lldb-vscode)
+list(APPEND LLDB_TEST_DEPS lldb-vscode)
+  endif()
+
   if(TARGET lldb-instr)
 list(APPEND LLDB_TEST_DEPS lldb-instr)
   endif()


Index: lldb/CMakeLists.txt
===
--- lldb/CMakeLists.txt
+++ lldb/CMakeLists.txt
@@ -91,6 +91,10 @@
 list(APPEND LLDB_TEST_DEPS lldb-mi)
   endif()
 
+  if(TARGET lldb-vscode)
+list(APPEND LLDB_TEST_DEPS lldb-vscode)
+  endif()
+
   if(TARGET lldb-instr)
 list(APPEND LLDB_TEST_DEPS lldb-instr)
   endif()
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D59828: Add lldb-vscode as a dependency of lldb tests.

2019-03-26 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL357016: Add lldb-vscode as a dependency of lldb tests. 
(authored by jgorbe, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D59828?vs=192296&id=192306#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D59828

Files:
  lldb/trunk/CMakeLists.txt


Index: lldb/trunk/CMakeLists.txt
===
--- lldb/trunk/CMakeLists.txt
+++ lldb/trunk/CMakeLists.txt
@@ -91,6 +91,10 @@
 list(APPEND LLDB_TEST_DEPS lldb-mi)
   endif()
 
+  if(TARGET lldb-vscode)
+list(APPEND LLDB_TEST_DEPS lldb-vscode)
+  endif()
+
   if(TARGET lldb-instr)
 list(APPEND LLDB_TEST_DEPS lldb-instr)
   endif()


Index: lldb/trunk/CMakeLists.txt
===
--- lldb/trunk/CMakeLists.txt
+++ lldb/trunk/CMakeLists.txt
@@ -91,6 +91,10 @@
 list(APPEND LLDB_TEST_DEPS lldb-mi)
   endif()
 
+  if(TARGET lldb-vscode)
+list(APPEND LLDB_TEST_DEPS lldb-vscode)
+  endif()
+
   if(TARGET lldb-instr)
 list(APPEND LLDB_TEST_DEPS lldb-instr)
   endif()
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D59849: [lldb-vscode] Add logic to handle EOF when reading from lldb-vscode stdout.

2019-03-26 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe created this revision.
jgorbe added reviewers: clayborg, zturner.
Herald added a project: LLDB.

This change prevents the lldb-vscode test harness from hanging up waiting for
new messages when the lldb-vscode subprocess crashes.

Now, when an EOF from the subprocess pipe is detected we enqueue a `None` packet
in the received packets list. Then, during the message processing loop, we can
use this `None` packet to tell apart the case where lldb-vscode has terminated
unexpectedly from the normal situation where no pending messages means blocking
and waiting for more data.

I believe this should be enough to fix the issues with these tests hanging on
multiple platforms. Once this lands, I'll prepare and test a separate change
removing the @skipIfLinux annotations.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D59849

Files:
  lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py

Index: lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py
===
--- lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py
+++ lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py
@@ -52,11 +52,11 @@
 
 def read_packet(f, verbose=False, trace_file=None):
 '''Decode a JSON packet that starts with the content length and is
-   followed by the JSON bytes from a file 'f'
+   followed by the JSON bytes from a file 'f'. Returns None on EOF.
 '''
 line = f.readline().decode("utf-8")
 if len(line) == 0:
-return None
+return None  # EOF.
 
 # Watch for line that starts with the prefix
 prefix = 'Content-Length: '
@@ -91,10 +91,10 @@
 done = False
 while not done:
 packet = read_packet(vs_comm.recv, trace_file=vs_comm.trace_file)
-if packet:
-done = not vs_comm.handle_recv_packet(packet)
-else:
-done = True
+# `packet` will be `None` on EOF. We want to pass it down to
+# handle_recv_packet anyway so the main thread can handle unexpected
+# termination of lldb-vscode and stop waiting for new packets.
+done = not vs_comm.handle_recv_packet(packet)
 
 
 class DebugCommunication(object):
@@ -146,6 +146,12 @@
 self.output_condition.release()
 return output
 
+def enqueue_recv_packet(self, packet):
+self.recv_condition.acquire()
+self.recv_packets.append(packet)
+self.recv_condition.notify()
+self.recv_condition.release()
+
 def handle_recv_packet(self, packet):
 '''Called by the read thread that is waiting for all incoming packets
to store the incoming packet in "self.recv_packets" in a thread safe
@@ -153,6 +159,11 @@
indicate a new packet is available. Returns True if the caller
should keep calling this function for more packets.
 '''
+# If EOF, notify the read thread by enqueing a None.
+if not packet:
+self.enqueue_recv_packet(None)
+return False
+
 # Check the packet to see if is an event packet
 keepGoing = True
 packet_type = packet['type']
@@ -191,10 +202,7 @@
 elif packet_type == 'response':
 if packet['command'] == 'disconnect':
 keepGoing = False
-self.recv_condition.acquire()
-self.recv_packets.append(packet)
-self.recv_condition.notify()
-self.recv_condition.release()
+self.enqueue_recv_packet(packet)
 return keepGoing
 
 def send_packet(self, command_dict, set_sequence=True):
@@ -222,27 +230,33 @@
function will wait for the packet to arrive and return it when
it does.'''
 while True:
-self.recv_condition.acquire()
-packet = None
-while True:
-for (i, curr_packet) in enumerate(self.recv_packets):
-packet_type = curr_packet['type']
-if filter_type is None or packet_type in filter_type:
-if (filter_event is None or
-(packet_type == 'event' and
- curr_packet['event'] in filter_event)):
-packet = self.recv_packets.pop(i)
-break
-if packet:
-break
-# Sleep until packet is received
-len_before = len(self.recv_packets)
-self.recv_condition.wait(timeout)
-len_after = len(self.recv_packets)
-if len_before == len_after:
-return None  # Timed out
-self.recv_condition.release()
-return packet
+try:
+self.recv_condition.acquire()
+packet = None
+while True:
+for (i, curr_packet) in enumerate(self.recv_packets):
+if no

[Lldb-commits] [PATCH] D59849: [lldb-vscode] Add logic to handle EOF when reading from lldb-vscode stdout.

2019-04-01 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL357426: [lldb-vscode] Add logic to handle EOF when reading 
from lldb-vscode stdout. (authored by jgorbe, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D59849?vs=192368&id=193170#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D59849

Files:
  lldb/trunk/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py

Index: lldb/trunk/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py
===
--- lldb/trunk/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py
+++ lldb/trunk/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py
@@ -52,11 +52,11 @@
 
 def read_packet(f, verbose=False, trace_file=None):
 '''Decode a JSON packet that starts with the content length and is
-   followed by the JSON bytes from a file 'f'
+   followed by the JSON bytes from a file 'f'. Returns None on EOF.
 '''
 line = f.readline().decode("utf-8")
 if len(line) == 0:
-return None
+return None  # EOF.
 
 # Watch for line that starts with the prefix
 prefix = 'Content-Length: '
@@ -91,10 +91,10 @@
 done = False
 while not done:
 packet = read_packet(vs_comm.recv, trace_file=vs_comm.trace_file)
-if packet:
-done = not vs_comm.handle_recv_packet(packet)
-else:
-done = True
+# `packet` will be `None` on EOF. We want to pass it down to
+# handle_recv_packet anyway so the main thread can handle unexpected
+# termination of lldb-vscode and stop waiting for new packets.
+done = not vs_comm.handle_recv_packet(packet)
 
 
 class DebugCommunication(object):
@@ -146,6 +146,12 @@
 self.output_condition.release()
 return output
 
+def enqueue_recv_packet(self, packet):
+self.recv_condition.acquire()
+self.recv_packets.append(packet)
+self.recv_condition.notify()
+self.recv_condition.release()
+
 def handle_recv_packet(self, packet):
 '''Called by the read thread that is waiting for all incoming packets
to store the incoming packet in "self.recv_packets" in a thread safe
@@ -153,6 +159,11 @@
indicate a new packet is available. Returns True if the caller
should keep calling this function for more packets.
 '''
+# If EOF, notify the read thread by enqueing a None.
+if not packet:
+self.enqueue_recv_packet(None)
+return False
+
 # Check the packet to see if is an event packet
 keepGoing = True
 packet_type = packet['type']
@@ -191,10 +202,7 @@
 elif packet_type == 'response':
 if packet['command'] == 'disconnect':
 keepGoing = False
-self.recv_condition.acquire()
-self.recv_packets.append(packet)
-self.recv_condition.notify()
-self.recv_condition.release()
+self.enqueue_recv_packet(packet)
 return keepGoing
 
 def send_packet(self, command_dict, set_sequence=True):
@@ -222,27 +230,33 @@
function will wait for the packet to arrive and return it when
it does.'''
 while True:
-self.recv_condition.acquire()
-packet = None
-while True:
-for (i, curr_packet) in enumerate(self.recv_packets):
-packet_type = curr_packet['type']
-if filter_type is None or packet_type in filter_type:
-if (filter_event is None or
-(packet_type == 'event' and
- curr_packet['event'] in filter_event)):
-packet = self.recv_packets.pop(i)
-break
-if packet:
-break
-# Sleep until packet is received
-len_before = len(self.recv_packets)
-self.recv_condition.wait(timeout)
-len_after = len(self.recv_packets)
-if len_before == len_after:
-return None  # Timed out
-self.recv_condition.release()
-return packet
+try:
+self.recv_condition.acquire()
+packet = None
+while True:
+for (i, curr_packet) in enumerate(self.recv_packets):
+if not curr_packet:
+raise EOFError
+packet_type = curr_packet['type']
+if filter_type is None or packet_type in filter_type:
+if (filter_event is None or
+(packet_type == 'event' and
+   

[Lldb-commits] [PATCH] D60153: Re-enable most lldb-vscode tests on Linux.

2019-04-02 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe created this revision.
jgorbe added reviewers: zturner, clayborg.
Herald added a project: LLDB.

After https://reviews.llvm.org/D59828 and https://reviews.llvm.org/D59849,
I believe the problems with these tests hanging have been solved.

I tried enabling all of them on my machine, and got two failures:

- One of them was spawning a child process that lives for 5 seconds, waited for 
5 seconds to attach to the child, and failed because the child wasn't there.

- The other one was a legit failure because shell expansion of arguments 
doesn't work on Linux.

This tests enables all lldb-vscode tests on Linux except for "launch process
with shell expansion of args" (which doesn't work), and fixes the other broken
test by reducing the time it waits before attaching to its child process.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D60153

Files:
  
lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/attach/TestVSCode_attach.py
  
lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/breakpoint/TestVSCode_setFunctionBreakpoints.py
  
lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/launch/TestVSCode_launch.py

Index: lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/launch/TestVSCode_launch.py
===
--- lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/launch/TestVSCode_launch.py
+++ lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/launch/TestVSCode_launch.py
@@ -21,7 +21,6 @@
 
 @skipIfWindows
 @skipIfDarwin # Skip this test for now until we can figure out why tings aren't working on build bots
-@skipIfLinux # This test is timing out and/or failing on Linux as well as Darwin
 @no_debug_info_test
 def test_default(self):
 '''
@@ -41,7 +40,6 @@
 
 @skipIfWindows
 @skipIfDarwin # Skip this test for now until we can figure out why tings aren't working on build bots
-@skipIfLinux # This test is timing out and/or failing on Linux as well as Darwin
 @no_debug_info_test
 def test_stopOnEntry(self):
 '''
@@ -63,7 +61,6 @@
 
 @skipIfWindows
 @skipIfDarwin # Skip this test for now until we can figure out why tings aren't working on build bots
-@skipIfLinux # This test is timing out and/or failing on Linux as well as Darwin
 @no_debug_info_test
 def test_cwd(self):
 '''
@@ -92,7 +89,6 @@
 
 @skipIfWindows
 @skipIfDarwin # Skip this test for now until we can figure out why tings aren't working on build bots
-@skipIfLinux # This test is timing out and/or failing on Linux as well as Darwin
 @no_debug_info_test
 def test_debuggerRoot(self):
 '''
@@ -122,7 +118,6 @@
 
 @skipIfWindows
 @skipIfDarwin # Skip this test for now until we can figure out why tings aren't working on build bots
-@skipIfLinux # This test is timing out and/or failing on Linux as well as Darwin
 @no_debug_info_test
 def test_sourcePath(self):
 '''
@@ -150,7 +145,6 @@
 
 @skipIfWindows
 @skipIfDarwin # Skip this test for now until we can figure out why tings aren't working on build bots
-@skipIfLinux # This test is timing out and/or failing on Linux as well as Darwin
 @no_debug_info_test
 def test_disableSTDIO(self):
 '''
@@ -167,7 +161,7 @@
 
 @skipIfWindows
 @skipIfDarwin # Skip this test for now until we can figure out why tings aren't working on build bots
-@skipIfLinux # This test is timing out and/or failing on Linux as well as Darwin
+@skipIfLinux # shell argument expansion doesn't seem to work on Linux
 @expectedFailureNetBSD
 @no_debug_info_test
 def test_shellExpandArguments_enabled(self):
@@ -194,7 +188,6 @@
 
 @skipIfWindows
 @skipIfDarwin # Skip this test for now until we can figure out why tings aren't working on build bots
-@skipIfLinux # This test is timing out and/or failing on Linux as well as Darwin
 @no_debug_info_test
 def test_shellExpandArguments_disabled(self):
 '''
@@ -222,7 +215,6 @@
 
 @skipIfWindows
 @skipIfDarwin # Skip this test for now until we can figure out why tings aren't working on build bots
-@skipIfLinux # This test is timing out and/or failing on Linux as well as Darwin
 @no_debug_info_test
 def test_args(self):
 '''
@@ -250,7 +242,6 @@
 
 @skipIfWindows
 @skipIfDarwin # Skip this test for now until we can figure out why tings aren't working on build bots
-@skipIfLinux # This test is timing out and/or failing on Linux as well as Darwin
 @no_debug_info_test
 def test_environment(self):
 '''
@@ -285,7 +276,6 @@
 
 @skipIfWindows
 @skipIfDarwin # Skip this test for now until we can figure out why tings aren't working on build bots
-@skipIfLinux # This test is timing out and/or failing on Linux as well as Darwin
 @no_debug_info_test
 def test_commands(self):
 '''
Index: lldb/packages/Python/lldbsuite/test/tools/ll

[Lldb-commits] [PATCH] D60153: Re-enable most lldb-vscode tests on Linux.

2019-04-03 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe updated this revision to Diff 193585.
jgorbe added a comment.

Increased wait time in test binary for TestVSCode_attach.py from 5 to 10 
seconds.

If this is still unreliable, or it makes the test take too long, I'll switch it
to use the `debugger_flag` pattern as suggested.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60153

Files:
  
lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/attach/TestVSCode_attach.py
  lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/attach/main.c
  
lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/breakpoint/TestVSCode_setFunctionBreakpoints.py
  
lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/launch/TestVSCode_launch.py

Index: lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/launch/TestVSCode_launch.py
===
--- lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/launch/TestVSCode_launch.py
+++ lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/launch/TestVSCode_launch.py
@@ -21,7 +21,6 @@
 
 @skipIfWindows
 @skipIfDarwin # Skip this test for now until we can figure out why tings aren't working on build bots
-@skipIfLinux # This test is timing out and/or failing on Linux as well as Darwin
 @no_debug_info_test
 def test_default(self):
 '''
@@ -41,7 +40,6 @@
 
 @skipIfWindows
 @skipIfDarwin # Skip this test for now until we can figure out why tings aren't working on build bots
-@skipIfLinux # This test is timing out and/or failing on Linux as well as Darwin
 @no_debug_info_test
 def test_stopOnEntry(self):
 '''
@@ -63,7 +61,6 @@
 
 @skipIfWindows
 @skipIfDarwin # Skip this test for now until we can figure out why tings aren't working on build bots
-@skipIfLinux # This test is timing out and/or failing on Linux as well as Darwin
 @no_debug_info_test
 def test_cwd(self):
 '''
@@ -92,7 +89,6 @@
 
 @skipIfWindows
 @skipIfDarwin # Skip this test for now until we can figure out why tings aren't working on build bots
-@skipIfLinux # This test is timing out and/or failing on Linux as well as Darwin
 @no_debug_info_test
 def test_debuggerRoot(self):
 '''
@@ -122,7 +118,6 @@
 
 @skipIfWindows
 @skipIfDarwin # Skip this test for now until we can figure out why tings aren't working on build bots
-@skipIfLinux # This test is timing out and/or failing on Linux as well as Darwin
 @no_debug_info_test
 def test_sourcePath(self):
 '''
@@ -150,7 +145,6 @@
 
 @skipIfWindows
 @skipIfDarwin # Skip this test for now until we can figure out why tings aren't working on build bots
-@skipIfLinux # This test is timing out and/or failing on Linux as well as Darwin
 @no_debug_info_test
 def test_disableSTDIO(self):
 '''
@@ -167,7 +161,7 @@
 
 @skipIfWindows
 @skipIfDarwin # Skip this test for now until we can figure out why tings aren't working on build bots
-@skipIfLinux # This test is timing out and/or failing on Linux as well as Darwin
+@skipIfLinux # shell argument expansion doesn't seem to work on Linux
 @expectedFailureNetBSD
 @no_debug_info_test
 def test_shellExpandArguments_enabled(self):
@@ -194,7 +188,6 @@
 
 @skipIfWindows
 @skipIfDarwin # Skip this test for now until we can figure out why tings aren't working on build bots
-@skipIfLinux # This test is timing out and/or failing on Linux as well as Darwin
 @no_debug_info_test
 def test_shellExpandArguments_disabled(self):
 '''
@@ -222,7 +215,6 @@
 
 @skipIfWindows
 @skipIfDarwin # Skip this test for now until we can figure out why tings aren't working on build bots
-@skipIfLinux # This test is timing out and/or failing on Linux as well as Darwin
 @no_debug_info_test
 def test_args(self):
 '''
@@ -250,7 +242,6 @@
 
 @skipIfWindows
 @skipIfDarwin # Skip this test for now until we can figure out why tings aren't working on build bots
-@skipIfLinux # This test is timing out and/or failing on Linux as well as Darwin
 @no_debug_info_test
 def test_environment(self):
 '''
@@ -285,7 +276,6 @@
 
 @skipIfWindows
 @skipIfDarwin # Skip this test for now until we can figure out why tings aren't working on build bots
-@skipIfLinux # This test is timing out and/or failing on Linux as well as Darwin
 @no_debug_info_test
 def test_commands(self):
 '''
Index: lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/breakpoint/TestVSCode_setFunctionBreakpoints.py
===
--- lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/breakpoint/TestVSCode_setFunctionBreakpoints.py
+++ lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/breakpoint/TestVSCode_setFunctionBreakpoints.py
@@ -21,7 +21,6 @@
 
 @skipIfWindows
   

[Lldb-commits] [PATCH] D60153: Re-enable most lldb-vscode tests on Linux.

2019-04-03 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
This revision was automatically updated to reflect the committed changes.
jgorbe marked 2 inline comments as done.
Closed by commit rL357633: Re-enable most lldb-vscode tests on Linux. (authored 
by jgorbe, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D60153?vs=193585&id=193586#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D60153

Files:
  
lldb/trunk/packages/Python/lldbsuite/test/tools/lldb-vscode/attach/TestVSCode_attach.py
  lldb/trunk/packages/Python/lldbsuite/test/tools/lldb-vscode/attach/main.c
  
lldb/trunk/packages/Python/lldbsuite/test/tools/lldb-vscode/breakpoint/TestVSCode_setFunctionBreakpoints.py
  
lldb/trunk/packages/Python/lldbsuite/test/tools/lldb-vscode/launch/TestVSCode_launch.py

Index: lldb/trunk/packages/Python/lldbsuite/test/tools/lldb-vscode/breakpoint/TestVSCode_setFunctionBreakpoints.py
===
--- lldb/trunk/packages/Python/lldbsuite/test/tools/lldb-vscode/breakpoint/TestVSCode_setFunctionBreakpoints.py
+++ lldb/trunk/packages/Python/lldbsuite/test/tools/lldb-vscode/breakpoint/TestVSCode_setFunctionBreakpoints.py
@@ -21,7 +21,6 @@
 
 @skipIfWindows
 @skipIfDarwin # Skip this test for now until we can figure out why tings aren't working on build bots
-@skipIfLinux # test hangs on linux under heavy load
 @no_debug_info_test
 def test_set_and_clear(self):
 '''Tests setting and clearing function breakpoints.
@@ -114,7 +113,6 @@
 
 @skipIfWindows
 @skipIfDarwin # Skip this test for now until we can figure out why tings aren't working on build bots
-@skipIfLinux # test hangs on linux under heavy load
 @no_debug_info_test
 def test_functionality(self):
 '''Tests hitting breakpoints and the functionality of a single
Index: lldb/trunk/packages/Python/lldbsuite/test/tools/lldb-vscode/launch/TestVSCode_launch.py
===
--- lldb/trunk/packages/Python/lldbsuite/test/tools/lldb-vscode/launch/TestVSCode_launch.py
+++ lldb/trunk/packages/Python/lldbsuite/test/tools/lldb-vscode/launch/TestVSCode_launch.py
@@ -21,7 +21,6 @@
 
 @skipIfWindows
 @skipIfDarwin # Skip this test for now until we can figure out why tings aren't working on build bots
-@skipIfLinux # This test is timing out and/or failing on Linux as well as Darwin
 @no_debug_info_test
 def test_default(self):
 '''
@@ -41,7 +40,6 @@
 
 @skipIfWindows
 @skipIfDarwin # Skip this test for now until we can figure out why tings aren't working on build bots
-@skipIfLinux # This test is timing out and/or failing on Linux as well as Darwin
 @no_debug_info_test
 def test_stopOnEntry(self):
 '''
@@ -63,7 +61,6 @@
 
 @skipIfWindows
 @skipIfDarwin # Skip this test for now until we can figure out why tings aren't working on build bots
-@skipIfLinux # This test is timing out and/or failing on Linux as well as Darwin
 @no_debug_info_test
 def test_cwd(self):
 '''
@@ -92,7 +89,6 @@
 
 @skipIfWindows
 @skipIfDarwin # Skip this test for now until we can figure out why tings aren't working on build bots
-@skipIfLinux # This test is timing out and/or failing on Linux as well as Darwin
 @no_debug_info_test
 def test_debuggerRoot(self):
 '''
@@ -122,7 +118,6 @@
 
 @skipIfWindows
 @skipIfDarwin # Skip this test for now until we can figure out why tings aren't working on build bots
-@skipIfLinux # This test is timing out and/or failing on Linux as well as Darwin
 @no_debug_info_test
 def test_sourcePath(self):
 '''
@@ -150,7 +145,6 @@
 
 @skipIfWindows
 @skipIfDarwin # Skip this test for now until we can figure out why tings aren't working on build bots
-@skipIfLinux # This test is timing out and/or failing on Linux as well as Darwin
 @no_debug_info_test
 def test_disableSTDIO(self):
 '''
@@ -167,7 +161,7 @@
 
 @skipIfWindows
 @skipIfDarwin # Skip this test for now until we can figure out why tings aren't working on build bots
-@skipIfLinux # This test is timing out and/or failing on Linux as well as Darwin
+@skipIfLinux # shell argument expansion doesn't seem to work on Linux
 @expectedFailureNetBSD
 @no_debug_info_test
 def test_shellExpandArguments_enabled(self):
@@ -194,7 +188,6 @@
 
 @skipIfWindows
 @skipIfDarwin # Skip this test for now until we can figure out why tings aren't working on build bots
-@skipIfLinux # This test is timing out and/or failing on Linux as well as Darwin
 @no_debug_info_test
 def test_shellExpandArguments_disabled(self):
 '''
@@ -222,7 +215,6 @@
 
 @skipIfWindows
 @skipIfDarwin # Skip this test for now until we can figure out why tings aren't working on build bots
-

[Lldb-commits] [PATCH] D60153: Re-enable most lldb-vscode tests on Linux.

2019-04-16 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe added a comment.

Thanks! Please let me know if it happens again and I'll try my best to debug it.


Repository:
  rL LLVM

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

https://reviews.llvm.org/D60153



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


[Lldb-commits] [PATCH] D60608: Make TestVSCode_step pass reliably

2019-04-22 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe added a comment.

Thanks for the fix!


Repository:
  rL LLVM

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

https://reviews.llvm.org/D60608



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


[Lldb-commits] [PATCH] D130219: [lldb][NFCI] Refactor regex filtering logic in CommandObjectTypeFormatterList

2022-07-20 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe created this revision.
jgorbe added a reviewer: labath.
jgorbe added a project: LLDB.
Herald added a subscriber: JDevlieghere.
Herald added a project: All.
jgorbe requested review of this revision.

Extract a bit of copy/pasted regex filtering logic into a separate function and 
simplify it a little bit.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D130219

Files:
  lldb/source/Commands/CommandObjectType.cpp

Index: lldb/source/Commands/CommandObjectType.cpp
===
--- lldb/source/Commands/CommandObjectType.cpp
+++ lldb/source/Commands/CommandObjectType.cpp
@@ -1055,6 +1055,15 @@
 return false;
   }
 
+  static bool ShouldListItem(llvm::StringRef s, RegularExpression *regex) {
+// If we have a regex, it can match two kinds of results:
+//   - An item created with that same regex string (exact string match), so
+// the user can list it using the same string it used at creation time.
+//   - Items that match the regex.
+// No regex means list everything.
+return (regex == nullptr || (s == regex->GetText() || regex->Execute(s)));
+  }
+
   bool DoExecute(Args &command, CommandReturnObject &result) override {
 const size_t argc = command.GetArgumentCount();
 
@@ -1096,24 +1105,13 @@
 .SetExact([&result, &formatter_regex, &any_printed](
   const TypeMatcher &type_matcher,
   const FormatterSharedPointer &format_sp) -> bool {
-  if (formatter_regex) {
-bool escape = true;
-if (type_matcher.CreatedBySameMatchString(
-ConstString(formatter_regex->GetText( {
-  escape = false;
-} else if (formatter_regex->Execute(
-   type_matcher.GetMatchString().GetStringRef())) {
-  escape = false;
-}
-
-if (escape)
-  return true;
+  if (ShouldListItem(type_matcher.GetMatchString().GetStringRef(),
+ formatter_regex.get())) {
+any_printed = true;
+result.GetOutputStream().Printf(
+"%s: %s\n", type_matcher.GetMatchString().GetCString(),
+format_sp->GetDescription().c_str());
   }
-
-  any_printed = true;
-  result.GetOutputStream().Printf(
-  "%s: %s\n", type_matcher.GetMatchString().GetCString(),
-  format_sp->GetDescription().c_str());
   return true;
 });
 
@@ -1121,24 +1119,13 @@
 .SetWithRegex([&result, &formatter_regex, &any_printed](
   const TypeMatcher &type_matcher,
   const FormatterSharedPointer &format_sp) -> bool {
-  if (formatter_regex) {
-bool escape = true;
-if (type_matcher.CreatedBySameMatchString(
-ConstString(formatter_regex->GetText( {
-  escape = false;
-} else if (formatter_regex->Execute(
-   type_matcher.GetMatchString().GetStringRef())) {
-  escape = false;
-}
-
-if (escape)
-  return true;
+  if (ShouldListItem(type_matcher.GetMatchString().GetStringRef(),
+ formatter_regex.get())) {
+any_printed = true;
+result.GetOutputStream().Printf(
+"%s: %s\n", type_matcher.GetMatchString().GetCString(),
+format_sp->GetDescription().c_str());
   }
-
-  any_printed = true;
-  result.GetOutputStream().Printf(
-  "%s: %s\n", type_matcher.GetMatchString().GetCString(),
-  format_sp->GetDescription().c_str());
   return true;
 });
 
@@ -1155,20 +1142,9 @@
   DataVisualization::Categories::ForEach(
   [&category_regex, &category_closure](
   const lldb::TypeCategoryImplSP &category) -> bool {
-if (category_regex) {
-  bool escape = true;
-  if (category->GetName() == category_regex->GetText()) {
-escape = false;
-  } else if (category_regex->Execute(category->GetName())) {
-escape = false;
-  }
-
-  if (escape)
-return true;
+if (ShouldListItem(category->GetName(), category_regex.get())) {
+  category_closure(category);
 }
-
-category_closure(category);
-
 return true;
   });
 
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D130219: [lldb][NFCI] Refactor regex filtering logic in CommandObjectTypeFormatterList

2022-07-21 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe updated this revision to Diff 446532.
jgorbe added a comment.

Removed unnecessary parentheses.


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

https://reviews.llvm.org/D130219

Files:
  lldb/source/Commands/CommandObjectType.cpp

Index: lldb/source/Commands/CommandObjectType.cpp
===
--- lldb/source/Commands/CommandObjectType.cpp
+++ lldb/source/Commands/CommandObjectType.cpp
@@ -1055,6 +1055,15 @@
 return false;
   }
 
+  static bool ShouldListItem(llvm::StringRef s, RegularExpression *regex) {
+// If we have a regex, it can match two kinds of results:
+//   - An item created with that same regex string (exact string match), so
+// the user can list it using the same string it used at creation time.
+//   - Items that match the regex.
+// No regex means list everything.
+return regex == nullptr || s == regex->GetText() || regex->Execute(s);
+  }
+
   bool DoExecute(Args &command, CommandReturnObject &result) override {
 const size_t argc = command.GetArgumentCount();
 
@@ -1096,24 +1105,13 @@
 .SetExact([&result, &formatter_regex, &any_printed](
   const TypeMatcher &type_matcher,
   const FormatterSharedPointer &format_sp) -> bool {
-  if (formatter_regex) {
-bool escape = true;
-if (type_matcher.CreatedBySameMatchString(
-ConstString(formatter_regex->GetText( {
-  escape = false;
-} else if (formatter_regex->Execute(
-   type_matcher.GetMatchString().GetStringRef())) {
-  escape = false;
-}
-
-if (escape)
-  return true;
+  if (ShouldListItem(type_matcher.GetMatchString().GetStringRef(),
+ formatter_regex.get())) {
+any_printed = true;
+result.GetOutputStream().Printf(
+"%s: %s\n", type_matcher.GetMatchString().GetCString(),
+format_sp->GetDescription().c_str());
   }
-
-  any_printed = true;
-  result.GetOutputStream().Printf(
-  "%s: %s\n", type_matcher.GetMatchString().GetCString(),
-  format_sp->GetDescription().c_str());
   return true;
 });
 
@@ -1121,24 +1119,13 @@
 .SetWithRegex([&result, &formatter_regex, &any_printed](
   const TypeMatcher &type_matcher,
   const FormatterSharedPointer &format_sp) -> bool {
-  if (formatter_regex) {
-bool escape = true;
-if (type_matcher.CreatedBySameMatchString(
-ConstString(formatter_regex->GetText( {
-  escape = false;
-} else if (formatter_regex->Execute(
-   type_matcher.GetMatchString().GetStringRef())) {
-  escape = false;
-}
-
-if (escape)
-  return true;
+  if (ShouldListItem(type_matcher.GetMatchString().GetStringRef(),
+ formatter_regex.get())) {
+any_printed = true;
+result.GetOutputStream().Printf(
+"%s: %s\n", type_matcher.GetMatchString().GetCString(),
+format_sp->GetDescription().c_str());
   }
-
-  any_printed = true;
-  result.GetOutputStream().Printf(
-  "%s: %s\n", type_matcher.GetMatchString().GetCString(),
-  format_sp->GetDescription().c_str());
   return true;
 });
 
@@ -1155,20 +1142,9 @@
   DataVisualization::Categories::ForEach(
   [&category_regex, &category_closure](
   const lldb::TypeCategoryImplSP &category) -> bool {
-if (category_regex) {
-  bool escape = true;
-  if (category->GetName() == category_regex->GetText()) {
-escape = false;
-  } else if (category_regex->Execute(category->GetName())) {
-escape = false;
-  }
-
-  if (escape)
-return true;
+if (ShouldListItem(category->GetName(), category_regex.get())) {
+  category_closure(category);
 }
-
-category_closure(category);
-
 return true;
   });
 
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D130219: [lldb][NFCI] Refactor regex filtering logic in CommandObjectTypeFormatterList

2022-07-21 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe added inline comments.



Comment at: lldb/source/Commands/CommandObjectType.cpp:1064
+// No regex means list everything.
+return (regex == nullptr || (s == regex->GetText() || regex->Execute(s)));
+  }

labath wrote:
> What's up with all the parentheses? This is just a regular `||` between three 
> choices...
Thanks for catching it. Fixed.


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

https://reviews.llvm.org/D130219

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


[Lldb-commits] [PATCH] D130219: [lldb][NFCI] Refactor regex filtering logic in CommandObjectTypeFormatterList

2022-07-21 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGfa3a2e611d84: [lldb][NFCI] Refactor regex filtering logic in 
CommandObjectTypeFormatterList (authored by jgorbe).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130219

Files:
  lldb/source/Commands/CommandObjectType.cpp

Index: lldb/source/Commands/CommandObjectType.cpp
===
--- lldb/source/Commands/CommandObjectType.cpp
+++ lldb/source/Commands/CommandObjectType.cpp
@@ -1055,6 +1055,15 @@
 return false;
   }
 
+  static bool ShouldListItem(llvm::StringRef s, RegularExpression *regex) {
+// If we have a regex, it can match two kinds of results:
+//   - An item created with that same regex string (exact string match), so
+// the user can list it using the same string it used at creation time.
+//   - Items that match the regex.
+// No regex means list everything.
+return regex == nullptr || s == regex->GetText() || regex->Execute(s);
+  }
+
   bool DoExecute(Args &command, CommandReturnObject &result) override {
 const size_t argc = command.GetArgumentCount();
 
@@ -1096,24 +1105,13 @@
 .SetExact([&result, &formatter_regex, &any_printed](
   const TypeMatcher &type_matcher,
   const FormatterSharedPointer &format_sp) -> bool {
-  if (formatter_regex) {
-bool escape = true;
-if (type_matcher.CreatedBySameMatchString(
-ConstString(formatter_regex->GetText( {
-  escape = false;
-} else if (formatter_regex->Execute(
-   type_matcher.GetMatchString().GetStringRef())) {
-  escape = false;
-}
-
-if (escape)
-  return true;
+  if (ShouldListItem(type_matcher.GetMatchString().GetStringRef(),
+ formatter_regex.get())) {
+any_printed = true;
+result.GetOutputStream().Printf(
+"%s: %s\n", type_matcher.GetMatchString().GetCString(),
+format_sp->GetDescription().c_str());
   }
-
-  any_printed = true;
-  result.GetOutputStream().Printf(
-  "%s: %s\n", type_matcher.GetMatchString().GetCString(),
-  format_sp->GetDescription().c_str());
   return true;
 });
 
@@ -1121,24 +1119,13 @@
 .SetWithRegex([&result, &formatter_regex, &any_printed](
   const TypeMatcher &type_matcher,
   const FormatterSharedPointer &format_sp) -> bool {
-  if (formatter_regex) {
-bool escape = true;
-if (type_matcher.CreatedBySameMatchString(
-ConstString(formatter_regex->GetText( {
-  escape = false;
-} else if (formatter_regex->Execute(
-   type_matcher.GetMatchString().GetStringRef())) {
-  escape = false;
-}
-
-if (escape)
-  return true;
+  if (ShouldListItem(type_matcher.GetMatchString().GetStringRef(),
+ formatter_regex.get())) {
+any_printed = true;
+result.GetOutputStream().Printf(
+"%s: %s\n", type_matcher.GetMatchString().GetCString(),
+format_sp->GetDescription().c_str());
   }
-
-  any_printed = true;
-  result.GetOutputStream().Printf(
-  "%s: %s\n", type_matcher.GetMatchString().GetCString(),
-  format_sp->GetDescription().c_str());
   return true;
 });
 
@@ -1155,20 +1142,9 @@
   DataVisualization::Categories::ForEach(
   [&category_regex, &category_closure](
   const lldb::TypeCategoryImplSP &category) -> bool {
-if (category_regex) {
-  bool escape = true;
-  if (category->GetName() == category_regex->GetText()) {
-escape = false;
-  } else if (category_regex->Execute(category->GetName())) {
-escape = false;
-  }
-
-  if (escape)
-return true;
+if (ShouldListItem(category->GetName(), category_regex.get())) {
+  category_closure(category);
 }
-
-category_closure(category);
-
 return true;
   });
 
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D131459: Move FormattersMatchCandidate flags to a struct.

2022-08-08 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe created this revision.
Herald added a project: All.
jgorbe requested review of this revision.
Herald added a project: LLDB.

Move FormattersMatchCandidate flags to a struct.

This removes some error-prone repetition in
FormatManager::GetPossibleMatches, where the same three boolean flags
are passed in a row multiple times as arguments to recursive calls to
GetPossibleMatches.

Instead of:

  // same flags, but with did_strip_typedef set to true.
  GetPossibleMatches(..., did_strip_ptr, did_strip_ref, true);

we can now say

  GetPossibleMatches(..., current_flags.WithStrippedTypedef());

which hopefully makes the intent clearer, and more readable in case we
add another flag.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D131459

Files:
  lldb/include/lldb/DataFormatters/FormatClasses.h
  lldb/include/lldb/DataFormatters/FormatManager.h
  lldb/source/DataFormatters/FormatManager.cpp

Index: lldb/source/DataFormatters/FormatManager.cpp
===
--- lldb/source/DataFormatters/FormatManager.cpp
+++ lldb/source/DataFormatters/FormatManager.cpp
@@ -175,60 +175,51 @@
 void FormatManager::GetPossibleMatches(
 ValueObject &valobj, CompilerType compiler_type,
 lldb::DynamicValueType use_dynamic, FormattersMatchVector &entries,
-bool did_strip_ptr, bool did_strip_ref, bool did_strip_typedef,
-bool root_level) {
+FormattersMatchCandidate::Flags current_flags, bool root_level) {
   compiler_type = compiler_type.GetTypeForFormatters();
   ConstString type_name(compiler_type.GetTypeName());
   if (valobj.GetBitfieldBitSize() > 0) {
 StreamString sstring;
 sstring.Printf("%s:%d", type_name.AsCString(), valobj.GetBitfieldBitSize());
 ConstString bitfieldname(sstring.GetString());
-entries.push_back(
-{bitfieldname, did_strip_ptr, did_strip_ref, did_strip_typedef});
+entries.push_back({bitfieldname, current_flags});
   }
 
   if (!compiler_type.IsMeaninglessWithoutDynamicResolution()) {
-entries.push_back(
-{type_name, did_strip_ptr, did_strip_ref, did_strip_typedef});
+entries.push_back({type_name, current_flags});
 
 ConstString display_type_name(compiler_type.GetTypeName());
 if (display_type_name != type_name)
-  entries.push_back({display_type_name, did_strip_ptr,
- did_strip_ref, did_strip_typedef});
+  entries.push_back({display_type_name, current_flags});
   }
 
   for (bool is_rvalue_ref = true, j = true;
j && compiler_type.IsReferenceType(nullptr, &is_rvalue_ref); j = false) {
 CompilerType non_ref_type = compiler_type.GetNonReferenceType();
-GetPossibleMatches(
-valobj, non_ref_type,
-use_dynamic, entries, did_strip_ptr, true, did_strip_typedef);
+GetPossibleMatches(valobj, non_ref_type, use_dynamic, entries,
+   current_flags.WithStrippedReference());
 if (non_ref_type.IsTypedefType()) {
   CompilerType deffed_referenced_type = non_ref_type.GetTypedefedType();
   deffed_referenced_type =
   is_rvalue_ref ? deffed_referenced_type.GetRValueReferenceType()
 : deffed_referenced_type.GetLValueReferenceType();
+  // this is not exactly the usual meaning of stripping typedefs
   GetPossibleMatches(
   valobj, deffed_referenced_type,
-  use_dynamic, entries, did_strip_ptr, did_strip_ref,
-  true); // this is not exactly the usual meaning of stripping typedefs
+  use_dynamic, entries, current_flags.WithStrippedTypedef());
 }
   }
 
   if (compiler_type.IsPointerType()) {
 CompilerType non_ptr_type = compiler_type.GetPointeeType();
-GetPossibleMatches(
-valobj, non_ptr_type,
-use_dynamic, entries, true, did_strip_ref, did_strip_typedef);
+GetPossibleMatches(valobj, non_ptr_type, use_dynamic, entries,
+   current_flags.WithStrippedPointer());
 if (non_ptr_type.IsTypedefType()) {
   CompilerType deffed_pointed_type =
   non_ptr_type.GetTypedefedType().GetPointerType();
-  const bool stripped_typedef = true;
-  GetPossibleMatches(
-  valobj, deffed_pointed_type,
-  use_dynamic, entries, did_strip_ptr, did_strip_ref,
-  stripped_typedef); // this is not exactly the usual meaning of
- // stripping typedefs
+  // this is not exactly the usual meaning of stripping typedefs
+  GetPossibleMatches(valobj, deffed_pointed_type, use_dynamic, entries,
+ current_flags.WithStrippedTypedef());
 }
   }
 
@@ -244,12 +235,10 @@
   // from it.
   CompilerType deffed_array_type =
   element_type.GetTypedefedType().GetArrayType(array_size);
-  const bool stripped_typedef = true;
+  // this is not exactly the usual meaning of stripping typedefs
   GetPossibleMatches(
   valobj, deffed_array_type,
-  use_dynamic, entri

[Lldb-commits] [PATCH] D131459: Move FormattersMatchCandidate flags to a struct.

2022-08-09 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGfe01292457fc: Move FormattersMatchCandidate flags to a 
struct. (authored by jgorbe).

Changed prior to commit:
  https://reviews.llvm.org/D131459?vs=451010&id=451211#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131459

Files:
  lldb/include/lldb/DataFormatters/FormatClasses.h
  lldb/include/lldb/DataFormatters/FormatManager.h
  lldb/source/DataFormatters/FormatManager.cpp

Index: lldb/source/DataFormatters/FormatManager.cpp
===
--- lldb/source/DataFormatters/FormatManager.cpp
+++ lldb/source/DataFormatters/FormatManager.cpp
@@ -175,60 +175,51 @@
 void FormatManager::GetPossibleMatches(
 ValueObject &valobj, CompilerType compiler_type,
 lldb::DynamicValueType use_dynamic, FormattersMatchVector &entries,
-bool did_strip_ptr, bool did_strip_ref, bool did_strip_typedef,
-bool root_level) {
+FormattersMatchCandidate::Flags current_flags, bool root_level) {
   compiler_type = compiler_type.GetTypeForFormatters();
   ConstString type_name(compiler_type.GetTypeName());
   if (valobj.GetBitfieldBitSize() > 0) {
 StreamString sstring;
 sstring.Printf("%s:%d", type_name.AsCString(), valobj.GetBitfieldBitSize());
 ConstString bitfieldname(sstring.GetString());
-entries.push_back(
-{bitfieldname, did_strip_ptr, did_strip_ref, did_strip_typedef});
+entries.push_back({bitfieldname, current_flags});
   }
 
   if (!compiler_type.IsMeaninglessWithoutDynamicResolution()) {
-entries.push_back(
-{type_name, did_strip_ptr, did_strip_ref, did_strip_typedef});
+entries.push_back({type_name, current_flags});
 
 ConstString display_type_name(compiler_type.GetTypeName());
 if (display_type_name != type_name)
-  entries.push_back({display_type_name, did_strip_ptr,
- did_strip_ref, did_strip_typedef});
+  entries.push_back({display_type_name, current_flags});
   }
 
   for (bool is_rvalue_ref = true, j = true;
j && compiler_type.IsReferenceType(nullptr, &is_rvalue_ref); j = false) {
 CompilerType non_ref_type = compiler_type.GetNonReferenceType();
-GetPossibleMatches(
-valobj, non_ref_type,
-use_dynamic, entries, did_strip_ptr, true, did_strip_typedef);
+GetPossibleMatches(valobj, non_ref_type, use_dynamic, entries,
+   current_flags.WithStrippedReference());
 if (non_ref_type.IsTypedefType()) {
   CompilerType deffed_referenced_type = non_ref_type.GetTypedefedType();
   deffed_referenced_type =
   is_rvalue_ref ? deffed_referenced_type.GetRValueReferenceType()
 : deffed_referenced_type.GetLValueReferenceType();
+  // this is not exactly the usual meaning of stripping typedefs
   GetPossibleMatches(
   valobj, deffed_referenced_type,
-  use_dynamic, entries, did_strip_ptr, did_strip_ref,
-  true); // this is not exactly the usual meaning of stripping typedefs
+  use_dynamic, entries, current_flags.WithStrippedTypedef());
 }
   }
 
   if (compiler_type.IsPointerType()) {
 CompilerType non_ptr_type = compiler_type.GetPointeeType();
-GetPossibleMatches(
-valobj, non_ptr_type,
-use_dynamic, entries, true, did_strip_ref, did_strip_typedef);
+GetPossibleMatches(valobj, non_ptr_type, use_dynamic, entries,
+   current_flags.WithStrippedPointer());
 if (non_ptr_type.IsTypedefType()) {
   CompilerType deffed_pointed_type =
   non_ptr_type.GetTypedefedType().GetPointerType();
-  const bool stripped_typedef = true;
-  GetPossibleMatches(
-  valobj, deffed_pointed_type,
-  use_dynamic, entries, did_strip_ptr, did_strip_ref,
-  stripped_typedef); // this is not exactly the usual meaning of
- // stripping typedefs
+  // this is not exactly the usual meaning of stripping typedefs
+  GetPossibleMatches(valobj, deffed_pointed_type, use_dynamic, entries,
+ current_flags.WithStrippedTypedef());
 }
   }
 
@@ -244,12 +235,10 @@
   // from it.
   CompilerType deffed_array_type =
   element_type.GetTypedefedType().GetArrayType(array_size);
-  const bool stripped_typedef = true;
+  // this is not exactly the usual meaning of stripping typedefs
   GetPossibleMatches(
   valobj, deffed_array_type,
-  use_dynamic, entries, did_strip_ptr, did_strip_ref,
-  stripped_typedef); // this is not exactly the usual meaning of
- // stripping typedefs
+  use_dynamic, entries, current_flags.WithStrippedTypedef());
 }
   }
 
@@ -258,9 +247,7 @@
 if (Language *language = Language::

[Lldb-commits] [PATCH] D126103: Remove `friend` classes from TypeCategoryMap

2022-05-20 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe created this revision.
jgorbe added reviewers: labath, JDevlieghere.
Herald added a project: All.
jgorbe requested review of this revision.
Herald added a project: LLDB.

As far as I can tell, the only thing those `friend` classes access is the
`ValueSP` typedef.

Given that this is a map-ish class, with "Map" in its name, it doesn't seem like
a stretch to make `KeyType`, `ValueType` and `ValueSP` public. More so when the
public methods of the class have `KeyType` and `ValueSP` arguments and clearly
`ValueSP` needs to be accessed from the outside.

`friend` complicates local reasoning about who can access private members, which
is valuable in a class like this that has every method locking a mutex to
prevent concurrent access.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D126103

Files:
  lldb/include/lldb/DataFormatters/TypeCategoryMap.h


Index: lldb/include/lldb/DataFormatters/TypeCategoryMap.h
===
--- lldb/include/lldb/DataFormatters/TypeCategoryMap.h
+++ lldb/include/lldb/DataFormatters/TypeCategoryMap.h
@@ -23,13 +23,13 @@
 namespace lldb_private {
 class TypeCategoryMap {
 private:
-  typedef ConstString KeyType;
-  typedef TypeCategoryImpl ValueType;
-  typedef ValueType::SharedPointer ValueSP;
   typedef std::list ActiveCategoriesList;
   typedef ActiveCategoriesList::iterator ActiveCategoriesIterator;
 
 public:
+  typedef ConstString KeyType;
+  typedef TypeCategoryImpl ValueType;
+  typedef ValueType::SharedPointer ValueSP;
   typedef std::map MapType;
   typedef MapType::iterator MapIterator;
   typedef std::function ForEachCallback;
@@ -103,9 +103,6 @@
   ActiveCategoriesList &active_list() { return m_active_categories; }
 
   std::recursive_mutex &mutex() { return m_map_mutex; }
-
-  friend class FormattersContainer;
-  friend class FormatManager;
 };
 } // namespace lldb_private
 


Index: lldb/include/lldb/DataFormatters/TypeCategoryMap.h
===
--- lldb/include/lldb/DataFormatters/TypeCategoryMap.h
+++ lldb/include/lldb/DataFormatters/TypeCategoryMap.h
@@ -23,13 +23,13 @@
 namespace lldb_private {
 class TypeCategoryMap {
 private:
-  typedef ConstString KeyType;
-  typedef TypeCategoryImpl ValueType;
-  typedef ValueType::SharedPointer ValueSP;
   typedef std::list ActiveCategoriesList;
   typedef ActiveCategoriesList::iterator ActiveCategoriesIterator;
 
 public:
+  typedef ConstString KeyType;
+  typedef TypeCategoryImpl ValueType;
+  typedef ValueType::SharedPointer ValueSP;
   typedef std::map MapType;
   typedef MapType::iterator MapIterator;
   typedef std::function ForEachCallback;
@@ -103,9 +103,6 @@
   ActiveCategoriesList &active_list() { return m_active_categories; }
 
   std::recursive_mutex &mutex() { return m_map_mutex; }
-
-  friend class FormattersContainer;
-  friend class FormatManager;
 };
 } // namespace lldb_private
 
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D126103: Remove `friend` classes from TypeCategoryMap

2022-05-23 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGf0a61c2ce2af: Remove `friend` classes from TypeCategoryMap 
(authored by jgorbe).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126103

Files:
  lldb/include/lldb/DataFormatters/TypeCategoryMap.h


Index: lldb/include/lldb/DataFormatters/TypeCategoryMap.h
===
--- lldb/include/lldb/DataFormatters/TypeCategoryMap.h
+++ lldb/include/lldb/DataFormatters/TypeCategoryMap.h
@@ -23,13 +23,13 @@
 namespace lldb_private {
 class TypeCategoryMap {
 private:
-  typedef ConstString KeyType;
-  typedef TypeCategoryImpl ValueType;
-  typedef ValueType::SharedPointer ValueSP;
   typedef std::list ActiveCategoriesList;
   typedef ActiveCategoriesList::iterator ActiveCategoriesIterator;
 
 public:
+  typedef ConstString KeyType;
+  typedef TypeCategoryImpl ValueType;
+  typedef ValueType::SharedPointer ValueSP;
   typedef std::map MapType;
   typedef MapType::iterator MapIterator;
   typedef std::function ForEachCallback;
@@ -103,9 +103,6 @@
   ActiveCategoriesList &active_list() { return m_active_categories; }
 
   std::recursive_mutex &mutex() { return m_map_mutex; }
-
-  friend class FormattersContainer;
-  friend class FormatManager;
 };
 } // namespace lldb_private
 


Index: lldb/include/lldb/DataFormatters/TypeCategoryMap.h
===
--- lldb/include/lldb/DataFormatters/TypeCategoryMap.h
+++ lldb/include/lldb/DataFormatters/TypeCategoryMap.h
@@ -23,13 +23,13 @@
 namespace lldb_private {
 class TypeCategoryMap {
 private:
-  typedef ConstString KeyType;
-  typedef TypeCategoryImpl ValueType;
-  typedef ValueType::SharedPointer ValueSP;
   typedef std::list ActiveCategoriesList;
   typedef ActiveCategoriesList::iterator ActiveCategoriesIterator;
 
 public:
+  typedef ConstString KeyType;
+  typedef TypeCategoryImpl ValueType;
+  typedef ValueType::SharedPointer ValueSP;
   typedef std::map MapType;
   typedef MapType::iterator MapIterator;
   typedef std::function ForEachCallback;
@@ -103,9 +103,6 @@
   ActiveCategoriesList &active_list() { return m_active_categories; }
 
   std::recursive_mutex &mutex() { return m_map_mutex; }
-
-  friend class FormattersContainer;
-  friend class FormatManager;
 };
 } // namespace lldb_private
 
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D126240: [lldb] Tighten the scope of a couple of locks in DataFormatters.

2022-05-23 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe created this revision.
jgorbe added reviewers: labath, JDevlieghere.
Herald added a subscriber: pengfei.
Herald added a project: All.
jgorbe requested review of this revision.
Herald added a project: LLDB.

I've noticed (what looked like) deadlocking behavior while running some
Python code that registers categories and formatters from a separate
thread. I ran lldb and my scripts through Helgrind and got (among other
unrelated reports) the report below.

In summary, there are two mutexes (`TypeCategoryMap::m_map_mutex` and
`FormatManager::m_language_categories_mutex`) that sometimes get
acquired in different order. This change attempts to fix that by
reducing the scope of the locks that appear in the Helgrind report.

- `TypeCategoryMap::Add` locks `m_map_mutex` and keeps holding it while 
notifying `listener`. The listener class shouldn't touch any data in 
`TypeCategoryMap` (because everything is private), except by using the class' 
own methods, and all of them acquire the mutex on entry.

  This change makes it release the lock after `m_map_mutex` is updated, but 
before the listener is invoked.

- `FormatManager::GetCategoryForLanguage` does a map lookup (holding 
`m_language_categories_mutex`) and, if the lookup fails, constructs a new 
`LanguageCategory`. This also results in listeners being called while still 
holding the mutex.

  This patch changes it so that the lock is only held during initial lookup. If 
lookup fails, the new category will be created and only then we'll acquire the 
lock again to insert the new category into the map.

Here's the Helgrind report for reference:

  ==3574084== 
  ==3574084==
  ==3574084== Thread #6: lock order "0x1472C070 before 0x1472C110" violated
  ==3574084==
  ==3574084== Observed (incorrect) order is: acquisition of lock at 0x1472C110
  ==3574084==at 0x484777F: mutex_lock_WRK (hg_intercepts.c:942)
  ==3574084==by 0xADFF5E2: __gthread_mutex_lock(pthread_mutex_t*) 
(bin/../lib/gcc/x86_64-linux-gnu/11/../../../../include/x86_64-linux-gnu/c++/11/bits/gthr-default.h:749)
  ==3574084==by 0xADFF5B4: __gthread_recursive_mutex_lock(pthread_mutex_t*) 
(bin/../lib/gcc/x86_64-linux-gnu/11/../../../../include/x86_64-linux-gnu/c++/11/bits/gthr-default.h:811)
  ==3574084==by 0xAE00D34: std::recursive_mutex::lock() 
(bin/../lib/gcc/x86_64-linux-gnu/11/../../../../include/c++/11/mutex:108)
  ==3574084==by 0xADFFEB2: 
std::lock_guard::lock_guard(std::recursive_mutex&) 
(bin/../lib/gcc/x86_64-linux-gnu/11/../../../../include/c++/11/bits/std_mutex.h:229)
  ==3574084==by 0xB2F1E04: 
lldb_private::TypeCategoryMap::Add(lldb_private::ConstString, 
std::shared_ptr const&) 
(llvm/lldb/source/DataFormatters/TypeCategoryMap.cpp:28)
  ==3574084==by 0xB2D8A57: 
lldb_private::FormatManager::GetCategory(lldb_private::ConstString, bool) 
(llvm/lldb/source/DataFormatters/FormatManager.cpp:423)
  ==3574084==by 0xB2D380B: 
lldb_private::DataVisualization::Categories::GetCategory(lldb_private::ConstString,
 std::shared_ptr&, bool) 
(llvm/lldb/source/DataFormatters/DataVisualization.cpp:79)
  ==3574084==by 0xAE47DFD: lldb::SBDebugger::CreateCategory(char const*) 
(llvm/lldb/source/API/SBDebugger.cpp:1535)
  ==3574084==by 0xAF7BA0B: _wrap_SBDebugger_CreateCategory(_object*, 
_object*) (LLDBWrapPython.cpp:24738)
  ==3574084==by 0x14E77483: ??? (in 
/usr/lib/x86_64-linux-gnu/libpython3.9.so.1.0)
  ==3574084==by 0x14E33A07: _PyObject_MakeTpCall (in 
/usr/lib/x86_64-linux-gnu/libpython3.9.so.1.0)
  ==3574084==
  ==3574084==  followed by a later acquisition of lock at 0x1472C070
  ==3574084==at 0x484777F: mutex_lock_WRK (hg_intercepts.c:942)
  ==3574084==by 0xADFF5E2: __gthread_mutex_lock(pthread_mutex_t*) 
(bin/../lib/gcc/x86_64-linux-gnu/11/../../../../include/x86_64-linux-gnu/c++/11/bits/gthr-default.h:749)
  ==3574084==by 0xADFF5B4: __gthread_recursive_mutex_lock(pthread_mutex_t*) 
(bin/../lib/gcc/x86_64-linux-gnu/11/../../../../include/x86_64-linux-gnu/c++/11/bits/gthr-default.h:811)
  ==3574084==by 0xAE00D34: std::recursive_mutex::lock() 
(bin/../lib/gcc/x86_64-linux-gnu/11/../../../../include/c++/11/mutex:108)
  ==3574084==by 0xADFFEB2: 
std::lock_guard::lock_guard(std::recursive_mutex&) 
(bin/../lib/gcc/x86_64-linux-gnu/11/../../../../include/c++/11/bits/std_mutex.h:229)
  ==3574084==by 0xB2D6DDA: lldb_private::FormatManager::Changed() 
(llvm/lldb/source/DataFormatters/FormatManager.cpp:118)
  ==3574084==by 0xB2F1E46: 
lldb_private::TypeCategoryMap::Add(lldb_private::ConstString, 
std::shared_ptr const&) 
(llvm/lldb/source/DataFormatters/TypeCategoryMap.cpp:31)
  ==3574084==by 0xB2D8A57: 
lldb_private::FormatManager::GetCategory(lldb_private::ConstString, bool) 
(llvm/lldb/source/DataFormatters/FormatManager.cpp:423)
  ==3574084==by 0xB2D380B: 
lldb_private::DataVisualization::Categories::GetCategory(lldb_private::ConstString,
 std::shared_p

[Lldb-commits] [PATCH] D126240: [lldb] Tighten the scope of a couple of locks in DataFormatters.

2022-06-03 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe added inline comments.



Comment at: lldb/source/DataFormatters/FormatManager.cpp:595
+  {
+std::lock_guard guard(m_language_categories_mutex);
+m_language_categories_map[lang_type] =

hawkinsw wrote:
> Forgive me if I am speaking out of turn, but do we need to check again here 
> for whether `lang_type` is in the map? In other words, it seems possible that 
> (in some zany situation) while we are doing the memory allocation (line 593) 
> someone else has come along and added that category since we released the 
> lock on it in 592. 
> 
> I hope that this is helpful. Please (again) forgive me if I am speaking out 
> of turn.
Not at all! Thank you for your comment! :)

You are absolutely right, I had overlooked this case. Another annoying 
consequence is that in this case the racing threads would create multiple 
`LanguageCategory` objects. The `LanguageCategory` constructor calls `Enable` 
which in turn ends up calling the `Changed` method of the listener, so even if 
we check the map before insertion I think we'd still see the listener receiving 
multiple notifications that the category was enabled, which is not ideal.

I don't know how to properly fix this. I'll give it some more thought.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126240

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


[Lldb-commits] [PATCH] D126240: [lldb] Tighten the scope of a couple of locks in DataFormatters.

2022-06-07 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe added a comment.

I've been experimenting a little bit and it seems that I can avoid the 
deadlocks I was seeing by applying only the modification to 
`TypeCategoryMap::Add`. This would avoid the problem that @hawkinsw pointed out 
in my change to `FormatManager::GetCategoryForLanguage`. However, the following 
problem could still happen with the change to `TypeCategoryMap::Add`:

1. Thread A acquires the lock, runs `m_map[key1] = value1`, and releases the 
lock
2. Thread B acquires the lock, runs `m_map[key2] = value2`, and releases the 
lock
3. Thread A runs `listener->Changed()`
4. Thread B runs `listener->Changed()`

So we would have two changes, the listener would be called twice, but both 
listener calls would see the same state with the two changes already applied, 
instead of observing each change individually. I'll keep thinking to see if I 
can fix this elsewhere.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126240

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


[Lldb-commits] [PATCH] D142672: [lldb] Make SBSection::GetSectionData call Section::GetSectionData.

2023-01-26 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe created this revision.
jgorbe added a reviewer: labath.
jgorbe added a project: LLDB.
Herald added a subscriber: JDevlieghere.
Herald added a project: All.
jgorbe requested review of this revision.

`SBSection::GetSectionData` and `Section::GetSectionData` are
implemented differently, and the `SBSection` method doesn't handle
compressed sections correctly.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D142672

Files:
  lldb/source/API/SBSection.cpp
  lldb/test/API/python_api/section/TestSectionAPI.py
  lldb/test/API/python_api/section/compressed-sections.yaml


Index: lldb/test/API/python_api/section/compressed-sections.yaml
===
--- /dev/null
+++ lldb/test/API/python_api/section/compressed-sections.yaml
@@ -0,0 +1,11 @@
+--- !ELF
+FileHeader:
+  Class:   ELFCLASS32
+  Data:ELFDATA2LSB
+  Type:ET_REL
+  Machine: EM_386
+Sections:
+  - Name:.compressed
+Type:SHT_PROGBITS
+Flags:   [ SHF_COMPRESSED ]
+Content: 010008000100789c533070084828689809c802c1
Index: lldb/test/API/python_api/section/TestSectionAPI.py
===
--- lldb/test/API/python_api/section/TestSectionAPI.py
+++ lldb/test/API/python_api/section/TestSectionAPI.py
@@ -48,3 +48,18 @@
 section = target.modules[0].sections[0]
 self.assertEqual(section.GetAlignment(), 0x1000)
 self.assertEqual(section.alignment, 0x1000)
+
+def test_compressed_section_data(self):
+exe = self.getBuildArtifact("compressed-sections.out")
+self.yaml2obj("compressed-sections.yaml", exe)
+target = self.dbg.CreateTarget(exe)
+self.assertTrue(target, VALID_TARGET)
+
+# exe contains a single section with SHF_COMPRESSED. Check that
+# GetSectionData returns the uncompressed data and not the raw contents
+# of the section.
+section = target.modules[0].sections[0]
+section_data = section.GetSectionData().uint8s
+self.assertEqual(section_data,
+ [0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90])
+
Index: lldb/source/API/SBSection.cpp
===
--- lldb/source/API/SBSection.cpp
+++ lldb/source/API/SBSection.cpp
@@ -182,35 +182,11 @@
   SBData sb_data;
   SectionSP section_sp(GetSP());
   if (section_sp) {
-const uint64_t sect_file_size = section_sp->GetFileSize();
-if (sect_file_size > 0) {
-  ModuleSP module_sp(section_sp->GetModule());
-  if (module_sp) {
-ObjectFile *objfile = module_sp->GetObjectFile();
-if (objfile) {
-  const uint64_t sect_file_offset =
-  objfile->GetFileOffset() + section_sp->GetFileOffset();
-  const uint64_t file_offset = sect_file_offset + offset;
-  uint64_t file_size = size;
-  if (file_size == UINT64_MAX) {
-file_size = section_sp->GetByteSize();
-if (file_size > offset)
-  file_size -= offset;
-else
-  file_size = 0;
-  }
-  auto data_buffer_sp = FileSystem::Instance().CreateDataBuffer(
-  objfile->GetFileSpec().GetPath(), file_size, file_offset);
-  if (data_buffer_sp && data_buffer_sp->GetByteSize() > 0) {
-DataExtractorSP data_extractor_sp(
-new DataExtractor(data_buffer_sp, objfile->GetByteOrder(),
-  objfile->GetAddressByteSize()));
-
-sb_data.SetOpaque(data_extractor_sp);
-  }
-}
-  }
-}
+DataExtractor section_data;
+section_sp->GetSectionData(section_data);
+DataExtractorSP result_data_sp =
+std::make_shared(section_data, offset, size);
+sb_data.SetOpaque(result_data_sp);
   }
   return sb_data;
 }


Index: lldb/test/API/python_api/section/compressed-sections.yaml
===
--- /dev/null
+++ lldb/test/API/python_api/section/compressed-sections.yaml
@@ -0,0 +1,11 @@
+--- !ELF
+FileHeader:
+  Class:   ELFCLASS32
+  Data:ELFDATA2LSB
+  Type:ET_REL
+  Machine: EM_386
+Sections:
+  - Name:.compressed
+Type:SHT_PROGBITS
+Flags:   [ SHF_COMPRESSED ]
+Content: 010008000100789c533070084828689809c802c1
Index: lldb/test/API/python_api/section/TestSectionAPI.py
===
--- lldb/test/API/python_api/section/TestSectionAPI.py
+++ lldb/test/API/python_api/section/TestSectionAPI.py
@@ -48,3 +48,18 @@
 section = target.modules[0].sections[0]
 self.assertEqual(section.GetAlignment(), 0x1000)
 self.assertEqual(section.alignment, 0x1000)
+
+def test_compressed_section_data(self):
+exe 

[Lldb-commits] [PATCH] D142672: [lldb] Make SBSection::GetSectionData call Section::GetSectionData.

2023-01-26 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe updated this revision to Diff 492602.
jgorbe added a comment.

Addressing review comment.


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

https://reviews.llvm.org/D142672

Files:
  lldb/source/API/SBSection.cpp
  lldb/test/API/python_api/section/TestSectionAPI.py
  lldb/test/API/python_api/section/compressed-sections.yaml


Index: lldb/test/API/python_api/section/compressed-sections.yaml
===
--- /dev/null
+++ lldb/test/API/python_api/section/compressed-sections.yaml
@@ -0,0 +1,11 @@
+--- !ELF
+FileHeader:
+  Class:   ELFCLASS32
+  Data:ELFDATA2LSB
+  Type:ET_REL
+  Machine: EM_386
+Sections:
+  - Name:.compressed
+Type:SHT_PROGBITS
+Flags:   [ SHF_COMPRESSED ]
+Content: 010008000100789c533070084828689809c802c1
Index: lldb/test/API/python_api/section/TestSectionAPI.py
===
--- lldb/test/API/python_api/section/TestSectionAPI.py
+++ lldb/test/API/python_api/section/TestSectionAPI.py
@@ -48,3 +48,18 @@
 section = target.modules[0].sections[0]
 self.assertEqual(section.GetAlignment(), 0x1000)
 self.assertEqual(section.alignment, 0x1000)
+
+def test_compressed_section_data(self):
+exe = self.getBuildArtifact("compressed-sections.out")
+self.yaml2obj("compressed-sections.yaml", exe)
+target = self.dbg.CreateTarget(exe)
+self.assertTrue(target, VALID_TARGET)
+
+# exe contains a single section with SHF_COMPRESSED. Check that
+# GetSectionData returns the uncompressed data and not the raw contents
+# of the section.
+section = target.modules[0].sections[0]
+section_data = section.GetSectionData().uint8s
+self.assertEqual(section_data,
+ [0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90])
+
Index: lldb/source/API/SBSection.cpp
===
--- lldb/source/API/SBSection.cpp
+++ lldb/source/API/SBSection.cpp
@@ -182,35 +182,10 @@
   SBData sb_data;
   SectionSP section_sp(GetSP());
   if (section_sp) {
-const uint64_t sect_file_size = section_sp->GetFileSize();
-if (sect_file_size > 0) {
-  ModuleSP module_sp(section_sp->GetModule());
-  if (module_sp) {
-ObjectFile *objfile = module_sp->GetObjectFile();
-if (objfile) {
-  const uint64_t sect_file_offset =
-  objfile->GetFileOffset() + section_sp->GetFileOffset();
-  const uint64_t file_offset = sect_file_offset + offset;
-  uint64_t file_size = size;
-  if (file_size == UINT64_MAX) {
-file_size = section_sp->GetByteSize();
-if (file_size > offset)
-  file_size -= offset;
-else
-  file_size = 0;
-  }
-  auto data_buffer_sp = FileSystem::Instance().CreateDataBuffer(
-  objfile->GetFileSpec().GetPath(), file_size, file_offset);
-  if (data_buffer_sp && data_buffer_sp->GetByteSize() > 0) {
-DataExtractorSP data_extractor_sp(
-new DataExtractor(data_buffer_sp, objfile->GetByteOrder(),
-  objfile->GetAddressByteSize()));
-
-sb_data.SetOpaque(data_extractor_sp);
-  }
-}
-  }
-}
+DataExtractor section_data;
+section_sp->GetSectionData(section_data);
+sb_data.SetOpaque(
+std::make_shared(section_data, offset, size));
   }
   return sb_data;
 }


Index: lldb/test/API/python_api/section/compressed-sections.yaml
===
--- /dev/null
+++ lldb/test/API/python_api/section/compressed-sections.yaml
@@ -0,0 +1,11 @@
+--- !ELF
+FileHeader:
+  Class:   ELFCLASS32
+  Data:ELFDATA2LSB
+  Type:ET_REL
+  Machine: EM_386
+Sections:
+  - Name:.compressed
+Type:SHT_PROGBITS
+Flags:   [ SHF_COMPRESSED ]
+Content: 010008000100789c533070084828689809c802c1
Index: lldb/test/API/python_api/section/TestSectionAPI.py
===
--- lldb/test/API/python_api/section/TestSectionAPI.py
+++ lldb/test/API/python_api/section/TestSectionAPI.py
@@ -48,3 +48,18 @@
 section = target.modules[0].sections[0]
 self.assertEqual(section.GetAlignment(), 0x1000)
 self.assertEqual(section.alignment, 0x1000)
+
+def test_compressed_section_data(self):
+exe = self.getBuildArtifact("compressed-sections.out")
+self.yaml2obj("compressed-sections.yaml", exe)
+target = self.dbg.CreateTarget(exe)
+self.assertTrue(target, VALID_TARGET)
+
+# exe contains a single section with SHF_COMPRESSED. Check that
+# GetSectio

[Lldb-commits] [PATCH] D142672: [lldb] Make SBSection::GetSectionData call Section::GetSectionData.

2023-01-26 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe marked an inline comment as done.
jgorbe added inline comments.



Comment at: lldb/source/API/SBSection.cpp:187-189
+DataExtractorSP result_data_sp =
+std::make_shared(section_data, offset, size);
+sb_data.SetOpaque(result_data_sp);

dblaikie wrote:
> Probably either use `std::move` when passing `result_data_sp` to `SetOpaque`, 
> or roll the expressions together (to avoid an unnecessary copy of a ref 
> counted smart pointer, that would cause extra increment/decrement of the ref 
> count)
Done, inlined `result_data_sp` into the `SetOpaque` call. Thanks!


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

https://reviews.llvm.org/D142672

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


[Lldb-commits] [PATCH] D142672: [lldb] Make SBSection::GetSectionData call Section::GetSectionData.

2023-01-27 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
This revision was automatically updated to reflect the committed changes.
jgorbe marked an inline comment as done.
Closed by commit rG805600c7d573: [lldb] Make SBSection::GetSectionData call 
Section::GetSectionData. (authored by jgorbe).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142672

Files:
  lldb/source/API/SBSection.cpp
  lldb/test/API/python_api/section/TestSectionAPI.py
  lldb/test/API/python_api/section/compressed-sections.yaml


Index: lldb/test/API/python_api/section/compressed-sections.yaml
===
--- /dev/null
+++ lldb/test/API/python_api/section/compressed-sections.yaml
@@ -0,0 +1,11 @@
+--- !ELF
+FileHeader:
+  Class:   ELFCLASS32
+  Data:ELFDATA2LSB
+  Type:ET_REL
+  Machine: EM_386
+Sections:
+  - Name:.compressed
+Type:SHT_PROGBITS
+Flags:   [ SHF_COMPRESSED ]
+Content: 010008000100789c533070084828689809c802c1
Index: lldb/test/API/python_api/section/TestSectionAPI.py
===
--- lldb/test/API/python_api/section/TestSectionAPI.py
+++ lldb/test/API/python_api/section/TestSectionAPI.py
@@ -48,3 +48,18 @@
 section = target.modules[0].sections[0]
 self.assertEqual(section.GetAlignment(), 0x1000)
 self.assertEqual(section.alignment, 0x1000)
+
+def test_compressed_section_data(self):
+exe = self.getBuildArtifact("compressed-sections.out")
+self.yaml2obj("compressed-sections.yaml", exe)
+target = self.dbg.CreateTarget(exe)
+self.assertTrue(target, VALID_TARGET)
+
+# exe contains a single section with SHF_COMPRESSED. Check that
+# GetSectionData returns the uncompressed data and not the raw contents
+# of the section.
+section = target.modules[0].sections[0]
+section_data = section.GetSectionData().uint8s
+self.assertEqual(section_data,
+ [0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90])
+
Index: lldb/source/API/SBSection.cpp
===
--- lldb/source/API/SBSection.cpp
+++ lldb/source/API/SBSection.cpp
@@ -182,35 +182,10 @@
   SBData sb_data;
   SectionSP section_sp(GetSP());
   if (section_sp) {
-const uint64_t sect_file_size = section_sp->GetFileSize();
-if (sect_file_size > 0) {
-  ModuleSP module_sp(section_sp->GetModule());
-  if (module_sp) {
-ObjectFile *objfile = module_sp->GetObjectFile();
-if (objfile) {
-  const uint64_t sect_file_offset =
-  objfile->GetFileOffset() + section_sp->GetFileOffset();
-  const uint64_t file_offset = sect_file_offset + offset;
-  uint64_t file_size = size;
-  if (file_size == UINT64_MAX) {
-file_size = section_sp->GetByteSize();
-if (file_size > offset)
-  file_size -= offset;
-else
-  file_size = 0;
-  }
-  auto data_buffer_sp = FileSystem::Instance().CreateDataBuffer(
-  objfile->GetFileSpec().GetPath(), file_size, file_offset);
-  if (data_buffer_sp && data_buffer_sp->GetByteSize() > 0) {
-DataExtractorSP data_extractor_sp(
-new DataExtractor(data_buffer_sp, objfile->GetByteOrder(),
-  objfile->GetAddressByteSize()));
-
-sb_data.SetOpaque(data_extractor_sp);
-  }
-}
-  }
-}
+DataExtractor section_data;
+section_sp->GetSectionData(section_data);
+sb_data.SetOpaque(
+std::make_shared(section_data, offset, size));
   }
   return sb_data;
 }


Index: lldb/test/API/python_api/section/compressed-sections.yaml
===
--- /dev/null
+++ lldb/test/API/python_api/section/compressed-sections.yaml
@@ -0,0 +1,11 @@
+--- !ELF
+FileHeader:
+  Class:   ELFCLASS32
+  Data:ELFDATA2LSB
+  Type:ET_REL
+  Machine: EM_386
+Sections:
+  - Name:.compressed
+Type:SHT_PROGBITS
+Flags:   [ SHF_COMPRESSED ]
+Content: 010008000100789c533070084828689809c802c1
Index: lldb/test/API/python_api/section/TestSectionAPI.py
===
--- lldb/test/API/python_api/section/TestSectionAPI.py
+++ lldb/test/API/python_api/section/TestSectionAPI.py
@@ -48,3 +48,18 @@
 section = target.modules[0].sections[0]
 self.assertEqual(section.GetAlignment(), 0x1000)
 self.assertEqual(section.alignment, 0x1000)
+
+def test_compressed_section_data(self):
+exe = self.getBuildArtifact("compressed-sections.out")
+self.yaml2obj("compressed-sections.yaml", exe)
+  

[Lldb-commits] [PATCH] D146590: [lldb] Update some uses of Python2 API in typemaps.

2023-03-21 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe created this revision.
jgorbe added reviewers: labath, rupprecht.
jgorbe added a project: LLDB.
Herald added a subscriber: JDevlieghere.
Herald added a project: All.
jgorbe requested review of this revision.

Python 3 doesn't have a distinction between PyInt and PyLong, it's all
PyLong now.

This also fixes a bug in SetNumberFromObject. This used to crash LLDB:

  lldb -o "script data=lldb.SBData(); data.SetDataFromUInt64Array([2**63])"

The problem happened in the PyInt path:

  if (PyInt_Check(obj))
  number = static_cast(PyInt_AsLong(obj));

when obj doesn't fit in a signed long, `PyInt_AsLong` would fail with
"OverflowError: Python int too large to convert to C long".

The existing long path does the right thing, as it will call
`PyLong_AsUnsignedLongLong` for uint64_t.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D146590

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


Index: lldb/bindings/python/python-typemaps.swig
===
--- lldb/bindings/python/python-typemaps.swig
+++ lldb/bindings/python/python-typemaps.swig
@@ -103,11 +103,11 @@
 
 // typemap for a char buffer
 %typemap(in) (char *dst, size_t dst_len) {
-  if (!PyInt_Check($input)) {
+  if (!PyLong_Check($input)) {
 PyErr_SetString(PyExc_ValueError, "Expecting an integer");
 SWIG_fail;
   }
-  $2 = PyInt_AsLong($input);
+  $2 = PyLong_AsLong($input);
   if ($2 <= 0) {
 PyErr_SetString(PyExc_ValueError, "Positive integer expected");
 SWIG_fail;
@@ -139,11 +139,11 @@
 
 // typemap for handling an snprintf-like API like SBThread::GetStopDescription.
 %typemap(in) (char *dst_or_null, size_t dst_len) {
-  if (!PyInt_Check($input)) {
+  if (!PyLong_Check($input)) {
 PyErr_SetString(PyExc_ValueError, "Expecting an integer");
 SWIG_fail;
   }
-  $2 = PyInt_AsLong($input);
+  $2 = PyLong_AsLong($input);
   if ($2 <= 0) {
 PyErr_SetString(PyExc_ValueError, "Positive integer expected");
 SWIG_fail;
@@ -205,9 +205,7 @@
 // typemap for an incoming buffer
 // See also SBProcess::ReadMemory.
 %typemap(in) (void *buf, size_t size) {
-  if (PyInt_Check($input)) {
-$2 = PyInt_AsLong($input);
-  } else if (PyLong_Check($input)) {
+  if (PyLong_Check($input)) {
 $2 = PyLong_AsLong($input);
   } else {
 PyErr_SetString(PyExc_ValueError, "Expecting an integer or long object");
@@ -258,9 +256,7 @@
 }
 
 template  bool SetNumberFromPyObject(T &number, PyObject *obj) {
-  if (PyInt_Check(obj))
-number = static_cast(PyInt_AsLong(obj));
-  else if (PyLong_Check(obj))
+  if (PyLong_Check(obj))
 number = PyLongAsT(obj);
   else
 return false;
@@ -345,7 +341,7 @@
 count = $2;
   PyObject *list = PyList_New(count);
   for (uint32_t j = 0; j < count; j++) {
-PyObject *item = PyInt_FromLong($1[j]);
+PyObject *item = PyLong_FromLong($1[j]);
 int ok = PyList_SetItem(list, j, item);
 if (ok != 0) {
   $result = Py_None;


Index: lldb/bindings/python/python-typemaps.swig
===
--- lldb/bindings/python/python-typemaps.swig
+++ lldb/bindings/python/python-typemaps.swig
@@ -103,11 +103,11 @@
 
 // typemap for a char buffer
 %typemap(in) (char *dst, size_t dst_len) {
-  if (!PyInt_Check($input)) {
+  if (!PyLong_Check($input)) {
 PyErr_SetString(PyExc_ValueError, "Expecting an integer");
 SWIG_fail;
   }
-  $2 = PyInt_AsLong($input);
+  $2 = PyLong_AsLong($input);
   if ($2 <= 0) {
 PyErr_SetString(PyExc_ValueError, "Positive integer expected");
 SWIG_fail;
@@ -139,11 +139,11 @@
 
 // typemap for handling an snprintf-like API like SBThread::GetStopDescription.
 %typemap(in) (char *dst_or_null, size_t dst_len) {
-  if (!PyInt_Check($input)) {
+  if (!PyLong_Check($input)) {
 PyErr_SetString(PyExc_ValueError, "Expecting an integer");
 SWIG_fail;
   }
-  $2 = PyInt_AsLong($input);
+  $2 = PyLong_AsLong($input);
   if ($2 <= 0) {
 PyErr_SetString(PyExc_ValueError, "Positive integer expected");
 SWIG_fail;
@@ -205,9 +205,7 @@
 // typemap for an incoming buffer
 // See also SBProcess::ReadMemory.
 %typemap(in) (void *buf, size_t size) {
-  if (PyInt_Check($input)) {
-$2 = PyInt_AsLong($input);
-  } else if (PyLong_Check($input)) {
+  if (PyLong_Check($input)) {
 $2 = PyLong_AsLong($input);
   } else {
 PyErr_SetString(PyExc_ValueError, "Expecting an integer or long object");
@@ -258,9 +256,7 @@
 }
 
 template  bool SetNumberFromPyObject(T &number, PyObject *obj) {
-  if (PyInt_Check(obj))
-number = static_cast(PyInt_AsLong(obj));
-  else if (PyLong_Check(obj))
+  if (PyLong_Check(obj))
 number = PyLongAsT(obj);
   else
 return false;
@@ -345,7 +341,7 @@
 count = $2;
   PyObject *list = PyList_New(count);
   for (uint32_t j = 0; j < count; j++) {
-PyObject *item = PyInt_FromLong($1[j]);
+PyObject *item = PyLong_FromLong($1[j]);
 int ok = PyList_SetItem(list, j, item);
 if (ok != 0)

[Lldb-commits] [PATCH] D146590: [lldb] Update some uses of Python2 API in typemaps.

2023-03-22 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe updated this revision to Diff 507442.
jgorbe added a comment.

Modified one of the existing test cases for `SBData.SetDataFromUInt64Array` to 
add a 2**63 to actually exercise the uint64 range.


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

https://reviews.llvm.org/D146590

Files:
  lldb/bindings/python/python-typemaps.swig
  lldb/test/API/python_api/sbdata/TestSBData.py


Index: lldb/test/API/python_api/sbdata/TestSBData.py
===
--- lldb/test/API/python_api/sbdata/TestSBData.py
+++ lldb/test/API/python_api/sbdata/TestSBData.py
@@ -387,12 +387,13 @@
 self.assert_data(data2.GetUnsignedInt8, 4, 111)
 self.assert_data(data2.GetUnsignedInt8, 5, 33)
 
-data2.SetDataFromUInt64Array([1, 2, 3, 4, 5])
+data2.SetDataFromUInt64Array([1, 2, 3, 4, 5, 2**63])
 self.assert_data(data2.GetUnsignedInt64, 0, 1)
 self.assert_data(data2.GetUnsignedInt64, 8, 2)
 self.assert_data(data2.GetUnsignedInt64, 16, 3)
 self.assert_data(data2.GetUnsignedInt64, 24, 4)
 self.assert_data(data2.GetUnsignedInt64, 32, 5)
+self.assert_data(data2.GetUnsignedInt64, 40, 2**63)
 
 self.assertEqual(
 data2.uint64[0], 1,
Index: lldb/bindings/python/python-typemaps.swig
===
--- lldb/bindings/python/python-typemaps.swig
+++ lldb/bindings/python/python-typemaps.swig
@@ -103,11 +103,11 @@
 
 // typemap for a char buffer
 %typemap(in) (char *dst, size_t dst_len) {
-  if (!PyInt_Check($input)) {
+  if (!PyLong_Check($input)) {
 PyErr_SetString(PyExc_ValueError, "Expecting an integer");
 SWIG_fail;
   }
-  $2 = PyInt_AsLong($input);
+  $2 = PyLong_AsLong($input);
   if ($2 <= 0) {
 PyErr_SetString(PyExc_ValueError, "Positive integer expected");
 SWIG_fail;
@@ -139,11 +139,11 @@
 
 // typemap for handling an snprintf-like API like SBThread::GetStopDescription.
 %typemap(in) (char *dst_or_null, size_t dst_len) {
-  if (!PyInt_Check($input)) {
+  if (!PyLong_Check($input)) {
 PyErr_SetString(PyExc_ValueError, "Expecting an integer");
 SWIG_fail;
   }
-  $2 = PyInt_AsLong($input);
+  $2 = PyLong_AsLong($input);
   if ($2 <= 0) {
 PyErr_SetString(PyExc_ValueError, "Positive integer expected");
 SWIG_fail;
@@ -205,9 +205,7 @@
 // typemap for an incoming buffer
 // See also SBProcess::ReadMemory.
 %typemap(in) (void *buf, size_t size) {
-  if (PyInt_Check($input)) {
-$2 = PyInt_AsLong($input);
-  } else if (PyLong_Check($input)) {
+  if (PyLong_Check($input)) {
 $2 = PyLong_AsLong($input);
   } else {
 PyErr_SetString(PyExc_ValueError, "Expecting an integer or long object");
@@ -258,9 +256,7 @@
 }
 
 template  bool SetNumberFromPyObject(T &number, PyObject *obj) {
-  if (PyInt_Check(obj))
-number = static_cast(PyInt_AsLong(obj));
-  else if (PyLong_Check(obj))
+  if (PyLong_Check(obj))
 number = PyLongAsT(obj);
   else
 return false;
@@ -345,7 +341,7 @@
 count = $2;
   PyObject *list = PyList_New(count);
   for (uint32_t j = 0; j < count; j++) {
-PyObject *item = PyInt_FromLong($1[j]);
+PyObject *item = PyLong_FromLong($1[j]);
 int ok = PyList_SetItem(list, j, item);
 if (ok != 0) {
   $result = Py_None;


Index: lldb/test/API/python_api/sbdata/TestSBData.py
===
--- lldb/test/API/python_api/sbdata/TestSBData.py
+++ lldb/test/API/python_api/sbdata/TestSBData.py
@@ -387,12 +387,13 @@
 self.assert_data(data2.GetUnsignedInt8, 4, 111)
 self.assert_data(data2.GetUnsignedInt8, 5, 33)
 
-data2.SetDataFromUInt64Array([1, 2, 3, 4, 5])
+data2.SetDataFromUInt64Array([1, 2, 3, 4, 5, 2**63])
 self.assert_data(data2.GetUnsignedInt64, 0, 1)
 self.assert_data(data2.GetUnsignedInt64, 8, 2)
 self.assert_data(data2.GetUnsignedInt64, 16, 3)
 self.assert_data(data2.GetUnsignedInt64, 24, 4)
 self.assert_data(data2.GetUnsignedInt64, 32, 5)
+self.assert_data(data2.GetUnsignedInt64, 40, 2**63)
 
 self.assertEqual(
 data2.uint64[0], 1,
Index: lldb/bindings/python/python-typemaps.swig
===
--- lldb/bindings/python/python-typemaps.swig
+++ lldb/bindings/python/python-typemaps.swig
@@ -103,11 +103,11 @@
 
 // typemap for a char buffer
 %typemap(in) (char *dst, size_t dst_len) {
-  if (!PyInt_Check($input)) {
+  if (!PyLong_Check($input)) {
 PyErr_SetString(PyExc_ValueError, "Expecting an integer");
 SWIG_fail;
   }
-  $2 = PyInt_AsLong($input);
+  $2 = PyLong_AsLong($input);
   if ($2 <= 0) {
 PyErr_SetString(PyExc_ValueError, "Positive integer expected");
 SWIG_fail;
@@ -139,11 +139,11 @@
 
 // typemap for handling an snprintf-like API like SBThread::GetStopDescription.
 %typemap(in) (char *dst_or_null, size_t dst_len) {
-  

[Lldb-commits] [PATCH] D146590: [lldb] Update some uses of Python2 API in typemaps.

2023-03-22 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG984354fbbe4e: [lldb] Update some uses of Python2 API in 
typemaps. (authored by jgorbe).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146590

Files:
  lldb/bindings/python/python-typemaps.swig
  lldb/test/API/python_api/sbdata/TestSBData.py


Index: lldb/test/API/python_api/sbdata/TestSBData.py
===
--- lldb/test/API/python_api/sbdata/TestSBData.py
+++ lldb/test/API/python_api/sbdata/TestSBData.py
@@ -387,12 +387,13 @@
 self.assert_data(data2.GetUnsignedInt8, 4, 111)
 self.assert_data(data2.GetUnsignedInt8, 5, 33)
 
-data2.SetDataFromUInt64Array([1, 2, 3, 4, 5])
+data2.SetDataFromUInt64Array([1, 2, 3, 4, 5, 2**63])
 self.assert_data(data2.GetUnsignedInt64, 0, 1)
 self.assert_data(data2.GetUnsignedInt64, 8, 2)
 self.assert_data(data2.GetUnsignedInt64, 16, 3)
 self.assert_data(data2.GetUnsignedInt64, 24, 4)
 self.assert_data(data2.GetUnsignedInt64, 32, 5)
+self.assert_data(data2.GetUnsignedInt64, 40, 2**63)
 
 self.assertEqual(
 data2.uint64[0], 1,
Index: lldb/bindings/python/python-typemaps.swig
===
--- lldb/bindings/python/python-typemaps.swig
+++ lldb/bindings/python/python-typemaps.swig
@@ -103,11 +103,11 @@
 
 // typemap for a char buffer
 %typemap(in) (char *dst, size_t dst_len) {
-  if (!PyInt_Check($input)) {
+  if (!PyLong_Check($input)) {
 PyErr_SetString(PyExc_ValueError, "Expecting an integer");
 SWIG_fail;
   }
-  $2 = PyInt_AsLong($input);
+  $2 = PyLong_AsLong($input);
   if ($2 <= 0) {
 PyErr_SetString(PyExc_ValueError, "Positive integer expected");
 SWIG_fail;
@@ -139,11 +139,11 @@
 
 // typemap for handling an snprintf-like API like SBThread::GetStopDescription.
 %typemap(in) (char *dst_or_null, size_t dst_len) {
-  if (!PyInt_Check($input)) {
+  if (!PyLong_Check($input)) {
 PyErr_SetString(PyExc_ValueError, "Expecting an integer");
 SWIG_fail;
   }
-  $2 = PyInt_AsLong($input);
+  $2 = PyLong_AsLong($input);
   if ($2 <= 0) {
 PyErr_SetString(PyExc_ValueError, "Positive integer expected");
 SWIG_fail;
@@ -205,9 +205,7 @@
 // typemap for an incoming buffer
 // See also SBProcess::ReadMemory.
 %typemap(in) (void *buf, size_t size) {
-  if (PyInt_Check($input)) {
-$2 = PyInt_AsLong($input);
-  } else if (PyLong_Check($input)) {
+  if (PyLong_Check($input)) {
 $2 = PyLong_AsLong($input);
   } else {
 PyErr_SetString(PyExc_ValueError, "Expecting an integer or long object");
@@ -258,9 +256,7 @@
 }
 
 template  bool SetNumberFromPyObject(T &number, PyObject *obj) {
-  if (PyInt_Check(obj))
-number = static_cast(PyInt_AsLong(obj));
-  else if (PyLong_Check(obj))
+  if (PyLong_Check(obj))
 number = PyLongAsT(obj);
   else
 return false;
@@ -345,7 +341,7 @@
 count = $2;
   PyObject *list = PyList_New(count);
   for (uint32_t j = 0; j < count; j++) {
-PyObject *item = PyInt_FromLong($1[j]);
+PyObject *item = PyLong_FromLong($1[j]);
 int ok = PyList_SetItem(list, j, item);
 if (ok != 0) {
   $result = Py_None;


Index: lldb/test/API/python_api/sbdata/TestSBData.py
===
--- lldb/test/API/python_api/sbdata/TestSBData.py
+++ lldb/test/API/python_api/sbdata/TestSBData.py
@@ -387,12 +387,13 @@
 self.assert_data(data2.GetUnsignedInt8, 4, 111)
 self.assert_data(data2.GetUnsignedInt8, 5, 33)
 
-data2.SetDataFromUInt64Array([1, 2, 3, 4, 5])
+data2.SetDataFromUInt64Array([1, 2, 3, 4, 5, 2**63])
 self.assert_data(data2.GetUnsignedInt64, 0, 1)
 self.assert_data(data2.GetUnsignedInt64, 8, 2)
 self.assert_data(data2.GetUnsignedInt64, 16, 3)
 self.assert_data(data2.GetUnsignedInt64, 24, 4)
 self.assert_data(data2.GetUnsignedInt64, 32, 5)
+self.assert_data(data2.GetUnsignedInt64, 40, 2**63)
 
 self.assertEqual(
 data2.uint64[0], 1,
Index: lldb/bindings/python/python-typemaps.swig
===
--- lldb/bindings/python/python-typemaps.swig
+++ lldb/bindings/python/python-typemaps.swig
@@ -103,11 +103,11 @@
 
 // typemap for a char buffer
 %typemap(in) (char *dst, size_t dst_len) {
-  if (!PyInt_Check($input)) {
+  if (!PyLong_Check($input)) {
 PyErr_SetString(PyExc_ValueError, "Expecting an integer");
 SWIG_fail;
   }
-  $2 = PyInt_AsLong($input);
+  $2 = PyLong_AsLong($input);
   if ($2 <= 0) {
 PyErr_SetString(PyExc_ValueError, "Positive integer expected");
 SWIG_fail;
@@ -139,11 +139,11 @@
 
 // typemap for handling an snprintf-like API like SBThread::

[Lldb-commits] [PATCH] D145609: [lldb] Change dwim-print to default to disabled persistent results

2023-03-23 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe added a comment.

What was the rationale for this change? It changes the output format of a 
common command (given that `print` is now an alias for `dwim-print`) and it 
breaks basically anything that examines debugger output.

Also `--persistent-result on` can't be passed to `print`, it only works for me 
if I run specifically `dwim-print`. Is that intended?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D145609

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


[Lldb-commits] [PATCH] D145609: [lldb] Change dwim-print to default to disabled persistent results

2023-03-23 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe added a comment.

> Are you using persistent results? If not, how much effort is it to either 1) 
> change the tools/code that examine the output to not look for $\d+, or 2) use 
> a custom print/p alias? Honest question.

I'm not using them myself, and it's not much effort to fix the problems I've 
seen because of this. It just seemed weird to have a user-facing behavior 
change like this being committed without a rationale given.

I assumed switching to `dwim-print` would be transparent for users, and I'm not 
sure how a user that relies on these convenience variables is supposed to 
discover what happened when `print` stops producing them.

> I'd be curious to learn about some example you have in mind here.

We have a python test harness that drives a debugger session that we mainly use 
for prettyprinter tests. Then we have tests that look like:

  self.ContinueTo('StopHereForDebugger')
  self.TestPrintOutputMatches('my_variable', 'Cord of length 4: "foo\\n"')

when I ported this from gdb I couldn't find an equivalent to gdb's `output` 
command (that prints just the value), so I reached for `print` which printed 
`(Type) $0 = value` instead, and kept everything after the ' = '. It wasn't 
even using the persistent values, but the change in the output format broke it.

I also found a failure in a one-off test that worked as a minimal sanity check 
for debug builds: build a debug binary, then run the debugger on it and try to 
print some variables in order to verify that debug builds do have debug info 
that the debugger can use (i.e. debug info is not completely missing, or 
corrupted). This is a shell script that basically does:

  OUTPUT=$("$LLDB" -b -s "$SCRIPT_FILE" "$TEST_PROGRAM")

and then used the conveniently sequentially-numbered persistent results to grep 
the output:

  # Check that `argc` is 1 and has type `int`.
  (echo "$OUTPUT" | grep "(int).*[$]0 = 1") || die

I know they're not the most robust tests in the world, and as I said, it was 
not much effort to fix (they're already fixed!). But it still feels like a 
user-facing regression, and the consistency argument can go both ways: you 
could similarly argue that `dwim-print` should put the result of `frame 
variable` into a convenience variable to keep it consistent with the cases 
where the expression evaluator is used. So the real argument is that most users 
don't need it and it shouldn't be enabled by default. Which is a fine argument 
to make (although it's sad that we don't have data to support it one way or the 
other), but I had to ask to know because the commit description didn't mention 
any reasons at all.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D145609

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


[Lldb-commits] [PATCH] D145609: [lldb] Change dwim-print to default to disabled persistent results

2023-03-23 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe added a comment.

By the way, I just bisected another problem to this commit: I'm seeing in some 
cases that prettyprinted values with synthetic children don't show child names 
when using `dwim-print`. So print used to show:

  (lldb) p c
  (MyClass) $0 = MyClass object with children: {
[0] = 0x6004 "hello"
  }
  (lldb) p m
  (MyMap) $1 = MyMap object with children: {
["my_key"] = 0x6011 "my_value"
  }

but now it shows

  (lldb) p c
  (MyClass)  MyClass object with children: {
0x6004 "hello"
  }
  (lldb) p m
  (MyMap)  MyMap object with children: {
0x6011 "my_value"
  }

I don't have a repro test case to share right away but I though I'd give you a 
heads-up in case the problem is easy to find from the description. Or maybe 
it's the intended behavior? I get the same behavior with `expr 
--persistent-result off -- m` so I can't tell if it's a bug or if it's just the 
expected behavior when disabling persistent results. If it's the latter, that's 
a strong argument for me to unalias `print` and restore the old behavior in the 
lldbinit file we ship to our internal users.

I'll work on a small shareable test case tomorrow anyway.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D145609

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


[Lldb-commits] [PATCH] D146783: [lldb] Add ability to hide the root name of a value

2023-03-24 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe added a comment.

I've tried building lldb with this patch applied and it fixes the problem I 
saw. Thanks for the quick fix!

I'm not very familiar with the code so I'd appreciate if someone else gives 
their LGTM too but the changes look reasonable to me (just one small nit I've 
mentioned in an inline comment).




Comment at: lldb/source/DataFormatters/ValueObjectPrinter.cpp:278
 
-  if (!m_options.m_hide_name) {
+  if (ShowName()) {
 if (m_options.m_flat_output)

This method name reads like a command, rather than a predicate. What about 
something like `ShouldShowName` or `ShouldPrintName`? This would also match the 
style of other method names already in this file such as 
`ShouldPrintValueObject`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146783

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


[Lldb-commits] [PATCH] D146590: [lldb] Update some uses of Python2 API in typemaps.

2023-03-24 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe added a comment.

I found the actual reason for the crash I was talking about. This patch only 
addressed the incorrect `OverflowError`, but the crash comes from a double free 
(as @rupprecht mentioned) in the error handling logic. The error path here 

 does both `free($1);` and `SWIG_fail;`. The same goes for another error check 
a few lines below that. In the generated code, the `SWIG_fail` macro is 
expanded to `goto fail` and the `fail` label also frees the same memory buffer.

I believe (but I don't have any experience with SWIG typemaps so this is an 
educated guess) that the call to `free` in the error path comes from the 
`%typemap(freearg)` immediately after that one. So if freearg already takes 
care of it, the error handling logic in `%typemap(in)` should just call 
`SWIG_fail`. Does that sound correct?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146590

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


[Lldb-commits] [PATCH] D146783: [lldb] Add ability to hide the root name of a value

2023-03-24 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe added a comment.

I just noticed a minor aesthetic problem with the input of `dwim-print` when 
using data formatters. There are some spacing adjustments in this commit but 
I'm not sure if they are the actual cause (please let me know if you'd prefer 
me to file a bug instead).

You can reproduce it by defining some random struct `X` and using `settings set 
auto-one-line-summaries false` like you did in the test case for this commit.

If you add a summary string:

  type summary add -s "my summary" -e "X"

then the output of dwim-print without persistent results has the wrong spacing:

  (lldb) dwim-print my_x
  (X)  my summary{
value = 0
  }

(note there are two spaces before "my summary" and no space before the opening 
brace).

Using `expr` or `dwim-print --persistent-result on --` doesn't have this 
problem:

  (lldb) dwim-print --persistent-result on -- my_x
  (X) $2 = my summary {
value = 0
  }


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146783

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


[Lldb-commits] [PATCH] D147007: [lldb] Fix double free in python bindings error handling.

2023-03-27 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe created this revision.
jgorbe added reviewers: bulbazord, mib, labath.
jgorbe added a project: LLDB.
Herald added a subscriber: JDevlieghere.
Herald added a project: All.
jgorbe requested review of this revision.

If we have a `%typemap(freearg)` that frees the argument, we shouldn't
free it manually on an error path before calling `SWIG_fail`.
`SWIG_fail` will already free the memory in this case, and doing it
manually results in a double free.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D147007

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


Index: lldb/bindings/python/python-typemaps.swig
===
--- lldb/bindings/python/python-typemaps.swig
+++ lldb/bindings/python/python-typemaps.swig
@@ -17,7 +17,6 @@
   PythonString py_str = list.GetItemAtIndex(i).AsType();
   if (!py_str.IsAllocated()) {
 PyErr_SetString(PyExc_TypeError, "list must contain strings");
-free($1);
 SWIG_fail;
   }
 
@@ -294,12 +293,10 @@
   PyObject *o = PyList_GetItem($input, i);
   if (!SetNumberFromPyObject($1[i], o)) {
 PyErr_SetString(PyExc_TypeError, "list must contain numbers");
-free($1);
 SWIG_fail;
   }
 
   if (PyErr_Occurred()) {
-free($1);
 SWIG_fail;
   }
 }


Index: lldb/bindings/python/python-typemaps.swig
===
--- lldb/bindings/python/python-typemaps.swig
+++ lldb/bindings/python/python-typemaps.swig
@@ -17,7 +17,6 @@
   PythonString py_str = list.GetItemAtIndex(i).AsType();
   if (!py_str.IsAllocated()) {
 PyErr_SetString(PyExc_TypeError, "list must contain strings");
-free($1);
 SWIG_fail;
   }
 
@@ -294,12 +293,10 @@
   PyObject *o = PyList_GetItem($input, i);
   if (!SetNumberFromPyObject($1[i], o)) {
 PyErr_SetString(PyExc_TypeError, "list must contain numbers");
-free($1);
 SWIG_fail;
   }
 
   if (PyErr_Occurred()) {
-free($1);
 SWIG_fail;
   }
 }
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D146590: [lldb] Update some uses of Python2 API in typemaps.

2023-03-27 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe added a comment.

In D146590#4225500 , @bulbazord wrote:

> Yea, after reading the SWIG documentation, this diagnosis looks correct. If 
> you'd like to fix this feel free to upload a patch and list myself and @mib 
> as reviewers. Otherwise let me know and I can take care of it. Thanks for 
> doing that investigation!

Thanks! Just sent you all https://reviews.llvm.org/D147007


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146590

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


[Lldb-commits] [PATCH] D147007: [lldb] Fix double free in python bindings error handling.

2023-03-27 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG4a38d3326895: [lldb] Fix double free in python bindings 
error handling. (authored by jgorbe).

Changed prior to commit:
  https://reviews.llvm.org/D147007?vs=508811&id=508827#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147007

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


Index: lldb/bindings/python/python-typemaps.swig
===
--- lldb/bindings/python/python-typemaps.swig
+++ lldb/bindings/python/python-typemaps.swig
@@ -1,4 +1,10 @@
-/* Typemap definitions, to allow SWIG to properly handle 'char**' data types. 
*/
+/* Typemap definitions, to allow SWIG to properly handle 'char**' data types.
+
+NOTE: If there's logic to free memory in a %typemap(freearg), it will also be
+run if you call SWIG_fail on an error path. Don't manually free() an argument
+AND call SWIG_fail at the same time, because it will result in a double free.
+
+*/
 
 %inline %{
 
@@ -17,7 +23,6 @@
   PythonString py_str = list.GetItemAtIndex(i).AsType();
   if (!py_str.IsAllocated()) {
 PyErr_SetString(PyExc_TypeError, "list must contain strings");
-free($1);
 SWIG_fail;
   }
 
@@ -294,12 +299,10 @@
   PyObject *o = PyList_GetItem($input, i);
   if (!SetNumberFromPyObject($1[i], o)) {
 PyErr_SetString(PyExc_TypeError, "list must contain numbers");
-free($1);
 SWIG_fail;
   }
 
   if (PyErr_Occurred()) {
-free($1);
 SWIG_fail;
   }
 }


Index: lldb/bindings/python/python-typemaps.swig
===
--- lldb/bindings/python/python-typemaps.swig
+++ lldb/bindings/python/python-typemaps.swig
@@ -1,4 +1,10 @@
-/* Typemap definitions, to allow SWIG to properly handle 'char**' data types. */
+/* Typemap definitions, to allow SWIG to properly handle 'char**' data types.
+
+NOTE: If there's logic to free memory in a %typemap(freearg), it will also be
+run if you call SWIG_fail on an error path. Don't manually free() an argument
+AND call SWIG_fail at the same time, because it will result in a double free.
+
+*/
 
 %inline %{
 
@@ -17,7 +23,6 @@
   PythonString py_str = list.GetItemAtIndex(i).AsType();
   if (!py_str.IsAllocated()) {
 PyErr_SetString(PyExc_TypeError, "list must contain strings");
-free($1);
 SWIG_fail;
   }
 
@@ -294,12 +299,10 @@
   PyObject *o = PyList_GetItem($input, i);
   if (!SetNumberFromPyObject($1[i], o)) {
 PyErr_SetString(PyExc_TypeError, "list must contain numbers");
-free($1);
 SWIG_fail;
   }
 
   if (PyErr_Occurred()) {
-free($1);
 SWIG_fail;
   }
 }
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D147007: [lldb] Fix double free in python bindings error handling.

2023-03-27 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe added a comment.

In D147007#4225762 , @JDevlieghere 
wrote:

> LGTM. I think it would be worth adding that information to the top of the 
> file to prevent similar mistakes in the future.

Good idea, thanks. I added a note at the top before committing.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147007

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


[Lldb-commits] [PATCH] D147006: [lldb] Fix value printing for a specific case

2023-03-27 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe accepted this revision.
jgorbe added a comment.
This revision is now accepted and ready to land.

Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147006

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


[Lldb-commits] [PATCH] D147805: [lldb-vscode] Fix two issues with runInTerminal test.

2023-04-07 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe created this revision.
jgorbe added reviewers: clayborg, wallace.
jgorbe added a project: LLDB.
Herald added subscribers: JDevlieghere, krytarowski.
Herald added a project: All.
jgorbe requested review of this revision.

With ptrace_scope = 1 the kernel only allows tracing descendants of a process.
When using runInTerminal, the target process is not launched by the debugger,
so we need to modify `LaunchRunInTerminal` to explicitly allow tracing.
This should fix a problem reported in https://reviews.llvm.org/D84974#3903716

Also, remove a special case from the `launch` method in the lldbvscode_testcase
test harness. The existing test was using stopOnEntry, so the first stop didn't
happen at the expected breakpoint unless the harness did configurationDone
first.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D147805

Files:
  lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/lldbvscode_testcase.py
  lldb/test/API/tools/lldb-vscode/runInTerminal/TestVSCode_runInTerminal.py
  lldb/tools/lldb-vscode/lldb-vscode.cpp


Index: lldb/tools/lldb-vscode/lldb-vscode.cpp
===
--- lldb/tools/lldb-vscode/lldb-vscode.cpp
+++ lldb/tools/lldb-vscode/lldb-vscode.cpp
@@ -32,6 +32,10 @@
 #include 
 #endif
 
+#if defined(__linux__)
+#include 
+#endif
+
 #include 
 #include 
 #include 
@@ -3146,6 +3150,14 @@
   llvm::errs() << "runInTerminal is only supported on POSIX systems\n";
   exit(EXIT_FAILURE);
 #else
+
+  // On Linux with the Yama security module enabled, a process can only attach
+  // to its descendants by default. In the runInTerminal case the target
+  // process is launched by the client so we need to allow tracing explicitly.
+#if defined(__linux__)
+  (void)prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0);
+#endif
+
   RunInTerminalLauncherCommChannel comm_channel(comm_file);
   if (llvm::Error err = comm_channel.NotifyPid()) {
 llvm::errs() << llvm::toString(std::move(err)) << "\n";
Index: lldb/test/API/tools/lldb-vscode/runInTerminal/TestVSCode_runInTerminal.py
===
--- lldb/test/API/tools/lldb-vscode/runInTerminal/TestVSCode_runInTerminal.py
+++ lldb/test/API/tools/lldb-vscode/runInTerminal/TestVSCode_runInTerminal.py
@@ -57,8 +57,7 @@
 program = self.getBuildArtifact("a.out")
 source = 'main.c'
 self.build_and_launch(
-program, stopOnEntry=True, runInTerminal=True, args=["foobar"],
-env=["FOO=bar"])
+program, runInTerminal=True, args=["foobar"], env=["FOO=bar"])
 
 breakpoint_line = line_number(source, '// breakpoint')
 
@@ -88,7 +87,7 @@
 return
 self.build_and_create_debug_adaptor()
 response = self.launch(
-"INVALIDPROGRAM", stopOnEntry=True, runInTerminal=True, 
args=["foobar"], env=["FOO=bar"], expectFailure=True)
+"INVALIDPROGRAM", runInTerminal=True, args=["foobar"], 
env=["FOO=bar"], expectFailure=True)
 self.assertFalse(response['success'])
 self.assertIn("Could not create a target for a program 
'INVALIDPROGRAM': unable to find executable",
 response['message'])
Index: 
lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/lldbvscode_testcase.py
===
--- lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/lldbvscode_testcase.py
+++ lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/lldbvscode_testcase.py
@@ -331,10 +331,6 @@
 if not (response and response['success']):
 self.assertTrue(response['success'],
 'launch failed (%s)' % (response['message']))
-# We need to trigger a request_configurationDone after we've 
successfully
-# attached a runInTerminal process to finish initialization.
-if runInTerminal:
-self.vscode.request_configurationDone()
 return response
 
 


Index: lldb/tools/lldb-vscode/lldb-vscode.cpp
===
--- lldb/tools/lldb-vscode/lldb-vscode.cpp
+++ lldb/tools/lldb-vscode/lldb-vscode.cpp
@@ -32,6 +32,10 @@
 #include 
 #endif
 
+#if defined(__linux__)
+#include 
+#endif
+
 #include 
 #include 
 #include 
@@ -3146,6 +3150,14 @@
   llvm::errs() << "runInTerminal is only supported on POSIX systems\n";
   exit(EXIT_FAILURE);
 #else
+
+  // On Linux with the Yama security module enabled, a process can only attach
+  // to its descendants by default. In the runInTerminal case the target
+  // process is launched by the client so we need to allow tracing explicitly.
+#if defined(__linux__)
+  (void)prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0);
+#endif
+
   RunInTerminalLauncherCommChannel comm_channel(comm_file);
   if (llvm::Error err = comm_channel.NotifyPid()) {
 llvm::errs() << llvm::toString(std::move(err)) << "\n";
Index: lldb/test/API/tools/lldb-vscode/r

[Lldb-commits] [PATCH] D147805: [lldb-vscode] Fix two issues with runInTerminal test.

2023-04-07 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe updated this revision to Diff 511818.
jgorbe added a comment.

Added a `--debugger-pid` flag that needs to be passed with `--launch-target` so
that we can restrict `PR_SET_PTRACER` to the main lldb-vscode instance instead 
of
using `PR_SET_PTRACER_ANY`.


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

https://reviews.llvm.org/D147805

Files:
  lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/lldbvscode_testcase.py
  lldb/test/API/tools/lldb-vscode/runInTerminal/TestVSCode_runInTerminal.py
  lldb/tools/lldb-vscode/JSONUtils.cpp
  lldb/tools/lldb-vscode/JSONUtils.h
  lldb/tools/lldb-vscode/Options.td
  lldb/tools/lldb-vscode/lldb-vscode.cpp

Index: lldb/tools/lldb-vscode/lldb-vscode.cpp
===
--- lldb/tools/lldb-vscode/lldb-vscode.cpp
+++ lldb/tools/lldb-vscode/lldb-vscode.cpp
@@ -32,6 +32,10 @@
 #include 
 #endif
 
+#if defined(__linux__)
+#include 
+#endif
+
 #include 
 #include 
 #include 
@@ -1562,8 +1566,12 @@
 
   RunInTerminalDebugAdapterCommChannel comm_channel(comm_file.m_path);
 
+  unsigned long debugger_pid = 0;
+#if !defined(_WIN32)
+  debugger_pid = getpid();
+#endif
   llvm::json::Object reverse_request = CreateRunInTerminalReverseRequest(
-  launch_request, g_vsc.debug_adaptor_path, comm_file.m_path);
+  launch_request, g_vsc.debug_adaptor_path, comm_file.m_path, debugger_pid);
   llvm::json::Object reverse_response;
   lldb_vscode::PacketStatus status =
   g_vsc.SendReverseRequest(reverse_request, reverse_response);
@@ -3141,11 +3149,20 @@
 // In case of errors launching the target, a suitable error message will be
 // emitted to the debug adaptor.
 void LaunchRunInTerminalTarget(llvm::opt::Arg &target_arg,
-   llvm::StringRef comm_file, char *argv[]) {
+   llvm::StringRef comm_file,
+   unsigned long debugger_pid, char *argv[]) {
 #if defined(_WIN32)
   llvm::errs() << "runInTerminal is only supported on POSIX systems\n";
   exit(EXIT_FAILURE);
 #else
+
+  // On Linux with the Yama security module enabled, a process can only attach
+  // to its descendants by default. In the runInTerminal case the target
+  // process is launched by the client so we need to allow tracing explicitly.
+#if defined(__linux__)
+  (void)prctl(PR_SET_PTRACER, debugger_pid, 0, 0, 0);
+#endif
+
   RunInTerminalLauncherCommChannel comm_channel(comm_file);
   if (llvm::Error err = comm_channel.NotifyPid()) {
 llvm::errs() << llvm::toString(std::move(err)) << "\n";
@@ -3237,18 +3254,27 @@
   }
 
   if (llvm::opt::Arg *target_arg = input_args.getLastArg(OPT_launch_target)) {
-if (llvm::opt::Arg *comm_file = input_args.getLastArg(OPT_comm_file)) {
+llvm::opt::Arg *debugger_pid = input_args.getLastArg(OPT_debugger_pid);
+llvm::opt::Arg *comm_file = input_args.getLastArg(OPT_comm_file);
+if (comm_file && debugger_pid) {
+  char *remainder;
+  unsigned long pid = strtoul(debugger_pid->getValue(), &remainder, 0);
+  if (remainder == debugger_pid->getValue() || *remainder != '\0') {
+llvm::errs() << "'" << debugger_pid->getValue() << "' is not a valid "
+"PID\n";
+return EXIT_FAILURE;
+  }
   int target_args_pos = argc;
   for (int i = 0; i < argc; i++)
 if (strcmp(argv[i], "--launch-target") == 0) {
   target_args_pos = i + 1;
   break;
 }
-  LaunchRunInTerminalTarget(*target_arg, comm_file->getValue(),
+  LaunchRunInTerminalTarget(*target_arg, comm_file->getValue(), pid,
 argv + target_args_pos);
 } else {
-  llvm::errs() << "\"--launch-target\" requires \"--comm-file\" to be "
-  "specified\n";
+  llvm::errs() << "\"--launch-target\" requires \"--comm-file\" and "
+  "\"--debugger-pid\" to be specified\n";
   return EXIT_FAILURE;
 }
   }
Index: lldb/tools/lldb-vscode/Options.td
===
--- lldb/tools/lldb-vscode/Options.td
+++ lldb/tools/lldb-vscode/Options.td
@@ -28,9 +28,14 @@
   MetaVarName<"">,
   HelpText<"Launch a target for the launchInTerminal request. Any argument "
 "provided after this one will be passed to the target. The parameter "
-"--comm-files-prefix must also be specified.">;
+"--comm-file must also be specified.">;
 
 def comm_file: Separate<["--", "-"], "comm-file">,
   MetaVarName<"">,
-  HelpText<"The fifo file used to communicate the with the debug adaptor"
+  HelpText<"The fifo file used to communicate the with the debug adaptor "
 "when using --launch-target.">;
+
+def debugger_pid: Separate<["--", "-"], "debugger-pid">,
+  MetaVarName<"">,
+  HelpText<"The PID of the lldb-vscode instance that sent the launchInTerminal "
+"request when using --launch-target.">;
Index: lldb/tools/lldb-vscode/JSONUtils.h
==

[Lldb-commits] [PATCH] D147831: [lldb-vscode] Implement RestartRequest

2023-04-07 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe created this revision.
jgorbe added reviewers: clayborg, wallace, labath, rupprecht.
jgorbe added a project: LLDB.
Herald added a subscriber: JDevlieghere.
Herald added a project: All.
jgorbe requested review of this revision.

This is an optional request, but supporting it makes the experience better when
re-launching a big binary that takes significant time to parse: instead of
tearing down and re-create the whole session we just need to kill the current
process and launch a new one.

Some non-obvious comments that might help review this change:

- After killing the process, we get an "exited" event for it. Because the 
process no longer exists some interesting things can occur that manifest as 
flaky failures if not dealt with:
  - `EventIsProcessEvent` relies on `SBEvent::GetBroadcasterClass`, which can 
crash if the broadcaster is no longer there: the event only holds a weak_ptr to 
its broadcaster, and `GetBroadcasterClass` uses it without checking.

Other `EventIs*` functions look at the flavor of the EventData, so I have 
modified EventIsProcessEvent to do that.
  - We keep the PID of the old process so we can detect its "exited" event and 
not terminate the whole session. But sometimes the SBProcess we get from the 
event won't have a PID, for some reason.

- I have factored out the code to launch a process out to a new LaunchProcess 
function, so it can be used from both `request_launch` and `request_restart`.

- The restart_runInTerminal test has the same problem with debug builds as the 
original runInTerminal test: when attaching to the launcher instance of 
lldb-vscode it takes a long time to parse its debug info. I have used the same 
workaround to disable that particular test for debug builds.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D147831

Files:
  lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py
  lldb/source/API/SBProcess.cpp
  lldb/test/API/tools/lldb-vscode/restart/Makefile
  lldb/test/API/tools/lldb-vscode/restart/TestVSCode_restart.py
  lldb/test/API/tools/lldb-vscode/restart/TestVSCode_restart_runInTerminal.py
  lldb/test/API/tools/lldb-vscode/restart/main.c
  lldb/tools/lldb-vscode/VSCode.cpp
  lldb/tools/lldb-vscode/VSCode.h
  lldb/tools/lldb-vscode/lldb-vscode.cpp

Index: lldb/tools/lldb-vscode/lldb-vscode.cpp
===
--- lldb/tools/lldb-vscode/lldb-vscode.cpp
+++ lldb/tools/lldb-vscode/lldb-vscode.cpp
@@ -458,7 +458,8 @@
 // manually send a stopped event in request_configurationDone(...)
 // so don't send any before then.
 if (g_vsc.configuration_done_sent) {
-  // Only report a stopped event if the process was not restarted.
+  // Only report a stopped event if the process was not
+  // automatically restarted.
   if (!lldb::SBProcess::GetRestartedFromEvent(event)) {
 SendStdOutStdErr(process);
 SendThreadStoppedEvent();
@@ -468,14 +469,22 @@
   case lldb::eStateRunning:
 g_vsc.WillContinue();
 break;
-  case lldb::eStateExited: {
-// Run any exit LLDB commands the user specified in the
-// launch.json
-g_vsc.RunExitCommands();
-SendProcessExitedEvent(process);
-SendTerminatedEvent();
-done = true;
-  } break;
+  case lldb::eStateExited:
+// When restarting, we can get an "exited" event for the process we
+// just killed with the old PID, or even with no PID. In that case
+// we don't have to terminate the session.
+if (process.GetProcessID() == LLDB_INVALID_PROCESS_ID ||
+process.GetProcessID() == g_vsc.restarting_process_id) {
+  g_vsc.restarting_process_id = LLDB_INVALID_PROCESS_ID;
+} else {
+  // Run any exit LLDB commands the user specified in the
+  // launch.json
+  g_vsc.RunExitCommands();
+  SendProcessExitedEvent(process);
+  SendTerminatedEvent();
+  done = true;
+}
+break;
   }
 } else if ((event_mask & lldb::SBProcess::eBroadcastBitSTDOUT) ||
(event_mask & lldb::SBProcess::eBroadcastBitSTDERR)) {
@@ -1527,7 +1536,7 @@
   // The debug adapter supports the RestartRequest. In this case a client
   // should not implement 'restart' by terminating and relaunching the adapter
   // but by calling the RestartRequest.
-  body.try_emplace("supportsRestartRequest", false);
+  body.try_emplace("supportsRestartRequest", true);
   // The debug adapter supports 'exceptionOptions' on the
   // setExceptionBreakpoints request.
   body.try_emplace("supportsExceptionOptions", true);
@@ -1622,6 +1631,71 @@
  error.GetCString());
 }
 
+// Takes a LaunchRequest object and launches the pr

[Lldb-commits] [PATCH] D147805: [lldb-vscode] Fix two issues with runInTerminal test.

2023-04-10 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe updated this revision to Diff 512272.
jgorbe marked 3 inline comments as done.
jgorbe added a comment.

Addressed review comments.

- Use `lldb::pid_t` instead of unsigned long, and `LLDB_INVALID_PROCESS_ID` 
instead of `0` in the cases where the PID is missing.
- Only pass the `--debugger-pid` flag if we're on Linux and we have a debugger 
PID. I don't think we need to be particularly lenient with flag parsing, 
because IIUC the command lines for the launcher should only ever be built by 
lldb-vscode itself and not by hand, but it can be confusing for users in other 
platforms to see `--debugger-pid 0` in the command line on the terminal.
- Changed parsing of the `--debugger-pid` numeric value to use 
`llvm::StringRef`.


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

https://reviews.llvm.org/D147805

Files:
  lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/lldbvscode_testcase.py
  lldb/test/API/tools/lldb-vscode/runInTerminal/TestVSCode_runInTerminal.py
  lldb/tools/lldb-vscode/JSONUtils.cpp
  lldb/tools/lldb-vscode/JSONUtils.h
  lldb/tools/lldb-vscode/Options.td
  lldb/tools/lldb-vscode/lldb-vscode.cpp

Index: lldb/tools/lldb-vscode/lldb-vscode.cpp
===
--- lldb/tools/lldb-vscode/lldb-vscode.cpp
+++ lldb/tools/lldb-vscode/lldb-vscode.cpp
@@ -32,6 +32,10 @@
 #include 
 #endif
 
+#if defined(__linux__)
+#include 
+#endif
+
 #include 
 #include 
 #include 
@@ -1562,8 +1566,12 @@
 
   RunInTerminalDebugAdapterCommChannel comm_channel(comm_file.m_path);
 
+  lldb::pid_t debugger_pid = LLDB_INVALID_PROCESS_ID;
+#if !defined(_WIN32)
+  debugger_pid = getpid();
+#endif
   llvm::json::Object reverse_request = CreateRunInTerminalReverseRequest(
-  launch_request, g_vsc.debug_adaptor_path, comm_file.m_path);
+  launch_request, g_vsc.debug_adaptor_path, comm_file.m_path, debugger_pid);
   llvm::json::Object reverse_response;
   lldb_vscode::PacketStatus status =
   g_vsc.SendReverseRequest(reverse_request, reverse_response);
@@ -3141,11 +3149,21 @@
 // In case of errors launching the target, a suitable error message will be
 // emitted to the debug adaptor.
 void LaunchRunInTerminalTarget(llvm::opt::Arg &target_arg,
-   llvm::StringRef comm_file, char *argv[]) {
+   llvm::StringRef comm_file,
+   lldb::pid_t debugger_pid, char *argv[]) {
 #if defined(_WIN32)
   llvm::errs() << "runInTerminal is only supported on POSIX systems\n";
   exit(EXIT_FAILURE);
 #else
+
+  // On Linux with the Yama security module enabled, a process can only attach
+  // to its descendants by default. In the runInTerminal case the target
+  // process is launched by the client so we need to allow tracing explicitly.
+#if defined(__linux__)
+  if (debugger_pid != LLDB_INVALID_PROCESS_ID)
+(void)prctl(PR_SET_PTRACER, debugger_pid, 0, 0, 0);
+#endif
+
   RunInTerminalLauncherCommChannel comm_channel(comm_file);
   if (llvm::Error err = comm_channel.NotifyPid()) {
 llvm::errs() << llvm::toString(std::move(err)) << "\n";
@@ -3238,13 +3256,23 @@
 
   if (llvm::opt::Arg *target_arg = input_args.getLastArg(OPT_launch_target)) {
 if (llvm::opt::Arg *comm_file = input_args.getLastArg(OPT_comm_file)) {
+  lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
+  llvm::opt::Arg *debugger_pid = input_args.getLastArg(OPT_debugger_pid);
+  if (debugger_pid) {
+llvm::StringRef debugger_pid_value = debugger_pid->getValue();
+if (debugger_pid_value.getAsInteger(10, pid)) {
+  llvm::errs() << "'" << debugger_pid_value << "' is not a valid "
+  "PID\n";
+  return EXIT_FAILURE;
+}
+  }
   int target_args_pos = argc;
   for (int i = 0; i < argc; i++)
 if (strcmp(argv[i], "--launch-target") == 0) {
   target_args_pos = i + 1;
   break;
 }
-  LaunchRunInTerminalTarget(*target_arg, comm_file->getValue(),
+  LaunchRunInTerminalTarget(*target_arg, comm_file->getValue(), pid,
 argv + target_args_pos);
 } else {
   llvm::errs() << "\"--launch-target\" requires \"--comm-file\" to be "
Index: lldb/tools/lldb-vscode/Options.td
===
--- lldb/tools/lldb-vscode/Options.td
+++ lldb/tools/lldb-vscode/Options.td
@@ -28,9 +28,14 @@
   MetaVarName<"">,
   HelpText<"Launch a target for the launchInTerminal request. Any argument "
 "provided after this one will be passed to the target. The parameter "
-"--comm-files-prefix must also be specified.">;
+"--comm-file must also be specified.">;
 
 def comm_file: Separate<["--", "-"], "comm-file">,
   MetaVarName<"">,
-  HelpText<"The fifo file used to communicate the with the debug adaptor"
+  HelpText<"The fifo file used to communicate the with the debug adaptor "
 "when using --launch-target.">;
+
+def d

[Lldb-commits] [PATCH] D147805: [lldb-vscode] Fix two issues with runInTerminal test.

2023-04-10 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe added inline comments.



Comment at: lldb/tools/lldb-vscode/JSONUtils.cpp:1120
   debug_adaptor_path.str(), "--comm-file", comm_file.str(),
+  "--debugger-pid", std::to_string(debugger_pid),
   "--launch-target", GetString(launch_request_arguments, "program").str()};

rupprecht wrote:
> Only pass this if != 0
> 
> (or get fancy and use a std::optional or whatever)
Done. Given that I've changed the `debugger_pid` argument to an `lldb::pid_t` 
I'm using `LLDB_INVALID_PROCESS_ID` as a sentinel value.



Comment at: lldb/tools/lldb-vscode/lldb-vscode.cpp:3163
+#if defined(__linux__)
+  (void)prctl(PR_SET_PTRACER, debugger_pid, 0, 0, 0);
+#endif

rupprecht wrote:
> Only invoke this if debugger_pid != 0
Done.



Comment at: lldb/tools/lldb-vscode/lldb-vscode.cpp:3261
+  char *remainder;
+  unsigned long pid = strtoul(debugger_pid->getValue(), &remainder, 0);
+  if (remainder == debugger_pid->getValue() || *remainder != '\0') {

rupprecht wrote:
> `StringRef` is usually used for parsing strings as numbers, something like:
> 
> ```
> unsigned long pid = 0;
>   llvm::StringRef debugger_pid_value = debugger_pid->getValue())
>   if (debugger_pid_value.getAsInteger(10, pid)) {
> llvm::errs() << ...
>   }
> }
> ```
Thanks! Once this patch lands we should consider changing how the `port` flag 
is parsed (just a few lines after this block) to match this style.


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

https://reviews.llvm.org/D147805

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


[Lldb-commits] [PATCH] D147805: [lldb-vscode] Fix two issues with runInTerminal test.

2023-04-10 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG53aa22cd9ac4: [lldb-vscode] Fix two issues with 
runInTerminal test. (authored by jgorbe).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147805

Files:
  lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/lldbvscode_testcase.py
  lldb/test/API/tools/lldb-vscode/runInTerminal/TestVSCode_runInTerminal.py
  lldb/tools/lldb-vscode/JSONUtils.cpp
  lldb/tools/lldb-vscode/JSONUtils.h
  lldb/tools/lldb-vscode/Options.td
  lldb/tools/lldb-vscode/lldb-vscode.cpp

Index: lldb/tools/lldb-vscode/lldb-vscode.cpp
===
--- lldb/tools/lldb-vscode/lldb-vscode.cpp
+++ lldb/tools/lldb-vscode/lldb-vscode.cpp
@@ -32,6 +32,10 @@
 #include 
 #endif
 
+#if defined(__linux__)
+#include 
+#endif
+
 #include 
 #include 
 #include 
@@ -1562,8 +1566,12 @@
 
   RunInTerminalDebugAdapterCommChannel comm_channel(comm_file.m_path);
 
+  lldb::pid_t debugger_pid = LLDB_INVALID_PROCESS_ID;
+#if !defined(_WIN32)
+  debugger_pid = getpid();
+#endif
   llvm::json::Object reverse_request = CreateRunInTerminalReverseRequest(
-  launch_request, g_vsc.debug_adaptor_path, comm_file.m_path);
+  launch_request, g_vsc.debug_adaptor_path, comm_file.m_path, debugger_pid);
   llvm::json::Object reverse_response;
   lldb_vscode::PacketStatus status =
   g_vsc.SendReverseRequest(reverse_request, reverse_response);
@@ -3141,11 +3149,21 @@
 // In case of errors launching the target, a suitable error message will be
 // emitted to the debug adaptor.
 void LaunchRunInTerminalTarget(llvm::opt::Arg &target_arg,
-   llvm::StringRef comm_file, char *argv[]) {
+   llvm::StringRef comm_file,
+   lldb::pid_t debugger_pid, char *argv[]) {
 #if defined(_WIN32)
   llvm::errs() << "runInTerminal is only supported on POSIX systems\n";
   exit(EXIT_FAILURE);
 #else
+
+  // On Linux with the Yama security module enabled, a process can only attach
+  // to its descendants by default. In the runInTerminal case the target
+  // process is launched by the client so we need to allow tracing explicitly.
+#if defined(__linux__)
+  if (debugger_pid != LLDB_INVALID_PROCESS_ID)
+(void)prctl(PR_SET_PTRACER, debugger_pid, 0, 0, 0);
+#endif
+
   RunInTerminalLauncherCommChannel comm_channel(comm_file);
   if (llvm::Error err = comm_channel.NotifyPid()) {
 llvm::errs() << llvm::toString(std::move(err)) << "\n";
@@ -3238,13 +3256,23 @@
 
   if (llvm::opt::Arg *target_arg = input_args.getLastArg(OPT_launch_target)) {
 if (llvm::opt::Arg *comm_file = input_args.getLastArg(OPT_comm_file)) {
+  lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
+  llvm::opt::Arg *debugger_pid = input_args.getLastArg(OPT_debugger_pid);
+  if (debugger_pid) {
+llvm::StringRef debugger_pid_value = debugger_pid->getValue();
+if (debugger_pid_value.getAsInteger(10, pid)) {
+  llvm::errs() << "'" << debugger_pid_value << "' is not a valid "
+  "PID\n";
+  return EXIT_FAILURE;
+}
+  }
   int target_args_pos = argc;
   for (int i = 0; i < argc; i++)
 if (strcmp(argv[i], "--launch-target") == 0) {
   target_args_pos = i + 1;
   break;
 }
-  LaunchRunInTerminalTarget(*target_arg, comm_file->getValue(),
+  LaunchRunInTerminalTarget(*target_arg, comm_file->getValue(), pid,
 argv + target_args_pos);
 } else {
   llvm::errs() << "\"--launch-target\" requires \"--comm-file\" to be "
Index: lldb/tools/lldb-vscode/Options.td
===
--- lldb/tools/lldb-vscode/Options.td
+++ lldb/tools/lldb-vscode/Options.td
@@ -28,9 +28,14 @@
   MetaVarName<"">,
   HelpText<"Launch a target for the launchInTerminal request. Any argument "
 "provided after this one will be passed to the target. The parameter "
-"--comm-files-prefix must also be specified.">;
+"--comm-file must also be specified.">;
 
 def comm_file: Separate<["--", "-"], "comm-file">,
   MetaVarName<"">,
-  HelpText<"The fifo file used to communicate the with the debug adaptor"
+  HelpText<"The fifo file used to communicate the with the debug adaptor "
 "when using --launch-target.">;
+
+def debugger_pid: Separate<["--", "-"], "debugger-pid">,
+  MetaVarName<"">,
+  HelpText<"The PID of the lldb-vscode instance that sent the launchInTerminal "
+"request when using --launch-target.">;
Index: lldb/tools/lldb-vscode/JSONUtils.h
===
--- lldb/tools/lldb-vscode/JSONUtils.h
+++ lldb/tools/lldb-vscode/JSONUtils.h
@@ -479,13 +479,19 @@
 /// \param[in] comm_file
 /// The fifo file used to communicate the with the target launcher.
 ///
+//

[Lldb-commits] [PATCH] D147831: [lldb-vscode] Implement RestartRequest

2023-04-10 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe updated this revision to Diff 512305.
jgorbe added a comment.

Addressed review comments.

- Changed `last_launch_or_attach_request` to be a 
`std::optional` so we can check if it has been set. Also 
check for `nullopt` in request_restart.
- Made `request_attach` also set `last_launch_or_attach_request`.


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

https://reviews.llvm.org/D147831

Files:
  lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py
  lldb/source/API/SBProcess.cpp
  lldb/test/API/tools/lldb-vscode/restart/Makefile
  lldb/test/API/tools/lldb-vscode/restart/TestVSCode_restart.py
  lldb/test/API/tools/lldb-vscode/restart/TestVSCode_restart_runInTerminal.py
  lldb/test/API/tools/lldb-vscode/restart/main.c
  lldb/tools/lldb-vscode/VSCode.cpp
  lldb/tools/lldb-vscode/VSCode.h
  lldb/tools/lldb-vscode/lldb-vscode.cpp

Index: lldb/tools/lldb-vscode/lldb-vscode.cpp
===
--- lldb/tools/lldb-vscode/lldb-vscode.cpp
+++ lldb/tools/lldb-vscode/lldb-vscode.cpp
@@ -458,7 +458,8 @@
 // manually send a stopped event in request_configurationDone(...)
 // so don't send any before then.
 if (g_vsc.configuration_done_sent) {
-  // Only report a stopped event if the process was not restarted.
+  // Only report a stopped event if the process was not
+  // automatically restarted.
   if (!lldb::SBProcess::GetRestartedFromEvent(event)) {
 SendStdOutStdErr(process);
 SendThreadStoppedEvent();
@@ -468,14 +469,22 @@
   case lldb::eStateRunning:
 g_vsc.WillContinue();
 break;
-  case lldb::eStateExited: {
-// Run any exit LLDB commands the user specified in the
-// launch.json
-g_vsc.RunExitCommands();
-SendProcessExitedEvent(process);
-SendTerminatedEvent();
-done = true;
-  } break;
+  case lldb::eStateExited:
+// When restarting, we can get an "exited" event for the process we
+// just killed with the old PID, or even with no PID. In that case
+// we don't have to terminate the session.
+if (process.GetProcessID() == LLDB_INVALID_PROCESS_ID ||
+process.GetProcessID() == g_vsc.restarting_process_id) {
+  g_vsc.restarting_process_id = LLDB_INVALID_PROCESS_ID;
+} else {
+  // Run any exit LLDB commands the user specified in the
+  // launch.json
+  g_vsc.RunExitCommands();
+  SendProcessExitedEvent(process);
+  SendTerminatedEvent();
+  done = true;
+}
+break;
   }
 } else if ((event_mask & lldb::SBProcess::eBroadcastBitSTDOUT) ||
(event_mask & lldb::SBProcess::eBroadcastBitSTDERR)) {
@@ -592,6 +601,7 @@
 // }
 void request_attach(const llvm::json::Object &request) {
   g_vsc.is_attach = true;
+  g_vsc.last_launch_or_attach_request = request;
   llvm::json::Object response;
   lldb::SBError error;
   FillResponse(request, response);
@@ -1527,7 +1537,7 @@
   // The debug adapter supports the RestartRequest. In this case a client
   // should not implement 'restart' by terminating and relaunching the adapter
   // but by calling the RestartRequest.
-  body.try_emplace("supportsRestartRequest", false);
+  body.try_emplace("supportsRestartRequest", true);
   // The debug adapter supports 'exceptionOptions' on the
   // setExceptionBreakpoints request.
   body.try_emplace("supportsExceptionOptions", true);
@@ -1622,6 +1632,71 @@
  error.GetCString());
 }
 
+// Takes a LaunchRequest object and launches the process, also handling
+// runInTerminal if applicable. It doesn't do any of the additional
+// initialization and bookkeeping stuff that is needed for `request_launch`.
+// This way we can reuse the process launching logic for RestartRequest too.
+lldb::SBError LaunchProcess(const llvm::json::Object &request) {
+  lldb::SBError error;
+  auto arguments = request.getObject("arguments");
+  auto launchCommands = GetStrings(arguments, "launchCommands");
+
+  // Instantiate a launch info instance for the target.
+  auto launch_info = g_vsc.target.GetLaunchInfo();
+
+  // Grab the current working directory if there is one and set it in the
+  // launch info.
+  const auto cwd = GetString(arguments, "cwd");
+  if (!cwd.empty())
+launch_info.SetWorkingDirectory(cwd.data());
+
+  // Extract any extra arguments and append them to our program arguments for
+  // when we launch
+  auto args = GetStrings(arguments, "args");
+  if (!args.empty())
+launch_info.SetArguments(MakeArgv(args).data(), true);
+
+  // Pass any environment variables along that the user specified.
+  auto envs = GetStrings(arguments, "env");
+  if (!envs.empty())
+lau

[Lldb-commits] [PATCH] D147831: [lldb-vscode] Implement RestartRequest

2023-04-10 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe marked 2 inline comments as done.
jgorbe added inline comments.



Comment at: lldb/tools/lldb-vscode/VSCode.h:146
+  // arguments if we get a RestartRequest.
+  llvm::json::Object last_launch_or_attach_request;
   lldb::tid_t focus_tid;

rupprecht wrote:
> std::optional? And then we can raise an error if the 
> client calls restart and this is std::nullopt.
Done, thanks!



Comment at: lldb/tools/lldb-vscode/lldb-vscode.cpp:602
 // }
 void request_attach(const llvm::json::Object &request) {
   g_vsc.is_attach = true;

rupprecht wrote:
> Should we also set `last_launch_or_attach_request` here?
> 
> If the user runs:
> 1) Launch
> 2) Attach
> 3) Restart
> 
> I would expect that should fail because of the reasons restarting an attach 
> will fail. But if we don't set `last_launch_or_attach_request`, it will pass, 
> because we set it in (1).
Yup, I missed that one, thanks for catching it! :)


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

https://reviews.llvm.org/D147831

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


[Lldb-commits] [PATCH] D148582: [lldb] Build libcxx unique_ptr and shared_ptr test programs with -glldb.

2023-04-17 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe created this revision.
jgorbe added reviewers: Michael137, dblaikie, aprantl.
jgorbe added a project: LLDB.
Herald added a subscriber: JDevlieghere.
Herald added a project: All.
jgorbe requested review of this revision.

The functionality added by https://reviews.llvm.org/D145803 is gated by
lldb tuning, so we need to build the test programs with `-glldb` to make
these tests print the expected preferred name.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D148582

Files:
  
lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/shared_ptr/Makefile
  
lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/Makefile


Index: 
lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/Makefile
===
--- 
lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/Makefile
+++ 
lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/Makefile
@@ -2,5 +2,7 @@
 
 USE_LIBCPP := 1
 
-CXXFLAGS_EXTRAS := -std=c++14
+# We need debug info tuning for lldb in order to emit the preferred name for
+# std::string. See https://reviews.llvm.org/D145803.
+CXXFLAGS_EXTRAS := -std=c++14 -glldb
 include Makefile.rules
Index: 
lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/shared_ptr/Makefile
===
--- 
lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/shared_ptr/Makefile
+++ 
lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/shared_ptr/Makefile
@@ -2,5 +2,7 @@
 
 USE_LIBCPP := 1
 
-CXXFLAGS_EXTRAS := -std=c++14
+# We need debug info tuning for lldb in order to emit the preferred name for
+# std::string. See https://reviews.llvm.org/D145803.
+CXXFLAGS_EXTRAS := -std=c++14 -glldb
 include Makefile.rules


Index: lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/Makefile
===
--- lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/Makefile
+++ lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/Makefile
@@ -2,5 +2,7 @@
 
 USE_LIBCPP := 1
 
-CXXFLAGS_EXTRAS := -std=c++14
+# We need debug info tuning for lldb in order to emit the preferred name for
+# std::string. See https://reviews.llvm.org/D145803.
+CXXFLAGS_EXTRAS := -std=c++14 -glldb
 include Makefile.rules
Index: lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/shared_ptr/Makefile
===
--- lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/shared_ptr/Makefile
+++ lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/shared_ptr/Makefile
@@ -2,5 +2,7 @@
 
 USE_LIBCPP := 1
 
-CXXFLAGS_EXTRAS := -std=c++14
+# We need debug info tuning for lldb in order to emit the preferred name for
+# std::string. See https://reviews.llvm.org/D145803.
+CXXFLAGS_EXTRAS := -std=c++14 -glldb
 include Makefile.rules
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D148582: [lldb] Build libcxx unique_ptr and shared_ptr test programs with -glldb.

2023-04-17 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG3c91d016349a: [lldb] Build libcxx unique_ptr and shared_ptr 
test programs with -glldb. (authored by jgorbe).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148582

Files:
  
lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/shared_ptr/Makefile
  
lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/Makefile


Index: 
lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/Makefile
===
--- 
lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/Makefile
+++ 
lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/Makefile
@@ -2,5 +2,7 @@
 
 USE_LIBCPP := 1
 
-CXXFLAGS_EXTRAS := -std=c++14
+# We need debug info tuning for lldb in order to emit the preferred name for
+# std::string. See https://reviews.llvm.org/D145803.
+CXXFLAGS_EXTRAS := -std=c++14 -glldb
 include Makefile.rules
Index: 
lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/shared_ptr/Makefile
===
--- 
lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/shared_ptr/Makefile
+++ 
lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/shared_ptr/Makefile
@@ -2,5 +2,7 @@
 
 USE_LIBCPP := 1
 
-CXXFLAGS_EXTRAS := -std=c++14
+# We need debug info tuning for lldb in order to emit the preferred name for
+# std::string. See https://reviews.llvm.org/D145803.
+CXXFLAGS_EXTRAS := -std=c++14 -glldb
 include Makefile.rules


Index: lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/Makefile
===
--- lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/Makefile
+++ lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/Makefile
@@ -2,5 +2,7 @@
 
 USE_LIBCPP := 1
 
-CXXFLAGS_EXTRAS := -std=c++14
+# We need debug info tuning for lldb in order to emit the preferred name for
+# std::string. See https://reviews.llvm.org/D145803.
+CXXFLAGS_EXTRAS := -std=c++14 -glldb
 include Makefile.rules
Index: lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/shared_ptr/Makefile
===
--- lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/shared_ptr/Makefile
+++ lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/shared_ptr/Makefile
@@ -2,5 +2,7 @@
 
 USE_LIBCPP := 1
 
-CXXFLAGS_EXTRAS := -std=c++14
+# We need debug info tuning for lldb in order to emit the preferred name for
+# std::string. See https://reviews.llvm.org/D145803.
+CXXFLAGS_EXTRAS := -std=c++14 -glldb
 include Makefile.rules
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D148662: [lldb] Make the libcxx unique_ptr prettyprinter support custom deleters.

2023-04-18 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe created this revision.
jgorbe added reviewers: shafik, kastiglione.
jgorbe added a project: LLDB.
Herald added a subscriber: JDevlieghere.
Herald added a project: All.
jgorbe requested review of this revision.

The unique_ptr prettyprinter calls `GetValueOfLibCXXCompressedPair`,
which looks for a `__value_` child. However, when the second value in
the compressed pair is not an empty class, there are two `__value_`
children because `__compressed_pair` derives twice from
`__compressed_pair_elem`, one for each member of the pair. And then the
lookup fails because it's ambiguous.

This patch makes the following changes:

- Rename `GetValueOfLibCXXCompressedPair` to 
`GetFirstValueOfLibCXXCompressedPair`, and add a similar function to get the 
second value. Put both functions in Plugin/Language/CPlusPlus/LibCxx.cpp 
because it seems inappropriate to have libcxx-specific helpers separate from 
all the libcxx-dependent code.

- Read the second value of the `__ptr_` pair and display a "deleter" child in 
the unique_ptr synthetic child provider, when available.

- Add a test case for the non-empty deleter case.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D148662

Files:
  lldb/include/lldb/DataFormatters/FormattersHelpers.h
  lldb/source/DataFormatters/FormattersHelpers.cpp
  lldb/source/Plugins/Language/CPlusPlus/LibCxx.cpp
  lldb/source/Plugins/Language/CPlusPlus/LibCxx.h
  lldb/source/Plugins/Language/CPlusPlus/LibCxxList.cpp
  
lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/TestDataFormatterLibcxxUniquePtr.py
  
lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/main.cpp

Index: lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/main.cpp
===
--- lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/main.cpp
+++ lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/main.cpp
@@ -6,6 +6,15 @@
   std::string name = "steph";
 };
 
+// libc++ stores unique_ptr data in a compressed pair, which has a specialized
+// representation when the type of the second element is an empty class. So
+// we need a deleter class with a dummy data member to trigger the other path.
+struct NonEmptyIntDeleter {
+  void operator()(int* ptr) { delete ptr; }
+
+  int dummy_ = ;
+};
+
 int main() {
   std::unique_ptr up_empty;
   std::unique_ptr up_int = std::make_unique(10);
@@ -13,6 +22,8 @@
   std::unique_ptr &up_int_ref = up_int;
   std::unique_ptr &&up_int_ref_ref = std::make_unique(10);
   std::unique_ptr up_user = std::make_unique();
+  auto up_non_empty_deleter =
+  std::unique_ptr(new int(1234));
 
   return 0; // break here
 }
Index: lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/TestDataFormatterLibcxxUniquePtr.py
===
--- lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/TestDataFormatterLibcxxUniquePtr.py
+++ lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/TestDataFormatterLibcxxUniquePtr.py
@@ -97,5 +97,18 @@
 )
 self.assertEqual(str(valobj), '(User) *__value_ = (id = 30, name = "steph")')
 
+valobj = self.expect_var_path(
+"up_non_empty_deleter",
+type="std::unique_ptr",
+summary="1234",
+children=[
+ValueCheck(name="__value_"),
+ValueCheck(name="deleter", children=[
+ValueCheck(name="dummy_", value="")
+]),
+],
+)
+self.assertNotEqual(valobj.child[0].unsigned, 0)
+
 self.expect_var_path("up_user->id", type="int", value="30")
 self.expect_var_path("up_user->name", type="std::string", summary='"steph"')
Index: lldb/source/Plugins/Language/CPlusPlus/LibCxxList.cpp
===
--- lldb/source/Plugins/Language/CPlusPlus/LibCxxList.cpp
+++ lldb/source/Plugins/Language/CPlusPlus/LibCxxList.cpp
@@ -300,7 +300,7 @@
   m_backend.GetChildMemberWithName(ConstString("__before_begin_"), true));
   if (!impl_sp)
 return false;
-  impl_sp = GetValueOfLibCXXCompressedPair(*impl_sp);
+  impl_sp = GetFirstValueOfLibCXXCompressedPair(*impl_sp);
   if (!impl_sp)
 return false;
   m_head = impl_sp->GetChildMemberWithName(ConstString("__next_"), true).get();
@@ -321,7 +321,7 @@
   ValueObjectSP size_alloc(
   m_backend.GetChildMemberWithName(ConstString("__size_alloc_"), true));
   if (size_alloc) {
-ValueObjectSP value = GetValueOfLibCXXCompressedPair(*size_alloc);
+ValueObjectSP value = GetFirstValueOfLibCXXCompressedPair(*size_alloc);
 if (value) {
   m_count = value->GetValueAsUnsigned(UINT32_MAX);
 }
Index: lldb/source/Plugins/Language/CPlusPlus/LibCxx.h
==

[Lldb-commits] [PATCH] D147831: [lldb-vscode] Implement RestartRequest

2023-04-21 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe added a comment.

Ping.


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

https://reviews.llvm.org/D147831

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


[Lldb-commits] [PATCH] D148662: [lldb] Make the libcxx unique_ptr prettyprinter support custom deleters.

2023-04-25 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe added a comment.

Ping.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148662

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


[Lldb-commits] [PATCH] D148662: [lldb] Make the libcxx unique_ptr prettyprinter support custom deleters.

2023-05-01 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe updated this revision to Diff 518540.
jgorbe added a comment.

Addressed review comments:

- Check pair values before attempting to call `GetChildMemberWithName` on them
- Rename first child from `__value_` to `pointer`. This is friendlier and also 
matches the name used by the libstdcxx unique_ptr prettyprinter.


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

https://reviews.llvm.org/D148662

Files:
  lldb/include/lldb/DataFormatters/FormattersHelpers.h
  lldb/source/DataFormatters/FormattersHelpers.cpp
  lldb/source/Plugins/Language/CPlusPlus/LibCxx.cpp
  lldb/source/Plugins/Language/CPlusPlus/LibCxx.h
  lldb/source/Plugins/Language/CPlusPlus/LibCxxList.cpp
  
lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/TestDataFormatterLibcxxUniquePtr.py
  
lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/main.cpp

Index: lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/main.cpp
===
--- lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/main.cpp
+++ lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/main.cpp
@@ -6,6 +6,15 @@
   std::string name = "steph";
 };
 
+// libc++ stores unique_ptr data in a compressed pair, which has a specialized
+// representation when the type of the second element is an empty class. So
+// we need a deleter class with a dummy data member to trigger the other path.
+struct NonEmptyIntDeleter {
+  void operator()(int* ptr) { delete ptr; }
+
+  int dummy_ = ;
+};
+
 int main() {
   std::unique_ptr up_empty;
   std::unique_ptr up_int = std::make_unique(10);
@@ -13,6 +22,8 @@
   std::unique_ptr &up_int_ref = up_int;
   std::unique_ptr &&up_int_ref_ref = std::make_unique(10);
   std::unique_ptr up_user = std::make_unique();
+  auto up_non_empty_deleter =
+  std::unique_ptr(new int(1234));
 
   return 0; // break here
 }
Index: lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/TestDataFormatterLibcxxUniquePtr.py
===
--- lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/TestDataFormatterLibcxxUniquePtr.py
+++ lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/TestDataFormatterLibcxxUniquePtr.py
@@ -40,7 +40,7 @@
 "up_empty",
 type=self.make_expected_type("int"),
 summary="nullptr",
-children=[ValueCheck(name="__value_")],
+children=[ValueCheck(name="pointer")],
 )
 self.assertEqual(
 valobj.child[0].GetValueAsUnsigned(lldb.LLDB_INVALID_ADDRESS), 0
@@ -54,7 +54,7 @@
 "up_int",
 type=self.make_expected_type("int"),
 summary="10",
-children=[ValueCheck(name="__value_")],
+children=[ValueCheck(name="pointer")],
 )
 self.assertNotEqual(valobj.child[0].unsigned, 0)
 
@@ -62,7 +62,7 @@
 "up_int_ref",
 type=self.make_expected_type("int", qualifiers="&"),
 summary="10",
-children=[ValueCheck(name="__value_")],
+children=[ValueCheck(name="pointer")],
 )
 self.assertNotEqual(valobj.child[0].unsigned, 0)
 
@@ -70,7 +70,7 @@
 "up_int_ref_ref",
 type=self.make_expected_type("int", qualifiers="&&"),
 summary="10",
-children=[ValueCheck(name="__value_")],
+children=[ValueCheck(name="pointer")],
 )
 self.assertNotEqual(valobj.child[0].unsigned, 0)
 
@@ -78,7 +78,7 @@
 "up_str",
 type=self.make_expected_basic_string_ptr(),
 summary='"hello"',
-children=[ValueCheck(name="__value_", summary='"hello"')],
+children=[ValueCheck(name="pointer", summary='"hello"')],
 )
 
 valobj = self.expect_var_path(
@@ -95,7 +95,20 @@
 ValueCheck(name="name", summary='"steph"'),
 ],
 )
-self.assertEqual(str(valobj), '(User) *__value_ = (id = 30, name = "steph")')
+self.assertEqual(str(valobj), '(User) *pointer = (id = 30, name = "steph")')
+
+valobj = self.expect_var_path(
+"up_non_empty_deleter",
+type="std::unique_ptr",
+summary="1234",
+children=[
+ValueCheck(name="pointer"),
+ValueCheck(name="deleter", children=[
+ValueCheck(name="dummy_", value="")
+]),
+],
+)
+self.assertNotEqual(valobj.child[0].unsigned, 0)
 
 self.expect_var_path("up_user->id", type="int", value="30")
 self.expect_var_path("up_user->name", type="std::string", summary='"steph"')
Index: lldb/source/Plugins/Language/CPlusPlus/LibCxxList.cpp
===

[Lldb-commits] [PATCH] D148662: [lldb] Make the libcxx unique_ptr prettyprinter support custom deleters.

2023-05-01 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGd366da97bd24: [lldb] Make the libcxx unique_ptr 
prettyprinter support custom deleters. (authored by jgorbe).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148662

Files:
  lldb/include/lldb/DataFormatters/FormattersHelpers.h
  lldb/source/DataFormatters/FormattersHelpers.cpp
  lldb/source/Plugins/Language/CPlusPlus/LibCxx.cpp
  lldb/source/Plugins/Language/CPlusPlus/LibCxx.h
  lldb/source/Plugins/Language/CPlusPlus/LibCxxList.cpp
  
lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/TestDataFormatterLibcxxUniquePtr.py
  
lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/main.cpp

Index: lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/main.cpp
===
--- lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/main.cpp
+++ lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/main.cpp
@@ -6,6 +6,15 @@
   std::string name = "steph";
 };
 
+// libc++ stores unique_ptr data in a compressed pair, which has a specialized
+// representation when the type of the second element is an empty class. So
+// we need a deleter class with a dummy data member to trigger the other path.
+struct NonEmptyIntDeleter {
+  void operator()(int* ptr) { delete ptr; }
+
+  int dummy_ = ;
+};
+
 int main() {
   std::unique_ptr up_empty;
   std::unique_ptr up_int = std::make_unique(10);
@@ -13,6 +22,8 @@
   std::unique_ptr &up_int_ref = up_int;
   std::unique_ptr &&up_int_ref_ref = std::make_unique(10);
   std::unique_ptr up_user = std::make_unique();
+  auto up_non_empty_deleter =
+  std::unique_ptr(new int(1234));
 
   return 0; // break here
 }
Index: lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/TestDataFormatterLibcxxUniquePtr.py
===
--- lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/TestDataFormatterLibcxxUniquePtr.py
+++ lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/TestDataFormatterLibcxxUniquePtr.py
@@ -40,7 +40,7 @@
 "up_empty",
 type=self.make_expected_type("int"),
 summary="nullptr",
-children=[ValueCheck(name="__value_")],
+children=[ValueCheck(name="pointer")],
 )
 self.assertEqual(
 valobj.child[0].GetValueAsUnsigned(lldb.LLDB_INVALID_ADDRESS), 0
@@ -54,7 +54,7 @@
 "up_int",
 type=self.make_expected_type("int"),
 summary="10",
-children=[ValueCheck(name="__value_")],
+children=[ValueCheck(name="pointer")],
 )
 self.assertNotEqual(valobj.child[0].unsigned, 0)
 
@@ -62,7 +62,7 @@
 "up_int_ref",
 type=self.make_expected_type("int", qualifiers="&"),
 summary="10",
-children=[ValueCheck(name="__value_")],
+children=[ValueCheck(name="pointer")],
 )
 self.assertNotEqual(valobj.child[0].unsigned, 0)
 
@@ -70,7 +70,7 @@
 "up_int_ref_ref",
 type=self.make_expected_type("int", qualifiers="&&"),
 summary="10",
-children=[ValueCheck(name="__value_")],
+children=[ValueCheck(name="pointer")],
 )
 self.assertNotEqual(valobj.child[0].unsigned, 0)
 
@@ -78,7 +78,7 @@
 "up_str",
 type=self.make_expected_basic_string_ptr(),
 summary='"hello"',
-children=[ValueCheck(name="__value_", summary='"hello"')],
+children=[ValueCheck(name="pointer", summary='"hello"')],
 )
 
 valobj = self.expect_var_path(
@@ -95,7 +95,20 @@
 ValueCheck(name="name", summary='"steph"'),
 ],
 )
-self.assertEqual(str(valobj), '(User) *__value_ = (id = 30, name = "steph")')
+self.assertEqual(str(valobj), '(User) *pointer = (id = 30, name = "steph")')
+
+valobj = self.expect_var_path(
+"up_non_empty_deleter",
+type="std::unique_ptr",
+summary="1234",
+children=[
+ValueCheck(name="pointer"),
+ValueCheck(name="deleter", children=[
+ValueCheck(name="dummy_", value="")
+]),
+],
+)
+self.assertNotEqual(valobj.child[0].unsigned, 0)
 
 self.expect_var_path("up_user->id", type="int", value="30")
 self.expect_var_path("up_user->name", type="std::string", summary='"steph"')
Index: lldb/source/Plugins/Language/CPlusPlus/LibCxxList.cpp

[Lldb-commits] [PATCH] D148662: [lldb] Make the libcxx unique_ptr prettyprinter support custom deleters.

2023-05-01 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe added a comment.

Sure, I'll revert. Thanks for notifying me of the problem.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148662

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


[Lldb-commits] [PATCH] D148662: [lldb] Make the libcxx unique_ptr prettyprinter support custom deleters.

2023-05-01 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe added a comment.

Landed again, with a fix for the test that was failing on Darwin, as 
https://github.com/llvm/llvm-project/commit/d69518b4e52d527b3f8fcc41e90ae21f1f234555.
 I'll keep an eye on the build bot.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148662

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


[Lldb-commits] [PATCH] D147831: [lldb-vscode] Implement RestartRequest

2023-05-01 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe added inline comments.



Comment at: lldb/tools/lldb-vscode/VSCode.h:152
   bool is_attach;
+  // The process event thread normally responds to process exited events by
+  // shutting down the entire adapter. When we're restarting, we keep the id of

labath wrote:
> So, it's not possible to restart a process if it has already terminated? 
> I.e., if the debugged process unexpectedly exits, the user will have to 
> restart lldb-vscode from scratch (so he can e.g., set a breakpoint in before 
> the exit).
I don't know if it's //possible// (as in, if the protocol allows it), but it's 
what lldb-vscode does.

It also matches the behavior I remember when I used Visual Studio back in the 
day: when the debugged process exits, the debugging session ends and the UI 
switches back to "editing" mode automatically. If you need to re-run, you hit 
F5 and run it again. It's usually not a big deal because the IDE keeps the list 
of breakpoints and will transparently start lldb-vscode and set everything up 
again when you click "Run". It's also what VS Code does when a debug adapter 
doesn't support the RestartRequest, it just kills the adapter and restarts 
everything transparently (which is how restart works on lldb-vscode so far).



Comment at: lldb/tools/lldb-vscode/lldb-vscode.cpp:1976
+if (state != lldb::eStateConnected) {
+  process.Kill();
+}

wallace wrote:
> Kill actually detaches if lldb originally attached to the debuggee. The 
> actual implementation says
> 
> ```
>   /// Kills the process and shuts down all threads that were spawned to track
>   /// and monitor the process.
>   ///
>   /// This function is not meant to be overridden by Process subclasses.
>   ///
>   /// \param[in] force_kill
>   /// Whether lldb should force a kill (instead of a detach) from
>   /// the inferior process.  Normally if lldb launched a binary and
>   /// Destory is called, lldb kills it.  If lldb attached to a
>   /// running process and Destory is called, lldb detaches.  If
>   /// this behavior needs to be over-ridden, this is the bool that
>   /// can be used.
>   ///
>   /// \return
>   /// Returns an error object.
>   Status Destroy(bool force_kill);
> ```
> You could have the restart command reattach to the process instead of failing 
> if the user originally attached. 
> 
> What do you think of this?
I think it's something you *could* do, but it's not restarting. As I mention in 
a code comment above, I don't think "restart" is even well defined in the 
attach case.

As a user I would be really confused if I clicked on restart and the debugger 
deattached from the process, then immediately reattached, but nothing 
restarted. I can't think of a case where this would be useful.

Looking for some references, I started Visual Studio (not Code) and it simply 
grays out the "restart" button when attaching. Visual Studio Code, however, 
allows you to restart. I found [this 
issue](https://github.com/microsoft/debug-adapter-protocol/issues/73) where 
someone asked for clarification on the meaning of Restart in the protocol and 
got this explanation:

> "restart sequence" means:
> terminate current debug session via the disconnect request and immediately 
> start a new session via the launch or attach request
> 
> For the "launch" case "restart" can be used to pickup source changes that are 
> not automatically picked up while the program is running.
> 
> For the "attach" case "restart" has no direct effect on the debug target 
> because the debug target continues running. But it still might have an effect 
> on debugging because the debug adapter is restarted and this could pick up 
> changes to files that the debug adapter uses, e.g. source maps.

But I'm not very convinced by this because we're implementing RestartRequest, 
which means precisely that the adapter won't be restarted.



Comment at: lldb/tools/lldb-vscode/lldb-vscode.cpp:1983
+  g_vsc.debugger.SetAsync(true);
+  LaunchProcess(*g_vsc.last_launch_or_attach_request);
+

labath wrote:
> I have no idea if that's a good idea or not, but I'm wondering if, instead of 
> from the last attach request, we should be taking the arguments from lldb. So 
> that if the user say changes the `target.run-args` setting, then the new 
> restart request will take that into account...
I think the intended way to allow the user to modify the configuration is to 
use the optional `arguments` field in `RestartRequest`, which the client can 
use to send the latest version of the config.

https://microsoft.github.io/debug-adapter-protocol/specification#Requests_Restart

> ```
> interface RestartRequest extends Request {
>   command: 'restart';
> 
>   arguments?: RestartArguments;
> }
> ```
> Arguments for restart request.
> 
> ```
> interface RestartArguments {
>   /**
>* The latest version of the `launch` or `attach` configuration.
>*/
>

[Lldb-commits] [PATCH] D147831: [lldb-vscode] Implement RestartRequest

2023-05-02 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG2b6c5bb995be: [lldb-vscode] Implement RestartRequest 
(authored by jgorbe).

Changed prior to commit:
  https://reviews.llvm.org/D147831?vs=512305&id=518866#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147831

Files:
  lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py
  lldb/source/API/SBProcess.cpp
  lldb/test/API/tools/lldb-vscode/restart/Makefile
  lldb/test/API/tools/lldb-vscode/restart/TestVSCode_restart.py
  lldb/test/API/tools/lldb-vscode/restart/TestVSCode_restart_runInTerminal.py
  lldb/test/API/tools/lldb-vscode/restart/main.c
  lldb/tools/lldb-vscode/VSCode.cpp
  lldb/tools/lldb-vscode/VSCode.h
  lldb/tools/lldb-vscode/lldb-vscode.cpp

Index: lldb/tools/lldb-vscode/lldb-vscode.cpp
===
--- lldb/tools/lldb-vscode/lldb-vscode.cpp
+++ lldb/tools/lldb-vscode/lldb-vscode.cpp
@@ -458,7 +458,8 @@
 // manually send a stopped event in request_configurationDone(...)
 // so don't send any before then.
 if (g_vsc.configuration_done_sent) {
-  // Only report a stopped event if the process was not restarted.
+  // Only report a stopped event if the process was not
+  // automatically restarted.
   if (!lldb::SBProcess::GetRestartedFromEvent(event)) {
 SendStdOutStdErr(process);
 SendThreadStoppedEvent();
@@ -468,14 +469,22 @@
   case lldb::eStateRunning:
 g_vsc.WillContinue();
 break;
-  case lldb::eStateExited: {
-// Run any exit LLDB commands the user specified in the
-// launch.json
-g_vsc.RunExitCommands();
-SendProcessExitedEvent(process);
-SendTerminatedEvent();
-done = true;
-  } break;
+  case lldb::eStateExited:
+// When restarting, we can get an "exited" event for the process we
+// just killed with the old PID, or even with no PID. In that case
+// we don't have to terminate the session.
+if (process.GetProcessID() == LLDB_INVALID_PROCESS_ID ||
+process.GetProcessID() == g_vsc.restarting_process_id) {
+  g_vsc.restarting_process_id = LLDB_INVALID_PROCESS_ID;
+} else {
+  // Run any exit LLDB commands the user specified in the
+  // launch.json
+  g_vsc.RunExitCommands();
+  SendProcessExitedEvent(process);
+  SendTerminatedEvent();
+  done = true;
+}
+break;
   }
 } else if ((event_mask & lldb::SBProcess::eBroadcastBitSTDOUT) ||
(event_mask & lldb::SBProcess::eBroadcastBitSTDERR)) {
@@ -592,6 +601,7 @@
 // }
 void request_attach(const llvm::json::Object &request) {
   g_vsc.is_attach = true;
+  g_vsc.last_launch_or_attach_request = request;
   llvm::json::Object response;
   lldb::SBError error;
   FillResponse(request, response);
@@ -1527,7 +1537,7 @@
   // The debug adapter supports the RestartRequest. In this case a client
   // should not implement 'restart' by terminating and relaunching the adapter
   // but by calling the RestartRequest.
-  body.try_emplace("supportsRestartRequest", false);
+  body.try_emplace("supportsRestartRequest", true);
   // The debug adapter supports 'exceptionOptions' on the
   // setExceptionBreakpoints request.
   body.try_emplace("supportsExceptionOptions", true);
@@ -1622,6 +1632,71 @@
  error.GetCString());
 }
 
+// Takes a LaunchRequest object and launches the process, also handling
+// runInTerminal if applicable. It doesn't do any of the additional
+// initialization and bookkeeping stuff that is needed for `request_launch`.
+// This way we can reuse the process launching logic for RestartRequest too.
+lldb::SBError LaunchProcess(const llvm::json::Object &request) {
+  lldb::SBError error;
+  auto arguments = request.getObject("arguments");
+  auto launchCommands = GetStrings(arguments, "launchCommands");
+
+  // Instantiate a launch info instance for the target.
+  auto launch_info = g_vsc.target.GetLaunchInfo();
+
+  // Grab the current working directory if there is one and set it in the
+  // launch info.
+  const auto cwd = GetString(arguments, "cwd");
+  if (!cwd.empty())
+launch_info.SetWorkingDirectory(cwd.data());
+
+  // Extract any extra arguments and append them to our program arguments for
+  // when we launch
+  auto args = GetStrings(arguments, "args");
+  if (!args.empty())
+launch_info.SetArguments(MakeArgv(args).data(), true);
+
+  // Pass any environment variables along that the user specified.
+  auto envs = GetStrings(arguments, "env");
+  if (!envs.empty())
+launch_info.SetEnvironme

[Lldb-commits] [PATCH] D149774: [lldb] Use templates to simplify {Get, Set}PropertyAtIndex (NFC)

2023-05-08 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe added inline comments.



Comment at: lldb/source/Target/Target.cpp:4520
   const uint32_t idx = ePropertyMaxSummaryLength;
-  return m_collection_sp->GetPropertyAtIndexAsSInt64(idx).value_or(
-  g_target_properties[idx].default_uint_value);
+  return GetPropertyAtIndexAs(
+  idx, g_target_properties[idx].default_uint_value);

I think this is causing `settings set target.max-string-summary-length` not to 
work properly.

As far as I can tell, the problem is that `GetPropertyAtIndexAs` will 
end up calling `OptionValue::GetAsUInt64()` which checks the declared type of 
the property and returns null if there's a mismatch. 
`target.max-string-summary-length` is, for some reason, defined as signed, so 
this will always return the default value regardless of what it was set to.

You should be able to reproduce it by writing a simple program with a 
`std::string`, setting `target.max-string-summary-length` to some small value 
and checking that the string is not truncated.

`GetMaximumMemReadSize`, just below this one, seems to be mismatched too 
because the diff shows a change from `GetPropertyAtIndexAsSInt64` to 
`GetPropertyAtIndexAs` but I haven't actually tested that one. It 
would probably be a good idea to double check the rest of the patch looking for 
other mismatches.




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D149774

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


[Lldb-commits] [PATCH] D150392: [lldb-vscode] Fix handling of RestartRequest arguments.

2023-05-11 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe created this revision.
jgorbe added reviewers: clayborg, wallace, labath, rupprecht.
jgorbe added a project: LLDB.
Herald added a subscriber: JDevlieghere.
Herald added a project: All.
jgorbe requested review of this revision.

According to the spec, RestartRequest has an optional "arguments" field, which
is a RestartArguments object. RestartArguments has its own optional "arguments"
field, which is a (LaunchRequestArguments | AttachRequestArguments) object. So
we need to to the "arguments" lookup twice to get to the actual launch
arguments.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D150392

Files:
  lldb/tools/lldb-vscode/lldb-vscode.cpp


Index: lldb/tools/lldb-vscode/lldb-vscode.cpp
===
--- lldb/tools/lldb-vscode/lldb-vscode.cpp
+++ lldb/tools/lldb-vscode/lldb-vscode.cpp
@@ -1963,11 +1963,13 @@
 
   // The optional `arguments` field in RestartRequest can contain an updated
   // version of the launch arguments. If there's one, use it.
-  auto request_arguments = request.getObject("arguments");
-  if (request_arguments) {
-llvm::json::Object arguments = *request_arguments;
-(*g_vsc.last_launch_or_attach_request)["arguments"] =
-llvm::json::Value(std::move(arguments));
+  auto restart_arguments = request.getObject("arguments");
+  if (restart_arguments) {
+auto launch_request_arguments = restart_arguments->getObject("arguments");
+if (launch_request_arguments) {
+  (*g_vsc.last_launch_or_attach_request)["arguments"] =
+  llvm::json::Value(llvm::json::Object(*launch_request_arguments));
+}
   }
 
   // Keep track of the old PID so when we get a "process exited" event from the


Index: lldb/tools/lldb-vscode/lldb-vscode.cpp
===
--- lldb/tools/lldb-vscode/lldb-vscode.cpp
+++ lldb/tools/lldb-vscode/lldb-vscode.cpp
@@ -1963,11 +1963,13 @@
 
   // The optional `arguments` field in RestartRequest can contain an updated
   // version of the launch arguments. If there's one, use it.
-  auto request_arguments = request.getObject("arguments");
-  if (request_arguments) {
-llvm::json::Object arguments = *request_arguments;
-(*g_vsc.last_launch_or_attach_request)["arguments"] =
-llvm::json::Value(std::move(arguments));
+  auto restart_arguments = request.getObject("arguments");
+  if (restart_arguments) {
+auto launch_request_arguments = restart_arguments->getObject("arguments");
+if (launch_request_arguments) {
+  (*g_vsc.last_launch_or_attach_request)["arguments"] =
+  llvm::json::Value(llvm::json::Object(*launch_request_arguments));
+}
   }
 
   // Keep track of the old PID so when we get a "process exited" event from the
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D150392: [lldb-vscode] Fix handling of RestartRequest arguments.

2023-05-11 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe updated this revision to Diff 521412.
jgorbe added a comment.

Added test case.


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

https://reviews.llvm.org/D150392

Files:
  lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py
  lldb/test/API/tools/lldb-vscode/restart/TestVSCode_restart.py
  lldb/tools/lldb-vscode/lldb-vscode.cpp


Index: lldb/tools/lldb-vscode/lldb-vscode.cpp
===
--- lldb/tools/lldb-vscode/lldb-vscode.cpp
+++ lldb/tools/lldb-vscode/lldb-vscode.cpp
@@ -1963,11 +1963,13 @@
 
   // The optional `arguments` field in RestartRequest can contain an updated
   // version of the launch arguments. If there's one, use it.
-  auto request_arguments = request.getObject("arguments");
-  if (request_arguments) {
-llvm::json::Object arguments = *request_arguments;
-(*g_vsc.last_launch_or_attach_request)["arguments"] =
-llvm::json::Value(std::move(arguments));
+  auto restart_arguments = request.getObject("arguments");
+  if (restart_arguments) {
+auto launch_request_arguments = restart_arguments->getObject("arguments");
+if (launch_request_arguments) {
+  (*g_vsc.last_launch_or_attach_request)["arguments"] =
+  llvm::json::Value(llvm::json::Object(*launch_request_arguments));
+}
   }
 
   // Keep track of the old PID so when we get a "process exited" event from the
Index: lldb/test/API/tools/lldb-vscode/restart/TestVSCode_restart.py
===
--- lldb/test/API/tools/lldb-vscode/restart/TestVSCode_restart.py
+++ lldb/test/API/tools/lldb-vscode/restart/TestVSCode_restart.py
@@ -80,3 +80,37 @@
 reason, 'breakpoint',
 'verify stop after restart isn\'t "main" breakpoint')
 
+@skipIfWindows
+@skipIfRemote
+def test_arguments(self):
+'''
+Tests that lldb-vscode will use updated launch arguments included
+with a restart request.
+'''
+line_A = line_number('main.c', '// breakpoint A')
+
+program = self.getBuildArtifact("a.out")
+self.build_and_launch(program)
+[bp_A] = self.set_source_breakpoints('main.c', [line_A])
+
+# Verify we hit A, then B.
+self.vscode.request_configurationDone()
+self.verify_breakpoint_hit([bp_A])
+
+# We don't set any arguments in the initial launch request, so argc
+# should be 1.
+self.assertEquals(int(self.vscode.get_local_variable_value('argc')),
+  1, 'argc != 1 before restart')
+
+# Restart with some extra 'args' and check that the new argc reflects
+# the updated launch config.
+self.vscode.request_restart(restartArguments={
+'arguments': {
+'program': program,
+'args': ['a', 'b', 'c', 'd'],
+}
+})
+self.verify_breakpoint_hit([bp_A])
+self.assertEquals(int(self.vscode.get_local_variable_value('argc')),
+  5, 'argc != 5 after restart')
+
Index: lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py
===
--- lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py
+++ lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py
@@ -588,11 +588,14 @@
 # Caller must still call wait_for_stopped.
 return response
 
-def request_restart(self):
+def request_restart(self, restartArguments=None):
 command_dict = {
 'command': 'restart',
 'type': 'request',
 }
+if restartArguments:
+  command_dict['arguments'] = restartArguments
+
 response = self.send_recv(command_dict)
 # Caller must still call wait_for_stopped.
 return response


Index: lldb/tools/lldb-vscode/lldb-vscode.cpp
===
--- lldb/tools/lldb-vscode/lldb-vscode.cpp
+++ lldb/tools/lldb-vscode/lldb-vscode.cpp
@@ -1963,11 +1963,13 @@
 
   // The optional `arguments` field in RestartRequest can contain an updated
   // version of the launch arguments. If there's one, use it.
-  auto request_arguments = request.getObject("arguments");
-  if (request_arguments) {
-llvm::json::Object arguments = *request_arguments;
-(*g_vsc.last_launch_or_attach_request)["arguments"] =
-llvm::json::Value(std::move(arguments));
+  auto restart_arguments = request.getObject("arguments");
+  if (restart_arguments) {
+auto launch_request_arguments = restart_arguments->getObject("arguments");
+if (launch_request_arguments) {
+  (*g_vsc.last_launch_or_attach_request)["arguments"] =
+  llvm::json::Value(llvm::json::Object(*launch_request_arguments));
+}
   }
 
   // Keep track of the old PID so when we get a "process exited" event from the
Index: lldb/test/API

[Lldb-commits] [PATCH] D150392: [lldb-vscode] Fix handling of RestartRequest arguments.

2023-05-11 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG1b11034c672f: [lldb-vscode] Fix handling of RestartRequest 
arguments. (authored by jgorbe).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D150392

Files:
  lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py
  lldb/test/API/tools/lldb-vscode/restart/TestVSCode_restart.py
  lldb/tools/lldb-vscode/lldb-vscode.cpp


Index: lldb/tools/lldb-vscode/lldb-vscode.cpp
===
--- lldb/tools/lldb-vscode/lldb-vscode.cpp
+++ lldb/tools/lldb-vscode/lldb-vscode.cpp
@@ -1963,11 +1963,13 @@
 
   // The optional `arguments` field in RestartRequest can contain an updated
   // version of the launch arguments. If there's one, use it.
-  auto request_arguments = request.getObject("arguments");
-  if (request_arguments) {
-llvm::json::Object arguments = *request_arguments;
-(*g_vsc.last_launch_or_attach_request)["arguments"] =
-llvm::json::Value(std::move(arguments));
+  auto restart_arguments = request.getObject("arguments");
+  if (restart_arguments) {
+auto launch_request_arguments = restart_arguments->getObject("arguments");
+if (launch_request_arguments) {
+  (*g_vsc.last_launch_or_attach_request)["arguments"] =
+  llvm::json::Value(llvm::json::Object(*launch_request_arguments));
+}
   }
 
   // Keep track of the old PID so when we get a "process exited" event from the
Index: lldb/test/API/tools/lldb-vscode/restart/TestVSCode_restart.py
===
--- lldb/test/API/tools/lldb-vscode/restart/TestVSCode_restart.py
+++ lldb/test/API/tools/lldb-vscode/restart/TestVSCode_restart.py
@@ -80,3 +80,37 @@
 reason, 'breakpoint',
 'verify stop after restart isn\'t "main" breakpoint')
 
+@skipIfWindows
+@skipIfRemote
+def test_arguments(self):
+'''
+Tests that lldb-vscode will use updated launch arguments included
+with a restart request.
+'''
+line_A = line_number('main.c', '// breakpoint A')
+
+program = self.getBuildArtifact("a.out")
+self.build_and_launch(program)
+[bp_A] = self.set_source_breakpoints('main.c', [line_A])
+
+# Verify we hit A, then B.
+self.vscode.request_configurationDone()
+self.verify_breakpoint_hit([bp_A])
+
+# We don't set any arguments in the initial launch request, so argc
+# should be 1.
+self.assertEquals(int(self.vscode.get_local_variable_value('argc')),
+  1, 'argc != 1 before restart')
+
+# Restart with some extra 'args' and check that the new argc reflects
+# the updated launch config.
+self.vscode.request_restart(restartArguments={
+'arguments': {
+'program': program,
+'args': ['a', 'b', 'c', 'd'],
+}
+})
+self.verify_breakpoint_hit([bp_A])
+self.assertEquals(int(self.vscode.get_local_variable_value('argc')),
+  5, 'argc != 5 after restart')
+
Index: lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py
===
--- lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py
+++ lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py
@@ -588,11 +588,14 @@
 # Caller must still call wait_for_stopped.
 return response
 
-def request_restart(self):
+def request_restart(self, restartArguments=None):
 command_dict = {
 'command': 'restart',
 'type': 'request',
 }
+if restartArguments:
+  command_dict['arguments'] = restartArguments
+
 response = self.send_recv(command_dict)
 # Caller must still call wait_for_stopped.
 return response


Index: lldb/tools/lldb-vscode/lldb-vscode.cpp
===
--- lldb/tools/lldb-vscode/lldb-vscode.cpp
+++ lldb/tools/lldb-vscode/lldb-vscode.cpp
@@ -1963,11 +1963,13 @@
 
   // The optional `arguments` field in RestartRequest can contain an updated
   // version of the launch arguments. If there's one, use it.
-  auto request_arguments = request.getObject("arguments");
-  if (request_arguments) {
-llvm::json::Object arguments = *request_arguments;
-(*g_vsc.last_launch_or_attach_request)["arguments"] =
-llvm::json::Value(std::move(arguments));
+  auto restart_arguments = request.getObject("arguments");
+  if (restart_arguments) {
+auto launch_request_arguments = restart_arguments->getObject("arguments");
+if (launch_request_arguments) {
+  (*g_vsc.last_launch_or_attach_request)["arguments"] =
+  llvm::json::Value(llvm::json::Object(*launch

[Lldb-commits] [PATCH] D150470: [lldb-vscode] Make tests not wait for 'launch' process events if launch fails.

2023-05-12 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe created this revision.
jgorbe added reviewers: ted, luporl, wallace.
jgorbe added a project: LLDB.
Herald added a subscriber: JDevlieghere.
Herald added a project: All.
jgorbe requested review of this revision.

After https://reviews.llvm.org/D147831, lldb-vscode doesn't send a
process event after launch/attach in case of failure. I believe this is
the right interpretation of the spec, because the description of the
event says:

> The event indicates that the debugger has begun debugging a new
> process.

and we haven't started debugging a process if there's no process because
we failed to launch it. This is also supported by the fact that
`request_launch` in vscode.py doesn't wait for the event if passed
`expectFailure=True`. However, this doesn't take into account
*unexpected* launch failures. In that case, `request_launch` will hang
indefinitely waiting for the process event.

This patch changes it so we'll only wait for these events if
`request["success"]` is true, independently of whether any failure was
expected or not.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D150470

Files:
  lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/lldbvscode_testcase.py
  lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py


Index: lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py
===
--- lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py
+++ lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py
@@ -661,8 +661,7 @@
stopCommands=None, exitCommands=None,
terminateCommands=None ,sourcePath=None,
debuggerRoot=None, launchCommands=None, sourceMap=None,
-   runInTerminal=False, expectFailure=False,
-   postRunCommands=None):
+   runInTerminal=False, postRunCommands=None):
 args_dict = {
 'program': program
 }
@@ -712,7 +711,7 @@
 }
 response = self.send_recv(command_dict)
 
-if not expectFailure:
+if response['success']:
 # Wait for a 'process' and 'initialized' event in any order
 self.wait_for_event(filter=['process', 'initialized'])
 self.wait_for_event(filter=['process', 'initialized'])
Index: 
lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/lldbvscode_testcase.py
===
--- lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/lldbvscode_testcase.py
+++ lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/lldbvscode_testcase.py
@@ -322,7 +322,6 @@
 launchCommands=launchCommands,
 sourceMap=sourceMap,
 runInTerminal=runInTerminal,
-expectFailure=expectFailure,
 postRunCommands=postRunCommands)
 
 if expectFailure:


Index: lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py
===
--- lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py
+++ lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py
@@ -661,8 +661,7 @@
stopCommands=None, exitCommands=None,
terminateCommands=None ,sourcePath=None,
debuggerRoot=None, launchCommands=None, sourceMap=None,
-   runInTerminal=False, expectFailure=False,
-   postRunCommands=None):
+   runInTerminal=False, postRunCommands=None):
 args_dict = {
 'program': program
 }
@@ -712,7 +711,7 @@
 }
 response = self.send_recv(command_dict)
 
-if not expectFailure:
+if response['success']:
 # Wait for a 'process' and 'initialized' event in any order
 self.wait_for_event(filter=['process', 'initialized'])
 self.wait_for_event(filter=['process', 'initialized'])
Index: lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/lldbvscode_testcase.py
===
--- lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/lldbvscode_testcase.py
+++ lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/lldbvscode_testcase.py
@@ -322,7 +322,6 @@
 launchCommands=launchCommands,
 sourceMap=sourceMap,
 runInTerminal=runInTerminal,
-expectFailure=expectFailure,
 postRunCommands=postRunCommands)
 
 if expectFailure:
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D150470: [lldb-vscode] Make tests not wait for 'launch' process events if launch fails.

2023-05-12 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe added a comment.

See also https://github.com/llvm/llvm-project/issues/62684


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D150470

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


[Lldb-commits] [PATCH] D150470: [lldb-vscode] Make tests not wait for 'launch' process events if launch fails.

2023-05-22 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGd25fb4e90c96: [lldb-vscode] Make tests not wait for 
'launch' process events if launch fails. (authored by jgorbe).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D150470

Files:
  lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/lldbvscode_testcase.py
  lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py


Index: lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py
===
--- lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py
+++ lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py
@@ -661,8 +661,7 @@
stopCommands=None, exitCommands=None,
terminateCommands=None ,sourcePath=None,
debuggerRoot=None, launchCommands=None, sourceMap=None,
-   runInTerminal=False, expectFailure=False,
-   postRunCommands=None):
+   runInTerminal=False, postRunCommands=None):
 args_dict = {
 'program': program
 }
@@ -712,7 +711,7 @@
 }
 response = self.send_recv(command_dict)
 
-if not expectFailure:
+if response['success']:
 # Wait for a 'process' and 'initialized' event in any order
 self.wait_for_event(filter=['process', 'initialized'])
 self.wait_for_event(filter=['process', 'initialized'])
Index: 
lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/lldbvscode_testcase.py
===
--- lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/lldbvscode_testcase.py
+++ lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/lldbvscode_testcase.py
@@ -322,7 +322,6 @@
 launchCommands=launchCommands,
 sourceMap=sourceMap,
 runInTerminal=runInTerminal,
-expectFailure=expectFailure,
 postRunCommands=postRunCommands)
 
 if expectFailure:


Index: lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py
===
--- lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py
+++ lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py
@@ -661,8 +661,7 @@
stopCommands=None, exitCommands=None,
terminateCommands=None ,sourcePath=None,
debuggerRoot=None, launchCommands=None, sourceMap=None,
-   runInTerminal=False, expectFailure=False,
-   postRunCommands=None):
+   runInTerminal=False, postRunCommands=None):
 args_dict = {
 'program': program
 }
@@ -712,7 +711,7 @@
 }
 response = self.send_recv(command_dict)
 
-if not expectFailure:
+if response['success']:
 # Wait for a 'process' and 'initialized' event in any order
 self.wait_for_event(filter=['process', 'initialized'])
 self.wait_for_event(filter=['process', 'initialized'])
Index: lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/lldbvscode_testcase.py
===
--- lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/lldbvscode_testcase.py
+++ lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/lldbvscode_testcase.py
@@ -322,7 +322,6 @@
 launchCommands=launchCommands,
 sourceMap=sourceMap,
 runInTerminal=runInTerminal,
-expectFailure=expectFailure,
 postRunCommands=postRunCommands)
 
 if expectFailure:
___
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits


[Lldb-commits] [PATCH] D133230: [NFCI] Remove duplicate code in SBTypeCategory

2022-09-02 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe created this revision.
jgorbe added a project: LLDB.
Herald added a subscriber: JDevlieghere.
Herald added a project: All.
jgorbe requested review of this revision.

TypeCategoryImpl has its own implementation of these, so it makes no
sense to have the same logic inlined in SBTypeCategory.

There are other methods in SBTypeCategory that are directly implemented
there, instead of delegating to TypeCategoryImpl (which IMO kinda
defeats the point of having an "opaque" member pointer in the SB type),
but they don't have equivalent implementations in TypeCategoryImpl, so
this patch only picks the low-hanging fruit for now.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D133230

Files:
  lldb/source/API/SBTypeCategory.cpp


Index: lldb/source/API/SBTypeCategory.cpp
===
--- lldb/source/API/SBTypeCategory.cpp
+++ lldb/source/API/SBTypeCategory.cpp
@@ -185,14 +185,8 @@
   if (!spec.IsValid())
 return SBTypeFilter();
 
-  lldb::TypeFilterImplSP children_sp;
-
-  if (spec.IsRegex())
-m_opaque_sp->GetRegexTypeFiltersContainer()->GetExact(
-ConstString(spec.GetName()), children_sp);
-  else
-m_opaque_sp->GetTypeFiltersContainer()->GetExact(
-ConstString(spec.GetName()), children_sp);
+  lldb::TypeFilterImplSP children_sp =
+  m_opaque_sp->GetFilterForType(spec.GetSP());
 
   if (!children_sp)
 return lldb::SBTypeFilter();
@@ -211,14 +205,8 @@
   if (!spec.IsValid())
 return SBTypeFormat();
 
-  lldb::TypeFormatImplSP format_sp;
-
-  if (spec.IsRegex())
-m_opaque_sp->GetRegexTypeFormatsContainer()->GetExact(
-ConstString(spec.GetName()), format_sp);
-  else
-m_opaque_sp->GetTypeFormatsContainer()->GetExact(
-ConstString(spec.GetName()), format_sp);
+  lldb::TypeFormatImplSP format_sp =
+  m_opaque_sp->GetFormatForType(spec.GetSP());
 
   if (!format_sp)
 return lldb::SBTypeFormat();
@@ -235,14 +223,8 @@
   if (!spec.IsValid())
 return SBTypeSummary();
 
-  lldb::TypeSummaryImplSP summary_sp;
-
-  if (spec.IsRegex())
-m_opaque_sp->GetRegexTypeSummariesContainer()->GetExact(
-ConstString(spec.GetName()), summary_sp);
-  else
-m_opaque_sp->GetTypeSummariesContainer()->GetExact(
-ConstString(spec.GetName()), summary_sp);
+  lldb::TypeSummaryImplSP summary_sp =
+  m_opaque_sp->GetSummaryForType(spec.GetSP());
 
   if (!summary_sp)
 return lldb::SBTypeSummary();
@@ -259,14 +241,8 @@
   if (!spec.IsValid())
 return SBTypeSynthetic();
 
-  lldb::SyntheticChildrenSP children_sp;
-
-  if (spec.IsRegex())
-m_opaque_sp->GetRegexTypeSyntheticsContainer()->GetExact(
-ConstString(spec.GetName()), children_sp);
-  else
-m_opaque_sp->GetTypeSyntheticsContainer()->GetExact(
-ConstString(spec.GetName()), children_sp);
+  lldb::SyntheticChildrenSP children_sp =
+  m_opaque_sp->GetSyntheticForType(spec.GetSP());
 
   if (!children_sp)
 return lldb::SBTypeSynthetic();


Index: lldb/source/API/SBTypeCategory.cpp
===
--- lldb/source/API/SBTypeCategory.cpp
+++ lldb/source/API/SBTypeCategory.cpp
@@ -185,14 +185,8 @@
   if (!spec.IsValid())
 return SBTypeFilter();
 
-  lldb::TypeFilterImplSP children_sp;
-
-  if (spec.IsRegex())
-m_opaque_sp->GetRegexTypeFiltersContainer()->GetExact(
-ConstString(spec.GetName()), children_sp);
-  else
-m_opaque_sp->GetTypeFiltersContainer()->GetExact(
-ConstString(spec.GetName()), children_sp);
+  lldb::TypeFilterImplSP children_sp =
+  m_opaque_sp->GetFilterForType(spec.GetSP());
 
   if (!children_sp)
 return lldb::SBTypeFilter();
@@ -211,14 +205,8 @@
   if (!spec.IsValid())
 return SBTypeFormat();
 
-  lldb::TypeFormatImplSP format_sp;
-
-  if (spec.IsRegex())
-m_opaque_sp->GetRegexTypeFormatsContainer()->GetExact(
-ConstString(spec.GetName()), format_sp);
-  else
-m_opaque_sp->GetTypeFormatsContainer()->GetExact(
-ConstString(spec.GetName()), format_sp);
+  lldb::TypeFormatImplSP format_sp =
+  m_opaque_sp->GetFormatForType(spec.GetSP());
 
   if (!format_sp)
 return lldb::SBTypeFormat();
@@ -235,14 +223,8 @@
   if (!spec.IsValid())
 return SBTypeSummary();
 
-  lldb::TypeSummaryImplSP summary_sp;
-
-  if (spec.IsRegex())
-m_opaque_sp->GetRegexTypeSummariesContainer()->GetExact(
-ConstString(spec.GetName()), summary_sp);
-  else
-m_opaque_sp->GetTypeSummariesContainer()->GetExact(
-ConstString(spec.GetName()), summary_sp);
+  lldb::TypeSummaryImplSP summary_sp =
+  m_opaque_sp->GetSummaryForType(spec.GetSP());
 
   if (!summary_sp)
 return lldb::SBTypeSummary();
@@ -259,14 +241,8 @@
   if (!spec.IsValid())
 return SBTypeSynthetic();
 
-  lldb::SyntheticChildrenSP children_sp;
-
-  if (spec.IsRegex())
-m_opaque_sp->GetRegexTypeSyntheticsContainer()->GetExact(
-ConstString(spec.GetName()), childre

[Lldb-commits] [PATCH] D133240: [Formatters][NFCI] Replace 'is_regex' arguments with an enum.

2022-09-02 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe created this revision.
jgorbe added reviewers: jingham, labath.
jgorbe added a project: LLDB.
Herald added a subscriber: JDevlieghere.
Herald added a project: All.
jgorbe requested review of this revision.

Modify `SBTypeNameSpecifier` and `lldb_private::TypeMatcher` so they
have an enum value for the type of matching to perform instead of an
`m_is_regex` boolean value.

This change paves the way for introducing formatter matching based on
the result of a python callback in addition to the existing name-based
matching. See the RFC thread at
https://discourse.llvm.org/t/rfc-python-callback-for-data-formatters-type-matching/64204
for more details.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D133240

Files:
  lldb/bindings/interface/SBTypeNameSpecifier.i
  lldb/include/lldb/API/SBTypeNameSpecifier.h
  lldb/include/lldb/DataFormatters/FormatClasses.h
  lldb/include/lldb/DataFormatters/FormattersContainer.h
  lldb/include/lldb/lldb-enumerations.h
  lldb/source/API/SBTypeNameSpecifier.cpp
  lldb/source/Core/FormatEntity.cpp

Index: lldb/source/Core/FormatEntity.cpp
===
--- lldb/source/Core/FormatEntity.cpp
+++ lldb/source/Core/FormatEntity.cpp
@@ -825,7 +825,7 @@
 bitfield_name.Printf("%s:%d", target->GetTypeName().AsCString(),
  target->GetBitfieldBitSize());
 auto type_sp = std::make_shared(
-bitfield_name.GetString(), false);
+bitfield_name.GetString(), lldb::eFormatterMatchExact);
 if (val_obj_display ==
 ValueObject::eValueObjectRepresentationStyleSummary &&
 !DataVisualization::GetSummaryForType(type_sp))
Index: lldb/source/API/SBTypeNameSpecifier.cpp
===
--- lldb/source/API/SBTypeNameSpecifier.cpp
+++ lldb/source/API/SBTypeNameSpecifier.cpp
@@ -20,8 +20,15 @@
 SBTypeNameSpecifier::SBTypeNameSpecifier() { LLDB_INSTRUMENT_VA(this); }
 
 SBTypeNameSpecifier::SBTypeNameSpecifier(const char *name, bool is_regex)
-: m_opaque_sp(new TypeNameSpecifierImpl(name, is_regex)) {
+: SBTypeNameSpecifier(name, is_regex ? eFormatterMatchRegex
+ : eFormatterMatchExact) {
   LLDB_INSTRUMENT_VA(this, name, is_regex);
+}
+
+SBTypeNameSpecifier::SBTypeNameSpecifier(const char *name,
+ FormatterMatchType match_type)
+: m_opaque_sp(new TypeNameSpecifierImpl(name, match_type)) {
+  LLDB_INSTRUMENT_VA(this, name, match_type);
 
   if (name == nullptr || (*name) == 0)
 m_opaque_sp.reset();
@@ -72,13 +79,20 @@
   return SBType();
 }
 
+FormatterMatchType SBTypeNameSpecifier::GetMatchType() {
+  LLDB_INSTRUMENT_VA(this);
+  if (!IsValid())
+return eFormatterMatchExact;
+  return m_opaque_sp->GetMatchType();
+}
+
 bool SBTypeNameSpecifier::IsRegex() {
   LLDB_INSTRUMENT_VA(this);
 
   if (!IsValid())
 return false;
 
-  return m_opaque_sp->IsRegex();
+  return m_opaque_sp->GetMatchType() == eFormatterMatchRegex;
 }
 
 bool SBTypeNameSpecifier::GetDescription(
@@ -116,7 +130,7 @@
   if (!IsValid())
 return !rhs.IsValid();
 
-  if (IsRegex() != rhs.IsRegex())
+  if (GetMatchType() != rhs.GetMatchType())
 return false;
   if (GetName() == nullptr || rhs.GetName() == nullptr)
 return false;
Index: lldb/include/lldb/lldb-enumerations.h
===
--- lldb/include/lldb/lldb-enumerations.h
+++ lldb/include/lldb/lldb-enumerations.h
@@ -832,6 +832,15 @@
   eTemplateArgumentKindNullPtr,
 };
 
+/// Type of match to be performed when looking for a formatter for a data type.
+/// Used by classes like SBTypeNameSpecifier or lldb_private::TypeMatcher.
+enum FormatterMatchType {
+  eFormatterMatchExact,
+  eFormatterMatchRegex,
+
+  kNumFormatterMatchTypes,
+};
+
 /// Options that can be set for a formatter to alter its behavior. Not
 /// all of these are applicable to all formatter types.
 FLAGS_ENUM(TypeOptions){eTypeOptionNone = (0u),
Index: lldb/include/lldb/DataFormatters/FormattersContainer.h
===
--- lldb/include/lldb/DataFormatters/FormattersContainer.h
+++ lldb/include/lldb/DataFormatters/FormattersContainer.h
@@ -43,7 +43,7 @@
   ConstString m_type_name;
   /// False if m_type_name_regex should be used for matching. False if this is
   /// just matching by comparing with m_type_name string.
-  bool m_is_regex;
+  lldb::FormatterMatchType m_match_type;
 
   // if the user tries to add formatters for, say, "struct Foo" those will not
   // match any type because of the way we strip qualifiers from typenames this
@@ -71,22 +71,25 @@
   TypeMatcher() = delete;
   /// Creates a matcher that accepts any type with exactly the given type name.
   TypeMatcher(ConstString type_name)
-  : m_type_name(type_name), m_is_regex(false) {}
+  : m_type_name(type_name), m_match_type(lldb::eFormat

[Lldb-commits] [PATCH] D133240: [Formatters][NFCI] Replace 'is_regex' arguments with an enum.

2022-09-02 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe added a comment.

This is the first step towards something like this big diff: 
https://reviews.llvm.org/differential/diff/457740/. It's a pretty simple patch, 
but I would like some feedback about whether you think it's going in the right 
direction or I should do something else instead.

Here's some more context for that diff linked above. There is, as you could 
expect, some amount of plumbing so that at callback matching time we have 
around pointers to the script interpreter, the type of the value, etc, and we 
can call the callback. But the biggest problem I've found is that there's some 
logic that is duplicated for each one of {exact, regex} AND for each kind of 
formatter (summaries, synthetic child providers...). An example of this is 
`TypeCategoryImpl::AnyMatches`. Adding a new matching strategy ({exact, regex, 
callback}) makes the combinatorial problem even worse. So a big chunk of that 
patch is moving stuff around to try to minimize this problem.

The main refactoring is replacing the existing `FormatterContainerPair` (that 
has two members that contain exact match formatters and regex formatters, 
respectively) with a `TieredFormatterContainer` which has an array of 
containers in priority order. The idea is to sink as much of duplicated logic 
as possible around `TypeCategoryImpl` (for example, `GetFormatAtIndex`, 
`GetSummaryAtIndex`, `GetFilterAtIndex`...) into this 
`TieredFormatterContainer` to reuse the implementation.

I hope this helps understand the general idea a bit better.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133240

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


[Lldb-commits] [PATCH] D133240: [Formatters][NFCI] Replace 'is_regex' arguments with an enum.

2022-09-12 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe updated this revision to Diff 459610.
jgorbe added a comment.

Updated comment above the declaration of TypeMatcher::m_match_type that 
referred to the old m_is_regex boolean, to address review feedback


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

https://reviews.llvm.org/D133240

Files:
  lldb/bindings/interface/SBTypeNameSpecifier.i
  lldb/include/lldb/API/SBTypeNameSpecifier.h
  lldb/include/lldb/DataFormatters/FormatClasses.h
  lldb/include/lldb/DataFormatters/FormattersContainer.h
  lldb/include/lldb/lldb-enumerations.h
  lldb/source/API/SBTypeNameSpecifier.cpp
  lldb/source/Core/FormatEntity.cpp

Index: lldb/source/Core/FormatEntity.cpp
===
--- lldb/source/Core/FormatEntity.cpp
+++ lldb/source/Core/FormatEntity.cpp
@@ -825,7 +825,7 @@
 bitfield_name.Printf("%s:%d", target->GetTypeName().AsCString(),
  target->GetBitfieldBitSize());
 auto type_sp = std::make_shared(
-bitfield_name.GetString(), false);
+bitfield_name.GetString(), lldb::eFormatterMatchExact);
 if (val_obj_display ==
 ValueObject::eValueObjectRepresentationStyleSummary &&
 !DataVisualization::GetSummaryForType(type_sp))
Index: lldb/source/API/SBTypeNameSpecifier.cpp
===
--- lldb/source/API/SBTypeNameSpecifier.cpp
+++ lldb/source/API/SBTypeNameSpecifier.cpp
@@ -20,8 +20,15 @@
 SBTypeNameSpecifier::SBTypeNameSpecifier() { LLDB_INSTRUMENT_VA(this); }
 
 SBTypeNameSpecifier::SBTypeNameSpecifier(const char *name, bool is_regex)
-: m_opaque_sp(new TypeNameSpecifierImpl(name, is_regex)) {
+: SBTypeNameSpecifier(name, is_regex ? eFormatterMatchRegex
+ : eFormatterMatchExact) {
   LLDB_INSTRUMENT_VA(this, name, is_regex);
+}
+
+SBTypeNameSpecifier::SBTypeNameSpecifier(const char *name,
+ FormatterMatchType match_type)
+: m_opaque_sp(new TypeNameSpecifierImpl(name, match_type)) {
+  LLDB_INSTRUMENT_VA(this, name, match_type);
 
   if (name == nullptr || (*name) == 0)
 m_opaque_sp.reset();
@@ -72,13 +79,20 @@
   return SBType();
 }
 
+FormatterMatchType SBTypeNameSpecifier::GetMatchType() {
+  LLDB_INSTRUMENT_VA(this);
+  if (!IsValid())
+return eFormatterMatchExact;
+  return m_opaque_sp->GetMatchType();
+}
+
 bool SBTypeNameSpecifier::IsRegex() {
   LLDB_INSTRUMENT_VA(this);
 
   if (!IsValid())
 return false;
 
-  return m_opaque_sp->IsRegex();
+  return m_opaque_sp->GetMatchType() == eFormatterMatchRegex;
 }
 
 bool SBTypeNameSpecifier::GetDescription(
@@ -116,7 +130,7 @@
   if (!IsValid())
 return !rhs.IsValid();
 
-  if (IsRegex() != rhs.IsRegex())
+  if (GetMatchType() != rhs.GetMatchType())
 return false;
   if (GetName() == nullptr || rhs.GetName() == nullptr)
 return false;
Index: lldb/include/lldb/lldb-enumerations.h
===
--- lldb/include/lldb/lldb-enumerations.h
+++ lldb/include/lldb/lldb-enumerations.h
@@ -832,6 +832,15 @@
   eTemplateArgumentKindNullPtr,
 };
 
+/// Type of match to be performed when looking for a formatter for a data type.
+/// Used by classes like SBTypeNameSpecifier or lldb_private::TypeMatcher.
+enum FormatterMatchType {
+  eFormatterMatchExact,
+  eFormatterMatchRegex,
+
+  kNumFormatterMatchTypes,
+};
+
 /// Options that can be set for a formatter to alter its behavior. Not
 /// all of these are applicable to all formatter types.
 FLAGS_ENUM(TypeOptions){eTypeOptionNone = (0u),
Index: lldb/include/lldb/DataFormatters/FormattersContainer.h
===
--- lldb/include/lldb/DataFormatters/FormattersContainer.h
+++ lldb/include/lldb/DataFormatters/FormattersContainer.h
@@ -41,9 +41,11 @@
 class TypeMatcher {
   RegularExpression m_type_name_regex;
   ConstString m_type_name;
-  /// False if m_type_name_regex should be used for matching. False if this is
-  /// just matching by comparing with m_type_name string.
-  bool m_is_regex;
+  /// Indicates what kind of matching strategy should be used:
+  /// - eFormatterMatchExact: match the exact type name in m_name.
+  /// - eFormatterMatchRegex: match using the RegularExpression object
+  ///   `m_type_name_regex` instead.
+  lldb::FormatterMatchType m_match_type;
 
   // if the user tries to add formatters for, say, "struct Foo" those will not
   // match any type because of the way we strip qualifiers from typenames this
@@ -71,22 +73,25 @@
   TypeMatcher() = delete;
   /// Creates a matcher that accepts any type with exactly the given type name.
   TypeMatcher(ConstString type_name)
-  : m_type_name(type_name), m_is_regex(false) {}
+  : m_type_name(type_name), m_match_type(lldb::eFormatterMatchExact) {}
   /// Creates a matcher that accepts any type matching the given regex.
   TypeMatcher(RegularExpres

[Lldb-commits] [PATCH] D133240: [Formatters][NFCI] Replace 'is_regex' arguments with an enum.

2022-09-12 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe marked an inline comment as done.
jgorbe added inline comments.



Comment at: lldb/include/lldb/DataFormatters/FormattersContainer.h:46
   /// just matching by comparing with m_type_name string.
-  bool m_is_regex;
+  lldb::FormatterMatchType m_match_type;
 

hawkinsw wrote:
> I am really intrigued by this entire patchset and just wanted to drop by to 
> help, if I could. I hope that I am not upsetting you by commenting on 
> something so trivial, but it seems like we would want to change the comment 
> for this data member while we are at it?
> 
> Again, I think this work is great and I hope I am helping!
Good catch! I have updated the comment. Thanks for pointing it out :)


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

https://reviews.llvm.org/D133240

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


[Lldb-commits] [PATCH] D133240: [Formatters][NFCI] Replace 'is_regex' arguments with an enum.

2022-09-12 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe updated this revision to Diff 459618.
jgorbe added a comment.

Fixed mis-spelled member name in comment.


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

https://reviews.llvm.org/D133240

Files:
  lldb/bindings/interface/SBTypeNameSpecifier.i
  lldb/include/lldb/API/SBTypeNameSpecifier.h
  lldb/include/lldb/DataFormatters/FormatClasses.h
  lldb/include/lldb/DataFormatters/FormattersContainer.h
  lldb/include/lldb/lldb-enumerations.h
  lldb/source/API/SBTypeNameSpecifier.cpp
  lldb/source/Core/FormatEntity.cpp

Index: lldb/source/Core/FormatEntity.cpp
===
--- lldb/source/Core/FormatEntity.cpp
+++ lldb/source/Core/FormatEntity.cpp
@@ -825,7 +825,7 @@
 bitfield_name.Printf("%s:%d", target->GetTypeName().AsCString(),
  target->GetBitfieldBitSize());
 auto type_sp = std::make_shared(
-bitfield_name.GetString(), false);
+bitfield_name.GetString(), lldb::eFormatterMatchExact);
 if (val_obj_display ==
 ValueObject::eValueObjectRepresentationStyleSummary &&
 !DataVisualization::GetSummaryForType(type_sp))
Index: lldb/source/API/SBTypeNameSpecifier.cpp
===
--- lldb/source/API/SBTypeNameSpecifier.cpp
+++ lldb/source/API/SBTypeNameSpecifier.cpp
@@ -20,8 +20,15 @@
 SBTypeNameSpecifier::SBTypeNameSpecifier() { LLDB_INSTRUMENT_VA(this); }
 
 SBTypeNameSpecifier::SBTypeNameSpecifier(const char *name, bool is_regex)
-: m_opaque_sp(new TypeNameSpecifierImpl(name, is_regex)) {
+: SBTypeNameSpecifier(name, is_regex ? eFormatterMatchRegex
+ : eFormatterMatchExact) {
   LLDB_INSTRUMENT_VA(this, name, is_regex);
+}
+
+SBTypeNameSpecifier::SBTypeNameSpecifier(const char *name,
+ FormatterMatchType match_type)
+: m_opaque_sp(new TypeNameSpecifierImpl(name, match_type)) {
+  LLDB_INSTRUMENT_VA(this, name, match_type);
 
   if (name == nullptr || (*name) == 0)
 m_opaque_sp.reset();
@@ -72,13 +79,20 @@
   return SBType();
 }
 
+FormatterMatchType SBTypeNameSpecifier::GetMatchType() {
+  LLDB_INSTRUMENT_VA(this);
+  if (!IsValid())
+return eFormatterMatchExact;
+  return m_opaque_sp->GetMatchType();
+}
+
 bool SBTypeNameSpecifier::IsRegex() {
   LLDB_INSTRUMENT_VA(this);
 
   if (!IsValid())
 return false;
 
-  return m_opaque_sp->IsRegex();
+  return m_opaque_sp->GetMatchType() == eFormatterMatchRegex;
 }
 
 bool SBTypeNameSpecifier::GetDescription(
@@ -116,7 +130,7 @@
   if (!IsValid())
 return !rhs.IsValid();
 
-  if (IsRegex() != rhs.IsRegex())
+  if (GetMatchType() != rhs.GetMatchType())
 return false;
   if (GetName() == nullptr || rhs.GetName() == nullptr)
 return false;
Index: lldb/include/lldb/lldb-enumerations.h
===
--- lldb/include/lldb/lldb-enumerations.h
+++ lldb/include/lldb/lldb-enumerations.h
@@ -832,6 +832,15 @@
   eTemplateArgumentKindNullPtr,
 };
 
+/// Type of match to be performed when looking for a formatter for a data type.
+/// Used by classes like SBTypeNameSpecifier or lldb_private::TypeMatcher.
+enum FormatterMatchType {
+  eFormatterMatchExact,
+  eFormatterMatchRegex,
+
+  kNumFormatterMatchTypes,
+};
+
 /// Options that can be set for a formatter to alter its behavior. Not
 /// all of these are applicable to all formatter types.
 FLAGS_ENUM(TypeOptions){eTypeOptionNone = (0u),
Index: lldb/include/lldb/DataFormatters/FormattersContainer.h
===
--- lldb/include/lldb/DataFormatters/FormattersContainer.h
+++ lldb/include/lldb/DataFormatters/FormattersContainer.h
@@ -41,9 +41,11 @@
 class TypeMatcher {
   RegularExpression m_type_name_regex;
   ConstString m_type_name;
-  /// False if m_type_name_regex should be used for matching. False if this is
-  /// just matching by comparing with m_type_name string.
-  bool m_is_regex;
+  /// Indicates what kind of matching strategy should be used:
+  /// - eFormatterMatchExact: match the exact type name in m_type_name.
+  /// - eFormatterMatchRegex: match using the RegularExpression object
+  ///   `m_type_name_regex` instead.
+  lldb::FormatterMatchType m_match_type;
 
   // if the user tries to add formatters for, say, "struct Foo" those will not
   // match any type because of the way we strip qualifiers from typenames this
@@ -71,22 +73,25 @@
   TypeMatcher() = delete;
   /// Creates a matcher that accepts any type with exactly the given type name.
   TypeMatcher(ConstString type_name)
-  : m_type_name(type_name), m_is_regex(false) {}
+  : m_type_name(type_name), m_match_type(lldb::eFormatterMatchExact) {}
   /// Creates a matcher that accepts any type matching the given regex.
   TypeMatcher(RegularExpression regex)
-  : m_type_name_regex(std::move(regex)), m_is_regex(true) {}
+  : m_type

[Lldb-commits] [PATCH] D133240: [Formatters][NFCI] Replace 'is_regex' arguments with an enum.

2022-09-13 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe added inline comments.



Comment at: lldb/include/lldb/lldb-enumerations.h:841
+
+  kNumFormatterMatchTypes,
+};

labath wrote:
> I see the enums in this file use wildly inconsistent styles for the "largest 
> value" enumerator. However, you've picked the one I like the least, because 
> this tends to produce `unhandled switch case "kNumFormatterMatchTypes"` 
> warnings. If you feel like you need to have a sentinel, I'd recommend going 
> with the `eLastFormatterMatchType = ` pattern (used e.g. in 
> the StateType enum).
I //do// want a sentinel because the plan is to replace some hardcoded 
instances of "check for an exact match and if nothing is found then check for a 
regex match" with a class that has an array of size `kNumFormatterMatchTypes` 
formatter containers, and knows how to do a lookup in priority order. So then I 
can add another "priority tier" for callback matchers and not add extra logic 
in a bunch of places.

But I have no strong preference between having a `std::array` and a `std::array`, and I agree the `unhandled switch case` warnings are annoying. I'll 
change it shortly.


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

https://reviews.llvm.org/D133240

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


[Lldb-commits] [PATCH] D133240: [Formatters][NFCI] Replace 'is_regex' arguments with an enum.

2022-09-13 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe updated this revision to Diff 459845.
jgorbe added a comment.

Replaced `kNumFormatterMatchTypes` with `eLastFormatterMatchType` to avoid 
"unhandled enum value" warnings, as suggested by Pavel.


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

https://reviews.llvm.org/D133240

Files:
  lldb/bindings/interface/SBTypeNameSpecifier.i
  lldb/include/lldb/API/SBTypeNameSpecifier.h
  lldb/include/lldb/DataFormatters/FormatClasses.h
  lldb/include/lldb/DataFormatters/FormattersContainer.h
  lldb/include/lldb/lldb-enumerations.h
  lldb/source/API/SBTypeNameSpecifier.cpp
  lldb/source/Core/FormatEntity.cpp

Index: lldb/source/Core/FormatEntity.cpp
===
--- lldb/source/Core/FormatEntity.cpp
+++ lldb/source/Core/FormatEntity.cpp
@@ -825,7 +825,7 @@
 bitfield_name.Printf("%s:%d", target->GetTypeName().AsCString(),
  target->GetBitfieldBitSize());
 auto type_sp = std::make_shared(
-bitfield_name.GetString(), false);
+bitfield_name.GetString(), lldb::eFormatterMatchExact);
 if (val_obj_display ==
 ValueObject::eValueObjectRepresentationStyleSummary &&
 !DataVisualization::GetSummaryForType(type_sp))
Index: lldb/source/API/SBTypeNameSpecifier.cpp
===
--- lldb/source/API/SBTypeNameSpecifier.cpp
+++ lldb/source/API/SBTypeNameSpecifier.cpp
@@ -20,8 +20,15 @@
 SBTypeNameSpecifier::SBTypeNameSpecifier() { LLDB_INSTRUMENT_VA(this); }
 
 SBTypeNameSpecifier::SBTypeNameSpecifier(const char *name, bool is_regex)
-: m_opaque_sp(new TypeNameSpecifierImpl(name, is_regex)) {
+: SBTypeNameSpecifier(name, is_regex ? eFormatterMatchRegex
+ : eFormatterMatchExact) {
   LLDB_INSTRUMENT_VA(this, name, is_regex);
+}
+
+SBTypeNameSpecifier::SBTypeNameSpecifier(const char *name,
+ FormatterMatchType match_type)
+: m_opaque_sp(new TypeNameSpecifierImpl(name, match_type)) {
+  LLDB_INSTRUMENT_VA(this, name, match_type);
 
   if (name == nullptr || (*name) == 0)
 m_opaque_sp.reset();
@@ -72,13 +79,20 @@
   return SBType();
 }
 
+FormatterMatchType SBTypeNameSpecifier::GetMatchType() {
+  LLDB_INSTRUMENT_VA(this);
+  if (!IsValid())
+return eFormatterMatchExact;
+  return m_opaque_sp->GetMatchType();
+}
+
 bool SBTypeNameSpecifier::IsRegex() {
   LLDB_INSTRUMENT_VA(this);
 
   if (!IsValid())
 return false;
 
-  return m_opaque_sp->IsRegex();
+  return m_opaque_sp->GetMatchType() == eFormatterMatchRegex;
 }
 
 bool SBTypeNameSpecifier::GetDescription(
@@ -116,7 +130,7 @@
   if (!IsValid())
 return !rhs.IsValid();
 
-  if (IsRegex() != rhs.IsRegex())
+  if (GetMatchType() != rhs.GetMatchType())
 return false;
   if (GetName() == nullptr || rhs.GetName() == nullptr)
 return false;
Index: lldb/include/lldb/lldb-enumerations.h
===
--- lldb/include/lldb/lldb-enumerations.h
+++ lldb/include/lldb/lldb-enumerations.h
@@ -832,6 +832,15 @@
   eTemplateArgumentKindNullPtr,
 };
 
+/// Type of match to be performed when looking for a formatter for a data type.
+/// Used by classes like SBTypeNameSpecifier or lldb_private::TypeMatcher.
+enum FormatterMatchType {
+  eFormatterMatchExact,
+  eFormatterMatchRegex,
+
+  eLastFormatterMatchType = eFormatterMatchRegex,
+};
+
 /// Options that can be set for a formatter to alter its behavior. Not
 /// all of these are applicable to all formatter types.
 FLAGS_ENUM(TypeOptions){eTypeOptionNone = (0u),
Index: lldb/include/lldb/DataFormatters/FormattersContainer.h
===
--- lldb/include/lldb/DataFormatters/FormattersContainer.h
+++ lldb/include/lldb/DataFormatters/FormattersContainer.h
@@ -41,9 +41,11 @@
 class TypeMatcher {
   RegularExpression m_type_name_regex;
   ConstString m_type_name;
-  /// False if m_type_name_regex should be used for matching. False if this is
-  /// just matching by comparing with m_type_name string.
-  bool m_is_regex;
+  /// Indicates what kind of matching strategy should be used:
+  /// - eFormatterMatchExact: match the exact type name in m_type_name.
+  /// - eFormatterMatchRegex: match using the RegularExpression object
+  ///   `m_type_name_regex` instead.
+  lldb::FormatterMatchType m_match_type;
 
   // if the user tries to add formatters for, say, "struct Foo" those will not
   // match any type because of the way we strip qualifiers from typenames this
@@ -71,22 +73,25 @@
   TypeMatcher() = delete;
   /// Creates a matcher that accepts any type with exactly the given type name.
   TypeMatcher(ConstString type_name)
-  : m_type_name(type_name), m_is_regex(false) {}
+  : m_type_name(type_name), m_match_type(lldb::eFormatterMatchExact) {}
   /// Creates a matcher that accepts any type matching the given regex.
   TypeM

[Lldb-commits] [PATCH] D133240: [Formatters][NFCI] Replace 'is_regex' arguments with an enum.

2022-09-13 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGef3fa232b338: [Formatters][NFCI] Replace 
'is_regex' arguments with an enum. (authored by jgorbe).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133240

Files:
  lldb/bindings/interface/SBTypeNameSpecifier.i
  lldb/include/lldb/API/SBTypeNameSpecifier.h
  lldb/include/lldb/DataFormatters/FormatClasses.h
  lldb/include/lldb/DataFormatters/FormattersContainer.h
  lldb/include/lldb/lldb-enumerations.h
  lldb/source/API/SBTypeNameSpecifier.cpp
  lldb/source/Core/FormatEntity.cpp

Index: lldb/source/Core/FormatEntity.cpp
===
--- lldb/source/Core/FormatEntity.cpp
+++ lldb/source/Core/FormatEntity.cpp
@@ -825,7 +825,7 @@
 bitfield_name.Printf("%s:%d", target->GetTypeName().AsCString(),
  target->GetBitfieldBitSize());
 auto type_sp = std::make_shared(
-bitfield_name.GetString(), false);
+bitfield_name.GetString(), lldb::eFormatterMatchExact);
 if (val_obj_display ==
 ValueObject::eValueObjectRepresentationStyleSummary &&
 !DataVisualization::GetSummaryForType(type_sp))
Index: lldb/source/API/SBTypeNameSpecifier.cpp
===
--- lldb/source/API/SBTypeNameSpecifier.cpp
+++ lldb/source/API/SBTypeNameSpecifier.cpp
@@ -20,8 +20,15 @@
 SBTypeNameSpecifier::SBTypeNameSpecifier() { LLDB_INSTRUMENT_VA(this); }
 
 SBTypeNameSpecifier::SBTypeNameSpecifier(const char *name, bool is_regex)
-: m_opaque_sp(new TypeNameSpecifierImpl(name, is_regex)) {
+: SBTypeNameSpecifier(name, is_regex ? eFormatterMatchRegex
+ : eFormatterMatchExact) {
   LLDB_INSTRUMENT_VA(this, name, is_regex);
+}
+
+SBTypeNameSpecifier::SBTypeNameSpecifier(const char *name,
+ FormatterMatchType match_type)
+: m_opaque_sp(new TypeNameSpecifierImpl(name, match_type)) {
+  LLDB_INSTRUMENT_VA(this, name, match_type);
 
   if (name == nullptr || (*name) == 0)
 m_opaque_sp.reset();
@@ -72,13 +79,20 @@
   return SBType();
 }
 
+FormatterMatchType SBTypeNameSpecifier::GetMatchType() {
+  LLDB_INSTRUMENT_VA(this);
+  if (!IsValid())
+return eFormatterMatchExact;
+  return m_opaque_sp->GetMatchType();
+}
+
 bool SBTypeNameSpecifier::IsRegex() {
   LLDB_INSTRUMENT_VA(this);
 
   if (!IsValid())
 return false;
 
-  return m_opaque_sp->IsRegex();
+  return m_opaque_sp->GetMatchType() == eFormatterMatchRegex;
 }
 
 bool SBTypeNameSpecifier::GetDescription(
@@ -116,7 +130,7 @@
   if (!IsValid())
 return !rhs.IsValid();
 
-  if (IsRegex() != rhs.IsRegex())
+  if (GetMatchType() != rhs.GetMatchType())
 return false;
   if (GetName() == nullptr || rhs.GetName() == nullptr)
 return false;
Index: lldb/include/lldb/lldb-enumerations.h
===
--- lldb/include/lldb/lldb-enumerations.h
+++ lldb/include/lldb/lldb-enumerations.h
@@ -832,6 +832,15 @@
   eTemplateArgumentKindNullPtr,
 };
 
+/// Type of match to be performed when looking for a formatter for a data type.
+/// Used by classes like SBTypeNameSpecifier or lldb_private::TypeMatcher.
+enum FormatterMatchType {
+  eFormatterMatchExact,
+  eFormatterMatchRegex,
+
+  eLastFormatterMatchType = eFormatterMatchRegex,
+};
+
 /// Options that can be set for a formatter to alter its behavior. Not
 /// all of these are applicable to all formatter types.
 FLAGS_ENUM(TypeOptions){eTypeOptionNone = (0u),
Index: lldb/include/lldb/DataFormatters/FormattersContainer.h
===
--- lldb/include/lldb/DataFormatters/FormattersContainer.h
+++ lldb/include/lldb/DataFormatters/FormattersContainer.h
@@ -41,9 +41,11 @@
 class TypeMatcher {
   RegularExpression m_type_name_regex;
   ConstString m_type_name;
-  /// False if m_type_name_regex should be used for matching. False if this is
-  /// just matching by comparing with m_type_name string.
-  bool m_is_regex;
+  /// Indicates what kind of matching strategy should be used:
+  /// - eFormatterMatchExact: match the exact type name in m_type_name.
+  /// - eFormatterMatchRegex: match using the RegularExpression object
+  ///   `m_type_name_regex` instead.
+  lldb::FormatterMatchType m_match_type;
 
   // if the user tries to add formatters for, say, "struct Foo" those will not
   // match any type because of the way we strip qualifiers from typenames this
@@ -71,22 +73,25 @@
   TypeMatcher() = delete;
   /// Creates a matcher that accepts any type with exactly the given type name.
   TypeMatcher(ConstString type_name)
-  : m_type_name(type_name), m_is_regex(false) {}
+  : m_type_name(type_name), m_match_type(lldb::eFormatterMatchExact) 

[Lldb-commits] [PATCH] D133910: [NFCI] Refactor FormatterContainerPair into TieredFormatterContainer.

2022-09-14 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe created this revision.
jgorbe added reviewers: labath, jingham.
jgorbe added a project: LLDB.
Herald added a subscriber: JDevlieghere.
Herald added a project: All.
jgorbe requested review of this revision.

`FormatterContainerPair` is (as its name indicates) a very thin wrapper
over two formatter containers, one for exact matches and another one for
regex matches. The logic to decide which subcontainer to access is
replicated everywhere `FormatterContainerPair`s are used.

So, for example, when we look for a formatter there's some adhoc code
that does a lookup in the exact match formatter container, and if it
fails it does a lookup in the regex match formatter container. The same
logic is then copied and pasted for summaries, filters, and synthetic
child providers.

This change introduces a new `TieredFormatterContainer` that has two
main characteristics:

- It generalizes `FormatterContainerPair` from 2 to any number of 
subcontainers, that are looked up in priority order.
- It centralizes all the logic to choose which subcontainer to use for lookups, 
add/delete, and indexing.

This allows us to have a single copy of the same logic, templatized for
each kind of formatter. It also simplifies the upcoming addition of a
new tier of callback-based matches. See
https://discourse.llvm.org/t/rfc-python-callback-for-data-formatters-type-matching/64204
for more details about this.

The rest of the change is mostly replacing copy-pasted code with calls
to methods of the relevant `TieredFormatterContainer`, and adding some
methods to the `TypeCategoryImpl` class so we can remove some of this
copy-pasted code from `SBTypeCategory`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D133910

Files:
  lldb/include/lldb/DataFormatters/FormattersContainer.h
  lldb/include/lldb/DataFormatters/TypeCategory.h
  lldb/source/API/SBTypeCategory.cpp
  lldb/source/DataFormatters/TypeCategory.cpp

Index: lldb/source/DataFormatters/TypeCategory.cpp
===
--- lldb/source/DataFormatters/TypeCategory.cpp
+++ lldb/source/DataFormatters/TypeCategory.cpp
@@ -87,10 +87,7 @@
lldb::TypeFormatImplSP &entry) {
   if (!IsEnabled() || !IsApplicable(lang))
 return false;
-  if (GetTypeFormatsContainer()->Get(candidates, entry))
-return true;
-  bool regex = GetRegexTypeFormatsContainer()->Get(candidates, entry);
-  return regex;
+  return m_format_cont.Get(candidates, entry);
 }
 
 bool TypeCategoryImpl::Get(lldb::LanguageType lang,
@@ -98,10 +95,7 @@
lldb::TypeSummaryImplSP &entry) {
   if (!IsEnabled() || !IsApplicable(lang))
 return false;
-  if (GetTypeSummariesContainer()->Get(candidates, entry))
-return true;
-  bool regex = GetRegexTypeSummariesContainer()->Get(candidates, entry);
-  return regex;
+  return m_summary_cont.Get(candidates, entry);
 }
 
 bool TypeCategoryImpl::Get(lldb::LanguageType lang,
@@ -109,30 +103,29 @@
lldb::SyntheticChildrenSP &entry) {
   if (!IsEnabled() || !IsApplicable(lang))
 return false;
-  TypeFilterImpl::SharedPointer filter_sp;
+
   // first find both Filter and Synth, and then check which is most recent
+  bool pick_synth = false;
 
-  if (!GetTypeFiltersContainer()->Get(candidates, filter_sp))
-GetRegexTypeFiltersContainer()->Get(candidates, filter_sp);
+  TypeFilterImpl::SharedPointer filter_sp;
+  m_filter_cont.Get(candidates, filter_sp);
 
-  bool pick_synth = false;
-  ScriptedSyntheticChildren::SharedPointer synth;
-  if (!GetTypeSyntheticsContainer()->Get(candidates, synth))
-GetRegexTypeSyntheticsContainer()->Get(candidates, synth);
-  if (!filter_sp.get() && !synth.get())
+  ScriptedSyntheticChildren::SharedPointer synth_sp;
+  m_synth_cont.Get(candidates, synth_sp);
+
+  if (!filter_sp.get() && !synth_sp.get())
 return false;
-  else if (!filter_sp.get() && synth.get())
+  else if (!filter_sp.get() && synth_sp.get())
 pick_synth = true;
-
-  else if (filter_sp.get() && !synth.get())
+  else if (filter_sp.get() && !synth_sp.get())
 pick_synth = false;
-
-  else /*if (filter_sp.get() && synth.get())*/
+  else /*if (filter_sp.get() && synth_sp.get())*/
   {
-pick_synth = filter_sp->GetRevision() <= synth->GetRevision();
+pick_synth = filter_sp->GetRevision() <= synth_sp->GetRevision();
   }
+
   if (pick_synth) {
-entry = synth;
+entry = synth_sp;
 return true;
   } else {
 entry = filter_sp;
@@ -318,138 +311,62 @@
 
 TypeCategoryImpl::FormatContainer::MapValueType
 TypeCategoryImpl::GetFormatForType(lldb::TypeNameSpecifierImplSP type_sp) {
-  FormatContainer::MapValueType retval;
-
-  if (type_sp) {
-if (type_sp->IsRegex())
-  GetRegexTypeFormatsContainer()->GetExact(ConstString(type_sp->GetName()),
-   retval);
-else
-  GetTypeFormatsContainer()->GetExact(ConstString(type_sp->GetName()),
-   

[Lldb-commits] [PATCH] D134244: [NFCI] Clean up enum FormatCategoryItem.

2022-09-19 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe created this revision.
jgorbe added reviewers: labath, rupprecht, jingham.
jgorbe added a project: LLDB.
Herald added a subscriber: JDevlieghere.
Herald added a project: All.
jgorbe requested review of this revision.



- Merge pairs like `eFormatCategoryItemSummary` and 
`eFormatCategoryItemRegexSummary` into a single value. See explanation below.

- Rename `eFormatCategoryItemValue` to `eFormatCategoryItemFormat`. This makes 
the enum match the names used elsewhere for formatter kinds (format, summary, 
filter, synth).

- Delete unused values `eFormatCategoryItemValidator` and 
`eFormatCategoryItemRegexValidator`.

This enum is only used to reuse some code in CommandObjectType.cpp.  For
example, instead of having separate implementations for `type summary
delete`, `type format delete`, and so on, there's a single generic
implementation that takes an enum value, and then the specific commands
derive from it and set the right flags for the specific kind of
formatter.

Even though the enum distinguishes between regular and regex matches for
every kind of formatter, this distinction is never used: enum values are
always specified in pairs like
`eFormatCategoryItemSummary | eFormatCategoryItemRegexSummary`.

This causes some ugly code duplication in TypeCategory.cpp. In order to
handle every flag combination some code appears 8 times:

{format, summary, synth, filter} x {exact, regex}


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D134244

Files:
  lldb/include/lldb/lldb-private-enumerations.h
  lldb/source/Commands/CommandObjectType.cpp
  lldb/source/DataFormatters/DataVisualization.cpp
  lldb/source/DataFormatters/TypeCategory.cpp

Index: lldb/source/DataFormatters/TypeCategory.cpp
===
--- lldb/source/DataFormatters/TypeCategory.cpp
+++ lldb/source/DataFormatters/TypeCategory.cpp
@@ -142,53 +142,49 @@
 }
 
 void TypeCategoryImpl::Clear(FormatCategoryItems items) {
-  if ((items & eFormatCategoryItemValue) == eFormatCategoryItemValue)
+  if (items & eFormatCategoryItemFormat) {
 GetTypeFormatsContainer()->Clear();
-  if ((items & eFormatCategoryItemRegexValue) == eFormatCategoryItemRegexValue)
 GetRegexTypeFormatsContainer()->Clear();
+  }
 
-  if ((items & eFormatCategoryItemSummary) == eFormatCategoryItemSummary)
+  if (items & eFormatCategoryItemSummary) {
 GetTypeSummariesContainer()->Clear();
-  if ((items & eFormatCategoryItemRegexSummary) ==
-  eFormatCategoryItemRegexSummary)
 GetRegexTypeSummariesContainer()->Clear();
+  }
 
-  if ((items & eFormatCategoryItemFilter) == eFormatCategoryItemFilter)
+  if (items & eFormatCategoryItemFilter) {
 GetTypeFiltersContainer()->Clear();
-  if ((items & eFormatCategoryItemRegexFilter) ==
-  eFormatCategoryItemRegexFilter)
 GetRegexTypeFiltersContainer()->Clear();
+  }
 
-  if ((items & eFormatCategoryItemSynth) == eFormatCategoryItemSynth)
+  if (items & eFormatCategoryItemSynth) {
 GetTypeSyntheticsContainer()->Clear();
-  if ((items & eFormatCategoryItemRegexSynth) == eFormatCategoryItemRegexSynth)
 GetRegexTypeSyntheticsContainer()->Clear();
+  }
 }
 
 bool TypeCategoryImpl::Delete(ConstString name, FormatCategoryItems items) {
   bool success = false;
 
-  if ((items & eFormatCategoryItemValue) == eFormatCategoryItemValue)
+  if (items & eFormatCategoryItemFormat) {
 success = GetTypeFormatsContainer()->Delete(name) || success;
-  if ((items & eFormatCategoryItemRegexValue) == eFormatCategoryItemRegexValue)
 success = GetRegexTypeFormatsContainer()->Delete(name) || success;
+  }
 
-  if ((items & eFormatCategoryItemSummary) == eFormatCategoryItemSummary)
+  if (items & eFormatCategoryItemSummary) {
 success = GetTypeSummariesContainer()->Delete(name) || success;
-  if ((items & eFormatCategoryItemRegexSummary) ==
-  eFormatCategoryItemRegexSummary)
 success = GetRegexTypeSummariesContainer()->Delete(name) || success;
+  }
 
-  if ((items & eFormatCategoryItemFilter) == eFormatCategoryItemFilter)
+  if (items & eFormatCategoryItemFilter) {
 success = GetTypeFiltersContainer()->Delete(name) || success;
-  if ((items & eFormatCategoryItemRegexFilter) ==
-  eFormatCategoryItemRegexFilter)
 success = GetRegexTypeFiltersContainer()->Delete(name) || success;
+  }
 
-  if ((items & eFormatCategoryItemSynth) == eFormatCategoryItemSynth)
+  if (items & eFormatCategoryItemSynth) {
 success = GetTypeSyntheticsContainer()->Delete(name) || success;
-  if ((items & eFormatCategoryItemRegexSynth) == eFormatCategoryItemRegexSynth)
 success = GetRegexTypeSyntheticsContainer()->Delete(name) || success;
+  }
 
   return success;
 }
@@ -196,27 +192,25 @@
 uint32_t TypeCategoryImpl::GetCount(FormatCategoryItems items) {
   uint32_t count = 0;
 
-  if ((items & eFormatCategoryItemValue) == eFormatCategoryItemValue)
+  if (items & eFormatCategoryItemFormat) {
 count += GetTypeFormatsContainer()->GetCount();
- 

[Lldb-commits] [PATCH] D134244: [NFCI] Clean up enum FormatCategoryItem.

2022-09-20 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGdce688733600: [NFCI] Clean up enum FormatCategoryItem. 
(authored by jgorbe).

Changed prior to commit:
  https://reviews.llvm.org/D134244?vs=461418&id=461613#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134244

Files:
  lldb/include/lldb/lldb-private-enumerations.h
  lldb/source/Commands/CommandObjectType.cpp
  lldb/source/DataFormatters/DataVisualization.cpp
  lldb/source/DataFormatters/TypeCategory.cpp

Index: lldb/source/DataFormatters/TypeCategory.cpp
===
--- lldb/source/DataFormatters/TypeCategory.cpp
+++ lldb/source/DataFormatters/TypeCategory.cpp
@@ -142,53 +142,49 @@
 }
 
 void TypeCategoryImpl::Clear(FormatCategoryItems items) {
-  if ((items & eFormatCategoryItemValue) == eFormatCategoryItemValue)
+  if (items & eFormatCategoryItemFormat) {
 GetTypeFormatsContainer()->Clear();
-  if ((items & eFormatCategoryItemRegexValue) == eFormatCategoryItemRegexValue)
 GetRegexTypeFormatsContainer()->Clear();
+  }
 
-  if ((items & eFormatCategoryItemSummary) == eFormatCategoryItemSummary)
+  if (items & eFormatCategoryItemSummary) {
 GetTypeSummariesContainer()->Clear();
-  if ((items & eFormatCategoryItemRegexSummary) ==
-  eFormatCategoryItemRegexSummary)
 GetRegexTypeSummariesContainer()->Clear();
+  }
 
-  if ((items & eFormatCategoryItemFilter) == eFormatCategoryItemFilter)
+  if (items & eFormatCategoryItemFilter) {
 GetTypeFiltersContainer()->Clear();
-  if ((items & eFormatCategoryItemRegexFilter) ==
-  eFormatCategoryItemRegexFilter)
 GetRegexTypeFiltersContainer()->Clear();
+  }
 
-  if ((items & eFormatCategoryItemSynth) == eFormatCategoryItemSynth)
+  if (items & eFormatCategoryItemSynth) {
 GetTypeSyntheticsContainer()->Clear();
-  if ((items & eFormatCategoryItemRegexSynth) == eFormatCategoryItemRegexSynth)
 GetRegexTypeSyntheticsContainer()->Clear();
+  }
 }
 
 bool TypeCategoryImpl::Delete(ConstString name, FormatCategoryItems items) {
   bool success = false;
 
-  if ((items & eFormatCategoryItemValue) == eFormatCategoryItemValue)
+  if (items & eFormatCategoryItemFormat) {
 success = GetTypeFormatsContainer()->Delete(name) || success;
-  if ((items & eFormatCategoryItemRegexValue) == eFormatCategoryItemRegexValue)
 success = GetRegexTypeFormatsContainer()->Delete(name) || success;
+  }
 
-  if ((items & eFormatCategoryItemSummary) == eFormatCategoryItemSummary)
+  if (items & eFormatCategoryItemSummary) {
 success = GetTypeSummariesContainer()->Delete(name) || success;
-  if ((items & eFormatCategoryItemRegexSummary) ==
-  eFormatCategoryItemRegexSummary)
 success = GetRegexTypeSummariesContainer()->Delete(name) || success;
+  }
 
-  if ((items & eFormatCategoryItemFilter) == eFormatCategoryItemFilter)
+  if (items & eFormatCategoryItemFilter) {
 success = GetTypeFiltersContainer()->Delete(name) || success;
-  if ((items & eFormatCategoryItemRegexFilter) ==
-  eFormatCategoryItemRegexFilter)
 success = GetRegexTypeFiltersContainer()->Delete(name) || success;
+  }
 
-  if ((items & eFormatCategoryItemSynth) == eFormatCategoryItemSynth)
+  if (items & eFormatCategoryItemSynth) {
 success = GetTypeSyntheticsContainer()->Delete(name) || success;
-  if ((items & eFormatCategoryItemRegexSynth) == eFormatCategoryItemRegexSynth)
 success = GetRegexTypeSyntheticsContainer()->Delete(name) || success;
+  }
 
   return success;
 }
@@ -196,27 +192,25 @@
 uint32_t TypeCategoryImpl::GetCount(FormatCategoryItems items) {
   uint32_t count = 0;
 
-  if ((items & eFormatCategoryItemValue) == eFormatCategoryItemValue)
+  if (items & eFormatCategoryItemFormat) {
 count += GetTypeFormatsContainer()->GetCount();
-  if ((items & eFormatCategoryItemRegexValue) == eFormatCategoryItemRegexValue)
 count += GetRegexTypeFormatsContainer()->GetCount();
+  }
 
-  if ((items & eFormatCategoryItemSummary) == eFormatCategoryItemSummary)
+  if (items & eFormatCategoryItemSummary) {
 count += GetTypeSummariesContainer()->GetCount();
-  if ((items & eFormatCategoryItemRegexSummary) ==
-  eFormatCategoryItemRegexSummary)
 count += GetRegexTypeSummariesContainer()->GetCount();
+  }
 
-  if ((items & eFormatCategoryItemFilter) == eFormatCategoryItemFilter)
+  if (items & eFormatCategoryItemFilter) {
 count += GetTypeFiltersContainer()->GetCount();
-  if ((items & eFormatCategoryItemRegexFilter) ==
-  eFormatCategoryItemRegexFilter)
 count += GetRegexTypeFiltersContainer()->GetCount();
+  }
 
-  if ((items & eFormatCategoryItemSynth) == eFormatCategoryItemSynth)
+  if (items & eFormatCategoryItemSynth) {
 count += GetTypeSyntheticsContainer()->GetCount();
-  if ((items & eFormatCategoryItemRegexSynth) == eFormatCategoryItemRegexSynth)
 count += GetRegexTypeSynthetics

[Lldb-commits] [PATCH] D134244: [NFCI] Clean up enum FormatCategoryItem.

2022-09-20 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe marked an inline comment as done.
jgorbe added inline comments.



Comment at: lldb/include/lldb/lldb-private-enumerations.h:131-134
   eFormatCategoryItemSummary = 0x0001,
-  eFormatCategoryItemRegexSummary = 0x0002,
   eFormatCategoryItemFilter = 0x0004,
-  eFormatCategoryItemRegexFilter = 0x0008,
   eFormatCategoryItemSynth = 0x0010,
+  eFormatCategoryItemFormat = 0x0040,

JDevlieghere wrote:
> As these are private we don't have to skip values I think. Also let's use 
> left shift operators to make it more obvious that these are flags.
Done, thanks! :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134244

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


[Lldb-commits] [PATCH] D133910: [NFCI] Refactor FormatterContainerPair into TieredFormatterContainer.

2022-09-20 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe updated this revision to Diff 461775.
jgorbe added a comment.

Address review feedback:

- Removed asserts on `GetXXXAtIndex` methods when the index is out of range. 
Return a default-initialized shared_ptr of the right type instead (which will 
result in an invalid value when returned back to the SB API).
- Removed unnecessary braces to follow the style guide.


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

https://reviews.llvm.org/D133910

Files:
  lldb/include/lldb/DataFormatters/FormattersContainer.h
  lldb/include/lldb/DataFormatters/TypeCategory.h
  lldb/source/API/SBTypeCategory.cpp
  lldb/source/DataFormatters/TypeCategory.cpp

Index: lldb/source/DataFormatters/TypeCategory.cpp
===
--- lldb/source/DataFormatters/TypeCategory.cpp
+++ lldb/source/DataFormatters/TypeCategory.cpp
@@ -87,10 +87,7 @@
lldb::TypeFormatImplSP &entry) {
   if (!IsEnabled() || !IsApplicable(lang))
 return false;
-  if (GetTypeFormatsContainer()->Get(candidates, entry))
-return true;
-  bool regex = GetRegexTypeFormatsContainer()->Get(candidates, entry);
-  return regex;
+  return m_format_cont.Get(candidates, entry);
 }
 
 bool TypeCategoryImpl::Get(lldb::LanguageType lang,
@@ -98,10 +95,7 @@
lldb::TypeSummaryImplSP &entry) {
   if (!IsEnabled() || !IsApplicable(lang))
 return false;
-  if (GetTypeSummariesContainer()->Get(candidates, entry))
-return true;
-  bool regex = GetRegexTypeSummariesContainer()->Get(candidates, entry);
-  return regex;
+  return m_summary_cont.Get(candidates, entry);
 }
 
 bool TypeCategoryImpl::Get(lldb::LanguageType lang,
@@ -109,30 +103,29 @@
lldb::SyntheticChildrenSP &entry) {
   if (!IsEnabled() || !IsApplicable(lang))
 return false;
-  TypeFilterImpl::SharedPointer filter_sp;
+
   // first find both Filter and Synth, and then check which is most recent
+  bool pick_synth = false;
 
-  if (!GetTypeFiltersContainer()->Get(candidates, filter_sp))
-GetRegexTypeFiltersContainer()->Get(candidates, filter_sp);
+  TypeFilterImpl::SharedPointer filter_sp;
+  m_filter_cont.Get(candidates, filter_sp);
 
-  bool pick_synth = false;
-  ScriptedSyntheticChildren::SharedPointer synth;
-  if (!GetTypeSyntheticsContainer()->Get(candidates, synth))
-GetRegexTypeSyntheticsContainer()->Get(candidates, synth);
-  if (!filter_sp.get() && !synth.get())
+  ScriptedSyntheticChildren::SharedPointer synth_sp;
+  m_synth_cont.Get(candidates, synth_sp);
+
+  if (!filter_sp.get() && !synth_sp.get())
 return false;
-  else if (!filter_sp.get() && synth.get())
+  else if (!filter_sp.get() && synth_sp.get())
 pick_synth = true;
-
-  else if (filter_sp.get() && !synth.get())
+  else if (filter_sp.get() && !synth_sp.get())
 pick_synth = false;
-
-  else /*if (filter_sp.get() && synth.get())*/
+  else /*if (filter_sp.get() && synth_sp.get())*/
   {
-pick_synth = filter_sp->GetRevision() <= synth->GetRevision();
+pick_synth = filter_sp->GetRevision() <= synth_sp->GetRevision();
   }
+
   if (pick_synth) {
-entry = synth;
+entry = synth_sp;
 return true;
   } else {
 entry = filter_sp;
@@ -276,138 +269,62 @@
 
 TypeCategoryImpl::FormatContainer::MapValueType
 TypeCategoryImpl::GetFormatForType(lldb::TypeNameSpecifierImplSP type_sp) {
-  FormatContainer::MapValueType retval;
-
-  if (type_sp) {
-if (type_sp->IsRegex())
-  GetRegexTypeFormatsContainer()->GetExact(ConstString(type_sp->GetName()),
-   retval);
-else
-  GetTypeFormatsContainer()->GetExact(ConstString(type_sp->GetName()),
-  retval);
-  }
-
-  return retval;
+  return m_format_cont.GetForTypeNameSpecifier(type_sp);
 }
 
 TypeCategoryImpl::SummaryContainer::MapValueType
 TypeCategoryImpl::GetSummaryForType(lldb::TypeNameSpecifierImplSP type_sp) {
-  SummaryContainer::MapValueType retval;
-
-  if (type_sp) {
-if (type_sp->IsRegex())
-  GetRegexTypeSummariesContainer()->GetExact(
-  ConstString(type_sp->GetName()), retval);
-else
-  GetTypeSummariesContainer()->GetExact(ConstString(type_sp->GetName()),
-retval);
-  }
-
-  return retval;
+  return m_summary_cont.GetForTypeNameSpecifier(type_sp);
 }
 
 TypeCategoryImpl::FilterContainer::MapValueType
 TypeCategoryImpl::GetFilterForType(lldb::TypeNameSpecifierImplSP type_sp) {
-  FilterContainer::MapValueType retval;
-
-  if (type_sp) {
-if (type_sp->IsRegex())
-  GetRegexTypeFiltersContainer()->GetExact(ConstString(type_sp->GetName()),
-   retval);
-else
-  GetTypeFiltersContainer()->GetExact(ConstString(type_sp->GetName()),
-  retval);
-  }
-
-  return retval;
+  return m_filter_cont.GetForTypeNameSpecifier(type_sp);
 }
 
 Typ

[Lldb-commits] [PATCH] D133910: [NFCI] Refactor FormatterContainerPair into TieredFormatterContainer.

2022-09-20 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe marked 3 inline comments as done.
jgorbe added a comment.

Thanks for the review! Please take another look.




Comment at: lldb/include/lldb/DataFormatters/TypeCategory.h:76
+uint32_t result = 0;
+for (auto sc : m_subcontainers) {
+  result += sc->GetCount();

labath wrote:
> According to 
> 
>  this loop body should not use the `{}` braces.
Removed them (and also another similar set of braces in the constructor). 
Thanks!



Comment at: lldb/include/lldb/DataFormatters/TypeCategory.h:90
+}
+assert(false && "formatter index out of range");
+  }

labath wrote:
> Is this reachable from the SB API (perhaps via 
> `SBTypeCategory::GetXXXAtIndex`). If so, we'd want to do something different 
> here (return a default/empty value), or add a check somewhere in the SB layer.
Yes, it's reachable. Changed it to a default-initialized return value (which is 
a null shared_ptr).



Comment at: lldb/include/lldb/DataFormatters/TypeCategory.h:132
+}
+assert(false && "formatter index out of range");
   }

labath wrote:
> same question.
same answer :)


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

https://reviews.llvm.org/D133910

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


[Lldb-commits] [PATCH] D134570: [lldb] Skip check for conflicting filter/synth when adding a new regex.

2022-09-23 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe created this revision.
jgorbe added a project: LLDB.
Herald added a subscriber: JDevlieghere.
Herald added a project: All.
jgorbe requested review of this revision.

When adding a new synthetic child provider, we check for an existing
conflicting filter in the same category (and vice versa). This is done
by trying to match the new type name against registered formatters.

However, the new type name we're registered can also be a regex
(`type synth add -x`), and in this case the conflict check is just
wrong: it will try to match the new regex as if it was a type name,
against previously registered regexes.

See https://github.com/llvm/llvm-project/issues/57947 for a longer
explanation with concrete examples of incorrect behavior.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D134570

Files:
  lldb/source/Commands/CommandObjectType.cpp


Index: lldb/source/Commands/CommandObjectType.cpp
===
--- lldb/source/Commands/CommandObjectType.cpp
+++ lldb/source/Commands/CommandObjectType.cpp
@@ -2335,12 +2335,17 @@
   type = eRegexSynth;
   }
 
-  if (category->AnyMatches(type_name, eFormatCategoryItemFilter, false)) {
-if (error)
-  error->SetErrorStringWithFormat("cannot add synthetic for type %s when "
-  "filter is defined in same category!",
-  type_name.AsCString());
-return false;
+  // Only check for conflicting filters in the same category if `type_name` is
+  // an actual type name. Matching a regex string against registered regexes
+  // doesn't work.
+  if (type == eRegularSynth) {
+if (category->AnyMatches(type_name, eFormatCategoryItemFilter, false)) {
+  if (error)
+error->SetErrorStringWithFormat("cannot add synthetic for type %s when 
"
+"filter is defined in same category!",
+type_name.AsCString());
+  return false;
+}
   }
 
   if (type == eRegexSynth) {
@@ -2458,13 +2463,18 @@
 type = eRegexFilter;
 }
 
-if (category->AnyMatches(type_name, eFormatCategoryItemSynth, false)) {
-  if (error)
-error->SetErrorStringWithFormat("cannot add filter for type %s when "
-"synthetic is defined in same "
-"category!",
-type_name.AsCString());
-  return false;
+// Only check for conflicting synthetic child providers in the same 
category
+// if `type_name` is an actual type name. Matching a regex string against
+// registered regexes doesn't work.
+if (type == eRegularFilter) {
+  if (category->AnyMatches(type_name, eFormatCategoryItemSynth, false)) {
+if (error)
+  error->SetErrorStringWithFormat("cannot add filter for type %s when "
+  "synthetic is defined in same "
+  "category!",
+  type_name.AsCString());
+return false;
+  }
 }
 
 if (type == eRegexFilter) {


Index: lldb/source/Commands/CommandObjectType.cpp
===
--- lldb/source/Commands/CommandObjectType.cpp
+++ lldb/source/Commands/CommandObjectType.cpp
@@ -2335,12 +2335,17 @@
   type = eRegexSynth;
   }
 
-  if (category->AnyMatches(type_name, eFormatCategoryItemFilter, false)) {
-if (error)
-  error->SetErrorStringWithFormat("cannot add synthetic for type %s when "
-  "filter is defined in same category!",
-  type_name.AsCString());
-return false;
+  // Only check for conflicting filters in the same category if `type_name` is
+  // an actual type name. Matching a regex string against registered regexes
+  // doesn't work.
+  if (type == eRegularSynth) {
+if (category->AnyMatches(type_name, eFormatCategoryItemFilter, false)) {
+  if (error)
+error->SetErrorStringWithFormat("cannot add synthetic for type %s when "
+"filter is defined in same category!",
+type_name.AsCString());
+  return false;
+}
   }
 
   if (type == eRegexSynth) {
@@ -2458,13 +2463,18 @@
 type = eRegexFilter;
 }
 
-if (category->AnyMatches(type_name, eFormatCategoryItemSynth, false)) {
-  if (error)
-error->SetErrorStringWithFormat("cannot add filter for type %s when "
-"synthetic is defined in same "
-"category!",
-type_name.AsCString());
-  return false;
+// Only check for conflicting synthetic child providers in the same category
+// if `type_name` is an actual type name. Ma

[Lldb-commits] [PATCH] D134570: [lldb] Skip check for conflicting filter/synth when adding a new regex.

2022-09-23 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe updated this revision to Diff 462637.
jgorbe added a comment.

Added a couple of test cases to TestDataFormatterPythonSynth.py.


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

https://reviews.llvm.org/D134570

Files:
  lldb/source/Commands/CommandObjectType.cpp
  
lldb/test/API/functionalities/data-formatter/data-formatter-python-synth/TestDataFormatterPythonSynth.py


Index: 
lldb/test/API/functionalities/data-formatter/data-formatter-python-synth/TestDataFormatterPythonSynth.py
===
--- 
lldb/test/API/functionalities/data-formatter/data-formatter-python-synth/TestDataFormatterPythonSynth.py
+++ 
lldb/test/API/functionalities/data-formatter/data-formatter-python-synth/TestDataFormatterPythonSynth.py
@@ -257,6 +257,22 @@
 self.expect("frame variable f00_1", matching=False,
 substrs=['fake_a = '])
 
+# check that we don't feed a regex into another regex when checking for
+# existing conflicting synth/filters. The two following expressions
+# accept different types: one will accept types that look like an array
+# of MyType, the other will accept types that contain "MyType1" or
+# "MyType2". But the second regex looks like an array of MyType, so
+# lldb used to incorrectly reject it.
+self.runCmd(r'type synth add -l fooSynthProvider -x 
"^MyType\[[0-9]+]$"')
+self.runCmd(r'type filter add --child a -x "MyType[12]"')
+
+# Same, but adding the filter first to verify the check when doing
+# `type synth add`. We need to delete the synth from the previous test
+# first.
+self.runCmd(r'type synth delete "^MyType\[[0-9]+]$"')
+self.runCmd(r'type filter add --child a -x "^MyType\[[0-9]+]$"')
+self.runCmd(r'type synth add -l fooSynthProvider -x "MyType[12]"')
+
 def rdar10960550_formatter_commands(self):
 """Test that synthetic children persist stoppoints."""
 self.runCmd("file " + self.getBuildArtifact("a.out"), 
CURRENT_EXECUTABLE_SET)
Index: lldb/source/Commands/CommandObjectType.cpp
===
--- lldb/source/Commands/CommandObjectType.cpp
+++ lldb/source/Commands/CommandObjectType.cpp
@@ -2335,12 +2335,17 @@
   type = eRegexSynth;
   }
 
-  if (category->AnyMatches(type_name, eFormatCategoryItemFilter, false)) {
-if (error)
-  error->SetErrorStringWithFormat("cannot add synthetic for type %s when "
-  "filter is defined in same category!",
-  type_name.AsCString());
-return false;
+  // Only check for conflicting filters in the same category if `type_name` is
+  // an actual type name. Matching a regex string against registered regexes
+  // doesn't work.
+  if (type == eRegularSynth) {
+if (category->AnyMatches(type_name, eFormatCategoryItemFilter, false)) {
+  if (error)
+error->SetErrorStringWithFormat("cannot add synthetic for type %s when 
"
+"filter is defined in same category!",
+type_name.AsCString());
+  return false;
+}
   }
 
   if (type == eRegexSynth) {
@@ -2458,13 +2463,18 @@
 type = eRegexFilter;
 }
 
-if (category->AnyMatches(type_name, eFormatCategoryItemSynth, false)) {
-  if (error)
-error->SetErrorStringWithFormat("cannot add filter for type %s when "
-"synthetic is defined in same "
-"category!",
-type_name.AsCString());
-  return false;
+// Only check for conflicting synthetic child providers in the same 
category
+// if `type_name` is an actual type name. Matching a regex string against
+// registered regexes doesn't work.
+if (type == eRegularFilter) {
+  if (category->AnyMatches(type_name, eFormatCategoryItemSynth, false)) {
+if (error)
+  error->SetErrorStringWithFormat("cannot add filter for type %s when "
+  "synthetic is defined in same "
+  "category!",
+  type_name.AsCString());
+return false;
+  }
 }
 
 if (type == eRegexFilter) {


Index: lldb/test/API/functionalities/data-formatter/data-formatter-python-synth/TestDataFormatterPythonSynth.py
===
--- lldb/test/API/functionalities/data-formatter/data-formatter-python-synth/TestDataFormatterPythonSynth.py
+++ lldb/test/API/functionalities/data-formatter/data-formatter-python-synth/TestDataFormatterPythonSynth.py
@@ -257,6 +257,22 @@
 self.expect("frame variable f00_1", matching=False,
 substrs=['fake_a = '])
 
+# check tha

[Lldb-commits] [PATCH] D133910: [NFCI] Refactor FormatterContainerPair into TieredFormatterContainer.

2022-09-27 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
jgorbe marked 3 inline comments as done.
Closed by commit rG1f2a21820dfa: [NFCI] Refactor FormatterContainerPair into 
TieredFormatterContainer. (authored by jgorbe).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133910

Files:
  lldb/include/lldb/DataFormatters/FormattersContainer.h
  lldb/include/lldb/DataFormatters/TypeCategory.h
  lldb/source/API/SBTypeCategory.cpp
  lldb/source/DataFormatters/TypeCategory.cpp

Index: lldb/source/DataFormatters/TypeCategory.cpp
===
--- lldb/source/DataFormatters/TypeCategory.cpp
+++ lldb/source/DataFormatters/TypeCategory.cpp
@@ -87,10 +87,7 @@
lldb::TypeFormatImplSP &entry) {
   if (!IsEnabled() || !IsApplicable(lang))
 return false;
-  if (GetTypeFormatsContainer()->Get(candidates, entry))
-return true;
-  bool regex = GetRegexTypeFormatsContainer()->Get(candidates, entry);
-  return regex;
+  return m_format_cont.Get(candidates, entry);
 }
 
 bool TypeCategoryImpl::Get(lldb::LanguageType lang,
@@ -98,10 +95,7 @@
lldb::TypeSummaryImplSP &entry) {
   if (!IsEnabled() || !IsApplicable(lang))
 return false;
-  if (GetTypeSummariesContainer()->Get(candidates, entry))
-return true;
-  bool regex = GetRegexTypeSummariesContainer()->Get(candidates, entry);
-  return regex;
+  return m_summary_cont.Get(candidates, entry);
 }
 
 bool TypeCategoryImpl::Get(lldb::LanguageType lang,
@@ -109,30 +103,29 @@
lldb::SyntheticChildrenSP &entry) {
   if (!IsEnabled() || !IsApplicable(lang))
 return false;
-  TypeFilterImpl::SharedPointer filter_sp;
+
   // first find both Filter and Synth, and then check which is most recent
+  bool pick_synth = false;
 
-  if (!GetTypeFiltersContainer()->Get(candidates, filter_sp))
-GetRegexTypeFiltersContainer()->Get(candidates, filter_sp);
+  TypeFilterImpl::SharedPointer filter_sp;
+  m_filter_cont.Get(candidates, filter_sp);
 
-  bool pick_synth = false;
-  ScriptedSyntheticChildren::SharedPointer synth;
-  if (!GetTypeSyntheticsContainer()->Get(candidates, synth))
-GetRegexTypeSyntheticsContainer()->Get(candidates, synth);
-  if (!filter_sp.get() && !synth.get())
+  ScriptedSyntheticChildren::SharedPointer synth_sp;
+  m_synth_cont.Get(candidates, synth_sp);
+
+  if (!filter_sp.get() && !synth_sp.get())
 return false;
-  else if (!filter_sp.get() && synth.get())
+  else if (!filter_sp.get() && synth_sp.get())
 pick_synth = true;
-
-  else if (filter_sp.get() && !synth.get())
+  else if (filter_sp.get() && !synth_sp.get())
 pick_synth = false;
-
-  else /*if (filter_sp.get() && synth.get())*/
+  else /*if (filter_sp.get() && synth_sp.get())*/
   {
-pick_synth = filter_sp->GetRevision() <= synth->GetRevision();
+pick_synth = filter_sp->GetRevision() <= synth_sp->GetRevision();
   }
+
   if (pick_synth) {
-entry = synth;
+entry = synth_sp;
 return true;
   } else {
 entry = filter_sp;
@@ -276,138 +269,62 @@
 
 TypeCategoryImpl::FormatContainer::MapValueType
 TypeCategoryImpl::GetFormatForType(lldb::TypeNameSpecifierImplSP type_sp) {
-  FormatContainer::MapValueType retval;
-
-  if (type_sp) {
-if (type_sp->IsRegex())
-  GetRegexTypeFormatsContainer()->GetExact(ConstString(type_sp->GetName()),
-   retval);
-else
-  GetTypeFormatsContainer()->GetExact(ConstString(type_sp->GetName()),
-  retval);
-  }
-
-  return retval;
+  return m_format_cont.GetForTypeNameSpecifier(type_sp);
 }
 
 TypeCategoryImpl::SummaryContainer::MapValueType
 TypeCategoryImpl::GetSummaryForType(lldb::TypeNameSpecifierImplSP type_sp) {
-  SummaryContainer::MapValueType retval;
-
-  if (type_sp) {
-if (type_sp->IsRegex())
-  GetRegexTypeSummariesContainer()->GetExact(
-  ConstString(type_sp->GetName()), retval);
-else
-  GetTypeSummariesContainer()->GetExact(ConstString(type_sp->GetName()),
-retval);
-  }
-
-  return retval;
+  return m_summary_cont.GetForTypeNameSpecifier(type_sp);
 }
 
 TypeCategoryImpl::FilterContainer::MapValueType
 TypeCategoryImpl::GetFilterForType(lldb::TypeNameSpecifierImplSP type_sp) {
-  FilterContainer::MapValueType retval;
-
-  if (type_sp) {
-if (type_sp->IsRegex())
-  GetRegexTypeFiltersContainer()->GetExact(ConstString(type_sp->GetName()),
-   retval);
-else
-  GetTypeFiltersContainer()->GetExact(ConstString(type_sp->GetName()),
-  retval);
-  }
-
-  return retval;
+  return m_filter_cont.GetForTypeNameSpecifier(type_sp);
 }
 
 TypeCategoryImpl::SynthContainer::MapVa

[Lldb-commits] [PATCH] D134768: [NFCI] More TypeCategoryImpl refactoring.

2022-09-27 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe created this revision.
jgorbe added reviewers: jingham, labath.
jgorbe added a project: LLDB.
Herald added a subscriber: JDevlieghere.
Herald added a project: All.
jgorbe requested review of this revision.

The main aim of this patch is deleting the remaining instances of code
reaching into the internals of `TypeCategoryImpl`. I made the following
changes:

- Add some more methods to `TieredFormatterContainer` and `TypeCategoryImpl` to 
expose functionality that is implemented in `FormattersContainer`.

- Add new overloads of `TypeCategoryImpl::AddTypeXXX` to make it easier to add 
formatters to categories without reaching into the internal 
`FormattersContainer` objects.

- Remove the `GetTypeXXXContainer` and `GetRegexTypeXXXContainer` accessors 
from `TypeCategoryImpl` and update all call sites to use the new methods 
instead.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D134768

Files:
  lldb/include/lldb/DataFormatters/TypeCategory.h
  lldb/source/Commands/CommandObjectType.cpp
  lldb/source/DataFormatters/FormatManager.cpp
  lldb/source/DataFormatters/FormattersHelpers.cpp
  lldb/source/DataFormatters/TypeCategory.cpp
  lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp
  lldb/source/Plugins/Language/ObjC/ObjCLanguage.cpp

Index: lldb/source/Plugins/Language/ObjC/ObjCLanguage.cpp
===
--- lldb/source/Plugins/Language/ObjC/ObjCLanguage.cpp
+++ lldb/source/Plugins/Language/ObjC/ObjCLanguage.cpp
@@ -284,12 +284,12 @@
 
   lldb::TypeSummaryImplSP ObjC_BOOL_summary(new CXXFunctionSummaryFormat(
   objc_flags, lldb_private::formatters::ObjCBOOLSummaryProvider, ""));
-  objc_category_sp->GetTypeSummariesContainer()->Add(ConstString("BOOL"),
- ObjC_BOOL_summary);
-  objc_category_sp->GetTypeSummariesContainer()->Add(ConstString("BOOL &"),
- ObjC_BOOL_summary);
-  objc_category_sp->GetTypeSummariesContainer()->Add(ConstString("BOOL *"),
- ObjC_BOOL_summary);
+  objc_category_sp->AddTypeSummary("BOOL", eFormatterMatchExact,
+   ObjC_BOOL_summary);
+  objc_category_sp->AddTypeSummary("BOOL &", eFormatterMatchExact,
+   ObjC_BOOL_summary);
+  objc_category_sp->AddTypeSummary("BOOL *", eFormatterMatchExact,
+   ObjC_BOOL_summary);
 
   // we need to skip pointers here since we are special casing a SEL* when
   // retrieving its value
Index: lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp
===
--- lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp
+++ lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp
@@ -764,8 +764,8 @@
   ConstString("^std::__[[:alnum:]]+::span<.+>(( )?&)?$"), stl_deref_flags,
   true);
 
-  cpp_category_sp->GetRegexTypeSyntheticsContainer()->Add(
-  RegularExpression("^(std::__[[:alnum:]]+::)deque<.+>(( )?&)?$"),
+  cpp_category_sp->AddTypeSynthetic(
+  "^(std::__[[:alnum:]]+::)deque<.+>(( )?&)?$", eFormatterMatchRegex,
   SyntheticChildrenSP(new ScriptedSyntheticChildren(
   stl_synth_flags,
   "lldb.formatters.cpp.libcxx.stddeque_SynthProvider")));
@@ -958,55 +958,52 @@
   stl_summary_flags, LibStdcppWStringSummaryProvider,
   "libstdc++ c++11 std::wstring summary provider"));
 
-  cpp_category_sp->GetTypeSummariesContainer()->Add(ConstString("std::string"),
-std_string_summary_sp);
-  cpp_category_sp->GetTypeSummariesContainer()->Add(
-  ConstString("std::basic_string"), std_string_summary_sp);
-  cpp_category_sp->GetTypeSummariesContainer()->Add(
-  ConstString("std::basic_string,std::"
-  "allocator >"),
-  std_string_summary_sp);
-  cpp_category_sp->GetTypeSummariesContainer()->Add(
-  ConstString("std::basic_string, "
-  "std::allocator >"),
-  std_string_summary_sp);
-
-  cpp_category_sp->GetTypeSummariesContainer()->Add(
-  ConstString("std::__cxx11::string"), cxx11_string_summary_sp);
-  cpp_category_sp->GetTypeSummariesContainer()->Add(
-  ConstString("std::__cxx11::basic_string, "
-  "std::allocator >"),
-  cxx11_string_summary_sp);
-  cpp_category_sp->GetTypeSummariesContainer()->Add(
-  ConstString("std::__cxx11::basic_string, "
-  "std::allocator >"),
-  cxx11_string_summary_sp);
+  cpp_category_sp->AddTypeSummary("std::string", eFormatterMatchExact,
+  std_string_summary_sp);
+  cpp_category_sp->AddTypeSummary("std::basic_string",
+  eFormatterMatchRegex, std_string_summary_sp);
+  cpp_category_sp->AddTypeSummary(
+  "std::basic_string,std::allocator >",
+  eFormatter

[Lldb-commits] [PATCH] D134768: [NFCI] More TypeCategoryImpl refactoring.

2022-09-27 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe abandoned this revision.
jgorbe added a comment.

whoops, I need to commit some other local change before this one. I'm going to 
abandon this revision and I'll re-send this patch when its dependency lands. 
Sorry for the noise.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134768

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


[Lldb-commits] [PATCH] D134771: [NFCI] Simplify TypeCategoryImpl for-each callbacks.

2022-09-27 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe created this revision.
jgorbe added reviewers: jingham, labath.
jgorbe added a project: LLDB.
Herald added a subscriber: JDevlieghere.
Herald added a project: All.
jgorbe requested review of this revision.

The callback system to iterate over every formatter of a given kind in
a TypeCategoryImpl is only used in one place (the implementation of
`type {formatter_kind} list`), and it's too convoluted for the sake of
unused flexibility.

This change changes it so that only one callback is passed to `ForEach`
(instead of a callback for exact matches and another one for regex
matches), and moves the iteration logic to `TieredFormatterContainer`
to avoid duplication.

If in the future we need different logic in the callback depending on
exact/regex match, the callback can get the type of formatter matching
used from the TypeMatcher argument anyway.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D134771

Files:
  lldb/include/lldb/DataFormatters/TypeCategory.h
  lldb/source/Commands/CommandObjectType.cpp

Index: lldb/source/Commands/CommandObjectType.cpp
===
--- lldb/source/Commands/CommandObjectType.cpp
+++ lldb/source/Commands/CommandObjectType.cpp
@@ -1097,36 +1097,20 @@
   "---\nCategory: %s%s\n---\n",
   category->GetName(), category->IsEnabled() ? "" : " (disabled)");
 
-  TypeCategoryImpl::ForEachCallbacks foreach;
-  foreach
-.SetExact([&result, &formatter_regex, &any_printed](
-  const TypeMatcher &type_matcher,
-  const FormatterSharedPointer &format_sp) -> bool {
-  if (ShouldListItem(type_matcher.GetMatchString().GetStringRef(),
- formatter_regex.get())) {
-any_printed = true;
-result.GetOutputStream().Printf(
-"%s: %s\n", type_matcher.GetMatchString().GetCString(),
-format_sp->GetDescription().c_str());
-  }
-  return true;
-});
-
-  foreach
-.SetWithRegex([&result, &formatter_regex, &any_printed](
-  const TypeMatcher &type_matcher,
-  const FormatterSharedPointer &format_sp) -> bool {
-  if (ShouldListItem(type_matcher.GetMatchString().GetStringRef(),
- formatter_regex.get())) {
-any_printed = true;
-result.GetOutputStream().Printf(
-"%s: %s\n", type_matcher.GetMatchString().GetCString(),
-format_sp->GetDescription().c_str());
-  }
-  return true;
-});
-
-  category->ForEach(foreach);
+  TypeCategoryImpl::ForEachCallback print_formatter =
+  [&result, &formatter_regex,
+   &any_printed](const TypeMatcher &type_matcher,
+ const FormatterSharedPointer &format_sp) -> bool {
+if (ShouldListItem(type_matcher.GetMatchString().GetStringRef(),
+   formatter_regex.get())) {
+  any_printed = true;
+  result.GetOutputStream().Printf(
+  "%s: %s\n", type_matcher.GetMatchString().GetCString(),
+  format_sp->GetDescription().c_str());
+}
+return true;
+  };
+  category->ForEach(print_formatter);
 };
 
 if (m_options.m_category_language.OptionWasSet()) {
Index: lldb/include/lldb/DataFormatters/TypeCategory.h
===
--- lldb/include/lldb/DataFormatters/TypeCategory.h
+++ lldb/include/lldb/DataFormatters/TypeCategory.h
@@ -130,6 +130,16 @@
 return lldb::TypeNameSpecifierImplSP();
   }
 
+  /// Iterates through tiers in order, running `callback` on each element of
+  /// each tier.
+  void ForEach(std::function)>
+   callback) {
+for (int tier = 0; tier <= lldb::eLastFormatterMatchType; ++tier) {
+  m_subcontainers[tier]->ForEach(callback);
+}
+  }
+
  private:
   std::array, lldb::eLastFormatterMatchType + 1>
   m_subcontainers;
@@ -146,120 +156,35 @@
   typedef uint16_t FormatCategoryItems;
   static const uint16_t ALL_ITEM_TYPES = UINT16_MAX;
 
-  template  class ForEachCallbacks {
-  public:
-ForEachCallbacks() = default;
-~ForEachCallbacks() = default;
-
-template 
-typename std::enable_if::value, ForEachCallbacks &>::type
-SetExact(FormatContainer::ForEachCallback callback) {
-  m_format_exact = std::move(callback);
-  return *this;
-}
-template 
-typename std::enable_if::value, ForEachCallbacks &>::type
-SetWithRegex(FormatContainer::ForEachCallback callback) {
-  m_format_regex = std::move(callback);
-  return *this;
-}
-
-template 
-typename std::enable_if::value, ForEachCallbacks &>::type
-SetExact(SummaryContainer::ForEachCallback callback) {
-  m_summary_exact = std::move(callback);
-  return *this;
- 

[Lldb-commits] [PATCH] D134771: [NFCI] Simplify TypeCategoryImpl for-each callbacks.

2022-09-28 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe updated this revision to Diff 463624.
jgorbe added a comment.

Fixed callback argument type (from `const std::shared_ptr` to 
`const std::shared_ptr &`) as suggested by reviewer.

Also use a range-based for loop to loop over subcontainers in 
`TieredFormattercontainer::ForEach`.


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

https://reviews.llvm.org/D134771

Files:
  lldb/include/lldb/DataFormatters/TypeCategory.h
  lldb/source/Commands/CommandObjectType.cpp

Index: lldb/source/Commands/CommandObjectType.cpp
===
--- lldb/source/Commands/CommandObjectType.cpp
+++ lldb/source/Commands/CommandObjectType.cpp
@@ -1097,36 +1097,20 @@
   "---\nCategory: %s%s\n---\n",
   category->GetName(), category->IsEnabled() ? "" : " (disabled)");
 
-  TypeCategoryImpl::ForEachCallbacks foreach;
-  foreach
-.SetExact([&result, &formatter_regex, &any_printed](
-  const TypeMatcher &type_matcher,
-  const FormatterSharedPointer &format_sp) -> bool {
-  if (ShouldListItem(type_matcher.GetMatchString().GetStringRef(),
- formatter_regex.get())) {
-any_printed = true;
-result.GetOutputStream().Printf(
-"%s: %s\n", type_matcher.GetMatchString().GetCString(),
-format_sp->GetDescription().c_str());
-  }
-  return true;
-});
-
-  foreach
-.SetWithRegex([&result, &formatter_regex, &any_printed](
-  const TypeMatcher &type_matcher,
-  const FormatterSharedPointer &format_sp) -> bool {
-  if (ShouldListItem(type_matcher.GetMatchString().GetStringRef(),
- formatter_regex.get())) {
-any_printed = true;
-result.GetOutputStream().Printf(
-"%s: %s\n", type_matcher.GetMatchString().GetCString(),
-format_sp->GetDescription().c_str());
-  }
-  return true;
-});
-
-  category->ForEach(foreach);
+  TypeCategoryImpl::ForEachCallback print_formatter =
+  [&result, &formatter_regex,
+   &any_printed](const TypeMatcher &type_matcher,
+ const FormatterSharedPointer &format_sp) -> bool {
+if (ShouldListItem(type_matcher.GetMatchString().GetStringRef(),
+   formatter_regex.get())) {
+  any_printed = true;
+  result.GetOutputStream().Printf(
+  "%s: %s\n", type_matcher.GetMatchString().GetCString(),
+  format_sp->GetDescription().c_str());
+}
+return true;
+  };
+  category->ForEach(print_formatter);
 };
 
 if (m_options.m_category_language.OptionWasSet()) {
Index: lldb/include/lldb/DataFormatters/TypeCategory.h
===
--- lldb/include/lldb/DataFormatters/TypeCategory.h
+++ lldb/include/lldb/DataFormatters/TypeCategory.h
@@ -130,6 +130,16 @@
 return lldb::TypeNameSpecifierImplSP();
   }
 
+  /// Iterates through tiers in order, running `callback` on each element of
+  /// each tier.
+  void ForEach(std::function &)>
+   callback) {
+for (auto sc : m_subcontainers) {
+  sc->ForEach(callback);
+}
+  }
+
  private:
   std::array, lldb::eLastFormatterMatchType + 1>
   m_subcontainers;
@@ -146,120 +156,35 @@
   typedef uint16_t FormatCategoryItems;
   static const uint16_t ALL_ITEM_TYPES = UINT16_MAX;
 
-  template  class ForEachCallbacks {
-  public:
-ForEachCallbacks() = default;
-~ForEachCallbacks() = default;
-
-template 
-typename std::enable_if::value, ForEachCallbacks &>::type
-SetExact(FormatContainer::ForEachCallback callback) {
-  m_format_exact = std::move(callback);
-  return *this;
-}
-template 
-typename std::enable_if::value, ForEachCallbacks &>::type
-SetWithRegex(FormatContainer::ForEachCallback callback) {
-  m_format_regex = std::move(callback);
-  return *this;
-}
-
-template 
-typename std::enable_if::value, ForEachCallbacks &>::type
-SetExact(SummaryContainer::ForEachCallback callback) {
-  m_summary_exact = std::move(callback);
-  return *this;
-}
-template 
-typename std::enable_if::value, ForEachCallbacks &>::type
-SetWithRegex(SummaryContainer::ForEachCallback callback) {
-  m_summary_regex = std::move(callback);
-  return *this;
-}
-
-template 
-typename std::enable_if::value, ForEachCallbacks &>::type
-SetExact(FilterContainer::ForEachCallback callback) {
-  m_filter_exact = std::move(callback);
-  return *this;
-}
-template 
-typename std::enable_if::value, ForEachCallbacks &>::type
-SetWithRegex(FilterContainer::ForEachCallback callback) {
-  m_filter_regex =

[Lldb-commits] [PATCH] D134771: [NFCI] Simplify TypeCategoryImpl for-each callbacks.

2022-09-28 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe marked an inline comment as done.
jgorbe added inline comments.



Comment at: lldb/include/lldb/DataFormatters/TypeCategory.h:136
+  void ForEach(std::function)>
+   callback) {

labath wrote:
> did you want to add a reference here? A const by-value argument is not 
> particularly useful.
Yeah, I just changed it. Thanks for catching it!



Comment at: lldb/include/lldb/DataFormatters/TypeCategory.h:159-162
+  // TypeFilterImpl inherits from SyntheticChildren, so we can't simply 
overload
+  // ForEach on the type of the callback because it would result in "call to
+  // member function 'ForEach' is ambiguous" errors. Instead we use this
+  // templated struct to hold the formatter type and the callback.

labath wrote:
> What if we just embed the type information into the method name? (So we could 
> have a set of `ForEachFormat`,`ForEachSummary`, ... methods instead of a 
> single overloaded ForEach)
The problem with that is that the call site is

```
template 
class CommandObjectTypeFormatterList {
  [...]
  bool DoExecute(...) {
  TypeCategoryImpl::ForEachCallbacks foreach;
  category->ForEach(foreach);
```

So if we want to keep that template for `CommandObjectTypeFormatterList` to 
avoid repeating the implementation of `type {format, summary, filter, 
synthetic} list`, we still need to switch based on type //somewhere//. So it 
might as well be here. Or did you have anything else in mind?


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

https://reviews.llvm.org/D134771

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


[Lldb-commits] [PATCH] D134570: [lldb] Skip check for conflicting filter/synth when adding a new regex.

2022-10-04 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe added a comment.

Ping? If anyone has other suggestions for reviewers I'd appreciate them.


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

https://reviews.llvm.org/D134570

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


[Lldb-commits] [PATCH] D134771: [NFCI] Simplify TypeCategoryImpl for-each callbacks.

2022-10-05 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe added a comment.

Ping.


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

https://reviews.llvm.org/D134771

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


[Lldb-commits] [PATCH] D134771: [NFCI] Simplify TypeCategoryImpl for-each callbacks.

2022-10-06 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGdee9c7f5d7e5: [NFCI] Simplify TypeCategoryImpl for-each 
callbacks. (authored by jgorbe).

Changed prior to commit:
  https://reviews.llvm.org/D134771?vs=463624&id=465824#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134771

Files:
  lldb/include/lldb/DataFormatters/TypeCategory.h
  lldb/source/Commands/CommandObjectType.cpp

Index: lldb/source/Commands/CommandObjectType.cpp
===
--- lldb/source/Commands/CommandObjectType.cpp
+++ lldb/source/Commands/CommandObjectType.cpp
@@ -1097,36 +1097,20 @@
   "---\nCategory: %s%s\n---\n",
   category->GetName(), category->IsEnabled() ? "" : " (disabled)");
 
-  TypeCategoryImpl::ForEachCallbacks foreach;
-  foreach
-.SetExact([&result, &formatter_regex, &any_printed](
-  const TypeMatcher &type_matcher,
-  const FormatterSharedPointer &format_sp) -> bool {
-  if (ShouldListItem(type_matcher.GetMatchString().GetStringRef(),
- formatter_regex.get())) {
-any_printed = true;
-result.GetOutputStream().Printf(
-"%s: %s\n", type_matcher.GetMatchString().GetCString(),
-format_sp->GetDescription().c_str());
-  }
-  return true;
-});
-
-  foreach
-.SetWithRegex([&result, &formatter_regex, &any_printed](
-  const TypeMatcher &type_matcher,
-  const FormatterSharedPointer &format_sp) -> bool {
-  if (ShouldListItem(type_matcher.GetMatchString().GetStringRef(),
- formatter_regex.get())) {
-any_printed = true;
-result.GetOutputStream().Printf(
-"%s: %s\n", type_matcher.GetMatchString().GetCString(),
-format_sp->GetDescription().c_str());
-  }
-  return true;
-});
-
-  category->ForEach(foreach);
+  TypeCategoryImpl::ForEachCallback print_formatter =
+  [&result, &formatter_regex,
+   &any_printed](const TypeMatcher &type_matcher,
+ const FormatterSharedPointer &format_sp) -> bool {
+if (ShouldListItem(type_matcher.GetMatchString().GetStringRef(),
+   formatter_regex.get())) {
+  any_printed = true;
+  result.GetOutputStream().Printf(
+  "%s: %s\n", type_matcher.GetMatchString().GetCString(),
+  format_sp->GetDescription().c_str());
+}
+return true;
+  };
+  category->ForEach(print_formatter);
 };
 
 if (m_options.m_category_language.OptionWasSet()) {
Index: lldb/include/lldb/DataFormatters/TypeCategory.h
===
--- lldb/include/lldb/DataFormatters/TypeCategory.h
+++ lldb/include/lldb/DataFormatters/TypeCategory.h
@@ -130,6 +130,16 @@
 return lldb::TypeNameSpecifierImplSP();
   }
 
+  /// Iterates through tiers in order, running `callback` on each element of
+  /// each tier.
+  void ForEach(std::function &)>
+   callback) {
+for (auto sc : m_subcontainers) {
+  sc->ForEach(callback);
+}
+  }
+
  private:
   std::array, lldb::eLastFormatterMatchType + 1>
   m_subcontainers;
@@ -146,120 +156,36 @@
   typedef uint16_t FormatCategoryItems;
   static const uint16_t ALL_ITEM_TYPES = UINT16_MAX;
 
-  template  class ForEachCallbacks {
-  public:
-ForEachCallbacks() = default;
-~ForEachCallbacks() = default;
-
-template 
-typename std::enable_if::value, ForEachCallbacks &>::type
-SetExact(FormatContainer::ForEachCallback callback) {
-  m_format_exact = std::move(callback);
-  return *this;
-}
-template 
-typename std::enable_if::value, ForEachCallbacks &>::type
-SetWithRegex(FormatContainer::ForEachCallback callback) {
-  m_format_regex = std::move(callback);
-  return *this;
-}
-
-template 
-typename std::enable_if::value, ForEachCallbacks &>::type
-SetExact(SummaryContainer::ForEachCallback callback) {
-  m_summary_exact = std::move(callback);
-  return *this;
-}
-template 
-typename std::enable_if::value, ForEachCallbacks &>::type
-SetWithRegex(SummaryContainer::ForEachCallback callback) {
-  m_summary_regex = std::move(callback);
-  return *this;
-}
-
-template 
-typename std::enable_if::value, ForEachCallbacks &>::type
-SetExact(FilterContainer::ForEachCallback callback) {
-  m_filter_exact = std::move(callback);
-  return *this;
-}
-template 
-typename std::enable_if::value, ForEachCallbacks &>::type
-SetWithRegex(FilterContainer::ForEachCallback callback) {
-   

[Lldb-commits] [PATCH] D134570: [lldb] Skip check for conflicting filter/synth when adding a new regex.

2022-10-06 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG69c661a65ff8: [lldb] Skip check for conflicting filter/synth 
when adding a new regex. (authored by jgorbe).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134570

Files:
  lldb/source/Commands/CommandObjectType.cpp
  
lldb/test/API/functionalities/data-formatter/data-formatter-python-synth/TestDataFormatterPythonSynth.py


Index: 
lldb/test/API/functionalities/data-formatter/data-formatter-python-synth/TestDataFormatterPythonSynth.py
===
--- 
lldb/test/API/functionalities/data-formatter/data-formatter-python-synth/TestDataFormatterPythonSynth.py
+++ 
lldb/test/API/functionalities/data-formatter/data-formatter-python-synth/TestDataFormatterPythonSynth.py
@@ -257,6 +257,22 @@
 self.expect("frame variable f00_1", matching=False,
 substrs=['fake_a = '])
 
+# check that we don't feed a regex into another regex when checking for
+# existing conflicting synth/filters. The two following expressions
+# accept different types: one will accept types that look like an array
+# of MyType, the other will accept types that contain "MyType1" or
+# "MyType2". But the second regex looks like an array of MyType, so
+# lldb used to incorrectly reject it.
+self.runCmd(r'type synth add -l fooSynthProvider -x 
"^MyType\[[0-9]+]$"')
+self.runCmd(r'type filter add --child a -x "MyType[12]"')
+
+# Same, but adding the filter first to verify the check when doing
+# `type synth add`. We need to delete the synth from the previous test
+# first.
+self.runCmd(r'type synth delete "^MyType\[[0-9]+]$"')
+self.runCmd(r'type filter add --child a -x "^MyType\[[0-9]+]$"')
+self.runCmd(r'type synth add -l fooSynthProvider -x "MyType[12]"')
+
 def rdar10960550_formatter_commands(self):
 """Test that synthetic children persist stoppoints."""
 self.runCmd("file " + self.getBuildArtifact("a.out"), 
CURRENT_EXECUTABLE_SET)
Index: lldb/source/Commands/CommandObjectType.cpp
===
--- lldb/source/Commands/CommandObjectType.cpp
+++ lldb/source/Commands/CommandObjectType.cpp
@@ -2319,12 +2319,17 @@
   type = eRegexSynth;
   }
 
-  if (category->AnyMatches(type_name, eFormatCategoryItemFilter, false)) {
-if (error)
-  error->SetErrorStringWithFormat("cannot add synthetic for type %s when "
-  "filter is defined in same category!",
-  type_name.AsCString());
-return false;
+  // Only check for conflicting filters in the same category if `type_name` is
+  // an actual type name. Matching a regex string against registered regexes
+  // doesn't work.
+  if (type == eRegularSynth) {
+if (category->AnyMatches(type_name, eFormatCategoryItemFilter, false)) {
+  if (error)
+error->SetErrorStringWithFormat("cannot add synthetic for type %s when 
"
+"filter is defined in same category!",
+type_name.AsCString());
+  return false;
+}
   }
 
   if (type == eRegexSynth) {
@@ -2442,13 +2447,18 @@
 type = eRegexFilter;
 }
 
-if (category->AnyMatches(type_name, eFormatCategoryItemSynth, false)) {
-  if (error)
-error->SetErrorStringWithFormat("cannot add filter for type %s when "
-"synthetic is defined in same "
-"category!",
-type_name.AsCString());
-  return false;
+// Only check for conflicting synthetic child providers in the same 
category
+// if `type_name` is an actual type name. Matching a regex string against
+// registered regexes doesn't work.
+if (type == eRegularFilter) {
+  if (category->AnyMatches(type_name, eFormatCategoryItemSynth, false)) {
+if (error)
+  error->SetErrorStringWithFormat("cannot add filter for type %s when "
+  "synthetic is defined in same "
+  "category!",
+  type_name.AsCString());
+return false;
+  }
 }
 
 if (type == eRegexFilter) {


Index: lldb/test/API/functionalities/data-formatter/data-formatter-python-synth/TestDataFormatterPythonSynth.py
===
--- lldb/test/API/functionalities/data-formatter/data-formatter-python-synth/TestDataFormatterPythonSynth.py
+++ lldb/test/API/functionalities/data-formatter/data-formatter-python-synth/TestDataFormatterPythonSynth.py
@@ -257,6 +257,22 @@
 self.expect("

[Lldb-commits] [PATCH] D135399: [NFCI] More TypeCategoryImpl refactoring.

2022-10-06 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
jgorbe created this revision.
jgorbe added reviewers: labath, jingham.
jgorbe added a project: LLDB.
Herald added a subscriber: JDevlieghere.
Herald added a project: All.
jgorbe requested review of this revision.

The main aim of this patch is to delete the remaining instances of code
reaching into the internals of `TypeCategoryImpl`. I made the following
changes:

- Add some more methods to `TieredFormatterContainer` and `TypeCategoryImpl` to 
expose functionality that is implemented in `FormattersContainer`.

- Add new overloads of `TypeCategoryImpl::AddTypeXXX` to make it easier to add 
formatters to categories without reaching into the internal 
`FormattersContainer` objects.

- Remove the `GetTypeXXXContainer` and `GetRegexTypeXXXContainer` accessors 
from `TypeCategoryImpl` and update all call sites to use the new methods 
instead.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D135399

Files:
  lldb/include/lldb/DataFormatters/TypeCategory.h
  lldb/source/Commands/CommandObjectType.cpp
  lldb/source/DataFormatters/FormatManager.cpp
  lldb/source/DataFormatters/FormattersHelpers.cpp
  lldb/source/DataFormatters/TypeCategory.cpp
  lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp
  lldb/source/Plugins/Language/ObjC/ObjCLanguage.cpp

Index: lldb/source/Plugins/Language/ObjC/ObjCLanguage.cpp
===
--- lldb/source/Plugins/Language/ObjC/ObjCLanguage.cpp
+++ lldb/source/Plugins/Language/ObjC/ObjCLanguage.cpp
@@ -284,12 +284,12 @@
 
   lldb::TypeSummaryImplSP ObjC_BOOL_summary(new CXXFunctionSummaryFormat(
   objc_flags, lldb_private::formatters::ObjCBOOLSummaryProvider, ""));
-  objc_category_sp->GetTypeSummariesContainer()->Add(ConstString("BOOL"),
- ObjC_BOOL_summary);
-  objc_category_sp->GetTypeSummariesContainer()->Add(ConstString("BOOL &"),
- ObjC_BOOL_summary);
-  objc_category_sp->GetTypeSummariesContainer()->Add(ConstString("BOOL *"),
- ObjC_BOOL_summary);
+  objc_category_sp->AddTypeSummary("BOOL", eFormatterMatchExact,
+   ObjC_BOOL_summary);
+  objc_category_sp->AddTypeSummary("BOOL &", eFormatterMatchExact,
+   ObjC_BOOL_summary);
+  objc_category_sp->AddTypeSummary("BOOL *", eFormatterMatchExact,
+   ObjC_BOOL_summary);
 
   // we need to skip pointers here since we are special casing a SEL* when
   // retrieving its value
Index: lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp
===
--- lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp
+++ lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp
@@ -764,8 +764,8 @@
   ConstString("^std::__[[:alnum:]]+::span<.+>(( )?&)?$"), stl_deref_flags,
   true);
 
-  cpp_category_sp->GetRegexTypeSyntheticsContainer()->Add(
-  RegularExpression("^(std::__[[:alnum:]]+::)deque<.+>(( )?&)?$"),
+  cpp_category_sp->AddTypeSynthetic(
+  "^(std::__[[:alnum:]]+::)deque<.+>(( )?&)?$", eFormatterMatchRegex,
   SyntheticChildrenSP(new ScriptedSyntheticChildren(
   stl_synth_flags,
   "lldb.formatters.cpp.libcxx.stddeque_SynthProvider")));
@@ -958,55 +958,52 @@
   stl_summary_flags, LibStdcppWStringSummaryProvider,
   "libstdc++ c++11 std::wstring summary provider"));
 
-  cpp_category_sp->GetTypeSummariesContainer()->Add(ConstString("std::string"),
-std_string_summary_sp);
-  cpp_category_sp->GetTypeSummariesContainer()->Add(
-  ConstString("std::basic_string"), std_string_summary_sp);
-  cpp_category_sp->GetTypeSummariesContainer()->Add(
-  ConstString("std::basic_string,std::"
-  "allocator >"),
-  std_string_summary_sp);
-  cpp_category_sp->GetTypeSummariesContainer()->Add(
-  ConstString("std::basic_string, "
-  "std::allocator >"),
-  std_string_summary_sp);
-
-  cpp_category_sp->GetTypeSummariesContainer()->Add(
-  ConstString("std::__cxx11::string"), cxx11_string_summary_sp);
-  cpp_category_sp->GetTypeSummariesContainer()->Add(
-  ConstString("std::__cxx11::basic_string, "
-  "std::allocator >"),
-  cxx11_string_summary_sp);
-  cpp_category_sp->GetTypeSummariesContainer()->Add(
-  ConstString("std::__cxx11::basic_string, "
-  "std::allocator >"),
-  cxx11_string_summary_sp);
+  cpp_category_sp->AddTypeSummary("std::string", eFormatterMatchExact,
+  std_string_summary_sp);
+  cpp_category_sp->AddTypeSummary("std::basic_string",
+  eFormatterMatchRegex, std_string_summary_sp);
+  cpp_category_sp->AddTypeSummary(
+  "std::basic_string,std::allocator >",
+  eFormatte

[Lldb-commits] [PATCH] D135399: [NFCI] More TypeCategoryImpl refactoring.

2022-10-10 Thread Jorge Gorbe Moya via Phabricator via lldb-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGe5fd507f9b6f: [NFCI] More TypeCategoryImpl refactoring. 
(authored by jgorbe).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135399

Files:
  lldb/include/lldb/DataFormatters/TypeCategory.h
  lldb/source/Commands/CommandObjectType.cpp
  lldb/source/DataFormatters/FormatManager.cpp
  lldb/source/DataFormatters/FormattersHelpers.cpp
  lldb/source/DataFormatters/TypeCategory.cpp
  lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp
  lldb/source/Plugins/Language/ObjC/ObjCLanguage.cpp

Index: lldb/source/Plugins/Language/ObjC/ObjCLanguage.cpp
===
--- lldb/source/Plugins/Language/ObjC/ObjCLanguage.cpp
+++ lldb/source/Plugins/Language/ObjC/ObjCLanguage.cpp
@@ -284,12 +284,12 @@
 
   lldb::TypeSummaryImplSP ObjC_BOOL_summary(new CXXFunctionSummaryFormat(
   objc_flags, lldb_private::formatters::ObjCBOOLSummaryProvider, ""));
-  objc_category_sp->GetTypeSummariesContainer()->Add(ConstString("BOOL"),
- ObjC_BOOL_summary);
-  objc_category_sp->GetTypeSummariesContainer()->Add(ConstString("BOOL &"),
- ObjC_BOOL_summary);
-  objc_category_sp->GetTypeSummariesContainer()->Add(ConstString("BOOL *"),
- ObjC_BOOL_summary);
+  objc_category_sp->AddTypeSummary("BOOL", eFormatterMatchExact,
+   ObjC_BOOL_summary);
+  objc_category_sp->AddTypeSummary("BOOL &", eFormatterMatchExact,
+   ObjC_BOOL_summary);
+  objc_category_sp->AddTypeSummary("BOOL *", eFormatterMatchExact,
+   ObjC_BOOL_summary);
 
   // we need to skip pointers here since we are special casing a SEL* when
   // retrieving its value
Index: lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp
===
--- lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp
+++ lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp
@@ -764,8 +764,8 @@
   ConstString("^std::__[[:alnum:]]+::span<.+>(( )?&)?$"), stl_deref_flags,
   true);
 
-  cpp_category_sp->GetRegexTypeSyntheticsContainer()->Add(
-  RegularExpression("^(std::__[[:alnum:]]+::)deque<.+>(( )?&)?$"),
+  cpp_category_sp->AddTypeSynthetic(
+  "^(std::__[[:alnum:]]+::)deque<.+>(( )?&)?$", eFormatterMatchRegex,
   SyntheticChildrenSP(new ScriptedSyntheticChildren(
   stl_synth_flags,
   "lldb.formatters.cpp.libcxx.stddeque_SynthProvider")));
@@ -958,55 +958,52 @@
   stl_summary_flags, LibStdcppWStringSummaryProvider,
   "libstdc++ c++11 std::wstring summary provider"));
 
-  cpp_category_sp->GetTypeSummariesContainer()->Add(ConstString("std::string"),
-std_string_summary_sp);
-  cpp_category_sp->GetTypeSummariesContainer()->Add(
-  ConstString("std::basic_string"), std_string_summary_sp);
-  cpp_category_sp->GetTypeSummariesContainer()->Add(
-  ConstString("std::basic_string,std::"
-  "allocator >"),
-  std_string_summary_sp);
-  cpp_category_sp->GetTypeSummariesContainer()->Add(
-  ConstString("std::basic_string, "
-  "std::allocator >"),
-  std_string_summary_sp);
-
-  cpp_category_sp->GetTypeSummariesContainer()->Add(
-  ConstString("std::__cxx11::string"), cxx11_string_summary_sp);
-  cpp_category_sp->GetTypeSummariesContainer()->Add(
-  ConstString("std::__cxx11::basic_string, "
-  "std::allocator >"),
-  cxx11_string_summary_sp);
-  cpp_category_sp->GetTypeSummariesContainer()->Add(
-  ConstString("std::__cxx11::basic_string, "
-  "std::allocator >"),
-  cxx11_string_summary_sp);
+  cpp_category_sp->AddTypeSummary("std::string", eFormatterMatchExact,
+  std_string_summary_sp);
+  cpp_category_sp->AddTypeSummary("std::basic_string",
+  eFormatterMatchRegex, std_string_summary_sp);
+  cpp_category_sp->AddTypeSummary(
+  "std::basic_string,std::allocator >",
+  eFormatterMatchExact, std_string_summary_sp);
+  cpp_category_sp->AddTypeSummary(
+  "std::basic_string, std::allocator >",
+  eFormatterMatchExact, std_string_summary_sp);
+
+  cpp_category_sp->AddTypeSummary("std::__cxx11::string", eFormatterMatchExact,
+  cxx11_string_summary_sp);
+  cpp_category_sp->AddTypeSummary(
+  "std::__cxx11::basic_string, "
+  "std::allocator >",
+  eFormatterMatchExact, cxx11_string_summary_sp);
+  cpp_category_sp->AddTypeSummary("std::__cxx11::basic_string, "
+  "std::allocator >",
+  

  1   2   >