public inbox for gdb-patches@sourceware.org
 help / color / mirror / Atom feed
* [PATCH 0/9] thread-specific breakpoints in just some inferiors
@ 2023-04-28 23:35 Andrew Burgess
  2023-04-28 23:35 ` [PATCH 1/9] gdb: create_breakpoint: assert for a valid thread-id Andrew Burgess
                   ` (9 more replies)
  0 siblings, 10 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-04-28 23:35 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

When I proposed my inferior-specific breakpoints patch, two people
independently asked: will these breakpoints only be inserted into the
relevant inferiors?

My answer at that point was, no, that's just not possible given how we
manage the breakpoint locations, but this series changes that.

But as the inferior specific breakpoints patch hasn't landed yet, this
series looks at thread-specific breakpoints.

A thread-specific breakpoint only applies to a single global
thread-id, and so will only apply for to a single thread in a single
inferior.  As such, we can limit the locations for a thread-specific
breakpoint to just those locations in the inferior containing the
thread we are interested in.

In the following series patch #6 and #9 are the really interesting
ones.  Patch #6 makes some pretty significant changes to how we setup
breakpoints, which opens the way for #9, which performs the location
limiting.

Patches #1 to #5 are me just trying to understand the breakpoint
creation code more -- adding asserts and making a couple of minor
cleanups.

Patches #7 and #8 are more cleanups, but now looking at the location
creation/re-setting code.

---

Andrew Burgess (9):
  gdb: create_breakpoint: assert for a valid thread-id
  gdb: create_breakpoint: asserts relating to extra_string/parse_extra
  gdb: change 'if' to gdb_assert in update_dprintf_command_list
  gdb: build dprintf commands just once in code_breakpoint constructor
  gdb: don't display inferior list for pending breakpoints
  gdb: parse pending breakpoint thread/task immediately
  gdb: remove breakpoint_re_set_one
  gdb: remove tracepoint_probe_create_sals_from_location_spec
  gdb: only insert thread-specific breakpoints in the relevant inferior

 gdb/Makefile.in                               |   2 +
 gdb/NEWS                                      |  11 +
 gdb/ada-lang.c                                |   6 +-
 gdb/break-catch-throw.c                       |   6 +-
 gdb/break-cond-parse.c                        | 403 +++++++++++
 gdb/break-cond-parse.h                        |  47 ++
 gdb/breakpoint.c                              | 666 ++++++++----------
 gdb/breakpoint.h                              |  64 +-
 gdb/testsuite/gdb.base/condbreak.exp          |  20 +-
 gdb/testsuite/gdb.base/pending.exp            |  23 +-
 gdb/testsuite/gdb.linespec/explicit.exp       |   4 +-
 gdb/testsuite/gdb.mi/mi-dprintf-pending.exp   |   3 +-
 .../gdb.mi/user-selected-context-sync.exp     |   2 +-
 .../gdb.multi/bp-thread-specific.exp          |   7 +-
 .../gdb.multi/multi-target-continue.exp       |   2 +-
 .../gdb.multi/multi-target-ping-pong-next.exp |   4 +-
 gdb/testsuite/gdb.multi/pending-bp-lib.c      |  22 +
 gdb/testsuite/gdb.multi/pending-bp.c          |  66 ++
 gdb/testsuite/gdb.multi/pending-bp.exp        | 321 +++++++++
 gdb/testsuite/gdb.multi/tids.exp              |   6 +-
 .../gdb.threads/del-pending-thread-bp-lib.c   |  22 +
 .../gdb.threads/del-pending-thread-bp.c       |  85 +++
 .../gdb.threads/del-pending-thread-bp.exp     | 108 +++
 23 files changed, 1498 insertions(+), 402 deletions(-)
 create mode 100644 gdb/break-cond-parse.c
 create mode 100644 gdb/break-cond-parse.h
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.exp
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.exp


base-commit: 00cdd79a5d3f910c1362b9c4654adea3db0a97de
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCH 1/9] gdb: create_breakpoint: assert for a valid thread-id
  2023-04-28 23:35 [PATCH 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
@ 2023-04-28 23:35 ` Andrew Burgess
  2023-04-28 23:35 ` [PATCH 2/9] gdb: create_breakpoint: asserts relating to extra_string/parse_extra Andrew Burgess
                   ` (8 subsequent siblings)
  9 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-04-28 23:35 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Add an assert into create_breakpoint (breakpoint.c) that the thread
argument is a valid thread-id; either a value greater than zero, or -1
to indicate any thread.

The thread is ignored if parse_extra is true though, so take that into
account too.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c | 4 ++++
 gdb/breakpoint.h | 6 ++++++
 2 files changed, 10 insertions(+)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 46287da5f87..e6940bc9671 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -9026,6 +9026,10 @@ create_breakpoint (struct gdbarch *gdbarch,
 
   gdb_assert (ops != NULL);
 
+  /* If PARSE_EXTRA is true then the thread-id will be parsed from
+     EXTRA_STRING, otherwise, ensure THREAD is valid.  */
+  gdb_assert (parse_extra || thread == -1 || thread > 0);
+
   /* If extra_string isn't useful, set it to NULL.  */
   if (extra_string != NULL && *extra_string == '\0')
     extra_string = NULL;
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index 7c5cf3f2bef..e57dc2523fb 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -1530,6 +1530,12 @@ enum breakpoint_create_flags
    the FORCE_CONDITION parameter is ignored and the corresponding argument
    is parsed from EXTRA_STRING.
 
+   The THREAD should be a global thread number, the created breakpoint will
+   only apply for that thread.  If the breakpoint should apply for all
+   threads then pass -1.  However, if PARSE_EXTRA is non-zero then the
+   THREAD parameter is ignored and an optional thread number will be parsed
+   from EXTRA_STRING.
+
    If INTERNAL is non-zero, the breakpoint number will be allocated
    from the internal breakpoint count.
 
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCH 2/9] gdb: create_breakpoint: asserts relating to extra_string/parse_extra
  2023-04-28 23:35 [PATCH 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
  2023-04-28 23:35 ` [PATCH 1/9] gdb: create_breakpoint: assert for a valid thread-id Andrew Burgess
@ 2023-04-28 23:35 ` Andrew Burgess
  2023-04-28 23:35 ` [PATCH 3/9] gdb: change 'if' to gdb_assert in update_dprintf_command_list Andrew Burgess
                   ` (7 subsequent siblings)
  9 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-04-28 23:35 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

The goal of this commit is to better define the API for
create_breakpoint especially around the use of extra_string and
parse_extra.  This will be useful in the next commit when I plan to
make some changes to create_breakpoint.

This commit makes one possibly breaking change: until this commit it
was possible to create thread-specific dprintf breakpoint like this:

  (gdb) dprintf call_me, thread 1 "%s", "hello"
  Dprintf 2 at 0x401152: file /tmp/hello.c, line 8.
  (gdb) info breakpoints
  Num     Type           Disp Enb Address            What
  2       dprintf        keep y   0x0000000000401152 in call_me at /tmp/hello.c:8 thread 1
          stop only in thread 1
          printf "%s", "hello"
  (gdb)

this feature of dprintf was not documented, was not tested, and is
slightly different in syntax to how we create thread specific
breakpoints and/or watchpoints -- the thread condition appears after
the first ','.

I believe that this worked at all was simply by luck.  We happen to
pass the parse_extra flag as true from dprintf_command to
create_breakpoint.

So in this commit I made the choice change this.  We now pass
parse_extra as false from dprintf_command to create_breakpoint.  With
this done it is assumed that the only thing in the extra_string is the
dprintf format and arguments.

Beyond this change I've updated the comment on create_breakpoint in
breakpoint.h, and I've then added some asserts into
create_breakpoint as well as moving around some of the error
handling.

 - We now assert on the incoming argument values,

 - I've moved an error check to sit after the call to
   find_condition_and_thread_for_sals, this ensures the extra_string
   was parsed correctly,

In dprintf_command:

 - We now throw an error if there is no format string after the
   dprintf location.  This error was already being thrown, but was
   being caught later in the process.  With this change we catch the
   missing string earlier,

 - And, as mentioned earlier, we pass parse_extra as false when
   calling create_breakpoint,

In create_tracepoint_from_upload:

 - We now throw an error if the parsed location doesn't completely
   consume the addr_str variable.  This error has now effectively
   moved out of create_breakpoint.
---
 gdb/breakpoint.c | 42 +++++++++++++++++++++++++++++-------------
 gdb/breakpoint.h | 38 ++++++++++++++++++++++++--------------
 2 files changed, 53 insertions(+), 27 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index e6940bc9671..350fa495319 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -9034,6 +9034,17 @@ create_breakpoint (struct gdbarch *gdbarch,
   if (extra_string != NULL && *extra_string == '\0')
     extra_string = NULL;
 
+  /* A bp_dprintf must always have an accompanying EXTRA_STRING containing
+     the dprintf format and arguments -- PARSE_EXTRA should always be false
+     in this case.
+
+     For all other breakpoint types, EXTRA_STRING should be nullptr unless
+     PARSE_EXTRA is true.  */
+  gdb_assert ((type_wanted == bp_dprintf
+	       && extra_string != nullptr && !parse_extra)
+	      || (type_wanted != bp_dprintf
+		  && (extra_string == nullptr || parse_extra)));
+
   try
     {
       ops->create_sals_from_location_spec (locspec, &canonical);
@@ -9097,6 +9108,8 @@ create_breakpoint (struct gdbarch *gdbarch,
 
       if (parse_extra)
 	{
+	  gdb_assert (type_wanted != bp_dprintf);
+
 	  gdb::unique_xmalloc_ptr<char> rest;
 	  gdb::unique_xmalloc_ptr<char> cond;
 
@@ -9104,15 +9117,15 @@ create_breakpoint (struct gdbarch *gdbarch,
 
 	  find_condition_and_thread_for_sals (lsal.sals, extra_string,
 					      &cond, &thread, &task, &rest);
+
+	  if (rest.get () != nullptr && *(rest.get ()) != '\0')
+	    error (_("Garbage '%s' at end of command"), rest.get ());
+
 	  cond_string_copy = std::move (cond);
 	  extra_string_copy = std::move (rest);
 	}
       else
 	{
-	  if (type_wanted != bp_dprintf
-	      && extra_string != NULL && *extra_string != '\0')
-		error (_("Garbage '%s' at end of location"), extra_string);
-
 	  /* Check the validity of the condition.  We should error out
 	     if the condition is invalid at all of the locations and
 	     if it is not forced.  In the PARSE_EXTRA case above, this
@@ -9321,20 +9334,17 @@ dprintf_command (const char *arg, int from_tty)
 
   /* If non-NULL, ARG should have been advanced past the location;
      the next character must be ','.  */
-  if (arg != NULL)
+  if (arg == nullptr || arg[0] != ',' || arg[1] == '\0')
+    error (_("Format string required"));
+  else
     {
-      if (arg[0] != ',' || arg[1] == '\0')
-	error (_("Format string required"));
-      else
-	{
-	  /* Skip the comma.  */
-	  ++arg;
-	}
+      /* Skip the comma.  */
+      ++arg;
     }
 
   create_breakpoint (get_current_arch (),
 		     locspec.get (),
-		     NULL, 0, arg, false, 1 /* parse arg */,
+		     NULL, -1, arg, false, 0 /* parse arg */,
 		     0, bp_dprintf,
 		     0 /* Ignore count */,
 		     pending_break_support,
@@ -13909,6 +13919,12 @@ create_tracepoint_from_upload (struct uploaded_tp *utp)
 
   location_spec_up locspec = string_to_location_spec (&addr_str,
 						      current_language);
+
+
+  gdb_assert (addr_str != nullptr);
+  if (*addr_str != '\0')
+    error (_("Garbage '%s' at end of location"), addr_str);
+
   if (!create_breakpoint (get_current_arch (),
 			  locspec.get (),
 			  utp->cond_string.get (), -1, addr_str,
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index e57dc2523fb..2adcc9fa338 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -1515,26 +1515,36 @@ enum breakpoint_create_flags
    functions for setting a breakpoint at LOCSPEC.
 
    This function has two major modes of operations, selected by the
-   PARSE_EXTRA parameter.
+   PARSE_EXTRA and WANTED_TYPE parameters.
 
-   If PARSE_EXTRA is zero, LOCSPEC is just the breakpoint's location
-   spec, with condition, thread, and extra string specified by the
-   COND_STRING, THREAD, and EXTRA_STRING parameters.
+   When WANTED_TYPE is not bp_dprintf the following rules apply:
 
-   If PARSE_EXTRA is non-zero, this function will attempt to extract
-   the condition, thread, and extra string from EXTRA_STRING, ignoring
-   the similarly named parameters.
+     If PARSE_EXTRA is zero, LOCSPEC is just the breakpoint's location
+     spec, with condition, thread, and extra string specified by the
+     COND_STRING, THREAD, and EXTRA_STRING parameters.
 
-   If FORCE_CONDITION is true, the condition is accepted even when it is
-   invalid at all of the locations.  However, if PARSE_EXTRA is non-zero,
-   the FORCE_CONDITION parameter is ignored and the corresponding argument
-   is parsed from EXTRA_STRING.
+     If PARSE_EXTRA is non-zero, this function will attempt to extract the
+     condition, thread, and extra string from EXTRA_STRING, ignoring the
+     similarly named parameters.
+
+   When WANTED_TYPE is bp_dprintf the following rules apply:
+
+     PARSE_EXTRA must always be zero, LOCSPEC is just the breakpoint's
+     location spec, with condition, thread, and extra string (which
+     contains the dprintf format and arguments) specified by the
+     COND_STRING, THREAD, and EXTRA_STRING parameters.
+
+   If FORCE_CONDITION is true, the condition (in COND_STRING) is accepted
+   even when it is invalid at all of the locations.  However, if
+   PARSE_EXTRA is non-zero and WANTED_TYPE is not bp_dprintf, the
+   FORCE_CONDITION parameter is ignored and the corresponding argument is
+   parsed from EXTRA_STRING.
 
    The THREAD should be a global thread number, the created breakpoint will
    only apply for that thread.  If the breakpoint should apply for all
-   threads then pass -1.  However, if PARSE_EXTRA is non-zero then the
-   THREAD parameter is ignored and an optional thread number will be parsed
-   from EXTRA_STRING.
+   threads then pass -1.  However, if PARSE_EXTRA is non-zero and
+   WANTED_TYPE is not bp_dprintf, then the THREAD parameter is ignored and
+   an optional thread number will be parsed from EXTRA_STRING.
 
    If INTERNAL is non-zero, the breakpoint number will be allocated
    from the internal breakpoint count.
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCH 3/9] gdb: change 'if' to gdb_assert in update_dprintf_command_list
  2023-04-28 23:35 [PATCH 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
  2023-04-28 23:35 ` [PATCH 1/9] gdb: create_breakpoint: assert for a valid thread-id Andrew Burgess
  2023-04-28 23:35 ` [PATCH 2/9] gdb: create_breakpoint: asserts relating to extra_string/parse_extra Andrew Burgess
@ 2023-04-28 23:35 ` Andrew Burgess
  2023-04-28 23:35 ` [PATCH 4/9] gdb: build dprintf commands just once in code_breakpoint constructor Andrew Burgess
                   ` (6 subsequent siblings)
  9 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-04-28 23:35 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

I noticed in update_dprintf_command_list that we handle the case where
the bp_dprintf style breakpoint doesn't have a format and args string.

However, I don't believe such a situation is possible.  The obvious
approach certainly already catches this case:

  (gdb) dprintf main
  Format string required

If it is possible to create a dprintf breakpoint without a format and
args string then I think we should be catching this case and handling
it at creation time, rather than having GDB just ignore the situation
later on.

And so, I propose that we change the 'if' that ignores the case where
the format/args string is empty, and instead assert that we do always
have a format/args string.  The original code, that handled an empty
format/args string has existed since commit e7e0cddfb0d4, which is
when dprintf support was added to GDB.

If I'm correct and this situation can't ever happen then there should
be no user visible changes after this commit.
---
 gdb/breakpoint.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 350fa495319..b75990963ca 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -8382,8 +8382,9 @@ update_dprintf_command_list (struct breakpoint *b)
   const char *dprintf_args = b->extra_string.get ();
   gdb::unique_xmalloc_ptr<char> printf_line = nullptr;
 
-  if (!dprintf_args)
-    return;
+  /* Trying to create a dprintf breakpoint without a format and args
+     string should be detected at creation time.  */
+  gdb_assert (dprintf_args != nullptr);
 
   dprintf_args = skip_spaces (dprintf_args);
 
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCH 4/9] gdb: build dprintf commands just once in code_breakpoint constructor
  2023-04-28 23:35 [PATCH 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
                   ` (2 preceding siblings ...)
  2023-04-28 23:35 ` [PATCH 3/9] gdb: change 'if' to gdb_assert in update_dprintf_command_list Andrew Burgess
@ 2023-04-28 23:35 ` Andrew Burgess
  2023-04-28 23:35 ` [PATCH 5/9] gdb: don't display inferior list for pending breakpoints Andrew Burgess
                   ` (5 subsequent siblings)
  9 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-04-28 23:35 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

I noticed in code_breakpoint::code_breakpoint that we are calling
update_dprintf_command_list once for each breakpoint location, when we
really only need to call this once per breakpoint -- the data updated
by this function, the breakpoint command list -- is per breakpoint,
not per breakpoint location.  Calling update_dprintf_command_list
multiple times is just wasted effort, there's no per location error
checking, we don't even pass the current location to the function.

This commit moves the update_dprintf_command_list call outside of the
per-location loop. I have also changes the 'if' that handles the case
where the extra_string (which holds the format/args) is empty.  I
don't believe that this situation can ever arise -- and if it does we
should be catching it earlier and throwing an error at that point.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c | 20 +++++++++-----------
 1 file changed, 9 insertions(+), 11 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index b75990963ca..1b06c7e0f5b 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -8543,19 +8543,17 @@ code_breakpoint::code_breakpoint (struct gdbarch *gdbarch_,
       /* Do not set breakpoint locations conditions yet.  As locations
 	 are inserted, they get sorted based on their addresses.  Let
 	 the list stabilize to have reliable location numbers.  */
+    }
 
-      /* Dynamic printf requires and uses additional arguments on the
-	 command line, otherwise it's an error.  */
-      if (type == bp_dprintf)
-	{
-	  if (extra_string != nullptr)
-	    update_dprintf_command_list (this);
-	  else
-	    error (_("Format string required"));
-	}
-      else if (extra_string != nullptr)
-	error (_("Garbage '%s' at end of command"), extra_string.get ());
+  /* Dynamic printf requires and uses additional arguments on the
+     command line, otherwise it's an error.  */
+  if (type == bp_dprintf)
+    {
+      gdb_assert (extra_string != nullptr);
+      update_dprintf_command_list (this);
     }
+  else if (extra_string != nullptr)
+    error (_("Garbage '%s' at end of command"), extra_string.get ());
 
   /* The order of the locations is now stable.  Set the location
      condition using the location's number.  */
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCH 5/9] gdb: don't display inferior list for pending breakpoints
  2023-04-28 23:35 [PATCH 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
                   ` (3 preceding siblings ...)
  2023-04-28 23:35 ` [PATCH 4/9] gdb: build dprintf commands just once in code_breakpoint constructor Andrew Burgess
@ 2023-04-28 23:35 ` Andrew Burgess
  2023-04-28 23:35 ` [PATCH 6/9] gdb: parse pending breakpoint thread/task immediately Andrew Burgess
                   ` (4 subsequent siblings)
  9 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-04-28 23:35 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

I noticed that in the 'info breakpoints' output, GDB sometimes prints
the inferior list for pending breakpoints, this doesn't seem right to
me.  A pending breakpoint has no locations (at least, as far as we
display things in the 'info breakpoints' output), so including an
inferior list seems odd.

Here's what I see right now:

  (gdb) info breakpoint 5
  Num     Type           Disp Enb Address            What
  5       breakpoint     keep y   <PENDING>          foo inf 1
  (gdb)

It's the 'inf 1' at the end of the line that I'm objecting too.

To trigger this behaviour we need to be in a multi-inferior debug
session.  The breakpoint must have been non-pending at some point in
the past, and so have a location assigned to it.

The breakpoint becomes pending again as a result of a shared library
being unloaded.  When this happens the location itself is marked
pending (via bp_location::shlib_disabled).

In print_one_breakpoint_location, in order to print the inferior list
we check that the breakpoint has a location, and that we have multiple
inferiors, but we don't check if the location itself is pending.

This commit adds that check, which means the output is now:

  (gdb) info breakpoint 5
  Num     Type           Disp Enb Address            What
  5       breakpoint     keep y   <PENDING>          foo
  (gdb)

Which I think makes more sense.
---
 gdb/breakpoint.c                         |   2 +-
 gdb/testsuite/gdb.multi/pending-bp-lib.c |  22 +++++
 gdb/testsuite/gdb.multi/pending-bp.c     |  66 +++++++++++++
 gdb/testsuite/gdb.multi/pending-bp.exp   | 115 +++++++++++++++++++++++
 4 files changed, 204 insertions(+), 1 deletion(-)
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.exp

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 1b06c7e0f5b..3e52234e72d 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -6473,7 +6473,7 @@ print_one_breakpoint_location (struct breakpoint *b,
 	}
     }
 
-  if (loc != NULL && !header_of_multiple)
+  if (loc != NULL && !header_of_multiple && !loc->shlib_disabled)
     {
       std::vector<int> inf_nums;
       int mi_only = 1;
diff --git a/gdb/testsuite/gdb.multi/pending-bp-lib.c b/gdb/testsuite/gdb.multi/pending-bp-lib.c
new file mode 100644
index 00000000000..15d1b9833dd
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp-lib.c
@@ -0,0 +1,22 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+int global_var = 0;
+
+void
+foo (int arg)
+{
+  global_var = arg;
+}
diff --git a/gdb/testsuite/gdb.multi/pending-bp.c b/gdb/testsuite/gdb.multi/pending-bp.c
new file mode 100644
index 00000000000..ca8a3c20b72
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp.c
@@ -0,0 +1,66 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#include <dlfcn.h>
+#include <stdlib.h>
+
+void
+breakpt ()
+{
+  /* Nothing.  */
+}
+
+volatile int global_counter = 0;
+
+volatile int call_count = 1;
+
+int
+main (void)
+{
+  void *handle;
+  void (*func)(int);
+
+  /* Some filler work so that we don't initially stop on the breakpt call
+     below.  */
+  ++global_counter;
+
+  breakpt ();	/* Break before open.  */
+
+  /* Now load the shared library.  */
+  handle = dlopen (SHLIB_NAME, RTLD_LAZY);
+  if (handle == NULL)
+    abort ();
+
+  breakpt ();	/* Break after open.  */
+
+  /* Find the function symbol.  */
+  func = (void (*)(int)) dlsym (handle, "foo");
+
+  for (; call_count > 0; --call_count)
+    {
+      /* Call the library function.  */
+      func (1);
+    }
+
+  breakpt ();	/* Break before close.  */
+
+  /* Unload the shared library.  */
+  if (dlclose (handle) != 0)
+    abort ();
+
+  breakpt ();	/* Break after close.  */
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.multi/pending-bp.exp b/gdb/testsuite/gdb.multi/pending-bp.exp
new file mode 100644
index 00000000000..4a65f79cfc4
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp.exp
@@ -0,0 +1,115 @@
+# Copyright 2023 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+# Tests related to pending breakpoints in a multi-inferior environment.
+
+require allow_shlib_tests !use_gdb_stub
+
+standard_testfile
+
+set libname $testfile-lib
+set srcfile_lib $srcdir/$subdir/$libname.c
+set binfile_lib [standard_output_file $libname.so]
+
+if { [gdb_compile_shlib $srcfile_lib $binfile_lib {}] != "" } {
+    untested "failed to compile shared library 1"
+    return -1
+}
+
+set binfile_lib_target [gdb_download_shlib $binfile_lib]
+
+if { [build_executable "failed to prepare" $testfile $srcfile \
+	  [list debug \
+	       additional_flags=-DSHLIB_NAME=\"$binfile_lib_target\" \
+	       shlib_load pthreads]] } {
+    return -1
+}
+
+# Used to override delete_breakpoints when we don't want breakpoints
+# deleted.
+proc do_nothing {} {}
+
+# Start two inferiors, both running the same test binary.  The arguments
+# INF_1_STOP and INF_2_STOP are source code patterns that are passed to
+# gdb_get_line_number to figure out where each inferior should be stopped.
+#
+# This proc does a clean_restart and leaves inferior 2 selected.  Also the
+# 'breakpoint pending' flag is enabled, so pending breakpoints can be created
+# without GDB prompting the user.
+proc do_test_setup { inf_1_stop inf_2_stop } {
+    clean_restart ${::binfile}
+
+    gdb_locate_shlib $::binfile_lib
+
+    if ![runto_main] {
+	return false
+    }
+
+    gdb_breakpoint [gdb_get_line_number ${inf_1_stop}] temporary
+    gdb_continue_to_breakpoint "move inferior 1 into position"
+
+    gdb_test "add-inferior -exec ${::binfile}" \
+	"Added inferior 2.*" "add inferior 2"
+    gdb_test "inferior 2" "Switching to inferior 2 .*" "switch to inferior 2"
+
+    with_override delete_breakpoints do_nothing {
+	if {![runto_main]} {
+	    return false
+	}
+    }
+
+    gdb_breakpoint [gdb_get_line_number ${inf_2_stop}] temporary
+    gdb_continue_to_breakpoint "move inferior 2 into position"
+
+    gdb_test_no_output "set breakpoint pending on"
+
+    return true
+}
+
+# Check that when a breakpoint is in the pending state, but that breakpoint
+# does have some locations (those locations themselves are pending), GDB
+# doesn't display the inferior list in the 'info breakpoints' output.
+proc_with_prefix test_no_inf_display {} {
+    do_test_setup "Break before close" "Break before open"
+
+    # Create a breakpoint on 'foo'.  This will find a location in inferior 1,
+    # but will not find a location in inferior 2 -- the shared library is not
+    # yet loaded in that inferior.
+    gdb_breakpoint "foo"
+    set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+		   "get foo breakpoint number"]
+
+    # Check the 'info breakpoints' output.  Notice we display the inferior
+    # list at the end of the breakpoint line.
+    gdb_test "info breakpoint $bpnum" \
+	"$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex\\s+<foo\[^>\]*>\\s+inf 1" \
+	"check info breakpoints while breakpoint is inserted"
+
+    # Ensure we are in inferior 1, move the inferior forward until the shared
+    # library has been unloaded.  The breakpoint on 'foo' will return to the
+    # pending state.
+    gdb_test "inferior 1" "Switching to inferior 1 .*"
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "after close library"
+
+    # Check the 'info breakpoints' output, check there is no 'inf 1' at the
+    # end of the breakpoint line.
+    gdb_test "info breakpoint $bpnum" \
+	"$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	"check info breakpoints while breakpoint is pending"
+}
+
+# Run all the tests.
+test_no_inf_display
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCH 6/9] gdb: parse pending breakpoint thread/task immediately
  2023-04-28 23:35 [PATCH 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
                   ` (4 preceding siblings ...)
  2023-04-28 23:35 ` [PATCH 5/9] gdb: don't display inferior list for pending breakpoints Andrew Burgess
@ 2023-04-28 23:35 ` Andrew Burgess
  2023-04-29  6:01   ` Eli Zaretskii
  2023-04-28 23:35 ` [PATCH 7/9] gdb: remove breakpoint_re_set_one Andrew Burgess
                   ` (3 subsequent siblings)
  9 siblings, 1 reply; 138+ messages in thread
From: Andrew Burgess @ 2023-04-28 23:35 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

The initial motivation for this commit was to allow thread or (in the
future) inferior specific breakpoints to only be inserted within the
appropriate inferior's program-space.  The benefit of this is that
inferiors for which the breakpoint does not apply will no longer need
to stop, and then resume, for such breakpoints.  This commit does not
make this change, but is a refactor to allow this change in a later
commit.

The problem we currently have is that when a thread-specific
breakpoint is created, the thread number is only parsed by calling
find_condition_and_thread_for_sals.  This function is only called for
non-pending breakpoints, and requires that we know the locations at
which the breakpoint will be placed (for expression checking in case
the breakpoint is also conditional).

A consequence of this is that by the time we figure out the breakpoint
is thread-specific we have already looked up locations in all program
spaces.  This feels wasteful -- if we knew the thread-id earlier then
we could reduce the work GDB does by only looking up locations within
the program space for which the breakpoint applies.

Another consequence of how find_condition_and_thread_for_sals is
called is that pending breakpoints don't currently know they are
thread-specific, nor even that they are conditional!  Additionally, by
delaying parsing the thread-id, pending breakpoints can be created for
non-existent threads, this is different to how non-pending
breakpoints are handled.

In this commit the create_breakpoint function is updated so that the
extra_string, which contains the thread/task/condition information, is
parsed immediately, even for pending breakpoints.

Obviously, the condition still can't be validated until the breakpoint
becomes non-pending, but the thread/task information can be pulled
from the extra-string, and can be validated early on, even for pending
breakpoints.

There are a couple of benefits to doing this:

1. Printing of breakpoints is more consistent now.  Consider creating
   a conditional breakpoint before this commit:

    (gdb) set breakpoint pending on
    (gdb) break pendingfunc if (0)
    Function "pendingfunc" not defined.
    Breakpoint 1 (pendingfunc if (0)) pending.
    (gdb) break main if (0)
    Breakpoint 2 at 0x401198: file /tmp/hello.c, line 18.
    (gdb) info breakpoints
    Num     Type           Disp Enb Address            What
    1       breakpoint     keep y   <PENDING>          pendingfunc if (0)
    2       breakpoint     keep y   0x0000000000401198 in main at /tmp/hello.c:18
            stop only if (0)
    (gdb)

   And after this commit:

    (gdb) set breakpoint pending on
    (gdb) break pendingfunc if (0)
    Function "pendingfunc" not defined.
    Breakpoint 1 (pendingfunc) pending.
    (gdb) break main if (0)
    Breakpoint 2 at 0x401198: file /home/andrew/tmp/hello.c, line 18.
    (gdb) info breakpoints
    Num     Type           Disp Enb Address            What
    1       breakpoint     keep y   <PENDING>          pendingfunc
            stop only if (0)
    2       breakpoint     keep y   0x0000000000401198 in main at /home/andrew/tmp/hello.c:18
            stop only if (0)
    (gdb)

   Notice that the display of the condition is now the same for the
   pending and non-pending breakpoints.

   The same is true for the thread information in thread-specific
   breakpoints, this information is displayed on its own line now
   rather than being part of the 'What' field.

2. We can check that the thread exists as soon as the pending
   breakpoint exits.  Currently there is a weird different between
   pending and non-pending breakpoints when creating a thread-specific
   breakpoint.  A pending thread-specific breakpoint only checks its
   thread when it becomes non-pending, at which point the thread the
   breakpoint was intended for might have exited.  Here's the
   behaviour before this commit:

    (gdb) set breakpoint pending on
    (gdb) break foo thread 2
    Function "foo" not defined.
    Breakpoint 2 (foo thread 2) pending.
    (gdb) c
    Continuing.
    [Thread 0x7ffff7c56700 (LWP 2948835) exited]
    Error in re-setting breakpoint 2: Unknown thread 2.
    [Inferior 1 (process 2948832) exited normally]
    (gdb)

   Notice the 'Error in re-setting breakpoint 2: Unknown thread 2.'
   line, this was triggered when the thread tried to become
   non-pending, and GDB discovers that the thread no longer exists.

   Compare that to the behaviour after this commit:

    (gdb) set breakpoint pending on
    (gdb) break foo thread 2
    Function "foo" not defined.
    Breakpoint 2 (foo) pending.
    (gdb) c
    Continuing.
    [Thread 0x7ffff7c56700 (LWP 2949243) exited]
    Thread-specific breakpoint 2 deleted - thread 2 no longer in the thread list.
    [Inferior 1 (process 2949240) exited normally]
    (gdb)

   Now the behaviour for pending breakpoints is identical to
   non-pending breakpoints, the thread specific breakpoint is removed
   as soon as the thread the breakpoint is associated with exits.

As a result of this commit the breakpoints 'extra_string' field is now
only used by bp_dprintf type breakpoints to hold the printf format and
arguments.  This string should always be empty for other breakpoint
types.  This allows me to clean up some code in
print_breakpoint_location.

In code_breakpoint::code_breakpoint I'm able to change an error case
into an assert.  This is because this error is now handled earlier in
create_breakpoint.  As a result we know that by this point, the
extra_string will always be nullptr for anything other than a
bp_dprintf style breakpoint.

The find_condition_and_thread_for_sals function is now no longer
needed, this was previously doing the delayed splitting of the extra
string into thread, task, and condition, but this is now all done in
create_breakpoint, so find_condition_and_thread_for_sals can be
deleted, and the code that calls this in
code_breakpoint::location_spec_to_sals can be removed.  With this
update this code would only ever be reached for bp_dprintf style
breakpoints, and in these cases the extra_string should not contain
anything other than format and args.

The most interesting changes are all in create_breakpoint and in the
new file break-cond-parse.c.  We have a new block of code early on in
create_breakpoint that is responsible for splitting the extra_string
into its component parts by calling create_breakpoint_parse_arg_string
a function in the new break-cond-parse.c file.  This means that some
of the later code can be simplified a little.

The new break-cond-parse.c file implements the splitting up the
extra_string and finding all the parts, as well as some self-tests for
the new function.

Finally, now we know all the details, these can be stored within the
breakpoint object if we end up creating a deferred breakpoint.
Additionally, if we are creating a deferred bp_dprintf we can parse
the extra_string to build the printf command.
---
 gdb/Makefile.in                               |   2 +
 gdb/NEWS                                      |   4 +
 gdb/break-cond-parse.c                        | 403 ++++++++++++++++++
 gdb/break-cond-parse.h                        |  47 ++
 gdb/breakpoint.c                              | 330 ++++----------
 gdb/testsuite/gdb.base/condbreak.exp          |  20 +-
 gdb/testsuite/gdb.base/pending.exp            |  23 +-
 gdb/testsuite/gdb.linespec/explicit.exp       |   4 +-
 gdb/testsuite/gdb.mi/mi-dprintf-pending.exp   |   3 +-
 .../gdb.threads/del-pending-thread-bp-lib.c   |  22 +
 .../gdb.threads/del-pending-thread-bp.c       |  85 ++++
 .../gdb.threads/del-pending-thread-bp.exp     | 108 +++++
 12 files changed, 793 insertions(+), 258 deletions(-)
 create mode 100644 gdb/break-cond-parse.c
 create mode 100644 gdb/break-cond-parse.h
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.exp

diff --git a/gdb/Makefile.in b/gdb/Makefile.in
index 40497541880..a0f8be91bc9 100644
--- a/gdb/Makefile.in
+++ b/gdb/Makefile.in
@@ -1025,6 +1025,7 @@ COMMON_SFILES = \
 	break-catch-sig.c \
 	break-catch-syscall.c \
 	break-catch-throw.c \
+	break-cond-parse.c \
 	breakpoint.c \
 	bt-utils.c \
 	btrace.c \
@@ -1290,6 +1291,7 @@ HFILES_NO_SRCDIR = \
 	bfd-target.h \
 	bfin-tdep.h \
 	block.h \
+	break-cond-parse.h \
 	breakpoint.h \
 	bsd-kvm.h \
 	bsd-uthread.h \
diff --git a/gdb/NEWS b/gdb/NEWS
index e3c095de09e..8a7d4b25830 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -67,6 +67,10 @@
     break foo thread 1 task 1
     watch var thread 2 task 3
 
+* For breakpoints that are created in the 'pending' state, any
+  'thread' or 'task' keywords are parsed at the time the breakpoint is
+  created, rather than at the time the breakpoint becomes non-pending.
+
 * New commands
 
 maintenance print record-instruction [ N ]
diff --git a/gdb/break-cond-parse.c b/gdb/break-cond-parse.c
new file mode 100644
index 00000000000..e8da24d2643
--- /dev/null
+++ b/gdb/break-cond-parse.c
@@ -0,0 +1,403 @@
+/* Copyright (C) 2023 Free Software Foundation, Inc.
+
+   This file is part of GDB.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#include "defs.h"
+#include "gdbsupport/gdb_assert.h"
+#include "gdbsupport/selftest.h"
+#include "test-target.h"
+#include "scoped-mock-context.h"
+#include "break-cond-parse.h"
+#include "tid-parse.h"
+#include "ada-lang.h"
+
+/* When parsing tokens from a string, which direction are we parsing?
+
+   Given the following string and pointer 'ptr':
+
+     ABC DEF GHI JKL
+            ^
+           ptr
+
+   Parsing 'forward' will return the token 'GHI' and update 'ptr' to point
+   between GHI and JKL.  Parsing 'backward' will return the token 'DEF' and
+   update 'ptr' to point between ABC and DEF.
+*/
+
+enum class parse_direction
+{
+  /* Parse the next token forwards.  */
+  forward,
+
+  /* Parse the previous token backwards.  */
+  backward
+};
+
+struct token
+{
+  /* Create a new token.  START points to the first character of the new
+     token, while END points at the last character of the new token.
+
+     Neither START or END can be nullptr, and both START and END must point
+     into the same C style string (i.e. there should be no null character
+     between START and END).  END must be equal to, or greater than START,
+     that is, it is not possible to create a zero length token.  */
+
+  token (const char *start, const char *end)
+    : m_start (start),
+      m_end (end)
+  {
+    gdb_assert (m_end >= m_start);
+    gdb_assert (m_start + strlen (m_start) > m_end);
+  }
+
+  /* Return a pointer to the first character of this token.  */
+  const char *start () const
+  {
+    return m_start;
+  }
+
+  /* Return a pointer to the last character of this token.  */
+  const char *end () const
+  {
+    return m_end;
+  }
+
+  /* Return the length of the token.  */
+  size_t length () const
+  {
+    return m_end - m_start + 1;
+  }
+
+  /* Return true if this token matches STR.  If this token is shorter than
+     STR then only a partial match is performed and true will be returned
+     if the token length sub-string matches.  Otherwise, return false.  */
+  bool matches (const char *str) const
+  {
+    return strncmp (m_start, str, length ()) == 0;
+  }
+
+private:
+  /* The first character of this token.  */
+  const char *m_start;
+
+  /* The last character of this token.  */
+  const char *m_end;
+};
+
+/* Find the next token in DIRECTION from *CURR.  */
+
+static token
+find_next_token (const char **curr, parse_direction direction)
+{
+  const char *tok_start, *tok_end;
+
+  if (direction == parse_direction::forward)
+    {
+      *curr = skip_spaces (*curr);
+      tok_start = *curr;
+      *curr = skip_to_space (*curr);
+      tok_end = *curr - 1;
+    }
+  else
+    {
+      gdb_assert (direction == parse_direction::backward);
+
+      while (isspace (**curr))
+	--(*curr);
+
+      tok_end = *curr;
+
+      while (!isspace (**curr))
+	--(*curr);
+
+      tok_start = (*curr) + 1;
+    }
+
+  return token (tok_start, tok_end);
+}
+
+/* See break-cond-parse.h.  */
+
+void
+create_breakpoint_parse_arg_string
+  (const char *tok, gdb::unique_xmalloc_ptr<char> *cond_string,
+   int *thread, int *task, gdb::unique_xmalloc_ptr<char> *rest, bool *force)
+{
+  /* Set up the defaults.  */
+  cond_string->reset ();
+  rest->reset ();
+  *thread = -1;
+  *task = -1;
+  *force = false;
+
+  if (tok == nullptr)
+    return;
+
+  const char *cond_start = nullptr;
+  const char *cond_end = nullptr;
+  parse_direction direction = parse_direction::forward;
+  while (*tok != '\0')
+    {
+      /* Find the next token.  If moving backward and this token starts at
+	 the same location as the condition then we must have found the
+	 other end of the condition string -- we're done.  */
+      token t = find_next_token (&tok, direction);
+      if (direction == parse_direction::backward && t.start () <= cond_start)
+	{
+	  cond_end = t.end () + 1;
+	  break;
+	}
+
+      /* We only have a single flag option to check for.  All the other
+	 options take a value so require an additional token to be found.  */
+      if (t.length () > 0 && t.matches ("-force-condition"))
+	{
+	  *force = true;
+	  continue;
+	}
+
+      /* Maybe the first token was the last token in the string.  If this
+	 is the case then we definitely can't try to extract a value
+	 token.  This also means that the token T is meaningless.  Reset
+	 TOK to point at the start of the unknown content and break out of
+	 the loop.  We'll record the unknown part of the string outside of
+	 the scanning loop (below).  */
+      if (direction == parse_direction::forward && *tok == '\0')
+	{
+	  tok = t.start ();
+	  break;
+	}
+
+      /* As before, find the next token and, if we are scanning backwards,
+	 check that we have not reached the start of the condition string.  */
+      token v = find_next_token (&tok, direction);
+      if (direction == parse_direction::backward && v.start () <= cond_start)
+	{
+	  /* Use token T here as that must also be part of the condition
+	     string.  */
+	  cond_end = t.end () + 1;
+	  break;
+	}
+
+      /* When moving backward we will first parse the value token then the
+	 keyword token, so swap them now.  */
+      if (direction == parse_direction::backward)
+	std::swap (t, v);
+
+      /* Check for valid option in token T.  If we find a valid option then
+	 parse the value from the token V.  Except for 'if', that's handled
+	 differently.
+
+         For the 'if' token we need to capture the entire condition
+         string, so record the start of the condition string and then
+         start scanning backwards looking for the end of the condition
+         string.  */
+      if (direction == parse_direction::forward && t.length () > 0
+	  && t.matches ("if"))
+	{
+	  cond_start = v.start ();
+	  tok = tok + strlen (tok);
+	  gdb_assert (*tok == '\0');
+	  --tok;
+	  direction = parse_direction::backward;
+	  continue;
+	}
+      else if (t.length () > 0 && t.matches ("thread"))
+	{
+	  const char *tmptok;
+	  struct thread_info *thr;
+
+	  if (*thread != -1)
+	    error(_("You can specify only one thread."));
+
+	  if (*task != -1)
+	    error (_("You can specify only one of thread or task."));
+
+	  thr = parse_thread_id (v.start (), &tmptok);
+	  const char *expected_end = skip_spaces (v.end () + 1);
+	  if (tmptok != expected_end)
+	    error (_("Junk after thread keyword."));
+	  *thread = thr->global_num;
+	}
+      else if (t.length () > 0 && t.matches ("task"))
+	{
+	  char *tmptok;
+
+	  if (*task != -1)
+	    error(_("You can specify only one task."));
+
+	  if (*thread != -1)
+	    error (_("You can specify only one of thread or task."));
+
+	  *task = strtol (v.start (), &tmptok, 0);
+	  const char *expected_end = v.end () + 1;
+	  if (tmptok != expected_end)
+	    error (_("Junk after task keyword."));
+	  if (!valid_task_id (*task))
+	    error (_("Unknown task %d."), *task);
+	}
+      else
+	{
+	  /* An unknown token.  If we are scanning forward then reset TOK
+	     to point at the start of the unknown content, we record this
+	     outside of the scanning loop (below).
+
+	     If we are scanning backward then unknown content is assumed to
+	     be the other end of the condition string, obviously, this is
+	     just a heuristic, we could be looking at a mistyped command
+	     line, but this will be spotted when the condition is
+	     eventually evaluated.
+
+	     Either way, no more scanning is required after this.  */
+	  if (direction == parse_direction::forward)
+	    tok = t.start ();
+	  else
+	    {
+	      gdb_assert (direction == parse_direction::backward);
+	      cond_end = v.end () + 1;
+	    }
+	  break;
+	}
+    }
+
+  if (cond_start != nullptr)
+    {
+      /* If we found the start of a condition string then we should have
+	 switched to backward scan mode, and found the end of the condition
+	 string.  Capture the whole condition string into COND_STRING now.  */
+      gdb_assert (direction == parse_direction::backward);
+      gdb_assert (cond_end != nullptr);
+      cond_string->reset (savestring (cond_start, cond_end - cond_start));
+    }
+  else if (*tok != '\0')
+    {
+      /* If we didn't have a condition start pointer then we should still
+	 be in forward scanning mode.  If we didn't reach the end of the
+	 input string (TOK is not at the null character) then the rest of
+	 the input string is garbage that we didn't understand.
+
+	 Record the unknown content into REST.  The caller of this function
+	 will report this as an error later on.  We could report the error
+	 here, but we prefer to allow the caller to run other checks, and
+	 prioritise other errors before reporting this problem.  */
+      gdb_assert (direction == parse_direction::forward);
+      rest->reset (savestring (tok, strlen (tok)));
+    }
+}
+
+#if GDB_SELF_TEST
+
+namespace selftests {
+
+/* Run a single test of the create_breakpoint_parse_arg_string function.
+   INPUT is passed to create_breakpoint_parse_arg_string while all other
+   arguments are the expected output from
+   create_breakpoint_parse_arg_string.  */
+
+static void
+test (const char *input, const char *condition, int thread = -1,
+      int task = -1, bool force = false, const char *rest = nullptr)
+{
+  gdb::unique_xmalloc_ptr<char> extracted_condition;
+  gdb::unique_xmalloc_ptr<char> extracted_rest;
+  int extracted_thread, extracted_task;
+  bool extracted_force_condition;
+  std::string exception_msg;
+
+  try
+    {
+      create_breakpoint_parse_arg_string (input, &extracted_condition,
+					  &extracted_thread,
+					  &extracted_task, &extracted_rest,
+					  &extracted_force_condition);
+    }
+  catch (const gdb_exception_error &ex)
+    {
+      string_file buf;
+
+      exception_print (&buf, ex);
+      exception_msg = buf.release ();
+    }
+
+  if ((condition == nullptr) != (extracted_condition.get () == nullptr)
+      || (condition != nullptr
+	  && strcmp (condition, extracted_condition.get ()) != 0)
+      || (rest == nullptr) != (extracted_rest.get () == nullptr)
+      || (rest != nullptr && strcmp (rest, extracted_rest.get ()) != 0)
+      || thread != extracted_thread
+      || task != extracted_task
+      || force != extracted_force_condition
+      || !exception_msg.empty ())
+    {
+      if (run_verbose ())
+	{
+	  debug_printf ("input: '%s'\n", input);
+	  debug_printf ("condition: '%s'\n", extracted_condition.get ());
+	  debug_printf ("rest: '%s'\n", extracted_rest.get ());
+	  debug_printf ("thread: %d\n", extracted_thread);
+	  debug_printf ("task: %d\n", extracted_task);
+	  debug_printf ("forced: %s\n",
+			extracted_force_condition ? "true" : "false");
+	  debug_printf ("exception: '%s'\n", exception_msg.c_str ());
+	}
+
+      /* Report the failure.  */
+      SELF_CHECK (false);
+    }
+}
+
+/* Test the create_breakpoint_parse_arg_string function.  Just wraps
+   multiple calls to the test function above.  */
+
+static void
+create_breakpoint_parse_arg_string_tests (void)
+{
+  gdbarch *arch = current_inferior ()->gdbarch;
+  scoped_restore_current_pspace_and_thread restore;
+  scoped_mock_context<test_target_ops> mock_target (arch);
+
+  int global_thread_num = mock_target.mock_thread.global_num;
+
+  test ("  if blah  ", "blah");
+  test (" if blah thread 1", "blah", global_thread_num);
+  test (" if blah thread 1  ", "blah", global_thread_num);
+  test ("thread 1 woof", nullptr, global_thread_num, -1, false, "woof");
+  test ("thread 1 X", nullptr, global_thread_num, -1, false, "X");
+  test (" if blah thread 1 -force-condition", "blah", global_thread_num,
+	-1, true);
+  test (" -force-condition if blah thread 1", "blah", global_thread_num,
+	-1, true);
+  test (" -force-condition if blah thread 1  ", "blah", global_thread_num,
+	-1, true);
+  test ("thread 1 -force-condition if blah", "blah", global_thread_num,
+	-1, true);
+  test ("if (A::outer::func ())", "(A::outer::func ())");
+}
+
+} // namespace selftests
+#endif /* GDB_SELF_TEST */
+
+void _initialize_break_cond_parse ();
+void
+_initialize_break_cond_parse ()
+{
+#if GDB_SELF_TEST
+  selftests::register_test
+    ("create_breakpoint_parse_arg_string",
+     selftests::create_breakpoint_parse_arg_string_tests);
+#endif
+}
diff --git a/gdb/break-cond-parse.h b/gdb/break-cond-parse.h
new file mode 100644
index 00000000000..ec62b88ea92
--- /dev/null
+++ b/gdb/break-cond-parse.h
@@ -0,0 +1,47 @@
+/* Copyright (C) 2023 Free Software Foundation, Inc.
+
+   This file is part of GDB.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#if !defined (BREAK_COND_PARSE_H)
+#define BREAK_COND_PARSE_H 1
+
+/* Given TOK, a string possibly containing a condition, thread, task and
+   force-condition flag, as accepted by the 'break' command, extract the
+   condition string, thread and task numbers, and the force_condition flag,
+   then set *COND_STRING, *THREAD, *TASK, and *FORCE.
+
+   As TOK is parsed, if an unknown keyword is encountered before the 'if'
+   keyword then everything starting from the unknown keyword is placed into
+   *REST.
+
+   Both *COND and *REST are initialized to nullptr.  If no 'if' keyword is
+   found then *COND will be returned as nullptr.  If no unknown content is
+   found then *REST is returned as nullptr.
+
+   If no thread is found, *THREAD is set to -1.  If no task is found, *TASK
+   is set to -1.  If the -force-condition flag is not found then *FORCE is
+   set to false.
+
+   Due to the free-form nature that the string TOK might take (a 'thread'
+   keyword can appear before or after an 'if' condition) then we end up
+   having to check for keywords from both the start of TOK and the end of
+   TOK.  */
+
+extern void create_breakpoint_parse_arg_string
+  (const char *tok, gdb::unique_xmalloc_ptr<char> *cond_string,
+   int *thread, int *task, gdb::unique_xmalloc_ptr<char> *rest, bool *force);
+
+#endif
diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 3e52234e72d..483777ce19b 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -68,6 +68,7 @@
 #include "tid-parse.h"
 #include "cli/cli-style.h"
 #include "cli/cli-decode.h"
+#include "break-cond-parse.h"
 
 /* readline include files */
 #include "readline/tilde.h"
@@ -6212,20 +6213,7 @@ print_breakpoint_location (const breakpoint *b,
       uiout->field_stream ("at", stb);
     }
   else
-    {
-      uiout->field_string ("pending", b->locspec->to_string ());
-      /* If extra_string is available, it could be holding a condition
-	 or dprintf arguments.  In either case, make sure it is printed,
-	 too, but only for non-MI streams.  */
-      if (!uiout->is_mi_like_p () && b->extra_string != NULL)
-	{
-	  if (b->type == bp_dprintf)
-	    uiout->text (",");
-	  else
-	    uiout->text (" ");
-	  uiout->text (b->extra_string.get ());
-	}
-    }
+    uiout->field_string ("pending", b->locspec->to_string ());
 
   if (loc && is_breakpoint (b)
       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
@@ -8552,8 +8540,8 @@ code_breakpoint::code_breakpoint (struct gdbarch *gdbarch_,
       gdb_assert (extra_string != nullptr);
       update_dprintf_command_list (this);
     }
-  else if (extra_string != nullptr)
-    error (_("Garbage '%s' at end of command"), extra_string.get ());
+  else
+    gdb_assert (extra_string == nullptr);
 
   /* The order of the locations is now stable.  Set the location
      condition using the location's number.  */
@@ -8780,160 +8768,6 @@ check_fast_tracepoint_sals (struct gdbarch *gdbarch,
     }
 }
 
-/* Given TOK, a string specification of condition and thread, as
-   accepted by the 'break' command, extract the condition
-   string and thread number and set *COND_STRING and *THREAD.
-   PC identifies the context at which the condition should be parsed.
-   If no condition is found, *COND_STRING is set to NULL.
-   If no thread is found, *THREAD is set to -1.  */
-
-static void
-find_condition_and_thread (const char *tok, CORE_ADDR pc,
-			   gdb::unique_xmalloc_ptr<char> *cond_string,
-			   int *thread, int *task,
-			   gdb::unique_xmalloc_ptr<char> *rest)
-{
-  cond_string->reset ();
-  *thread = -1;
-  *task = -1;
-  rest->reset ();
-  bool force = false;
-
-  while (tok && *tok)
-    {
-      const char *end_tok;
-      int toklen;
-      const char *cond_start = NULL;
-      const char *cond_end = NULL;
-
-      tok = skip_spaces (tok);
-
-      if ((*tok == '"' || *tok == ',') && rest)
-	{
-	  rest->reset (savestring (tok, strlen (tok)));
-	  return;
-	}
-
-      end_tok = skip_to_space (tok);
-
-      toklen = end_tok - tok;
-
-      if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
-	{
-	  tok = cond_start = end_tok + 1;
-	  try
-	    {
-	      parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
-	    }
-	  catch (const gdb_exception_error &)
-	    {
-	      if (!force)
-		throw;
-	      else
-		tok = tok + strlen (tok);
-	    }
-	  cond_end = tok;
-	  cond_string->reset (savestring (cond_start, cond_end - cond_start));
-	}
-      else if (toklen >= 1 && strncmp (tok, "-force-condition", toklen) == 0)
-	{
-	  tok = tok + toklen;
-	  force = true;
-	}
-      else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
-	{
-	  const char *tmptok;
-	  struct thread_info *thr;
-
-	  if (*thread != -1)
-	    error(_("You can specify only one thread."));
-
-	  if (*task != -1)
-	    error (_("You can specify only one of thread or task."));
-
-	  tok = end_tok + 1;
-	  thr = parse_thread_id (tok, &tmptok);
-	  if (tok == tmptok)
-	    error (_("Junk after thread keyword."));
-	  *thread = thr->global_num;
-	  tok = tmptok;
-	}
-      else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
-	{
-	  char *tmptok;
-
-	  if (*task != -1)
-	    error(_("You can specify only one task."));
-
-	  if (*thread != -1)
-	    error (_("You can specify only one of thread or task."));
-
-	  tok = end_tok + 1;
-	  *task = strtol (tok, &tmptok, 0);
-	  if (tok == tmptok)
-	    error (_("Junk after task keyword."));
-	  if (!valid_task_id (*task))
-	    error (_("Unknown task %d."), *task);
-	  tok = tmptok;
-	}
-      else if (rest)
-	{
-	  rest->reset (savestring (tok, strlen (tok)));
-	  return;
-	}
-      else
-	error (_("Junk at end of arguments."));
-    }
-}
-
-/* Call 'find_condition_and_thread' for each sal in SALS until a parse
-   succeeds.  The parsed values are written to COND_STRING, THREAD,
-   TASK, and REST.  See the comment of 'find_condition_and_thread'
-   for the description of these parameters and INPUT.  */
-
-static void
-find_condition_and_thread_for_sals (const std::vector<symtab_and_line> &sals,
-				    const char *input,
-				    gdb::unique_xmalloc_ptr<char> *cond_string,
-				    int *thread, int *task,
-				    gdb::unique_xmalloc_ptr<char> *rest)
-{
-  int num_failures = 0;
-  for (auto &sal : sals)
-    {
-      gdb::unique_xmalloc_ptr<char> cond;
-      int thread_id = -1;
-      int task_id = -1;
-      gdb::unique_xmalloc_ptr<char> remaining;
-
-      /* Here we want to parse 'arg' to separate condition from thread
-	 number.  But because parsing happens in a context and the
-	 contexts of sals might be different, try each until there is
-	 success.  Finding one successful parse is sufficient for our
-	 goal.  When setting the breakpoint we'll re-parse the
-	 condition in the context of each sal.  */
-      try
-	{
-	  find_condition_and_thread (input, sal.pc, &cond, &thread_id,
-				     &task_id, &remaining);
-	  *cond_string = std::move (cond);
-	  /* At most one of thread or task can be set.  */
-	  gdb_assert (thread_id == -1 || task_id == -1);
-	  *thread = thread_id;
-	  *task = task_id;
-	  *rest = std::move (remaining);
-	  break;
-	}
-      catch (const gdb_exception_error &e)
-	{
-	  num_failures++;
-	  /* If no sal remains, do not continue.  */
-	  if (num_failures == sals.size ())
-	    throw;
-	}
-    }
-}
-
 /* Decode a static tracepoint marker spec.  */
 
 static std::vector<symtab_and_line>
@@ -9044,6 +8878,44 @@ create_breakpoint (struct gdbarch *gdbarch,
 	      || (type_wanted != bp_dprintf
 		  && (extra_string == nullptr || parse_extra)));
 
+  /* Will hold either copies of the similarly named function argument, or
+     will hold a modified version of the function argument, depending on
+     the value of PARSE_EXTRA.  */
+  gdb::unique_xmalloc_ptr<char> cond_string_copy;
+  gdb::unique_xmalloc_ptr<char> extra_string_copy;
+
+  if (parse_extra)
+    {
+      /* Parse EXTRA_STRING splitting the parts out.  */
+      create_breakpoint_parse_arg_string (extra_string, &cond_string_copy,
+					  &thread, &task, &extra_string_copy,
+					  &force_condition);
+
+      /* We could check that EXTRA_STRING_COPY is empty at this point -- it
+	 should be, as we only get here for things that are not bp_dprintf,
+	 however, we prefer to give the location spec parser a chance to
+	 run first, this means the user will get errors about invalid
+	 location spec instead of an error about garbage at the end of the
+	 command line.
+
+	 We still do the EXTRA_STRING_COPY is empty check, just later in
+	 this function.  */
+
+      gdb_assert (thread == -1 || thread > 0);
+      gdb_assert (task == -1 || task > 0);
+    }
+  else
+    {
+      if (cond_string != nullptr)
+	cond_string_copy.reset (xstrdup (cond_string));
+      if (extra_string != nullptr)
+	extra_string_copy.reset (xstrdup (extra_string));
+    }
+
+  /* Clear these.  Updated values are now held in the *_copy locals.  */
+  cond_string = nullptr;
+  extra_string = nullptr;
+
   try
     {
       ops->create_sals_from_location_spec (locspec, &canonical);
@@ -9079,6 +8951,13 @@ create_breakpoint (struct gdbarch *gdbarch,
 	throw;
     }
 
+  /* The only bp_dprintf should have anything in EXTRA_STRING_COPY by this
+     point.  For all other breakpoints this indicates an error.  We could
+     place this check earlier in the function, but we prefer to see errors
+     from the location spec parser before we see this error message.  */
+  if (type_wanted != bp_dprintf && extra_string_copy.get () != nullptr)
+    error (_("Garbage '%s' at end of command"), extra_string_copy.get ());
+
   if (!pending && canonical.lsals.empty ())
     return 0;
 
@@ -9102,62 +8981,31 @@ create_breakpoint (struct gdbarch *gdbarch,
      breakpoint.  */
   if (!pending)
     {
-      gdb::unique_xmalloc_ptr<char> cond_string_copy;
-      gdb::unique_xmalloc_ptr<char> extra_string_copy;
-
-      if (parse_extra)
+      /* Check the validity of the condition.  We should error out if the
+	 condition is invalid at all of the locations and if it is not
+	 forced.  In the PARSE_EXTRA case above, this check is done when
+	 parsing the EXTRA_STRING.  */
+      if (cond_string_copy.get () != nullptr && !force_condition)
 	{
-	  gdb_assert (type_wanted != bp_dprintf);
-
-	  gdb::unique_xmalloc_ptr<char> rest;
-	  gdb::unique_xmalloc_ptr<char> cond;
-
+	  int num_failures = 0;
 	  const linespec_sals &lsal = canonical.lsals[0];
-
-	  find_condition_and_thread_for_sals (lsal.sals, extra_string,
-					      &cond, &thread, &task, &rest);
-
-	  if (rest.get () != nullptr && *(rest.get ()) != '\0')
-	    error (_("Garbage '%s' at end of command"), rest.get ());
-
-	  cond_string_copy = std::move (cond);
-	  extra_string_copy = std::move (rest);
-	}
-      else
-	{
-	  /* Check the validity of the condition.  We should error out
-	     if the condition is invalid at all of the locations and
-	     if it is not forced.  In the PARSE_EXTRA case above, this
-	     check is done when parsing the EXTRA_STRING.  */
-	  if (cond_string != nullptr && !force_condition)
+	  for (const auto &sal : lsal.sals)
 	    {
-	      int num_failures = 0;
-	      const linespec_sals &lsal = canonical.lsals[0];
-	      for (const auto &sal : lsal.sals)
+	      const char *cond = cond_string_copy.get ();
+	      try
 		{
-		  const char *cond = cond_string;
-		  try
-		    {
-		      parse_exp_1 (&cond, sal.pc, block_for_pc (sal.pc), 0);
-		      /* One success is sufficient to keep going.  */
-		      break;
-		    }
-		  catch (const gdb_exception_error &)
-		    {
-		      num_failures++;
-		      /* If this is the last sal, error out.  */
-		      if (num_failures == lsal.sals.size ())
-			throw;
-		    }
+		  parse_exp_1 (&cond, sal.pc, block_for_pc (sal.pc), 0);
+		  /* One success is sufficient to keep going.  */
+		  break;
+		}
+	      catch (const gdb_exception_error &)
+		{
+		  num_failures++;
+		  /* If this is the last sal, error out.  */
+		  if (num_failures == lsal.sals.size ())
+		    throw;
 		}
 	    }
-
-	  /* Create a private copy of condition string.  */
-	  if (cond_string)
-	    cond_string_copy.reset (xstrdup (cond_string));
-	  /* Create a private copy of any extra string.  */
-	  if (extra_string)
-	    extra_string_copy.reset (xstrdup (extra_string));
 	}
 
       ops->create_breakpoints_sal (gdbarch, &canonical,
@@ -9174,21 +9022,15 @@ create_breakpoint (struct gdbarch *gdbarch,
 								 type_wanted);
       b->locspec = locspec->clone ();
 
-      if (parse_extra)
-	b->cond_string = NULL;
-      else
-	{
-	  /* Create a private copy of condition string.  */
-	  b->cond_string.reset (cond_string != NULL
-				? xstrdup (cond_string)
-				: NULL);
-	  b->thread = thread;
-	}
+      /* Create a private copy of condition string.  */
+      b->cond_string = std::move (cond_string_copy);
+
+      b->thread = thread;
+      b->task = task;
 
       /* Create a private copy of any extra string.  */
-      b->extra_string.reset (extra_string != NULL
-			     ? xstrdup (extra_string)
-			     : NULL);
+      b->extra_string = std::move (extra_string_copy);
+
       b->ignore_count = ignore_count;
       b->disposition = tempflag ? disp_del : disp_donttouch;
       b->condition_not_parsed = 1;
@@ -9197,9 +9039,12 @@ create_breakpoint (struct gdbarch *gdbarch,
 	   && type_wanted != bp_hardware_breakpoint) || thread != -1)
 	b->pspace = current_program_space;
 
+      if (type_wanted == bp_dprintf)
+	update_dprintf_command_list (b.get ());
+
       install_breakpoint (internal, std::move (b), 0);
     }
-  
+
   if (canonical.lsals.size () > 1)
     {
       warning (_("Multiple breakpoints were set.\nUse the "
@@ -12915,23 +12760,6 @@ code_breakpoint::location_spec_to_sals (location_spec *locspec,
     {
       for (auto &sal : sals)
 	resolve_sal_pc (&sal);
-      if (condition_not_parsed && extra_string != NULL)
-	{
-	  gdb::unique_xmalloc_ptr<char> local_cond, local_extra;
-	  int local_thread, local_task;
-
-	  find_condition_and_thread_for_sals (sals, extra_string.get (),
-					      &local_cond, &local_thread,
-					      &local_task, &local_extra);
-	  gdb_assert (cond_string == nullptr);
-	  if (local_cond != nullptr)
-	    cond_string = std::move (local_cond);
-	  thread = local_thread;
-	  task = local_task;
-	  if (local_extra != nullptr)
-	    extra_string = std::move (local_extra);
-	  condition_not_parsed = 0;
-	}
 
       if (type == bp_static_tracepoint)
 	sals[0] = update_static_tracepoint (this, sals[0]);
diff --git a/gdb/testsuite/gdb.base/condbreak.exp b/gdb/testsuite/gdb.base/condbreak.exp
index a5b2a28701b..50ae82c3f32 100644
--- a/gdb/testsuite/gdb.base/condbreak.exp
+++ b/gdb/testsuite/gdb.base/condbreak.exp
@@ -179,6 +179,10 @@ gdb_test "break -q main if (1==1) thread 999" \
     "Unknown thread 999\\."
 gdb_test "break -q main thread 999 if (1==1)" \
     "Unknown thread 999\\."
+gdb_test "break -q main if (1==1) thread 999 -force-condition" \
+    "Unknown thread 999\\."
+gdb_test "break -q main thread 999 if (1==1) -force-condition" \
+    "Unknown thread 999\\."
 
 # Verify that both if and thread can be distinguished from a breakpoint
 # address expression.
@@ -186,20 +190,34 @@ gdb_test "break *main if (1==1) thread 999" \
     "Unknown thread 999\\."
 gdb_test "break *main thread 999 if (1==1)" \
     "Unknown thread 999\\."
+gdb_test "break *main if (1==1) thread 999 -force-condition" \
+    "Unknown thread 999\\."
+gdb_test "break *main thread 999 if (1==1) -force-condition" \
+    "Unknown thread 999\\."
 
 # Similarly for task.
 gdb_test "break *main if (1==1) task 999" \
     "Unknown task 999\\."
 gdb_test "break *main task 999 if (1==1)" \
     "Unknown task 999\\."
+gdb_test "break *main if (1==1) task 999 -force-condition" \
+    "Unknown task 999\\."
+gdb_test "break *main task 999 if (1==1) -force-condition" \
+    "Unknown task 999\\."
 
-# GDB accepts abbreviations for "thread" and "task".
+# GDB accepts abbreviations for "thread" and "task" and "-force-condition"
 gdb_test "break *main if (1==1) t 999" \
     "Unknown thread 999\\."
 gdb_test "break *main if (1==1) th 999" \
     "Unknown thread 999\\."
 gdb_test "break *main if (1==1) ta 999" \
     "Unknown task 999\\."
+gdb_test "break *main if (1==1) t 999 -force" \
+    "Unknown thread 999\\."
+gdb_test "break *main if (1==1) th 999 -force" \
+    "Unknown thread 999\\."
+gdb_test "break *main if (1==1) ta 999 -force" \
+    "Unknown task 999\\."
 
 set test "run until breakpoint at marker3"
 gdb_test_multiple "continue" $test {
diff --git a/gdb/testsuite/gdb.base/pending.exp b/gdb/testsuite/gdb.base/pending.exp
index d7d3735000a..645f63bdb16 100644
--- a/gdb/testsuite/gdb.base/pending.exp
+++ b/gdb/testsuite/gdb.base/pending.exp
@@ -170,7 +170,8 @@ gdb_test "info break" \
 \[\t \]+stop only if k == 1.*
 \[\t \]+print k.*
 \[0-9\]+\[\t \]+breakpoint     keep y.* in main at .*$srcfile:$mainline.*
-\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc if x > 3.*" \
+\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc.*
+\\s+stop only if x > 3.*" \
 "multiple pending breakpoints"
 
 
@@ -195,8 +196,10 @@ gdb_test "info break" \
 \[\t \]+stop only if k == 1.*
 \[\t \]+print k.*
 \[0-9\]+\[\t \]+breakpoint     keep y.* in main at .*$srcfile:$mainline.*
-\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc if x > 3.*
-\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp3_loc.*ignore next 2 hits.*" \
+\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc.*
+\\s+stop only if x > 3.*
+\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp3_loc.*
+\\s+ignore next 2 hits.*" \
 "multiple pending breakpoints 2"
 
 #
@@ -267,3 +270,17 @@ gdb_test "info break" \
 \[0-9\]+\[\t \]+breakpoint     keep y.* in main at .*$srcfile:$mainline.*
 \[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*imaginary.*" \
 "verify pending breakpoint after restart"
+
+# Test GDB's parsing of pending breakpoint thread and condition.
+
+gdb_test_no_output "set breakpoint pending on"
+gdb_test "break foo if (unknown_var && another_unknown_var) thread 1" \
+    "Breakpoint $decimal \\(foo\\) pending\\."
+set bpnum [get_integer_valueof "\$bpnum" "*INVALID" \
+	       "get number for foo breakpoint"]
+gdb_test "info breakpoints $bpnum" \
+    [multi_line \
+	 "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	 "\\s+stop only if \\(unknown_var && another_unknown_var\\)" \
+	 "\\s+stop only in thread 1"] \
+    "check pending breakpoint on foo"
diff --git a/gdb/testsuite/gdb.linespec/explicit.exp b/gdb/testsuite/gdb.linespec/explicit.exp
index b08d65953d2..7c8b2475881 100644
--- a/gdb/testsuite/gdb.linespec/explicit.exp
+++ b/gdb/testsuite/gdb.linespec/explicit.exp
@@ -574,7 +574,7 @@ namespace eval $testfile {
 	      allow-pending]} {
 	fail "set $tst"
     } else {
-	gdb_test "info break" ".*PENDING.*myfunction if foofoofoo == 1.*" $tst
+	gdb_test "info break" ".*PENDING.*myfunction\r\n\\s+stop only if foofoofoo == 1.*" $tst
     }
 
     gdb_exit
@@ -585,7 +585,7 @@ namespace eval $testfile {
 	      allow-pending]} {
 	fail "set $tst"
     } else {
-	gdb_test "info break" ".*PENDING.*myfunction if arg == 0" $tst
+	gdb_test "info break" ".*PENDING.*myfunction\r\n\\s+stop only if arg == 0" $tst
 
 	gdb_load [standard_output_file $exefile]
 	gdb_test "info break" \
diff --git a/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp b/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp
index 28f52938aeb..bb9987a5572 100644
--- a/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp
+++ b/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp
@@ -50,7 +50,8 @@ set bp_location1 [gdb_get_line_number "set breakpoint 1 here"]
 # Set pending dprintf via MI.
 set bp [mi_make_breakpoint_pending -number "1" -type "dprintf" \
 	    -disp "keep" -enabled "y" -pending "pendfunc1" \
-	    -original-location "pendfunc1"]
+	    -original-location "pendfunc1" \
+	    -script {\["printf \\\"hello\\\""\]}]
 mi_gdb_test "-dprintf-insert -f pendfunc1 \"hello\"" \
     ".*\\^done,$bp" "mi set dprintf"
 
diff --git a/gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c b/gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
new file mode 100644
index 00000000000..15d1b9833dd
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
@@ -0,0 +1,22 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+int global_var = 0;
+
+void
+foo (int arg)
+{
+  global_var = arg;
+}
diff --git a/gdb/testsuite/gdb.threads/del-pending-thread-bp.c b/gdb/testsuite/gdb.threads/del-pending-thread-bp.c
new file mode 100644
index 00000000000..938e05bc4d7
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/del-pending-thread-bp.c
@@ -0,0 +1,85 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#include <dlfcn.h>
+#include <pthread.h>
+#include <stdlib.h>
+
+pthread_barrier_t barrier;
+
+static void
+barrier_wait (pthread_barrier_t *b)
+{
+  int res = pthread_barrier_wait (b);
+  if (res != 0 && res != PTHREAD_BARRIER_SERIAL_THREAD)
+    abort ();
+}
+
+static void *
+thread_worker (void *arg)
+{
+  barrier_wait (&barrier);
+  return NULL;
+}
+
+void
+breakpt ()
+{
+  /* Nothing.  */
+}
+
+int
+main (void)
+{
+  void *handle;
+  void (*func)(int);
+  pthread_t thread;
+
+  if (pthread_barrier_init (&barrier, NULL, 2) != 0)
+    abort ();
+
+  if (pthread_create (&thread, NULL, thread_worker, NULL) != 0)
+    abort ();
+
+  breakpt ();
+
+  /* Allow the worker thread to complete.  */
+  barrier_wait (&barrier);
+
+  if (pthread_join (thread, NULL) != 0)
+    abort ();
+
+  breakpt ();
+
+  /* Now load the shared library.  */
+  handle = dlopen (SHLIB_NAME, RTLD_LAZY);
+  if (handle == NULL)
+    abort ();
+
+  /* Find the function symbol.  */
+  func = (void (*)(int)) dlsym (handle, "foo");
+
+  /* Call the library function.  */
+  func (1);
+
+  /* Unload the shared library.  */
+  if (dlclose (handle) != 0)
+    abort ();
+
+  breakpt ();
+
+  return 0;
+}
+
diff --git a/gdb/testsuite/gdb.threads/del-pending-thread-bp.exp b/gdb/testsuite/gdb.threads/del-pending-thread-bp.exp
new file mode 100644
index 00000000000..4ed05eaa42d
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/del-pending-thread-bp.exp
@@ -0,0 +1,108 @@
+# Copyright 2023 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+# This test checks that pending thread-specific breakpoints are
+# correctly deleted when the thread the breakpoint is for goes out of
+# scope.
+#
+# We also check that we can't create a pending thread-specific
+# breakpoint for a non-existent thread.
+
+require allow_shlib_tests
+
+standard_testfile
+
+set libname $testfile-lib
+set srcfile_lib $srcdir/$subdir/$libname.c
+set binfile_lib [standard_output_file $libname.so]
+
+if { [gdb_compile_shlib $srcfile_lib $binfile_lib {}] != "" } {
+    untested "failed to compile shared library 1"
+    return -1
+}
+
+set binfile_lib_target [gdb_download_shlib $binfile_lib]
+
+if { [prepare_for_testing "failed to prepare" $testfile $srcfile \
+	  [list debug \
+	       additional_flags=-DSHLIB_NAME=\"$binfile_lib_target\" \
+	       shlib_load pthreads]] } {
+    return -1
+}
+
+gdb_locate_shlib $binfile_lib
+
+if ![runto_main] {
+    return 0
+}
+
+# Run until we have two threads.
+gdb_breakpoint "breakpt"
+gdb_continue_to_breakpoint "first breakpt call"
+
+# Confirm that we have a thread '2'.
+gdb_test "info threads" "\r\n\\s+2\\s+\[^\r\n\]+"
+
+# Create a pending, thread-specific, breakpoint on 'foo'.
+gdb_breakpoint "foo thread 2" allow-pending
+set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+	       "get breakpoint number"]
+
+# Check we can't create a pending thread-specific breakpoint for a
+# non-existent thread.
+gdb_test "with breakpoint pending on -- break foo thread 99" \
+    "Unknown thread 99\\."
+
+# Continue to 'breakpt' again.  Don't use gdb_continue_to_breakpoint
+# as we are looking for the thread exited and breakpoint deleted
+# messages.
+set output [list "Continuing\\."]
+
+if {!([target_info exists gdb_protocol]
+      && ([target_info gdb_protocol] == "remote"
+	  || [target_info gdb_protocol] == "extended-remote"))} {
+    # Due to bug PR gdb/30129 we don't see the thread exited messages
+    # for remote targets.  When this bit of this test can be cleaned
+    # up.
+    lappend output "\\\[Thread \[^\r\n\]+ exited\\\]"
+}
+
+lappend output "Thread-specific breakpoint $bpnum deleted - thread 2 no longer in the thread list\\." \
+    "" \
+    "Thread 1 \[^\r\n\]+, breakpt \\(\\) at \[^\r\n\]+" \
+    "$decimal\\s+\[^\r\n\]+"
+
+gdb_test "continue" \
+    [multi_line {*}$output] \
+    "second breakpt call"
+
+# Confirm breakpoint has been deleted.
+gdb_test "info breakpoints $bpnum" \
+    "No breakpoint or watchpoint matching '$bpnum'\\."
+
+# Continue again.  This will pass through 'foo'.  We should not stop
+# in 'foo', the breakpoint has been deleted.  We should next stop in
+# breakpt again.
+gdb_test "continue" \
+    [multi_line \
+	 "Continuing\\." \
+	 "" \
+	 "Thread 1 \[^\r\n\]+ hit Breakpoint $decimal, breakpt \\(\\) at \[^\r\n\]+" \
+	 "$decimal\\s+\[^\r\n\]+"] \
+    "third breakpt call"
+gdb_test "bt 1" \
+    [multi_line \
+	 "#0\\s+breakpt \\(\\) at \[^\r\n\]+" \
+	 "\\(More stack frames follow\\.\\.\\.\\)"]
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCH 7/9] gdb: remove breakpoint_re_set_one
  2023-04-28 23:35 [PATCH 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
                   ` (5 preceding siblings ...)
  2023-04-28 23:35 ` [PATCH 6/9] gdb: parse pending breakpoint thread/task immediately Andrew Burgess
@ 2023-04-28 23:35 ` Andrew Burgess
  2023-04-28 23:35 ` [PATCH 8/9] gdb: remove tracepoint_probe_create_sals_from_location_spec Andrew Burgess
                   ` (2 subsequent siblings)
  9 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-04-28 23:35 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

During a later patch I wanted to reset a single breakpoint, so I
called breakpoint_re_set_one.  However, this is not the right thing to
do.  If we look at breakpoint_re_set then we see that there's a whole
bunch of state that needs to be preserved prior to calling
breakpoint_re_set_one, and after calling breakpoint_re_set_one we
still need to call update_global_location_list.

I could just update the comment on breakpoint_re_set_one to make it
clearer how the function should be used -- or more likely to warn that
the function should only be used as a helper from breakpoint_re_set.

However, breakpoint_re_set_one is only 3 lines long.  So I figure it
might actually be easier to just fold breakpoint_re_set_one into
breakpoint_re_set, then there's no risk of accidentally calling
breakpoint_re_set_one when we shouldn't.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c | 26 ++++++++------------------
 1 file changed, 8 insertions(+), 18 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 483777ce19b..e6e8fcd485e 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -12811,17 +12811,6 @@ create_sals_from_location_spec_default (location_spec *locspec,
   parse_breakpoint_sals (locspec, canonical);
 }
 
-/* Reset a breakpoint.  */
-
-static void
-breakpoint_re_set_one (breakpoint *b)
-{
-  input_radix = b->input_radix;
-  set_language (b->language);
-
-  b->re_set ();
-}
-
 /* Re-set breakpoint locations for the current program space.
    Locations bound to other program spaces are left untouched.  */
 
@@ -12833,12 +12822,11 @@ breakpoint_re_set (void)
     scoped_restore save_input_radix = make_scoped_restore (&input_radix);
     scoped_restore_current_pspace_and_thread restore_pspace_thread;
 
-    /* breakpoint_re_set_one sets the current_language to the language
-       of the breakpoint it is resetting (see prepare_re_set_context)
-       before re-evaluating the breakpoint's location.  This change can
-       unfortunately get undone by accident if the language_mode is set
-       to auto, and we either switch frames, or more likely in this context,
-       we select the current frame.
+    /* To ::re_set each breakpoint we set the current_language to the
+       language of the breakpoint before re-evaluating the breakpoint's
+       location.  This change can unfortunately get undone by accident if
+       the language_mode is set to auto, and we either switch frames, or
+       more likely in this context, we select the current frame.
 
        We prevent this by temporarily turning the language_mode to
        language_mode_manual.  We restore it once all breakpoints
@@ -12855,7 +12843,9 @@ breakpoint_re_set (void)
       {
 	try
 	  {
-	    breakpoint_re_set_one (b);
+	    input_radix = b->input_radix;
+	    set_language (b->language);
+	    b->re_set ();
 	  }
 	catch (const gdb_exception &ex)
 	  {
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCH 8/9] gdb: remove tracepoint_probe_create_sals_from_location_spec
  2023-04-28 23:35 [PATCH 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
                   ` (6 preceding siblings ...)
  2023-04-28 23:35 ` [PATCH 7/9] gdb: remove breakpoint_re_set_one Andrew Burgess
@ 2023-04-28 23:35 ` Andrew Burgess
  2023-04-28 23:35 ` [PATCH 9/9] gdb: only insert thread-specific breakpoints in the relevant inferior Andrew Burgess
  2023-05-15 19:27 ` [PATCHv2 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
  9 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-04-28 23:35 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

The tracepoint_probe_create_sals_from_location_spec function just
forwards all its arguments to
bkpt_probe_create_sals_from_location_spec, and is only used in one
place.

Lets delete tracepoint_probe_create_sals_from_location_spec and
replace it with bkpt_probe_create_sals_from_location_spec.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c | 19 +++----------------
 1 file changed, 3 insertions(+), 16 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index e6e8fcd485e..4b37a217972 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -219,9 +219,6 @@ static bool strace_marker_p (struct breakpoint *b);
 static void bkpt_probe_create_sals_from_location_spec
      (location_spec *locspec,
       struct linespec_result *canonical);
-static void tracepoint_probe_create_sals_from_location_spec
-     (location_spec *locspec,
-      struct linespec_result *canonical);
 
 const struct breakpoint_ops code_breakpoint_ops =
 {
@@ -236,10 +233,11 @@ static const struct breakpoint_ops bkpt_probe_breakpoint_ops =
   create_breakpoints_sal,
 };
 
-/* Tracepoints set on probes.  */
+/* Tracepoints set on probes.  We use the same methods as for breakpoints
+   on probes.  */
 static const struct breakpoint_ops tracepoint_probe_breakpoint_ops =
 {
-  tracepoint_probe_create_sals_from_location_spec,
+  bkpt_probe_create_sals_from_location_spec,
   create_breakpoints_sal,
 };
 
@@ -12006,17 +12004,6 @@ tracepoint::print_recreate (struct ui_file *fp) const
     gdb_printf (fp, "  passcount %d\n", pass_count);
 }
 
-/* Virtual table for tracepoints on static probes.  */
-
-static void
-tracepoint_probe_create_sals_from_location_spec
-  (location_spec *locspec,
-   struct linespec_result *canonical)
-{
-  /* We use the same method for breakpoint on probes.  */
-  bkpt_probe_create_sals_from_location_spec (locspec, canonical);
-}
-
 void
 dprintf_breakpoint::re_set ()
 {
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCH 9/9] gdb: only insert thread-specific breakpoints in the relevant inferior
  2023-04-28 23:35 [PATCH 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
                   ` (7 preceding siblings ...)
  2023-04-28 23:35 ` [PATCH 8/9] gdb: remove tracepoint_probe_create_sals_from_location_spec Andrew Burgess
@ 2023-04-28 23:35 ` Andrew Burgess
  2023-04-29  6:02   ` Eli Zaretskii
  2023-05-15 19:27 ` [PATCHv2 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
  9 siblings, 1 reply; 138+ messages in thread
From: Andrew Burgess @ 2023-04-28 23:35 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

This commit updates GDB so that thread-specific breakpoints are only
inserted into the inferior that contains the thread we are interested
in.

Actually, as breakpoints are placed in program spaces, we insert the
breakpoint in any inferior that shares a program space with the
inferior containing the thread we are interested in.  But as far as
most users are concerned this really means the one inferior.

In terms of implementation, getting this basically working is easy
enough, now that a breakpoint's thread field is setup prior to GDB
looking for locations, we can easily use the thread to find a suitable
program_space and pass this to as a filter when creating the sals.

Or we could if breakpoint_ops::create_sals_from_location_spec allowed
us to pass in a filter program_space.

So, this commit extends breakpoint_ops::create_sals_from_location_spec
to take a program_space argument, and uses this to filter the set of
returned sals.  This accounts for about half the change in this patch.

The second set of changes starts from breakpoint_set_thread, this is
called when the thread for a thread-specific breakpoint changes,
e.g. from the Python API.

Previously this call would never result in the locations of a
breakpoint changing, after all, locations were inserted in every
program space, and we just use the thread field to decide when we
should stop.  Now though, changing a breakpoint's thread can mean we
need to figure out a new set of breakpoint locations.

To support this I've added a new breakpoint_re_set_one function, which
is like breakpoint_re_set, but takes a single breakpoint, and just
updates the locations for that one breakpoint.  We only need to call
this function if the program_space in which a breakpoint's thread is
running actually changes.  If the program_space does change then we
call the new breakpoint_re_set_one function passing in the
program_space which should be used to filter the locations (or nullptr
to indicate we should set locations in all program spaces).  This
filter program_space needs to propagate down to all the re_set
methods, this accounts for the remaining half of the changes in this
patch.

There were a couple of existing tests that created thread-specific
breakpoints and then checked the 'info breakpoints' output, these
needed updating.  These were:

  gdb.mi/user-selected-context-sync.exp
  gdb.multi/bp-thread-specific.exp
  gdb.multi/multi-target-continue.exp
  gdb.multi/multi-target-ping-pong-next.exp
  gdb.multi/tids.exp

I've also added some additional tests to:

  gdb.multi/pending-bp.exp

I've updated the documentation and added a NEWS entry.
---
 gdb/NEWS                                      |   7 +
 gdb/ada-lang.c                                |   6 +-
 gdb/break-catch-throw.c                       |   6 +-
 gdb/breakpoint.c                              | 236 ++++++++++++++----
 gdb/breakpoint.h                              |  26 +-
 .../gdb.mi/user-selected-context-sync.exp     |   2 +-
 .../gdb.multi/bp-thread-specific.exp          |   7 +-
 .../gdb.multi/multi-target-continue.exp       |   2 +-
 .../gdb.multi/multi-target-ping-pong-next.exp |   4 +-
 gdb/testsuite/gdb.multi/pending-bp.exp        | 206 +++++++++++++++
 gdb/testsuite/gdb.multi/tids.exp              |   6 +-
 11 files changed, 427 insertions(+), 81 deletions(-)

diff --git a/gdb/NEWS b/gdb/NEWS
index 8a7d4b25830..1cfa8102c6d 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -71,6 +71,13 @@
   'thread' or 'task' keywords are parsed at the time the breakpoint is
   created, rather than at the time the breakpoint becomes non-pending.
 
+* Thread-specific breakpoints are only inserted into the program space
+  in which the thread of interest is running.  In most cases program
+  spaces are unique for each inferior, so this means that
+  thread-specific breakpoints will usually only be inserted for the
+  inferior containing the thread of interest.  The breakpoint will
+  be hit no less than before.
+
 * New commands
 
 maintenance print record-instruction [ N ]
diff --git a/gdb/ada-lang.c b/gdb/ada-lang.c
index 3a9f554ce4c..1057d7f7aa6 100644
--- a/gdb/ada-lang.c
+++ b/gdb/ada-lang.c
@@ -12162,7 +12162,7 @@ struct ada_catchpoint : public code_breakpoint
   }
 
   struct bp_location *allocate_location () override;
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   void check_status (struct bpstat *bs) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   bool print_one (bp_location **) const override;
@@ -12256,11 +12256,11 @@ ada_catchpoint::allocate_location ()
    catchpoint kinds.  */
 
 void
-ada_catchpoint::re_set ()
+ada_catchpoint::re_set (program_space *pspace)
 {
   /* Call the base class's method.  This updates the catchpoint's
      locations.  */
-  this->code_breakpoint::re_set ();
+  this->code_breakpoint::re_set (pspace);
 
   /* Reparse the exception conditional expressions.  One for each
      location.  */
diff --git a/gdb/break-catch-throw.c b/gdb/break-catch-throw.c
index 457446efbc6..854ca6a624c 100644
--- a/gdb/break-catch-throw.c
+++ b/gdb/break-catch-throw.c
@@ -82,10 +82,10 @@ struct exception_catchpoint : public code_breakpoint
 				     _("invalid type-matching regexp")))
   {
     pspace = current_program_space;
-    re_set ();
+    re_set (pspace);
   }
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   bool print_one (bp_location **) const override;
   void print_mention () const override;
@@ -200,7 +200,7 @@ exception_catchpoint::check_status (struct bpstat *bs)
 /* Implement the 're_set' method.  */
 
 void
-exception_catchpoint::re_set ()
+exception_catchpoint::re_set (program_space *pspace)
 {
   std::vector<symtab_and_line> sals;
   struct program_space *filter_pspace = current_program_space;
diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 4b37a217972..b584cc92883 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -88,9 +88,12 @@
 static void map_breakpoint_numbers (const char *,
 				    gdb::function_view<void (breakpoint *)>);
 
-static void
-  create_sals_from_location_spec_default (location_spec *locspec,
-					  linespec_result *canonical);
+static void parse_breakpoint_sals (location_spec *locspec,
+				   linespec_result *canonical,
+				   program_space *search_pspace);
+
+static void breakpoint_re_set_one (breakpoint *b,
+				   program_space *filter_pspace);
 
 static void create_breakpoints_sal (struct gdbarch *,
 				    struct linespec_result *,
@@ -218,11 +221,12 @@ static bool strace_marker_p (struct breakpoint *b);
 
 static void bkpt_probe_create_sals_from_location_spec
      (location_spec *locspec,
-      struct linespec_result *canonical);
+      struct linespec_result *canonical,
+      struct program_space *search_pspace);
 
 const struct breakpoint_ops code_breakpoint_ops =
 {
-  create_sals_from_location_spec_default,
+  parse_breakpoint_sals,
   create_breakpoints_sal,
 };
 
@@ -287,7 +291,7 @@ struct internal_breakpoint : public code_breakpoint
     disposition = disp_donttouch;
   }
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   void check_status (struct bpstat *bs) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   void print_mention () const override;
@@ -321,7 +325,7 @@ struct momentary_breakpoint : public code_breakpoint
     thread = thread_;
   }
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   void check_status (struct bpstat *bs) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   void print_mention () const override;
@@ -332,7 +336,7 @@ struct dprintf_breakpoint : public ordinary_breakpoint
 {
   using ordinary_breakpoint::ordinary_breakpoint;
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   int breakpoint_hit (const struct bp_location *bl,
 		      const address_space *aspace,
 		      CORE_ADDR bp_addr,
@@ -1467,7 +1471,36 @@ breakpoint_set_thread (struct breakpoint *b, int thread)
 
   b->thread = thread;
   if (old_thread != thread)
-    gdb::observers::breakpoint_modified.notify (b);
+    {
+      /* If THREAD is in a different program_space than OLD_THREAD, or the
+	 breakpoint has switched to or from being thread-specific, then we
+	 need to re-set the locations of this breakpoint.  First, figure
+	 out the program_space for the old and new threads, use a value of
+	 nullptr to indicate the breakpoint is in all program spaces.  */
+      program_space *old_pspace = nullptr;
+      if (old_thread != -1)
+	{
+	  struct thread_info *thr = find_thread_global_id (old_thread);
+	  gdb_assert (thr != nullptr);
+	  old_pspace = thr->inf->pspace;
+	}
+
+      program_space *new_pspace = nullptr;
+      if (thread != -1)
+	{
+	  struct thread_info *thr = find_thread_global_id (thread);
+	  gdb_assert (thr != nullptr);
+	  new_pspace = thr->inf->pspace;
+	}
+
+      /* If the program space has changed for this breakpoint, then
+	 re-evaluate it's locations.  */
+      if (old_pspace != new_pspace)
+	breakpoint_re_set_one (b, new_pspace);
+
+      /* Let others know the breakpoint has changed.  */
+      gdb::observers::breakpoint_modified.notify (b);
+    }
 }
 
 /* See breakpoint.h.  */
@@ -8652,7 +8685,8 @@ create_breakpoints_sal (struct gdbarch *gdbarch,
 
 static void
 parse_breakpoint_sals (location_spec *locspec,
-		       struct linespec_result *canonical)
+		       struct linespec_result *canonical,
+		       struct program_space *search_pspace)
 {
   struct symtab_and_line cursal;
 
@@ -8716,7 +8750,7 @@ parse_breakpoint_sals (location_spec *locspec,
 	      && strchr ("+-", spec[0]) != NULL
 	      && spec[1] != '['))
 	{
-	  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, NULL,
+	  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, search_pspace,
 			    get_last_displayed_symtab (),
 			    get_last_displayed_line (),
 			    canonical, NULL, NULL);
@@ -8724,7 +8758,7 @@ parse_breakpoint_sals (location_spec *locspec,
 	}
     }
 
-  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, NULL,
+  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, search_pspace,
 		    cursal.symtab, cursal.line, canonical, NULL, NULL);
 }
 
@@ -8823,6 +8857,24 @@ breakpoint_ops_for_location_spec_type (enum location_spec_type locspec_type,
     }
 }
 
+/* Return the program space to use as a filter when searching for locations
+   of a breakpoint specific to THREAD.  If THREAD is -1, meaning all
+   threads, then this function returns nullptr, indicating no program space
+   filtering should be performed.  Otherwise, this function returns the
+   program space for the inferior that contains THREAD.  */
+
+static struct program_space *
+find_program_space_for_global_thread_id (int thread)
+{
+  if (thread == -1)
+    return nullptr;
+
+  struct thread_info *thr = find_thread_global_id (thread);
+  gdb_assert (thr != nullptr);
+  gdb_assert (thr->inf != nullptr);
+  return thr->inf->pspace;
+}
+
 /* See breakpoint.h.  */
 
 const struct breakpoint_ops *
@@ -8916,7 +8968,10 @@ create_breakpoint (struct gdbarch *gdbarch,
 
   try
     {
-      ops->create_sals_from_location_spec (locspec, &canonical);
+      struct program_space *search_pspace
+	= find_program_space_for_global_thread_id (thread);
+      ops->create_sals_from_location_spec (locspec, &canonical,
+					   search_pspace);
     }
   catch (const gdb_exception_error &e)
     {
@@ -9392,7 +9447,7 @@ break_range_command (const char *arg, int from_tty)
   arg_start = arg;
   location_spec_up start_locspec
     = string_to_location_spec (&arg, current_language);
-  parse_breakpoint_sals (start_locspec.get (), &canonical_start);
+  parse_breakpoint_sals (start_locspec.get (), &canonical_start, nullptr);
 
   if (arg[0] != ',')
     error (_("Too few arguments."));
@@ -9479,7 +9534,7 @@ watchpoint_exp_is_const (const struct expression *exp)
 /* Implement the "re_set" method for watchpoints.  */
 
 void
-watchpoint::re_set ()
+watchpoint::re_set (struct program_space *pspace)
 {
   /* Watchpoint can be either on expression using entirely global
      variables, or it can be on local variables.
@@ -11560,7 +11615,7 @@ breakpoint::print_recreate (struct ui_file *fp) const
 /* Default breakpoint_ops methods.  */
 
 void
-code_breakpoint::re_set ()
+code_breakpoint::re_set (struct program_space *pspace)
 {
   /* FIXME: is this still reachable?  */
   if (breakpoint_location_spec_empty_p (this))
@@ -11570,7 +11625,7 @@ code_breakpoint::re_set ()
       return;
     }
 
-  re_set_default ();
+  re_set_default (pspace);
 }
 
 int
@@ -11776,7 +11831,7 @@ code_breakpoint::decode_location_spec (location_spec *locspec,
 /* Virtual table for internal breakpoints.  */
 
 void
-internal_breakpoint::re_set ()
+internal_breakpoint::re_set (struct program_space *pspace)
 {
   switch (type)
     {
@@ -11869,7 +11924,7 @@ internal_breakpoint::print_mention () const
 /* Virtual table for momentary breakpoints  */
 
 void
-momentary_breakpoint::re_set ()
+momentary_breakpoint::re_set (struct program_space *pspace)
 {
   /* Keep temporary breakpoints, which can be encountered when we step
      over a dlopen call and solib_add is resetting the breakpoints.
@@ -11910,12 +11965,13 @@ longjmp_breakpoint::~longjmp_breakpoint ()
 
 static void
 bkpt_probe_create_sals_from_location_spec (location_spec *locspec,
-					   struct linespec_result *canonical)
+					   struct linespec_result *canonical,
+					   struct program_space *search_pspace)
 
 {
   struct linespec_sals lsal;
 
-  lsal.sals = parse_probes (locspec, NULL, canonical);
+  lsal.sals = parse_probes (locspec, search_pspace, canonical);
   lsal.canonical = xstrdup (canonical->locspec->to_string ());
   canonical->lsals.push_back (std::move (lsal));
 }
@@ -12005,9 +12061,9 @@ tracepoint::print_recreate (struct ui_file *fp) const
 }
 
 void
-dprintf_breakpoint::re_set ()
+dprintf_breakpoint::re_set (struct program_space *pspace)
 {
-  re_set_default ();
+  re_set_default (pspace);
 
   /* extra_string should never be non-NULL for dprintf.  */
   gdb_assert (extra_string != NULL);
@@ -12065,8 +12121,10 @@ dprintf_breakpoint::after_condition_true (struct bpstat *bs)
    markers (`-m').  */
 
 static void
-strace_marker_create_sals_from_location_spec (location_spec *locspec,
-					      struct linespec_result *canonical)
+strace_marker_create_sals_from_location_spec
+	(location_spec *locspec,
+	 struct linespec_result *canonical,
+	 struct program_space *search_pspace)
 {
   struct linespec_sals lsal;
   const char *arg_start, *arg;
@@ -12596,12 +12654,32 @@ update_breakpoint_locations (code_breakpoint *b,
      all locations are in the same shared library, that was unloaded.
      We'd like to retain the location, so that when the library is
      loaded again, we don't loose the enabled/disabled status of the
-     individual locations.  */
+     individual locations.
+
+     Thread specific breakpoints will also trigger this case if the thread
+     is changed to a different program space, and all of the old locations
+     go out of scope.  In this case we do (currently) discard the old
+     locations -- we assume the change in thread is permanent and the old
+     locations will never come back into scope.  */
   if (all_locations_are_pending (b, filter_pspace) && sals.empty ())
-    return;
+    {
+      if (b->thread != -1)
+	b->loc = nullptr;
+      return;
+    }
 
   existing_locations = hoist_existing_locations (b, filter_pspace);
 
+  /* If this is a thread-specific breakpoint then any locations left on the
+     breakpoint are for a program space in which the thread of interest
+     does not operate.  This can happen when the user changes the thread of
+     a thread-specific breakpoint.
+
+     We assume that the change in thread is permanent, and that the old
+     locations will never be used again, so discard them now.  */
+  if (b->thread != -1)
+    b->loc = nullptr;
+
   for (const auto &sal : sals)
     {
       struct bp_location *new_loc;
@@ -12764,40 +12842,45 @@ code_breakpoint::location_spec_to_sals (location_spec *locspec,
    locations.  */
 
 void
-code_breakpoint::re_set_default ()
+code_breakpoint::re_set_default (struct program_space *filter_pspace)
 {
-  struct program_space *filter_pspace = current_program_space;
   std::vector<symtab_and_line> expanded, expanded_end;
 
-  int found;
-  std::vector<symtab_and_line> sals = location_spec_to_sals (locspec.get (),
-							     filter_pspace,
-							     &found);
-  if (found)
-    expanded = std::move (sals);
-
-  if (locspec_range_end != nullptr)
-    {
-      std::vector<symtab_and_line> sals_end
-	= location_spec_to_sals (locspec_range_end.get (),
-				 filter_pspace, &found);
+  /* If this breakpoint is thread-specific then find the program space in
+     which the specific thread exists.  Otherwise, for breakpoints that are
+     not thread-specific THREAD_PSPACE will be nullptr.  */
+  program_space *thread_pspace
+    = find_program_space_for_global_thread_id (this->thread);
+
+  /* If this is not a thread-specific breakpoint, or it is a
+     thread-specific breakpoint but we are looking for new locations in the
+     program space that the specific thread is running, then look for new
+     locations for this breakpoint.  */
+  if (thread_pspace == nullptr || filter_pspace == thread_pspace)
+    {
+      int found;
+      std::vector<symtab_and_line> sals
+	= location_spec_to_sals (locspec.get (), filter_pspace, &found);
       if (found)
-	expanded_end = std::move (sals_end);
+	expanded = std::move (sals);
+
+      if (locspec_range_end != nullptr)
+	{
+	  std::vector<symtab_and_line> sals_end
+	    = location_spec_to_sals (locspec_range_end.get (),
+				     filter_pspace, &found);
+	  if (found)
+	    expanded_end = std::move (sals_end);
+	}
     }
 
+  /* Update the locations for this breakpoint.  For thread-specific
+     breakpoints this will remove any old locations that are for the wrong
+     program space -- this can happen if the user changes the thread of a
+     thread-specific breakpoint.  */
   update_breakpoint_locations (this, filter_pspace, expanded, expanded_end);
 }
 
-/* Default method for creating SALs from an address string.  It basically
-   calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
-
-static void
-create_sals_from_location_spec_default (location_spec *locspec,
-					struct linespec_result *canonical)
-{
-  parse_breakpoint_sals (locspec, canonical);
-}
-
 /* Re-set breakpoint locations for the current program space.
    Locations bound to other program spaces are left untouched.  */
 
@@ -12832,7 +12915,7 @@ breakpoint_re_set (void)
 	  {
 	    input_radix = b->input_radix;
 	    set_language (b->language);
-	    b->re_set ();
+	    b->re_set (current_program_space);
 	  }
 	catch (const gdb_exception &ex)
 	  {
@@ -12853,6 +12936,53 @@ breakpoint_re_set (void)
   /* Now we can insert.  */
   update_global_location_list (UGLL_MAY_INSERT);
 }
+
+/* Re-set locations for breakpoint B in FILTER_PSPACE.  If FILTER_PSPACE is
+   nullptr then re-set locations for B in all program spaces.  Locations
+   bound to program spaces other than FILTER_PSPACE are left untouched.  */
+
+static void
+breakpoint_re_set_one (breakpoint *b, program_space *filter_pspace)
+{
+  {
+    scoped_restore_current_language save_language;
+    scoped_restore save_input_radix = make_scoped_restore (&input_radix);
+    scoped_restore_current_pspace_and_thread restore_pspace_thread;
+
+    /* To ::re_set each breakpoint we set the current_language to the
+       language of the breakpoint before re-evaluating the breakpoint's
+       location.  This change can unfortunately get undone by accident if
+       the language_mode is set to auto, and we either switch frames, or
+       more likely in this context, we select the current frame.
+
+       We prevent this by temporarily turning the language_mode to
+       language_mode_manual.  We restore it once all breakpoints
+       have been reset.  */
+    scoped_restore save_language_mode = make_scoped_restore (&language_mode);
+    language_mode = language_mode_manual;
+
+    /* Note: we must not try to insert locations until after all
+       breakpoints have been re-set.  Otherwise, e.g., when re-setting
+       breakpoint 1, we'd insert the locations of breakpoint 2, which
+       hadn't been re-set yet, and thus may have stale locations.  */
+
+    try
+      {
+	input_radix = b->input_radix;
+	set_language (b->language);
+	b->re_set (filter_pspace);
+      }
+    catch (const gdb_exception &ex)
+      {
+	exception_fprintf (gdb_stderr, ex,
+			   "Error in re-setting breakpoint %d: ",
+			   b->number);
+      }
+  }
+
+  /* Now we can insert.  */
+  update_global_location_list (UGLL_MAY_INSERT);
+}
 \f
 /* Reset the thread number of this breakpoint:
 
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index 2adcc9fa338..8a643301264 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -564,15 +564,15 @@ enum print_stop_action
 
 struct breakpoint_ops
 {
-  /* Create SALs from location spec, storing the result in
-     linespec_result.
-
-     For an explanation about the arguments, see the function
-     `create_sals_from_location_spec_default'.
+  /* Create SALs from LOCSPEC, storing the result in linespec_result
+     CANONICAL.  If SEARCH_PSPACE is not nullptr then only results in the
+     corresponding program space are returned.  If SEARCH_PSPACE is nullptr
+     then results for all program spaces are returned.
 
      This function is called inside `create_breakpoint'.  */
   void (*create_sals_from_location_spec) (location_spec *locspec,
-					  struct linespec_result *canonical);
+					  linespec_result *canonical,
+					  program_space *search_pspace);
 
   /* This method will be responsible for creating a breakpoint given its SALs.
      Usually, it just calls `create_breakpoints_sal' (for ordinary
@@ -635,8 +635,12 @@ struct breakpoint
 
   /* Reevaluate a breakpoint.  This is necessary after symbols change
      (e.g., an executable or DSO was loaded, or the inferior just
-     started).  */
-  virtual void re_set ()
+     started).
+
+     FILTER_PSPACE is the program space in which symbols may have changed,
+     or can be nullptr to indicate that all program spaces may have
+     changed.  */
+  virtual void re_set (program_space *filter_pspace)
   {
     /* Nothing to re-set.  */
   }
@@ -868,7 +872,7 @@ struct code_breakpoint : public breakpoint
   /* Add a location for SAL to this breakpoint.  */
   bp_location *add_location (const symtab_and_line &sal);
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   int insert_location (struct bp_location *) override;
   int remove_location (struct bp_location *,
 		       enum remove_bp_reason reason) override;
@@ -890,7 +894,7 @@ struct code_breakpoint : public breakpoint
      struct program_space *search_pspace);
 
   /* Helper method that does the basic work of re_set.  */
-  void re_set_default ();
+  void re_set_default (program_space *pspace);
 
   /* Find the SaL locations corresponding to the given LOCATION.
      On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
@@ -912,7 +916,7 @@ struct watchpoint : public breakpoint
 {
   using breakpoint::breakpoint;
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   int insert_location (struct bp_location *) override;
   int remove_location (struct bp_location *,
 		       enum remove_bp_reason reason) override;
diff --git a/gdb/testsuite/gdb.mi/user-selected-context-sync.exp b/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
index 4889c31aff3..8cc47537e68 100644
--- a/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
+++ b/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
@@ -370,7 +370,7 @@ proc test_continue_to_start { mode inf } {
 			    "thread $inf.2 stops MI"
 		    } else {
 			mi_expect_stop "breakpoint-hit" "child_sub_function" \
-			    "" "$srcfile" "$decimal" {"" "disp=\"del\"" "locno=\"[0-9]+\""} \
+			    "" "$srcfile" "$decimal" {"" "disp=\"del\""} \
 			    "thread $inf.2 stops MI"
 		    }
 		}
diff --git a/gdb/testsuite/gdb.multi/bp-thread-specific.exp b/gdb/testsuite/gdb.multi/bp-thread-specific.exp
index 85c08f44a2c..68001e92044 100644
--- a/gdb/testsuite/gdb.multi/bp-thread-specific.exp
+++ b/gdb/testsuite/gdb.multi/bp-thread-specific.exp
@@ -50,7 +50,7 @@ gdb_test "info threads" \
 # locations ('foo' in both inferiors) even though only one of those
 # locations will ever trigger ('foo' in inferior 2).
 gdb_test "break foo thread 2.1" \
-    "Breakpoint $decimal at $hex: foo\\. \\(2 locations\\)"
+    "Breakpoint $decimal at $hex: file \[^\r\n\]+$srcfile, line $decimal\\."
 
 set bpnum [get_integer_valueof "\$bpnum" "INVALID"]
 
@@ -58,10 +58,7 @@ set bpnum [get_integer_valueof "\$bpnum" "INVALID"]
 # earlier breakpoint.  Check that the thread-id used when describing
 # the earlier breakpoints is correct.
 gdb_test "break foo thread 1.1" \
-    [multi_line \
-	 "Note: breakpoint $bpnum \\(thread 2.1\\) also set at pc $hex\\." \
-	 "Note: breakpoint $bpnum \\(thread 2.1\\) also set at pc $hex\\." \
-	 "Breakpoint $decimal at $hex: foo\\. \\(2 locations\\)"]
+    "Breakpoint $decimal at $hex: file \[^\r\n\]+$srcfile, line $decimal\\."
 
 # Save the breakpoints into a file.
 if {[is_remote host]} {
diff --git a/gdb/testsuite/gdb.multi/multi-target-continue.exp b/gdb/testsuite/gdb.multi/multi-target-continue.exp
index bf19cc00968..a1bffb7b613 100644
--- a/gdb/testsuite/gdb.multi/multi-target-continue.exp
+++ b/gdb/testsuite/gdb.multi/multi-target-continue.exp
@@ -30,7 +30,7 @@ proc test_continue {non-stop} {
 
     proc set_break {inf} {
 	gdb_test "break function${inf} thread ${inf}.1" \
-	"Breakpoint .* function${inf}\\..*"
+	    "Breakpoint ${::decimal} at ${::hex}: file .*, line ${::decimal}\\."
     }
 
     # Select inferior INF, and then run to a breakpoint on inferior
diff --git a/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp b/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp
index 64645b8ec8a..51fd70b018a 100644
--- a/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp
+++ b/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp
@@ -52,12 +52,12 @@ proc test_ping_pong_next {} {
     gdb_test "thread 1.1" "Switching to thread 1.1 .*"
 
     gdb_test "break $srcfile:$line1 thread 1.1" \
-	"Breakpoint .*$srcfile:$line1\\..*"
+	"Breakpoint .*$srcfile, line $line1\\."
 
     gdb_test "continue" "hit Breakpoint .*"
 
     gdb_test "break $srcfile:$line2 thread 2.1" \
-	"Breakpoint .*$srcfile:$line2\\..*"
+	"Breakpoint .*$srcfile, line $line2\\."
 
     # Now block inferior 1 and issue "next".  We should stop at the
     # breakpoint for inferior 2, given schedlock off.
diff --git a/gdb/testsuite/gdb.multi/pending-bp.exp b/gdb/testsuite/gdb.multi/pending-bp.exp
index 4a65f79cfc4..8e1d1234948 100644
--- a/gdb/testsuite/gdb.multi/pending-bp.exp
+++ b/gdb/testsuite/gdb.multi/pending-bp.exp
@@ -78,6 +78,48 @@ proc do_test_setup { inf_1_stop inf_2_stop } {
     return true
 }
 
+# Create a breakpoint on the function 'foo' in THREAD.  It is expected
+# that the breakpoint created will be pending, this is checked by
+# running the 'info breakpoints' command.
+#
+# Returns the number for the newly created breakpoint.
+proc do_create_pending_foo_breakpoint { {thread "1.1"} } {
+    gdb_test "break foo thread $thread" \
+	[multi_line \
+	     "Function \"foo\" not defined\\." \
+	     "Breakpoint $::decimal \\(foo\\) pending\."] \
+	"set pending thread-specific breakpoint"
+    set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+		   "get number for thread-specific breakpoint on foo"]
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	     "\\s+stop only in thread [string_to_regexp $thread]"] \
+	"check thread-specific breakpoint is initially pending"
+
+    return $bpnum
+}
+
+# Create a breakpoint on the function 'foo' in THREAD.  It is expected
+# that the breakpoint created will not be pending, this is checked by
+# running the 'info breakpoints' command.
+#
+# Returns the number for the newly created breakpoint.
+proc do_create_foo_breakpoint { {thread "1.1"} } {
+    gdb_test "break foo thread $thread" \
+	"Breakpoint $::decimal at $::hex" \
+	"set thread-specific breakpoint"
+    set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+		   "get number for thread-specific breakpoint on foo"]
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex\\s+<foo\[^>\]*> inf $::decimal" \
+	     "\\s+stop only in thread [string_to_regexp $thread]"] \
+	"check thread-specific breakpoint is initially pending"
+
+    return $bpnum
+}
+
 # Check that when a breakpoint is in the pending state, but that breakpoint
 # does have some locations (those locations themselves are pending), GDB
 # doesn't display the inferior list in the 'info breakpoints' output.
@@ -111,5 +153,169 @@ proc_with_prefix test_no_inf_display {} {
 	"check info breakpoints while breakpoint is pending"
 }
 
+# Setup two inferiors.  In #1 the symbol 'foo' has not yet been
+# loaded, while in #2 the symbol 'foo' has been loaded.
+#
+# Create a thread-specific breakpoint on 'foo' tied to a thread in
+# inferior #1, the breakpoint should be pending -- 'foo' is not yet
+# loaded in #1.
+#
+# Now move inferior #1 forward until 'foo' is loaded, check the
+# breakpoint is no longer pending.
+#
+# Move inferior #1 forward more until 'foo' is unloaded, check that
+# the breakpoint returns to the pending state.
+proc_with_prefix test_pending_toggle { } {
+
+    do_test_setup "Break before open" "Break before close"
+
+    set bpnum [do_create_pending_foo_breakpoint]
+
+    # Now return to inferior 1 and continue until the shared library is
+    # loaded, the breakpoint should become non-pending.
+    gdb_test "inferior 1" "Switching to inferior 1 .*" \
+	"switch back to inferior 1"
+    gdb_continue_to_breakpoint "stop in foo in inferior 1" "foo \\(\\) .*"
+
+    gdb_test "info breakpoint $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex <foo\[^>\]*> inf 1" \
+	     "\\s+stop only in thread 1\\.1" \
+	     "\\s+breakpoint already hit 1 time"] \
+	"check thread-specific breakpoint is no longer pending"
+
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "close library"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	     "\\s+stop only in thread 1\\.1" \
+	     "\\s+breakpoint already hit 1 time"] \
+	"check thread-specific breakpoint is pending again"
+}
+
+# Create a Python variable VAR and set it to the gdb.Breakpoint object
+# corresponding to the breakpoint numbered BPNUM.  If THREAD is not
+# the empty string then THREAD should be an integer, check that
+# gdb.Breakpoint.thread is set to the value of THREAD.  Otherwise, if
+# THREAD is the empty string, check that gdb.Breakpoint.thread is set
+# to None.
+proc py_find_breakpoint { var bpnum {thread ""} } {
+    gdb_test_no_output \
+	"python ${var}=\[b for b in gdb.breakpoints() if b.number == $bpnum\]\[0\]" \
+	"find Python gdb.Breakpoint object"
+    if { $thread ne "" } {
+	gdb_test_no_output "python assert(${var}.thread == ${thread})" \
+	    "check thread attribute is currently correct"
+    } else {
+	gdb_test_no_output "python assert(${var}.thread is None)" \
+	    "check thread attribute is currently correct"
+    }
+}
+
+# Setup two inferiors.  In #1 the symbol 'foo' has not yet been
+# loaded, while in #2 the symbol 'foo' has been loaded.
+#
+# Create a thread-specific breakpoint on 'foo' tied to a thread in
+# inferior #1, the breakpoint should be pending -- 'foo' is not yet
+# loaded in #1.
+#
+# Use Python to change the thread of the thread-specific breakpoint to
+# a thread in inferior #2, at this point the thread should gain a
+# location and become non-pending.
+#
+# Set the thread back to a thread in inferior #1, the breakpoint
+# should return to the pending state.
+proc_with_prefix py_test_toggle_thread {} {
+    do_test_setup "Break before open" "Break after open"
+
+    set bpnum [do_create_pending_foo_breakpoint]
+
+    py_find_breakpoint "bp" $bpnum 1
+
+    gdb_test_no_output "python bp.thread = 2" \
+	"change thread on thread-specific breakpoint"
+    gdb_test "info breakpoint $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex <foo\[^>\]*> inf 2" \
+	     "\\s+stop only in thread 2\\.1"] \
+	"check thread-specific breakpoint now has a location"
+
+    gdb_test_no_output "set call_count = 2" "set call_count in inferior 2"
+    gdb_continue_to_breakpoint "stop at foo in inferior 2" "foo \\(\\) .*"
+
+    gdb_test_no_output "python bp.thread = 1" \
+	"restore thread on thread-specific breakpoint"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	     "\\s+stop only in thread 1\\.1" \
+	     "\\s+breakpoint already hit 1 time"] \
+	"check thread-specific breakpoint has returned to pending"
+
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "stop after close in inferior 2" \
+	".* Break after close\\. .*"
+
+    gdb_test "inferior 1" "Switching to inferior 1 .*" \
+	"switch to inferior 1"
+    gdb_continue_to_breakpoint "stop at foo in inferior 1" "foo \\(\\) .*"
+}
+
+# Setup two inferiors.  Both inferiors have the symbol 'foo'
+# available.
+#
+# Create a thread-specific breakpoint on 'foo' tied to a thread in
+# inferior #1, the breakpoint should not be pending, but will only
+# have a single location, the location in inferior #1.
+#
+# Use Python to change the thread of the thread-specific breakpoint to
+# None.  At this point the breakpoint should gain a second location, a
+# location in inferior #2.
+proc_with_prefix py_test_clear_thread {} {
+    do_test_setup "Break after open" "Break after open"
+
+    set bpnum [do_create_foo_breakpoint]
+
+    py_find_breakpoint "bp" $bpnum 1
+
+    gdb_test_no_output "python bp.thread = None" \
+	"clear thread on thread-specific breakpoint"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "${bpnum}\\s+breakpoint\\s+keep y\\s+<MULTIPLE>\\s*" \
+	     "${bpnum}\\.1\\s+y\\s+${::hex}\\s+<foo\[^>\]*> inf $::decimal" \
+	     "${bpnum}\\.2\\s+y\\s+${::hex}\\s+<foo\[^>\]*> inf $::decimal"] \
+	"check for a location in both inferiors"
+
+    gdb_continue_to_breakpoint "stop at foo in inferior 2" "foo \\(\\) .*"
+    gdb_test_no_output "set call_count = 2" "set call_count in inferior 2"
+
+    gdb_test "inferior 1" "Switching to inferior 1 .*" \
+	"switch to inferior 1"
+    gdb_continue_to_breakpoint "stop at foo in inferior 1" "foo \\(\\) .*"
+    gdb_test_no_output "set call_count = 2" "set call_count in inferior 1"
+
+    gdb_test_no_output "python bp.thread = 2"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "${bpnum}\\s+breakpoint\\s+keep y\\s+${::hex}\\s+<foo\[^>\]*> inf 2" \
+	     "\\s+stop only in thread 2\\.1" \
+	     "\\s+breakpoint already hit 2 times"] \
+	"check for a location only in inferior 2"
+
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "stop after close in inferior 1" \
+	".* Break after close\\. .*"
+
+    gdb_test "inferior 2" "Switching to inferior 2 .*" \
+	"switch back to inferior 2"
+    gdb_continue_to_breakpoint "stop at foo again in inferior 2" \
+	"foo \\(\\) .*"
+}
+
 # Run all the tests.
 test_no_inf_display
+test_pending_toggle
+py_test_toggle_thread
+py_test_clear_thread
diff --git a/gdb/testsuite/gdb.multi/tids.exp b/gdb/testsuite/gdb.multi/tids.exp
index 18fc4970fe7..34c270309de 100644
--- a/gdb/testsuite/gdb.multi/tids.exp
+++ b/gdb/testsuite/gdb.multi/tids.exp
@@ -433,11 +433,13 @@ if { [allow_python_tests] } {
 
 	gdb_py_test_silent_cmd "python bp = gdb.breakpoints()\[0\]" \
 	    "get python breakpoint" 0
-	gdb_test "python bp.thread = 6" "thread = 6" \
+	gdb_test_no_output "python bp.thread = 6" \
 	    "make breakpoint thread-specific with python"
 	# Check that the inferior-qualified ID is correct.
 	gdb_test "info breakpoint" \
-	    "stop only in thread 1.3\r\n.*" \
+	    [multi_line \
+		 "$decimal\\s+\[^\r\n\]+ in thread_function1 at \[^\r\n\]+" \
+		 "\\s+stop only in thread 1\\.3"] \
 	    "thread specific breakpoint right thread"
     }
 }
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* Re: [PATCH 6/9] gdb: parse pending breakpoint thread/task immediately
  2023-04-28 23:35 ` [PATCH 6/9] gdb: parse pending breakpoint thread/task immediately Andrew Burgess
@ 2023-04-29  6:01   ` Eli Zaretskii
  0 siblings, 0 replies; 138+ messages in thread
From: Eli Zaretskii @ 2023-04-29  6:01 UTC (permalink / raw)
  To: Andrew Burgess; +Cc: gdb-patches

> Cc: Andrew Burgess <aburgess@redhat.com>
> Date: Sat, 29 Apr 2023 00:35:42 +0100
> From: Andrew Burgess via Gdb-patches <gdb-patches@sourceware.org>
> 
>  gdb/Makefile.in                               |   2 +
>  gdb/NEWS                                      |   4 +
>  gdb/break-cond-parse.c                        | 403 ++++++++++++++++++
>  gdb/break-cond-parse.h                        |  47 ++
>  gdb/breakpoint.c                              | 330 ++++----------
>  gdb/testsuite/gdb.base/condbreak.exp          |  20 +-
>  gdb/testsuite/gdb.base/pending.exp            |  23 +-
>  gdb/testsuite/gdb.linespec/explicit.exp       |   4 +-
>  gdb/testsuite/gdb.mi/mi-dprintf-pending.exp   |   3 +-
>  .../gdb.threads/del-pending-thread-bp-lib.c   |  22 +
>  .../gdb.threads/del-pending-thread-bp.c       |  85 ++++
>  .../gdb.threads/del-pending-thread-bp.exp     | 108 +++++
>  12 files changed, 793 insertions(+), 258 deletions(-)
>  create mode 100644 gdb/break-cond-parse.c
>  create mode 100644 gdb/break-cond-parse.h
>  create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
>  create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.c
>  create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.exp

The NEWS part is OK, thanks.

Reviewed-By: Eli Zaretskii <eliz@gnu.org>

^ permalink raw reply	[flat|nested] 138+ messages in thread

* Re: [PATCH 9/9] gdb: only insert thread-specific breakpoints in the relevant inferior
  2023-04-28 23:35 ` [PATCH 9/9] gdb: only insert thread-specific breakpoints in the relevant inferior Andrew Burgess
@ 2023-04-29  6:02   ` Eli Zaretskii
  0 siblings, 0 replies; 138+ messages in thread
From: Eli Zaretskii @ 2023-04-29  6:02 UTC (permalink / raw)
  To: Andrew Burgess; +Cc: gdb-patches

> Cc: Andrew Burgess <aburgess@redhat.com>
> Date: Sat, 29 Apr 2023 00:35:45 +0100
> From: Andrew Burgess via Gdb-patches <gdb-patches@sourceware.org>
> 
>  gdb/NEWS                                      |   7 +
>  gdb/ada-lang.c                                |   6 +-
>  gdb/break-catch-throw.c                       |   6 +-
>  gdb/breakpoint.c                              | 236 ++++++++++++++----
>  gdb/breakpoint.h                              |  26 +-
>  .../gdb.mi/user-selected-context-sync.exp     |   2 +-
>  .../gdb.multi/bp-thread-specific.exp          |   7 +-
>  .../gdb.multi/multi-target-continue.exp       |   2 +-
>  .../gdb.multi/multi-target-ping-pong-next.exp |   4 +-
>  gdb/testsuite/gdb.multi/pending-bp.exp        | 206 +++++++++++++++
>  gdb/testsuite/gdb.multi/tids.exp              |   6 +-
>  11 files changed, 427 insertions(+), 81 deletions(-)

The NEWS part is OK, thanks.

Reviewed-By: Eli Zaretskii <eliz@gnu.org>

^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv2 0/9] thread-specific breakpoints in just some inferiors
  2023-04-28 23:35 [PATCH 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
                   ` (8 preceding siblings ...)
  2023-04-28 23:35 ` [PATCH 9/9] gdb: only insert thread-specific breakpoints in the relevant inferior Andrew Burgess
@ 2023-05-15 19:27 ` Andrew Burgess
  2023-05-15 19:27   ` [PATCHv2 1/9] gdb: create_breakpoint: assert for a valid thread-id Andrew Burgess
                     ` (9 more replies)
  9 siblings, 10 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-05-15 19:27 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

In v2:

  - Rebased on current upstream/master and retested,

  - No changes to code or docs.

---

Andrew Burgess (9):
  gdb: create_breakpoint: assert for a valid thread-id
  gdb: create_breakpoint: asserts relating to extra_string/parse_extra
  gdb: change 'if' to gdb_assert in update_dprintf_command_list
  gdb: build dprintf commands just once in code_breakpoint constructor
  gdb: don't display inferior list for pending breakpoints
  gdb: parse pending breakpoint thread/task immediately
  gdb: remove breakpoint_re_set_one
  gdb: remove tracepoint_probe_create_sals_from_location_spec
  gdb: only insert thread-specific breakpoints in the relevant inferior

 gdb/Makefile.in                               |   2 +
 gdb/NEWS                                      |  11 +
 gdb/ada-lang.c                                |   6 +-
 gdb/break-catch-throw.c                       |   6 +-
 gdb/break-cond-parse.c                        | 403 +++++++++++
 gdb/break-cond-parse.h                        |  47 ++
 gdb/breakpoint.c                              | 666 ++++++++----------
 gdb/breakpoint.h                              |  64 +-
 gdb/testsuite/gdb.base/condbreak.exp          |  20 +-
 gdb/testsuite/gdb.base/pending.exp            |  23 +-
 gdb/testsuite/gdb.linespec/explicit.exp       |   4 +-
 gdb/testsuite/gdb.mi/mi-dprintf-pending.exp   |   3 +-
 .../gdb.mi/user-selected-context-sync.exp     |   2 +-
 .../gdb.multi/bp-thread-specific.exp          |   7 +-
 .../gdb.multi/multi-target-continue.exp       |   2 +-
 .../gdb.multi/multi-target-ping-pong-next.exp |   4 +-
 gdb/testsuite/gdb.multi/pending-bp-lib.c      |  22 +
 gdb/testsuite/gdb.multi/pending-bp.c          |  66 ++
 gdb/testsuite/gdb.multi/pending-bp.exp        | 321 +++++++++
 gdb/testsuite/gdb.multi/tids.exp              |   6 +-
 .../gdb.threads/del-pending-thread-bp-lib.c   |  22 +
 .../gdb.threads/del-pending-thread-bp.c       |  85 +++
 .../gdb.threads/del-pending-thread-bp.exp     | 108 +++
 23 files changed, 1498 insertions(+), 402 deletions(-)
 create mode 100644 gdb/break-cond-parse.c
 create mode 100644 gdb/break-cond-parse.h
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.exp
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.exp


base-commit: 6a1cf1bfedbcdb977d9ead3bf6a228360d78cc1b
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv2 1/9] gdb: create_breakpoint: assert for a valid thread-id
  2023-05-15 19:27 ` [PATCHv2 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
@ 2023-05-15 19:27   ` Andrew Burgess
  2023-05-15 19:27   ` [PATCHv2 2/9] gdb: create_breakpoint: asserts relating to extra_string/parse_extra Andrew Burgess
                     ` (8 subsequent siblings)
  9 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-05-15 19:27 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Add an assert into create_breakpoint (breakpoint.c) that the thread
argument is a valid thread-id; either a value greater than zero, or -1
to indicate any thread.

The thread is ignored if parse_extra is true though, so take that into
account too.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c | 4 ++++
 gdb/breakpoint.h | 6 ++++++
 2 files changed, 10 insertions(+)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index fdb184ae81f..31448e0a895 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -9027,6 +9027,10 @@ create_breakpoint (struct gdbarch *gdbarch,
 
   gdb_assert (ops != NULL);
 
+  /* If PARSE_EXTRA is true then the thread-id will be parsed from
+     EXTRA_STRING, otherwise, ensure THREAD is valid.  */
+  gdb_assert (parse_extra || thread == -1 || thread > 0);
+
   /* If extra_string isn't useful, set it to NULL.  */
   if (extra_string != NULL && *extra_string == '\0')
     extra_string = NULL;
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index 7c5cf3f2bef..e57dc2523fb 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -1530,6 +1530,12 @@ enum breakpoint_create_flags
    the FORCE_CONDITION parameter is ignored and the corresponding argument
    is parsed from EXTRA_STRING.
 
+   The THREAD should be a global thread number, the created breakpoint will
+   only apply for that thread.  If the breakpoint should apply for all
+   threads then pass -1.  However, if PARSE_EXTRA is non-zero then the
+   THREAD parameter is ignored and an optional thread number will be parsed
+   from EXTRA_STRING.
+
    If INTERNAL is non-zero, the breakpoint number will be allocated
    from the internal breakpoint count.
 
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv2 2/9] gdb: create_breakpoint: asserts relating to extra_string/parse_extra
  2023-05-15 19:27 ` [PATCHv2 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
  2023-05-15 19:27   ` [PATCHv2 1/9] gdb: create_breakpoint: assert for a valid thread-id Andrew Burgess
@ 2023-05-15 19:27   ` Andrew Burgess
  2023-05-15 19:27   ` [PATCHv2 3/9] gdb: change 'if' to gdb_assert in update_dprintf_command_list Andrew Burgess
                     ` (7 subsequent siblings)
  9 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-05-15 19:27 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

The goal of this commit is to better define the API for
create_breakpoint especially around the use of extra_string and
parse_extra.  This will be useful in the next commit when I plan to
make some changes to create_breakpoint.

This commit makes one possibly breaking change: until this commit it
was possible to create thread-specific dprintf breakpoint like this:

  (gdb) dprintf call_me, thread 1 "%s", "hello"
  Dprintf 2 at 0x401152: file /tmp/hello.c, line 8.
  (gdb) info breakpoints
  Num     Type           Disp Enb Address            What
  2       dprintf        keep y   0x0000000000401152 in call_me at /tmp/hello.c:8 thread 1
          stop only in thread 1
          printf "%s", "hello"
  (gdb)

this feature of dprintf was not documented, was not tested, and is
slightly different in syntax to how we create thread specific
breakpoints and/or watchpoints -- the thread condition appears after
the first ','.

I believe that this worked at all was simply by luck.  We happen to
pass the parse_extra flag as true from dprintf_command to
create_breakpoint.

So in this commit I made the choice change this.  We now pass
parse_extra as false from dprintf_command to create_breakpoint.  With
this done it is assumed that the only thing in the extra_string is the
dprintf format and arguments.

Beyond this change I've updated the comment on create_breakpoint in
breakpoint.h, and I've then added some asserts into
create_breakpoint as well as moving around some of the error
handling.

 - We now assert on the incoming argument values,

 - I've moved an error check to sit after the call to
   find_condition_and_thread_for_sals, this ensures the extra_string
   was parsed correctly,

In dprintf_command:

 - We now throw an error if there is no format string after the
   dprintf location.  This error was already being thrown, but was
   being caught later in the process.  With this change we catch the
   missing string earlier,

 - And, as mentioned earlier, we pass parse_extra as false when
   calling create_breakpoint,

In create_tracepoint_from_upload:

 - We now throw an error if the parsed location doesn't completely
   consume the addr_str variable.  This error has now effectively
   moved out of create_breakpoint.
---
 gdb/breakpoint.c | 42 +++++++++++++++++++++++++++++-------------
 gdb/breakpoint.h | 38 ++++++++++++++++++++++++--------------
 2 files changed, 53 insertions(+), 27 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 31448e0a895..4d182ac0143 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -9035,6 +9035,17 @@ create_breakpoint (struct gdbarch *gdbarch,
   if (extra_string != NULL && *extra_string == '\0')
     extra_string = NULL;
 
+  /* A bp_dprintf must always have an accompanying EXTRA_STRING containing
+     the dprintf format and arguments -- PARSE_EXTRA should always be false
+     in this case.
+
+     For all other breakpoint types, EXTRA_STRING should be nullptr unless
+     PARSE_EXTRA is true.  */
+  gdb_assert ((type_wanted == bp_dprintf
+	       && extra_string != nullptr && !parse_extra)
+	      || (type_wanted != bp_dprintf
+		  && (extra_string == nullptr || parse_extra)));
+
   try
     {
       ops->create_sals_from_location_spec (locspec, &canonical);
@@ -9098,6 +9109,8 @@ create_breakpoint (struct gdbarch *gdbarch,
 
       if (parse_extra)
 	{
+	  gdb_assert (type_wanted != bp_dprintf);
+
 	  gdb::unique_xmalloc_ptr<char> rest;
 	  gdb::unique_xmalloc_ptr<char> cond;
 
@@ -9105,15 +9118,15 @@ create_breakpoint (struct gdbarch *gdbarch,
 
 	  find_condition_and_thread_for_sals (lsal.sals, extra_string,
 					      &cond, &thread, &task, &rest);
+
+	  if (rest.get () != nullptr && *(rest.get ()) != '\0')
+	    error (_("Garbage '%s' at end of command"), rest.get ());
+
 	  cond_string_copy = std::move (cond);
 	  extra_string_copy = std::move (rest);
 	}
       else
 	{
-	  if (type_wanted != bp_dprintf
-	      && extra_string != NULL && *extra_string != '\0')
-		error (_("Garbage '%s' at end of location"), extra_string);
-
 	  /* Check the validity of the condition.  We should error out
 	     if the condition is invalid at all of the locations and
 	     if it is not forced.  In the PARSE_EXTRA case above, this
@@ -9322,20 +9335,17 @@ dprintf_command (const char *arg, int from_tty)
 
   /* If non-NULL, ARG should have been advanced past the location;
      the next character must be ','.  */
-  if (arg != NULL)
+  if (arg == nullptr || arg[0] != ',' || arg[1] == '\0')
+    error (_("Format string required"));
+  else
     {
-      if (arg[0] != ',' || arg[1] == '\0')
-	error (_("Format string required"));
-      else
-	{
-	  /* Skip the comma.  */
-	  ++arg;
-	}
+      /* Skip the comma.  */
+      ++arg;
     }
 
   create_breakpoint (get_current_arch (),
 		     locspec.get (),
-		     NULL, 0, arg, false, 1 /* parse arg */,
+		     NULL, -1, arg, false, 0 /* parse arg */,
 		     0, bp_dprintf,
 		     0 /* Ignore count */,
 		     pending_break_support,
@@ -13910,6 +13920,12 @@ create_tracepoint_from_upload (struct uploaded_tp *utp)
 
   location_spec_up locspec = string_to_location_spec (&addr_str,
 						      current_language);
+
+
+  gdb_assert (addr_str != nullptr);
+  if (*addr_str != '\0')
+    error (_("Garbage '%s' at end of location"), addr_str);
+
   if (!create_breakpoint (get_current_arch (),
 			  locspec.get (),
 			  utp->cond_string.get (), -1, addr_str,
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index e57dc2523fb..2adcc9fa338 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -1515,26 +1515,36 @@ enum breakpoint_create_flags
    functions for setting a breakpoint at LOCSPEC.
 
    This function has two major modes of operations, selected by the
-   PARSE_EXTRA parameter.
+   PARSE_EXTRA and WANTED_TYPE parameters.
 
-   If PARSE_EXTRA is zero, LOCSPEC is just the breakpoint's location
-   spec, with condition, thread, and extra string specified by the
-   COND_STRING, THREAD, and EXTRA_STRING parameters.
+   When WANTED_TYPE is not bp_dprintf the following rules apply:
 
-   If PARSE_EXTRA is non-zero, this function will attempt to extract
-   the condition, thread, and extra string from EXTRA_STRING, ignoring
-   the similarly named parameters.
+     If PARSE_EXTRA is zero, LOCSPEC is just the breakpoint's location
+     spec, with condition, thread, and extra string specified by the
+     COND_STRING, THREAD, and EXTRA_STRING parameters.
 
-   If FORCE_CONDITION is true, the condition is accepted even when it is
-   invalid at all of the locations.  However, if PARSE_EXTRA is non-zero,
-   the FORCE_CONDITION parameter is ignored and the corresponding argument
-   is parsed from EXTRA_STRING.
+     If PARSE_EXTRA is non-zero, this function will attempt to extract the
+     condition, thread, and extra string from EXTRA_STRING, ignoring the
+     similarly named parameters.
+
+   When WANTED_TYPE is bp_dprintf the following rules apply:
+
+     PARSE_EXTRA must always be zero, LOCSPEC is just the breakpoint's
+     location spec, with condition, thread, and extra string (which
+     contains the dprintf format and arguments) specified by the
+     COND_STRING, THREAD, and EXTRA_STRING parameters.
+
+   If FORCE_CONDITION is true, the condition (in COND_STRING) is accepted
+   even when it is invalid at all of the locations.  However, if
+   PARSE_EXTRA is non-zero and WANTED_TYPE is not bp_dprintf, the
+   FORCE_CONDITION parameter is ignored and the corresponding argument is
+   parsed from EXTRA_STRING.
 
    The THREAD should be a global thread number, the created breakpoint will
    only apply for that thread.  If the breakpoint should apply for all
-   threads then pass -1.  However, if PARSE_EXTRA is non-zero then the
-   THREAD parameter is ignored and an optional thread number will be parsed
-   from EXTRA_STRING.
+   threads then pass -1.  However, if PARSE_EXTRA is non-zero and
+   WANTED_TYPE is not bp_dprintf, then the THREAD parameter is ignored and
+   an optional thread number will be parsed from EXTRA_STRING.
 
    If INTERNAL is non-zero, the breakpoint number will be allocated
    from the internal breakpoint count.
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv2 3/9] gdb: change 'if' to gdb_assert in update_dprintf_command_list
  2023-05-15 19:27 ` [PATCHv2 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
  2023-05-15 19:27   ` [PATCHv2 1/9] gdb: create_breakpoint: assert for a valid thread-id Andrew Burgess
  2023-05-15 19:27   ` [PATCHv2 2/9] gdb: create_breakpoint: asserts relating to extra_string/parse_extra Andrew Burgess
@ 2023-05-15 19:27   ` Andrew Burgess
  2023-05-15 19:27   ` [PATCHv2 4/9] gdb: build dprintf commands just once in code_breakpoint constructor Andrew Burgess
                     ` (6 subsequent siblings)
  9 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-05-15 19:27 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

I noticed in update_dprintf_command_list that we handle the case where
the bp_dprintf style breakpoint doesn't have a format and args string.

However, I don't believe such a situation is possible.  The obvious
approach certainly already catches this case:

  (gdb) dprintf main
  Format string required

If it is possible to create a dprintf breakpoint without a format and
args string then I think we should be catching this case and handling
it at creation time, rather than having GDB just ignore the situation
later on.

And so, I propose that we change the 'if' that ignores the case where
the format/args string is empty, and instead assert that we do always
have a format/args string.  The original code, that handled an empty
format/args string has existed since commit e7e0cddfb0d4, which is
when dprintf support was added to GDB.

If I'm correct and this situation can't ever happen then there should
be no user visible changes after this commit.
---
 gdb/breakpoint.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 4d182ac0143..0827b587d5f 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -8383,8 +8383,9 @@ update_dprintf_command_list (struct breakpoint *b)
   const char *dprintf_args = b->extra_string.get ();
   gdb::unique_xmalloc_ptr<char> printf_line = nullptr;
 
-  if (!dprintf_args)
-    return;
+  /* Trying to create a dprintf breakpoint without a format and args
+     string should be detected at creation time.  */
+  gdb_assert (dprintf_args != nullptr);
 
   dprintf_args = skip_spaces (dprintf_args);
 
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv2 4/9] gdb: build dprintf commands just once in code_breakpoint constructor
  2023-05-15 19:27 ` [PATCHv2 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
                     ` (2 preceding siblings ...)
  2023-05-15 19:27   ` [PATCHv2 3/9] gdb: change 'if' to gdb_assert in update_dprintf_command_list Andrew Burgess
@ 2023-05-15 19:27   ` Andrew Burgess
  2023-05-15 19:27   ` [PATCHv2 5/9] gdb: don't display inferior list for pending breakpoints Andrew Burgess
                     ` (5 subsequent siblings)
  9 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-05-15 19:27 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

I noticed in code_breakpoint::code_breakpoint that we are calling
update_dprintf_command_list once for each breakpoint location, when we
really only need to call this once per breakpoint -- the data updated
by this function, the breakpoint command list -- is per breakpoint,
not per breakpoint location.  Calling update_dprintf_command_list
multiple times is just wasted effort, there's no per location error
checking, we don't even pass the current location to the function.

This commit moves the update_dprintf_command_list call outside of the
per-location loop. I have also changes the 'if' that handles the case
where the extra_string (which holds the format/args) is empty.  I
don't believe that this situation can ever arise -- and if it does we
should be catching it earlier and throwing an error at that point.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c | 20 +++++++++-----------
 1 file changed, 9 insertions(+), 11 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 0827b587d5f..d03c55587be 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -8544,19 +8544,17 @@ code_breakpoint::code_breakpoint (struct gdbarch *gdbarch_,
       /* Do not set breakpoint locations conditions yet.  As locations
 	 are inserted, they get sorted based on their addresses.  Let
 	 the list stabilize to have reliable location numbers.  */
+    }
 
-      /* Dynamic printf requires and uses additional arguments on the
-	 command line, otherwise it's an error.  */
-      if (type == bp_dprintf)
-	{
-	  if (extra_string != nullptr)
-	    update_dprintf_command_list (this);
-	  else
-	    error (_("Format string required"));
-	}
-      else if (extra_string != nullptr)
-	error (_("Garbage '%s' at end of command"), extra_string.get ());
+  /* Dynamic printf requires and uses additional arguments on the
+     command line, otherwise it's an error.  */
+  if (type == bp_dprintf)
+    {
+      gdb_assert (extra_string != nullptr);
+      update_dprintf_command_list (this);
     }
+  else if (extra_string != nullptr)
+    error (_("Garbage '%s' at end of command"), extra_string.get ());
 
   /* The order of the locations is now stable.  Set the location
      condition using the location's number.  */
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv2 5/9] gdb: don't display inferior list for pending breakpoints
  2023-05-15 19:27 ` [PATCHv2 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
                     ` (3 preceding siblings ...)
  2023-05-15 19:27   ` [PATCHv2 4/9] gdb: build dprintf commands just once in code_breakpoint constructor Andrew Burgess
@ 2023-05-15 19:27   ` Andrew Burgess
  2023-05-15 19:27   ` [PATCHv2 6/9] gdb: parse pending breakpoint thread/task immediately Andrew Burgess
                     ` (4 subsequent siblings)
  9 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-05-15 19:27 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

I noticed that in the 'info breakpoints' output, GDB sometimes prints
the inferior list for pending breakpoints, this doesn't seem right to
me.  A pending breakpoint has no locations (at least, as far as we
display things in the 'info breakpoints' output), so including an
inferior list seems odd.

Here's what I see right now:

  (gdb) info breakpoint 5
  Num     Type           Disp Enb Address            What
  5       breakpoint     keep y   <PENDING>          foo inf 1
  (gdb)

It's the 'inf 1' at the end of the line that I'm objecting too.

To trigger this behaviour we need to be in a multi-inferior debug
session.  The breakpoint must have been non-pending at some point in
the past, and so have a location assigned to it.

The breakpoint becomes pending again as a result of a shared library
being unloaded.  When this happens the location itself is marked
pending (via bp_location::shlib_disabled).

In print_one_breakpoint_location, in order to print the inferior list
we check that the breakpoint has a location, and that we have multiple
inferiors, but we don't check if the location itself is pending.

This commit adds that check, which means the output is now:

  (gdb) info breakpoint 5
  Num     Type           Disp Enb Address            What
  5       breakpoint     keep y   <PENDING>          foo
  (gdb)

Which I think makes more sense.
---
 gdb/breakpoint.c                         |   2 +-
 gdb/testsuite/gdb.multi/pending-bp-lib.c |  22 +++++
 gdb/testsuite/gdb.multi/pending-bp.c     |  66 +++++++++++++
 gdb/testsuite/gdb.multi/pending-bp.exp   | 115 +++++++++++++++++++++++
 4 files changed, 204 insertions(+), 1 deletion(-)
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.exp

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index d03c55587be..f9020c49d90 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -6467,7 +6467,7 @@ print_one_breakpoint_location (struct breakpoint *b,
 	}
     }
 
-  if (loc != NULL && !header_of_multiple)
+  if (loc != NULL && !header_of_multiple && !loc->shlib_disabled)
     {
       std::vector<int> inf_nums;
       int mi_only = 1;
diff --git a/gdb/testsuite/gdb.multi/pending-bp-lib.c b/gdb/testsuite/gdb.multi/pending-bp-lib.c
new file mode 100644
index 00000000000..15d1b9833dd
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp-lib.c
@@ -0,0 +1,22 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+int global_var = 0;
+
+void
+foo (int arg)
+{
+  global_var = arg;
+}
diff --git a/gdb/testsuite/gdb.multi/pending-bp.c b/gdb/testsuite/gdb.multi/pending-bp.c
new file mode 100644
index 00000000000..ca8a3c20b72
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp.c
@@ -0,0 +1,66 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#include <dlfcn.h>
+#include <stdlib.h>
+
+void
+breakpt ()
+{
+  /* Nothing.  */
+}
+
+volatile int global_counter = 0;
+
+volatile int call_count = 1;
+
+int
+main (void)
+{
+  void *handle;
+  void (*func)(int);
+
+  /* Some filler work so that we don't initially stop on the breakpt call
+     below.  */
+  ++global_counter;
+
+  breakpt ();	/* Break before open.  */
+
+  /* Now load the shared library.  */
+  handle = dlopen (SHLIB_NAME, RTLD_LAZY);
+  if (handle == NULL)
+    abort ();
+
+  breakpt ();	/* Break after open.  */
+
+  /* Find the function symbol.  */
+  func = (void (*)(int)) dlsym (handle, "foo");
+
+  for (; call_count > 0; --call_count)
+    {
+      /* Call the library function.  */
+      func (1);
+    }
+
+  breakpt ();	/* Break before close.  */
+
+  /* Unload the shared library.  */
+  if (dlclose (handle) != 0)
+    abort ();
+
+  breakpt ();	/* Break after close.  */
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.multi/pending-bp.exp b/gdb/testsuite/gdb.multi/pending-bp.exp
new file mode 100644
index 00000000000..4a65f79cfc4
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp.exp
@@ -0,0 +1,115 @@
+# Copyright 2023 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+# Tests related to pending breakpoints in a multi-inferior environment.
+
+require allow_shlib_tests !use_gdb_stub
+
+standard_testfile
+
+set libname $testfile-lib
+set srcfile_lib $srcdir/$subdir/$libname.c
+set binfile_lib [standard_output_file $libname.so]
+
+if { [gdb_compile_shlib $srcfile_lib $binfile_lib {}] != "" } {
+    untested "failed to compile shared library 1"
+    return -1
+}
+
+set binfile_lib_target [gdb_download_shlib $binfile_lib]
+
+if { [build_executable "failed to prepare" $testfile $srcfile \
+	  [list debug \
+	       additional_flags=-DSHLIB_NAME=\"$binfile_lib_target\" \
+	       shlib_load pthreads]] } {
+    return -1
+}
+
+# Used to override delete_breakpoints when we don't want breakpoints
+# deleted.
+proc do_nothing {} {}
+
+# Start two inferiors, both running the same test binary.  The arguments
+# INF_1_STOP and INF_2_STOP are source code patterns that are passed to
+# gdb_get_line_number to figure out where each inferior should be stopped.
+#
+# This proc does a clean_restart and leaves inferior 2 selected.  Also the
+# 'breakpoint pending' flag is enabled, so pending breakpoints can be created
+# without GDB prompting the user.
+proc do_test_setup { inf_1_stop inf_2_stop } {
+    clean_restart ${::binfile}
+
+    gdb_locate_shlib $::binfile_lib
+
+    if ![runto_main] {
+	return false
+    }
+
+    gdb_breakpoint [gdb_get_line_number ${inf_1_stop}] temporary
+    gdb_continue_to_breakpoint "move inferior 1 into position"
+
+    gdb_test "add-inferior -exec ${::binfile}" \
+	"Added inferior 2.*" "add inferior 2"
+    gdb_test "inferior 2" "Switching to inferior 2 .*" "switch to inferior 2"
+
+    with_override delete_breakpoints do_nothing {
+	if {![runto_main]} {
+	    return false
+	}
+    }
+
+    gdb_breakpoint [gdb_get_line_number ${inf_2_stop}] temporary
+    gdb_continue_to_breakpoint "move inferior 2 into position"
+
+    gdb_test_no_output "set breakpoint pending on"
+
+    return true
+}
+
+# Check that when a breakpoint is in the pending state, but that breakpoint
+# does have some locations (those locations themselves are pending), GDB
+# doesn't display the inferior list in the 'info breakpoints' output.
+proc_with_prefix test_no_inf_display {} {
+    do_test_setup "Break before close" "Break before open"
+
+    # Create a breakpoint on 'foo'.  This will find a location in inferior 1,
+    # but will not find a location in inferior 2 -- the shared library is not
+    # yet loaded in that inferior.
+    gdb_breakpoint "foo"
+    set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+		   "get foo breakpoint number"]
+
+    # Check the 'info breakpoints' output.  Notice we display the inferior
+    # list at the end of the breakpoint line.
+    gdb_test "info breakpoint $bpnum" \
+	"$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex\\s+<foo\[^>\]*>\\s+inf 1" \
+	"check info breakpoints while breakpoint is inserted"
+
+    # Ensure we are in inferior 1, move the inferior forward until the shared
+    # library has been unloaded.  The breakpoint on 'foo' will return to the
+    # pending state.
+    gdb_test "inferior 1" "Switching to inferior 1 .*"
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "after close library"
+
+    # Check the 'info breakpoints' output, check there is no 'inf 1' at the
+    # end of the breakpoint line.
+    gdb_test "info breakpoint $bpnum" \
+	"$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	"check info breakpoints while breakpoint is pending"
+}
+
+# Run all the tests.
+test_no_inf_display
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv2 6/9] gdb: parse pending breakpoint thread/task immediately
  2023-05-15 19:27 ` [PATCHv2 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
                     ` (4 preceding siblings ...)
  2023-05-15 19:27   ` [PATCHv2 5/9] gdb: don't display inferior list for pending breakpoints Andrew Burgess
@ 2023-05-15 19:27   ` Andrew Burgess
  2023-05-15 19:27   ` [PATCHv2 7/9] gdb: remove breakpoint_re_set_one Andrew Burgess
                     ` (3 subsequent siblings)
  9 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-05-15 19:27 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Eli Zaretskii

Eli approved the docs changes here:

  https://sourceware.org/pipermail/gdb-patches/2023-April/199221.html


---

The initial motivation for this commit was to allow thread or (in the
future) inferior specific breakpoints to only be inserted within the
appropriate inferior's program-space.  The benefit of this is that
inferiors for which the breakpoint does not apply will no longer need
to stop, and then resume, for such breakpoints.  This commit does not
make this change, but is a refactor to allow this change in a later
commit.

The problem we currently have is that when a thread-specific
breakpoint is created, the thread number is only parsed by calling
find_condition_and_thread_for_sals.  This function is only called for
non-pending breakpoints, and requires that we know the locations at
which the breakpoint will be placed (for expression checking in case
the breakpoint is also conditional).

A consequence of this is that by the time we figure out the breakpoint
is thread-specific we have already looked up locations in all program
spaces.  This feels wasteful -- if we knew the thread-id earlier then
we could reduce the work GDB does by only looking up locations within
the program space for which the breakpoint applies.

Another consequence of how find_condition_and_thread_for_sals is
called is that pending breakpoints don't currently know they are
thread-specific, nor even that they are conditional!  Additionally, by
delaying parsing the thread-id, pending breakpoints can be created for
non-existent threads, this is different to how non-pending
breakpoints are handled.

In this commit the create_breakpoint function is updated so that the
extra_string, which contains the thread/task/condition information, is
parsed immediately, even for pending breakpoints.

Obviously, the condition still can't be validated until the breakpoint
becomes non-pending, but the thread/task information can be pulled
from the extra-string, and can be validated early on, even for pending
breakpoints.

There are a couple of benefits to doing this:

1. Printing of breakpoints is more consistent now.  Consider creating
   a conditional breakpoint before this commit:

    (gdb) set breakpoint pending on
    (gdb) break pendingfunc if (0)
    Function "pendingfunc" not defined.
    Breakpoint 1 (pendingfunc if (0)) pending.
    (gdb) break main if (0)
    Breakpoint 2 at 0x401198: file /tmp/hello.c, line 18.
    (gdb) info breakpoints
    Num     Type           Disp Enb Address            What
    1       breakpoint     keep y   <PENDING>          pendingfunc if (0)
    2       breakpoint     keep y   0x0000000000401198 in main at /tmp/hello.c:18
            stop only if (0)
    (gdb)

   And after this commit:

    (gdb) set breakpoint pending on
    (gdb) break pendingfunc if (0)
    Function "pendingfunc" not defined.
    Breakpoint 1 (pendingfunc) pending.
    (gdb) break main if (0)
    Breakpoint 2 at 0x401198: file /home/andrew/tmp/hello.c, line 18.
    (gdb) info breakpoints
    Num     Type           Disp Enb Address            What
    1       breakpoint     keep y   <PENDING>          pendingfunc
            stop only if (0)
    2       breakpoint     keep y   0x0000000000401198 in main at /home/andrew/tmp/hello.c:18
            stop only if (0)
    (gdb)

   Notice that the display of the condition is now the same for the
   pending and non-pending breakpoints.

   The same is true for the thread information in thread-specific
   breakpoints, this information is displayed on its own line now
   rather than being part of the 'What' field.

2. We can check that the thread exists as soon as the pending
   breakpoint exits.  Currently there is a weird different between
   pending and non-pending breakpoints when creating a thread-specific
   breakpoint.  A pending thread-specific breakpoint only checks its
   thread when it becomes non-pending, at which point the thread the
   breakpoint was intended for might have exited.  Here's the
   behaviour before this commit:

    (gdb) set breakpoint pending on
    (gdb) break foo thread 2
    Function "foo" not defined.
    Breakpoint 2 (foo thread 2) pending.
    (gdb) c
    Continuing.
    [Thread 0x7ffff7c56700 (LWP 2948835) exited]
    Error in re-setting breakpoint 2: Unknown thread 2.
    [Inferior 1 (process 2948832) exited normally]
    (gdb)

   Notice the 'Error in re-setting breakpoint 2: Unknown thread 2.'
   line, this was triggered when the thread tried to become
   non-pending, and GDB discovers that the thread no longer exists.

   Compare that to the behaviour after this commit:

    (gdb) set breakpoint pending on
    (gdb) break foo thread 2
    Function "foo" not defined.
    Breakpoint 2 (foo) pending.
    (gdb) c
    Continuing.
    [Thread 0x7ffff7c56700 (LWP 2949243) exited]
    Thread-specific breakpoint 2 deleted - thread 2 no longer in the thread list.
    [Inferior 1 (process 2949240) exited normally]
    (gdb)

   Now the behaviour for pending breakpoints is identical to
   non-pending breakpoints, the thread specific breakpoint is removed
   as soon as the thread the breakpoint is associated with exits.

As a result of this commit the breakpoints 'extra_string' field is now
only used by bp_dprintf type breakpoints to hold the printf format and
arguments.  This string should always be empty for other breakpoint
types.  This allows me to clean up some code in
print_breakpoint_location.

In code_breakpoint::code_breakpoint I'm able to change an error case
into an assert.  This is because this error is now handled earlier in
create_breakpoint.  As a result we know that by this point, the
extra_string will always be nullptr for anything other than a
bp_dprintf style breakpoint.

The find_condition_and_thread_for_sals function is now no longer
needed, this was previously doing the delayed splitting of the extra
string into thread, task, and condition, but this is now all done in
create_breakpoint, so find_condition_and_thread_for_sals can be
deleted, and the code that calls this in
code_breakpoint::location_spec_to_sals can be removed.  With this
update this code would only ever be reached for bp_dprintf style
breakpoints, and in these cases the extra_string should not contain
anything other than format and args.

The most interesting changes are all in create_breakpoint and in the
new file break-cond-parse.c.  We have a new block of code early on in
create_breakpoint that is responsible for splitting the extra_string
into its component parts by calling create_breakpoint_parse_arg_string
a function in the new break-cond-parse.c file.  This means that some
of the later code can be simplified a little.

The new break-cond-parse.c file implements the splitting up the
extra_string and finding all the parts, as well as some self-tests for
the new function.

Finally, now we know all the details, these can be stored within the
breakpoint object if we end up creating a deferred breakpoint.
Additionally, if we are creating a deferred bp_dprintf we can parse
the extra_string to build the printf command.

Reviewed-By: Eli Zaretskii <eliz@gnu.org>
---
 gdb/Makefile.in                               |   2 +
 gdb/NEWS                                      |   4 +
 gdb/break-cond-parse.c                        | 403 ++++++++++++++++++
 gdb/break-cond-parse.h                        |  47 ++
 gdb/breakpoint.c                              | 330 ++++----------
 gdb/testsuite/gdb.base/condbreak.exp          |  20 +-
 gdb/testsuite/gdb.base/pending.exp            |  23 +-
 gdb/testsuite/gdb.linespec/explicit.exp       |   4 +-
 gdb/testsuite/gdb.mi/mi-dprintf-pending.exp   |   3 +-
 .../gdb.threads/del-pending-thread-bp-lib.c   |  22 +
 .../gdb.threads/del-pending-thread-bp.c       |  85 ++++
 .../gdb.threads/del-pending-thread-bp.exp     | 108 +++++
 12 files changed, 793 insertions(+), 258 deletions(-)
 create mode 100644 gdb/break-cond-parse.c
 create mode 100644 gdb/break-cond-parse.h
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.exp

diff --git a/gdb/Makefile.in b/gdb/Makefile.in
index 14b5dd0bad6..ad7014c8c48 100644
--- a/gdb/Makefile.in
+++ b/gdb/Makefile.in
@@ -1024,6 +1024,7 @@ COMMON_SFILES = \
 	break-catch-sig.c \
 	break-catch-syscall.c \
 	break-catch-throw.c \
+	break-cond-parse.c \
 	breakpoint.c \
 	bt-utils.c \
 	btrace.c \
@@ -1291,6 +1292,7 @@ HFILES_NO_SRCDIR = \
 	bfd-target.h \
 	bfin-tdep.h \
 	block.h \
+	break-cond-parse.h \
 	breakpoint.h \
 	bsd-kvm.h \
 	bsd-uthread.h \
diff --git a/gdb/NEWS b/gdb/NEWS
index 6aa0d5171f2..376c4c223be 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -67,6 +67,10 @@
     break foo thread 1 task 1
     watch var thread 2 task 3
 
+* For breakpoints that are created in the 'pending' state, any
+  'thread' or 'task' keywords are parsed at the time the breakpoint is
+  created, rather than at the time the breakpoint becomes non-pending.
+
 * New commands
 
 maintenance print record-instruction [ N ]
diff --git a/gdb/break-cond-parse.c b/gdb/break-cond-parse.c
new file mode 100644
index 00000000000..e8da24d2643
--- /dev/null
+++ b/gdb/break-cond-parse.c
@@ -0,0 +1,403 @@
+/* Copyright (C) 2023 Free Software Foundation, Inc.
+
+   This file is part of GDB.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#include "defs.h"
+#include "gdbsupport/gdb_assert.h"
+#include "gdbsupport/selftest.h"
+#include "test-target.h"
+#include "scoped-mock-context.h"
+#include "break-cond-parse.h"
+#include "tid-parse.h"
+#include "ada-lang.h"
+
+/* When parsing tokens from a string, which direction are we parsing?
+
+   Given the following string and pointer 'ptr':
+
+     ABC DEF GHI JKL
+            ^
+           ptr
+
+   Parsing 'forward' will return the token 'GHI' and update 'ptr' to point
+   between GHI and JKL.  Parsing 'backward' will return the token 'DEF' and
+   update 'ptr' to point between ABC and DEF.
+*/
+
+enum class parse_direction
+{
+  /* Parse the next token forwards.  */
+  forward,
+
+  /* Parse the previous token backwards.  */
+  backward
+};
+
+struct token
+{
+  /* Create a new token.  START points to the first character of the new
+     token, while END points at the last character of the new token.
+
+     Neither START or END can be nullptr, and both START and END must point
+     into the same C style string (i.e. there should be no null character
+     between START and END).  END must be equal to, or greater than START,
+     that is, it is not possible to create a zero length token.  */
+
+  token (const char *start, const char *end)
+    : m_start (start),
+      m_end (end)
+  {
+    gdb_assert (m_end >= m_start);
+    gdb_assert (m_start + strlen (m_start) > m_end);
+  }
+
+  /* Return a pointer to the first character of this token.  */
+  const char *start () const
+  {
+    return m_start;
+  }
+
+  /* Return a pointer to the last character of this token.  */
+  const char *end () const
+  {
+    return m_end;
+  }
+
+  /* Return the length of the token.  */
+  size_t length () const
+  {
+    return m_end - m_start + 1;
+  }
+
+  /* Return true if this token matches STR.  If this token is shorter than
+     STR then only a partial match is performed and true will be returned
+     if the token length sub-string matches.  Otherwise, return false.  */
+  bool matches (const char *str) const
+  {
+    return strncmp (m_start, str, length ()) == 0;
+  }
+
+private:
+  /* The first character of this token.  */
+  const char *m_start;
+
+  /* The last character of this token.  */
+  const char *m_end;
+};
+
+/* Find the next token in DIRECTION from *CURR.  */
+
+static token
+find_next_token (const char **curr, parse_direction direction)
+{
+  const char *tok_start, *tok_end;
+
+  if (direction == parse_direction::forward)
+    {
+      *curr = skip_spaces (*curr);
+      tok_start = *curr;
+      *curr = skip_to_space (*curr);
+      tok_end = *curr - 1;
+    }
+  else
+    {
+      gdb_assert (direction == parse_direction::backward);
+
+      while (isspace (**curr))
+	--(*curr);
+
+      tok_end = *curr;
+
+      while (!isspace (**curr))
+	--(*curr);
+
+      tok_start = (*curr) + 1;
+    }
+
+  return token (tok_start, tok_end);
+}
+
+/* See break-cond-parse.h.  */
+
+void
+create_breakpoint_parse_arg_string
+  (const char *tok, gdb::unique_xmalloc_ptr<char> *cond_string,
+   int *thread, int *task, gdb::unique_xmalloc_ptr<char> *rest, bool *force)
+{
+  /* Set up the defaults.  */
+  cond_string->reset ();
+  rest->reset ();
+  *thread = -1;
+  *task = -1;
+  *force = false;
+
+  if (tok == nullptr)
+    return;
+
+  const char *cond_start = nullptr;
+  const char *cond_end = nullptr;
+  parse_direction direction = parse_direction::forward;
+  while (*tok != '\0')
+    {
+      /* Find the next token.  If moving backward and this token starts at
+	 the same location as the condition then we must have found the
+	 other end of the condition string -- we're done.  */
+      token t = find_next_token (&tok, direction);
+      if (direction == parse_direction::backward && t.start () <= cond_start)
+	{
+	  cond_end = t.end () + 1;
+	  break;
+	}
+
+      /* We only have a single flag option to check for.  All the other
+	 options take a value so require an additional token to be found.  */
+      if (t.length () > 0 && t.matches ("-force-condition"))
+	{
+	  *force = true;
+	  continue;
+	}
+
+      /* Maybe the first token was the last token in the string.  If this
+	 is the case then we definitely can't try to extract a value
+	 token.  This also means that the token T is meaningless.  Reset
+	 TOK to point at the start of the unknown content and break out of
+	 the loop.  We'll record the unknown part of the string outside of
+	 the scanning loop (below).  */
+      if (direction == parse_direction::forward && *tok == '\0')
+	{
+	  tok = t.start ();
+	  break;
+	}
+
+      /* As before, find the next token and, if we are scanning backwards,
+	 check that we have not reached the start of the condition string.  */
+      token v = find_next_token (&tok, direction);
+      if (direction == parse_direction::backward && v.start () <= cond_start)
+	{
+	  /* Use token T here as that must also be part of the condition
+	     string.  */
+	  cond_end = t.end () + 1;
+	  break;
+	}
+
+      /* When moving backward we will first parse the value token then the
+	 keyword token, so swap them now.  */
+      if (direction == parse_direction::backward)
+	std::swap (t, v);
+
+      /* Check for valid option in token T.  If we find a valid option then
+	 parse the value from the token V.  Except for 'if', that's handled
+	 differently.
+
+         For the 'if' token we need to capture the entire condition
+         string, so record the start of the condition string and then
+         start scanning backwards looking for the end of the condition
+         string.  */
+      if (direction == parse_direction::forward && t.length () > 0
+	  && t.matches ("if"))
+	{
+	  cond_start = v.start ();
+	  tok = tok + strlen (tok);
+	  gdb_assert (*tok == '\0');
+	  --tok;
+	  direction = parse_direction::backward;
+	  continue;
+	}
+      else if (t.length () > 0 && t.matches ("thread"))
+	{
+	  const char *tmptok;
+	  struct thread_info *thr;
+
+	  if (*thread != -1)
+	    error(_("You can specify only one thread."));
+
+	  if (*task != -1)
+	    error (_("You can specify only one of thread or task."));
+
+	  thr = parse_thread_id (v.start (), &tmptok);
+	  const char *expected_end = skip_spaces (v.end () + 1);
+	  if (tmptok != expected_end)
+	    error (_("Junk after thread keyword."));
+	  *thread = thr->global_num;
+	}
+      else if (t.length () > 0 && t.matches ("task"))
+	{
+	  char *tmptok;
+
+	  if (*task != -1)
+	    error(_("You can specify only one task."));
+
+	  if (*thread != -1)
+	    error (_("You can specify only one of thread or task."));
+
+	  *task = strtol (v.start (), &tmptok, 0);
+	  const char *expected_end = v.end () + 1;
+	  if (tmptok != expected_end)
+	    error (_("Junk after task keyword."));
+	  if (!valid_task_id (*task))
+	    error (_("Unknown task %d."), *task);
+	}
+      else
+	{
+	  /* An unknown token.  If we are scanning forward then reset TOK
+	     to point at the start of the unknown content, we record this
+	     outside of the scanning loop (below).
+
+	     If we are scanning backward then unknown content is assumed to
+	     be the other end of the condition string, obviously, this is
+	     just a heuristic, we could be looking at a mistyped command
+	     line, but this will be spotted when the condition is
+	     eventually evaluated.
+
+	     Either way, no more scanning is required after this.  */
+	  if (direction == parse_direction::forward)
+	    tok = t.start ();
+	  else
+	    {
+	      gdb_assert (direction == parse_direction::backward);
+	      cond_end = v.end () + 1;
+	    }
+	  break;
+	}
+    }
+
+  if (cond_start != nullptr)
+    {
+      /* If we found the start of a condition string then we should have
+	 switched to backward scan mode, and found the end of the condition
+	 string.  Capture the whole condition string into COND_STRING now.  */
+      gdb_assert (direction == parse_direction::backward);
+      gdb_assert (cond_end != nullptr);
+      cond_string->reset (savestring (cond_start, cond_end - cond_start));
+    }
+  else if (*tok != '\0')
+    {
+      /* If we didn't have a condition start pointer then we should still
+	 be in forward scanning mode.  If we didn't reach the end of the
+	 input string (TOK is not at the null character) then the rest of
+	 the input string is garbage that we didn't understand.
+
+	 Record the unknown content into REST.  The caller of this function
+	 will report this as an error later on.  We could report the error
+	 here, but we prefer to allow the caller to run other checks, and
+	 prioritise other errors before reporting this problem.  */
+      gdb_assert (direction == parse_direction::forward);
+      rest->reset (savestring (tok, strlen (tok)));
+    }
+}
+
+#if GDB_SELF_TEST
+
+namespace selftests {
+
+/* Run a single test of the create_breakpoint_parse_arg_string function.
+   INPUT is passed to create_breakpoint_parse_arg_string while all other
+   arguments are the expected output from
+   create_breakpoint_parse_arg_string.  */
+
+static void
+test (const char *input, const char *condition, int thread = -1,
+      int task = -1, bool force = false, const char *rest = nullptr)
+{
+  gdb::unique_xmalloc_ptr<char> extracted_condition;
+  gdb::unique_xmalloc_ptr<char> extracted_rest;
+  int extracted_thread, extracted_task;
+  bool extracted_force_condition;
+  std::string exception_msg;
+
+  try
+    {
+      create_breakpoint_parse_arg_string (input, &extracted_condition,
+					  &extracted_thread,
+					  &extracted_task, &extracted_rest,
+					  &extracted_force_condition);
+    }
+  catch (const gdb_exception_error &ex)
+    {
+      string_file buf;
+
+      exception_print (&buf, ex);
+      exception_msg = buf.release ();
+    }
+
+  if ((condition == nullptr) != (extracted_condition.get () == nullptr)
+      || (condition != nullptr
+	  && strcmp (condition, extracted_condition.get ()) != 0)
+      || (rest == nullptr) != (extracted_rest.get () == nullptr)
+      || (rest != nullptr && strcmp (rest, extracted_rest.get ()) != 0)
+      || thread != extracted_thread
+      || task != extracted_task
+      || force != extracted_force_condition
+      || !exception_msg.empty ())
+    {
+      if (run_verbose ())
+	{
+	  debug_printf ("input: '%s'\n", input);
+	  debug_printf ("condition: '%s'\n", extracted_condition.get ());
+	  debug_printf ("rest: '%s'\n", extracted_rest.get ());
+	  debug_printf ("thread: %d\n", extracted_thread);
+	  debug_printf ("task: %d\n", extracted_task);
+	  debug_printf ("forced: %s\n",
+			extracted_force_condition ? "true" : "false");
+	  debug_printf ("exception: '%s'\n", exception_msg.c_str ());
+	}
+
+      /* Report the failure.  */
+      SELF_CHECK (false);
+    }
+}
+
+/* Test the create_breakpoint_parse_arg_string function.  Just wraps
+   multiple calls to the test function above.  */
+
+static void
+create_breakpoint_parse_arg_string_tests (void)
+{
+  gdbarch *arch = current_inferior ()->gdbarch;
+  scoped_restore_current_pspace_and_thread restore;
+  scoped_mock_context<test_target_ops> mock_target (arch);
+
+  int global_thread_num = mock_target.mock_thread.global_num;
+
+  test ("  if blah  ", "blah");
+  test (" if blah thread 1", "blah", global_thread_num);
+  test (" if blah thread 1  ", "blah", global_thread_num);
+  test ("thread 1 woof", nullptr, global_thread_num, -1, false, "woof");
+  test ("thread 1 X", nullptr, global_thread_num, -1, false, "X");
+  test (" if blah thread 1 -force-condition", "blah", global_thread_num,
+	-1, true);
+  test (" -force-condition if blah thread 1", "blah", global_thread_num,
+	-1, true);
+  test (" -force-condition if blah thread 1  ", "blah", global_thread_num,
+	-1, true);
+  test ("thread 1 -force-condition if blah", "blah", global_thread_num,
+	-1, true);
+  test ("if (A::outer::func ())", "(A::outer::func ())");
+}
+
+} // namespace selftests
+#endif /* GDB_SELF_TEST */
+
+void _initialize_break_cond_parse ();
+void
+_initialize_break_cond_parse ()
+{
+#if GDB_SELF_TEST
+  selftests::register_test
+    ("create_breakpoint_parse_arg_string",
+     selftests::create_breakpoint_parse_arg_string_tests);
+#endif
+}
diff --git a/gdb/break-cond-parse.h b/gdb/break-cond-parse.h
new file mode 100644
index 00000000000..ec62b88ea92
--- /dev/null
+++ b/gdb/break-cond-parse.h
@@ -0,0 +1,47 @@
+/* Copyright (C) 2023 Free Software Foundation, Inc.
+
+   This file is part of GDB.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#if !defined (BREAK_COND_PARSE_H)
+#define BREAK_COND_PARSE_H 1
+
+/* Given TOK, a string possibly containing a condition, thread, task and
+   force-condition flag, as accepted by the 'break' command, extract the
+   condition string, thread and task numbers, and the force_condition flag,
+   then set *COND_STRING, *THREAD, *TASK, and *FORCE.
+
+   As TOK is parsed, if an unknown keyword is encountered before the 'if'
+   keyword then everything starting from the unknown keyword is placed into
+   *REST.
+
+   Both *COND and *REST are initialized to nullptr.  If no 'if' keyword is
+   found then *COND will be returned as nullptr.  If no unknown content is
+   found then *REST is returned as nullptr.
+
+   If no thread is found, *THREAD is set to -1.  If no task is found, *TASK
+   is set to -1.  If the -force-condition flag is not found then *FORCE is
+   set to false.
+
+   Due to the free-form nature that the string TOK might take (a 'thread'
+   keyword can appear before or after an 'if' condition) then we end up
+   having to check for keywords from both the start of TOK and the end of
+   TOK.  */
+
+extern void create_breakpoint_parse_arg_string
+  (const char *tok, gdb::unique_xmalloc_ptr<char> *cond_string,
+   int *thread, int *task, gdb::unique_xmalloc_ptr<char> *rest, bool *force);
+
+#endif
diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index f9020c49d90..c4accfb6d28 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -70,6 +70,7 @@
 #include "cli/cli-style.h"
 #include "cli/cli-decode.h"
 #include <unordered_set>
+#include "break-cond-parse.h"
 
 /* readline include files */
 #include "readline/tilde.h"
@@ -6206,20 +6207,7 @@ print_breakpoint_location (const breakpoint *b,
       uiout->field_stream ("at", stb);
     }
   else
-    {
-      uiout->field_string ("pending", b->locspec->to_string ());
-      /* If extra_string is available, it could be holding a condition
-	 or dprintf arguments.  In either case, make sure it is printed,
-	 too, but only for non-MI streams.  */
-      if (!uiout->is_mi_like_p () && b->extra_string != NULL)
-	{
-	  if (b->type == bp_dprintf)
-	    uiout->text (",");
-	  else
-	    uiout->text (" ");
-	  uiout->text (b->extra_string.get ());
-	}
-    }
+    uiout->field_string ("pending", b->locspec->to_string ());
 
   if (loc && is_breakpoint (b)
       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
@@ -8553,8 +8541,8 @@ code_breakpoint::code_breakpoint (struct gdbarch *gdbarch_,
       gdb_assert (extra_string != nullptr);
       update_dprintf_command_list (this);
     }
-  else if (extra_string != nullptr)
-    error (_("Garbage '%s' at end of command"), extra_string.get ());
+  else
+    gdb_assert (extra_string == nullptr);
 
   /* The order of the locations is now stable.  Set the location
      condition using the location's number.  */
@@ -8781,160 +8769,6 @@ check_fast_tracepoint_sals (struct gdbarch *gdbarch,
     }
 }
 
-/* Given TOK, a string specification of condition and thread, as
-   accepted by the 'break' command, extract the condition
-   string and thread number and set *COND_STRING and *THREAD.
-   PC identifies the context at which the condition should be parsed.
-   If no condition is found, *COND_STRING is set to NULL.
-   If no thread is found, *THREAD is set to -1.  */
-
-static void
-find_condition_and_thread (const char *tok, CORE_ADDR pc,
-			   gdb::unique_xmalloc_ptr<char> *cond_string,
-			   int *thread, int *task,
-			   gdb::unique_xmalloc_ptr<char> *rest)
-{
-  cond_string->reset ();
-  *thread = -1;
-  *task = -1;
-  rest->reset ();
-  bool force = false;
-
-  while (tok && *tok)
-    {
-      const char *end_tok;
-      int toklen;
-      const char *cond_start = NULL;
-      const char *cond_end = NULL;
-
-      tok = skip_spaces (tok);
-
-      if ((*tok == '"' || *tok == ',') && rest)
-	{
-	  rest->reset (savestring (tok, strlen (tok)));
-	  return;
-	}
-
-      end_tok = skip_to_space (tok);
-
-      toklen = end_tok - tok;
-
-      if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
-	{
-	  tok = cond_start = end_tok + 1;
-	  try
-	    {
-	      parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
-	    }
-	  catch (const gdb_exception_error &)
-	    {
-	      if (!force)
-		throw;
-	      else
-		tok = tok + strlen (tok);
-	    }
-	  cond_end = tok;
-	  cond_string->reset (savestring (cond_start, cond_end - cond_start));
-	}
-      else if (toklen >= 1 && strncmp (tok, "-force-condition", toklen) == 0)
-	{
-	  tok = tok + toklen;
-	  force = true;
-	}
-      else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
-	{
-	  const char *tmptok;
-	  struct thread_info *thr;
-
-	  if (*thread != -1)
-	    error(_("You can specify only one thread."));
-
-	  if (*task != -1)
-	    error (_("You can specify only one of thread or task."));
-
-	  tok = end_tok + 1;
-	  thr = parse_thread_id (tok, &tmptok);
-	  if (tok == tmptok)
-	    error (_("Junk after thread keyword."));
-	  *thread = thr->global_num;
-	  tok = tmptok;
-	}
-      else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
-	{
-	  char *tmptok;
-
-	  if (*task != -1)
-	    error(_("You can specify only one task."));
-
-	  if (*thread != -1)
-	    error (_("You can specify only one of thread or task."));
-
-	  tok = end_tok + 1;
-	  *task = strtol (tok, &tmptok, 0);
-	  if (tok == tmptok)
-	    error (_("Junk after task keyword."));
-	  if (!valid_task_id (*task))
-	    error (_("Unknown task %d."), *task);
-	  tok = tmptok;
-	}
-      else if (rest)
-	{
-	  rest->reset (savestring (tok, strlen (tok)));
-	  return;
-	}
-      else
-	error (_("Junk at end of arguments."));
-    }
-}
-
-/* Call 'find_condition_and_thread' for each sal in SALS until a parse
-   succeeds.  The parsed values are written to COND_STRING, THREAD,
-   TASK, and REST.  See the comment of 'find_condition_and_thread'
-   for the description of these parameters and INPUT.  */
-
-static void
-find_condition_and_thread_for_sals (const std::vector<symtab_and_line> &sals,
-				    const char *input,
-				    gdb::unique_xmalloc_ptr<char> *cond_string,
-				    int *thread, int *task,
-				    gdb::unique_xmalloc_ptr<char> *rest)
-{
-  int num_failures = 0;
-  for (auto &sal : sals)
-    {
-      gdb::unique_xmalloc_ptr<char> cond;
-      int thread_id = -1;
-      int task_id = -1;
-      gdb::unique_xmalloc_ptr<char> remaining;
-
-      /* Here we want to parse 'arg' to separate condition from thread
-	 number.  But because parsing happens in a context and the
-	 contexts of sals might be different, try each until there is
-	 success.  Finding one successful parse is sufficient for our
-	 goal.  When setting the breakpoint we'll re-parse the
-	 condition in the context of each sal.  */
-      try
-	{
-	  find_condition_and_thread (input, sal.pc, &cond, &thread_id,
-				     &task_id, &remaining);
-	  *cond_string = std::move (cond);
-	  /* At most one of thread or task can be set.  */
-	  gdb_assert (thread_id == -1 || task_id == -1);
-	  *thread = thread_id;
-	  *task = task_id;
-	  *rest = std::move (remaining);
-	  break;
-	}
-      catch (const gdb_exception_error &e)
-	{
-	  num_failures++;
-	  /* If no sal remains, do not continue.  */
-	  if (num_failures == sals.size ())
-	    throw;
-	}
-    }
-}
-
 /* Decode a static tracepoint marker spec.  */
 
 static std::vector<symtab_and_line>
@@ -9045,6 +8879,44 @@ create_breakpoint (struct gdbarch *gdbarch,
 	      || (type_wanted != bp_dprintf
 		  && (extra_string == nullptr || parse_extra)));
 
+  /* Will hold either copies of the similarly named function argument, or
+     will hold a modified version of the function argument, depending on
+     the value of PARSE_EXTRA.  */
+  gdb::unique_xmalloc_ptr<char> cond_string_copy;
+  gdb::unique_xmalloc_ptr<char> extra_string_copy;
+
+  if (parse_extra)
+    {
+      /* Parse EXTRA_STRING splitting the parts out.  */
+      create_breakpoint_parse_arg_string (extra_string, &cond_string_copy,
+					  &thread, &task, &extra_string_copy,
+					  &force_condition);
+
+      /* We could check that EXTRA_STRING_COPY is empty at this point -- it
+	 should be, as we only get here for things that are not bp_dprintf,
+	 however, we prefer to give the location spec parser a chance to
+	 run first, this means the user will get errors about invalid
+	 location spec instead of an error about garbage at the end of the
+	 command line.
+
+	 We still do the EXTRA_STRING_COPY is empty check, just later in
+	 this function.  */
+
+      gdb_assert (thread == -1 || thread > 0);
+      gdb_assert (task == -1 || task > 0);
+    }
+  else
+    {
+      if (cond_string != nullptr)
+	cond_string_copy.reset (xstrdup (cond_string));
+      if (extra_string != nullptr)
+	extra_string_copy.reset (xstrdup (extra_string));
+    }
+
+  /* Clear these.  Updated values are now held in the *_copy locals.  */
+  cond_string = nullptr;
+  extra_string = nullptr;
+
   try
     {
       ops->create_sals_from_location_spec (locspec, &canonical);
@@ -9080,6 +8952,13 @@ create_breakpoint (struct gdbarch *gdbarch,
 	throw;
     }
 
+  /* The only bp_dprintf should have anything in EXTRA_STRING_COPY by this
+     point.  For all other breakpoints this indicates an error.  We could
+     place this check earlier in the function, but we prefer to see errors
+     from the location spec parser before we see this error message.  */
+  if (type_wanted != bp_dprintf && extra_string_copy.get () != nullptr)
+    error (_("Garbage '%s' at end of command"), extra_string_copy.get ());
+
   if (!pending && canonical.lsals.empty ())
     return 0;
 
@@ -9103,62 +8982,31 @@ create_breakpoint (struct gdbarch *gdbarch,
      breakpoint.  */
   if (!pending)
     {
-      gdb::unique_xmalloc_ptr<char> cond_string_copy;
-      gdb::unique_xmalloc_ptr<char> extra_string_copy;
-
-      if (parse_extra)
+      /* Check the validity of the condition.  We should error out if the
+	 condition is invalid at all of the locations and if it is not
+	 forced.  In the PARSE_EXTRA case above, this check is done when
+	 parsing the EXTRA_STRING.  */
+      if (cond_string_copy.get () != nullptr && !force_condition)
 	{
-	  gdb_assert (type_wanted != bp_dprintf);
-
-	  gdb::unique_xmalloc_ptr<char> rest;
-	  gdb::unique_xmalloc_ptr<char> cond;
-
+	  int num_failures = 0;
 	  const linespec_sals &lsal = canonical.lsals[0];
-
-	  find_condition_and_thread_for_sals (lsal.sals, extra_string,
-					      &cond, &thread, &task, &rest);
-
-	  if (rest.get () != nullptr && *(rest.get ()) != '\0')
-	    error (_("Garbage '%s' at end of command"), rest.get ());
-
-	  cond_string_copy = std::move (cond);
-	  extra_string_copy = std::move (rest);
-	}
-      else
-	{
-	  /* Check the validity of the condition.  We should error out
-	     if the condition is invalid at all of the locations and
-	     if it is not forced.  In the PARSE_EXTRA case above, this
-	     check is done when parsing the EXTRA_STRING.  */
-	  if (cond_string != nullptr && !force_condition)
+	  for (const auto &sal : lsal.sals)
 	    {
-	      int num_failures = 0;
-	      const linespec_sals &lsal = canonical.lsals[0];
-	      for (const auto &sal : lsal.sals)
+	      const char *cond = cond_string_copy.get ();
+	      try
 		{
-		  const char *cond = cond_string;
-		  try
-		    {
-		      parse_exp_1 (&cond, sal.pc, block_for_pc (sal.pc), 0);
-		      /* One success is sufficient to keep going.  */
-		      break;
-		    }
-		  catch (const gdb_exception_error &)
-		    {
-		      num_failures++;
-		      /* If this is the last sal, error out.  */
-		      if (num_failures == lsal.sals.size ())
-			throw;
-		    }
+		  parse_exp_1 (&cond, sal.pc, block_for_pc (sal.pc), 0);
+		  /* One success is sufficient to keep going.  */
+		  break;
+		}
+	      catch (const gdb_exception_error &)
+		{
+		  num_failures++;
+		  /* If this is the last sal, error out.  */
+		  if (num_failures == lsal.sals.size ())
+		    throw;
 		}
 	    }
-
-	  /* Create a private copy of condition string.  */
-	  if (cond_string)
-	    cond_string_copy.reset (xstrdup (cond_string));
-	  /* Create a private copy of any extra string.  */
-	  if (extra_string)
-	    extra_string_copy.reset (xstrdup (extra_string));
 	}
 
       ops->create_breakpoints_sal (gdbarch, &canonical,
@@ -9175,21 +9023,15 @@ create_breakpoint (struct gdbarch *gdbarch,
 								 type_wanted);
       b->locspec = locspec->clone ();
 
-      if (parse_extra)
-	b->cond_string = NULL;
-      else
-	{
-	  /* Create a private copy of condition string.  */
-	  b->cond_string.reset (cond_string != NULL
-				? xstrdup (cond_string)
-				: NULL);
-	  b->thread = thread;
-	}
+      /* Create a private copy of condition string.  */
+      b->cond_string = std::move (cond_string_copy);
+
+      b->thread = thread;
+      b->task = task;
 
       /* Create a private copy of any extra string.  */
-      b->extra_string.reset (extra_string != NULL
-			     ? xstrdup (extra_string)
-			     : NULL);
+      b->extra_string = std::move (extra_string_copy);
+
       b->ignore_count = ignore_count;
       b->disposition = tempflag ? disp_del : disp_donttouch;
       b->condition_not_parsed = 1;
@@ -9198,9 +9040,12 @@ create_breakpoint (struct gdbarch *gdbarch,
 	   && type_wanted != bp_hardware_breakpoint) || thread != -1)
 	b->pspace = current_program_space;
 
+      if (type_wanted == bp_dprintf)
+	update_dprintf_command_list (b.get ());
+
       install_breakpoint (internal, std::move (b), 0);
     }
-  
+
   if (canonical.lsals.size () > 1)
     {
       warning (_("Multiple breakpoints were set.\nUse the "
@@ -12916,23 +12761,6 @@ code_breakpoint::location_spec_to_sals (location_spec *locspec,
     {
       for (auto &sal : sals)
 	resolve_sal_pc (&sal);
-      if (condition_not_parsed && extra_string != NULL)
-	{
-	  gdb::unique_xmalloc_ptr<char> local_cond, local_extra;
-	  int local_thread, local_task;
-
-	  find_condition_and_thread_for_sals (sals, extra_string.get (),
-					      &local_cond, &local_thread,
-					      &local_task, &local_extra);
-	  gdb_assert (cond_string == nullptr);
-	  if (local_cond != nullptr)
-	    cond_string = std::move (local_cond);
-	  thread = local_thread;
-	  task = local_task;
-	  if (local_extra != nullptr)
-	    extra_string = std::move (local_extra);
-	  condition_not_parsed = 0;
-	}
 
       if (type == bp_static_tracepoint)
 	sals[0] = update_static_tracepoint (this, sals[0]);
diff --git a/gdb/testsuite/gdb.base/condbreak.exp b/gdb/testsuite/gdb.base/condbreak.exp
index a5b2a28701b..50ae82c3f32 100644
--- a/gdb/testsuite/gdb.base/condbreak.exp
+++ b/gdb/testsuite/gdb.base/condbreak.exp
@@ -179,6 +179,10 @@ gdb_test "break -q main if (1==1) thread 999" \
     "Unknown thread 999\\."
 gdb_test "break -q main thread 999 if (1==1)" \
     "Unknown thread 999\\."
+gdb_test "break -q main if (1==1) thread 999 -force-condition" \
+    "Unknown thread 999\\."
+gdb_test "break -q main thread 999 if (1==1) -force-condition" \
+    "Unknown thread 999\\."
 
 # Verify that both if and thread can be distinguished from a breakpoint
 # address expression.
@@ -186,20 +190,34 @@ gdb_test "break *main if (1==1) thread 999" \
     "Unknown thread 999\\."
 gdb_test "break *main thread 999 if (1==1)" \
     "Unknown thread 999\\."
+gdb_test "break *main if (1==1) thread 999 -force-condition" \
+    "Unknown thread 999\\."
+gdb_test "break *main thread 999 if (1==1) -force-condition" \
+    "Unknown thread 999\\."
 
 # Similarly for task.
 gdb_test "break *main if (1==1) task 999" \
     "Unknown task 999\\."
 gdb_test "break *main task 999 if (1==1)" \
     "Unknown task 999\\."
+gdb_test "break *main if (1==1) task 999 -force-condition" \
+    "Unknown task 999\\."
+gdb_test "break *main task 999 if (1==1) -force-condition" \
+    "Unknown task 999\\."
 
-# GDB accepts abbreviations for "thread" and "task".
+# GDB accepts abbreviations for "thread" and "task" and "-force-condition"
 gdb_test "break *main if (1==1) t 999" \
     "Unknown thread 999\\."
 gdb_test "break *main if (1==1) th 999" \
     "Unknown thread 999\\."
 gdb_test "break *main if (1==1) ta 999" \
     "Unknown task 999\\."
+gdb_test "break *main if (1==1) t 999 -force" \
+    "Unknown thread 999\\."
+gdb_test "break *main if (1==1) th 999 -force" \
+    "Unknown thread 999\\."
+gdb_test "break *main if (1==1) ta 999 -force" \
+    "Unknown task 999\\."
 
 set test "run until breakpoint at marker3"
 gdb_test_multiple "continue" $test {
diff --git a/gdb/testsuite/gdb.base/pending.exp b/gdb/testsuite/gdb.base/pending.exp
index d7d3735000a..645f63bdb16 100644
--- a/gdb/testsuite/gdb.base/pending.exp
+++ b/gdb/testsuite/gdb.base/pending.exp
@@ -170,7 +170,8 @@ gdb_test "info break" \
 \[\t \]+stop only if k == 1.*
 \[\t \]+print k.*
 \[0-9\]+\[\t \]+breakpoint     keep y.* in main at .*$srcfile:$mainline.*
-\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc if x > 3.*" \
+\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc.*
+\\s+stop only if x > 3.*" \
 "multiple pending breakpoints"
 
 
@@ -195,8 +196,10 @@ gdb_test "info break" \
 \[\t \]+stop only if k == 1.*
 \[\t \]+print k.*
 \[0-9\]+\[\t \]+breakpoint     keep y.* in main at .*$srcfile:$mainline.*
-\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc if x > 3.*
-\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp3_loc.*ignore next 2 hits.*" \
+\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc.*
+\\s+stop only if x > 3.*
+\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp3_loc.*
+\\s+ignore next 2 hits.*" \
 "multiple pending breakpoints 2"
 
 #
@@ -267,3 +270,17 @@ gdb_test "info break" \
 \[0-9\]+\[\t \]+breakpoint     keep y.* in main at .*$srcfile:$mainline.*
 \[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*imaginary.*" \
 "verify pending breakpoint after restart"
+
+# Test GDB's parsing of pending breakpoint thread and condition.
+
+gdb_test_no_output "set breakpoint pending on"
+gdb_test "break foo if (unknown_var && another_unknown_var) thread 1" \
+    "Breakpoint $decimal \\(foo\\) pending\\."
+set bpnum [get_integer_valueof "\$bpnum" "*INVALID" \
+	       "get number for foo breakpoint"]
+gdb_test "info breakpoints $bpnum" \
+    [multi_line \
+	 "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	 "\\s+stop only if \\(unknown_var && another_unknown_var\\)" \
+	 "\\s+stop only in thread 1"] \
+    "check pending breakpoint on foo"
diff --git a/gdb/testsuite/gdb.linespec/explicit.exp b/gdb/testsuite/gdb.linespec/explicit.exp
index b08d65953d2..7c8b2475881 100644
--- a/gdb/testsuite/gdb.linespec/explicit.exp
+++ b/gdb/testsuite/gdb.linespec/explicit.exp
@@ -574,7 +574,7 @@ namespace eval $testfile {
 	      allow-pending]} {
 	fail "set $tst"
     } else {
-	gdb_test "info break" ".*PENDING.*myfunction if foofoofoo == 1.*" $tst
+	gdb_test "info break" ".*PENDING.*myfunction\r\n\\s+stop only if foofoofoo == 1.*" $tst
     }
 
     gdb_exit
@@ -585,7 +585,7 @@ namespace eval $testfile {
 	      allow-pending]} {
 	fail "set $tst"
     } else {
-	gdb_test "info break" ".*PENDING.*myfunction if arg == 0" $tst
+	gdb_test "info break" ".*PENDING.*myfunction\r\n\\s+stop only if arg == 0" $tst
 
 	gdb_load [standard_output_file $exefile]
 	gdb_test "info break" \
diff --git a/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp b/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp
index 28f52938aeb..bb9987a5572 100644
--- a/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp
+++ b/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp
@@ -50,7 +50,8 @@ set bp_location1 [gdb_get_line_number "set breakpoint 1 here"]
 # Set pending dprintf via MI.
 set bp [mi_make_breakpoint_pending -number "1" -type "dprintf" \
 	    -disp "keep" -enabled "y" -pending "pendfunc1" \
-	    -original-location "pendfunc1"]
+	    -original-location "pendfunc1" \
+	    -script {\["printf \\\"hello\\\""\]}]
 mi_gdb_test "-dprintf-insert -f pendfunc1 \"hello\"" \
     ".*\\^done,$bp" "mi set dprintf"
 
diff --git a/gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c b/gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
new file mode 100644
index 00000000000..15d1b9833dd
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
@@ -0,0 +1,22 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+int global_var = 0;
+
+void
+foo (int arg)
+{
+  global_var = arg;
+}
diff --git a/gdb/testsuite/gdb.threads/del-pending-thread-bp.c b/gdb/testsuite/gdb.threads/del-pending-thread-bp.c
new file mode 100644
index 00000000000..938e05bc4d7
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/del-pending-thread-bp.c
@@ -0,0 +1,85 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#include <dlfcn.h>
+#include <pthread.h>
+#include <stdlib.h>
+
+pthread_barrier_t barrier;
+
+static void
+barrier_wait (pthread_barrier_t *b)
+{
+  int res = pthread_barrier_wait (b);
+  if (res != 0 && res != PTHREAD_BARRIER_SERIAL_THREAD)
+    abort ();
+}
+
+static void *
+thread_worker (void *arg)
+{
+  barrier_wait (&barrier);
+  return NULL;
+}
+
+void
+breakpt ()
+{
+  /* Nothing.  */
+}
+
+int
+main (void)
+{
+  void *handle;
+  void (*func)(int);
+  pthread_t thread;
+
+  if (pthread_barrier_init (&barrier, NULL, 2) != 0)
+    abort ();
+
+  if (pthread_create (&thread, NULL, thread_worker, NULL) != 0)
+    abort ();
+
+  breakpt ();
+
+  /* Allow the worker thread to complete.  */
+  barrier_wait (&barrier);
+
+  if (pthread_join (thread, NULL) != 0)
+    abort ();
+
+  breakpt ();
+
+  /* Now load the shared library.  */
+  handle = dlopen (SHLIB_NAME, RTLD_LAZY);
+  if (handle == NULL)
+    abort ();
+
+  /* Find the function symbol.  */
+  func = (void (*)(int)) dlsym (handle, "foo");
+
+  /* Call the library function.  */
+  func (1);
+
+  /* Unload the shared library.  */
+  if (dlclose (handle) != 0)
+    abort ();
+
+  breakpt ();
+
+  return 0;
+}
+
diff --git a/gdb/testsuite/gdb.threads/del-pending-thread-bp.exp b/gdb/testsuite/gdb.threads/del-pending-thread-bp.exp
new file mode 100644
index 00000000000..4ed05eaa42d
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/del-pending-thread-bp.exp
@@ -0,0 +1,108 @@
+# Copyright 2023 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+# This test checks that pending thread-specific breakpoints are
+# correctly deleted when the thread the breakpoint is for goes out of
+# scope.
+#
+# We also check that we can't create a pending thread-specific
+# breakpoint for a non-existent thread.
+
+require allow_shlib_tests
+
+standard_testfile
+
+set libname $testfile-lib
+set srcfile_lib $srcdir/$subdir/$libname.c
+set binfile_lib [standard_output_file $libname.so]
+
+if { [gdb_compile_shlib $srcfile_lib $binfile_lib {}] != "" } {
+    untested "failed to compile shared library 1"
+    return -1
+}
+
+set binfile_lib_target [gdb_download_shlib $binfile_lib]
+
+if { [prepare_for_testing "failed to prepare" $testfile $srcfile \
+	  [list debug \
+	       additional_flags=-DSHLIB_NAME=\"$binfile_lib_target\" \
+	       shlib_load pthreads]] } {
+    return -1
+}
+
+gdb_locate_shlib $binfile_lib
+
+if ![runto_main] {
+    return 0
+}
+
+# Run until we have two threads.
+gdb_breakpoint "breakpt"
+gdb_continue_to_breakpoint "first breakpt call"
+
+# Confirm that we have a thread '2'.
+gdb_test "info threads" "\r\n\\s+2\\s+\[^\r\n\]+"
+
+# Create a pending, thread-specific, breakpoint on 'foo'.
+gdb_breakpoint "foo thread 2" allow-pending
+set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+	       "get breakpoint number"]
+
+# Check we can't create a pending thread-specific breakpoint for a
+# non-existent thread.
+gdb_test "with breakpoint pending on -- break foo thread 99" \
+    "Unknown thread 99\\."
+
+# Continue to 'breakpt' again.  Don't use gdb_continue_to_breakpoint
+# as we are looking for the thread exited and breakpoint deleted
+# messages.
+set output [list "Continuing\\."]
+
+if {!([target_info exists gdb_protocol]
+      && ([target_info gdb_protocol] == "remote"
+	  || [target_info gdb_protocol] == "extended-remote"))} {
+    # Due to bug PR gdb/30129 we don't see the thread exited messages
+    # for remote targets.  When this bit of this test can be cleaned
+    # up.
+    lappend output "\\\[Thread \[^\r\n\]+ exited\\\]"
+}
+
+lappend output "Thread-specific breakpoint $bpnum deleted - thread 2 no longer in the thread list\\." \
+    "" \
+    "Thread 1 \[^\r\n\]+, breakpt \\(\\) at \[^\r\n\]+" \
+    "$decimal\\s+\[^\r\n\]+"
+
+gdb_test "continue" \
+    [multi_line {*}$output] \
+    "second breakpt call"
+
+# Confirm breakpoint has been deleted.
+gdb_test "info breakpoints $bpnum" \
+    "No breakpoint or watchpoint matching '$bpnum'\\."
+
+# Continue again.  This will pass through 'foo'.  We should not stop
+# in 'foo', the breakpoint has been deleted.  We should next stop in
+# breakpt again.
+gdb_test "continue" \
+    [multi_line \
+	 "Continuing\\." \
+	 "" \
+	 "Thread 1 \[^\r\n\]+ hit Breakpoint $decimal, breakpt \\(\\) at \[^\r\n\]+" \
+	 "$decimal\\s+\[^\r\n\]+"] \
+    "third breakpt call"
+gdb_test "bt 1" \
+    [multi_line \
+	 "#0\\s+breakpt \\(\\) at \[^\r\n\]+" \
+	 "\\(More stack frames follow\\.\\.\\.\\)"]
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv2 7/9] gdb: remove breakpoint_re_set_one
  2023-05-15 19:27 ` [PATCHv2 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
                     ` (5 preceding siblings ...)
  2023-05-15 19:27   ` [PATCHv2 6/9] gdb: parse pending breakpoint thread/task immediately Andrew Burgess
@ 2023-05-15 19:27   ` Andrew Burgess
  2023-05-15 19:27   ` [PATCHv2 8/9] gdb: remove tracepoint_probe_create_sals_from_location_spec Andrew Burgess
                     ` (2 subsequent siblings)
  9 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-05-15 19:27 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

During a later patch I wanted to reset a single breakpoint, so I
called breakpoint_re_set_one.  However, this is not the right thing to
do.  If we look at breakpoint_re_set then we see that there's a whole
bunch of state that needs to be preserved prior to calling
breakpoint_re_set_one, and after calling breakpoint_re_set_one we
still need to call update_global_location_list.

I could just update the comment on breakpoint_re_set_one to make it
clearer how the function should be used -- or more likely to warn that
the function should only be used as a helper from breakpoint_re_set.

However, breakpoint_re_set_one is only 3 lines long.  So I figure it
might actually be easier to just fold breakpoint_re_set_one into
breakpoint_re_set, then there's no risk of accidentally calling
breakpoint_re_set_one when we shouldn't.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c | 26 ++++++++------------------
 1 file changed, 8 insertions(+), 18 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index c4accfb6d28..be035def12a 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -12812,17 +12812,6 @@ create_sals_from_location_spec_default (location_spec *locspec,
   parse_breakpoint_sals (locspec, canonical);
 }
 
-/* Reset a breakpoint.  */
-
-static void
-breakpoint_re_set_one (breakpoint *b)
-{
-  input_radix = b->input_radix;
-  set_language (b->language);
-
-  b->re_set ();
-}
-
 /* Re-set breakpoint locations for the current program space.
    Locations bound to other program spaces are left untouched.  */
 
@@ -12834,12 +12823,11 @@ breakpoint_re_set (void)
     scoped_restore save_input_radix = make_scoped_restore (&input_radix);
     scoped_restore_current_pspace_and_thread restore_pspace_thread;
 
-    /* breakpoint_re_set_one sets the current_language to the language
-       of the breakpoint it is resetting (see prepare_re_set_context)
-       before re-evaluating the breakpoint's location.  This change can
-       unfortunately get undone by accident if the language_mode is set
-       to auto, and we either switch frames, or more likely in this context,
-       we select the current frame.
+    /* To ::re_set each breakpoint we set the current_language to the
+       language of the breakpoint before re-evaluating the breakpoint's
+       location.  This change can unfortunately get undone by accident if
+       the language_mode is set to auto, and we either switch frames, or
+       more likely in this context, we select the current frame.
 
        We prevent this by temporarily turning the language_mode to
        language_mode_manual.  We restore it once all breakpoints
@@ -12856,7 +12844,9 @@ breakpoint_re_set (void)
       {
 	try
 	  {
-	    breakpoint_re_set_one (b);
+	    input_radix = b->input_radix;
+	    set_language (b->language);
+	    b->re_set ();
 	  }
 	catch (const gdb_exception &ex)
 	  {
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv2 8/9] gdb: remove tracepoint_probe_create_sals_from_location_spec
  2023-05-15 19:27 ` [PATCHv2 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
                     ` (6 preceding siblings ...)
  2023-05-15 19:27   ` [PATCHv2 7/9] gdb: remove breakpoint_re_set_one Andrew Burgess
@ 2023-05-15 19:27   ` Andrew Burgess
  2023-05-15 19:27   ` [PATCHv2 9/9] gdb: only insert thread-specific breakpoints in the relevant inferior Andrew Burgess
  2023-05-30 20:46   ` [PATCHv3 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
  9 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-05-15 19:27 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

The tracepoint_probe_create_sals_from_location_spec function just
forwards all its arguments to
bkpt_probe_create_sals_from_location_spec, and is only used in one
place.

Lets delete tracepoint_probe_create_sals_from_location_spec and
replace it with bkpt_probe_create_sals_from_location_spec.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c | 19 +++----------------
 1 file changed, 3 insertions(+), 16 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index be035def12a..3964665d867 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -221,9 +221,6 @@ static bool strace_marker_p (struct breakpoint *b);
 static void bkpt_probe_create_sals_from_location_spec
      (location_spec *locspec,
       struct linespec_result *canonical);
-static void tracepoint_probe_create_sals_from_location_spec
-     (location_spec *locspec,
-      struct linespec_result *canonical);
 
 const struct breakpoint_ops code_breakpoint_ops =
 {
@@ -238,10 +235,11 @@ static const struct breakpoint_ops bkpt_probe_breakpoint_ops =
   create_breakpoints_sal,
 };
 
-/* Tracepoints set on probes.  */
+/* Tracepoints set on probes.  We use the same methods as for breakpoints
+   on probes.  */
 static const struct breakpoint_ops tracepoint_probe_breakpoint_ops =
 {
-  tracepoint_probe_create_sals_from_location_spec,
+  bkpt_probe_create_sals_from_location_spec,
   create_breakpoints_sal,
 };
 
@@ -12007,17 +12005,6 @@ tracepoint::print_recreate (struct ui_file *fp) const
     gdb_printf (fp, "  passcount %d\n", pass_count);
 }
 
-/* Virtual table for tracepoints on static probes.  */
-
-static void
-tracepoint_probe_create_sals_from_location_spec
-  (location_spec *locspec,
-   struct linespec_result *canonical)
-{
-  /* We use the same method for breakpoint on probes.  */
-  bkpt_probe_create_sals_from_location_spec (locspec, canonical);
-}
-
 void
 dprintf_breakpoint::re_set ()
 {
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv2 9/9] gdb: only insert thread-specific breakpoints in the relevant inferior
  2023-05-15 19:27 ` [PATCHv2 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
                     ` (7 preceding siblings ...)
  2023-05-15 19:27   ` [PATCHv2 8/9] gdb: remove tracepoint_probe_create_sals_from_location_spec Andrew Burgess
@ 2023-05-15 19:27   ` Andrew Burgess
  2023-05-30 20:46   ` [PATCHv3 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
  9 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-05-15 19:27 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Eli Zaretskii

Eli approved the docs changes here:

  https://sourceware.org/pipermail/gdb-patches/2023-April/199222.html

---

This commit updates GDB so that thread-specific breakpoints are only
inserted into the inferior that contains the thread we are interested
in.

Actually, as breakpoints are placed in program spaces, we insert the
breakpoint in any inferior that shares a program space with the
inferior containing the thread we are interested in.  But as far as
most users are concerned this really means the one inferior.

In terms of implementation, getting this basically working is easy
enough, now that a breakpoint's thread field is setup prior to GDB
looking for locations, we can easily use the thread to find a suitable
program_space and pass this to as a filter when creating the sals.

Or we could if breakpoint_ops::create_sals_from_location_spec allowed
us to pass in a filter program_space.

So, this commit extends breakpoint_ops::create_sals_from_location_spec
to take a program_space argument, and uses this to filter the set of
returned sals.  This accounts for about half the change in this patch.

The second set of changes starts from breakpoint_set_thread, this is
called when the thread for a thread-specific breakpoint changes,
e.g. from the Python API.

Previously this call would never result in the locations of a
breakpoint changing, after all, locations were inserted in every
program space, and we just use the thread field to decide when we
should stop.  Now though, changing a breakpoint's thread can mean we
need to figure out a new set of breakpoint locations.

To support this I've added a new breakpoint_re_set_one function, which
is like breakpoint_re_set, but takes a single breakpoint, and just
updates the locations for that one breakpoint.  We only need to call
this function if the program_space in which a breakpoint's thread is
running actually changes.  If the program_space does change then we
call the new breakpoint_re_set_one function passing in the
program_space which should be used to filter the locations (or nullptr
to indicate we should set locations in all program spaces).  This
filter program_space needs to propagate down to all the re_set
methods, this accounts for the remaining half of the changes in this
patch.

There were a couple of existing tests that created thread-specific
breakpoints and then checked the 'info breakpoints' output, these
needed updating.  These were:

  gdb.mi/user-selected-context-sync.exp
  gdb.multi/bp-thread-specific.exp
  gdb.multi/multi-target-continue.exp
  gdb.multi/multi-target-ping-pong-next.exp
  gdb.multi/tids.exp

I've also added some additional tests to:

  gdb.multi/pending-bp.exp

I've updated the documentation and added a NEWS entry.

Reviewed-By: Eli Zaretskii <eliz@gnu.org>
---
 gdb/NEWS                                      |   7 +
 gdb/ada-lang.c                                |   6 +-
 gdb/break-catch-throw.c                       |   6 +-
 gdb/breakpoint.c                              | 236 ++++++++++++++----
 gdb/breakpoint.h                              |  26 +-
 .../gdb.mi/user-selected-context-sync.exp     |   2 +-
 .../gdb.multi/bp-thread-specific.exp          |   7 +-
 .../gdb.multi/multi-target-continue.exp       |   2 +-
 .../gdb.multi/multi-target-ping-pong-next.exp |   4 +-
 gdb/testsuite/gdb.multi/pending-bp.exp        | 206 +++++++++++++++
 gdb/testsuite/gdb.multi/tids.exp              |   6 +-
 11 files changed, 427 insertions(+), 81 deletions(-)

diff --git a/gdb/NEWS b/gdb/NEWS
index 376c4c223be..8e0ed944fcf 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -71,6 +71,13 @@
   'thread' or 'task' keywords are parsed at the time the breakpoint is
   created, rather than at the time the breakpoint becomes non-pending.
 
+* Thread-specific breakpoints are only inserted into the program space
+  in which the thread of interest is running.  In most cases program
+  spaces are unique for each inferior, so this means that
+  thread-specific breakpoints will usually only be inserted for the
+  inferior containing the thread of interest.  The breakpoint will
+  be hit no less than before.
+
 * New commands
 
 maintenance print record-instruction [ N ]
diff --git a/gdb/ada-lang.c b/gdb/ada-lang.c
index 21f3348a161..474601274ad 100644
--- a/gdb/ada-lang.c
+++ b/gdb/ada-lang.c
@@ -12176,7 +12176,7 @@ struct ada_catchpoint : public code_breakpoint
   }
 
   struct bp_location *allocate_location () override;
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   void check_status (struct bpstat *bs) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   bool print_one (bp_location **) const override;
@@ -12270,11 +12270,11 @@ ada_catchpoint::allocate_location ()
    catchpoint kinds.  */
 
 void
-ada_catchpoint::re_set ()
+ada_catchpoint::re_set (program_space *pspace)
 {
   /* Call the base class's method.  This updates the catchpoint's
      locations.  */
-  this->code_breakpoint::re_set ();
+  this->code_breakpoint::re_set (pspace);
 
   /* Reparse the exception conditional expressions.  One for each
      location.  */
diff --git a/gdb/break-catch-throw.c b/gdb/break-catch-throw.c
index 457446efbc6..854ca6a624c 100644
--- a/gdb/break-catch-throw.c
+++ b/gdb/break-catch-throw.c
@@ -82,10 +82,10 @@ struct exception_catchpoint : public code_breakpoint
 				     _("invalid type-matching regexp")))
   {
     pspace = current_program_space;
-    re_set ();
+    re_set (pspace);
   }
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   bool print_one (bp_location **) const override;
   void print_mention () const override;
@@ -200,7 +200,7 @@ exception_catchpoint::check_status (struct bpstat *bs)
 /* Implement the 're_set' method.  */
 
 void
-exception_catchpoint::re_set ()
+exception_catchpoint::re_set (program_space *pspace)
 {
   std::vector<symtab_and_line> sals;
   struct program_space *filter_pspace = current_program_space;
diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 3964665d867..53c0c69a441 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -90,9 +90,12 @@
 static void map_breakpoint_numbers (const char *,
 				    gdb::function_view<void (breakpoint *)>);
 
-static void
-  create_sals_from_location_spec_default (location_spec *locspec,
-					  linespec_result *canonical);
+static void parse_breakpoint_sals (location_spec *locspec,
+				   linespec_result *canonical,
+				   program_space *search_pspace);
+
+static void breakpoint_re_set_one (breakpoint *b,
+				   program_space *filter_pspace);
 
 static void create_breakpoints_sal (struct gdbarch *,
 				    struct linespec_result *,
@@ -220,11 +223,12 @@ static bool strace_marker_p (struct breakpoint *b);
 
 static void bkpt_probe_create_sals_from_location_spec
      (location_spec *locspec,
-      struct linespec_result *canonical);
+      struct linespec_result *canonical,
+      struct program_space *search_pspace);
 
 const struct breakpoint_ops code_breakpoint_ops =
 {
-  create_sals_from_location_spec_default,
+  parse_breakpoint_sals,
   create_breakpoints_sal,
 };
 
@@ -289,7 +293,7 @@ struct internal_breakpoint : public code_breakpoint
     disposition = disp_donttouch;
   }
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   void check_status (struct bpstat *bs) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   void print_mention () const override;
@@ -323,7 +327,7 @@ struct momentary_breakpoint : public code_breakpoint
     thread = thread_;
   }
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   void check_status (struct bpstat *bs) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   void print_mention () const override;
@@ -334,7 +338,7 @@ struct dprintf_breakpoint : public ordinary_breakpoint
 {
   using ordinary_breakpoint::ordinary_breakpoint;
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   int breakpoint_hit (const struct bp_location *bl,
 		      const address_space *aspace,
 		      CORE_ADDR bp_addr,
@@ -1460,7 +1464,36 @@ breakpoint_set_thread (struct breakpoint *b, int thread)
 
   b->thread = thread;
   if (old_thread != thread)
-    gdb::observers::breakpoint_modified.notify (b);
+    {
+      /* If THREAD is in a different program_space than OLD_THREAD, or the
+	 breakpoint has switched to or from being thread-specific, then we
+	 need to re-set the locations of this breakpoint.  First, figure
+	 out the program_space for the old and new threads, use a value of
+	 nullptr to indicate the breakpoint is in all program spaces.  */
+      program_space *old_pspace = nullptr;
+      if (old_thread != -1)
+	{
+	  struct thread_info *thr = find_thread_global_id (old_thread);
+	  gdb_assert (thr != nullptr);
+	  old_pspace = thr->inf->pspace;
+	}
+
+      program_space *new_pspace = nullptr;
+      if (thread != -1)
+	{
+	  struct thread_info *thr = find_thread_global_id (thread);
+	  gdb_assert (thr != nullptr);
+	  new_pspace = thr->inf->pspace;
+	}
+
+      /* If the program space has changed for this breakpoint, then
+	 re-evaluate it's locations.  */
+      if (old_pspace != new_pspace)
+	breakpoint_re_set_one (b, new_pspace);
+
+      /* Let others know the breakpoint has changed.  */
+      gdb::observers::breakpoint_modified.notify (b);
+    }
 }
 
 /* See breakpoint.h.  */
@@ -8653,7 +8686,8 @@ create_breakpoints_sal (struct gdbarch *gdbarch,
 
 static void
 parse_breakpoint_sals (location_spec *locspec,
-		       struct linespec_result *canonical)
+		       struct linespec_result *canonical,
+		       struct program_space *search_pspace)
 {
   struct symtab_and_line cursal;
 
@@ -8717,7 +8751,7 @@ parse_breakpoint_sals (location_spec *locspec,
 	      && strchr ("+-", spec[0]) != NULL
 	      && spec[1] != '['))
 	{
-	  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, NULL,
+	  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, search_pspace,
 			    get_last_displayed_symtab (),
 			    get_last_displayed_line (),
 			    canonical, NULL, NULL);
@@ -8725,7 +8759,7 @@ parse_breakpoint_sals (location_spec *locspec,
 	}
     }
 
-  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, NULL,
+  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, search_pspace,
 		    cursal.symtab, cursal.line, canonical, NULL, NULL);
 }
 
@@ -8824,6 +8858,24 @@ breakpoint_ops_for_location_spec_type (enum location_spec_type locspec_type,
     }
 }
 
+/* Return the program space to use as a filter when searching for locations
+   of a breakpoint specific to THREAD.  If THREAD is -1, meaning all
+   threads, then this function returns nullptr, indicating no program space
+   filtering should be performed.  Otherwise, this function returns the
+   program space for the inferior that contains THREAD.  */
+
+static struct program_space *
+find_program_space_for_global_thread_id (int thread)
+{
+  if (thread == -1)
+    return nullptr;
+
+  struct thread_info *thr = find_thread_global_id (thread);
+  gdb_assert (thr != nullptr);
+  gdb_assert (thr->inf != nullptr);
+  return thr->inf->pspace;
+}
+
 /* See breakpoint.h.  */
 
 const struct breakpoint_ops *
@@ -8917,7 +8969,10 @@ create_breakpoint (struct gdbarch *gdbarch,
 
   try
     {
-      ops->create_sals_from_location_spec (locspec, &canonical);
+      struct program_space *search_pspace
+	= find_program_space_for_global_thread_id (thread);
+      ops->create_sals_from_location_spec (locspec, &canonical,
+					   search_pspace);
     }
   catch (const gdb_exception_error &e)
     {
@@ -9393,7 +9448,7 @@ break_range_command (const char *arg, int from_tty)
   arg_start = arg;
   location_spec_up start_locspec
     = string_to_location_spec (&arg, current_language);
-  parse_breakpoint_sals (start_locspec.get (), &canonical_start);
+  parse_breakpoint_sals (start_locspec.get (), &canonical_start, nullptr);
 
   if (arg[0] != ',')
     error (_("Too few arguments."));
@@ -9480,7 +9535,7 @@ watchpoint_exp_is_const (const struct expression *exp)
 /* Implement the "re_set" method for watchpoints.  */
 
 void
-watchpoint::re_set ()
+watchpoint::re_set (struct program_space *pspace)
 {
   /* Watchpoint can be either on expression using entirely global
      variables, or it can be on local variables.
@@ -11561,7 +11616,7 @@ breakpoint::print_recreate (struct ui_file *fp) const
 /* Default breakpoint_ops methods.  */
 
 void
-code_breakpoint::re_set ()
+code_breakpoint::re_set (struct program_space *pspace)
 {
   /* FIXME: is this still reachable?  */
   if (breakpoint_location_spec_empty_p (this))
@@ -11571,7 +11626,7 @@ code_breakpoint::re_set ()
       return;
     }
 
-  re_set_default ();
+  re_set_default (pspace);
 }
 
 int
@@ -11777,7 +11832,7 @@ code_breakpoint::decode_location_spec (location_spec *locspec,
 /* Virtual table for internal breakpoints.  */
 
 void
-internal_breakpoint::re_set ()
+internal_breakpoint::re_set (struct program_space *pspace)
 {
   switch (type)
     {
@@ -11870,7 +11925,7 @@ internal_breakpoint::print_mention () const
 /* Virtual table for momentary breakpoints  */
 
 void
-momentary_breakpoint::re_set ()
+momentary_breakpoint::re_set (struct program_space *pspace)
 {
   /* Keep temporary breakpoints, which can be encountered when we step
      over a dlopen call and solib_add is resetting the breakpoints.
@@ -11911,12 +11966,13 @@ longjmp_breakpoint::~longjmp_breakpoint ()
 
 static void
 bkpt_probe_create_sals_from_location_spec (location_spec *locspec,
-					   struct linespec_result *canonical)
+					   struct linespec_result *canonical,
+					   struct program_space *search_pspace)
 
 {
   struct linespec_sals lsal;
 
-  lsal.sals = parse_probes (locspec, NULL, canonical);
+  lsal.sals = parse_probes (locspec, search_pspace, canonical);
   lsal.canonical = xstrdup (canonical->locspec->to_string ());
   canonical->lsals.push_back (std::move (lsal));
 }
@@ -12006,9 +12062,9 @@ tracepoint::print_recreate (struct ui_file *fp) const
 }
 
 void
-dprintf_breakpoint::re_set ()
+dprintf_breakpoint::re_set (struct program_space *pspace)
 {
-  re_set_default ();
+  re_set_default (pspace);
 
   /* extra_string should never be non-NULL for dprintf.  */
   gdb_assert (extra_string != NULL);
@@ -12066,8 +12122,10 @@ dprintf_breakpoint::after_condition_true (struct bpstat *bs)
    markers (`-m').  */
 
 static void
-strace_marker_create_sals_from_location_spec (location_spec *locspec,
-					      struct linespec_result *canonical)
+strace_marker_create_sals_from_location_spec
+	(location_spec *locspec,
+	 struct linespec_result *canonical,
+	 struct program_space *search_pspace)
 {
   struct linespec_sals lsal;
   const char *arg_start, *arg;
@@ -12597,12 +12655,32 @@ update_breakpoint_locations (code_breakpoint *b,
      all locations are in the same shared library, that was unloaded.
      We'd like to retain the location, so that when the library is
      loaded again, we don't loose the enabled/disabled status of the
-     individual locations.  */
+     individual locations.
+
+     Thread specific breakpoints will also trigger this case if the thread
+     is changed to a different program space, and all of the old locations
+     go out of scope.  In this case we do (currently) discard the old
+     locations -- we assume the change in thread is permanent and the old
+     locations will never come back into scope.  */
   if (all_locations_are_pending (b, filter_pspace) && sals.empty ())
-    return;
+    {
+      if (b->thread != -1)
+	b->loc = nullptr;
+      return;
+    }
 
   existing_locations = hoist_existing_locations (b, filter_pspace);
 
+  /* If this is a thread-specific breakpoint then any locations left on the
+     breakpoint are for a program space in which the thread of interest
+     does not operate.  This can happen when the user changes the thread of
+     a thread-specific breakpoint.
+
+     We assume that the change in thread is permanent, and that the old
+     locations will never be used again, so discard them now.  */
+  if (b->thread != -1)
+    b->loc = nullptr;
+
   for (const auto &sal : sals)
     {
       struct bp_location *new_loc;
@@ -12765,40 +12843,45 @@ code_breakpoint::location_spec_to_sals (location_spec *locspec,
    locations.  */
 
 void
-code_breakpoint::re_set_default ()
+code_breakpoint::re_set_default (struct program_space *filter_pspace)
 {
-  struct program_space *filter_pspace = current_program_space;
   std::vector<symtab_and_line> expanded, expanded_end;
 
-  int found;
-  std::vector<symtab_and_line> sals = location_spec_to_sals (locspec.get (),
-							     filter_pspace,
-							     &found);
-  if (found)
-    expanded = std::move (sals);
-
-  if (locspec_range_end != nullptr)
-    {
-      std::vector<symtab_and_line> sals_end
-	= location_spec_to_sals (locspec_range_end.get (),
-				 filter_pspace, &found);
+  /* If this breakpoint is thread-specific then find the program space in
+     which the specific thread exists.  Otherwise, for breakpoints that are
+     not thread-specific THREAD_PSPACE will be nullptr.  */
+  program_space *thread_pspace
+    = find_program_space_for_global_thread_id (this->thread);
+
+  /* If this is not a thread-specific breakpoint, or it is a
+     thread-specific breakpoint but we are looking for new locations in the
+     program space that the specific thread is running, then look for new
+     locations for this breakpoint.  */
+  if (thread_pspace == nullptr || filter_pspace == thread_pspace)
+    {
+      int found;
+      std::vector<symtab_and_line> sals
+	= location_spec_to_sals (locspec.get (), filter_pspace, &found);
       if (found)
-	expanded_end = std::move (sals_end);
+	expanded = std::move (sals);
+
+      if (locspec_range_end != nullptr)
+	{
+	  std::vector<symtab_and_line> sals_end
+	    = location_spec_to_sals (locspec_range_end.get (),
+				     filter_pspace, &found);
+	  if (found)
+	    expanded_end = std::move (sals_end);
+	}
     }
 
+  /* Update the locations for this breakpoint.  For thread-specific
+     breakpoints this will remove any old locations that are for the wrong
+     program space -- this can happen if the user changes the thread of a
+     thread-specific breakpoint.  */
   update_breakpoint_locations (this, filter_pspace, expanded, expanded_end);
 }
 
-/* Default method for creating SALs from an address string.  It basically
-   calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
-
-static void
-create_sals_from_location_spec_default (location_spec *locspec,
-					struct linespec_result *canonical)
-{
-  parse_breakpoint_sals (locspec, canonical);
-}
-
 /* Re-set breakpoint locations for the current program space.
    Locations bound to other program spaces are left untouched.  */
 
@@ -12833,7 +12916,7 @@ breakpoint_re_set (void)
 	  {
 	    input_radix = b->input_radix;
 	    set_language (b->language);
-	    b->re_set ();
+	    b->re_set (current_program_space);
 	  }
 	catch (const gdb_exception &ex)
 	  {
@@ -12854,6 +12937,53 @@ breakpoint_re_set (void)
   /* Now we can insert.  */
   update_global_location_list (UGLL_MAY_INSERT);
 }
+
+/* Re-set locations for breakpoint B in FILTER_PSPACE.  If FILTER_PSPACE is
+   nullptr then re-set locations for B in all program spaces.  Locations
+   bound to program spaces other than FILTER_PSPACE are left untouched.  */
+
+static void
+breakpoint_re_set_one (breakpoint *b, program_space *filter_pspace)
+{
+  {
+    scoped_restore_current_language save_language;
+    scoped_restore save_input_radix = make_scoped_restore (&input_radix);
+    scoped_restore_current_pspace_and_thread restore_pspace_thread;
+
+    /* To ::re_set each breakpoint we set the current_language to the
+       language of the breakpoint before re-evaluating the breakpoint's
+       location.  This change can unfortunately get undone by accident if
+       the language_mode is set to auto, and we either switch frames, or
+       more likely in this context, we select the current frame.
+
+       We prevent this by temporarily turning the language_mode to
+       language_mode_manual.  We restore it once all breakpoints
+       have been reset.  */
+    scoped_restore save_language_mode = make_scoped_restore (&language_mode);
+    language_mode = language_mode_manual;
+
+    /* Note: we must not try to insert locations until after all
+       breakpoints have been re-set.  Otherwise, e.g., when re-setting
+       breakpoint 1, we'd insert the locations of breakpoint 2, which
+       hadn't been re-set yet, and thus may have stale locations.  */
+
+    try
+      {
+	input_radix = b->input_radix;
+	set_language (b->language);
+	b->re_set (filter_pspace);
+      }
+    catch (const gdb_exception &ex)
+      {
+	exception_fprintf (gdb_stderr, ex,
+			   "Error in re-setting breakpoint %d: ",
+			   b->number);
+      }
+  }
+
+  /* Now we can insert.  */
+  update_global_location_list (UGLL_MAY_INSERT);
+}
 \f
 /* Reset the thread number of this breakpoint:
 
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index 2adcc9fa338..8a643301264 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -564,15 +564,15 @@ enum print_stop_action
 
 struct breakpoint_ops
 {
-  /* Create SALs from location spec, storing the result in
-     linespec_result.
-
-     For an explanation about the arguments, see the function
-     `create_sals_from_location_spec_default'.
+  /* Create SALs from LOCSPEC, storing the result in linespec_result
+     CANONICAL.  If SEARCH_PSPACE is not nullptr then only results in the
+     corresponding program space are returned.  If SEARCH_PSPACE is nullptr
+     then results for all program spaces are returned.
 
      This function is called inside `create_breakpoint'.  */
   void (*create_sals_from_location_spec) (location_spec *locspec,
-					  struct linespec_result *canonical);
+					  linespec_result *canonical,
+					  program_space *search_pspace);
 
   /* This method will be responsible for creating a breakpoint given its SALs.
      Usually, it just calls `create_breakpoints_sal' (for ordinary
@@ -635,8 +635,12 @@ struct breakpoint
 
   /* Reevaluate a breakpoint.  This is necessary after symbols change
      (e.g., an executable or DSO was loaded, or the inferior just
-     started).  */
-  virtual void re_set ()
+     started).
+
+     FILTER_PSPACE is the program space in which symbols may have changed,
+     or can be nullptr to indicate that all program spaces may have
+     changed.  */
+  virtual void re_set (program_space *filter_pspace)
   {
     /* Nothing to re-set.  */
   }
@@ -868,7 +872,7 @@ struct code_breakpoint : public breakpoint
   /* Add a location for SAL to this breakpoint.  */
   bp_location *add_location (const symtab_and_line &sal);
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   int insert_location (struct bp_location *) override;
   int remove_location (struct bp_location *,
 		       enum remove_bp_reason reason) override;
@@ -890,7 +894,7 @@ struct code_breakpoint : public breakpoint
      struct program_space *search_pspace);
 
   /* Helper method that does the basic work of re_set.  */
-  void re_set_default ();
+  void re_set_default (program_space *pspace);
 
   /* Find the SaL locations corresponding to the given LOCATION.
      On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
@@ -912,7 +916,7 @@ struct watchpoint : public breakpoint
 {
   using breakpoint::breakpoint;
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   int insert_location (struct bp_location *) override;
   int remove_location (struct bp_location *,
 		       enum remove_bp_reason reason) override;
diff --git a/gdb/testsuite/gdb.mi/user-selected-context-sync.exp b/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
index 4889c31aff3..8cc47537e68 100644
--- a/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
+++ b/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
@@ -370,7 +370,7 @@ proc test_continue_to_start { mode inf } {
 			    "thread $inf.2 stops MI"
 		    } else {
 			mi_expect_stop "breakpoint-hit" "child_sub_function" \
-			    "" "$srcfile" "$decimal" {"" "disp=\"del\"" "locno=\"[0-9]+\""} \
+			    "" "$srcfile" "$decimal" {"" "disp=\"del\""} \
 			    "thread $inf.2 stops MI"
 		    }
 		}
diff --git a/gdb/testsuite/gdb.multi/bp-thread-specific.exp b/gdb/testsuite/gdb.multi/bp-thread-specific.exp
index 85c08f44a2c..68001e92044 100644
--- a/gdb/testsuite/gdb.multi/bp-thread-specific.exp
+++ b/gdb/testsuite/gdb.multi/bp-thread-specific.exp
@@ -50,7 +50,7 @@ gdb_test "info threads" \
 # locations ('foo' in both inferiors) even though only one of those
 # locations will ever trigger ('foo' in inferior 2).
 gdb_test "break foo thread 2.1" \
-    "Breakpoint $decimal at $hex: foo\\. \\(2 locations\\)"
+    "Breakpoint $decimal at $hex: file \[^\r\n\]+$srcfile, line $decimal\\."
 
 set bpnum [get_integer_valueof "\$bpnum" "INVALID"]
 
@@ -58,10 +58,7 @@ set bpnum [get_integer_valueof "\$bpnum" "INVALID"]
 # earlier breakpoint.  Check that the thread-id used when describing
 # the earlier breakpoints is correct.
 gdb_test "break foo thread 1.1" \
-    [multi_line \
-	 "Note: breakpoint $bpnum \\(thread 2.1\\) also set at pc $hex\\." \
-	 "Note: breakpoint $bpnum \\(thread 2.1\\) also set at pc $hex\\." \
-	 "Breakpoint $decimal at $hex: foo\\. \\(2 locations\\)"]
+    "Breakpoint $decimal at $hex: file \[^\r\n\]+$srcfile, line $decimal\\."
 
 # Save the breakpoints into a file.
 if {[is_remote host]} {
diff --git a/gdb/testsuite/gdb.multi/multi-target-continue.exp b/gdb/testsuite/gdb.multi/multi-target-continue.exp
index bf19cc00968..a1bffb7b613 100644
--- a/gdb/testsuite/gdb.multi/multi-target-continue.exp
+++ b/gdb/testsuite/gdb.multi/multi-target-continue.exp
@@ -30,7 +30,7 @@ proc test_continue {non-stop} {
 
     proc set_break {inf} {
 	gdb_test "break function${inf} thread ${inf}.1" \
-	"Breakpoint .* function${inf}\\..*"
+	    "Breakpoint ${::decimal} at ${::hex}: file .*, line ${::decimal}\\."
     }
 
     # Select inferior INF, and then run to a breakpoint on inferior
diff --git a/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp b/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp
index 64645b8ec8a..51fd70b018a 100644
--- a/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp
+++ b/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp
@@ -52,12 +52,12 @@ proc test_ping_pong_next {} {
     gdb_test "thread 1.1" "Switching to thread 1.1 .*"
 
     gdb_test "break $srcfile:$line1 thread 1.1" \
-	"Breakpoint .*$srcfile:$line1\\..*"
+	"Breakpoint .*$srcfile, line $line1\\."
 
     gdb_test "continue" "hit Breakpoint .*"
 
     gdb_test "break $srcfile:$line2 thread 2.1" \
-	"Breakpoint .*$srcfile:$line2\\..*"
+	"Breakpoint .*$srcfile, line $line2\\."
 
     # Now block inferior 1 and issue "next".  We should stop at the
     # breakpoint for inferior 2, given schedlock off.
diff --git a/gdb/testsuite/gdb.multi/pending-bp.exp b/gdb/testsuite/gdb.multi/pending-bp.exp
index 4a65f79cfc4..8e1d1234948 100644
--- a/gdb/testsuite/gdb.multi/pending-bp.exp
+++ b/gdb/testsuite/gdb.multi/pending-bp.exp
@@ -78,6 +78,48 @@ proc do_test_setup { inf_1_stop inf_2_stop } {
     return true
 }
 
+# Create a breakpoint on the function 'foo' in THREAD.  It is expected
+# that the breakpoint created will be pending, this is checked by
+# running the 'info breakpoints' command.
+#
+# Returns the number for the newly created breakpoint.
+proc do_create_pending_foo_breakpoint { {thread "1.1"} } {
+    gdb_test "break foo thread $thread" \
+	[multi_line \
+	     "Function \"foo\" not defined\\." \
+	     "Breakpoint $::decimal \\(foo\\) pending\."] \
+	"set pending thread-specific breakpoint"
+    set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+		   "get number for thread-specific breakpoint on foo"]
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	     "\\s+stop only in thread [string_to_regexp $thread]"] \
+	"check thread-specific breakpoint is initially pending"
+
+    return $bpnum
+}
+
+# Create a breakpoint on the function 'foo' in THREAD.  It is expected
+# that the breakpoint created will not be pending, this is checked by
+# running the 'info breakpoints' command.
+#
+# Returns the number for the newly created breakpoint.
+proc do_create_foo_breakpoint { {thread "1.1"} } {
+    gdb_test "break foo thread $thread" \
+	"Breakpoint $::decimal at $::hex" \
+	"set thread-specific breakpoint"
+    set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+		   "get number for thread-specific breakpoint on foo"]
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex\\s+<foo\[^>\]*> inf $::decimal" \
+	     "\\s+stop only in thread [string_to_regexp $thread]"] \
+	"check thread-specific breakpoint is initially pending"
+
+    return $bpnum
+}
+
 # Check that when a breakpoint is in the pending state, but that breakpoint
 # does have some locations (those locations themselves are pending), GDB
 # doesn't display the inferior list in the 'info breakpoints' output.
@@ -111,5 +153,169 @@ proc_with_prefix test_no_inf_display {} {
 	"check info breakpoints while breakpoint is pending"
 }
 
+# Setup two inferiors.  In #1 the symbol 'foo' has not yet been
+# loaded, while in #2 the symbol 'foo' has been loaded.
+#
+# Create a thread-specific breakpoint on 'foo' tied to a thread in
+# inferior #1, the breakpoint should be pending -- 'foo' is not yet
+# loaded in #1.
+#
+# Now move inferior #1 forward until 'foo' is loaded, check the
+# breakpoint is no longer pending.
+#
+# Move inferior #1 forward more until 'foo' is unloaded, check that
+# the breakpoint returns to the pending state.
+proc_with_prefix test_pending_toggle { } {
+
+    do_test_setup "Break before open" "Break before close"
+
+    set bpnum [do_create_pending_foo_breakpoint]
+
+    # Now return to inferior 1 and continue until the shared library is
+    # loaded, the breakpoint should become non-pending.
+    gdb_test "inferior 1" "Switching to inferior 1 .*" \
+	"switch back to inferior 1"
+    gdb_continue_to_breakpoint "stop in foo in inferior 1" "foo \\(\\) .*"
+
+    gdb_test "info breakpoint $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex <foo\[^>\]*> inf 1" \
+	     "\\s+stop only in thread 1\\.1" \
+	     "\\s+breakpoint already hit 1 time"] \
+	"check thread-specific breakpoint is no longer pending"
+
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "close library"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	     "\\s+stop only in thread 1\\.1" \
+	     "\\s+breakpoint already hit 1 time"] \
+	"check thread-specific breakpoint is pending again"
+}
+
+# Create a Python variable VAR and set it to the gdb.Breakpoint object
+# corresponding to the breakpoint numbered BPNUM.  If THREAD is not
+# the empty string then THREAD should be an integer, check that
+# gdb.Breakpoint.thread is set to the value of THREAD.  Otherwise, if
+# THREAD is the empty string, check that gdb.Breakpoint.thread is set
+# to None.
+proc py_find_breakpoint { var bpnum {thread ""} } {
+    gdb_test_no_output \
+	"python ${var}=\[b for b in gdb.breakpoints() if b.number == $bpnum\]\[0\]" \
+	"find Python gdb.Breakpoint object"
+    if { $thread ne "" } {
+	gdb_test_no_output "python assert(${var}.thread == ${thread})" \
+	    "check thread attribute is currently correct"
+    } else {
+	gdb_test_no_output "python assert(${var}.thread is None)" \
+	    "check thread attribute is currently correct"
+    }
+}
+
+# Setup two inferiors.  In #1 the symbol 'foo' has not yet been
+# loaded, while in #2 the symbol 'foo' has been loaded.
+#
+# Create a thread-specific breakpoint on 'foo' tied to a thread in
+# inferior #1, the breakpoint should be pending -- 'foo' is not yet
+# loaded in #1.
+#
+# Use Python to change the thread of the thread-specific breakpoint to
+# a thread in inferior #2, at this point the thread should gain a
+# location and become non-pending.
+#
+# Set the thread back to a thread in inferior #1, the breakpoint
+# should return to the pending state.
+proc_with_prefix py_test_toggle_thread {} {
+    do_test_setup "Break before open" "Break after open"
+
+    set bpnum [do_create_pending_foo_breakpoint]
+
+    py_find_breakpoint "bp" $bpnum 1
+
+    gdb_test_no_output "python bp.thread = 2" \
+	"change thread on thread-specific breakpoint"
+    gdb_test "info breakpoint $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex <foo\[^>\]*> inf 2" \
+	     "\\s+stop only in thread 2\\.1"] \
+	"check thread-specific breakpoint now has a location"
+
+    gdb_test_no_output "set call_count = 2" "set call_count in inferior 2"
+    gdb_continue_to_breakpoint "stop at foo in inferior 2" "foo \\(\\) .*"
+
+    gdb_test_no_output "python bp.thread = 1" \
+	"restore thread on thread-specific breakpoint"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	     "\\s+stop only in thread 1\\.1" \
+	     "\\s+breakpoint already hit 1 time"] \
+	"check thread-specific breakpoint has returned to pending"
+
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "stop after close in inferior 2" \
+	".* Break after close\\. .*"
+
+    gdb_test "inferior 1" "Switching to inferior 1 .*" \
+	"switch to inferior 1"
+    gdb_continue_to_breakpoint "stop at foo in inferior 1" "foo \\(\\) .*"
+}
+
+# Setup two inferiors.  Both inferiors have the symbol 'foo'
+# available.
+#
+# Create a thread-specific breakpoint on 'foo' tied to a thread in
+# inferior #1, the breakpoint should not be pending, but will only
+# have a single location, the location in inferior #1.
+#
+# Use Python to change the thread of the thread-specific breakpoint to
+# None.  At this point the breakpoint should gain a second location, a
+# location in inferior #2.
+proc_with_prefix py_test_clear_thread {} {
+    do_test_setup "Break after open" "Break after open"
+
+    set bpnum [do_create_foo_breakpoint]
+
+    py_find_breakpoint "bp" $bpnum 1
+
+    gdb_test_no_output "python bp.thread = None" \
+	"clear thread on thread-specific breakpoint"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "${bpnum}\\s+breakpoint\\s+keep y\\s+<MULTIPLE>\\s*" \
+	     "${bpnum}\\.1\\s+y\\s+${::hex}\\s+<foo\[^>\]*> inf $::decimal" \
+	     "${bpnum}\\.2\\s+y\\s+${::hex}\\s+<foo\[^>\]*> inf $::decimal"] \
+	"check for a location in both inferiors"
+
+    gdb_continue_to_breakpoint "stop at foo in inferior 2" "foo \\(\\) .*"
+    gdb_test_no_output "set call_count = 2" "set call_count in inferior 2"
+
+    gdb_test "inferior 1" "Switching to inferior 1 .*" \
+	"switch to inferior 1"
+    gdb_continue_to_breakpoint "stop at foo in inferior 1" "foo \\(\\) .*"
+    gdb_test_no_output "set call_count = 2" "set call_count in inferior 1"
+
+    gdb_test_no_output "python bp.thread = 2"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "${bpnum}\\s+breakpoint\\s+keep y\\s+${::hex}\\s+<foo\[^>\]*> inf 2" \
+	     "\\s+stop only in thread 2\\.1" \
+	     "\\s+breakpoint already hit 2 times"] \
+	"check for a location only in inferior 2"
+
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "stop after close in inferior 1" \
+	".* Break after close\\. .*"
+
+    gdb_test "inferior 2" "Switching to inferior 2 .*" \
+	"switch back to inferior 2"
+    gdb_continue_to_breakpoint "stop at foo again in inferior 2" \
+	"foo \\(\\) .*"
+}
+
 # Run all the tests.
 test_no_inf_display
+test_pending_toggle
+py_test_toggle_thread
+py_test_clear_thread
diff --git a/gdb/testsuite/gdb.multi/tids.exp b/gdb/testsuite/gdb.multi/tids.exp
index 18fc4970fe7..34c270309de 100644
--- a/gdb/testsuite/gdb.multi/tids.exp
+++ b/gdb/testsuite/gdb.multi/tids.exp
@@ -433,11 +433,13 @@ if { [allow_python_tests] } {
 
 	gdb_py_test_silent_cmd "python bp = gdb.breakpoints()\[0\]" \
 	    "get python breakpoint" 0
-	gdb_test "python bp.thread = 6" "thread = 6" \
+	gdb_test_no_output "python bp.thread = 6" \
 	    "make breakpoint thread-specific with python"
 	# Check that the inferior-qualified ID is correct.
 	gdb_test "info breakpoint" \
-	    "stop only in thread 1.3\r\n.*" \
+	    [multi_line \
+		 "$decimal\\s+\[^\r\n\]+ in thread_function1 at \[^\r\n\]+" \
+		 "\\s+stop only in thread 1\\.3"] \
 	    "thread specific breakpoint right thread"
     }
 }
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv3 0/9] thread-specific breakpoints in just some inferiors
  2023-05-15 19:27 ` [PATCHv2 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
                     ` (8 preceding siblings ...)
  2023-05-15 19:27   ` [PATCHv2 9/9] gdb: only insert thread-specific breakpoints in the relevant inferior Andrew Burgess
@ 2023-05-30 20:46   ` Andrew Burgess
  2023-05-30 20:46     ` [PATCHv3 1/9] gdb: create_breakpoint: assert for a valid thread-id Andrew Burgess
                       ` (9 more replies)
  9 siblings, 10 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-05-30 20:46 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

When I proposed my inferior-specific breakpoints patch, two people
independently asked: will these breakpoints only be inserted into the
relevant inferiors?

My answer at that point was, no, that's just not possible given how we
manage the breakpoint locations, but this series changes that.

But as the inferior specific breakpoints patch hasn't landed yet, this
series looks at thread-specific breakpoints.

A thread-specific breakpoint only applies to a single global
thread-id, and so will only apply for to a single thread in a single
inferior.  As such, we can limit the locations for a thread-specific
breakpoint to just those locations in the inferior containing the
thread we are interested in.

In the following series patch #6 and #9 are the really interesting
ones.  Patch #6 makes some pretty significant changes to how we setup
breakpoints, which opens the way for #9, which performs the location
limiting.

Patches #1 to #5 are me just trying to understand the breakpoint
creation code more -- adding asserts and making a couple of minor
cleanups.

Patches #7 and #8 are more cleanups, but now looking at the location
creation/re-setting code.

---

In v3:

  - Rebased on to current upstream/master, this includes all Simon's
    recent breakpoint changes.  Retested with no regressions seen.

In v2:

  - Rebased on current upstream/master and retested,

  - No changes to code or docs.

---

Andrew Burgess (9):
  gdb: create_breakpoint: assert for a valid thread-id
  gdb: create_breakpoint: asserts relating to extra_string/parse_extra
  gdb: change 'if' to gdb_assert in update_dprintf_command_list
  gdb: build dprintf commands just once in code_breakpoint constructor
  gdb: don't display inferior list for pending breakpoints
  gdb: parse pending breakpoint thread/task immediately
  gdb: remove breakpoint_re_set_one
  gdb: remove tracepoint_probe_create_sals_from_location_spec
  gdb: only insert thread-specific breakpoints in the relevant inferior

 gdb/Makefile.in                               |   2 +
 gdb/NEWS                                      |  11 +
 gdb/ada-lang.c                                |   6 +-
 gdb/break-catch-throw.c                       |   6 +-
 gdb/break-cond-parse.c                        | 403 +++++++++++
 gdb/break-cond-parse.h                        |  47 ++
 gdb/breakpoint.c                              | 666 ++++++++----------
 gdb/breakpoint.h                              |  64 +-
 gdb/testsuite/gdb.base/condbreak.exp          |  20 +-
 gdb/testsuite/gdb.base/pending.exp            |  23 +-
 gdb/testsuite/gdb.linespec/explicit.exp       |   4 +-
 gdb/testsuite/gdb.mi/mi-dprintf-pending.exp   |   3 +-
 .../gdb.mi/user-selected-context-sync.exp     |   2 +-
 .../gdb.multi/bp-thread-specific.exp          |   7 +-
 .../gdb.multi/multi-target-continue.exp       |   2 +-
 .../gdb.multi/multi-target-ping-pong-next.exp |   4 +-
 gdb/testsuite/gdb.multi/pending-bp-lib.c      |  22 +
 gdb/testsuite/gdb.multi/pending-bp.c          |  66 ++
 gdb/testsuite/gdb.multi/pending-bp.exp        | 321 +++++++++
 gdb/testsuite/gdb.multi/tids.exp              |   6 +-
 .../gdb.threads/del-pending-thread-bp-lib.c   |  22 +
 .../gdb.threads/del-pending-thread-bp.c       |  85 +++
 .../gdb.threads/del-pending-thread-bp.exp     | 108 +++
 23 files changed, 1498 insertions(+), 402 deletions(-)
 create mode 100644 gdb/break-cond-parse.c
 create mode 100644 gdb/break-cond-parse.h
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.exp
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.exp


base-commit: 2bd766d6245bf9db77c42da3537c949ffb814bfc
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv3 1/9] gdb: create_breakpoint: assert for a valid thread-id
  2023-05-30 20:46   ` [PATCHv3 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
@ 2023-05-30 20:46     ` Andrew Burgess
  2023-05-30 20:46     ` [PATCHv3 2/9] gdb: create_breakpoint: asserts relating to extra_string/parse_extra Andrew Burgess
                       ` (8 subsequent siblings)
  9 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-05-30 20:46 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Add an assert into create_breakpoint (breakpoint.c) that the thread
argument is a valid thread-id; either a value greater than zero, or -1
to indicate any thread.

The thread is ignored if parse_extra is true though, so take that into
account too.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c | 4 ++++
 gdb/breakpoint.h | 6 ++++++
 2 files changed, 10 insertions(+)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index a94277f0c6c..fe92893863d 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -9000,6 +9000,10 @@ create_breakpoint (struct gdbarch *gdbarch,
 
   gdb_assert (ops != NULL);
 
+  /* If PARSE_EXTRA is true then the thread-id will be parsed from
+     EXTRA_STRING, otherwise, ensure THREAD is valid.  */
+  gdb_assert (parse_extra || thread == -1 || thread > 0);
+
   /* If extra_string isn't useful, set it to NULL.  */
   if (extra_string != NULL && *extra_string == '\0')
     extra_string = NULL;
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index 709d27fa4db..331c908ecbc 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -1589,6 +1589,12 @@ enum breakpoint_create_flags
    the FORCE_CONDITION parameter is ignored and the corresponding argument
    is parsed from EXTRA_STRING.
 
+   The THREAD should be a global thread number, the created breakpoint will
+   only apply for that thread.  If the breakpoint should apply for all
+   threads then pass -1.  However, if PARSE_EXTRA is non-zero then the
+   THREAD parameter is ignored and an optional thread number will be parsed
+   from EXTRA_STRING.
+
    If INTERNAL is non-zero, the breakpoint number will be allocated
    from the internal breakpoint count.
 
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv3 2/9] gdb: create_breakpoint: asserts relating to extra_string/parse_extra
  2023-05-30 20:46   ` [PATCHv3 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
  2023-05-30 20:46     ` [PATCHv3 1/9] gdb: create_breakpoint: assert for a valid thread-id Andrew Burgess
@ 2023-05-30 20:46     ` Andrew Burgess
  2023-05-30 20:46     ` [PATCHv3 3/9] gdb: change 'if' to gdb_assert in update_dprintf_command_list Andrew Burgess
                       ` (7 subsequent siblings)
  9 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-05-30 20:46 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

The goal of this commit is to better define the API for
create_breakpoint especially around the use of extra_string and
parse_extra.  This will be useful in the next commit when I plan to
make some changes to create_breakpoint.

This commit makes one possibly breaking change: until this commit it
was possible to create thread-specific dprintf breakpoint like this:

  (gdb) dprintf call_me, thread 1 "%s", "hello"
  Dprintf 2 at 0x401152: file /tmp/hello.c, line 8.
  (gdb) info breakpoints
  Num     Type           Disp Enb Address            What
  2       dprintf        keep y   0x0000000000401152 in call_me at /tmp/hello.c:8 thread 1
          stop only in thread 1
          printf "%s", "hello"
  (gdb)

this feature of dprintf was not documented, was not tested, and is
slightly different in syntax to how we create thread specific
breakpoints and/or watchpoints -- the thread condition appears after
the first ','.

I believe that this worked at all was simply by luck.  We happen to
pass the parse_extra flag as true from dprintf_command to
create_breakpoint.

So in this commit I made the choice change this.  We now pass
parse_extra as false from dprintf_command to create_breakpoint.  With
this done it is assumed that the only thing in the extra_string is the
dprintf format and arguments.

Beyond this change I've updated the comment on create_breakpoint in
breakpoint.h, and I've then added some asserts into
create_breakpoint as well as moving around some of the error
handling.

 - We now assert on the incoming argument values,

 - I've moved an error check to sit after the call to
   find_condition_and_thread_for_sals, this ensures the extra_string
   was parsed correctly,

In dprintf_command:

 - We now throw an error if there is no format string after the
   dprintf location.  This error was already being thrown, but was
   being caught later in the process.  With this change we catch the
   missing string earlier,

 - And, as mentioned earlier, we pass parse_extra as false when
   calling create_breakpoint,

In create_tracepoint_from_upload:

 - We now throw an error if the parsed location doesn't completely
   consume the addr_str variable.  This error has now effectively
   moved out of create_breakpoint.
---
 gdb/breakpoint.c | 42 +++++++++++++++++++++++++++++-------------
 gdb/breakpoint.h | 38 ++++++++++++++++++++++++--------------
 2 files changed, 53 insertions(+), 27 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index fe92893863d..fcd2f472bf7 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -9008,6 +9008,17 @@ create_breakpoint (struct gdbarch *gdbarch,
   if (extra_string != NULL && *extra_string == '\0')
     extra_string = NULL;
 
+  /* A bp_dprintf must always have an accompanying EXTRA_STRING containing
+     the dprintf format and arguments -- PARSE_EXTRA should always be false
+     in this case.
+
+     For all other breakpoint types, EXTRA_STRING should be nullptr unless
+     PARSE_EXTRA is true.  */
+  gdb_assert ((type_wanted == bp_dprintf
+	       && extra_string != nullptr && !parse_extra)
+	      || (type_wanted != bp_dprintf
+		  && (extra_string == nullptr || parse_extra)));
+
   try
     {
       ops->create_sals_from_location_spec (locspec, &canonical);
@@ -9071,6 +9082,8 @@ create_breakpoint (struct gdbarch *gdbarch,
 
       if (parse_extra)
 	{
+	  gdb_assert (type_wanted != bp_dprintf);
+
 	  gdb::unique_xmalloc_ptr<char> rest;
 	  gdb::unique_xmalloc_ptr<char> cond;
 
@@ -9078,15 +9091,15 @@ create_breakpoint (struct gdbarch *gdbarch,
 
 	  find_condition_and_thread_for_sals (lsal.sals, extra_string,
 					      &cond, &thread, &task, &rest);
+
+	  if (rest.get () != nullptr && *(rest.get ()) != '\0')
+	    error (_("Garbage '%s' at end of command"), rest.get ());
+
 	  cond_string_copy = std::move (cond);
 	  extra_string_copy = std::move (rest);
 	}
       else
 	{
-	  if (type_wanted != bp_dprintf
-	      && extra_string != NULL && *extra_string != '\0')
-		error (_("Garbage '%s' at end of location"), extra_string);
-
 	  /* Check the validity of the condition.  We should error out
 	     if the condition is invalid at all of the locations and
 	     if it is not forced.  In the PARSE_EXTRA case above, this
@@ -9295,20 +9308,17 @@ dprintf_command (const char *arg, int from_tty)
 
   /* If non-NULL, ARG should have been advanced past the location;
      the next character must be ','.  */
-  if (arg != NULL)
+  if (arg == nullptr || arg[0] != ',' || arg[1] == '\0')
+    error (_("Format string required"));
+  else
     {
-      if (arg[0] != ',' || arg[1] == '\0')
-	error (_("Format string required"));
-      else
-	{
-	  /* Skip the comma.  */
-	  ++arg;
-	}
+      /* Skip the comma.  */
+      ++arg;
     }
 
   create_breakpoint (get_current_arch (),
 		     locspec.get (),
-		     NULL, 0, arg, false, 1 /* parse arg */,
+		     NULL, -1, arg, false, 0 /* parse arg */,
 		     0, bp_dprintf,
 		     0 /* Ignore count */,
 		     pending_break_support,
@@ -13874,6 +13884,12 @@ create_tracepoint_from_upload (struct uploaded_tp *utp)
 
   location_spec_up locspec = string_to_location_spec (&addr_str,
 						      current_language);
+
+
+  gdb_assert (addr_str != nullptr);
+  if (*addr_str != '\0')
+    error (_("Garbage '%s' at end of location"), addr_str);
+
   if (!create_breakpoint (get_current_arch (),
 			  locspec.get (),
 			  utp->cond_string.get (), -1, addr_str,
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index 331c908ecbc..8abb46b54ad 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -1574,26 +1574,36 @@ enum breakpoint_create_flags
    functions for setting a breakpoint at LOCSPEC.
 
    This function has two major modes of operations, selected by the
-   PARSE_EXTRA parameter.
+   PARSE_EXTRA and WANTED_TYPE parameters.
 
-   If PARSE_EXTRA is zero, LOCSPEC is just the breakpoint's location
-   spec, with condition, thread, and extra string specified by the
-   COND_STRING, THREAD, and EXTRA_STRING parameters.
+   When WANTED_TYPE is not bp_dprintf the following rules apply:
 
-   If PARSE_EXTRA is non-zero, this function will attempt to extract
-   the condition, thread, and extra string from EXTRA_STRING, ignoring
-   the similarly named parameters.
+     If PARSE_EXTRA is zero, LOCSPEC is just the breakpoint's location
+     spec, with condition, thread, and extra string specified by the
+     COND_STRING, THREAD, and EXTRA_STRING parameters.
 
-   If FORCE_CONDITION is true, the condition is accepted even when it is
-   invalid at all of the locations.  However, if PARSE_EXTRA is non-zero,
-   the FORCE_CONDITION parameter is ignored and the corresponding argument
-   is parsed from EXTRA_STRING.
+     If PARSE_EXTRA is non-zero, this function will attempt to extract the
+     condition, thread, and extra string from EXTRA_STRING, ignoring the
+     similarly named parameters.
+
+   When WANTED_TYPE is bp_dprintf the following rules apply:
+
+     PARSE_EXTRA must always be zero, LOCSPEC is just the breakpoint's
+     location spec, with condition, thread, and extra string (which
+     contains the dprintf format and arguments) specified by the
+     COND_STRING, THREAD, and EXTRA_STRING parameters.
+
+   If FORCE_CONDITION is true, the condition (in COND_STRING) is accepted
+   even when it is invalid at all of the locations.  However, if
+   PARSE_EXTRA is non-zero and WANTED_TYPE is not bp_dprintf, the
+   FORCE_CONDITION parameter is ignored and the corresponding argument is
+   parsed from EXTRA_STRING.
 
    The THREAD should be a global thread number, the created breakpoint will
    only apply for that thread.  If the breakpoint should apply for all
-   threads then pass -1.  However, if PARSE_EXTRA is non-zero then the
-   THREAD parameter is ignored and an optional thread number will be parsed
-   from EXTRA_STRING.
+   threads then pass -1.  However, if PARSE_EXTRA is non-zero and
+   WANTED_TYPE is not bp_dprintf, then the THREAD parameter is ignored and
+   an optional thread number will be parsed from EXTRA_STRING.
 
    If INTERNAL is non-zero, the breakpoint number will be allocated
    from the internal breakpoint count.
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv3 3/9] gdb: change 'if' to gdb_assert in update_dprintf_command_list
  2023-05-30 20:46   ` [PATCHv3 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
  2023-05-30 20:46     ` [PATCHv3 1/9] gdb: create_breakpoint: assert for a valid thread-id Andrew Burgess
  2023-05-30 20:46     ` [PATCHv3 2/9] gdb: create_breakpoint: asserts relating to extra_string/parse_extra Andrew Burgess
@ 2023-05-30 20:46     ` Andrew Burgess
  2023-05-30 20:46     ` [PATCHv3 4/9] gdb: build dprintf commands just once in code_breakpoint constructor Andrew Burgess
                       ` (6 subsequent siblings)
  9 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-05-30 20:46 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

I noticed in update_dprintf_command_list that we handle the case where
the bp_dprintf style breakpoint doesn't have a format and args string.

However, I don't believe such a situation is possible.  The obvious
approach certainly already catches this case:

  (gdb) dprintf main
  Format string required

If it is possible to create a dprintf breakpoint without a format and
args string then I think we should be catching this case and handling
it at creation time, rather than having GDB just ignore the situation
later on.

And so, I propose that we change the 'if' that ignores the case where
the format/args string is empty, and instead assert that we do always
have a format/args string.  The original code, that handled an empty
format/args string has existed since commit e7e0cddfb0d4, which is
when dprintf support was added to GDB.

If I'm correct and this situation can't ever happen then there should
be no user visible changes after this commit.
---
 gdb/breakpoint.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index fcd2f472bf7..2cadc8c0295 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -8356,8 +8356,9 @@ update_dprintf_command_list (struct breakpoint *b)
   const char *dprintf_args = b->extra_string.get ();
   gdb::unique_xmalloc_ptr<char> printf_line = nullptr;
 
-  if (!dprintf_args)
-    return;
+  /* Trying to create a dprintf breakpoint without a format and args
+     string should be detected at creation time.  */
+  gdb_assert (dprintf_args != nullptr);
 
   dprintf_args = skip_spaces (dprintf_args);
 
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv3 4/9] gdb: build dprintf commands just once in code_breakpoint constructor
  2023-05-30 20:46   ` [PATCHv3 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
                       ` (2 preceding siblings ...)
  2023-05-30 20:46     ` [PATCHv3 3/9] gdb: change 'if' to gdb_assert in update_dprintf_command_list Andrew Burgess
@ 2023-05-30 20:46     ` Andrew Burgess
  2023-05-30 20:46     ` [PATCHv3 5/9] gdb: don't display inferior list for pending breakpoints Andrew Burgess
                       ` (5 subsequent siblings)
  9 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-05-30 20:46 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

I noticed in code_breakpoint::code_breakpoint that we are calling
update_dprintf_command_list once for each breakpoint location, when we
really only need to call this once per breakpoint -- the data updated
by this function, the breakpoint command list -- is per breakpoint,
not per breakpoint location.  Calling update_dprintf_command_list
multiple times is just wasted effort, there's no per location error
checking, we don't even pass the current location to the function.

This commit moves the update_dprintf_command_list call outside of the
per-location loop. I have also changes the 'if' that handles the case
where the extra_string (which holds the format/args) is empty.  I
don't believe that this situation can ever arise -- and if it does we
should be catching it earlier and throwing an error at that point.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c | 20 +++++++++-----------
 1 file changed, 9 insertions(+), 11 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 2cadc8c0295..4eb40c01274 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -8517,19 +8517,17 @@ code_breakpoint::code_breakpoint (struct gdbarch *gdbarch_,
       /* Do not set breakpoint locations conditions yet.  As locations
 	 are inserted, they get sorted based on their addresses.  Let
 	 the list stabilize to have reliable location numbers.  */
+    }
 
-      /* Dynamic printf requires and uses additional arguments on the
-	 command line, otherwise it's an error.  */
-      if (type == bp_dprintf)
-	{
-	  if (extra_string != nullptr)
-	    update_dprintf_command_list (this);
-	  else
-	    error (_("Format string required"));
-	}
-      else if (extra_string != nullptr)
-	error (_("Garbage '%s' at end of command"), extra_string.get ());
+  /* Dynamic printf requires and uses additional arguments on the
+     command line, otherwise it's an error.  */
+  if (type == bp_dprintf)
+    {
+      gdb_assert (extra_string != nullptr);
+      update_dprintf_command_list (this);
     }
+  else if (extra_string != nullptr)
+    error (_("Garbage '%s' at end of command"), extra_string.get ());
 
   /* The order of the locations is now stable.  Set the location
      condition using the location's number.  */
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv3 5/9] gdb: don't display inferior list for pending breakpoints
  2023-05-30 20:46   ` [PATCHv3 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
                       ` (3 preceding siblings ...)
  2023-05-30 20:46     ` [PATCHv3 4/9] gdb: build dprintf commands just once in code_breakpoint constructor Andrew Burgess
@ 2023-05-30 20:46     ` Andrew Burgess
  2023-05-30 20:46     ` [PATCHv3 6/9] gdb: parse pending breakpoint thread/task immediately Andrew Burgess
                       ` (4 subsequent siblings)
  9 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-05-30 20:46 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

I noticed that in the 'info breakpoints' output, GDB sometimes prints
the inferior list for pending breakpoints, this doesn't seem right to
me.  A pending breakpoint has no locations (at least, as far as we
display things in the 'info breakpoints' output), so including an
inferior list seems odd.

Here's what I see right now:

  (gdb) info breakpoint 5
  Num     Type           Disp Enb Address            What
  5       breakpoint     keep y   <PENDING>          foo inf 1
  (gdb)

It's the 'inf 1' at the end of the line that I'm objecting too.

To trigger this behaviour we need to be in a multi-inferior debug
session.  The breakpoint must have been non-pending at some point in
the past, and so have a location assigned to it.

The breakpoint becomes pending again as a result of a shared library
being unloaded.  When this happens the location itself is marked
pending (via bp_location::shlib_disabled).

In print_one_breakpoint_location, in order to print the inferior list
we check that the breakpoint has a location, and that we have multiple
inferiors, but we don't check if the location itself is pending.

This commit adds that check, which means the output is now:

  (gdb) info breakpoint 5
  Num     Type           Disp Enb Address            What
  5       breakpoint     keep y   <PENDING>          foo
  (gdb)

Which I think makes more sense.
---
 gdb/breakpoint.c                         |   2 +-
 gdb/testsuite/gdb.multi/pending-bp-lib.c |  22 +++++
 gdb/testsuite/gdb.multi/pending-bp.c     |  66 +++++++++++++
 gdb/testsuite/gdb.multi/pending-bp.exp   | 115 +++++++++++++++++++++++
 4 files changed, 204 insertions(+), 1 deletion(-)
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.exp

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 4eb40c01274..6a76bfbefe8 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -6452,7 +6452,7 @@ print_one_breakpoint_location (struct breakpoint *b,
 	}
     }
 
-  if (loc != NULL && !header_of_multiple)
+  if (loc != NULL && !header_of_multiple && !loc->shlib_disabled)
     {
       std::vector<int> inf_nums;
       int mi_only = 1;
diff --git a/gdb/testsuite/gdb.multi/pending-bp-lib.c b/gdb/testsuite/gdb.multi/pending-bp-lib.c
new file mode 100644
index 00000000000..15d1b9833dd
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp-lib.c
@@ -0,0 +1,22 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+int global_var = 0;
+
+void
+foo (int arg)
+{
+  global_var = arg;
+}
diff --git a/gdb/testsuite/gdb.multi/pending-bp.c b/gdb/testsuite/gdb.multi/pending-bp.c
new file mode 100644
index 00000000000..ca8a3c20b72
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp.c
@@ -0,0 +1,66 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#include <dlfcn.h>
+#include <stdlib.h>
+
+void
+breakpt ()
+{
+  /* Nothing.  */
+}
+
+volatile int global_counter = 0;
+
+volatile int call_count = 1;
+
+int
+main (void)
+{
+  void *handle;
+  void (*func)(int);
+
+  /* Some filler work so that we don't initially stop on the breakpt call
+     below.  */
+  ++global_counter;
+
+  breakpt ();	/* Break before open.  */
+
+  /* Now load the shared library.  */
+  handle = dlopen (SHLIB_NAME, RTLD_LAZY);
+  if (handle == NULL)
+    abort ();
+
+  breakpt ();	/* Break after open.  */
+
+  /* Find the function symbol.  */
+  func = (void (*)(int)) dlsym (handle, "foo");
+
+  for (; call_count > 0; --call_count)
+    {
+      /* Call the library function.  */
+      func (1);
+    }
+
+  breakpt ();	/* Break before close.  */
+
+  /* Unload the shared library.  */
+  if (dlclose (handle) != 0)
+    abort ();
+
+  breakpt ();	/* Break after close.  */
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.multi/pending-bp.exp b/gdb/testsuite/gdb.multi/pending-bp.exp
new file mode 100644
index 00000000000..4a65f79cfc4
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp.exp
@@ -0,0 +1,115 @@
+# Copyright 2023 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+# Tests related to pending breakpoints in a multi-inferior environment.
+
+require allow_shlib_tests !use_gdb_stub
+
+standard_testfile
+
+set libname $testfile-lib
+set srcfile_lib $srcdir/$subdir/$libname.c
+set binfile_lib [standard_output_file $libname.so]
+
+if { [gdb_compile_shlib $srcfile_lib $binfile_lib {}] != "" } {
+    untested "failed to compile shared library 1"
+    return -1
+}
+
+set binfile_lib_target [gdb_download_shlib $binfile_lib]
+
+if { [build_executable "failed to prepare" $testfile $srcfile \
+	  [list debug \
+	       additional_flags=-DSHLIB_NAME=\"$binfile_lib_target\" \
+	       shlib_load pthreads]] } {
+    return -1
+}
+
+# Used to override delete_breakpoints when we don't want breakpoints
+# deleted.
+proc do_nothing {} {}
+
+# Start two inferiors, both running the same test binary.  The arguments
+# INF_1_STOP and INF_2_STOP are source code patterns that are passed to
+# gdb_get_line_number to figure out where each inferior should be stopped.
+#
+# This proc does a clean_restart and leaves inferior 2 selected.  Also the
+# 'breakpoint pending' flag is enabled, so pending breakpoints can be created
+# without GDB prompting the user.
+proc do_test_setup { inf_1_stop inf_2_stop } {
+    clean_restart ${::binfile}
+
+    gdb_locate_shlib $::binfile_lib
+
+    if ![runto_main] {
+	return false
+    }
+
+    gdb_breakpoint [gdb_get_line_number ${inf_1_stop}] temporary
+    gdb_continue_to_breakpoint "move inferior 1 into position"
+
+    gdb_test "add-inferior -exec ${::binfile}" \
+	"Added inferior 2.*" "add inferior 2"
+    gdb_test "inferior 2" "Switching to inferior 2 .*" "switch to inferior 2"
+
+    with_override delete_breakpoints do_nothing {
+	if {![runto_main]} {
+	    return false
+	}
+    }
+
+    gdb_breakpoint [gdb_get_line_number ${inf_2_stop}] temporary
+    gdb_continue_to_breakpoint "move inferior 2 into position"
+
+    gdb_test_no_output "set breakpoint pending on"
+
+    return true
+}
+
+# Check that when a breakpoint is in the pending state, but that breakpoint
+# does have some locations (those locations themselves are pending), GDB
+# doesn't display the inferior list in the 'info breakpoints' output.
+proc_with_prefix test_no_inf_display {} {
+    do_test_setup "Break before close" "Break before open"
+
+    # Create a breakpoint on 'foo'.  This will find a location in inferior 1,
+    # but will not find a location in inferior 2 -- the shared library is not
+    # yet loaded in that inferior.
+    gdb_breakpoint "foo"
+    set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+		   "get foo breakpoint number"]
+
+    # Check the 'info breakpoints' output.  Notice we display the inferior
+    # list at the end of the breakpoint line.
+    gdb_test "info breakpoint $bpnum" \
+	"$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex\\s+<foo\[^>\]*>\\s+inf 1" \
+	"check info breakpoints while breakpoint is inserted"
+
+    # Ensure we are in inferior 1, move the inferior forward until the shared
+    # library has been unloaded.  The breakpoint on 'foo' will return to the
+    # pending state.
+    gdb_test "inferior 1" "Switching to inferior 1 .*"
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "after close library"
+
+    # Check the 'info breakpoints' output, check there is no 'inf 1' at the
+    # end of the breakpoint line.
+    gdb_test "info breakpoint $bpnum" \
+	"$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	"check info breakpoints while breakpoint is pending"
+}
+
+# Run all the tests.
+test_no_inf_display
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv3 6/9] gdb: parse pending breakpoint thread/task immediately
  2023-05-30 20:46   ` [PATCHv3 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
                       ` (4 preceding siblings ...)
  2023-05-30 20:46     ` [PATCHv3 5/9] gdb: don't display inferior list for pending breakpoints Andrew Burgess
@ 2023-05-30 20:46     ` Andrew Burgess
  2023-05-30 20:46     ` [PATCHv3 7/9] gdb: remove breakpoint_re_set_one Andrew Burgess
                       ` (3 subsequent siblings)
  9 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-05-30 20:46 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Eli Zaretskii

The initial motivation for this commit was to allow thread or (in the
future) inferior specific breakpoints to only be inserted within the
appropriate inferior's program-space.  The benefit of this is that
inferiors for which the breakpoint does not apply will no longer need
to stop, and then resume, for such breakpoints.  This commit does not
make this change, but is a refactor to allow this change in a later
commit.

The problem we currently have is that when a thread-specific
breakpoint is created, the thread number is only parsed by calling
find_condition_and_thread_for_sals.  This function is only called for
non-pending breakpoints, and requires that we know the locations at
which the breakpoint will be placed (for expression checking in case
the breakpoint is also conditional).

A consequence of this is that by the time we figure out the breakpoint
is thread-specific we have already looked up locations in all program
spaces.  This feels wasteful -- if we knew the thread-id earlier then
we could reduce the work GDB does by only looking up locations within
the program space for which the breakpoint applies.

Another consequence of how find_condition_and_thread_for_sals is
called is that pending breakpoints don't currently know they are
thread-specific, nor even that they are conditional!  Additionally, by
delaying parsing the thread-id, pending breakpoints can be created for
non-existent threads, this is different to how non-pending
breakpoints are handled.

In this commit the create_breakpoint function is updated so that the
extra_string, which contains the thread/task/condition information, is
parsed immediately, even for pending breakpoints.

Obviously, the condition still can't be validated until the breakpoint
becomes non-pending, but the thread/task information can be pulled
from the extra-string, and can be validated early on, even for pending
breakpoints.

There are a couple of benefits to doing this:

1. Printing of breakpoints is more consistent now.  Consider creating
   a conditional breakpoint before this commit:

    (gdb) set breakpoint pending on
    (gdb) break pendingfunc if (0)
    Function "pendingfunc" not defined.
    Breakpoint 1 (pendingfunc if (0)) pending.
    (gdb) break main if (0)
    Breakpoint 2 at 0x401198: file /tmp/hello.c, line 18.
    (gdb) info breakpoints
    Num     Type           Disp Enb Address            What
    1       breakpoint     keep y   <PENDING>          pendingfunc if (0)
    2       breakpoint     keep y   0x0000000000401198 in main at /tmp/hello.c:18
            stop only if (0)
    (gdb)

   And after this commit:

    (gdb) set breakpoint pending on
    (gdb) break pendingfunc if (0)
    Function "pendingfunc" not defined.
    Breakpoint 1 (pendingfunc) pending.
    (gdb) break main if (0)
    Breakpoint 2 at 0x401198: file /home/andrew/tmp/hello.c, line 18.
    (gdb) info breakpoints
    Num     Type           Disp Enb Address            What
    1       breakpoint     keep y   <PENDING>          pendingfunc
            stop only if (0)
    2       breakpoint     keep y   0x0000000000401198 in main at /home/andrew/tmp/hello.c:18
            stop only if (0)
    (gdb)

   Notice that the display of the condition is now the same for the
   pending and non-pending breakpoints.

   The same is true for the thread information in thread-specific
   breakpoints, this information is displayed on its own line now
   rather than being part of the 'What' field.

2. We can check that the thread exists as soon as the pending
   breakpoint exits.  Currently there is a weird different between
   pending and non-pending breakpoints when creating a thread-specific
   breakpoint.  A pending thread-specific breakpoint only checks its
   thread when it becomes non-pending, at which point the thread the
   breakpoint was intended for might have exited.  Here's the
   behaviour before this commit:

    (gdb) set breakpoint pending on
    (gdb) break foo thread 2
    Function "foo" not defined.
    Breakpoint 2 (foo thread 2) pending.
    (gdb) c
    Continuing.
    [Thread 0x7ffff7c56700 (LWP 2948835) exited]
    Error in re-setting breakpoint 2: Unknown thread 2.
    [Inferior 1 (process 2948832) exited normally]
    (gdb)

   Notice the 'Error in re-setting breakpoint 2: Unknown thread 2.'
   line, this was triggered when the thread tried to become
   non-pending, and GDB discovers that the thread no longer exists.

   Compare that to the behaviour after this commit:

    (gdb) set breakpoint pending on
    (gdb) break foo thread 2
    Function "foo" not defined.
    Breakpoint 2 (foo) pending.
    (gdb) c
    Continuing.
    [Thread 0x7ffff7c56700 (LWP 2949243) exited]
    Thread-specific breakpoint 2 deleted - thread 2 no longer in the thread list.
    [Inferior 1 (process 2949240) exited normally]
    (gdb)

   Now the behaviour for pending breakpoints is identical to
   non-pending breakpoints, the thread specific breakpoint is removed
   as soon as the thread the breakpoint is associated with exits.

As a result of this commit the breakpoints 'extra_string' field is now
only used by bp_dprintf type breakpoints to hold the printf format and
arguments.  This string should always be empty for other breakpoint
types.  This allows me to clean up some code in
print_breakpoint_location.

In code_breakpoint::code_breakpoint I'm able to change an error case
into an assert.  This is because this error is now handled earlier in
create_breakpoint.  As a result we know that by this point, the
extra_string will always be nullptr for anything other than a
bp_dprintf style breakpoint.

The find_condition_and_thread_for_sals function is now no longer
needed, this was previously doing the delayed splitting of the extra
string into thread, task, and condition, but this is now all done in
create_breakpoint, so find_condition_and_thread_for_sals can be
deleted, and the code that calls this in
code_breakpoint::location_spec_to_sals can be removed.  With this
update this code would only ever be reached for bp_dprintf style
breakpoints, and in these cases the extra_string should not contain
anything other than format and args.

The most interesting changes are all in create_breakpoint and in the
new file break-cond-parse.c.  We have a new block of code early on in
create_breakpoint that is responsible for splitting the extra_string
into its component parts by calling create_breakpoint_parse_arg_string
a function in the new break-cond-parse.c file.  This means that some
of the later code can be simplified a little.

The new break-cond-parse.c file implements the splitting up the
extra_string and finding all the parts, as well as some self-tests for
the new function.

Finally, now we know all the details, these can be stored within the
breakpoint object if we end up creating a deferred breakpoint.
Additionally, if we are creating a deferred bp_dprintf we can parse
the extra_string to build the printf command.

Reviewed-By: Eli Zaretskii <eliz@gnu.org>
---
 gdb/Makefile.in                               |   2 +
 gdb/NEWS                                      |   4 +
 gdb/break-cond-parse.c                        | 403 ++++++++++++++++++
 gdb/break-cond-parse.h                        |  47 ++
 gdb/breakpoint.c                              | 330 ++++----------
 gdb/testsuite/gdb.base/condbreak.exp          |  20 +-
 gdb/testsuite/gdb.base/pending.exp            |  23 +-
 gdb/testsuite/gdb.linespec/explicit.exp       |   4 +-
 gdb/testsuite/gdb.mi/mi-dprintf-pending.exp   |   3 +-
 .../gdb.threads/del-pending-thread-bp-lib.c   |  22 +
 .../gdb.threads/del-pending-thread-bp.c       |  85 ++++
 .../gdb.threads/del-pending-thread-bp.exp     | 108 +++++
 12 files changed, 793 insertions(+), 258 deletions(-)
 create mode 100644 gdb/break-cond-parse.c
 create mode 100644 gdb/break-cond-parse.h
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.exp

diff --git a/gdb/Makefile.in b/gdb/Makefile.in
index d909786792c..afa43b8e4de 100644
--- a/gdb/Makefile.in
+++ b/gdb/Makefile.in
@@ -1025,6 +1025,7 @@ COMMON_SFILES = \
 	break-catch-sig.c \
 	break-catch-syscall.c \
 	break-catch-throw.c \
+	break-cond-parse.c \
 	breakpoint.c \
 	bt-utils.c \
 	btrace.c \
@@ -1292,6 +1293,7 @@ HFILES_NO_SRCDIR = \
 	bfd-target.h \
 	bfin-tdep.h \
 	block.h \
+	break-cond-parse.h \
 	breakpoint.h \
 	bsd-kvm.h \
 	bsd-uthread.h \
diff --git a/gdb/NEWS b/gdb/NEWS
index d97e3c15a87..d50b01ffa4f 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -67,6 +67,10 @@
     break foo thread 1 task 1
     watch var thread 2 task 3
 
+* For breakpoints that are created in the 'pending' state, any
+  'thread' or 'task' keywords are parsed at the time the breakpoint is
+  created, rather than at the time the breakpoint becomes non-pending.
+
 * New commands
 
 maintenance print record-instruction [ N ]
diff --git a/gdb/break-cond-parse.c b/gdb/break-cond-parse.c
new file mode 100644
index 00000000000..e8da24d2643
--- /dev/null
+++ b/gdb/break-cond-parse.c
@@ -0,0 +1,403 @@
+/* Copyright (C) 2023 Free Software Foundation, Inc.
+
+   This file is part of GDB.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#include "defs.h"
+#include "gdbsupport/gdb_assert.h"
+#include "gdbsupport/selftest.h"
+#include "test-target.h"
+#include "scoped-mock-context.h"
+#include "break-cond-parse.h"
+#include "tid-parse.h"
+#include "ada-lang.h"
+
+/* When parsing tokens from a string, which direction are we parsing?
+
+   Given the following string and pointer 'ptr':
+
+     ABC DEF GHI JKL
+            ^
+           ptr
+
+   Parsing 'forward' will return the token 'GHI' and update 'ptr' to point
+   between GHI and JKL.  Parsing 'backward' will return the token 'DEF' and
+   update 'ptr' to point between ABC and DEF.
+*/
+
+enum class parse_direction
+{
+  /* Parse the next token forwards.  */
+  forward,
+
+  /* Parse the previous token backwards.  */
+  backward
+};
+
+struct token
+{
+  /* Create a new token.  START points to the first character of the new
+     token, while END points at the last character of the new token.
+
+     Neither START or END can be nullptr, and both START and END must point
+     into the same C style string (i.e. there should be no null character
+     between START and END).  END must be equal to, or greater than START,
+     that is, it is not possible to create a zero length token.  */
+
+  token (const char *start, const char *end)
+    : m_start (start),
+      m_end (end)
+  {
+    gdb_assert (m_end >= m_start);
+    gdb_assert (m_start + strlen (m_start) > m_end);
+  }
+
+  /* Return a pointer to the first character of this token.  */
+  const char *start () const
+  {
+    return m_start;
+  }
+
+  /* Return a pointer to the last character of this token.  */
+  const char *end () const
+  {
+    return m_end;
+  }
+
+  /* Return the length of the token.  */
+  size_t length () const
+  {
+    return m_end - m_start + 1;
+  }
+
+  /* Return true if this token matches STR.  If this token is shorter than
+     STR then only a partial match is performed and true will be returned
+     if the token length sub-string matches.  Otherwise, return false.  */
+  bool matches (const char *str) const
+  {
+    return strncmp (m_start, str, length ()) == 0;
+  }
+
+private:
+  /* The first character of this token.  */
+  const char *m_start;
+
+  /* The last character of this token.  */
+  const char *m_end;
+};
+
+/* Find the next token in DIRECTION from *CURR.  */
+
+static token
+find_next_token (const char **curr, parse_direction direction)
+{
+  const char *tok_start, *tok_end;
+
+  if (direction == parse_direction::forward)
+    {
+      *curr = skip_spaces (*curr);
+      tok_start = *curr;
+      *curr = skip_to_space (*curr);
+      tok_end = *curr - 1;
+    }
+  else
+    {
+      gdb_assert (direction == parse_direction::backward);
+
+      while (isspace (**curr))
+	--(*curr);
+
+      tok_end = *curr;
+
+      while (!isspace (**curr))
+	--(*curr);
+
+      tok_start = (*curr) + 1;
+    }
+
+  return token (tok_start, tok_end);
+}
+
+/* See break-cond-parse.h.  */
+
+void
+create_breakpoint_parse_arg_string
+  (const char *tok, gdb::unique_xmalloc_ptr<char> *cond_string,
+   int *thread, int *task, gdb::unique_xmalloc_ptr<char> *rest, bool *force)
+{
+  /* Set up the defaults.  */
+  cond_string->reset ();
+  rest->reset ();
+  *thread = -1;
+  *task = -1;
+  *force = false;
+
+  if (tok == nullptr)
+    return;
+
+  const char *cond_start = nullptr;
+  const char *cond_end = nullptr;
+  parse_direction direction = parse_direction::forward;
+  while (*tok != '\0')
+    {
+      /* Find the next token.  If moving backward and this token starts at
+	 the same location as the condition then we must have found the
+	 other end of the condition string -- we're done.  */
+      token t = find_next_token (&tok, direction);
+      if (direction == parse_direction::backward && t.start () <= cond_start)
+	{
+	  cond_end = t.end () + 1;
+	  break;
+	}
+
+      /* We only have a single flag option to check for.  All the other
+	 options take a value so require an additional token to be found.  */
+      if (t.length () > 0 && t.matches ("-force-condition"))
+	{
+	  *force = true;
+	  continue;
+	}
+
+      /* Maybe the first token was the last token in the string.  If this
+	 is the case then we definitely can't try to extract a value
+	 token.  This also means that the token T is meaningless.  Reset
+	 TOK to point at the start of the unknown content and break out of
+	 the loop.  We'll record the unknown part of the string outside of
+	 the scanning loop (below).  */
+      if (direction == parse_direction::forward && *tok == '\0')
+	{
+	  tok = t.start ();
+	  break;
+	}
+
+      /* As before, find the next token and, if we are scanning backwards,
+	 check that we have not reached the start of the condition string.  */
+      token v = find_next_token (&tok, direction);
+      if (direction == parse_direction::backward && v.start () <= cond_start)
+	{
+	  /* Use token T here as that must also be part of the condition
+	     string.  */
+	  cond_end = t.end () + 1;
+	  break;
+	}
+
+      /* When moving backward we will first parse the value token then the
+	 keyword token, so swap them now.  */
+      if (direction == parse_direction::backward)
+	std::swap (t, v);
+
+      /* Check for valid option in token T.  If we find a valid option then
+	 parse the value from the token V.  Except for 'if', that's handled
+	 differently.
+
+         For the 'if' token we need to capture the entire condition
+         string, so record the start of the condition string and then
+         start scanning backwards looking for the end of the condition
+         string.  */
+      if (direction == parse_direction::forward && t.length () > 0
+	  && t.matches ("if"))
+	{
+	  cond_start = v.start ();
+	  tok = tok + strlen (tok);
+	  gdb_assert (*tok == '\0');
+	  --tok;
+	  direction = parse_direction::backward;
+	  continue;
+	}
+      else if (t.length () > 0 && t.matches ("thread"))
+	{
+	  const char *tmptok;
+	  struct thread_info *thr;
+
+	  if (*thread != -1)
+	    error(_("You can specify only one thread."));
+
+	  if (*task != -1)
+	    error (_("You can specify only one of thread or task."));
+
+	  thr = parse_thread_id (v.start (), &tmptok);
+	  const char *expected_end = skip_spaces (v.end () + 1);
+	  if (tmptok != expected_end)
+	    error (_("Junk after thread keyword."));
+	  *thread = thr->global_num;
+	}
+      else if (t.length () > 0 && t.matches ("task"))
+	{
+	  char *tmptok;
+
+	  if (*task != -1)
+	    error(_("You can specify only one task."));
+
+	  if (*thread != -1)
+	    error (_("You can specify only one of thread or task."));
+
+	  *task = strtol (v.start (), &tmptok, 0);
+	  const char *expected_end = v.end () + 1;
+	  if (tmptok != expected_end)
+	    error (_("Junk after task keyword."));
+	  if (!valid_task_id (*task))
+	    error (_("Unknown task %d."), *task);
+	}
+      else
+	{
+	  /* An unknown token.  If we are scanning forward then reset TOK
+	     to point at the start of the unknown content, we record this
+	     outside of the scanning loop (below).
+
+	     If we are scanning backward then unknown content is assumed to
+	     be the other end of the condition string, obviously, this is
+	     just a heuristic, we could be looking at a mistyped command
+	     line, but this will be spotted when the condition is
+	     eventually evaluated.
+
+	     Either way, no more scanning is required after this.  */
+	  if (direction == parse_direction::forward)
+	    tok = t.start ();
+	  else
+	    {
+	      gdb_assert (direction == parse_direction::backward);
+	      cond_end = v.end () + 1;
+	    }
+	  break;
+	}
+    }
+
+  if (cond_start != nullptr)
+    {
+      /* If we found the start of a condition string then we should have
+	 switched to backward scan mode, and found the end of the condition
+	 string.  Capture the whole condition string into COND_STRING now.  */
+      gdb_assert (direction == parse_direction::backward);
+      gdb_assert (cond_end != nullptr);
+      cond_string->reset (savestring (cond_start, cond_end - cond_start));
+    }
+  else if (*tok != '\0')
+    {
+      /* If we didn't have a condition start pointer then we should still
+	 be in forward scanning mode.  If we didn't reach the end of the
+	 input string (TOK is not at the null character) then the rest of
+	 the input string is garbage that we didn't understand.
+
+	 Record the unknown content into REST.  The caller of this function
+	 will report this as an error later on.  We could report the error
+	 here, but we prefer to allow the caller to run other checks, and
+	 prioritise other errors before reporting this problem.  */
+      gdb_assert (direction == parse_direction::forward);
+      rest->reset (savestring (tok, strlen (tok)));
+    }
+}
+
+#if GDB_SELF_TEST
+
+namespace selftests {
+
+/* Run a single test of the create_breakpoint_parse_arg_string function.
+   INPUT is passed to create_breakpoint_parse_arg_string while all other
+   arguments are the expected output from
+   create_breakpoint_parse_arg_string.  */
+
+static void
+test (const char *input, const char *condition, int thread = -1,
+      int task = -1, bool force = false, const char *rest = nullptr)
+{
+  gdb::unique_xmalloc_ptr<char> extracted_condition;
+  gdb::unique_xmalloc_ptr<char> extracted_rest;
+  int extracted_thread, extracted_task;
+  bool extracted_force_condition;
+  std::string exception_msg;
+
+  try
+    {
+      create_breakpoint_parse_arg_string (input, &extracted_condition,
+					  &extracted_thread,
+					  &extracted_task, &extracted_rest,
+					  &extracted_force_condition);
+    }
+  catch (const gdb_exception_error &ex)
+    {
+      string_file buf;
+
+      exception_print (&buf, ex);
+      exception_msg = buf.release ();
+    }
+
+  if ((condition == nullptr) != (extracted_condition.get () == nullptr)
+      || (condition != nullptr
+	  && strcmp (condition, extracted_condition.get ()) != 0)
+      || (rest == nullptr) != (extracted_rest.get () == nullptr)
+      || (rest != nullptr && strcmp (rest, extracted_rest.get ()) != 0)
+      || thread != extracted_thread
+      || task != extracted_task
+      || force != extracted_force_condition
+      || !exception_msg.empty ())
+    {
+      if (run_verbose ())
+	{
+	  debug_printf ("input: '%s'\n", input);
+	  debug_printf ("condition: '%s'\n", extracted_condition.get ());
+	  debug_printf ("rest: '%s'\n", extracted_rest.get ());
+	  debug_printf ("thread: %d\n", extracted_thread);
+	  debug_printf ("task: %d\n", extracted_task);
+	  debug_printf ("forced: %s\n",
+			extracted_force_condition ? "true" : "false");
+	  debug_printf ("exception: '%s'\n", exception_msg.c_str ());
+	}
+
+      /* Report the failure.  */
+      SELF_CHECK (false);
+    }
+}
+
+/* Test the create_breakpoint_parse_arg_string function.  Just wraps
+   multiple calls to the test function above.  */
+
+static void
+create_breakpoint_parse_arg_string_tests (void)
+{
+  gdbarch *arch = current_inferior ()->gdbarch;
+  scoped_restore_current_pspace_and_thread restore;
+  scoped_mock_context<test_target_ops> mock_target (arch);
+
+  int global_thread_num = mock_target.mock_thread.global_num;
+
+  test ("  if blah  ", "blah");
+  test (" if blah thread 1", "blah", global_thread_num);
+  test (" if blah thread 1  ", "blah", global_thread_num);
+  test ("thread 1 woof", nullptr, global_thread_num, -1, false, "woof");
+  test ("thread 1 X", nullptr, global_thread_num, -1, false, "X");
+  test (" if blah thread 1 -force-condition", "blah", global_thread_num,
+	-1, true);
+  test (" -force-condition if blah thread 1", "blah", global_thread_num,
+	-1, true);
+  test (" -force-condition if blah thread 1  ", "blah", global_thread_num,
+	-1, true);
+  test ("thread 1 -force-condition if blah", "blah", global_thread_num,
+	-1, true);
+  test ("if (A::outer::func ())", "(A::outer::func ())");
+}
+
+} // namespace selftests
+#endif /* GDB_SELF_TEST */
+
+void _initialize_break_cond_parse ();
+void
+_initialize_break_cond_parse ()
+{
+#if GDB_SELF_TEST
+  selftests::register_test
+    ("create_breakpoint_parse_arg_string",
+     selftests::create_breakpoint_parse_arg_string_tests);
+#endif
+}
diff --git a/gdb/break-cond-parse.h b/gdb/break-cond-parse.h
new file mode 100644
index 00000000000..ec62b88ea92
--- /dev/null
+++ b/gdb/break-cond-parse.h
@@ -0,0 +1,47 @@
+/* Copyright (C) 2023 Free Software Foundation, Inc.
+
+   This file is part of GDB.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#if !defined (BREAK_COND_PARSE_H)
+#define BREAK_COND_PARSE_H 1
+
+/* Given TOK, a string possibly containing a condition, thread, task and
+   force-condition flag, as accepted by the 'break' command, extract the
+   condition string, thread and task numbers, and the force_condition flag,
+   then set *COND_STRING, *THREAD, *TASK, and *FORCE.
+
+   As TOK is parsed, if an unknown keyword is encountered before the 'if'
+   keyword then everything starting from the unknown keyword is placed into
+   *REST.
+
+   Both *COND and *REST are initialized to nullptr.  If no 'if' keyword is
+   found then *COND will be returned as nullptr.  If no unknown content is
+   found then *REST is returned as nullptr.
+
+   If no thread is found, *THREAD is set to -1.  If no task is found, *TASK
+   is set to -1.  If the -force-condition flag is not found then *FORCE is
+   set to false.
+
+   Due to the free-form nature that the string TOK might take (a 'thread'
+   keyword can appear before or after an 'if' condition) then we end up
+   having to check for keywords from both the start of TOK and the end of
+   TOK.  */
+
+extern void create_breakpoint_parse_arg_string
+  (const char *tok, gdb::unique_xmalloc_ptr<char> *cond_string,
+   int *thread, int *task, gdb::unique_xmalloc_ptr<char> *rest, bool *force);
+
+#endif
diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 6a76bfbefe8..ed3d61605bf 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -70,6 +70,7 @@
 #include "cli/cli-style.h"
 #include "cli/cli-decode.h"
 #include <unordered_set>
+#include "break-cond-parse.h"
 
 /* readline include files */
 #include "readline/tilde.h"
@@ -6190,20 +6191,7 @@ print_breakpoint_location (const breakpoint *b, const bp_location *loc)
       uiout->field_stream ("at", stb);
     }
   else
-    {
-      uiout->field_string ("pending", b->locspec->to_string ());
-      /* If extra_string is available, it could be holding a condition
-	 or dprintf arguments.  In either case, make sure it is printed,
-	 too, but only for non-MI streams.  */
-      if (!uiout->is_mi_like_p () && b->extra_string != NULL)
-	{
-	  if (b->type == bp_dprintf)
-	    uiout->text (",");
-	  else
-	    uiout->text (" ");
-	  uiout->text (b->extra_string.get ());
-	}
-    }
+    uiout->field_string ("pending", b->locspec->to_string ());
 
   if (loc && is_breakpoint (b)
       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
@@ -8526,8 +8514,8 @@ code_breakpoint::code_breakpoint (struct gdbarch *gdbarch_,
       gdb_assert (extra_string != nullptr);
       update_dprintf_command_list (this);
     }
-  else if (extra_string != nullptr)
-    error (_("Garbage '%s' at end of command"), extra_string.get ());
+  else
+    gdb_assert (extra_string == nullptr);
 
   /* The order of the locations is now stable.  Set the location
      condition using the location's number.  */
@@ -8754,160 +8742,6 @@ check_fast_tracepoint_sals (struct gdbarch *gdbarch,
     }
 }
 
-/* Given TOK, a string specification of condition and thread, as
-   accepted by the 'break' command, extract the condition
-   string and thread number and set *COND_STRING and *THREAD.
-   PC identifies the context at which the condition should be parsed.
-   If no condition is found, *COND_STRING is set to NULL.
-   If no thread is found, *THREAD is set to -1.  */
-
-static void
-find_condition_and_thread (const char *tok, CORE_ADDR pc,
-			   gdb::unique_xmalloc_ptr<char> *cond_string,
-			   int *thread, int *task,
-			   gdb::unique_xmalloc_ptr<char> *rest)
-{
-  cond_string->reset ();
-  *thread = -1;
-  *task = -1;
-  rest->reset ();
-  bool force = false;
-
-  while (tok && *tok)
-    {
-      const char *end_tok;
-      int toklen;
-      const char *cond_start = NULL;
-      const char *cond_end = NULL;
-
-      tok = skip_spaces (tok);
-
-      if ((*tok == '"' || *tok == ',') && rest)
-	{
-	  rest->reset (savestring (tok, strlen (tok)));
-	  return;
-	}
-
-      end_tok = skip_to_space (tok);
-
-      toklen = end_tok - tok;
-
-      if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
-	{
-	  tok = cond_start = end_tok + 1;
-	  try
-	    {
-	      parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
-	    }
-	  catch (const gdb_exception_error &)
-	    {
-	      if (!force)
-		throw;
-	      else
-		tok = tok + strlen (tok);
-	    }
-	  cond_end = tok;
-	  cond_string->reset (savestring (cond_start, cond_end - cond_start));
-	}
-      else if (toklen >= 1 && strncmp (tok, "-force-condition", toklen) == 0)
-	{
-	  tok = tok + toklen;
-	  force = true;
-	}
-      else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
-	{
-	  const char *tmptok;
-	  struct thread_info *thr;
-
-	  if (*thread != -1)
-	    error(_("You can specify only one thread."));
-
-	  if (*task != -1)
-	    error (_("You can specify only one of thread or task."));
-
-	  tok = end_tok + 1;
-	  thr = parse_thread_id (tok, &tmptok);
-	  if (tok == tmptok)
-	    error (_("Junk after thread keyword."));
-	  *thread = thr->global_num;
-	  tok = tmptok;
-	}
-      else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
-	{
-	  char *tmptok;
-
-	  if (*task != -1)
-	    error(_("You can specify only one task."));
-
-	  if (*thread != -1)
-	    error (_("You can specify only one of thread or task."));
-
-	  tok = end_tok + 1;
-	  *task = strtol (tok, &tmptok, 0);
-	  if (tok == tmptok)
-	    error (_("Junk after task keyword."));
-	  if (!valid_task_id (*task))
-	    error (_("Unknown task %d."), *task);
-	  tok = tmptok;
-	}
-      else if (rest)
-	{
-	  rest->reset (savestring (tok, strlen (tok)));
-	  return;
-	}
-      else
-	error (_("Junk at end of arguments."));
-    }
-}
-
-/* Call 'find_condition_and_thread' for each sal in SALS until a parse
-   succeeds.  The parsed values are written to COND_STRING, THREAD,
-   TASK, and REST.  See the comment of 'find_condition_and_thread'
-   for the description of these parameters and INPUT.  */
-
-static void
-find_condition_and_thread_for_sals (const std::vector<symtab_and_line> &sals,
-				    const char *input,
-				    gdb::unique_xmalloc_ptr<char> *cond_string,
-				    int *thread, int *task,
-				    gdb::unique_xmalloc_ptr<char> *rest)
-{
-  int num_failures = 0;
-  for (auto &sal : sals)
-    {
-      gdb::unique_xmalloc_ptr<char> cond;
-      int thread_id = -1;
-      int task_id = -1;
-      gdb::unique_xmalloc_ptr<char> remaining;
-
-      /* Here we want to parse 'arg' to separate condition from thread
-	 number.  But because parsing happens in a context and the
-	 contexts of sals might be different, try each until there is
-	 success.  Finding one successful parse is sufficient for our
-	 goal.  When setting the breakpoint we'll re-parse the
-	 condition in the context of each sal.  */
-      try
-	{
-	  find_condition_and_thread (input, sal.pc, &cond, &thread_id,
-				     &task_id, &remaining);
-	  *cond_string = std::move (cond);
-	  /* At most one of thread or task can be set.  */
-	  gdb_assert (thread_id == -1 || task_id == -1);
-	  *thread = thread_id;
-	  *task = task_id;
-	  *rest = std::move (remaining);
-	  break;
-	}
-      catch (const gdb_exception_error &e)
-	{
-	  num_failures++;
-	  /* If no sal remains, do not continue.  */
-	  if (num_failures == sals.size ())
-	    throw;
-	}
-    }
-}
-
 /* Decode a static tracepoint marker spec.  */
 
 static std::vector<symtab_and_line>
@@ -9018,6 +8852,44 @@ create_breakpoint (struct gdbarch *gdbarch,
 	      || (type_wanted != bp_dprintf
 		  && (extra_string == nullptr || parse_extra)));
 
+  /* Will hold either copies of the similarly named function argument, or
+     will hold a modified version of the function argument, depending on
+     the value of PARSE_EXTRA.  */
+  gdb::unique_xmalloc_ptr<char> cond_string_copy;
+  gdb::unique_xmalloc_ptr<char> extra_string_copy;
+
+  if (parse_extra)
+    {
+      /* Parse EXTRA_STRING splitting the parts out.  */
+      create_breakpoint_parse_arg_string (extra_string, &cond_string_copy,
+					  &thread, &task, &extra_string_copy,
+					  &force_condition);
+
+      /* We could check that EXTRA_STRING_COPY is empty at this point -- it
+	 should be, as we only get here for things that are not bp_dprintf,
+	 however, we prefer to give the location spec parser a chance to
+	 run first, this means the user will get errors about invalid
+	 location spec instead of an error about garbage at the end of the
+	 command line.
+
+	 We still do the EXTRA_STRING_COPY is empty check, just later in
+	 this function.  */
+
+      gdb_assert (thread == -1 || thread > 0);
+      gdb_assert (task == -1 || task > 0);
+    }
+  else
+    {
+      if (cond_string != nullptr)
+	cond_string_copy.reset (xstrdup (cond_string));
+      if (extra_string != nullptr)
+	extra_string_copy.reset (xstrdup (extra_string));
+    }
+
+  /* Clear these.  Updated values are now held in the *_copy locals.  */
+  cond_string = nullptr;
+  extra_string = nullptr;
+
   try
     {
       ops->create_sals_from_location_spec (locspec, &canonical);
@@ -9053,6 +8925,13 @@ create_breakpoint (struct gdbarch *gdbarch,
 	throw;
     }
 
+  /* The only bp_dprintf should have anything in EXTRA_STRING_COPY by this
+     point.  For all other breakpoints this indicates an error.  We could
+     place this check earlier in the function, but we prefer to see errors
+     from the location spec parser before we see this error message.  */
+  if (type_wanted != bp_dprintf && extra_string_copy.get () != nullptr)
+    error (_("Garbage '%s' at end of command"), extra_string_copy.get ());
+
   if (!pending && canonical.lsals.empty ())
     return 0;
 
@@ -9076,62 +8955,31 @@ create_breakpoint (struct gdbarch *gdbarch,
      breakpoint.  */
   if (!pending)
     {
-      gdb::unique_xmalloc_ptr<char> cond_string_copy;
-      gdb::unique_xmalloc_ptr<char> extra_string_copy;
-
-      if (parse_extra)
+      /* Check the validity of the condition.  We should error out if the
+	 condition is invalid at all of the locations and if it is not
+	 forced.  In the PARSE_EXTRA case above, this check is done when
+	 parsing the EXTRA_STRING.  */
+      if (cond_string_copy.get () != nullptr && !force_condition)
 	{
-	  gdb_assert (type_wanted != bp_dprintf);
-
-	  gdb::unique_xmalloc_ptr<char> rest;
-	  gdb::unique_xmalloc_ptr<char> cond;
-
+	  int num_failures = 0;
 	  const linespec_sals &lsal = canonical.lsals[0];
-
-	  find_condition_and_thread_for_sals (lsal.sals, extra_string,
-					      &cond, &thread, &task, &rest);
-
-	  if (rest.get () != nullptr && *(rest.get ()) != '\0')
-	    error (_("Garbage '%s' at end of command"), rest.get ());
-
-	  cond_string_copy = std::move (cond);
-	  extra_string_copy = std::move (rest);
-	}
-      else
-	{
-	  /* Check the validity of the condition.  We should error out
-	     if the condition is invalid at all of the locations and
-	     if it is not forced.  In the PARSE_EXTRA case above, this
-	     check is done when parsing the EXTRA_STRING.  */
-	  if (cond_string != nullptr && !force_condition)
+	  for (const auto &sal : lsal.sals)
 	    {
-	      int num_failures = 0;
-	      const linespec_sals &lsal = canonical.lsals[0];
-	      for (const auto &sal : lsal.sals)
+	      const char *cond = cond_string_copy.get ();
+	      try
 		{
-		  const char *cond = cond_string;
-		  try
-		    {
-		      parse_exp_1 (&cond, sal.pc, block_for_pc (sal.pc), 0);
-		      /* One success is sufficient to keep going.  */
-		      break;
-		    }
-		  catch (const gdb_exception_error &)
-		    {
-		      num_failures++;
-		      /* If this is the last sal, error out.  */
-		      if (num_failures == lsal.sals.size ())
-			throw;
-		    }
+		  parse_exp_1 (&cond, sal.pc, block_for_pc (sal.pc), 0);
+		  /* One success is sufficient to keep going.  */
+		  break;
+		}
+	      catch (const gdb_exception_error &)
+		{
+		  num_failures++;
+		  /* If this is the last sal, error out.  */
+		  if (num_failures == lsal.sals.size ())
+		    throw;
 		}
 	    }
-
-	  /* Create a private copy of condition string.  */
-	  if (cond_string)
-	    cond_string_copy.reset (xstrdup (cond_string));
-	  /* Create a private copy of any extra string.  */
-	  if (extra_string)
-	    extra_string_copy.reset (xstrdup (extra_string));
 	}
 
       ops->create_breakpoints_sal (gdbarch, &canonical,
@@ -9148,21 +8996,15 @@ create_breakpoint (struct gdbarch *gdbarch,
 								 type_wanted);
       b->locspec = locspec->clone ();
 
-      if (parse_extra)
-	b->cond_string = NULL;
-      else
-	{
-	  /* Create a private copy of condition string.  */
-	  b->cond_string.reset (cond_string != NULL
-				? xstrdup (cond_string)
-				: NULL);
-	  b->thread = thread;
-	}
+      /* Create a private copy of condition string.  */
+      b->cond_string = std::move (cond_string_copy);
+
+      b->thread = thread;
+      b->task = task;
 
       /* Create a private copy of any extra string.  */
-      b->extra_string.reset (extra_string != NULL
-			     ? xstrdup (extra_string)
-			     : NULL);
+      b->extra_string = std::move (extra_string_copy);
+
       b->ignore_count = ignore_count;
       b->disposition = tempflag ? disp_del : disp_donttouch;
       b->condition_not_parsed = 1;
@@ -9171,9 +9013,12 @@ create_breakpoint (struct gdbarch *gdbarch,
 	   && type_wanted != bp_hardware_breakpoint) || thread != -1)
 	b->pspace = current_program_space;
 
+      if (type_wanted == bp_dprintf)
+	update_dprintf_command_list (b.get ());
+
       install_breakpoint (internal, std::move (b), 0);
     }
-  
+
   if (canonical.lsals.size () > 1)
     {
       warning (_("Multiple breakpoints were set.\nUse the "
@@ -12880,23 +12725,6 @@ code_breakpoint::location_spec_to_sals (location_spec *locspec,
     {
       for (auto &sal : sals)
 	resolve_sal_pc (&sal);
-      if (condition_not_parsed && extra_string != NULL)
-	{
-	  gdb::unique_xmalloc_ptr<char> local_cond, local_extra;
-	  int local_thread, local_task;
-
-	  find_condition_and_thread_for_sals (sals, extra_string.get (),
-					      &local_cond, &local_thread,
-					      &local_task, &local_extra);
-	  gdb_assert (cond_string == nullptr);
-	  if (local_cond != nullptr)
-	    cond_string = std::move (local_cond);
-	  thread = local_thread;
-	  task = local_task;
-	  if (local_extra != nullptr)
-	    extra_string = std::move (local_extra);
-	  condition_not_parsed = 0;
-	}
 
       if (type == bp_static_tracepoint)
 	sals[0] = update_static_tracepoint (this, sals[0]);
diff --git a/gdb/testsuite/gdb.base/condbreak.exp b/gdb/testsuite/gdb.base/condbreak.exp
index a5b2a28701b..50ae82c3f32 100644
--- a/gdb/testsuite/gdb.base/condbreak.exp
+++ b/gdb/testsuite/gdb.base/condbreak.exp
@@ -179,6 +179,10 @@ gdb_test "break -q main if (1==1) thread 999" \
     "Unknown thread 999\\."
 gdb_test "break -q main thread 999 if (1==1)" \
     "Unknown thread 999\\."
+gdb_test "break -q main if (1==1) thread 999 -force-condition" \
+    "Unknown thread 999\\."
+gdb_test "break -q main thread 999 if (1==1) -force-condition" \
+    "Unknown thread 999\\."
 
 # Verify that both if and thread can be distinguished from a breakpoint
 # address expression.
@@ -186,20 +190,34 @@ gdb_test "break *main if (1==1) thread 999" \
     "Unknown thread 999\\."
 gdb_test "break *main thread 999 if (1==1)" \
     "Unknown thread 999\\."
+gdb_test "break *main if (1==1) thread 999 -force-condition" \
+    "Unknown thread 999\\."
+gdb_test "break *main thread 999 if (1==1) -force-condition" \
+    "Unknown thread 999\\."
 
 # Similarly for task.
 gdb_test "break *main if (1==1) task 999" \
     "Unknown task 999\\."
 gdb_test "break *main task 999 if (1==1)" \
     "Unknown task 999\\."
+gdb_test "break *main if (1==1) task 999 -force-condition" \
+    "Unknown task 999\\."
+gdb_test "break *main task 999 if (1==1) -force-condition" \
+    "Unknown task 999\\."
 
-# GDB accepts abbreviations for "thread" and "task".
+# GDB accepts abbreviations for "thread" and "task" and "-force-condition"
 gdb_test "break *main if (1==1) t 999" \
     "Unknown thread 999\\."
 gdb_test "break *main if (1==1) th 999" \
     "Unknown thread 999\\."
 gdb_test "break *main if (1==1) ta 999" \
     "Unknown task 999\\."
+gdb_test "break *main if (1==1) t 999 -force" \
+    "Unknown thread 999\\."
+gdb_test "break *main if (1==1) th 999 -force" \
+    "Unknown thread 999\\."
+gdb_test "break *main if (1==1) ta 999 -force" \
+    "Unknown task 999\\."
 
 set test "run until breakpoint at marker3"
 gdb_test_multiple "continue" $test {
diff --git a/gdb/testsuite/gdb.base/pending.exp b/gdb/testsuite/gdb.base/pending.exp
index d7d3735000a..645f63bdb16 100644
--- a/gdb/testsuite/gdb.base/pending.exp
+++ b/gdb/testsuite/gdb.base/pending.exp
@@ -170,7 +170,8 @@ gdb_test "info break" \
 \[\t \]+stop only if k == 1.*
 \[\t \]+print k.*
 \[0-9\]+\[\t \]+breakpoint     keep y.* in main at .*$srcfile:$mainline.*
-\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc if x > 3.*" \
+\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc.*
+\\s+stop only if x > 3.*" \
 "multiple pending breakpoints"
 
 
@@ -195,8 +196,10 @@ gdb_test "info break" \
 \[\t \]+stop only if k == 1.*
 \[\t \]+print k.*
 \[0-9\]+\[\t \]+breakpoint     keep y.* in main at .*$srcfile:$mainline.*
-\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc if x > 3.*
-\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp3_loc.*ignore next 2 hits.*" \
+\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc.*
+\\s+stop only if x > 3.*
+\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp3_loc.*
+\\s+ignore next 2 hits.*" \
 "multiple pending breakpoints 2"
 
 #
@@ -267,3 +270,17 @@ gdb_test "info break" \
 \[0-9\]+\[\t \]+breakpoint     keep y.* in main at .*$srcfile:$mainline.*
 \[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*imaginary.*" \
 "verify pending breakpoint after restart"
+
+# Test GDB's parsing of pending breakpoint thread and condition.
+
+gdb_test_no_output "set breakpoint pending on"
+gdb_test "break foo if (unknown_var && another_unknown_var) thread 1" \
+    "Breakpoint $decimal \\(foo\\) pending\\."
+set bpnum [get_integer_valueof "\$bpnum" "*INVALID" \
+	       "get number for foo breakpoint"]
+gdb_test "info breakpoints $bpnum" \
+    [multi_line \
+	 "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	 "\\s+stop only if \\(unknown_var && another_unknown_var\\)" \
+	 "\\s+stop only in thread 1"] \
+    "check pending breakpoint on foo"
diff --git a/gdb/testsuite/gdb.linespec/explicit.exp b/gdb/testsuite/gdb.linespec/explicit.exp
index b08d65953d2..7c8b2475881 100644
--- a/gdb/testsuite/gdb.linespec/explicit.exp
+++ b/gdb/testsuite/gdb.linespec/explicit.exp
@@ -574,7 +574,7 @@ namespace eval $testfile {
 	      allow-pending]} {
 	fail "set $tst"
     } else {
-	gdb_test "info break" ".*PENDING.*myfunction if foofoofoo == 1.*" $tst
+	gdb_test "info break" ".*PENDING.*myfunction\r\n\\s+stop only if foofoofoo == 1.*" $tst
     }
 
     gdb_exit
@@ -585,7 +585,7 @@ namespace eval $testfile {
 	      allow-pending]} {
 	fail "set $tst"
     } else {
-	gdb_test "info break" ".*PENDING.*myfunction if arg == 0" $tst
+	gdb_test "info break" ".*PENDING.*myfunction\r\n\\s+stop only if arg == 0" $tst
 
 	gdb_load [standard_output_file $exefile]
 	gdb_test "info break" \
diff --git a/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp b/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp
index 28f52938aeb..bb9987a5572 100644
--- a/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp
+++ b/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp
@@ -50,7 +50,8 @@ set bp_location1 [gdb_get_line_number "set breakpoint 1 here"]
 # Set pending dprintf via MI.
 set bp [mi_make_breakpoint_pending -number "1" -type "dprintf" \
 	    -disp "keep" -enabled "y" -pending "pendfunc1" \
-	    -original-location "pendfunc1"]
+	    -original-location "pendfunc1" \
+	    -script {\["printf \\\"hello\\\""\]}]
 mi_gdb_test "-dprintf-insert -f pendfunc1 \"hello\"" \
     ".*\\^done,$bp" "mi set dprintf"
 
diff --git a/gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c b/gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
new file mode 100644
index 00000000000..15d1b9833dd
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
@@ -0,0 +1,22 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+int global_var = 0;
+
+void
+foo (int arg)
+{
+  global_var = arg;
+}
diff --git a/gdb/testsuite/gdb.threads/del-pending-thread-bp.c b/gdb/testsuite/gdb.threads/del-pending-thread-bp.c
new file mode 100644
index 00000000000..938e05bc4d7
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/del-pending-thread-bp.c
@@ -0,0 +1,85 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#include <dlfcn.h>
+#include <pthread.h>
+#include <stdlib.h>
+
+pthread_barrier_t barrier;
+
+static void
+barrier_wait (pthread_barrier_t *b)
+{
+  int res = pthread_barrier_wait (b);
+  if (res != 0 && res != PTHREAD_BARRIER_SERIAL_THREAD)
+    abort ();
+}
+
+static void *
+thread_worker (void *arg)
+{
+  barrier_wait (&barrier);
+  return NULL;
+}
+
+void
+breakpt ()
+{
+  /* Nothing.  */
+}
+
+int
+main (void)
+{
+  void *handle;
+  void (*func)(int);
+  pthread_t thread;
+
+  if (pthread_barrier_init (&barrier, NULL, 2) != 0)
+    abort ();
+
+  if (pthread_create (&thread, NULL, thread_worker, NULL) != 0)
+    abort ();
+
+  breakpt ();
+
+  /* Allow the worker thread to complete.  */
+  barrier_wait (&barrier);
+
+  if (pthread_join (thread, NULL) != 0)
+    abort ();
+
+  breakpt ();
+
+  /* Now load the shared library.  */
+  handle = dlopen (SHLIB_NAME, RTLD_LAZY);
+  if (handle == NULL)
+    abort ();
+
+  /* Find the function symbol.  */
+  func = (void (*)(int)) dlsym (handle, "foo");
+
+  /* Call the library function.  */
+  func (1);
+
+  /* Unload the shared library.  */
+  if (dlclose (handle) != 0)
+    abort ();
+
+  breakpt ();
+
+  return 0;
+}
+
diff --git a/gdb/testsuite/gdb.threads/del-pending-thread-bp.exp b/gdb/testsuite/gdb.threads/del-pending-thread-bp.exp
new file mode 100644
index 00000000000..4ed05eaa42d
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/del-pending-thread-bp.exp
@@ -0,0 +1,108 @@
+# Copyright 2023 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+# This test checks that pending thread-specific breakpoints are
+# correctly deleted when the thread the breakpoint is for goes out of
+# scope.
+#
+# We also check that we can't create a pending thread-specific
+# breakpoint for a non-existent thread.
+
+require allow_shlib_tests
+
+standard_testfile
+
+set libname $testfile-lib
+set srcfile_lib $srcdir/$subdir/$libname.c
+set binfile_lib [standard_output_file $libname.so]
+
+if { [gdb_compile_shlib $srcfile_lib $binfile_lib {}] != "" } {
+    untested "failed to compile shared library 1"
+    return -1
+}
+
+set binfile_lib_target [gdb_download_shlib $binfile_lib]
+
+if { [prepare_for_testing "failed to prepare" $testfile $srcfile \
+	  [list debug \
+	       additional_flags=-DSHLIB_NAME=\"$binfile_lib_target\" \
+	       shlib_load pthreads]] } {
+    return -1
+}
+
+gdb_locate_shlib $binfile_lib
+
+if ![runto_main] {
+    return 0
+}
+
+# Run until we have two threads.
+gdb_breakpoint "breakpt"
+gdb_continue_to_breakpoint "first breakpt call"
+
+# Confirm that we have a thread '2'.
+gdb_test "info threads" "\r\n\\s+2\\s+\[^\r\n\]+"
+
+# Create a pending, thread-specific, breakpoint on 'foo'.
+gdb_breakpoint "foo thread 2" allow-pending
+set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+	       "get breakpoint number"]
+
+# Check we can't create a pending thread-specific breakpoint for a
+# non-existent thread.
+gdb_test "with breakpoint pending on -- break foo thread 99" \
+    "Unknown thread 99\\."
+
+# Continue to 'breakpt' again.  Don't use gdb_continue_to_breakpoint
+# as we are looking for the thread exited and breakpoint deleted
+# messages.
+set output [list "Continuing\\."]
+
+if {!([target_info exists gdb_protocol]
+      && ([target_info gdb_protocol] == "remote"
+	  || [target_info gdb_protocol] == "extended-remote"))} {
+    # Due to bug PR gdb/30129 we don't see the thread exited messages
+    # for remote targets.  When this bit of this test can be cleaned
+    # up.
+    lappend output "\\\[Thread \[^\r\n\]+ exited\\\]"
+}
+
+lappend output "Thread-specific breakpoint $bpnum deleted - thread 2 no longer in the thread list\\." \
+    "" \
+    "Thread 1 \[^\r\n\]+, breakpt \\(\\) at \[^\r\n\]+" \
+    "$decimal\\s+\[^\r\n\]+"
+
+gdb_test "continue" \
+    [multi_line {*}$output] \
+    "second breakpt call"
+
+# Confirm breakpoint has been deleted.
+gdb_test "info breakpoints $bpnum" \
+    "No breakpoint or watchpoint matching '$bpnum'\\."
+
+# Continue again.  This will pass through 'foo'.  We should not stop
+# in 'foo', the breakpoint has been deleted.  We should next stop in
+# breakpt again.
+gdb_test "continue" \
+    [multi_line \
+	 "Continuing\\." \
+	 "" \
+	 "Thread 1 \[^\r\n\]+ hit Breakpoint $decimal, breakpt \\(\\) at \[^\r\n\]+" \
+	 "$decimal\\s+\[^\r\n\]+"] \
+    "third breakpt call"
+gdb_test "bt 1" \
+    [multi_line \
+	 "#0\\s+breakpt \\(\\) at \[^\r\n\]+" \
+	 "\\(More stack frames follow\\.\\.\\.\\)"]
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv3 7/9] gdb: remove breakpoint_re_set_one
  2023-05-30 20:46   ` [PATCHv3 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
                       ` (5 preceding siblings ...)
  2023-05-30 20:46     ` [PATCHv3 6/9] gdb: parse pending breakpoint thread/task immediately Andrew Burgess
@ 2023-05-30 20:46     ` Andrew Burgess
  2023-05-30 20:46     ` [PATCHv3 8/9] gdb: remove tracepoint_probe_create_sals_from_location_spec Andrew Burgess
                       ` (2 subsequent siblings)
  9 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-05-30 20:46 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

During a later patch I wanted to reset a single breakpoint, so I
called breakpoint_re_set_one.  However, this is not the right thing to
do.  If we look at breakpoint_re_set then we see that there's a whole
bunch of state that needs to be preserved prior to calling
breakpoint_re_set_one, and after calling breakpoint_re_set_one we
still need to call update_global_location_list.

I could just update the comment on breakpoint_re_set_one to make it
clearer how the function should be used -- or more likely to warn that
the function should only be used as a helper from breakpoint_re_set.

However, breakpoint_re_set_one is only 3 lines long.  So I figure it
might actually be easier to just fold breakpoint_re_set_one into
breakpoint_re_set, then there's no risk of accidentally calling
breakpoint_re_set_one when we shouldn't.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c | 26 ++++++++------------------
 1 file changed, 8 insertions(+), 18 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index ed3d61605bf..79a55d66f08 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -12776,17 +12776,6 @@ create_sals_from_location_spec_default (location_spec *locspec,
   parse_breakpoint_sals (locspec, canonical);
 }
 
-/* Reset a breakpoint.  */
-
-static void
-breakpoint_re_set_one (breakpoint *b)
-{
-  input_radix = b->input_radix;
-  set_language (b->language);
-
-  b->re_set ();
-}
-
 /* Re-set breakpoint locations for the current program space.
    Locations bound to other program spaces are left untouched.  */
 
@@ -12798,12 +12787,11 @@ breakpoint_re_set (void)
     scoped_restore save_input_radix = make_scoped_restore (&input_radix);
     scoped_restore_current_pspace_and_thread restore_pspace_thread;
 
-    /* breakpoint_re_set_one sets the current_language to the language
-       of the breakpoint it is resetting (see prepare_re_set_context)
-       before re-evaluating the breakpoint's location.  This change can
-       unfortunately get undone by accident if the language_mode is set
-       to auto, and we either switch frames, or more likely in this context,
-       we select the current frame.
+    /* To ::re_set each breakpoint we set the current_language to the
+       language of the breakpoint before re-evaluating the breakpoint's
+       location.  This change can unfortunately get undone by accident if
+       the language_mode is set to auto, and we either switch frames, or
+       more likely in this context, we select the current frame.
 
        We prevent this by temporarily turning the language_mode to
        language_mode_manual.  We restore it once all breakpoints
@@ -12820,7 +12808,9 @@ breakpoint_re_set (void)
       {
 	try
 	  {
-	    breakpoint_re_set_one (&b);
+	    input_radix = b.input_radix;
+	    set_language (b.language);
+	    b.re_set ();
 	  }
 	catch (const gdb_exception &ex)
 	  {
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv3 8/9] gdb: remove tracepoint_probe_create_sals_from_location_spec
  2023-05-30 20:46   ` [PATCHv3 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
                       ` (6 preceding siblings ...)
  2023-05-30 20:46     ` [PATCHv3 7/9] gdb: remove breakpoint_re_set_one Andrew Burgess
@ 2023-05-30 20:46     ` Andrew Burgess
  2023-05-30 20:46     ` [PATCHv3 9/9] gdb: only insert thread-specific breakpoints in the relevant inferior Andrew Burgess
  2023-08-23 15:59     ` [PATCHv4 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
  9 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-05-30 20:46 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

The tracepoint_probe_create_sals_from_location_spec function just
forwards all its arguments to
bkpt_probe_create_sals_from_location_spec, and is only used in one
place.

Lets delete tracepoint_probe_create_sals_from_location_spec and
replace it with bkpt_probe_create_sals_from_location_spec.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c | 19 +++----------------
 1 file changed, 3 insertions(+), 16 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 79a55d66f08..4343016b6b2 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -221,9 +221,6 @@ static bool strace_marker_p (struct breakpoint *b);
 static void bkpt_probe_create_sals_from_location_spec
      (location_spec *locspec,
       struct linespec_result *canonical);
-static void tracepoint_probe_create_sals_from_location_spec
-     (location_spec *locspec,
-      struct linespec_result *canonical);
 
 const struct breakpoint_ops code_breakpoint_ops =
 {
@@ -238,10 +235,11 @@ static const struct breakpoint_ops bkpt_probe_breakpoint_ops =
   create_breakpoints_sal,
 };
 
-/* Tracepoints set on probes.  */
+/* Tracepoints set on probes.  We use the same methods as for breakpoints
+   on probes.  */
 static const struct breakpoint_ops tracepoint_probe_breakpoint_ops =
 {
-  tracepoint_probe_create_sals_from_location_spec,
+  bkpt_probe_create_sals_from_location_spec,
   create_breakpoints_sal,
 };
 
@@ -11994,17 +11992,6 @@ tracepoint::print_recreate (struct ui_file *fp) const
     gdb_printf (fp, "  passcount %d\n", pass_count);
 }
 
-/* Virtual table for tracepoints on static probes.  */
-
-static void
-tracepoint_probe_create_sals_from_location_spec
-  (location_spec *locspec,
-   struct linespec_result *canonical)
-{
-  /* We use the same method for breakpoint on probes.  */
-  bkpt_probe_create_sals_from_location_spec (locspec, canonical);
-}
-
 void
 dprintf_breakpoint::re_set ()
 {
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv3 9/9] gdb: only insert thread-specific breakpoints in the relevant inferior
  2023-05-30 20:46   ` [PATCHv3 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
                       ` (7 preceding siblings ...)
  2023-05-30 20:46     ` [PATCHv3 8/9] gdb: remove tracepoint_probe_create_sals_from_location_spec Andrew Burgess
@ 2023-05-30 20:46     ` Andrew Burgess
  2023-08-23 15:59     ` [PATCHv4 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
  9 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-05-30 20:46 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Eli Zaretskii

This commit updates GDB so that thread-specific breakpoints are only
inserted into the inferior that contains the thread we are interested
in.

Actually, as breakpoints are placed in program spaces, we insert the
breakpoint in any inferior that shares a program space with the
inferior containing the thread we are interested in.  But as far as
most users are concerned this really means the one inferior.

In terms of implementation, getting this basically working is easy
enough, now that a breakpoint's thread field is setup prior to GDB
looking for locations, we can easily use the thread to find a suitable
program_space and pass this to as a filter when creating the sals.

Or we could if breakpoint_ops::create_sals_from_location_spec allowed
us to pass in a filter program_space.

So, this commit extends breakpoint_ops::create_sals_from_location_spec
to take a program_space argument, and uses this to filter the set of
returned sals.  This accounts for about half the change in this patch.

The second set of changes starts from breakpoint_set_thread, this is
called when the thread for a thread-specific breakpoint changes,
e.g. from the Python API.

Previously this call would never result in the locations of a
breakpoint changing, after all, locations were inserted in every
program space, and we just use the thread field to decide when we
should stop.  Now though, changing a breakpoint's thread can mean we
need to figure out a new set of breakpoint locations.

To support this I've added a new breakpoint_re_set_one function, which
is like breakpoint_re_set, but takes a single breakpoint, and just
updates the locations for that one breakpoint.  We only need to call
this function if the program_space in which a breakpoint's thread is
running actually changes.  If the program_space does change then we
call the new breakpoint_re_set_one function passing in the
program_space which should be used to filter the locations (or nullptr
to indicate we should set locations in all program spaces).  This
filter program_space needs to propagate down to all the re_set
methods, this accounts for the remaining half of the changes in this
patch.

There were a couple of existing tests that created thread-specific
breakpoints and then checked the 'info breakpoints' output, these
needed updating.  These were:

  gdb.mi/user-selected-context-sync.exp
  gdb.multi/bp-thread-specific.exp
  gdb.multi/multi-target-continue.exp
  gdb.multi/multi-target-ping-pong-next.exp
  gdb.multi/tids.exp

I've also added some additional tests to:

  gdb.multi/pending-bp.exp

I've updated the documentation and added a NEWS entry.

Reviewed-By: Eli Zaretskii <eliz@gnu.org>
---
 gdb/NEWS                                      |   7 +
 gdb/ada-lang.c                                |   6 +-
 gdb/break-catch-throw.c                       |   6 +-
 gdb/breakpoint.c                              | 236 ++++++++++++++----
 gdb/breakpoint.h                              |  26 +-
 .../gdb.mi/user-selected-context-sync.exp     |   2 +-
 .../gdb.multi/bp-thread-specific.exp          |   7 +-
 .../gdb.multi/multi-target-continue.exp       |   2 +-
 .../gdb.multi/multi-target-ping-pong-next.exp |   4 +-
 gdb/testsuite/gdb.multi/pending-bp.exp        | 206 +++++++++++++++
 gdb/testsuite/gdb.multi/tids.exp              |   6 +-
 11 files changed, 427 insertions(+), 81 deletions(-)

diff --git a/gdb/NEWS b/gdb/NEWS
index d50b01ffa4f..eb7a984af16 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -71,6 +71,13 @@
   'thread' or 'task' keywords are parsed at the time the breakpoint is
   created, rather than at the time the breakpoint becomes non-pending.
 
+* Thread-specific breakpoints are only inserted into the program space
+  in which the thread of interest is running.  In most cases program
+  spaces are unique for each inferior, so this means that
+  thread-specific breakpoints will usually only be inserted for the
+  inferior containing the thread of interest.  The breakpoint will
+  be hit no less than before.
+
 * New commands
 
 maintenance print record-instruction [ N ]
diff --git a/gdb/ada-lang.c b/gdb/ada-lang.c
index 237ec09050c..8a56b78ee61 100644
--- a/gdb/ada-lang.c
+++ b/gdb/ada-lang.c
@@ -12176,7 +12176,7 @@ struct ada_catchpoint : public code_breakpoint
   }
 
   struct bp_location *allocate_location () override;
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   void check_status (struct bpstat *bs) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   bool print_one (const bp_location **) const override;
@@ -12268,11 +12268,11 @@ ada_catchpoint::allocate_location ()
    catchpoint kinds.  */
 
 void
-ada_catchpoint::re_set ()
+ada_catchpoint::re_set (program_space *pspace)
 {
   /* Call the base class's method.  This updates the catchpoint's
      locations.  */
-  this->code_breakpoint::re_set ();
+  this->code_breakpoint::re_set (pspace);
 
   /* Reparse the exception conditional expressions.  One for each
      location.  */
diff --git a/gdb/break-catch-throw.c b/gdb/break-catch-throw.c
index 47d534c5ee8..e661d1624e8 100644
--- a/gdb/break-catch-throw.c
+++ b/gdb/break-catch-throw.c
@@ -82,10 +82,10 @@ struct exception_catchpoint : public code_breakpoint
 				     _("invalid type-matching regexp")))
   {
     pspace = current_program_space;
-    re_set ();
+    re_set (pspace);
   }
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   bool print_one (const bp_location **) const override;
   void print_mention () const override;
@@ -198,7 +198,7 @@ exception_catchpoint::check_status (struct bpstat *bs)
 /* Implement the 're_set' method.  */
 
 void
-exception_catchpoint::re_set ()
+exception_catchpoint::re_set (program_space *pspace)
 {
   std::vector<symtab_and_line> sals;
   struct program_space *filter_pspace = current_program_space;
diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 4343016b6b2..9a7d487981c 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -90,9 +90,12 @@
 static void map_breakpoint_numbers (const char *,
 				    gdb::function_view<void (breakpoint *)>);
 
-static void
-  create_sals_from_location_spec_default (location_spec *locspec,
-					  linespec_result *canonical);
+static void parse_breakpoint_sals (location_spec *locspec,
+				   linespec_result *canonical,
+				   program_space *search_pspace);
+
+static void breakpoint_re_set_one (breakpoint *b,
+				   program_space *filter_pspace);
 
 static void create_breakpoints_sal (struct gdbarch *,
 				    struct linespec_result *,
@@ -220,11 +223,12 @@ static bool strace_marker_p (struct breakpoint *b);
 
 static void bkpt_probe_create_sals_from_location_spec
      (location_spec *locspec,
-      struct linespec_result *canonical);
+      struct linespec_result *canonical,
+      struct program_space *search_pspace);
 
 const struct breakpoint_ops code_breakpoint_ops =
 {
-  create_sals_from_location_spec_default,
+  parse_breakpoint_sals,
   create_breakpoints_sal,
 };
 
@@ -289,7 +293,7 @@ struct internal_breakpoint : public code_breakpoint
     disposition = disp_donttouch;
   }
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   void check_status (struct bpstat *bs) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   void print_mention () const override;
@@ -323,7 +327,7 @@ struct momentary_breakpoint : public code_breakpoint
     thread = thread_;
   }
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   void check_status (struct bpstat *bs) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   void print_mention () const override;
@@ -334,7 +338,7 @@ struct dprintf_breakpoint : public ordinary_breakpoint
 {
   using ordinary_breakpoint::ordinary_breakpoint;
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   int breakpoint_hit (const struct bp_location *bl,
 		      const address_space *aspace,
 		      CORE_ADDR bp_addr,
@@ -1461,7 +1465,36 @@ breakpoint_set_thread (struct breakpoint *b, int thread)
 
   b->thread = thread;
   if (old_thread != thread)
-    gdb::observers::breakpoint_modified.notify (b);
+    {
+      /* If THREAD is in a different program_space than OLD_THREAD, or the
+	 breakpoint has switched to or from being thread-specific, then we
+	 need to re-set the locations of this breakpoint.  First, figure
+	 out the program_space for the old and new threads, use a value of
+	 nullptr to indicate the breakpoint is in all program spaces.  */
+      program_space *old_pspace = nullptr;
+      if (old_thread != -1)
+	{
+	  struct thread_info *thr = find_thread_global_id (old_thread);
+	  gdb_assert (thr != nullptr);
+	  old_pspace = thr->inf->pspace;
+	}
+
+      program_space *new_pspace = nullptr;
+      if (thread != -1)
+	{
+	  struct thread_info *thr = find_thread_global_id (thread);
+	  gdb_assert (thr != nullptr);
+	  new_pspace = thr->inf->pspace;
+	}
+
+      /* If the program space has changed for this breakpoint, then
+	 re-evaluate it's locations.  */
+      if (old_pspace != new_pspace)
+	breakpoint_re_set_one (b, new_pspace);
+
+      /* Let others know the breakpoint has changed.  */
+      gdb::observers::breakpoint_modified.notify (b);
+    }
 }
 
 /* See breakpoint.h.  */
@@ -8626,7 +8659,8 @@ create_breakpoints_sal (struct gdbarch *gdbarch,
 
 static void
 parse_breakpoint_sals (location_spec *locspec,
-		       struct linespec_result *canonical)
+		       struct linespec_result *canonical,
+		       struct program_space *search_pspace)
 {
   struct symtab_and_line cursal;
 
@@ -8690,7 +8724,7 @@ parse_breakpoint_sals (location_spec *locspec,
 	      && strchr ("+-", spec[0]) != NULL
 	      && spec[1] != '['))
 	{
-	  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, NULL,
+	  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, search_pspace,
 			    get_last_displayed_symtab (),
 			    get_last_displayed_line (),
 			    canonical, NULL, NULL);
@@ -8698,7 +8732,7 @@ parse_breakpoint_sals (location_spec *locspec,
 	}
     }
 
-  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, NULL,
+  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, search_pspace,
 		    cursal.symtab, cursal.line, canonical, NULL, NULL);
 }
 
@@ -8797,6 +8831,24 @@ breakpoint_ops_for_location_spec_type (enum location_spec_type locspec_type,
     }
 }
 
+/* Return the program space to use as a filter when searching for locations
+   of a breakpoint specific to THREAD.  If THREAD is -1, meaning all
+   threads, then this function returns nullptr, indicating no program space
+   filtering should be performed.  Otherwise, this function returns the
+   program space for the inferior that contains THREAD.  */
+
+static struct program_space *
+find_program_space_for_global_thread_id (int thread)
+{
+  if (thread == -1)
+    return nullptr;
+
+  struct thread_info *thr = find_thread_global_id (thread);
+  gdb_assert (thr != nullptr);
+  gdb_assert (thr->inf != nullptr);
+  return thr->inf->pspace;
+}
+
 /* See breakpoint.h.  */
 
 const struct breakpoint_ops *
@@ -8890,7 +8942,10 @@ create_breakpoint (struct gdbarch *gdbarch,
 
   try
     {
-      ops->create_sals_from_location_spec (locspec, &canonical);
+      struct program_space *search_pspace
+	= find_program_space_for_global_thread_id (thread);
+      ops->create_sals_from_location_spec (locspec, &canonical,
+					   search_pspace);
     }
   catch (const gdb_exception_error &e)
     {
@@ -9361,7 +9416,7 @@ break_range_command (const char *arg, int from_tty)
   arg_start = arg;
   location_spec_up start_locspec
     = string_to_location_spec (&arg, current_language);
-  parse_breakpoint_sals (start_locspec.get (), &canonical_start);
+  parse_breakpoint_sals (start_locspec.get (), &canonical_start, nullptr);
 
   if (arg[0] != ',')
     error (_("Too few arguments."));
@@ -9448,7 +9503,7 @@ watchpoint_exp_is_const (const struct expression *exp)
 /* Implement the "re_set" method for watchpoints.  */
 
 void
-watchpoint::re_set ()
+watchpoint::re_set (struct program_space *pspace)
 {
   /* Watchpoint can be either on expression using entirely global
      variables, or it can be on local variables.
@@ -11548,7 +11603,7 @@ breakpoint::print_recreate (struct ui_file *fp) const
 /* Default breakpoint_ops methods.  */
 
 void
-code_breakpoint::re_set ()
+code_breakpoint::re_set (struct program_space *pspace)
 {
   /* FIXME: is this still reachable?  */
   if (breakpoint_location_spec_empty_p (this))
@@ -11558,7 +11613,7 @@ code_breakpoint::re_set ()
       return;
     }
 
-  re_set_default ();
+  re_set_default (pspace);
 }
 
 int
@@ -11764,7 +11819,7 @@ code_breakpoint::decode_location_spec (location_spec *locspec,
 /* Virtual table for internal breakpoints.  */
 
 void
-internal_breakpoint::re_set ()
+internal_breakpoint::re_set (struct program_space *pspace)
 {
   switch (type)
     {
@@ -11857,7 +11912,7 @@ internal_breakpoint::print_mention () const
 /* Virtual table for momentary breakpoints  */
 
 void
-momentary_breakpoint::re_set ()
+momentary_breakpoint::re_set (struct program_space *pspace)
 {
   /* Keep temporary breakpoints, which can be encountered when we step
      over a dlopen call and solib_add is resetting the breakpoints.
@@ -11898,12 +11953,13 @@ longjmp_breakpoint::~longjmp_breakpoint ()
 
 static void
 bkpt_probe_create_sals_from_location_spec (location_spec *locspec,
-					   struct linespec_result *canonical)
+					   struct linespec_result *canonical,
+					   struct program_space *search_pspace)
 
 {
   struct linespec_sals lsal;
 
-  lsal.sals = parse_probes (locspec, NULL, canonical);
+  lsal.sals = parse_probes (locspec, search_pspace, canonical);
   lsal.canonical = xstrdup (canonical->locspec->to_string ());
   canonical->lsals.push_back (std::move (lsal));
 }
@@ -11993,9 +12049,9 @@ tracepoint::print_recreate (struct ui_file *fp) const
 }
 
 void
-dprintf_breakpoint::re_set ()
+dprintf_breakpoint::re_set (struct program_space *pspace)
 {
-  re_set_default ();
+  re_set_default (pspace);
 
   /* extra_string should never be non-NULL for dprintf.  */
   gdb_assert (extra_string != NULL);
@@ -12053,8 +12109,10 @@ dprintf_breakpoint::after_condition_true (struct bpstat *bs)
    markers (`-m').  */
 
 static void
-strace_marker_create_sals_from_location_spec (location_spec *locspec,
-					      struct linespec_result *canonical)
+strace_marker_create_sals_from_location_spec
+	(location_spec *locspec,
+	 struct linespec_result *canonical,
+	 struct program_space *search_pspace)
 {
   struct linespec_sals lsal;
   const char *arg_start, *arg;
@@ -12561,12 +12619,32 @@ update_breakpoint_locations (code_breakpoint *b,
      all locations are in the same shared library, that was unloaded.
      We'd like to retain the location, so that when the library is
      loaded again, we don't loose the enabled/disabled status of the
-     individual locations.  */
+     individual locations.
+
+     Thread specific breakpoints will also trigger this case if the thread
+     is changed to a different program space, and all of the old locations
+     go out of scope.  In this case we do (currently) discard the old
+     locations -- we assume the change in thread is permanent and the old
+     locations will never come back into scope.  */
   if (all_locations_are_pending (b, filter_pspace) && sals.empty ())
-    return;
+    {
+      if (b->thread != -1)
+	b->clear_locations ();
+      return;
+    }
 
   bp_location_list existing_locations = b->steal_locations (filter_pspace);
 
+  /* If this is a thread-specific breakpoint then any locations left on the
+     breakpoint are for a program space in which the thread of interest
+     does not operate.  This can happen when the user changes the thread of
+     a thread-specific breakpoint.
+
+     We assume that the change in thread is permanent, and that the old
+     locations will never be used again, so discard them now.  */
+  if (b->thread != -1)
+    b->clear_locations ();
+
   for (const auto &sal : sals)
     {
       struct bp_location *new_loc;
@@ -12729,40 +12807,45 @@ code_breakpoint::location_spec_to_sals (location_spec *locspec,
    locations.  */
 
 void
-code_breakpoint::re_set_default ()
+code_breakpoint::re_set_default (struct program_space *filter_pspace)
 {
-  struct program_space *filter_pspace = current_program_space;
   std::vector<symtab_and_line> expanded, expanded_end;
 
-  int found;
-  std::vector<symtab_and_line> sals = location_spec_to_sals (locspec.get (),
-							     filter_pspace,
-							     &found);
-  if (found)
-    expanded = std::move (sals);
-
-  if (locspec_range_end != nullptr)
-    {
-      std::vector<symtab_and_line> sals_end
-	= location_spec_to_sals (locspec_range_end.get (),
-				 filter_pspace, &found);
+  /* If this breakpoint is thread-specific then find the program space in
+     which the specific thread exists.  Otherwise, for breakpoints that are
+     not thread-specific THREAD_PSPACE will be nullptr.  */
+  program_space *thread_pspace
+    = find_program_space_for_global_thread_id (this->thread);
+
+  /* If this is not a thread-specific breakpoint, or it is a
+     thread-specific breakpoint but we are looking for new locations in the
+     program space that the specific thread is running, then look for new
+     locations for this breakpoint.  */
+  if (thread_pspace == nullptr || filter_pspace == thread_pspace)
+    {
+      int found;
+      std::vector<symtab_and_line> sals
+	= location_spec_to_sals (locspec.get (), filter_pspace, &found);
       if (found)
-	expanded_end = std::move (sals_end);
+	expanded = std::move (sals);
+
+      if (locspec_range_end != nullptr)
+	{
+	  std::vector<symtab_and_line> sals_end
+	    = location_spec_to_sals (locspec_range_end.get (),
+				     filter_pspace, &found);
+	  if (found)
+	    expanded_end = std::move (sals_end);
+	}
     }
 
+  /* Update the locations for this breakpoint.  For thread-specific
+     breakpoints this will remove any old locations that are for the wrong
+     program space -- this can happen if the user changes the thread of a
+     thread-specific breakpoint.  */
   update_breakpoint_locations (this, filter_pspace, expanded, expanded_end);
 }
 
-/* Default method for creating SALs from an address string.  It basically
-   calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
-
-static void
-create_sals_from_location_spec_default (location_spec *locspec,
-					struct linespec_result *canonical)
-{
-  parse_breakpoint_sals (locspec, canonical);
-}
-
 /* Re-set breakpoint locations for the current program space.
    Locations bound to other program spaces are left untouched.  */
 
@@ -12797,7 +12880,7 @@ breakpoint_re_set (void)
 	  {
 	    input_radix = b.input_radix;
 	    set_language (b.language);
-	    b.re_set ();
+	    b.re_set (current_program_space);
 	  }
 	catch (const gdb_exception &ex)
 	  {
@@ -12818,6 +12901,53 @@ breakpoint_re_set (void)
   /* Now we can insert.  */
   update_global_location_list (UGLL_MAY_INSERT);
 }
+
+/* Re-set locations for breakpoint B in FILTER_PSPACE.  If FILTER_PSPACE is
+   nullptr then re-set locations for B in all program spaces.  Locations
+   bound to program spaces other than FILTER_PSPACE are left untouched.  */
+
+static void
+breakpoint_re_set_one (breakpoint *b, program_space *filter_pspace)
+{
+  {
+    scoped_restore_current_language save_language;
+    scoped_restore save_input_radix = make_scoped_restore (&input_radix);
+    scoped_restore_current_pspace_and_thread restore_pspace_thread;
+
+    /* To ::re_set each breakpoint we set the current_language to the
+       language of the breakpoint before re-evaluating the breakpoint's
+       location.  This change can unfortunately get undone by accident if
+       the language_mode is set to auto, and we either switch frames, or
+       more likely in this context, we select the current frame.
+
+       We prevent this by temporarily turning the language_mode to
+       language_mode_manual.  We restore it once all breakpoints
+       have been reset.  */
+    scoped_restore save_language_mode = make_scoped_restore (&language_mode);
+    language_mode = language_mode_manual;
+
+    /* Note: we must not try to insert locations until after all
+       breakpoints have been re-set.  Otherwise, e.g., when re-setting
+       breakpoint 1, we'd insert the locations of breakpoint 2, which
+       hadn't been re-set yet, and thus may have stale locations.  */
+
+    try
+      {
+	input_radix = b->input_radix;
+	set_language (b->language);
+	b->re_set (filter_pspace);
+      }
+    catch (const gdb_exception &ex)
+      {
+	exception_fprintf (gdb_stderr, ex,
+			   "Error in re-setting breakpoint %d: ",
+			   b->number);
+      }
+  }
+
+  /* Now we can insert.  */
+  update_global_location_list (UGLL_MAY_INSERT);
+}
 \f
 /* Reset the thread number of this breakpoint:
 
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index 8abb46b54ad..e5293448536 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -558,15 +558,15 @@ enum print_stop_action
 
 struct breakpoint_ops
 {
-  /* Create SALs from location spec, storing the result in
-     linespec_result.
-
-     For an explanation about the arguments, see the function
-     `create_sals_from_location_spec_default'.
+  /* Create SALs from LOCSPEC, storing the result in linespec_result
+     CANONICAL.  If SEARCH_PSPACE is not nullptr then only results in the
+     corresponding program space are returned.  If SEARCH_PSPACE is nullptr
+     then results for all program spaces are returned.
 
      This function is called inside `create_breakpoint'.  */
   void (*create_sals_from_location_spec) (location_spec *locspec,
-					  struct linespec_result *canonical);
+					  linespec_result *canonical,
+					  program_space *search_pspace);
 
   /* This method will be responsible for creating a breakpoint given its SALs.
      Usually, it just calls `create_breakpoints_sal' (for ordinary
@@ -698,8 +698,12 @@ struct breakpoint : public intrusive_list_node<breakpoint>
 
   /* Reevaluate a breakpoint.  This is necessary after symbols change
      (e.g., an executable or DSO was loaded, or the inferior just
-     started).  */
-  virtual void re_set ()
+     started).
+
+     FILTER_PSPACE is the program space in which symbols may have changed,
+     or can be nullptr to indicate that all program spaces may have
+     changed.  */
+  virtual void re_set (program_space *filter_pspace)
   {
     /* Nothing to re-set.  */
   }
@@ -927,7 +931,7 @@ struct code_breakpoint : public breakpoint
   /* Add a location for SAL to this breakpoint.  */
   bp_location *add_location (const symtab_and_line &sal);
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   int insert_location (struct bp_location *) override;
   int remove_location (struct bp_location *,
 		       enum remove_bp_reason reason) override;
@@ -949,7 +953,7 @@ struct code_breakpoint : public breakpoint
      struct program_space *search_pspace);
 
   /* Helper method that does the basic work of re_set.  */
-  void re_set_default ();
+  void re_set_default (program_space *pspace);
 
   /* Find the SaL locations corresponding to the given LOCATION.
      On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
@@ -971,7 +975,7 @@ struct watchpoint : public breakpoint
 {
   using breakpoint::breakpoint;
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   int insert_location (struct bp_location *) override;
   int remove_location (struct bp_location *,
 		       enum remove_bp_reason reason) override;
diff --git a/gdb/testsuite/gdb.mi/user-selected-context-sync.exp b/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
index 4889c31aff3..8cc47537e68 100644
--- a/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
+++ b/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
@@ -370,7 +370,7 @@ proc test_continue_to_start { mode inf } {
 			    "thread $inf.2 stops MI"
 		    } else {
 			mi_expect_stop "breakpoint-hit" "child_sub_function" \
-			    "" "$srcfile" "$decimal" {"" "disp=\"del\"" "locno=\"[0-9]+\""} \
+			    "" "$srcfile" "$decimal" {"" "disp=\"del\""} \
 			    "thread $inf.2 stops MI"
 		    }
 		}
diff --git a/gdb/testsuite/gdb.multi/bp-thread-specific.exp b/gdb/testsuite/gdb.multi/bp-thread-specific.exp
index 85c08f44a2c..68001e92044 100644
--- a/gdb/testsuite/gdb.multi/bp-thread-specific.exp
+++ b/gdb/testsuite/gdb.multi/bp-thread-specific.exp
@@ -50,7 +50,7 @@ gdb_test "info threads" \
 # locations ('foo' in both inferiors) even though only one of those
 # locations will ever trigger ('foo' in inferior 2).
 gdb_test "break foo thread 2.1" \
-    "Breakpoint $decimal at $hex: foo\\. \\(2 locations\\)"
+    "Breakpoint $decimal at $hex: file \[^\r\n\]+$srcfile, line $decimal\\."
 
 set bpnum [get_integer_valueof "\$bpnum" "INVALID"]
 
@@ -58,10 +58,7 @@ set bpnum [get_integer_valueof "\$bpnum" "INVALID"]
 # earlier breakpoint.  Check that the thread-id used when describing
 # the earlier breakpoints is correct.
 gdb_test "break foo thread 1.1" \
-    [multi_line \
-	 "Note: breakpoint $bpnum \\(thread 2.1\\) also set at pc $hex\\." \
-	 "Note: breakpoint $bpnum \\(thread 2.1\\) also set at pc $hex\\." \
-	 "Breakpoint $decimal at $hex: foo\\. \\(2 locations\\)"]
+    "Breakpoint $decimal at $hex: file \[^\r\n\]+$srcfile, line $decimal\\."
 
 # Save the breakpoints into a file.
 if {[is_remote host]} {
diff --git a/gdb/testsuite/gdb.multi/multi-target-continue.exp b/gdb/testsuite/gdb.multi/multi-target-continue.exp
index bf19cc00968..a1bffb7b613 100644
--- a/gdb/testsuite/gdb.multi/multi-target-continue.exp
+++ b/gdb/testsuite/gdb.multi/multi-target-continue.exp
@@ -30,7 +30,7 @@ proc test_continue {non-stop} {
 
     proc set_break {inf} {
 	gdb_test "break function${inf} thread ${inf}.1" \
-	"Breakpoint .* function${inf}\\..*"
+	    "Breakpoint ${::decimal} at ${::hex}: file .*, line ${::decimal}\\."
     }
 
     # Select inferior INF, and then run to a breakpoint on inferior
diff --git a/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp b/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp
index 64645b8ec8a..51fd70b018a 100644
--- a/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp
+++ b/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp
@@ -52,12 +52,12 @@ proc test_ping_pong_next {} {
     gdb_test "thread 1.1" "Switching to thread 1.1 .*"
 
     gdb_test "break $srcfile:$line1 thread 1.1" \
-	"Breakpoint .*$srcfile:$line1\\..*"
+	"Breakpoint .*$srcfile, line $line1\\."
 
     gdb_test "continue" "hit Breakpoint .*"
 
     gdb_test "break $srcfile:$line2 thread 2.1" \
-	"Breakpoint .*$srcfile:$line2\\..*"
+	"Breakpoint .*$srcfile, line $line2\\."
 
     # Now block inferior 1 and issue "next".  We should stop at the
     # breakpoint for inferior 2, given schedlock off.
diff --git a/gdb/testsuite/gdb.multi/pending-bp.exp b/gdb/testsuite/gdb.multi/pending-bp.exp
index 4a65f79cfc4..8e1d1234948 100644
--- a/gdb/testsuite/gdb.multi/pending-bp.exp
+++ b/gdb/testsuite/gdb.multi/pending-bp.exp
@@ -78,6 +78,48 @@ proc do_test_setup { inf_1_stop inf_2_stop } {
     return true
 }
 
+# Create a breakpoint on the function 'foo' in THREAD.  It is expected
+# that the breakpoint created will be pending, this is checked by
+# running the 'info breakpoints' command.
+#
+# Returns the number for the newly created breakpoint.
+proc do_create_pending_foo_breakpoint { {thread "1.1"} } {
+    gdb_test "break foo thread $thread" \
+	[multi_line \
+	     "Function \"foo\" not defined\\." \
+	     "Breakpoint $::decimal \\(foo\\) pending\."] \
+	"set pending thread-specific breakpoint"
+    set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+		   "get number for thread-specific breakpoint on foo"]
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	     "\\s+stop only in thread [string_to_regexp $thread]"] \
+	"check thread-specific breakpoint is initially pending"
+
+    return $bpnum
+}
+
+# Create a breakpoint on the function 'foo' in THREAD.  It is expected
+# that the breakpoint created will not be pending, this is checked by
+# running the 'info breakpoints' command.
+#
+# Returns the number for the newly created breakpoint.
+proc do_create_foo_breakpoint { {thread "1.1"} } {
+    gdb_test "break foo thread $thread" \
+	"Breakpoint $::decimal at $::hex" \
+	"set thread-specific breakpoint"
+    set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+		   "get number for thread-specific breakpoint on foo"]
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex\\s+<foo\[^>\]*> inf $::decimal" \
+	     "\\s+stop only in thread [string_to_regexp $thread]"] \
+	"check thread-specific breakpoint is initially pending"
+
+    return $bpnum
+}
+
 # Check that when a breakpoint is in the pending state, but that breakpoint
 # does have some locations (those locations themselves are pending), GDB
 # doesn't display the inferior list in the 'info breakpoints' output.
@@ -111,5 +153,169 @@ proc_with_prefix test_no_inf_display {} {
 	"check info breakpoints while breakpoint is pending"
 }
 
+# Setup two inferiors.  In #1 the symbol 'foo' has not yet been
+# loaded, while in #2 the symbol 'foo' has been loaded.
+#
+# Create a thread-specific breakpoint on 'foo' tied to a thread in
+# inferior #1, the breakpoint should be pending -- 'foo' is not yet
+# loaded in #1.
+#
+# Now move inferior #1 forward until 'foo' is loaded, check the
+# breakpoint is no longer pending.
+#
+# Move inferior #1 forward more until 'foo' is unloaded, check that
+# the breakpoint returns to the pending state.
+proc_with_prefix test_pending_toggle { } {
+
+    do_test_setup "Break before open" "Break before close"
+
+    set bpnum [do_create_pending_foo_breakpoint]
+
+    # Now return to inferior 1 and continue until the shared library is
+    # loaded, the breakpoint should become non-pending.
+    gdb_test "inferior 1" "Switching to inferior 1 .*" \
+	"switch back to inferior 1"
+    gdb_continue_to_breakpoint "stop in foo in inferior 1" "foo \\(\\) .*"
+
+    gdb_test "info breakpoint $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex <foo\[^>\]*> inf 1" \
+	     "\\s+stop only in thread 1\\.1" \
+	     "\\s+breakpoint already hit 1 time"] \
+	"check thread-specific breakpoint is no longer pending"
+
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "close library"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	     "\\s+stop only in thread 1\\.1" \
+	     "\\s+breakpoint already hit 1 time"] \
+	"check thread-specific breakpoint is pending again"
+}
+
+# Create a Python variable VAR and set it to the gdb.Breakpoint object
+# corresponding to the breakpoint numbered BPNUM.  If THREAD is not
+# the empty string then THREAD should be an integer, check that
+# gdb.Breakpoint.thread is set to the value of THREAD.  Otherwise, if
+# THREAD is the empty string, check that gdb.Breakpoint.thread is set
+# to None.
+proc py_find_breakpoint { var bpnum {thread ""} } {
+    gdb_test_no_output \
+	"python ${var}=\[b for b in gdb.breakpoints() if b.number == $bpnum\]\[0\]" \
+	"find Python gdb.Breakpoint object"
+    if { $thread ne "" } {
+	gdb_test_no_output "python assert(${var}.thread == ${thread})" \
+	    "check thread attribute is currently correct"
+    } else {
+	gdb_test_no_output "python assert(${var}.thread is None)" \
+	    "check thread attribute is currently correct"
+    }
+}
+
+# Setup two inferiors.  In #1 the symbol 'foo' has not yet been
+# loaded, while in #2 the symbol 'foo' has been loaded.
+#
+# Create a thread-specific breakpoint on 'foo' tied to a thread in
+# inferior #1, the breakpoint should be pending -- 'foo' is not yet
+# loaded in #1.
+#
+# Use Python to change the thread of the thread-specific breakpoint to
+# a thread in inferior #2, at this point the thread should gain a
+# location and become non-pending.
+#
+# Set the thread back to a thread in inferior #1, the breakpoint
+# should return to the pending state.
+proc_with_prefix py_test_toggle_thread {} {
+    do_test_setup "Break before open" "Break after open"
+
+    set bpnum [do_create_pending_foo_breakpoint]
+
+    py_find_breakpoint "bp" $bpnum 1
+
+    gdb_test_no_output "python bp.thread = 2" \
+	"change thread on thread-specific breakpoint"
+    gdb_test "info breakpoint $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex <foo\[^>\]*> inf 2" \
+	     "\\s+stop only in thread 2\\.1"] \
+	"check thread-specific breakpoint now has a location"
+
+    gdb_test_no_output "set call_count = 2" "set call_count in inferior 2"
+    gdb_continue_to_breakpoint "stop at foo in inferior 2" "foo \\(\\) .*"
+
+    gdb_test_no_output "python bp.thread = 1" \
+	"restore thread on thread-specific breakpoint"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	     "\\s+stop only in thread 1\\.1" \
+	     "\\s+breakpoint already hit 1 time"] \
+	"check thread-specific breakpoint has returned to pending"
+
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "stop after close in inferior 2" \
+	".* Break after close\\. .*"
+
+    gdb_test "inferior 1" "Switching to inferior 1 .*" \
+	"switch to inferior 1"
+    gdb_continue_to_breakpoint "stop at foo in inferior 1" "foo \\(\\) .*"
+}
+
+# Setup two inferiors.  Both inferiors have the symbol 'foo'
+# available.
+#
+# Create a thread-specific breakpoint on 'foo' tied to a thread in
+# inferior #1, the breakpoint should not be pending, but will only
+# have a single location, the location in inferior #1.
+#
+# Use Python to change the thread of the thread-specific breakpoint to
+# None.  At this point the breakpoint should gain a second location, a
+# location in inferior #2.
+proc_with_prefix py_test_clear_thread {} {
+    do_test_setup "Break after open" "Break after open"
+
+    set bpnum [do_create_foo_breakpoint]
+
+    py_find_breakpoint "bp" $bpnum 1
+
+    gdb_test_no_output "python bp.thread = None" \
+	"clear thread on thread-specific breakpoint"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "${bpnum}\\s+breakpoint\\s+keep y\\s+<MULTIPLE>\\s*" \
+	     "${bpnum}\\.1\\s+y\\s+${::hex}\\s+<foo\[^>\]*> inf $::decimal" \
+	     "${bpnum}\\.2\\s+y\\s+${::hex}\\s+<foo\[^>\]*> inf $::decimal"] \
+	"check for a location in both inferiors"
+
+    gdb_continue_to_breakpoint "stop at foo in inferior 2" "foo \\(\\) .*"
+    gdb_test_no_output "set call_count = 2" "set call_count in inferior 2"
+
+    gdb_test "inferior 1" "Switching to inferior 1 .*" \
+	"switch to inferior 1"
+    gdb_continue_to_breakpoint "stop at foo in inferior 1" "foo \\(\\) .*"
+    gdb_test_no_output "set call_count = 2" "set call_count in inferior 1"
+
+    gdb_test_no_output "python bp.thread = 2"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "${bpnum}\\s+breakpoint\\s+keep y\\s+${::hex}\\s+<foo\[^>\]*> inf 2" \
+	     "\\s+stop only in thread 2\\.1" \
+	     "\\s+breakpoint already hit 2 times"] \
+	"check for a location only in inferior 2"
+
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "stop after close in inferior 1" \
+	".* Break after close\\. .*"
+
+    gdb_test "inferior 2" "Switching to inferior 2 .*" \
+	"switch back to inferior 2"
+    gdb_continue_to_breakpoint "stop at foo again in inferior 2" \
+	"foo \\(\\) .*"
+}
+
 # Run all the tests.
 test_no_inf_display
+test_pending_toggle
+py_test_toggle_thread
+py_test_clear_thread
diff --git a/gdb/testsuite/gdb.multi/tids.exp b/gdb/testsuite/gdb.multi/tids.exp
index 18fc4970fe7..34c270309de 100644
--- a/gdb/testsuite/gdb.multi/tids.exp
+++ b/gdb/testsuite/gdb.multi/tids.exp
@@ -433,11 +433,13 @@ if { [allow_python_tests] } {
 
 	gdb_py_test_silent_cmd "python bp = gdb.breakpoints()\[0\]" \
 	    "get python breakpoint" 0
-	gdb_test "python bp.thread = 6" "thread = 6" \
+	gdb_test_no_output "python bp.thread = 6" \
 	    "make breakpoint thread-specific with python"
 	# Check that the inferior-qualified ID is correct.
 	gdb_test "info breakpoint" \
-	    "stop only in thread 1.3\r\n.*" \
+	    [multi_line \
+		 "$decimal\\s+\[^\r\n\]+ in thread_function1 at \[^\r\n\]+" \
+		 "\\s+stop only in thread 1\\.3"] \
 	    "thread specific breakpoint right thread"
     }
 }
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv4 00/10] thread-specific breakpoints in just some inferiors
  2023-05-30 20:46   ` [PATCHv3 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
                       ` (8 preceding siblings ...)
  2023-05-30 20:46     ` [PATCHv3 9/9] gdb: only insert thread-specific breakpoints in the relevant inferior Andrew Burgess
@ 2023-08-23 15:59     ` Andrew Burgess
  2023-08-23 15:59       ` [PATCHv4 01/10] gdb: create_breakpoint: add asserts and additional comments Andrew Burgess
                         ` (10 more replies)
  9 siblings, 11 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-08-23 15:59 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

This series makes it so that GDB will only insert thread-specific and
inferior-specific breakpoints into the program space in which the
thread or inferior is running.

This means that threads or inferiors running in different program
spaces will no longer hit these breakpoints at all.

Earlier versions of this series only handled thread-specific
breakpoints as the inferior-specific breakpoint support had not been
merged.  In v4 this is no longer the case and both types of breakpoint
are now handled.

---

In v4:

  - Big update, this series now handles thread-specific and
    inferior-specific breakpoints.

In v3:

  - Rebased on to current upstream/master, this includes all Simon's
    recent breakpoint changes.  Retested with no regressions seen.

In v2:

  - Rebased on current upstream/master and retested,

  - No changes to code or docs.

---

Andrew Burgess (10):
  gdb: create_breakpoint: add asserts and additional comments
  gdb: create_breakpoint: asserts relating to extra_string/parse_extra
  gdb: change 'if' to gdb_assert in update_dprintf_command_list
  gdb: build dprintf commands just once in code_breakpoint constructor
  gdb: don't display inferior list for pending breakpoints
  gdb: parse pending breakpoint thread/task immediately
  gdb: don't set breakpoint::pspace for in create_breakpoint
  gdb: remove breakpoint_re_set_one
  gdb: remove tracepoint_probe_create_sals_from_location_spec
  gdb: only insert thread-specific breakpoints in the relevant inferior

 gdb/Makefile.in                               |   2 +
 gdb/NEWS                                      |  11 +
 gdb/ada-lang.c                                |   6 +-
 gdb/break-catch-throw.c                       |   6 +-
 gdb/break-cond-parse.c                        | 425 ++++++++++
 gdb/break-cond-parse.h                        |  49 ++
 gdb/breakpoint.c                              | 759 +++++++++---------
 gdb/breakpoint.h                              | 101 ++-
 gdb/testsuite/gdb.ada/tasks.exp               |   6 +-
 gdb/testsuite/gdb.base/condbreak.exp          |  20 +-
 gdb/testsuite/gdb.base/pending.exp            |  23 +-
 gdb/testsuite/gdb.linespec/explicit.exp       |   4 +-
 gdb/testsuite/gdb.mi/mi-dprintf-pending.exp   |   3 +-
 gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp    |   8 +-
 .../gdb.mi/user-selected-context-sync.exp     |   4 +-
 .../gdb.multi/bp-thread-specific.exp          |   7 +-
 .../gdb.multi/inferior-specific-bp.exp        |  16 +-
 .../gdb.multi/multi-target-continue.exp       |   2 +-
 .../gdb.multi/multi-target-ping-pong-next.exp |   4 +-
 .../gdb.multi/pending-bp-del-inferior.c       |  28 +
 .../gdb.multi/pending-bp-del-inferior.exp     | 214 +++++
 gdb/testsuite/gdb.multi/pending-bp-lib.c      |  22 +
 gdb/testsuite/gdb.multi/pending-bp.c          |  66 ++
 gdb/testsuite/gdb.multi/pending-bp.exp        | 336 ++++++++
 gdb/testsuite/gdb.multi/tids.exp              |   6 +-
 .../gdb.threads/del-pending-thread-bp-lib.c   |  22 +
 .../gdb.threads/del-pending-thread-bp.c       |  85 ++
 .../gdb.threads/del-pending-thread-bp.exp     | 108 +++
 28 files changed, 1873 insertions(+), 470 deletions(-)
 create mode 100644 gdb/break-cond-parse.c
 create mode 100644 gdb/break-cond-parse.h
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-del-inferior.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.exp
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.exp


base-commit: cdb090c88b4ebf6f728a000d1ee73d9bdee9ebb3
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv4 01/10] gdb: create_breakpoint: add asserts and additional comments
  2023-08-23 15:59     ` [PATCHv4 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
@ 2023-08-23 15:59       ` Andrew Burgess
  2023-08-23 15:59       ` [PATCHv4 02/10] gdb: create_breakpoint: asserts relating to extra_string/parse_extra Andrew Burgess
                         ` (9 subsequent siblings)
  10 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-08-23 15:59 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

This commit extends the asserts on create_breakpoint (in the header
file), and adds some additional assertions into the definition.

The new assert confirms that when the thread and inferior information
is going to be parsed from the extra_string, then the thread and
inferior arguments should be -1.  That is, the caller of
create_breakpoint should not try to create a thread/inferior specific
breakpoint by *both* specifying thread/inferior *and* asking to parse
the extra_string, it's one or the other.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c |  6 ++++++
 gdb/breakpoint.h | 16 ++++++++++++++++
 2 files changed, 22 insertions(+)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index c429af455ff..490aa3f7de7 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -9233,6 +9233,12 @@ create_breakpoint (struct gdbarch *gdbarch,
   gdb_assert (inferior == -1 || inferior > 0);
   gdb_assert (thread == -1 || inferior == -1);
 
+  /* If PARSE_EXTRA is true then the thread and inferior details will be
+     parsed from  the EXTRA_STRING, the THREAD and INFERIOR arguments
+     should be -1.  */
+  gdb_assert (!parse_extra || thread == -1);
+  gdb_assert (!parse_extra || inferior == -1);
+
   gdb_assert (ops != NULL);
 
   /* If extra_string isn't useful, set it to NULL.  */
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index 1a73d08a887..24ceac2a6ce 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -1597,6 +1597,22 @@ enum breakpoint_create_flags
    the FORCE_CONDITION parameter is ignored and the corresponding argument
    is parsed from EXTRA_STRING.
 
+   The THREAD should be a global thread number, the created breakpoint will
+   only apply for that thread.  If the breakpoint should apply for all
+   threads then pass -1.  However, if PARSE_EXTRA is non-zero then the
+   THREAD parameter is ignored and an optional thread number will be parsed
+   from EXTRA_STRING.
+
+   The INFERIOR should be a global inferior number, the created breakpoint
+   will only apply for that inferior.  If the breakpoint should apply for
+   all inferiors then pass -1.  However, if PARSE_EXTRA is non-zero then
+   the INFERIOR parameter is ignored and an optional inferior number will
+   be parsed from EXTRA_STRING.
+
+   At most one of THREAD and INFERIOR should be set to a value other than
+   -1; breakpoints can be thread specific, or inferior specific, but not
+   both.
+
    If INTERNAL is non-zero, the breakpoint number will be allocated
    from the internal breakpoint count.
 
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv4 02/10] gdb: create_breakpoint: asserts relating to extra_string/parse_extra
  2023-08-23 15:59     ` [PATCHv4 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
  2023-08-23 15:59       ` [PATCHv4 01/10] gdb: create_breakpoint: add asserts and additional comments Andrew Burgess
@ 2023-08-23 15:59       ` Andrew Burgess
  2023-08-23 15:59       ` [PATCHv4 03/10] gdb: change 'if' to gdb_assert in update_dprintf_command_list Andrew Burgess
                         ` (8 subsequent siblings)
  10 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-08-23 15:59 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

The goal of this commit is to better define the API for
create_breakpoint especially around the use of extra_string and
parse_extra.  This will be useful in the next commit when I plan to
make some changes to create_breakpoint.

This commit makes one possibly breaking change: until this commit it
was possible to create thread-specific dprintf breakpoint like this:

  (gdb) dprintf call_me, thread 1 "%s", "hello"
  Dprintf 2 at 0x401152: file /tmp/hello.c, line 8.
  (gdb) info breakpoints
  Num     Type           Disp Enb Address            What
  2       dprintf        keep y   0x0000000000401152 in call_me at /tmp/hello.c:8 thread 1
          stop only in thread 1
          printf "%s", "hello"
  (gdb)

this feature of dprintf was not documented, was not tested, and is
slightly different in syntax to how we create thread specific
breakpoints and/or watchpoints -- the thread condition appears after
the first ','.

I believe that this worked at all was simply by luck.  We happen to
pass the parse_extra flag as true from dprintf_command to
create_breakpoint.

So in this commit I made the choice change this.  We now pass
parse_extra as false from dprintf_command to create_breakpoint.  With
this done it is assumed that the only thing in the extra_string is the
dprintf format and arguments.

Beyond this change I've updated the comment on create_breakpoint in
breakpoint.h, and I've then added some asserts into
create_breakpoint as well as moving around some of the error
handling.

 - We now assert on the incoming argument values,

 - I've moved an error check to sit after the call to
   find_condition_and_thread_for_sals, this ensures the extra_string
   was parsed correctly,

In dprintf_command:

 - We now throw an error if there is no format string after the
   dprintf location.  This error was already being thrown, but was
   being caught later in the process.  With this change we catch the
   missing string earlier,

 - And, as mentioned earlier, we pass parse_extra as false when
   calling create_breakpoint,

In create_tracepoint_from_upload:

 - We now throw an error if the parsed location doesn't completely
   consume the addr_str variable.  This error has now effectively
   moved out of create_breakpoint.
---
 gdb/breakpoint.c | 42 +++++++++++++++++++++++++++++-------------
 gdb/breakpoint.h | 44 +++++++++++++++++++++++++++-----------------
 2 files changed, 56 insertions(+), 30 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 490aa3f7de7..66d52fd2f07 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -9245,6 +9245,17 @@ create_breakpoint (struct gdbarch *gdbarch,
   if (extra_string != NULL && *extra_string == '\0')
     extra_string = NULL;
 
+  /* A bp_dprintf must always have an accompanying EXTRA_STRING containing
+     the dprintf format and arguments -- PARSE_EXTRA should always be false
+     in this case.
+
+     For all other breakpoint types, EXTRA_STRING should be nullptr unless
+     PARSE_EXTRA is true.  */
+  gdb_assert ((type_wanted == bp_dprintf
+	       && extra_string != nullptr && !parse_extra)
+	      || (type_wanted != bp_dprintf
+		  && (extra_string == nullptr || parse_extra)));
+
   try
     {
       ops->create_sals_from_location_spec (locspec, &canonical);
@@ -9308,6 +9319,8 @@ create_breakpoint (struct gdbarch *gdbarch,
 
       if (parse_extra)
 	{
+	  gdb_assert (type_wanted != bp_dprintf);
+
 	  gdb::unique_xmalloc_ptr<char> rest;
 	  gdb::unique_xmalloc_ptr<char> cond;
 
@@ -9316,15 +9329,15 @@ create_breakpoint (struct gdbarch *gdbarch,
 	  find_condition_and_thread_for_sals (lsal.sals, extra_string,
 					      &cond, &thread, &inferior,
 					      &task, &rest);
+
+	  if (rest.get () != nullptr && *(rest.get ()) != '\0')
+	    error (_("Garbage '%s' at end of command"), rest.get ());
+
 	  cond_string_copy = std::move (cond);
 	  extra_string_copy = std::move (rest);
 	}
       else
 	{
-	  if (type_wanted != bp_dprintf
-	      && extra_string != NULL && *extra_string != '\0')
-		error (_("Garbage '%s' at end of location"), extra_string);
-
 	  /* Check the validity of the condition.  We should error out
 	     if the condition is invalid at all of the locations and
 	     if it is not forced.  In the PARSE_EXTRA case above, this
@@ -9535,21 +9548,18 @@ dprintf_command (const char *arg, int from_tty)
 
   /* If non-NULL, ARG should have been advanced past the location;
      the next character must be ','.  */
-  if (arg != NULL)
+  if (arg == nullptr || arg[0] != ',' || arg[1] == '\0')
+    error (_("Format string required"));
+  else
     {
-      if (arg[0] != ',' || arg[1] == '\0')
-	error (_("Format string required"));
-      else
-	{
-	  /* Skip the comma.  */
-	  ++arg;
-	}
+      /* Skip the comma.  */
+      ++arg;
     }
 
   create_breakpoint (get_current_arch (),
 		     locspec.get (),
 		     NULL, -1, -1,
-		     arg, false, 1 /* parse arg */,
+		     arg, false, 0 /* parse arg */,
 		     0, bp_dprintf,
 		     0 /* Ignore count */,
 		     pending_break_support,
@@ -14140,6 +14150,12 @@ create_tracepoint_from_upload (struct uploaded_tp *utp)
 
   location_spec_up locspec = string_to_location_spec (&addr_str,
 						      current_language);
+
+
+  gdb_assert (addr_str != nullptr);
+  if (*addr_str != '\0')
+    error (_("Garbage '%s' at end of location"), addr_str);
+
   if (!create_breakpoint (get_current_arch (),
 			  locspec.get (),
 			  utp->cond_string.get (), -1, -1, addr_str,
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index 24ceac2a6ce..4b14bc95d63 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -1582,32 +1582,42 @@ enum breakpoint_create_flags
    functions for setting a breakpoint at LOCSPEC.
 
    This function has two major modes of operations, selected by the
-   PARSE_EXTRA parameter.
+   PARSE_EXTRA and WANTED_TYPE parameters.
 
-   If PARSE_EXTRA is zero, LOCSPEC is just the breakpoint's location
-   spec, with condition, thread, and extra string specified by the
-   COND_STRING, THREAD, and EXTRA_STRING parameters.
+   When WANTED_TYPE is not bp_dprintf the following rules apply:
 
-   If PARSE_EXTRA is non-zero, this function will attempt to extract
-   the condition, thread, and extra string from EXTRA_STRING, ignoring
-   the similarly named parameters.
+     If PARSE_EXTRA is zero, LOCSPEC is just the breakpoint's location
+     spec, with condition, thread, and extra string specified by the
+     COND_STRING, THREAD, and EXTRA_STRING parameters.
 
-   If FORCE_CONDITION is true, the condition is accepted even when it is
-   invalid at all of the locations.  However, if PARSE_EXTRA is non-zero,
-   the FORCE_CONDITION parameter is ignored and the corresponding argument
-   is parsed from EXTRA_STRING.
+     If PARSE_EXTRA is non-zero, this function will attempt to extract the
+     condition, thread, and extra string from EXTRA_STRING, ignoring the
+     similarly named parameters.
+
+   When WANTED_TYPE is bp_dprintf the following rules apply:
+
+     PARSE_EXTRA must always be zero, LOCSPEC is just the breakpoint's
+     location spec, with condition, thread, and extra string (which
+     contains the dprintf format and arguments) specified by the
+     COND_STRING, THREAD, and EXTRA_STRING parameters.
+
+   If FORCE_CONDITION is true, the condition (in COND_STRING) is accepted
+   even when it is invalid at all of the locations.  However, if
+   PARSE_EXTRA is non-zero and WANTED_TYPE is not bp_dprintf, the
+   FORCE_CONDITION parameter is ignored and the corresponding argument is
+   parsed from EXTRA_STRING.
 
    The THREAD should be a global thread number, the created breakpoint will
    only apply for that thread.  If the breakpoint should apply for all
-   threads then pass -1.  However, if PARSE_EXTRA is non-zero then the
-   THREAD parameter is ignored and an optional thread number will be parsed
-   from EXTRA_STRING.
+   threads then pass -1.  However, if PARSE_EXTRA is non-zero and
+   WANTED_TYPE is not bp_dprintf, then the THREAD parameter is ignored and
+   an optional thread number will be parsed from EXTRA_STRING.
 
    The INFERIOR should be a global inferior number, the created breakpoint
    will only apply for that inferior.  If the breakpoint should apply for
-   all inferiors then pass -1.  However, if PARSE_EXTRA is non-zero then
-   the INFERIOR parameter is ignored and an optional inferior number will
-   be parsed from EXTRA_STRING.
+   all inferiors then pass -1.  However, if PARSE_EXTRA is non-zero and
+   WANTED_TYPE is not bp_dprintf, then the INFERIOR parameter is ignored
+   and an optional inferior number will be parsed from EXTRA_STRING.
 
    At most one of THREAD and INFERIOR should be set to a value other than
    -1; breakpoints can be thread specific, or inferior specific, but not
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv4 03/10] gdb: change 'if' to gdb_assert in update_dprintf_command_list
  2023-08-23 15:59     ` [PATCHv4 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
  2023-08-23 15:59       ` [PATCHv4 01/10] gdb: create_breakpoint: add asserts and additional comments Andrew Burgess
  2023-08-23 15:59       ` [PATCHv4 02/10] gdb: create_breakpoint: asserts relating to extra_string/parse_extra Andrew Burgess
@ 2023-08-23 15:59       ` Andrew Burgess
  2023-08-23 15:59       ` [PATCHv4 04/10] gdb: build dprintf commands just once in code_breakpoint constructor Andrew Burgess
                         ` (7 subsequent siblings)
  10 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-08-23 15:59 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

I noticed in update_dprintf_command_list that we handle the case where
the bp_dprintf style breakpoint doesn't have a format and args string.

However, I don't believe such a situation is possible.  The obvious
approach certainly already catches this case:

  (gdb) dprintf main
  Format string required

If it is possible to create a dprintf breakpoint without a format and
args string then I think we should be catching this case and handling
it at creation time, rather than having GDB just ignore the situation
later on.

And so, I propose that we change the 'if' that ignores the case where
the format/args string is empty, and instead assert that we do always
have a format/args string.  The original code, that handled an empty
format/args string has existed since commit e7e0cddfb0d4, which is
when dprintf support was added to GDB.

If I'm correct and this situation can't ever happen then there should
be no user visible changes after this commit.
---
 gdb/breakpoint.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 66d52fd2f07..86225ef82fa 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -8543,8 +8543,9 @@ update_dprintf_command_list (struct breakpoint *b)
   const char *dprintf_args = b->extra_string.get ();
   gdb::unique_xmalloc_ptr<char> printf_line = nullptr;
 
-  if (!dprintf_args)
-    return;
+  /* Trying to create a dprintf breakpoint without a format and args
+     string should be detected at creation time.  */
+  gdb_assert (dprintf_args != nullptr);
 
   dprintf_args = skip_spaces (dprintf_args);
 
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv4 04/10] gdb: build dprintf commands just once in code_breakpoint constructor
  2023-08-23 15:59     ` [PATCHv4 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
                         ` (2 preceding siblings ...)
  2023-08-23 15:59       ` [PATCHv4 03/10] gdb: change 'if' to gdb_assert in update_dprintf_command_list Andrew Burgess
@ 2023-08-23 15:59       ` Andrew Burgess
  2023-08-23 15:59       ` [PATCHv4 05/10] gdb: don't display inferior list for pending breakpoints Andrew Burgess
                         ` (6 subsequent siblings)
  10 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-08-23 15:59 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

I noticed in code_breakpoint::code_breakpoint that we are calling
update_dprintf_command_list once for each breakpoint location, when we
really only need to call this once per breakpoint -- the data updated
by this function, the breakpoint command list -- is per breakpoint,
not per breakpoint location.  Calling update_dprintf_command_list
multiple times is just wasted effort, there's no per location error
checking, we don't even pass the current location to the function.

This commit moves the update_dprintf_command_list call outside of the
per-location loop. I have also changes the 'if' that handles the case
where the extra_string (which holds the format/args) is empty.  I
don't believe that this situation can ever arise -- and if it does we
should be catching it earlier and throwing an error at that point.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c | 20 +++++++++-----------
 1 file changed, 9 insertions(+), 11 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 86225ef82fa..1cf1f4468a1 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -8709,19 +8709,17 @@ code_breakpoint::code_breakpoint (struct gdbarch *gdbarch_,
       /* Do not set breakpoint locations conditions yet.  As locations
 	 are inserted, they get sorted based on their addresses.  Let
 	 the list stabilize to have reliable location numbers.  */
+    }
 
-      /* Dynamic printf requires and uses additional arguments on the
-	 command line, otherwise it's an error.  */
-      if (type == bp_dprintf)
-	{
-	  if (extra_string != nullptr)
-	    update_dprintf_command_list (this);
-	  else
-	    error (_("Format string required"));
-	}
-      else if (extra_string != nullptr)
-	error (_("Garbage '%s' at end of command"), extra_string.get ());
+  /* Dynamic printf requires and uses additional arguments on the
+     command line, otherwise it's an error.  */
+  if (type == bp_dprintf)
+    {
+      gdb_assert (extra_string != nullptr);
+      update_dprintf_command_list (this);
     }
+  else if (extra_string != nullptr)
+    error (_("Garbage '%s' at end of command"), extra_string.get ());
 
   /* The order of the locations is now stable.  Set the location
      condition using the location's number.  */
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv4 05/10] gdb: don't display inferior list for pending breakpoints
  2023-08-23 15:59     ` [PATCHv4 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
                         ` (3 preceding siblings ...)
  2023-08-23 15:59       ` [PATCHv4 04/10] gdb: build dprintf commands just once in code_breakpoint constructor Andrew Burgess
@ 2023-08-23 15:59       ` Andrew Burgess
  2023-08-23 15:59       ` [PATCHv4 06/10] gdb: parse pending breakpoint thread/task immediately Andrew Burgess
                         ` (5 subsequent siblings)
  10 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-08-23 15:59 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

I noticed that in the 'info breakpoints' output, GDB sometimes prints
the inferior list for pending breakpoints, this doesn't seem right to
me.  A pending breakpoint has no locations (at least, as far as we
display things in the 'info breakpoints' output), so including an
inferior list seems odd.

Here's what I see right now:

  (gdb) info breakpoint 5
  Num     Type           Disp Enb Address            What
  5       breakpoint     keep y   <PENDING>          foo inf 1
  (gdb)

It's the 'inf 1' at the end of the line that I'm objecting too.

To trigger this behaviour we need to be in a multi-inferior debug
session.  The breakpoint must have been non-pending at some point in
the past, and so have a location assigned to it.

The breakpoint becomes pending again as a result of a shared library
being unloaded.  When this happens the location itself is marked
pending (via bp_location::shlib_disabled).

In print_one_breakpoint_location, in order to print the inferior list
we check that the breakpoint has a location, and that we have multiple
inferiors, but we don't check if the location itself is pending.

This commit adds that check, which means the output is now:

  (gdb) info breakpoint 5
  Num     Type           Disp Enb Address            What
  5       breakpoint     keep y   <PENDING>          foo
  (gdb)

Which I think makes more sense -- indeed, the format without the
inferior list is what we display for a pending breakpoint that has
never had any locations assigned, so I think this change in behaviour
makes GDB more consistent.
---
 gdb/breakpoint.c                         |   2 +-
 gdb/testsuite/gdb.multi/pending-bp-lib.c |  22 ++++
 gdb/testsuite/gdb.multi/pending-bp.c     |  66 ++++++++++++
 gdb/testsuite/gdb.multi/pending-bp.exp   | 130 +++++++++++++++++++++++
 4 files changed, 219 insertions(+), 1 deletion(-)
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.exp

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 1cf1f4468a1..5a608ba2495 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -6602,7 +6602,7 @@ print_one_breakpoint_location (struct breakpoint *b,
 	}
     }
 
-  if (loc != NULL && !header_of_multiple)
+  if (loc != NULL && !header_of_multiple && !loc->shlib_disabled)
     {
       std::vector<int> inf_nums;
       int mi_only = 1;
diff --git a/gdb/testsuite/gdb.multi/pending-bp-lib.c b/gdb/testsuite/gdb.multi/pending-bp-lib.c
new file mode 100644
index 00000000000..15d1b9833dd
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp-lib.c
@@ -0,0 +1,22 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+int global_var = 0;
+
+void
+foo (int arg)
+{
+  global_var = arg;
+}
diff --git a/gdb/testsuite/gdb.multi/pending-bp.c b/gdb/testsuite/gdb.multi/pending-bp.c
new file mode 100644
index 00000000000..ca8a3c20b72
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp.c
@@ -0,0 +1,66 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#include <dlfcn.h>
+#include <stdlib.h>
+
+void
+breakpt ()
+{
+  /* Nothing.  */
+}
+
+volatile int global_counter = 0;
+
+volatile int call_count = 1;
+
+int
+main (void)
+{
+  void *handle;
+  void (*func)(int);
+
+  /* Some filler work so that we don't initially stop on the breakpt call
+     below.  */
+  ++global_counter;
+
+  breakpt ();	/* Break before open.  */
+
+  /* Now load the shared library.  */
+  handle = dlopen (SHLIB_NAME, RTLD_LAZY);
+  if (handle == NULL)
+    abort ();
+
+  breakpt ();	/* Break after open.  */
+
+  /* Find the function symbol.  */
+  func = (void (*)(int)) dlsym (handle, "foo");
+
+  for (; call_count > 0; --call_count)
+    {
+      /* Call the library function.  */
+      func (1);
+    }
+
+  breakpt ();	/* Break before close.  */
+
+  /* Unload the shared library.  */
+  if (dlclose (handle) != 0)
+    abort ();
+
+  breakpt ();	/* Break after close.  */
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.multi/pending-bp.exp b/gdb/testsuite/gdb.multi/pending-bp.exp
new file mode 100644
index 00000000000..e4f0aa2e38a
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp.exp
@@ -0,0 +1,130 @@
+# Copyright 2023 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+# Tests related to pending breakpoints in a multi-inferior environment.
+
+require allow_shlib_tests !use_gdb_stub
+
+standard_testfile
+
+set libname $testfile-lib
+set srcfile_lib $srcdir/$subdir/$libname.c
+set binfile_lib [standard_output_file $libname.so]
+
+if { [gdb_compile_shlib $srcfile_lib $binfile_lib {}] != "" } {
+    untested "failed to compile shared library 1"
+    return -1
+}
+
+set binfile_lib_target [gdb_download_shlib $binfile_lib]
+
+if { [build_executable "failed to prepare" $testfile $srcfile \
+	  [list debug \
+	       additional_flags=-DSHLIB_NAME=\"$binfile_lib_target\" \
+	       shlib_load pthreads]] } {
+    return -1
+}
+
+# Used to override delete_breakpoints when we don't want breakpoints
+# deleted.
+proc do_nothing {} {}
+
+# Start two inferiors, both running the same test binary.  The arguments
+# INF_1_STOP and INF_2_STOP are source code patterns that are passed to
+# gdb_get_line_number to figure out where each inferior should be stopped.
+#
+# This proc does a clean_restart and leaves inferior 2 selected.  Also the
+# 'breakpoint pending' flag is enabled, so pending breakpoints can be created
+# without GDB prompting the user.
+proc do_test_setup { inf_1_stop inf_2_stop } {
+    clean_restart ${::binfile}
+
+    gdb_locate_shlib $::binfile_lib
+
+    if ![runto_main] {
+	return false
+    }
+
+    gdb_breakpoint [gdb_get_line_number ${inf_1_stop}] temporary
+    gdb_continue_to_breakpoint "move inferior 1 into position"
+
+    gdb_test "add-inferior -exec ${::binfile}" \
+	"Added inferior 2.*" "add inferior 2"
+    gdb_test "inferior 2" "Switching to inferior 2 .*" "switch to inferior 2"
+
+    with_override delete_breakpoints do_nothing {
+	if {![runto_main]} {
+	    return false
+	}
+    }
+
+    gdb_breakpoint [gdb_get_line_number ${inf_2_stop}] temporary
+    gdb_continue_to_breakpoint "move inferior 2 into position"
+
+    gdb_test_no_output "set breakpoint pending on"
+
+    return true
+}
+
+# Check that when a breakpoint is in the pending state, but that breakpoint
+# does have some locations (those locations themselves are pending), GDB
+# doesn't display the inferior list in the 'info breakpoints' output.
+proc_with_prefix test_no_inf_display {} {
+    do_test_setup "Break before open" "Break before open"
+
+    # Create a breakpoint on 'foo'.  As the shared library (that contains
+    # foo) has not been loaded into any inferior yet, then there will be no
+    # locations and the breakpoint will be created pending.
+    gdb_breakpoint "foo" allow-pending
+    set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+		   "get foo breakpoint number"]
+
+    # Check the 'info breakpoints' output; the breakpoint is pending with
+    # not 'inf X' appearing at the end of the line.
+    gdb_test "info breakpoint $bpnum" \
+	"$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	"check info bp before locations have been created"
+
+    # Now select inferior 1 and allow the inferior to run forward to the
+    # point where a breakpoint location for foo will have been created.
+    gdb_test "inferior 1" "Switching to inferior 1 .*"
+    gdb_breakpoint [gdb_get_line_number "Break after open"] temporary
+    gdb_continue_to_breakpoint \
+	"move inferior 1 until a location has been added"
+
+    # Check the 'info breakpoints' output.  Notice we display the inferior
+    # list at the end of the breakpoint line.
+    gdb_test "info breakpoint $bpnum" \
+	"$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex\\s+<foo\[^>\]*>\\s+inf 1" \
+	"check info breakpoints while breakpoint is inserted"
+
+    # Continue inferior 1 until the shared library has been unloaded.  The
+    # breakpoint on 'foo' will return to the pending state.  We will need to
+    # 'continue' twice as the first time will hit the 'foo' breakpoint.
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "hit the breakpoint in foo"
+    gdb_continue_to_breakpoint "after close library"
+
+    # Check the 'info breakpoints' output, check there is no 'inf 1' at the
+    # end of the breakpoint line.
+    gdb_test "info breakpoint $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	     "\\s+breakpoint already hit 1 time"] \
+	"check info breakpoints while breakpoint is pending"
+}
+
+# Run all the tests.
+test_no_inf_display
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv4 06/10] gdb: parse pending breakpoint thread/task immediately
  2023-08-23 15:59     ` [PATCHv4 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
                         ` (4 preceding siblings ...)
  2023-08-23 15:59       ` [PATCHv4 05/10] gdb: don't display inferior list for pending breakpoints Andrew Burgess
@ 2023-08-23 15:59       ` Andrew Burgess
  2023-08-23 16:32         ` Eli Zaretskii
  2023-09-06 22:06         ` Lancelot SIX
  2023-08-23 15:59       ` [PATCHv4 07/10] gdb: don't set breakpoint::pspace for in create_breakpoint Andrew Burgess
                         ` (4 subsequent siblings)
  10 siblings, 2 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-08-23 15:59 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Eli Zaretskii

The initial motivation for this commit was to allow thread or inferior
specific breakpoints to only be inserted within the appropriate
inferior's program-space.  The benefit of this is that inferiors for
which the breakpoint does not apply will no longer need to stop, and
then resume, for such breakpoints.  This commit does not make this
change, but is a refactor to allow this to happen in a later commit.

The problem we currently have is that when a thread-specific (or
inferior-specific) breakpoint is created, the thread (or inferior)
number is only parsed by calling find_condition_and_thread_for_sals.
This function is only called for non-pending breakpoints, and requires
that we know the locations at which the breakpoint will be placed (for
expression checking in case the breakpoint is also conditional).

A consequence of this is that by the time we figure out the breakpoint
is thread-specific we have already looked up locations in all program
spaces.  This feels wasteful -- if we knew the thread-id earlier then
we could reduce the work GDB does by only looking up locations within
the program space for which the breakpoint applies.

Another consequence of how find_condition_and_thread_for_sals is
called is that pending breakpoints don't currently know they are
thread-specific, nor even that they are conditional!  Additionally, by
delaying parsing the thread-id, pending breakpoints can be created for
non-existent threads, this is different to how non-pending
breakpoints are handled, so I can do this:

  $ gdb -q ./gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp
  Reading symbols from ./gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp...
  (gdb) break foo thread 99
  Function "foo" not defined.
  Make breakpoint pending on future shared library load? (y or [n]) y
  Breakpoint 1 (foo thread 99) pending.
  (gdb) r
  Starting program: /tmp/gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp
  [Thread debugging using libthread_db enabled]
  Using host libthread_db library "/lib64/libthread_db.so.1".
  Error in re-setting breakpoint 1: Unknown thread 99.
  [Inferior 1 (process 3329749) exited normally]
  (gdb)

GDB only checked the validity of 'thread 99' at the point the 'foo'
location became non-pending.  In contrast, if I try this:

  $ gdb -q ./gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp
  Reading symbols from ./gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp...
  (gdb) break main thread 99
  Unknown thread 99.
  (gdb)

GDB immediately checks if 'thread 99' exists.  I think inconsistencies
like this are confusing, and should be fixed if possible.

In this commit the create_breakpoint function is updated so that the
extra_string, which contains the thread, inferior, task, and/or
condition information, is parsed immediately, even for pending
breakpoints.

Obviously, the condition still can't be validated until the breakpoint
becomes non-pending, but the thread, inferior, and task information
can be pulled from the extra-string, and can be validated early on,
even for pending breakpoints.

There are a couple of benefits to doing this:

1. Printing of breakpoints is more consistent now.  Consider creating
   a conditional breakpoint before this commit:

    (gdb) set breakpoint pending on
    (gdb) break pendingfunc if (0)
    Function "pendingfunc" not defined.
    Breakpoint 1 (pendingfunc if (0)) pending.
    (gdb) break main if (0)
    Breakpoint 2 at 0x401198: file /tmp/hello.c, line 18.
    (gdb) info breakpoints
    Num     Type           Disp Enb Address            What
    1       breakpoint     keep y   <PENDING>          pendingfunc if (0)
    2       breakpoint     keep y   0x0000000000401198 in main at /tmp/hello.c:18
            stop only if (0)
    (gdb)

   And after this commit:

    (gdb) set breakpoint pending on
    (gdb) break pendingfunc if (0)
    Function "pendingfunc" not defined.
    Breakpoint 1 (pendingfunc) pending.
    (gdb) break main if (0)
    Breakpoint 2 at 0x401198: file /home/andrew/tmp/hello.c, line 18.
    (gdb) info breakpoints
    Num     Type           Disp Enb Address            What
    1       breakpoint     keep y   <PENDING>          pendingfunc
            stop only if (0)
    2       breakpoint     keep y   0x0000000000401198 in main at /home/andrew/tmp/hello.c:18
            stop only if (0)
    (gdb)

   Notice that the display of the condition is now the same for the
   pending and non-pending breakpoints.

   The same is true for the thread information in thread-specific
   breakpoints, this information is displayed on its own line now
   rather than being part of the 'What' field.

2. We can check that the thread exists as soon as the pending
   breakpoint exits.  Currently there is a weird different between
   pending and non-pending breakpoints when creating a thread-specific
   breakpoint.  A pending thread-specific breakpoint only checks its
   thread when it becomes non-pending, at which point the thread the
   breakpoint was intended for might have exited.  Here's the
   behaviour before this commit:

    (gdb) set breakpoint pending on
    (gdb) break foo thread 2
    Function "foo" not defined.
    Breakpoint 2 (foo thread 2) pending.
    (gdb) c
    Continuing.
    [Thread 0x7ffff7c56700 (LWP 2948835) exited]
    Error in re-setting breakpoint 2: Unknown thread 2.
    [Inferior 1 (process 2948832) exited normally]
    (gdb)

   Notice the 'Error in re-setting breakpoint 2: Unknown thread 2.'
   line, this was triggered when the thread tried to become
   non-pending, and GDB discovers that the thread no longer exists.

   Compare that to the behaviour after this commit:

    (gdb) set breakpoint pending on
    (gdb) break foo thread 2
    Function "foo" not defined.
    Breakpoint 2 (foo) pending.
    (gdb) c
    Continuing.
    [Thread 0x7ffff7c56700 (LWP 2949243) exited]
    Thread-specific breakpoint 2 deleted - thread 2 no longer in the thread list.
    [Inferior 1 (process 2949240) exited normally]
    (gdb)

   Now the behaviour for pending breakpoints is identical to
   non-pending breakpoints, the thread specific breakpoint is removed
   as soon as the thread the breakpoint is associated with exits.

As a result of this commit the breakpoints 'extra_string' field is now
only used by bp_dprintf type breakpoints to hold the printf format and
arguments.  This string should always be empty for other breakpoint
types.  This allows me to clean up some code in
print_breakpoint_location.

In code_breakpoint::code_breakpoint I'm able to change an error case
into an assert.  This is because this error is now handled earlier in
create_breakpoint.  As a result we know that by this point, the
extra_string will always be nullptr for anything other than a
bp_dprintf style breakpoint.

The find_condition_and_thread_for_sals function is now no longer
needed, this was previously doing the delayed splitting of the extra
string into thread, task, and condition, but this is now all done in
create_breakpoint, so find_condition_and_thread_for_sals can be
deleted, and the code that calls this in
code_breakpoint::location_spec_to_sals can be removed.  With this
update this code would only ever be reached for bp_dprintf style
breakpoints, and in these cases the extra_string should not contain
anything other than format and args.

The most interesting changes are all in create_breakpoint and in the
new file break-cond-parse.c.  We have a new block of code early on in
create_breakpoint that is responsible for splitting the extra_string
into its component parts by calling create_breakpoint_parse_arg_string
a function in the new break-cond-parse.c file.  This means that some
of the later code can be simplified a little.

The new break-cond-parse.c file implements the splitting up the
extra_string and finding all the parts, as well as some self-tests for
the new function.

Finally, now we know all the details, these can be stored within the
breakpoint object if we end up creating a deferred breakpoint.
Additionally, if we are creating a deferred bp_dprintf we can parse
the extra_string to build the printf command.

Reviewed-By: Eli Zaretskii <eliz@gnu.org>
---
 gdb/Makefile.in                               |   2 +
 gdb/NEWS                                      |   4 +
 gdb/break-cond-parse.c                        | 425 ++++++++++++++++++
 gdb/break-cond-parse.h                        |  49 ++
 gdb/breakpoint.c                              | 374 ++++-----------
 gdb/testsuite/gdb.ada/tasks.exp               |   6 +-
 gdb/testsuite/gdb.base/condbreak.exp          |  20 +-
 gdb/testsuite/gdb.base/pending.exp            |  23 +-
 gdb/testsuite/gdb.linespec/explicit.exp       |   4 +-
 gdb/testsuite/gdb.mi/mi-dprintf-pending.exp   |   3 +-
 .../gdb.multi/inferior-specific-bp.exp        |   4 +-
 .../gdb.threads/del-pending-thread-bp-lib.c   |  22 +
 .../gdb.threads/del-pending-thread-bp.c       |  85 ++++
 .../gdb.threads/del-pending-thread-bp.exp     | 108 +++++
 14 files changed, 826 insertions(+), 303 deletions(-)
 create mode 100644 gdb/break-cond-parse.c
 create mode 100644 gdb/break-cond-parse.h
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.exp

diff --git a/gdb/Makefile.in b/gdb/Makefile.in
index 9b992a3d8c0..43b867cd796 100644
--- a/gdb/Makefile.in
+++ b/gdb/Makefile.in
@@ -1026,6 +1026,7 @@ COMMON_SFILES = \
 	break-catch-sig.c \
 	break-catch-syscall.c \
 	break-catch-throw.c \
+	break-cond-parse.c \
 	breakpoint.c \
 	bt-utils.c \
 	btrace.c \
@@ -1293,6 +1294,7 @@ HFILES_NO_SRCDIR = \
 	bfd-target.h \
 	bfin-tdep.h \
 	block.h \
+	break-cond-parse.h \
 	breakpoint.h \
 	bsd-kvm.h \
 	bsd-uthread.h \
diff --git a/gdb/NEWS b/gdb/NEWS
index c4b1f7a7e3b..7c38ecb8b46 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -105,6 +105,10 @@
   'inferior' keyword with either the 'thread' or 'task' keywords when
   creating a breakpoint.
 
+* For breakpoints that are created in the 'pending' state, any
+  'thread' or 'task' keywords are parsed at the time the breakpoint is
+  created, rather than at the time the breakpoint becomes non-pending.
+
 * New commands
 
 set debug breakpoint on|off
diff --git a/gdb/break-cond-parse.c b/gdb/break-cond-parse.c
new file mode 100644
index 00000000000..ebe67c90736
--- /dev/null
+++ b/gdb/break-cond-parse.c
@@ -0,0 +1,425 @@
+/* Copyright (C) 2023 Free Software Foundation, Inc.
+
+   This file is part of GDB.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#include "defs.h"
+#include "gdbsupport/gdb_assert.h"
+#include "gdbsupport/selftest.h"
+#include "test-target.h"
+#include "scoped-mock-context.h"
+#include "break-cond-parse.h"
+#include "tid-parse.h"
+#include "ada-lang.h"
+
+/* When parsing tokens from a string, which direction are we parsing?
+
+   Given the following string and pointer 'ptr':
+
+     ABC DEF GHI JKL
+            ^
+           ptr
+
+   Parsing 'forward' will return the token 'GHI' and update 'ptr' to point
+   between GHI and JKL.  Parsing 'backward' will return the token 'DEF' and
+   update 'ptr' to point between ABC and DEF.
+*/
+
+enum class parse_direction
+{
+  /* Parse the next token forwards.  */
+  forward,
+
+  /* Parse the previous token backwards.  */
+  backward
+};
+
+struct token
+{
+  /* Create a new token.  START points to the first character of the new
+     token, while END points at the last character of the new token.
+
+     Neither START or END can be nullptr, and both START and END must point
+     into the same C style string (i.e. there should be no null character
+     between START and END).  END must be equal to, or greater than START,
+     that is, it is not possible to create a zero length token.  */
+
+  token (const char *start, const char *end)
+    : m_start (start),
+      m_end (end)
+  {
+    gdb_assert (m_end >= m_start);
+    gdb_assert (m_start + strlen (m_start) > m_end);
+  }
+
+  /* Return a pointer to the first character of this token.  */
+  const char *start () const
+  {
+    return m_start;
+  }
+
+  /* Return a pointer to the last character of this token.  */
+  const char *end () const
+  {
+    return m_end;
+  }
+
+  /* Return the length of the token.  */
+  size_t length () const
+  {
+    return m_end - m_start + 1;
+  }
+
+  /* Return true if this token matches STR.  If this token is shorter than
+     STR then only a partial match is performed and true will be returned
+     if the token length sub-string matches.  Otherwise, return false.  */
+  bool matches (const char *str) const
+  {
+    return strncmp (m_start, str, length ()) == 0;
+  }
+
+private:
+  /* The first character of this token.  */
+  const char *m_start;
+
+  /* The last character of this token.  */
+  const char *m_end;
+};
+
+/* Find the next token in DIRECTION from *CURR.  */
+
+static token
+find_next_token (const char **curr, parse_direction direction)
+{
+  const char *tok_start, *tok_end;
+
+  if (direction == parse_direction::forward)
+    {
+      *curr = skip_spaces (*curr);
+      tok_start = *curr;
+      *curr = skip_to_space (*curr);
+      tok_end = *curr - 1;
+    }
+  else
+    {
+      gdb_assert (direction == parse_direction::backward);
+
+      while (isspace (**curr))
+	--(*curr);
+
+      tok_end = *curr;
+
+      while (!isspace (**curr))
+	--(*curr);
+
+      tok_start = (*curr) + 1;
+    }
+
+  return token (tok_start, tok_end);
+}
+
+/* See break-cond-parse.h.  */
+
+void
+create_breakpoint_parse_arg_string
+  (const char *tok, gdb::unique_xmalloc_ptr<char> *cond_string,
+   int *thread, int *inferior, int *task,
+   gdb::unique_xmalloc_ptr<char> *rest, bool *force)
+{
+  /* Set up the defaults.  */
+  cond_string->reset ();
+  rest->reset ();
+  *thread = -1;
+  *inferior = -1;
+  *task = -1;
+  *force = false;
+
+  if (tok == nullptr)
+    return;
+
+  const char *cond_start = nullptr;
+  const char *cond_end = nullptr;
+  parse_direction direction = parse_direction::forward;
+  while (*tok != '\0')
+    {
+      /* Find the next token.  If moving backward and this token starts at
+	 the same location as the condition then we must have found the
+	 other end of the condition string -- we're done.  */
+      token t = find_next_token (&tok, direction);
+      if (direction == parse_direction::backward && t.start () <= cond_start)
+	{
+	  cond_end = t.end () + 1;
+	  break;
+	}
+
+      /* We only have a single flag option to check for.  All the other
+	 options take a value so require an additional token to be found.  */
+      if (t.length () > 0 && t.matches ("-force-condition"))
+	{
+	  *force = true;
+	  continue;
+	}
+
+      /* Maybe the first token was the last token in the string.  If this
+	 is the case then we definitely can't try to extract a value
+	 token.  This also means that the token T is meaningless.  Reset
+	 TOK to point at the start of the unknown content and break out of
+	 the loop.  We'll record the unknown part of the string outside of
+	 the scanning loop (below).  */
+      if (direction == parse_direction::forward && *tok == '\0')
+	{
+	  tok = t.start ();
+	  break;
+	}
+
+      /* As before, find the next token and, if we are scanning backwards,
+	 check that we have not reached the start of the condition string.  */
+      token v = find_next_token (&tok, direction);
+      if (direction == parse_direction::backward && v.start () <= cond_start)
+	{
+	  /* Use token T here as that must also be part of the condition
+	     string.  */
+	  cond_end = t.end () + 1;
+	  break;
+	}
+
+      /* When moving backward we will first parse the value token then the
+	 keyword token, so swap them now.  */
+      if (direction == parse_direction::backward)
+	std::swap (t, v);
+
+      /* Check for valid option in token T.  If we find a valid option then
+	 parse the value from the token V.  Except for 'if', that's handled
+	 differently.
+
+         For the 'if' token we need to capture the entire condition
+         string, so record the start of the condition string and then
+         start scanning backwards looking for the end of the condition
+         string.  */
+      if (direction == parse_direction::forward && t.length () > 0
+	  && t.matches ("if"))
+	{
+	  cond_start = v.start ();
+	  tok = tok + strlen (tok);
+	  gdb_assert (*tok == '\0');
+	  --tok;
+	  direction = parse_direction::backward;
+	  continue;
+	}
+      else if (t.length () > 0 && t.matches ("thread"))
+	{
+	  const char *tmptok;
+	  struct thread_info *thr;
+
+	  if (*thread != -1)
+	    error(_("You can specify only one thread."));
+
+	  if (*task != -1 || *inferior != -1)
+	    error (_("You can specify only one of thread, inferior, or task."));
+
+	  thr = parse_thread_id (v.start (), &tmptok);
+	  const char *expected_end = skip_spaces (v.end () + 1);
+	  if (tmptok != expected_end)
+	    error (_("Junk after thread keyword."));
+	  *thread = thr->global_num;
+	}
+      else if (t.length () > 0 && t.matches ("inferior"))
+	{
+	  char *tmptok;
+
+	  if (*inferior != -1)
+	    error(_("You can specify only one inferior."));
+
+	  if (*task != -1 || *thread != -1)
+	    error (_("You can specify only one of thread, inferior, or task."));
+
+	  *inferior = strtol (v.start (), &tmptok, 0);
+	  const char *expected_end = v.end () + 1;
+	  if (tmptok != expected_end)
+	    error (_("Junk after inferior keyword."));
+	}
+      else if (t.length () > 0 && t.matches ("task"))
+	{
+	  char *tmptok;
+
+	  if (*task != -1)
+	    error(_("You can specify only one task."));
+
+	  if (*thread != -1 || *inferior != -1)
+	    error (_("You can specify only one of thread, inferior, or task."));
+
+	  *task = strtol (v.start (), &tmptok, 0);
+	  const char *expected_end = v.end () + 1;
+	  if (tmptok != expected_end)
+	    error (_("Junk after task keyword."));
+	  if (!valid_task_id (*task))
+	    error (_("Unknown task %d."), *task);
+	}
+      else
+	{
+	  /* An unknown token.  If we are scanning forward then reset TOK
+	     to point at the start of the unknown content, we record this
+	     outside of the scanning loop (below).
+
+	     If we are scanning backward then unknown content is assumed to
+	     be the other end of the condition string, obviously, this is
+	     just a heuristic, we could be looking at a mistyped command
+	     line, but this will be spotted when the condition is
+	     eventually evaluated.
+
+	     Either way, no more scanning is required after this.  */
+	  if (direction == parse_direction::forward)
+	    tok = t.start ();
+	  else
+	    {
+	      gdb_assert (direction == parse_direction::backward);
+	      cond_end = v.end () + 1;
+	    }
+	  break;
+	}
+    }
+
+  if (cond_start != nullptr)
+    {
+      /* If we found the start of a condition string then we should have
+	 switched to backward scan mode, and found the end of the condition
+	 string.  Capture the whole condition string into COND_STRING now.  */
+      gdb_assert (direction == parse_direction::backward);
+      gdb_assert (cond_end != nullptr);
+      cond_string->reset (savestring (cond_start, cond_end - cond_start));
+    }
+  else if (*tok != '\0')
+    {
+      /* If we didn't have a condition start pointer then we should still
+	 be in forward scanning mode.  If we didn't reach the end of the
+	 input string (TOK is not at the null character) then the rest of
+	 the input string is garbage that we didn't understand.
+
+	 Record the unknown content into REST.  The caller of this function
+	 will report this as an error later on.  We could report the error
+	 here, but we prefer to allow the caller to run other checks, and
+	 prioritise other errors before reporting this problem.  */
+      gdb_assert (direction == parse_direction::forward);
+      rest->reset (savestring (tok, strlen (tok)));
+    }
+}
+
+#if GDB_SELF_TEST
+
+namespace selftests {
+
+/* Run a single test of the create_breakpoint_parse_arg_string function.
+   INPUT is passed to create_breakpoint_parse_arg_string while all other
+   arguments are the expected output from
+   create_breakpoint_parse_arg_string.  */
+
+static void
+test (const char *input, const char *condition, int thread = -1,
+      int inferior = -1, int task = -1, bool force = false,
+      const char *rest = nullptr)
+{
+  gdb::unique_xmalloc_ptr<char> extracted_condition;
+  gdb::unique_xmalloc_ptr<char> extracted_rest;
+  int extracted_thread, extracted_inferior, extracted_task;
+  bool extracted_force_condition;
+  std::string exception_msg;
+
+  try
+    {
+      create_breakpoint_parse_arg_string (input, &extracted_condition,
+					  &extracted_thread,
+					  &extracted_inferior,
+					  &extracted_task, &extracted_rest,
+					  &extracted_force_condition);
+    }
+  catch (const gdb_exception_error &ex)
+    {
+      string_file buf;
+
+      exception_print (&buf, ex);
+      exception_msg = buf.release ();
+    }
+
+  if ((condition == nullptr) != (extracted_condition.get () == nullptr)
+      || (condition != nullptr
+	  && strcmp (condition, extracted_condition.get ()) != 0)
+      || (rest == nullptr) != (extracted_rest.get () == nullptr)
+      || (rest != nullptr && strcmp (rest, extracted_rest.get ()) != 0)
+      || thread != extracted_thread
+      || inferior != extracted_inferior
+      || task != extracted_task
+      || force != extracted_force_condition
+      || !exception_msg.empty ())
+    {
+      if (run_verbose ())
+	{
+	  debug_printf ("input: '%s'\n", input);
+	  debug_printf ("condition: '%s'\n", extracted_condition.get ());
+	  debug_printf ("rest: '%s'\n", extracted_rest.get ());
+	  debug_printf ("thread: %d\n", extracted_thread);
+	  debug_printf ("inferior: %d\n", extracted_inferior);
+	  debug_printf ("task: %d\n", extracted_task);
+	  debug_printf ("forced: %s\n",
+			extracted_force_condition ? "true" : "false");
+	  debug_printf ("exception: '%s'\n", exception_msg.c_str ());
+	}
+
+      /* Report the failure.  */
+      SELF_CHECK (false);
+    }
+}
+
+/* Test the create_breakpoint_parse_arg_string function.  Just wraps
+   multiple calls to the test function above.  */
+
+static void
+create_breakpoint_parse_arg_string_tests (void)
+{
+  gdbarch *arch = current_inferior ()->gdbarch;
+  scoped_restore_current_pspace_and_thread restore;
+  scoped_mock_context<test_target_ops> mock_target (arch);
+
+  int global_thread_num = mock_target.mock_thread.global_num;
+
+  test ("  if blah  ", "blah");
+  test (" if blah thread 1", "blah", global_thread_num);
+  test (" if blah inferior 1", "blah", -1, 1);
+  test (" if blah thread 1  ", "blah", global_thread_num);
+  test ("thread 1 woof", nullptr, global_thread_num, -1, -1, false, "woof");
+  test ("thread 1 X", nullptr, global_thread_num, -1, -1, false, "X");
+  test (" if blah thread 1 -force-condition", "blah", global_thread_num,
+	-1, -1, true);
+  test (" -force-condition if blah thread 1", "blah", global_thread_num,
+	-1, -1, true);
+  test (" -force-condition if blah thread 1  ", "blah", global_thread_num,
+	-1, -1, true);
+  test ("thread 1 -force-condition if blah", "blah", global_thread_num,
+	-1, -1, true);
+  test ("if (A::outer::func ())", "(A::outer::func ())");
+}
+
+} // namespace selftests
+#endif /* GDB_SELF_TEST */
+
+void _initialize_break_cond_parse ();
+void
+_initialize_break_cond_parse ()
+{
+#if GDB_SELF_TEST
+  selftests::register_test
+    ("create_breakpoint_parse_arg_string",
+     selftests::create_breakpoint_parse_arg_string_tests);
+#endif
+}
diff --git a/gdb/break-cond-parse.h b/gdb/break-cond-parse.h
new file mode 100644
index 00000000000..b08b6fc6cc9
--- /dev/null
+++ b/gdb/break-cond-parse.h
@@ -0,0 +1,49 @@
+/* Copyright (C) 2023 Free Software Foundation, Inc.
+
+   This file is part of GDB.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#if !defined (BREAK_COND_PARSE_H)
+#define BREAK_COND_PARSE_H 1
+
+/* Given TOK, a string possibly containing a condition, thread, inferior,
+   task and force-condition flag, as accepted by the 'break' command,
+   extract the condition string, thread, inferior, task number, and the
+   force_condition flag, then set *COND_STRING, *THREAD, *INFERIOR, *TASK,
+   and *FORCE.
+
+   As TOK is parsed, if an unknown keyword is encountered before the 'if'
+   keyword then everything starting from the unknown keyword is placed into
+   *REST.
+
+   Both *COND and *REST are initialized to nullptr.  If no 'if' keyword is
+   found then *COND will be returned as nullptr.  If no unknown content is
+   found then *REST is returned as nullptr.
+
+   If no thread is found, *THREAD is set to -1.  If no inferior is found,
+   *INFERIOR is set to -1.  If no task is found, *TASK is set to -1.  If
+   the -force-condition flag is not found then *FORCE is set to false.
+
+   Due to the free-form nature that the string TOK might take (a 'thread'
+   keyword can appear before or after an 'if' condition) then we end up
+   having to check for keywords from both the start of TOK and the end of
+   TOK.  */
+
+extern void create_breakpoint_parse_arg_string
+  (const char *tok, gdb::unique_xmalloc_ptr<char> *cond_string,
+   int *thread, int *inferior, int *task,
+   gdb::unique_xmalloc_ptr<char> *rest, bool *force);
+
+#endif
diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 5a608ba2495..50225f55522 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -70,6 +70,7 @@
 #include "cli/cli-style.h"
 #include "cli/cli-decode.h"
 #include <unordered_set>
+#include "break-cond-parse.h"
 
 /* readline include files */
 #include "readline/tilde.h"
@@ -6340,20 +6341,7 @@ print_breakpoint_location (const breakpoint *b, const bp_location *loc)
       uiout->field_stream ("at", stb);
     }
   else
-    {
-      uiout->field_string ("pending", b->locspec->to_string ());
-      /* If extra_string is available, it could be holding a condition
-	 or dprintf arguments.  In either case, make sure it is printed,
-	 too, but only for non-MI streams.  */
-      if (!uiout->is_mi_like_p () && b->extra_string != NULL)
-	{
-	  if (b->type == bp_dprintf)
-	    uiout->text (",");
-	  else
-	    uiout->text (" ");
-	  uiout->text (b->extra_string.get ());
-	}
-    }
+    uiout->field_string ("pending", b->locspec->to_string ());
 
   if (loc && is_breakpoint (b)
       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
@@ -8718,8 +8706,8 @@ code_breakpoint::code_breakpoint (struct gdbarch *gdbarch_,
       gdb_assert (extra_string != nullptr);
       update_dprintf_command_list (this);
     }
-  else if (extra_string != nullptr)
-    error (_("Garbage '%s' at end of command"), extra_string.get ());
+  else
+    gdb_assert (extra_string == nullptr);
 
   /* The order of the locations is now stable.  Set the location
      condition using the location's number.  */
@@ -8947,197 +8935,6 @@ check_fast_tracepoint_sals (struct gdbarch *gdbarch,
     }
 }
 
-/* Given TOK, a string specification of condition and thread, as accepted
-   by the 'break' command, extract the condition string into *COND_STRING.
-   If no condition string is found then *COND_STRING is set to nullptr.
-
-   If the breakpoint specification has an associated thread, task, or
-   inferior, these are extracted into *THREAD, *TASK, and *INFERIOR
-   respectively, otherwise these arguments are set to -1 (for THREAD and
-   INFERIOR) or 0 (for TASK).
-
-   PC identifies the context at which the condition should be parsed.  */
-
-static void
-find_condition_and_thread (const char *tok, CORE_ADDR pc,
-			   gdb::unique_xmalloc_ptr<char> *cond_string,
-			   int *thread, int *inferior, int *task,
-			   gdb::unique_xmalloc_ptr<char> *rest)
-{
-  cond_string->reset ();
-  *thread = -1;
-  *inferior = -1;
-  *task = -1;
-  rest->reset ();
-  bool force = false;
-
-  while (tok && *tok)
-    {
-      const char *end_tok;
-      int toklen;
-      const char *cond_start = NULL;
-      const char *cond_end = NULL;
-
-      tok = skip_spaces (tok);
-
-      if ((*tok == '"' || *tok == ',') && rest)
-	{
-	  rest->reset (savestring (tok, strlen (tok)));
-	  break;
-	}
-
-      end_tok = skip_to_space (tok);
-
-      toklen = end_tok - tok;
-
-      if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
-	{
-	  tok = cond_start = end_tok + 1;
-	  try
-	    {
-	      parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
-	    }
-	  catch (const gdb_exception_error &)
-	    {
-	      if (!force)
-		throw;
-	      else
-		tok = tok + strlen (tok);
-	    }
-	  cond_end = tok;
-	  cond_string->reset (savestring (cond_start, cond_end - cond_start));
-	}
-      else if (toklen >= 1 && strncmp (tok, "-force-condition", toklen) == 0)
-	{
-	  tok = tok + toklen;
-	  force = true;
-	}
-      else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
-	{
-	  const char *tmptok;
-	  struct thread_info *thr;
-
-	  if (*thread != -1)
-	    error(_("You can specify only one thread."));
-
-	  if (*task != -1)
-	    error (_("You can specify only one of thread or task."));
-
-	  if (*inferior != -1)
-	    error (_("You can specify only one of inferior or thread."));
-
-	  tok = end_tok + 1;
-	  thr = parse_thread_id (tok, &tmptok);
-	  if (tok == tmptok)
-	    error (_("Junk after thread keyword."));
-	  *thread = thr->global_num;
-	  tok = tmptok;
-	}
-      else if (toklen >= 1 && strncmp (tok, "inferior", toklen) == 0)
-	{
-	  if (*inferior != -1)
-	    error(_("You can specify only one inferior."));
-
-	  if (*task != -1)
-	    error (_("You can specify only one of inferior or task."));
-
-	  if (*thread != -1)
-	    error (_("You can specify only one of inferior or thread."));
-
-	  char *tmptok;
-	  tok = end_tok + 1;
-	  *inferior = strtol (tok, &tmptok, 0);
-	  if (tok == tmptok)
-	    error (_("Junk after inferior keyword."));
-	  if (!valid_global_inferior_id (*inferior))
-	    error (_("Unknown inferior number %d."), *inferior);
-	  tok = tmptok;
-	}
-      else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
-	{
-	  char *tmptok;
-
-	  if (*task != -1)
-	    error(_("You can specify only one task."));
-
-	  if (*thread != -1)
-	    error (_("You can specify only one of thread or task."));
-
-	  if (*inferior != -1)
-	    error (_("You can specify only one of inferior or task."));
-
-	  tok = end_tok + 1;
-	  *task = strtol (tok, &tmptok, 0);
-	  if (tok == tmptok)
-	    error (_("Junk after task keyword."));
-	  if (!valid_task_id (*task))
-	    error (_("Unknown task %d."), *task);
-	  tok = tmptok;
-	}
-      else if (rest)
-	{
-	  rest->reset (savestring (tok, strlen (tok)));
-	  break;
-	}
-      else
-	error (_("Junk at end of arguments."));
-    }
-}
-
-/* Call 'find_condition_and_thread' for each sal in SALS until a parse
-   succeeds.  The parsed values are written to COND_STRING, THREAD,
-   TASK, and REST.  See the comment of 'find_condition_and_thread'
-   for the description of these parameters and INPUT.  */
-
-static void
-find_condition_and_thread_for_sals (const std::vector<symtab_and_line> &sals,
-				    const char *input,
-				    gdb::unique_xmalloc_ptr<char> *cond_string,
-				    int *thread, int *inferior, int *task,
-				    gdb::unique_xmalloc_ptr<char> *rest)
-{
-  int num_failures = 0;
-  for (auto &sal : sals)
-    {
-      gdb::unique_xmalloc_ptr<char> cond;
-      int thread_id = -1;
-      int inferior_id = -1;
-      int task_id = -1;
-      gdb::unique_xmalloc_ptr<char> remaining;
-
-      /* Here we want to parse 'arg' to separate condition from thread
-	 number.  But because parsing happens in a context and the
-	 contexts of sals might be different, try each until there is
-	 success.  Finding one successful parse is sufficient for our
-	 goal.  When setting the breakpoint we'll re-parse the
-	 condition in the context of each sal.  */
-      try
-	{
-	  find_condition_and_thread (input, sal.pc, &cond, &thread_id,
-				     &inferior_id, &task_id, &remaining);
-	  *cond_string = std::move (cond);
-	  /* A value of -1 indicates that these fields are unset.  At most
-	     one of these fields should be set (to a value other than -1)
-	     at this point.  */
-	  gdb_assert (((thread_id == -1 ? 1 : 0)
-		       + (task_id == -1 ? 1 : 0)
-		       + (inferior_id == -1 ? 1 : 0)) >= 2);
-	  *thread = thread_id;
-	  *inferior = inferior_id;
-	  *task = task_id;
-	  *rest = std::move (remaining);
-	  break;
-	}
-      catch (const gdb_exception_error &e)
-	{
-	  num_failures++;
-	  /* If no sal remains, do not continue.  */
-	  if (num_failures == sals.size ())
-	    throw;
-	}
-    }
-}
-
 /* Decode a static tracepoint marker spec.  */
 
 static std::vector<symtab_and_line>
@@ -9255,6 +9052,46 @@ create_breakpoint (struct gdbarch *gdbarch,
 	      || (type_wanted != bp_dprintf
 		  && (extra_string == nullptr || parse_extra)));
 
+  /* Will hold either copies of the similarly named function argument, or
+     will hold a modified version of the function argument, depending on
+     the value of PARSE_EXTRA.  */
+  gdb::unique_xmalloc_ptr<char> cond_string_copy;
+  gdb::unique_xmalloc_ptr<char> extra_string_copy;
+
+  if (parse_extra)
+    {
+      /* Parse EXTRA_STRING splitting the parts out.  */
+      create_breakpoint_parse_arg_string (extra_string, &cond_string_copy,
+					  &thread, &inferior, &task,
+					  &extra_string_copy,
+					  &force_condition);
+
+      /* We could check that EXTRA_STRING_COPY is empty at this point -- it
+	 should be, as we only get here for things that are not bp_dprintf,
+	 however, we prefer to give the location spec parser a chance to
+	 run first, this means the user will get errors about invalid
+	 location spec instead of an error about garbage at the end of the
+	 command line.
+
+	 We still do the EXTRA_STRING_COPY is empty check, just later in
+	 this function.  */
+
+      gdb_assert (thread == -1 || thread > 0);
+      gdb_assert (task == -1 || task > 0);
+      gdb_assert (inferior == -1 || inferior > 0);
+    }
+  else
+    {
+      if (cond_string != nullptr)
+	cond_string_copy.reset (xstrdup (cond_string));
+      if (extra_string != nullptr)
+	extra_string_copy.reset (xstrdup (extra_string));
+    }
+
+  /* Clear these.  Updated values are now held in the *_copy locals.  */
+  cond_string = nullptr;
+  extra_string = nullptr;
+
   try
     {
       ops->create_sals_from_location_spec (locspec, &canonical);
@@ -9290,6 +9127,13 @@ create_breakpoint (struct gdbarch *gdbarch,
 	throw;
     }
 
+  /* The only bp_dprintf should have anything in EXTRA_STRING_COPY by this
+     point.  For all other breakpoints this indicates an error.  We could
+     place this check earlier in the function, but we prefer to see errors
+     from the location spec parser before we see this error message.  */
+  if (type_wanted != bp_dprintf && extra_string_copy.get () != nullptr)
+    error (_("Garbage '%s' at end of command"), extra_string_copy.get ());
+
   if (!pending && canonical.lsals.empty ())
     return 0;
 
@@ -9313,63 +9157,31 @@ create_breakpoint (struct gdbarch *gdbarch,
      breakpoint.  */
   if (!pending)
     {
-      gdb::unique_xmalloc_ptr<char> cond_string_copy;
-      gdb::unique_xmalloc_ptr<char> extra_string_copy;
-
-      if (parse_extra)
+      /* Check the validity of the condition.  We should error out if the
+	 condition is invalid at all of the locations and if it is not
+	 forced.  In the PARSE_EXTRA case above, this check is done when
+	 parsing the EXTRA_STRING.  */
+      if (cond_string_copy.get () != nullptr && !force_condition)
 	{
-	  gdb_assert (type_wanted != bp_dprintf);
-
-	  gdb::unique_xmalloc_ptr<char> rest;
-	  gdb::unique_xmalloc_ptr<char> cond;
-
-	  const linespec_sals &lsal = canonical.lsals[0];
-
-	  find_condition_and_thread_for_sals (lsal.sals, extra_string,
-					      &cond, &thread, &inferior,
-					      &task, &rest);
-
-	  if (rest.get () != nullptr && *(rest.get ()) != '\0')
-	    error (_("Garbage '%s' at end of command"), rest.get ());
-
-	  cond_string_copy = std::move (cond);
-	  extra_string_copy = std::move (rest);
-	}
-      else
-	{
-	  /* Check the validity of the condition.  We should error out
-	     if the condition is invalid at all of the locations and
-	     if it is not forced.  In the PARSE_EXTRA case above, this
-	     check is done when parsing the EXTRA_STRING.  */
-	  if (cond_string != nullptr && !force_condition)
+	  int num_failures = 0;
+          const linespec_sals &lsal = canonical.lsals[0];
+	  for (const auto &sal : lsal.sals)
 	    {
-	      int num_failures = 0;
-	      const linespec_sals &lsal = canonical.lsals[0];
-	      for (const auto &sal : lsal.sals)
+	      const char *cond = cond_string_copy.get ();
+	      try
 		{
-		  const char *cond = cond_string;
-		  try
-		    {
-		      parse_exp_1 (&cond, sal.pc, block_for_pc (sal.pc), 0);
-		      /* One success is sufficient to keep going.  */
-		      break;
-		    }
-		  catch (const gdb_exception_error &)
-		    {
-		      num_failures++;
-		      /* If this is the last sal, error out.  */
-		      if (num_failures == lsal.sals.size ())
-			throw;
-		    }
+		  parse_exp_1 (&cond, sal.pc, block_for_pc (sal.pc), 0);
+		  /* One success is sufficient to keep going.  */
+		  break;
+		}
+	      catch (const gdb_exception_error &)
+		{
+		  num_failures++;
+		  /* If this is the last sal, error out.  */
+		  if (num_failures == lsal.sals.size ())
+		    throw;
 		}
 	    }
-
-	  /* Create a private copy of condition string.  */
-	  if (cond_string)
-	    cond_string_copy.reset (xstrdup (cond_string));
-	  /* Create a private copy of any extra string.  */
-	  if (extra_string)
-	    extra_string_copy.reset (xstrdup (extra_string));
 	}
 
       ops->create_breakpoints_sal (gdbarch, &canonical,
@@ -9386,21 +9198,16 @@ create_breakpoint (struct gdbarch *gdbarch,
 								 type_wanted);
       b->locspec = locspec->clone ();
 
-      if (parse_extra)
-	b->cond_string = NULL;
-      else
-	{
-	  /* Create a private copy of condition string.  */
-	  b->cond_string.reset (cond_string != NULL
-				? xstrdup (cond_string)
-				: NULL);
-	  b->thread = thread;
-	}
+      /* Create a private copy of the condition string.  */
+      b->cond_string = std::move (cond_string_copy);
+
+      b->thread = thread;
+      b->task = task;
+      b->inferior = inferior;
 
       /* Create a private copy of any extra string.  */
-      b->extra_string.reset (extra_string != NULL
-			     ? xstrdup (extra_string)
-			     : NULL);
+      b->extra_string = std::move (extra_string_copy);
+
       b->ignore_count = ignore_count;
       b->disposition = tempflag ? disp_del : disp_donttouch;
       b->condition_not_parsed = 1;
@@ -9409,9 +9216,12 @@ create_breakpoint (struct gdbarch *gdbarch,
 	   && type_wanted != bp_hardware_breakpoint) || thread != -1)
 	b->pspace = current_program_space;
 
+      if (b->type == bp_dprintf)
+	update_dprintf_command_list (b.get ());
+
       install_breakpoint (internal, std::move (b), 0);
     }
-  
+
   if (canonical.lsals.size () > 1)
     {
       warning (_("Multiple breakpoints were set.\nUse the "
@@ -13145,24 +12955,6 @@ code_breakpoint::location_spec_to_sals (location_spec *locspec,
     {
       for (auto &sal : sals)
 	resolve_sal_pc (&sal);
-      if (condition_not_parsed && extra_string != NULL)
-	{
-	  gdb::unique_xmalloc_ptr<char> local_cond, local_extra;
-	  int local_thread, local_task, local_inferior;
-
-	  find_condition_and_thread_for_sals (sals, extra_string.get (),
-					      &local_cond, &local_thread,
-					      &local_inferior,
-					      &local_task, &local_extra);
-	  gdb_assert (cond_string == nullptr);
-	  if (local_cond != nullptr)
-	    cond_string = std::move (local_cond);
-	  thread = local_thread;
-	  task = local_task;
-	  if (local_extra != nullptr)
-	    extra_string = std::move (local_extra);
-	  condition_not_parsed = 0;
-	}
 
       if (type == bp_static_tracepoint)
 	sals[0] = update_static_tracepoint (this, sals[0]);
diff --git a/gdb/testsuite/gdb.ada/tasks.exp b/gdb/testsuite/gdb.ada/tasks.exp
index 603d43f7c36..337ee1b6f07 100644
--- a/gdb/testsuite/gdb.ada/tasks.exp
+++ b/gdb/testsuite/gdb.ada/tasks.exp
@@ -55,11 +55,11 @@ gdb_test "watch j task 1 task 3" "You can specify only one task\\."
 
 # Check that attempting to combine 'task' and 'thread' gives an error.
 gdb_test "break break_me task 1 thread 1" \
-    "You can specify only one of thread or task\\."
+    "You can specify only one of thread, inferior, or task\\."
 gdb_test "break break_me thread 1 task 1" \
-    "You can specify only one of thread or task\\."
+    "You can specify only one of thread, inferior, or task\\."
 gdb_test "break break_me inferior 1 task 1" \
-    "You can specify only one of inferior or task\\."
+    "You can specify only one of thread, inferior, or task\\."
 gdb_test "watch j task 1 thread 1" \
     "You can specify only one of thread or task\\."
 gdb_test "watch j thread 1 task 1" \
diff --git a/gdb/testsuite/gdb.base/condbreak.exp b/gdb/testsuite/gdb.base/condbreak.exp
index a5b2a28701b..50ae82c3f32 100644
--- a/gdb/testsuite/gdb.base/condbreak.exp
+++ b/gdb/testsuite/gdb.base/condbreak.exp
@@ -179,6 +179,10 @@ gdb_test "break -q main if (1==1) thread 999" \
     "Unknown thread 999\\."
 gdb_test "break -q main thread 999 if (1==1)" \
     "Unknown thread 999\\."
+gdb_test "break -q main if (1==1) thread 999 -force-condition" \
+    "Unknown thread 999\\."
+gdb_test "break -q main thread 999 if (1==1) -force-condition" \
+    "Unknown thread 999\\."
 
 # Verify that both if and thread can be distinguished from a breakpoint
 # address expression.
@@ -186,20 +190,34 @@ gdb_test "break *main if (1==1) thread 999" \
     "Unknown thread 999\\."
 gdb_test "break *main thread 999 if (1==1)" \
     "Unknown thread 999\\."
+gdb_test "break *main if (1==1) thread 999 -force-condition" \
+    "Unknown thread 999\\."
+gdb_test "break *main thread 999 if (1==1) -force-condition" \
+    "Unknown thread 999\\."
 
 # Similarly for task.
 gdb_test "break *main if (1==1) task 999" \
     "Unknown task 999\\."
 gdb_test "break *main task 999 if (1==1)" \
     "Unknown task 999\\."
+gdb_test "break *main if (1==1) task 999 -force-condition" \
+    "Unknown task 999\\."
+gdb_test "break *main task 999 if (1==1) -force-condition" \
+    "Unknown task 999\\."
 
-# GDB accepts abbreviations for "thread" and "task".
+# GDB accepts abbreviations for "thread" and "task" and "-force-condition"
 gdb_test "break *main if (1==1) t 999" \
     "Unknown thread 999\\."
 gdb_test "break *main if (1==1) th 999" \
     "Unknown thread 999\\."
 gdb_test "break *main if (1==1) ta 999" \
     "Unknown task 999\\."
+gdb_test "break *main if (1==1) t 999 -force" \
+    "Unknown thread 999\\."
+gdb_test "break *main if (1==1) th 999 -force" \
+    "Unknown thread 999\\."
+gdb_test "break *main if (1==1) ta 999 -force" \
+    "Unknown task 999\\."
 
 set test "run until breakpoint at marker3"
 gdb_test_multiple "continue" $test {
diff --git a/gdb/testsuite/gdb.base/pending.exp b/gdb/testsuite/gdb.base/pending.exp
index d7d3735000a..645f63bdb16 100644
--- a/gdb/testsuite/gdb.base/pending.exp
+++ b/gdb/testsuite/gdb.base/pending.exp
@@ -170,7 +170,8 @@ gdb_test "info break" \
 \[\t \]+stop only if k == 1.*
 \[\t \]+print k.*
 \[0-9\]+\[\t \]+breakpoint     keep y.* in main at .*$srcfile:$mainline.*
-\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc if x > 3.*" \
+\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc.*
+\\s+stop only if x > 3.*" \
 "multiple pending breakpoints"
 
 
@@ -195,8 +196,10 @@ gdb_test "info break" \
 \[\t \]+stop only if k == 1.*
 \[\t \]+print k.*
 \[0-9\]+\[\t \]+breakpoint     keep y.* in main at .*$srcfile:$mainline.*
-\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc if x > 3.*
-\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp3_loc.*ignore next 2 hits.*" \
+\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc.*
+\\s+stop only if x > 3.*
+\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp3_loc.*
+\\s+ignore next 2 hits.*" \
 "multiple pending breakpoints 2"
 
 #
@@ -267,3 +270,17 @@ gdb_test "info break" \
 \[0-9\]+\[\t \]+breakpoint     keep y.* in main at .*$srcfile:$mainline.*
 \[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*imaginary.*" \
 "verify pending breakpoint after restart"
+
+# Test GDB's parsing of pending breakpoint thread and condition.
+
+gdb_test_no_output "set breakpoint pending on"
+gdb_test "break foo if (unknown_var && another_unknown_var) thread 1" \
+    "Breakpoint $decimal \\(foo\\) pending\\."
+set bpnum [get_integer_valueof "\$bpnum" "*INVALID" \
+	       "get number for foo breakpoint"]
+gdb_test "info breakpoints $bpnum" \
+    [multi_line \
+	 "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	 "\\s+stop only if \\(unknown_var && another_unknown_var\\)" \
+	 "\\s+stop only in thread 1"] \
+    "check pending breakpoint on foo"
diff --git a/gdb/testsuite/gdb.linespec/explicit.exp b/gdb/testsuite/gdb.linespec/explicit.exp
index 668002d9038..8cbefe204ec 100644
--- a/gdb/testsuite/gdb.linespec/explicit.exp
+++ b/gdb/testsuite/gdb.linespec/explicit.exp
@@ -575,7 +575,7 @@ namespace eval $testfile {
 	      allow-pending]} {
 	fail "set $tst"
     } else {
-	gdb_test "info break" ".*PENDING.*myfunction if foofoofoo == 1.*" $tst
+	gdb_test "info break" ".*PENDING.*myfunction\r\n\\s+stop only if foofoofoo == 1.*" $tst
     }
 
     gdb_exit
@@ -586,7 +586,7 @@ namespace eval $testfile {
 	      allow-pending]} {
 	fail "set $tst"
     } else {
-	gdb_test "info break" ".*PENDING.*myfunction if arg == 0" $tst
+	gdb_test "info break" ".*PENDING.*myfunction\r\n\\s+stop only if arg == 0" $tst
 
 	gdb_load [standard_output_file $exefile]
 	gdb_test "info break" \
diff --git a/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp b/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp
index 28f52938aeb..bb9987a5572 100644
--- a/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp
+++ b/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp
@@ -50,7 +50,8 @@ set bp_location1 [gdb_get_line_number "set breakpoint 1 here"]
 # Set pending dprintf via MI.
 set bp [mi_make_breakpoint_pending -number "1" -type "dprintf" \
 	    -disp "keep" -enabled "y" -pending "pendfunc1" \
-	    -original-location "pendfunc1"]
+	    -original-location "pendfunc1" \
+	    -script {\["printf \\\"hello\\\""\]}]
 mi_gdb_test "-dprintf-insert -f pendfunc1 \"hello\"" \
     ".*\\^done,$bp" "mi set dprintf"
 
diff --git a/gdb/testsuite/gdb.multi/inferior-specific-bp.exp b/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
index 1f6573268da..b8aceabcad6 100644
--- a/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
+++ b/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
@@ -51,9 +51,9 @@ if {![runto_main]} {
 # this should fail.  Try with the keywords in both orders just in case the
 # parser has a bug.
 gdb_test "break foo thread 1.1 inferior 1" \
-    "You can specify only one of inferior or thread\\."
+    "You can specify only one of thread, inferior, or task\\."
 gdb_test "break foo inferior 1 thread 1.1" \
-    "You can specify only one of inferior or thread\\."
+    "You can specify only one of thread, inferior, or task\\."
 
 # Try to create a breakpoint using the 'inferior' keyword multiple times.
 gdb_test "break foo inferior 1 inferior 2" \
diff --git a/gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c b/gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
new file mode 100644
index 00000000000..15d1b9833dd
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
@@ -0,0 +1,22 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+int global_var = 0;
+
+void
+foo (int arg)
+{
+  global_var = arg;
+}
diff --git a/gdb/testsuite/gdb.threads/del-pending-thread-bp.c b/gdb/testsuite/gdb.threads/del-pending-thread-bp.c
new file mode 100644
index 00000000000..938e05bc4d7
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/del-pending-thread-bp.c
@@ -0,0 +1,85 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#include <dlfcn.h>
+#include <pthread.h>
+#include <stdlib.h>
+
+pthread_barrier_t barrier;
+
+static void
+barrier_wait (pthread_barrier_t *b)
+{
+  int res = pthread_barrier_wait (b);
+  if (res != 0 && res != PTHREAD_BARRIER_SERIAL_THREAD)
+    abort ();
+}
+
+static void *
+thread_worker (void *arg)
+{
+  barrier_wait (&barrier);
+  return NULL;
+}
+
+void
+breakpt ()
+{
+  /* Nothing.  */
+}
+
+int
+main (void)
+{
+  void *handle;
+  void (*func)(int);
+  pthread_t thread;
+
+  if (pthread_barrier_init (&barrier, NULL, 2) != 0)
+    abort ();
+
+  if (pthread_create (&thread, NULL, thread_worker, NULL) != 0)
+    abort ();
+
+  breakpt ();
+
+  /* Allow the worker thread to complete.  */
+  barrier_wait (&barrier);
+
+  if (pthread_join (thread, NULL) != 0)
+    abort ();
+
+  breakpt ();
+
+  /* Now load the shared library.  */
+  handle = dlopen (SHLIB_NAME, RTLD_LAZY);
+  if (handle == NULL)
+    abort ();
+
+  /* Find the function symbol.  */
+  func = (void (*)(int)) dlsym (handle, "foo");
+
+  /* Call the library function.  */
+  func (1);
+
+  /* Unload the shared library.  */
+  if (dlclose (handle) != 0)
+    abort ();
+
+  breakpt ();
+
+  return 0;
+}
+
diff --git a/gdb/testsuite/gdb.threads/del-pending-thread-bp.exp b/gdb/testsuite/gdb.threads/del-pending-thread-bp.exp
new file mode 100644
index 00000000000..4ed05eaa42d
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/del-pending-thread-bp.exp
@@ -0,0 +1,108 @@
+# Copyright 2023 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+# This test checks that pending thread-specific breakpoints are
+# correctly deleted when the thread the breakpoint is for goes out of
+# scope.
+#
+# We also check that we can't create a pending thread-specific
+# breakpoint for a non-existent thread.
+
+require allow_shlib_tests
+
+standard_testfile
+
+set libname $testfile-lib
+set srcfile_lib $srcdir/$subdir/$libname.c
+set binfile_lib [standard_output_file $libname.so]
+
+if { [gdb_compile_shlib $srcfile_lib $binfile_lib {}] != "" } {
+    untested "failed to compile shared library 1"
+    return -1
+}
+
+set binfile_lib_target [gdb_download_shlib $binfile_lib]
+
+if { [prepare_for_testing "failed to prepare" $testfile $srcfile \
+	  [list debug \
+	       additional_flags=-DSHLIB_NAME=\"$binfile_lib_target\" \
+	       shlib_load pthreads]] } {
+    return -1
+}
+
+gdb_locate_shlib $binfile_lib
+
+if ![runto_main] {
+    return 0
+}
+
+# Run until we have two threads.
+gdb_breakpoint "breakpt"
+gdb_continue_to_breakpoint "first breakpt call"
+
+# Confirm that we have a thread '2'.
+gdb_test "info threads" "\r\n\\s+2\\s+\[^\r\n\]+"
+
+# Create a pending, thread-specific, breakpoint on 'foo'.
+gdb_breakpoint "foo thread 2" allow-pending
+set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+	       "get breakpoint number"]
+
+# Check we can't create a pending thread-specific breakpoint for a
+# non-existent thread.
+gdb_test "with breakpoint pending on -- break foo thread 99" \
+    "Unknown thread 99\\."
+
+# Continue to 'breakpt' again.  Don't use gdb_continue_to_breakpoint
+# as we are looking for the thread exited and breakpoint deleted
+# messages.
+set output [list "Continuing\\."]
+
+if {!([target_info exists gdb_protocol]
+      && ([target_info gdb_protocol] == "remote"
+	  || [target_info gdb_protocol] == "extended-remote"))} {
+    # Due to bug PR gdb/30129 we don't see the thread exited messages
+    # for remote targets.  When this bit of this test can be cleaned
+    # up.
+    lappend output "\\\[Thread \[^\r\n\]+ exited\\\]"
+}
+
+lappend output "Thread-specific breakpoint $bpnum deleted - thread 2 no longer in the thread list\\." \
+    "" \
+    "Thread 1 \[^\r\n\]+, breakpt \\(\\) at \[^\r\n\]+" \
+    "$decimal\\s+\[^\r\n\]+"
+
+gdb_test "continue" \
+    [multi_line {*}$output] \
+    "second breakpt call"
+
+# Confirm breakpoint has been deleted.
+gdb_test "info breakpoints $bpnum" \
+    "No breakpoint or watchpoint matching '$bpnum'\\."
+
+# Continue again.  This will pass through 'foo'.  We should not stop
+# in 'foo', the breakpoint has been deleted.  We should next stop in
+# breakpt again.
+gdb_test "continue" \
+    [multi_line \
+	 "Continuing\\." \
+	 "" \
+	 "Thread 1 \[^\r\n\]+ hit Breakpoint $decimal, breakpt \\(\\) at \[^\r\n\]+" \
+	 "$decimal\\s+\[^\r\n\]+"] \
+    "third breakpt call"
+gdb_test "bt 1" \
+    [multi_line \
+	 "#0\\s+breakpt \\(\\) at \[^\r\n\]+" \
+	 "\\(More stack frames follow\\.\\.\\.\\)"]
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv4 07/10] gdb: don't set breakpoint::pspace for in create_breakpoint
  2023-08-23 15:59     ` [PATCHv4 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
                         ` (5 preceding siblings ...)
  2023-08-23 15:59       ` [PATCHv4 06/10] gdb: parse pending breakpoint thread/task immediately Andrew Burgess
@ 2023-08-23 15:59       ` Andrew Burgess
  2023-08-23 15:59       ` [PATCHv4 08/10] gdb: remove breakpoint_re_set_one Andrew Burgess
                         ` (3 subsequent siblings)
  10 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-08-23 15:59 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

While working on the previous commit, I ran into this code within
create_breakpoint:

  if ((type_wanted != bp_breakpoint
      && type_wanted != bp_hardware_breakpoint) || thread != -1)
   b->pspace = current_program_space;

this code is only executed when creating a pending breakpoint, and
sets the breakpoint::pspace member variable.

The above code gained the 'thread != -1' clause with this commit:

  commit cc72b2a2da6d6372cbdb1d14639a5fce84e1a325
  Date:   Fri Dec 23 17:06:16 2011 +0000

              Introduce gdb.FinishBreakpoint in Python

While the type_wanted checks were added with this commit:

  commit f8eba3c61629b3c03ac1f33853eab4d8507adb9c
  Date:   Tue Dec 6 18:54:43 2011 +0000

      the "ambiguous linespec" series

Before this breakpoint::pspace was set unconditionally.

If we look at how breakpoint::pspace is used today, some breakpoint
types specifically set this field, either in their constructors, or in
a wrapper function that calls the constructor.  So, the watchpoint
type and its sub-class set this variable, as does the catchpoint type,
and all it's sub-classes.

However, code_breakpoint doesn't specifically set this field within
its constructor, though some sub-classes of
code_breakpoint (ada_catchpoint, exception_catchpoint,
internal_breakpoint, and momentary_breakpoint) do set this field.

When I examine all the places that breakpoint::pspace is used, I
believe that in every place where it is expected that this field is
set, the breakpoint type will be one that specifically sets this
field.

Next, I observe two problems with the existing code.

First, the above code is only hit for pending breakpoints, there's no
equivalent code for non-pending breakpoints.  This opens up the
possibility of GDB entering non-consistent states; if a breakpoint is
first created pending and then later gets a location, the pspace field
will be set, while if the breakpoint is immediately non-pending, then
the pspace field will never be set.

Second, if we look at how breakpoint::pspace is used in the function
breakpoint_program_space_exit, we see that when a program space is
removed, any breakpoint with breakpoint::pspace set to the removed
program space, will be deleted.  This makes sense, but does mean we
need to ensure breakpoint::pspace is only set for breakpoints that
apply to a single program space.

So, if I create pending dprintf breakpoint (type bp_dprintf) then the
breakpoint::pspace variable will be set even though the dprintf is not
really tied to that one program space.  As a result, when the matching
program space is removed the dprintf is incorrectly removed.

Also, if I create a thread specific breakpoint, then, thanks to the
'thread != -1' clause the wrong program space will be stored in
breakpoint::pspace (the current program space is always used, which
might not be the program space that corresponds to the selected
thread), as a result, the thread specific breakpoint will be deleted
when the matching program space is removed.

If we look at commit cc72b2a2da6d which added the 'thread != -1'
clause, we can see this change was entirely redundant, the
breakpoint::pspace is also set in bpfinishpy_init after
create_breakpoint has been called.  As such, I think we can safely
drop the 'thread != -1' clause.

For the other problems, I'm proposing to be pretty aggressive - I'd
like to drop the breakpoint::pspace assignment completely from
create_breakpoint.  Having looked at how this variable is used, I
believe that it is already set elsewhere in all the cases that it is
needed.  Maybe this code was needed at one time, but I can't see how
it's needed any more.

There's tests to expose the issues I've spotted with this code, and
there's no regressions in testing.
---
 gdb/breakpoint.c                              |   3 -
 gdb/breakpoint.h                              |  18 +-
 .../gdb.multi/pending-bp-del-inferior.c       |  28 +++
 .../gdb.multi/pending-bp-del-inferior.exp     | 216 ++++++++++++++++++
 4 files changed, 259 insertions(+), 6 deletions(-)
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-del-inferior.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 50225f55522..10af2fa3373 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -9212,9 +9212,6 @@ create_breakpoint (struct gdbarch *gdbarch,
       b->disposition = tempflag ? disp_del : disp_donttouch;
       b->condition_not_parsed = 1;
       b->enable_state = enabled ? bp_enabled : bp_disabled;
-      if ((type_wanted != bp_breakpoint
-	   && type_wanted != bp_hardware_breakpoint) || thread != -1)
-	b->pspace = current_program_space;
 
       if (b->type == bp_dprintf)
 	update_dprintf_command_list (b.get ());
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index 4b14bc95d63..a30bc5d2879 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -823,9 +823,21 @@ struct breakpoint : public intrusive_list_node<breakpoint>
      equals this.  */
   struct frame_id frame_id = null_frame_id;
 
-  /* The program space used to set the breakpoint.  This is only set
-     for breakpoints which are specific to a program space; for
-     non-thread-specific ordinary breakpoints this is NULL.  */
+  /* The program space used to set the breakpoint.  This is only set for
+     breakpoints that are not type bp_breakpoint or bp_hardware_breakpoint.
+     For thread or inferior specific breakpoints, the breakpoints are
+     managed via the thread and inferior member variables.  */
+
+  /* If not nullptr then this is the program space for which this
+     breakpoint was created.  All watchpoint and catchpoint sub-types set
+     this field, but not all of the code_breakpoint sub-types do;
+     generally, user created breakpoint types don't set this field, though
+     things might be more consistent if they did.
+
+     When this variable is nullptr then a breakpoint might be associated
+     with multiple program spaces, though you need to check the thread,
+     inferior and task variables to see if a breakpoint was created for a
+     specific thread, inferior, or Ada task respectively.  */
   program_space *pspace = NULL;
 
   /* The location specification we used to set the breakpoint.  */
diff --git a/gdb/testsuite/gdb.multi/pending-bp-del-inferior.c b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.c
new file mode 100644
index 00000000000..51b6492085f
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.c
@@ -0,0 +1,28 @@
+/* This testcase is part of GDB, the GNU debugger.
+
+   Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+int
+foo ()
+{
+  return 0;
+}
+
+int
+main ()
+{
+  return foo ();
+}
diff --git a/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
new file mode 100644
index 00000000000..cb1f119ff94
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
@@ -0,0 +1,216 @@
+# Copyright 2023 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+# Setup two inferiors.  Select one inferior and create a pending
+# thread specific breakpoint in the other inferior.
+#
+# Delete the selected inferior (the one for which the thread specific
+# breakpoint doesn't apply), and check that the breakpoint still exists.
+#
+# Repeat this process, but this time, create an inferior specific
+# breakpoint.
+
+# The plain remote target can't do multiple inferiors.
+require !use_gdb_stub
+
+standard_testfile
+
+if {[prepare_for_testing "failed to prepare" $testfile $srcfile]} {
+    return -1
+}
+
+# Setup for the tests.  Create two inferiors, both running the global
+# BINFILE, and proceed to main in both inferiors.  Delete all
+# breakpoints, and check that we do have two threads.
+#
+# Return true after a successful setup, otherwise, return false.
+proc test_setup {} {
+    clean_restart $::binfile
+
+    if {![runto_main]} {
+	return 0
+    }
+
+    gdb_test "add-inferior -exec ${::binfile}" "Added inferior 2.*" \
+	"add inferior 2"
+    gdb_test "inferior 2" "Switching to inferior 2 .*" \
+	"select inferior 2"
+
+    if {![runto_main]} {
+	return 0
+    }
+
+    delete_breakpoints
+
+    gdb_test "info threads" \
+	[multi_line \
+	     "  Id\\s+Target Id\\s+Frame\\s*" \
+	     "  1\\.1\\s+\[^\r\n\]+" \
+	     "\\* 2\\.1\\s+\[^\r\n\]+"] \
+	"check we have the expected threads"
+
+    return 1
+}
+
+# Assuming inferior 2 is already selected, kill the current inferior
+# (inferior 2), selected inferior 1, and then remove inferior 2.
+proc kill_and_remove_inferior_2 {} {
+    gdb_test "kill" "" "kill inferior 2" \
+	"Kill the program being debugged.*y or n. $" "y"
+
+    gdb_test "inferior 1" "Switching to inferior 1 .*" \
+	"select inferior 1"
+
+    gdb_test_no_output "remove-inferiors 2"
+}
+
+# Setup two inferiors, then created a breakpoint.  If BP_PENDING is
+# true then the breakpoint will be pending, otherwise, the breakpoint
+# will be non-pending.
+#
+# BP_TYPE is either 'thread' or 'inferior', and indicates if the
+# created breakpoint should be thread or inferior specific.
+#
+# The breakpoint is created while inferior 2 is selected, and the
+# thread/inferior restriction always identifies inferior 1.
+#
+# Then inferior 2 is killed and removed.
+#
+# Finally, check that the breakpoint still exists and correctly refers
+# to inferior 1.
+proc do_bp_test { bp_type bp_pending } {
+    if {![test_setup]} {
+	return
+    }
+
+    if { $bp_pending } {
+	set bp_func "bar"
+    } else {
+	set bp_func "foo"
+    }
+
+    if { $bp_type eq "thread" } {
+	set bp_restriction "thread 1.1"
+    } else {
+	set bp_restriction "inferior 1"
+    }
+
+    gdb_breakpoint "$bp_func $bp_restriction" allow-pending
+    set bp_number [get_integer_valueof "\$bpnum" "INVALID" \
+		       "get b/p number for previous breakpoint"]
+
+    if { $bp_restriction eq "thread 1.1" } {
+	set bp_after_restriction "thread 1"
+    } else {
+	set bp_after_restriction $bp_restriction
+    }
+
+    if { $bp_pending } {
+	set bp_pattern_before \
+	    [multi_line \
+		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+${bp_func}" \
+		 "\\s+stop only in [string_to_regexp $bp_restriction]"]
+	set bp_pattern_after \
+	    [multi_line \
+		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+${bp_func}" \
+		 "\\s+stop only in [string_to_regexp $bp_after_restriction]"]
+    } else {
+	set bp_pattern_before \
+	    [multi_line \
+		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+<MULTIPLE>\\s*" \
+		 "\\s+stop only in [string_to_regexp $bp_restriction]" \
+		 "$bp_number\\.1\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 1" \
+		 "$bp_number\\.2\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 2"]
+
+	set bp_pattern_after \
+	    [multi_line \
+		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+" \
+		 "\\s+stop only in [string_to_regexp $bp_after_restriction]"]
+    }
+
+    gdb_test "info breakpoints" $bp_pattern_before \
+	"info breakpoints before inferior removal"
+
+    kill_and_remove_inferior_2
+
+    gdb_test "info breakpoints" $bp_pattern_after \
+	"info breakpoints after inferior removal"
+}
+
+# Setup two inferiors, then created a dprintf.  If BP_PENDING is
+# true then the dprintf will be pending, otherwise, the dprintf
+# will be non-pending.
+#
+# The dprintf is created while inferior 2.  Then inferior 2 is killed
+# and removed.
+#
+# Finally, check that the dprintf still exists.
+proc do_dprintf_test { bp_pending } {
+    if {![test_setup]} {
+	return
+    }
+
+    if { $bp_pending } {
+	set bp_func "bar"
+
+	gdb_test "dprintf $bp_func,\"in $bp_func\"" ".*" \
+	    "create dprintf breakpoint" \
+	    "Make dprintf pending on future shared library load\\? \\(y or .n.\\) $" "y"
+    } else {
+	set bp_func "foo"
+
+	gdb_test "dprintf $bp_func,\"in $bp_func\"" ".*" \
+	    "create dprintf breakpoint"
+    }
+
+    set bp_number [get_integer_valueof "\$bpnum" "INVALID" \
+		       "get b/p number for previous breakpoint"]
+
+    if { $bp_pending } {
+	set bp_pattern_before \
+	    [multi_line \
+		 "$bp_number\\s+dprintf\\s+keep\\s+y\\s+<PENDING>\\s+${bp_func}" \
+		 "\\s+printf \"in $bp_func\""]
+	set bp_pattern_after $bp_pattern_before
+    } else {
+	set bp_pattern_before \
+	    [multi_line \
+		 "$bp_number\\s+dprintf\\s+keep\\s+y\\s+<MULTIPLE>\\s*" \
+		 "\\s+printf \"in $bp_func\"" \
+		 "$bp_number\\.1\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 1" \
+		 "$bp_number\\.2\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 2"]
+
+	set bp_pattern_after \
+	    [multi_line \
+		 "$bp_number\\s+dprintf\\s+keep\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+" \
+		 "\\s+printf \"in $bp_func\""]
+    }
+
+    gdb_test "info breakpoints" $bp_pattern_before \
+	"info breakpoints before inferior removal"
+
+    kill_and_remove_inferior_2
+
+    gdb_test "info breakpoints" $bp_pattern_after \
+	"info breakpoints after inferior removal"
+}
+
+foreach_with_prefix bp_pending { true false } {
+    foreach_with_prefix bp_type { thread inferior } {
+	do_bp_test $bp_type $bp_pending
+    }
+
+    do_dprintf_test $bp_pending
+}
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv4 08/10] gdb: remove breakpoint_re_set_one
  2023-08-23 15:59     ` [PATCHv4 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
                         ` (6 preceding siblings ...)
  2023-08-23 15:59       ` [PATCHv4 07/10] gdb: don't set breakpoint::pspace for in create_breakpoint Andrew Burgess
@ 2023-08-23 15:59       ` Andrew Burgess
  2023-08-23 15:59       ` [PATCHv4 09/10] gdb: remove tracepoint_probe_create_sals_from_location_spec Andrew Burgess
                         ` (2 subsequent siblings)
  10 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-08-23 15:59 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

During a later patch I wanted to reset a single breakpoint, so I
called breakpoint_re_set_one.  However, this is not the right thing to
do.  If we look at breakpoint_re_set then we see that there's a whole
bunch of state that needs to be preserved prior to calling
breakpoint_re_set_one, and after calling breakpoint_re_set_one we
still need to call update_global_location_list.

I could just update the comment on breakpoint_re_set_one to make it
clearer how the function should be used -- or more likely to warn that
the function should only be used as a helper from breakpoint_re_set.

However, breakpoint_re_set_one is only 3 lines long.  So I figure it
might actually be easier to just fold breakpoint_re_set_one into
breakpoint_re_set, then there's no risk of accidentally calling
breakpoint_re_set_one when we shouldn't.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c | 26 ++++++++------------------
 1 file changed, 8 insertions(+), 18 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 10af2fa3373..be2ef196f80 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -13003,17 +13003,6 @@ create_sals_from_location_spec_default (location_spec *locspec,
   parse_breakpoint_sals (locspec, canonical);
 }
 
-/* Reset a breakpoint.  */
-
-static void
-breakpoint_re_set_one (breakpoint *b)
-{
-  input_radix = b->input_radix;
-  set_language (b->language);
-
-  b->re_set ();
-}
-
 /* Re-set breakpoint locations for the current program space.
    Locations bound to other program spaces are left untouched.  */
 
@@ -13025,12 +13014,11 @@ breakpoint_re_set (void)
     scoped_restore save_input_radix = make_scoped_restore (&input_radix);
     scoped_restore_current_pspace_and_thread restore_pspace_thread;
 
-    /* breakpoint_re_set_one sets the current_language to the language
-       of the breakpoint it is resetting (see prepare_re_set_context)
-       before re-evaluating the breakpoint's location.  This change can
-       unfortunately get undone by accident if the language_mode is set
-       to auto, and we either switch frames, or more likely in this context,
-       we select the current frame.
+    /* To ::re_set each breakpoint we set the current_language to the
+       language of the breakpoint before re-evaluating the breakpoint's
+       location.  This change can unfortunately get undone by accident if
+       the language_mode is set to auto, and we either switch frames, or
+       more likely in this context, we select the current frame.
 
        We prevent this by temporarily turning the language_mode to
        language_mode_manual.  We restore it once all breakpoints
@@ -13047,7 +13035,9 @@ breakpoint_re_set (void)
       {
 	try
 	  {
-	    breakpoint_re_set_one (&b);
+	    input_radix = b.input_radix;
+	    set_language (b.language);
+	    b.re_set ();
 	  }
 	catch (const gdb_exception &ex)
 	  {
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv4 09/10] gdb: remove tracepoint_probe_create_sals_from_location_spec
  2023-08-23 15:59     ` [PATCHv4 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
                         ` (7 preceding siblings ...)
  2023-08-23 15:59       ` [PATCHv4 08/10] gdb: remove breakpoint_re_set_one Andrew Burgess
@ 2023-08-23 15:59       ` Andrew Burgess
  2023-08-23 15:59       ` [PATCHv4 10/10] gdb: only insert thread-specific breakpoints in the relevant inferior Andrew Burgess
  2023-10-03 21:29       ` [PATCHv5 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
  10 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-08-23 15:59 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

The tracepoint_probe_create_sals_from_location_spec function just
forwards all its arguments to
bkpt_probe_create_sals_from_location_spec, and is only used in one
place.

Lets delete tracepoint_probe_create_sals_from_location_spec and
replace it with bkpt_probe_create_sals_from_location_spec.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c | 19 +++----------------
 1 file changed, 3 insertions(+), 16 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index be2ef196f80..c6abb953ca5 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -284,9 +284,6 @@ static bool strace_marker_p (struct breakpoint *b);
 static void bkpt_probe_create_sals_from_location_spec
      (location_spec *locspec,
       struct linespec_result *canonical);
-static void tracepoint_probe_create_sals_from_location_spec
-     (location_spec *locspec,
-      struct linespec_result *canonical);
 
 const struct breakpoint_ops code_breakpoint_ops =
 {
@@ -301,10 +298,11 @@ static const struct breakpoint_ops bkpt_probe_breakpoint_ops =
   create_breakpoints_sal,
 };
 
-/* Tracepoints set on probes.  */
+/* Tracepoints set on probes.  We use the same methods as for breakpoints
+   on probes.  */
 static const struct breakpoint_ops tracepoint_probe_breakpoint_ops =
 {
-  tracepoint_probe_create_sals_from_location_spec,
+  bkpt_probe_create_sals_from_location_spec,
   create_breakpoints_sal,
 };
 
@@ -12211,17 +12209,6 @@ tracepoint::print_recreate (struct ui_file *fp) const
     gdb_printf (fp, "  passcount %d\n", pass_count);
 }
 
-/* Virtual table for tracepoints on static probes.  */
-
-static void
-tracepoint_probe_create_sals_from_location_spec
-  (location_spec *locspec,
-   struct linespec_result *canonical)
-{
-  /* We use the same method for breakpoint on probes.  */
-  bkpt_probe_create_sals_from_location_spec (locspec, canonical);
-}
-
 void
 dprintf_breakpoint::re_set ()
 {
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv4 10/10] gdb: only insert thread-specific breakpoints in the relevant inferior
  2023-08-23 15:59     ` [PATCHv4 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
                         ` (8 preceding siblings ...)
  2023-08-23 15:59       ` [PATCHv4 09/10] gdb: remove tracepoint_probe_create_sals_from_location_spec Andrew Burgess
@ 2023-08-23 15:59       ` Andrew Burgess
  2023-10-03 21:29       ` [PATCHv5 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
  10 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-08-23 15:59 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Eli Zaretskii

This commit updates GDB so that thread or inferior specific
breakpoints are only inserted into the program space in which the
specific thread or inferior is running.

In terms of implementation, getting this basically working is easy
enough, now that a breakpoint's thread or inferior field is setup
prior to GDB looking for locations, we can easily use this information
to find a suitable program_space and pass this to as a filter when
creating the sals.

Or we could if breakpoint_ops::create_sals_from_location_spec allowed
us to pass in a filter program_space.

So, this commit extends breakpoint_ops::create_sals_from_location_spec
to take a program_space argument, and uses this to filter the set of
returned sals.  This accounts for about half the change in this patch.

The second set of changes starts from breakpoint_set_thread and
breakpoint_set_inferior, this is called when the thread or inferior
for a breakpoint changes, e.g. from the Python API.

Previously this call would never result in the locations of a
breakpoint changing, after all, locations were inserted in every
program space, and we just use the thread or inferior variable to
decide when we should stop.  Now though, changing a breakpoint's
thread or inferior can mean we need to figure out a new set of
breakpoint locations.

To support this I've added a new breakpoint_re_set_one function, which
is like breakpoint_re_set, but takes a single breakpoint, and just
updates the locations for that one breakpoint.  We only need to call
this function if the program_space in which a breakpoint's thread (or
inferior) is running actually changes.  If the program_space does
change then we call the new breakpoint_re_set_one function passing in
the program_space which should be used to filter the new locations (or
nullptr to indicate we should set locations in all program spaces).
This filter program_space needs to propagate down to all the re_set
methods, this accounts for the remaining half of the changes in this
patch.

There were a couple of existing tests that created thread or inferior
specific breakpoints and then checked the 'info breakpoints' output,
these needed updating.  These were:

  gdb.mi/user-selected-context-sync.exp
  gdb.multi/bp-thread-specific.exp
  gdb.multi/multi-target-continue.exp
  gdb.multi/multi-target-ping-pong-next.exp
  gdb.multi/tids.exp
  gdb.mi/new-ui-bp-deleted.exp
  gdb.multi/inferior-specific-bp.exp
  gdb.multi/pending-bp-del-inferior.exp

I've also added some additional tests to:

  gdb.multi/pending-bp.exp

I've updated the documentation and added a NEWS entry.

Reviewed-By: Eli Zaretskii <eliz@gnu.org>
---
 gdb/NEWS                                      |   7 +
 gdb/ada-lang.c                                |   6 +-
 gdb/break-catch-throw.c                       |   6 +-
 gdb/breakpoint.c                              | 280 ++++++++++++++----
 gdb/breakpoint.h                              |  29 +-
 gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp    |   8 +-
 .../gdb.mi/user-selected-context-sync.exp     |   4 +-
 .../gdb.multi/bp-thread-specific.exp          |   7 +-
 .../gdb.multi/inferior-specific-bp.exp        |  12 +-
 .../gdb.multi/multi-target-continue.exp       |   2 +-
 .../gdb.multi/multi-target-ping-pong-next.exp |   4 +-
 .../gdb.multi/pending-bp-del-inferior.exp     |   6 +-
 gdb/testsuite/gdb.multi/pending-bp.exp        | 206 +++++++++++++
 gdb/testsuite/gdb.multi/tids.exp              |   6 +-
 14 files changed, 484 insertions(+), 99 deletions(-)

diff --git a/gdb/NEWS b/gdb/NEWS
index 7c38ecb8b46..e4b432c8bdb 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -109,6 +109,13 @@
   'thread' or 'task' keywords are parsed at the time the breakpoint is
   created, rather than at the time the breakpoint becomes non-pending.
 
+* Thread-specific breakpoints are only inserted into the program space
+  in which the thread of interest is running.  In most cases program
+  spaces are unique for each inferior, so this means that
+  thread-specific breakpoints will usually only be inserted for the
+  inferior containing the thread of interest.  The breakpoint will
+  be hit no less than before.
+
 * New commands
 
 set debug breakpoint on|off
diff --git a/gdb/ada-lang.c b/gdb/ada-lang.c
index 575568cffb5..c32c64a3fde 100644
--- a/gdb/ada-lang.c
+++ b/gdb/ada-lang.c
@@ -12061,11 +12061,11 @@ struct ada_catchpoint : public code_breakpoint
     enable_state = enabled ? bp_enabled : bp_disabled;
     language = language_ada;
 
-    re_set ();
+    re_set (pspace);
   }
 
   struct bp_location *allocate_location () override;
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   void check_status (struct bpstat *bs) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   bool print_one (const bp_location **) const override;
@@ -12110,7 +12110,7 @@ static struct symtab_and_line ada_exception_sal
    catchpoint kinds.  */
 
 void
-ada_catchpoint::re_set ()
+ada_catchpoint::re_set (program_space *pspace)
 {
   std::vector<symtab_and_line> sals;
   try
diff --git a/gdb/break-catch-throw.c b/gdb/break-catch-throw.c
index 47d534c5ee8..e661d1624e8 100644
--- a/gdb/break-catch-throw.c
+++ b/gdb/break-catch-throw.c
@@ -82,10 +82,10 @@ struct exception_catchpoint : public code_breakpoint
 				     _("invalid type-matching regexp")))
   {
     pspace = current_program_space;
-    re_set ();
+    re_set (pspace);
   }
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   bool print_one (const bp_location **) const override;
   void print_mention () const override;
@@ -198,7 +198,7 @@ exception_catchpoint::check_status (struct bpstat *bs)
 /* Implement the 're_set' method.  */
 
 void
-exception_catchpoint::re_set ()
+exception_catchpoint::re_set (program_space *pspace)
 {
   std::vector<symtab_and_line> sals;
   struct program_space *filter_pspace = current_program_space;
diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index c6abb953ca5..817efeb3b01 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -91,9 +91,12 @@
 static void map_breakpoint_numbers (const char *,
 				    gdb::function_view<void (breakpoint *)>);
 
-static void
-  create_sals_from_location_spec_default (location_spec *locspec,
-					  linespec_result *canonical);
+static void parse_breakpoint_sals (location_spec *locspec,
+				   linespec_result *canonical,
+				   program_space *search_pspace);
+
+static void breakpoint_re_set_one (breakpoint *b,
+				   program_space *filter_pspace);
 
 static void create_breakpoints_sal (struct gdbarch *,
 				    struct linespec_result *,
@@ -283,11 +286,12 @@ static bool strace_marker_p (struct breakpoint *b);
 
 static void bkpt_probe_create_sals_from_location_spec
      (location_spec *locspec,
-      struct linespec_result *canonical);
+      struct linespec_result *canonical,
+      struct program_space *search_pspace);
 
 const struct breakpoint_ops code_breakpoint_ops =
 {
-  create_sals_from_location_spec_default,
+  parse_breakpoint_sals,
   create_breakpoints_sal,
 };
 
@@ -352,7 +356,7 @@ struct internal_breakpoint : public code_breakpoint
     disposition = disp_donttouch;
   }
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   void check_status (struct bpstat *bs) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   void print_mention () const override;
@@ -389,7 +393,7 @@ struct momentary_breakpoint : public code_breakpoint
     gdb_assert (inferior == -1);
   }
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   void check_status (struct bpstat *bs) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   void print_mention () const override;
@@ -400,7 +404,7 @@ struct dprintf_breakpoint : public ordinary_breakpoint
 {
   using ordinary_breakpoint::ordinary_breakpoint;
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   int breakpoint_hit (const struct bp_location *bl,
 		      const address_space *aspace,
 		      CORE_ADDR bp_addr,
@@ -1554,7 +1558,36 @@ breakpoint_set_thread (struct breakpoint *b, int thread)
   int old_thread = b->thread;
   b->thread = thread;
   if (old_thread != thread)
-    notify_breakpoint_modified (b);
+    {
+      /* If THREAD is in a different program_space than OLD_THREAD, or the
+	 breakpoint has switched to or from being thread-specific, then we
+	 need to re-set the locations of this breakpoint.  First, figure
+	 out the program_space for the old and new threads, use a value of
+	 nullptr to indicate the breakpoint is in all program spaces.  */
+      program_space *old_pspace = nullptr;
+      if (old_thread != -1)
+	{
+	  struct thread_info *thr = find_thread_global_id (old_thread);
+	  gdb_assert (thr != nullptr);
+	  old_pspace = thr->inf->pspace;
+	}
+
+      program_space *new_pspace = nullptr;
+      if (thread != -1)
+	{
+	  struct thread_info *thr = find_thread_global_id (thread);
+	  gdb_assert (thr != nullptr);
+	  new_pspace = thr->inf->pspace;
+	}
+
+      /* If the program space has changed for this breakpoint, then
+	 re-evaluate it's locations.  */
+      if (old_pspace != new_pspace)
+	breakpoint_re_set_one (b, new_pspace);
+
+      /* Let others know the breakpoint has changed.  */
+      notify_breakpoint_modified (b);
+    }
 }
 
 /* See breakpoint.h.  */
@@ -1573,7 +1606,34 @@ breakpoint_set_inferior (struct breakpoint *b, int inferior)
   int old_inferior = b->inferior;
   b->inferior = inferior;
   if (old_inferior != inferior)
-    notify_breakpoint_modified (b);
+    {
+      /* If INFERIOR is in a different program_space than OLD_INFERIOR, or
+	 the breakpoint has switch to or from inferior-specific, then we
+	 need to re-set the locations of this breakpoint.  First, figure
+	 out the program_space for the old and new inferiors, use a value
+	 of nullptr to indicate the breakpoint is in all program
+	 spaces.  */
+      program_space *old_pspace = nullptr;
+      if (old_inferior != -1)
+	{
+	  struct inferior *inf = find_inferior_id (old_inferior);
+	  gdb_assert (inf != nullptr);
+	  old_pspace = inf->pspace;
+	}
+
+      program_space *new_pspace = nullptr;
+      if (inferior != -1)
+	{
+	  struct inferior *inf = find_inferior_id (inferior);
+	  gdb_assert (inf != nullptr);
+	  new_pspace = inf->pspace;
+	}
+
+      if (old_pspace != new_pspace)
+	breakpoint_re_set_one (b, new_pspace);
+
+      notify_breakpoint_modified (b);
+    }
 }
 
 /* See breakpoint.h.  */
@@ -8819,7 +8879,8 @@ create_breakpoints_sal (struct gdbarch *gdbarch,
 
 static void
 parse_breakpoint_sals (location_spec *locspec,
-		       struct linespec_result *canonical)
+		       struct linespec_result *canonical,
+		       struct program_space *search_pspace)
 {
   struct symtab_and_line cursal;
 
@@ -8883,7 +8944,7 @@ parse_breakpoint_sals (location_spec *locspec,
 	      && strchr ("+-", spec[0]) != NULL
 	      && spec[1] != '['))
 	{
-	  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, NULL,
+	  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, search_pspace,
 			    get_last_displayed_symtab (),
 			    get_last_displayed_line (),
 			    canonical, NULL, NULL);
@@ -8891,7 +8952,7 @@ parse_breakpoint_sals (location_spec *locspec,
 	}
     }
 
-  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, NULL,
+  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, search_pspace,
 		    cursal.symtab, cursal.line, canonical, NULL, NULL);
 }
 
@@ -8990,6 +9051,39 @@ breakpoint_ops_for_location_spec_type (enum location_spec_type locspec_type,
     }
 }
 
+/* Return the program space to use as a filter when searching for locations
+   of a breakpoint specific to THREAD or INFERIOR.  If THREAD and INFERIOR
+   are both -1, meaning all threads/inferiors, then this function returns
+   nullptr, indicating no program space filtering should be performed.
+   Otherwise, this function returns the program space for the inferior that
+   contains THREAD (when THREAD is not -1), or the program space for
+   INFERIOR (when INFERIOR is not -1).  */
+
+static struct program_space *
+find_program_space_for_breakpoint (int thread, int inferior)
+{
+  if (thread != -1)
+    {
+      gdb_assert (inferior == -1);
+
+      struct thread_info *thr = find_thread_global_id (thread);
+      gdb_assert (thr != nullptr);
+      gdb_assert (thr->inf != nullptr);
+      return thr->inf->pspace;
+    }
+  else if (inferior != -1)
+    {
+      gdb_assert (thread == -1);
+
+      struct inferior *inf = find_inferior_id (inferior);
+      gdb_assert (inf != nullptr);
+
+      return inf->pspace;
+    }
+
+  return nullptr;
+}
+
 /* See breakpoint.h.  */
 
 const struct breakpoint_ops *
@@ -9092,7 +9186,10 @@ create_breakpoint (struct gdbarch *gdbarch,
 
   try
     {
-      ops->create_sals_from_location_spec (locspec, &canonical);
+      struct program_space *search_pspace
+	= find_program_space_for_breakpoint (thread, inferior);
+      ops->create_sals_from_location_spec (locspec, &canonical,
+					   search_pspace);
     }
   catch (const gdb_exception_error &e)
     {
@@ -9564,7 +9661,7 @@ break_range_command (const char *arg, int from_tty)
   arg_start = arg;
   location_spec_up start_locspec
     = string_to_location_spec (&arg, current_language);
-  parse_breakpoint_sals (start_locspec.get (), &canonical_start);
+  parse_breakpoint_sals (start_locspec.get (), &canonical_start, nullptr);
 
   if (arg[0] != ',')
     error (_("Too few arguments."));
@@ -9651,7 +9748,7 @@ watchpoint_exp_is_const (const struct expression *exp)
 /* Implement the "re_set" method for watchpoints.  */
 
 void
-watchpoint::re_set ()
+watchpoint::re_set (struct program_space *pspace)
 {
   /* Watchpoint can be either on expression using entirely global
      variables, or it can be on local variables.
@@ -11765,7 +11862,7 @@ breakpoint::print_recreate (struct ui_file *fp) const
 /* Default breakpoint_ops methods.  */
 
 void
-code_breakpoint::re_set ()
+code_breakpoint::re_set (struct program_space *pspace)
 {
   /* FIXME: is this still reachable?  */
   if (breakpoint_location_spec_empty_p (this))
@@ -11775,7 +11872,7 @@ code_breakpoint::re_set ()
       return;
     }
 
-  re_set_default ();
+  re_set_default (pspace);
 }
 
 int
@@ -11981,7 +12078,7 @@ code_breakpoint::decode_location_spec (location_spec *locspec,
 /* Virtual table for internal breakpoints.  */
 
 void
-internal_breakpoint::re_set ()
+internal_breakpoint::re_set (struct program_space *pspace)
 {
   switch (type)
     {
@@ -12074,7 +12171,7 @@ internal_breakpoint::print_mention () const
 /* Virtual table for momentary breakpoints  */
 
 void
-momentary_breakpoint::re_set ()
+momentary_breakpoint::re_set (struct program_space *pspace)
 {
   /* Keep temporary breakpoints, which can be encountered when we step
      over a dlopen call and solib_add is resetting the breakpoints.
@@ -12115,12 +12212,13 @@ longjmp_breakpoint::~longjmp_breakpoint ()
 
 static void
 bkpt_probe_create_sals_from_location_spec (location_spec *locspec,
-					   struct linespec_result *canonical)
+					   struct linespec_result *canonical,
+					   struct program_space *search_pspace)
 
 {
   struct linespec_sals lsal;
 
-  lsal.sals = parse_probes (locspec, NULL, canonical);
+  lsal.sals = parse_probes (locspec, search_pspace, canonical);
   lsal.canonical = xstrdup (canonical->locspec->to_string ());
   canonical->lsals.push_back (std::move (lsal));
 }
@@ -12210,9 +12308,9 @@ tracepoint::print_recreate (struct ui_file *fp) const
 }
 
 void
-dprintf_breakpoint::re_set ()
+dprintf_breakpoint::re_set (struct program_space *pspace)
 {
-  re_set_default ();
+  re_set_default (pspace);
 
   /* extra_string should never be non-NULL for dprintf.  */
   gdb_assert (extra_string != NULL);
@@ -12270,8 +12368,10 @@ dprintf_breakpoint::after_condition_true (struct bpstat *bs)
    markers (`-m').  */
 
 static void
-strace_marker_create_sals_from_location_spec (location_spec *locspec,
-					      struct linespec_result *canonical)
+strace_marker_create_sals_from_location_spec
+	(location_spec *locspec,
+	 struct linespec_result *canonical,
+	 struct program_space *search_pspace)
 {
   struct linespec_sals lsal;
   const char *arg_start, *arg;
@@ -12788,12 +12888,32 @@ update_breakpoint_locations (code_breakpoint *b,
      all locations are in the same shared library, that was unloaded.
      We'd like to retain the location, so that when the library is
      loaded again, we don't loose the enabled/disabled status of the
-     individual locations.  */
+     individual locations.
+
+     Thread specific breakpoints will also trigger this case if the thread
+     is changed to a different program space, and all of the old locations
+     go out of scope.  In this case we do (currently) discard the old
+     locations -- we assume the change in thread is permanent and the old
+     locations will never come back into scope.  */
   if (all_locations_are_pending (b, filter_pspace) && sals.empty ())
-    return;
+    {
+      if (b->thread != -1)
+	b->clear_locations ();
+      return;
+    }
 
   bp_location_list existing_locations = b->steal_locations (filter_pspace);
 
+  /* If this is a thread-specific breakpoint then any locations left on the
+     breakpoint are for a program space in which the thread of interest
+     does not operate.  This can happen when the user changes the thread of
+     a thread-specific breakpoint.
+
+     We assume that the change in thread is permanent, and that the old
+     locations will never be used again, so discard them now.  */
+  if (b->thread != -1)
+    b->clear_locations ();
+
   for (const auto &sal : sals)
     {
       struct bp_location *new_loc;
@@ -12956,40 +13076,45 @@ code_breakpoint::location_spec_to_sals (location_spec *locspec,
    locations.  */
 
 void
-code_breakpoint::re_set_default ()
+code_breakpoint::re_set_default (struct program_space *filter_pspace)
 {
-  struct program_space *filter_pspace = current_program_space;
   std::vector<symtab_and_line> expanded, expanded_end;
 
-  int found;
-  std::vector<symtab_and_line> sals = location_spec_to_sals (locspec.get (),
-							     filter_pspace,
-							     &found);
-  if (found)
-    expanded = std::move (sals);
-
-  if (locspec_range_end != nullptr)
-    {
-      std::vector<symtab_and_line> sals_end
-	= location_spec_to_sals (locspec_range_end.get (),
-				 filter_pspace, &found);
+  /* If this breakpoint is thread-specific then find the program space in
+     which the specific thread exists.  Otherwise, for breakpoints that are
+     not thread-specific THREAD_PSPACE will be nullptr.  */
+  program_space *bp_pspace
+    = find_program_space_for_breakpoint (this->thread, this->inferior);
+
+  /* If this is not a thread or inferior specific breakpoint, or it is a
+     thread or inferior specific breakpoint but we are looking for new
+     locations in the program space that the specific thread or inferior is
+     running, then look for new locations for this breakpoint.  */
+  if (bp_pspace == nullptr || filter_pspace == bp_pspace)
+    {
+      int found;
+      std::vector<symtab_and_line> sals
+	= location_spec_to_sals (locspec.get (), filter_pspace, &found);
       if (found)
-	expanded_end = std::move (sals_end);
+	expanded = std::move (sals);
+
+      if (locspec_range_end != nullptr)
+	{
+	  std::vector<symtab_and_line> sals_end
+	    = location_spec_to_sals (locspec_range_end.get (),
+				     filter_pspace, &found);
+	  if (found)
+	    expanded_end = std::move (sals_end);
+	}
     }
 
+  /* Update the locations for this breakpoint.  For thread-specific
+     breakpoints this will remove any old locations that are for the wrong
+     program space -- this can happen if the user changes the thread of a
+     thread-specific breakpoint.  */
   update_breakpoint_locations (this, filter_pspace, expanded, expanded_end);
 }
 
-/* Default method for creating SALs from an address string.  It basically
-   calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
-
-static void
-create_sals_from_location_spec_default (location_spec *locspec,
-					struct linespec_result *canonical)
-{
-  parse_breakpoint_sals (locspec, canonical);
-}
-
 /* Re-set breakpoint locations for the current program space.
    Locations bound to other program spaces are left untouched.  */
 
@@ -13024,7 +13149,7 @@ breakpoint_re_set (void)
 	  {
 	    input_radix = b.input_radix;
 	    set_language (b.language);
-	    b.re_set ();
+	    b.re_set (current_program_space);
 	  }
 	catch (const gdb_exception &ex)
 	  {
@@ -13045,6 +13170,53 @@ breakpoint_re_set (void)
   /* Now we can insert.  */
   update_global_location_list (UGLL_MAY_INSERT);
 }
+
+/* Re-set locations for breakpoint B in FILTER_PSPACE.  If FILTER_PSPACE is
+   nullptr then re-set locations for B in all program spaces.  Locations
+   bound to program spaces other than FILTER_PSPACE are left untouched.  */
+
+static void
+breakpoint_re_set_one (breakpoint *b, program_space *filter_pspace)
+{
+  {
+    scoped_restore_current_language save_language;
+    scoped_restore save_input_radix = make_scoped_restore (&input_radix);
+    scoped_restore_current_pspace_and_thread restore_pspace_thread;
+
+    /* To ::re_set each breakpoint we set the current_language to the
+       language of the breakpoint before re-evaluating the breakpoint's
+       location.  This change can unfortunately get undone by accident if
+       the language_mode is set to auto, and we either switch frames, or
+       more likely in this context, we select the current frame.
+
+       We prevent this by temporarily turning the language_mode to
+       language_mode_manual.  We restore it once all breakpoints
+       have been reset.  */
+    scoped_restore save_language_mode = make_scoped_restore (&language_mode);
+    language_mode = language_mode_manual;
+
+    /* Note: we must not try to insert locations until after all
+       breakpoints have been re-set.  Otherwise, e.g., when re-setting
+       breakpoint 1, we'd insert the locations of breakpoint 2, which
+       hadn't been re-set yet, and thus may have stale locations.  */
+
+    try
+      {
+	input_radix = b->input_radix;
+	set_language (b->language);
+	b->re_set (filter_pspace);
+      }
+    catch (const gdb_exception &ex)
+      {
+	exception_fprintf (gdb_stderr, ex,
+			   "Error in re-setting breakpoint %d: ",
+			   b->number);
+      }
+  }
+
+  /* Now we can insert.  */
+  update_global_location_list (UGLL_MAY_INSERT);
+}
 \f
 /* Reset the thread number of this breakpoint:
 
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index a30bc5d2879..f2e78b5fde2 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -562,15 +562,15 @@ enum print_stop_action
 
 struct breakpoint_ops
 {
-  /* Create SALs from location spec, storing the result in
-     linespec_result.
-
-     For an explanation about the arguments, see the function
-     `create_sals_from_location_spec_default'.
+  /* Create SALs from LOCSPEC, storing the result in linespec_result
+     CANONICAL.  If SEARCH_PSPACE is not nullptr then only results in the
+     corresponding program space are returned.  If SEARCH_PSPACE is nullptr
+     then results for all program spaces are returned.
 
      This function is called inside `create_breakpoint'.  */
   void (*create_sals_from_location_spec) (location_spec *locspec,
-					  struct linespec_result *canonical);
+					  linespec_result *canonical,
+					  program_space *search_pspace);
 
   /* This method will be responsible for creating a breakpoint given its SALs.
      Usually, it just calls `create_breakpoints_sal' (for ordinary
@@ -702,8 +702,15 @@ struct breakpoint : public intrusive_list_node<breakpoint>
 
   /* Reevaluate a breakpoint.  This is necessary after symbols change
      (e.g., an executable or DSO was loaded, or the inferior just
-     started).  */
-  virtual void re_set ()
+     started).
+
+     If not nullptr, then FILTER_PSPACE is the program space in which
+     symbols may have changed, we only need to add new locations in
+     FILTER_PSPACE.
+
+     If FILTER_PSPACE is nullptr then all program spaces may have changed,
+     new locations need to be searched for in every program space.  */
+  virtual void re_set (program_space *filter_pspace)
   {
     /* Nothing to re-set.  */
   }
@@ -947,7 +954,7 @@ struct code_breakpoint : public breakpoint
   /* Add a location for SAL to this breakpoint.  */
   bp_location *add_location (const symtab_and_line &sal);
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   int insert_location (struct bp_location *) override;
   int remove_location (struct bp_location *,
 		       enum remove_bp_reason reason) override;
@@ -969,7 +976,7 @@ struct code_breakpoint : public breakpoint
      struct program_space *search_pspace);
 
   /* Helper method that does the basic work of re_set.  */
-  void re_set_default ();
+  void re_set_default (program_space *pspace);
 
   /* Find the SaL locations corresponding to the given LOCATION.
      On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
@@ -991,7 +998,7 @@ struct watchpoint : public breakpoint
 {
   using breakpoint::breakpoint;
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   int insert_location (struct bp_location *) override;
   int remove_location (struct bp_location *,
 		       enum remove_bp_reason reason) override;
diff --git a/gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp b/gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp
index 57e69ef6240..3afc1787026 100644
--- a/gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp
+++ b/gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp
@@ -76,8 +76,12 @@ foreach_mi_ui_mode mode {
     set loc2 [make_bp_loc "$::decimal\\.2"]
 
     # Create the inferior-specific breakpoint.
-    mi_create_breakpoint_multi "-g i2 foo" "create breakpoint in inferior 2" \
-	-inferior "2" -locations "\\\[$loc1,$loc2\\\]"
+    mi_create_breakpoint "-g i2 foo" "create breakpoint in inferior 2" \
+	-number "$decimal" \
+	-type "breakpoint" \
+	-enabled "y" \
+	-func "foo" \
+	-inferior "2"
     set bpnum [mi_get_valueof "/d" "\$bpnum" "INVALID"]
 
     if {$mode eq "separate"} {
diff --git a/gdb/testsuite/gdb.mi/user-selected-context-sync.exp b/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
index 4889c31aff3..b39745bdf17 100644
--- a/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
+++ b/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
@@ -370,7 +370,7 @@ proc test_continue_to_start { mode inf } {
 			    "thread $inf.2 stops MI"
 		    } else {
 			mi_expect_stop "breakpoint-hit" "child_sub_function" \
-			    "" "$srcfile" "$decimal" {"" "disp=\"del\"" "locno=\"[0-9]+\""} \
+			    "" "$srcfile" "$decimal" {"" "disp=\"del\""} \
 			    "thread $inf.2 stops MI"
 		    }
 		}
@@ -439,7 +439,7 @@ proc_with_prefix test_setup { mode } {
 
 	with_spawn_id $mi_spawn_id {
 	    mi_expect_stop "breakpoint-hit" "main" "" "$srcfile" "$decimal" \
-		{"" "disp=\"del\"" "locno=\"[0-9]+\""} "main stop"
+		{"" "disp=\"del\""} "main stop"
 	}
 
 	# Consume CLI output.
diff --git a/gdb/testsuite/gdb.multi/bp-thread-specific.exp b/gdb/testsuite/gdb.multi/bp-thread-specific.exp
index 85c08f44a2c..68001e92044 100644
--- a/gdb/testsuite/gdb.multi/bp-thread-specific.exp
+++ b/gdb/testsuite/gdb.multi/bp-thread-specific.exp
@@ -50,7 +50,7 @@ gdb_test "info threads" \
 # locations ('foo' in both inferiors) even though only one of those
 # locations will ever trigger ('foo' in inferior 2).
 gdb_test "break foo thread 2.1" \
-    "Breakpoint $decimal at $hex: foo\\. \\(2 locations\\)"
+    "Breakpoint $decimal at $hex: file \[^\r\n\]+$srcfile, line $decimal\\."
 
 set bpnum [get_integer_valueof "\$bpnum" "INVALID"]
 
@@ -58,10 +58,7 @@ set bpnum [get_integer_valueof "\$bpnum" "INVALID"]
 # earlier breakpoint.  Check that the thread-id used when describing
 # the earlier breakpoints is correct.
 gdb_test "break foo thread 1.1" \
-    [multi_line \
-	 "Note: breakpoint $bpnum \\(thread 2.1\\) also set at pc $hex\\." \
-	 "Note: breakpoint $bpnum \\(thread 2.1\\) also set at pc $hex\\." \
-	 "Breakpoint $decimal at $hex: foo\\. \\(2 locations\\)"]
+    "Breakpoint $decimal at $hex: file \[^\r\n\]+$srcfile, line $decimal\\."
 
 # Save the breakpoints into a file.
 if {[is_remote host]} {
diff --git a/gdb/testsuite/gdb.multi/inferior-specific-bp.exp b/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
index b8aceabcad6..dda167dd39f 100644
--- a/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
+++ b/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
@@ -105,16 +105,8 @@ proc check_info_breakpoints { testname bp_number expected_loc_count } {
 # Create an inferior-specific breakpoint.  Use gdb_test instead of
 # gdb_breakpoint here as we want to check the breakpoint was placed in
 # multiple locations.
-#
-# Currently GDB still places inferior specific breakpoints into every
-# inferior, just like it does with thread specific breakpoints.
-# Hopefully this will change in the future, at which point, this test
-# will need updating.
-#
-# Two of these locations are in inferior 1, while the third is in
-# inferior 2.
 gdb_test "break foo inferior 1" \
-    "Breakpoint $decimal at $hex: foo\\. \\(3 locations\\)"
+    "Breakpoint $decimal at $hex: foo\\. \\(2 locations\\)"
 set bp_number [get_integer_valueof "\$bpnum" "INVALID" \
 		  "get b/p number for inferior specific breakpoint"]
 
@@ -123,7 +115,7 @@ set location_count 0
 set saw_inf_cond false
 
 check_info_breakpoints "first check for inferior specific breakpoint" \
-    $bp_number 3
+    $bp_number 2
 
 # Create a multi-inferior breakpoint to stop at.
 gdb_breakpoint "stop_breakpt" message
diff --git a/gdb/testsuite/gdb.multi/multi-target-continue.exp b/gdb/testsuite/gdb.multi/multi-target-continue.exp
index bf19cc00968..a1bffb7b613 100644
--- a/gdb/testsuite/gdb.multi/multi-target-continue.exp
+++ b/gdb/testsuite/gdb.multi/multi-target-continue.exp
@@ -30,7 +30,7 @@ proc test_continue {non-stop} {
 
     proc set_break {inf} {
 	gdb_test "break function${inf} thread ${inf}.1" \
-	"Breakpoint .* function${inf}\\..*"
+	    "Breakpoint ${::decimal} at ${::hex}: file .*, line ${::decimal}\\."
     }
 
     # Select inferior INF, and then run to a breakpoint on inferior
diff --git a/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp b/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp
index 64645b8ec8a..51fd70b018a 100644
--- a/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp
+++ b/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp
@@ -52,12 +52,12 @@ proc test_ping_pong_next {} {
     gdb_test "thread 1.1" "Switching to thread 1.1 .*"
 
     gdb_test "break $srcfile:$line1 thread 1.1" \
-	"Breakpoint .*$srcfile:$line1\\..*"
+	"Breakpoint .*$srcfile, line $line1\\."
 
     gdb_test "continue" "hit Breakpoint .*"
 
     gdb_test "break $srcfile:$line2 thread 2.1" \
-	"Breakpoint .*$srcfile:$line2\\..*"
+	"Breakpoint .*$srcfile, line $line2\\."
 
     # Now block inferior 1 and issue "next".  We should stop at the
     # breakpoint for inferior 2, given schedlock off.
diff --git a/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
index cb1f119ff94..897d4a1cf52 100644
--- a/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
+++ b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
@@ -129,10 +129,8 @@ proc do_bp_test { bp_type bp_pending } {
     } else {
 	set bp_pattern_before \
 	    [multi_line \
-		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+<MULTIPLE>\\s*" \
-		 "\\s+stop only in [string_to_regexp $bp_restriction]" \
-		 "$bp_number\\.1\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 1" \
-		 "$bp_number\\.2\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 2"]
+		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 1" \
+		 "\\s+stop only in [string_to_regexp $bp_restriction]"]
 
 	set bp_pattern_after \
 	    [multi_line \
diff --git a/gdb/testsuite/gdb.multi/pending-bp.exp b/gdb/testsuite/gdb.multi/pending-bp.exp
index e4f0aa2e38a..16803488a7f 100644
--- a/gdb/testsuite/gdb.multi/pending-bp.exp
+++ b/gdb/testsuite/gdb.multi/pending-bp.exp
@@ -78,6 +78,48 @@ proc do_test_setup { inf_1_stop inf_2_stop } {
     return true
 }
 
+# Create a breakpoint on the function 'foo' in THREAD.  It is expected
+# that the breakpoint created will be pending, this is checked by
+# running the 'info breakpoints' command.
+#
+# Returns the number for the newly created breakpoint.
+proc do_create_pending_foo_breakpoint { {thread "1.1"} } {
+    gdb_test "break foo thread $thread" \
+	[multi_line \
+	     "Function \"foo\" not defined\\." \
+	     "Breakpoint $::decimal \\(foo\\) pending\."] \
+	"set pending thread-specific breakpoint"
+    set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+		   "get number for thread-specific breakpoint on foo"]
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	     "\\s+stop only in thread [string_to_regexp $thread]"] \
+	"check thread-specific breakpoint is initially pending"
+
+    return $bpnum
+}
+
+# Create a breakpoint on the function 'foo' in THREAD.  It is expected
+# that the breakpoint created will not be pending, this is checked by
+# running the 'info breakpoints' command.
+#
+# Returns the number for the newly created breakpoint.
+proc do_create_foo_breakpoint { {thread "1.1"} } {
+    gdb_test "break foo thread $thread" \
+	"Breakpoint $::decimal at $::hex" \
+	"set thread-specific breakpoint"
+    set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+		   "get number for thread-specific breakpoint on foo"]
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex\\s+<foo\[^>\]*> inf $::decimal" \
+	     "\\s+stop only in thread [string_to_regexp $thread]"] \
+	"check thread-specific breakpoint is initially pending"
+
+    return $bpnum
+}
+
 # Check that when a breakpoint is in the pending state, but that breakpoint
 # does have some locations (those locations themselves are pending), GDB
 # doesn't display the inferior list in the 'info breakpoints' output.
@@ -126,5 +168,169 @@ proc_with_prefix test_no_inf_display {} {
 	"check info breakpoints while breakpoint is pending"
 }
 
+# Setup two inferiors.  In #1 the symbol 'foo' has not yet been
+# loaded, while in #2 the symbol 'foo' has been loaded.
+#
+# Create a thread-specific breakpoint on 'foo' tied to a thread in
+# inferior #1, the breakpoint should be pending -- 'foo' is not yet
+# loaded in #1.
+#
+# Now move inferior #1 forward until 'foo' is loaded, check the
+# breakpoint is no longer pending.
+#
+# Move inferior #1 forward more until 'foo' is unloaded, check that
+# the breakpoint returns to the pending state.
+proc_with_prefix test_pending_toggle { } {
+
+    do_test_setup "Break before open" "Break before close"
+
+    set bpnum [do_create_pending_foo_breakpoint]
+
+    # Now return to inferior 1 and continue until the shared library is
+    # loaded, the breakpoint should become non-pending.
+    gdb_test "inferior 1" "Switching to inferior 1 .*" \
+	"switch back to inferior 1"
+    gdb_continue_to_breakpoint "stop in foo in inferior 1" "foo \\(\\) .*"
+
+    gdb_test "info breakpoint $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex <foo\[^>\]*> inf 1" \
+	     "\\s+stop only in thread 1\\.1" \
+	     "\\s+breakpoint already hit 1 time"] \
+	"check thread-specific breakpoint is no longer pending"
+
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "close library"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	     "\\s+stop only in thread 1\\.1" \
+	     "\\s+breakpoint already hit 1 time"] \
+	"check thread-specific breakpoint is pending again"
+}
+
+# Create a Python variable VAR and set it to the gdb.Breakpoint object
+# corresponding to the breakpoint numbered BPNUM.  If THREAD is not
+# the empty string then THREAD should be an integer, check that
+# gdb.Breakpoint.thread is set to the value of THREAD.  Otherwise, if
+# THREAD is the empty string, check that gdb.Breakpoint.thread is set
+# to None.
+proc py_find_breakpoint { var bpnum {thread ""} } {
+    gdb_test_no_output \
+	"python ${var}=\[b for b in gdb.breakpoints() if b.number == $bpnum\]\[0\]" \
+	"find Python gdb.Breakpoint object"
+    if { $thread ne "" } {
+	gdb_test_no_output "python assert(${var}.thread == ${thread})" \
+	    "check thread attribute is currently correct"
+    } else {
+	gdb_test_no_output "python assert(${var}.thread is None)" \
+	    "check thread attribute is currently correct"
+    }
+}
+
+# Setup two inferiors.  In #1 the symbol 'foo' has not yet been
+# loaded, while in #2 the symbol 'foo' has been loaded.
+#
+# Create a thread-specific breakpoint on 'foo' tied to a thread in
+# inferior #1, the breakpoint should be pending -- 'foo' is not yet
+# loaded in #1.
+#
+# Use Python to change the thread of the thread-specific breakpoint to
+# a thread in inferior #2, at this point the thread should gain a
+# location and become non-pending.
+#
+# Set the thread back to a thread in inferior #1, the breakpoint
+# should return to the pending state.
+proc_with_prefix py_test_toggle_thread {} {
+    do_test_setup "Break before open" "Break after open"
+
+    set bpnum [do_create_pending_foo_breakpoint]
+
+    py_find_breakpoint "bp" $bpnum 1
+
+    gdb_test_no_output "python bp.thread = 2" \
+	"change thread on thread-specific breakpoint"
+    gdb_test "info breakpoint $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex <foo\[^>\]*> inf 2" \
+	     "\\s+stop only in thread 2\\.1"] \
+	"check thread-specific breakpoint now has a location"
+
+    gdb_test_no_output "set call_count = 2" "set call_count in inferior 2"
+    gdb_continue_to_breakpoint "stop at foo in inferior 2" "foo \\(\\) .*"
+
+    gdb_test_no_output "python bp.thread = 1" \
+	"restore thread on thread-specific breakpoint"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	     "\\s+stop only in thread 1\\.1" \
+	     "\\s+breakpoint already hit 1 time"] \
+	"check thread-specific breakpoint has returned to pending"
+
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "stop after close in inferior 2" \
+	".* Break after close\\. .*"
+
+    gdb_test "inferior 1" "Switching to inferior 1 .*" \
+	"switch to inferior 1"
+    gdb_continue_to_breakpoint "stop at foo in inferior 1" "foo \\(\\) .*"
+}
+
+# Setup two inferiors.  Both inferiors have the symbol 'foo'
+# available.
+#
+# Create a thread-specific breakpoint on 'foo' tied to a thread in
+# inferior #1, the breakpoint should not be pending, but will only
+# have a single location, the location in inferior #1.
+#
+# Use Python to change the thread of the thread-specific breakpoint to
+# None.  At this point the breakpoint should gain a second location, a
+# location in inferior #2.
+proc_with_prefix py_test_clear_thread {} {
+    do_test_setup "Break after open" "Break after open"
+
+    set bpnum [do_create_foo_breakpoint]
+
+    py_find_breakpoint "bp" $bpnum 1
+
+    gdb_test_no_output "python bp.thread = None" \
+	"clear thread on thread-specific breakpoint"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "${bpnum}\\s+breakpoint\\s+keep y\\s+<MULTIPLE>\\s*" \
+	     "${bpnum}\\.1\\s+y\\s+${::hex}\\s+<foo\[^>\]*> inf $::decimal" \
+	     "${bpnum}\\.2\\s+y\\s+${::hex}\\s+<foo\[^>\]*> inf $::decimal"] \
+	"check for a location in both inferiors"
+
+    gdb_continue_to_breakpoint "stop at foo in inferior 2" "foo \\(\\) .*"
+    gdb_test_no_output "set call_count = 2" "set call_count in inferior 2"
+
+    gdb_test "inferior 1" "Switching to inferior 1 .*" \
+	"switch to inferior 1"
+    gdb_continue_to_breakpoint "stop at foo in inferior 1" "foo \\(\\) .*"
+    gdb_test_no_output "set call_count = 2" "set call_count in inferior 1"
+
+    gdb_test_no_output "python bp.thread = 2"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "${bpnum}\\s+breakpoint\\s+keep y\\s+${::hex}\\s+<foo\[^>\]*> inf 2" \
+	     "\\s+stop only in thread 2\\.1" \
+	     "\\s+breakpoint already hit 2 times"] \
+	"check for a location only in inferior 2"
+
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "stop after close in inferior 1" \
+	".* Break after close\\. .*"
+
+    gdb_test "inferior 2" "Switching to inferior 2 .*" \
+	"switch back to inferior 2"
+    gdb_continue_to_breakpoint "stop at foo again in inferior 2" \
+	"foo \\(\\) .*"
+}
+
 # Run all the tests.
 test_no_inf_display
+test_pending_toggle
+py_test_toggle_thread
+py_test_clear_thread
diff --git a/gdb/testsuite/gdb.multi/tids.exp b/gdb/testsuite/gdb.multi/tids.exp
index 18fc4970fe7..34c270309de 100644
--- a/gdb/testsuite/gdb.multi/tids.exp
+++ b/gdb/testsuite/gdb.multi/tids.exp
@@ -433,11 +433,13 @@ if { [allow_python_tests] } {
 
 	gdb_py_test_silent_cmd "python bp = gdb.breakpoints()\[0\]" \
 	    "get python breakpoint" 0
-	gdb_test "python bp.thread = 6" "thread = 6" \
+	gdb_test_no_output "python bp.thread = 6" \
 	    "make breakpoint thread-specific with python"
 	# Check that the inferior-qualified ID is correct.
 	gdb_test "info breakpoint" \
-	    "stop only in thread 1.3\r\n.*" \
+	    [multi_line \
+		 "$decimal\\s+\[^\r\n\]+ in thread_function1 at \[^\r\n\]+" \
+		 "\\s+stop only in thread 1\\.3"] \
 	    "thread specific breakpoint right thread"
     }
 }
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* Re: [PATCHv4 06/10] gdb: parse pending breakpoint thread/task immediately
  2023-08-23 15:59       ` [PATCHv4 06/10] gdb: parse pending breakpoint thread/task immediately Andrew Burgess
@ 2023-08-23 16:32         ` Eli Zaretskii
  2023-09-06 22:06         ` Lancelot SIX
  1 sibling, 0 replies; 138+ messages in thread
From: Eli Zaretskii @ 2023-08-23 16:32 UTC (permalink / raw)
  To: Andrew Burgess; +Cc: gdb-patches

> From: Andrew Burgess <aburgess@redhat.com>
> Cc: Andrew Burgess <aburgess@redhat.com>,
> 	Eli Zaretskii <eliz@gnu.org>
> Date: Wed, 23 Aug 2023 16:59:11 +0100
> 
>  gdb/Makefile.in                               |   2 +
>  gdb/NEWS                                      |   4 +
>  gdb/break-cond-parse.c                        | 425 ++++++++++++++++++
>  gdb/break-cond-parse.h                        |  49 ++
>  gdb/breakpoint.c                              | 374 ++++-----------
>  gdb/testsuite/gdb.ada/tasks.exp               |   6 +-
>  gdb/testsuite/gdb.base/condbreak.exp          |  20 +-
>  gdb/testsuite/gdb.base/pending.exp            |  23 +-
>  gdb/testsuite/gdb.linespec/explicit.exp       |   4 +-
>  gdb/testsuite/gdb.mi/mi-dprintf-pending.exp   |   3 +-
>  .../gdb.multi/inferior-specific-bp.exp        |   4 +-
>  .../gdb.threads/del-pending-thread-bp-lib.c   |  22 +
>  .../gdb.threads/del-pending-thread-bp.c       |  85 ++++
>  .../gdb.threads/del-pending-thread-bp.exp     | 108 +++++
>  14 files changed, 826 insertions(+), 303 deletions(-)
>  create mode 100644 gdb/break-cond-parse.c
>  create mode 100644 gdb/break-cond-parse.h
>  create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
>  create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.c
>  create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.exp

The NEWS part is OK, thanks.

Reviewed-By: Eli Zaretskii <eliz@gnu.org>

^ permalink raw reply	[flat|nested] 138+ messages in thread

* Re: [PATCHv4 06/10] gdb: parse pending breakpoint thread/task immediately
  2023-08-23 15:59       ` [PATCHv4 06/10] gdb: parse pending breakpoint thread/task immediately Andrew Burgess
  2023-08-23 16:32         ` Eli Zaretskii
@ 2023-09-06 22:06         ` Lancelot SIX
  2023-10-02 15:02           ` Andrew Burgess
  1 sibling, 1 reply; 138+ messages in thread
From: Lancelot SIX @ 2023-09-06 22:06 UTC (permalink / raw)
  To: Andrew Burgess; +Cc: gdb-patches, Eli Zaretskii

Hi Andrew,

First, thanks for the patch, I really like what it changes!

When applying the patch, I get the following warnings from git:

    Applying: gdb: parse pending breakpoint thread/task immediately
    .git/rebase-apply/patch:95: indent with spaces.
                ^
    .git/rebase-apply/patch:96: indent with spaces.
               ptr
    .git/rebase-apply/patch:270: indent with spaces.
             For the 'if' token we need to capture the entire condition
    .git/rebase-apply/patch:271: indent with spaces.
             string, so record the start of the condition string and then
    .git/rebase-apply/patch:272: indent with spaces.
             start scanning backwards looking for the end of the condition
    warning: squelched 3 whitespace errors
    warning: 8 lines add whitespace errors.

I have added comments along the patch.

Best,
Lancelot.

On Wed, Aug 23, 2023 at 04:59:11PM +0100, Andrew Burgess via Gdb-patches wrote:
> The initial motivation for this commit was to allow thread or inferior
> specific breakpoints to only be inserted within the appropriate
> inferior's program-space.  The benefit of this is that inferiors for
> which the breakpoint does not apply will no longer need to stop, and
> then resume, for such breakpoints.  This commit does not make this
> change, but is a refactor to allow this to happen in a later commit.
> 
> The problem we currently have is that when a thread-specific (or
> inferior-specific) breakpoint is created, the thread (or inferior)
> number is only parsed by calling find_condition_and_thread_for_sals.
> This function is only called for non-pending breakpoints, and requires
> that we know the locations at which the breakpoint will be placed (for
> expression checking in case the breakpoint is also conditional).
> 
> A consequence of this is that by the time we figure out the breakpoint
> is thread-specific we have already looked up locations in all program
> spaces.  This feels wasteful -- if we knew the thread-id earlier then
> we could reduce the work GDB does by only looking up locations within
> the program space for which the breakpoint applies.
> 
> Another consequence of how find_condition_and_thread_for_sals is
> called is that pending breakpoints don't currently know they are
> thread-specific, nor even that they are conditional!  Additionally, by
> delaying parsing the thread-id, pending breakpoints can be created for
> non-existent threads, this is different to how non-pending
> breakpoints are handled, so I can do this:
> 
>   $ gdb -q ./gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp
>   Reading symbols from ./gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp...
>   (gdb) break foo thread 99
>   Function "foo" not defined.
>   Make breakpoint pending on future shared library load? (y or [n]) y
>   Breakpoint 1 (foo thread 99) pending.
>   (gdb) r
>   Starting program: /tmp/gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp
>   [Thread debugging using libthread_db enabled]
>   Using host libthread_db library "/lib64/libthread_db.so.1".
>   Error in re-setting breakpoint 1: Unknown thread 99.
>   [Inferior 1 (process 3329749) exited normally]
>   (gdb)
> 
> GDB only checked the validity of 'thread 99' at the point the 'foo'
> location became non-pending.  In contrast, if I try this:
> 
>   $ gdb -q ./gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp
>   Reading symbols from ./gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp...
>   (gdb) break main thread 99
>   Unknown thread 99.
>   (gdb)
> 
> GDB immediately checks if 'thread 99' exists.  I think inconsistencies
> like this are confusing, and should be fixed if possible.
> 
> In this commit the create_breakpoint function is updated so that the
> extra_string, which contains the thread, inferior, task, and/or
> condition information, is parsed immediately, even for pending
> breakpoints.
> 
> Obviously, the condition still can't be validated until the breakpoint
> becomes non-pending, but the thread, inferior, and task information
> can be pulled from the extra-string, and can be validated early on,
> even for pending breakpoints.
> 
> There are a couple of benefits to doing this:
> 
> 1. Printing of breakpoints is more consistent now.  Consider creating
>    a conditional breakpoint before this commit:
> 
>     (gdb) set breakpoint pending on
>     (gdb) break pendingfunc if (0)
>     Function "pendingfunc" not defined.
>     Breakpoint 1 (pendingfunc if (0)) pending.
>     (gdb) break main if (0)
>     Breakpoint 2 at 0x401198: file /tmp/hello.c, line 18.
>     (gdb) info breakpoints
>     Num     Type           Disp Enb Address            What
>     1       breakpoint     keep y   <PENDING>          pendingfunc if (0)
>     2       breakpoint     keep y   0x0000000000401198 in main at /tmp/hello.c:18
>             stop only if (0)
>     (gdb)
> 
>    And after this commit:
> 
>     (gdb) set breakpoint pending on
>     (gdb) break pendingfunc if (0)
>     Function "pendingfunc" not defined.
>     Breakpoint 1 (pendingfunc) pending.
>     (gdb) break main if (0)
>     Breakpoint 2 at 0x401198: file /home/andrew/tmp/hello.c, line 18.
>     (gdb) info breakpoints
>     Num     Type           Disp Enb Address            What
>     1       breakpoint     keep y   <PENDING>          pendingfunc
>             stop only if (0)
>     2       breakpoint     keep y   0x0000000000401198 in main at /home/andrew/tmp/hello.c:18
>             stop only if (0)
>     (gdb)
> 
>    Notice that the display of the condition is now the same for the
>    pending and non-pending breakpoints.
> 
>    The same is true for the thread information in thread-specific
>    breakpoints, this information is displayed on its own line now
>    rather than being part of the 'What' field.
> 
> 2. We can check that the thread exists as soon as the pending
>    breakpoint exits.  Currently there is a weird different between
>    pending and non-pending breakpoints when creating a thread-specific
>    breakpoint.  A pending thread-specific breakpoint only checks its
>    thread when it becomes non-pending, at which point the thread the
>    breakpoint was intended for might have exited.  Here's the
>    behaviour before this commit:
> 
>     (gdb) set breakpoint pending on
>     (gdb) break foo thread 2
>     Function "foo" not defined.
>     Breakpoint 2 (foo thread 2) pending.
>     (gdb) c
>     Continuing.
>     [Thread 0x7ffff7c56700 (LWP 2948835) exited]
>     Error in re-setting breakpoint 2: Unknown thread 2.
>     [Inferior 1 (process 2948832) exited normally]
>     (gdb)
> 
>    Notice the 'Error in re-setting breakpoint 2: Unknown thread 2.'
>    line, this was triggered when the thread tried to become
                                   ^
				   the breakpoint?

>    non-pending, and GDB discovers that the thread no longer exists.
> 
>    Compare that to the behaviour after this commit:
> 
>     (gdb) set breakpoint pending on
>     (gdb) break foo thread 2
>     Function "foo" not defined.
>     Breakpoint 2 (foo) pending.
>     (gdb) c
>     Continuing.
>     [Thread 0x7ffff7c56700 (LWP 2949243) exited]
>     Thread-specific breakpoint 2 deleted - thread 2 no longer in the thread list.
>     [Inferior 1 (process 2949240) exited normally]
>     (gdb)
> 
>    Now the behaviour for pending breakpoints is identical to
>    non-pending breakpoints, the thread specific breakpoint is removed
>    as soon as the thread the breakpoint is associated with exits.
> 
> As a result of this commit the breakpoints 'extra_string' field is now
> only used by bp_dprintf type breakpoints to hold the printf format and
> arguments.  This string should always be empty for other breakpoint
> types.  This allows me to clean up some code in
> print_breakpoint_location.
> 
> In code_breakpoint::code_breakpoint I'm able to change an error case
> into an assert.  This is because this error is now handled earlier in
> create_breakpoint.  As a result we know that by this point, the
> extra_string will always be nullptr for anything other than a
> bp_dprintf style breakpoint.
> 
> The find_condition_and_thread_for_sals function is now no longer
> needed, this was previously doing the delayed splitting of the extra
> string into thread, task, and condition, but this is now all done in
> create_breakpoint, so find_condition_and_thread_for_sals can be
> deleted, and the code that calls this in
> code_breakpoint::location_spec_to_sals can be removed.  With this
> update this code would only ever be reached for bp_dprintf style
> breakpoints, and in these cases the extra_string should not contain
> anything other than format and args.
> 
> The most interesting changes are all in create_breakpoint and in the
> new file break-cond-parse.c.  We have a new block of code early on in
> create_breakpoint that is responsible for splitting the extra_string
> into its component parts by calling create_breakpoint_parse_arg_string
> a function in the new break-cond-parse.c file.  This means that some
> of the later code can be simplified a little.
> 
> The new break-cond-parse.c file implements the splitting up the
> extra_string and finding all the parts, as well as some self-tests for
> the new function.
> 
> Finally, now we know all the details, these can be stored within the
> breakpoint object if we end up creating a deferred breakpoint.
> Additionally, if we are creating a deferred bp_dprintf we can parse
> the extra_string to build the printf command.
> 
> Reviewed-By: Eli Zaretskii <eliz@gnu.org>
> ---
>  gdb/Makefile.in                               |   2 +
>  gdb/NEWS                                      |   4 +
>  gdb/break-cond-parse.c                        | 425 ++++++++++++++++++
>  gdb/break-cond-parse.h                        |  49 ++
>  gdb/breakpoint.c                              | 374 ++++-----------
>  gdb/testsuite/gdb.ada/tasks.exp               |   6 +-
>  gdb/testsuite/gdb.base/condbreak.exp          |  20 +-
>  gdb/testsuite/gdb.base/pending.exp            |  23 +-
>  gdb/testsuite/gdb.linespec/explicit.exp       |   4 +-
>  gdb/testsuite/gdb.mi/mi-dprintf-pending.exp   |   3 +-
>  .../gdb.multi/inferior-specific-bp.exp        |   4 +-
>  .../gdb.threads/del-pending-thread-bp-lib.c   |  22 +
>  .../gdb.threads/del-pending-thread-bp.c       |  85 ++++
>  .../gdb.threads/del-pending-thread-bp.exp     | 108 +++++
>  14 files changed, 826 insertions(+), 303 deletions(-)
>  create mode 100644 gdb/break-cond-parse.c
>  create mode 100644 gdb/break-cond-parse.h
>  create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
>  create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.c
>  create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.exp
> 
> diff --git a/gdb/Makefile.in b/gdb/Makefile.in
> index 9b992a3d8c0..43b867cd796 100644
> --- a/gdb/Makefile.in
> +++ b/gdb/Makefile.in
> @@ -1026,6 +1026,7 @@ COMMON_SFILES = \
>  	break-catch-sig.c \
>  	break-catch-syscall.c \
>  	break-catch-throw.c \
> +	break-cond-parse.c \
>  	breakpoint.c \
>  	bt-utils.c \
>  	btrace.c \
> @@ -1293,6 +1294,7 @@ HFILES_NO_SRCDIR = \
>  	bfd-target.h \
>  	bfin-tdep.h \
>  	block.h \
> +	break-cond-parse.h \
>  	breakpoint.h \
>  	bsd-kvm.h \
>  	bsd-uthread.h \
> diff --git a/gdb/NEWS b/gdb/NEWS
> index c4b1f7a7e3b..7c38ecb8b46 100644
> --- a/gdb/NEWS
> +++ b/gdb/NEWS
> @@ -105,6 +105,10 @@
>    'inferior' keyword with either the 'thread' or 'task' keywords when
>    creating a breakpoint.
>  
> +* For breakpoints that are created in the 'pending' state, any
> +  'thread' or 'task' keywords are parsed at the time the breakpoint is
> +  created, rather than at the time the breakpoint becomes non-pending.
> +
>  * New commands
>  
>  set debug breakpoint on|off
> diff --git a/gdb/break-cond-parse.c b/gdb/break-cond-parse.c
> new file mode 100644
> index 00000000000..ebe67c90736
> --- /dev/null
> +++ b/gdb/break-cond-parse.c
> @@ -0,0 +1,425 @@
> +/* Copyright (C) 2023 Free Software Foundation, Inc.
> +
> +   This file is part of GDB.
> +
> +   This program is free software; you can redistribute it and/or modify
> +   it under the terms of the GNU General Public License as published by
> +   the Free Software Foundation; either version 3 of the License, or
> +   (at your option) any later version.
> +
> +   This program is distributed in the hope that it will be useful,
> +   but WITHOUT ANY WARRANTY; without even the implied warranty of
> +   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
> +   GNU General Public License for more details.
> +
> +   You should have received a copy of the GNU General Public License
> +   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
> +
> +#include "defs.h"
> +#include "gdbsupport/gdb_assert.h"
> +#include "gdbsupport/selftest.h"
> +#include "test-target.h"
> +#include "scoped-mock-context.h"
> +#include "break-cond-parse.h"
> +#include "tid-parse.h"
> +#include "ada-lang.h"
> +
> +/* When parsing tokens from a string, which direction are we parsing?
> +
> +   Given the following string and pointer 'ptr':
> +
> +     ABC DEF GHI JKL
> +            ^
> +           ptr

Initial indentation with tabs here.

> +
> +   Parsing 'forward' will return the token 'GHI' and update 'ptr' to point
> +   between GHI and JKL.  Parsing 'backward' will return the token 'DEF' and
> +   update 'ptr' to point between ABC and DEF.
> +*/
> +
> +enum class parse_direction
> +{
> +  /* Parse the next token forwards.  */
> +  forward,
> +
> +  /* Parse the previous token backwards.  */
> +  backward
> +};
> +
> +struct token
> +{
> +  /* Create a new token.  START points to the first character of the new
> +     token, while END points at the last character of the new token.
> +
> +     Neither START or END can be nullptr, and both START and END must point
> +     into the same C style string (i.e. there should be no null character
> +     between START and END).  END must be equal to, or greater than START,
> +     that is, it is not possible to create a zero length token.  */
> +
> +  token (const char *start, const char *end)
> +    : m_start (start),
> +      m_end (end)
> +  {
> +    gdb_assert (m_end >= m_start);
> +    gdb_assert (m_start + strlen (m_start) > m_end);
> +  }
> +
> +  /* Return a pointer to the first character of this token.  */
> +  const char *start () const
> +  {
> +    return m_start;
> +  }
> +
> +  /* Return a pointer to the last character of this token.  */
> +  const char *end () const
> +  {
> +    return m_end;
> +  }
> +
> +  /* Return the length of the token.  */
> +  size_t length () const
> +  {
> +    return m_end - m_start + 1;

Note here that since we know that m_end >= m_start (this is asserted in
the ctor), length must return at least 1.  It cannot be 0 (this will
become relevant later).

> +  }
> +
> +  /* Return true if this token matches STR.  If this token is shorter than
> +     STR then only a partial match is performed and true will be returned
> +     if the token length sub-string matches.  Otherwise, return false.  */

I am not sure that partial matching here was a good choice of the
initial implementation (you did not change this).  The token you are
interested in here are matched entirely when parsing the locdesc
(linespec_lexer_lex_keyword), doing partial matching seems inconsistent.
See later comments for further details.

> +  bool matches (const char *str) const
> +  {
> +    return strncmp (m_start, str, length ()) == 0;
> +  }
> +
> +private:
> +  /* The first character of this token.  */
> +  const char *m_start;
> +
> +  /* The last character of this token.  */
> +  const char *m_end;
> +};
> +
> +/* Find the next token in DIRECTION from *CURR.  */
> +
> +static token
> +find_next_token (const char **curr, parse_direction direction)
> +{
> +  const char *tok_start, *tok_end;
> +
> +  if (direction == parse_direction::forward)
> +    {
> +      *curr = skip_spaces (*curr);
> +      tok_start = *curr;
> +      *curr = skip_to_space (*curr);
> +      tok_end = *curr - 1;
> +    }
> +  else
> +    {
> +      gdb_assert (direction == parse_direction::backward);
> +
> +      while (isspace (**curr))
> +	--(*curr);
> +
> +      tok_end = *curr;
> +
> +      while (!isspace (**curr))
> +	--(*curr);
> +
> +      tok_start = (*curr) + 1;
> +    }
> +
> +  return token (tok_start, tok_end);
> +}
> +
> +/* See break-cond-parse.h.  */
> +
> +void
> +create_breakpoint_parse_arg_string
> +  (const char *tok, gdb::unique_xmalloc_ptr<char> *cond_string,
> +   int *thread, int *inferior, int *task,
> +   gdb::unique_xmalloc_ptr<char> *rest, bool *force)
> +{
> +  /* Set up the defaults.  */
> +  cond_string->reset ();
> +  rest->reset ();
> +  *thread = -1;
> +  *inferior = -1;
> +  *task = -1;
> +  *force = false;
> +
> +  if (tok == nullptr)
> +    return;
> +
> +  const char *cond_start = nullptr;
> +  const char *cond_end = nullptr;
> +  parse_direction direction = parse_direction::forward;
> +  while (*tok != '\0')
> +    {
> +      /* Find the next token.  If moving backward and this token starts at
> +	 the same location as the condition then we must have found the
> +	 other end of the condition string -- we're done.  */
> +      token t = find_next_token (&tok, direction);
> +      if (direction == parse_direction::backward && t.start () <= cond_start)
> +	{
> +	  cond_end = t.end () + 1;
> +	  break;
> +	}
> +
> +      /* We only have a single flag option to check for.  All the other
> +	 options take a value so require an additional token to be found.  */
> +      if (t.length () > 0 && t.matches ("-force-condition"))

First thing, as mentioned above, I don’t think that "t.length () > 0"
can ever be false, so this part of the test can safely be removed.

Also, it seems to be a new behavior linked to the fact that you don’t
use "parse_exp_1" anymore.  Before this patch, "-force-condition" could
not really be placed after the condition (at least with C/C++ as current
language) as the expression parser would try to consume it.  Now it can
be partially matched, which can give surprising results.

Doing

    break foo if 0 -

is now interpreted as

    break foo if 0 -force-condition

this used to be an error.

Similarly, doing

    break foo if var -f

used to be interpreted as

    break foo if (var - f)

which could be valid if "var" and "f" are valid, but with the patch it
now interprets it as

    break foo if var -force-condition

I don’t expect many users will ever notice such change in behavior,
but overall I would find that it makes more sense to only match
"-force-condition" entirely.

This would be consistent with the parsing behavior if -force-condition
is placed before the condition.  In such case,
linespec_lexer_lex_keyword only does a full match.


> +	{
> +	  *force = true;
> +	  continue;
> +	}
> +
> +      /* Maybe the first token was the last token in the string.  If this
> +	 is the case then we definitely can't try to extract a value
> +	 token.  This also means that the token T is meaningless.  Reset
> +	 TOK to point at the start of the unknown content and break out of
> +	 the loop.  We'll record the unknown part of the string outside of
> +	 the scanning loop (below).  */
> +      if (direction == parse_direction::forward && *tok == '\0')
> +	{
> +	  tok = t.start ();
> +	  break;
> +	}
> +
> +      /* As before, find the next token and, if we are scanning backwards,
> +	 check that we have not reached the start of the condition string.  */
> +      token v = find_next_token (&tok, direction);
> +      if (direction == parse_direction::backward && v.start () <= cond_start)
> +	{
> +	  /* Use token T here as that must also be part of the condition
> +	     string.  */
> +	  cond_end = t.end () + 1;
> +	  break;
> +	}
> +
> +      /* When moving backward we will first parse the value token then the
> +	 keyword token, so swap them now.  */
> +      if (direction == parse_direction::backward)
> +	std::swap (t, v);
> +
> +      /* Check for valid option in token T.  If we find a valid option then
> +	 parse the value from the token V.  Except for 'if', that's handled
> +	 differently.
> +
> +         For the 'if' token we need to capture the entire condition
> +         string, so record the start of the condition string and then
> +         start scanning backwards looking for the end of the condition
> +         string.  */

Initial indentation with tabs here.

> +      if (direction == parse_direction::forward && t.length () > 0

dito for t.length

> +	  && t.matches ("if"))
> +	{
> +	  cond_start = v.start ();
> +	  tok = tok + strlen (tok);
> +	  gdb_assert (*tok == '\0');
> +	  --tok;
> +	  direction = parse_direction::backward;
> +	  continue;
> +	}
> +      else if (t.length () > 0 && t.matches ("thread"))

dito for t.length


Also,

    b foo if 0 t 1

is ambiguous.  The "t" could match both "task" and "thread", and it
really is an implementation detail that "thread" is tested first.

This ambiguity used to exist before the patch.

However, since parsing "thread" or "task" just after the linespec does
not accept partial matches, and it does not look that partial matching
has ever been documented, I’d be in favor of just removing partial
matching.

WDYT?

> +	{
> +	  const char *tmptok;
> +	  struct thread_info *thr;
> +
> +	  if (*thread != -1)
> +	    error(_("You can specify only one thread."));
> +
> +	  if (*task != -1 || *inferior != -1)
> +	    error (_("You can specify only one of thread, inferior, or task."));
> +
> +	  thr = parse_thread_id (v.start (), &tmptok);
> +	  const char *expected_end = skip_spaces (v.end () + 1);
> +	  if (tmptok != expected_end)
> +	    error (_("Junk after thread keyword."));
> +	  *thread = thr->global_num;
> +	}
> +      else if (t.length () > 0 && t.matches ("inferior"))

dito for t.length

> +	{
> +	  char *tmptok;
> +
> +	  if (*inferior != -1)
> +	    error(_("You can specify only one inferior."));
> +
> +	  if (*task != -1 || *thread != -1)
> +	    error (_("You can specify only one of thread, inferior, or task."));
> +
> +	  *inferior = strtol (v.start (), &tmptok, 0);
> +	  const char *expected_end = v.end () + 1;
> +	  if (tmptok != expected_end)
> +	    error (_("Junk after inferior keyword."));
> +	}
> +      else if (t.length () > 0 && t.matches ("task"))

dito for t.length

> +	{
> +	  char *tmptok;
> +
> +	  if (*task != -1)
> +	    error(_("You can specify only one task."));
> +
> +	  if (*thread != -1 || *inferior != -1)
> +	    error (_("You can specify only one of thread, inferior, or task."));
> +
> +	  *task = strtol (v.start (), &tmptok, 0);
> +	  const char *expected_end = v.end () + 1;
> +	  if (tmptok != expected_end)
> +	    error (_("Junk after task keyword."));
> +	  if (!valid_task_id (*task))
> +	    error (_("Unknown task %d."), *task);
> +	}
> +      else
> +	{
> +	  /* An unknown token.  If we are scanning forward then reset TOK
> +	     to point at the start of the unknown content, we record this
> +	     outside of the scanning loop (below).
> +
> +	     If we are scanning backward then unknown content is assumed to
> +	     be the other end of the condition string, obviously, this is
> +	     just a heuristic, we could be looking at a mistyped command
> +	     line, but this will be spotted when the condition is
> +	     eventually evaluated.
> +
> +	     Either way, no more scanning is required after this.  */
> +	  if (direction == parse_direction::forward)
> +	    tok = t.start ();
> +	  else
> +	    {
> +	      gdb_assert (direction == parse_direction::backward);
> +	      cond_end = v.end () + 1;
> +	    }
> +	  break;
> +	}
> +    }
> +
> +  if (cond_start != nullptr)
> +    {
> +      /* If we found the start of a condition string then we should have
> +	 switched to backward scan mode, and found the end of the condition
> +	 string.  Capture the whole condition string into COND_STRING now.  */
> +      gdb_assert (direction == parse_direction::backward);
> +      gdb_assert (cond_end != nullptr);
> +      cond_string->reset (savestring (cond_start, cond_end - cond_start));
> +    }
> +  else if (*tok != '\0')
> +    {
> +      /* If we didn't have a condition start pointer then we should still
> +	 be in forward scanning mode.  If we didn't reach the end of the
> +	 input string (TOK is not at the null character) then the rest of
> +	 the input string is garbage that we didn't understand.
> +
> +	 Record the unknown content into REST.  The caller of this function
> +	 will report this as an error later on.  We could report the error
> +	 here, but we prefer to allow the caller to run other checks, and
> +	 prioritise other errors before reporting this problem.  */
> +      gdb_assert (direction == parse_direction::forward);
> +      rest->reset (savestring (tok, strlen (tok)));
> +    }
> +}
> +
> +#if GDB_SELF_TEST
> +
> +namespace selftests {
> +
> +/* Run a single test of the create_breakpoint_parse_arg_string function.
> +   INPUT is passed to create_breakpoint_parse_arg_string while all other
> +   arguments are the expected output from
> +   create_breakpoint_parse_arg_string.  */
> +
> +static void
> +test (const char *input, const char *condition, int thread = -1,
> +      int inferior = -1, int task = -1, bool force = false,
> +      const char *rest = nullptr)
> +{
> +  gdb::unique_xmalloc_ptr<char> extracted_condition;
> +  gdb::unique_xmalloc_ptr<char> extracted_rest;
> +  int extracted_thread, extracted_inferior, extracted_task;
> +  bool extracted_force_condition;
> +  std::string exception_msg;
> +
> +  try
> +    {
> +      create_breakpoint_parse_arg_string (input, &extracted_condition,
> +					  &extracted_thread,
> +					  &extracted_inferior,
> +					  &extracted_task, &extracted_rest,
> +					  &extracted_force_condition);
> +    }
> +  catch (const gdb_exception_error &ex)
> +    {
> +      string_file buf;
> +
> +      exception_print (&buf, ex);
> +      exception_msg = buf.release ();
> +    }
> +
> +  if ((condition == nullptr) != (extracted_condition.get () == nullptr)
> +      || (condition != nullptr
> +	  && strcmp (condition, extracted_condition.get ()) != 0)
> +      || (rest == nullptr) != (extracted_rest.get () == nullptr)
> +      || (rest != nullptr && strcmp (rest, extracted_rest.get ()) != 0)
> +      || thread != extracted_thread
> +      || inferior != extracted_inferior
> +      || task != extracted_task
> +      || force != extracted_force_condition
> +      || !exception_msg.empty ())
> +    {
> +      if (run_verbose ())
> +	{
> +	  debug_printf ("input: '%s'\n", input);
> +	  debug_printf ("condition: '%s'\n", extracted_condition.get ());
> +	  debug_printf ("rest: '%s'\n", extracted_rest.get ());
> +	  debug_printf ("thread: %d\n", extracted_thread);
> +	  debug_printf ("inferior: %d\n", extracted_inferior);
> +	  debug_printf ("task: %d\n", extracted_task);
> +	  debug_printf ("forced: %s\n",
> +			extracted_force_condition ? "true" : "false");
> +	  debug_printf ("exception: '%s'\n", exception_msg.c_str ());
> +	}
> +
> +      /* Report the failure.  */
> +      SELF_CHECK (false);
> +    }
> +}
> +
> +/* Test the create_breakpoint_parse_arg_string function.  Just wraps
> +   multiple calls to the test function above.  */
> +
> +static void
> +create_breakpoint_parse_arg_string_tests (void)
> +{
> +  gdbarch *arch = current_inferior ()->gdbarch;
> +  scoped_restore_current_pspace_and_thread restore;
> +  scoped_mock_context<test_target_ops> mock_target (arch);
> +
> +  int global_thread_num = mock_target.mock_thread.global_num;
> +
> +  test ("  if blah  ", "blah");
> +  test (" if blah thread 1", "blah", global_thread_num);
> +  test (" if blah inferior 1", "blah", -1, 1);
> +  test (" if blah thread 1  ", "blah", global_thread_num);
> +  test ("thread 1 woof", nullptr, global_thread_num, -1, -1, false, "woof");
> +  test ("thread 1 X", nullptr, global_thread_num, -1, -1, false, "X");
> +  test (" if blah thread 1 -force-condition", "blah", global_thread_num,
> +	-1, -1, true);
> +  test (" -force-condition if blah thread 1", "blah", global_thread_num,
> +	-1, -1, true);
> +  test (" -force-condition if blah thread 1  ", "blah", global_thread_num,
> +	-1, -1, true);
> +  test ("thread 1 -force-condition if blah", "blah", global_thread_num,
> +	-1, -1, true);
> +  test ("if (A::outer::func ())", "(A::outer::func ())");
> +}
> +
> +} // namespace selftests
> +#endif /* GDB_SELF_TEST */
> +
> +void _initialize_break_cond_parse ();
> +void
> +_initialize_break_cond_parse ()
> +{
> +#if GDB_SELF_TEST
> +  selftests::register_test
> +    ("create_breakpoint_parse_arg_string",
> +     selftests::create_breakpoint_parse_arg_string_tests);
> +#endif
> +}
> diff --git a/gdb/break-cond-parse.h b/gdb/break-cond-parse.h
> new file mode 100644
> index 00000000000..b08b6fc6cc9
> --- /dev/null
> +++ b/gdb/break-cond-parse.h
> @@ -0,0 +1,49 @@
> +/* Copyright (C) 2023 Free Software Foundation, Inc.
> +
> +   This file is part of GDB.
> +
> +   This program is free software; you can redistribute it and/or modify
> +   it under the terms of the GNU General Public License as published by
> +   the Free Software Foundation; either version 3 of the License, or
> +   (at your option) any later version.
> +
> +   This program is distributed in the hope that it will be useful,
> +   but WITHOUT ANY WARRANTY; without even the implied warranty of
> +   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
> +   GNU General Public License for more details.
> +
> +   You should have received a copy of the GNU General Public License
> +   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
> +
> +#if !defined (BREAK_COND_PARSE_H)
> +#define BREAK_COND_PARSE_H 1
> +
> +/* Given TOK, a string possibly containing a condition, thread, inferior,
> +   task and force-condition flag, as accepted by the 'break' command,
> +   extract the condition string, thread, inferior, task number, and the
> +   force_condition flag, then set *COND_STRING, *THREAD, *INFERIOR, *TASK,
> +   and *FORCE.
> +
> +   As TOK is parsed, if an unknown keyword is encountered before the 'if'
> +   keyword then everything starting from the unknown keyword is placed into
> +   *REST.
> +
> +   Both *COND and *REST are initialized to nullptr.  If no 'if' keyword is
> +   found then *COND will be returned as nullptr.  If no unknown content is
> +   found then *REST is returned as nullptr.
> +
> +   If no thread is found, *THREAD is set to -1.  If no inferior is found,
> +   *INFERIOR is set to -1.  If no task is found, *TASK is set to -1.  If
> +   the -force-condition flag is not found then *FORCE is set to false.
> +
> +   Due to the free-form nature that the string TOK might take (a 'thread'
> +   keyword can appear before or after an 'if' condition) then we end up
> +   having to check for keywords from both the start of TOK and the end of
> +   TOK.  */
> +
> +extern void create_breakpoint_parse_arg_string
> +  (const char *tok, gdb::unique_xmalloc_ptr<char> *cond_string,
> +   int *thread, int *inferior, int *task,
> +   gdb::unique_xmalloc_ptr<char> *rest, bool *force);
> +
> +#endif
> diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
> index 5a608ba2495..50225f55522 100644
> --- a/gdb/breakpoint.c
> +++ b/gdb/breakpoint.c
> @@ -70,6 +70,7 @@
>  #include "cli/cli-style.h"
>  #include "cli/cli-decode.h"
>  #include <unordered_set>
> +#include "break-cond-parse.h"
>  
>  /* readline include files */
>  #include "readline/tilde.h"
> @@ -6340,20 +6341,7 @@ print_breakpoint_location (const breakpoint *b, const bp_location *loc)
>        uiout->field_stream ("at", stb);
>      }
>    else
> -    {
> -      uiout->field_string ("pending", b->locspec->to_string ());
> -      /* If extra_string is available, it could be holding a condition
> -	 or dprintf arguments.  In either case, make sure it is printed,
> -	 too, but only for non-MI streams.  */
> -      if (!uiout->is_mi_like_p () && b->extra_string != NULL)
> -	{
> -	  if (b->type == bp_dprintf)
> -	    uiout->text (",");
> -	  else
> -	    uiout->text (" ");
> -	  uiout->text (b->extra_string.get ());
> -	}
> -    }
> +    uiout->field_string ("pending", b->locspec->to_string ());
>  
>    if (loc && is_breakpoint (b)
>        && breakpoint_condition_evaluation_mode () == condition_evaluation_target
> @@ -8718,8 +8706,8 @@ code_breakpoint::code_breakpoint (struct gdbarch *gdbarch_,
>        gdb_assert (extra_string != nullptr);
>        update_dprintf_command_list (this);
>      }
> -  else if (extra_string != nullptr)
> -    error (_("Garbage '%s' at end of command"), extra_string.get ());
> +  else
> +    gdb_assert (extra_string == nullptr);
>  
>    /* The order of the locations is now stable.  Set the location
>       condition using the location's number.  */
> @@ -8947,197 +8935,6 @@ check_fast_tracepoint_sals (struct gdbarch *gdbarch,
>      }
>  }
>  
> -/* Given TOK, a string specification of condition and thread, as accepted
> -   by the 'break' command, extract the condition string into *COND_STRING.
> -   If no condition string is found then *COND_STRING is set to nullptr.
> -
> -   If the breakpoint specification has an associated thread, task, or
> -   inferior, these are extracted into *THREAD, *TASK, and *INFERIOR
> -   respectively, otherwise these arguments are set to -1 (for THREAD and
> -   INFERIOR) or 0 (for TASK).
> -
> -   PC identifies the context at which the condition should be parsed.  */
> -
> -static void
> -find_condition_and_thread (const char *tok, CORE_ADDR pc,
> -			   gdb::unique_xmalloc_ptr<char> *cond_string,
> -			   int *thread, int *inferior, int *task,
> -			   gdb::unique_xmalloc_ptr<char> *rest)
> -{
> -  cond_string->reset ();
> -  *thread = -1;
> -  *inferior = -1;
> -  *task = -1;
> -  rest->reset ();
> -  bool force = false;
> -
> -  while (tok && *tok)
> -    {
> -      const char *end_tok;
> -      int toklen;
> -      const char *cond_start = NULL;
> -      const char *cond_end = NULL;
> -
> -      tok = skip_spaces (tok);
> -
> -      if ((*tok == '"' || *tok == ',') && rest)
> -	{
> -	  rest->reset (savestring (tok, strlen (tok)));
> -	  break;
> -	}
> -
> -      end_tok = skip_to_space (tok);
> -
> -      toklen = end_tok - tok;
> -
> -      if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
> -	{
> -	  tok = cond_start = end_tok + 1;
> -	  try
> -	    {
> -	      parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
> -	    }
> -	  catch (const gdb_exception_error &)
> -	    {
> -	      if (!force)
> -		throw;
> -	      else
> -		tok = tok + strlen (tok);
> -	    }
> -	  cond_end = tok;
> -	  cond_string->reset (savestring (cond_start, cond_end - cond_start));
> -	}
> -      else if (toklen >= 1 && strncmp (tok, "-force-condition", toklen) == 0)
> -	{
> -	  tok = tok + toklen;
> -	  force = true;
> -	}
> -      else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
> -	{
> -	  const char *tmptok;
> -	  struct thread_info *thr;
> -
> -	  if (*thread != -1)
> -	    error(_("You can specify only one thread."));
> -
> -	  if (*task != -1)
> -	    error (_("You can specify only one of thread or task."));
> -
> -	  if (*inferior != -1)
> -	    error (_("You can specify only one of inferior or thread."));
> -
> -	  tok = end_tok + 1;
> -	  thr = parse_thread_id (tok, &tmptok);
> -	  if (tok == tmptok)
> -	    error (_("Junk after thread keyword."));
> -	  *thread = thr->global_num;
> -	  tok = tmptok;
> -	}
> -      else if (toklen >= 1 && strncmp (tok, "inferior", toklen) == 0)
> -	{
> -	  if (*inferior != -1)
> -	    error(_("You can specify only one inferior."));
> -
> -	  if (*task != -1)
> -	    error (_("You can specify only one of inferior or task."));
> -
> -	  if (*thread != -1)
> -	    error (_("You can specify only one of inferior or thread."));
> -
> -	  char *tmptok;
> -	  tok = end_tok + 1;
> -	  *inferior = strtol (tok, &tmptok, 0);
> -	  if (tok == tmptok)
> -	    error (_("Junk after inferior keyword."));
> -	  if (!valid_global_inferior_id (*inferior))
> -	    error (_("Unknown inferior number %d."), *inferior);
> -	  tok = tmptok;
> -	}
> -      else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
> -	{
> -	  char *tmptok;
> -
> -	  if (*task != -1)
> -	    error(_("You can specify only one task."));
> -
> -	  if (*thread != -1)
> -	    error (_("You can specify only one of thread or task."));
> -
> -	  if (*inferior != -1)
> -	    error (_("You can specify only one of inferior or task."));
> -
> -	  tok = end_tok + 1;
> -	  *task = strtol (tok, &tmptok, 0);
> -	  if (tok == tmptok)
> -	    error (_("Junk after task keyword."));
> -	  if (!valid_task_id (*task))
> -	    error (_("Unknown task %d."), *task);
> -	  tok = tmptok;
> -	}
> -      else if (rest)
> -	{
> -	  rest->reset (savestring (tok, strlen (tok)));
> -	  break;
> -	}
> -      else
> -	error (_("Junk at end of arguments."));
> -    }
> -}
> -
> -/* Call 'find_condition_and_thread' for each sal in SALS until a parse
> -   succeeds.  The parsed values are written to COND_STRING, THREAD,
> -   TASK, and REST.  See the comment of 'find_condition_and_thread'
> -   for the description of these parameters and INPUT.  */
> -
> -static void
> -find_condition_and_thread_for_sals (const std::vector<symtab_and_line> &sals,
> -				    const char *input,
> -				    gdb::unique_xmalloc_ptr<char> *cond_string,
> -				    int *thread, int *inferior, int *task,
> -				    gdb::unique_xmalloc_ptr<char> *rest)
> -{
> -  int num_failures = 0;
> -  for (auto &sal : sals)
> -    {
> -      gdb::unique_xmalloc_ptr<char> cond;
> -      int thread_id = -1;
> -      int inferior_id = -1;
> -      int task_id = -1;
> -      gdb::unique_xmalloc_ptr<char> remaining;
> -
> -      /* Here we want to parse 'arg' to separate condition from thread
> -	 number.  But because parsing happens in a context and the
> -	 contexts of sals might be different, try each until there is
> -	 success.  Finding one successful parse is sufficient for our
> -	 goal.  When setting the breakpoint we'll re-parse the
> -	 condition in the context of each sal.  */
> -      try
> -	{
> -	  find_condition_and_thread (input, sal.pc, &cond, &thread_id,
> -				     &inferior_id, &task_id, &remaining);
> -	  *cond_string = std::move (cond);
> -	  /* A value of -1 indicates that these fields are unset.  At most
> -	     one of these fields should be set (to a value other than -1)
> -	     at this point.  */
> -	  gdb_assert (((thread_id == -1 ? 1 : 0)
> -		       + (task_id == -1 ? 1 : 0)
> -		       + (inferior_id == -1 ? 1 : 0)) >= 2);
> -	  *thread = thread_id;
> -	  *inferior = inferior_id;
> -	  *task = task_id;
> -	  *rest = std::move (remaining);
> -	  break;
> -	}
> -      catch (const gdb_exception_error &e)
> -	{
> -	  num_failures++;
> -	  /* If no sal remains, do not continue.  */
> -	  if (num_failures == sals.size ())
> -	    throw;
> -	}
> -    }
> -}
> -
>  /* Decode a static tracepoint marker spec.  */
>  
>  static std::vector<symtab_and_line>
> @@ -9255,6 +9052,46 @@ create_breakpoint (struct gdbarch *gdbarch,
>  	      || (type_wanted != bp_dprintf
>  		  && (extra_string == nullptr || parse_extra)));
>  
> +  /* Will hold either copies of the similarly named function argument, or
> +     will hold a modified version of the function argument, depending on
> +     the value of PARSE_EXTRA.  */
> +  gdb::unique_xmalloc_ptr<char> cond_string_copy;
> +  gdb::unique_xmalloc_ptr<char> extra_string_copy;
> +
> +  if (parse_extra)
> +    {
> +      /* Parse EXTRA_STRING splitting the parts out.  */
> +      create_breakpoint_parse_arg_string (extra_string, &cond_string_copy,
> +					  &thread, &inferior, &task,
> +					  &extra_string_copy,
> +					  &force_condition);
> +
> +      /* We could check that EXTRA_STRING_COPY is empty at this point -- it
> +	 should be, as we only get here for things that are not bp_dprintf,
> +	 however, we prefer to give the location spec parser a chance to
> +	 run first, this means the user will get errors about invalid
> +	 location spec instead of an error about garbage at the end of the
> +	 command line.
> +
> +	 We still do the EXTRA_STRING_COPY is empty check, just later in
> +	 this function.  */
> +
> +      gdb_assert (thread == -1 || thread > 0);
> +      gdb_assert (task == -1 || task > 0);
> +      gdb_assert (inferior == -1 || inferior > 0);
> +    }
> +  else
> +    {
> +      if (cond_string != nullptr)
> +	cond_string_copy.reset (xstrdup (cond_string));
> +      if (extra_string != nullptr)
> +	extra_string_copy.reset (xstrdup (extra_string));
> +    }
> +
> +  /* Clear these.  Updated values are now held in the *_copy locals.  */
> +  cond_string = nullptr;
> +  extra_string = nullptr;
> +
>    try
>      {
>        ops->create_sals_from_location_spec (locspec, &canonical);
> @@ -9290,6 +9127,13 @@ create_breakpoint (struct gdbarch *gdbarch,
>  	throw;
>      }
>  
> +  /* The only bp_dprintf should have anything in EXTRA_STRING_COPY by this
> +     point.  For all other breakpoints this indicates an error.  We could
> +     place this check earlier in the function, but we prefer to see errors
> +     from the location spec parser before we see this error message.  */
> +  if (type_wanted != bp_dprintf && extra_string_copy.get () != nullptr)
> +    error (_("Garbage '%s' at end of command"), extra_string_copy.get ());
> +
>    if (!pending && canonical.lsals.empty ())
>      return 0;
>  
> @@ -9313,63 +9157,31 @@ create_breakpoint (struct gdbarch *gdbarch,
>       breakpoint.  */
>    if (!pending)
>      {
> -      gdb::unique_xmalloc_ptr<char> cond_string_copy;
> -      gdb::unique_xmalloc_ptr<char> extra_string_copy;
> -
> -      if (parse_extra)
> +      /* Check the validity of the condition.  We should error out if the
> +	 condition is invalid at all of the locations and if it is not
> +	 forced.  In the PARSE_EXTRA case above, this check is done when
> +	 parsing the EXTRA_STRING.  */
> +      if (cond_string_copy.get () != nullptr && !force_condition)
>  	{
> -	  gdb_assert (type_wanted != bp_dprintf);
> -
> -	  gdb::unique_xmalloc_ptr<char> rest;
> -	  gdb::unique_xmalloc_ptr<char> cond;
> -
> -	  const linespec_sals &lsal = canonical.lsals[0];
> -
> -	  find_condition_and_thread_for_sals (lsal.sals, extra_string,
> -					      &cond, &thread, &inferior,
> -					      &task, &rest);
> -
> -	  if (rest.get () != nullptr && *(rest.get ()) != '\0')
> -	    error (_("Garbage '%s' at end of command"), rest.get ());
> -
> -	  cond_string_copy = std::move (cond);
> -	  extra_string_copy = std::move (rest);
> -	}
> -      else
> -	{
> -	  /* Check the validity of the condition.  We should error out
> -	     if the condition is invalid at all of the locations and
> -	     if it is not forced.  In the PARSE_EXTRA case above, this
> -	     check is done when parsing the EXTRA_STRING.  */
> -	  if (cond_string != nullptr && !force_condition)
> +	  int num_failures = 0;
> +          const linespec_sals &lsal = canonical.lsals[0];

Indentation issue.

> +	  for (const auto &sal : lsal.sals)
>  	    {
> -	      int num_failures = 0;
> -	      const linespec_sals &lsal = canonical.lsals[0];
> -	      for (const auto &sal : lsal.sals)
> +	      const char *cond = cond_string_copy.get ();
> +	      try
>  		{
> -		  const char *cond = cond_string;
> -		  try
> -		    {
> -		      parse_exp_1 (&cond, sal.pc, block_for_pc (sal.pc), 0);
> -		      /* One success is sufficient to keep going.  */
> -		      break;
> -		    }
> -		  catch (const gdb_exception_error &)
> -		    {
> -		      num_failures++;
> -		      /* If this is the last sal, error out.  */
> -		      if (num_failures == lsal.sals.size ())
> -			throw;
> -		    }
> +		  parse_exp_1 (&cond, sal.pc, block_for_pc (sal.pc), 0);
> +		  /* One success is sufficient to keep going.  */
> +		  break;
> +		}
> +	      catch (const gdb_exception_error &)
> +		{
> +		  num_failures++;
> +		  /* If this is the last sal, error out.  */
> +		  if (num_failures == lsal.sals.size ())
> +		    throw;
>  		}
>  	    }
> -
> -	  /* Create a private copy of condition string.  */
> -	  if (cond_string)
> -	    cond_string_copy.reset (xstrdup (cond_string));
> -	  /* Create a private copy of any extra string.  */
> -	  if (extra_string)
> -	    extra_string_copy.reset (xstrdup (extra_string));
>  	}
>  
>        ops->create_breakpoints_sal (gdbarch, &canonical,
> @@ -9386,21 +9198,16 @@ create_breakpoint (struct gdbarch *gdbarch,
>  								 type_wanted);
>        b->locspec = locspec->clone ();
>  
> -      if (parse_extra)
> -	b->cond_string = NULL;
> -      else
> -	{
> -	  /* Create a private copy of condition string.  */
> -	  b->cond_string.reset (cond_string != NULL
> -				? xstrdup (cond_string)
> -				: NULL);
> -	  b->thread = thread;
> -	}
> +      /* Create a private copy of the condition string.  */
> +      b->cond_string = std::move (cond_string_copy);
> +
> +      b->thread = thread;
> +      b->task = task;
> +      b->inferior = inferior;
>  
>        /* Create a private copy of any extra string.  */
> -      b->extra_string.reset (extra_string != NULL
> -			     ? xstrdup (extra_string)
> -			     : NULL);
> +      b->extra_string = std::move (extra_string_copy);
> +
>        b->ignore_count = ignore_count;
>        b->disposition = tempflag ? disp_del : disp_donttouch;
>        b->condition_not_parsed = 1;
> @@ -9409,9 +9216,12 @@ create_breakpoint (struct gdbarch *gdbarch,
>  	   && type_wanted != bp_hardware_breakpoint) || thread != -1)
>  	b->pspace = current_program_space;
>  
> +      if (b->type == bp_dprintf)
> +	update_dprintf_command_list (b.get ());
> +
>        install_breakpoint (internal, std::move (b), 0);
>      }
> -  
> +
>    if (canonical.lsals.size () > 1)
>      {
>        warning (_("Multiple breakpoints were set.\nUse the "
> @@ -13145,24 +12955,6 @@ code_breakpoint::location_spec_to_sals (location_spec *locspec,
>      {
>        for (auto &sal : sals)
>  	resolve_sal_pc (&sal);
> -      if (condition_not_parsed && extra_string != NULL)
> -	{
> -	  gdb::unique_xmalloc_ptr<char> local_cond, local_extra;
> -	  int local_thread, local_task, local_inferior;
> -
> -	  find_condition_and_thread_for_sals (sals, extra_string.get (),
> -					      &local_cond, &local_thread,
> -					      &local_inferior,
> -					      &local_task, &local_extra);
> -	  gdb_assert (cond_string == nullptr);
> -	  if (local_cond != nullptr)
> -	    cond_string = std::move (local_cond);
> -	  thread = local_thread;
> -	  task = local_task;
> -	  if (local_extra != nullptr)
> -	    extra_string = std::move (local_extra);
> -	  condition_not_parsed = 0;
> -	}
>  
>        if (type == bp_static_tracepoint)
>  	sals[0] = update_static_tracepoint (this, sals[0]);
> diff --git a/gdb/testsuite/gdb.ada/tasks.exp b/gdb/testsuite/gdb.ada/tasks.exp
> index 603d43f7c36..337ee1b6f07 100644
> --- a/gdb/testsuite/gdb.ada/tasks.exp
> +++ b/gdb/testsuite/gdb.ada/tasks.exp
> @@ -55,11 +55,11 @@ gdb_test "watch j task 1 task 3" "You can specify only one task\\."
>  
>  # Check that attempting to combine 'task' and 'thread' gives an error.
>  gdb_test "break break_me task 1 thread 1" \
> -    "You can specify only one of thread or task\\."
> +    "You can specify only one of thread, inferior, or task\\."
>  gdb_test "break break_me thread 1 task 1" \
> -    "You can specify only one of thread or task\\."
> +    "You can specify only one of thread, inferior, or task\\."
>  gdb_test "break break_me inferior 1 task 1" \
> -    "You can specify only one of inferior or task\\."
> +    "You can specify only one of thread, inferior, or task\\."
>  gdb_test "watch j task 1 thread 1" \
>      "You can specify only one of thread or task\\."
>  gdb_test "watch j thread 1 task 1" \
> diff --git a/gdb/testsuite/gdb.base/condbreak.exp b/gdb/testsuite/gdb.base/condbreak.exp
> index a5b2a28701b..50ae82c3f32 100644
> --- a/gdb/testsuite/gdb.base/condbreak.exp
> +++ b/gdb/testsuite/gdb.base/condbreak.exp
> @@ -179,6 +179,10 @@ gdb_test "break -q main if (1==1) thread 999" \
>      "Unknown thread 999\\."
>  gdb_test "break -q main thread 999 if (1==1)" \
>      "Unknown thread 999\\."
> +gdb_test "break -q main if (1==1) thread 999 -force-condition" \
> +    "Unknown thread 999\\."
> +gdb_test "break -q main thread 999 if (1==1) -force-condition" \
> +    "Unknown thread 999\\."
>  
>  # Verify that both if and thread can be distinguished from a breakpoint
>  # address expression.
> @@ -186,20 +190,34 @@ gdb_test "break *main if (1==1) thread 999" \
>      "Unknown thread 999\\."
>  gdb_test "break *main thread 999 if (1==1)" \
>      "Unknown thread 999\\."
> +gdb_test "break *main if (1==1) thread 999 -force-condition" \
> +    "Unknown thread 999\\."
> +gdb_test "break *main thread 999 if (1==1) -force-condition" \
> +    "Unknown thread 999\\."
>  
>  # Similarly for task.
>  gdb_test "break *main if (1==1) task 999" \
>      "Unknown task 999\\."
>  gdb_test "break *main task 999 if (1==1)" \
>      "Unknown task 999\\."
> +gdb_test "break *main if (1==1) task 999 -force-condition" \
> +    "Unknown task 999\\."
> +gdb_test "break *main task 999 if (1==1) -force-condition" \
> +    "Unknown task 999\\."
>  
> -# GDB accepts abbreviations for "thread" and "task".
> +# GDB accepts abbreviations for "thread" and "task" and "-force-condition"
>  gdb_test "break *main if (1==1) t 999" \
>      "Unknown thread 999\\."

As stated above, I’m not a fan of this way to handle the ambiguity, but
at least it have been tested.  Something like "b *main t 999 if (1==1)"
does not work, which I find inconsistent.

>  gdb_test "break *main if (1==1) th 999" \
>      "Unknown thread 999\\."
>  gdb_test "break *main if (1==1) ta 999" \
>      "Unknown task 999\\."
> +gdb_test "break *main if (1==1) t 999 -force" \
> +    "Unknown thread 999\\."
> +gdb_test "break *main if (1==1) th 999 -force" \
> +    "Unknown thread 999\\."
> +gdb_test "break *main if (1==1) ta 999 -force" \
> +    "Unknown task 999\\."
>  
>  set test "run until breakpoint at marker3"
>  gdb_test_multiple "continue" $test {
> diff --git a/gdb/testsuite/gdb.base/pending.exp b/gdb/testsuite/gdb.base/pending.exp
> index d7d3735000a..645f63bdb16 100644
> --- a/gdb/testsuite/gdb.base/pending.exp
> +++ b/gdb/testsuite/gdb.base/pending.exp
> @@ -170,7 +170,8 @@ gdb_test "info break" \
>  \[\t \]+stop only if k == 1.*
>  \[\t \]+print k.*
>  \[0-9\]+\[\t \]+breakpoint     keep y.* in main at .*$srcfile:$mainline.*
> -\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc if x > 3.*" \
> +\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc.*
> +\\s+stop only if x > 3.*" \
>  "multiple pending breakpoints"
>  
>  
> @@ -195,8 +196,10 @@ gdb_test "info break" \
>  \[\t \]+stop only if k == 1.*
>  \[\t \]+print k.*
>  \[0-9\]+\[\t \]+breakpoint     keep y.* in main at .*$srcfile:$mainline.*
> -\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc if x > 3.*
> -\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp3_loc.*ignore next 2 hits.*" \
> +\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc.*
> +\\s+stop only if x > 3.*
> +\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp3_loc.*
> +\\s+ignore next 2 hits.*" \
>  "multiple pending breakpoints 2"
>  
>  #
> @@ -267,3 +270,17 @@ gdb_test "info break" \
>  \[0-9\]+\[\t \]+breakpoint     keep y.* in main at .*$srcfile:$mainline.*
>  \[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*imaginary.*" \
>  "verify pending breakpoint after restart"
> +
> +# Test GDB's parsing of pending breakpoint thread and condition.
> +
> +gdb_test_no_output "set breakpoint pending on"
> +gdb_test "break foo if (unknown_var && another_unknown_var) thread 1" \
> +    "Breakpoint $decimal \\(foo\\) pending\\."
> +set bpnum [get_integer_valueof "\$bpnum" "*INVALID" \
> +	       "get number for foo breakpoint"]
> +gdb_test "info breakpoints $bpnum" \
> +    [multi_line \
> +	 "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
> +	 "\\s+stop only if \\(unknown_var && another_unknown_var\\)" \
> +	 "\\s+stop only in thread 1"] \
> +    "check pending breakpoint on foo"
> diff --git a/gdb/testsuite/gdb.linespec/explicit.exp b/gdb/testsuite/gdb.linespec/explicit.exp
> index 668002d9038..8cbefe204ec 100644
> --- a/gdb/testsuite/gdb.linespec/explicit.exp
> +++ b/gdb/testsuite/gdb.linespec/explicit.exp
> @@ -575,7 +575,7 @@ namespace eval $testfile {
>  	      allow-pending]} {
>  	fail "set $tst"
>      } else {
> -	gdb_test "info break" ".*PENDING.*myfunction if foofoofoo == 1.*" $tst
> +	gdb_test "info break" ".*PENDING.*myfunction\r\n\\s+stop only if foofoofoo == 1.*" $tst
>      }
>  
>      gdb_exit
> @@ -586,7 +586,7 @@ namespace eval $testfile {
>  	      allow-pending]} {
>  	fail "set $tst"
>      } else {
> -	gdb_test "info break" ".*PENDING.*myfunction if arg == 0" $tst
> +	gdb_test "info break" ".*PENDING.*myfunction\r\n\\s+stop only if arg == 0" $tst
>  
>  	gdb_load [standard_output_file $exefile]
>  	gdb_test "info break" \
> diff --git a/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp b/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp
> index 28f52938aeb..bb9987a5572 100644
> --- a/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp
> +++ b/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp
> @@ -50,7 +50,8 @@ set bp_location1 [gdb_get_line_number "set breakpoint 1 here"]
>  # Set pending dprintf via MI.
>  set bp [mi_make_breakpoint_pending -number "1" -type "dprintf" \
>  	    -disp "keep" -enabled "y" -pending "pendfunc1" \
> -	    -original-location "pendfunc1"]
> +	    -original-location "pendfunc1" \
> +	    -script {\["printf \\\"hello\\\""\]}]
>  mi_gdb_test "-dprintf-insert -f pendfunc1 \"hello\"" \
>      ".*\\^done,$bp" "mi set dprintf"
>  
> diff --git a/gdb/testsuite/gdb.multi/inferior-specific-bp.exp b/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
> index 1f6573268da..b8aceabcad6 100644
> --- a/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
> +++ b/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
> @@ -51,9 +51,9 @@ if {![runto_main]} {
>  # this should fail.  Try with the keywords in both orders just in case the
>  # parser has a bug.
>  gdb_test "break foo thread 1.1 inferior 1" \
> -    "You can specify only one of inferior or thread\\."
> +    "You can specify only one of thread, inferior, or task\\."
>  gdb_test "break foo inferior 1 thread 1.1" \
> -    "You can specify only one of inferior or thread\\."
> +    "You can specify only one of thread, inferior, or task\\."
>  
>  # Try to create a breakpoint using the 'inferior' keyword multiple times.
>  gdb_test "break foo inferior 1 inferior 2" \
> diff --git a/gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c b/gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
> new file mode 100644
> index 00000000000..15d1b9833dd
> --- /dev/null
> +++ b/gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
> @@ -0,0 +1,22 @@
> +/* Copyright 2023 Free Software Foundation, Inc.
> +
> +   This program is free software; you can redistribute it and/or modify
> +   it under the terms of the GNU General Public License as published by
> +   the Free Software Foundation; either version 3 of the License, or
> +   (at your option) any later version.
> +
> +   This program is distributed in the hope that it will be useful,
> +   but WITHOUT ANY WARRANTY; without even the implied warranty of
> +   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
> +   GNU General Public License for more details.
> +
> +   You should have received a copy of the GNU General Public License
> +   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
> +
> +int global_var = 0;
> +
> +void
> +foo (int arg)
> +{
> +  global_var = arg;
> +}
> diff --git a/gdb/testsuite/gdb.threads/del-pending-thread-bp.c b/gdb/testsuite/gdb.threads/del-pending-thread-bp.c
> new file mode 100644
> index 00000000000..938e05bc4d7
> --- /dev/null
> +++ b/gdb/testsuite/gdb.threads/del-pending-thread-bp.c
> @@ -0,0 +1,85 @@
> +/* Copyright 2023 Free Software Foundation, Inc.
> +
> +   This program is free software; you can redistribute it and/or modify
> +   it under the terms of the GNU General Public License as published by
> +   the Free Software Foundation; either version 3 of the License, or
> +   (at your option) any later version.
> +
> +   This program is distributed in the hope that it will be useful,
> +   but WITHOUT ANY WARRANTY; without even the implied warranty of
> +   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
> +   GNU General Public License for more details.
> +
> +   You should have received a copy of the GNU General Public License
> +   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
> +
> +#include <dlfcn.h>
> +#include <pthread.h>
> +#include <stdlib.h>
> +
> +pthread_barrier_t barrier;
> +
> +static void
> +barrier_wait (pthread_barrier_t *b)
> +{
> +  int res = pthread_barrier_wait (b);
> +  if (res != 0 && res != PTHREAD_BARRIER_SERIAL_THREAD)
> +    abort ();
> +}
> +
> +static void *
> +thread_worker (void *arg)
> +{
> +  barrier_wait (&barrier);
> +  return NULL;
> +}
> +
> +void
> +breakpt ()
> +{
> +  /* Nothing.  */
> +}
> +
> +int
> +main (void)
> +{
> +  void *handle;
> +  void (*func)(int);
> +  pthread_t thread;
> +
> +  if (pthread_barrier_init (&barrier, NULL, 2) != 0)
> +    abort ();
> +
> +  if (pthread_create (&thread, NULL, thread_worker, NULL) != 0)
> +    abort ();
> +
> +  breakpt ();
> +
> +  /* Allow the worker thread to complete.  */
> +  barrier_wait (&barrier);
> +
> +  if (pthread_join (thread, NULL) != 0)
> +    abort ();
> +
> +  breakpt ();
> +
> +  /* Now load the shared library.  */
> +  handle = dlopen (SHLIB_NAME, RTLD_LAZY);
> +  if (handle == NULL)
> +    abort ();
> +
> +  /* Find the function symbol.  */
> +  func = (void (*)(int)) dlsym (handle, "foo");
> +
> +  /* Call the library function.  */
> +  func (1);
> +
> +  /* Unload the shared library.  */
> +  if (dlclose (handle) != 0)
> +    abort ();
> +
> +  breakpt ();
> +
> +  return 0;
> +}
> +
> diff --git a/gdb/testsuite/gdb.threads/del-pending-thread-bp.exp b/gdb/testsuite/gdb.threads/del-pending-thread-bp.exp
> new file mode 100644
> index 00000000000..4ed05eaa42d
> --- /dev/null
> +++ b/gdb/testsuite/gdb.threads/del-pending-thread-bp.exp
> @@ -0,0 +1,108 @@
> +# Copyright 2023 Free Software Foundation, Inc.
> +
> +# This program is free software; you can redistribute it and/or modify
> +# it under the terms of the GNU General Public License as published by
> +# the Free Software Foundation; either version 3 of the License, or
> +# (at your option) any later version.
> +#
> +# This program is distributed in the hope that it will be useful,
> +# but WITHOUT ANY WARRANTY; without even the implied warranty of
> +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
> +# GNU General Public License for more details.
> +#
> +# You should have received a copy of the GNU General Public License
> +# along with this program.  If not, see <http://www.gnu.org/licenses/>.
> +
> +# This test checks that pending thread-specific breakpoints are
> +# correctly deleted when the thread the breakpoint is for goes out of
> +# scope.
> +#
> +# We also check that we can't create a pending thread-specific
> +# breakpoint for a non-existent thread.
> +
> +require allow_shlib_tests
> +
> +standard_testfile
> +
> +set libname $testfile-lib
> +set srcfile_lib $srcdir/$subdir/$libname.c
> +set binfile_lib [standard_output_file $libname.so]
> +
> +if { [gdb_compile_shlib $srcfile_lib $binfile_lib {}] != "" } {
> +    untested "failed to compile shared library 1"
> +    return -1
> +}
> +
> +set binfile_lib_target [gdb_download_shlib $binfile_lib]
> +
> +if { [prepare_for_testing "failed to prepare" $testfile $srcfile \
> +	  [list debug \
> +	       additional_flags=-DSHLIB_NAME=\"$binfile_lib_target\" \
> +	       shlib_load pthreads]] } {
> +    return -1
> +}
> +
> +gdb_locate_shlib $binfile_lib
> +
> +if ![runto_main] {
> +    return 0
> +}
> +
> +# Run until we have two threads.
> +gdb_breakpoint "breakpt"
> +gdb_continue_to_breakpoint "first breakpt call"
> +
> +# Confirm that we have a thread '2'.
> +gdb_test "info threads" "\r\n\\s+2\\s+\[^\r\n\]+"
> +
> +# Create a pending, thread-specific, breakpoint on 'foo'.
> +gdb_breakpoint "foo thread 2" allow-pending
> +set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
> +	       "get breakpoint number"]
> +
> +# Check we can't create a pending thread-specific breakpoint for a
> +# non-existent thread.
> +gdb_test "with breakpoint pending on -- break foo thread 99" \
> +    "Unknown thread 99\\."
> +
> +# Continue to 'breakpt' again.  Don't use gdb_continue_to_breakpoint
> +# as we are looking for the thread exited and breakpoint deleted
> +# messages.
> +set output [list "Continuing\\."]
> +
> +if {!([target_info exists gdb_protocol]
> +      && ([target_info gdb_protocol] == "remote"
> +	  || [target_info gdb_protocol] == "extended-remote"))} {
> +    # Due to bug PR gdb/30129 we don't see the thread exited messages
> +    # for remote targets.  When this bit of this test can be cleaned
> +    # up.
> +    lappend output "\\\[Thread \[^\r\n\]+ exited\\\]"
> +}
> +
> +lappend output "Thread-specific breakpoint $bpnum deleted - thread 2 no longer in the thread list\\." \
> +    "" \
> +    "Thread 1 \[^\r\n\]+, breakpt \\(\\) at \[^\r\n\]+" \
> +    "$decimal\\s+\[^\r\n\]+"
> +
> +gdb_test "continue" \
> +    [multi_line {*}$output] \
> +    "second breakpt call"
> +
> +# Confirm breakpoint has been deleted.
> +gdb_test "info breakpoints $bpnum" \
> +    "No breakpoint or watchpoint matching '$bpnum'\\."
> +
> +# Continue again.  This will pass through 'foo'.  We should not stop
> +# in 'foo', the breakpoint has been deleted.  We should next stop in
> +# breakpt again.
> +gdb_test "continue" \
> +    [multi_line \
> +	 "Continuing\\." \
> +	 "" \
> +	 "Thread 1 \[^\r\n\]+ hit Breakpoint $decimal, breakpt \\(\\) at \[^\r\n\]+" \
> +	 "$decimal\\s+\[^\r\n\]+"] \
> +    "third breakpt call"
> +gdb_test "bt 1" \
> +    [multi_line \
> +	 "#0\\s+breakpt \\(\\) at \[^\r\n\]+" \
> +	 "\\(More stack frames follow\\.\\.\\.\\)"]
> -- 
> 2.25.4
> 

^ permalink raw reply	[flat|nested] 138+ messages in thread

* Re: [PATCHv4 06/10] gdb: parse pending breakpoint thread/task immediately
  2023-09-06 22:06         ` Lancelot SIX
@ 2023-10-02 15:02           ` Andrew Burgess
  0 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-10-02 15:02 UTC (permalink / raw)
  To: Lancelot SIX; +Cc: gdb-patches, Eli Zaretskii

Lancelot SIX <lsix@lancelotsix.com> writes:

> Hi Andrew,
>
> First, thanks for the patch, I really like what it changes!

Lancelot,

Thanks for the review, and sorry it's taken me so long to get back
around to this work.

>
> When applying the patch, I get the following warnings from git:
>
>     Applying: gdb: parse pending breakpoint thread/task immediately
>     .git/rebase-apply/patch:95: indent with spaces.
>                 ^
>     .git/rebase-apply/patch:96: indent with spaces.
>                ptr
>     .git/rebase-apply/patch:270: indent with spaces.
>              For the 'if' token we need to capture the entire condition
>     .git/rebase-apply/patch:271: indent with spaces.
>              string, so record the start of the condition string and then
>     .git/rebase-apply/patch:272: indent with spaces.
>              start scanning backwards looking for the end of the condition
>     warning: squelched 3 whitespace errors
>     warning: 8 lines add whitespace errors.
>
> I have added comments along the patch.

I believe these should all be fixed.

>
> Best,
> Lancelot.
>
> On Wed, Aug 23, 2023 at 04:59:11PM +0100, Andrew Burgess via Gdb-patches wrote:
>> The initial motivation for this commit was to allow thread or inferior
>> specific breakpoints to only be inserted within the appropriate
>> inferior's program-space.  The benefit of this is that inferiors for
>> which the breakpoint does not apply will no longer need to stop, and
>> then resume, for such breakpoints.  This commit does not make this
>> change, but is a refactor to allow this to happen in a later commit.
>> 
>> The problem we currently have is that when a thread-specific (or
>> inferior-specific) breakpoint is created, the thread (or inferior)
>> number is only parsed by calling find_condition_and_thread_for_sals.
>> This function is only called for non-pending breakpoints, and requires
>> that we know the locations at which the breakpoint will be placed (for
>> expression checking in case the breakpoint is also conditional).
>> 
>> A consequence of this is that by the time we figure out the breakpoint
>> is thread-specific we have already looked up locations in all program
>> spaces.  This feels wasteful -- if we knew the thread-id earlier then
>> we could reduce the work GDB does by only looking up locations within
>> the program space for which the breakpoint applies.
>> 
>> Another consequence of how find_condition_and_thread_for_sals is
>> called is that pending breakpoints don't currently know they are
>> thread-specific, nor even that they are conditional!  Additionally, by
>> delaying parsing the thread-id, pending breakpoints can be created for
>> non-existent threads, this is different to how non-pending
>> breakpoints are handled, so I can do this:
>> 
>>   $ gdb -q ./gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp
>>   Reading symbols from ./gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp...
>>   (gdb) break foo thread 99
>>   Function "foo" not defined.
>>   Make breakpoint pending on future shared library load? (y or [n]) y
>>   Breakpoint 1 (foo thread 99) pending.
>>   (gdb) r
>>   Starting program: /tmp/gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp
>>   [Thread debugging using libthread_db enabled]
>>   Using host libthread_db library "/lib64/libthread_db.so.1".
>>   Error in re-setting breakpoint 1: Unknown thread 99.
>>   [Inferior 1 (process 3329749) exited normally]
>>   (gdb)
>> 
>> GDB only checked the validity of 'thread 99' at the point the 'foo'
>> location became non-pending.  In contrast, if I try this:
>> 
>>   $ gdb -q ./gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp
>>   Reading symbols from ./gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp...
>>   (gdb) break main thread 99
>>   Unknown thread 99.
>>   (gdb)
>> 
>> GDB immediately checks if 'thread 99' exists.  I think inconsistencies
>> like this are confusing, and should be fixed if possible.
>> 
>> In this commit the create_breakpoint function is updated so that the
>> extra_string, which contains the thread, inferior, task, and/or
>> condition information, is parsed immediately, even for pending
>> breakpoints.
>> 
>> Obviously, the condition still can't be validated until the breakpoint
>> becomes non-pending, but the thread, inferior, and task information
>> can be pulled from the extra-string, and can be validated early on,
>> even for pending breakpoints.
>> 
>> There are a couple of benefits to doing this:
>> 
>> 1. Printing of breakpoints is more consistent now.  Consider creating
>>    a conditional breakpoint before this commit:
>> 
>>     (gdb) set breakpoint pending on
>>     (gdb) break pendingfunc if (0)
>>     Function "pendingfunc" not defined.
>>     Breakpoint 1 (pendingfunc if (0)) pending.
>>     (gdb) break main if (0)
>>     Breakpoint 2 at 0x401198: file /tmp/hello.c, line 18.
>>     (gdb) info breakpoints
>>     Num     Type           Disp Enb Address            What
>>     1       breakpoint     keep y   <PENDING>          pendingfunc if (0)
>>     2       breakpoint     keep y   0x0000000000401198 in main at /tmp/hello.c:18
>>             stop only if (0)
>>     (gdb)
>> 
>>    And after this commit:
>> 
>>     (gdb) set breakpoint pending on
>>     (gdb) break pendingfunc if (0)
>>     Function "pendingfunc" not defined.
>>     Breakpoint 1 (pendingfunc) pending.
>>     (gdb) break main if (0)
>>     Breakpoint 2 at 0x401198: file /home/andrew/tmp/hello.c, line 18.
>>     (gdb) info breakpoints
>>     Num     Type           Disp Enb Address            What
>>     1       breakpoint     keep y   <PENDING>          pendingfunc
>>             stop only if (0)
>>     2       breakpoint     keep y   0x0000000000401198 in main at /home/andrew/tmp/hello.c:18
>>             stop only if (0)
>>     (gdb)
>> 
>>    Notice that the display of the condition is now the same for the
>>    pending and non-pending breakpoints.
>> 
>>    The same is true for the thread information in thread-specific
>>    breakpoints, this information is displayed on its own line now
>>    rather than being part of the 'What' field.
>> 
>> 2. We can check that the thread exists as soon as the pending
>>    breakpoint exits.  Currently there is a weird different between
>>    pending and non-pending breakpoints when creating a thread-specific
>>    breakpoint.  A pending thread-specific breakpoint only checks its
>>    thread when it becomes non-pending, at which point the thread the
>>    breakpoint was intended for might have exited.  Here's the
>>    behaviour before this commit:
>> 
>>     (gdb) set breakpoint pending on
>>     (gdb) break foo thread 2
>>     Function "foo" not defined.
>>     Breakpoint 2 (foo thread 2) pending.
>>     (gdb) c
>>     Continuing.
>>     [Thread 0x7ffff7c56700 (LWP 2948835) exited]
>>     Error in re-setting breakpoint 2: Unknown thread 2.
>>     [Inferior 1 (process 2948832) exited normally]
>>     (gdb)
>> 
>>    Notice the 'Error in re-setting breakpoint 2: Unknown thread 2.'
>>    line, this was triggered when the thread tried to become
>                                    ^
> 				   the breakpoint?
>
>>    non-pending, and GDB discovers that the thread no longer exists.
>> 
>>    Compare that to the behaviour after this commit:
>> 
>>     (gdb) set breakpoint pending on
>>     (gdb) break foo thread 2
>>     Function "foo" not defined.
>>     Breakpoint 2 (foo) pending.
>>     (gdb) c
>>     Continuing.
>>     [Thread 0x7ffff7c56700 (LWP 2949243) exited]
>>     Thread-specific breakpoint 2 deleted - thread 2 no longer in the thread list.
>>     [Inferior 1 (process 2949240) exited normally]
>>     (gdb)
>> 
>>    Now the behaviour for pending breakpoints is identical to
>>    non-pending breakpoints, the thread specific breakpoint is removed
>>    as soon as the thread the breakpoint is associated with exits.
>> 
>> As a result of this commit the breakpoints 'extra_string' field is now
>> only used by bp_dprintf type breakpoints to hold the printf format and
>> arguments.  This string should always be empty for other breakpoint
>> types.  This allows me to clean up some code in
>> print_breakpoint_location.
>> 
>> In code_breakpoint::code_breakpoint I'm able to change an error case
>> into an assert.  This is because this error is now handled earlier in
>> create_breakpoint.  As a result we know that by this point, the
>> extra_string will always be nullptr for anything other than a
>> bp_dprintf style breakpoint.
>> 
>> The find_condition_and_thread_for_sals function is now no longer
>> needed, this was previously doing the delayed splitting of the extra
>> string into thread, task, and condition, but this is now all done in
>> create_breakpoint, so find_condition_and_thread_for_sals can be
>> deleted, and the code that calls this in
>> code_breakpoint::location_spec_to_sals can be removed.  With this
>> update this code would only ever be reached for bp_dprintf style
>> breakpoints, and in these cases the extra_string should not contain
>> anything other than format and args.
>> 
>> The most interesting changes are all in create_breakpoint and in the
>> new file break-cond-parse.c.  We have a new block of code early on in
>> create_breakpoint that is responsible for splitting the extra_string
>> into its component parts by calling create_breakpoint_parse_arg_string
>> a function in the new break-cond-parse.c file.  This means that some
>> of the later code can be simplified a little.
>> 
>> The new break-cond-parse.c file implements the splitting up the
>> extra_string and finding all the parts, as well as some self-tests for
>> the new function.
>> 
>> Finally, now we know all the details, these can be stored within the
>> breakpoint object if we end up creating a deferred breakpoint.
>> Additionally, if we are creating a deferred bp_dprintf we can parse
>> the extra_string to build the printf command.
>> 
>> Reviewed-By: Eli Zaretskii <eliz@gnu.org>
>> ---
>>  gdb/Makefile.in                               |   2 +
>>  gdb/NEWS                                      |   4 +
>>  gdb/break-cond-parse.c                        | 425 ++++++++++++++++++
>>  gdb/break-cond-parse.h                        |  49 ++
>>  gdb/breakpoint.c                              | 374 ++++-----------
>>  gdb/testsuite/gdb.ada/tasks.exp               |   6 +-
>>  gdb/testsuite/gdb.base/condbreak.exp          |  20 +-
>>  gdb/testsuite/gdb.base/pending.exp            |  23 +-
>>  gdb/testsuite/gdb.linespec/explicit.exp       |   4 +-
>>  gdb/testsuite/gdb.mi/mi-dprintf-pending.exp   |   3 +-
>>  .../gdb.multi/inferior-specific-bp.exp        |   4 +-
>>  .../gdb.threads/del-pending-thread-bp-lib.c   |  22 +
>>  .../gdb.threads/del-pending-thread-bp.c       |  85 ++++
>>  .../gdb.threads/del-pending-thread-bp.exp     | 108 +++++
>>  14 files changed, 826 insertions(+), 303 deletions(-)
>>  create mode 100644 gdb/break-cond-parse.c
>>  create mode 100644 gdb/break-cond-parse.h
>>  create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
>>  create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.c
>>  create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.exp
>> 
>> diff --git a/gdb/Makefile.in b/gdb/Makefile.in
>> index 9b992a3d8c0..43b867cd796 100644
>> --- a/gdb/Makefile.in
>> +++ b/gdb/Makefile.in
>> @@ -1026,6 +1026,7 @@ COMMON_SFILES = \
>>  	break-catch-sig.c \
>>  	break-catch-syscall.c \
>>  	break-catch-throw.c \
>> +	break-cond-parse.c \
>>  	breakpoint.c \
>>  	bt-utils.c \
>>  	btrace.c \
>> @@ -1293,6 +1294,7 @@ HFILES_NO_SRCDIR = \
>>  	bfd-target.h \
>>  	bfin-tdep.h \
>>  	block.h \
>> +	break-cond-parse.h \
>>  	breakpoint.h \
>>  	bsd-kvm.h \
>>  	bsd-uthread.h \
>> diff --git a/gdb/NEWS b/gdb/NEWS
>> index c4b1f7a7e3b..7c38ecb8b46 100644
>> --- a/gdb/NEWS
>> +++ b/gdb/NEWS
>> @@ -105,6 +105,10 @@
>>    'inferior' keyword with either the 'thread' or 'task' keywords when
>>    creating a breakpoint.
>>  
>> +* For breakpoints that are created in the 'pending' state, any
>> +  'thread' or 'task' keywords are parsed at the time the breakpoint is
>> +  created, rather than at the time the breakpoint becomes non-pending.
>> +
>>  * New commands
>>  
>>  set debug breakpoint on|off
>> diff --git a/gdb/break-cond-parse.c b/gdb/break-cond-parse.c
>> new file mode 100644
>> index 00000000000..ebe67c90736
>> --- /dev/null
>> +++ b/gdb/break-cond-parse.c
>> @@ -0,0 +1,425 @@
>> +/* Copyright (C) 2023 Free Software Foundation, Inc.
>> +
>> +   This file is part of GDB.
>> +
>> +   This program is free software; you can redistribute it and/or modify
>> +   it under the terms of the GNU General Public License as published by
>> +   the Free Software Foundation; either version 3 of the License, or
>> +   (at your option) any later version.
>> +
>> +   This program is distributed in the hope that it will be useful,
>> +   but WITHOUT ANY WARRANTY; without even the implied warranty of
>> +   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
>> +   GNU General Public License for more details.
>> +
>> +   You should have received a copy of the GNU General Public License
>> +   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
>> +
>> +#include "defs.h"
>> +#include "gdbsupport/gdb_assert.h"
>> +#include "gdbsupport/selftest.h"
>> +#include "test-target.h"
>> +#include "scoped-mock-context.h"
>> +#include "break-cond-parse.h"
>> +#include "tid-parse.h"
>> +#include "ada-lang.h"
>> +
>> +/* When parsing tokens from a string, which direction are we parsing?
>> +
>> +   Given the following string and pointer 'ptr':
>> +
>> +     ABC DEF GHI JKL
>> +            ^
>> +           ptr
>
> Initial indentation with tabs here.
>
>> +
>> +   Parsing 'forward' will return the token 'GHI' and update 'ptr' to point
>> +   between GHI and JKL.  Parsing 'backward' will return the token 'DEF' and
>> +   update 'ptr' to point between ABC and DEF.
>> +*/
>> +
>> +enum class parse_direction
>> +{
>> +  /* Parse the next token forwards.  */
>> +  forward,
>> +
>> +  /* Parse the previous token backwards.  */
>> +  backward
>> +};
>> +
>> +struct token
>> +{
>> +  /* Create a new token.  START points to the first character of the new
>> +     token, while END points at the last character of the new token.
>> +
>> +     Neither START or END can be nullptr, and both START and END must point
>> +     into the same C style string (i.e. there should be no null character
>> +     between START and END).  END must be equal to, or greater than START,
>> +     that is, it is not possible to create a zero length token.  */
>> +
>> +  token (const char *start, const char *end)
>> +    : m_start (start),
>> +      m_end (end)
>> +  {
>> +    gdb_assert (m_end >= m_start);
>> +    gdb_assert (m_start + strlen (m_start) > m_end);
>> +  }
>> +
>> +  /* Return a pointer to the first character of this token.  */
>> +  const char *start () const
>> +  {
>> +    return m_start;
>> +  }
>> +
>> +  /* Return a pointer to the last character of this token.  */
>> +  const char *end () const
>> +  {
>> +    return m_end;
>> +  }
>> +
>> +  /* Return the length of the token.  */
>> +  size_t length () const
>> +  {
>> +    return m_end - m_start + 1;
>
> Note here that since we know that m_end >= m_start (this is asserted in
> the ctor), length must return at least 1.  It cannot be 0 (this will
> become relevant later).

Thanks, I've fixes all the length zero checks you pointed out.


>
>> +  }
>> +
>> +  /* Return true if this token matches STR.  If this token is shorter than
>> +     STR then only a partial match is performed and true will be returned
>> +     if the token length sub-string matches.  Otherwise, return false.  */
>
> I am not sure that partial matching here was a good choice of the
> initial implementation (you did not change this).  The token you are
> interested in here are matched entirely when parsing the locdesc
> (linespec_lexer_lex_keyword), doing partial matching seems inconsistent.
> See later comments for further details.
>
>> +  bool matches (const char *str) const
>> +  {
>> +    return strncmp (m_start, str, length ()) == 0;
>> +  }
>> +
>> +private:
>> +  /* The first character of this token.  */
>> +  const char *m_start;
>> +
>> +  /* The last character of this token.  */
>> +  const char *m_end;
>> +};
>> +
>> +/* Find the next token in DIRECTION from *CURR.  */
>> +
>> +static token
>> +find_next_token (const char **curr, parse_direction direction)
>> +{
>> +  const char *tok_start, *tok_end;
>> +
>> +  if (direction == parse_direction::forward)
>> +    {
>> +      *curr = skip_spaces (*curr);
>> +      tok_start = *curr;
>> +      *curr = skip_to_space (*curr);
>> +      tok_end = *curr - 1;
>> +    }
>> +  else
>> +    {
>> +      gdb_assert (direction == parse_direction::backward);
>> +
>> +      while (isspace (**curr))
>> +	--(*curr);
>> +
>> +      tok_end = *curr;
>> +
>> +      while (!isspace (**curr))
>> +	--(*curr);
>> +
>> +      tok_start = (*curr) + 1;
>> +    }
>> +
>> +  return token (tok_start, tok_end);
>> +}
>> +
>> +/* See break-cond-parse.h.  */
>> +
>> +void
>> +create_breakpoint_parse_arg_string
>> +  (const char *tok, gdb::unique_xmalloc_ptr<char> *cond_string,
>> +   int *thread, int *inferior, int *task,
>> +   gdb::unique_xmalloc_ptr<char> *rest, bool *force)
>> +{
>> +  /* Set up the defaults.  */
>> +  cond_string->reset ();
>> +  rest->reset ();
>> +  *thread = -1;
>> +  *inferior = -1;
>> +  *task = -1;
>> +  *force = false;
>> +
>> +  if (tok == nullptr)
>> +    return;
>> +
>> +  const char *cond_start = nullptr;
>> +  const char *cond_end = nullptr;
>> +  parse_direction direction = parse_direction::forward;
>> +  while (*tok != '\0')
>> +    {
>> +      /* Find the next token.  If moving backward and this token starts at
>> +	 the same location as the condition then we must have found the
>> +	 other end of the condition string -- we're done.  */
>> +      token t = find_next_token (&tok, direction);
>> +      if (direction == parse_direction::backward && t.start () <= cond_start)
>> +	{
>> +	  cond_end = t.end () + 1;
>> +	  break;
>> +	}
>> +
>> +      /* We only have a single flag option to check for.  All the other
>> +	 options take a value so require an additional token to be found.  */
>> +      if (t.length () > 0 && t.matches ("-force-condition"))
>
> First thing, as mentioned above, I don’t think that "t.length () > 0"
> can ever be false, so this part of the test can safely be removed.
>
> Also, it seems to be a new behavior linked to the fact that you don’t
> use "parse_exp_1" anymore.  Before this patch, "-force-condition" could
> not really be placed after the condition (at least with C/C++ as current
> language) as the expression parser would try to consume it.  Now it can
> be partially matched, which can give surprising results.
>
> Doing
>
>     break foo if 0 -
>
> is now interpreted as
>
>     break foo if 0 -force-condition
>
> this used to be an error.

I've added a t.length() check here to ensure that only a token of length
2 or more will match -force-condition, i.e. '-f' is OK, but '-' is not.

>
> Similarly, doing
>
>     break foo if var -f
>
> used to be interpreted as
>
>     break foo if (var - f)
>
> which could be valid if "var" and "f" are valid, but with the patch it
> now interprets it as
>
>     break foo if var -force-condition
>
> I don’t expect many users will ever notice such change in behavior,
> but overall I would find that it makes more sense to only match
> "-force-condition" entirely.
>
> This would be consistent with the parsing behavior if -force-condition
> is placed before the condition.  In such case,
> linespec_lexer_lex_keyword only does a full match.

There's two issues here, partial matching, which I'll discuss later on
in this reply.  But there's also the choice of how to handle
-force-condition immediately after the condition string.

As you point out, -force-condition immediately after the condition
string is handled as part of the condition string, while this cut of the
patch changes that.

I'd like this patch to focus on just restructuring the code, and
bringing in those changes which I think are an essential consequence of
the restructure.  This is things like the say the pending breakpoint is
announced and displayed to the user, or that the thread is checked as
soon as the breakpoint is created.  These changes are "core" to this
patch.

In contrast, the handling of -force-condition is just a random
consequence of the implementation.  As such, in the updated patch which
I'll post soon I've made a minor change which restores the old handling
of -force-condition.

That said, I think the points you raised are good ones, and I think more
consistent handling of -force-condition would be a good improvement.

But I'd like to make that change as part of a later patch (series).

>
>
>> +	{
>> +	  *force = true;
>> +	  continue;
>> +	}
>> +
>> +      /* Maybe the first token was the last token in the string.  If this
>> +	 is the case then we definitely can't try to extract a value
>> +	 token.  This also means that the token T is meaningless.  Reset
>> +	 TOK to point at the start of the unknown content and break out of
>> +	 the loop.  We'll record the unknown part of the string outside of
>> +	 the scanning loop (below).  */
>> +      if (direction == parse_direction::forward && *tok == '\0')
>> +	{
>> +	  tok = t.start ();
>> +	  break;
>> +	}
>> +
>> +      /* As before, find the next token and, if we are scanning backwards,
>> +	 check that we have not reached the start of the condition string.  */
>> +      token v = find_next_token (&tok, direction);
>> +      if (direction == parse_direction::backward && v.start () <= cond_start)
>> +	{
>> +	  /* Use token T here as that must also be part of the condition
>> +	     string.  */
>> +	  cond_end = t.end () + 1;
>> +	  break;
>> +	}
>> +
>> +      /* When moving backward we will first parse the value token then the
>> +	 keyword token, so swap them now.  */
>> +      if (direction == parse_direction::backward)
>> +	std::swap (t, v);
>> +
>> +      /* Check for valid option in token T.  If we find a valid option then
>> +	 parse the value from the token V.  Except for 'if', that's handled
>> +	 differently.
>> +
>> +         For the 'if' token we need to capture the entire condition
>> +         string, so record the start of the condition string and then
>> +         start scanning backwards looking for the end of the condition
>> +         string.  */
>
> Initial indentation with tabs here.
>
>> +      if (direction == parse_direction::forward && t.length () > 0
>
> dito for t.length
>
>> +	  && t.matches ("if"))
>> +	{
>> +	  cond_start = v.start ();
>> +	  tok = tok + strlen (tok);
>> +	  gdb_assert (*tok == '\0');
>> +	  --tok;
>> +	  direction = parse_direction::backward;
>> +	  continue;
>> +	}
>> +      else if (t.length () > 0 && t.matches ("thread"))
>
> dito for t.length
>
>
> Also,
>
>     b foo if 0 t 1
>
> is ambiguous.  The "t" could match both "task" and "thread", and it
> really is an implementation detail that "thread" is tested first.
>
> This ambiguity used to exist before the patch.
>
> However, since parsing "thread" or "task" just after the linespec does
> not accept partial matches, and it does not look that partial matching
> has ever been documented, I’d be in favor of just removing partial
> matching.

It's not documented, but, as you point out later, it is tested for, so
changing this would be a change in behaviour.  Also, it really is a bit
of a mess, e.g. as you suggest, this is invalid:

  (gdb) break main th 1

However, this is valid:

  (gdb) break *main th 1

Yeah, this is a bit of a mess.

Like I said earlier, I don't really want to tie this patch up with
trying to sort this out, so my ideal solution is to leave the behaviour
as-is for now.  But, that doesn't mean that I think you are wrong, I'm
inclined to agree with you.

In my updated series (I'll post it soon) I've added comments to point
out that the thread / task parsing order is important because of the
abbreviations, but otherwise I've left the behaviour as is.

>
> WDYT?
>
>> +	{
>> +	  const char *tmptok;
>> +	  struct thread_info *thr;
>> +
>> +	  if (*thread != -1)
>> +	    error(_("You can specify only one thread."));
>> +
>> +	  if (*task != -1 || *inferior != -1)
>> +	    error (_("You can specify only one of thread, inferior, or task."));
>> +
>> +	  thr = parse_thread_id (v.start (), &tmptok);
>> +	  const char *expected_end = skip_spaces (v.end () + 1);
>> +	  if (tmptok != expected_end)
>> +	    error (_("Junk after thread keyword."));
>> +	  *thread = thr->global_num;
>> +	}
>> +      else if (t.length () > 0 && t.matches ("inferior"))
>
> dito for t.length
>
>> +	{
>> +	  char *tmptok;
>> +
>> +	  if (*inferior != -1)
>> +	    error(_("You can specify only one inferior."));
>> +
>> +	  if (*task != -1 || *thread != -1)
>> +	    error (_("You can specify only one of thread, inferior, or task."));
>> +
>> +	  *inferior = strtol (v.start (), &tmptok, 0);
>> +	  const char *expected_end = v.end () + 1;
>> +	  if (tmptok != expected_end)
>> +	    error (_("Junk after inferior keyword."));
>> +	}
>> +      else if (t.length () > 0 && t.matches ("task"))
>
> dito for t.length
>
>> +	{
>> +	  char *tmptok;
>> +
>> +	  if (*task != -1)
>> +	    error(_("You can specify only one task."));
>> +
>> +	  if (*thread != -1 || *inferior != -1)
>> +	    error (_("You can specify only one of thread, inferior, or task."));
>> +
>> +	  *task = strtol (v.start (), &tmptok, 0);
>> +	  const char *expected_end = v.end () + 1;
>> +	  if (tmptok != expected_end)
>> +	    error (_("Junk after task keyword."));
>> +	  if (!valid_task_id (*task))
>> +	    error (_("Unknown task %d."), *task);
>> +	}
>> +      else
>> +	{
>> +	  /* An unknown token.  If we are scanning forward then reset TOK
>> +	     to point at the start of the unknown content, we record this
>> +	     outside of the scanning loop (below).
>> +
>> +	     If we are scanning backward then unknown content is assumed to
>> +	     be the other end of the condition string, obviously, this is
>> +	     just a heuristic, we could be looking at a mistyped command
>> +	     line, but this will be spotted when the condition is
>> +	     eventually evaluated.
>> +
>> +	     Either way, no more scanning is required after this.  */
>> +	  if (direction == parse_direction::forward)
>> +	    tok = t.start ();
>> +	  else
>> +	    {
>> +	      gdb_assert (direction == parse_direction::backward);
>> +	      cond_end = v.end () + 1;
>> +	    }
>> +	  break;
>> +	}
>> +    }
>> +
>> +  if (cond_start != nullptr)
>> +    {
>> +      /* If we found the start of a condition string then we should have
>> +	 switched to backward scan mode, and found the end of the condition
>> +	 string.  Capture the whole condition string into COND_STRING now.  */
>> +      gdb_assert (direction == parse_direction::backward);
>> +      gdb_assert (cond_end != nullptr);
>> +      cond_string->reset (savestring (cond_start, cond_end - cond_start));
>> +    }
>> +  else if (*tok != '\0')
>> +    {
>> +      /* If we didn't have a condition start pointer then we should still
>> +	 be in forward scanning mode.  If we didn't reach the end of the
>> +	 input string (TOK is not at the null character) then the rest of
>> +	 the input string is garbage that we didn't understand.
>> +
>> +	 Record the unknown content into REST.  The caller of this function
>> +	 will report this as an error later on.  We could report the error
>> +	 here, but we prefer to allow the caller to run other checks, and
>> +	 prioritise other errors before reporting this problem.  */
>> +      gdb_assert (direction == parse_direction::forward);
>> +      rest->reset (savestring (tok, strlen (tok)));
>> +    }
>> +}
>> +
>> +#if GDB_SELF_TEST
>> +
>> +namespace selftests {
>> +
>> +/* Run a single test of the create_breakpoint_parse_arg_string function.
>> +   INPUT is passed to create_breakpoint_parse_arg_string while all other
>> +   arguments are the expected output from
>> +   create_breakpoint_parse_arg_string.  */
>> +
>> +static void
>> +test (const char *input, const char *condition, int thread = -1,
>> +      int inferior = -1, int task = -1, bool force = false,
>> +      const char *rest = nullptr)
>> +{
>> +  gdb::unique_xmalloc_ptr<char> extracted_condition;
>> +  gdb::unique_xmalloc_ptr<char> extracted_rest;
>> +  int extracted_thread, extracted_inferior, extracted_task;
>> +  bool extracted_force_condition;
>> +  std::string exception_msg;
>> +
>> +  try
>> +    {
>> +      create_breakpoint_parse_arg_string (input, &extracted_condition,
>> +					  &extracted_thread,
>> +					  &extracted_inferior,
>> +					  &extracted_task, &extracted_rest,
>> +					  &extracted_force_condition);
>> +    }
>> +  catch (const gdb_exception_error &ex)
>> +    {
>> +      string_file buf;
>> +
>> +      exception_print (&buf, ex);
>> +      exception_msg = buf.release ();
>> +    }
>> +
>> +  if ((condition == nullptr) != (extracted_condition.get () == nullptr)
>> +      || (condition != nullptr
>> +	  && strcmp (condition, extracted_condition.get ()) != 0)
>> +      || (rest == nullptr) != (extracted_rest.get () == nullptr)
>> +      || (rest != nullptr && strcmp (rest, extracted_rest.get ()) != 0)
>> +      || thread != extracted_thread
>> +      || inferior != extracted_inferior
>> +      || task != extracted_task
>> +      || force != extracted_force_condition
>> +      || !exception_msg.empty ())
>> +    {
>> +      if (run_verbose ())
>> +	{
>> +	  debug_printf ("input: '%s'\n", input);
>> +	  debug_printf ("condition: '%s'\n", extracted_condition.get ());
>> +	  debug_printf ("rest: '%s'\n", extracted_rest.get ());
>> +	  debug_printf ("thread: %d\n", extracted_thread);
>> +	  debug_printf ("inferior: %d\n", extracted_inferior);
>> +	  debug_printf ("task: %d\n", extracted_task);
>> +	  debug_printf ("forced: %s\n",
>> +			extracted_force_condition ? "true" : "false");
>> +	  debug_printf ("exception: '%s'\n", exception_msg.c_str ());
>> +	}
>> +
>> +      /* Report the failure.  */
>> +      SELF_CHECK (false);
>> +    }
>> +}
>> +
>> +/* Test the create_breakpoint_parse_arg_string function.  Just wraps
>> +   multiple calls to the test function above.  */
>> +
>> +static void
>> +create_breakpoint_parse_arg_string_tests (void)
>> +{
>> +  gdbarch *arch = current_inferior ()->gdbarch;
>> +  scoped_restore_current_pspace_and_thread restore;
>> +  scoped_mock_context<test_target_ops> mock_target (arch);
>> +
>> +  int global_thread_num = mock_target.mock_thread.global_num;
>> +
>> +  test ("  if blah  ", "blah");
>> +  test (" if blah thread 1", "blah", global_thread_num);
>> +  test (" if blah inferior 1", "blah", -1, 1);
>> +  test (" if blah thread 1  ", "blah", global_thread_num);
>> +  test ("thread 1 woof", nullptr, global_thread_num, -1, -1, false, "woof");
>> +  test ("thread 1 X", nullptr, global_thread_num, -1, -1, false, "X");
>> +  test (" if blah thread 1 -force-condition", "blah", global_thread_num,
>> +	-1, -1, true);
>> +  test (" -force-condition if blah thread 1", "blah", global_thread_num,
>> +	-1, -1, true);
>> +  test (" -force-condition if blah thread 1  ", "blah", global_thread_num,
>> +	-1, -1, true);
>> +  test ("thread 1 -force-condition if blah", "blah", global_thread_num,
>> +	-1, -1, true);
>> +  test ("if (A::outer::func ())", "(A::outer::func ())");
>> +}
>> +
>> +} // namespace selftests
>> +#endif /* GDB_SELF_TEST */
>> +
>> +void _initialize_break_cond_parse ();
>> +void
>> +_initialize_break_cond_parse ()
>> +{
>> +#if GDB_SELF_TEST
>> +  selftests::register_test
>> +    ("create_breakpoint_parse_arg_string",
>> +     selftests::create_breakpoint_parse_arg_string_tests);
>> +#endif
>> +}
>> diff --git a/gdb/break-cond-parse.h b/gdb/break-cond-parse.h
>> new file mode 100644
>> index 00000000000..b08b6fc6cc9
>> --- /dev/null
>> +++ b/gdb/break-cond-parse.h
>> @@ -0,0 +1,49 @@
>> +/* Copyright (C) 2023 Free Software Foundation, Inc.
>> +
>> +   This file is part of GDB.
>> +
>> +   This program is free software; you can redistribute it and/or modify
>> +   it under the terms of the GNU General Public License as published by
>> +   the Free Software Foundation; either version 3 of the License, or
>> +   (at your option) any later version.
>> +
>> +   This program is distributed in the hope that it will be useful,
>> +   but WITHOUT ANY WARRANTY; without even the implied warranty of
>> +   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
>> +   GNU General Public License for more details.
>> +
>> +   You should have received a copy of the GNU General Public License
>> +   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
>> +
>> +#if !defined (BREAK_COND_PARSE_H)
>> +#define BREAK_COND_PARSE_H 1
>> +
>> +/* Given TOK, a string possibly containing a condition, thread, inferior,
>> +   task and force-condition flag, as accepted by the 'break' command,
>> +   extract the condition string, thread, inferior, task number, and the
>> +   force_condition flag, then set *COND_STRING, *THREAD, *INFERIOR, *TASK,
>> +   and *FORCE.
>> +
>> +   As TOK is parsed, if an unknown keyword is encountered before the 'if'
>> +   keyword then everything starting from the unknown keyword is placed into
>> +   *REST.
>> +
>> +   Both *COND and *REST are initialized to nullptr.  If no 'if' keyword is
>> +   found then *COND will be returned as nullptr.  If no unknown content is
>> +   found then *REST is returned as nullptr.
>> +
>> +   If no thread is found, *THREAD is set to -1.  If no inferior is found,
>> +   *INFERIOR is set to -1.  If no task is found, *TASK is set to -1.  If
>> +   the -force-condition flag is not found then *FORCE is set to false.
>> +
>> +   Due to the free-form nature that the string TOK might take (a 'thread'
>> +   keyword can appear before or after an 'if' condition) then we end up
>> +   having to check for keywords from both the start of TOK and the end of
>> +   TOK.  */
>> +
>> +extern void create_breakpoint_parse_arg_string
>> +  (const char *tok, gdb::unique_xmalloc_ptr<char> *cond_string,
>> +   int *thread, int *inferior, int *task,
>> +   gdb::unique_xmalloc_ptr<char> *rest, bool *force);
>> +
>> +#endif
>> diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
>> index 5a608ba2495..50225f55522 100644
>> --- a/gdb/breakpoint.c
>> +++ b/gdb/breakpoint.c
>> @@ -70,6 +70,7 @@
>>  #include "cli/cli-style.h"
>>  #include "cli/cli-decode.h"
>>  #include <unordered_set>
>> +#include "break-cond-parse.h"
>>  
>>  /* readline include files */
>>  #include "readline/tilde.h"
>> @@ -6340,20 +6341,7 @@ print_breakpoint_location (const breakpoint *b, const bp_location *loc)
>>        uiout->field_stream ("at", stb);
>>      }
>>    else
>> -    {
>> -      uiout->field_string ("pending", b->locspec->to_string ());
>> -      /* If extra_string is available, it could be holding a condition
>> -	 or dprintf arguments.  In either case, make sure it is printed,
>> -	 too, but only for non-MI streams.  */
>> -      if (!uiout->is_mi_like_p () && b->extra_string != NULL)
>> -	{
>> -	  if (b->type == bp_dprintf)
>> -	    uiout->text (",");
>> -	  else
>> -	    uiout->text (" ");
>> -	  uiout->text (b->extra_string.get ());
>> -	}
>> -    }
>> +    uiout->field_string ("pending", b->locspec->to_string ());
>>  
>>    if (loc && is_breakpoint (b)
>>        && breakpoint_condition_evaluation_mode () == condition_evaluation_target
>> @@ -8718,8 +8706,8 @@ code_breakpoint::code_breakpoint (struct gdbarch *gdbarch_,
>>        gdb_assert (extra_string != nullptr);
>>        update_dprintf_command_list (this);
>>      }
>> -  else if (extra_string != nullptr)
>> -    error (_("Garbage '%s' at end of command"), extra_string.get ());
>> +  else
>> +    gdb_assert (extra_string == nullptr);
>>  
>>    /* The order of the locations is now stable.  Set the location
>>       condition using the location's number.  */
>> @@ -8947,197 +8935,6 @@ check_fast_tracepoint_sals (struct gdbarch *gdbarch,
>>      }
>>  }
>>  
>> -/* Given TOK, a string specification of condition and thread, as accepted
>> -   by the 'break' command, extract the condition string into *COND_STRING.
>> -   If no condition string is found then *COND_STRING is set to nullptr.
>> -
>> -   If the breakpoint specification has an associated thread, task, or
>> -   inferior, these are extracted into *THREAD, *TASK, and *INFERIOR
>> -   respectively, otherwise these arguments are set to -1 (for THREAD and
>> -   INFERIOR) or 0 (for TASK).
>> -
>> -   PC identifies the context at which the condition should be parsed.  */
>> -
>> -static void
>> -find_condition_and_thread (const char *tok, CORE_ADDR pc,
>> -			   gdb::unique_xmalloc_ptr<char> *cond_string,
>> -			   int *thread, int *inferior, int *task,
>> -			   gdb::unique_xmalloc_ptr<char> *rest)
>> -{
>> -  cond_string->reset ();
>> -  *thread = -1;
>> -  *inferior = -1;
>> -  *task = -1;
>> -  rest->reset ();
>> -  bool force = false;
>> -
>> -  while (tok && *tok)
>> -    {
>> -      const char *end_tok;
>> -      int toklen;
>> -      const char *cond_start = NULL;
>> -      const char *cond_end = NULL;
>> -
>> -      tok = skip_spaces (tok);
>> -
>> -      if ((*tok == '"' || *tok == ',') && rest)
>> -	{
>> -	  rest->reset (savestring (tok, strlen (tok)));
>> -	  break;
>> -	}
>> -
>> -      end_tok = skip_to_space (tok);
>> -
>> -      toklen = end_tok - tok;
>> -
>> -      if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
>> -	{
>> -	  tok = cond_start = end_tok + 1;
>> -	  try
>> -	    {
>> -	      parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
>> -	    }
>> -	  catch (const gdb_exception_error &)
>> -	    {
>> -	      if (!force)
>> -		throw;
>> -	      else
>> -		tok = tok + strlen (tok);
>> -	    }
>> -	  cond_end = tok;
>> -	  cond_string->reset (savestring (cond_start, cond_end - cond_start));
>> -	}
>> -      else if (toklen >= 1 && strncmp (tok, "-force-condition", toklen) == 0)
>> -	{
>> -	  tok = tok + toklen;
>> -	  force = true;
>> -	}
>> -      else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
>> -	{
>> -	  const char *tmptok;
>> -	  struct thread_info *thr;
>> -
>> -	  if (*thread != -1)
>> -	    error(_("You can specify only one thread."));
>> -
>> -	  if (*task != -1)
>> -	    error (_("You can specify only one of thread or task."));
>> -
>> -	  if (*inferior != -1)
>> -	    error (_("You can specify only one of inferior or thread."));
>> -
>> -	  tok = end_tok + 1;
>> -	  thr = parse_thread_id (tok, &tmptok);
>> -	  if (tok == tmptok)
>> -	    error (_("Junk after thread keyword."));
>> -	  *thread = thr->global_num;
>> -	  tok = tmptok;
>> -	}
>> -      else if (toklen >= 1 && strncmp (tok, "inferior", toklen) == 0)
>> -	{
>> -	  if (*inferior != -1)
>> -	    error(_("You can specify only one inferior."));
>> -
>> -	  if (*task != -1)
>> -	    error (_("You can specify only one of inferior or task."));
>> -
>> -	  if (*thread != -1)
>> -	    error (_("You can specify only one of inferior or thread."));
>> -
>> -	  char *tmptok;
>> -	  tok = end_tok + 1;
>> -	  *inferior = strtol (tok, &tmptok, 0);
>> -	  if (tok == tmptok)
>> -	    error (_("Junk after inferior keyword."));
>> -	  if (!valid_global_inferior_id (*inferior))
>> -	    error (_("Unknown inferior number %d."), *inferior);
>> -	  tok = tmptok;
>> -	}
>> -      else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
>> -	{
>> -	  char *tmptok;
>> -
>> -	  if (*task != -1)
>> -	    error(_("You can specify only one task."));
>> -
>> -	  if (*thread != -1)
>> -	    error (_("You can specify only one of thread or task."));
>> -
>> -	  if (*inferior != -1)
>> -	    error (_("You can specify only one of inferior or task."));
>> -
>> -	  tok = end_tok + 1;
>> -	  *task = strtol (tok, &tmptok, 0);
>> -	  if (tok == tmptok)
>> -	    error (_("Junk after task keyword."));
>> -	  if (!valid_task_id (*task))
>> -	    error (_("Unknown task %d."), *task);
>> -	  tok = tmptok;
>> -	}
>> -      else if (rest)
>> -	{
>> -	  rest->reset (savestring (tok, strlen (tok)));
>> -	  break;
>> -	}
>> -      else
>> -	error (_("Junk at end of arguments."));
>> -    }
>> -}
>> -
>> -/* Call 'find_condition_and_thread' for each sal in SALS until a parse
>> -   succeeds.  The parsed values are written to COND_STRING, THREAD,
>> -   TASK, and REST.  See the comment of 'find_condition_and_thread'
>> -   for the description of these parameters and INPUT.  */
>> -
>> -static void
>> -find_condition_and_thread_for_sals (const std::vector<symtab_and_line> &sals,
>> -				    const char *input,
>> -				    gdb::unique_xmalloc_ptr<char> *cond_string,
>> -				    int *thread, int *inferior, int *task,
>> -				    gdb::unique_xmalloc_ptr<char> *rest)
>> -{
>> -  int num_failures = 0;
>> -  for (auto &sal : sals)
>> -    {
>> -      gdb::unique_xmalloc_ptr<char> cond;
>> -      int thread_id = -1;
>> -      int inferior_id = -1;
>> -      int task_id = -1;
>> -      gdb::unique_xmalloc_ptr<char> remaining;
>> -
>> -      /* Here we want to parse 'arg' to separate condition from thread
>> -	 number.  But because parsing happens in a context and the
>> -	 contexts of sals might be different, try each until there is
>> -	 success.  Finding one successful parse is sufficient for our
>> -	 goal.  When setting the breakpoint we'll re-parse the
>> -	 condition in the context of each sal.  */
>> -      try
>> -	{
>> -	  find_condition_and_thread (input, sal.pc, &cond, &thread_id,
>> -				     &inferior_id, &task_id, &remaining);
>> -	  *cond_string = std::move (cond);
>> -	  /* A value of -1 indicates that these fields are unset.  At most
>> -	     one of these fields should be set (to a value other than -1)
>> -	     at this point.  */
>> -	  gdb_assert (((thread_id == -1 ? 1 : 0)
>> -		       + (task_id == -1 ? 1 : 0)
>> -		       + (inferior_id == -1 ? 1 : 0)) >= 2);
>> -	  *thread = thread_id;
>> -	  *inferior = inferior_id;
>> -	  *task = task_id;
>> -	  *rest = std::move (remaining);
>> -	  break;
>> -	}
>> -      catch (const gdb_exception_error &e)
>> -	{
>> -	  num_failures++;
>> -	  /* If no sal remains, do not continue.  */
>> -	  if (num_failures == sals.size ())
>> -	    throw;
>> -	}
>> -    }
>> -}
>> -
>>  /* Decode a static tracepoint marker spec.  */
>>  
>>  static std::vector<symtab_and_line>
>> @@ -9255,6 +9052,46 @@ create_breakpoint (struct gdbarch *gdbarch,
>>  	      || (type_wanted != bp_dprintf
>>  		  && (extra_string == nullptr || parse_extra)));
>>  
>> +  /* Will hold either copies of the similarly named function argument, or
>> +     will hold a modified version of the function argument, depending on
>> +     the value of PARSE_EXTRA.  */
>> +  gdb::unique_xmalloc_ptr<char> cond_string_copy;
>> +  gdb::unique_xmalloc_ptr<char> extra_string_copy;
>> +
>> +  if (parse_extra)
>> +    {
>> +      /* Parse EXTRA_STRING splitting the parts out.  */
>> +      create_breakpoint_parse_arg_string (extra_string, &cond_string_copy,
>> +					  &thread, &inferior, &task,
>> +					  &extra_string_copy,
>> +					  &force_condition);
>> +
>> +      /* We could check that EXTRA_STRING_COPY is empty at this point -- it
>> +	 should be, as we only get here for things that are not bp_dprintf,
>> +	 however, we prefer to give the location spec parser a chance to
>> +	 run first, this means the user will get errors about invalid
>> +	 location spec instead of an error about garbage at the end of the
>> +	 command line.
>> +
>> +	 We still do the EXTRA_STRING_COPY is empty check, just later in
>> +	 this function.  */
>> +
>> +      gdb_assert (thread == -1 || thread > 0);
>> +      gdb_assert (task == -1 || task > 0);
>> +      gdb_assert (inferior == -1 || inferior > 0);
>> +    }
>> +  else
>> +    {
>> +      if (cond_string != nullptr)
>> +	cond_string_copy.reset (xstrdup (cond_string));
>> +      if (extra_string != nullptr)
>> +	extra_string_copy.reset (xstrdup (extra_string));
>> +    }
>> +
>> +  /* Clear these.  Updated values are now held in the *_copy locals.  */
>> +  cond_string = nullptr;
>> +  extra_string = nullptr;
>> +
>>    try
>>      {
>>        ops->create_sals_from_location_spec (locspec, &canonical);
>> @@ -9290,6 +9127,13 @@ create_breakpoint (struct gdbarch *gdbarch,
>>  	throw;
>>      }
>>  
>> +  /* The only bp_dprintf should have anything in EXTRA_STRING_COPY by this
>> +     point.  For all other breakpoints this indicates an error.  We could
>> +     place this check earlier in the function, but we prefer to see errors
>> +     from the location spec parser before we see this error message.  */
>> +  if (type_wanted != bp_dprintf && extra_string_copy.get () != nullptr)
>> +    error (_("Garbage '%s' at end of command"), extra_string_copy.get ());
>> +
>>    if (!pending && canonical.lsals.empty ())
>>      return 0;
>>  
>> @@ -9313,63 +9157,31 @@ create_breakpoint (struct gdbarch *gdbarch,
>>       breakpoint.  */
>>    if (!pending)
>>      {
>> -      gdb::unique_xmalloc_ptr<char> cond_string_copy;
>> -      gdb::unique_xmalloc_ptr<char> extra_string_copy;
>> -
>> -      if (parse_extra)
>> +      /* Check the validity of the condition.  We should error out if the
>> +	 condition is invalid at all of the locations and if it is not
>> +	 forced.  In the PARSE_EXTRA case above, this check is done when
>> +	 parsing the EXTRA_STRING.  */
>> +      if (cond_string_copy.get () != nullptr && !force_condition)
>>  	{
>> -	  gdb_assert (type_wanted != bp_dprintf);
>> -
>> -	  gdb::unique_xmalloc_ptr<char> rest;
>> -	  gdb::unique_xmalloc_ptr<char> cond;
>> -
>> -	  const linespec_sals &lsal = canonical.lsals[0];
>> -
>> -	  find_condition_and_thread_for_sals (lsal.sals, extra_string,
>> -					      &cond, &thread, &inferior,
>> -					      &task, &rest);
>> -
>> -	  if (rest.get () != nullptr && *(rest.get ()) != '\0')
>> -	    error (_("Garbage '%s' at end of command"), rest.get ());
>> -
>> -	  cond_string_copy = std::move (cond);
>> -	  extra_string_copy = std::move (rest);
>> -	}
>> -      else
>> -	{
>> -	  /* Check the validity of the condition.  We should error out
>> -	     if the condition is invalid at all of the locations and
>> -	     if it is not forced.  In the PARSE_EXTRA case above, this
>> -	     check is done when parsing the EXTRA_STRING.  */
>> -	  if (cond_string != nullptr && !force_condition)
>> +	  int num_failures = 0;
>> +          const linespec_sals &lsal = canonical.lsals[0];
>
> Indentation issue.
>
>> +	  for (const auto &sal : lsal.sals)
>>  	    {
>> -	      int num_failures = 0;
>> -	      const linespec_sals &lsal = canonical.lsals[0];
>> -	      for (const auto &sal : lsal.sals)
>> +	      const char *cond = cond_string_copy.get ();
>> +	      try
>>  		{
>> -		  const char *cond = cond_string;
>> -		  try
>> -		    {
>> -		      parse_exp_1 (&cond, sal.pc, block_for_pc (sal.pc), 0);
>> -		      /* One success is sufficient to keep going.  */
>> -		      break;
>> -		    }
>> -		  catch (const gdb_exception_error &)
>> -		    {
>> -		      num_failures++;
>> -		      /* If this is the last sal, error out.  */
>> -		      if (num_failures == lsal.sals.size ())
>> -			throw;
>> -		    }
>> +		  parse_exp_1 (&cond, sal.pc, block_for_pc (sal.pc), 0);
>> +		  /* One success is sufficient to keep going.  */
>> +		  break;
>> +		}
>> +	      catch (const gdb_exception_error &)
>> +		{
>> +		  num_failures++;
>> +		  /* If this is the last sal, error out.  */
>> +		  if (num_failures == lsal.sals.size ())
>> +		    throw;
>>  		}
>>  	    }
>> -
>> -	  /* Create a private copy of condition string.  */
>> -	  if (cond_string)
>> -	    cond_string_copy.reset (xstrdup (cond_string));
>> -	  /* Create a private copy of any extra string.  */
>> -	  if (extra_string)
>> -	    extra_string_copy.reset (xstrdup (extra_string));
>>  	}
>>  
>>        ops->create_breakpoints_sal (gdbarch, &canonical,
>> @@ -9386,21 +9198,16 @@ create_breakpoint (struct gdbarch *gdbarch,
>>  								 type_wanted);
>>        b->locspec = locspec->clone ();
>>  
>> -      if (parse_extra)
>> -	b->cond_string = NULL;
>> -      else
>> -	{
>> -	  /* Create a private copy of condition string.  */
>> -	  b->cond_string.reset (cond_string != NULL
>> -				? xstrdup (cond_string)
>> -				: NULL);
>> -	  b->thread = thread;
>> -	}
>> +      /* Create a private copy of the condition string.  */
>> +      b->cond_string = std::move (cond_string_copy);
>> +
>> +      b->thread = thread;
>> +      b->task = task;
>> +      b->inferior = inferior;
>>  
>>        /* Create a private copy of any extra string.  */
>> -      b->extra_string.reset (extra_string != NULL
>> -			     ? xstrdup (extra_string)
>> -			     : NULL);
>> +      b->extra_string = std::move (extra_string_copy);
>> +
>>        b->ignore_count = ignore_count;
>>        b->disposition = tempflag ? disp_del : disp_donttouch;
>>        b->condition_not_parsed = 1;
>> @@ -9409,9 +9216,12 @@ create_breakpoint (struct gdbarch *gdbarch,
>>  	   && type_wanted != bp_hardware_breakpoint) || thread != -1)
>>  	b->pspace = current_program_space;
>>  
>> +      if (b->type == bp_dprintf)
>> +	update_dprintf_command_list (b.get ());
>> +
>>        install_breakpoint (internal, std::move (b), 0);
>>      }
>> -  
>> +
>>    if (canonical.lsals.size () > 1)
>>      {
>>        warning (_("Multiple breakpoints were set.\nUse the "
>> @@ -13145,24 +12955,6 @@ code_breakpoint::location_spec_to_sals (location_spec *locspec,
>>      {
>>        for (auto &sal : sals)
>>  	resolve_sal_pc (&sal);
>> -      if (condition_not_parsed && extra_string != NULL)
>> -	{
>> -	  gdb::unique_xmalloc_ptr<char> local_cond, local_extra;
>> -	  int local_thread, local_task, local_inferior;
>> -
>> -	  find_condition_and_thread_for_sals (sals, extra_string.get (),
>> -					      &local_cond, &local_thread,
>> -					      &local_inferior,
>> -					      &local_task, &local_extra);
>> -	  gdb_assert (cond_string == nullptr);
>> -	  if (local_cond != nullptr)
>> -	    cond_string = std::move (local_cond);
>> -	  thread = local_thread;
>> -	  task = local_task;
>> -	  if (local_extra != nullptr)
>> -	    extra_string = std::move (local_extra);
>> -	  condition_not_parsed = 0;
>> -	}
>>  
>>        if (type == bp_static_tracepoint)
>>  	sals[0] = update_static_tracepoint (this, sals[0]);
>> diff --git a/gdb/testsuite/gdb.ada/tasks.exp b/gdb/testsuite/gdb.ada/tasks.exp
>> index 603d43f7c36..337ee1b6f07 100644
>> --- a/gdb/testsuite/gdb.ada/tasks.exp
>> +++ b/gdb/testsuite/gdb.ada/tasks.exp
>> @@ -55,11 +55,11 @@ gdb_test "watch j task 1 task 3" "You can specify only one task\\."
>>  
>>  # Check that attempting to combine 'task' and 'thread' gives an error.
>>  gdb_test "break break_me task 1 thread 1" \
>> -    "You can specify only one of thread or task\\."
>> +    "You can specify only one of thread, inferior, or task\\."
>>  gdb_test "break break_me thread 1 task 1" \
>> -    "You can specify only one of thread or task\\."
>> +    "You can specify only one of thread, inferior, or task\\."
>>  gdb_test "break break_me inferior 1 task 1" \
>> -    "You can specify only one of inferior or task\\."
>> +    "You can specify only one of thread, inferior, or task\\."
>>  gdb_test "watch j task 1 thread 1" \
>>      "You can specify only one of thread or task\\."
>>  gdb_test "watch j thread 1 task 1" \
>> diff --git a/gdb/testsuite/gdb.base/condbreak.exp b/gdb/testsuite/gdb.base/condbreak.exp
>> index a5b2a28701b..50ae82c3f32 100644
>> --- a/gdb/testsuite/gdb.base/condbreak.exp
>> +++ b/gdb/testsuite/gdb.base/condbreak.exp
>> @@ -179,6 +179,10 @@ gdb_test "break -q main if (1==1) thread 999" \
>>      "Unknown thread 999\\."
>>  gdb_test "break -q main thread 999 if (1==1)" \
>>      "Unknown thread 999\\."
>> +gdb_test "break -q main if (1==1) thread 999 -force-condition" \
>> +    "Unknown thread 999\\."
>> +gdb_test "break -q main thread 999 if (1==1) -force-condition" \
>> +    "Unknown thread 999\\."
>>  
>>  # Verify that both if and thread can be distinguished from a breakpoint
>>  # address expression.
>> @@ -186,20 +190,34 @@ gdb_test "break *main if (1==1) thread 999" \
>>      "Unknown thread 999\\."
>>  gdb_test "break *main thread 999 if (1==1)" \
>>      "Unknown thread 999\\."
>> +gdb_test "break *main if (1==1) thread 999 -force-condition" \
>> +    "Unknown thread 999\\."
>> +gdb_test "break *main thread 999 if (1==1) -force-condition" \
>> +    "Unknown thread 999\\."
>>  
>>  # Similarly for task.
>>  gdb_test "break *main if (1==1) task 999" \
>>      "Unknown task 999\\."
>>  gdb_test "break *main task 999 if (1==1)" \
>>      "Unknown task 999\\."
>> +gdb_test "break *main if (1==1) task 999 -force-condition" \
>> +    "Unknown task 999\\."
>> +gdb_test "break *main task 999 if (1==1) -force-condition" \
>> +    "Unknown task 999\\."
>>  
>> -# GDB accepts abbreviations for "thread" and "task".
>> +# GDB accepts abbreviations for "thread" and "task" and "-force-condition"
>>  gdb_test "break *main if (1==1) t 999" \
>>      "Unknown thread 999\\."
>
> As stated above, I’m not a fan of this way to handle the ambiguity, but
> at least it have been tested.  Something like "b *main t 999 if (1==1)"
> does not work, which I find inconsistent.

I've added some additional tests in this area to cover some of the other
"weird" behaviours that you pointed out.  This doesn't mean I think
these behaviours are the best possible behaviour GDB could have, I'm
just trying to ensure that this patch doesn't change the behaviour at
all.

I'll post an updated version of this series soon.

Thanks,
Andrew

>
>>  gdb_test "break *main if (1==1) th 999" \
>>      "Unknown thread 999\\."
>>  gdb_test "break *main if (1==1) ta 999" \
>>      "Unknown task 999\\."
>> +gdb_test "break *main if (1==1) t 999 -force" \
>> +    "Unknown thread 999\\."
>> +gdb_test "break *main if (1==1) th 999 -force" \
>> +    "Unknown thread 999\\."
>> +gdb_test "break *main if (1==1) ta 999 -force" \
>> +    "Unknown task 999\\."
>>  
>>  set test "run until breakpoint at marker3"
>>  gdb_test_multiple "continue" $test {
>> diff --git a/gdb/testsuite/gdb.base/pending.exp b/gdb/testsuite/gdb.base/pending.exp
>> index d7d3735000a..645f63bdb16 100644
>> --- a/gdb/testsuite/gdb.base/pending.exp
>> +++ b/gdb/testsuite/gdb.base/pending.exp
>> @@ -170,7 +170,8 @@ gdb_test "info break" \
>>  \[\t \]+stop only if k == 1.*
>>  \[\t \]+print k.*
>>  \[0-9\]+\[\t \]+breakpoint     keep y.* in main at .*$srcfile:$mainline.*
>> -\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc if x > 3.*" \
>> +\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc.*
>> +\\s+stop only if x > 3.*" \
>>  "multiple pending breakpoints"
>>  
>>  
>> @@ -195,8 +196,10 @@ gdb_test "info break" \
>>  \[\t \]+stop only if k == 1.*
>>  \[\t \]+print k.*
>>  \[0-9\]+\[\t \]+breakpoint     keep y.* in main at .*$srcfile:$mainline.*
>> -\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc if x > 3.*
>> -\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp3_loc.*ignore next 2 hits.*" \
>> +\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc.*
>> +\\s+stop only if x > 3.*
>> +\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp3_loc.*
>> +\\s+ignore next 2 hits.*" \
>>  "multiple pending breakpoints 2"
>>  
>>  #
>> @@ -267,3 +270,17 @@ gdb_test "info break" \
>>  \[0-9\]+\[\t \]+breakpoint     keep y.* in main at .*$srcfile:$mainline.*
>>  \[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*imaginary.*" \
>>  "verify pending breakpoint after restart"
>> +
>> +# Test GDB's parsing of pending breakpoint thread and condition.
>> +
>> +gdb_test_no_output "set breakpoint pending on"
>> +gdb_test "break foo if (unknown_var && another_unknown_var) thread 1" \
>> +    "Breakpoint $decimal \\(foo\\) pending\\."
>> +set bpnum [get_integer_valueof "\$bpnum" "*INVALID" \
>> +	       "get number for foo breakpoint"]
>> +gdb_test "info breakpoints $bpnum" \
>> +    [multi_line \
>> +	 "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
>> +	 "\\s+stop only if \\(unknown_var && another_unknown_var\\)" \
>> +	 "\\s+stop only in thread 1"] \
>> +    "check pending breakpoint on foo"
>> diff --git a/gdb/testsuite/gdb.linespec/explicit.exp b/gdb/testsuite/gdb.linespec/explicit.exp
>> index 668002d9038..8cbefe204ec 100644
>> --- a/gdb/testsuite/gdb.linespec/explicit.exp
>> +++ b/gdb/testsuite/gdb.linespec/explicit.exp
>> @@ -575,7 +575,7 @@ namespace eval $testfile {
>>  	      allow-pending]} {
>>  	fail "set $tst"
>>      } else {
>> -	gdb_test "info break" ".*PENDING.*myfunction if foofoofoo == 1.*" $tst
>> +	gdb_test "info break" ".*PENDING.*myfunction\r\n\\s+stop only if foofoofoo == 1.*" $tst
>>      }
>>  
>>      gdb_exit
>> @@ -586,7 +586,7 @@ namespace eval $testfile {
>>  	      allow-pending]} {
>>  	fail "set $tst"
>>      } else {
>> -	gdb_test "info break" ".*PENDING.*myfunction if arg == 0" $tst
>> +	gdb_test "info break" ".*PENDING.*myfunction\r\n\\s+stop only if arg == 0" $tst
>>  
>>  	gdb_load [standard_output_file $exefile]
>>  	gdb_test "info break" \
>> diff --git a/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp b/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp
>> index 28f52938aeb..bb9987a5572 100644
>> --- a/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp
>> +++ b/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp
>> @@ -50,7 +50,8 @@ set bp_location1 [gdb_get_line_number "set breakpoint 1 here"]
>>  # Set pending dprintf via MI.
>>  set bp [mi_make_breakpoint_pending -number "1" -type "dprintf" \
>>  	    -disp "keep" -enabled "y" -pending "pendfunc1" \
>> -	    -original-location "pendfunc1"]
>> +	    -original-location "pendfunc1" \
>> +	    -script {\["printf \\\"hello\\\""\]}]
>>  mi_gdb_test "-dprintf-insert -f pendfunc1 \"hello\"" \
>>      ".*\\^done,$bp" "mi set dprintf"
>>  
>> diff --git a/gdb/testsuite/gdb.multi/inferior-specific-bp.exp b/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
>> index 1f6573268da..b8aceabcad6 100644
>> --- a/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
>> +++ b/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
>> @@ -51,9 +51,9 @@ if {![runto_main]} {
>>  # this should fail.  Try with the keywords in both orders just in case the
>>  # parser has a bug.
>>  gdb_test "break foo thread 1.1 inferior 1" \
>> -    "You can specify only one of inferior or thread\\."
>> +    "You can specify only one of thread, inferior, or task\\."
>>  gdb_test "break foo inferior 1 thread 1.1" \
>> -    "You can specify only one of inferior or thread\\."
>> +    "You can specify only one of thread, inferior, or task\\."
>>  
>>  # Try to create a breakpoint using the 'inferior' keyword multiple times.
>>  gdb_test "break foo inferior 1 inferior 2" \
>> diff --git a/gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c b/gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
>> new file mode 100644
>> index 00000000000..15d1b9833dd
>> --- /dev/null
>> +++ b/gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
>> @@ -0,0 +1,22 @@
>> +/* Copyright 2023 Free Software Foundation, Inc.
>> +
>> +   This program is free software; you can redistribute it and/or modify
>> +   it under the terms of the GNU General Public License as published by
>> +   the Free Software Foundation; either version 3 of the License, or
>> +   (at your option) any later version.
>> +
>> +   This program is distributed in the hope that it will be useful,
>> +   but WITHOUT ANY WARRANTY; without even the implied warranty of
>> +   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
>> +   GNU General Public License for more details.
>> +
>> +   You should have received a copy of the GNU General Public License
>> +   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
>> +
>> +int global_var = 0;
>> +
>> +void
>> +foo (int arg)
>> +{
>> +  global_var = arg;
>> +}
>> diff --git a/gdb/testsuite/gdb.threads/del-pending-thread-bp.c b/gdb/testsuite/gdb.threads/del-pending-thread-bp.c
>> new file mode 100644
>> index 00000000000..938e05bc4d7
>> --- /dev/null
>> +++ b/gdb/testsuite/gdb.threads/del-pending-thread-bp.c
>> @@ -0,0 +1,85 @@
>> +/* Copyright 2023 Free Software Foundation, Inc.
>> +
>> +   This program is free software; you can redistribute it and/or modify
>> +   it under the terms of the GNU General Public License as published by
>> +   the Free Software Foundation; either version 3 of the License, or
>> +   (at your option) any later version.
>> +
>> +   This program is distributed in the hope that it will be useful,
>> +   but WITHOUT ANY WARRANTY; without even the implied warranty of
>> +   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
>> +   GNU General Public License for more details.
>> +
>> +   You should have received a copy of the GNU General Public License
>> +   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
>> +
>> +#include <dlfcn.h>
>> +#include <pthread.h>
>> +#include <stdlib.h>
>> +
>> +pthread_barrier_t barrier;
>> +
>> +static void
>> +barrier_wait (pthread_barrier_t *b)
>> +{
>> +  int res = pthread_barrier_wait (b);
>> +  if (res != 0 && res != PTHREAD_BARRIER_SERIAL_THREAD)
>> +    abort ();
>> +}
>> +
>> +static void *
>> +thread_worker (void *arg)
>> +{
>> +  barrier_wait (&barrier);
>> +  return NULL;
>> +}
>> +
>> +void
>> +breakpt ()
>> +{
>> +  /* Nothing.  */
>> +}
>> +
>> +int
>> +main (void)
>> +{
>> +  void *handle;
>> +  void (*func)(int);
>> +  pthread_t thread;
>> +
>> +  if (pthread_barrier_init (&barrier, NULL, 2) != 0)
>> +    abort ();
>> +
>> +  if (pthread_create (&thread, NULL, thread_worker, NULL) != 0)
>> +    abort ();
>> +
>> +  breakpt ();
>> +
>> +  /* Allow the worker thread to complete.  */
>> +  barrier_wait (&barrier);
>> +
>> +  if (pthread_join (thread, NULL) != 0)
>> +    abort ();
>> +
>> +  breakpt ();
>> +
>> +  /* Now load the shared library.  */
>> +  handle = dlopen (SHLIB_NAME, RTLD_LAZY);
>> +  if (handle == NULL)
>> +    abort ();
>> +
>> +  /* Find the function symbol.  */
>> +  func = (void (*)(int)) dlsym (handle, "foo");
>> +
>> +  /* Call the library function.  */
>> +  func (1);
>> +
>> +  /* Unload the shared library.  */
>> +  if (dlclose (handle) != 0)
>> +    abort ();
>> +
>> +  breakpt ();
>> +
>> +  return 0;
>> +}
>> +
>> diff --git a/gdb/testsuite/gdb.threads/del-pending-thread-bp.exp b/gdb/testsuite/gdb.threads/del-pending-thread-bp.exp
>> new file mode 100644
>> index 00000000000..4ed05eaa42d
>> --- /dev/null
>> +++ b/gdb/testsuite/gdb.threads/del-pending-thread-bp.exp
>> @@ -0,0 +1,108 @@
>> +# Copyright 2023 Free Software Foundation, Inc.
>> +
>> +# This program is free software; you can redistribute it and/or modify
>> +# it under the terms of the GNU General Public License as published by
>> +# the Free Software Foundation; either version 3 of the License, or
>> +# (at your option) any later version.
>> +#
>> +# This program is distributed in the hope that it will be useful,
>> +# but WITHOUT ANY WARRANTY; without even the implied warranty of
>> +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
>> +# GNU General Public License for more details.
>> +#
>> +# You should have received a copy of the GNU General Public License
>> +# along with this program.  If not, see <http://www.gnu.org/licenses/>.
>> +
>> +# This test checks that pending thread-specific breakpoints are
>> +# correctly deleted when the thread the breakpoint is for goes out of
>> +# scope.
>> +#
>> +# We also check that we can't create a pending thread-specific
>> +# breakpoint for a non-existent thread.
>> +
>> +require allow_shlib_tests
>> +
>> +standard_testfile
>> +
>> +set libname $testfile-lib
>> +set srcfile_lib $srcdir/$subdir/$libname.c
>> +set binfile_lib [standard_output_file $libname.so]
>> +
>> +if { [gdb_compile_shlib $srcfile_lib $binfile_lib {}] != "" } {
>> +    untested "failed to compile shared library 1"
>> +    return -1
>> +}
>> +
>> +set binfile_lib_target [gdb_download_shlib $binfile_lib]
>> +
>> +if { [prepare_for_testing "failed to prepare" $testfile $srcfile \
>> +	  [list debug \
>> +	       additional_flags=-DSHLIB_NAME=\"$binfile_lib_target\" \
>> +	       shlib_load pthreads]] } {
>> +    return -1
>> +}
>> +
>> +gdb_locate_shlib $binfile_lib
>> +
>> +if ![runto_main] {
>> +    return 0
>> +}
>> +
>> +# Run until we have two threads.
>> +gdb_breakpoint "breakpt"
>> +gdb_continue_to_breakpoint "first breakpt call"
>> +
>> +# Confirm that we have a thread '2'.
>> +gdb_test "info threads" "\r\n\\s+2\\s+\[^\r\n\]+"
>> +
>> +# Create a pending, thread-specific, breakpoint on 'foo'.
>> +gdb_breakpoint "foo thread 2" allow-pending
>> +set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
>> +	       "get breakpoint number"]
>> +
>> +# Check we can't create a pending thread-specific breakpoint for a
>> +# non-existent thread.
>> +gdb_test "with breakpoint pending on -- break foo thread 99" \
>> +    "Unknown thread 99\\."
>> +
>> +# Continue to 'breakpt' again.  Don't use gdb_continue_to_breakpoint
>> +# as we are looking for the thread exited and breakpoint deleted
>> +# messages.
>> +set output [list "Continuing\\."]
>> +
>> +if {!([target_info exists gdb_protocol]
>> +      && ([target_info gdb_protocol] == "remote"
>> +	  || [target_info gdb_protocol] == "extended-remote"))} {
>> +    # Due to bug PR gdb/30129 we don't see the thread exited messages
>> +    # for remote targets.  When this bit of this test can be cleaned
>> +    # up.
>> +    lappend output "\\\[Thread \[^\r\n\]+ exited\\\]"
>> +}
>> +
>> +lappend output "Thread-specific breakpoint $bpnum deleted - thread 2 no longer in the thread list\\." \
>> +    "" \
>> +    "Thread 1 \[^\r\n\]+, breakpt \\(\\) at \[^\r\n\]+" \
>> +    "$decimal\\s+\[^\r\n\]+"
>> +
>> +gdb_test "continue" \
>> +    [multi_line {*}$output] \
>> +    "second breakpt call"
>> +
>> +# Confirm breakpoint has been deleted.
>> +gdb_test "info breakpoints $bpnum" \
>> +    "No breakpoint or watchpoint matching '$bpnum'\\."
>> +
>> +# Continue again.  This will pass through 'foo'.  We should not stop
>> +# in 'foo', the breakpoint has been deleted.  We should next stop in
>> +# breakpt again.
>> +gdb_test "continue" \
>> +    [multi_line \
>> +	 "Continuing\\." \
>> +	 "" \
>> +	 "Thread 1 \[^\r\n\]+ hit Breakpoint $decimal, breakpt \\(\\) at \[^\r\n\]+" \
>> +	 "$decimal\\s+\[^\r\n\]+"] \
>> +    "third breakpt call"
>> +gdb_test "bt 1" \
>> +    [multi_line \
>> +	 "#0\\s+breakpt \\(\\) at \[^\r\n\]+" \
>> +	 "\\(More stack frames follow\\.\\.\\.\\)"]
>> -- 
>> 2.25.4
>> 


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv5 00/10] thread-specific breakpoints in just some inferiors
  2023-08-23 15:59     ` [PATCHv4 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
                         ` (9 preceding siblings ...)
  2023-08-23 15:59       ` [PATCHv4 10/10] gdb: only insert thread-specific breakpoints in the relevant inferior Andrew Burgess
@ 2023-10-03 21:29       ` Andrew Burgess
  2023-10-03 21:29         ` [PATCHv5 01/10] gdb: create_breakpoint: add asserts and additional comments Andrew Burgess
                           ` (9 more replies)
  10 siblings, 10 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-10-03 21:29 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Lancelot SIX

In v5:

  - Updates after Lancelot's feedback, including, -force-condition can
    no longer be abbreviated to '-', and can't be used immediately
    after the breakpoint condition.

  - More tests to check some of the edge cases.

In v4:

  - Big update, this series now handles thread-specific and
    inferior-specific breakpoints.

In v3:

  - Rebased on to current upstream/master, this includes all Simon's
    recent breakpoint changes.  Retested with no regressions seen.

In v2:

  - Rebased on current upstream/master and retested,

  - No changes to code or docs.

---

Andrew Burgess (10):
  gdb: create_breakpoint: add asserts and additional comments
  gdb: create_breakpoint: asserts relating to extra_string/parse_extra
  gdb: change 'if' to gdb_assert in update_dprintf_command_list
  gdb: build dprintf commands just once in code_breakpoint constructor
  gdb: don't display inferior list for pending breakpoints
  gdb: parse pending breakpoint thread/task immediately
  gdb: don't set breakpoint::pspace for in create_breakpoint
  gdb: remove breakpoint_re_set_one
  gdb: remove tracepoint_probe_create_sals_from_location_spec
  gdb: only insert thread-specific breakpoints in the relevant inferior

 gdb/Makefile.in                               |   2 +
 gdb/NEWS                                      |  11 +
 gdb/ada-lang.c                                |   6 +-
 gdb/break-catch-throw.c                       |   6 +-
 gdb/break-cond-parse.c                        | 463 +++++++++++
 gdb/break-cond-parse.h                        |  49 ++
 gdb/breakpoint.c                              | 757 +++++++++---------
 gdb/breakpoint.h                              | 101 ++-
 gdb/testsuite/gdb.ada/tasks.exp               |   6 +-
 gdb/testsuite/gdb.base/condbreak.exp          |  57 +-
 gdb/testsuite/gdb.base/pending.exp            |  23 +-
 gdb/testsuite/gdb.linespec/explicit.exp       |   4 +-
 gdb/testsuite/gdb.mi/mi-dprintf-pending.exp   |   3 +-
 gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp    |   8 +-
 .../gdb.mi/user-selected-context-sync.exp     |   4 +-
 .../gdb.multi/bp-thread-specific.exp          |   7 +-
 .../gdb.multi/inferior-specific-bp.exp        |  16 +-
 .../gdb.multi/multi-target-continue.exp       |   2 +-
 .../gdb.multi/multi-target-ping-pong-next.exp |   4 +-
 .../gdb.multi/pending-bp-del-inferior.c       |  28 +
 .../gdb.multi/pending-bp-del-inferior.exp     | 214 +++++
 gdb/testsuite/gdb.multi/pending-bp-lib.c      |  22 +
 gdb/testsuite/gdb.multi/pending-bp.c          |  66 ++
 gdb/testsuite/gdb.multi/pending-bp.exp        | 336 ++++++++
 gdb/testsuite/gdb.multi/tids.exp              |   6 +-
 .../gdb.threads/del-pending-thread-bp-lib.c   |  22 +
 .../gdb.threads/del-pending-thread-bp.c       |  85 ++
 .../gdb.threads/del-pending-thread-bp.exp     | 108 +++
 28 files changed, 1947 insertions(+), 469 deletions(-)
 create mode 100644 gdb/break-cond-parse.c
 create mode 100644 gdb/break-cond-parse.h
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-del-inferior.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.exp
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.exp


base-commit: e030ce2c79feee6a35665a6580a23dcf937ea46f
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv5 01/10] gdb: create_breakpoint: add asserts and additional comments
  2023-10-03 21:29       ` [PATCHv5 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
@ 2023-10-03 21:29         ` Andrew Burgess
  2023-10-03 21:29         ` [PATCHv5 02/10] gdb: create_breakpoint: asserts relating to extra_string/parse_extra Andrew Burgess
                           ` (8 subsequent siblings)
  9 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-10-03 21:29 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Lancelot SIX

This commit extends the asserts on create_breakpoint (in the header
file), and adds some additional assertions into the definition.

The new assert confirms that when the thread and inferior information
is going to be parsed from the extra_string, then the thread and
inferior arguments should be -1.  That is, the caller of
create_breakpoint should not try to create a thread/inferior specific
breakpoint by *both* specifying thread/inferior *and* asking to parse
the extra_string, it's one or the other.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c |  6 ++++++
 gdb/breakpoint.h | 16 ++++++++++++++++
 2 files changed, 22 insertions(+)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index f378edf865e..c3641439911 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -9232,6 +9232,12 @@ create_breakpoint (struct gdbarch *gdbarch,
   gdb_assert (inferior == -1 || inferior > 0);
   gdb_assert (thread == -1 || inferior == -1);
 
+  /* If PARSE_EXTRA is true then the thread and inferior details will be
+     parsed from  the EXTRA_STRING, the THREAD and INFERIOR arguments
+     should be -1.  */
+  gdb_assert (!parse_extra || thread == -1);
+  gdb_assert (!parse_extra || inferior == -1);
+
   gdb_assert (ops != NULL);
 
   /* If extra_string isn't useful, set it to NULL.  */
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index e75efc90495..07370b83a24 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -1600,6 +1600,22 @@ enum breakpoint_create_flags
    the FORCE_CONDITION parameter is ignored and the corresponding argument
    is parsed from EXTRA_STRING.
 
+   The THREAD should be a global thread number, the created breakpoint will
+   only apply for that thread.  If the breakpoint should apply for all
+   threads then pass -1.  However, if PARSE_EXTRA is non-zero then the
+   THREAD parameter is ignored and an optional thread number will be parsed
+   from EXTRA_STRING.
+
+   The INFERIOR should be a global inferior number, the created breakpoint
+   will only apply for that inferior.  If the breakpoint should apply for
+   all inferiors then pass -1.  However, if PARSE_EXTRA is non-zero then
+   the INFERIOR parameter is ignored and an optional inferior number will
+   be parsed from EXTRA_STRING.
+
+   At most one of THREAD and INFERIOR should be set to a value other than
+   -1; breakpoints can be thread specific, or inferior specific, but not
+   both.
+
    If INTERNAL is non-zero, the breakpoint number will be allocated
    from the internal breakpoint count.
 
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv5 02/10] gdb: create_breakpoint: asserts relating to extra_string/parse_extra
  2023-10-03 21:29       ` [PATCHv5 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
  2023-10-03 21:29         ` [PATCHv5 01/10] gdb: create_breakpoint: add asserts and additional comments Andrew Burgess
@ 2023-10-03 21:29         ` Andrew Burgess
  2023-10-03 21:29         ` [PATCHv5 03/10] gdb: change 'if' to gdb_assert in update_dprintf_command_list Andrew Burgess
                           ` (7 subsequent siblings)
  9 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-10-03 21:29 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Lancelot SIX

The goal of this commit is to better define the API for
create_breakpoint especially around the use of extra_string and
parse_extra.  This will be useful in the next commit when I plan to
make some changes to create_breakpoint.

This commit makes one possibly breaking change: until this commit it
was possible to create thread-specific dprintf breakpoint like this:

  (gdb) dprintf call_me, thread 1 "%s", "hello"
  Dprintf 2 at 0x401152: file /tmp/hello.c, line 8.
  (gdb) info breakpoints
  Num     Type           Disp Enb Address            What
  2       dprintf        keep y   0x0000000000401152 in call_me at /tmp/hello.c:8 thread 1
          stop only in thread 1
          printf "%s", "hello"
  (gdb)

this feature of dprintf was not documented, was not tested, and is
slightly different in syntax to how we create thread specific
breakpoints and/or watchpoints -- the thread condition appears after
the first ','.

I believe that this worked at all was simply by luck.  We happen to
pass the parse_extra flag as true from dprintf_command to
create_breakpoint.

So in this commit I made the choice change this.  We now pass
parse_extra as false from dprintf_command to create_breakpoint.  With
this done it is assumed that the only thing in the extra_string is the
dprintf format and arguments.

Beyond this change I've updated the comment on create_breakpoint in
breakpoint.h, and I've then added some asserts into
create_breakpoint as well as moving around some of the error
handling.

 - We now assert on the incoming argument values,

 - I've moved an error check to sit after the call to
   find_condition_and_thread_for_sals, this ensures the extra_string
   was parsed correctly,

In dprintf_command:

 - We now throw an error if there is no format string after the
   dprintf location.  This error was already being thrown, but was
   being caught later in the process.  With this change we catch the
   missing string earlier,

 - And, as mentioned earlier, we pass parse_extra as false when
   calling create_breakpoint,

In create_tracepoint_from_upload:

 - We now throw an error if the parsed location doesn't completely
   consume the addr_str variable.  This error has now effectively
   moved out of create_breakpoint.
---
 gdb/breakpoint.c | 42 +++++++++++++++++++++++++++++-------------
 gdb/breakpoint.h | 44 +++++++++++++++++++++++++++-----------------
 2 files changed, 56 insertions(+), 30 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index c3641439911..5849e7df1af 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -9244,6 +9244,17 @@ create_breakpoint (struct gdbarch *gdbarch,
   if (extra_string != NULL && *extra_string == '\0')
     extra_string = NULL;
 
+  /* A bp_dprintf must always have an accompanying EXTRA_STRING containing
+     the dprintf format and arguments -- PARSE_EXTRA should always be false
+     in this case.
+
+     For all other breakpoint types, EXTRA_STRING should be nullptr unless
+     PARSE_EXTRA is true.  */
+  gdb_assert ((type_wanted == bp_dprintf
+	       && extra_string != nullptr && !parse_extra)
+	      || (type_wanted != bp_dprintf
+		  && (extra_string == nullptr || parse_extra)));
+
   try
     {
       ops->create_sals_from_location_spec (locspec, &canonical);
@@ -9307,6 +9318,8 @@ create_breakpoint (struct gdbarch *gdbarch,
 
       if (parse_extra)
 	{
+	  gdb_assert (type_wanted != bp_dprintf);
+
 	  gdb::unique_xmalloc_ptr<char> rest;
 	  gdb::unique_xmalloc_ptr<char> cond;
 
@@ -9315,15 +9328,15 @@ create_breakpoint (struct gdbarch *gdbarch,
 	  find_condition_and_thread_for_sals (lsal.sals, extra_string,
 					      &cond, &thread, &inferior,
 					      &task, &rest);
+
+	  if (rest.get () != nullptr && *(rest.get ()) != '\0')
+	    error (_("Garbage '%s' at end of command"), rest.get ());
+
 	  cond_string_copy = std::move (cond);
 	  extra_string_copy = std::move (rest);
 	}
       else
 	{
-	  if (type_wanted != bp_dprintf
-	      && extra_string != NULL && *extra_string != '\0')
-		error (_("Garbage '%s' at end of location"), extra_string);
-
 	  /* Check the validity of the condition.  We should error out
 	     if the condition is invalid at all of the locations and
 	     if it is not forced.  In the PARSE_EXTRA case above, this
@@ -9534,21 +9547,18 @@ dprintf_command (const char *arg, int from_tty)
 
   /* If non-NULL, ARG should have been advanced past the location;
      the next character must be ','.  */
-  if (arg != NULL)
+  if (arg == nullptr || arg[0] != ',' || arg[1] == '\0')
+    error (_("Format string required"));
+  else
     {
-      if (arg[0] != ',' || arg[1] == '\0')
-	error (_("Format string required"));
-      else
-	{
-	  /* Skip the comma.  */
-	  ++arg;
-	}
+      /* Skip the comma.  */
+      ++arg;
     }
 
   create_breakpoint (get_current_arch (),
 		     locspec.get (),
 		     NULL, -1, -1,
-		     arg, false, 1 /* parse arg */,
+		     arg, false, 0 /* parse arg */,
 		     0, bp_dprintf,
 		     0 /* Ignore count */,
 		     pending_break_support,
@@ -14155,6 +14165,12 @@ create_tracepoint_from_upload (struct uploaded_tp *utp)
 
   location_spec_up locspec = string_to_location_spec (&addr_str,
 						      current_language);
+
+
+  gdb_assert (addr_str != nullptr);
+  if (*addr_str != '\0')
+    error (_("Garbage '%s' at end of location"), addr_str);
+
   if (!create_breakpoint (get_current_arch (),
 			  locspec.get (),
 			  utp->cond_string.get (), -1, -1, addr_str,
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index 07370b83a24..baa54573e1a 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -1585,32 +1585,42 @@ enum breakpoint_create_flags
    functions for setting a breakpoint at LOCSPEC.
 
    This function has two major modes of operations, selected by the
-   PARSE_EXTRA parameter.
+   PARSE_EXTRA and WANTED_TYPE parameters.
 
-   If PARSE_EXTRA is zero, LOCSPEC is just the breakpoint's location
-   spec, with condition, thread, and extra string specified by the
-   COND_STRING, THREAD, and EXTRA_STRING parameters.
+   When WANTED_TYPE is not bp_dprintf the following rules apply:
 
-   If PARSE_EXTRA is non-zero, this function will attempt to extract
-   the condition, thread, and extra string from EXTRA_STRING, ignoring
-   the similarly named parameters.
+     If PARSE_EXTRA is zero, LOCSPEC is just the breakpoint's location
+     spec, with condition, thread, and extra string specified by the
+     COND_STRING, THREAD, and EXTRA_STRING parameters.
 
-   If FORCE_CONDITION is true, the condition is accepted even when it is
-   invalid at all of the locations.  However, if PARSE_EXTRA is non-zero,
-   the FORCE_CONDITION parameter is ignored and the corresponding argument
-   is parsed from EXTRA_STRING.
+     If PARSE_EXTRA is non-zero, this function will attempt to extract the
+     condition, thread, and extra string from EXTRA_STRING, ignoring the
+     similarly named parameters.
+
+   When WANTED_TYPE is bp_dprintf the following rules apply:
+
+     PARSE_EXTRA must always be zero, LOCSPEC is just the breakpoint's
+     location spec, with condition, thread, and extra string (which
+     contains the dprintf format and arguments) specified by the
+     COND_STRING, THREAD, and EXTRA_STRING parameters.
+
+   If FORCE_CONDITION is true, the condition (in COND_STRING) is accepted
+   even when it is invalid at all of the locations.  However, if
+   PARSE_EXTRA is non-zero and WANTED_TYPE is not bp_dprintf, the
+   FORCE_CONDITION parameter is ignored and the corresponding argument is
+   parsed from EXTRA_STRING.
 
    The THREAD should be a global thread number, the created breakpoint will
    only apply for that thread.  If the breakpoint should apply for all
-   threads then pass -1.  However, if PARSE_EXTRA is non-zero then the
-   THREAD parameter is ignored and an optional thread number will be parsed
-   from EXTRA_STRING.
+   threads then pass -1.  However, if PARSE_EXTRA is non-zero and
+   WANTED_TYPE is not bp_dprintf, then the THREAD parameter is ignored and
+   an optional thread number will be parsed from EXTRA_STRING.
 
    The INFERIOR should be a global inferior number, the created breakpoint
    will only apply for that inferior.  If the breakpoint should apply for
-   all inferiors then pass -1.  However, if PARSE_EXTRA is non-zero then
-   the INFERIOR parameter is ignored and an optional inferior number will
-   be parsed from EXTRA_STRING.
+   all inferiors then pass -1.  However, if PARSE_EXTRA is non-zero and
+   WANTED_TYPE is not bp_dprintf, then the INFERIOR parameter is ignored
+   and an optional inferior number will be parsed from EXTRA_STRING.
 
    At most one of THREAD and INFERIOR should be set to a value other than
    -1; breakpoints can be thread specific, or inferior specific, but not
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv5 03/10] gdb: change 'if' to gdb_assert in update_dprintf_command_list
  2023-10-03 21:29       ` [PATCHv5 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
  2023-10-03 21:29         ` [PATCHv5 01/10] gdb: create_breakpoint: add asserts and additional comments Andrew Burgess
  2023-10-03 21:29         ` [PATCHv5 02/10] gdb: create_breakpoint: asserts relating to extra_string/parse_extra Andrew Burgess
@ 2023-10-03 21:29         ` Andrew Burgess
  2023-10-03 21:29         ` [PATCHv5 04/10] gdb: build dprintf commands just once in code_breakpoint constructor Andrew Burgess
                           ` (6 subsequent siblings)
  9 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-10-03 21:29 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Lancelot SIX

I noticed in update_dprintf_command_list that we handle the case where
the bp_dprintf style breakpoint doesn't have a format and args string.

However, I don't believe such a situation is possible.  The obvious
approach certainly already catches this case:

  (gdb) dprintf main
  Format string required

If it is possible to create a dprintf breakpoint without a format and
args string then I think we should be catching this case and handling
it at creation time, rather than having GDB just ignore the situation
later on.

And so, I propose that we change the 'if' that ignores the case where
the format/args string is empty, and instead assert that we do always
have a format/args string.  The original code, that handled an empty
format/args string has existed since commit e7e0cddfb0d4, which is
when dprintf support was added to GDB.

If I'm correct and this situation can't ever happen then there should
be no user visible changes after this commit.
---
 gdb/breakpoint.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 5849e7df1af..c615ed65011 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -8542,8 +8542,9 @@ update_dprintf_command_list (struct breakpoint *b)
   const char *dprintf_args = b->extra_string.get ();
   gdb::unique_xmalloc_ptr<char> printf_line = nullptr;
 
-  if (!dprintf_args)
-    return;
+  /* Trying to create a dprintf breakpoint without a format and args
+     string should be detected at creation time.  */
+  gdb_assert (dprintf_args != nullptr);
 
   dprintf_args = skip_spaces (dprintf_args);
 
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv5 04/10] gdb: build dprintf commands just once in code_breakpoint constructor
  2023-10-03 21:29       ` [PATCHv5 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
                           ` (2 preceding siblings ...)
  2023-10-03 21:29         ` [PATCHv5 03/10] gdb: change 'if' to gdb_assert in update_dprintf_command_list Andrew Burgess
@ 2023-10-03 21:29         ` Andrew Burgess
  2023-10-03 21:29         ` [PATCHv5 05/10] gdb: don't display inferior list for pending breakpoints Andrew Burgess
                           ` (5 subsequent siblings)
  9 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-10-03 21:29 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Lancelot SIX

I noticed in code_breakpoint::code_breakpoint that we are calling
update_dprintf_command_list once for each breakpoint location, when we
really only need to call this once per breakpoint -- the data updated
by this function, the breakpoint command list -- is per breakpoint,
not per breakpoint location.  Calling update_dprintf_command_list
multiple times is just wasted effort, there's no per location error
checking, we don't even pass the current location to the function.

This commit moves the update_dprintf_command_list call outside of the
per-location loop. I have also changes the 'if' that handles the case
where the extra_string (which holds the format/args) is empty.  I
don't believe that this situation can ever arise -- and if it does we
should be catching it earlier and throwing an error at that point.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c | 20 +++++++++-----------
 1 file changed, 9 insertions(+), 11 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index c615ed65011..ee5978bd3a3 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -8708,19 +8708,17 @@ code_breakpoint::code_breakpoint (struct gdbarch *gdbarch_,
       /* Do not set breakpoint locations conditions yet.  As locations
 	 are inserted, they get sorted based on their addresses.  Let
 	 the list stabilize to have reliable location numbers.  */
+    }
 
-      /* Dynamic printf requires and uses additional arguments on the
-	 command line, otherwise it's an error.  */
-      if (type == bp_dprintf)
-	{
-	  if (extra_string != nullptr)
-	    update_dprintf_command_list (this);
-	  else
-	    error (_("Format string required"));
-	}
-      else if (extra_string != nullptr)
-	error (_("Garbage '%s' at end of command"), extra_string.get ());
+  /* Dynamic printf requires and uses additional arguments on the
+     command line, otherwise it's an error.  */
+  if (type == bp_dprintf)
+    {
+      gdb_assert (extra_string != nullptr);
+      update_dprintf_command_list (this);
     }
+  else if (extra_string != nullptr)
+    error (_("Garbage '%s' at end of command"), extra_string.get ());
 
   /* The order of the locations is now stable.  Set the location
      condition using the location's number.  */
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv5 05/10] gdb: don't display inferior list for pending breakpoints
  2023-10-03 21:29       ` [PATCHv5 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
                           ` (3 preceding siblings ...)
  2023-10-03 21:29         ` [PATCHv5 04/10] gdb: build dprintf commands just once in code_breakpoint constructor Andrew Burgess
@ 2023-10-03 21:29         ` Andrew Burgess
  2023-10-03 21:29         ` [PATCHv5 06/10] gdb: parse pending breakpoint thread/task immediately Andrew Burgess
                           ` (4 subsequent siblings)
  9 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-10-03 21:29 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Lancelot SIX

I noticed that in the 'info breakpoints' output, GDB sometimes prints
the inferior list for pending breakpoints, this doesn't seem right to
me.  A pending breakpoint has no locations (at least, as far as we
display things in the 'info breakpoints' output), so including an
inferior list seems odd.

Here's what I see right now:

  (gdb) info breakpoint 5
  Num     Type           Disp Enb Address            What
  5       breakpoint     keep y   <PENDING>          foo inf 1
  (gdb)

It's the 'inf 1' at the end of the line that I'm objecting too.

To trigger this behaviour we need to be in a multi-inferior debug
session.  The breakpoint must have been non-pending at some point in
the past, and so have a location assigned to it.

The breakpoint becomes pending again as a result of a shared library
being unloaded.  When this happens the location itself is marked
pending (via bp_location::shlib_disabled).

In print_one_breakpoint_location, in order to print the inferior list
we check that the breakpoint has a location, and that we have multiple
inferiors, but we don't check if the location itself is pending.

This commit adds that check, which means the output is now:

  (gdb) info breakpoint 5
  Num     Type           Disp Enb Address            What
  5       breakpoint     keep y   <PENDING>          foo
  (gdb)

Which I think makes more sense -- indeed, the format without the
inferior list is what we display for a pending breakpoint that has
never had any locations assigned, so I think this change in behaviour
makes GDB more consistent.
---
 gdb/breakpoint.c                         |   2 +-
 gdb/testsuite/gdb.multi/pending-bp-lib.c |  22 ++++
 gdb/testsuite/gdb.multi/pending-bp.c     |  66 ++++++++++++
 gdb/testsuite/gdb.multi/pending-bp.exp   | 130 +++++++++++++++++++++++
 4 files changed, 219 insertions(+), 1 deletion(-)
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.exp

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index ee5978bd3a3..0f246531a26 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -6601,7 +6601,7 @@ print_one_breakpoint_location (struct breakpoint *b,
 	}
     }
 
-  if (loc != NULL && !header_of_multiple)
+  if (loc != NULL && !header_of_multiple && !loc->shlib_disabled)
     {
       std::vector<int> inf_nums;
       int mi_only = 1;
diff --git a/gdb/testsuite/gdb.multi/pending-bp-lib.c b/gdb/testsuite/gdb.multi/pending-bp-lib.c
new file mode 100644
index 00000000000..15d1b9833dd
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp-lib.c
@@ -0,0 +1,22 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+int global_var = 0;
+
+void
+foo (int arg)
+{
+  global_var = arg;
+}
diff --git a/gdb/testsuite/gdb.multi/pending-bp.c b/gdb/testsuite/gdb.multi/pending-bp.c
new file mode 100644
index 00000000000..ca8a3c20b72
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp.c
@@ -0,0 +1,66 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#include <dlfcn.h>
+#include <stdlib.h>
+
+void
+breakpt ()
+{
+  /* Nothing.  */
+}
+
+volatile int global_counter = 0;
+
+volatile int call_count = 1;
+
+int
+main (void)
+{
+  void *handle;
+  void (*func)(int);
+
+  /* Some filler work so that we don't initially stop on the breakpt call
+     below.  */
+  ++global_counter;
+
+  breakpt ();	/* Break before open.  */
+
+  /* Now load the shared library.  */
+  handle = dlopen (SHLIB_NAME, RTLD_LAZY);
+  if (handle == NULL)
+    abort ();
+
+  breakpt ();	/* Break after open.  */
+
+  /* Find the function symbol.  */
+  func = (void (*)(int)) dlsym (handle, "foo");
+
+  for (; call_count > 0; --call_count)
+    {
+      /* Call the library function.  */
+      func (1);
+    }
+
+  breakpt ();	/* Break before close.  */
+
+  /* Unload the shared library.  */
+  if (dlclose (handle) != 0)
+    abort ();
+
+  breakpt ();	/* Break after close.  */
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.multi/pending-bp.exp b/gdb/testsuite/gdb.multi/pending-bp.exp
new file mode 100644
index 00000000000..e4f0aa2e38a
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp.exp
@@ -0,0 +1,130 @@
+# Copyright 2023 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+# Tests related to pending breakpoints in a multi-inferior environment.
+
+require allow_shlib_tests !use_gdb_stub
+
+standard_testfile
+
+set libname $testfile-lib
+set srcfile_lib $srcdir/$subdir/$libname.c
+set binfile_lib [standard_output_file $libname.so]
+
+if { [gdb_compile_shlib $srcfile_lib $binfile_lib {}] != "" } {
+    untested "failed to compile shared library 1"
+    return -1
+}
+
+set binfile_lib_target [gdb_download_shlib $binfile_lib]
+
+if { [build_executable "failed to prepare" $testfile $srcfile \
+	  [list debug \
+	       additional_flags=-DSHLIB_NAME=\"$binfile_lib_target\" \
+	       shlib_load pthreads]] } {
+    return -1
+}
+
+# Used to override delete_breakpoints when we don't want breakpoints
+# deleted.
+proc do_nothing {} {}
+
+# Start two inferiors, both running the same test binary.  The arguments
+# INF_1_STOP and INF_2_STOP are source code patterns that are passed to
+# gdb_get_line_number to figure out where each inferior should be stopped.
+#
+# This proc does a clean_restart and leaves inferior 2 selected.  Also the
+# 'breakpoint pending' flag is enabled, so pending breakpoints can be created
+# without GDB prompting the user.
+proc do_test_setup { inf_1_stop inf_2_stop } {
+    clean_restart ${::binfile}
+
+    gdb_locate_shlib $::binfile_lib
+
+    if ![runto_main] {
+	return false
+    }
+
+    gdb_breakpoint [gdb_get_line_number ${inf_1_stop}] temporary
+    gdb_continue_to_breakpoint "move inferior 1 into position"
+
+    gdb_test "add-inferior -exec ${::binfile}" \
+	"Added inferior 2.*" "add inferior 2"
+    gdb_test "inferior 2" "Switching to inferior 2 .*" "switch to inferior 2"
+
+    with_override delete_breakpoints do_nothing {
+	if {![runto_main]} {
+	    return false
+	}
+    }
+
+    gdb_breakpoint [gdb_get_line_number ${inf_2_stop}] temporary
+    gdb_continue_to_breakpoint "move inferior 2 into position"
+
+    gdb_test_no_output "set breakpoint pending on"
+
+    return true
+}
+
+# Check that when a breakpoint is in the pending state, but that breakpoint
+# does have some locations (those locations themselves are pending), GDB
+# doesn't display the inferior list in the 'info breakpoints' output.
+proc_with_prefix test_no_inf_display {} {
+    do_test_setup "Break before open" "Break before open"
+
+    # Create a breakpoint on 'foo'.  As the shared library (that contains
+    # foo) has not been loaded into any inferior yet, then there will be no
+    # locations and the breakpoint will be created pending.
+    gdb_breakpoint "foo" allow-pending
+    set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+		   "get foo breakpoint number"]
+
+    # Check the 'info breakpoints' output; the breakpoint is pending with
+    # not 'inf X' appearing at the end of the line.
+    gdb_test "info breakpoint $bpnum" \
+	"$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	"check info bp before locations have been created"
+
+    # Now select inferior 1 and allow the inferior to run forward to the
+    # point where a breakpoint location for foo will have been created.
+    gdb_test "inferior 1" "Switching to inferior 1 .*"
+    gdb_breakpoint [gdb_get_line_number "Break after open"] temporary
+    gdb_continue_to_breakpoint \
+	"move inferior 1 until a location has been added"
+
+    # Check the 'info breakpoints' output.  Notice we display the inferior
+    # list at the end of the breakpoint line.
+    gdb_test "info breakpoint $bpnum" \
+	"$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex\\s+<foo\[^>\]*>\\s+inf 1" \
+	"check info breakpoints while breakpoint is inserted"
+
+    # Continue inferior 1 until the shared library has been unloaded.  The
+    # breakpoint on 'foo' will return to the pending state.  We will need to
+    # 'continue' twice as the first time will hit the 'foo' breakpoint.
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "hit the breakpoint in foo"
+    gdb_continue_to_breakpoint "after close library"
+
+    # Check the 'info breakpoints' output, check there is no 'inf 1' at the
+    # end of the breakpoint line.
+    gdb_test "info breakpoint $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	     "\\s+breakpoint already hit 1 time"] \
+	"check info breakpoints while breakpoint is pending"
+}
+
+# Run all the tests.
+test_no_inf_display
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv5 06/10] gdb: parse pending breakpoint thread/task immediately
  2023-10-03 21:29       ` [PATCHv5 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
                           ` (4 preceding siblings ...)
  2023-10-03 21:29         ` [PATCHv5 05/10] gdb: don't display inferior list for pending breakpoints Andrew Burgess
@ 2023-10-03 21:29         ` Andrew Burgess
  2023-10-03 21:29         ` [PATCHv5 07/10] gdb: don't set breakpoint::pspace for in create_breakpoint Andrew Burgess
                           ` (3 subsequent siblings)
  9 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-10-03 21:29 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Lancelot SIX, Eli Zaretskii

The initial motivation for this commit was to allow thread or inferior
specific breakpoints to only be inserted within the appropriate
inferior's program-space.  The benefit of this is that inferiors for
which the breakpoint does not apply will no longer need to stop, and
then resume, for such breakpoints.  This commit does not make this
change, but is a refactor to allow this to happen in a later commit.

The problem we currently have is that when a thread-specific (or
inferior-specific) breakpoint is created, the thread (or inferior)
number is only parsed by calling find_condition_and_thread_for_sals.
This function is only called for non-pending breakpoints, and requires
that we know the locations at which the breakpoint will be placed (for
expression checking in case the breakpoint is also conditional).

A consequence of this is that by the time we figure out the breakpoint
is thread-specific we have already looked up locations in all program
spaces.  This feels wasteful -- if we knew the thread-id earlier then
we could reduce the work GDB does by only looking up locations within
the program space for which the breakpoint applies.

Another consequence of how find_condition_and_thread_for_sals is
called is that pending breakpoints don't currently know they are
thread-specific, nor even that they are conditional!  Additionally, by
delaying parsing the thread-id, pending breakpoints can be created for
non-existent threads, this is different to how non-pending
breakpoints are handled, so I can do this:

  $ gdb -q ./gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp
  Reading symbols from ./gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp...
  (gdb) break foo thread 99
  Function "foo" not defined.
  Make breakpoint pending on future shared library load? (y or [n]) y
  Breakpoint 1 (foo thread 99) pending.
  (gdb) r
  Starting program: /tmp/gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp
  [Thread debugging using libthread_db enabled]
  Using host libthread_db library "/lib64/libthread_db.so.1".
  Error in re-setting breakpoint 1: Unknown thread 99.
  [Inferior 1 (process 3329749) exited normally]
  (gdb)

GDB only checked the validity of 'thread 99' at the point the 'foo'
location became non-pending.  In contrast, if I try this:

  $ gdb -q ./gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp
  Reading symbols from ./gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp...
  (gdb) break main thread 99
  Unknown thread 99.
  (gdb)

GDB immediately checks if 'thread 99' exists.  I think inconsistencies
like this are confusing, and should be fixed if possible.

In this commit the create_breakpoint function is updated so that the
extra_string, which contains the thread, inferior, task, and/or
condition information, is parsed immediately, even for pending
breakpoints.

Obviously, the condition still can't be validated until the breakpoint
becomes non-pending, but the thread, inferior, and task information
can be pulled from the extra-string, and can be validated early on,
even for pending breakpoints.  The -force-condition flag is also
parsed as part of this early parsing change.

There are a couple of benefits to doing this:

1. Printing of breakpoints is more consistent now.  Consider creating
   a conditional breakpoint before this commit:

    (gdb) set breakpoint pending on
    (gdb) break pendingfunc if (0)
    Function "pendingfunc" not defined.
    Breakpoint 1 (pendingfunc if (0)) pending.
    (gdb) break main if (0)
    Breakpoint 2 at 0x401198: file /tmp/hello.c, line 18.
    (gdb) info breakpoints
    Num     Type           Disp Enb Address            What
    1       breakpoint     keep y   <PENDING>          pendingfunc if (0)
    2       breakpoint     keep y   0x0000000000401198 in main at /tmp/hello.c:18
            stop only if (0)
    (gdb)

   And after this commit:

    (gdb) set breakpoint pending on
    (gdb) break pendingfunc if (0)
    Function "pendingfunc" not defined.
    Breakpoint 1 (pendingfunc) pending.
    (gdb) break main if (0)
    Breakpoint 2 at 0x401198: file /home/andrew/tmp/hello.c, line 18.
    (gdb) info breakpoints
    Num     Type           Disp Enb Address            What
    1       breakpoint     keep y   <PENDING>          pendingfunc
            stop only if (0)
    2       breakpoint     keep y   0x0000000000401198 in main at /home/andrew/tmp/hello.c:18
            stop only if (0)
    (gdb)

   Notice that the display of the condition is now the same for the
   pending and non-pending breakpoints.

   The same is true for the thread, inferior, or task information in
   thread, inferior, or task specific breakpoints; this information is
   displayed on its own line rather than being part of the 'What'
   field.

2. We can check that the thread exists as soon as the pending
   breakpoint is created.  Currently there is a weird difference
   between pending and non-pending breakpoints when creating a
   thread-specific breakpoint.

   A pending thread-specific breakpoint only checks its thread when it
   becomes non-pending, at which point the thread the breakpoint was
   intended for might have exited.  Here's the behaviour before this
   commit:

    (gdb) set breakpoint pending on
    (gdb) break foo thread 2
    Function "foo" not defined.
    Breakpoint 2 (foo thread 2) pending.
    (gdb) c
    Continuing.
    [Thread 0x7ffff7c56700 (LWP 2948835) exited]
    Error in re-setting breakpoint 2: Unknown thread 2.
    [Inferior 1 (process 2948832) exited normally]
    (gdb)

   Notice the 'Error in re-setting breakpoint 2: Unknown thread 2.'
   line, this was triggered when GDB tried to make the breakpoint
   non-pending, and GDB discovers that the thread no longer exists.

   Compare that to the behaviour after this commit:

    (gdb) set breakpoint pending on
    (gdb) break foo thread 2
    Function "foo" not defined.
    Breakpoint 2 (foo) pending.
    (gdb) c
    Continuing.
    [Thread 0x7ffff7c56700 (LWP 2949243) exited]
    Thread-specific breakpoint 2 deleted - thread 2 no longer in the thread list.
    [Inferior 1 (process 2949240) exited normally]
    (gdb)

   Now the behaviour for pending breakpoints is identical to
   non-pending breakpoints, the thread specific breakpoint is removed
   as soon as the thread the breakpoint is associated with exits.

   There is an additional change; when the pending breakpoint is
   created prior to this patch we see this line:

     Breakpoint 2 (foo thread 2) pending.

   While after this patch we get this line:

     Breakpoint 2 (foo) pending.

   Notice that 'thread 2' has disappeared.  This might look like a
   regression, but I don't think it is.  That we said 'thread 2'
   before was just a consequence of the lazy parsing of the breakpoint
   specification, while with this patch GDB understands, and has
   parsed away the 'thread 2' bit of the spec.  If folk think the old
   information was useful then this would be trivial to add back in
   code_breakpoint::say_where.

As a result of this commit the breakpoints 'extra_string' field is now
only used by bp_dprintf type breakpoints to hold the printf format and
arguments.  This string should always be empty for other breakpoint
types.  This allows me to clean up some code in
print_breakpoint_location.

In code_breakpoint::code_breakpoint I'm able to change an error case
into an assert.  This is because this error is now handled earlier in
create_breakpoint.  As a result we know that by this point, the
extra_string will always be nullptr for anything other than a
bp_dprintf style breakpoint.

The find_condition_and_thread_for_sals function is now no longer
needed, this was previously doing the delayed splitting of the extra
string into thread, task, and condition, but this is now all done in
create_breakpoint, so find_condition_and_thread_for_sals can be
deleted, and the code that calls this in
code_breakpoint::location_spec_to_sals can be removed.  With this
update this code would only ever be reached for bp_dprintf style
breakpoints, and in these cases the extra_string should not contain
anything other than format and args.

The most interesting changes are all in create_breakpoint and in the
new file break-cond-parse.c.  We have a new block of code early on in
create_breakpoint that is responsible for splitting the extra_string
into its component parts by calling create_breakpoint_parse_arg_string
a function in the new break-cond-parse.c file.  This means that some
of the later code can be simplified a little.

The new break-cond-parse.c file implements the splitting up the
extra_string and finding all the parts, as well as some self-tests for
the new function.

Finally, now we know all the details, these can be stored within the
breakpoint object if we end up creating a deferred breakpoint.
Additionally, if we are creating a deferred bp_dprintf we can parse
the extra_string to build the printf command.

The implementation here aims to maintain backwards compatibility as
much as possible, this means that:

  1. We support abbreviations of 'thread', 'task', and 'inferior' in
  some places on the breakpoint line.  The handling of abbreviations
  has (before this patch) been a little weird, so this works:

  (gdb) break *main th 1

  And creates a breakpoint at '*main' for thread 1 only, while this
  does not work:

  (gdb) break main th 1

  In this case GDB will try to find the symbol 'main th 1'.  This
  weirdness exists before and after this patch.

  2. The handling of '-force-condition' is odd, if this flag appears
  immediately after a condition then it will be treated as part of the
  condition, e.g.:

  (gdb) break main if 0 -force-condition
  No symbol "force" in current context.

  But we are fine with these alternatives:

  (gdb) break main if 0 thread 1 -force-condition
  (gdb) break main -force-condition if 0

  Again, this is just a quirk of how the breakpoint line used to be
  parsed, but I've chosen to maintain this for backward
  compatibility.  Maybe in the future we might wish to consider
  changing this behaviour, but I'd rather do that as a separate commit
  later on, if that was of interest to people.

Reviewed-By: Eli Zaretskii <eliz@gnu.org>
---
 gdb/Makefile.in                               |   2 +
 gdb/NEWS                                      |   4 +
 gdb/break-cond-parse.c                        | 463 ++++++++++++++++++
 gdb/break-cond-parse.h                        |  49 ++
 gdb/breakpoint.c                              | 372 ++++----------
 gdb/testsuite/gdb.ada/tasks.exp               |   6 +-
 gdb/testsuite/gdb.base/condbreak.exp          |  57 ++-
 gdb/testsuite/gdb.base/pending.exp            |  23 +-
 gdb/testsuite/gdb.linespec/explicit.exp       |   4 +-
 gdb/testsuite/gdb.mi/mi-dprintf-pending.exp   |   3 +-
 .../gdb.multi/inferior-specific-bp.exp        |   4 +-
 .../gdb.threads/del-pending-thread-bp-lib.c   |  22 +
 .../gdb.threads/del-pending-thread-bp.c       |  85 ++++
 .../gdb.threads/del-pending-thread-bp.exp     | 108 ++++
 14 files changed, 900 insertions(+), 302 deletions(-)
 create mode 100644 gdb/break-cond-parse.c
 create mode 100644 gdb/break-cond-parse.h
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.exp

diff --git a/gdb/Makefile.in b/gdb/Makefile.in
index 9b992a3d8c0..43b867cd796 100644
--- a/gdb/Makefile.in
+++ b/gdb/Makefile.in
@@ -1026,6 +1026,7 @@ COMMON_SFILES = \
 	break-catch-sig.c \
 	break-catch-syscall.c \
 	break-catch-throw.c \
+	break-cond-parse.c \
 	breakpoint.c \
 	bt-utils.c \
 	btrace.c \
@@ -1293,6 +1294,7 @@ HFILES_NO_SRCDIR = \
 	bfd-target.h \
 	bfin-tdep.h \
 	block.h \
+	break-cond-parse.h \
 	breakpoint.h \
 	bsd-kvm.h \
 	bsd-uthread.h \
diff --git a/gdb/NEWS b/gdb/NEWS
index 20f53a0d542..172b59a2c34 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -110,6 +110,10 @@
   'inferior' keyword with either the 'thread' or 'task' keywords when
   creating a breakpoint.
 
+* For breakpoints that are created in the 'pending' state, any
+  'thread' or 'task' keywords are parsed at the time the breakpoint is
+  created, rather than at the time the breakpoint becomes non-pending.
+
 * New commands
 
 set debug breakpoint on|off
diff --git a/gdb/break-cond-parse.c b/gdb/break-cond-parse.c
new file mode 100644
index 00000000000..b0449f411c7
--- /dev/null
+++ b/gdb/break-cond-parse.c
@@ -0,0 +1,463 @@
+/* Copyright (C) 2023 Free Software Foundation, Inc.
+
+   This file is part of GDB.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#include "defs.h"
+#include "gdbsupport/gdb_assert.h"
+#include "gdbsupport/selftest.h"
+#include "test-target.h"
+#include "scoped-mock-context.h"
+#include "break-cond-parse.h"
+#include "tid-parse.h"
+#include "ada-lang.h"
+
+/* When parsing tokens from a string, which direction are we parsing?
+
+   Given the following string and pointer 'ptr':
+
+	ABC DEF GHI JKL
+	       ^
+	       ptr
+
+   Parsing 'forward' will return the token 'GHI' and update 'ptr' to point
+   between GHI and JKL.  Parsing 'backward' will return the token 'DEF' and
+   update 'ptr' to point between ABC and DEF.
+*/
+
+enum class parse_direction
+{
+  /* Parse the next token forwards.  */
+  forward,
+
+  /* Parse the previous token backwards.  */
+  backward
+};
+
+struct token
+{
+  /* Create a new token.  START points to the first character of the new
+     token, while END points at the last character of the new token.
+
+     Neither START or END can be nullptr, and both START and END must point
+     into the same C style string (i.e. there should be no null character
+     between START and END).  END must be equal to, or greater than START,
+     that is, it is not possible to create a zero length token.  */
+
+  token (const char *start, const char *end)
+    : m_start (start),
+      m_end (end)
+  {
+    gdb_assert (m_end >= m_start);
+    gdb_assert (m_start + strlen (m_start) > m_end);
+  }
+
+  /* Return a pointer to the first character of this token.  */
+  const char *start () const
+  {
+    return m_start;
+  }
+
+  /* Return a pointer to the last character of this token.  */
+  const char *end () const
+  {
+    return m_end;
+  }
+
+  /* Return the length of the token.  */
+  size_t length () const
+  {
+    /* The + 1 is because the character at m_end is part of the token.  */
+    return m_end - m_start + 1;
+  }
+
+  /* Return true if this token matches STR.  */
+  bool matches (const char *str) const
+  {
+    return strncmp (m_start, str, length ()) == 0;
+  }
+
+private:
+  /* The first character of this token.  */
+  const char *m_start;
+
+  /* The last character of this token.  */
+  const char *m_end;
+};
+
+/* Find the next token in DIRECTION from *CURR.  */
+
+static token
+find_next_token (const char **curr, parse_direction direction)
+{
+  const char *tok_start, *tok_end;
+
+  gdb_assert (**curr != '\0');
+
+  if (direction == parse_direction::forward)
+    {
+      *curr = skip_spaces (*curr);
+      tok_start = *curr;
+      *curr = skip_to_space (*curr);
+      tok_end = *curr - 1;
+    }
+  else
+    {
+      gdb_assert (direction == parse_direction::backward);
+
+      while (isspace (**curr))
+	--(*curr);
+
+      tok_end = *curr;
+
+      while (!isspace (**curr))
+	--(*curr);
+
+      tok_start = (*curr) + 1;
+    }
+
+  return token (tok_start, tok_end);
+}
+
+/* See break-cond-parse.h.  */
+
+void
+create_breakpoint_parse_arg_string
+  (const char *tok, gdb::unique_xmalloc_ptr<char> *cond_string,
+   int *thread, int *inferior, int *task,
+   gdb::unique_xmalloc_ptr<char> *rest, bool *force)
+{
+  /* Set up the defaults.  */
+  cond_string->reset ();
+  rest->reset ();
+  *thread = -1;
+  *inferior = -1;
+  *task = -1;
+  *force = false;
+
+  if (tok == nullptr)
+    return;
+
+  /* The "-force-condition" flag gets some special treatment.  If this
+     token is immediately after the condition string then we treat this as
+     part of the condition string rather than a separate token.  This is
+     just a quirk of how this token used to be parsed, and has been
+     retained for backwards compatibility.  Maybe this should be updated
+     in the future.  */
+  gdb::optional<token> force_condition_token;
+
+  const char *cond_start = nullptr;
+  const char *cond_end = nullptr;
+  parse_direction direction = parse_direction::forward;
+  while (*tok != '\0')
+    {
+      /* Find the next token.  If moving backward and this token starts at
+	 the same location as the condition then we must have found the
+	 other end of the condition string -- we're done.  */
+      token t = find_next_token (&tok, direction);
+      if (direction == parse_direction::backward && t.start () <= cond_start)
+	{
+	  cond_end = t.end ();
+	  break;
+	}
+
+      /* We only have a single flag option to check for.  All the other
+	 options take a value so require an additional token to be found.
+	 Additionally, we require that this flag be at least '-f', we
+	 don't allow it to be abbreviated to '-'.  */
+      if (t.length () > 1 && t.matches ("-force-condition"))
+	{
+	  force_condition_token.emplace (t);
+	  continue;
+	}
+
+      /* Maybe the first token was the last token in the string.  If this
+	 is the case then we definitely can't try to extract a value
+	 token.  This also means that the token T is meaningless.  Reset
+	 TOK to point at the start of the unknown content and break out of
+	 the loop.  We'll record the unknown part of the string outside of
+	 the scanning loop (below).  */
+      if (direction == parse_direction::forward && *tok == '\0')
+	{
+	  tok = t.start ();
+	  break;
+	}
+
+      /* As before, find the next token and, if we are scanning backwards,
+	 check that we have not reached the start of the condition string.  */
+      token v = find_next_token (&tok, direction);
+      if (direction == parse_direction::backward && v.start () <= cond_start)
+	{
+	  /* Use token T here as that must also be part of the condition
+	     string.  */
+	  cond_end = t.end ();
+	  break;
+	}
+
+      /* When moving backward we will first parse the value token then the
+	 keyword token, so swap them now.  */
+      if (direction == parse_direction::backward)
+	std::swap (t, v);
+
+      /* Check for valid option in token T.  If we find a valid option then
+	 parse the value from the token V.  Except for 'if', that's handled
+	 differently.
+
+	 For the 'if' token we need to capture the entire condition
+	 string, so record the start of the condition string and then
+	 start scanning backwards looking for the end of the condition
+	 string.
+
+	 The order of these checks is important, at least the check for
+	 'thread' must occur before the check for 'task'.  We accept
+	 abbreviations of these token names, and 't' should resolve to
+	 'thread', which will only happen if we check 'thread' first.  */
+      if (direction == parse_direction::forward && t.matches ("if"))
+	{
+	  cond_start = v.start ();
+	  tok = tok + strlen (tok);
+	  gdb_assert (*tok == '\0');
+	  --tok;
+	  direction = parse_direction::backward;
+	  continue;
+	}
+      else if (t.matches ("thread"))
+	{
+	  if (*thread != -1)
+	    error(_("You can specify only one thread."));
+
+	  if (*task != -1 || *inferior != -1)
+	    error (_("You can specify only one of thread, inferior, or task."));
+
+	  const char *tmptok;
+	  thread_info *thr = parse_thread_id (v.start (), &tmptok);
+	  const char *expected_end = skip_spaces (v.end () + 1);
+	  if (tmptok != expected_end)
+	    error (_("Junk after thread keyword."));
+	  *thread = thr->global_num;
+	}
+      else if (t.matches ("inferior"))
+	{
+	  if (*inferior != -1)
+	    error(_("You can specify only one inferior."));
+
+	  if (*task != -1 || *thread != -1)
+	    error (_("You can specify only one of thread, inferior, or task."));
+
+	  char *tmptok;
+	  *inferior = strtol (v.start (), &tmptok, 0);
+	  const char *expected_end = v.end () + 1;
+	  if (tmptok != expected_end)
+	    error (_("Junk after inferior keyword."));
+	}
+      else if (t.matches ("task"))
+	{
+	  if (*task != -1)
+	    error(_("You can specify only one task."));
+
+	  if (*thread != -1 || *inferior != -1)
+	    error (_("You can specify only one of thread, inferior, or task."));
+
+	  char *tmptok;
+	  *task = strtol (v.start (), &tmptok, 0);
+	  const char *expected_end = v.end () + 1;
+	  if (tmptok != expected_end)
+	    error (_("Junk after task keyword."));
+	  if (!valid_task_id (*task))
+	    error (_("Unknown task %d."), *task);
+	}
+      else
+	{
+	  /* An unknown token.  If we are scanning forward then reset TOK
+	     to point at the start of the unknown content, we record this
+	     outside of the scanning loop (below).
+
+	     If we are scanning backward then unknown content is assumed to
+	     be the other end of the condition string, obviously, this is
+	     just a heuristic, we could be looking at a mistyped command
+	     line, but this will be spotted when the condition is
+	     eventually evaluated.
+
+	     Either way, no more scanning is required after this.  */
+	  if (direction == parse_direction::forward)
+	    tok = t.start ();
+	  else
+	    {
+	      gdb_assert (direction == parse_direction::backward);
+	      cond_end = v.end ();
+	    }
+	  break;
+	}
+    }
+
+  if (cond_start != nullptr)
+    {
+      /* If we found the start of a condition string then we should have
+	 switched to backward scan mode, and found the end of the condition
+	 string.  Capture the whole condition string into COND_STRING
+	 now.  */
+      gdb_assert (direction == parse_direction::backward);
+      gdb_assert (cond_end != nullptr);
+
+      /* If the first token after the condition string is the
+	 "-force-condition" token, then we merge the "-force-condition"
+	 token with the condition string and forget ever seeing the
+	 "-force-condition".  */
+      if (force_condition_token.has_value ())
+	{
+	  const char *next_token_start = skip_spaces (cond_end + 1);
+
+	  if (next_token_start == force_condition_token->start ())
+	    {
+	      cond_end = force_condition_token->end ();
+	      force_condition_token.reset ();
+	    }
+	}
+
+      /* The '+ 1' here is because COND_END points to the last character of
+	 the condition string rather than the null-character at the end of
+	 the condition string, and we need the string length here.  */
+      cond_string->reset (savestring (cond_start, cond_end - cond_start + 1));
+    }
+  else if (*tok != '\0')
+    {
+      /* If we didn't have a condition start pointer then we should still
+	 be in forward scanning mode.  If we didn't reach the end of the
+	 input string (TOK is not at the null character) then the rest of
+	 the input string is garbage that we didn't understand.
+
+	 Record the unknown content into REST.  The caller of this function
+	 will report this as an error later on.  We could report the error
+	 here, but we prefer to allow the caller to run other checks, and
+	 prioritise other errors before reporting this problem.  */
+      gdb_assert (direction == parse_direction::forward);
+      gdb_assert (cond_end == nullptr);
+      rest->reset (savestring (tok, strlen (tok)));
+    }
+
+  /* If we saw "-force-condition" then set the *FORCE flag.  Depending on
+     which path we took above we might have chosen to forget having seen
+     the "-force-condition" token.  */
+  if (force_condition_token.has_value ())
+    *force = true;
+}
+
+#if GDB_SELF_TEST
+
+namespace selftests {
+
+/* Run a single test of the create_breakpoint_parse_arg_string function.
+   INPUT is passed to create_breakpoint_parse_arg_string while all other
+   arguments are the expected output from
+   create_breakpoint_parse_arg_string.  */
+
+static void
+test (const char *input, const char *condition, int thread = -1,
+      int inferior = -1, int task = -1, bool force = false,
+      const char *rest = nullptr)
+{
+  gdb::unique_xmalloc_ptr<char> extracted_condition;
+  gdb::unique_xmalloc_ptr<char> extracted_rest;
+  int extracted_thread, extracted_inferior, extracted_task;
+  bool extracted_force_condition;
+  std::string exception_msg;
+
+  try
+    {
+      create_breakpoint_parse_arg_string (input, &extracted_condition,
+					  &extracted_thread,
+					  &extracted_inferior,
+					  &extracted_task, &extracted_rest,
+					  &extracted_force_condition);
+    }
+  catch (const gdb_exception_error &ex)
+    {
+      string_file buf;
+
+      exception_print (&buf, ex);
+      exception_msg = buf.release ();
+    }
+
+  if ((condition == nullptr) != (extracted_condition.get () == nullptr)
+      || (condition != nullptr
+	  && strcmp (condition, extracted_condition.get ()) != 0)
+      || (rest == nullptr) != (extracted_rest.get () == nullptr)
+      || (rest != nullptr && strcmp (rest, extracted_rest.get ()) != 0)
+      || thread != extracted_thread
+      || inferior != extracted_inferior
+      || task != extracted_task
+      || force != extracted_force_condition
+      || !exception_msg.empty ())
+    {
+      if (run_verbose ())
+	{
+	  debug_printf ("input: '%s'\n", input);
+	  debug_printf ("condition: '%s'\n", extracted_condition.get ());
+	  debug_printf ("rest: '%s'\n", extracted_rest.get ());
+	  debug_printf ("thread: %d\n", extracted_thread);
+	  debug_printf ("inferior: %d\n", extracted_inferior);
+	  debug_printf ("task: %d\n", extracted_task);
+	  debug_printf ("forced: %s\n",
+			extracted_force_condition ? "true" : "false");
+	  debug_printf ("exception: '%s'\n", exception_msg.c_str ());
+	}
+
+      /* Report the failure.  */
+      SELF_CHECK (false);
+    }
+}
+
+/* Test the create_breakpoint_parse_arg_string function.  Just wraps
+   multiple calls to the test function above.  */
+
+static void
+create_breakpoint_parse_arg_string_tests (void)
+{
+  gdbarch *arch = current_inferior ()->gdbarch;
+  scoped_restore_current_pspace_and_thread restore;
+  scoped_mock_context<test_target_ops> mock_target (arch);
+
+  int global_thread_num = mock_target.mock_thread.global_num;
+
+  test ("  if blah  ", "blah");
+  test (" if blah thread 1", "blah", global_thread_num);
+  test (" if blah inferior 1", "blah", -1, 1);
+  test (" if blah thread 1  ", "blah", global_thread_num);
+  test ("thread 1 woof", nullptr, global_thread_num, -1, -1, false, "woof");
+  test ("thread 1 X", nullptr, global_thread_num, -1, -1, false, "X");
+  test (" if blah thread 1 -force-condition", "blah", global_thread_num,
+	-1, -1, true);
+  test (" -force-condition if blah thread 1", "blah", global_thread_num,
+	-1, -1, true);
+  test (" -force-condition if blah thread 1  ", "blah", global_thread_num,
+	-1, -1, true);
+  test ("thread 1 -force-condition if blah", "blah", global_thread_num,
+	-1, -1, true);
+  test ("if (A::outer::func ())", "(A::outer::func ())");
+}
+
+} // namespace selftests
+#endif /* GDB_SELF_TEST */
+
+void _initialize_break_cond_parse ();
+void
+_initialize_break_cond_parse ()
+{
+#if GDB_SELF_TEST
+  selftests::register_test
+    ("create_breakpoint_parse_arg_string",
+     selftests::create_breakpoint_parse_arg_string_tests);
+#endif
+}
diff --git a/gdb/break-cond-parse.h b/gdb/break-cond-parse.h
new file mode 100644
index 00000000000..b08b6fc6cc9
--- /dev/null
+++ b/gdb/break-cond-parse.h
@@ -0,0 +1,49 @@
+/* Copyright (C) 2023 Free Software Foundation, Inc.
+
+   This file is part of GDB.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#if !defined (BREAK_COND_PARSE_H)
+#define BREAK_COND_PARSE_H 1
+
+/* Given TOK, a string possibly containing a condition, thread, inferior,
+   task and force-condition flag, as accepted by the 'break' command,
+   extract the condition string, thread, inferior, task number, and the
+   force_condition flag, then set *COND_STRING, *THREAD, *INFERIOR, *TASK,
+   and *FORCE.
+
+   As TOK is parsed, if an unknown keyword is encountered before the 'if'
+   keyword then everything starting from the unknown keyword is placed into
+   *REST.
+
+   Both *COND and *REST are initialized to nullptr.  If no 'if' keyword is
+   found then *COND will be returned as nullptr.  If no unknown content is
+   found then *REST is returned as nullptr.
+
+   If no thread is found, *THREAD is set to -1.  If no inferior is found,
+   *INFERIOR is set to -1.  If no task is found, *TASK is set to -1.  If
+   the -force-condition flag is not found then *FORCE is set to false.
+
+   Due to the free-form nature that the string TOK might take (a 'thread'
+   keyword can appear before or after an 'if' condition) then we end up
+   having to check for keywords from both the start of TOK and the end of
+   TOK.  */
+
+extern void create_breakpoint_parse_arg_string
+  (const char *tok, gdb::unique_xmalloc_ptr<char> *cond_string,
+   int *thread, int *inferior, int *task,
+   gdb::unique_xmalloc_ptr<char> *rest, bool *force);
+
+#endif
diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 0f246531a26..d880844f07b 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -70,6 +70,7 @@
 #include "cli/cli-style.h"
 #include "cli/cli-decode.h"
 #include <unordered_set>
+#include "break-cond-parse.h"
 
 /* readline include files */
 #include "readline/tilde.h"
@@ -6339,20 +6340,7 @@ print_breakpoint_location (const breakpoint *b, const bp_location *loc)
       uiout->field_stream ("at", stb);
     }
   else
-    {
-      uiout->field_string ("pending", b->locspec->to_string ());
-      /* If extra_string is available, it could be holding a condition
-	 or dprintf arguments.  In either case, make sure it is printed,
-	 too, but only for non-MI streams.  */
-      if (!uiout->is_mi_like_p () && b->extra_string != NULL)
-	{
-	  if (b->type == bp_dprintf)
-	    uiout->text (",");
-	  else
-	    uiout->text (" ");
-	  uiout->text (b->extra_string.get ());
-	}
-    }
+    uiout->field_string ("pending", b->locspec->to_string ());
 
   if (loc && is_breakpoint (b)
       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
@@ -8717,8 +8705,8 @@ code_breakpoint::code_breakpoint (struct gdbarch *gdbarch_,
       gdb_assert (extra_string != nullptr);
       update_dprintf_command_list (this);
     }
-  else if (extra_string != nullptr)
-    error (_("Garbage '%s' at end of command"), extra_string.get ());
+  else
+    gdb_assert (extra_string == nullptr);
 
   /* The order of the locations is now stable.  Set the location
      condition using the location's number.  */
@@ -8946,197 +8934,6 @@ check_fast_tracepoint_sals (struct gdbarch *gdbarch,
     }
 }
 
-/* Given TOK, a string specification of condition and thread, as accepted
-   by the 'break' command, extract the condition string into *COND_STRING.
-   If no condition string is found then *COND_STRING is set to nullptr.
-
-   If the breakpoint specification has an associated thread, task, or
-   inferior, these are extracted into *THREAD, *TASK, and *INFERIOR
-   respectively, otherwise these arguments are set to -1 (for THREAD and
-   INFERIOR) or 0 (for TASK).
-
-   PC identifies the context at which the condition should be parsed.  */
-
-static void
-find_condition_and_thread (const char *tok, CORE_ADDR pc,
-			   gdb::unique_xmalloc_ptr<char> *cond_string,
-			   int *thread, int *inferior, int *task,
-			   gdb::unique_xmalloc_ptr<char> *rest)
-{
-  cond_string->reset ();
-  *thread = -1;
-  *inferior = -1;
-  *task = -1;
-  rest->reset ();
-  bool force = false;
-
-  while (tok && *tok)
-    {
-      const char *end_tok;
-      int toklen;
-      const char *cond_start = NULL;
-      const char *cond_end = NULL;
-
-      tok = skip_spaces (tok);
-
-      if ((*tok == '"' || *tok == ',') && rest)
-	{
-	  rest->reset (savestring (tok, strlen (tok)));
-	  break;
-	}
-
-      end_tok = skip_to_space (tok);
-
-      toklen = end_tok - tok;
-
-      if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
-	{
-	  tok = cond_start = end_tok + 1;
-	  try
-	    {
-	      parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
-	    }
-	  catch (const gdb_exception_error &)
-	    {
-	      if (!force)
-		throw;
-	      else
-		tok = tok + strlen (tok);
-	    }
-	  cond_end = tok;
-	  cond_string->reset (savestring (cond_start, cond_end - cond_start));
-	}
-      else if (toklen >= 1 && strncmp (tok, "-force-condition", toklen) == 0)
-	{
-	  tok = tok + toklen;
-	  force = true;
-	}
-      else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
-	{
-	  const char *tmptok;
-	  struct thread_info *thr;
-
-	  if (*thread != -1)
-	    error(_("You can specify only one thread."));
-
-	  if (*task != -1)
-	    error (_("You can specify only one of thread or task."));
-
-	  if (*inferior != -1)
-	    error (_("You can specify only one of inferior or thread."));
-
-	  tok = end_tok + 1;
-	  thr = parse_thread_id (tok, &tmptok);
-	  if (tok == tmptok)
-	    error (_("Junk after thread keyword."));
-	  *thread = thr->global_num;
-	  tok = tmptok;
-	}
-      else if (toklen >= 1 && strncmp (tok, "inferior", toklen) == 0)
-	{
-	  if (*inferior != -1)
-	    error(_("You can specify only one inferior."));
-
-	  if (*task != -1)
-	    error (_("You can specify only one of inferior or task."));
-
-	  if (*thread != -1)
-	    error (_("You can specify only one of inferior or thread."));
-
-	  char *tmptok;
-	  tok = end_tok + 1;
-	  *inferior = strtol (tok, &tmptok, 0);
-	  if (tok == tmptok)
-	    error (_("Junk after inferior keyword."));
-	  if (!valid_global_inferior_id (*inferior))
-	    error (_("Unknown inferior number %d."), *inferior);
-	  tok = tmptok;
-	}
-      else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
-	{
-	  char *tmptok;
-
-	  if (*task != -1)
-	    error(_("You can specify only one task."));
-
-	  if (*thread != -1)
-	    error (_("You can specify only one of thread or task."));
-
-	  if (*inferior != -1)
-	    error (_("You can specify only one of inferior or task."));
-
-	  tok = end_tok + 1;
-	  *task = strtol (tok, &tmptok, 0);
-	  if (tok == tmptok)
-	    error (_("Junk after task keyword."));
-	  if (!valid_task_id (*task))
-	    error (_("Unknown task %d."), *task);
-	  tok = tmptok;
-	}
-      else if (rest)
-	{
-	  rest->reset (savestring (tok, strlen (tok)));
-	  break;
-	}
-      else
-	error (_("Junk at end of arguments."));
-    }
-}
-
-/* Call 'find_condition_and_thread' for each sal in SALS until a parse
-   succeeds.  The parsed values are written to COND_STRING, THREAD,
-   TASK, and REST.  See the comment of 'find_condition_and_thread'
-   for the description of these parameters and INPUT.  */
-
-static void
-find_condition_and_thread_for_sals (const std::vector<symtab_and_line> &sals,
-				    const char *input,
-				    gdb::unique_xmalloc_ptr<char> *cond_string,
-				    int *thread, int *inferior, int *task,
-				    gdb::unique_xmalloc_ptr<char> *rest)
-{
-  int num_failures = 0;
-  for (auto &sal : sals)
-    {
-      gdb::unique_xmalloc_ptr<char> cond;
-      int thread_id = -1;
-      int inferior_id = -1;
-      int task_id = -1;
-      gdb::unique_xmalloc_ptr<char> remaining;
-
-      /* Here we want to parse 'arg' to separate condition from thread
-	 number.  But because parsing happens in a context and the
-	 contexts of sals might be different, try each until there is
-	 success.  Finding one successful parse is sufficient for our
-	 goal.  When setting the breakpoint we'll re-parse the
-	 condition in the context of each sal.  */
-      try
-	{
-	  find_condition_and_thread (input, sal.pc, &cond, &thread_id,
-				     &inferior_id, &task_id, &remaining);
-	  *cond_string = std::move (cond);
-	  /* A value of -1 indicates that these fields are unset.  At most
-	     one of these fields should be set (to a value other than -1)
-	     at this point.  */
-	  gdb_assert (((thread_id == -1 ? 1 : 0)
-		       + (task_id == -1 ? 1 : 0)
-		       + (inferior_id == -1 ? 1 : 0)) >= 2);
-	  *thread = thread_id;
-	  *inferior = inferior_id;
-	  *task = task_id;
-	  *rest = std::move (remaining);
-	  break;
-	}
-      catch (const gdb_exception_error &e)
-	{
-	  num_failures++;
-	  /* If no sal remains, do not continue.  */
-	  if (num_failures == sals.size ())
-	    throw;
-	}
-    }
-}
-
 /* Decode a static tracepoint marker spec.  */
 
 static std::vector<symtab_and_line>
@@ -9254,6 +9051,46 @@ create_breakpoint (struct gdbarch *gdbarch,
 	      || (type_wanted != bp_dprintf
 		  && (extra_string == nullptr || parse_extra)));
 
+  /* Will hold either copies of the similarly named function argument, or
+     will hold a modified version of the function argument, depending on
+     the value of PARSE_EXTRA.  */
+  gdb::unique_xmalloc_ptr<char> cond_string_copy;
+  gdb::unique_xmalloc_ptr<char> extra_string_copy;
+
+  if (parse_extra)
+    {
+      /* Parse EXTRA_STRING splitting the parts out.  */
+      create_breakpoint_parse_arg_string (extra_string, &cond_string_copy,
+					  &thread, &inferior, &task,
+					  &extra_string_copy,
+					  &force_condition);
+
+      /* We could check that EXTRA_STRING_COPY is empty at this point -- it
+	 should be, as we only get here for things that are not bp_dprintf,
+	 however, we prefer to give the location spec parser a chance to
+	 run first, this means the user will get errors about invalid
+	 location spec instead of an error about garbage at the end of the
+	 command line.
+
+	 We still do the EXTRA_STRING_COPY is empty check, just later in
+	 this function.  */
+
+      gdb_assert (thread == -1 || thread > 0);
+      gdb_assert (task == -1 || task > 0);
+      gdb_assert (inferior == -1 || inferior > 0);
+    }
+  else
+    {
+      if (cond_string != nullptr)
+	cond_string_copy.reset (xstrdup (cond_string));
+      if (extra_string != nullptr)
+	extra_string_copy.reset (xstrdup (extra_string));
+    }
+
+  /* Clear these.  Updated values are now held in the *_copy locals.  */
+  cond_string = nullptr;
+  extra_string = nullptr;
+
   try
     {
       ops->create_sals_from_location_spec (locspec, &canonical);
@@ -9289,6 +9126,13 @@ create_breakpoint (struct gdbarch *gdbarch,
 	throw;
     }
 
+  /* The only bp_dprintf should have anything in EXTRA_STRING_COPY by this
+     point.  For all other breakpoints this indicates an error.  We could
+     place this check earlier in the function, but we prefer to see errors
+     from the location spec parser before we see this error message.  */
+  if (type_wanted != bp_dprintf && extra_string_copy.get () != nullptr)
+    error (_("Garbage '%s' at end of command"), extra_string_copy.get ());
+
   if (!pending && canonical.lsals.empty ())
     return 0;
 
@@ -9312,63 +9156,31 @@ create_breakpoint (struct gdbarch *gdbarch,
      breakpoint.  */
   if (!pending)
     {
-      gdb::unique_xmalloc_ptr<char> cond_string_copy;
-      gdb::unique_xmalloc_ptr<char> extra_string_copy;
-
-      if (parse_extra)
+      /* Check the validity of the condition.  We should error out if the
+	 condition is invalid at all of the locations and if it is not
+	 forced.  In the PARSE_EXTRA case above, this check is done when
+	 parsing the EXTRA_STRING.  */
+      if (cond_string_copy.get () != nullptr && !force_condition)
 	{
-	  gdb_assert (type_wanted != bp_dprintf);
-
-	  gdb::unique_xmalloc_ptr<char> rest;
-	  gdb::unique_xmalloc_ptr<char> cond;
-
+	  int num_failures = 0;
 	  const linespec_sals &lsal = canonical.lsals[0];
-
-	  find_condition_and_thread_for_sals (lsal.sals, extra_string,
-					      &cond, &thread, &inferior,
-					      &task, &rest);
-
-	  if (rest.get () != nullptr && *(rest.get ()) != '\0')
-	    error (_("Garbage '%s' at end of command"), rest.get ());
-
-	  cond_string_copy = std::move (cond);
-	  extra_string_copy = std::move (rest);
-	}
-      else
-	{
-	  /* Check the validity of the condition.  We should error out
-	     if the condition is invalid at all of the locations and
-	     if it is not forced.  In the PARSE_EXTRA case above, this
-	     check is done when parsing the EXTRA_STRING.  */
-	  if (cond_string != nullptr && !force_condition)
+	  for (const auto &sal : lsal.sals)
 	    {
-	      int num_failures = 0;
-	      const linespec_sals &lsal = canonical.lsals[0];
-	      for (const auto &sal : lsal.sals)
+	      const char *cond = cond_string_copy.get ();
+	      try
 		{
-		  const char *cond = cond_string;
-		  try
-		    {
-		      parse_exp_1 (&cond, sal.pc, block_for_pc (sal.pc), 0);
-		      /* One success is sufficient to keep going.  */
-		      break;
-		    }
-		  catch (const gdb_exception_error &)
-		    {
-		      num_failures++;
-		      /* If this is the last sal, error out.  */
-		      if (num_failures == lsal.sals.size ())
-			throw;
-		    }
+		  parse_exp_1 (&cond, sal.pc, block_for_pc (sal.pc), 0);
+		  /* One success is sufficient to keep going.  */
+		  break;
+		}
+	      catch (const gdb_exception_error &)
+		{
+		  num_failures++;
+		  /* If this is the last sal, error out.  */
+		  if (num_failures == lsal.sals.size ())
+		    throw;
 		}
 	    }
-
-	  /* Create a private copy of condition string.  */
-	  if (cond_string)
-	    cond_string_copy.reset (xstrdup (cond_string));
-	  /* Create a private copy of any extra string.  */
-	  if (extra_string)
-	    extra_string_copy.reset (xstrdup (extra_string));
 	}
 
       ops->create_breakpoints_sal (gdbarch, &canonical,
@@ -9385,21 +9197,16 @@ create_breakpoint (struct gdbarch *gdbarch,
 								 type_wanted);
       b->locspec = locspec->clone ();
 
-      if (parse_extra)
-	b->cond_string = NULL;
-      else
-	{
-	  /* Create a private copy of condition string.  */
-	  b->cond_string.reset (cond_string != NULL
-				? xstrdup (cond_string)
-				: NULL);
-	  b->thread = thread;
-	}
+      /* Create a private copy of the condition string.  */
+      b->cond_string = std::move (cond_string_copy);
+
+      b->thread = thread;
+      b->task = task;
+      b->inferior = inferior;
 
       /* Create a private copy of any extra string.  */
-      b->extra_string.reset (extra_string != NULL
-			     ? xstrdup (extra_string)
-			     : NULL);
+      b->extra_string = std::move (extra_string_copy);
+
       b->ignore_count = ignore_count;
       b->disposition = tempflag ? disp_del : disp_donttouch;
       b->condition_not_parsed = 1;
@@ -9408,9 +9215,12 @@ create_breakpoint (struct gdbarch *gdbarch,
 	   && type_wanted != bp_hardware_breakpoint) || thread != -1)
 	b->pspace = current_program_space;
 
+      if (b->type == bp_dprintf)
+	update_dprintf_command_list (b.get ());
+
       install_breakpoint (internal, std::move (b), 0);
     }
-  
+
   if (canonical.lsals.size () > 1)
     {
       warning (_("Multiple breakpoints were set.\nUse the "
@@ -13157,24 +12967,6 @@ code_breakpoint::location_spec_to_sals (location_spec *locspec,
     {
       for (auto &sal : sals)
 	resolve_sal_pc (&sal);
-      if (condition_not_parsed && extra_string != NULL)
-	{
-	  gdb::unique_xmalloc_ptr<char> local_cond, local_extra;
-	  int local_thread, local_task, local_inferior;
-
-	  find_condition_and_thread_for_sals (sals, extra_string.get (),
-					      &local_cond, &local_thread,
-					      &local_inferior,
-					      &local_task, &local_extra);
-	  gdb_assert (cond_string == nullptr);
-	  if (local_cond != nullptr)
-	    cond_string = std::move (local_cond);
-	  thread = local_thread;
-	  task = local_task;
-	  if (local_extra != nullptr)
-	    extra_string = std::move (local_extra);
-	  condition_not_parsed = 0;
-	}
 
       if (type == bp_static_tracepoint)
 	{
diff --git a/gdb/testsuite/gdb.ada/tasks.exp b/gdb/testsuite/gdb.ada/tasks.exp
index 603d43f7c36..337ee1b6f07 100644
--- a/gdb/testsuite/gdb.ada/tasks.exp
+++ b/gdb/testsuite/gdb.ada/tasks.exp
@@ -55,11 +55,11 @@ gdb_test "watch j task 1 task 3" "You can specify only one task\\."
 
 # Check that attempting to combine 'task' and 'thread' gives an error.
 gdb_test "break break_me task 1 thread 1" \
-    "You can specify only one of thread or task\\."
+    "You can specify only one of thread, inferior, or task\\."
 gdb_test "break break_me thread 1 task 1" \
-    "You can specify only one of thread or task\\."
+    "You can specify only one of thread, inferior, or task\\."
 gdb_test "break break_me inferior 1 task 1" \
-    "You can specify only one of inferior or task\\."
+    "You can specify only one of thread, inferior, or task\\."
 gdb_test "watch j task 1 thread 1" \
     "You can specify only one of thread or task\\."
 gdb_test "watch j thread 1 task 1" \
diff --git a/gdb/testsuite/gdb.base/condbreak.exp b/gdb/testsuite/gdb.base/condbreak.exp
index a5b2a28701b..5a6a42e073b 100644
--- a/gdb/testsuite/gdb.base/condbreak.exp
+++ b/gdb/testsuite/gdb.base/condbreak.exp
@@ -179,6 +179,10 @@ gdb_test "break -q main if (1==1) thread 999" \
     "Unknown thread 999\\."
 gdb_test "break -q main thread 999 if (1==1)" \
     "Unknown thread 999\\."
+gdb_test "break -q main if (1==1) thread 999 -force-condition" \
+    "Unknown thread 999\\."
+gdb_test "break -q main thread 999 if (1==1) -force-condition" \
+    "Unknown thread 999\\."
 
 # Verify that both if and thread can be distinguished from a breakpoint
 # address expression.
@@ -186,20 +190,71 @@ gdb_test "break *main if (1==1) thread 999" \
     "Unknown thread 999\\."
 gdb_test "break *main thread 999 if (1==1)" \
     "Unknown thread 999\\."
+gdb_test "break *main if (1==1) thread 999 -force-condition" \
+    "Unknown thread 999\\."
+gdb_test "break *main thread 999 if (1==1) -force-condition" \
+    "Unknown thread 999\\."
 
 # Similarly for task.
 gdb_test "break *main if (1==1) task 999" \
     "Unknown task 999\\."
 gdb_test "break *main task 999 if (1==1)" \
     "Unknown task 999\\."
+gdb_test "break *main if (1==1) task 999 -force-condition" \
+    "Unknown task 999\\."
+gdb_test "break *main task 999 if (1==1) -force-condition" \
+    "Unknown task 999\\."
 
-# GDB accepts abbreviations for "thread" and "task".
+# GDB accepts abbreviations for "thread", "task" and
+# "-force-condition", when these keywords appear after
+# the breakpoint condition.
 gdb_test "break *main if (1==1) t 999" \
     "Unknown thread 999\\."
 gdb_test "break *main if (1==1) th 999" \
     "Unknown thread 999\\."
 gdb_test "break *main if (1==1) ta 999" \
     "Unknown task 999\\."
+gdb_test "break *main if (1==1) t 999 -force" \
+    "Unknown thread 999\\."
+gdb_test "break *main if (1==1) th 999 -force" \
+    "Unknown thread 999\\."
+gdb_test "break *main if (1==1) ta 999 -force" \
+    "Unknown task 999\\."
+
+# Check the use of abbreviations before the condition.  This works
+# because, when the location spec starts with '*' GDB is able to
+# figure out that the complete location is '*main'.
+gdb_test "break *main t 999 if (1==1)" \
+    "Unknown thread 999\\."
+gdb_test "break *main th 999 if (1==1)" \
+    "Unknown thread 999\\."
+gdb_test "break *main ta 999 if (1==1)" \
+    "Unknown task 999\\."
+gdb_test "break *main t 999 -force if (1==1)" \
+    "Unknown thread 999\\."
+gdb_test "break *main th 999 -force if (1==1)" \
+    "Unknown thread 999\\."
+gdb_test "break *main ta 999 -force if (1==1)" \
+    "Unknown task 999\\."
+
+# However, when the location spec doesn't start with '*' GDB relies on
+# the linespec parser to spot the keyword which marks the end of the
+# linespec, and this parser doesn't check for abbreviations.
+gdb_test "with breakpoint pending off -- break main t 999 if (1==1)" \
+    "Function \"main t 999\" not defined\\."
+gdb_test "with breakpoint pending off -- break main th 999 if (1==1)" \
+    "Function \"main th 999\" not defined\\."
+gdb_test "with breakpoint pending off -- break main ta 999 if (1==1)" \
+    "Function \"main ta 999\" not defined\\."
+
+# GDB does not treat a "-force-condition" flag that appears
+# immediately after the condition as the flag, but instead treats it
+# as " - force - condition", that is, subtraction of the symbol
+# "force" followed by subtraction of symbol "context".  This is really
+# just a quirk of how this used to be implemented, and should maybe be
+# changed in the future.  However, for now GDB retains this behaviour.
+gdb_test "break *main if (1==1) -force-condition" \
+    "No symbol \"force\" in current context\\."
 
 set test "run until breakpoint at marker3"
 gdb_test_multiple "continue" $test {
diff --git a/gdb/testsuite/gdb.base/pending.exp b/gdb/testsuite/gdb.base/pending.exp
index d7d3735000a..645f63bdb16 100644
--- a/gdb/testsuite/gdb.base/pending.exp
+++ b/gdb/testsuite/gdb.base/pending.exp
@@ -170,7 +170,8 @@ gdb_test "info break" \
 \[\t \]+stop only if k == 1.*
 \[\t \]+print k.*
 \[0-9\]+\[\t \]+breakpoint     keep y.* in main at .*$srcfile:$mainline.*
-\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc if x > 3.*" \
+\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc.*
+\\s+stop only if x > 3.*" \
 "multiple pending breakpoints"
 
 
@@ -195,8 +196,10 @@ gdb_test "info break" \
 \[\t \]+stop only if k == 1.*
 \[\t \]+print k.*
 \[0-9\]+\[\t \]+breakpoint     keep y.* in main at .*$srcfile:$mainline.*
-\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc if x > 3.*
-\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp3_loc.*ignore next 2 hits.*" \
+\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc.*
+\\s+stop only if x > 3.*
+\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp3_loc.*
+\\s+ignore next 2 hits.*" \
 "multiple pending breakpoints 2"
 
 #
@@ -267,3 +270,17 @@ gdb_test "info break" \
 \[0-9\]+\[\t \]+breakpoint     keep y.* in main at .*$srcfile:$mainline.*
 \[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*imaginary.*" \
 "verify pending breakpoint after restart"
+
+# Test GDB's parsing of pending breakpoint thread and condition.
+
+gdb_test_no_output "set breakpoint pending on"
+gdb_test "break foo if (unknown_var && another_unknown_var) thread 1" \
+    "Breakpoint $decimal \\(foo\\) pending\\."
+set bpnum [get_integer_valueof "\$bpnum" "*INVALID" \
+	       "get number for foo breakpoint"]
+gdb_test "info breakpoints $bpnum" \
+    [multi_line \
+	 "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	 "\\s+stop only if \\(unknown_var && another_unknown_var\\)" \
+	 "\\s+stop only in thread 1"] \
+    "check pending breakpoint on foo"
diff --git a/gdb/testsuite/gdb.linespec/explicit.exp b/gdb/testsuite/gdb.linespec/explicit.exp
index 668002d9038..8cbefe204ec 100644
--- a/gdb/testsuite/gdb.linespec/explicit.exp
+++ b/gdb/testsuite/gdb.linespec/explicit.exp
@@ -575,7 +575,7 @@ namespace eval $testfile {
 	      allow-pending]} {
 	fail "set $tst"
     } else {
-	gdb_test "info break" ".*PENDING.*myfunction if foofoofoo == 1.*" $tst
+	gdb_test "info break" ".*PENDING.*myfunction\r\n\\s+stop only if foofoofoo == 1.*" $tst
     }
 
     gdb_exit
@@ -586,7 +586,7 @@ namespace eval $testfile {
 	      allow-pending]} {
 	fail "set $tst"
     } else {
-	gdb_test "info break" ".*PENDING.*myfunction if arg == 0" $tst
+	gdb_test "info break" ".*PENDING.*myfunction\r\n\\s+stop only if arg == 0" $tst
 
 	gdb_load [standard_output_file $exefile]
 	gdb_test "info break" \
diff --git a/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp b/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp
index 28f52938aeb..bb9987a5572 100644
--- a/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp
+++ b/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp
@@ -50,7 +50,8 @@ set bp_location1 [gdb_get_line_number "set breakpoint 1 here"]
 # Set pending dprintf via MI.
 set bp [mi_make_breakpoint_pending -number "1" -type "dprintf" \
 	    -disp "keep" -enabled "y" -pending "pendfunc1" \
-	    -original-location "pendfunc1"]
+	    -original-location "pendfunc1" \
+	    -script {\["printf \\\"hello\\\""\]}]
 mi_gdb_test "-dprintf-insert -f pendfunc1 \"hello\"" \
     ".*\\^done,$bp" "mi set dprintf"
 
diff --git a/gdb/testsuite/gdb.multi/inferior-specific-bp.exp b/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
index 1f6573268da..b8aceabcad6 100644
--- a/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
+++ b/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
@@ -51,9 +51,9 @@ if {![runto_main]} {
 # this should fail.  Try with the keywords in both orders just in case the
 # parser has a bug.
 gdb_test "break foo thread 1.1 inferior 1" \
-    "You can specify only one of inferior or thread\\."
+    "You can specify only one of thread, inferior, or task\\."
 gdb_test "break foo inferior 1 thread 1.1" \
-    "You can specify only one of inferior or thread\\."
+    "You can specify only one of thread, inferior, or task\\."
 
 # Try to create a breakpoint using the 'inferior' keyword multiple times.
 gdb_test "break foo inferior 1 inferior 2" \
diff --git a/gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c b/gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
new file mode 100644
index 00000000000..15d1b9833dd
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
@@ -0,0 +1,22 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+int global_var = 0;
+
+void
+foo (int arg)
+{
+  global_var = arg;
+}
diff --git a/gdb/testsuite/gdb.threads/del-pending-thread-bp.c b/gdb/testsuite/gdb.threads/del-pending-thread-bp.c
new file mode 100644
index 00000000000..938e05bc4d7
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/del-pending-thread-bp.c
@@ -0,0 +1,85 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#include <dlfcn.h>
+#include <pthread.h>
+#include <stdlib.h>
+
+pthread_barrier_t barrier;
+
+static void
+barrier_wait (pthread_barrier_t *b)
+{
+  int res = pthread_barrier_wait (b);
+  if (res != 0 && res != PTHREAD_BARRIER_SERIAL_THREAD)
+    abort ();
+}
+
+static void *
+thread_worker (void *arg)
+{
+  barrier_wait (&barrier);
+  return NULL;
+}
+
+void
+breakpt ()
+{
+  /* Nothing.  */
+}
+
+int
+main (void)
+{
+  void *handle;
+  void (*func)(int);
+  pthread_t thread;
+
+  if (pthread_barrier_init (&barrier, NULL, 2) != 0)
+    abort ();
+
+  if (pthread_create (&thread, NULL, thread_worker, NULL) != 0)
+    abort ();
+
+  breakpt ();
+
+  /* Allow the worker thread to complete.  */
+  barrier_wait (&barrier);
+
+  if (pthread_join (thread, NULL) != 0)
+    abort ();
+
+  breakpt ();
+
+  /* Now load the shared library.  */
+  handle = dlopen (SHLIB_NAME, RTLD_LAZY);
+  if (handle == NULL)
+    abort ();
+
+  /* Find the function symbol.  */
+  func = (void (*)(int)) dlsym (handle, "foo");
+
+  /* Call the library function.  */
+  func (1);
+
+  /* Unload the shared library.  */
+  if (dlclose (handle) != 0)
+    abort ();
+
+  breakpt ();
+
+  return 0;
+}
+
diff --git a/gdb/testsuite/gdb.threads/del-pending-thread-bp.exp b/gdb/testsuite/gdb.threads/del-pending-thread-bp.exp
new file mode 100644
index 00000000000..4ed05eaa42d
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/del-pending-thread-bp.exp
@@ -0,0 +1,108 @@
+# Copyright 2023 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+# This test checks that pending thread-specific breakpoints are
+# correctly deleted when the thread the breakpoint is for goes out of
+# scope.
+#
+# We also check that we can't create a pending thread-specific
+# breakpoint for a non-existent thread.
+
+require allow_shlib_tests
+
+standard_testfile
+
+set libname $testfile-lib
+set srcfile_lib $srcdir/$subdir/$libname.c
+set binfile_lib [standard_output_file $libname.so]
+
+if { [gdb_compile_shlib $srcfile_lib $binfile_lib {}] != "" } {
+    untested "failed to compile shared library 1"
+    return -1
+}
+
+set binfile_lib_target [gdb_download_shlib $binfile_lib]
+
+if { [prepare_for_testing "failed to prepare" $testfile $srcfile \
+	  [list debug \
+	       additional_flags=-DSHLIB_NAME=\"$binfile_lib_target\" \
+	       shlib_load pthreads]] } {
+    return -1
+}
+
+gdb_locate_shlib $binfile_lib
+
+if ![runto_main] {
+    return 0
+}
+
+# Run until we have two threads.
+gdb_breakpoint "breakpt"
+gdb_continue_to_breakpoint "first breakpt call"
+
+# Confirm that we have a thread '2'.
+gdb_test "info threads" "\r\n\\s+2\\s+\[^\r\n\]+"
+
+# Create a pending, thread-specific, breakpoint on 'foo'.
+gdb_breakpoint "foo thread 2" allow-pending
+set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+	       "get breakpoint number"]
+
+# Check we can't create a pending thread-specific breakpoint for a
+# non-existent thread.
+gdb_test "with breakpoint pending on -- break foo thread 99" \
+    "Unknown thread 99\\."
+
+# Continue to 'breakpt' again.  Don't use gdb_continue_to_breakpoint
+# as we are looking for the thread exited and breakpoint deleted
+# messages.
+set output [list "Continuing\\."]
+
+if {!([target_info exists gdb_protocol]
+      && ([target_info gdb_protocol] == "remote"
+	  || [target_info gdb_protocol] == "extended-remote"))} {
+    # Due to bug PR gdb/30129 we don't see the thread exited messages
+    # for remote targets.  When this bit of this test can be cleaned
+    # up.
+    lappend output "\\\[Thread \[^\r\n\]+ exited\\\]"
+}
+
+lappend output "Thread-specific breakpoint $bpnum deleted - thread 2 no longer in the thread list\\." \
+    "" \
+    "Thread 1 \[^\r\n\]+, breakpt \\(\\) at \[^\r\n\]+" \
+    "$decimal\\s+\[^\r\n\]+"
+
+gdb_test "continue" \
+    [multi_line {*}$output] \
+    "second breakpt call"
+
+# Confirm breakpoint has been deleted.
+gdb_test "info breakpoints $bpnum" \
+    "No breakpoint or watchpoint matching '$bpnum'\\."
+
+# Continue again.  This will pass through 'foo'.  We should not stop
+# in 'foo', the breakpoint has been deleted.  We should next stop in
+# breakpt again.
+gdb_test "continue" \
+    [multi_line \
+	 "Continuing\\." \
+	 "" \
+	 "Thread 1 \[^\r\n\]+ hit Breakpoint $decimal, breakpt \\(\\) at \[^\r\n\]+" \
+	 "$decimal\\s+\[^\r\n\]+"] \
+    "third breakpt call"
+gdb_test "bt 1" \
+    [multi_line \
+	 "#0\\s+breakpt \\(\\) at \[^\r\n\]+" \
+	 "\\(More stack frames follow\\.\\.\\.\\)"]
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv5 07/10] gdb: don't set breakpoint::pspace for in create_breakpoint
  2023-10-03 21:29       ` [PATCHv5 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
                           ` (5 preceding siblings ...)
  2023-10-03 21:29         ` [PATCHv5 06/10] gdb: parse pending breakpoint thread/task immediately Andrew Burgess
@ 2023-10-03 21:29         ` Andrew Burgess
  2023-10-03 21:29         ` [PATCHv5 08/10] gdb: remove breakpoint_re_set_one Andrew Burgess
                           ` (2 subsequent siblings)
  9 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-10-03 21:29 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Lancelot SIX

While working on the previous commit, I ran into this code within
create_breakpoint:

  if ((type_wanted != bp_breakpoint
      && type_wanted != bp_hardware_breakpoint) || thread != -1)
   b->pspace = current_program_space;

this code is only executed when creating a pending breakpoint, and
sets the breakpoint::pspace member variable.

The above code gained the 'thread != -1' clause with this commit:

  commit cc72b2a2da6d6372cbdb1d14639a5fce84e1a325
  Date:   Fri Dec 23 17:06:16 2011 +0000

              Introduce gdb.FinishBreakpoint in Python

While the type_wanted checks were added with this commit:

  commit f8eba3c61629b3c03ac1f33853eab4d8507adb9c
  Date:   Tue Dec 6 18:54:43 2011 +0000

      the "ambiguous linespec" series

Before this breakpoint::pspace was set unconditionally.

If we look at how breakpoint::pspace is used today, some breakpoint
types specifically set this field, either in their constructors, or in
a wrapper function that calls the constructor.  So, the watchpoint
type and its sub-class set this variable, as does the catchpoint type,
and all it's sub-classes.

However, code_breakpoint doesn't specifically set this field within
its constructor, though some sub-classes of
code_breakpoint (ada_catchpoint, exception_catchpoint,
internal_breakpoint, and momentary_breakpoint) do set this field.

When I examine all the places that breakpoint::pspace is used, I
believe that in every place where it is expected that this field is
set, the breakpoint type will be one that specifically sets this
field.

Next, I observe two problems with the existing code.

First, the above code is only hit for pending breakpoints, there's no
equivalent code for non-pending breakpoints.  This opens up the
possibility of GDB entering non-consistent states; if a breakpoint is
first created pending and then later gets a location, the pspace field
will be set, while if the breakpoint is immediately non-pending, then
the pspace field will never be set.

Second, if we look at how breakpoint::pspace is used in the function
breakpoint_program_space_exit, we see that when a program space is
removed, any breakpoint with breakpoint::pspace set to the removed
program space, will be deleted.  This makes sense, but does mean we
need to ensure breakpoint::pspace is only set for breakpoints that
apply to a single program space.

So, if I create pending dprintf breakpoint (type bp_dprintf) then the
breakpoint::pspace variable will be set even though the dprintf is not
really tied to that one program space.  As a result, when the matching
program space is removed the dprintf is incorrectly removed.

Also, if I create a thread specific breakpoint, then, thanks to the
'thread != -1' clause the wrong program space will be stored in
breakpoint::pspace (the current program space is always used, which
might not be the program space that corresponds to the selected
thread), as a result, the thread specific breakpoint will be deleted
when the matching program space is removed.

If we look at commit cc72b2a2da6d which added the 'thread != -1'
clause, we can see this change was entirely redundant, the
breakpoint::pspace is also set in bpfinishpy_init after
create_breakpoint has been called.  As such, I think we can safely
drop the 'thread != -1' clause.

For the other problems, I'm proposing to be pretty aggressive - I'd
like to drop the breakpoint::pspace assignment completely from
create_breakpoint.  Having looked at how this variable is used, I
believe that it is already set elsewhere in all the cases that it is
needed.  Maybe this code was needed at one time, but I can't see how
it's needed any more.

There's tests to expose the issues I've spotted with this code, and
there's no regressions in testing.
---
 gdb/breakpoint.c                              |   3 -
 gdb/breakpoint.h                              |  18 +-
 .../gdb.multi/pending-bp-del-inferior.c       |  28 +++
 .../gdb.multi/pending-bp-del-inferior.exp     | 216 ++++++++++++++++++
 4 files changed, 259 insertions(+), 6 deletions(-)
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-del-inferior.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index d880844f07b..0a88f89898f 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -9211,9 +9211,6 @@ create_breakpoint (struct gdbarch *gdbarch,
       b->disposition = tempflag ? disp_del : disp_donttouch;
       b->condition_not_parsed = 1;
       b->enable_state = enabled ? bp_enabled : bp_disabled;
-      if ((type_wanted != bp_breakpoint
-	   && type_wanted != bp_hardware_breakpoint) || thread != -1)
-	b->pspace = current_program_space;
 
       if (b->type == bp_dprintf)
 	update_dprintf_command_list (b.get ());
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index baa54573e1a..b37208271e4 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -823,9 +823,21 @@ struct breakpoint : public intrusive_list_node<breakpoint>
      equals this.  */
   struct frame_id frame_id = null_frame_id;
 
-  /* The program space used to set the breakpoint.  This is only set
-     for breakpoints which are specific to a program space; for
-     non-thread-specific ordinary breakpoints this is NULL.  */
+  /* The program space used to set the breakpoint.  This is only set for
+     breakpoints that are not type bp_breakpoint or bp_hardware_breakpoint.
+     For thread or inferior specific breakpoints, the breakpoints are
+     managed via the thread and inferior member variables.  */
+
+  /* If not nullptr then this is the program space for which this
+     breakpoint was created.  All watchpoint and catchpoint sub-types set
+     this field, but not all of the code_breakpoint sub-types do;
+     generally, user created breakpoint types don't set this field, though
+     things might be more consistent if they did.
+
+     When this variable is nullptr then a breakpoint might be associated
+     with multiple program spaces, though you need to check the thread,
+     inferior and task variables to see if a breakpoint was created for a
+     specific thread, inferior, or Ada task respectively.  */
   program_space *pspace = NULL;
 
   /* The location specification we used to set the breakpoint.  */
diff --git a/gdb/testsuite/gdb.multi/pending-bp-del-inferior.c b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.c
new file mode 100644
index 00000000000..51b6492085f
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.c
@@ -0,0 +1,28 @@
+/* This testcase is part of GDB, the GNU debugger.
+
+   Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+int
+foo ()
+{
+  return 0;
+}
+
+int
+main ()
+{
+  return foo ();
+}
diff --git a/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
new file mode 100644
index 00000000000..cb1f119ff94
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
@@ -0,0 +1,216 @@
+# Copyright 2023 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+# Setup two inferiors.  Select one inferior and create a pending
+# thread specific breakpoint in the other inferior.
+#
+# Delete the selected inferior (the one for which the thread specific
+# breakpoint doesn't apply), and check that the breakpoint still exists.
+#
+# Repeat this process, but this time, create an inferior specific
+# breakpoint.
+
+# The plain remote target can't do multiple inferiors.
+require !use_gdb_stub
+
+standard_testfile
+
+if {[prepare_for_testing "failed to prepare" $testfile $srcfile]} {
+    return -1
+}
+
+# Setup for the tests.  Create two inferiors, both running the global
+# BINFILE, and proceed to main in both inferiors.  Delete all
+# breakpoints, and check that we do have two threads.
+#
+# Return true after a successful setup, otherwise, return false.
+proc test_setup {} {
+    clean_restart $::binfile
+
+    if {![runto_main]} {
+	return 0
+    }
+
+    gdb_test "add-inferior -exec ${::binfile}" "Added inferior 2.*" \
+	"add inferior 2"
+    gdb_test "inferior 2" "Switching to inferior 2 .*" \
+	"select inferior 2"
+
+    if {![runto_main]} {
+	return 0
+    }
+
+    delete_breakpoints
+
+    gdb_test "info threads" \
+	[multi_line \
+	     "  Id\\s+Target Id\\s+Frame\\s*" \
+	     "  1\\.1\\s+\[^\r\n\]+" \
+	     "\\* 2\\.1\\s+\[^\r\n\]+"] \
+	"check we have the expected threads"
+
+    return 1
+}
+
+# Assuming inferior 2 is already selected, kill the current inferior
+# (inferior 2), selected inferior 1, and then remove inferior 2.
+proc kill_and_remove_inferior_2 {} {
+    gdb_test "kill" "" "kill inferior 2" \
+	"Kill the program being debugged.*y or n. $" "y"
+
+    gdb_test "inferior 1" "Switching to inferior 1 .*" \
+	"select inferior 1"
+
+    gdb_test_no_output "remove-inferiors 2"
+}
+
+# Setup two inferiors, then created a breakpoint.  If BP_PENDING is
+# true then the breakpoint will be pending, otherwise, the breakpoint
+# will be non-pending.
+#
+# BP_TYPE is either 'thread' or 'inferior', and indicates if the
+# created breakpoint should be thread or inferior specific.
+#
+# The breakpoint is created while inferior 2 is selected, and the
+# thread/inferior restriction always identifies inferior 1.
+#
+# Then inferior 2 is killed and removed.
+#
+# Finally, check that the breakpoint still exists and correctly refers
+# to inferior 1.
+proc do_bp_test { bp_type bp_pending } {
+    if {![test_setup]} {
+	return
+    }
+
+    if { $bp_pending } {
+	set bp_func "bar"
+    } else {
+	set bp_func "foo"
+    }
+
+    if { $bp_type eq "thread" } {
+	set bp_restriction "thread 1.1"
+    } else {
+	set bp_restriction "inferior 1"
+    }
+
+    gdb_breakpoint "$bp_func $bp_restriction" allow-pending
+    set bp_number [get_integer_valueof "\$bpnum" "INVALID" \
+		       "get b/p number for previous breakpoint"]
+
+    if { $bp_restriction eq "thread 1.1" } {
+	set bp_after_restriction "thread 1"
+    } else {
+	set bp_after_restriction $bp_restriction
+    }
+
+    if { $bp_pending } {
+	set bp_pattern_before \
+	    [multi_line \
+		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+${bp_func}" \
+		 "\\s+stop only in [string_to_regexp $bp_restriction]"]
+	set bp_pattern_after \
+	    [multi_line \
+		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+${bp_func}" \
+		 "\\s+stop only in [string_to_regexp $bp_after_restriction]"]
+    } else {
+	set bp_pattern_before \
+	    [multi_line \
+		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+<MULTIPLE>\\s*" \
+		 "\\s+stop only in [string_to_regexp $bp_restriction]" \
+		 "$bp_number\\.1\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 1" \
+		 "$bp_number\\.2\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 2"]
+
+	set bp_pattern_after \
+	    [multi_line \
+		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+" \
+		 "\\s+stop only in [string_to_regexp $bp_after_restriction]"]
+    }
+
+    gdb_test "info breakpoints" $bp_pattern_before \
+	"info breakpoints before inferior removal"
+
+    kill_and_remove_inferior_2
+
+    gdb_test "info breakpoints" $bp_pattern_after \
+	"info breakpoints after inferior removal"
+}
+
+# Setup two inferiors, then created a dprintf.  If BP_PENDING is
+# true then the dprintf will be pending, otherwise, the dprintf
+# will be non-pending.
+#
+# The dprintf is created while inferior 2.  Then inferior 2 is killed
+# and removed.
+#
+# Finally, check that the dprintf still exists.
+proc do_dprintf_test { bp_pending } {
+    if {![test_setup]} {
+	return
+    }
+
+    if { $bp_pending } {
+	set bp_func "bar"
+
+	gdb_test "dprintf $bp_func,\"in $bp_func\"" ".*" \
+	    "create dprintf breakpoint" \
+	    "Make dprintf pending on future shared library load\\? \\(y or .n.\\) $" "y"
+    } else {
+	set bp_func "foo"
+
+	gdb_test "dprintf $bp_func,\"in $bp_func\"" ".*" \
+	    "create dprintf breakpoint"
+    }
+
+    set bp_number [get_integer_valueof "\$bpnum" "INVALID" \
+		       "get b/p number for previous breakpoint"]
+
+    if { $bp_pending } {
+	set bp_pattern_before \
+	    [multi_line \
+		 "$bp_number\\s+dprintf\\s+keep\\s+y\\s+<PENDING>\\s+${bp_func}" \
+		 "\\s+printf \"in $bp_func\""]
+	set bp_pattern_after $bp_pattern_before
+    } else {
+	set bp_pattern_before \
+	    [multi_line \
+		 "$bp_number\\s+dprintf\\s+keep\\s+y\\s+<MULTIPLE>\\s*" \
+		 "\\s+printf \"in $bp_func\"" \
+		 "$bp_number\\.1\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 1" \
+		 "$bp_number\\.2\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 2"]
+
+	set bp_pattern_after \
+	    [multi_line \
+		 "$bp_number\\s+dprintf\\s+keep\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+" \
+		 "\\s+printf \"in $bp_func\""]
+    }
+
+    gdb_test "info breakpoints" $bp_pattern_before \
+	"info breakpoints before inferior removal"
+
+    kill_and_remove_inferior_2
+
+    gdb_test "info breakpoints" $bp_pattern_after \
+	"info breakpoints after inferior removal"
+}
+
+foreach_with_prefix bp_pending { true false } {
+    foreach_with_prefix bp_type { thread inferior } {
+	do_bp_test $bp_type $bp_pending
+    }
+
+    do_dprintf_test $bp_pending
+}
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv5 08/10] gdb: remove breakpoint_re_set_one
  2023-10-03 21:29       ` [PATCHv5 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
                           ` (6 preceding siblings ...)
  2023-10-03 21:29         ` [PATCHv5 07/10] gdb: don't set breakpoint::pspace for in create_breakpoint Andrew Burgess
@ 2023-10-03 21:29         ` Andrew Burgess
  2023-10-03 21:29         ` [PATCHv5 09/10] gdb: remove tracepoint_probe_create_sals_from_location_spec Andrew Burgess
  2023-12-02 10:42         ` [PATCHv6 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
  9 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-10-03 21:29 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Lancelot SIX

During a later patch I wanted to reset a single breakpoint, so I
called breakpoint_re_set_one.  However, this is not the right thing to
do.  If we look at breakpoint_re_set then we see that there's a whole
bunch of state that needs to be preserved prior to calling
breakpoint_re_set_one, and after calling breakpoint_re_set_one we
still need to call update_global_location_list.

I could just update the comment on breakpoint_re_set_one to make it
clearer how the function should be used -- or more likely to warn that
the function should only be used as a helper from breakpoint_re_set.

However, breakpoint_re_set_one is only 3 lines long.  So I figure it
might actually be easier to just fold breakpoint_re_set_one into
breakpoint_re_set, then there's no risk of accidentally calling
breakpoint_re_set_one when we shouldn't.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c | 26 ++++++++------------------
 1 file changed, 8 insertions(+), 18 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 0a88f89898f..fcd0dfd9c20 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -13018,17 +13018,6 @@ create_sals_from_location_spec_default (location_spec *locspec,
   parse_breakpoint_sals (locspec, canonical);
 }
 
-/* Reset a breakpoint.  */
-
-static void
-breakpoint_re_set_one (breakpoint *b)
-{
-  input_radix = b->input_radix;
-  set_language (b->language);
-
-  b->re_set ();
-}
-
 /* Re-set breakpoint locations for the current program space.
    Locations bound to other program spaces are left untouched.  */
 
@@ -13040,12 +13029,11 @@ breakpoint_re_set (void)
     scoped_restore save_input_radix = make_scoped_restore (&input_radix);
     scoped_restore_current_pspace_and_thread restore_pspace_thread;
 
-    /* breakpoint_re_set_one sets the current_language to the language
-       of the breakpoint it is resetting (see prepare_re_set_context)
-       before re-evaluating the breakpoint's location.  This change can
-       unfortunately get undone by accident if the language_mode is set
-       to auto, and we either switch frames, or more likely in this context,
-       we select the current frame.
+    /* To ::re_set each breakpoint we set the current_language to the
+       language of the breakpoint before re-evaluating the breakpoint's
+       location.  This change can unfortunately get undone by accident if
+       the language_mode is set to auto, and we either switch frames, or
+       more likely in this context, we select the current frame.
 
        We prevent this by temporarily turning the language_mode to
        language_mode_manual.  We restore it once all breakpoints
@@ -13062,7 +13050,9 @@ breakpoint_re_set (void)
       {
 	try
 	  {
-	    breakpoint_re_set_one (&b);
+	    input_radix = b.input_radix;
+	    set_language (b.language);
+	    b.re_set ();
 	  }
 	catch (const gdb_exception &ex)
 	  {
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv5 09/10] gdb: remove tracepoint_probe_create_sals_from_location_spec
  2023-10-03 21:29       ` [PATCHv5 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
                           ` (7 preceding siblings ...)
  2023-10-03 21:29         ` [PATCHv5 08/10] gdb: remove breakpoint_re_set_one Andrew Burgess
@ 2023-10-03 21:29         ` Andrew Burgess
  2023-12-02 10:42         ` [PATCHv6 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
  9 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-10-03 21:29 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Lancelot SIX

The tracepoint_probe_create_sals_from_location_spec function just
forwards all its arguments to
bkpt_probe_create_sals_from_location_spec, and is only used in one
place.

Lets delete tracepoint_probe_create_sals_from_location_spec and
replace it with bkpt_probe_create_sals_from_location_spec.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c | 19 +++----------------
 1 file changed, 3 insertions(+), 16 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index fcd0dfd9c20..e0464e1f173 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -284,9 +284,6 @@ static bool strace_marker_p (struct breakpoint *b);
 static void bkpt_probe_create_sals_from_location_spec
      (location_spec *locspec,
       struct linespec_result *canonical);
-static void tracepoint_probe_create_sals_from_location_spec
-     (location_spec *locspec,
-      struct linespec_result *canonical);
 
 const struct breakpoint_ops code_breakpoint_ops =
 {
@@ -301,10 +298,11 @@ static const struct breakpoint_ops bkpt_probe_breakpoint_ops =
   create_breakpoints_sal,
 };
 
-/* Tracepoints set on probes.  */
+/* Tracepoints set on probes.  We use the same methods as for breakpoints
+   on probes.  */
 static const struct breakpoint_ops tracepoint_probe_breakpoint_ops =
 {
-  tracepoint_probe_create_sals_from_location_spec,
+  bkpt_probe_create_sals_from_location_spec,
   create_breakpoints_sal,
 };
 
@@ -12224,17 +12222,6 @@ tracepoint::print_recreate (struct ui_file *fp) const
     gdb_printf (fp, "  passcount %d\n", pass_count);
 }
 
-/* Virtual table for tracepoints on static probes.  */
-
-static void
-tracepoint_probe_create_sals_from_location_spec
-  (location_spec *locspec,
-   struct linespec_result *canonical)
-{
-  /* We use the same method for breakpoint on probes.  */
-  bkpt_probe_create_sals_from_location_spec (locspec, canonical);
-}
-
 void
 dprintf_breakpoint::re_set ()
 {
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv6 00/10] thread-specific breakpoints in just some inferiors
  2023-10-03 21:29       ` [PATCHv5 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
                           ` (8 preceding siblings ...)
  2023-10-03 21:29         ` [PATCHv5 09/10] gdb: remove tracepoint_probe_create_sals_from_location_spec Andrew Burgess
@ 2023-12-02 10:42         ` Andrew Burgess
  2023-12-02 10:42           ` [PATCHv6 01/10] gdb: create_breakpoint: add asserts and additional comments Andrew Burgess
                             ` (10 more replies)
  9 siblings, 11 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-12-02 10:42 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

In v6:

  - Rebased to current master, one minor fix due to the C++17 changes,
    nothing major.  Retested.

In v5:

  - Updates after Lancelot's feedback, including, -force-condition can
    no longer be abbreviated to '-', and can't be used immediately
    after the breakpoint condition.

  - More tests to check some of the edge cases.

In v4:

  - Big update, this series now handles thread-specific and
    inferior-specific breakpoints.

In v3:

  - Rebased on to current upstream/master, this includes all Simon's
    recent breakpoint changes.  Retested with no regressions seen.

In v2:

  - Rebased on current upstream/master and retested,

  - No changes to code or docs.

---

Andrew Burgess (10):
  gdb: create_breakpoint: add asserts and additional comments
  gdb: create_breakpoint: asserts relating to extra_string/parse_extra
  gdb: change 'if' to gdb_assert in update_dprintf_command_list
  gdb: build dprintf commands just once in code_breakpoint constructor
  gdb: don't display inferior list for pending breakpoints
  gdb: parse pending breakpoint thread/task immediately
  gdb: don't set breakpoint::pspace for in create_breakpoint
  gdb: remove breakpoint_re_set_one
  gdb: remove tracepoint_probe_create_sals_from_location_spec
  gdb: only insert thread-specific breakpoints in the relevant inferior

 gdb/Makefile.in                               |   2 +
 gdb/NEWS                                      |  11 +
 gdb/ada-lang.c                                |   6 +-
 gdb/break-catch-throw.c                       |   6 +-
 gdb/break-cond-parse.c                        | 463 +++++++++++
 gdb/break-cond-parse.h                        |  49 ++
 gdb/breakpoint.c                              | 757 +++++++++---------
 gdb/breakpoint.h                              | 101 ++-
 gdb/testsuite/gdb.ada/tasks.exp               |   6 +-
 gdb/testsuite/gdb.base/condbreak.exp          |  57 +-
 gdb/testsuite/gdb.base/pending.exp            |  23 +-
 gdb/testsuite/gdb.linespec/explicit.exp       |   4 +-
 gdb/testsuite/gdb.mi/mi-dprintf-pending.exp   |   3 +-
 gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp    |   8 +-
 .../gdb.mi/user-selected-context-sync.exp     |   4 +-
 .../gdb.multi/bp-thread-specific.exp          |   7 +-
 .../gdb.multi/inferior-specific-bp.exp        |  16 +-
 .../gdb.multi/multi-target-continue.exp       |   2 +-
 .../gdb.multi/multi-target-ping-pong-next.exp |   4 +-
 .../gdb.multi/pending-bp-del-inferior.c       |  28 +
 .../gdb.multi/pending-bp-del-inferior.exp     | 214 +++++
 gdb/testsuite/gdb.multi/pending-bp-lib.c      |  22 +
 gdb/testsuite/gdb.multi/pending-bp.c          |  66 ++
 gdb/testsuite/gdb.multi/pending-bp.exp        | 336 ++++++++
 gdb/testsuite/gdb.multi/tids.exp              |   6 +-
 .../gdb.threads/del-pending-thread-bp-lib.c   |  22 +
 .../gdb.threads/del-pending-thread-bp.c       |  85 ++
 .../gdb.threads/del-pending-thread-bp.exp     | 108 +++
 28 files changed, 1947 insertions(+), 469 deletions(-)
 create mode 100644 gdb/break-cond-parse.c
 create mode 100644 gdb/break-cond-parse.h
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-del-inferior.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.exp
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.exp


base-commit: a393b155174d20d3d120b5012b87c5438ab9e3d4
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv6 01/10] gdb: create_breakpoint: add asserts and additional comments
  2023-12-02 10:42         ` [PATCHv6 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
@ 2023-12-02 10:42           ` Andrew Burgess
  2023-12-04 19:21             ` Aktemur, Tankut Baris
  2023-12-02 10:42           ` [PATCHv6 02/10] gdb: create_breakpoint: asserts relating to extra_string/parse_extra Andrew Burgess
                             ` (9 subsequent siblings)
  10 siblings, 1 reply; 138+ messages in thread
From: Andrew Burgess @ 2023-12-02 10:42 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

This commit extends the asserts on create_breakpoint (in the header
file), and adds some additional assertions into the definition.

The new assert confirms that when the thread and inferior information
is going to be parsed from the extra_string, then the thread and
inferior arguments should be -1.  That is, the caller of
create_breakpoint should not try to create a thread/inferior specific
breakpoint by *both* specifying thread/inferior *and* asking to parse
the extra_string, it's one or the other.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c |  6 ++++++
 gdb/breakpoint.h | 16 ++++++++++++++++
 2 files changed, 22 insertions(+)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 699919e32b3..dd415ff42f0 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -9228,6 +9228,12 @@ create_breakpoint (struct gdbarch *gdbarch,
   gdb_assert (inferior == -1 || inferior > 0);
   gdb_assert (thread == -1 || inferior == -1);
 
+  /* If PARSE_EXTRA is true then the thread and inferior details will be
+     parsed from  the EXTRA_STRING, the THREAD and INFERIOR arguments
+     should be -1.  */
+  gdb_assert (!parse_extra || thread == -1);
+  gdb_assert (!parse_extra || inferior == -1);
+
   gdb_assert (ops != NULL);
 
   /* If extra_string isn't useful, set it to NULL.  */
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index feb798224c0..4abf6d0762c 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -1600,6 +1600,22 @@ enum breakpoint_create_flags
    the FORCE_CONDITION parameter is ignored and the corresponding argument
    is parsed from EXTRA_STRING.
 
+   The THREAD should be a global thread number, the created breakpoint will
+   only apply for that thread.  If the breakpoint should apply for all
+   threads then pass -1.  However, if PARSE_EXTRA is non-zero then the
+   THREAD parameter is ignored and an optional thread number will be parsed
+   from EXTRA_STRING.
+
+   The INFERIOR should be a global inferior number, the created breakpoint
+   will only apply for that inferior.  If the breakpoint should apply for
+   all inferiors then pass -1.  However, if PARSE_EXTRA is non-zero then
+   the INFERIOR parameter is ignored and an optional inferior number will
+   be parsed from EXTRA_STRING.
+
+   At most one of THREAD and INFERIOR should be set to a value other than
+   -1; breakpoints can be thread specific, or inferior specific, but not
+   both.
+
    If INTERNAL is non-zero, the breakpoint number will be allocated
    from the internal breakpoint count.
 
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv6 02/10] gdb: create_breakpoint: asserts relating to extra_string/parse_extra
  2023-12-02 10:42         ` [PATCHv6 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
  2023-12-02 10:42           ` [PATCHv6 01/10] gdb: create_breakpoint: add asserts and additional comments Andrew Burgess
@ 2023-12-02 10:42           ` Andrew Burgess
  2023-12-04 19:40             ` Aktemur, Tankut Baris
  2023-12-02 10:42           ` [PATCHv6 03/10] gdb: change 'if' to gdb_assert in update_dprintf_command_list Andrew Burgess
                             ` (8 subsequent siblings)
  10 siblings, 1 reply; 138+ messages in thread
From: Andrew Burgess @ 2023-12-02 10:42 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

The goal of this commit is to better define the API for
create_breakpoint especially around the use of extra_string and
parse_extra.  This will be useful in the next commit when I plan to
make some changes to create_breakpoint.

This commit makes one possibly breaking change: until this commit it
was possible to create thread-specific dprintf breakpoint like this:

  (gdb) dprintf call_me, thread 1 "%s", "hello"
  Dprintf 2 at 0x401152: file /tmp/hello.c, line 8.
  (gdb) info breakpoints
  Num     Type           Disp Enb Address            What
  2       dprintf        keep y   0x0000000000401152 in call_me at /tmp/hello.c:8 thread 1
          stop only in thread 1
          printf "%s", "hello"
  (gdb)

this feature of dprintf was not documented, was not tested, and is
slightly different in syntax to how we create thread specific
breakpoints and/or watchpoints -- the thread condition appears after
the first ','.

I believe that this worked at all was simply by luck.  We happen to
pass the parse_extra flag as true from dprintf_command to
create_breakpoint.

So in this commit I made the choice change this.  We now pass
parse_extra as false from dprintf_command to create_breakpoint.  With
this done it is assumed that the only thing in the extra_string is the
dprintf format and arguments.

Beyond this change I've updated the comment on create_breakpoint in
breakpoint.h, and I've then added some asserts into
create_breakpoint as well as moving around some of the error
handling.

 - We now assert on the incoming argument values,

 - I've moved an error check to sit after the call to
   find_condition_and_thread_for_sals, this ensures the extra_string
   was parsed correctly,

In dprintf_command:

 - We now throw an error if there is no format string after the
   dprintf location.  This error was already being thrown, but was
   being caught later in the process.  With this change we catch the
   missing string earlier,

 - And, as mentioned earlier, we pass parse_extra as false when
   calling create_breakpoint,

In create_tracepoint_from_upload:

 - We now throw an error if the parsed location doesn't completely
   consume the addr_str variable.  This error has now effectively
   moved out of create_breakpoint.
---
 gdb/breakpoint.c | 42 +++++++++++++++++++++++++++++-------------
 gdb/breakpoint.h | 44 +++++++++++++++++++++++++++-----------------
 2 files changed, 56 insertions(+), 30 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index dd415ff42f0..bd28236ce7d 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -9240,6 +9240,17 @@ create_breakpoint (struct gdbarch *gdbarch,
   if (extra_string != NULL && *extra_string == '\0')
     extra_string = NULL;
 
+  /* A bp_dprintf must always have an accompanying EXTRA_STRING containing
+     the dprintf format and arguments -- PARSE_EXTRA should always be false
+     in this case.
+
+     For all other breakpoint types, EXTRA_STRING should be nullptr unless
+     PARSE_EXTRA is true.  */
+  gdb_assert ((type_wanted == bp_dprintf
+	       && extra_string != nullptr && !parse_extra)
+	      || (type_wanted != bp_dprintf
+		  && (extra_string == nullptr || parse_extra)));
+
   try
     {
       ops->create_sals_from_location_spec (locspec, &canonical);
@@ -9303,6 +9314,8 @@ create_breakpoint (struct gdbarch *gdbarch,
 
       if (parse_extra)
 	{
+	  gdb_assert (type_wanted != bp_dprintf);
+
 	  gdb::unique_xmalloc_ptr<char> rest;
 	  gdb::unique_xmalloc_ptr<char> cond;
 
@@ -9311,15 +9324,15 @@ create_breakpoint (struct gdbarch *gdbarch,
 	  find_condition_and_thread_for_sals (lsal.sals, extra_string,
 					      &cond, &thread, &inferior,
 					      &task, &rest);
+
+	  if (rest.get () != nullptr && *(rest.get ()) != '\0')
+	    error (_("Garbage '%s' at end of command"), rest.get ());
+
 	  cond_string_copy = std::move (cond);
 	  extra_string_copy = std::move (rest);
 	}
       else
 	{
-	  if (type_wanted != bp_dprintf
-	      && extra_string != NULL && *extra_string != '\0')
-		error (_("Garbage '%s' at end of location"), extra_string);
-
 	  /* Check the validity of the condition.  We should error out
 	     if the condition is invalid at all of the locations and
 	     if it is not forced.  In the PARSE_EXTRA case above, this
@@ -9530,21 +9543,18 @@ dprintf_command (const char *arg, int from_tty)
 
   /* If non-NULL, ARG should have been advanced past the location;
      the next character must be ','.  */
-  if (arg != NULL)
+  if (arg == nullptr || arg[0] != ',' || arg[1] == '\0')
+    error (_("Format string required"));
+  else
     {
-      if (arg[0] != ',' || arg[1] == '\0')
-	error (_("Format string required"));
-      else
-	{
-	  /* Skip the comma.  */
-	  ++arg;
-	}
+      /* Skip the comma.  */
+      ++arg;
     }
 
   create_breakpoint (get_current_arch (),
 		     locspec.get (),
 		     NULL, -1, -1,
-		     arg, false, 1 /* parse arg */,
+		     arg, false, 0 /* parse arg */,
 		     0, bp_dprintf,
 		     0 /* Ignore count */,
 		     pending_break_support,
@@ -14149,6 +14159,12 @@ create_tracepoint_from_upload (struct uploaded_tp *utp)
 
   location_spec_up locspec = string_to_location_spec (&addr_str,
 						      current_language);
+
+
+  gdb_assert (addr_str != nullptr);
+  if (*addr_str != '\0')
+    error (_("Garbage '%s' at end of location"), addr_str);
+
   if (!create_breakpoint (get_current_arch (),
 			  locspec.get (),
 			  utp->cond_string.get (), -1, -1, addr_str,
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index 4abf6d0762c..95f98b59e41 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -1585,32 +1585,42 @@ enum breakpoint_create_flags
    functions for setting a breakpoint at LOCSPEC.
 
    This function has two major modes of operations, selected by the
-   PARSE_EXTRA parameter.
+   PARSE_EXTRA and WANTED_TYPE parameters.
 
-   If PARSE_EXTRA is zero, LOCSPEC is just the breakpoint's location
-   spec, with condition, thread, and extra string specified by the
-   COND_STRING, THREAD, and EXTRA_STRING parameters.
+   When WANTED_TYPE is not bp_dprintf the following rules apply:
 
-   If PARSE_EXTRA is non-zero, this function will attempt to extract
-   the condition, thread, and extra string from EXTRA_STRING, ignoring
-   the similarly named parameters.
+     If PARSE_EXTRA is zero, LOCSPEC is just the breakpoint's location
+     spec, with condition, thread, and extra string specified by the
+     COND_STRING, THREAD, and EXTRA_STRING parameters.
 
-   If FORCE_CONDITION is true, the condition is accepted even when it is
-   invalid at all of the locations.  However, if PARSE_EXTRA is non-zero,
-   the FORCE_CONDITION parameter is ignored and the corresponding argument
-   is parsed from EXTRA_STRING.
+     If PARSE_EXTRA is non-zero, this function will attempt to extract the
+     condition, thread, and extra string from EXTRA_STRING, ignoring the
+     similarly named parameters.
+
+   When WANTED_TYPE is bp_dprintf the following rules apply:
+
+     PARSE_EXTRA must always be zero, LOCSPEC is just the breakpoint's
+     location spec, with condition, thread, and extra string (which
+     contains the dprintf format and arguments) specified by the
+     COND_STRING, THREAD, and EXTRA_STRING parameters.
+
+   If FORCE_CONDITION is true, the condition (in COND_STRING) is accepted
+   even when it is invalid at all of the locations.  However, if
+   PARSE_EXTRA is non-zero and WANTED_TYPE is not bp_dprintf, the
+   FORCE_CONDITION parameter is ignored and the corresponding argument is
+   parsed from EXTRA_STRING.
 
    The THREAD should be a global thread number, the created breakpoint will
    only apply for that thread.  If the breakpoint should apply for all
-   threads then pass -1.  However, if PARSE_EXTRA is non-zero then the
-   THREAD parameter is ignored and an optional thread number will be parsed
-   from EXTRA_STRING.
+   threads then pass -1.  However, if PARSE_EXTRA is non-zero and
+   WANTED_TYPE is not bp_dprintf, then the THREAD parameter is ignored and
+   an optional thread number will be parsed from EXTRA_STRING.
 
    The INFERIOR should be a global inferior number, the created breakpoint
    will only apply for that inferior.  If the breakpoint should apply for
-   all inferiors then pass -1.  However, if PARSE_EXTRA is non-zero then
-   the INFERIOR parameter is ignored and an optional inferior number will
-   be parsed from EXTRA_STRING.
+   all inferiors then pass -1.  However, if PARSE_EXTRA is non-zero and
+   WANTED_TYPE is not bp_dprintf, then the INFERIOR parameter is ignored
+   and an optional inferior number will be parsed from EXTRA_STRING.
 
    At most one of THREAD and INFERIOR should be set to a value other than
    -1; breakpoints can be thread specific, or inferior specific, but not
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv6 03/10] gdb: change 'if' to gdb_assert in update_dprintf_command_list
  2023-12-02 10:42         ` [PATCHv6 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
  2023-12-02 10:42           ` [PATCHv6 01/10] gdb: create_breakpoint: add asserts and additional comments Andrew Burgess
  2023-12-02 10:42           ` [PATCHv6 02/10] gdb: create_breakpoint: asserts relating to extra_string/parse_extra Andrew Burgess
@ 2023-12-02 10:42           ` Andrew Burgess
  2023-12-02 10:42           ` [PATCHv6 04/10] gdb: build dprintf commands just once in code_breakpoint constructor Andrew Burgess
                             ` (7 subsequent siblings)
  10 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-12-02 10:42 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

I noticed in update_dprintf_command_list that we handle the case where
the bp_dprintf style breakpoint doesn't have a format and args string.

However, I don't believe such a situation is possible.  The obvious
approach certainly already catches this case:

  (gdb) dprintf main
  Format string required

If it is possible to create a dprintf breakpoint without a format and
args string then I think we should be catching this case and handling
it at creation time, rather than having GDB just ignore the situation
later on.

And so, I propose that we change the 'if' that ignores the case where
the format/args string is empty, and instead assert that we do always
have a format/args string.  The original code, that handled an empty
format/args string has existed since commit e7e0cddfb0d4, which is
when dprintf support was added to GDB.

If I'm correct and this situation can't ever happen then there should
be no user visible changes after this commit.
---
 gdb/breakpoint.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index bd28236ce7d..c629d27c4c0 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -8538,8 +8538,9 @@ update_dprintf_command_list (struct breakpoint *b)
   const char *dprintf_args = b->extra_string.get ();
   gdb::unique_xmalloc_ptr<char> printf_line = nullptr;
 
-  if (!dprintf_args)
-    return;
+  /* Trying to create a dprintf breakpoint without a format and args
+     string should be detected at creation time.  */
+  gdb_assert (dprintf_args != nullptr);
 
   dprintf_args = skip_spaces (dprintf_args);
 
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv6 04/10] gdb: build dprintf commands just once in code_breakpoint constructor
  2023-12-02 10:42         ` [PATCHv6 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
                             ` (2 preceding siblings ...)
  2023-12-02 10:42           ` [PATCHv6 03/10] gdb: change 'if' to gdb_assert in update_dprintf_command_list Andrew Burgess
@ 2023-12-02 10:42           ` Andrew Burgess
  2023-12-05  8:17             ` Aktemur, Tankut Baris
  2023-12-02 10:42           ` [PATCHv6 05/10] gdb: don't display inferior list for pending breakpoints Andrew Burgess
                             ` (6 subsequent siblings)
  10 siblings, 1 reply; 138+ messages in thread
From: Andrew Burgess @ 2023-12-02 10:42 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

I noticed in code_breakpoint::code_breakpoint that we are calling
update_dprintf_command_list once for each breakpoint location, when we
really only need to call this once per breakpoint -- the data updated
by this function, the breakpoint command list -- is per breakpoint,
not per breakpoint location.  Calling update_dprintf_command_list
multiple times is just wasted effort, there's no per location error
checking, we don't even pass the current location to the function.

This commit moves the update_dprintf_command_list call outside of the
per-location loop. I have also changes the 'if' that handles the case
where the extra_string (which holds the format/args) is empty.  I
don't believe that this situation can ever arise -- and if it does we
should be catching it earlier and throwing an error at that point.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c | 20 +++++++++-----------
 1 file changed, 9 insertions(+), 11 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index c629d27c4c0..c1440a6921f 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -8704,19 +8704,17 @@ code_breakpoint::code_breakpoint (struct gdbarch *gdbarch_,
       /* Do not set breakpoint locations conditions yet.  As locations
 	 are inserted, they get sorted based on their addresses.  Let
 	 the list stabilize to have reliable location numbers.  */
+    }
 
-      /* Dynamic printf requires and uses additional arguments on the
-	 command line, otherwise it's an error.  */
-      if (type == bp_dprintf)
-	{
-	  if (extra_string != nullptr)
-	    update_dprintf_command_list (this);
-	  else
-	    error (_("Format string required"));
-	}
-      else if (extra_string != nullptr)
-	error (_("Garbage '%s' at end of command"), extra_string.get ());
+  /* Dynamic printf requires and uses additional arguments on the
+     command line, otherwise it's an error.  */
+  if (type == bp_dprintf)
+    {
+      gdb_assert (extra_string != nullptr);
+      update_dprintf_command_list (this);
     }
+  else if (extra_string != nullptr)
+    error (_("Garbage '%s' at end of command"), extra_string.get ());
 
   /* The order of the locations is now stable.  Set the location
      condition using the location's number.  */
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv6 05/10] gdb: don't display inferior list for pending breakpoints
  2023-12-02 10:42         ` [PATCHv6 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
                             ` (3 preceding siblings ...)
  2023-12-02 10:42           ` [PATCHv6 04/10] gdb: build dprintf commands just once in code_breakpoint constructor Andrew Burgess
@ 2023-12-02 10:42           ` Andrew Burgess
  2023-12-05  8:35             ` Aktemur, Tankut Baris
  2023-12-02 10:42           ` [PATCHv6 06/10] gdb: parse pending breakpoint thread/task immediately Andrew Burgess
                             ` (5 subsequent siblings)
  10 siblings, 1 reply; 138+ messages in thread
From: Andrew Burgess @ 2023-12-02 10:42 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

I noticed that in the 'info breakpoints' output, GDB sometimes prints
the inferior list for pending breakpoints, this doesn't seem right to
me.  A pending breakpoint has no locations (at least, as far as we
display things in the 'info breakpoints' output), so including an
inferior list seems odd.

Here's what I see right now:

  (gdb) info breakpoint 5
  Num     Type           Disp Enb Address            What
  5       breakpoint     keep y   <PENDING>          foo inf 1
  (gdb)

It's the 'inf 1' at the end of the line that I'm objecting too.

To trigger this behaviour we need to be in a multi-inferior debug
session.  The breakpoint must have been non-pending at some point in
the past, and so have a location assigned to it.

The breakpoint becomes pending again as a result of a shared library
being unloaded.  When this happens the location itself is marked
pending (via bp_location::shlib_disabled).

In print_one_breakpoint_location, in order to print the inferior list
we check that the breakpoint has a location, and that we have multiple
inferiors, but we don't check if the location itself is pending.

This commit adds that check, which means the output is now:

  (gdb) info breakpoint 5
  Num     Type           Disp Enb Address            What
  5       breakpoint     keep y   <PENDING>          foo
  (gdb)

Which I think makes more sense -- indeed, the format without the
inferior list is what we display for a pending breakpoint that has
never had any locations assigned, so I think this change in behaviour
makes GDB more consistent.
---
 gdb/breakpoint.c                         |   2 +-
 gdb/testsuite/gdb.multi/pending-bp-lib.c |  22 ++++
 gdb/testsuite/gdb.multi/pending-bp.c     |  66 ++++++++++++
 gdb/testsuite/gdb.multi/pending-bp.exp   | 130 +++++++++++++++++++++++
 4 files changed, 219 insertions(+), 1 deletion(-)
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.exp

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index c1440a6921f..3ee23af83d6 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -6597,7 +6597,7 @@ print_one_breakpoint_location (struct breakpoint *b,
 	}
     }
 
-  if (loc != NULL && !header_of_multiple)
+  if (loc != NULL && !header_of_multiple && !loc->shlib_disabled)
     {
       std::vector<int> inf_nums;
       int mi_only = 1;
diff --git a/gdb/testsuite/gdb.multi/pending-bp-lib.c b/gdb/testsuite/gdb.multi/pending-bp-lib.c
new file mode 100644
index 00000000000..15d1b9833dd
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp-lib.c
@@ -0,0 +1,22 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+int global_var = 0;
+
+void
+foo (int arg)
+{
+  global_var = arg;
+}
diff --git a/gdb/testsuite/gdb.multi/pending-bp.c b/gdb/testsuite/gdb.multi/pending-bp.c
new file mode 100644
index 00000000000..ca8a3c20b72
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp.c
@@ -0,0 +1,66 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#include <dlfcn.h>
+#include <stdlib.h>
+
+void
+breakpt ()
+{
+  /* Nothing.  */
+}
+
+volatile int global_counter = 0;
+
+volatile int call_count = 1;
+
+int
+main (void)
+{
+  void *handle;
+  void (*func)(int);
+
+  /* Some filler work so that we don't initially stop on the breakpt call
+     below.  */
+  ++global_counter;
+
+  breakpt ();	/* Break before open.  */
+
+  /* Now load the shared library.  */
+  handle = dlopen (SHLIB_NAME, RTLD_LAZY);
+  if (handle == NULL)
+    abort ();
+
+  breakpt ();	/* Break after open.  */
+
+  /* Find the function symbol.  */
+  func = (void (*)(int)) dlsym (handle, "foo");
+
+  for (; call_count > 0; --call_count)
+    {
+      /* Call the library function.  */
+      func (1);
+    }
+
+  breakpt ();	/* Break before close.  */
+
+  /* Unload the shared library.  */
+  if (dlclose (handle) != 0)
+    abort ();
+
+  breakpt ();	/* Break after close.  */
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.multi/pending-bp.exp b/gdb/testsuite/gdb.multi/pending-bp.exp
new file mode 100644
index 00000000000..e4f0aa2e38a
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp.exp
@@ -0,0 +1,130 @@
+# Copyright 2023 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+# Tests related to pending breakpoints in a multi-inferior environment.
+
+require allow_shlib_tests !use_gdb_stub
+
+standard_testfile
+
+set libname $testfile-lib
+set srcfile_lib $srcdir/$subdir/$libname.c
+set binfile_lib [standard_output_file $libname.so]
+
+if { [gdb_compile_shlib $srcfile_lib $binfile_lib {}] != "" } {
+    untested "failed to compile shared library 1"
+    return -1
+}
+
+set binfile_lib_target [gdb_download_shlib $binfile_lib]
+
+if { [build_executable "failed to prepare" $testfile $srcfile \
+	  [list debug \
+	       additional_flags=-DSHLIB_NAME=\"$binfile_lib_target\" \
+	       shlib_load pthreads]] } {
+    return -1
+}
+
+# Used to override delete_breakpoints when we don't want breakpoints
+# deleted.
+proc do_nothing {} {}
+
+# Start two inferiors, both running the same test binary.  The arguments
+# INF_1_STOP and INF_2_STOP are source code patterns that are passed to
+# gdb_get_line_number to figure out where each inferior should be stopped.
+#
+# This proc does a clean_restart and leaves inferior 2 selected.  Also the
+# 'breakpoint pending' flag is enabled, so pending breakpoints can be created
+# without GDB prompting the user.
+proc do_test_setup { inf_1_stop inf_2_stop } {
+    clean_restart ${::binfile}
+
+    gdb_locate_shlib $::binfile_lib
+
+    if ![runto_main] {
+	return false
+    }
+
+    gdb_breakpoint [gdb_get_line_number ${inf_1_stop}] temporary
+    gdb_continue_to_breakpoint "move inferior 1 into position"
+
+    gdb_test "add-inferior -exec ${::binfile}" \
+	"Added inferior 2.*" "add inferior 2"
+    gdb_test "inferior 2" "Switching to inferior 2 .*" "switch to inferior 2"
+
+    with_override delete_breakpoints do_nothing {
+	if {![runto_main]} {
+	    return false
+	}
+    }
+
+    gdb_breakpoint [gdb_get_line_number ${inf_2_stop}] temporary
+    gdb_continue_to_breakpoint "move inferior 2 into position"
+
+    gdb_test_no_output "set breakpoint pending on"
+
+    return true
+}
+
+# Check that when a breakpoint is in the pending state, but that breakpoint
+# does have some locations (those locations themselves are pending), GDB
+# doesn't display the inferior list in the 'info breakpoints' output.
+proc_with_prefix test_no_inf_display {} {
+    do_test_setup "Break before open" "Break before open"
+
+    # Create a breakpoint on 'foo'.  As the shared library (that contains
+    # foo) has not been loaded into any inferior yet, then there will be no
+    # locations and the breakpoint will be created pending.
+    gdb_breakpoint "foo" allow-pending
+    set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+		   "get foo breakpoint number"]
+
+    # Check the 'info breakpoints' output; the breakpoint is pending with
+    # not 'inf X' appearing at the end of the line.
+    gdb_test "info breakpoint $bpnum" \
+	"$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	"check info bp before locations have been created"
+
+    # Now select inferior 1 and allow the inferior to run forward to the
+    # point where a breakpoint location for foo will have been created.
+    gdb_test "inferior 1" "Switching to inferior 1 .*"
+    gdb_breakpoint [gdb_get_line_number "Break after open"] temporary
+    gdb_continue_to_breakpoint \
+	"move inferior 1 until a location has been added"
+
+    # Check the 'info breakpoints' output.  Notice we display the inferior
+    # list at the end of the breakpoint line.
+    gdb_test "info breakpoint $bpnum" \
+	"$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex\\s+<foo\[^>\]*>\\s+inf 1" \
+	"check info breakpoints while breakpoint is inserted"
+
+    # Continue inferior 1 until the shared library has been unloaded.  The
+    # breakpoint on 'foo' will return to the pending state.  We will need to
+    # 'continue' twice as the first time will hit the 'foo' breakpoint.
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "hit the breakpoint in foo"
+    gdb_continue_to_breakpoint "after close library"
+
+    # Check the 'info breakpoints' output, check there is no 'inf 1' at the
+    # end of the breakpoint line.
+    gdb_test "info breakpoint $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	     "\\s+breakpoint already hit 1 time"] \
+	"check info breakpoints while breakpoint is pending"
+}
+
+# Run all the tests.
+test_no_inf_display
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv6 06/10] gdb: parse pending breakpoint thread/task immediately
  2023-12-02 10:42         ` [PATCHv6 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
                             ` (4 preceding siblings ...)
  2023-12-02 10:42           ` [PATCHv6 05/10] gdb: don't display inferior list for pending breakpoints Andrew Burgess
@ 2023-12-02 10:42           ` Andrew Burgess
  2023-12-05 15:09             ` Aktemur, Tankut Baris
  2023-12-02 10:42           ` [PATCHv6 07/10] gdb: don't set breakpoint::pspace for in create_breakpoint Andrew Burgess
                             ` (4 subsequent siblings)
  10 siblings, 1 reply; 138+ messages in thread
From: Andrew Burgess @ 2023-12-02 10:42 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Eli Zaretskii

Eli has already approved the docs changes in this commit.

---

The initial motivation for this commit was to allow thread or inferior
specific breakpoints to only be inserted within the appropriate
inferior's program-space.  The benefit of this is that inferiors for
which the breakpoint does not apply will no longer need to stop, and
then resume, for such breakpoints.  This commit does not make this
change, but is a refactor to allow this to happen in a later commit.

The problem we currently have is that when a thread-specific (or
inferior-specific) breakpoint is created, the thread (or inferior)
number is only parsed by calling find_condition_and_thread_for_sals.
This function is only called for non-pending breakpoints, and requires
that we know the locations at which the breakpoint will be placed (for
expression checking in case the breakpoint is also conditional).

A consequence of this is that by the time we figure out the breakpoint
is thread-specific we have already looked up locations in all program
spaces.  This feels wasteful -- if we knew the thread-id earlier then
we could reduce the work GDB does by only looking up locations within
the program space for which the breakpoint applies.

Another consequence of how find_condition_and_thread_for_sals is
called is that pending breakpoints don't currently know they are
thread-specific, nor even that they are conditional!  Additionally, by
delaying parsing the thread-id, pending breakpoints can be created for
non-existent threads, this is different to how non-pending
breakpoints are handled, so I can do this:

  $ gdb -q ./gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp
  Reading symbols from ./gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp...
  (gdb) break foo thread 99
  Function "foo" not defined.
  Make breakpoint pending on future shared library load? (y or [n]) y
  Breakpoint 1 (foo thread 99) pending.
  (gdb) r
  Starting program: /tmp/gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp
  [Thread debugging using libthread_db enabled]
  Using host libthread_db library "/lib64/libthread_db.so.1".
  Error in re-setting breakpoint 1: Unknown thread 99.
  [Inferior 1 (process 3329749) exited normally]
  (gdb)

GDB only checked the validity of 'thread 99' at the point the 'foo'
location became non-pending.  In contrast, if I try this:

  $ gdb -q ./gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp
  Reading symbols from ./gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp...
  (gdb) break main thread 99
  Unknown thread 99.
  (gdb)

GDB immediately checks if 'thread 99' exists.  I think inconsistencies
like this are confusing, and should be fixed if possible.

In this commit the create_breakpoint function is updated so that the
extra_string, which contains the thread, inferior, task, and/or
condition information, is parsed immediately, even for pending
breakpoints.

Obviously, the condition still can't be validated until the breakpoint
becomes non-pending, but the thread, inferior, and task information
can be pulled from the extra-string, and can be validated early on,
even for pending breakpoints.  The -force-condition flag is also
parsed as part of this early parsing change.

There are a couple of benefits to doing this:

1. Printing of breakpoints is more consistent now.  Consider creating
   a conditional breakpoint before this commit:

    (gdb) set breakpoint pending on
    (gdb) break pendingfunc if (0)
    Function "pendingfunc" not defined.
    Breakpoint 1 (pendingfunc if (0)) pending.
    (gdb) break main if (0)
    Breakpoint 2 at 0x401198: file /tmp/hello.c, line 18.
    (gdb) info breakpoints
    Num     Type           Disp Enb Address            What
    1       breakpoint     keep y   <PENDING>          pendingfunc if (0)
    2       breakpoint     keep y   0x0000000000401198 in main at /tmp/hello.c:18
            stop only if (0)
    (gdb)

   And after this commit:

    (gdb) set breakpoint pending on
    (gdb) break pendingfunc if (0)
    Function "pendingfunc" not defined.
    Breakpoint 1 (pendingfunc) pending.
    (gdb) break main if (0)
    Breakpoint 2 at 0x401198: file /home/andrew/tmp/hello.c, line 18.
    (gdb) info breakpoints
    Num     Type           Disp Enb Address            What
    1       breakpoint     keep y   <PENDING>          pendingfunc
            stop only if (0)
    2       breakpoint     keep y   0x0000000000401198 in main at /home/andrew/tmp/hello.c:18
            stop only if (0)
    (gdb)

   Notice that the display of the condition is now the same for the
   pending and non-pending breakpoints.

   The same is true for the thread, inferior, or task information in
   thread, inferior, or task specific breakpoints; this information is
   displayed on its own line rather than being part of the 'What'
   field.

2. We can check that the thread exists as soon as the pending
   breakpoint is created.  Currently there is a weird difference
   between pending and non-pending breakpoints when creating a
   thread-specific breakpoint.

   A pending thread-specific breakpoint only checks its thread when it
   becomes non-pending, at which point the thread the breakpoint was
   intended for might have exited.  Here's the behaviour before this
   commit:

    (gdb) set breakpoint pending on
    (gdb) break foo thread 2
    Function "foo" not defined.
    Breakpoint 2 (foo thread 2) pending.
    (gdb) c
    Continuing.
    [Thread 0x7ffff7c56700 (LWP 2948835) exited]
    Error in re-setting breakpoint 2: Unknown thread 2.
    [Inferior 1 (process 2948832) exited normally]
    (gdb)

   Notice the 'Error in re-setting breakpoint 2: Unknown thread 2.'
   line, this was triggered when GDB tried to make the breakpoint
   non-pending, and GDB discovers that the thread no longer exists.

   Compare that to the behaviour after this commit:

    (gdb) set breakpoint pending on
    (gdb) break foo thread 2
    Function "foo" not defined.
    Breakpoint 2 (foo) pending.
    (gdb) c
    Continuing.
    [Thread 0x7ffff7c56700 (LWP 2949243) exited]
    Thread-specific breakpoint 2 deleted - thread 2 no longer in the thread list.
    [Inferior 1 (process 2949240) exited normally]
    (gdb)

   Now the behaviour for pending breakpoints is identical to
   non-pending breakpoints, the thread specific breakpoint is removed
   as soon as the thread the breakpoint is associated with exits.

   There is an additional change; when the pending breakpoint is
   created prior to this patch we see this line:

     Breakpoint 2 (foo thread 2) pending.

   While after this patch we get this line:

     Breakpoint 2 (foo) pending.

   Notice that 'thread 2' has disappeared.  This might look like a
   regression, but I don't think it is.  That we said 'thread 2'
   before was just a consequence of the lazy parsing of the breakpoint
   specification, while with this patch GDB understands, and has
   parsed away the 'thread 2' bit of the spec.  If folk think the old
   information was useful then this would be trivial to add back in
   code_breakpoint::say_where.

As a result of this commit the breakpoints 'extra_string' field is now
only used by bp_dprintf type breakpoints to hold the printf format and
arguments.  This string should always be empty for other breakpoint
types.  This allows me to clean up some code in
print_breakpoint_location.

In code_breakpoint::code_breakpoint I'm able to change an error case
into an assert.  This is because this error is now handled earlier in
create_breakpoint.  As a result we know that by this point, the
extra_string will always be nullptr for anything other than a
bp_dprintf style breakpoint.

The find_condition_and_thread_for_sals function is now no longer
needed, this was previously doing the delayed splitting of the extra
string into thread, task, and condition, but this is now all done in
create_breakpoint, so find_condition_and_thread_for_sals can be
deleted, and the code that calls this in
code_breakpoint::location_spec_to_sals can be removed.  With this
update this code would only ever be reached for bp_dprintf style
breakpoints, and in these cases the extra_string should not contain
anything other than format and args.

The most interesting changes are all in create_breakpoint and in the
new file break-cond-parse.c.  We have a new block of code early on in
create_breakpoint that is responsible for splitting the extra_string
into its component parts by calling create_breakpoint_parse_arg_string
a function in the new break-cond-parse.c file.  This means that some
of the later code can be simplified a little.

The new break-cond-parse.c file implements the splitting up the
extra_string and finding all the parts, as well as some self-tests for
the new function.

Finally, now we know all the details, these can be stored within the
breakpoint object if we end up creating a deferred breakpoint.
Additionally, if we are creating a deferred bp_dprintf we can parse
the extra_string to build the printf command.

The implementation here aims to maintain backwards compatibility as
much as possible, this means that:

  1. We support abbreviations of 'thread', 'task', and 'inferior' in
  some places on the breakpoint line.  The handling of abbreviations
  has (before this patch) been a little weird, so this works:

  (gdb) break *main th 1

  And creates a breakpoint at '*main' for thread 1 only, while this
  does not work:

  (gdb) break main th 1

  In this case GDB will try to find the symbol 'main th 1'.  This
  weirdness exists before and after this patch.

  2. The handling of '-force-condition' is odd, if this flag appears
  immediately after a condition then it will be treated as part of the
  condition, e.g.:

  (gdb) break main if 0 -force-condition
  No symbol "force" in current context.

  But we are fine with these alternatives:

  (gdb) break main if 0 thread 1 -force-condition
  (gdb) break main -force-condition if 0

  Again, this is just a quirk of how the breakpoint line used to be
  parsed, but I've chosen to maintain this for backward
  compatibility.  Maybe in the future we might wish to consider
  changing this behaviour, but I'd rather do that as a separate commit
  later on, if that was of interest to people.

Reviewed-By: Eli Zaretskii <eliz@gnu.org>
---
 gdb/Makefile.in                               |   2 +
 gdb/NEWS                                      |   4 +
 gdb/break-cond-parse.c                        | 463 ++++++++++++++++++
 gdb/break-cond-parse.h                        |  49 ++
 gdb/breakpoint.c                              | 372 ++++----------
 gdb/testsuite/gdb.ada/tasks.exp               |   6 +-
 gdb/testsuite/gdb.base/condbreak.exp          |  57 ++-
 gdb/testsuite/gdb.base/pending.exp            |  23 +-
 gdb/testsuite/gdb.linespec/explicit.exp       |   4 +-
 gdb/testsuite/gdb.mi/mi-dprintf-pending.exp   |   3 +-
 .../gdb.multi/inferior-specific-bp.exp        |   4 +-
 .../gdb.threads/del-pending-thread-bp-lib.c   |  22 +
 .../gdb.threads/del-pending-thread-bp.c       |  85 ++++
 .../gdb.threads/del-pending-thread-bp.exp     | 108 ++++
 14 files changed, 900 insertions(+), 302 deletions(-)
 create mode 100644 gdb/break-cond-parse.c
 create mode 100644 gdb/break-cond-parse.h
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.exp

diff --git a/gdb/Makefile.in b/gdb/Makefile.in
index 3510577f090..425b41f5973 100644
--- a/gdb/Makefile.in
+++ b/gdb/Makefile.in
@@ -1025,6 +1025,7 @@ COMMON_SFILES = \
 	break-catch-sig.c \
 	break-catch-syscall.c \
 	break-catch-throw.c \
+	break-cond-parse.c \
 	breakpoint.c \
 	bt-utils.c \
 	btrace.c \
@@ -1293,6 +1294,7 @@ HFILES_NO_SRCDIR = \
 	bfd-target.h \
 	bfin-tdep.h \
 	block.h \
+	break-cond-parse.h \
 	breakpoint.h \
 	bsd-kvm.h \
 	bsd-uthread.h \
diff --git a/gdb/NEWS b/gdb/NEWS
index 1073e38dfc6..a3cbd34f1d0 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -9,6 +9,10 @@
 * GDB index now contains information about the main function.  This speeds up
   startup when it is being used for some large binaries.
 
+* For breakpoints that are created in the 'pending' state, any
+  'thread' or 'task' keywords are parsed at the time the breakpoint is
+  created, rather than at the time the breakpoint becomes non-pending.
+
 * Changed commands
 
 disassemble
diff --git a/gdb/break-cond-parse.c b/gdb/break-cond-parse.c
new file mode 100644
index 00000000000..b59bd7aeeec
--- /dev/null
+++ b/gdb/break-cond-parse.c
@@ -0,0 +1,463 @@
+/* Copyright (C) 2023 Free Software Foundation, Inc.
+
+   This file is part of GDB.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#include "defs.h"
+#include "gdbsupport/gdb_assert.h"
+#include "gdbsupport/selftest.h"
+#include "test-target.h"
+#include "scoped-mock-context.h"
+#include "break-cond-parse.h"
+#include "tid-parse.h"
+#include "ada-lang.h"
+
+/* When parsing tokens from a string, which direction are we parsing?
+
+   Given the following string and pointer 'ptr':
+
+	ABC DEF GHI JKL
+	       ^
+	       ptr
+
+   Parsing 'forward' will return the token 'GHI' and update 'ptr' to point
+   between GHI and JKL.  Parsing 'backward' will return the token 'DEF' and
+   update 'ptr' to point between ABC and DEF.
+*/
+
+enum class parse_direction
+{
+  /* Parse the next token forwards.  */
+  forward,
+
+  /* Parse the previous token backwards.  */
+  backward
+};
+
+struct token
+{
+  /* Create a new token.  START points to the first character of the new
+     token, while END points at the last character of the new token.
+
+     Neither START or END can be nullptr, and both START and END must point
+     into the same C style string (i.e. there should be no null character
+     between START and END).  END must be equal to, or greater than START,
+     that is, it is not possible to create a zero length token.  */
+
+  token (const char *start, const char *end)
+    : m_start (start),
+      m_end (end)
+  {
+    gdb_assert (m_end >= m_start);
+    gdb_assert (m_start + strlen (m_start) > m_end);
+  }
+
+  /* Return a pointer to the first character of this token.  */
+  const char *start () const
+  {
+    return m_start;
+  }
+
+  /* Return a pointer to the last character of this token.  */
+  const char *end () const
+  {
+    return m_end;
+  }
+
+  /* Return the length of the token.  */
+  size_t length () const
+  {
+    /* The + 1 is because the character at m_end is part of the token.  */
+    return m_end - m_start + 1;
+  }
+
+  /* Return true if this token matches STR.  */
+  bool matches (const char *str) const
+  {
+    return strncmp (m_start, str, length ()) == 0;
+  }
+
+private:
+  /* The first character of this token.  */
+  const char *m_start;
+
+  /* The last character of this token.  */
+  const char *m_end;
+};
+
+/* Find the next token in DIRECTION from *CURR.  */
+
+static token
+find_next_token (const char **curr, parse_direction direction)
+{
+  const char *tok_start, *tok_end;
+
+  gdb_assert (**curr != '\0');
+
+  if (direction == parse_direction::forward)
+    {
+      *curr = skip_spaces (*curr);
+      tok_start = *curr;
+      *curr = skip_to_space (*curr);
+      tok_end = *curr - 1;
+    }
+  else
+    {
+      gdb_assert (direction == parse_direction::backward);
+
+      while (isspace (**curr))
+	--(*curr);
+
+      tok_end = *curr;
+
+      while (!isspace (**curr))
+	--(*curr);
+
+      tok_start = (*curr) + 1;
+    }
+
+  return token (tok_start, tok_end);
+}
+
+/* See break-cond-parse.h.  */
+
+void
+create_breakpoint_parse_arg_string
+  (const char *tok, gdb::unique_xmalloc_ptr<char> *cond_string,
+   int *thread, int *inferior, int *task,
+   gdb::unique_xmalloc_ptr<char> *rest, bool *force)
+{
+  /* Set up the defaults.  */
+  cond_string->reset ();
+  rest->reset ();
+  *thread = -1;
+  *inferior = -1;
+  *task = -1;
+  *force = false;
+
+  if (tok == nullptr)
+    return;
+
+  /* The "-force-condition" flag gets some special treatment.  If this
+     token is immediately after the condition string then we treat this as
+     part of the condition string rather than a separate token.  This is
+     just a quirk of how this token used to be parsed, and has been
+     retained for backwards compatibility.  Maybe this should be updated
+     in the future.  */
+  std::optional<token> force_condition_token;
+
+  const char *cond_start = nullptr;
+  const char *cond_end = nullptr;
+  parse_direction direction = parse_direction::forward;
+  while (*tok != '\0')
+    {
+      /* Find the next token.  If moving backward and this token starts at
+	 the same location as the condition then we must have found the
+	 other end of the condition string -- we're done.  */
+      token t = find_next_token (&tok, direction);
+      if (direction == parse_direction::backward && t.start () <= cond_start)
+	{
+	  cond_end = t.end ();
+	  break;
+	}
+
+      /* We only have a single flag option to check for.  All the other
+	 options take a value so require an additional token to be found.
+	 Additionally, we require that this flag be at least '-f', we
+	 don't allow it to be abbreviated to '-'.  */
+      if (t.length () > 1 && t.matches ("-force-condition"))
+	{
+	  force_condition_token.emplace (t);
+	  continue;
+	}
+
+      /* Maybe the first token was the last token in the string.  If this
+	 is the case then we definitely can't try to extract a value
+	 token.  This also means that the token T is meaningless.  Reset
+	 TOK to point at the start of the unknown content and break out of
+	 the loop.  We'll record the unknown part of the string outside of
+	 the scanning loop (below).  */
+      if (direction == parse_direction::forward && *tok == '\0')
+	{
+	  tok = t.start ();
+	  break;
+	}
+
+      /* As before, find the next token and, if we are scanning backwards,
+	 check that we have not reached the start of the condition string.  */
+      token v = find_next_token (&tok, direction);
+      if (direction == parse_direction::backward && v.start () <= cond_start)
+	{
+	  /* Use token T here as that must also be part of the condition
+	     string.  */
+	  cond_end = t.end ();
+	  break;
+	}
+
+      /* When moving backward we will first parse the value token then the
+	 keyword token, so swap them now.  */
+      if (direction == parse_direction::backward)
+	std::swap (t, v);
+
+      /* Check for valid option in token T.  If we find a valid option then
+	 parse the value from the token V.  Except for 'if', that's handled
+	 differently.
+
+	 For the 'if' token we need to capture the entire condition
+	 string, so record the start of the condition string and then
+	 start scanning backwards looking for the end of the condition
+	 string.
+
+	 The order of these checks is important, at least the check for
+	 'thread' must occur before the check for 'task'.  We accept
+	 abbreviations of these token names, and 't' should resolve to
+	 'thread', which will only happen if we check 'thread' first.  */
+      if (direction == parse_direction::forward && t.matches ("if"))
+	{
+	  cond_start = v.start ();
+	  tok = tok + strlen (tok);
+	  gdb_assert (*tok == '\0');
+	  --tok;
+	  direction = parse_direction::backward;
+	  continue;
+	}
+      else if (t.matches ("thread"))
+	{
+	  if (*thread != -1)
+	    error(_("You can specify only one thread."));
+
+	  if (*task != -1 || *inferior != -1)
+	    error (_("You can specify only one of thread, inferior, or task."));
+
+	  const char *tmptok;
+	  thread_info *thr = parse_thread_id (v.start (), &tmptok);
+	  const char *expected_end = skip_spaces (v.end () + 1);
+	  if (tmptok != expected_end)
+	    error (_("Junk after thread keyword."));
+	  *thread = thr->global_num;
+	}
+      else if (t.matches ("inferior"))
+	{
+	  if (*inferior != -1)
+	    error(_("You can specify only one inferior."));
+
+	  if (*task != -1 || *thread != -1)
+	    error (_("You can specify only one of thread, inferior, or task."));
+
+	  char *tmptok;
+	  *inferior = strtol (v.start (), &tmptok, 0);
+	  const char *expected_end = v.end () + 1;
+	  if (tmptok != expected_end)
+	    error (_("Junk after inferior keyword."));
+	}
+      else if (t.matches ("task"))
+	{
+	  if (*task != -1)
+	    error(_("You can specify only one task."));
+
+	  if (*thread != -1 || *inferior != -1)
+	    error (_("You can specify only one of thread, inferior, or task."));
+
+	  char *tmptok;
+	  *task = strtol (v.start (), &tmptok, 0);
+	  const char *expected_end = v.end () + 1;
+	  if (tmptok != expected_end)
+	    error (_("Junk after task keyword."));
+	  if (!valid_task_id (*task))
+	    error (_("Unknown task %d."), *task);
+	}
+      else
+	{
+	  /* An unknown token.  If we are scanning forward then reset TOK
+	     to point at the start of the unknown content, we record this
+	     outside of the scanning loop (below).
+
+	     If we are scanning backward then unknown content is assumed to
+	     be the other end of the condition string, obviously, this is
+	     just a heuristic, we could be looking at a mistyped command
+	     line, but this will be spotted when the condition is
+	     eventually evaluated.
+
+	     Either way, no more scanning is required after this.  */
+	  if (direction == parse_direction::forward)
+	    tok = t.start ();
+	  else
+	    {
+	      gdb_assert (direction == parse_direction::backward);
+	      cond_end = v.end ();
+	    }
+	  break;
+	}
+    }
+
+  if (cond_start != nullptr)
+    {
+      /* If we found the start of a condition string then we should have
+	 switched to backward scan mode, and found the end of the condition
+	 string.  Capture the whole condition string into COND_STRING
+	 now.  */
+      gdb_assert (direction == parse_direction::backward);
+      gdb_assert (cond_end != nullptr);
+
+      /* If the first token after the condition string is the
+	 "-force-condition" token, then we merge the "-force-condition"
+	 token with the condition string and forget ever seeing the
+	 "-force-condition".  */
+      if (force_condition_token.has_value ())
+	{
+	  const char *next_token_start = skip_spaces (cond_end + 1);
+
+	  if (next_token_start == force_condition_token->start ())
+	    {
+	      cond_end = force_condition_token->end ();
+	      force_condition_token.reset ();
+	    }
+	}
+
+      /* The '+ 1' here is because COND_END points to the last character of
+	 the condition string rather than the null-character at the end of
+	 the condition string, and we need the string length here.  */
+      cond_string->reset (savestring (cond_start, cond_end - cond_start + 1));
+    }
+  else if (*tok != '\0')
+    {
+      /* If we didn't have a condition start pointer then we should still
+	 be in forward scanning mode.  If we didn't reach the end of the
+	 input string (TOK is not at the null character) then the rest of
+	 the input string is garbage that we didn't understand.
+
+	 Record the unknown content into REST.  The caller of this function
+	 will report this as an error later on.  We could report the error
+	 here, but we prefer to allow the caller to run other checks, and
+	 prioritise other errors before reporting this problem.  */
+      gdb_assert (direction == parse_direction::forward);
+      gdb_assert (cond_end == nullptr);
+      rest->reset (savestring (tok, strlen (tok)));
+    }
+
+  /* If we saw "-force-condition" then set the *FORCE flag.  Depending on
+     which path we took above we might have chosen to forget having seen
+     the "-force-condition" token.  */
+  if (force_condition_token.has_value ())
+    *force = true;
+}
+
+#if GDB_SELF_TEST
+
+namespace selftests {
+
+/* Run a single test of the create_breakpoint_parse_arg_string function.
+   INPUT is passed to create_breakpoint_parse_arg_string while all other
+   arguments are the expected output from
+   create_breakpoint_parse_arg_string.  */
+
+static void
+test (const char *input, const char *condition, int thread = -1,
+      int inferior = -1, int task = -1, bool force = false,
+      const char *rest = nullptr)
+{
+  gdb::unique_xmalloc_ptr<char> extracted_condition;
+  gdb::unique_xmalloc_ptr<char> extracted_rest;
+  int extracted_thread, extracted_inferior, extracted_task;
+  bool extracted_force_condition;
+  std::string exception_msg;
+
+  try
+    {
+      create_breakpoint_parse_arg_string (input, &extracted_condition,
+					  &extracted_thread,
+					  &extracted_inferior,
+					  &extracted_task, &extracted_rest,
+					  &extracted_force_condition);
+    }
+  catch (const gdb_exception_error &ex)
+    {
+      string_file buf;
+
+      exception_print (&buf, ex);
+      exception_msg = buf.release ();
+    }
+
+  if ((condition == nullptr) != (extracted_condition.get () == nullptr)
+      || (condition != nullptr
+	  && strcmp (condition, extracted_condition.get ()) != 0)
+      || (rest == nullptr) != (extracted_rest.get () == nullptr)
+      || (rest != nullptr && strcmp (rest, extracted_rest.get ()) != 0)
+      || thread != extracted_thread
+      || inferior != extracted_inferior
+      || task != extracted_task
+      || force != extracted_force_condition
+      || !exception_msg.empty ())
+    {
+      if (run_verbose ())
+	{
+	  debug_printf ("input: '%s'\n", input);
+	  debug_printf ("condition: '%s'\n", extracted_condition.get ());
+	  debug_printf ("rest: '%s'\n", extracted_rest.get ());
+	  debug_printf ("thread: %d\n", extracted_thread);
+	  debug_printf ("inferior: %d\n", extracted_inferior);
+	  debug_printf ("task: %d\n", extracted_task);
+	  debug_printf ("forced: %s\n",
+			extracted_force_condition ? "true" : "false");
+	  debug_printf ("exception: '%s'\n", exception_msg.c_str ());
+	}
+
+      /* Report the failure.  */
+      SELF_CHECK (false);
+    }
+}
+
+/* Test the create_breakpoint_parse_arg_string function.  Just wraps
+   multiple calls to the test function above.  */
+
+static void
+create_breakpoint_parse_arg_string_tests (void)
+{
+  gdbarch *arch = current_inferior ()->arch ();
+  scoped_restore_current_pspace_and_thread restore;
+  scoped_mock_context<test_target_ops> mock_target (arch);
+
+  int global_thread_num = mock_target.mock_thread.global_num;
+
+  test ("  if blah  ", "blah");
+  test (" if blah thread 1", "blah", global_thread_num);
+  test (" if blah inferior 1", "blah", -1, 1);
+  test (" if blah thread 1  ", "blah", global_thread_num);
+  test ("thread 1 woof", nullptr, global_thread_num, -1, -1, false, "woof");
+  test ("thread 1 X", nullptr, global_thread_num, -1, -1, false, "X");
+  test (" if blah thread 1 -force-condition", "blah", global_thread_num,
+	-1, -1, true);
+  test (" -force-condition if blah thread 1", "blah", global_thread_num,
+	-1, -1, true);
+  test (" -force-condition if blah thread 1  ", "blah", global_thread_num,
+	-1, -1, true);
+  test ("thread 1 -force-condition if blah", "blah", global_thread_num,
+	-1, -1, true);
+  test ("if (A::outer::func ())", "(A::outer::func ())");
+}
+
+} // namespace selftests
+#endif /* GDB_SELF_TEST */
+
+void _initialize_break_cond_parse ();
+void
+_initialize_break_cond_parse ()
+{
+#if GDB_SELF_TEST
+  selftests::register_test
+    ("create_breakpoint_parse_arg_string",
+     selftests::create_breakpoint_parse_arg_string_tests);
+#endif
+}
diff --git a/gdb/break-cond-parse.h b/gdb/break-cond-parse.h
new file mode 100644
index 00000000000..b08b6fc6cc9
--- /dev/null
+++ b/gdb/break-cond-parse.h
@@ -0,0 +1,49 @@
+/* Copyright (C) 2023 Free Software Foundation, Inc.
+
+   This file is part of GDB.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#if !defined (BREAK_COND_PARSE_H)
+#define BREAK_COND_PARSE_H 1
+
+/* Given TOK, a string possibly containing a condition, thread, inferior,
+   task and force-condition flag, as accepted by the 'break' command,
+   extract the condition string, thread, inferior, task number, and the
+   force_condition flag, then set *COND_STRING, *THREAD, *INFERIOR, *TASK,
+   and *FORCE.
+
+   As TOK is parsed, if an unknown keyword is encountered before the 'if'
+   keyword then everything starting from the unknown keyword is placed into
+   *REST.
+
+   Both *COND and *REST are initialized to nullptr.  If no 'if' keyword is
+   found then *COND will be returned as nullptr.  If no unknown content is
+   found then *REST is returned as nullptr.
+
+   If no thread is found, *THREAD is set to -1.  If no inferior is found,
+   *INFERIOR is set to -1.  If no task is found, *TASK is set to -1.  If
+   the -force-condition flag is not found then *FORCE is set to false.
+
+   Due to the free-form nature that the string TOK might take (a 'thread'
+   keyword can appear before or after an 'if' condition) then we end up
+   having to check for keywords from both the start of TOK and the end of
+   TOK.  */
+
+extern void create_breakpoint_parse_arg_string
+  (const char *tok, gdb::unique_xmalloc_ptr<char> *cond_string,
+   int *thread, int *inferior, int *task,
+   gdb::unique_xmalloc_ptr<char> *rest, bool *force);
+
+#endif
diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 3ee23af83d6..e2cd4d360f2 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -70,6 +70,7 @@
 #include "cli/cli-style.h"
 #include "cli/cli-decode.h"
 #include <unordered_set>
+#include "break-cond-parse.h"
 
 /* readline include files */
 #include "readline/tilde.h"
@@ -6335,20 +6336,7 @@ print_breakpoint_location (const breakpoint *b, const bp_location *loc)
       uiout->field_stream ("at", stb);
     }
   else
-    {
-      uiout->field_string ("pending", b->locspec->to_string ());
-      /* If extra_string is available, it could be holding a condition
-	 or dprintf arguments.  In either case, make sure it is printed,
-	 too, but only for non-MI streams.  */
-      if (!uiout->is_mi_like_p () && b->extra_string != NULL)
-	{
-	  if (b->type == bp_dprintf)
-	    uiout->text (",");
-	  else
-	    uiout->text (" ");
-	  uiout->text (b->extra_string.get ());
-	}
-    }
+    uiout->field_string ("pending", b->locspec->to_string ());
 
   if (loc && is_breakpoint (b)
       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
@@ -8713,8 +8701,8 @@ code_breakpoint::code_breakpoint (struct gdbarch *gdbarch_,
       gdb_assert (extra_string != nullptr);
       update_dprintf_command_list (this);
     }
-  else if (extra_string != nullptr)
-    error (_("Garbage '%s' at end of command"), extra_string.get ());
+  else
+    gdb_assert (extra_string == nullptr);
 
   /* The order of the locations is now stable.  Set the location
      condition using the location's number.  */
@@ -8942,197 +8930,6 @@ check_fast_tracepoint_sals (struct gdbarch *gdbarch,
     }
 }
 
-/* Given TOK, a string specification of condition and thread, as accepted
-   by the 'break' command, extract the condition string into *COND_STRING.
-   If no condition string is found then *COND_STRING is set to nullptr.
-
-   If the breakpoint specification has an associated thread, task, or
-   inferior, these are extracted into *THREAD, *TASK, and *INFERIOR
-   respectively, otherwise these arguments are set to -1 (for THREAD and
-   INFERIOR) or 0 (for TASK).
-
-   PC identifies the context at which the condition should be parsed.  */
-
-static void
-find_condition_and_thread (const char *tok, CORE_ADDR pc,
-			   gdb::unique_xmalloc_ptr<char> *cond_string,
-			   int *thread, int *inferior, int *task,
-			   gdb::unique_xmalloc_ptr<char> *rest)
-{
-  cond_string->reset ();
-  *thread = -1;
-  *inferior = -1;
-  *task = -1;
-  rest->reset ();
-  bool force = false;
-
-  while (tok && *tok)
-    {
-      const char *end_tok;
-      int toklen;
-      const char *cond_start = NULL;
-      const char *cond_end = NULL;
-
-      tok = skip_spaces (tok);
-
-      if ((*tok == '"' || *tok == ',') && rest)
-	{
-	  rest->reset (savestring (tok, strlen (tok)));
-	  break;
-	}
-
-      end_tok = skip_to_space (tok);
-
-      toklen = end_tok - tok;
-
-      if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
-	{
-	  tok = cond_start = end_tok + 1;
-	  try
-	    {
-	      parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
-	    }
-	  catch (const gdb_exception_error &)
-	    {
-	      if (!force)
-		throw;
-	      else
-		tok = tok + strlen (tok);
-	    }
-	  cond_end = tok;
-	  cond_string->reset (savestring (cond_start, cond_end - cond_start));
-	}
-      else if (toklen >= 1 && strncmp (tok, "-force-condition", toklen) == 0)
-	{
-	  tok = tok + toklen;
-	  force = true;
-	}
-      else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
-	{
-	  const char *tmptok;
-	  struct thread_info *thr;
-
-	  if (*thread != -1)
-	    error(_("You can specify only one thread."));
-
-	  if (*task != -1)
-	    error (_("You can specify only one of thread or task."));
-
-	  if (*inferior != -1)
-	    error (_("You can specify only one of inferior or thread."));
-
-	  tok = end_tok + 1;
-	  thr = parse_thread_id (tok, &tmptok);
-	  if (tok == tmptok)
-	    error (_("Junk after thread keyword."));
-	  *thread = thr->global_num;
-	  tok = tmptok;
-	}
-      else if (toklen >= 1 && strncmp (tok, "inferior", toklen) == 0)
-	{
-	  if (*inferior != -1)
-	    error(_("You can specify only one inferior."));
-
-	  if (*task != -1)
-	    error (_("You can specify only one of inferior or task."));
-
-	  if (*thread != -1)
-	    error (_("You can specify only one of inferior or thread."));
-
-	  char *tmptok;
-	  tok = end_tok + 1;
-	  *inferior = strtol (tok, &tmptok, 0);
-	  if (tok == tmptok)
-	    error (_("Junk after inferior keyword."));
-	  if (!valid_global_inferior_id (*inferior))
-	    error (_("Unknown inferior number %d."), *inferior);
-	  tok = tmptok;
-	}
-      else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
-	{
-	  char *tmptok;
-
-	  if (*task != -1)
-	    error(_("You can specify only one task."));
-
-	  if (*thread != -1)
-	    error (_("You can specify only one of thread or task."));
-
-	  if (*inferior != -1)
-	    error (_("You can specify only one of inferior or task."));
-
-	  tok = end_tok + 1;
-	  *task = strtol (tok, &tmptok, 0);
-	  if (tok == tmptok)
-	    error (_("Junk after task keyword."));
-	  if (!valid_task_id (*task))
-	    error (_("Unknown task %d."), *task);
-	  tok = tmptok;
-	}
-      else if (rest)
-	{
-	  rest->reset (savestring (tok, strlen (tok)));
-	  break;
-	}
-      else
-	error (_("Junk at end of arguments."));
-    }
-}
-
-/* Call 'find_condition_and_thread' for each sal in SALS until a parse
-   succeeds.  The parsed values are written to COND_STRING, THREAD,
-   TASK, and REST.  See the comment of 'find_condition_and_thread'
-   for the description of these parameters and INPUT.  */
-
-static void
-find_condition_and_thread_for_sals (const std::vector<symtab_and_line> &sals,
-				    const char *input,
-				    gdb::unique_xmalloc_ptr<char> *cond_string,
-				    int *thread, int *inferior, int *task,
-				    gdb::unique_xmalloc_ptr<char> *rest)
-{
-  int num_failures = 0;
-  for (auto &sal : sals)
-    {
-      gdb::unique_xmalloc_ptr<char> cond;
-      int thread_id = -1;
-      int inferior_id = -1;
-      int task_id = -1;
-      gdb::unique_xmalloc_ptr<char> remaining;
-
-      /* Here we want to parse 'arg' to separate condition from thread
-	 number.  But because parsing happens in a context and the
-	 contexts of sals might be different, try each until there is
-	 success.  Finding one successful parse is sufficient for our
-	 goal.  When setting the breakpoint we'll re-parse the
-	 condition in the context of each sal.  */
-      try
-	{
-	  find_condition_and_thread (input, sal.pc, &cond, &thread_id,
-				     &inferior_id, &task_id, &remaining);
-	  *cond_string = std::move (cond);
-	  /* A value of -1 indicates that these fields are unset.  At most
-	     one of these fields should be set (to a value other than -1)
-	     at this point.  */
-	  gdb_assert (((thread_id == -1 ? 1 : 0)
-		       + (task_id == -1 ? 1 : 0)
-		       + (inferior_id == -1 ? 1 : 0)) >= 2);
-	  *thread = thread_id;
-	  *inferior = inferior_id;
-	  *task = task_id;
-	  *rest = std::move (remaining);
-	  break;
-	}
-      catch (const gdb_exception_error &e)
-	{
-	  num_failures++;
-	  /* If no sal remains, do not continue.  */
-	  if (num_failures == sals.size ())
-	    throw;
-	}
-    }
-}
-
 /* Decode a static tracepoint marker spec.  */
 
 static std::vector<symtab_and_line>
@@ -9250,6 +9047,46 @@ create_breakpoint (struct gdbarch *gdbarch,
 	      || (type_wanted != bp_dprintf
 		  && (extra_string == nullptr || parse_extra)));
 
+  /* Will hold either copies of the similarly named function argument, or
+     will hold a modified version of the function argument, depending on
+     the value of PARSE_EXTRA.  */
+  gdb::unique_xmalloc_ptr<char> cond_string_copy;
+  gdb::unique_xmalloc_ptr<char> extra_string_copy;
+
+  if (parse_extra)
+    {
+      /* Parse EXTRA_STRING splitting the parts out.  */
+      create_breakpoint_parse_arg_string (extra_string, &cond_string_copy,
+					  &thread, &inferior, &task,
+					  &extra_string_copy,
+					  &force_condition);
+
+      /* We could check that EXTRA_STRING_COPY is empty at this point -- it
+	 should be, as we only get here for things that are not bp_dprintf,
+	 however, we prefer to give the location spec parser a chance to
+	 run first, this means the user will get errors about invalid
+	 location spec instead of an error about garbage at the end of the
+	 command line.
+
+	 We still do the EXTRA_STRING_COPY is empty check, just later in
+	 this function.  */
+
+      gdb_assert (thread == -1 || thread > 0);
+      gdb_assert (task == -1 || task > 0);
+      gdb_assert (inferior == -1 || inferior > 0);
+    }
+  else
+    {
+      if (cond_string != nullptr)
+	cond_string_copy.reset (xstrdup (cond_string));
+      if (extra_string != nullptr)
+	extra_string_copy.reset (xstrdup (extra_string));
+    }
+
+  /* Clear these.  Updated values are now held in the *_copy locals.  */
+  cond_string = nullptr;
+  extra_string = nullptr;
+
   try
     {
       ops->create_sals_from_location_spec (locspec, &canonical);
@@ -9285,6 +9122,13 @@ create_breakpoint (struct gdbarch *gdbarch,
 	throw;
     }
 
+  /* The only bp_dprintf should have anything in EXTRA_STRING_COPY by this
+     point.  For all other breakpoints this indicates an error.  We could
+     place this check earlier in the function, but we prefer to see errors
+     from the location spec parser before we see this error message.  */
+  if (type_wanted != bp_dprintf && extra_string_copy.get () != nullptr)
+    error (_("Garbage '%s' at end of command"), extra_string_copy.get ());
+
   if (!pending && canonical.lsals.empty ())
     return 0;
 
@@ -9308,63 +9152,31 @@ create_breakpoint (struct gdbarch *gdbarch,
      breakpoint.  */
   if (!pending)
     {
-      gdb::unique_xmalloc_ptr<char> cond_string_copy;
-      gdb::unique_xmalloc_ptr<char> extra_string_copy;
-
-      if (parse_extra)
+      /* Check the validity of the condition.  We should error out if the
+	 condition is invalid at all of the locations and if it is not
+	 forced.  In the PARSE_EXTRA case above, this check is done when
+	 parsing the EXTRA_STRING.  */
+      if (cond_string_copy.get () != nullptr && !force_condition)
 	{
-	  gdb_assert (type_wanted != bp_dprintf);
-
-	  gdb::unique_xmalloc_ptr<char> rest;
-	  gdb::unique_xmalloc_ptr<char> cond;
-
+	  int num_failures = 0;
 	  const linespec_sals &lsal = canonical.lsals[0];
-
-	  find_condition_and_thread_for_sals (lsal.sals, extra_string,
-					      &cond, &thread, &inferior,
-					      &task, &rest);
-
-	  if (rest.get () != nullptr && *(rest.get ()) != '\0')
-	    error (_("Garbage '%s' at end of command"), rest.get ());
-
-	  cond_string_copy = std::move (cond);
-	  extra_string_copy = std::move (rest);
-	}
-      else
-	{
-	  /* Check the validity of the condition.  We should error out
-	     if the condition is invalid at all of the locations and
-	     if it is not forced.  In the PARSE_EXTRA case above, this
-	     check is done when parsing the EXTRA_STRING.  */
-	  if (cond_string != nullptr && !force_condition)
+	  for (const auto &sal : lsal.sals)
 	    {
-	      int num_failures = 0;
-	      const linespec_sals &lsal = canonical.lsals[0];
-	      for (const auto &sal : lsal.sals)
+	      const char *cond = cond_string_copy.get ();
+	      try
 		{
-		  const char *cond = cond_string;
-		  try
-		    {
-		      parse_exp_1 (&cond, sal.pc, block_for_pc (sal.pc), 0);
-		      /* One success is sufficient to keep going.  */
-		      break;
-		    }
-		  catch (const gdb_exception_error &)
-		    {
-		      num_failures++;
-		      /* If this is the last sal, error out.  */
-		      if (num_failures == lsal.sals.size ())
-			throw;
-		    }
+		  parse_exp_1 (&cond, sal.pc, block_for_pc (sal.pc), 0);
+		  /* One success is sufficient to keep going.  */
+		  break;
+		}
+	      catch (const gdb_exception_error &)
+		{
+		  num_failures++;
+		  /* If this is the last sal, error out.  */
+		  if (num_failures == lsal.sals.size ())
+		    throw;
 		}
 	    }
-
-	  /* Create a private copy of condition string.  */
-	  if (cond_string)
-	    cond_string_copy.reset (xstrdup (cond_string));
-	  /* Create a private copy of any extra string.  */
-	  if (extra_string)
-	    extra_string_copy.reset (xstrdup (extra_string));
 	}
 
       ops->create_breakpoints_sal (gdbarch, &canonical,
@@ -9381,21 +9193,16 @@ create_breakpoint (struct gdbarch *gdbarch,
 								 type_wanted);
       b->locspec = locspec->clone ();
 
-      if (parse_extra)
-	b->cond_string = NULL;
-      else
-	{
-	  /* Create a private copy of condition string.  */
-	  b->cond_string.reset (cond_string != NULL
-				? xstrdup (cond_string)
-				: NULL);
-	  b->thread = thread;
-	}
+      /* Create a private copy of the condition string.  */
+      b->cond_string = std::move (cond_string_copy);
+
+      b->thread = thread;
+      b->task = task;
+      b->inferior = inferior;
 
       /* Create a private copy of any extra string.  */
-      b->extra_string.reset (extra_string != NULL
-			     ? xstrdup (extra_string)
-			     : NULL);
+      b->extra_string = std::move (extra_string_copy);
+
       b->ignore_count = ignore_count;
       b->disposition = tempflag ? disp_del : disp_donttouch;
       b->condition_not_parsed = 1;
@@ -9404,9 +9211,12 @@ create_breakpoint (struct gdbarch *gdbarch,
 	   && type_wanted != bp_hardware_breakpoint) || thread != -1)
 	b->pspace = current_program_space;
 
+      if (b->type == bp_dprintf)
+	update_dprintf_command_list (b.get ());
+
       install_breakpoint (internal, std::move (b), 0);
     }
-  
+
   if (canonical.lsals.size () > 1)
     {
       warning (_("Multiple breakpoints were set.\nUse the "
@@ -13151,24 +12961,6 @@ code_breakpoint::location_spec_to_sals (location_spec *locspec,
     {
       for (auto &sal : sals)
 	resolve_sal_pc (&sal);
-      if (condition_not_parsed && extra_string != NULL)
-	{
-	  gdb::unique_xmalloc_ptr<char> local_cond, local_extra;
-	  int local_thread, local_task, local_inferior;
-
-	  find_condition_and_thread_for_sals (sals, extra_string.get (),
-					      &local_cond, &local_thread,
-					      &local_inferior,
-					      &local_task, &local_extra);
-	  gdb_assert (cond_string == nullptr);
-	  if (local_cond != nullptr)
-	    cond_string = std::move (local_cond);
-	  thread = local_thread;
-	  task = local_task;
-	  if (local_extra != nullptr)
-	    extra_string = std::move (local_extra);
-	  condition_not_parsed = 0;
-	}
 
       if (type == bp_static_tracepoint)
 	{
diff --git a/gdb/testsuite/gdb.ada/tasks.exp b/gdb/testsuite/gdb.ada/tasks.exp
index 603d43f7c36..337ee1b6f07 100644
--- a/gdb/testsuite/gdb.ada/tasks.exp
+++ b/gdb/testsuite/gdb.ada/tasks.exp
@@ -55,11 +55,11 @@ gdb_test "watch j task 1 task 3" "You can specify only one task\\."
 
 # Check that attempting to combine 'task' and 'thread' gives an error.
 gdb_test "break break_me task 1 thread 1" \
-    "You can specify only one of thread or task\\."
+    "You can specify only one of thread, inferior, or task\\."
 gdb_test "break break_me thread 1 task 1" \
-    "You can specify only one of thread or task\\."
+    "You can specify only one of thread, inferior, or task\\."
 gdb_test "break break_me inferior 1 task 1" \
-    "You can specify only one of inferior or task\\."
+    "You can specify only one of thread, inferior, or task\\."
 gdb_test "watch j task 1 thread 1" \
     "You can specify only one of thread or task\\."
 gdb_test "watch j thread 1 task 1" \
diff --git a/gdb/testsuite/gdb.base/condbreak.exp b/gdb/testsuite/gdb.base/condbreak.exp
index a5b2a28701b..5a6a42e073b 100644
--- a/gdb/testsuite/gdb.base/condbreak.exp
+++ b/gdb/testsuite/gdb.base/condbreak.exp
@@ -179,6 +179,10 @@ gdb_test "break -q main if (1==1) thread 999" \
     "Unknown thread 999\\."
 gdb_test "break -q main thread 999 if (1==1)" \
     "Unknown thread 999\\."
+gdb_test "break -q main if (1==1) thread 999 -force-condition" \
+    "Unknown thread 999\\."
+gdb_test "break -q main thread 999 if (1==1) -force-condition" \
+    "Unknown thread 999\\."
 
 # Verify that both if and thread can be distinguished from a breakpoint
 # address expression.
@@ -186,20 +190,71 @@ gdb_test "break *main if (1==1) thread 999" \
     "Unknown thread 999\\."
 gdb_test "break *main thread 999 if (1==1)" \
     "Unknown thread 999\\."
+gdb_test "break *main if (1==1) thread 999 -force-condition" \
+    "Unknown thread 999\\."
+gdb_test "break *main thread 999 if (1==1) -force-condition" \
+    "Unknown thread 999\\."
 
 # Similarly for task.
 gdb_test "break *main if (1==1) task 999" \
     "Unknown task 999\\."
 gdb_test "break *main task 999 if (1==1)" \
     "Unknown task 999\\."
+gdb_test "break *main if (1==1) task 999 -force-condition" \
+    "Unknown task 999\\."
+gdb_test "break *main task 999 if (1==1) -force-condition" \
+    "Unknown task 999\\."
 
-# GDB accepts abbreviations for "thread" and "task".
+# GDB accepts abbreviations for "thread", "task" and
+# "-force-condition", when these keywords appear after
+# the breakpoint condition.
 gdb_test "break *main if (1==1) t 999" \
     "Unknown thread 999\\."
 gdb_test "break *main if (1==1) th 999" \
     "Unknown thread 999\\."
 gdb_test "break *main if (1==1) ta 999" \
     "Unknown task 999\\."
+gdb_test "break *main if (1==1) t 999 -force" \
+    "Unknown thread 999\\."
+gdb_test "break *main if (1==1) th 999 -force" \
+    "Unknown thread 999\\."
+gdb_test "break *main if (1==1) ta 999 -force" \
+    "Unknown task 999\\."
+
+# Check the use of abbreviations before the condition.  This works
+# because, when the location spec starts with '*' GDB is able to
+# figure out that the complete location is '*main'.
+gdb_test "break *main t 999 if (1==1)" \
+    "Unknown thread 999\\."
+gdb_test "break *main th 999 if (1==1)" \
+    "Unknown thread 999\\."
+gdb_test "break *main ta 999 if (1==1)" \
+    "Unknown task 999\\."
+gdb_test "break *main t 999 -force if (1==1)" \
+    "Unknown thread 999\\."
+gdb_test "break *main th 999 -force if (1==1)" \
+    "Unknown thread 999\\."
+gdb_test "break *main ta 999 -force if (1==1)" \
+    "Unknown task 999\\."
+
+# However, when the location spec doesn't start with '*' GDB relies on
+# the linespec parser to spot the keyword which marks the end of the
+# linespec, and this parser doesn't check for abbreviations.
+gdb_test "with breakpoint pending off -- break main t 999 if (1==1)" \
+    "Function \"main t 999\" not defined\\."
+gdb_test "with breakpoint pending off -- break main th 999 if (1==1)" \
+    "Function \"main th 999\" not defined\\."
+gdb_test "with breakpoint pending off -- break main ta 999 if (1==1)" \
+    "Function \"main ta 999\" not defined\\."
+
+# GDB does not treat a "-force-condition" flag that appears
+# immediately after the condition as the flag, but instead treats it
+# as " - force - condition", that is, subtraction of the symbol
+# "force" followed by subtraction of symbol "context".  This is really
+# just a quirk of how this used to be implemented, and should maybe be
+# changed in the future.  However, for now GDB retains this behaviour.
+gdb_test "break *main if (1==1) -force-condition" \
+    "No symbol \"force\" in current context\\."
 
 set test "run until breakpoint at marker3"
 gdb_test_multiple "continue" $test {
diff --git a/gdb/testsuite/gdb.base/pending.exp b/gdb/testsuite/gdb.base/pending.exp
index d7d3735000a..645f63bdb16 100644
--- a/gdb/testsuite/gdb.base/pending.exp
+++ b/gdb/testsuite/gdb.base/pending.exp
@@ -170,7 +170,8 @@ gdb_test "info break" \
 \[\t \]+stop only if k == 1.*
 \[\t \]+print k.*
 \[0-9\]+\[\t \]+breakpoint     keep y.* in main at .*$srcfile:$mainline.*
-\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc if x > 3.*" \
+\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc.*
+\\s+stop only if x > 3.*" \
 "multiple pending breakpoints"
 
 
@@ -195,8 +196,10 @@ gdb_test "info break" \
 \[\t \]+stop only if k == 1.*
 \[\t \]+print k.*
 \[0-9\]+\[\t \]+breakpoint     keep y.* in main at .*$srcfile:$mainline.*
-\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc if x > 3.*
-\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp3_loc.*ignore next 2 hits.*" \
+\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc.*
+\\s+stop only if x > 3.*
+\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp3_loc.*
+\\s+ignore next 2 hits.*" \
 "multiple pending breakpoints 2"
 
 #
@@ -267,3 +270,17 @@ gdb_test "info break" \
 \[0-9\]+\[\t \]+breakpoint     keep y.* in main at .*$srcfile:$mainline.*
 \[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*imaginary.*" \
 "verify pending breakpoint after restart"
+
+# Test GDB's parsing of pending breakpoint thread and condition.
+
+gdb_test_no_output "set breakpoint pending on"
+gdb_test "break foo if (unknown_var && another_unknown_var) thread 1" \
+    "Breakpoint $decimal \\(foo\\) pending\\."
+set bpnum [get_integer_valueof "\$bpnum" "*INVALID" \
+	       "get number for foo breakpoint"]
+gdb_test "info breakpoints $bpnum" \
+    [multi_line \
+	 "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	 "\\s+stop only if \\(unknown_var && another_unknown_var\\)" \
+	 "\\s+stop only in thread 1"] \
+    "check pending breakpoint on foo"
diff --git a/gdb/testsuite/gdb.linespec/explicit.exp b/gdb/testsuite/gdb.linespec/explicit.exp
index 668002d9038..8cbefe204ec 100644
--- a/gdb/testsuite/gdb.linespec/explicit.exp
+++ b/gdb/testsuite/gdb.linespec/explicit.exp
@@ -575,7 +575,7 @@ namespace eval $testfile {
 	      allow-pending]} {
 	fail "set $tst"
     } else {
-	gdb_test "info break" ".*PENDING.*myfunction if foofoofoo == 1.*" $tst
+	gdb_test "info break" ".*PENDING.*myfunction\r\n\\s+stop only if foofoofoo == 1.*" $tst
     }
 
     gdb_exit
@@ -586,7 +586,7 @@ namespace eval $testfile {
 	      allow-pending]} {
 	fail "set $tst"
     } else {
-	gdb_test "info break" ".*PENDING.*myfunction if arg == 0" $tst
+	gdb_test "info break" ".*PENDING.*myfunction\r\n\\s+stop only if arg == 0" $tst
 
 	gdb_load [standard_output_file $exefile]
 	gdb_test "info break" \
diff --git a/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp b/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp
index 28f52938aeb..bb9987a5572 100644
--- a/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp
+++ b/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp
@@ -50,7 +50,8 @@ set bp_location1 [gdb_get_line_number "set breakpoint 1 here"]
 # Set pending dprintf via MI.
 set bp [mi_make_breakpoint_pending -number "1" -type "dprintf" \
 	    -disp "keep" -enabled "y" -pending "pendfunc1" \
-	    -original-location "pendfunc1"]
+	    -original-location "pendfunc1" \
+	    -script {\["printf \\\"hello\\\""\]}]
 mi_gdb_test "-dprintf-insert -f pendfunc1 \"hello\"" \
     ".*\\^done,$bp" "mi set dprintf"
 
diff --git a/gdb/testsuite/gdb.multi/inferior-specific-bp.exp b/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
index 1f6573268da..b8aceabcad6 100644
--- a/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
+++ b/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
@@ -51,9 +51,9 @@ if {![runto_main]} {
 # this should fail.  Try with the keywords in both orders just in case the
 # parser has a bug.
 gdb_test "break foo thread 1.1 inferior 1" \
-    "You can specify only one of inferior or thread\\."
+    "You can specify only one of thread, inferior, or task\\."
 gdb_test "break foo inferior 1 thread 1.1" \
-    "You can specify only one of inferior or thread\\."
+    "You can specify only one of thread, inferior, or task\\."
 
 # Try to create a breakpoint using the 'inferior' keyword multiple times.
 gdb_test "break foo inferior 1 inferior 2" \
diff --git a/gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c b/gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
new file mode 100644
index 00000000000..15d1b9833dd
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
@@ -0,0 +1,22 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+int global_var = 0;
+
+void
+foo (int arg)
+{
+  global_var = arg;
+}
diff --git a/gdb/testsuite/gdb.threads/del-pending-thread-bp.c b/gdb/testsuite/gdb.threads/del-pending-thread-bp.c
new file mode 100644
index 00000000000..938e05bc4d7
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/del-pending-thread-bp.c
@@ -0,0 +1,85 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#include <dlfcn.h>
+#include <pthread.h>
+#include <stdlib.h>
+
+pthread_barrier_t barrier;
+
+static void
+barrier_wait (pthread_barrier_t *b)
+{
+  int res = pthread_barrier_wait (b);
+  if (res != 0 && res != PTHREAD_BARRIER_SERIAL_THREAD)
+    abort ();
+}
+
+static void *
+thread_worker (void *arg)
+{
+  barrier_wait (&barrier);
+  return NULL;
+}
+
+void
+breakpt ()
+{
+  /* Nothing.  */
+}
+
+int
+main (void)
+{
+  void *handle;
+  void (*func)(int);
+  pthread_t thread;
+
+  if (pthread_barrier_init (&barrier, NULL, 2) != 0)
+    abort ();
+
+  if (pthread_create (&thread, NULL, thread_worker, NULL) != 0)
+    abort ();
+
+  breakpt ();
+
+  /* Allow the worker thread to complete.  */
+  barrier_wait (&barrier);
+
+  if (pthread_join (thread, NULL) != 0)
+    abort ();
+
+  breakpt ();
+
+  /* Now load the shared library.  */
+  handle = dlopen (SHLIB_NAME, RTLD_LAZY);
+  if (handle == NULL)
+    abort ();
+
+  /* Find the function symbol.  */
+  func = (void (*)(int)) dlsym (handle, "foo");
+
+  /* Call the library function.  */
+  func (1);
+
+  /* Unload the shared library.  */
+  if (dlclose (handle) != 0)
+    abort ();
+
+  breakpt ();
+
+  return 0;
+}
+
diff --git a/gdb/testsuite/gdb.threads/del-pending-thread-bp.exp b/gdb/testsuite/gdb.threads/del-pending-thread-bp.exp
new file mode 100644
index 00000000000..4ed05eaa42d
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/del-pending-thread-bp.exp
@@ -0,0 +1,108 @@
+# Copyright 2023 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+# This test checks that pending thread-specific breakpoints are
+# correctly deleted when the thread the breakpoint is for goes out of
+# scope.
+#
+# We also check that we can't create a pending thread-specific
+# breakpoint for a non-existent thread.
+
+require allow_shlib_tests
+
+standard_testfile
+
+set libname $testfile-lib
+set srcfile_lib $srcdir/$subdir/$libname.c
+set binfile_lib [standard_output_file $libname.so]
+
+if { [gdb_compile_shlib $srcfile_lib $binfile_lib {}] != "" } {
+    untested "failed to compile shared library 1"
+    return -1
+}
+
+set binfile_lib_target [gdb_download_shlib $binfile_lib]
+
+if { [prepare_for_testing "failed to prepare" $testfile $srcfile \
+	  [list debug \
+	       additional_flags=-DSHLIB_NAME=\"$binfile_lib_target\" \
+	       shlib_load pthreads]] } {
+    return -1
+}
+
+gdb_locate_shlib $binfile_lib
+
+if ![runto_main] {
+    return 0
+}
+
+# Run until we have two threads.
+gdb_breakpoint "breakpt"
+gdb_continue_to_breakpoint "first breakpt call"
+
+# Confirm that we have a thread '2'.
+gdb_test "info threads" "\r\n\\s+2\\s+\[^\r\n\]+"
+
+# Create a pending, thread-specific, breakpoint on 'foo'.
+gdb_breakpoint "foo thread 2" allow-pending
+set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+	       "get breakpoint number"]
+
+# Check we can't create a pending thread-specific breakpoint for a
+# non-existent thread.
+gdb_test "with breakpoint pending on -- break foo thread 99" \
+    "Unknown thread 99\\."
+
+# Continue to 'breakpt' again.  Don't use gdb_continue_to_breakpoint
+# as we are looking for the thread exited and breakpoint deleted
+# messages.
+set output [list "Continuing\\."]
+
+if {!([target_info exists gdb_protocol]
+      && ([target_info gdb_protocol] == "remote"
+	  || [target_info gdb_protocol] == "extended-remote"))} {
+    # Due to bug PR gdb/30129 we don't see the thread exited messages
+    # for remote targets.  When this bit of this test can be cleaned
+    # up.
+    lappend output "\\\[Thread \[^\r\n\]+ exited\\\]"
+}
+
+lappend output "Thread-specific breakpoint $bpnum deleted - thread 2 no longer in the thread list\\." \
+    "" \
+    "Thread 1 \[^\r\n\]+, breakpt \\(\\) at \[^\r\n\]+" \
+    "$decimal\\s+\[^\r\n\]+"
+
+gdb_test "continue" \
+    [multi_line {*}$output] \
+    "second breakpt call"
+
+# Confirm breakpoint has been deleted.
+gdb_test "info breakpoints $bpnum" \
+    "No breakpoint or watchpoint matching '$bpnum'\\."
+
+# Continue again.  This will pass through 'foo'.  We should not stop
+# in 'foo', the breakpoint has been deleted.  We should next stop in
+# breakpt again.
+gdb_test "continue" \
+    [multi_line \
+	 "Continuing\\." \
+	 "" \
+	 "Thread 1 \[^\r\n\]+ hit Breakpoint $decimal, breakpt \\(\\) at \[^\r\n\]+" \
+	 "$decimal\\s+\[^\r\n\]+"] \
+    "third breakpt call"
+gdb_test "bt 1" \
+    [multi_line \
+	 "#0\\s+breakpt \\(\\) at \[^\r\n\]+" \
+	 "\\(More stack frames follow\\.\\.\\.\\)"]
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv6 07/10] gdb: don't set breakpoint::pspace for in create_breakpoint
  2023-12-02 10:42         ` [PATCHv6 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
                             ` (5 preceding siblings ...)
  2023-12-02 10:42           ` [PATCHv6 06/10] gdb: parse pending breakpoint thread/task immediately Andrew Burgess
@ 2023-12-02 10:42           ` Andrew Burgess
  2023-12-05 16:05             ` Aktemur, Tankut Baris
  2023-12-02 10:42           ` [PATCHv6 08/10] gdb: remove breakpoint_re_set_one Andrew Burgess
                             ` (3 subsequent siblings)
  10 siblings, 1 reply; 138+ messages in thread
From: Andrew Burgess @ 2023-12-02 10:42 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

While working on the previous commit, I ran into this code within
create_breakpoint:

  if ((type_wanted != bp_breakpoint
      && type_wanted != bp_hardware_breakpoint) || thread != -1)
   b->pspace = current_program_space;

this code is only executed when creating a pending breakpoint, and
sets the breakpoint::pspace member variable.

The above code gained the 'thread != -1' clause with this commit:

  commit cc72b2a2da6d6372cbdb1d14639a5fce84e1a325
  Date:   Fri Dec 23 17:06:16 2011 +0000

              Introduce gdb.FinishBreakpoint in Python

While the type_wanted checks were added with this commit:

  commit f8eba3c61629b3c03ac1f33853eab4d8507adb9c
  Date:   Tue Dec 6 18:54:43 2011 +0000

      the "ambiguous linespec" series

Before this breakpoint::pspace was set unconditionally.

If we look at how breakpoint::pspace is used today, some breakpoint
types specifically set this field, either in their constructors, or in
a wrapper function that calls the constructor.  So, the watchpoint
type and its sub-class set this variable, as does the catchpoint type,
and all it's sub-classes.

However, code_breakpoint doesn't specifically set this field within
its constructor, though some sub-classes of
code_breakpoint (ada_catchpoint, exception_catchpoint,
internal_breakpoint, and momentary_breakpoint) do set this field.

When I examine all the places that breakpoint::pspace is used, I
believe that in every place where it is expected that this field is
set, the breakpoint type will be one that specifically sets this
field.

Next, I observe two problems with the existing code.

First, the above code is only hit for pending breakpoints, there's no
equivalent code for non-pending breakpoints.  This opens up the
possibility of GDB entering non-consistent states; if a breakpoint is
first created pending and then later gets a location, the pspace field
will be set, while if the breakpoint is immediately non-pending, then
the pspace field will never be set.

Second, if we look at how breakpoint::pspace is used in the function
breakpoint_program_space_exit, we see that when a program space is
removed, any breakpoint with breakpoint::pspace set to the removed
program space, will be deleted.  This makes sense, but does mean we
need to ensure breakpoint::pspace is only set for breakpoints that
apply to a single program space.

So, if I create pending dprintf breakpoint (type bp_dprintf) then the
breakpoint::pspace variable will be set even though the dprintf is not
really tied to that one program space.  As a result, when the matching
program space is removed the dprintf is incorrectly removed.

Also, if I create a thread specific breakpoint, then, thanks to the
'thread != -1' clause the wrong program space will be stored in
breakpoint::pspace (the current program space is always used, which
might not be the program space that corresponds to the selected
thread), as a result, the thread specific breakpoint will be deleted
when the matching program space is removed.

If we look at commit cc72b2a2da6d which added the 'thread != -1'
clause, we can see this change was entirely redundant, the
breakpoint::pspace is also set in bpfinishpy_init after
create_breakpoint has been called.  As such, I think we can safely
drop the 'thread != -1' clause.

For the other problems, I'm proposing to be pretty aggressive - I'd
like to drop the breakpoint::pspace assignment completely from
create_breakpoint.  Having looked at how this variable is used, I
believe that it is already set elsewhere in all the cases that it is
needed.  Maybe this code was needed at one time, but I can't see how
it's needed any more.

There's tests to expose the issues I've spotted with this code, and
there's no regressions in testing.
---
 gdb/breakpoint.c                              |   3 -
 gdb/breakpoint.h                              |  18 +-
 .../gdb.multi/pending-bp-del-inferior.c       |  28 +++
 .../gdb.multi/pending-bp-del-inferior.exp     | 216 ++++++++++++++++++
 4 files changed, 259 insertions(+), 6 deletions(-)
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-del-inferior.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index e2cd4d360f2..bbf28d82558 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -9207,9 +9207,6 @@ create_breakpoint (struct gdbarch *gdbarch,
       b->disposition = tempflag ? disp_del : disp_donttouch;
       b->condition_not_parsed = 1;
       b->enable_state = enabled ? bp_enabled : bp_disabled;
-      if ((type_wanted != bp_breakpoint
-	   && type_wanted != bp_hardware_breakpoint) || thread != -1)
-	b->pspace = current_program_space;
 
       if (b->type == bp_dprintf)
 	update_dprintf_command_list (b.get ());
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index 95f98b59e41..2bf63b90072 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -823,9 +823,21 @@ struct breakpoint : public intrusive_list_node<breakpoint>
      equals this.  */
   struct frame_id frame_id = null_frame_id;
 
-  /* The program space used to set the breakpoint.  This is only set
-     for breakpoints which are specific to a program space; for
-     non-thread-specific ordinary breakpoints this is NULL.  */
+  /* The program space used to set the breakpoint.  This is only set for
+     breakpoints that are not type bp_breakpoint or bp_hardware_breakpoint.
+     For thread or inferior specific breakpoints, the breakpoints are
+     managed via the thread and inferior member variables.  */
+
+  /* If not nullptr then this is the program space for which this
+     breakpoint was created.  All watchpoint and catchpoint sub-types set
+     this field, but not all of the code_breakpoint sub-types do;
+     generally, user created breakpoint types don't set this field, though
+     things might be more consistent if they did.
+
+     When this variable is nullptr then a breakpoint might be associated
+     with multiple program spaces, though you need to check the thread,
+     inferior and task variables to see if a breakpoint was created for a
+     specific thread, inferior, or Ada task respectively.  */
   program_space *pspace = NULL;
 
   /* The location specification we used to set the breakpoint.  */
diff --git a/gdb/testsuite/gdb.multi/pending-bp-del-inferior.c b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.c
new file mode 100644
index 00000000000..51b6492085f
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.c
@@ -0,0 +1,28 @@
+/* This testcase is part of GDB, the GNU debugger.
+
+   Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+int
+foo ()
+{
+  return 0;
+}
+
+int
+main ()
+{
+  return foo ();
+}
diff --git a/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
new file mode 100644
index 00000000000..cb1f119ff94
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
@@ -0,0 +1,216 @@
+# Copyright 2023 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+# Setup two inferiors.  Select one inferior and create a pending
+# thread specific breakpoint in the other inferior.
+#
+# Delete the selected inferior (the one for which the thread specific
+# breakpoint doesn't apply), and check that the breakpoint still exists.
+#
+# Repeat this process, but this time, create an inferior specific
+# breakpoint.
+
+# The plain remote target can't do multiple inferiors.
+require !use_gdb_stub
+
+standard_testfile
+
+if {[prepare_for_testing "failed to prepare" $testfile $srcfile]} {
+    return -1
+}
+
+# Setup for the tests.  Create two inferiors, both running the global
+# BINFILE, and proceed to main in both inferiors.  Delete all
+# breakpoints, and check that we do have two threads.
+#
+# Return true after a successful setup, otherwise, return false.
+proc test_setup {} {
+    clean_restart $::binfile
+
+    if {![runto_main]} {
+	return 0
+    }
+
+    gdb_test "add-inferior -exec ${::binfile}" "Added inferior 2.*" \
+	"add inferior 2"
+    gdb_test "inferior 2" "Switching to inferior 2 .*" \
+	"select inferior 2"
+
+    if {![runto_main]} {
+	return 0
+    }
+
+    delete_breakpoints
+
+    gdb_test "info threads" \
+	[multi_line \
+	     "  Id\\s+Target Id\\s+Frame\\s*" \
+	     "  1\\.1\\s+\[^\r\n\]+" \
+	     "\\* 2\\.1\\s+\[^\r\n\]+"] \
+	"check we have the expected threads"
+
+    return 1
+}
+
+# Assuming inferior 2 is already selected, kill the current inferior
+# (inferior 2), selected inferior 1, and then remove inferior 2.
+proc kill_and_remove_inferior_2 {} {
+    gdb_test "kill" "" "kill inferior 2" \
+	"Kill the program being debugged.*y or n. $" "y"
+
+    gdb_test "inferior 1" "Switching to inferior 1 .*" \
+	"select inferior 1"
+
+    gdb_test_no_output "remove-inferiors 2"
+}
+
+# Setup two inferiors, then created a breakpoint.  If BP_PENDING is
+# true then the breakpoint will be pending, otherwise, the breakpoint
+# will be non-pending.
+#
+# BP_TYPE is either 'thread' or 'inferior', and indicates if the
+# created breakpoint should be thread or inferior specific.
+#
+# The breakpoint is created while inferior 2 is selected, and the
+# thread/inferior restriction always identifies inferior 1.
+#
+# Then inferior 2 is killed and removed.
+#
+# Finally, check that the breakpoint still exists and correctly refers
+# to inferior 1.
+proc do_bp_test { bp_type bp_pending } {
+    if {![test_setup]} {
+	return
+    }
+
+    if { $bp_pending } {
+	set bp_func "bar"
+    } else {
+	set bp_func "foo"
+    }
+
+    if { $bp_type eq "thread" } {
+	set bp_restriction "thread 1.1"
+    } else {
+	set bp_restriction "inferior 1"
+    }
+
+    gdb_breakpoint "$bp_func $bp_restriction" allow-pending
+    set bp_number [get_integer_valueof "\$bpnum" "INVALID" \
+		       "get b/p number for previous breakpoint"]
+
+    if { $bp_restriction eq "thread 1.1" } {
+	set bp_after_restriction "thread 1"
+    } else {
+	set bp_after_restriction $bp_restriction
+    }
+
+    if { $bp_pending } {
+	set bp_pattern_before \
+	    [multi_line \
+		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+${bp_func}" \
+		 "\\s+stop only in [string_to_regexp $bp_restriction]"]
+	set bp_pattern_after \
+	    [multi_line \
+		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+${bp_func}" \
+		 "\\s+stop only in [string_to_regexp $bp_after_restriction]"]
+    } else {
+	set bp_pattern_before \
+	    [multi_line \
+		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+<MULTIPLE>\\s*" \
+		 "\\s+stop only in [string_to_regexp $bp_restriction]" \
+		 "$bp_number\\.1\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 1" \
+		 "$bp_number\\.2\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 2"]
+
+	set bp_pattern_after \
+	    [multi_line \
+		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+" \
+		 "\\s+stop only in [string_to_regexp $bp_after_restriction]"]
+    }
+
+    gdb_test "info breakpoints" $bp_pattern_before \
+	"info breakpoints before inferior removal"
+
+    kill_and_remove_inferior_2
+
+    gdb_test "info breakpoints" $bp_pattern_after \
+	"info breakpoints after inferior removal"
+}
+
+# Setup two inferiors, then created a dprintf.  If BP_PENDING is
+# true then the dprintf will be pending, otherwise, the dprintf
+# will be non-pending.
+#
+# The dprintf is created while inferior 2.  Then inferior 2 is killed
+# and removed.
+#
+# Finally, check that the dprintf still exists.
+proc do_dprintf_test { bp_pending } {
+    if {![test_setup]} {
+	return
+    }
+
+    if { $bp_pending } {
+	set bp_func "bar"
+
+	gdb_test "dprintf $bp_func,\"in $bp_func\"" ".*" \
+	    "create dprintf breakpoint" \
+	    "Make dprintf pending on future shared library load\\? \\(y or .n.\\) $" "y"
+    } else {
+	set bp_func "foo"
+
+	gdb_test "dprintf $bp_func,\"in $bp_func\"" ".*" \
+	    "create dprintf breakpoint"
+    }
+
+    set bp_number [get_integer_valueof "\$bpnum" "INVALID" \
+		       "get b/p number for previous breakpoint"]
+
+    if { $bp_pending } {
+	set bp_pattern_before \
+	    [multi_line \
+		 "$bp_number\\s+dprintf\\s+keep\\s+y\\s+<PENDING>\\s+${bp_func}" \
+		 "\\s+printf \"in $bp_func\""]
+	set bp_pattern_after $bp_pattern_before
+    } else {
+	set bp_pattern_before \
+	    [multi_line \
+		 "$bp_number\\s+dprintf\\s+keep\\s+y\\s+<MULTIPLE>\\s*" \
+		 "\\s+printf \"in $bp_func\"" \
+		 "$bp_number\\.1\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 1" \
+		 "$bp_number\\.2\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 2"]
+
+	set bp_pattern_after \
+	    [multi_line \
+		 "$bp_number\\s+dprintf\\s+keep\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+" \
+		 "\\s+printf \"in $bp_func\""]
+    }
+
+    gdb_test "info breakpoints" $bp_pattern_before \
+	"info breakpoints before inferior removal"
+
+    kill_and_remove_inferior_2
+
+    gdb_test "info breakpoints" $bp_pattern_after \
+	"info breakpoints after inferior removal"
+}
+
+foreach_with_prefix bp_pending { true false } {
+    foreach_with_prefix bp_type { thread inferior } {
+	do_bp_test $bp_type $bp_pending
+    }
+
+    do_dprintf_test $bp_pending
+}
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv6 08/10] gdb: remove breakpoint_re_set_one
  2023-12-02 10:42         ` [PATCHv6 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
                             ` (6 preceding siblings ...)
  2023-12-02 10:42           ` [PATCHv6 07/10] gdb: don't set breakpoint::pspace for in create_breakpoint Andrew Burgess
@ 2023-12-02 10:42           ` Andrew Burgess
  2023-12-02 10:42           ` [PATCHv6 09/10] gdb: remove tracepoint_probe_create_sals_from_location_spec Andrew Burgess
                             ` (2 subsequent siblings)
  10 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-12-02 10:42 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

During a later patch I wanted to reset a single breakpoint, so I
called breakpoint_re_set_one.  However, this is not the right thing to
do.  If we look at breakpoint_re_set then we see that there's a whole
bunch of state that needs to be preserved prior to calling
breakpoint_re_set_one, and after calling breakpoint_re_set_one we
still need to call update_global_location_list.

I could just update the comment on breakpoint_re_set_one to make it
clearer how the function should be used -- or more likely to warn that
the function should only be used as a helper from breakpoint_re_set.

However, breakpoint_re_set_one is only 3 lines long.  So I figure it
might actually be easier to just fold breakpoint_re_set_one into
breakpoint_re_set, then there's no risk of accidentally calling
breakpoint_re_set_one when we shouldn't.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c | 26 ++++++++------------------
 1 file changed, 8 insertions(+), 18 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index bbf28d82558..7ca3377150d 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -13012,17 +13012,6 @@ create_sals_from_location_spec_default (location_spec *locspec,
   parse_breakpoint_sals (locspec, canonical);
 }
 
-/* Reset a breakpoint.  */
-
-static void
-breakpoint_re_set_one (breakpoint *b)
-{
-  input_radix = b->input_radix;
-  set_language (b->language);
-
-  b->re_set ();
-}
-
 /* Re-set breakpoint locations for the current program space.
    Locations bound to other program spaces are left untouched.  */
 
@@ -13034,12 +13023,11 @@ breakpoint_re_set (void)
     scoped_restore save_input_radix = make_scoped_restore (&input_radix);
     scoped_restore_current_pspace_and_thread restore_pspace_thread;
 
-    /* breakpoint_re_set_one sets the current_language to the language
-       of the breakpoint it is resetting (see prepare_re_set_context)
-       before re-evaluating the breakpoint's location.  This change can
-       unfortunately get undone by accident if the language_mode is set
-       to auto, and we either switch frames, or more likely in this context,
-       we select the current frame.
+    /* To ::re_set each breakpoint we set the current_language to the
+       language of the breakpoint before re-evaluating the breakpoint's
+       location.  This change can unfortunately get undone by accident if
+       the language_mode is set to auto, and we either switch frames, or
+       more likely in this context, we select the current frame.
 
        We prevent this by temporarily turning the language_mode to
        language_mode_manual.  We restore it once all breakpoints
@@ -13056,7 +13044,9 @@ breakpoint_re_set (void)
       {
 	try
 	  {
-	    breakpoint_re_set_one (&b);
+	    input_radix = b.input_radix;
+	    set_language (b.language);
+	    b.re_set ();
 	  }
 	catch (const gdb_exception &ex)
 	  {
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv6 09/10] gdb: remove tracepoint_probe_create_sals_from_location_spec
  2023-12-02 10:42         ` [PATCHv6 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
                             ` (7 preceding siblings ...)
  2023-12-02 10:42           ` [PATCHv6 08/10] gdb: remove breakpoint_re_set_one Andrew Burgess
@ 2023-12-02 10:42           ` Andrew Burgess
  2023-12-02 10:42           ` [PATCHv6 10/10] gdb: only insert thread-specific breakpoints in the relevant inferior Andrew Burgess
  2023-12-13 22:38           ` [PATCHv7 00/11] thread-specific breakpoints in just some inferiors Andrew Burgess
  10 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-12-02 10:42 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

The tracepoint_probe_create_sals_from_location_spec function just
forwards all its arguments to
bkpt_probe_create_sals_from_location_spec, and is only used in one
place.

Lets delete tracepoint_probe_create_sals_from_location_spec and
replace it with bkpt_probe_create_sals_from_location_spec.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c | 19 +++----------------
 1 file changed, 3 insertions(+), 16 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 7ca3377150d..7590cd7248c 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -284,9 +284,6 @@ static bool strace_marker_p (struct breakpoint *b);
 static void bkpt_probe_create_sals_from_location_spec
      (location_spec *locspec,
       struct linespec_result *canonical);
-static void tracepoint_probe_create_sals_from_location_spec
-     (location_spec *locspec,
-      struct linespec_result *canonical);
 
 const struct breakpoint_ops code_breakpoint_ops =
 {
@@ -301,10 +298,11 @@ static const struct breakpoint_ops bkpt_probe_breakpoint_ops =
   create_breakpoints_sal,
 };
 
-/* Tracepoints set on probes.  */
+/* Tracepoints set on probes.  We use the same methods as for breakpoints
+   on probes.  */
 static const struct breakpoint_ops tracepoint_probe_breakpoint_ops =
 {
-  tracepoint_probe_create_sals_from_location_spec,
+  bkpt_probe_create_sals_from_location_spec,
   create_breakpoints_sal,
 };
 
@@ -12218,17 +12216,6 @@ tracepoint::print_recreate (struct ui_file *fp) const
     gdb_printf (fp, "  passcount %d\n", pass_count);
 }
 
-/* Virtual table for tracepoints on static probes.  */
-
-static void
-tracepoint_probe_create_sals_from_location_spec
-  (location_spec *locspec,
-   struct linespec_result *canonical)
-{
-  /* We use the same method for breakpoint on probes.  */
-  bkpt_probe_create_sals_from_location_spec (locspec, canonical);
-}
-
 void
 dprintf_breakpoint::re_set ()
 {
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv6 10/10] gdb: only insert thread-specific breakpoints in the relevant inferior
  2023-12-02 10:42         ` [PATCHv6 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
                             ` (8 preceding siblings ...)
  2023-12-02 10:42           ` [PATCHv6 09/10] gdb: remove tracepoint_probe_create_sals_from_location_spec Andrew Burgess
@ 2023-12-02 10:42           ` Andrew Burgess
  2023-12-13 22:38           ` [PATCHv7 00/11] thread-specific breakpoints in just some inferiors Andrew Burgess
  10 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-12-02 10:42 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Eli Zaretskii

Eli has already approved the NEWS changes in this commit.

---

This commit updates GDB so that thread or inferior specific
breakpoints are only inserted into the program space in which the
specific thread or inferior is running.

In terms of implementation, getting this basically working is easy
enough, now that a breakpoint's thread or inferior field is setup
prior to GDB looking for locations, we can easily use this information
to find a suitable program_space and pass this to as a filter when
creating the sals.

Or we could if breakpoint_ops::create_sals_from_location_spec allowed
us to pass in a filter program_space.

So, this commit extends breakpoint_ops::create_sals_from_location_spec
to take a program_space argument, and uses this to filter the set of
returned sals.  This accounts for about half the change in this patch.

The second set of changes starts from breakpoint_set_thread and
breakpoint_set_inferior, this is called when the thread or inferior
for a breakpoint changes, e.g. from the Python API.

Previously this call would never result in the locations of a
breakpoint changing, after all, locations were inserted in every
program space, and we just use the thread or inferior variable to
decide when we should stop.  Now though, changing a breakpoint's
thread or inferior can mean we need to figure out a new set of
breakpoint locations.

To support this I've added a new breakpoint_re_set_one function, which
is like breakpoint_re_set, but takes a single breakpoint, and just
updates the locations for that one breakpoint.  We only need to call
this function if the program_space in which a breakpoint's thread (or
inferior) is running actually changes.  If the program_space does
change then we call the new breakpoint_re_set_one function passing in
the program_space which should be used to filter the new locations (or
nullptr to indicate we should set locations in all program spaces).
This filter program_space needs to propagate down to all the re_set
methods, this accounts for the remaining half of the changes in this
patch.

There were a couple of existing tests that created thread or inferior
specific breakpoints and then checked the 'info breakpoints' output,
these needed updating.  These were:

  gdb.mi/user-selected-context-sync.exp
  gdb.multi/bp-thread-specific.exp
  gdb.multi/multi-target-continue.exp
  gdb.multi/multi-target-ping-pong-next.exp
  gdb.multi/tids.exp
  gdb.mi/new-ui-bp-deleted.exp
  gdb.multi/inferior-specific-bp.exp
  gdb.multi/pending-bp-del-inferior.exp

I've also added some additional tests to:

  gdb.multi/pending-bp.exp

I've updated the documentation and added a NEWS entry.

Reviewed-By: Eli Zaretskii <eliz@gnu.org>
---
 gdb/NEWS                                      |   7 +
 gdb/ada-lang.c                                |   6 +-
 gdb/break-catch-throw.c                       |   6 +-
 gdb/breakpoint.c                              | 280 ++++++++++++++----
 gdb/breakpoint.h                              |  29 +-
 gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp    |   8 +-
 .../gdb.mi/user-selected-context-sync.exp     |   4 +-
 .../gdb.multi/bp-thread-specific.exp          |   7 +-
 .../gdb.multi/inferior-specific-bp.exp        |  12 +-
 .../gdb.multi/multi-target-continue.exp       |   2 +-
 .../gdb.multi/multi-target-ping-pong-next.exp |   4 +-
 .../gdb.multi/pending-bp-del-inferior.exp     |   6 +-
 gdb/testsuite/gdb.multi/pending-bp.exp        | 206 +++++++++++++
 gdb/testsuite/gdb.multi/tids.exp              |   6 +-
 14 files changed, 484 insertions(+), 99 deletions(-)

diff --git a/gdb/NEWS b/gdb/NEWS
index a3cbd34f1d0..b2cf70b2c64 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -13,6 +13,13 @@
   'thread' or 'task' keywords are parsed at the time the breakpoint is
   created, rather than at the time the breakpoint becomes non-pending.
 
+* Thread-specific breakpoints are only inserted into the program space
+  in which the thread of interest is running.  In most cases program
+  spaces are unique for each inferior, so this means that
+  thread-specific breakpoints will usually only be inserted for the
+  inferior containing the thread of interest.  The breakpoint will
+  be hit no less than before.
+
 * Changed commands
 
 disassemble
diff --git a/gdb/ada-lang.c b/gdb/ada-lang.c
index ff7222c7eed..a2bf42a5703 100644
--- a/gdb/ada-lang.c
+++ b/gdb/ada-lang.c
@@ -12079,11 +12079,11 @@ struct ada_catchpoint : public code_breakpoint
     enable_state = enabled ? bp_enabled : bp_disabled;
     language = language_ada;
 
-    re_set ();
+    re_set (pspace);
   }
 
   struct bp_location *allocate_location () override;
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   void check_status (struct bpstat *bs) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   bool print_one (const bp_location **) const override;
@@ -12128,7 +12128,7 @@ static struct symtab_and_line ada_exception_sal
    catchpoint kinds.  */
 
 void
-ada_catchpoint::re_set ()
+ada_catchpoint::re_set (program_space *pspace)
 {
   std::vector<symtab_and_line> sals;
   try
diff --git a/gdb/break-catch-throw.c b/gdb/break-catch-throw.c
index 47d534c5ee8..e661d1624e8 100644
--- a/gdb/break-catch-throw.c
+++ b/gdb/break-catch-throw.c
@@ -82,10 +82,10 @@ struct exception_catchpoint : public code_breakpoint
 				     _("invalid type-matching regexp")))
   {
     pspace = current_program_space;
-    re_set ();
+    re_set (pspace);
   }
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   bool print_one (const bp_location **) const override;
   void print_mention () const override;
@@ -198,7 +198,7 @@ exception_catchpoint::check_status (struct bpstat *bs)
 /* Implement the 're_set' method.  */
 
 void
-exception_catchpoint::re_set ()
+exception_catchpoint::re_set (program_space *pspace)
 {
   std::vector<symtab_and_line> sals;
   struct program_space *filter_pspace = current_program_space;
diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 7590cd7248c..0fd48b4cde9 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -91,9 +91,12 @@
 static void map_breakpoint_numbers (const char *,
 				    gdb::function_view<void (breakpoint *)>);
 
-static void
-  create_sals_from_location_spec_default (location_spec *locspec,
-					  linespec_result *canonical);
+static void parse_breakpoint_sals (location_spec *locspec,
+				   linespec_result *canonical,
+				   program_space *search_pspace);
+
+static void breakpoint_re_set_one (breakpoint *b,
+				   program_space *filter_pspace);
 
 static void create_breakpoints_sal (struct gdbarch *,
 				    struct linespec_result *,
@@ -283,11 +286,12 @@ static bool strace_marker_p (struct breakpoint *b);
 
 static void bkpt_probe_create_sals_from_location_spec
      (location_spec *locspec,
-      struct linespec_result *canonical);
+      struct linespec_result *canonical,
+      struct program_space *search_pspace);
 
 const struct breakpoint_ops code_breakpoint_ops =
 {
-  create_sals_from_location_spec_default,
+  parse_breakpoint_sals,
   create_breakpoints_sal,
 };
 
@@ -352,7 +356,7 @@ struct internal_breakpoint : public code_breakpoint
     disposition = disp_donttouch;
   }
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   void check_status (struct bpstat *bs) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   void print_mention () const override;
@@ -389,7 +393,7 @@ struct momentary_breakpoint : public code_breakpoint
     gdb_assert (inferior == -1);
   }
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   void check_status (struct bpstat *bs) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   void print_mention () const override;
@@ -400,7 +404,7 @@ struct dprintf_breakpoint : public ordinary_breakpoint
 {
   using ordinary_breakpoint::ordinary_breakpoint;
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   int breakpoint_hit (const struct bp_location *bl,
 		      const address_space *aspace,
 		      CORE_ADDR bp_addr,
@@ -1554,7 +1558,36 @@ breakpoint_set_thread (struct breakpoint *b, int thread)
   int old_thread = b->thread;
   b->thread = thread;
   if (old_thread != thread)
-    notify_breakpoint_modified (b);
+    {
+      /* If THREAD is in a different program_space than OLD_THREAD, or the
+	 breakpoint has switched to or from being thread-specific, then we
+	 need to re-set the locations of this breakpoint.  First, figure
+	 out the program_space for the old and new threads, use a value of
+	 nullptr to indicate the breakpoint is in all program spaces.  */
+      program_space *old_pspace = nullptr;
+      if (old_thread != -1)
+	{
+	  struct thread_info *thr = find_thread_global_id (old_thread);
+	  gdb_assert (thr != nullptr);
+	  old_pspace = thr->inf->pspace;
+	}
+
+      program_space *new_pspace = nullptr;
+      if (thread != -1)
+	{
+	  struct thread_info *thr = find_thread_global_id (thread);
+	  gdb_assert (thr != nullptr);
+	  new_pspace = thr->inf->pspace;
+	}
+
+      /* If the program space has changed for this breakpoint, then
+	 re-evaluate it's locations.  */
+      if (old_pspace != new_pspace)
+	breakpoint_re_set_one (b, new_pspace);
+
+      /* Let others know the breakpoint has changed.  */
+      notify_breakpoint_modified (b);
+    }
 }
 
 /* See breakpoint.h.  */
@@ -1573,7 +1606,34 @@ breakpoint_set_inferior (struct breakpoint *b, int inferior)
   int old_inferior = b->inferior;
   b->inferior = inferior;
   if (old_inferior != inferior)
-    notify_breakpoint_modified (b);
+    {
+      /* If INFERIOR is in a different program_space than OLD_INFERIOR, or
+	 the breakpoint has switch to or from inferior-specific, then we
+	 need to re-set the locations of this breakpoint.  First, figure
+	 out the program_space for the old and new inferiors, use a value
+	 of nullptr to indicate the breakpoint is in all program
+	 spaces.  */
+      program_space *old_pspace = nullptr;
+      if (old_inferior != -1)
+	{
+	  struct inferior *inf = find_inferior_id (old_inferior);
+	  gdb_assert (inf != nullptr);
+	  old_pspace = inf->pspace;
+	}
+
+      program_space *new_pspace = nullptr;
+      if (inferior != -1)
+	{
+	  struct inferior *inf = find_inferior_id (inferior);
+	  gdb_assert (inf != nullptr);
+	  new_pspace = inf->pspace;
+	}
+
+      if (old_pspace != new_pspace)
+	breakpoint_re_set_one (b, new_pspace);
+
+      notify_breakpoint_modified (b);
+    }
 }
 
 /* See breakpoint.h.  */
@@ -8814,7 +8874,8 @@ create_breakpoints_sal (struct gdbarch *gdbarch,
 
 static void
 parse_breakpoint_sals (location_spec *locspec,
-		       struct linespec_result *canonical)
+		       struct linespec_result *canonical,
+		       struct program_space *search_pspace)
 {
   struct symtab_and_line cursal;
 
@@ -8878,7 +8939,7 @@ parse_breakpoint_sals (location_spec *locspec,
 	      && strchr ("+-", spec[0]) != NULL
 	      && spec[1] != '['))
 	{
-	  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, NULL,
+	  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, search_pspace,
 			    get_last_displayed_symtab (),
 			    get_last_displayed_line (),
 			    canonical, NULL, NULL);
@@ -8886,7 +8947,7 @@ parse_breakpoint_sals (location_spec *locspec,
 	}
     }
 
-  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, NULL,
+  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, search_pspace,
 		    cursal.symtab, cursal.line, canonical, NULL, NULL);
 }
 
@@ -8985,6 +9046,39 @@ breakpoint_ops_for_location_spec_type (enum location_spec_type locspec_type,
     }
 }
 
+/* Return the program space to use as a filter when searching for locations
+   of a breakpoint specific to THREAD or INFERIOR.  If THREAD and INFERIOR
+   are both -1, meaning all threads/inferiors, then this function returns
+   nullptr, indicating no program space filtering should be performed.
+   Otherwise, this function returns the program space for the inferior that
+   contains THREAD (when THREAD is not -1), or the program space for
+   INFERIOR (when INFERIOR is not -1).  */
+
+static struct program_space *
+find_program_space_for_breakpoint (int thread, int inferior)
+{
+  if (thread != -1)
+    {
+      gdb_assert (inferior == -1);
+
+      struct thread_info *thr = find_thread_global_id (thread);
+      gdb_assert (thr != nullptr);
+      gdb_assert (thr->inf != nullptr);
+      return thr->inf->pspace;
+    }
+  else if (inferior != -1)
+    {
+      gdb_assert (thread == -1);
+
+      struct inferior *inf = find_inferior_id (inferior);
+      gdb_assert (inf != nullptr);
+
+      return inf->pspace;
+    }
+
+  return nullptr;
+}
+
 /* See breakpoint.h.  */
 
 const struct breakpoint_ops *
@@ -9087,7 +9181,10 @@ create_breakpoint (struct gdbarch *gdbarch,
 
   try
     {
-      ops->create_sals_from_location_spec (locspec, &canonical);
+      struct program_space *search_pspace
+	= find_program_space_for_breakpoint (thread, inferior);
+      ops->create_sals_from_location_spec (locspec, &canonical,
+					   search_pspace);
     }
   catch (const gdb_exception_error &e)
     {
@@ -9560,7 +9657,7 @@ break_range_command (const char *arg, int from_tty)
   arg_start = arg;
   location_spec_up start_locspec
     = string_to_location_spec (&arg, current_language);
-  parse_breakpoint_sals (start_locspec.get (), &canonical_start);
+  parse_breakpoint_sals (start_locspec.get (), &canonical_start, nullptr);
 
   if (arg[0] != ',')
     error (_("Too few arguments."));
@@ -9661,7 +9758,7 @@ watchpoint_exp_is_const (const struct expression *exp)
 /* Implement the "re_set" method for watchpoints.  */
 
 void
-watchpoint::re_set ()
+watchpoint::re_set (struct program_space *pspace)
 {
   /* Watchpoint can be either on expression using entirely global
      variables, or it can be on local variables.
@@ -11772,7 +11869,7 @@ breakpoint::print_recreate (struct ui_file *fp) const
 /* Default breakpoint_ops methods.  */
 
 void
-code_breakpoint::re_set ()
+code_breakpoint::re_set (struct program_space *pspace)
 {
   /* FIXME: is this still reachable?  */
   if (breakpoint_location_spec_empty_p (this))
@@ -11782,7 +11879,7 @@ code_breakpoint::re_set ()
       return;
     }
 
-  re_set_default ();
+  re_set_default (pspace);
 }
 
 int
@@ -11988,7 +12085,7 @@ code_breakpoint::decode_location_spec (location_spec *locspec,
 /* Virtual table for internal breakpoints.  */
 
 void
-internal_breakpoint::re_set ()
+internal_breakpoint::re_set (struct program_space *pspace)
 {
   switch (type)
     {
@@ -12081,7 +12178,7 @@ internal_breakpoint::print_mention () const
 /* Virtual table for momentary breakpoints  */
 
 void
-momentary_breakpoint::re_set ()
+momentary_breakpoint::re_set (struct program_space *pspace)
 {
   /* Keep temporary breakpoints, which can be encountered when we step
      over a dlopen call and solib_add is resetting the breakpoints.
@@ -12122,12 +12219,13 @@ longjmp_breakpoint::~longjmp_breakpoint ()
 
 static void
 bkpt_probe_create_sals_from_location_spec (location_spec *locspec,
-					   struct linespec_result *canonical)
+					   struct linespec_result *canonical,
+					   struct program_space *search_pspace)
 
 {
   struct linespec_sals lsal;
 
-  lsal.sals = parse_probes (locspec, NULL, canonical);
+  lsal.sals = parse_probes (locspec, search_pspace, canonical);
   lsal.canonical = xstrdup (canonical->locspec->to_string ());
   canonical->lsals.push_back (std::move (lsal));
 }
@@ -12217,9 +12315,9 @@ tracepoint::print_recreate (struct ui_file *fp) const
 }
 
 void
-dprintf_breakpoint::re_set ()
+dprintf_breakpoint::re_set (struct program_space *pspace)
 {
-  re_set_default ();
+  re_set_default (pspace);
 
   /* extra_string should never be non-NULL for dprintf.  */
   gdb_assert (extra_string != NULL);
@@ -12277,8 +12375,10 @@ dprintf_breakpoint::after_condition_true (struct bpstat *bs)
    markers (`-m').  */
 
 static void
-strace_marker_create_sals_from_location_spec (location_spec *locspec,
-					      struct linespec_result *canonical)
+strace_marker_create_sals_from_location_spec
+	(location_spec *locspec,
+	 struct linespec_result *canonical,
+	 struct program_space *search_pspace)
 {
   struct linespec_sals lsal;
   const char *arg_start, *arg;
@@ -12794,12 +12894,32 @@ update_breakpoint_locations (code_breakpoint *b,
      all locations are in the same shared library, that was unloaded.
      We'd like to retain the location, so that when the library is
      loaded again, we don't loose the enabled/disabled status of the
-     individual locations.  */
+     individual locations.
+
+     Thread specific breakpoints will also trigger this case if the thread
+     is changed to a different program space, and all of the old locations
+     go out of scope.  In this case we do (currently) discard the old
+     locations -- we assume the change in thread is permanent and the old
+     locations will never come back into scope.  */
   if (all_locations_are_pending (b, filter_pspace) && sals.empty ())
-    return;
+    {
+      if (b->thread != -1)
+	b->clear_locations ();
+      return;
+    }
 
   bp_location_list existing_locations = b->steal_locations (filter_pspace);
 
+  /* If this is a thread-specific breakpoint then any locations left on the
+     breakpoint are for a program space in which the thread of interest
+     does not operate.  This can happen when the user changes the thread of
+     a thread-specific breakpoint.
+
+     We assume that the change in thread is permanent, and that the old
+     locations will never be used again, so discard them now.  */
+  if (b->thread != -1)
+    b->clear_locations ();
+
   for (const auto &sal : sals)
     {
       struct bp_location *new_loc;
@@ -12965,40 +13085,45 @@ code_breakpoint::location_spec_to_sals (location_spec *locspec,
    locations.  */
 
 void
-code_breakpoint::re_set_default ()
+code_breakpoint::re_set_default (struct program_space *filter_pspace)
 {
-  struct program_space *filter_pspace = current_program_space;
   std::vector<symtab_and_line> expanded, expanded_end;
 
-  int found;
-  std::vector<symtab_and_line> sals = location_spec_to_sals (locspec.get (),
-							     filter_pspace,
-							     &found);
-  if (found)
-    expanded = std::move (sals);
-
-  if (locspec_range_end != nullptr)
-    {
-      std::vector<symtab_and_line> sals_end
-	= location_spec_to_sals (locspec_range_end.get (),
-				 filter_pspace, &found);
+  /* If this breakpoint is thread-specific then find the program space in
+     which the specific thread exists.  Otherwise, for breakpoints that are
+     not thread-specific THREAD_PSPACE will be nullptr.  */
+  program_space *bp_pspace
+    = find_program_space_for_breakpoint (this->thread, this->inferior);
+
+  /* If this is not a thread or inferior specific breakpoint, or it is a
+     thread or inferior specific breakpoint but we are looking for new
+     locations in the program space that the specific thread or inferior is
+     running, then look for new locations for this breakpoint.  */
+  if (bp_pspace == nullptr || filter_pspace == bp_pspace)
+    {
+      int found;
+      std::vector<symtab_and_line> sals
+	= location_spec_to_sals (locspec.get (), filter_pspace, &found);
       if (found)
-	expanded_end = std::move (sals_end);
+	expanded = std::move (sals);
+
+      if (locspec_range_end != nullptr)
+	{
+	  std::vector<symtab_and_line> sals_end
+	    = location_spec_to_sals (locspec_range_end.get (),
+				     filter_pspace, &found);
+	  if (found)
+	    expanded_end = std::move (sals_end);
+	}
     }
 
+  /* Update the locations for this breakpoint.  For thread-specific
+     breakpoints this will remove any old locations that are for the wrong
+     program space -- this can happen if the user changes the thread of a
+     thread-specific breakpoint.  */
   update_breakpoint_locations (this, filter_pspace, expanded, expanded_end);
 }
 
-/* Default method for creating SALs from an address string.  It basically
-   calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
-
-static void
-create_sals_from_location_spec_default (location_spec *locspec,
-					struct linespec_result *canonical)
-{
-  parse_breakpoint_sals (locspec, canonical);
-}
-
 /* Re-set breakpoint locations for the current program space.
    Locations bound to other program spaces are left untouched.  */
 
@@ -13033,7 +13158,7 @@ breakpoint_re_set (void)
 	  {
 	    input_radix = b.input_radix;
 	    set_language (b.language);
-	    b.re_set ();
+	    b.re_set (current_program_space);
 	  }
 	catch (const gdb_exception &ex)
 	  {
@@ -13054,6 +13179,53 @@ breakpoint_re_set (void)
   /* Now we can insert.  */
   update_global_location_list (UGLL_MAY_INSERT);
 }
+
+/* Re-set locations for breakpoint B in FILTER_PSPACE.  If FILTER_PSPACE is
+   nullptr then re-set locations for B in all program spaces.  Locations
+   bound to program spaces other than FILTER_PSPACE are left untouched.  */
+
+static void
+breakpoint_re_set_one (breakpoint *b, program_space *filter_pspace)
+{
+  {
+    scoped_restore_current_language save_language;
+    scoped_restore save_input_radix = make_scoped_restore (&input_radix);
+    scoped_restore_current_pspace_and_thread restore_pspace_thread;
+
+    /* To ::re_set each breakpoint we set the current_language to the
+       language of the breakpoint before re-evaluating the breakpoint's
+       location.  This change can unfortunately get undone by accident if
+       the language_mode is set to auto, and we either switch frames, or
+       more likely in this context, we select the current frame.
+
+       We prevent this by temporarily turning the language_mode to
+       language_mode_manual.  We restore it once all breakpoints
+       have been reset.  */
+    scoped_restore save_language_mode = make_scoped_restore (&language_mode);
+    language_mode = language_mode_manual;
+
+    /* Note: we must not try to insert locations until after all
+       breakpoints have been re-set.  Otherwise, e.g., when re-setting
+       breakpoint 1, we'd insert the locations of breakpoint 2, which
+       hadn't been re-set yet, and thus may have stale locations.  */
+
+    try
+      {
+	input_radix = b->input_radix;
+	set_language (b->language);
+	b->re_set (filter_pspace);
+      }
+    catch (const gdb_exception &ex)
+      {
+	exception_fprintf (gdb_stderr, ex,
+			   "Error in re-setting breakpoint %d: ",
+			   b->number);
+      }
+  }
+
+  /* Now we can insert.  */
+  update_global_location_list (UGLL_MAY_INSERT);
+}
 \f
 /* Reset the thread number of this breakpoint:
 
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index 2bf63b90072..a48a9fe81fd 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -562,15 +562,15 @@ enum print_stop_action
 
 struct breakpoint_ops
 {
-  /* Create SALs from location spec, storing the result in
-     linespec_result.
-
-     For an explanation about the arguments, see the function
-     `create_sals_from_location_spec_default'.
+  /* Create SALs from LOCSPEC, storing the result in linespec_result
+     CANONICAL.  If SEARCH_PSPACE is not nullptr then only results in the
+     corresponding program space are returned.  If SEARCH_PSPACE is nullptr
+     then results for all program spaces are returned.
 
      This function is called inside `create_breakpoint'.  */
   void (*create_sals_from_location_spec) (location_spec *locspec,
-					  struct linespec_result *canonical);
+					  linespec_result *canonical,
+					  program_space *search_pspace);
 
   /* This method will be responsible for creating a breakpoint given its SALs.
      Usually, it just calls `create_breakpoints_sal' (for ordinary
@@ -702,8 +702,15 @@ struct breakpoint : public intrusive_list_node<breakpoint>
 
   /* Reevaluate a breakpoint.  This is necessary after symbols change
      (e.g., an executable or DSO was loaded, or the inferior just
-     started).  */
-  virtual void re_set ()
+     started).
+
+     If not nullptr, then FILTER_PSPACE is the program space in which
+     symbols may have changed, we only need to add new locations in
+     FILTER_PSPACE.
+
+     If FILTER_PSPACE is nullptr then all program spaces may have changed,
+     new locations need to be searched for in every program space.  */
+  virtual void re_set (program_space *filter_pspace)
   {
     /* Nothing to re-set.  */
   }
@@ -947,7 +954,7 @@ struct code_breakpoint : public breakpoint
   /* Add a location for SAL to this breakpoint.  */
   bp_location *add_location (const symtab_and_line &sal);
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   int insert_location (struct bp_location *) override;
   int remove_location (struct bp_location *,
 		       enum remove_bp_reason reason) override;
@@ -969,7 +976,7 @@ struct code_breakpoint : public breakpoint
      struct program_space *search_pspace);
 
   /* Helper method that does the basic work of re_set.  */
-  void re_set_default ();
+  void re_set_default (program_space *pspace);
 
   /* Find the SaL locations corresponding to the given LOCATION.
      On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
@@ -991,7 +998,7 @@ struct watchpoint : public breakpoint
 {
   using breakpoint::breakpoint;
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   int insert_location (struct bp_location *) override;
   int remove_location (struct bp_location *,
 		       enum remove_bp_reason reason) override;
diff --git a/gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp b/gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp
index 57e69ef6240..3afc1787026 100644
--- a/gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp
+++ b/gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp
@@ -76,8 +76,12 @@ foreach_mi_ui_mode mode {
     set loc2 [make_bp_loc "$::decimal\\.2"]
 
     # Create the inferior-specific breakpoint.
-    mi_create_breakpoint_multi "-g i2 foo" "create breakpoint in inferior 2" \
-	-inferior "2" -locations "\\\[$loc1,$loc2\\\]"
+    mi_create_breakpoint "-g i2 foo" "create breakpoint in inferior 2" \
+	-number "$decimal" \
+	-type "breakpoint" \
+	-enabled "y" \
+	-func "foo" \
+	-inferior "2"
     set bpnum [mi_get_valueof "/d" "\$bpnum" "INVALID"]
 
     if {$mode eq "separate"} {
diff --git a/gdb/testsuite/gdb.mi/user-selected-context-sync.exp b/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
index 4889c31aff3..b39745bdf17 100644
--- a/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
+++ b/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
@@ -370,7 +370,7 @@ proc test_continue_to_start { mode inf } {
 			    "thread $inf.2 stops MI"
 		    } else {
 			mi_expect_stop "breakpoint-hit" "child_sub_function" \
-			    "" "$srcfile" "$decimal" {"" "disp=\"del\"" "locno=\"[0-9]+\""} \
+			    "" "$srcfile" "$decimal" {"" "disp=\"del\""} \
 			    "thread $inf.2 stops MI"
 		    }
 		}
@@ -439,7 +439,7 @@ proc_with_prefix test_setup { mode } {
 
 	with_spawn_id $mi_spawn_id {
 	    mi_expect_stop "breakpoint-hit" "main" "" "$srcfile" "$decimal" \
-		{"" "disp=\"del\"" "locno=\"[0-9]+\""} "main stop"
+		{"" "disp=\"del\""} "main stop"
 	}
 
 	# Consume CLI output.
diff --git a/gdb/testsuite/gdb.multi/bp-thread-specific.exp b/gdb/testsuite/gdb.multi/bp-thread-specific.exp
index 85c08f44a2c..68001e92044 100644
--- a/gdb/testsuite/gdb.multi/bp-thread-specific.exp
+++ b/gdb/testsuite/gdb.multi/bp-thread-specific.exp
@@ -50,7 +50,7 @@ gdb_test "info threads" \
 # locations ('foo' in both inferiors) even though only one of those
 # locations will ever trigger ('foo' in inferior 2).
 gdb_test "break foo thread 2.1" \
-    "Breakpoint $decimal at $hex: foo\\. \\(2 locations\\)"
+    "Breakpoint $decimal at $hex: file \[^\r\n\]+$srcfile, line $decimal\\."
 
 set bpnum [get_integer_valueof "\$bpnum" "INVALID"]
 
@@ -58,10 +58,7 @@ set bpnum [get_integer_valueof "\$bpnum" "INVALID"]
 # earlier breakpoint.  Check that the thread-id used when describing
 # the earlier breakpoints is correct.
 gdb_test "break foo thread 1.1" \
-    [multi_line \
-	 "Note: breakpoint $bpnum \\(thread 2.1\\) also set at pc $hex\\." \
-	 "Note: breakpoint $bpnum \\(thread 2.1\\) also set at pc $hex\\." \
-	 "Breakpoint $decimal at $hex: foo\\. \\(2 locations\\)"]
+    "Breakpoint $decimal at $hex: file \[^\r\n\]+$srcfile, line $decimal\\."
 
 # Save the breakpoints into a file.
 if {[is_remote host]} {
diff --git a/gdb/testsuite/gdb.multi/inferior-specific-bp.exp b/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
index b8aceabcad6..dda167dd39f 100644
--- a/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
+++ b/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
@@ -105,16 +105,8 @@ proc check_info_breakpoints { testname bp_number expected_loc_count } {
 # Create an inferior-specific breakpoint.  Use gdb_test instead of
 # gdb_breakpoint here as we want to check the breakpoint was placed in
 # multiple locations.
-#
-# Currently GDB still places inferior specific breakpoints into every
-# inferior, just like it does with thread specific breakpoints.
-# Hopefully this will change in the future, at which point, this test
-# will need updating.
-#
-# Two of these locations are in inferior 1, while the third is in
-# inferior 2.
 gdb_test "break foo inferior 1" \
-    "Breakpoint $decimal at $hex: foo\\. \\(3 locations\\)"
+    "Breakpoint $decimal at $hex: foo\\. \\(2 locations\\)"
 set bp_number [get_integer_valueof "\$bpnum" "INVALID" \
 		  "get b/p number for inferior specific breakpoint"]
 
@@ -123,7 +115,7 @@ set location_count 0
 set saw_inf_cond false
 
 check_info_breakpoints "first check for inferior specific breakpoint" \
-    $bp_number 3
+    $bp_number 2
 
 # Create a multi-inferior breakpoint to stop at.
 gdb_breakpoint "stop_breakpt" message
diff --git a/gdb/testsuite/gdb.multi/multi-target-continue.exp b/gdb/testsuite/gdb.multi/multi-target-continue.exp
index bf19cc00968..a1bffb7b613 100644
--- a/gdb/testsuite/gdb.multi/multi-target-continue.exp
+++ b/gdb/testsuite/gdb.multi/multi-target-continue.exp
@@ -30,7 +30,7 @@ proc test_continue {non-stop} {
 
     proc set_break {inf} {
 	gdb_test "break function${inf} thread ${inf}.1" \
-	"Breakpoint .* function${inf}\\..*"
+	    "Breakpoint ${::decimal} at ${::hex}: file .*, line ${::decimal}\\."
     }
 
     # Select inferior INF, and then run to a breakpoint on inferior
diff --git a/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp b/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp
index 64645b8ec8a..51fd70b018a 100644
--- a/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp
+++ b/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp
@@ -52,12 +52,12 @@ proc test_ping_pong_next {} {
     gdb_test "thread 1.1" "Switching to thread 1.1 .*"
 
     gdb_test "break $srcfile:$line1 thread 1.1" \
-	"Breakpoint .*$srcfile:$line1\\..*"
+	"Breakpoint .*$srcfile, line $line1\\."
 
     gdb_test "continue" "hit Breakpoint .*"
 
     gdb_test "break $srcfile:$line2 thread 2.1" \
-	"Breakpoint .*$srcfile:$line2\\..*"
+	"Breakpoint .*$srcfile, line $line2\\."
 
     # Now block inferior 1 and issue "next".  We should stop at the
     # breakpoint for inferior 2, given schedlock off.
diff --git a/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
index cb1f119ff94..897d4a1cf52 100644
--- a/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
+++ b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
@@ -129,10 +129,8 @@ proc do_bp_test { bp_type bp_pending } {
     } else {
 	set bp_pattern_before \
 	    [multi_line \
-		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+<MULTIPLE>\\s*" \
-		 "\\s+stop only in [string_to_regexp $bp_restriction]" \
-		 "$bp_number\\.1\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 1" \
-		 "$bp_number\\.2\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 2"]
+		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 1" \
+		 "\\s+stop only in [string_to_regexp $bp_restriction]"]
 
 	set bp_pattern_after \
 	    [multi_line \
diff --git a/gdb/testsuite/gdb.multi/pending-bp.exp b/gdb/testsuite/gdb.multi/pending-bp.exp
index e4f0aa2e38a..16803488a7f 100644
--- a/gdb/testsuite/gdb.multi/pending-bp.exp
+++ b/gdb/testsuite/gdb.multi/pending-bp.exp
@@ -78,6 +78,48 @@ proc do_test_setup { inf_1_stop inf_2_stop } {
     return true
 }
 
+# Create a breakpoint on the function 'foo' in THREAD.  It is expected
+# that the breakpoint created will be pending, this is checked by
+# running the 'info breakpoints' command.
+#
+# Returns the number for the newly created breakpoint.
+proc do_create_pending_foo_breakpoint { {thread "1.1"} } {
+    gdb_test "break foo thread $thread" \
+	[multi_line \
+	     "Function \"foo\" not defined\\." \
+	     "Breakpoint $::decimal \\(foo\\) pending\."] \
+	"set pending thread-specific breakpoint"
+    set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+		   "get number for thread-specific breakpoint on foo"]
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	     "\\s+stop only in thread [string_to_regexp $thread]"] \
+	"check thread-specific breakpoint is initially pending"
+
+    return $bpnum
+}
+
+# Create a breakpoint on the function 'foo' in THREAD.  It is expected
+# that the breakpoint created will not be pending, this is checked by
+# running the 'info breakpoints' command.
+#
+# Returns the number for the newly created breakpoint.
+proc do_create_foo_breakpoint { {thread "1.1"} } {
+    gdb_test "break foo thread $thread" \
+	"Breakpoint $::decimal at $::hex" \
+	"set thread-specific breakpoint"
+    set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+		   "get number for thread-specific breakpoint on foo"]
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex\\s+<foo\[^>\]*> inf $::decimal" \
+	     "\\s+stop only in thread [string_to_regexp $thread]"] \
+	"check thread-specific breakpoint is initially pending"
+
+    return $bpnum
+}
+
 # Check that when a breakpoint is in the pending state, but that breakpoint
 # does have some locations (those locations themselves are pending), GDB
 # doesn't display the inferior list in the 'info breakpoints' output.
@@ -126,5 +168,169 @@ proc_with_prefix test_no_inf_display {} {
 	"check info breakpoints while breakpoint is pending"
 }
 
+# Setup two inferiors.  In #1 the symbol 'foo' has not yet been
+# loaded, while in #2 the symbol 'foo' has been loaded.
+#
+# Create a thread-specific breakpoint on 'foo' tied to a thread in
+# inferior #1, the breakpoint should be pending -- 'foo' is not yet
+# loaded in #1.
+#
+# Now move inferior #1 forward until 'foo' is loaded, check the
+# breakpoint is no longer pending.
+#
+# Move inferior #1 forward more until 'foo' is unloaded, check that
+# the breakpoint returns to the pending state.
+proc_with_prefix test_pending_toggle { } {
+
+    do_test_setup "Break before open" "Break before close"
+
+    set bpnum [do_create_pending_foo_breakpoint]
+
+    # Now return to inferior 1 and continue until the shared library is
+    # loaded, the breakpoint should become non-pending.
+    gdb_test "inferior 1" "Switching to inferior 1 .*" \
+	"switch back to inferior 1"
+    gdb_continue_to_breakpoint "stop in foo in inferior 1" "foo \\(\\) .*"
+
+    gdb_test "info breakpoint $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex <foo\[^>\]*> inf 1" \
+	     "\\s+stop only in thread 1\\.1" \
+	     "\\s+breakpoint already hit 1 time"] \
+	"check thread-specific breakpoint is no longer pending"
+
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "close library"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	     "\\s+stop only in thread 1\\.1" \
+	     "\\s+breakpoint already hit 1 time"] \
+	"check thread-specific breakpoint is pending again"
+}
+
+# Create a Python variable VAR and set it to the gdb.Breakpoint object
+# corresponding to the breakpoint numbered BPNUM.  If THREAD is not
+# the empty string then THREAD should be an integer, check that
+# gdb.Breakpoint.thread is set to the value of THREAD.  Otherwise, if
+# THREAD is the empty string, check that gdb.Breakpoint.thread is set
+# to None.
+proc py_find_breakpoint { var bpnum {thread ""} } {
+    gdb_test_no_output \
+	"python ${var}=\[b for b in gdb.breakpoints() if b.number == $bpnum\]\[0\]" \
+	"find Python gdb.Breakpoint object"
+    if { $thread ne "" } {
+	gdb_test_no_output "python assert(${var}.thread == ${thread})" \
+	    "check thread attribute is currently correct"
+    } else {
+	gdb_test_no_output "python assert(${var}.thread is None)" \
+	    "check thread attribute is currently correct"
+    }
+}
+
+# Setup two inferiors.  In #1 the symbol 'foo' has not yet been
+# loaded, while in #2 the symbol 'foo' has been loaded.
+#
+# Create a thread-specific breakpoint on 'foo' tied to a thread in
+# inferior #1, the breakpoint should be pending -- 'foo' is not yet
+# loaded in #1.
+#
+# Use Python to change the thread of the thread-specific breakpoint to
+# a thread in inferior #2, at this point the thread should gain a
+# location and become non-pending.
+#
+# Set the thread back to a thread in inferior #1, the breakpoint
+# should return to the pending state.
+proc_with_prefix py_test_toggle_thread {} {
+    do_test_setup "Break before open" "Break after open"
+
+    set bpnum [do_create_pending_foo_breakpoint]
+
+    py_find_breakpoint "bp" $bpnum 1
+
+    gdb_test_no_output "python bp.thread = 2" \
+	"change thread on thread-specific breakpoint"
+    gdb_test "info breakpoint $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex <foo\[^>\]*> inf 2" \
+	     "\\s+stop only in thread 2\\.1"] \
+	"check thread-specific breakpoint now has a location"
+
+    gdb_test_no_output "set call_count = 2" "set call_count in inferior 2"
+    gdb_continue_to_breakpoint "stop at foo in inferior 2" "foo \\(\\) .*"
+
+    gdb_test_no_output "python bp.thread = 1" \
+	"restore thread on thread-specific breakpoint"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	     "\\s+stop only in thread 1\\.1" \
+	     "\\s+breakpoint already hit 1 time"] \
+	"check thread-specific breakpoint has returned to pending"
+
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "stop after close in inferior 2" \
+	".* Break after close\\. .*"
+
+    gdb_test "inferior 1" "Switching to inferior 1 .*" \
+	"switch to inferior 1"
+    gdb_continue_to_breakpoint "stop at foo in inferior 1" "foo \\(\\) .*"
+}
+
+# Setup two inferiors.  Both inferiors have the symbol 'foo'
+# available.
+#
+# Create a thread-specific breakpoint on 'foo' tied to a thread in
+# inferior #1, the breakpoint should not be pending, but will only
+# have a single location, the location in inferior #1.
+#
+# Use Python to change the thread of the thread-specific breakpoint to
+# None.  At this point the breakpoint should gain a second location, a
+# location in inferior #2.
+proc_with_prefix py_test_clear_thread {} {
+    do_test_setup "Break after open" "Break after open"
+
+    set bpnum [do_create_foo_breakpoint]
+
+    py_find_breakpoint "bp" $bpnum 1
+
+    gdb_test_no_output "python bp.thread = None" \
+	"clear thread on thread-specific breakpoint"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "${bpnum}\\s+breakpoint\\s+keep y\\s+<MULTIPLE>\\s*" \
+	     "${bpnum}\\.1\\s+y\\s+${::hex}\\s+<foo\[^>\]*> inf $::decimal" \
+	     "${bpnum}\\.2\\s+y\\s+${::hex}\\s+<foo\[^>\]*> inf $::decimal"] \
+	"check for a location in both inferiors"
+
+    gdb_continue_to_breakpoint "stop at foo in inferior 2" "foo \\(\\) .*"
+    gdb_test_no_output "set call_count = 2" "set call_count in inferior 2"
+
+    gdb_test "inferior 1" "Switching to inferior 1 .*" \
+	"switch to inferior 1"
+    gdb_continue_to_breakpoint "stop at foo in inferior 1" "foo \\(\\) .*"
+    gdb_test_no_output "set call_count = 2" "set call_count in inferior 1"
+
+    gdb_test_no_output "python bp.thread = 2"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "${bpnum}\\s+breakpoint\\s+keep y\\s+${::hex}\\s+<foo\[^>\]*> inf 2" \
+	     "\\s+stop only in thread 2\\.1" \
+	     "\\s+breakpoint already hit 2 times"] \
+	"check for a location only in inferior 2"
+
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "stop after close in inferior 1" \
+	".* Break after close\\. .*"
+
+    gdb_test "inferior 2" "Switching to inferior 2 .*" \
+	"switch back to inferior 2"
+    gdb_continue_to_breakpoint "stop at foo again in inferior 2" \
+	"foo \\(\\) .*"
+}
+
 # Run all the tests.
 test_no_inf_display
+test_pending_toggle
+py_test_toggle_thread
+py_test_clear_thread
diff --git a/gdb/testsuite/gdb.multi/tids.exp b/gdb/testsuite/gdb.multi/tids.exp
index 18fc4970fe7..34c270309de 100644
--- a/gdb/testsuite/gdb.multi/tids.exp
+++ b/gdb/testsuite/gdb.multi/tids.exp
@@ -433,11 +433,13 @@ if { [allow_python_tests] } {
 
 	gdb_py_test_silent_cmd "python bp = gdb.breakpoints()\[0\]" \
 	    "get python breakpoint" 0
-	gdb_test "python bp.thread = 6" "thread = 6" \
+	gdb_test_no_output "python bp.thread = 6" \
 	    "make breakpoint thread-specific with python"
 	# Check that the inferior-qualified ID is correct.
 	gdb_test "info breakpoint" \
-	    "stop only in thread 1.3\r\n.*" \
+	    [multi_line \
+		 "$decimal\\s+\[^\r\n\]+ in thread_function1 at \[^\r\n\]+" \
+		 "\\s+stop only in thread 1\\.3"] \
 	    "thread specific breakpoint right thread"
     }
 }
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* RE: [PATCHv6 01/10] gdb: create_breakpoint: add asserts and additional comments
  2023-12-02 10:42           ` [PATCHv6 01/10] gdb: create_breakpoint: add asserts and additional comments Andrew Burgess
@ 2023-12-04 19:21             ` Aktemur, Tankut Baris
  0 siblings, 0 replies; 138+ messages in thread
From: Aktemur, Tankut Baris @ 2023-12-04 19:21 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

On Saturday, December 2, 2023 11:42 AM, Andrew Burgess wrote:
> This commit extends the asserts on create_breakpoint (in the header
> file), and adds some additional assertions into the definition.
> 
> The new assert confirms that when the thread and inferior information
> is going to be parsed from the extra_string, then the thread and
> inferior arguments should be -1.  That is, the caller of
> create_breakpoint should not try to create a thread/inferior specific
> breakpoint by *both* specifying thread/inferior *and* asking to parse
> the extra_string, it's one or the other.
> 
> There should be no user visible changes after this commit.
> ---
>  gdb/breakpoint.c |  6 ++++++
>  gdb/breakpoint.h | 16 ++++++++++++++++
>  2 files changed, 22 insertions(+)
> 
> diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
> index 699919e32b3..dd415ff42f0 100644
> --- a/gdb/breakpoint.c
> +++ b/gdb/breakpoint.c
> @@ -9228,6 +9228,12 @@ create_breakpoint (struct gdbarch *gdbarch,
>    gdb_assert (inferior == -1 || inferior > 0);
>    gdb_assert (thread == -1 || inferior == -1);
> 
> +  /* If PARSE_EXTRA is true then the thread and inferior details will be
> +     parsed from  the EXTRA_STRING, the THREAD and INFERIOR arguments
                   ^^^
Redundant space.

-Baris


Intel Deutschland GmbH
Registered Address: Am Campeon 10, 85579 Neubiberg, Germany
Tel: +49 89 99 8853-0, www.intel.de <http://www.intel.de>
Managing Directors: Christin Eisenschmid, Sharon Heck, Tiffany Doon Silva  
Chairperson of the Supervisory Board: Nicole Lau
Registered Office: Munich
Commercial Register: Amtsgericht Muenchen HRB 186928


^ permalink raw reply	[flat|nested] 138+ messages in thread

* RE: [PATCHv6 02/10] gdb: create_breakpoint: asserts relating to extra_string/parse_extra
  2023-12-02 10:42           ` [PATCHv6 02/10] gdb: create_breakpoint: asserts relating to extra_string/parse_extra Andrew Burgess
@ 2023-12-04 19:40             ` Aktemur, Tankut Baris
  0 siblings, 0 replies; 138+ messages in thread
From: Aktemur, Tankut Baris @ 2023-12-04 19:40 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

On Saturday, December 2, 2023 11:42 AM, Andrew Burgess wrote:
> The goal of this commit is to better define the API for
> create_breakpoint especially around the use of extra_string and
> parse_extra.  This will be useful in the next commit when I plan to
> make some changes to create_breakpoint.
> 
> This commit makes one possibly breaking change: until this commit it
> was possible to create thread-specific dprintf breakpoint like this:
> 
>   (gdb) dprintf call_me, thread 1 "%s", "hello"
>   Dprintf 2 at 0x401152: file /tmp/hello.c, line 8.
>   (gdb) info breakpoints
>   Num     Type           Disp Enb Address            What
>   2       dprintf        keep y   0x0000000000401152 in call_me at /tmp/hello.c:8 thread 1
>           stop only in thread 1
>           printf "%s", "hello"
>   (gdb)
> 
> this feature of dprintf was not documented, was not tested, and is

this -> This

> slightly different in syntax to how we create thread specific
> breakpoints and/or watchpoints -- the thread condition appears after
> the first ','.
> 
> I believe that this worked at all was simply by luck.  We happen to
> pass the parse_extra flag as true from dprintf_command to
> create_breakpoint.
> 
> So in this commit I made the choice change this.  We now pass
> parse_extra as false from dprintf_command to create_breakpoint.  With
> this done it is assumed that the only thing in the extra_string is the
> dprintf format and arguments.
> 
> Beyond this change I've updated the comment on create_breakpoint in
> breakpoint.h, and I've then added some asserts into
> create_breakpoint as well as moving around some of the error
> handling.
> 
>  - We now assert on the incoming argument values,
> 
>  - I've moved an error check to sit after the call to
>    find_condition_and_thread_for_sals, this ensures the extra_string
>    was parsed correctly,
> 
> In dprintf_command:
> 
>  - We now throw an error if there is no format string after the
>    dprintf location.  This error was already being thrown, but was
>    being caught later in the process.  With this change we catch the
>    missing string earlier,
> 
>  - And, as mentioned earlier, we pass parse_extra as false when
>    calling create_breakpoint,
> 
> In create_tracepoint_from_upload:
> 
>  - We now throw an error if the parsed location doesn't completely
>    consume the addr_str variable.  This error has now effectively
>    moved out of create_breakpoint.
> ---
>  gdb/breakpoint.c | 42 +++++++++++++++++++++++++++++-------------
>  gdb/breakpoint.h | 44 +++++++++++++++++++++++++++-----------------
>  2 files changed, 56 insertions(+), 30 deletions(-)
> 
> diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
> index dd415ff42f0..bd28236ce7d 100644
> --- a/gdb/breakpoint.c
> +++ b/gdb/breakpoint.c
> @@ -9240,6 +9240,17 @@ create_breakpoint (struct gdbarch *gdbarch,
>    if (extra_string != NULL && *extra_string == '\0')
>      extra_string = NULL;
> 
> +  /* A bp_dprintf must always have an accompanying EXTRA_STRING containing
> +     the dprintf format and arguments -- PARSE_EXTRA should always be false
> +     in this case.
> +
> +     For all other breakpoint types, EXTRA_STRING should be nullptr unless
> +     PARSE_EXTRA is true.  */
> +  gdb_assert ((type_wanted == bp_dprintf
> +	       && extra_string != nullptr && !parse_extra)
> +	      || (type_wanted != bp_dprintf
> +		  && (extra_string == nullptr || parse_extra)));
> +

This could be a personal taste, but I'd find it easier to read if
it was written 

  if (type_wanted == bp_dprintf)
    gdb_assert ((extra_string != nullptr) && !parse_extra);
  else
    gdb_assert ((extra_string == nullptr) || parse_extra);

or

  gdb_assert ((type_wanted == bp_dprintf)
		 ? (extra_string != nullptr) && !parse_extra
		 : (extra_string == nullptr) || parse_extra));

Thanks
-Baris



Intel Deutschland GmbH
Registered Address: Am Campeon 10, 85579 Neubiberg, Germany
Tel: +49 89 99 8853-0, www.intel.de <http://www.intel.de>
Managing Directors: Christin Eisenschmid, Sharon Heck, Tiffany Doon Silva  
Chairperson of the Supervisory Board: Nicole Lau
Registered Office: Munich
Commercial Register: Amtsgericht Muenchen HRB 186928


^ permalink raw reply	[flat|nested] 138+ messages in thread

* RE: [PATCHv6 04/10] gdb: build dprintf commands just once in code_breakpoint constructor
  2023-12-02 10:42           ` [PATCHv6 04/10] gdb: build dprintf commands just once in code_breakpoint constructor Andrew Burgess
@ 2023-12-05  8:17             ` Aktemur, Tankut Baris
  0 siblings, 0 replies; 138+ messages in thread
From: Aktemur, Tankut Baris @ 2023-12-05  8:17 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

On Saturday, December 2, 2023 11:42 AM, Andrew Burgess wrote:
> I noticed in code_breakpoint::code_breakpoint that we are calling
> update_dprintf_command_list once for each breakpoint location, when we
> really only need to call this once per breakpoint -- the data updated
> by this function, the breakpoint command list -- is per breakpoint,
> not per breakpoint location.  Calling update_dprintf_command_list
> multiple times is just wasted effort, there's no per location error
> checking, we don't even pass the current location to the function.
> 
> This commit moves the update_dprintf_command_list call outside of the
> per-location loop. I have also changes the 'if' that handles the case
> where the extra_string (which holds the format/args) is empty.  I
> don't believe that this situation can ever arise -- and if it does we
> should be catching it earlier and throwing an error at that point.
> 
> There should be no user visible changes after this commit.
> ---
>  gdb/breakpoint.c | 20 +++++++++-----------
>  1 file changed, 9 insertions(+), 11 deletions(-)
> 
> diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
> index c629d27c4c0..c1440a6921f 100644
> --- a/gdb/breakpoint.c
> +++ b/gdb/breakpoint.c
> @@ -8704,19 +8704,17 @@ code_breakpoint::code_breakpoint (struct gdbarch *gdbarch_,
>        /* Do not set breakpoint locations conditions yet.  As locations
>  	 are inserted, they get sorted based on their addresses.  Let
>  	 the list stabilize to have reliable location numbers.  */
> +    }
> 
> -      /* Dynamic printf requires and uses additional arguments on the
> -	 command line, otherwise it's an error.  */
> -      if (type == bp_dprintf)
> -	{
> -	  if (extra_string != nullptr)
> -	    update_dprintf_command_list (this);
> -	  else
> -	    error (_("Format string required"));
> -	}
> -      else if (extra_string != nullptr)
> -	error (_("Garbage '%s' at end of command"), extra_string.get ());
> +  /* Dynamic printf requires and uses additional arguments on the
> +     command line, otherwise it's an error.  */
> +  if (type == bp_dprintf)
> +    {
> +      gdb_assert (extra_string != nullptr);
> +      update_dprintf_command_list (this);

In Patch 3, a gdb_assert was added inside update_dprintf_command_list.  I also
noticed that in dprintf_breakpoint::re_set, we have

  /* extra_string should never be non-NULL for dprintf.  */
  gdb_assert (extra_string != NULL);

  /* 1 - connect to target 1, that can run breakpoint commands.
     2 - create a dprintf, which resolves fine.
     3 - disconnect from target 1
     4 - connect to target 2, that can NOT run breakpoint commands.

     After steps #3/#4, you'll want the dprintf command list to
     be updated, because target 1 and 2 may well return different
     answers for target_can_run_breakpoint_commands().
     Given absence of finer grained resetting, we get to do
     it all the time.  */
  if (extra_string != NULL)
    update_dprintf_command_list (this);

So, I wonder if it wouldn't be simpler to have the assert in
update_dprintf_command_list only and remove the asserts and if-checks
from the call sites.

Thanks
-Baris


Intel Deutschland GmbH
Registered Address: Am Campeon 10, 85579 Neubiberg, Germany
Tel: +49 89 99 8853-0, www.intel.de <http://www.intel.de>
Managing Directors: Christin Eisenschmid, Sharon Heck, Tiffany Doon Silva  
Chairperson of the Supervisory Board: Nicole Lau
Registered Office: Munich
Commercial Register: Amtsgericht Muenchen HRB 186928


^ permalink raw reply	[flat|nested] 138+ messages in thread

* RE: [PATCHv6 05/10] gdb: don't display inferior list for pending breakpoints
  2023-12-02 10:42           ` [PATCHv6 05/10] gdb: don't display inferior list for pending breakpoints Andrew Burgess
@ 2023-12-05  8:35             ` Aktemur, Tankut Baris
  0 siblings, 0 replies; 138+ messages in thread
From: Aktemur, Tankut Baris @ 2023-12-05  8:35 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

On Saturday, December 2, 2023 11:42 AM, Andrew Burgess wrote:
> I noticed that in the 'info breakpoints' output, GDB sometimes prints
> the inferior list for pending breakpoints, this doesn't seem right to
> me.  A pending breakpoint has no locations (at least, as far as we
> display things in the 'info breakpoints' output), so including an
> inferior list seems odd.
> 
> Here's what I see right now:
> 
>   (gdb) info breakpoint 5
>   Num     Type           Disp Enb Address            What
>   5       breakpoint     keep y   <PENDING>          foo inf 1
>   (gdb)
> 
> It's the 'inf 1' at the end of the line that I'm objecting too.
> 
> To trigger this behaviour we need to be in a multi-inferior debug
> session.  The breakpoint must have been non-pending at some point in
> the past, and so have a location assigned to it.
> 
> The breakpoint becomes pending again as a result of a shared library
> being unloaded.  When this happens the location itself is marked
> pending (via bp_location::shlib_disabled).
> 
> In print_one_breakpoint_location, in order to print the inferior list
> we check that the breakpoint has a location, and that we have multiple
> inferiors, but we don't check if the location itself is pending.
> 
> This commit adds that check, which means the output is now:
> 
>   (gdb) info breakpoint 5
>   Num     Type           Disp Enb Address            What
>   5       breakpoint     keep y   <PENDING>          foo
>   (gdb)
> 
> Which I think makes more sense -- indeed, the format without the
> inferior list is what we display for a pending breakpoint that has
> never had any locations assigned, so I think this change in behaviour
> makes GDB more consistent.
> ---
>  gdb/breakpoint.c                         |   2 +-
>  gdb/testsuite/gdb.multi/pending-bp-lib.c |  22 ++++
>  gdb/testsuite/gdb.multi/pending-bp.c     |  66 ++++++++++++
>  gdb/testsuite/gdb.multi/pending-bp.exp   | 130 +++++++++++++++++++++++
>  4 files changed, 219 insertions(+), 1 deletion(-)
>  create mode 100644 gdb/testsuite/gdb.multi/pending-bp-lib.c
>  create mode 100644 gdb/testsuite/gdb.multi/pending-bp.c
>  create mode 100644 gdb/testsuite/gdb.multi/pending-bp.exp
> 
> diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
> index c1440a6921f..3ee23af83d6 100644
> --- a/gdb/breakpoint.c
> +++ b/gdb/breakpoint.c
> @@ -6597,7 +6597,7 @@ print_one_breakpoint_location (struct breakpoint *b,
>  	}
>      }
> 
> -  if (loc != NULL && !header_of_multiple)
> +  if (loc != NULL && !header_of_multiple && !loc->shlib_disabled)

Since you're touching the line, would you consider turning NULL
into nullptr?

>      {
>        std::vector<int> inf_nums;
>        int mi_only = 1;
> diff --git a/gdb/testsuite/gdb.multi/pending-bp-lib.c b/gdb/testsuite/gdb.multi/pending-bp-
> lib.c
> new file mode 100644
> index 00000000000..15d1b9833dd
> --- /dev/null
> +++ b/gdb/testsuite/gdb.multi/pending-bp-lib.c
> @@ -0,0 +1,22 @@
> +/* Copyright 2023 Free Software Foundation, Inc.
> +
> +   This program is free software; you can redistribute it and/or modify
> +   it under the terms of the GNU General Public License as published by
> +   the Free Software Foundation; either version 3 of the License, or
> +   (at your option) any later version.
> +
> +   This program is distributed in the hope that it will be useful,
> +   but WITHOUT ANY WARRANTY; without even the implied warranty of
> +   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
> +   GNU General Public License for more details.
> +
> +   You should have received a copy of the GNU General Public License
> +   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
> +
> +int global_var = 0;
> +
> +void
> +foo (int arg)
> +{
> +  global_var = arg;
> +}
> diff --git a/gdb/testsuite/gdb.multi/pending-bp.c b/gdb/testsuite/gdb.multi/pending-bp.c
> new file mode 100644
> index 00000000000..ca8a3c20b72
> --- /dev/null
> +++ b/gdb/testsuite/gdb.multi/pending-bp.c
> @@ -0,0 +1,66 @@
> +/* Copyright 2023 Free Software Foundation, Inc.
> +
> +   This program is free software; you can redistribute it and/or modify
> +   it under the terms of the GNU General Public License as published by
> +   the Free Software Foundation; either version 3 of the License, or
> +   (at your option) any later version.
> +
> +   This program is distributed in the hope that it will be useful,
> +   but WITHOUT ANY WARRANTY; without even the implied warranty of
> +   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
> +   GNU General Public License for more details.
> +
> +   You should have received a copy of the GNU General Public License
> +   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
> +
> +#include <dlfcn.h>
> +#include <stdlib.h>
> +
> +void
> +breakpt ()
> +{
> +  /* Nothing.  */
> +}
> +
> +volatile int global_counter = 0;
> +
> +volatile int call_count = 1;
> +
> +int
> +main (void)
> +{
> +  void *handle;
> +  void (*func)(int);
> +
> +  /* Some filler work so that we don't initially stop on the breakpt call
> +     below.  */
> +  ++global_counter;
> +
> +  breakpt ();	/* Break before open.  */
> +
> +  /* Now load the shared library.  */
> +  handle = dlopen (SHLIB_NAME, RTLD_LAZY);
> +  if (handle == NULL)
> +    abort ();
> +
> +  breakpt ();	/* Break after open.  */
> +
> +  /* Find the function symbol.  */
> +  func = (void (*)(int)) dlsym (handle, "foo");
> +
> +  for (; call_count > 0; --call_count)
> +    {
> +      /* Call the library function.  */
> +      func (1);
> +    }
> +
> +  breakpt ();	/* Break before close.  */
> +
> +  /* Unload the shared library.  */
> +  if (dlclose (handle) != 0)
> +    abort ();
> +
> +  breakpt ();	/* Break after close.  */
> +
> +  return 0;
> +}
> diff --git a/gdb/testsuite/gdb.multi/pending-bp.exp b/gdb/testsuite/gdb.multi/pending-bp.exp
> new file mode 100644
> index 00000000000..e4f0aa2e38a
> --- /dev/null
> +++ b/gdb/testsuite/gdb.multi/pending-bp.exp
> @@ -0,0 +1,130 @@
> +# Copyright 2023 Free Software Foundation, Inc.
> +
> +# This program is free software; you can redistribute it and/or modify
> +# it under the terms of the GNU General Public License as published by
> +# the Free Software Foundation; either version 3 of the License, or
> +# (at your option) any later version.
> +#
> +# This program is distributed in the hope that it will be useful,
> +# but WITHOUT ANY WARRANTY; without even the implied warranty of
> +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
> +# GNU General Public License for more details.
> +#
> +# You should have received a copy of the GNU General Public License
> +# along with this program.  If not, see <http://www.gnu.org/licenses/>.
> +
> +# Tests related to pending breakpoints in a multi-inferior environment.
> +
> +require allow_shlib_tests !use_gdb_stub
> +
> +standard_testfile
> +
> +set libname $testfile-lib
> +set srcfile_lib $srcdir/$subdir/$libname.c
> +set binfile_lib [standard_output_file $libname.so]
> +
> +if { [gdb_compile_shlib $srcfile_lib $binfile_lib {}] != "" } {
> +    untested "failed to compile shared library 1"
> +    return -1
> +}
> +
> +set binfile_lib_target [gdb_download_shlib $binfile_lib]
> +
> +if { [build_executable "failed to prepare" $testfile $srcfile \
> +	  [list debug \
> +	       additional_flags=-DSHLIB_NAME=\"$binfile_lib_target\" \
> +	       shlib_load pthreads]] } {

Is pthreads needed?

> +    return -1
> +}
> +
> +# Used to override delete_breakpoints when we don't want breakpoints
> +# deleted.
> +proc do_nothing {} {}
> +
> +# Start two inferiors, both running the same test binary.  The arguments
> +# INF_1_STOP and INF_2_STOP are source code patterns that are passed to
> +# gdb_get_line_number to figure out where each inferior should be stopped.
> +#
> +# This proc does a clean_restart and leaves inferior 2 selected.  Also the
> +# 'breakpoint pending' flag is enabled, so pending breakpoints can be created
> +# without GDB prompting the user.
> +proc do_test_setup { inf_1_stop inf_2_stop } {
> +    clean_restart ${::binfile}
> +
> +    gdb_locate_shlib $::binfile_lib
> +
> +    if ![runto_main] {

Braces can be added for consistency with the other if-statements.

> +	return false
> +    }
> +
> +    gdb_breakpoint [gdb_get_line_number ${inf_1_stop}] temporary
> +    gdb_continue_to_breakpoint "move inferior 1 into position"
> +
> +    gdb_test "add-inferior -exec ${::binfile}" \
> +	"Added inferior 2.*" "add inferior 2"
> +    gdb_test "inferior 2" "Switching to inferior 2 .*" "switch to inferior 2"
> +
> +    with_override delete_breakpoints do_nothing {

I'm not sure why this is needed.  The BP at inf_1_stop was already
defined temporary.  Is there any breakpoint left that we want to retain?

> +	if {![runto_main]} {
> +	    return false
> +	}
> +    }
> +
> +    gdb_breakpoint [gdb_get_line_number ${inf_2_stop}] temporary
> +    gdb_continue_to_breakpoint "move inferior 2 into position"
> +
> +    gdb_test_no_output "set breakpoint pending on"
> +
> +    return true
> +}
> +
> +# Check that when a breakpoint is in the pending state, but that breakpoint
> +# does have some locations (those locations themselves are pending), GDB
> +# doesn't display the inferior list in the 'info breakpoints' output.
> +proc_with_prefix test_no_inf_display {} {
> +    do_test_setup "Break before open" "Break before open"
> +
> +    # Create a breakpoint on 'foo'.  As the shared library (that contains
> +    # foo) has not been loaded into any inferior yet, then there will be no
> +    # locations and the breakpoint will be created pending.
> +    gdb_breakpoint "foo" allow-pending

We already did "set breakpoint pending on" in setup.  Do we need "allow-pending"?

> +    set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
> +		   "get foo breakpoint number"]
> +
> +    # Check the 'info breakpoints' output; the breakpoint is pending with
> +    # not 'inf X' appearing at the end of the line.

"not" -> "no"

Regards
-Baris


Intel Deutschland GmbH
Registered Address: Am Campeon 10, 85579 Neubiberg, Germany
Tel: +49 89 99 8853-0, www.intel.de <http://www.intel.de>
Managing Directors: Christin Eisenschmid, Sharon Heck, Tiffany Doon Silva  
Chairperson of the Supervisory Board: Nicole Lau
Registered Office: Munich
Commercial Register: Amtsgericht Muenchen HRB 186928


^ permalink raw reply	[flat|nested] 138+ messages in thread

* RE: [PATCHv6 06/10] gdb: parse pending breakpoint thread/task immediately
  2023-12-02 10:42           ` [PATCHv6 06/10] gdb: parse pending breakpoint thread/task immediately Andrew Burgess
@ 2023-12-05 15:09             ` Aktemur, Tankut Baris
  2023-12-13 13:51               ` Andrew Burgess
  0 siblings, 1 reply; 138+ messages in thread
From: Aktemur, Tankut Baris @ 2023-12-05 15:09 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches; +Cc: Eli Zaretskii

On Saturday, December 2, 2023 11:42 AM, Andrew Burgess wrote:
> diff --git a/gdb/break-cond-parse.c b/gdb/break-cond-parse.c
> new file mode 100644
> index 00000000000..b59bd7aeeec
> --- /dev/null
> +++ b/gdb/break-cond-parse.c
> @@ -0,0 +1,463 @@
> +/* Copyright (C) 2023 Free Software Foundation, Inc.
> +
> +   This file is part of GDB.
> +
> +   This program is free software; you can redistribute it and/or modify
> +   it under the terms of the GNU General Public License as published by
> +   the Free Software Foundation; either version 3 of the License, or
> +   (at your option) any later version.
> +
> +   This program is distributed in the hope that it will be useful,
> +   but WITHOUT ANY WARRANTY; without even the implied warranty of
> +   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
> +   GNU General Public License for more details.
> +
> +   You should have received a copy of the GNU General Public License
> +   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
> +
> +#include "defs.h"
> +#include "gdbsupport/gdb_assert.h"
> +#include "gdbsupport/selftest.h"
> +#include "test-target.h"
> +#include "scoped-mock-context.h"
> +#include "break-cond-parse.h"
> +#include "tid-parse.h"
> +#include "ada-lang.h"
> +
> +/* When parsing tokens from a string, which direction are we parsing?
> +
> +   Given the following string and pointer 'ptr':
> +
> +	ABC DEF GHI JKL
> +	       ^
> +	       ptr
> +
> +   Parsing 'forward' will return the token 'GHI' and update 'ptr' to point
> +   between GHI and JKL.  Parsing 'backward' will return the token 'DEF' and
> +   update 'ptr' to point between ABC and DEF.
> +*/
> +
> +enum class parse_direction
> +{
> +  /* Parse the next token forwards.  */
> +  forward,
> +
> +  /* Parse the previous token backwards.  */
> +  backward
> +};
> +
> +struct token
> +{
> +  /* Create a new token.  START points to the first character of the new
> +     token, while END points at the last character of the new token.
> +
> +     Neither START or END can be nullptr, and both START and END must point
> +     into the same C style string (i.e. there should be no null character
> +     between START and END).  END must be equal to, or greater than START,
> +     that is, it is not possible to create a zero length token.  */
> +
> +  token (const char *start, const char *end)

Have you considered using std::string_view?

> +    : m_start (start),
> +      m_end (end)
> +  {
> +    gdb_assert (m_end >= m_start);
> +    gdb_assert (m_start + strlen (m_start) > m_end);
> +  }
> +
> +  /* Return a pointer to the first character of this token.  */
> +  const char *start () const
> +  {
> +    return m_start;
> +  }
> +
> +  /* Return a pointer to the last character of this token.  */
> +  const char *end () const
> +  {
> +    return m_end;
> +  }
> +
> +  /* Return the length of the token.  */
> +  size_t length () const
> +  {
> +    /* The + 1 is because the character at m_end is part of the token.  */
> +    return m_end - m_start + 1;
> +  }
> +
> +  /* Return true if this token matches STR.  */
> +  bool matches (const char *str) const
> +  {
> +    return strncmp (m_start, str, length ()) == 0;
> +  }
> +
> +private:
> +  /* The first character of this token.  */
> +  const char *m_start;
> +
> +  /* The last character of this token.  */
> +  const char *m_end;
> +};
> +
> +/* Find the next token in DIRECTION from *CURR.  */
> +
> +static token
> +find_next_token (const char **curr, parse_direction direction)
> +{
> +  const char *tok_start, *tok_end;
> +
> +  gdb_assert (**curr != '\0');
> +
> +  if (direction == parse_direction::forward)
> +    {
> +      *curr = skip_spaces (*curr);
> +      tok_start = *curr;
> +      *curr = skip_to_space (*curr);
> +      tok_end = *curr - 1;
> +    }
> +  else
> +    {
> +      gdb_assert (direction == parse_direction::backward);
> +
> +      while (isspace (**curr))
> +	--(*curr);
> +
> +      tok_end = *curr;
> +
> +      while (!isspace (**curr))
> +	--(*curr);
> +
> +      tok_start = (*curr) + 1;
> +    }
> +
> +  return token (tok_start, tok_end);
> +}
> +
> +/* See break-cond-parse.h.  */
> +
> +void
> +create_breakpoint_parse_arg_string
> +  (const char *tok, gdb::unique_xmalloc_ptr<char> *cond_string,
> +   int *thread, int *inferior, int *task,
> +   gdb::unique_xmalloc_ptr<char> *rest, bool *force)
> +{
> +  /* Set up the defaults.  */
> +  cond_string->reset ();
> +  rest->reset ();
> +  *thread = -1;
> +  *inferior = -1;
> +  *task = -1;
> +  *force = false;
> +
> +  if (tok == nullptr)
> +    return;
> +
> +  /* The "-force-condition" flag gets some special treatment.  If this
> +     token is immediately after the condition string then we treat this as
> +     part of the condition string rather than a separate token.  This is
> +     just a quirk of how this token used to be parsed, and has been
> +     retained for backwards compatibility.  Maybe this should be updated
> +     in the future.  */

(I was the author of the -force-condition patch.)
The quirks about the -force-condition flag were not a deliberate feature.
For whatever it's worth, I think it's OK to de-prioritize backwards
compatibility for this flag.  I doubt that it would impact many users.

In fact, in a post-merge comment, Pedro and Tom had suggested converting
the flag to an option rather than a keyword:

https://sourceware.org/pipermail/gdb-patches/2020-October/172952.html
https://sourceware.org/pipermail/gdb-patches/2020-December/173802.html
https://sourceware.org/pipermail/gdb-patches/2020-December/173999.html

I (embarrassingly) did not have the opportunity to get back to it.  Maybe
it's now the correct time to address the concerns?  I can gladly help.
What do you think?

...
>    try
>      {
>        ops->create_sals_from_location_spec (locspec, &canonical);
> @@ -9285,6 +9122,13 @@ create_breakpoint (struct gdbarch *gdbarch,
>  	throw;
>      }
> 
> +  /* The only bp_dprintf should have anything in EXTRA_STRING_COPY by this

This sentence sounds odd.  Did you mean "Only the bp_dprintf type should have..."?

> +     point.  For all other breakpoints this indicates an error.  We could
> +     place this check earlier in the function, but we prefer to see errors
> +     from the location spec parser before we see this error message.  */
> +  if (type_wanted != bp_dprintf && extra_string_copy.get () != nullptr)
> +    error (_("Garbage '%s' at end of command"), extra_string_copy.get ());
> +
>    if (!pending && canonical.lsals.empty ())
>      return 0;
> 

Regards
-Baris


Intel Deutschland GmbH
Registered Address: Am Campeon 10, 85579 Neubiberg, Germany
Tel: +49 89 99 8853-0, www.intel.de <http://www.intel.de>
Managing Directors: Christin Eisenschmid, Sharon Heck, Tiffany Doon Silva  
Chairperson of the Supervisory Board: Nicole Lau
Registered Office: Munich
Commercial Register: Amtsgericht Muenchen HRB 186928


^ permalink raw reply	[flat|nested] 138+ messages in thread

* RE: [PATCHv6 07/10] gdb: don't set breakpoint::pspace for in create_breakpoint
  2023-12-02 10:42           ` [PATCHv6 07/10] gdb: don't set breakpoint::pspace for in create_breakpoint Andrew Burgess
@ 2023-12-05 16:05             ` Aktemur, Tankut Baris
  0 siblings, 0 replies; 138+ messages in thread
From: Aktemur, Tankut Baris @ 2023-12-05 16:05 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

On Saturday, December 2, 2023 11:42 AM, Andrew Burgess wrote:
> While working on the previous commit, I ran into this code within
> create_breakpoint:
> 
>   if ((type_wanted != bp_breakpoint
>       && type_wanted != bp_hardware_breakpoint) || thread != -1)
>    b->pspace = current_program_space;
> 
...
> diff --git a/gdb/testsuite/gdb.multi/pending-bp-del-inferior.c
> b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.c
> new file mode 100644
> index 00000000000..51b6492085f
> --- /dev/null
> +++ b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.c
> @@ -0,0 +1,28 @@
> +/* This testcase is part of GDB, the GNU debugger.
> +
> +   Copyright 2023 Free Software Foundation, Inc.
> +
> +   This program is free software; you can redistribute it and/or modify
> +   it under the terms of the GNU General Public License as published by
> +   the Free Software Foundation; either version 3 of the License, or
> +   (at your option) any later version.
> +
> +   This program is distributed in the hope that it will be useful,
> +   but WITHOUT ANY WARRANTY; without even the implied warranty of
> +   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
> +   GNU General Public License for more details.
> +
> +   You should have received a copy of the GNU General Public License
> +   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
> +
> +int
> +foo ()

Based on my fresh Q&A at

  https://sourceware.org/pipermail/gdb-patches/2023-December/204812.html

this shall be `foo (void)`, right?  Also `main (void)` below.

> +{
> +  return 0;
> +}
> +
> +int
> +main ()
> +{
> +  return foo ();
> +}
> diff --git a/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
> b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
> new file mode 100644
> index 00000000000..cb1f119ff94
> --- /dev/null
> +++ b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
> @@ -0,0 +1,216 @@
> +# Copyright 2023 Free Software Foundation, Inc.
> +
> +# This program is free software; you can redistribute it and/or modify
> +# it under the terms of the GNU General Public License as published by
> +# the Free Software Foundation; either version 3 of the License, or
> +# (at your option) any later version.
> +#
> +# This program is distributed in the hope that it will be useful,
> +# but WITHOUT ANY WARRANTY; without even the implied warranty of
> +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
> +# GNU General Public License for more details.
> +#
> +# You should have received a copy of the GNU General Public License
> +# along with this program.  If not, see <http://www.gnu.org/licenses/>.
> +
> +# Setup two inferiors.  Select one inferior and create a pending
> +# thread specific breakpoint in the other inferior.
> +#
> +# Delete the selected inferior (the one for which the thread specific
> +# breakpoint doesn't apply), and check that the breakpoint still exists.
> +#
> +# Repeat this process, but this time, create an inferior specific
> +# breakpoint.
> +
> +# The plain remote target can't do multiple inferiors.
> +require !use_gdb_stub
> +
> +standard_testfile
> +
> +if {[prepare_for_testing "failed to prepare" $testfile $srcfile]} {
> +    return -1
> +}
> +
> +# Setup for the tests.  Create two inferiors, both running the global
> +# BINFILE, and proceed to main in both inferiors.  Delete all
> +# breakpoints, and check that we do have two threads.
> +#
> +# Return true after a successful setup, otherwise, return false.
> +proc test_setup {} {
> +    clean_restart $::binfile
> +
> +    if {![runto_main]} {
> +	return 0
> +    }
> +
> +    gdb_test "add-inferior -exec ${::binfile}" "Added inferior 2.*" \
> +	"add inferior 2"
> +    gdb_test "inferior 2" "Switching to inferior 2 .*" \
> +	"select inferior 2"
> +
> +    if {![runto_main]} {
> +	return 0
> +    }
> +
> +    delete_breakpoints
> +
> +    gdb_test "info threads" \
> +	[multi_line \
> +	     "  Id\\s+Target Id\\s+Frame\\s*" \
> +	     "  1\\.1\\s+\[^\r\n\]+" \
> +	     "\\* 2\\.1\\s+\[^\r\n\]+"] \
> +	"check we have the expected threads"
> +
> +    return 1
> +}
> +
> +# Assuming inferior 2 is already selected, kill the current inferior
> +# (inferior 2), selected inferior 1, and then remove inferior 2.

selected -> select

> +proc kill_and_remove_inferior_2 {} {
> +    gdb_test "kill" "" "kill inferior 2" \
> +	"Kill the program being debugged.*y or n. $" "y"
> +
> +    gdb_test "inferior 1" "Switching to inferior 1 .*" \
> +	"select inferior 1"
> +
> +    gdb_test_no_output "remove-inferiors 2"
> +}
> +
> +# Setup two inferiors, then created a breakpoint.  If BP_PENDING is

created -> create

> +# true then the breakpoint will be pending, otherwise, the breakpoint
> +# will be non-pending.
> +#
> +# BP_TYPE is either 'thread' or 'inferior', and indicates if the
> +# created breakpoint should be thread or inferior specific.
> +#
> +# The breakpoint is created while inferior 2 is selected, and the
> +# thread/inferior restriction always identifies inferior 1.
> +#
> +# Then inferior 2 is killed and removed.
> +#
> +# Finally, check that the breakpoint still exists and correctly refers
> +# to inferior 1.
> +proc do_bp_test { bp_type bp_pending } {
> +    if {![test_setup]} {
> +	return
> +    }
> +
> +    if { $bp_pending } {
> +	set bp_func "bar"
> +    } else {
> +	set bp_func "foo"
> +    }
> +
> +    if { $bp_type eq "thread" } {
> +	set bp_restriction "thread 1.1"
> +    } else {
> +	set bp_restriction "inferior 1"
> +    }
> +
> +    gdb_breakpoint "$bp_func $bp_restriction" allow-pending
> +    set bp_number [get_integer_valueof "\$bpnum" "INVALID" \
> +		       "get b/p number for previous breakpoint"]
> +
> +    if { $bp_restriction eq "thread 1.1" } {
> +	set bp_after_restriction "thread 1"
> +    } else {
> +	set bp_after_restriction $bp_restriction
> +    }
> +
> +    if { $bp_pending } {
> +	set bp_pattern_before \
> +	    [multi_line \
> +		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+${bp_func}" \
> +		 "\\s+stop only in [string_to_regexp $bp_restriction]"]
> +	set bp_pattern_after \
> +	    [multi_line \
> +		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+${bp_func}" \
> +		 "\\s+stop only in [string_to_regexp $bp_after_restriction]"]
> +    } else {
> +	set bp_pattern_before \
> +	    [multi_line \
> +		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+<MULTIPLE>\\s*" \
> +		 "\\s+stop only in [string_to_regexp $bp_restriction]" \
> +		 "$bp_number\\.1\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 1" \
> +		 "$bp_number\\.2\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 2"]
> +
> +	set bp_pattern_after \
> +	    [multi_line \
> +		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+" \
> +		 "\\s+stop only in [string_to_regexp $bp_after_restriction]"]
> +    }
> +
> +    gdb_test "info breakpoints" $bp_pattern_before \
> +	"info breakpoints before inferior removal"
> +
> +    kill_and_remove_inferior_2
> +
> +    gdb_test "info breakpoints" $bp_pattern_after \
> +	"info breakpoints after inferior removal"
> +}
> +
> +# Setup two inferiors, then created a dprintf.  If BP_PENDING is

created -> create

> +# true then the dprintf will be pending, otherwise, the dprintf
> +# will be non-pending.
> +#
> +# The dprintf is created while inferior 2.  Then inferior 2 is killed

The sentence seems incomplete.  Did you mean "... while inferior 2 is
selected."?

> +# and removed.
> +#
> +# Finally, check that the dprintf still exists.
> +proc do_dprintf_test { bp_pending } {
> +    if {![test_setup]} {
> +	return
> +    }
> +
> +    if { $bp_pending } {
> +	set bp_func "bar"
> +
> +	gdb_test "dprintf $bp_func,\"in $bp_func\"" ".*" \
> +	    "create dprintf breakpoint" \
> +	    "Make dprintf pending on future shared library load\\? \\(y or .n.\\) $" "y"
> +    } else {
> +	set bp_func "foo"
> +
> +	gdb_test "dprintf $bp_func,\"in $bp_func\"" ".*" \
> +	    "create dprintf breakpoint"
> +    }
> +
> +    set bp_number [get_integer_valueof "\$bpnum" "INVALID" \
> +		       "get b/p number for previous breakpoint"]
> +
> +    if { $bp_pending } {
> +	set bp_pattern_before \
> +	    [multi_line \
> +		 "$bp_number\\s+dprintf\\s+keep\\s+y\\s+<PENDING>\\s+${bp_func}" \
> +		 "\\s+printf \"in $bp_func\""]
> +	set bp_pattern_after $bp_pattern_before
> +    } else {
> +	set bp_pattern_before \
> +	    [multi_line \
> +		 "$bp_number\\s+dprintf\\s+keep\\s+y\\s+<MULTIPLE>\\s*" \
> +		 "\\s+printf \"in $bp_func\"" \
> +		 "$bp_number\\.1\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 1" \
> +		 "$bp_number\\.2\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 2"]
> +
> +	set bp_pattern_after \
> +	    [multi_line \
> +		 "$bp_number\\s+dprintf\\s+keep\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+" \
> +		 "\\s+printf \"in $bp_func\""]
> +    }
> +
> +    gdb_test "info breakpoints" $bp_pattern_before \
> +	"info breakpoints before inferior removal"
> +
> +    kill_and_remove_inferior_2
> +
> +    gdb_test "info breakpoints" $bp_pattern_after \
> +	"info breakpoints after inferior removal"
> +}
> +
> +foreach_with_prefix bp_pending { true false } {
> +    foreach_with_prefix bp_type { thread inferior } {
> +	do_bp_test $bp_type $bp_pending
> +    }
> +
> +    do_dprintf_test $bp_pending
> +}
> --
> 2.25.4

Thanks,
-Baris


Intel Deutschland GmbH
Registered Address: Am Campeon 10, 85579 Neubiberg, Germany
Tel: +49 89 99 8853-0, www.intel.de <http://www.intel.de>
Managing Directors: Christin Eisenschmid, Sharon Heck, Tiffany Doon Silva  
Chairperson of the Supervisory Board: Nicole Lau
Registered Office: Munich
Commercial Register: Amtsgericht Muenchen HRB 186928


^ permalink raw reply	[flat|nested] 138+ messages in thread

* RE: [PATCHv6 06/10] gdb: parse pending breakpoint thread/task immediately
  2023-12-05 15:09             ` Aktemur, Tankut Baris
@ 2023-12-13 13:51               ` Andrew Burgess
  2023-12-27 12:23                 ` Aktemur, Tankut Baris
  0 siblings, 1 reply; 138+ messages in thread
From: Andrew Burgess @ 2023-12-13 13:51 UTC (permalink / raw)
  To: Aktemur, Tankut Baris, gdb-patches; +Cc: Eli Zaretskii

"Aktemur, Tankut Baris" <tankut.baris.aktemur@intel.com> writes:

> On Saturday, December 2, 2023 11:42 AM, Andrew Burgess wrote:
>> diff --git a/gdb/break-cond-parse.c b/gdb/break-cond-parse.c
>> new file mode 100644
>> index 00000000000..b59bd7aeeec
>> --- /dev/null
>> +++ b/gdb/break-cond-parse.c
>> @@ -0,0 +1,463 @@
>> +/* Copyright (C) 2023 Free Software Foundation, Inc.
>> +
>> +   This file is part of GDB.
>> +
>> +   This program is free software; you can redistribute it and/or modify
>> +   it under the terms of the GNU General Public License as published by
>> +   the Free Software Foundation; either version 3 of the License, or
>> +   (at your option) any later version.
>> +
>> +   This program is distributed in the hope that it will be useful,
>> +   but WITHOUT ANY WARRANTY; without even the implied warranty of
>> +   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
>> +   GNU General Public License for more details.
>> +
>> +   You should have received a copy of the GNU General Public License
>> +   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
>> +
>> +#include "defs.h"
>> +#include "gdbsupport/gdb_assert.h"
>> +#include "gdbsupport/selftest.h"
>> +#include "test-target.h"
>> +#include "scoped-mock-context.h"
>> +#include "break-cond-parse.h"
>> +#include "tid-parse.h"
>> +#include "ada-lang.h"
>> +
>> +/* When parsing tokens from a string, which direction are we parsing?
>> +
>> +   Given the following string and pointer 'ptr':
>> +
>> +	ABC DEF GHI JKL
>> +	       ^
>> +	       ptr
>> +
>> +   Parsing 'forward' will return the token 'GHI' and update 'ptr' to point
>> +   between GHI and JKL.  Parsing 'backward' will return the token 'DEF' and
>> +   update 'ptr' to point between ABC and DEF.
>> +*/
>> +
>> +enum class parse_direction
>> +{
>> +  /* Parse the next token forwards.  */
>> +  forward,
>> +
>> +  /* Parse the previous token backwards.  */
>> +  backward
>> +};
>> +
>> +struct token
>> +{
>> +  /* Create a new token.  START points to the first character of the new
>> +     token, while END points at the last character of the new token.
>> +
>> +     Neither START or END can be nullptr, and both START and END must point
>> +     into the same C style string (i.e. there should be no null character
>> +     between START and END).  END must be equal to, or greater than START,
>> +     that is, it is not possible to create a zero length token.  */
>> +
>> +  token (const char *start, const char *end)
>
> Have you considered using std::string_view?
>
>> +    : m_start (start),
>> +      m_end (end)
>> +  {
>> +    gdb_assert (m_end >= m_start);
>> +    gdb_assert (m_start + strlen (m_start) > m_end);
>> +  }
>> +
>> +  /* Return a pointer to the first character of this token.  */
>> +  const char *start () const
>> +  {
>> +    return m_start;
>> +  }
>> +
>> +  /* Return a pointer to the last character of this token.  */
>> +  const char *end () const
>> +  {
>> +    return m_end;
>> +  }
>> +
>> +  /* Return the length of the token.  */
>> +  size_t length () const
>> +  {
>> +    /* The + 1 is because the character at m_end is part of the token.  */
>> +    return m_end - m_start + 1;
>> +  }
>> +
>> +  /* Return true if this token matches STR.  */
>> +  bool matches (const char *str) const
>> +  {
>> +    return strncmp (m_start, str, length ()) == 0;
>> +  }
>> +
>> +private:
>> +  /* The first character of this token.  */
>> +  const char *m_start;
>> +
>> +  /* The last character of this token.  */
>> +  const char *m_end;
>> +};
>> +
>> +/* Find the next token in DIRECTION from *CURR.  */
>> +
>> +static token
>> +find_next_token (const char **curr, parse_direction direction)
>> +{
>> +  const char *tok_start, *tok_end;
>> +
>> +  gdb_assert (**curr != '\0');
>> +
>> +  if (direction == parse_direction::forward)
>> +    {
>> +      *curr = skip_spaces (*curr);
>> +      tok_start = *curr;
>> +      *curr = skip_to_space (*curr);
>> +      tok_end = *curr - 1;
>> +    }
>> +  else
>> +    {
>> +      gdb_assert (direction == parse_direction::backward);
>> +
>> +      while (isspace (**curr))
>> +	--(*curr);
>> +
>> +      tok_end = *curr;
>> +
>> +      while (!isspace (**curr))
>> +	--(*curr);
>> +
>> +      tok_start = (*curr) + 1;
>> +    }
>> +
>> +  return token (tok_start, tok_end);
>> +}
>> +
>> +/* See break-cond-parse.h.  */
>> +
>> +void
>> +create_breakpoint_parse_arg_string
>> +  (const char *tok, gdb::unique_xmalloc_ptr<char> *cond_string,
>> +   int *thread, int *inferior, int *task,
>> +   gdb::unique_xmalloc_ptr<char> *rest, bool *force)
>> +{
>> +  /* Set up the defaults.  */
>> +  cond_string->reset ();
>> +  rest->reset ();
>> +  *thread = -1;
>> +  *inferior = -1;
>> +  *task = -1;
>> +  *force = false;
>> +
>> +  if (tok == nullptr)
>> +    return;
>> +
>> +  /* The "-force-condition" flag gets some special treatment.  If this
>> +     token is immediately after the condition string then we treat this as
>> +     part of the condition string rather than a separate token.  This is
>> +     just a quirk of how this token used to be parsed, and has been
>> +     retained for backwards compatibility.  Maybe this should be updated
>> +     in the future.  */
>
> (I was the author of the -force-condition patch.)
> The quirks about the -force-condition flag were not a deliberate feature.
> For whatever it's worth, I think it's OK to de-prioritize backwards
> compatibility for this flag.  I doubt that it would impact many users.
>
> In fact, in a post-merge comment, Pedro and Tom had suggested converting
> the flag to an option rather than a keyword:
>
> https://sourceware.org/pipermail/gdb-patches/2020-October/172952.html
> https://sourceware.org/pipermail/gdb-patches/2020-December/173802.html
> https://sourceware.org/pipermail/gdb-patches/2020-December/173999.html
>
> I (embarrassingly) did not have the opportunity to get back to it.  Maybe
> it's now the correct time to address the concerns?  I can gladly help.
> What do you think?

I think this sounds like a good idea, but ....

... I took a quick look at how this might be done, and the problem I see
is that the current 'break' option parsing is buried within
string_to_explicit_location_spec, which is called from
string_to_location_spec, which is called from multiple commands.

Which makes sense, currently, all of the options for 'break' are about
specifying the location.

In contrast, -force-condition has nothing to do with the location, but
relates (as you know) to the condition.

We could handle -force-condition in string_to_explicit_location_spec,
but then commands like 'edit', which take a location, but not a
condition would accept -force-condition, and we'd have to have some
mechanism to the 'force' flag true/false value back out of
string_to_explicit_location_spec, either passing a container around, or
storing the 'force' state within the locspec... this all sounds like the
wrong approach.

Better I think would be to pull the option parsing out of
string_to_explicit_location_spec, and move it into the individual
commands.  What we'd ideally want is to convert the current bespoke
option parsing (for location spec options) to use GDB's generic option
parsing mechanism.  It's possible to bind multiple
gdb::option::option_def into a single gdb::option::option_def_group, so
we can imagine that the 'break' command would use a common
gdb::option::option_def from location.h, which defines all the location
spec arguments, and then a separate gdb::option::option_def which adds
the -force-condition flag.  The only issue then is that we'd need to
pass the location spec related arguments into
string_to_explicit_location_spec somehow....

Phew.  Now the next problem is that the gdb::option::option_def contains
a list of gdb::option::*_option_def objects, the precise type of which
defines how the options are parsed.  It we look at how the arguments to
things like -function are parsed, these get special language specific
handling, which the current option mechanism doesn't support, so I think
we'd need to add that, which will mean at least extending the option
process, or maybe even some reworking of the option handling...

All that is to say that I agree with Pedro that this would be better
done as an real option ... but I really don't want to tie this work to
that refactoring if at all possible...

Thanks,
Andrew

>
> ...
>>    try
>>      {
>>        ops->create_sals_from_location_spec (locspec, &canonical);
>> @@ -9285,6 +9122,13 @@ create_breakpoint (struct gdbarch *gdbarch,
>>  	throw;
>>      }
>> 
>> +  /* The only bp_dprintf should have anything in EXTRA_STRING_COPY by this
>
> This sentence sounds odd.  Did you mean "Only the bp_dprintf type should have..."?
>
>> +     point.  For all other breakpoints this indicates an error.  We could
>> +     place this check earlier in the function, but we prefer to see errors
>> +     from the location spec parser before we see this error message.  */
>> +  if (type_wanted != bp_dprintf && extra_string_copy.get () != nullptr)
>> +    error (_("Garbage '%s' at end of command"), extra_string_copy.get ());
>> +
>>    if (!pending && canonical.lsals.empty ())
>>      return 0;
>> 
>
> Regards
> -Baris
>
>
> Intel Deutschland GmbH
> Registered Address: Am Campeon 10, 85579 Neubiberg, Germany
> Tel: +49 89 99 8853-0, www.intel.de <http://www.intel.de>
> Managing Directors: Christin Eisenschmid, Sharon Heck, Tiffany Doon Silva  
> Chairperson of the Supervisory Board: Nicole Lau
> Registered Office: Munich
> Commercial Register: Amtsgericht Muenchen HRB 186928


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv7 00/11] thread-specific breakpoints in just some inferiors
  2023-12-02 10:42         ` [PATCHv6 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
                             ` (9 preceding siblings ...)
  2023-12-02 10:42           ` [PATCHv6 10/10] gdb: only insert thread-specific breakpoints in the relevant inferior Andrew Burgess
@ 2023-12-13 22:38           ` Andrew Burgess
  2023-12-13 22:38             ` [PATCHv7 01/11] gdb: create_breakpoint: add asserts and additional comments Andrew Burgess
                               ` (12 more replies)
  10 siblings, 13 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-12-13 22:38 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

In v7:

  - Addressed all the issues except one that Baris pointed out, this
    includes typos, some minor testsuite cleanups, and reformatting an
    assert (but not changing the meaning).

  - As requested, switched to use std::string_view in
    break-parse-cond.c file instead of a custom class, I agree that
    this is an improvement.

  - I've not changed the handling of -force-condition flag.  I replied
    to the review email with my thoughts, TLDR: fixing this would be a
    bigger task which I'd rather leave for ... the future.
    
  - Rebased and retested.

In v6:

  - Rebased to current master, one minor fix due to the C++17 changes,
    nothing major.  Retested.

In v5:

  - Updates after Lancelot's feedback, including, -force-condition can
    no longer be abbreviated to '-', and can't be used immediately
    after the breakpoint condition.

  - More tests to check some of the edge cases.

In v4:

  - Big update, this series now handles thread-specific and
    inferior-specific breakpoints.

In v3:

  - Rebased on to current upstream/master, this includes all Simon's
    recent breakpoint changes.  Retested with no regressions seen.

In v2:

  - Rebased on current upstream/master and retested,

  - No changes to code or docs.

---

Andrew Burgess (11):
  gdb: create_breakpoint: add asserts and additional comments
  gdb: create_breakpoint: asserts relating to extra_string/parse_extra
  gdb: change 'if' to gdb_assert in update_dprintf_command_list
  gdb: the extra_string in a dprintf breakpoint is never nullptr
  gdb: build dprintf commands just once in code_breakpoint constructor
  gdb: don't display inferior list for pending breakpoints
  gdb: parse pending breakpoint thread/task immediately
  gdb: don't set breakpoint::pspace for in create_breakpoint
  gdb: remove breakpoint_re_set_one
  gdb: remove tracepoint_probe_create_sals_from_location_spec
  gdb: only insert thread-specific breakpoints in the relevant inferior

 gdb/Makefile.in                               |   2 +
 gdb/NEWS                                      |  11 +
 gdb/ada-lang.c                                |   6 +-
 gdb/break-catch-throw.c                       |   6 +-
 gdb/break-cond-parse.c                        | 425 ++++++++++
 gdb/break-cond-parse.h                        |  49 ++
 gdb/breakpoint.c                              | 764 ++++++++----------
 gdb/breakpoint.h                              | 101 ++-
 gdb/testsuite/gdb.ada/tasks.exp               |   6 +-
 gdb/testsuite/gdb.base/condbreak.exp          |  57 +-
 gdb/testsuite/gdb.base/pending.exp            |  23 +-
 gdb/testsuite/gdb.linespec/explicit.exp       |   4 +-
 gdb/testsuite/gdb.mi/mi-dprintf-pending.exp   |   3 +-
 gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp    |   8 +-
 .../gdb.mi/user-selected-context-sync.exp     |   4 +-
 .../gdb.multi/bp-thread-specific.exp          |   7 +-
 .../gdb.multi/inferior-specific-bp.exp        |  16 +-
 .../gdb.multi/multi-target-continue.exp       |   2 +-
 .../gdb.multi/multi-target-ping-pong-next.exp |   4 +-
 .../gdb.multi/pending-bp-del-inferior.c       |  28 +
 .../gdb.multi/pending-bp-del-inferior.exp     | 214 +++++
 gdb/testsuite/gdb.multi/pending-bp-lib.c      |  22 +
 gdb/testsuite/gdb.multi/pending-bp.c          |  66 ++
 gdb/testsuite/gdb.multi/pending-bp.exp        | 332 ++++++++
 gdb/testsuite/gdb.multi/tids.exp              |   6 +-
 .../gdb.threads/del-pending-thread-bp-lib.c   |  22 +
 .../gdb.threads/del-pending-thread-bp.c       |  85 ++
 .../gdb.threads/del-pending-thread-bp.exp     | 108 +++
 28 files changed, 1906 insertions(+), 475 deletions(-)
 create mode 100644 gdb/break-cond-parse.c
 create mode 100644 gdb/break-cond-parse.h
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-del-inferior.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.exp
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.exp


base-commit: 5c5e642dc0f6b223c2339d8dee64fbc63eee8e1a
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv7 01/11] gdb: create_breakpoint: add asserts and additional comments
  2023-12-13 22:38           ` [PATCHv7 00/11] thread-specific breakpoints in just some inferiors Andrew Burgess
@ 2023-12-13 22:38             ` Andrew Burgess
  2023-12-13 22:38             ` [PATCHv7 02/11] gdb: create_breakpoint: asserts relating to extra_string/parse_extra Andrew Burgess
                               ` (11 subsequent siblings)
  12 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-12-13 22:38 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

This commit extends the asserts on create_breakpoint (in the header
file), and adds some additional assertions into the definition.

The new assert confirms that when the thread and inferior information
is going to be parsed from the extra_string, then the thread and
inferior arguments should be -1.  That is, the caller of
create_breakpoint should not try to create a thread/inferior specific
breakpoint by *both* specifying thread/inferior *and* asking to parse
the extra_string, it's one or the other.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c |  6 ++++++
 gdb/breakpoint.h | 16 ++++++++++++++++
 2 files changed, 22 insertions(+)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 699919e32b3..c0d6991c96d 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -9228,6 +9228,12 @@ create_breakpoint (struct gdbarch *gdbarch,
   gdb_assert (inferior == -1 || inferior > 0);
   gdb_assert (thread == -1 || inferior == -1);
 
+  /* If PARSE_EXTRA is true then the thread and inferior details will be
+     parsed from the EXTRA_STRING, the THREAD and INFERIOR arguments
+     should be -1.  */
+  gdb_assert (!parse_extra || thread == -1);
+  gdb_assert (!parse_extra || inferior == -1);
+
   gdb_assert (ops != NULL);
 
   /* If extra_string isn't useful, set it to NULL.  */
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index feb798224c0..4abf6d0762c 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -1600,6 +1600,22 @@ enum breakpoint_create_flags
    the FORCE_CONDITION parameter is ignored and the corresponding argument
    is parsed from EXTRA_STRING.
 
+   The THREAD should be a global thread number, the created breakpoint will
+   only apply for that thread.  If the breakpoint should apply for all
+   threads then pass -1.  However, if PARSE_EXTRA is non-zero then the
+   THREAD parameter is ignored and an optional thread number will be parsed
+   from EXTRA_STRING.
+
+   The INFERIOR should be a global inferior number, the created breakpoint
+   will only apply for that inferior.  If the breakpoint should apply for
+   all inferiors then pass -1.  However, if PARSE_EXTRA is non-zero then
+   the INFERIOR parameter is ignored and an optional inferior number will
+   be parsed from EXTRA_STRING.
+
+   At most one of THREAD and INFERIOR should be set to a value other than
+   -1; breakpoints can be thread specific, or inferior specific, but not
+   both.
+
    If INTERNAL is non-zero, the breakpoint number will be allocated
    from the internal breakpoint count.
 
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv7 02/11] gdb: create_breakpoint: asserts relating to extra_string/parse_extra
  2023-12-13 22:38           ` [PATCHv7 00/11] thread-specific breakpoints in just some inferiors Andrew Burgess
  2023-12-13 22:38             ` [PATCHv7 01/11] gdb: create_breakpoint: add asserts and additional comments Andrew Burgess
@ 2023-12-13 22:38             ` Andrew Burgess
  2023-12-15 20:08               ` Tom Tromey
  2023-12-13 22:38             ` [PATCHv7 03/11] gdb: change 'if' to gdb_assert in update_dprintf_command_list Andrew Burgess
                               ` (10 subsequent siblings)
  12 siblings, 1 reply; 138+ messages in thread
From: Andrew Burgess @ 2023-12-13 22:38 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

The goal of this commit is to better define the API for
create_breakpoint especially around the use of extra_string and
parse_extra.  This will be useful in the next commit when I plan to
make some changes to create_breakpoint.

This commit makes one possibly breaking change: until this commit it
was possible to create thread-specific dprintf breakpoint like this:

  (gdb) dprintf call_me, thread 1 "%s", "hello"
  Dprintf 2 at 0x401152: file /tmp/hello.c, line 8.
  (gdb) info breakpoints
  Num     Type           Disp Enb Address            What
  2       dprintf        keep y   0x0000000000401152 in call_me at /tmp/hello.c:8 thread 1
          stop only in thread 1
          printf "%s", "hello"
  (gdb)

This feature of dprintf was not documented, was not tested, and is
slightly different in syntax to how we create thread specific
breakpoints and/or watchpoints -- the thread condition appears after
the first ','.

I believe that this worked at all was simply by luck.  We happen to
pass the parse_extra flag as true from dprintf_command to
create_breakpoint.

So in this commit I made the choice change this.  We now pass
parse_extra as false from dprintf_command to create_breakpoint.  With
this done it is assumed that the only thing in the extra_string is the
dprintf format and arguments.

Beyond this change I've updated the comment on create_breakpoint in
breakpoint.h, and I've then added some asserts into
create_breakpoint as well as moving around some of the error
handling.

 - We now assert on the incoming argument values,

 - I've moved an error check to sit after the call to
   find_condition_and_thread_for_sals, this ensures the extra_string
   was parsed correctly,

In dprintf_command:

 - We now throw an error if there is no format string after the
   dprintf location.  This error was already being thrown, but was
   being caught later in the process.  With this change we catch the
   missing string earlier,

 - And, as mentioned earlier, we pass parse_extra as false when
   calling create_breakpoint,

In create_tracepoint_from_upload:

 - We now throw an error if the parsed location doesn't completely
   consume the addr_str variable.  This error has now effectively
   moved out of create_breakpoint.
---
 gdb/breakpoint.c | 41 ++++++++++++++++++++++++++++-------------
 gdb/breakpoint.h | 44 +++++++++++++++++++++++++++-----------------
 2 files changed, 55 insertions(+), 30 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index c0d6991c96d..5cc74e828b6 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -9240,6 +9240,16 @@ create_breakpoint (struct gdbarch *gdbarch,
   if (extra_string != NULL && *extra_string == '\0')
     extra_string = NULL;
 
+  /* A bp_dprintf must always have an accompanying EXTRA_STRING containing
+     the dprintf format and arguments -- PARSE_EXTRA should always be false
+     in this case.
+
+     For all other breakpoint types, EXTRA_STRING should be nullptr unless
+     PARSE_EXTRA is true.  */
+  gdb_assert ((type_wanted == bp_dprintf)
+	      ? (extra_string != nullptr && !parse_extra)
+	      : (extra_string == nullptr || parse_extra));
+
   try
     {
       ops->create_sals_from_location_spec (locspec, &canonical);
@@ -9303,6 +9313,8 @@ create_breakpoint (struct gdbarch *gdbarch,
 
       if (parse_extra)
 	{
+	  gdb_assert (type_wanted != bp_dprintf);
+
 	  gdb::unique_xmalloc_ptr<char> rest;
 	  gdb::unique_xmalloc_ptr<char> cond;
 
@@ -9311,15 +9323,15 @@ create_breakpoint (struct gdbarch *gdbarch,
 	  find_condition_and_thread_for_sals (lsal.sals, extra_string,
 					      &cond, &thread, &inferior,
 					      &task, &rest);
+
+	  if (rest.get () != nullptr && *(rest.get ()) != '\0')
+	    error (_("Garbage '%s' at end of command"), rest.get ());
+
 	  cond_string_copy = std::move (cond);
 	  extra_string_copy = std::move (rest);
 	}
       else
 	{
-	  if (type_wanted != bp_dprintf
-	      && extra_string != NULL && *extra_string != '\0')
-		error (_("Garbage '%s' at end of location"), extra_string);
-
 	  /* Check the validity of the condition.  We should error out
 	     if the condition is invalid at all of the locations and
 	     if it is not forced.  In the PARSE_EXTRA case above, this
@@ -9530,21 +9542,18 @@ dprintf_command (const char *arg, int from_tty)
 
   /* If non-NULL, ARG should have been advanced past the location;
      the next character must be ','.  */
-  if (arg != NULL)
+  if (arg == nullptr || arg[0] != ',' || arg[1] == '\0')
+    error (_("Format string required"));
+  else
     {
-      if (arg[0] != ',' || arg[1] == '\0')
-	error (_("Format string required"));
-      else
-	{
-	  /* Skip the comma.  */
-	  ++arg;
-	}
+      /* Skip the comma.  */
+      ++arg;
     }
 
   create_breakpoint (get_current_arch (),
 		     locspec.get (),
 		     NULL, -1, -1,
-		     arg, false, 1 /* parse arg */,
+		     arg, false, 0 /* parse arg */,
 		     0, bp_dprintf,
 		     0 /* Ignore count */,
 		     pending_break_support,
@@ -14149,6 +14158,12 @@ create_tracepoint_from_upload (struct uploaded_tp *utp)
 
   location_spec_up locspec = string_to_location_spec (&addr_str,
 						      current_language);
+
+
+  gdb_assert (addr_str != nullptr);
+  if (*addr_str != '\0')
+    error (_("Garbage '%s' at end of location"), addr_str);
+
   if (!create_breakpoint (get_current_arch (),
 			  locspec.get (),
 			  utp->cond_string.get (), -1, -1, addr_str,
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index 4abf6d0762c..95f98b59e41 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -1585,32 +1585,42 @@ enum breakpoint_create_flags
    functions for setting a breakpoint at LOCSPEC.
 
    This function has two major modes of operations, selected by the
-   PARSE_EXTRA parameter.
+   PARSE_EXTRA and WANTED_TYPE parameters.
 
-   If PARSE_EXTRA is zero, LOCSPEC is just the breakpoint's location
-   spec, with condition, thread, and extra string specified by the
-   COND_STRING, THREAD, and EXTRA_STRING parameters.
+   When WANTED_TYPE is not bp_dprintf the following rules apply:
 
-   If PARSE_EXTRA is non-zero, this function will attempt to extract
-   the condition, thread, and extra string from EXTRA_STRING, ignoring
-   the similarly named parameters.
+     If PARSE_EXTRA is zero, LOCSPEC is just the breakpoint's location
+     spec, with condition, thread, and extra string specified by the
+     COND_STRING, THREAD, and EXTRA_STRING parameters.
 
-   If FORCE_CONDITION is true, the condition is accepted even when it is
-   invalid at all of the locations.  However, if PARSE_EXTRA is non-zero,
-   the FORCE_CONDITION parameter is ignored and the corresponding argument
-   is parsed from EXTRA_STRING.
+     If PARSE_EXTRA is non-zero, this function will attempt to extract the
+     condition, thread, and extra string from EXTRA_STRING, ignoring the
+     similarly named parameters.
+
+   When WANTED_TYPE is bp_dprintf the following rules apply:
+
+     PARSE_EXTRA must always be zero, LOCSPEC is just the breakpoint's
+     location spec, with condition, thread, and extra string (which
+     contains the dprintf format and arguments) specified by the
+     COND_STRING, THREAD, and EXTRA_STRING parameters.
+
+   If FORCE_CONDITION is true, the condition (in COND_STRING) is accepted
+   even when it is invalid at all of the locations.  However, if
+   PARSE_EXTRA is non-zero and WANTED_TYPE is not bp_dprintf, the
+   FORCE_CONDITION parameter is ignored and the corresponding argument is
+   parsed from EXTRA_STRING.
 
    The THREAD should be a global thread number, the created breakpoint will
    only apply for that thread.  If the breakpoint should apply for all
-   threads then pass -1.  However, if PARSE_EXTRA is non-zero then the
-   THREAD parameter is ignored and an optional thread number will be parsed
-   from EXTRA_STRING.
+   threads then pass -1.  However, if PARSE_EXTRA is non-zero and
+   WANTED_TYPE is not bp_dprintf, then the THREAD parameter is ignored and
+   an optional thread number will be parsed from EXTRA_STRING.
 
    The INFERIOR should be a global inferior number, the created breakpoint
    will only apply for that inferior.  If the breakpoint should apply for
-   all inferiors then pass -1.  However, if PARSE_EXTRA is non-zero then
-   the INFERIOR parameter is ignored and an optional inferior number will
-   be parsed from EXTRA_STRING.
+   all inferiors then pass -1.  However, if PARSE_EXTRA is non-zero and
+   WANTED_TYPE is not bp_dprintf, then the INFERIOR parameter is ignored
+   and an optional inferior number will be parsed from EXTRA_STRING.
 
    At most one of THREAD and INFERIOR should be set to a value other than
    -1; breakpoints can be thread specific, or inferior specific, but not
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv7 03/11] gdb: change 'if' to gdb_assert in update_dprintf_command_list
  2023-12-13 22:38           ` [PATCHv7 00/11] thread-specific breakpoints in just some inferiors Andrew Burgess
  2023-12-13 22:38             ` [PATCHv7 01/11] gdb: create_breakpoint: add asserts and additional comments Andrew Burgess
  2023-12-13 22:38             ` [PATCHv7 02/11] gdb: create_breakpoint: asserts relating to extra_string/parse_extra Andrew Burgess
@ 2023-12-13 22:38             ` Andrew Burgess
  2023-12-13 22:38             ` [PATCHv7 04/11] gdb: the extra_string in a dprintf breakpoint is never nullptr Andrew Burgess
                               ` (9 subsequent siblings)
  12 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-12-13 22:38 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

I noticed in update_dprintf_command_list that we handle the case where
the bp_dprintf style breakpoint doesn't have a format and args string.

However, I don't believe such a situation is possible.  The obvious
approach certainly already catches this case:

  (gdb) dprintf main
  Format string required

If it is possible to create a dprintf breakpoint without a format and
args string then I think we should be catching this case and handling
it at creation time, rather than having GDB just ignore the situation
later on.

And so, I propose that we change the 'if' that ignores the case where
the format/args string is empty, and instead assert that we do always
have a format/args string.  The original code, that handled an empty
format/args string has existed since commit e7e0cddfb0d4, which is
when dprintf support was added to GDB.

If I'm correct and this situation can't ever happen then there should
be no user visible changes after this commit.
---
 gdb/breakpoint.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 5cc74e828b6..31abf3e34ca 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -8538,8 +8538,9 @@ update_dprintf_command_list (struct breakpoint *b)
   const char *dprintf_args = b->extra_string.get ();
   gdb::unique_xmalloc_ptr<char> printf_line = nullptr;
 
-  if (!dprintf_args)
-    return;
+  /* Trying to create a dprintf breakpoint without a format and args
+     string should be detected at creation time.  */
+  gdb_assert (dprintf_args != nullptr);
 
   dprintf_args = skip_spaces (dprintf_args);
 
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv7 04/11] gdb: the extra_string in a dprintf breakpoint is never nullptr
  2023-12-13 22:38           ` [PATCHv7 00/11] thread-specific breakpoints in just some inferiors Andrew Burgess
                               ` (2 preceding siblings ...)
  2023-12-13 22:38             ` [PATCHv7 03/11] gdb: change 'if' to gdb_assert in update_dprintf_command_list Andrew Burgess
@ 2023-12-13 22:38             ` Andrew Burgess
  2023-12-13 22:38             ` [PATCHv7 05/11] gdb: build dprintf commands just once in code_breakpoint constructor Andrew Burgess
                               ` (8 subsequent siblings)
  12 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-12-13 22:38 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Given the changes in the previous couple of commits, this commit
cleans up some of the asserts and 'if' checks related to the
extra_string within a dprintf breakpoint.

This commit:

  1. Adds some asserts to update_dprintf_command_list about the
  breakpoint type, and that the extra_string is not nullptr,

  2. Given that we know extra_string is not nullptr (this is enforced
  when the breakpoint is created), we can simplify
  code_breakpoint::code_breakpoint -- it no longer needs to check for
  the extra_string is nullptr case,

  3. In dprintf_breakpoint::re_set we can remove the assert (this will
  be checked within update_dprintf_command_list, we can also remove
  the redundant 'if' check.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c | 16 +++++-----------
 1 file changed, 5 insertions(+), 11 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 31abf3e34ca..783a05d9a6b 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -8535,6 +8535,9 @@ bp_loc_is_permanent (struct bp_location *loc)
 static void
 update_dprintf_command_list (struct breakpoint *b)
 {
+  gdb_assert (b->type == bp_dprintf);
+  gdb_assert (b->extra_string != nullptr);
+
   const char *dprintf_args = b->extra_string.get ();
   gdb::unique_xmalloc_ptr<char> printf_line = nullptr;
 
@@ -8708,12 +8711,7 @@ code_breakpoint::code_breakpoint (struct gdbarch *gdbarch_,
       /* Dynamic printf requires and uses additional arguments on the
 	 command line, otherwise it's an error.  */
       if (type == bp_dprintf)
-	{
-	  if (extra_string != nullptr)
-	    update_dprintf_command_list (this);
-	  else
-	    error (_("Format string required"));
-	}
+	update_dprintf_command_list (this);
       else if (extra_string != nullptr)
 	error (_("Garbage '%s' at end of command"), extra_string.get ());
     }
@@ -12428,9 +12426,6 @@ dprintf_breakpoint::re_set ()
 {
   re_set_default ();
 
-  /* extra_string should never be non-NULL for dprintf.  */
-  gdb_assert (extra_string != NULL);
-
   /* 1 - connect to target 1, that can run breakpoint commands.
      2 - create a dprintf, which resolves fine.
      3 - disconnect from target 1
@@ -12441,8 +12436,7 @@ dprintf_breakpoint::re_set ()
      answers for target_can_run_breakpoint_commands().
      Given absence of finer grained resetting, we get to do
      it all the time.  */
-  if (extra_string != NULL)
-    update_dprintf_command_list (this);
+  update_dprintf_command_list (this);
 }
 
 /* Implement the "print_recreate" method for dprintf.  */
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv7 05/11] gdb: build dprintf commands just once in code_breakpoint constructor
  2023-12-13 22:38           ` [PATCHv7 00/11] thread-specific breakpoints in just some inferiors Andrew Burgess
                               ` (3 preceding siblings ...)
  2023-12-13 22:38             ` [PATCHv7 04/11] gdb: the extra_string in a dprintf breakpoint is never nullptr Andrew Burgess
@ 2023-12-13 22:38             ` Andrew Burgess
  2023-12-13 22:38             ` [PATCHv7 06/11] gdb: don't display inferior list for pending breakpoints Andrew Burgess
                               ` (7 subsequent siblings)
  12 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-12-13 22:38 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

I noticed in code_breakpoint::code_breakpoint that we are calling
update_dprintf_command_list once for each breakpoint location, when we
really only need to call this once per breakpoint -- the data updated
by this function, the breakpoint command list -- is per breakpoint,
not per breakpoint location.  Calling update_dprintf_command_list
multiple times is just wasted effort, there's no per location error
checking, we don't even pass the current location to the function.

This commit moves the update_dprintf_command_list call outside of the
per-location loop.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c | 14 +++++++-------
 1 file changed, 7 insertions(+), 7 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 783a05d9a6b..99496f8de76 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -8707,15 +8707,15 @@ code_breakpoint::code_breakpoint (struct gdbarch *gdbarch_,
       /* Do not set breakpoint locations conditions yet.  As locations
 	 are inserted, they get sorted based on their addresses.  Let
 	 the list stabilize to have reliable location numbers.  */
-
-      /* Dynamic printf requires and uses additional arguments on the
-	 command line, otherwise it's an error.  */
-      if (type == bp_dprintf)
-	update_dprintf_command_list (this);
-      else if (extra_string != nullptr)
-	error (_("Garbage '%s' at end of command"), extra_string.get ());
     }
 
+  /* Dynamic printf requires and uses additional arguments on the
+     command line, otherwise it's an error.  */
+  if (type == bp_dprintf)
+    update_dprintf_command_list (this);
+  else if (extra_string != nullptr)
+    error (_("Garbage '%s' at end of command"), extra_string.get ());
+
   /* The order of the locations is now stable.  Set the location
      condition using the location's number.  */
   int loc_num = 1;
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv7 06/11] gdb: don't display inferior list for pending breakpoints
  2023-12-13 22:38           ` [PATCHv7 00/11] thread-specific breakpoints in just some inferiors Andrew Burgess
                               ` (4 preceding siblings ...)
  2023-12-13 22:38             ` [PATCHv7 05/11] gdb: build dprintf commands just once in code_breakpoint constructor Andrew Burgess
@ 2023-12-13 22:38             ` Andrew Burgess
  2023-12-13 22:38             ` [PATCHv7 07/11] gdb: parse pending breakpoint thread/task immediately Andrew Burgess
                               ` (6 subsequent siblings)
  12 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-12-13 22:38 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

I noticed that in the 'info breakpoints' output, GDB sometimes prints
the inferior list for pending breakpoints, this doesn't seem right to
me.  A pending breakpoint has no locations (at least, as far as we
display things in the 'info breakpoints' output), so including an
inferior list seems odd.

Here's what I see right now:

  (gdb) info breakpoint 5
  Num     Type           Disp Enb Address            What
  5       breakpoint     keep y   <PENDING>          foo inf 1
  (gdb)

It's the 'inf 1' at the end of the line that I'm objecting too.

To trigger this behaviour we need to be in a multi-inferior debug
session.  The breakpoint must have been non-pending at some point in
the past, and so have a location assigned to it.

The breakpoint becomes pending again as a result of a shared library
being unloaded.  When this happens the location itself is marked
pending (via bp_location::shlib_disabled).

In print_one_breakpoint_location, in order to print the inferior list
we check that the breakpoint has a location, and that we have multiple
inferiors, but we don't check if the location itself is pending.

This commit adds that check, which means the output is now:

  (gdb) info breakpoint 5
  Num     Type           Disp Enb Address            What
  5       breakpoint     keep y   <PENDING>          foo
  (gdb)

Which I think makes more sense -- indeed, the format without the
inferior list is what we display for a pending breakpoint that has
never had any locations assigned, so I think this change in behaviour
makes GDB more consistent.
---
 gdb/breakpoint.c                         |   2 +-
 gdb/testsuite/gdb.multi/pending-bp-lib.c |  22 ++++
 gdb/testsuite/gdb.multi/pending-bp.c     |  66 ++++++++++++
 gdb/testsuite/gdb.multi/pending-bp.exp   | 126 +++++++++++++++++++++++
 4 files changed, 215 insertions(+), 1 deletion(-)
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.exp

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 99496f8de76..eba2e741a72 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -6597,7 +6597,7 @@ print_one_breakpoint_location (struct breakpoint *b,
 	}
     }
 
-  if (loc != NULL && !header_of_multiple)
+  if (loc != nullptr && !header_of_multiple && !loc->shlib_disabled)
     {
       std::vector<int> inf_nums;
       int mi_only = 1;
diff --git a/gdb/testsuite/gdb.multi/pending-bp-lib.c b/gdb/testsuite/gdb.multi/pending-bp-lib.c
new file mode 100644
index 00000000000..15d1b9833dd
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp-lib.c
@@ -0,0 +1,22 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+int global_var = 0;
+
+void
+foo (int arg)
+{
+  global_var = arg;
+}
diff --git a/gdb/testsuite/gdb.multi/pending-bp.c b/gdb/testsuite/gdb.multi/pending-bp.c
new file mode 100644
index 00000000000..879e0b11ac7
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp.c
@@ -0,0 +1,66 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#include <dlfcn.h>
+#include <stdlib.h>
+
+void
+breakpt (void)
+{
+  /* Nothing.  */
+}
+
+volatile int global_counter = 0;
+
+volatile int call_count = 1;
+
+int
+main (void)
+{
+  void *handle;
+  void (*func)(int);
+
+  /* Some filler work so that we don't initially stop on the breakpt call
+     below.  */
+  ++global_counter;
+
+  breakpt ();	/* Break before open.  */
+
+  /* Now load the shared library.  */
+  handle = dlopen (SHLIB_NAME, RTLD_LAZY);
+  if (handle == NULL)
+    abort ();
+
+  breakpt ();	/* Break after open.  */
+
+  /* Find the function symbol.  */
+  func = (void (*)(int)) dlsym (handle, "foo");
+
+  for (; call_count > 0; --call_count)
+    {
+      /* Call the library function.  */
+      func (1);
+    }
+
+  breakpt ();	/* Break before close.  */
+
+  /* Unload the shared library.  */
+  if (dlclose (handle) != 0)
+    abort ();
+
+  breakpt ();	/* Break after close.  */
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.multi/pending-bp.exp b/gdb/testsuite/gdb.multi/pending-bp.exp
new file mode 100644
index 00000000000..478d8d7c037
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp.exp
@@ -0,0 +1,126 @@
+# Copyright 2023 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+# Tests related to pending breakpoints in a multi-inferior environment.
+
+require allow_shlib_tests !use_gdb_stub
+
+standard_testfile
+
+set libname $testfile-lib
+set srcfile_lib $srcdir/$subdir/$libname.c
+set binfile_lib [standard_output_file $libname.so]
+
+if { [gdb_compile_shlib $srcfile_lib $binfile_lib {}] != "" } {
+    untested "failed to compile shared library 1"
+    return -1
+}
+
+set binfile_lib_target [gdb_download_shlib $binfile_lib]
+
+if { [build_executable "failed to prepare" $testfile $srcfile \
+	  [list debug \
+	       additional_flags=-DSHLIB_NAME=\"$binfile_lib_target\" \
+	       shlib_load]] } {
+    return -1
+}
+
+# Start two inferiors, both running the same test binary.  The arguments
+# INF_1_STOP and INF_2_STOP are source code patterns that are passed to
+# gdb_get_line_number to figure out where each inferior should be stopped.
+#
+# This proc does a clean_restart and leaves inferior 2 selected.  Also the
+# 'breakpoint pending' flag is enabled, so pending breakpoints can be created
+# without GDB prompting the user.
+proc do_test_setup { inf_1_stop inf_2_stop } {
+    clean_restart ${::binfile}
+
+    gdb_locate_shlib $::binfile_lib
+
+    if {![runto_main]} {
+	return false
+    }
+
+    gdb_breakpoint [gdb_get_line_number ${inf_1_stop}] temporary
+    gdb_continue_to_breakpoint "move inferior 1 into position"
+
+    gdb_test "add-inferior -exec ${::binfile}" \
+	"Added inferior 2.*" "add inferior 2"
+    gdb_test "inferior 2" "Switching to inferior 2 .*" "switch to inferior 2"
+
+    if {![runto_main]} {
+	return false
+    }
+
+    gdb_breakpoint [gdb_get_line_number ${inf_2_stop}] temporary
+    gdb_continue_to_breakpoint "move inferior 2 into position"
+
+    gdb_test_no_output "set breakpoint pending on"
+
+    return true
+}
+
+# Check that when a breakpoint is in the pending state, but that breakpoint
+# does have some locations (those locations themselves are pending), GDB
+# doesn't display the inferior list in the 'info breakpoints' output.
+proc_with_prefix test_no_inf_display {} {
+    do_test_setup "Break before open" "Break before open"
+
+    # Create a breakpoint on 'foo'.  As the shared library (that
+    # contains foo) has not been loaded into any inferior yet, then
+    # there will be no locations and the breakpoint will be created
+    # pending.  Pass the 'allow-pending' flag so the gdb_breakpoint
+    # correctly expects the new breakpoint to be pending.
+    gdb_breakpoint "foo" allow-pending
+    set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+		   "get foo breakpoint number"]
+
+    # Check the 'info breakpoints' output; the breakpoint is pending with
+    # no 'inf X' appearing at the end of the line.
+    gdb_test "info breakpoint $bpnum" \
+	"$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	"check info bp before locations have been created"
+
+    # Now select inferior 1 and allow the inferior to run forward to the
+    # point where a breakpoint location for foo will have been created.
+    gdb_test "inferior 1" "Switching to inferior 1 .*"
+    gdb_breakpoint [gdb_get_line_number "Break after open"] temporary
+    gdb_continue_to_breakpoint \
+	"move inferior 1 until a location has been added"
+
+    # Check the 'info breakpoints' output.  Notice we display the inferior
+    # list at the end of the breakpoint line.
+    gdb_test "info breakpoint $bpnum" \
+	"$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex\\s+<foo\[^>\]*>\\s+inf 1" \
+	"check info breakpoints while breakpoint is inserted"
+
+    # Continue inferior 1 until the shared library has been unloaded.  The
+    # breakpoint on 'foo' will return to the pending state.  We will need to
+    # 'continue' twice as the first time will hit the 'foo' breakpoint.
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "hit the breakpoint in foo"
+    gdb_continue_to_breakpoint "after close library"
+
+    # Check the 'info breakpoints' output, check there is no 'inf 1' at the
+    # end of the breakpoint line.
+    gdb_test "info breakpoint $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	     "\\s+breakpoint already hit 1 time"] \
+	"check info breakpoints while breakpoint is pending"
+}
+
+# Run all the tests.
+test_no_inf_display
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv7 07/11] gdb: parse pending breakpoint thread/task immediately
  2023-12-13 22:38           ` [PATCHv7 00/11] thread-specific breakpoints in just some inferiors Andrew Burgess
                               ` (5 preceding siblings ...)
  2023-12-13 22:38             ` [PATCHv7 06/11] gdb: don't display inferior list for pending breakpoints Andrew Burgess
@ 2023-12-13 22:38             ` Andrew Burgess
  2023-12-15 20:53               ` Tom Tromey
  2023-12-13 22:38             ` [PATCHv7 08/11] gdb: don't set breakpoint::pspace for in create_breakpoint Andrew Burgess
                               ` (5 subsequent siblings)
  12 siblings, 1 reply; 138+ messages in thread
From: Andrew Burgess @ 2023-12-13 22:38 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Eli Zaretskii

Eli has already approved the docs changes in this commit.

---

The initial motivation for this commit was to allow thread or inferior
specific breakpoints to only be inserted within the appropriate
inferior's program-space.  The benefit of this is that inferiors for
which the breakpoint does not apply will no longer need to stop, and
then resume, for such breakpoints.  This commit does not make this
change, but is a refactor to allow this to happen in a later commit.

The problem we currently have is that when a thread-specific (or
inferior-specific) breakpoint is created, the thread (or inferior)
number is only parsed by calling find_condition_and_thread_for_sals.
This function is only called for non-pending breakpoints, and requires
that we know the locations at which the breakpoint will be placed (for
expression checking in case the breakpoint is also conditional).

A consequence of this is that by the time we figure out the breakpoint
is thread-specific we have already looked up locations in all program
spaces.  This feels wasteful -- if we knew the thread-id earlier then
we could reduce the work GDB does by only looking up locations within
the program space for which the breakpoint applies.

Another consequence of how find_condition_and_thread_for_sals is
called is that pending breakpoints don't currently know they are
thread-specific, nor even that they are conditional!  Additionally, by
delaying parsing the thread-id, pending breakpoints can be created for
non-existent threads, this is different to how non-pending
breakpoints are handled, so I can do this:

  $ gdb -q ./gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp
  Reading symbols from ./gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp...
  (gdb) break foo thread 99
  Function "foo" not defined.
  Make breakpoint pending on future shared library load? (y or [n]) y
  Breakpoint 1 (foo thread 99) pending.
  (gdb) r
  Starting program: /tmp/gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp
  [Thread debugging using libthread_db enabled]
  Using host libthread_db library "/lib64/libthread_db.so.1".
  Error in re-setting breakpoint 1: Unknown thread 99.
  [Inferior 1 (process 3329749) exited normally]
  (gdb)

GDB only checked the validity of 'thread 99' at the point the 'foo'
location became non-pending.  In contrast, if I try this:

  $ gdb -q ./gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp
  Reading symbols from ./gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp...
  (gdb) break main thread 99
  Unknown thread 99.
  (gdb)

GDB immediately checks if 'thread 99' exists.  I think inconsistencies
like this are confusing, and should be fixed if possible.

In this commit the create_breakpoint function is updated so that the
extra_string, which contains the thread, inferior, task, and/or
condition information, is parsed immediately, even for pending
breakpoints.

Obviously, the condition still can't be validated until the breakpoint
becomes non-pending, but the thread, inferior, and task information
can be pulled from the extra-string, and can be validated early on,
even for pending breakpoints.  The -force-condition flag is also
parsed as part of this early parsing change.

There are a couple of benefits to doing this:

1. Printing of breakpoints is more consistent now.  Consider creating
   a conditional breakpoint before this commit:

    (gdb) set breakpoint pending on
    (gdb) break pendingfunc if (0)
    Function "pendingfunc" not defined.
    Breakpoint 1 (pendingfunc if (0)) pending.
    (gdb) break main if (0)
    Breakpoint 2 at 0x401198: file /tmp/hello.c, line 18.
    (gdb) info breakpoints
    Num     Type           Disp Enb Address            What
    1       breakpoint     keep y   <PENDING>          pendingfunc if (0)
    2       breakpoint     keep y   0x0000000000401198 in main at /tmp/hello.c:18
            stop only if (0)
    (gdb)

   And after this commit:

    (gdb) set breakpoint pending on
    (gdb) break pendingfunc if (0)
    Function "pendingfunc" not defined.
    Breakpoint 1 (pendingfunc) pending.
    (gdb) break main if (0)
    Breakpoint 2 at 0x401198: file /home/andrew/tmp/hello.c, line 18.
    (gdb) info breakpoints
    Num     Type           Disp Enb Address            What
    1       breakpoint     keep y   <PENDING>          pendingfunc
            stop only if (0)
    2       breakpoint     keep y   0x0000000000401198 in main at /home/andrew/tmp/hello.c:18
            stop only if (0)
    (gdb)

   Notice that the display of the condition is now the same for the
   pending and non-pending breakpoints.

   The same is true for the thread, inferior, or task information in
   thread, inferior, or task specific breakpoints; this information is
   displayed on its own line rather than being part of the 'What'
   field.

2. We can check that the thread exists as soon as the pending
   breakpoint is created.  Currently there is a weird difference
   between pending and non-pending breakpoints when creating a
   thread-specific breakpoint.

   A pending thread-specific breakpoint only checks its thread when it
   becomes non-pending, at which point the thread the breakpoint was
   intended for might have exited.  Here's the behaviour before this
   commit:

    (gdb) set breakpoint pending on
    (gdb) break foo thread 2
    Function "foo" not defined.
    Breakpoint 2 (foo thread 2) pending.
    (gdb) c
    Continuing.
    [Thread 0x7ffff7c56700 (LWP 2948835) exited]
    Error in re-setting breakpoint 2: Unknown thread 2.
    [Inferior 1 (process 2948832) exited normally]
    (gdb)

   Notice the 'Error in re-setting breakpoint 2: Unknown thread 2.'
   line, this was triggered when GDB tried to make the breakpoint
   non-pending, and GDB discovers that the thread no longer exists.

   Compare that to the behaviour after this commit:

    (gdb) set breakpoint pending on
    (gdb) break foo thread 2
    Function "foo" not defined.
    Breakpoint 2 (foo) pending.
    (gdb) c
    Continuing.
    [Thread 0x7ffff7c56700 (LWP 2949243) exited]
    Thread-specific breakpoint 2 deleted - thread 2 no longer in the thread list.
    [Inferior 1 (process 2949240) exited normally]
    (gdb)

   Now the behaviour for pending breakpoints is identical to
   non-pending breakpoints, the thread specific breakpoint is removed
   as soon as the thread the breakpoint is associated with exits.

   There is an additional change; when the pending breakpoint is
   created prior to this patch we see this line:

     Breakpoint 2 (foo thread 2) pending.

   While after this patch we get this line:

     Breakpoint 2 (foo) pending.

   Notice that 'thread 2' has disappeared.  This might look like a
   regression, but I don't think it is.  That we said 'thread 2'
   before was just a consequence of the lazy parsing of the breakpoint
   specification, while with this patch GDB understands, and has
   parsed away the 'thread 2' bit of the spec.  If folk think the old
   information was useful then this would be trivial to add back in
   code_breakpoint::say_where.

As a result of this commit the breakpoints 'extra_string' field is now
only used by bp_dprintf type breakpoints to hold the printf format and
arguments.  This string should always be empty for other breakpoint
types.  This allows me to clean up some code in
print_breakpoint_location.

In code_breakpoint::code_breakpoint I'm able to change an error case
into an assert.  This is because this error is now handled earlier in
create_breakpoint.  As a result we know that by this point, the
extra_string will always be nullptr for anything other than a
bp_dprintf style breakpoint.

The find_condition_and_thread_for_sals function is now no longer
needed, this was previously doing the delayed splitting of the extra
string into thread, task, and condition, but this is now all done in
create_breakpoint, so find_condition_and_thread_for_sals can be
deleted, and the code that calls this in
code_breakpoint::location_spec_to_sals can be removed.  With this
update this code would only ever be reached for bp_dprintf style
breakpoints, and in these cases the extra_string should not contain
anything other than format and args.

The most interesting changes are all in create_breakpoint and in the
new file break-cond-parse.c.  We have a new block of code early on in
create_breakpoint that is responsible for splitting the extra_string
into its component parts by calling create_breakpoint_parse_arg_string
a function in the new break-cond-parse.c file.  This means that some
of the later code can be simplified a little.

The new break-cond-parse.c file implements the splitting up the
extra_string and finding all the parts, as well as some self-tests for
the new function.

Finally, now we know all the details, these can be stored within the
breakpoint object if we end up creating a deferred breakpoint.
Additionally, if we are creating a deferred bp_dprintf we can parse
the extra_string to build the printf command.

The implementation here aims to maintain backwards compatibility as
much as possible, this means that:

  1. We support abbreviations of 'thread', 'task', and 'inferior' in
  some places on the breakpoint line.  The handling of abbreviations
  has (before this patch) been a little weird, so this works:

  (gdb) break *main th 1

  And creates a breakpoint at '*main' for thread 1 only, while this
  does not work:

  (gdb) break main th 1

  In this case GDB will try to find the symbol 'main th 1'.  This
  weirdness exists before and after this patch.

  2. The handling of '-force-condition' is odd, if this flag appears
  immediately after a condition then it will be treated as part of the
  condition, e.g.:

  (gdb) break main if 0 -force-condition
  No symbol "force" in current context.

  But we are fine with these alternatives:

  (gdb) break main if 0 thread 1 -force-condition
  (gdb) break main -force-condition if 0

  Again, this is just a quirk of how the breakpoint line used to be
  parsed, but I've chosen to maintain this for backward
  compatibility.  Maybe in the future we might wish to consider
  changing this behaviour, but I'd rather do that as a separate commit
  later on, if that was of interest to people.

Reviewed-By: Eli Zaretskii <eliz@gnu.org>
---
 gdb/Makefile.in                               |   2 +
 gdb/NEWS                                      |   4 +
 gdb/break-cond-parse.c                        | 425 ++++++++++++++++++
 gdb/break-cond-parse.h                        |  49 ++
 gdb/breakpoint.c                              | 372 ++++-----------
 gdb/testsuite/gdb.ada/tasks.exp               |   6 +-
 gdb/testsuite/gdb.base/condbreak.exp          |  57 ++-
 gdb/testsuite/gdb.base/pending.exp            |  23 +-
 gdb/testsuite/gdb.linespec/explicit.exp       |   4 +-
 gdb/testsuite/gdb.mi/mi-dprintf-pending.exp   |   3 +-
 .../gdb.multi/inferior-specific-bp.exp        |   4 +-
 .../gdb.threads/del-pending-thread-bp-lib.c   |  22 +
 .../gdb.threads/del-pending-thread-bp.c       |  85 ++++
 .../gdb.threads/del-pending-thread-bp.exp     | 108 +++++
 14 files changed, 862 insertions(+), 302 deletions(-)
 create mode 100644 gdb/break-cond-parse.c
 create mode 100644 gdb/break-cond-parse.h
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.exp

diff --git a/gdb/Makefile.in b/gdb/Makefile.in
index 0886c0e8495..d6747aa640c 100644
--- a/gdb/Makefile.in
+++ b/gdb/Makefile.in
@@ -1028,6 +1028,7 @@ COMMON_SFILES = \
 	break-catch-sig.c \
 	break-catch-syscall.c \
 	break-catch-throw.c \
+	break-cond-parse.c \
 	breakpoint.c \
 	bt-utils.c \
 	btrace.c \
@@ -1296,6 +1297,7 @@ HFILES_NO_SRCDIR = \
 	bfd-target.h \
 	bfin-tdep.h \
 	block.h \
+	break-cond-parse.h \
 	breakpoint.h \
 	bsd-kvm.h \
 	bsd-uthread.h \
diff --git a/gdb/NEWS b/gdb/NEWS
index 534e2e7f364..72f5a15bd26 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -9,6 +9,10 @@
 * GDB index now contains information about the main function.  This speeds up
   startup when it is being used for some large binaries.
 
+* For breakpoints that are created in the 'pending' state, any
+  'thread' or 'task' keywords are parsed at the time the breakpoint is
+  created, rather than at the time the breakpoint becomes non-pending.
+
 * Changed commands
 
 disassemble
diff --git a/gdb/break-cond-parse.c b/gdb/break-cond-parse.c
new file mode 100644
index 00000000000..a93983f6294
--- /dev/null
+++ b/gdb/break-cond-parse.c
@@ -0,0 +1,425 @@
+/* Copyright (C) 2023 Free Software Foundation, Inc.
+
+   This file is part of GDB.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#include "defs.h"
+#include "gdbsupport/gdb_assert.h"
+#include "gdbsupport/selftest.h"
+#include "test-target.h"
+#include "scoped-mock-context.h"
+#include "break-cond-parse.h"
+#include "tid-parse.h"
+#include "ada-lang.h"
+
+/* When parsing tokens from a string, which direction are we parsing?
+
+   Given the following string and pointer 'ptr':
+
+	ABC DEF GHI JKL
+	       ^
+	       ptr
+
+   Parsing 'forward' will return the token 'GHI' and update 'ptr' to point
+   between GHI and JKL.  Parsing 'backward' will return the token 'DEF' and
+   update 'ptr' to point between ABC and DEF.
+*/
+
+enum class parse_direction
+{
+  /* Parse the next token forwards.  */
+  forward,
+
+  /* Parse the previous token backwards.  */
+  backward
+};
+
+/* The tokens we parse are just views into the string from which the tokens
+   are being parsed.  */
+
+using token = std::string_view;
+
+/* Return true if STR starts with PREFIX, otherwise return false.  */
+
+static bool
+startswith (const char *str, const token &prefix)
+{
+  return strncmp (str, prefix.data (), prefix.length ()) == 0;
+}
+
+/* Find the next token in DIRECTION from *CURR.  */
+
+static token
+find_next_token (const char **curr, parse_direction direction)
+{
+  const char *tok_start, *tok_end;
+
+  gdb_assert (**curr != '\0');
+
+  if (direction == parse_direction::forward)
+    {
+      *curr = skip_spaces (*curr);
+      tok_start = *curr;
+      *curr = skip_to_space (*curr);
+      tok_end = *curr - 1;
+    }
+  else
+    {
+      gdb_assert (direction == parse_direction::backward);
+
+      while (isspace (**curr))
+	--(*curr);
+
+      tok_end = *curr;
+
+      while (!isspace (**curr))
+	--(*curr);
+
+      tok_start = (*curr) + 1;
+    }
+
+  return token (tok_start, tok_end - tok_start + 1);
+}
+
+/* See break-cond-parse.h.  */
+
+void
+create_breakpoint_parse_arg_string
+  (const char *tok, gdb::unique_xmalloc_ptr<char> *cond_string,
+   int *thread, int *inferior, int *task,
+   gdb::unique_xmalloc_ptr<char> *rest, bool *force)
+{
+  /* Set up the defaults.  */
+  cond_string->reset ();
+  rest->reset ();
+  *thread = -1;
+  *inferior = -1;
+  *task = -1;
+  *force = false;
+
+  if (tok == nullptr)
+    return;
+
+  /* The "-force-condition" flag gets some special treatment.  If this
+     token is immediately after the condition string then we treat this as
+     part of the condition string rather than a separate token.  This is
+     just a quirk of how this token used to be parsed, and has been
+     retained for backwards compatibility.  Maybe this should be updated
+     in the future.  */
+  std::optional<token> force_condition_token;
+
+  const char *cond_start = nullptr;
+  const char *cond_end = nullptr;
+  parse_direction direction = parse_direction::forward;
+  while (*tok != '\0')
+    {
+      /* Find the next token.  If moving backward and this token starts at
+	 the same location as the condition then we must have found the
+	 other end of the condition string -- we're done.  */
+      token t = find_next_token (&tok, direction);
+      if (direction == parse_direction::backward && t.data () <= cond_start)
+	{
+	  cond_end = &t.back ();
+	  break;
+	}
+
+      /* We only have a single flag option to check for.  All the other
+	 options take a value so require an additional token to be found.
+	 Additionally, we require that this flag be at least '-f', we
+	 don't allow it to be abbreviated to '-'.  */
+      if (t.length () > 1 && startswith ("-force-condition", t))
+	{
+	  force_condition_token.emplace (t);
+	  continue;
+	}
+
+      /* Maybe the first token was the last token in the string.  If this
+	 is the case then we definitely can't try to extract a value
+	 token.  This also means that the token T is meaningless.  Reset
+	 TOK to point at the start of the unknown content and break out of
+	 the loop.  We'll record the unknown part of the string outside of
+	 the scanning loop (below).  */
+      if (direction == parse_direction::forward && *tok == '\0')
+	{
+	  tok = t.data ();
+	  break;
+	}
+
+      /* As before, find the next token and, if we are scanning backwards,
+	 check that we have not reached the start of the condition string.  */
+      token v = find_next_token (&tok, direction);
+      if (direction == parse_direction::backward && v.data () <= cond_start)
+	{
+	  /* Use token T here as that must also be part of the condition
+	     string.  */
+	  cond_end = &t.back ();
+	  break;
+	}
+
+      /* When moving backward we will first parse the value token then the
+	 keyword token, so swap them now.  */
+      if (direction == parse_direction::backward)
+	std::swap (t, v);
+
+      /* Check for valid option in token T.  If we find a valid option then
+	 parse the value from the token V.  Except for 'if', that's handled
+	 differently.
+
+	 For the 'if' token we need to capture the entire condition
+	 string, so record the start of the condition string and then
+	 start scanning backwards looking for the end of the condition
+	 string.
+
+	 The order of these checks is important, at least the check for
+	 'thread' must occur before the check for 'task'.  We accept
+	 abbreviations of these token names, and 't' should resolve to
+	 'thread', which will only happen if we check 'thread' first.  */
+      if (direction == parse_direction::forward && startswith ("if", t))
+	{
+	  cond_start = v.data ();
+	  tok = tok + strlen (tok);
+	  gdb_assert (*tok == '\0');
+	  --tok;
+	  direction = parse_direction::backward;
+	  continue;
+	}
+      else if (startswith ("thread", t))
+	{
+	  if (*thread != -1)
+	    error(_("You can specify only one thread."));
+
+	  if (*task != -1 || *inferior != -1)
+	    error (_("You can specify only one of thread, inferior, or task."));
+
+	  const char *tmptok;
+	  thread_info *thr = parse_thread_id (v.data (), &tmptok);
+	  const char *expected_end = skip_spaces (v.data () + v.length ());
+	  if (tmptok != expected_end)
+	    error (_("Junk after thread keyword."));
+	  *thread = thr->global_num;
+	}
+      else if (startswith ("inferior", t))
+	{
+	  if (*inferior != -1)
+	    error(_("You can specify only one inferior."));
+
+	  if (*task != -1 || *thread != -1)
+	    error (_("You can specify only one of thread, inferior, or task."));
+
+	  char *tmptok;
+	  *inferior = strtol (v.data (), &tmptok, 0);
+	  const char *expected_end = v.data () + v.length ();
+	  if (tmptok != expected_end)
+	    error (_("Junk after inferior keyword."));
+	}
+      else if (startswith ("task", t))
+	{
+	  if (*task != -1)
+	    error(_("You can specify only one task."));
+
+	  if (*thread != -1 || *inferior != -1)
+	    error (_("You can specify only one of thread, inferior, or task."));
+
+	  char *tmptok;
+	  *task = strtol (v.data (), &tmptok, 0);
+	  const char *expected_end = v.data () + v.length ();
+	  if (tmptok != expected_end)
+	    error (_("Junk after task keyword."));
+	  if (!valid_task_id (*task))
+	    error (_("Unknown task %d."), *task);
+	}
+      else
+	{
+	  /* An unknown token.  If we are scanning forward then reset TOK
+	     to point at the start of the unknown content, we record this
+	     outside of the scanning loop (below).
+
+	     If we are scanning backward then unknown content is assumed to
+	     be the other end of the condition string, obviously, this is
+	     just a heuristic, we could be looking at a mistyped command
+	     line, but this will be spotted when the condition is
+	     eventually evaluated.
+
+	     Either way, no more scanning is required after this.  */
+	  if (direction == parse_direction::forward)
+	    tok = t.data ();
+	  else
+	    {
+	      gdb_assert (direction == parse_direction::backward);
+	      cond_end = &v.back ();
+	    }
+	  break;
+	}
+    }
+
+  if (cond_start != nullptr)
+    {
+      /* If we found the start of a condition string then we should have
+	 switched to backward scan mode, and found the end of the condition
+	 string.  Capture the whole condition string into COND_STRING
+	 now.  */
+      gdb_assert (direction == parse_direction::backward);
+      gdb_assert (cond_end != nullptr);
+
+      /* If the first token after the condition string is the
+	 "-force-condition" token, then we merge the "-force-condition"
+	 token with the condition string and forget ever seeing the
+	 "-force-condition".  */
+      if (force_condition_token.has_value ())
+	{
+	  const char *next_token_start = skip_spaces (cond_end + 1);
+
+	  if (next_token_start == force_condition_token->data ())
+	    {
+	      cond_end = force_condition_token->end ();
+	      force_condition_token.reset ();
+	    }
+	}
+
+      /* The '+ 1' here is because COND_END points to the last character of
+	 the condition string rather than the null-character at the end of
+	 the condition string, and we need the string length here.  */
+      cond_string->reset (savestring (cond_start, cond_end - cond_start + 1));
+    }
+  else if (*tok != '\0')
+    {
+      /* If we didn't have a condition start pointer then we should still
+	 be in forward scanning mode.  If we didn't reach the end of the
+	 input string (TOK is not at the null character) then the rest of
+	 the input string is garbage that we didn't understand.
+
+	 Record the unknown content into REST.  The caller of this function
+	 will report this as an error later on.  We could report the error
+	 here, but we prefer to allow the caller to run other checks, and
+	 prioritise other errors before reporting this problem.  */
+      gdb_assert (direction == parse_direction::forward);
+      gdb_assert (cond_end == nullptr);
+      rest->reset (savestring (tok, strlen (tok)));
+    }
+
+  /* If we saw "-force-condition" then set the *FORCE flag.  Depending on
+     which path we took above we might have chosen to forget having seen
+     the "-force-condition" token.  */
+  if (force_condition_token.has_value ())
+    *force = true;
+}
+
+#if GDB_SELF_TEST
+
+namespace selftests {
+
+/* Run a single test of the create_breakpoint_parse_arg_string function.
+   INPUT is passed to create_breakpoint_parse_arg_string while all other
+   arguments are the expected output from
+   create_breakpoint_parse_arg_string.  */
+
+static void
+test (const char *input, const char *condition, int thread = -1,
+      int inferior = -1, int task = -1, bool force = false,
+      const char *rest = nullptr)
+{
+  gdb::unique_xmalloc_ptr<char> extracted_condition;
+  gdb::unique_xmalloc_ptr<char> extracted_rest;
+  int extracted_thread, extracted_inferior, extracted_task;
+  bool extracted_force_condition;
+  std::string exception_msg;
+
+  try
+    {
+      create_breakpoint_parse_arg_string (input, &extracted_condition,
+					  &extracted_thread,
+					  &extracted_inferior,
+					  &extracted_task, &extracted_rest,
+					  &extracted_force_condition);
+    }
+  catch (const gdb_exception_error &ex)
+    {
+      string_file buf;
+
+      exception_print (&buf, ex);
+      exception_msg = buf.release ();
+    }
+
+  if ((condition == nullptr) != (extracted_condition.get () == nullptr)
+      || (condition != nullptr
+	  && strcmp (condition, extracted_condition.get ()) != 0)
+      || (rest == nullptr) != (extracted_rest.get () == nullptr)
+      || (rest != nullptr && strcmp (rest, extracted_rest.get ()) != 0)
+      || thread != extracted_thread
+      || inferior != extracted_inferior
+      || task != extracted_task
+      || force != extracted_force_condition
+      || !exception_msg.empty ())
+    {
+      if (run_verbose ())
+	{
+	  debug_printf ("input: '%s'\n", input);
+	  debug_printf ("condition: '%s'\n", extracted_condition.get ());
+	  debug_printf ("rest: '%s'\n", extracted_rest.get ());
+	  debug_printf ("thread: %d\n", extracted_thread);
+	  debug_printf ("inferior: %d\n", extracted_inferior);
+	  debug_printf ("task: %d\n", extracted_task);
+	  debug_printf ("forced: %s\n",
+			extracted_force_condition ? "true" : "false");
+	  debug_printf ("exception: '%s'\n", exception_msg.c_str ());
+	}
+
+      /* Report the failure.  */
+      SELF_CHECK (false);
+    }
+}
+
+/* Test the create_breakpoint_parse_arg_string function.  Just wraps
+   multiple calls to the test function above.  */
+
+static void
+create_breakpoint_parse_arg_string_tests (void)
+{
+  gdbarch *arch = current_inferior ()->arch ();
+  scoped_restore_current_pspace_and_thread restore;
+  scoped_mock_context<test_target_ops> mock_target (arch);
+
+  int global_thread_num = mock_target.mock_thread.global_num;
+
+  test ("  if blah  ", "blah");
+  test (" if blah thread 1", "blah", global_thread_num);
+  test (" if blah inferior 1", "blah", -1, 1);
+  test (" if blah thread 1  ", "blah", global_thread_num);
+  test ("thread 1 woof", nullptr, global_thread_num, -1, -1, false, "woof");
+  test ("thread 1 X", nullptr, global_thread_num, -1, -1, false, "X");
+  test (" if blah thread 1 -force-condition", "blah", global_thread_num,
+	-1, -1, true);
+  test (" -force-condition if blah thread 1", "blah", global_thread_num,
+	-1, -1, true);
+  test (" -force-condition if blah thread 1  ", "blah", global_thread_num,
+	-1, -1, true);
+  test ("thread 1 -force-condition if blah", "blah", global_thread_num,
+	-1, -1, true);
+  test ("if (A::outer::func ())", "(A::outer::func ())");
+}
+
+} // namespace selftests
+#endif /* GDB_SELF_TEST */
+
+void _initialize_break_cond_parse ();
+void
+_initialize_break_cond_parse ()
+{
+#if GDB_SELF_TEST
+  selftests::register_test
+    ("create_breakpoint_parse_arg_string",
+     selftests::create_breakpoint_parse_arg_string_tests);
+#endif
+}
diff --git a/gdb/break-cond-parse.h b/gdb/break-cond-parse.h
new file mode 100644
index 00000000000..b08b6fc6cc9
--- /dev/null
+++ b/gdb/break-cond-parse.h
@@ -0,0 +1,49 @@
+/* Copyright (C) 2023 Free Software Foundation, Inc.
+
+   This file is part of GDB.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#if !defined (BREAK_COND_PARSE_H)
+#define BREAK_COND_PARSE_H 1
+
+/* Given TOK, a string possibly containing a condition, thread, inferior,
+   task and force-condition flag, as accepted by the 'break' command,
+   extract the condition string, thread, inferior, task number, and the
+   force_condition flag, then set *COND_STRING, *THREAD, *INFERIOR, *TASK,
+   and *FORCE.
+
+   As TOK is parsed, if an unknown keyword is encountered before the 'if'
+   keyword then everything starting from the unknown keyword is placed into
+   *REST.
+
+   Both *COND and *REST are initialized to nullptr.  If no 'if' keyword is
+   found then *COND will be returned as nullptr.  If no unknown content is
+   found then *REST is returned as nullptr.
+
+   If no thread is found, *THREAD is set to -1.  If no inferior is found,
+   *INFERIOR is set to -1.  If no task is found, *TASK is set to -1.  If
+   the -force-condition flag is not found then *FORCE is set to false.
+
+   Due to the free-form nature that the string TOK might take (a 'thread'
+   keyword can appear before or after an 'if' condition) then we end up
+   having to check for keywords from both the start of TOK and the end of
+   TOK.  */
+
+extern void create_breakpoint_parse_arg_string
+  (const char *tok, gdb::unique_xmalloc_ptr<char> *cond_string,
+   int *thread, int *inferior, int *task,
+   gdb::unique_xmalloc_ptr<char> *rest, bool *force);
+
+#endif
diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index eba2e741a72..e672e6a7699 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -70,6 +70,7 @@
 #include "cli/cli-style.h"
 #include "cli/cli-decode.h"
 #include <unordered_set>
+#include "break-cond-parse.h"
 
 /* readline include files */
 #include "readline/tilde.h"
@@ -6335,20 +6336,7 @@ print_breakpoint_location (const breakpoint *b, const bp_location *loc)
       uiout->field_stream ("at", stb);
     }
   else
-    {
-      uiout->field_string ("pending", b->locspec->to_string ());
-      /* If extra_string is available, it could be holding a condition
-	 or dprintf arguments.  In either case, make sure it is printed,
-	 too, but only for non-MI streams.  */
-      if (!uiout->is_mi_like_p () && b->extra_string != NULL)
-	{
-	  if (b->type == bp_dprintf)
-	    uiout->text (",");
-	  else
-	    uiout->text (" ");
-	  uiout->text (b->extra_string.get ());
-	}
-    }
+    uiout->field_string ("pending", b->locspec->to_string ());
 
   if (loc && is_breakpoint (b)
       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
@@ -8713,8 +8701,8 @@ code_breakpoint::code_breakpoint (struct gdbarch *gdbarch_,
      command line, otherwise it's an error.  */
   if (type == bp_dprintf)
     update_dprintf_command_list (this);
-  else if (extra_string != nullptr)
-    error (_("Garbage '%s' at end of command"), extra_string.get ());
+  else
+    gdb_assert (extra_string == nullptr);
 
   /* The order of the locations is now stable.  Set the location
      condition using the location's number.  */
@@ -8942,197 +8930,6 @@ check_fast_tracepoint_sals (struct gdbarch *gdbarch,
     }
 }
 
-/* Given TOK, a string specification of condition and thread, as accepted
-   by the 'break' command, extract the condition string into *COND_STRING.
-   If no condition string is found then *COND_STRING is set to nullptr.
-
-   If the breakpoint specification has an associated thread, task, or
-   inferior, these are extracted into *THREAD, *TASK, and *INFERIOR
-   respectively, otherwise these arguments are set to -1 (for THREAD and
-   INFERIOR) or 0 (for TASK).
-
-   PC identifies the context at which the condition should be parsed.  */
-
-static void
-find_condition_and_thread (const char *tok, CORE_ADDR pc,
-			   gdb::unique_xmalloc_ptr<char> *cond_string,
-			   int *thread, int *inferior, int *task,
-			   gdb::unique_xmalloc_ptr<char> *rest)
-{
-  cond_string->reset ();
-  *thread = -1;
-  *inferior = -1;
-  *task = -1;
-  rest->reset ();
-  bool force = false;
-
-  while (tok && *tok)
-    {
-      const char *end_tok;
-      int toklen;
-      const char *cond_start = NULL;
-      const char *cond_end = NULL;
-
-      tok = skip_spaces (tok);
-
-      if ((*tok == '"' || *tok == ',') && rest)
-	{
-	  rest->reset (savestring (tok, strlen (tok)));
-	  break;
-	}
-
-      end_tok = skip_to_space (tok);
-
-      toklen = end_tok - tok;
-
-      if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
-	{
-	  tok = cond_start = end_tok + 1;
-	  try
-	    {
-	      parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
-	    }
-	  catch (const gdb_exception_error &)
-	    {
-	      if (!force)
-		throw;
-	      else
-		tok = tok + strlen (tok);
-	    }
-	  cond_end = tok;
-	  cond_string->reset (savestring (cond_start, cond_end - cond_start));
-	}
-      else if (toklen >= 1 && strncmp (tok, "-force-condition", toklen) == 0)
-	{
-	  tok = tok + toklen;
-	  force = true;
-	}
-      else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
-	{
-	  const char *tmptok;
-	  struct thread_info *thr;
-
-	  if (*thread != -1)
-	    error(_("You can specify only one thread."));
-
-	  if (*task != -1)
-	    error (_("You can specify only one of thread or task."));
-
-	  if (*inferior != -1)
-	    error (_("You can specify only one of inferior or thread."));
-
-	  tok = end_tok + 1;
-	  thr = parse_thread_id (tok, &tmptok);
-	  if (tok == tmptok)
-	    error (_("Junk after thread keyword."));
-	  *thread = thr->global_num;
-	  tok = tmptok;
-	}
-      else if (toklen >= 1 && strncmp (tok, "inferior", toklen) == 0)
-	{
-	  if (*inferior != -1)
-	    error(_("You can specify only one inferior."));
-
-	  if (*task != -1)
-	    error (_("You can specify only one of inferior or task."));
-
-	  if (*thread != -1)
-	    error (_("You can specify only one of inferior or thread."));
-
-	  char *tmptok;
-	  tok = end_tok + 1;
-	  *inferior = strtol (tok, &tmptok, 0);
-	  if (tok == tmptok)
-	    error (_("Junk after inferior keyword."));
-	  if (!valid_global_inferior_id (*inferior))
-	    error (_("Unknown inferior number %d."), *inferior);
-	  tok = tmptok;
-	}
-      else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
-	{
-	  char *tmptok;
-
-	  if (*task != -1)
-	    error(_("You can specify only one task."));
-
-	  if (*thread != -1)
-	    error (_("You can specify only one of thread or task."));
-
-	  if (*inferior != -1)
-	    error (_("You can specify only one of inferior or task."));
-
-	  tok = end_tok + 1;
-	  *task = strtol (tok, &tmptok, 0);
-	  if (tok == tmptok)
-	    error (_("Junk after task keyword."));
-	  if (!valid_task_id (*task))
-	    error (_("Unknown task %d."), *task);
-	  tok = tmptok;
-	}
-      else if (rest)
-	{
-	  rest->reset (savestring (tok, strlen (tok)));
-	  break;
-	}
-      else
-	error (_("Junk at end of arguments."));
-    }
-}
-
-/* Call 'find_condition_and_thread' for each sal in SALS until a parse
-   succeeds.  The parsed values are written to COND_STRING, THREAD,
-   TASK, and REST.  See the comment of 'find_condition_and_thread'
-   for the description of these parameters and INPUT.  */
-
-static void
-find_condition_and_thread_for_sals (const std::vector<symtab_and_line> &sals,
-				    const char *input,
-				    gdb::unique_xmalloc_ptr<char> *cond_string,
-				    int *thread, int *inferior, int *task,
-				    gdb::unique_xmalloc_ptr<char> *rest)
-{
-  int num_failures = 0;
-  for (auto &sal : sals)
-    {
-      gdb::unique_xmalloc_ptr<char> cond;
-      int thread_id = -1;
-      int inferior_id = -1;
-      int task_id = -1;
-      gdb::unique_xmalloc_ptr<char> remaining;
-
-      /* Here we want to parse 'arg' to separate condition from thread
-	 number.  But because parsing happens in a context and the
-	 contexts of sals might be different, try each until there is
-	 success.  Finding one successful parse is sufficient for our
-	 goal.  When setting the breakpoint we'll re-parse the
-	 condition in the context of each sal.  */
-      try
-	{
-	  find_condition_and_thread (input, sal.pc, &cond, &thread_id,
-				     &inferior_id, &task_id, &remaining);
-	  *cond_string = std::move (cond);
-	  /* A value of -1 indicates that these fields are unset.  At most
-	     one of these fields should be set (to a value other than -1)
-	     at this point.  */
-	  gdb_assert (((thread_id == -1 ? 1 : 0)
-		       + (task_id == -1 ? 1 : 0)
-		       + (inferior_id == -1 ? 1 : 0)) >= 2);
-	  *thread = thread_id;
-	  *inferior = inferior_id;
-	  *task = task_id;
-	  *rest = std::move (remaining);
-	  break;
-	}
-      catch (const gdb_exception_error &e)
-	{
-	  num_failures++;
-	  /* If no sal remains, do not continue.  */
-	  if (num_failures == sals.size ())
-	    throw;
-	}
-    }
-}
-
 /* Decode a static tracepoint marker spec.  */
 
 static std::vector<symtab_and_line>
@@ -9249,6 +9046,46 @@ create_breakpoint (struct gdbarch *gdbarch,
 	      ? (extra_string != nullptr && !parse_extra)
 	      : (extra_string == nullptr || parse_extra));
 
+  /* Will hold either copies of the similarly named function argument, or
+     will hold a modified version of the function argument, depending on
+     the value of PARSE_EXTRA.  */
+  gdb::unique_xmalloc_ptr<char> cond_string_copy;
+  gdb::unique_xmalloc_ptr<char> extra_string_copy;
+
+  if (parse_extra)
+    {
+      /* Parse EXTRA_STRING splitting the parts out.  */
+      create_breakpoint_parse_arg_string (extra_string, &cond_string_copy,
+					  &thread, &inferior, &task,
+					  &extra_string_copy,
+					  &force_condition);
+
+      /* We could check that EXTRA_STRING_COPY is empty at this point -- it
+	 should be, as we only get here for things that are not bp_dprintf,
+	 however, we prefer to give the location spec parser a chance to
+	 run first, this means the user will get errors about invalid
+	 location spec instead of an error about garbage at the end of the
+	 command line.
+
+	 We still do the EXTRA_STRING_COPY is empty check, just later in
+	 this function.  */
+
+      gdb_assert (thread == -1 || thread > 0);
+      gdb_assert (task == -1 || task > 0);
+      gdb_assert (inferior == -1 || inferior > 0);
+    }
+  else
+    {
+      if (cond_string != nullptr)
+	cond_string_copy.reset (xstrdup (cond_string));
+      if (extra_string != nullptr)
+	extra_string_copy.reset (xstrdup (extra_string));
+    }
+
+  /* Clear these.  Updated values are now held in the *_copy locals.  */
+  cond_string = nullptr;
+  extra_string = nullptr;
+
   try
     {
       ops->create_sals_from_location_spec (locspec, &canonical);
@@ -9284,6 +9121,13 @@ create_breakpoint (struct gdbarch *gdbarch,
 	throw;
     }
 
+  /* Only bp_dprintf breakpoints should have anything in EXTRA_STRING_COPY
+     by this point.  For all other breakpoints this indicates an error.  We
+     could place this check earlier in the function, but we prefer to see
+     errors from the location spec parser before we see this error message.  */
+  if (type_wanted != bp_dprintf && extra_string_copy.get () != nullptr)
+    error (_("Garbage '%s' at end of command"), extra_string_copy.get ());
+
   if (!pending && canonical.lsals.empty ())
     return 0;
 
@@ -9307,63 +9151,31 @@ create_breakpoint (struct gdbarch *gdbarch,
      breakpoint.  */
   if (!pending)
     {
-      gdb::unique_xmalloc_ptr<char> cond_string_copy;
-      gdb::unique_xmalloc_ptr<char> extra_string_copy;
-
-      if (parse_extra)
+      /* Check the validity of the condition.  We should error out if the
+	 condition is invalid at all of the locations and if it is not
+	 forced.  In the PARSE_EXTRA case above, this check is done when
+	 parsing the EXTRA_STRING.  */
+      if (cond_string_copy.get () != nullptr && !force_condition)
 	{
-	  gdb_assert (type_wanted != bp_dprintf);
-
-	  gdb::unique_xmalloc_ptr<char> rest;
-	  gdb::unique_xmalloc_ptr<char> cond;
-
+	  int num_failures = 0;
 	  const linespec_sals &lsal = canonical.lsals[0];
-
-	  find_condition_and_thread_for_sals (lsal.sals, extra_string,
-					      &cond, &thread, &inferior,
-					      &task, &rest);
-
-	  if (rest.get () != nullptr && *(rest.get ()) != '\0')
-	    error (_("Garbage '%s' at end of command"), rest.get ());
-
-	  cond_string_copy = std::move (cond);
-	  extra_string_copy = std::move (rest);
-	}
-      else
-	{
-	  /* Check the validity of the condition.  We should error out
-	     if the condition is invalid at all of the locations and
-	     if it is not forced.  In the PARSE_EXTRA case above, this
-	     check is done when parsing the EXTRA_STRING.  */
-	  if (cond_string != nullptr && !force_condition)
+	  for (const auto &sal : lsal.sals)
 	    {
-	      int num_failures = 0;
-	      const linespec_sals &lsal = canonical.lsals[0];
-	      for (const auto &sal : lsal.sals)
+	      const char *cond = cond_string_copy.get ();
+	      try
 		{
-		  const char *cond = cond_string;
-		  try
-		    {
-		      parse_exp_1 (&cond, sal.pc, block_for_pc (sal.pc), 0);
-		      /* One success is sufficient to keep going.  */
-		      break;
-		    }
-		  catch (const gdb_exception_error &)
-		    {
-		      num_failures++;
-		      /* If this is the last sal, error out.  */
-		      if (num_failures == lsal.sals.size ())
-			throw;
-		    }
+		  parse_exp_1 (&cond, sal.pc, block_for_pc (sal.pc), 0);
+		  /* One success is sufficient to keep going.  */
+		  break;
+		}
+	      catch (const gdb_exception_error &)
+		{
+		  num_failures++;
+		  /* If this is the last sal, error out.  */
+		  if (num_failures == lsal.sals.size ())
+		    throw;
 		}
 	    }
-
-	  /* Create a private copy of condition string.  */
-	  if (cond_string)
-	    cond_string_copy.reset (xstrdup (cond_string));
-	  /* Create a private copy of any extra string.  */
-	  if (extra_string)
-	    extra_string_copy.reset (xstrdup (extra_string));
 	}
 
       ops->create_breakpoints_sal (gdbarch, &canonical,
@@ -9380,21 +9192,16 @@ create_breakpoint (struct gdbarch *gdbarch,
 								 type_wanted);
       b->locspec = locspec->clone ();
 
-      if (parse_extra)
-	b->cond_string = NULL;
-      else
-	{
-	  /* Create a private copy of condition string.  */
-	  b->cond_string.reset (cond_string != NULL
-				? xstrdup (cond_string)
-				: NULL);
-	  b->thread = thread;
-	}
+      /* Create a private copy of the condition string.  */
+      b->cond_string = std::move (cond_string_copy);
+
+      b->thread = thread;
+      b->task = task;
+      b->inferior = inferior;
 
       /* Create a private copy of any extra string.  */
-      b->extra_string.reset (extra_string != NULL
-			     ? xstrdup (extra_string)
-			     : NULL);
+      b->extra_string = std::move (extra_string_copy);
+
       b->ignore_count = ignore_count;
       b->disposition = tempflag ? disp_del : disp_donttouch;
       b->condition_not_parsed = 1;
@@ -9403,9 +9210,12 @@ create_breakpoint (struct gdbarch *gdbarch,
 	   && type_wanted != bp_hardware_breakpoint) || thread != -1)
 	b->pspace = current_program_space;
 
+      if (b->type == bp_dprintf)
+	update_dprintf_command_list (b.get ());
+
       install_breakpoint (internal, std::move (b), 0);
     }
-  
+
   if (canonical.lsals.size () > 1)
     {
       warning (_("Multiple breakpoints were set.\nUse the "
@@ -13146,24 +12956,6 @@ code_breakpoint::location_spec_to_sals (location_spec *locspec,
     {
       for (auto &sal : sals)
 	resolve_sal_pc (&sal);
-      if (condition_not_parsed && extra_string != NULL)
-	{
-	  gdb::unique_xmalloc_ptr<char> local_cond, local_extra;
-	  int local_thread, local_task, local_inferior;
-
-	  find_condition_and_thread_for_sals (sals, extra_string.get (),
-					      &local_cond, &local_thread,
-					      &local_inferior,
-					      &local_task, &local_extra);
-	  gdb_assert (cond_string == nullptr);
-	  if (local_cond != nullptr)
-	    cond_string = std::move (local_cond);
-	  thread = local_thread;
-	  task = local_task;
-	  if (local_extra != nullptr)
-	    extra_string = std::move (local_extra);
-	  condition_not_parsed = 0;
-	}
 
       if (type == bp_static_tracepoint)
 	{
diff --git a/gdb/testsuite/gdb.ada/tasks.exp b/gdb/testsuite/gdb.ada/tasks.exp
index 603d43f7c36..337ee1b6f07 100644
--- a/gdb/testsuite/gdb.ada/tasks.exp
+++ b/gdb/testsuite/gdb.ada/tasks.exp
@@ -55,11 +55,11 @@ gdb_test "watch j task 1 task 3" "You can specify only one task\\."
 
 # Check that attempting to combine 'task' and 'thread' gives an error.
 gdb_test "break break_me task 1 thread 1" \
-    "You can specify only one of thread or task\\."
+    "You can specify only one of thread, inferior, or task\\."
 gdb_test "break break_me thread 1 task 1" \
-    "You can specify only one of thread or task\\."
+    "You can specify only one of thread, inferior, or task\\."
 gdb_test "break break_me inferior 1 task 1" \
-    "You can specify only one of inferior or task\\."
+    "You can specify only one of thread, inferior, or task\\."
 gdb_test "watch j task 1 thread 1" \
     "You can specify only one of thread or task\\."
 gdb_test "watch j thread 1 task 1" \
diff --git a/gdb/testsuite/gdb.base/condbreak.exp b/gdb/testsuite/gdb.base/condbreak.exp
index a5b2a28701b..5a6a42e073b 100644
--- a/gdb/testsuite/gdb.base/condbreak.exp
+++ b/gdb/testsuite/gdb.base/condbreak.exp
@@ -179,6 +179,10 @@ gdb_test "break -q main if (1==1) thread 999" \
     "Unknown thread 999\\."
 gdb_test "break -q main thread 999 if (1==1)" \
     "Unknown thread 999\\."
+gdb_test "break -q main if (1==1) thread 999 -force-condition" \
+    "Unknown thread 999\\."
+gdb_test "break -q main thread 999 if (1==1) -force-condition" \
+    "Unknown thread 999\\."
 
 # Verify that both if and thread can be distinguished from a breakpoint
 # address expression.
@@ -186,20 +190,71 @@ gdb_test "break *main if (1==1) thread 999" \
     "Unknown thread 999\\."
 gdb_test "break *main thread 999 if (1==1)" \
     "Unknown thread 999\\."
+gdb_test "break *main if (1==1) thread 999 -force-condition" \
+    "Unknown thread 999\\."
+gdb_test "break *main thread 999 if (1==1) -force-condition" \
+    "Unknown thread 999\\."
 
 # Similarly for task.
 gdb_test "break *main if (1==1) task 999" \
     "Unknown task 999\\."
 gdb_test "break *main task 999 if (1==1)" \
     "Unknown task 999\\."
+gdb_test "break *main if (1==1) task 999 -force-condition" \
+    "Unknown task 999\\."
+gdb_test "break *main task 999 if (1==1) -force-condition" \
+    "Unknown task 999\\."
 
-# GDB accepts abbreviations for "thread" and "task".
+# GDB accepts abbreviations for "thread", "task" and
+# "-force-condition", when these keywords appear after
+# the breakpoint condition.
 gdb_test "break *main if (1==1) t 999" \
     "Unknown thread 999\\."
 gdb_test "break *main if (1==1) th 999" \
     "Unknown thread 999\\."
 gdb_test "break *main if (1==1) ta 999" \
     "Unknown task 999\\."
+gdb_test "break *main if (1==1) t 999 -force" \
+    "Unknown thread 999\\."
+gdb_test "break *main if (1==1) th 999 -force" \
+    "Unknown thread 999\\."
+gdb_test "break *main if (1==1) ta 999 -force" \
+    "Unknown task 999\\."
+
+# Check the use of abbreviations before the condition.  This works
+# because, when the location spec starts with '*' GDB is able to
+# figure out that the complete location is '*main'.
+gdb_test "break *main t 999 if (1==1)" \
+    "Unknown thread 999\\."
+gdb_test "break *main th 999 if (1==1)" \
+    "Unknown thread 999\\."
+gdb_test "break *main ta 999 if (1==1)" \
+    "Unknown task 999\\."
+gdb_test "break *main t 999 -force if (1==1)" \
+    "Unknown thread 999\\."
+gdb_test "break *main th 999 -force if (1==1)" \
+    "Unknown thread 999\\."
+gdb_test "break *main ta 999 -force if (1==1)" \
+    "Unknown task 999\\."
+
+# However, when the location spec doesn't start with '*' GDB relies on
+# the linespec parser to spot the keyword which marks the end of the
+# linespec, and this parser doesn't check for abbreviations.
+gdb_test "with breakpoint pending off -- break main t 999 if (1==1)" \
+    "Function \"main t 999\" not defined\\."
+gdb_test "with breakpoint pending off -- break main th 999 if (1==1)" \
+    "Function \"main th 999\" not defined\\."
+gdb_test "with breakpoint pending off -- break main ta 999 if (1==1)" \
+    "Function \"main ta 999\" not defined\\."
+
+# GDB does not treat a "-force-condition" flag that appears
+# immediately after the condition as the flag, but instead treats it
+# as " - force - condition", that is, subtraction of the symbol
+# "force" followed by subtraction of symbol "context".  This is really
+# just a quirk of how this used to be implemented, and should maybe be
+# changed in the future.  However, for now GDB retains this behaviour.
+gdb_test "break *main if (1==1) -force-condition" \
+    "No symbol \"force\" in current context\\."
 
 set test "run until breakpoint at marker3"
 gdb_test_multiple "continue" $test {
diff --git a/gdb/testsuite/gdb.base/pending.exp b/gdb/testsuite/gdb.base/pending.exp
index d7d3735000a..645f63bdb16 100644
--- a/gdb/testsuite/gdb.base/pending.exp
+++ b/gdb/testsuite/gdb.base/pending.exp
@@ -170,7 +170,8 @@ gdb_test "info break" \
 \[\t \]+stop only if k == 1.*
 \[\t \]+print k.*
 \[0-9\]+\[\t \]+breakpoint     keep y.* in main at .*$srcfile:$mainline.*
-\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc if x > 3.*" \
+\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc.*
+\\s+stop only if x > 3.*" \
 "multiple pending breakpoints"
 
 
@@ -195,8 +196,10 @@ gdb_test "info break" \
 \[\t \]+stop only if k == 1.*
 \[\t \]+print k.*
 \[0-9\]+\[\t \]+breakpoint     keep y.* in main at .*$srcfile:$mainline.*
-\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc if x > 3.*
-\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp3_loc.*ignore next 2 hits.*" \
+\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc.*
+\\s+stop only if x > 3.*
+\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp3_loc.*
+\\s+ignore next 2 hits.*" \
 "multiple pending breakpoints 2"
 
 #
@@ -267,3 +270,17 @@ gdb_test "info break" \
 \[0-9\]+\[\t \]+breakpoint     keep y.* in main at .*$srcfile:$mainline.*
 \[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*imaginary.*" \
 "verify pending breakpoint after restart"
+
+# Test GDB's parsing of pending breakpoint thread and condition.
+
+gdb_test_no_output "set breakpoint pending on"
+gdb_test "break foo if (unknown_var && another_unknown_var) thread 1" \
+    "Breakpoint $decimal \\(foo\\) pending\\."
+set bpnum [get_integer_valueof "\$bpnum" "*INVALID" \
+	       "get number for foo breakpoint"]
+gdb_test "info breakpoints $bpnum" \
+    [multi_line \
+	 "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	 "\\s+stop only if \\(unknown_var && another_unknown_var\\)" \
+	 "\\s+stop only in thread 1"] \
+    "check pending breakpoint on foo"
diff --git a/gdb/testsuite/gdb.linespec/explicit.exp b/gdb/testsuite/gdb.linespec/explicit.exp
index 668002d9038..8cbefe204ec 100644
--- a/gdb/testsuite/gdb.linespec/explicit.exp
+++ b/gdb/testsuite/gdb.linespec/explicit.exp
@@ -575,7 +575,7 @@ namespace eval $testfile {
 	      allow-pending]} {
 	fail "set $tst"
     } else {
-	gdb_test "info break" ".*PENDING.*myfunction if foofoofoo == 1.*" $tst
+	gdb_test "info break" ".*PENDING.*myfunction\r\n\\s+stop only if foofoofoo == 1.*" $tst
     }
 
     gdb_exit
@@ -586,7 +586,7 @@ namespace eval $testfile {
 	      allow-pending]} {
 	fail "set $tst"
     } else {
-	gdb_test "info break" ".*PENDING.*myfunction if arg == 0" $tst
+	gdb_test "info break" ".*PENDING.*myfunction\r\n\\s+stop only if arg == 0" $tst
 
 	gdb_load [standard_output_file $exefile]
 	gdb_test "info break" \
diff --git a/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp b/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp
index 28f52938aeb..bb9987a5572 100644
--- a/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp
+++ b/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp
@@ -50,7 +50,8 @@ set bp_location1 [gdb_get_line_number "set breakpoint 1 here"]
 # Set pending dprintf via MI.
 set bp [mi_make_breakpoint_pending -number "1" -type "dprintf" \
 	    -disp "keep" -enabled "y" -pending "pendfunc1" \
-	    -original-location "pendfunc1"]
+	    -original-location "pendfunc1" \
+	    -script {\["printf \\\"hello\\\""\]}]
 mi_gdb_test "-dprintf-insert -f pendfunc1 \"hello\"" \
     ".*\\^done,$bp" "mi set dprintf"
 
diff --git a/gdb/testsuite/gdb.multi/inferior-specific-bp.exp b/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
index 1f6573268da..b8aceabcad6 100644
--- a/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
+++ b/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
@@ -51,9 +51,9 @@ if {![runto_main]} {
 # this should fail.  Try with the keywords in both orders just in case the
 # parser has a bug.
 gdb_test "break foo thread 1.1 inferior 1" \
-    "You can specify only one of inferior or thread\\."
+    "You can specify only one of thread, inferior, or task\\."
 gdb_test "break foo inferior 1 thread 1.1" \
-    "You can specify only one of inferior or thread\\."
+    "You can specify only one of thread, inferior, or task\\."
 
 # Try to create a breakpoint using the 'inferior' keyword multiple times.
 gdb_test "break foo inferior 1 inferior 2" \
diff --git a/gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c b/gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
new file mode 100644
index 00000000000..15d1b9833dd
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
@@ -0,0 +1,22 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+int global_var = 0;
+
+void
+foo (int arg)
+{
+  global_var = arg;
+}
diff --git a/gdb/testsuite/gdb.threads/del-pending-thread-bp.c b/gdb/testsuite/gdb.threads/del-pending-thread-bp.c
new file mode 100644
index 00000000000..6fc76dbf08c
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/del-pending-thread-bp.c
@@ -0,0 +1,85 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#include <dlfcn.h>
+#include <pthread.h>
+#include <stdlib.h>
+
+pthread_barrier_t barrier;
+
+static void
+barrier_wait (pthread_barrier_t *b)
+{
+  int res = pthread_barrier_wait (b);
+  if (res != 0 && res != PTHREAD_BARRIER_SERIAL_THREAD)
+    abort ();
+}
+
+static void *
+thread_worker (void *arg)
+{
+  barrier_wait (&barrier);
+  return NULL;
+}
+
+void
+breakpt (void)
+{
+  /* Nothing.  */
+}
+
+int
+main (void)
+{
+  void *handle;
+  void (*func)(int);
+  pthread_t thread;
+
+  if (pthread_barrier_init (&barrier, NULL, 2) != 0)
+    abort ();
+
+  if (pthread_create (&thread, NULL, thread_worker, NULL) != 0)
+    abort ();
+
+  breakpt ();
+
+  /* Allow the worker thread to complete.  */
+  barrier_wait (&barrier);
+
+  if (pthread_join (thread, NULL) != 0)
+    abort ();
+
+  breakpt ();
+
+  /* Now load the shared library.  */
+  handle = dlopen (SHLIB_NAME, RTLD_LAZY);
+  if (handle == NULL)
+    abort ();
+
+  /* Find the function symbol.  */
+  func = (void (*)(int)) dlsym (handle, "foo");
+
+  /* Call the library function.  */
+  func (1);
+
+  /* Unload the shared library.  */
+  if (dlclose (handle) != 0)
+    abort ();
+
+  breakpt ();
+
+  return 0;
+}
+
diff --git a/gdb/testsuite/gdb.threads/del-pending-thread-bp.exp b/gdb/testsuite/gdb.threads/del-pending-thread-bp.exp
new file mode 100644
index 00000000000..4ed05eaa42d
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/del-pending-thread-bp.exp
@@ -0,0 +1,108 @@
+# Copyright 2023 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+# This test checks that pending thread-specific breakpoints are
+# correctly deleted when the thread the breakpoint is for goes out of
+# scope.
+#
+# We also check that we can't create a pending thread-specific
+# breakpoint for a non-existent thread.
+
+require allow_shlib_tests
+
+standard_testfile
+
+set libname $testfile-lib
+set srcfile_lib $srcdir/$subdir/$libname.c
+set binfile_lib [standard_output_file $libname.so]
+
+if { [gdb_compile_shlib $srcfile_lib $binfile_lib {}] != "" } {
+    untested "failed to compile shared library 1"
+    return -1
+}
+
+set binfile_lib_target [gdb_download_shlib $binfile_lib]
+
+if { [prepare_for_testing "failed to prepare" $testfile $srcfile \
+	  [list debug \
+	       additional_flags=-DSHLIB_NAME=\"$binfile_lib_target\" \
+	       shlib_load pthreads]] } {
+    return -1
+}
+
+gdb_locate_shlib $binfile_lib
+
+if ![runto_main] {
+    return 0
+}
+
+# Run until we have two threads.
+gdb_breakpoint "breakpt"
+gdb_continue_to_breakpoint "first breakpt call"
+
+# Confirm that we have a thread '2'.
+gdb_test "info threads" "\r\n\\s+2\\s+\[^\r\n\]+"
+
+# Create a pending, thread-specific, breakpoint on 'foo'.
+gdb_breakpoint "foo thread 2" allow-pending
+set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+	       "get breakpoint number"]
+
+# Check we can't create a pending thread-specific breakpoint for a
+# non-existent thread.
+gdb_test "with breakpoint pending on -- break foo thread 99" \
+    "Unknown thread 99\\."
+
+# Continue to 'breakpt' again.  Don't use gdb_continue_to_breakpoint
+# as we are looking for the thread exited and breakpoint deleted
+# messages.
+set output [list "Continuing\\."]
+
+if {!([target_info exists gdb_protocol]
+      && ([target_info gdb_protocol] == "remote"
+	  || [target_info gdb_protocol] == "extended-remote"))} {
+    # Due to bug PR gdb/30129 we don't see the thread exited messages
+    # for remote targets.  When this bit of this test can be cleaned
+    # up.
+    lappend output "\\\[Thread \[^\r\n\]+ exited\\\]"
+}
+
+lappend output "Thread-specific breakpoint $bpnum deleted - thread 2 no longer in the thread list\\." \
+    "" \
+    "Thread 1 \[^\r\n\]+, breakpt \\(\\) at \[^\r\n\]+" \
+    "$decimal\\s+\[^\r\n\]+"
+
+gdb_test "continue" \
+    [multi_line {*}$output] \
+    "second breakpt call"
+
+# Confirm breakpoint has been deleted.
+gdb_test "info breakpoints $bpnum" \
+    "No breakpoint or watchpoint matching '$bpnum'\\."
+
+# Continue again.  This will pass through 'foo'.  We should not stop
+# in 'foo', the breakpoint has been deleted.  We should next stop in
+# breakpt again.
+gdb_test "continue" \
+    [multi_line \
+	 "Continuing\\." \
+	 "" \
+	 "Thread 1 \[^\r\n\]+ hit Breakpoint $decimal, breakpt \\(\\) at \[^\r\n\]+" \
+	 "$decimal\\s+\[^\r\n\]+"] \
+    "third breakpt call"
+gdb_test "bt 1" \
+    [multi_line \
+	 "#0\\s+breakpt \\(\\) at \[^\r\n\]+" \
+	 "\\(More stack frames follow\\.\\.\\.\\)"]
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv7 08/11] gdb: don't set breakpoint::pspace for in create_breakpoint
  2023-12-13 22:38           ` [PATCHv7 00/11] thread-specific breakpoints in just some inferiors Andrew Burgess
                               ` (6 preceding siblings ...)
  2023-12-13 22:38             ` [PATCHv7 07/11] gdb: parse pending breakpoint thread/task immediately Andrew Burgess
@ 2023-12-13 22:38             ` Andrew Burgess
  2023-12-13 22:38             ` [PATCHv7 09/11] gdb: remove breakpoint_re_set_one Andrew Burgess
                               ` (4 subsequent siblings)
  12 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-12-13 22:38 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

While working on the previous commit, I ran into this code within
create_breakpoint:

  if ((type_wanted != bp_breakpoint
      && type_wanted != bp_hardware_breakpoint) || thread != -1)
   b->pspace = current_program_space;

this code is only executed when creating a pending breakpoint, and
sets the breakpoint::pspace member variable.

The above code gained the 'thread != -1' clause with this commit:

  commit cc72b2a2da6d6372cbdb1d14639a5fce84e1a325
  Date:   Fri Dec 23 17:06:16 2011 +0000

              Introduce gdb.FinishBreakpoint in Python

While the type_wanted checks were added with this commit:

  commit f8eba3c61629b3c03ac1f33853eab4d8507adb9c
  Date:   Tue Dec 6 18:54:43 2011 +0000

      the "ambiguous linespec" series

Before this breakpoint::pspace was set unconditionally.

If we look at how breakpoint::pspace is used today, some breakpoint
types specifically set this field, either in their constructors, or in
a wrapper function that calls the constructor.  So, the watchpoint
type and its sub-class set this variable, as does the catchpoint type,
and all it's sub-classes.

However, code_breakpoint doesn't specifically set this field within
its constructor, though some sub-classes of
code_breakpoint (ada_catchpoint, exception_catchpoint,
internal_breakpoint, and momentary_breakpoint) do set this field.

When I examine all the places that breakpoint::pspace is used, I
believe that in every place where it is expected that this field is
set, the breakpoint type will be one that specifically sets this
field.

Next, I observe two problems with the existing code.

First, the above code is only hit for pending breakpoints, there's no
equivalent code for non-pending breakpoints.  This opens up the
possibility of GDB entering non-consistent states; if a breakpoint is
first created pending and then later gets a location, the pspace field
will be set, while if the breakpoint is immediately non-pending, then
the pspace field will never be set.

Second, if we look at how breakpoint::pspace is used in the function
breakpoint_program_space_exit, we see that when a program space is
removed, any breakpoint with breakpoint::pspace set to the removed
program space, will be deleted.  This makes sense, but does mean we
need to ensure breakpoint::pspace is only set for breakpoints that
apply to a single program space.

So, if I create a pending dprintf breakpoint (type bp_dprintf) then
the breakpoint::pspace variable will be set even though the dprintf is
not really tied to that one program space.  As a result, when the
matching program space is removed the dprintf is incorrectly removed.

Also, if I create a thread specific breakpoint, then, thanks to the
'thread != -1' clause the wrong program space will be stored in
breakpoint::pspace (the current program space is always used, which
might not be the program space that corresponds to the selected
thread), as a result, the thread specific breakpoint will be deleted
when the matching program space is removed.

If we look at commit cc72b2a2da6d which added the 'thread != -1'
clause, we can see this change was entirely redundant, the
breakpoint::pspace is also set in bpfinishpy_init after
create_breakpoint has been called.  As such, I think we can safely
drop the 'thread != -1' clause.

For the other problems, I'm proposing to be pretty aggressive - I'd
like to drop the breakpoint::pspace assignment completely from
create_breakpoint.  Having looked at how this variable is used, I
believe that it is already set elsewhere in all the cases that it is
needed.  Maybe this code was needed at one time, but I can't see how
it's needed any more.

There's tests to expose the issues I've spotted with this code, and
there's no regressions in testing.
---
 gdb/breakpoint.c                              |   3 -
 gdb/breakpoint.h                              |  18 +-
 .../gdb.multi/pending-bp-del-inferior.c       |  28 +++
 .../gdb.multi/pending-bp-del-inferior.exp     | 216 ++++++++++++++++++
 4 files changed, 259 insertions(+), 6 deletions(-)
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-del-inferior.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index e672e6a7699..2e1cf3172d4 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -9206,9 +9206,6 @@ create_breakpoint (struct gdbarch *gdbarch,
       b->disposition = tempflag ? disp_del : disp_donttouch;
       b->condition_not_parsed = 1;
       b->enable_state = enabled ? bp_enabled : bp_disabled;
-      if ((type_wanted != bp_breakpoint
-	   && type_wanted != bp_hardware_breakpoint) || thread != -1)
-	b->pspace = current_program_space;
 
       if (b->type == bp_dprintf)
 	update_dprintf_command_list (b.get ());
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index 95f98b59e41..2bf63b90072 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -823,9 +823,21 @@ struct breakpoint : public intrusive_list_node<breakpoint>
      equals this.  */
   struct frame_id frame_id = null_frame_id;
 
-  /* The program space used to set the breakpoint.  This is only set
-     for breakpoints which are specific to a program space; for
-     non-thread-specific ordinary breakpoints this is NULL.  */
+  /* The program space used to set the breakpoint.  This is only set for
+     breakpoints that are not type bp_breakpoint or bp_hardware_breakpoint.
+     For thread or inferior specific breakpoints, the breakpoints are
+     managed via the thread and inferior member variables.  */
+
+  /* If not nullptr then this is the program space for which this
+     breakpoint was created.  All watchpoint and catchpoint sub-types set
+     this field, but not all of the code_breakpoint sub-types do;
+     generally, user created breakpoint types don't set this field, though
+     things might be more consistent if they did.
+
+     When this variable is nullptr then a breakpoint might be associated
+     with multiple program spaces, though you need to check the thread,
+     inferior and task variables to see if a breakpoint was created for a
+     specific thread, inferior, or Ada task respectively.  */
   program_space *pspace = NULL;
 
   /* The location specification we used to set the breakpoint.  */
diff --git a/gdb/testsuite/gdb.multi/pending-bp-del-inferior.c b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.c
new file mode 100644
index 00000000000..1d030007819
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.c
@@ -0,0 +1,28 @@
+/* This testcase is part of GDB, the GNU debugger.
+
+   Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+int
+foo (void)
+{
+  return 0;
+}
+
+int
+main (void)
+{
+  return foo ();
+}
diff --git a/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
new file mode 100644
index 00000000000..5fcd1ef2e39
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
@@ -0,0 +1,216 @@
+# Copyright 2023 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+# Setup two inferiors.  Select one inferior and create a pending
+# thread specific breakpoint in the other inferior.
+#
+# Delete the selected inferior (the one for which the thread specific
+# breakpoint doesn't apply), and check that the breakpoint still exists.
+#
+# Repeat this process, but this time, create an inferior specific
+# breakpoint.
+
+# The plain remote target can't do multiple inferiors.
+require !use_gdb_stub
+
+standard_testfile
+
+if {[prepare_for_testing "failed to prepare" $testfile $srcfile]} {
+    return -1
+}
+
+# Setup for the tests.  Create two inferiors, both running the global
+# BINFILE, and proceed to main in both inferiors.  Delete all
+# breakpoints, and check that we do have two threads.
+#
+# Return true after a successful setup, otherwise, return false.
+proc test_setup {} {
+    clean_restart $::binfile
+
+    if {![runto_main]} {
+	return 0
+    }
+
+    gdb_test "add-inferior -exec ${::binfile}" "Added inferior 2.*" \
+	"add inferior 2"
+    gdb_test "inferior 2" "Switching to inferior 2 .*" \
+	"select inferior 2"
+
+    if {![runto_main]} {
+	return 0
+    }
+
+    delete_breakpoints
+
+    gdb_test "info threads" \
+	[multi_line \
+	     "  Id\\s+Target Id\\s+Frame\\s*" \
+	     "  1\\.1\\s+\[^\r\n\]+" \
+	     "\\* 2\\.1\\s+\[^\r\n\]+"] \
+	"check we have the expected threads"
+
+    return 1
+}
+
+# Assuming inferior 2 is already selected, kill the current inferior
+# (inferior 2), select inferior 1, and then remove inferior 2.
+proc kill_and_remove_inferior_2 {} {
+    gdb_test "kill" "" "kill inferior 2" \
+	"Kill the program being debugged.*y or n. $" "y"
+
+    gdb_test "inferior 1" "Switching to inferior 1 .*" \
+	"select inferior 1"
+
+    gdb_test_no_output "remove-inferiors 2"
+}
+
+# Setup two inferiors, then create a breakpoint.  If BP_PENDING is
+# true then the breakpoint will be pending, otherwise, the breakpoint
+# will be non-pending.
+#
+# BP_TYPE is either 'thread' or 'inferior', and indicates if the
+# created breakpoint should be thread or inferior specific.
+#
+# The breakpoint is created while inferior 2 is selected, and the
+# thread/inferior restriction always identifies inferior 1.
+#
+# Then inferior 2 is killed and removed.
+#
+# Finally, check that the breakpoint still exists and correctly refers
+# to inferior 1.
+proc do_bp_test { bp_type bp_pending } {
+    if {![test_setup]} {
+	return
+    }
+
+    if { $bp_pending } {
+	set bp_func "bar"
+    } else {
+	set bp_func "foo"
+    }
+
+    if { $bp_type eq "thread" } {
+	set bp_restriction "thread 1.1"
+    } else {
+	set bp_restriction "inferior 1"
+    }
+
+    gdb_breakpoint "$bp_func $bp_restriction" allow-pending
+    set bp_number [get_integer_valueof "\$bpnum" "INVALID" \
+		       "get b/p number for previous breakpoint"]
+
+    if { $bp_restriction eq "thread 1.1" } {
+	set bp_after_restriction "thread 1"
+    } else {
+	set bp_after_restriction $bp_restriction
+    }
+
+    if { $bp_pending } {
+	set bp_pattern_before \
+	    [multi_line \
+		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+${bp_func}" \
+		 "\\s+stop only in [string_to_regexp $bp_restriction]"]
+	set bp_pattern_after \
+	    [multi_line \
+		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+${bp_func}" \
+		 "\\s+stop only in [string_to_regexp $bp_after_restriction]"]
+    } else {
+	set bp_pattern_before \
+	    [multi_line \
+		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+<MULTIPLE>\\s*" \
+		 "\\s+stop only in [string_to_regexp $bp_restriction]" \
+		 "$bp_number\\.1\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 1" \
+		 "$bp_number\\.2\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 2"]
+
+	set bp_pattern_after \
+	    [multi_line \
+		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+" \
+		 "\\s+stop only in [string_to_regexp $bp_after_restriction]"]
+    }
+
+    gdb_test "info breakpoints" $bp_pattern_before \
+	"info breakpoints before inferior removal"
+
+    kill_and_remove_inferior_2
+
+    gdb_test "info breakpoints" $bp_pattern_after \
+	"info breakpoints after inferior removal"
+}
+
+# Setup two inferiors, then create a dprintf.  If BP_PENDING is
+# true then the dprintf will be pending, otherwise, the dprintf
+# will be non-pending.
+#
+# The dprintf is created while inferior 2 is selected.  Then inferior
+# 2 is killed and removed.
+#
+# Finally, check that the dprintf still exists.
+proc do_dprintf_test { bp_pending } {
+    if {![test_setup]} {
+	return
+    }
+
+    if { $bp_pending } {
+	set bp_func "bar"
+
+	gdb_test "dprintf $bp_func,\"in $bp_func\"" ".*" \
+	    "create dprintf breakpoint" \
+	    "Make dprintf pending on future shared library load\\? \\(y or .n.\\) $" "y"
+    } else {
+	set bp_func "foo"
+
+	gdb_test "dprintf $bp_func,\"in $bp_func\"" ".*" \
+	    "create dprintf breakpoint"
+    }
+
+    set bp_number [get_integer_valueof "\$bpnum" "INVALID" \
+		       "get b/p number for previous breakpoint"]
+
+    if { $bp_pending } {
+	set bp_pattern_before \
+	    [multi_line \
+		 "$bp_number\\s+dprintf\\s+keep\\s+y\\s+<PENDING>\\s+${bp_func}" \
+		 "\\s+printf \"in $bp_func\""]
+	set bp_pattern_after $bp_pattern_before
+    } else {
+	set bp_pattern_before \
+	    [multi_line \
+		 "$bp_number\\s+dprintf\\s+keep\\s+y\\s+<MULTIPLE>\\s*" \
+		 "\\s+printf \"in $bp_func\"" \
+		 "$bp_number\\.1\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 1" \
+		 "$bp_number\\.2\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 2"]
+
+	set bp_pattern_after \
+	    [multi_line \
+		 "$bp_number\\s+dprintf\\s+keep\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+" \
+		 "\\s+printf \"in $bp_func\""]
+    }
+
+    gdb_test "info breakpoints" $bp_pattern_before \
+	"info breakpoints before inferior removal"
+
+    kill_and_remove_inferior_2
+
+    gdb_test "info breakpoints" $bp_pattern_after \
+	"info breakpoints after inferior removal"
+}
+
+foreach_with_prefix bp_pending { true false } {
+    foreach_with_prefix bp_type { thread inferior } {
+	do_bp_test $bp_type $bp_pending
+    }
+
+    do_dprintf_test $bp_pending
+}
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv7 09/11] gdb: remove breakpoint_re_set_one
  2023-12-13 22:38           ` [PATCHv7 00/11] thread-specific breakpoints in just some inferiors Andrew Burgess
                               ` (7 preceding siblings ...)
  2023-12-13 22:38             ` [PATCHv7 08/11] gdb: don't set breakpoint::pspace for in create_breakpoint Andrew Burgess
@ 2023-12-13 22:38             ` Andrew Burgess
  2023-12-13 22:38             ` [PATCHv7 10/11] gdb: remove tracepoint_probe_create_sals_from_location_spec Andrew Burgess
                               ` (3 subsequent siblings)
  12 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-12-13 22:38 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

During a later patch I wanted to reset a single breakpoint, so I
called breakpoint_re_set_one.  However, this is not the right thing to
do.  If we look at breakpoint_re_set then we see that there's a whole
bunch of state that needs to be preserved prior to calling
breakpoint_re_set_one, and after calling breakpoint_re_set_one we
still need to call update_global_location_list.

I could just update the comment on breakpoint_re_set_one to make it
clearer how the function should be used -- or more likely to warn that
the function should only be used as a helper from breakpoint_re_set.

However, breakpoint_re_set_one is only 3 lines long.  So I figure it
might actually be easier to just fold breakpoint_re_set_one into
breakpoint_re_set, then there's no risk of accidentally calling
breakpoint_re_set_one when we shouldn't.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c | 26 ++++++++------------------
 1 file changed, 8 insertions(+), 18 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 2e1cf3172d4..da47e99979f 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -13007,17 +13007,6 @@ create_sals_from_location_spec_default (location_spec *locspec,
   parse_breakpoint_sals (locspec, canonical);
 }
 
-/* Reset a breakpoint.  */
-
-static void
-breakpoint_re_set_one (breakpoint *b)
-{
-  input_radix = b->input_radix;
-  set_language (b->language);
-
-  b->re_set ();
-}
-
 /* Re-set breakpoint locations for the current program space.
    Locations bound to other program spaces are left untouched.  */
 
@@ -13029,12 +13018,11 @@ breakpoint_re_set (void)
     scoped_restore save_input_radix = make_scoped_restore (&input_radix);
     scoped_restore_current_pspace_and_thread restore_pspace_thread;
 
-    /* breakpoint_re_set_one sets the current_language to the language
-       of the breakpoint it is resetting (see prepare_re_set_context)
-       before re-evaluating the breakpoint's location.  This change can
-       unfortunately get undone by accident if the language_mode is set
-       to auto, and we either switch frames, or more likely in this context,
-       we select the current frame.
+    /* To ::re_set each breakpoint we set the current_language to the
+       language of the breakpoint before re-evaluating the breakpoint's
+       location.  This change can unfortunately get undone by accident if
+       the language_mode is set to auto, and we either switch frames, or
+       more likely in this context, we select the current frame.
 
        We prevent this by temporarily turning the language_mode to
        language_mode_manual.  We restore it once all breakpoints
@@ -13051,7 +13039,9 @@ breakpoint_re_set (void)
       {
 	try
 	  {
-	    breakpoint_re_set_one (&b);
+	    input_radix = b.input_radix;
+	    set_language (b.language);
+	    b.re_set ();
 	  }
 	catch (const gdb_exception &ex)
 	  {
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv7 10/11] gdb: remove tracepoint_probe_create_sals_from_location_spec
  2023-12-13 22:38           ` [PATCHv7 00/11] thread-specific breakpoints in just some inferiors Andrew Burgess
                               ` (8 preceding siblings ...)
  2023-12-13 22:38             ` [PATCHv7 09/11] gdb: remove breakpoint_re_set_one Andrew Burgess
@ 2023-12-13 22:38             ` Andrew Burgess
  2023-12-13 22:38             ` [PATCHv7 11/11] gdb: only insert thread-specific breakpoints in the relevant inferior Andrew Burgess
                               ` (2 subsequent siblings)
  12 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-12-13 22:38 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

The tracepoint_probe_create_sals_from_location_spec function just
forwards all its arguments to
bkpt_probe_create_sals_from_location_spec, and is only used in one
place.

Lets delete tracepoint_probe_create_sals_from_location_spec and
replace it with bkpt_probe_create_sals_from_location_spec.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c | 19 +++----------------
 1 file changed, 3 insertions(+), 16 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index da47e99979f..b7329e83196 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -284,9 +284,6 @@ static bool strace_marker_p (struct breakpoint *b);
 static void bkpt_probe_create_sals_from_location_spec
      (location_spec *locspec,
       struct linespec_result *canonical);
-static void tracepoint_probe_create_sals_from_location_spec
-     (location_spec *locspec,
-      struct linespec_result *canonical);
 
 const struct breakpoint_ops code_breakpoint_ops =
 {
@@ -301,10 +298,11 @@ static const struct breakpoint_ops bkpt_probe_breakpoint_ops =
   create_breakpoints_sal,
 };
 
-/* Tracepoints set on probes.  */
+/* Tracepoints set on probes.  We use the same methods as for breakpoints
+   on probes.  */
 static const struct breakpoint_ops tracepoint_probe_breakpoint_ops =
 {
-  tracepoint_probe_create_sals_from_location_spec,
+  bkpt_probe_create_sals_from_location_spec,
   create_breakpoints_sal,
 };
 
@@ -12217,17 +12215,6 @@ tracepoint::print_recreate (struct ui_file *fp) const
     gdb_printf (fp, "  passcount %d\n", pass_count);
 }
 
-/* Virtual table for tracepoints on static probes.  */
-
-static void
-tracepoint_probe_create_sals_from_location_spec
-  (location_spec *locspec,
-   struct linespec_result *canonical)
-{
-  /* We use the same method for breakpoint on probes.  */
-  bkpt_probe_create_sals_from_location_spec (locspec, canonical);
-}
-
 void
 dprintf_breakpoint::re_set ()
 {
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv7 11/11] gdb: only insert thread-specific breakpoints in the relevant inferior
  2023-12-13 22:38           ` [PATCHv7 00/11] thread-specific breakpoints in just some inferiors Andrew Burgess
                               ` (9 preceding siblings ...)
  2023-12-13 22:38             ` [PATCHv7 10/11] gdb: remove tracepoint_probe_create_sals_from_location_spec Andrew Burgess
@ 2023-12-13 22:38             ` Andrew Burgess
  2023-12-15 20:54             ` [PATCHv7 00/11] thread-specific breakpoints in just some inferiors Tom Tromey
  2023-12-29  9:26             ` [PATCHv8 00/14] " Andrew Burgess
  12 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-12-13 22:38 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Eli Zaretskii

Eli has already approved the docs changes in this commit.

---

This commit updates GDB so that thread or inferior specific
breakpoints are only inserted into the program space in which the
specific thread or inferior is running.

In terms of implementation, getting this basically working is easy
enough, now that a breakpoint's thread or inferior field is setup
prior to GDB looking for locations, we can easily use this information
to find a suitable program_space and pass this to as a filter when
creating the sals.

Or we could if breakpoint_ops::create_sals_from_location_spec allowed
us to pass in a filter program_space.

So, this commit extends breakpoint_ops::create_sals_from_location_spec
to take a program_space argument, and uses this to filter the set of
returned sals.  This accounts for about half the change in this patch.

The second set of changes starts from breakpoint_set_thread and
breakpoint_set_inferior, this is called when the thread or inferior
for a breakpoint changes, e.g. from the Python API.

Previously this call would never result in the locations of a
breakpoint changing, after all, locations were inserted in every
program space, and we just use the thread or inferior variable to
decide when we should stop.  Now though, changing a breakpoint's
thread or inferior can mean we need to figure out a new set of
breakpoint locations.

To support this I've added a new breakpoint_re_set_one function, which
is like breakpoint_re_set, but takes a single breakpoint, and just
updates the locations for that one breakpoint.  We only need to call
this function if the program_space in which a breakpoint's thread (or
inferior) is running actually changes.  If the program_space does
change then we call the new breakpoint_re_set_one function passing in
the program_space which should be used to filter the new locations (or
nullptr to indicate we should set locations in all program spaces).
This filter program_space needs to propagate down to all the re_set
methods, this accounts for the remaining half of the changes in this
patch.

There were a couple of existing tests that created thread or inferior
specific breakpoints and then checked the 'info breakpoints' output,
these needed updating.  These were:

  gdb.mi/user-selected-context-sync.exp
  gdb.multi/bp-thread-specific.exp
  gdb.multi/multi-target-continue.exp
  gdb.multi/multi-target-ping-pong-next.exp
  gdb.multi/tids.exp
  gdb.mi/new-ui-bp-deleted.exp
  gdb.multi/inferior-specific-bp.exp
  gdb.multi/pending-bp-del-inferior.exp

I've also added some additional tests to:

  gdb.multi/pending-bp.exp

I've updated the documentation and added a NEWS entry.

Reviewed-By: Eli Zaretskii <eliz@gnu.org>
---
 gdb/NEWS                                      |   7 +
 gdb/ada-lang.c                                |   6 +-
 gdb/break-catch-throw.c                       |   6 +-
 gdb/breakpoint.c                              | 280 ++++++++++++++----
 gdb/breakpoint.h                              |  29 +-
 gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp    |   8 +-
 .../gdb.mi/user-selected-context-sync.exp     |   4 +-
 .../gdb.multi/bp-thread-specific.exp          |   7 +-
 .../gdb.multi/inferior-specific-bp.exp        |  12 +-
 .../gdb.multi/multi-target-continue.exp       |   2 +-
 .../gdb.multi/multi-target-ping-pong-next.exp |   4 +-
 .../gdb.multi/pending-bp-del-inferior.exp     |   6 +-
 gdb/testsuite/gdb.multi/pending-bp.exp        | 206 +++++++++++++
 gdb/testsuite/gdb.multi/tids.exp              |   6 +-
 14 files changed, 484 insertions(+), 99 deletions(-)

diff --git a/gdb/NEWS b/gdb/NEWS
index 72f5a15bd26..1dccb573539 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -13,6 +13,13 @@
   'thread' or 'task' keywords are parsed at the time the breakpoint is
   created, rather than at the time the breakpoint becomes non-pending.
 
+* Thread-specific breakpoints are only inserted into the program space
+  in which the thread of interest is running.  In most cases program
+  spaces are unique for each inferior, so this means that
+  thread-specific breakpoints will usually only be inserted for the
+  inferior containing the thread of interest.  The breakpoint will
+  be hit no less than before.
+
 * Changed commands
 
 disassemble
diff --git a/gdb/ada-lang.c b/gdb/ada-lang.c
index edd68cd2c32..7bf611acc88 100644
--- a/gdb/ada-lang.c
+++ b/gdb/ada-lang.c
@@ -11996,11 +11996,11 @@ struct ada_catchpoint : public code_breakpoint
     enable_state = enabled ? bp_enabled : bp_disabled;
     language = language_ada;
 
-    re_set ();
+    re_set (pspace);
   }
 
   struct bp_location *allocate_location () override;
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   void check_status (struct bpstat *bs) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   bool print_one (const bp_location **) const override;
@@ -12045,7 +12045,7 @@ static struct symtab_and_line ada_exception_sal
    catchpoint kinds.  */
 
 void
-ada_catchpoint::re_set ()
+ada_catchpoint::re_set (program_space *pspace)
 {
   std::vector<symtab_and_line> sals;
   try
diff --git a/gdb/break-catch-throw.c b/gdb/break-catch-throw.c
index 47d534c5ee8..e661d1624e8 100644
--- a/gdb/break-catch-throw.c
+++ b/gdb/break-catch-throw.c
@@ -82,10 +82,10 @@ struct exception_catchpoint : public code_breakpoint
 				     _("invalid type-matching regexp")))
   {
     pspace = current_program_space;
-    re_set ();
+    re_set (pspace);
   }
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   bool print_one (const bp_location **) const override;
   void print_mention () const override;
@@ -198,7 +198,7 @@ exception_catchpoint::check_status (struct bpstat *bs)
 /* Implement the 're_set' method.  */
 
 void
-exception_catchpoint::re_set ()
+exception_catchpoint::re_set (program_space *pspace)
 {
   std::vector<symtab_and_line> sals;
   struct program_space *filter_pspace = current_program_space;
diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index b7329e83196..fbcd912bb6f 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -91,9 +91,12 @@
 static void map_breakpoint_numbers (const char *,
 				    gdb::function_view<void (breakpoint *)>);
 
-static void
-  create_sals_from_location_spec_default (location_spec *locspec,
-					  linespec_result *canonical);
+static void parse_breakpoint_sals (location_spec *locspec,
+				   linespec_result *canonical,
+				   program_space *search_pspace);
+
+static void breakpoint_re_set_one (breakpoint *b,
+				   program_space *filter_pspace);
 
 static void create_breakpoints_sal (struct gdbarch *,
 				    struct linespec_result *,
@@ -283,11 +286,12 @@ static bool strace_marker_p (struct breakpoint *b);
 
 static void bkpt_probe_create_sals_from_location_spec
      (location_spec *locspec,
-      struct linespec_result *canonical);
+      struct linespec_result *canonical,
+      struct program_space *search_pspace);
 
 const struct breakpoint_ops code_breakpoint_ops =
 {
-  create_sals_from_location_spec_default,
+  parse_breakpoint_sals,
   create_breakpoints_sal,
 };
 
@@ -352,7 +356,7 @@ struct internal_breakpoint : public code_breakpoint
     disposition = disp_donttouch;
   }
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   void check_status (struct bpstat *bs) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   void print_mention () const override;
@@ -389,7 +393,7 @@ struct momentary_breakpoint : public code_breakpoint
     gdb_assert (inferior == -1);
   }
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   void check_status (struct bpstat *bs) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   void print_mention () const override;
@@ -400,7 +404,7 @@ struct dprintf_breakpoint : public ordinary_breakpoint
 {
   using ordinary_breakpoint::ordinary_breakpoint;
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   int breakpoint_hit (const struct bp_location *bl,
 		      const address_space *aspace,
 		      CORE_ADDR bp_addr,
@@ -1554,7 +1558,36 @@ breakpoint_set_thread (struct breakpoint *b, int thread)
   int old_thread = b->thread;
   b->thread = thread;
   if (old_thread != thread)
-    notify_breakpoint_modified (b);
+    {
+      /* If THREAD is in a different program_space than OLD_THREAD, or the
+	 breakpoint has switched to or from being thread-specific, then we
+	 need to re-set the locations of this breakpoint.  First, figure
+	 out the program_space for the old and new threads, use a value of
+	 nullptr to indicate the breakpoint is in all program spaces.  */
+      program_space *old_pspace = nullptr;
+      if (old_thread != -1)
+	{
+	  struct thread_info *thr = find_thread_global_id (old_thread);
+	  gdb_assert (thr != nullptr);
+	  old_pspace = thr->inf->pspace;
+	}
+
+      program_space *new_pspace = nullptr;
+      if (thread != -1)
+	{
+	  struct thread_info *thr = find_thread_global_id (thread);
+	  gdb_assert (thr != nullptr);
+	  new_pspace = thr->inf->pspace;
+	}
+
+      /* If the program space has changed for this breakpoint, then
+	 re-evaluate it's locations.  */
+      if (old_pspace != new_pspace)
+	breakpoint_re_set_one (b, new_pspace);
+
+      /* Let others know the breakpoint has changed.  */
+      notify_breakpoint_modified (b);
+    }
 }
 
 /* See breakpoint.h.  */
@@ -1573,7 +1606,34 @@ breakpoint_set_inferior (struct breakpoint *b, int inferior)
   int old_inferior = b->inferior;
   b->inferior = inferior;
   if (old_inferior != inferior)
-    notify_breakpoint_modified (b);
+    {
+      /* If INFERIOR is in a different program_space than OLD_INFERIOR, or
+	 the breakpoint has switch to or from inferior-specific, then we
+	 need to re-set the locations of this breakpoint.  First, figure
+	 out the program_space for the old and new inferiors, use a value
+	 of nullptr to indicate the breakpoint is in all program
+	 spaces.  */
+      program_space *old_pspace = nullptr;
+      if (old_inferior != -1)
+	{
+	  struct inferior *inf = find_inferior_id (old_inferior);
+	  gdb_assert (inf != nullptr);
+	  old_pspace = inf->pspace;
+	}
+
+      program_space *new_pspace = nullptr;
+      if (inferior != -1)
+	{
+	  struct inferior *inf = find_inferior_id (inferior);
+	  gdb_assert (inf != nullptr);
+	  new_pspace = inf->pspace;
+	}
+
+      if (old_pspace != new_pspace)
+	breakpoint_re_set_one (b, new_pspace);
+
+      notify_breakpoint_modified (b);
+    }
 }
 
 /* See breakpoint.h.  */
@@ -8814,7 +8874,8 @@ create_breakpoints_sal (struct gdbarch *gdbarch,
 
 static void
 parse_breakpoint_sals (location_spec *locspec,
-		       struct linespec_result *canonical)
+		       struct linespec_result *canonical,
+		       struct program_space *search_pspace)
 {
   struct symtab_and_line cursal;
 
@@ -8878,7 +8939,7 @@ parse_breakpoint_sals (location_spec *locspec,
 	      && strchr ("+-", spec[0]) != NULL
 	      && spec[1] != '['))
 	{
-	  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, NULL,
+	  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, search_pspace,
 			    get_last_displayed_symtab (),
 			    get_last_displayed_line (),
 			    canonical, NULL, NULL);
@@ -8886,7 +8947,7 @@ parse_breakpoint_sals (location_spec *locspec,
 	}
     }
 
-  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, NULL,
+  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, search_pspace,
 		    cursal.symtab, cursal.line, canonical, NULL, NULL);
 }
 
@@ -8985,6 +9046,39 @@ breakpoint_ops_for_location_spec_type (enum location_spec_type locspec_type,
     }
 }
 
+/* Return the program space to use as a filter when searching for locations
+   of a breakpoint specific to THREAD or INFERIOR.  If THREAD and INFERIOR
+   are both -1, meaning all threads/inferiors, then this function returns
+   nullptr, indicating no program space filtering should be performed.
+   Otherwise, this function returns the program space for the inferior that
+   contains THREAD (when THREAD is not -1), or the program space for
+   INFERIOR (when INFERIOR is not -1).  */
+
+static struct program_space *
+find_program_space_for_breakpoint (int thread, int inferior)
+{
+  if (thread != -1)
+    {
+      gdb_assert (inferior == -1);
+
+      struct thread_info *thr = find_thread_global_id (thread);
+      gdb_assert (thr != nullptr);
+      gdb_assert (thr->inf != nullptr);
+      return thr->inf->pspace;
+    }
+  else if (inferior != -1)
+    {
+      gdb_assert (thread == -1);
+
+      struct inferior *inf = find_inferior_id (inferior);
+      gdb_assert (inf != nullptr);
+
+      return inf->pspace;
+    }
+
+  return nullptr;
+}
+
 /* See breakpoint.h.  */
 
 const struct breakpoint_ops *
@@ -9086,7 +9180,10 @@ create_breakpoint (struct gdbarch *gdbarch,
 
   try
     {
-      ops->create_sals_from_location_spec (locspec, &canonical);
+      struct program_space *search_pspace
+	= find_program_space_for_breakpoint (thread, inferior);
+      ops->create_sals_from_location_spec (locspec, &canonical,
+					   search_pspace);
     }
   catch (const gdb_exception_error &e)
     {
@@ -9559,7 +9656,7 @@ break_range_command (const char *arg, int from_tty)
   arg_start = arg;
   location_spec_up start_locspec
     = string_to_location_spec (&arg, current_language);
-  parse_breakpoint_sals (start_locspec.get (), &canonical_start);
+  parse_breakpoint_sals (start_locspec.get (), &canonical_start, nullptr);
 
   if (arg[0] != ',')
     error (_("Too few arguments."));
@@ -9660,7 +9757,7 @@ watchpoint_exp_is_const (const struct expression *exp)
 /* Implement the "re_set" method for watchpoints.  */
 
 void
-watchpoint::re_set ()
+watchpoint::re_set (struct program_space *pspace)
 {
   /* Watchpoint can be either on expression using entirely global
      variables, or it can be on local variables.
@@ -11771,7 +11868,7 @@ breakpoint::print_recreate (struct ui_file *fp) const
 /* Default breakpoint_ops methods.  */
 
 void
-code_breakpoint::re_set ()
+code_breakpoint::re_set (struct program_space *pspace)
 {
   /* FIXME: is this still reachable?  */
   if (breakpoint_location_spec_empty_p (this))
@@ -11781,7 +11878,7 @@ code_breakpoint::re_set ()
       return;
     }
 
-  re_set_default ();
+  re_set_default (pspace);
 }
 
 int
@@ -11987,7 +12084,7 @@ code_breakpoint::decode_location_spec (location_spec *locspec,
 /* Virtual table for internal breakpoints.  */
 
 void
-internal_breakpoint::re_set ()
+internal_breakpoint::re_set (struct program_space *pspace)
 {
   switch (type)
     {
@@ -12080,7 +12177,7 @@ internal_breakpoint::print_mention () const
 /* Virtual table for momentary breakpoints  */
 
 void
-momentary_breakpoint::re_set ()
+momentary_breakpoint::re_set (struct program_space *pspace)
 {
   /* Keep temporary breakpoints, which can be encountered when we step
      over a dlopen call and solib_add is resetting the breakpoints.
@@ -12121,12 +12218,13 @@ longjmp_breakpoint::~longjmp_breakpoint ()
 
 static void
 bkpt_probe_create_sals_from_location_spec (location_spec *locspec,
-					   struct linespec_result *canonical)
+					   struct linespec_result *canonical,
+					   struct program_space *search_pspace)
 
 {
   struct linespec_sals lsal;
 
-  lsal.sals = parse_probes (locspec, NULL, canonical);
+  lsal.sals = parse_probes (locspec, search_pspace, canonical);
   lsal.canonical = xstrdup (canonical->locspec->to_string ());
   canonical->lsals.push_back (std::move (lsal));
 }
@@ -12216,9 +12314,9 @@ tracepoint::print_recreate (struct ui_file *fp) const
 }
 
 void
-dprintf_breakpoint::re_set ()
+dprintf_breakpoint::re_set (struct program_space *pspace)
 {
-  re_set_default ();
+  re_set_default (pspace);
 
   /* 1 - connect to target 1, that can run breakpoint commands.
      2 - create a dprintf, which resolves fine.
@@ -12272,8 +12370,10 @@ dprintf_breakpoint::after_condition_true (struct bpstat *bs)
    markers (`-m').  */
 
 static void
-strace_marker_create_sals_from_location_spec (location_spec *locspec,
-					      struct linespec_result *canonical)
+strace_marker_create_sals_from_location_spec
+	(location_spec *locspec,
+	 struct linespec_result *canonical,
+	 struct program_space *search_pspace)
 {
   struct linespec_sals lsal;
   const char *arg_start, *arg;
@@ -12789,12 +12889,32 @@ update_breakpoint_locations (code_breakpoint *b,
      all locations are in the same shared library, that was unloaded.
      We'd like to retain the location, so that when the library is
      loaded again, we don't loose the enabled/disabled status of the
-     individual locations.  */
+     individual locations.
+
+     Thread specific breakpoints will also trigger this case if the thread
+     is changed to a different program space, and all of the old locations
+     go out of scope.  In this case we do (currently) discard the old
+     locations -- we assume the change in thread is permanent and the old
+     locations will never come back into scope.  */
   if (all_locations_are_pending (b, filter_pspace) && sals.empty ())
-    return;
+    {
+      if (b->thread != -1)
+	b->clear_locations ();
+      return;
+    }
 
   bp_location_list existing_locations = b->steal_locations (filter_pspace);
 
+  /* If this is a thread-specific breakpoint then any locations left on the
+     breakpoint are for a program space in which the thread of interest
+     does not operate.  This can happen when the user changes the thread of
+     a thread-specific breakpoint.
+
+     We assume that the change in thread is permanent, and that the old
+     locations will never be used again, so discard them now.  */
+  if (b->thread != -1)
+    b->clear_locations ();
+
   for (const auto &sal : sals)
     {
       struct bp_location *new_loc;
@@ -12960,40 +13080,45 @@ code_breakpoint::location_spec_to_sals (location_spec *locspec,
    locations.  */
 
 void
-code_breakpoint::re_set_default ()
+code_breakpoint::re_set_default (struct program_space *filter_pspace)
 {
-  struct program_space *filter_pspace = current_program_space;
   std::vector<symtab_and_line> expanded, expanded_end;
 
-  int found;
-  std::vector<symtab_and_line> sals = location_spec_to_sals (locspec.get (),
-							     filter_pspace,
-							     &found);
-  if (found)
-    expanded = std::move (sals);
-
-  if (locspec_range_end != nullptr)
-    {
-      std::vector<symtab_and_line> sals_end
-	= location_spec_to_sals (locspec_range_end.get (),
-				 filter_pspace, &found);
+  /* If this breakpoint is thread-specific then find the program space in
+     which the specific thread exists.  Otherwise, for breakpoints that are
+     not thread-specific THREAD_PSPACE will be nullptr.  */
+  program_space *bp_pspace
+    = find_program_space_for_breakpoint (this->thread, this->inferior);
+
+  /* If this is not a thread or inferior specific breakpoint, or it is a
+     thread or inferior specific breakpoint but we are looking for new
+     locations in the program space that the specific thread or inferior is
+     running, then look for new locations for this breakpoint.  */
+  if (bp_pspace == nullptr || filter_pspace == bp_pspace)
+    {
+      int found;
+      std::vector<symtab_and_line> sals
+	= location_spec_to_sals (locspec.get (), filter_pspace, &found);
       if (found)
-	expanded_end = std::move (sals_end);
+	expanded = std::move (sals);
+
+      if (locspec_range_end != nullptr)
+	{
+	  std::vector<symtab_and_line> sals_end
+	    = location_spec_to_sals (locspec_range_end.get (),
+				     filter_pspace, &found);
+	  if (found)
+	    expanded_end = std::move (sals_end);
+	}
     }
 
+  /* Update the locations for this breakpoint.  For thread-specific
+     breakpoints this will remove any old locations that are for the wrong
+     program space -- this can happen if the user changes the thread of a
+     thread-specific breakpoint.  */
   update_breakpoint_locations (this, filter_pspace, expanded, expanded_end);
 }
 
-/* Default method for creating SALs from an address string.  It basically
-   calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
-
-static void
-create_sals_from_location_spec_default (location_spec *locspec,
-					struct linespec_result *canonical)
-{
-  parse_breakpoint_sals (locspec, canonical);
-}
-
 /* Re-set breakpoint locations for the current program space.
    Locations bound to other program spaces are left untouched.  */
 
@@ -13028,7 +13153,7 @@ breakpoint_re_set (void)
 	  {
 	    input_radix = b.input_radix;
 	    set_language (b.language);
-	    b.re_set ();
+	    b.re_set (current_program_space);
 	  }
 	catch (const gdb_exception &ex)
 	  {
@@ -13049,6 +13174,53 @@ breakpoint_re_set (void)
   /* Now we can insert.  */
   update_global_location_list (UGLL_MAY_INSERT);
 }
+
+/* Re-set locations for breakpoint B in FILTER_PSPACE.  If FILTER_PSPACE is
+   nullptr then re-set locations for B in all program spaces.  Locations
+   bound to program spaces other than FILTER_PSPACE are left untouched.  */
+
+static void
+breakpoint_re_set_one (breakpoint *b, program_space *filter_pspace)
+{
+  {
+    scoped_restore_current_language save_language;
+    scoped_restore save_input_radix = make_scoped_restore (&input_radix);
+    scoped_restore_current_pspace_and_thread restore_pspace_thread;
+
+    /* To ::re_set each breakpoint we set the current_language to the
+       language of the breakpoint before re-evaluating the breakpoint's
+       location.  This change can unfortunately get undone by accident if
+       the language_mode is set to auto, and we either switch frames, or
+       more likely in this context, we select the current frame.
+
+       We prevent this by temporarily turning the language_mode to
+       language_mode_manual.  We restore it once all breakpoints
+       have been reset.  */
+    scoped_restore save_language_mode = make_scoped_restore (&language_mode);
+    language_mode = language_mode_manual;
+
+    /* Note: we must not try to insert locations until after all
+       breakpoints have been re-set.  Otherwise, e.g., when re-setting
+       breakpoint 1, we'd insert the locations of breakpoint 2, which
+       hadn't been re-set yet, and thus may have stale locations.  */
+
+    try
+      {
+	input_radix = b->input_radix;
+	set_language (b->language);
+	b->re_set (filter_pspace);
+      }
+    catch (const gdb_exception &ex)
+      {
+	exception_fprintf (gdb_stderr, ex,
+			   "Error in re-setting breakpoint %d: ",
+			   b->number);
+      }
+  }
+
+  /* Now we can insert.  */
+  update_global_location_list (UGLL_MAY_INSERT);
+}
 \f
 /* Reset the thread number of this breakpoint:
 
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index 2bf63b90072..a48a9fe81fd 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -562,15 +562,15 @@ enum print_stop_action
 
 struct breakpoint_ops
 {
-  /* Create SALs from location spec, storing the result in
-     linespec_result.
-
-     For an explanation about the arguments, see the function
-     `create_sals_from_location_spec_default'.
+  /* Create SALs from LOCSPEC, storing the result in linespec_result
+     CANONICAL.  If SEARCH_PSPACE is not nullptr then only results in the
+     corresponding program space are returned.  If SEARCH_PSPACE is nullptr
+     then results for all program spaces are returned.
 
      This function is called inside `create_breakpoint'.  */
   void (*create_sals_from_location_spec) (location_spec *locspec,
-					  struct linespec_result *canonical);
+					  linespec_result *canonical,
+					  program_space *search_pspace);
 
   /* This method will be responsible for creating a breakpoint given its SALs.
      Usually, it just calls `create_breakpoints_sal' (for ordinary
@@ -702,8 +702,15 @@ struct breakpoint : public intrusive_list_node<breakpoint>
 
   /* Reevaluate a breakpoint.  This is necessary after symbols change
      (e.g., an executable or DSO was loaded, or the inferior just
-     started).  */
-  virtual void re_set ()
+     started).
+
+     If not nullptr, then FILTER_PSPACE is the program space in which
+     symbols may have changed, we only need to add new locations in
+     FILTER_PSPACE.
+
+     If FILTER_PSPACE is nullptr then all program spaces may have changed,
+     new locations need to be searched for in every program space.  */
+  virtual void re_set (program_space *filter_pspace)
   {
     /* Nothing to re-set.  */
   }
@@ -947,7 +954,7 @@ struct code_breakpoint : public breakpoint
   /* Add a location for SAL to this breakpoint.  */
   bp_location *add_location (const symtab_and_line &sal);
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   int insert_location (struct bp_location *) override;
   int remove_location (struct bp_location *,
 		       enum remove_bp_reason reason) override;
@@ -969,7 +976,7 @@ struct code_breakpoint : public breakpoint
      struct program_space *search_pspace);
 
   /* Helper method that does the basic work of re_set.  */
-  void re_set_default ();
+  void re_set_default (program_space *pspace);
 
   /* Find the SaL locations corresponding to the given LOCATION.
      On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
@@ -991,7 +998,7 @@ struct watchpoint : public breakpoint
 {
   using breakpoint::breakpoint;
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   int insert_location (struct bp_location *) override;
   int remove_location (struct bp_location *,
 		       enum remove_bp_reason reason) override;
diff --git a/gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp b/gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp
index 57e69ef6240..3afc1787026 100644
--- a/gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp
+++ b/gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp
@@ -76,8 +76,12 @@ foreach_mi_ui_mode mode {
     set loc2 [make_bp_loc "$::decimal\\.2"]
 
     # Create the inferior-specific breakpoint.
-    mi_create_breakpoint_multi "-g i2 foo" "create breakpoint in inferior 2" \
-	-inferior "2" -locations "\\\[$loc1,$loc2\\\]"
+    mi_create_breakpoint "-g i2 foo" "create breakpoint in inferior 2" \
+	-number "$decimal" \
+	-type "breakpoint" \
+	-enabled "y" \
+	-func "foo" \
+	-inferior "2"
     set bpnum [mi_get_valueof "/d" "\$bpnum" "INVALID"]
 
     if {$mode eq "separate"} {
diff --git a/gdb/testsuite/gdb.mi/user-selected-context-sync.exp b/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
index 4889c31aff3..b39745bdf17 100644
--- a/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
+++ b/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
@@ -370,7 +370,7 @@ proc test_continue_to_start { mode inf } {
 			    "thread $inf.2 stops MI"
 		    } else {
 			mi_expect_stop "breakpoint-hit" "child_sub_function" \
-			    "" "$srcfile" "$decimal" {"" "disp=\"del\"" "locno=\"[0-9]+\""} \
+			    "" "$srcfile" "$decimal" {"" "disp=\"del\""} \
 			    "thread $inf.2 stops MI"
 		    }
 		}
@@ -439,7 +439,7 @@ proc_with_prefix test_setup { mode } {
 
 	with_spawn_id $mi_spawn_id {
 	    mi_expect_stop "breakpoint-hit" "main" "" "$srcfile" "$decimal" \
-		{"" "disp=\"del\"" "locno=\"[0-9]+\""} "main stop"
+		{"" "disp=\"del\""} "main stop"
 	}
 
 	# Consume CLI output.
diff --git a/gdb/testsuite/gdb.multi/bp-thread-specific.exp b/gdb/testsuite/gdb.multi/bp-thread-specific.exp
index 85c08f44a2c..68001e92044 100644
--- a/gdb/testsuite/gdb.multi/bp-thread-specific.exp
+++ b/gdb/testsuite/gdb.multi/bp-thread-specific.exp
@@ -50,7 +50,7 @@ gdb_test "info threads" \
 # locations ('foo' in both inferiors) even though only one of those
 # locations will ever trigger ('foo' in inferior 2).
 gdb_test "break foo thread 2.1" \
-    "Breakpoint $decimal at $hex: foo\\. \\(2 locations\\)"
+    "Breakpoint $decimal at $hex: file \[^\r\n\]+$srcfile, line $decimal\\."
 
 set bpnum [get_integer_valueof "\$bpnum" "INVALID"]
 
@@ -58,10 +58,7 @@ set bpnum [get_integer_valueof "\$bpnum" "INVALID"]
 # earlier breakpoint.  Check that the thread-id used when describing
 # the earlier breakpoints is correct.
 gdb_test "break foo thread 1.1" \
-    [multi_line \
-	 "Note: breakpoint $bpnum \\(thread 2.1\\) also set at pc $hex\\." \
-	 "Note: breakpoint $bpnum \\(thread 2.1\\) also set at pc $hex\\." \
-	 "Breakpoint $decimal at $hex: foo\\. \\(2 locations\\)"]
+    "Breakpoint $decimal at $hex: file \[^\r\n\]+$srcfile, line $decimal\\."
 
 # Save the breakpoints into a file.
 if {[is_remote host]} {
diff --git a/gdb/testsuite/gdb.multi/inferior-specific-bp.exp b/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
index b8aceabcad6..dda167dd39f 100644
--- a/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
+++ b/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
@@ -105,16 +105,8 @@ proc check_info_breakpoints { testname bp_number expected_loc_count } {
 # Create an inferior-specific breakpoint.  Use gdb_test instead of
 # gdb_breakpoint here as we want to check the breakpoint was placed in
 # multiple locations.
-#
-# Currently GDB still places inferior specific breakpoints into every
-# inferior, just like it does with thread specific breakpoints.
-# Hopefully this will change in the future, at which point, this test
-# will need updating.
-#
-# Two of these locations are in inferior 1, while the third is in
-# inferior 2.
 gdb_test "break foo inferior 1" \
-    "Breakpoint $decimal at $hex: foo\\. \\(3 locations\\)"
+    "Breakpoint $decimal at $hex: foo\\. \\(2 locations\\)"
 set bp_number [get_integer_valueof "\$bpnum" "INVALID" \
 		  "get b/p number for inferior specific breakpoint"]
 
@@ -123,7 +115,7 @@ set location_count 0
 set saw_inf_cond false
 
 check_info_breakpoints "first check for inferior specific breakpoint" \
-    $bp_number 3
+    $bp_number 2
 
 # Create a multi-inferior breakpoint to stop at.
 gdb_breakpoint "stop_breakpt" message
diff --git a/gdb/testsuite/gdb.multi/multi-target-continue.exp b/gdb/testsuite/gdb.multi/multi-target-continue.exp
index bf19cc00968..a1bffb7b613 100644
--- a/gdb/testsuite/gdb.multi/multi-target-continue.exp
+++ b/gdb/testsuite/gdb.multi/multi-target-continue.exp
@@ -30,7 +30,7 @@ proc test_continue {non-stop} {
 
     proc set_break {inf} {
 	gdb_test "break function${inf} thread ${inf}.1" \
-	"Breakpoint .* function${inf}\\..*"
+	    "Breakpoint ${::decimal} at ${::hex}: file .*, line ${::decimal}\\."
     }
 
     # Select inferior INF, and then run to a breakpoint on inferior
diff --git a/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp b/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp
index 64645b8ec8a..51fd70b018a 100644
--- a/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp
+++ b/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp
@@ -52,12 +52,12 @@ proc test_ping_pong_next {} {
     gdb_test "thread 1.1" "Switching to thread 1.1 .*"
 
     gdb_test "break $srcfile:$line1 thread 1.1" \
-	"Breakpoint .*$srcfile:$line1\\..*"
+	"Breakpoint .*$srcfile, line $line1\\."
 
     gdb_test "continue" "hit Breakpoint .*"
 
     gdb_test "break $srcfile:$line2 thread 2.1" \
-	"Breakpoint .*$srcfile:$line2\\..*"
+	"Breakpoint .*$srcfile, line $line2\\."
 
     # Now block inferior 1 and issue "next".  We should stop at the
     # breakpoint for inferior 2, given schedlock off.
diff --git a/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
index 5fcd1ef2e39..12c0a84bb02 100644
--- a/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
+++ b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
@@ -129,10 +129,8 @@ proc do_bp_test { bp_type bp_pending } {
     } else {
 	set bp_pattern_before \
 	    [multi_line \
-		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+<MULTIPLE>\\s*" \
-		 "\\s+stop only in [string_to_regexp $bp_restriction]" \
-		 "$bp_number\\.1\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 1" \
-		 "$bp_number\\.2\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 2"]
+		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 1" \
+		 "\\s+stop only in [string_to_regexp $bp_restriction]"]
 
 	set bp_pattern_after \
 	    [multi_line \
diff --git a/gdb/testsuite/gdb.multi/pending-bp.exp b/gdb/testsuite/gdb.multi/pending-bp.exp
index 478d8d7c037..aeb8c2c886e 100644
--- a/gdb/testsuite/gdb.multi/pending-bp.exp
+++ b/gdb/testsuite/gdb.multi/pending-bp.exp
@@ -72,6 +72,48 @@ proc do_test_setup { inf_1_stop inf_2_stop } {
     return true
 }
 
+# Create a breakpoint on the function 'foo' in THREAD.  It is expected
+# that the breakpoint created will be pending, this is checked by
+# running the 'info breakpoints' command.
+#
+# Returns the number for the newly created breakpoint.
+proc do_create_pending_foo_breakpoint { {thread "1.1"} } {
+    gdb_test "break foo thread $thread" \
+	[multi_line \
+	     "Function \"foo\" not defined\\." \
+	     "Breakpoint $::decimal \\(foo\\) pending\."] \
+	"set pending thread-specific breakpoint"
+    set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+		   "get number for thread-specific breakpoint on foo"]
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	     "\\s+stop only in thread [string_to_regexp $thread]"] \
+	"check thread-specific breakpoint is initially pending"
+
+    return $bpnum
+}
+
+# Create a breakpoint on the function 'foo' in THREAD.  It is expected
+# that the breakpoint created will not be pending, this is checked by
+# running the 'info breakpoints' command.
+#
+# Returns the number for the newly created breakpoint.
+proc do_create_foo_breakpoint { {thread "1.1"} } {
+    gdb_test "break foo thread $thread" \
+	"Breakpoint $::decimal at $::hex" \
+	"set thread-specific breakpoint"
+    set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+		   "get number for thread-specific breakpoint on foo"]
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex\\s+<foo\[^>\]*> inf $::decimal" \
+	     "\\s+stop only in thread [string_to_regexp $thread]"] \
+	"check thread-specific breakpoint is initially pending"
+
+    return $bpnum
+}
+
 # Check that when a breakpoint is in the pending state, but that breakpoint
 # does have some locations (those locations themselves are pending), GDB
 # doesn't display the inferior list in the 'info breakpoints' output.
@@ -122,5 +164,169 @@ proc_with_prefix test_no_inf_display {} {
 	"check info breakpoints while breakpoint is pending"
 }
 
+# Setup two inferiors.  In #1 the symbol 'foo' has not yet been
+# loaded, while in #2 the symbol 'foo' has been loaded.
+#
+# Create a thread-specific breakpoint on 'foo' tied to a thread in
+# inferior #1, the breakpoint should be pending -- 'foo' is not yet
+# loaded in #1.
+#
+# Now move inferior #1 forward until 'foo' is loaded, check the
+# breakpoint is no longer pending.
+#
+# Move inferior #1 forward more until 'foo' is unloaded, check that
+# the breakpoint returns to the pending state.
+proc_with_prefix test_pending_toggle { } {
+
+    do_test_setup "Break before open" "Break before close"
+
+    set bpnum [do_create_pending_foo_breakpoint]
+
+    # Now return to inferior 1 and continue until the shared library is
+    # loaded, the breakpoint should become non-pending.
+    gdb_test "inferior 1" "Switching to inferior 1 .*" \
+	"switch back to inferior 1"
+    gdb_continue_to_breakpoint "stop in foo in inferior 1" "foo \\(\\) .*"
+
+    gdb_test "info breakpoint $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex <foo\[^>\]*> inf 1" \
+	     "\\s+stop only in thread 1\\.1" \
+	     "\\s+breakpoint already hit 1 time"] \
+	"check thread-specific breakpoint is no longer pending"
+
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "close library"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	     "\\s+stop only in thread 1\\.1" \
+	     "\\s+breakpoint already hit 1 time"] \
+	"check thread-specific breakpoint is pending again"
+}
+
+# Create a Python variable VAR and set it to the gdb.Breakpoint object
+# corresponding to the breakpoint numbered BPNUM.  If THREAD is not
+# the empty string then THREAD should be an integer, check that
+# gdb.Breakpoint.thread is set to the value of THREAD.  Otherwise, if
+# THREAD is the empty string, check that gdb.Breakpoint.thread is set
+# to None.
+proc py_find_breakpoint { var bpnum {thread ""} } {
+    gdb_test_no_output \
+	"python ${var}=\[b for b in gdb.breakpoints() if b.number == $bpnum\]\[0\]" \
+	"find Python gdb.Breakpoint object"
+    if { $thread ne "" } {
+	gdb_test_no_output "python assert(${var}.thread == ${thread})" \
+	    "check thread attribute is currently correct"
+    } else {
+	gdb_test_no_output "python assert(${var}.thread is None)" \
+	    "check thread attribute is currently correct"
+    }
+}
+
+# Setup two inferiors.  In #1 the symbol 'foo' has not yet been
+# loaded, while in #2 the symbol 'foo' has been loaded.
+#
+# Create a thread-specific breakpoint on 'foo' tied to a thread in
+# inferior #1, the breakpoint should be pending -- 'foo' is not yet
+# loaded in #1.
+#
+# Use Python to change the thread of the thread-specific breakpoint to
+# a thread in inferior #2, at this point the thread should gain a
+# location and become non-pending.
+#
+# Set the thread back to a thread in inferior #1, the breakpoint
+# should return to the pending state.
+proc_with_prefix py_test_toggle_thread {} {
+    do_test_setup "Break before open" "Break after open"
+
+    set bpnum [do_create_pending_foo_breakpoint]
+
+    py_find_breakpoint "bp" $bpnum 1
+
+    gdb_test_no_output "python bp.thread = 2" \
+	"change thread on thread-specific breakpoint"
+    gdb_test "info breakpoint $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex <foo\[^>\]*> inf 2" \
+	     "\\s+stop only in thread 2\\.1"] \
+	"check thread-specific breakpoint now has a location"
+
+    gdb_test_no_output "set call_count = 2" "set call_count in inferior 2"
+    gdb_continue_to_breakpoint "stop at foo in inferior 2" "foo \\(\\) .*"
+
+    gdb_test_no_output "python bp.thread = 1" \
+	"restore thread on thread-specific breakpoint"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	     "\\s+stop only in thread 1\\.1" \
+	     "\\s+breakpoint already hit 1 time"] \
+	"check thread-specific breakpoint has returned to pending"
+
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "stop after close in inferior 2" \
+	".* Break after close\\. .*"
+
+    gdb_test "inferior 1" "Switching to inferior 1 .*" \
+	"switch to inferior 1"
+    gdb_continue_to_breakpoint "stop at foo in inferior 1" "foo \\(\\) .*"
+}
+
+# Setup two inferiors.  Both inferiors have the symbol 'foo'
+# available.
+#
+# Create a thread-specific breakpoint on 'foo' tied to a thread in
+# inferior #1, the breakpoint should not be pending, but will only
+# have a single location, the location in inferior #1.
+#
+# Use Python to change the thread of the thread-specific breakpoint to
+# None.  At this point the breakpoint should gain a second location, a
+# location in inferior #2.
+proc_with_prefix py_test_clear_thread {} {
+    do_test_setup "Break after open" "Break after open"
+
+    set bpnum [do_create_foo_breakpoint]
+
+    py_find_breakpoint "bp" $bpnum 1
+
+    gdb_test_no_output "python bp.thread = None" \
+	"clear thread on thread-specific breakpoint"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "${bpnum}\\s+breakpoint\\s+keep y\\s+<MULTIPLE>\\s*" \
+	     "${bpnum}\\.1\\s+y\\s+${::hex}\\s+<foo\[^>\]*> inf $::decimal" \
+	     "${bpnum}\\.2\\s+y\\s+${::hex}\\s+<foo\[^>\]*> inf $::decimal"] \
+	"check for a location in both inferiors"
+
+    gdb_continue_to_breakpoint "stop at foo in inferior 2" "foo \\(\\) .*"
+    gdb_test_no_output "set call_count = 2" "set call_count in inferior 2"
+
+    gdb_test "inferior 1" "Switching to inferior 1 .*" \
+	"switch to inferior 1"
+    gdb_continue_to_breakpoint "stop at foo in inferior 1" "foo \\(\\) .*"
+    gdb_test_no_output "set call_count = 2" "set call_count in inferior 1"
+
+    gdb_test_no_output "python bp.thread = 2"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "${bpnum}\\s+breakpoint\\s+keep y\\s+${::hex}\\s+<foo\[^>\]*> inf 2" \
+	     "\\s+stop only in thread 2\\.1" \
+	     "\\s+breakpoint already hit 2 times"] \
+	"check for a location only in inferior 2"
+
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "stop after close in inferior 1" \
+	".* Break after close\\. .*"
+
+    gdb_test "inferior 2" "Switching to inferior 2 .*" \
+	"switch back to inferior 2"
+    gdb_continue_to_breakpoint "stop at foo again in inferior 2" \
+	"foo \\(\\) .*"
+}
+
 # Run all the tests.
 test_no_inf_display
+test_pending_toggle
+py_test_toggle_thread
+py_test_clear_thread
diff --git a/gdb/testsuite/gdb.multi/tids.exp b/gdb/testsuite/gdb.multi/tids.exp
index 18fc4970fe7..34c270309de 100644
--- a/gdb/testsuite/gdb.multi/tids.exp
+++ b/gdb/testsuite/gdb.multi/tids.exp
@@ -433,11 +433,13 @@ if { [allow_python_tests] } {
 
 	gdb_py_test_silent_cmd "python bp = gdb.breakpoints()\[0\]" \
 	    "get python breakpoint" 0
-	gdb_test "python bp.thread = 6" "thread = 6" \
+	gdb_test_no_output "python bp.thread = 6" \
 	    "make breakpoint thread-specific with python"
 	# Check that the inferior-qualified ID is correct.
 	gdb_test "info breakpoint" \
-	    "stop only in thread 1.3\r\n.*" \
+	    [multi_line \
+		 "$decimal\\s+\[^\r\n\]+ in thread_function1 at \[^\r\n\]+" \
+		 "\\s+stop only in thread 1\\.3"] \
 	    "thread specific breakpoint right thread"
     }
 }
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* Re: [PATCHv7 02/11] gdb: create_breakpoint: asserts relating to extra_string/parse_extra
  2023-12-13 22:38             ` [PATCHv7 02/11] gdb: create_breakpoint: asserts relating to extra_string/parse_extra Andrew Burgess
@ 2023-12-15 20:08               ` Tom Tromey
  0 siblings, 0 replies; 138+ messages in thread
From: Tom Tromey @ 2023-12-15 20:08 UTC (permalink / raw)
  To: Andrew Burgess; +Cc: gdb-patches

>>>>> "Andrew" == Andrew Burgess <aburgess@redhat.com> writes:

Andrew> This commit makes one possibly breaking change: until this commit it
Andrew> was possible to create thread-specific dprintf breakpoint like this:

Andrew>   (gdb) dprintf call_me, thread 1 "%s", "hello"
Andrew>   Dprintf 2 at 0x401152: file /tmp/hello.c, line 8.
Andrew>   (gdb) info breakpoints
Andrew>   Num     Type           Disp Enb Address            What
Andrew>   2       dprintf        keep y   0x0000000000401152 in call_me at /tmp/hello.c:8 thread 1
Andrew>           stop only in thread 1
Andrew>           printf "%s", "hello"
Andrew>   (gdb)

Andrew> This feature of dprintf was not documented, was not tested, and is
Andrew> slightly different in syntax to how we create thread specific
Andrew> breakpoints and/or watchpoints -- the thread condition appears after
Andrew> the first ','.

Andrew> I believe that this worked at all was simply by luck.  We happen to
Andrew> pass the parse_extra flag as true from dprintf_command to
Andrew> create_breakpoint.

FWIW, I agree, this is just an accident of the implementation and not
something we should continue to support.

Tom

^ permalink raw reply	[flat|nested] 138+ messages in thread

* Re: [PATCHv7 07/11] gdb: parse pending breakpoint thread/task immediately
  2023-12-13 22:38             ` [PATCHv7 07/11] gdb: parse pending breakpoint thread/task immediately Andrew Burgess
@ 2023-12-15 20:53               ` Tom Tromey
  2023-12-18 11:33                 ` Andrew Burgess
  0 siblings, 1 reply; 138+ messages in thread
From: Tom Tromey @ 2023-12-15 20:53 UTC (permalink / raw)
  To: Andrew Burgess; +Cc: gdb-patches, Eli Zaretskii

>>>>> "Andrew" == Andrew Burgess <aburgess@redhat.com> writes:

Andrew> As a result of this commit the breakpoints 'extra_string' field is now
Andrew> only used by bp_dprintf type breakpoints to hold the printf format and
Andrew> arguments.  This string should always be empty for other breakpoint
Andrew> types.  This allows me to clean up some code in
Andrew> print_breakpoint_location.

I wonder if this member can be pushed into struct dprintf_breakpoint.
(I don't think you should do that in this series, you've been waiting
long enough.)

Andrew>   2. The handling of '-force-condition' is odd, if this flag appears
Andrew>   immediately after a condition then it will be treated as part of the
Andrew>   condition, e.g.:

We probably should have required this to appear before the linespec.

Maybe also thread/task/etc.

Andrew> +/* Return true if STR starts with PREFIX, otherwise return false.  */
Andrew> +
Andrew> +static bool
Andrew> +startswith (const char *str, const token &prefix)
Andrew> +{
Andrew> +  return strncmp (str, prefix.data (), prefix.length ()) == 0;
Andrew> +}

I wouldn't mind this in common-utils.h alongside the other startswith,
but it's fine here too.

Andrew> +  test ("  if blah  ", "blah");
Andrew> +  test (" if blah thread 1", "blah", global_thread_num);
Andrew> +  test (" if blah inferior 1", "blah", -1, 1);
Andrew> +  test (" if blah thread 1  ", "blah", global_thread_num);

It seems like there are some confounding cases, where gdb would previous
(rightly) give a syntax error, but where now they may be passed through
without notice.

I thought of some... maybe in the "don't care" bucket.  I mean, it would
be nice if we could do a little better, since I guess the user could
typo and then wind up with a breakpoint that's never really useful,
like:

    break some_future_function -force-condition if x == thread 5

Will this ever yield an error?  Maybe the user accidentally left out the
right-hand-side of that 'thread'.  Or maybe meant to write "thread thread".

Probably the worst cases involve deliberately confounding macro
definitions, but these IMO are definitely "don't care".  Maybe advising
the user to surround the 'if' in parens and that's enough, assuming:

    break func if ( x == thread )

... does the right thing.

Tom

^ permalink raw reply	[flat|nested] 138+ messages in thread

* Re: [PATCHv7 00/11] thread-specific breakpoints in just some inferiors
  2023-12-13 22:38           ` [PATCHv7 00/11] thread-specific breakpoints in just some inferiors Andrew Burgess
                               ` (10 preceding siblings ...)
  2023-12-13 22:38             ` [PATCHv7 11/11] gdb: only insert thread-specific breakpoints in the relevant inferior Andrew Burgess
@ 2023-12-15 20:54             ` Tom Tromey
  2023-12-29  9:26             ` [PATCHv8 00/14] " Andrew Burgess
  12 siblings, 0 replies; 138+ messages in thread
From: Tom Tromey @ 2023-12-15 20:54 UTC (permalink / raw)
  To: Andrew Burgess; +Cc: gdb-patches

>>>>> "Andrew" == Andrew Burgess <aburgess@redhat.com> writes:

Andrew> In v7:

Not a record but getting up there.

Anyway I read all the shorter patches and skimmed the longer ones.
I sent a few notes, but there's nothing serious and I think you should
move forward with it.

Thank you for doing this, I feel like its sort of a step toward
fine-grained breakpoint resetting as well.

Tom

^ permalink raw reply	[flat|nested] 138+ messages in thread

* Re: [PATCHv7 07/11] gdb: parse pending breakpoint thread/task immediately
  2023-12-15 20:53               ` Tom Tromey
@ 2023-12-18 11:33                 ` Andrew Burgess
  0 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-12-18 11:33 UTC (permalink / raw)
  To: Tom Tromey; +Cc: gdb-patches, Eli Zaretskii

Tom Tromey <tom@tromey.com> writes:

>>>>>> "Andrew" == Andrew Burgess <aburgess@redhat.com> writes:
>
> Andrew> As a result of this commit the breakpoints 'extra_string' field is now
> Andrew> only used by bp_dprintf type breakpoints to hold the printf format and
> Andrew> arguments.  This string should always be empty for other breakpoint
> Andrew> types.  This allows me to clean up some code in
> Andrew> print_breakpoint_location.
>
> I wonder if this member can be pushed into struct dprintf_breakpoint.
> (I don't think you should do that in this series, you've been waiting
> long enough.)
>
> Andrew>   2. The handling of '-force-condition' is odd, if this flag appears
> Andrew>   immediately after a condition then it will be treated as part of the
> Andrew>   condition, e.g.:
>
> We probably should have required this to appear before the linespec.
>
> Maybe also thread/task/etc.

So Baris also asked about this change on V6.  Apparently when the
-force-condition flag was first added there was a couple of requests
that the implementation change to use a more GDB option like approach,
and I think that makes sense.

I looked into this a little, and it's a slightly more complex change.

The existing breakpoint options are not handled like "normal" options,
but are tied up with location parsing.  And I don't think it makes sense
to handle -force-condition (or thread/task/etc) there -- these options
are related to the condition, not the location.

So my thinking is that what should happen is that the location parsing
code should export the gdb::option::* related data structures needed to
parse the location related options.

The condition related code should export the gdb::option::* related data
structures needed to parse the condition related options.

Then in breakpoint.c we'd create a gdb::option::option_def_group that
can parse all of the various options.

And finally, we can send those parsed options from breakpoint.c down
into the various parts of GDB (the location parsing and condition
parsing).

However.... one of the breakpoint options is a filename, and that
option currently supports filename completion.

So, to move to the gdb::option::* approach we need a new
gdb::option::filename_option_def, which we don't currently have.
Actually we're going to need a couple of new *_option_def types, but I
think filenames are the hardest.

I'm aware of a couple of attempts to add a filename_option_def; Pedro
has a branch `filename-options` on his github, and also Lancelot posted
this a while back:

  https://inbox.sourceware.org/gdb-patches/20210213220752.32581-1-lsix@lancelotsix.com/

I prefer Pedro's approach, though I haven't finished re-reading
Lancelot's branch (apparently I did review it when it was originally
posted, but I don't remember it), so maybe Lancelot's work offers
something Pedro's is missing.  However, Pedro never posted his work, so
I can't post anything based on that branch yet (Copyright), but I've
reached out to ask for permission.

Anyway.... the summary of all this, is that I have a multi-step plan to
change how -force-condition (and possibly thread/task/etc, we'll see)
are handled, but it requires a bunch of setup, so I don't plan to
combine these tasks (unless that becomes a requirement).

>
> Andrew> +/* Return true if STR starts with PREFIX, otherwise return false.  */
> Andrew> +
> Andrew> +static bool
> Andrew> +startswith (const char *str, const token &prefix)
> Andrew> +{
> Andrew> +  return strncmp (str, prefix.data (), prefix.length ()) == 0;
> Andrew> +}
>
> I wouldn't mind this in common-utils.h alongside the other startswith,
> but it's fine here too.
>
> Andrew> +  test ("  if blah  ", "blah");
> Andrew> +  test (" if blah thread 1", "blah", global_thread_num);
> Andrew> +  test (" if blah inferior 1", "blah", -1, 1);
> Andrew> +  test (" if blah thread 1  ", "blah", global_thread_num);
>
> It seems like there are some confounding cases, where gdb would previous
> (rightly) give a syntax error, but where now they may be passed through
> without notice.
>
> I thought of some... maybe in the "don't care" bucket.  I mean, it would
> be nice if we could do a little better, since I guess the user could
> typo and then wind up with a breakpoint that's never really useful,
> like:
>
>     break some_future_function -force-condition if x == thread 5
>
> Will this ever yield an error?  Maybe the user accidentally left out the
> right-hand-side of that 'thread'.  Or maybe meant to write "thread thread".
>
> Probably the worst cases involve deliberately confounding macro
> definitions, but these IMO are definitely "don't care".  Maybe advising
> the user to surround the 'if' in parens and that's enough, assuming:
>
>     break func if ( x == thread )
>
> ... does the right thing.

I'll add some new tests for these cases and dig into how they behave.

Thank,
Andrew


>
> Tom


^ permalink raw reply	[flat|nested] 138+ messages in thread

* RE: [PATCHv6 06/10] gdb: parse pending breakpoint thread/task immediately
  2023-12-13 13:51               ` Andrew Burgess
@ 2023-12-27 12:23                 ` Aktemur, Tankut Baris
  0 siblings, 0 replies; 138+ messages in thread
From: Aktemur, Tankut Baris @ 2023-12-27 12:23 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches; +Cc: Eli Zaretskii

On Wednesday, December 13, 2023 2:51 PM, Andrew Burgess wrote:
> >> +  /* The "-force-condition" flag gets some special treatment.  If this
> >> +     token is immediately after the condition string then we treat this as
> >> +     part of the condition string rather than a separate token.  This is
> >> +     just a quirk of how this token used to be parsed, and has been
> >> +     retained for backwards compatibility.  Maybe this should be updated
> >> +     in the future.  */
> >
> > (I was the author of the -force-condition patch.)
> > The quirks about the -force-condition flag were not a deliberate feature.
> > For whatever it's worth, I think it's OK to de-prioritize backwards
> > compatibility for this flag.  I doubt that it would impact many users.
> >
> > In fact, in a post-merge comment, Pedro and Tom had suggested converting
> > the flag to an option rather than a keyword:
> >
> > https://sourceware.org/pipermail/gdb-patches/2020-October/172952.html
> > https://sourceware.org/pipermail/gdb-patches/2020-December/173802.html
> > https://sourceware.org/pipermail/gdb-patches/2020-December/173999.html
> >
> > I (embarrassingly) did not have the opportunity to get back to it.  Maybe
> > it's now the correct time to address the concerns?  I can gladly help.
> > What do you think?
> 
> I think this sounds like a good idea, but ....
> 
> ... I took a quick look at how this might be done,

Thanks for taking a look!

> and the problem I see
> is that the current 'break' option parsing is buried within
> string_to_explicit_location_spec, which is called from
> string_to_location_spec, which is called from multiple commands.
> 
> Which makes sense, currently, all of the options for 'break' are about
> specifying the location.
> 
> In contrast, -force-condition has nothing to do with the location, but
> relates (as you know) to the condition.
> 
> We could handle -force-condition in string_to_explicit_location_spec,
> but then commands like 'edit', which take a location, but not a
> condition would accept -force-condition, and we'd have to have some
> mechanism to the 'force' flag true/false value back out of
> string_to_explicit_location_spec, either passing a container around, or
> storing the 'force' state within the locspec... this all sounds like the
> wrong approach.
> 
> Better I think would be to pull the option parsing out of
> string_to_explicit_location_spec, and move it into the individual
> commands.  What we'd ideally want is to convert the current bespoke
> option parsing (for location spec options) to use GDB's generic option
> parsing mechanism.  It's possible to bind multiple
> gdb::option::option_def into a single gdb::option::option_def_group, so
> we can imagine that the 'break' command would use a common
> gdb::option::option_def from location.h, which defines all the location
> spec arguments, and then a separate gdb::option::option_def which adds
> the -force-condition flag.  The only issue then is that we'd need to
> pass the location spec related arguments into
> string_to_explicit_location_spec somehow....
> 
> Phew.  Now the next problem is that the gdb::option::option_def contains
> a list of gdb::option::*_option_def objects, the precise type of which
> defines how the options are parsed.  It we look at how the arguments to
> things like -function are parsed, these get special language specific
> handling, which the current option mechanism doesn't support, so I think
> we'd need to add that, which will mean at least extending the option
> process, or maybe even some reworking of the option handling...
> 
> All that is to say that I agree with Pedro that this would be better
> done as an real option ... but I really don't want to tie this work to
> that refactoring if at all possible...

Yes, sure, given the non-trivial nature of that refactoring, this makes sense.

Thanks
-Baris


Intel Deutschland GmbH
Registered Address: Am Campeon 10, 85579 Neubiberg, Germany
Tel: +49 89 99 8853-0, www.intel.de <http://www.intel.de>
Managing Directors: Christin Eisenschmid, Sharon Heck, Tiffany Doon Silva  
Chairperson of the Supervisory Board: Nicole Lau
Registered Office: Munich
Commercial Register: Amtsgericht Muenchen HRB 186928


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv8 00/14] thread-specific breakpoints in just some inferiors
  2023-12-13 22:38           ` [PATCHv7 00/11] thread-specific breakpoints in just some inferiors Andrew Burgess
                               ` (11 preceding siblings ...)
  2023-12-15 20:54             ` [PATCHv7 00/11] thread-specific breakpoints in just some inferiors Tom Tromey
@ 2023-12-29  9:26             ` Andrew Burgess
  2023-12-29  9:26               ` [PATCHv8 01/14] gdb: create_breakpoint: add asserts and additional comments Andrew Burgess
                                 ` (14 more replies)
  12 siblings, 15 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-12-29  9:26 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

In v8:

  - Rebased onto current upstream/master branch.

  - Reordered the patches a little.  Patches 0 to 8 are unchanged from
    previous.  If there's no objections then I'm planning to merge
    these some point soon as I think these are all good cleanup patches.

  - Patches 9, 10, and 11 are new.  These are also refactoring
    commits, but are all tied pretty tightly to what is now patch 12.

  - Patch 12 is the most important patch.  This has had a complete
    rewrite since V7 in order to address Tom's feedback.  The general
    idea is unchanged; the breakpoint condition string is parsed first
    forwards, and then backwards, but we now have a two phase
    analysis, rather than immediately parsing things like the
    thread-id as we find them.  This resolves this problem:

    (gdb) break some_function if ( 3 == thread )

    Previous GDB would try to match 'thread )' as a thread-id and give
    an error that ')' as invalid.  Now GDB correctly understands that
    the 'thread )' is likely part of the 'if' condition, and parses it
    as such.

  - Patches 13 and 14 are unchanged from V7.  These patches depend on
    the changes in patch 12 so can't be merged without that patch.

In v7:

  - Addressed all the issues except one that Baris pointed out, this
    includes typos, some minor testsuite cleanups, and reformatting an
    assert (but not changing the meaning).

  - As requested, switched to use std::string_view in
    break-parse-cond.c file instead of a custom class, I agree that
    this is an improvement.

  - I've not changed the handling of -force-condition flag.  I replied
    to the review email with my thoughts, TLDR: fixing this would be a
    bigger task which I'd rather leave for ... the future.

  - Rebased and retested.

In v6:

  - Rebased to current master, one minor fix due to the C++17 changes,
    nothing major.  Retested.

In v5:

  - Updates after Lancelot's feedback, including, -force-condition can
    no longer be abbreviated to '-', and can't be used immediately
    after the breakpoint condition.

  - More tests to check some of the edge cases.

In v4:

  - Big update, this series now handles thread-specific and
    inferior-specific breakpoints.

In v3:

  - Rebased on to current upstream/master, this includes all Simon's
    recent breakpoint changes.  Retested with no regressions seen.

In v2:

  - Rebased on current upstream/master and retested,

  - No changes to code or docs.

---

Andrew Burgess (14):
  gdb: create_breakpoint: add asserts and additional comments
  gdb: create_breakpoint: asserts relating to extra_string/parse_extra
  gdb: change 'if' to gdb_assert in update_dprintf_command_list
  gdb: the extra_string in a dprintf breakpoint is never nullptr
  gdb: build dprintf commands just once in code_breakpoint constructor
  gdb: don't display inferior list for pending breakpoints
  gdb: remove breakpoint_re_set_one
  gdb: remove tracepoint_probe_create_sals_from_location_spec
  gdb: make breakpoint_debug_printf global
  gdb: add another overload of startswith
  gdb: create new is_thread_id helper function
  gdb: parse pending breakpoint thread/task immediately
  gdb: don't set breakpoint::pspace in create_breakpoint
  gdb: only insert thread-specific breakpoints in the relevant inferior

 gdb/Makefile.in                               |   2 +
 gdb/NEWS                                      |  11 +
 gdb/ada-lang.c                                |   6 +-
 gdb/break-catch-throw.c                       |   6 +-
 gdb/break-cond-parse.c                        | 701 ++++++++++++++++
 gdb/break-cond-parse.h                        |  52 ++
 gdb/breakpoint.c                              | 773 ++++++++----------
 gdb/breakpoint.h                              | 109 ++-
 gdb/testsuite/gdb.ada/tasks.exp               |   6 +-
 gdb/testsuite/gdb.base/condbreak.exp          |  57 +-
 gdb/testsuite/gdb.base/pending.exp            |  23 +-
 gdb/testsuite/gdb.linespec/explicit.exp       |   4 +-
 gdb/testsuite/gdb.linespec/keywords.exp       |   8 +-
 gdb/testsuite/gdb.mi/mi-dprintf-pending.exp   |   3 +-
 gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp    |   8 +-
 .../gdb.mi/user-selected-context-sync.exp     |   4 +-
 .../gdb.multi/bp-thread-specific.exp          |   7 +-
 .../gdb.multi/inferior-specific-bp.exp        |  16 +-
 .../gdb.multi/multi-target-continue.exp       |   2 +-
 .../gdb.multi/multi-target-ping-pong-next.exp |   4 +-
 .../gdb.multi/pending-bp-del-inferior.c       |  28 +
 .../gdb.multi/pending-bp-del-inferior.exp     | 214 +++++
 gdb/testsuite/gdb.multi/pending-bp-lib.c      |  22 +
 gdb/testsuite/gdb.multi/pending-bp.c          |  66 ++
 gdb/testsuite/gdb.multi/pending-bp.exp        | 332 ++++++++
 gdb/testsuite/gdb.multi/tids.exp              |   6 +-
 .../gdb.threads/del-pending-thread-bp-lib.c   |  22 +
 .../gdb.threads/del-pending-thread-bp.c       |  85 ++
 .../gdb.threads/del-pending-thread-bp.exp     | 108 +++
 gdb/tid-parse.c                               |  82 +-
 gdb/tid-parse.h                               |   8 +
 gdbsupport/common-utils.h                     |  10 +
 32 files changed, 2279 insertions(+), 506 deletions(-)
 create mode 100644 gdb/break-cond-parse.c
 create mode 100644 gdb/break-cond-parse.h
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-del-inferior.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.exp
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.exp


base-commit: 90827b4eefb06f6e0ab6cbac9eb94922e2cc8aee
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv8 01/14] gdb: create_breakpoint: add asserts and additional comments
  2023-12-29  9:26             ` [PATCHv8 00/14] " Andrew Burgess
@ 2023-12-29  9:26               ` Andrew Burgess
  2023-12-29  9:26               ` [PATCHv8 02/14] gdb: create_breakpoint: asserts relating to extra_string/parse_extra Andrew Burgess
                                 ` (13 subsequent siblings)
  14 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-12-29  9:26 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

This commit extends the asserts on create_breakpoint (in the header
file), and adds some additional assertions into the definition.

The new assert confirms that when the thread and inferior information
is going to be parsed from the extra_string, then the thread and
inferior arguments should be -1.  That is, the caller of
create_breakpoint should not try to create a thread/inferior specific
breakpoint by *both* specifying thread/inferior *and* asking to parse
the extra_string, it's one or the other.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c |  6 ++++++
 gdb/breakpoint.h | 16 ++++++++++++++++
 2 files changed, 22 insertions(+)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index bd7f74671ce..c16530c5400 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -9229,6 +9229,12 @@ create_breakpoint (struct gdbarch *gdbarch,
   gdb_assert (inferior == -1 || inferior > 0);
   gdb_assert (thread == -1 || inferior == -1);
 
+  /* If PARSE_EXTRA is true then the thread and inferior details will be
+     parsed from the EXTRA_STRING, the THREAD and INFERIOR arguments
+     should be -1.  */
+  gdb_assert (!parse_extra || thread == -1);
+  gdb_assert (!parse_extra || inferior == -1);
+
   gdb_assert (ops != NULL);
 
   /* If extra_string isn't useful, set it to NULL.  */
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index feb798224c0..4abf6d0762c 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -1600,6 +1600,22 @@ enum breakpoint_create_flags
    the FORCE_CONDITION parameter is ignored and the corresponding argument
    is parsed from EXTRA_STRING.
 
+   The THREAD should be a global thread number, the created breakpoint will
+   only apply for that thread.  If the breakpoint should apply for all
+   threads then pass -1.  However, if PARSE_EXTRA is non-zero then the
+   THREAD parameter is ignored and an optional thread number will be parsed
+   from EXTRA_STRING.
+
+   The INFERIOR should be a global inferior number, the created breakpoint
+   will only apply for that inferior.  If the breakpoint should apply for
+   all inferiors then pass -1.  However, if PARSE_EXTRA is non-zero then
+   the INFERIOR parameter is ignored and an optional inferior number will
+   be parsed from EXTRA_STRING.
+
+   At most one of THREAD and INFERIOR should be set to a value other than
+   -1; breakpoints can be thread specific, or inferior specific, but not
+   both.
+
    If INTERNAL is non-zero, the breakpoint number will be allocated
    from the internal breakpoint count.
 
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv8 02/14] gdb: create_breakpoint: asserts relating to extra_string/parse_extra
  2023-12-29  9:26             ` [PATCHv8 00/14] " Andrew Burgess
  2023-12-29  9:26               ` [PATCHv8 01/14] gdb: create_breakpoint: add asserts and additional comments Andrew Burgess
@ 2023-12-29  9:26               ` Andrew Burgess
  2023-12-29  9:26               ` [PATCHv8 03/14] gdb: change 'if' to gdb_assert in update_dprintf_command_list Andrew Burgess
                                 ` (12 subsequent siblings)
  14 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-12-29  9:26 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

The goal of this commit is to better define the API for
create_breakpoint especially around the use of extra_string and
parse_extra.  This will be useful in the next commit when I plan to
make some changes to create_breakpoint.

This commit makes one possibly breaking change: until this commit it
was possible to create thread-specific dprintf breakpoint like this:

  (gdb) dprintf call_me, thread 1 "%s", "hello"
  Dprintf 2 at 0x401152: file /tmp/hello.c, line 8.
  (gdb) info breakpoints
  Num     Type           Disp Enb Address            What
  2       dprintf        keep y   0x0000000000401152 in call_me at /tmp/hello.c:8 thread 1
          stop only in thread 1
          printf "%s", "hello"
  (gdb)

This feature of dprintf was not documented, was not tested, and is
slightly different in syntax to how we create thread specific
breakpoints and/or watchpoints -- the thread condition appears after
the first ','.

I believe that this worked at all was simply by luck.  We happen to
pass the parse_extra flag as true from dprintf_command to
create_breakpoint.

So in this commit I made the choice change this.  We now pass
parse_extra as false from dprintf_command to create_breakpoint.  With
this done it is assumed that the only thing in the extra_string is the
dprintf format and arguments.

Beyond this change I've updated the comment on create_breakpoint in
breakpoint.h, and I've then added some asserts into
create_breakpoint as well as moving around some of the error
handling.

 - We now assert on the incoming argument values,

 - I've moved an error check to sit after the call to
   find_condition_and_thread_for_sals, this ensures the extra_string
   was parsed correctly,

In dprintf_command:

 - We now throw an error if there is no format string after the
   dprintf location.  This error was already being thrown, but was
   being caught later in the process.  With this change we catch the
   missing string earlier,

 - And, as mentioned earlier, we pass parse_extra as false when
   calling create_breakpoint,

In create_tracepoint_from_upload:

 - We now throw an error if the parsed location doesn't completely
   consume the addr_str variable.  This error has now effectively
   moved out of create_breakpoint.
---
 gdb/breakpoint.c | 41 ++++++++++++++++++++++++++++-------------
 gdb/breakpoint.h | 44 +++++++++++++++++++++++++++-----------------
 2 files changed, 55 insertions(+), 30 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index c16530c5400..3ba3d0d3d12 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -9241,6 +9241,16 @@ create_breakpoint (struct gdbarch *gdbarch,
   if (extra_string != NULL && *extra_string == '\0')
     extra_string = NULL;
 
+  /* A bp_dprintf must always have an accompanying EXTRA_STRING containing
+     the dprintf format and arguments -- PARSE_EXTRA should always be false
+     in this case.
+
+     For all other breakpoint types, EXTRA_STRING should be nullptr unless
+     PARSE_EXTRA is true.  */
+  gdb_assert ((type_wanted == bp_dprintf)
+	      ? (extra_string != nullptr && !parse_extra)
+	      : (extra_string == nullptr || parse_extra));
+
   try
     {
       ops->create_sals_from_location_spec (locspec, &canonical);
@@ -9304,6 +9314,8 @@ create_breakpoint (struct gdbarch *gdbarch,
 
       if (parse_extra)
 	{
+	  gdb_assert (type_wanted != bp_dprintf);
+
 	  gdb::unique_xmalloc_ptr<char> rest;
 	  gdb::unique_xmalloc_ptr<char> cond;
 
@@ -9312,15 +9324,15 @@ create_breakpoint (struct gdbarch *gdbarch,
 	  find_condition_and_thread_for_sals (lsal.sals, extra_string,
 					      &cond, &thread, &inferior,
 					      &task, &rest);
+
+	  if (rest.get () != nullptr && *(rest.get ()) != '\0')
+	    error (_("Garbage '%s' at end of command"), rest.get ());
+
 	  cond_string_copy = std::move (cond);
 	  extra_string_copy = std::move (rest);
 	}
       else
 	{
-	  if (type_wanted != bp_dprintf
-	      && extra_string != NULL && *extra_string != '\0')
-		error (_("Garbage '%s' at end of location"), extra_string);
-
 	  /* Check the validity of the condition.  We should error out
 	     if the condition is invalid at all of the locations and
 	     if it is not forced.  In the PARSE_EXTRA case above, this
@@ -9531,21 +9543,18 @@ dprintf_command (const char *arg, int from_tty)
 
   /* If non-NULL, ARG should have been advanced past the location;
      the next character must be ','.  */
-  if (arg != NULL)
+  if (arg == nullptr || arg[0] != ',' || arg[1] == '\0')
+    error (_("Format string required"));
+  else
     {
-      if (arg[0] != ',' || arg[1] == '\0')
-	error (_("Format string required"));
-      else
-	{
-	  /* Skip the comma.  */
-	  ++arg;
-	}
+      /* Skip the comma.  */
+      ++arg;
     }
 
   create_breakpoint (get_current_arch (),
 		     locspec.get (),
 		     NULL, -1, -1,
-		     arg, false, 1 /* parse arg */,
+		     arg, false, 0 /* parse arg */,
 		     0, bp_dprintf,
 		     0 /* Ignore count */,
 		     pending_break_support,
@@ -14149,6 +14158,12 @@ create_tracepoint_from_upload (struct uploaded_tp *utp)
 
   location_spec_up locspec = string_to_location_spec (&addr_str,
 						      current_language);
+
+
+  gdb_assert (addr_str != nullptr);
+  if (*addr_str != '\0')
+    error (_("Garbage '%s' at end of location"), addr_str);
+
   if (!create_breakpoint (get_current_arch (),
 			  locspec.get (),
 			  utp->cond_string.get (), -1, -1, addr_str,
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index 4abf6d0762c..95f98b59e41 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -1585,32 +1585,42 @@ enum breakpoint_create_flags
    functions for setting a breakpoint at LOCSPEC.
 
    This function has two major modes of operations, selected by the
-   PARSE_EXTRA parameter.
+   PARSE_EXTRA and WANTED_TYPE parameters.
 
-   If PARSE_EXTRA is zero, LOCSPEC is just the breakpoint's location
-   spec, with condition, thread, and extra string specified by the
-   COND_STRING, THREAD, and EXTRA_STRING parameters.
+   When WANTED_TYPE is not bp_dprintf the following rules apply:
 
-   If PARSE_EXTRA is non-zero, this function will attempt to extract
-   the condition, thread, and extra string from EXTRA_STRING, ignoring
-   the similarly named parameters.
+     If PARSE_EXTRA is zero, LOCSPEC is just the breakpoint's location
+     spec, with condition, thread, and extra string specified by the
+     COND_STRING, THREAD, and EXTRA_STRING parameters.
 
-   If FORCE_CONDITION is true, the condition is accepted even when it is
-   invalid at all of the locations.  However, if PARSE_EXTRA is non-zero,
-   the FORCE_CONDITION parameter is ignored and the corresponding argument
-   is parsed from EXTRA_STRING.
+     If PARSE_EXTRA is non-zero, this function will attempt to extract the
+     condition, thread, and extra string from EXTRA_STRING, ignoring the
+     similarly named parameters.
+
+   When WANTED_TYPE is bp_dprintf the following rules apply:
+
+     PARSE_EXTRA must always be zero, LOCSPEC is just the breakpoint's
+     location spec, with condition, thread, and extra string (which
+     contains the dprintf format and arguments) specified by the
+     COND_STRING, THREAD, and EXTRA_STRING parameters.
+
+   If FORCE_CONDITION is true, the condition (in COND_STRING) is accepted
+   even when it is invalid at all of the locations.  However, if
+   PARSE_EXTRA is non-zero and WANTED_TYPE is not bp_dprintf, the
+   FORCE_CONDITION parameter is ignored and the corresponding argument is
+   parsed from EXTRA_STRING.
 
    The THREAD should be a global thread number, the created breakpoint will
    only apply for that thread.  If the breakpoint should apply for all
-   threads then pass -1.  However, if PARSE_EXTRA is non-zero then the
-   THREAD parameter is ignored and an optional thread number will be parsed
-   from EXTRA_STRING.
+   threads then pass -1.  However, if PARSE_EXTRA is non-zero and
+   WANTED_TYPE is not bp_dprintf, then the THREAD parameter is ignored and
+   an optional thread number will be parsed from EXTRA_STRING.
 
    The INFERIOR should be a global inferior number, the created breakpoint
    will only apply for that inferior.  If the breakpoint should apply for
-   all inferiors then pass -1.  However, if PARSE_EXTRA is non-zero then
-   the INFERIOR parameter is ignored and an optional inferior number will
-   be parsed from EXTRA_STRING.
+   all inferiors then pass -1.  However, if PARSE_EXTRA is non-zero and
+   WANTED_TYPE is not bp_dprintf, then the INFERIOR parameter is ignored
+   and an optional inferior number will be parsed from EXTRA_STRING.
 
    At most one of THREAD and INFERIOR should be set to a value other than
    -1; breakpoints can be thread specific, or inferior specific, but not
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv8 03/14] gdb: change 'if' to gdb_assert in update_dprintf_command_list
  2023-12-29  9:26             ` [PATCHv8 00/14] " Andrew Burgess
  2023-12-29  9:26               ` [PATCHv8 01/14] gdb: create_breakpoint: add asserts and additional comments Andrew Burgess
  2023-12-29  9:26               ` [PATCHv8 02/14] gdb: create_breakpoint: asserts relating to extra_string/parse_extra Andrew Burgess
@ 2023-12-29  9:26               ` Andrew Burgess
  2023-12-29  9:26               ` [PATCHv8 04/14] gdb: the extra_string in a dprintf breakpoint is never nullptr Andrew Burgess
                                 ` (11 subsequent siblings)
  14 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-12-29  9:26 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

I noticed in update_dprintf_command_list that we handle the case where
the bp_dprintf style breakpoint doesn't have a format and args string.

However, I don't believe such a situation is possible.  The obvious
approach certainly already catches this case:

  (gdb) dprintf main
  Format string required

If it is possible to create a dprintf breakpoint without a format and
args string then I think we should be catching this case and handling
it at creation time, rather than having GDB just ignore the situation
later on.

And so, I propose that we change the 'if' that ignores the case where
the format/args string is empty, and instead assert that we do always
have a format/args string.  The original code, that handled an empty
format/args string has existed since commit e7e0cddfb0d4, which is
when dprintf support was added to GDB.

If I'm correct and this situation can't ever happen then there should
be no user visible changes after this commit.
---
 gdb/breakpoint.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 3ba3d0d3d12..48c44ea27cc 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -8538,8 +8538,9 @@ update_dprintf_command_list (struct breakpoint *b)
   const char *dprintf_args = b->extra_string.get ();
   gdb::unique_xmalloc_ptr<char> printf_line = nullptr;
 
-  if (!dprintf_args)
-    return;
+  /* Trying to create a dprintf breakpoint without a format and args
+     string should be detected at creation time.  */
+  gdb_assert (dprintf_args != nullptr);
 
   dprintf_args = skip_spaces (dprintf_args);
 
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv8 04/14] gdb: the extra_string in a dprintf breakpoint is never nullptr
  2023-12-29  9:26             ` [PATCHv8 00/14] " Andrew Burgess
                                 ` (2 preceding siblings ...)
  2023-12-29  9:26               ` [PATCHv8 03/14] gdb: change 'if' to gdb_assert in update_dprintf_command_list Andrew Burgess
@ 2023-12-29  9:26               ` Andrew Burgess
  2023-12-29  9:27               ` [PATCHv8 05/14] gdb: build dprintf commands just once in code_breakpoint constructor Andrew Burgess
                                 ` (10 subsequent siblings)
  14 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-12-29  9:26 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Given the changes in the previous couple of commits, this commit
cleans up some of the asserts and 'if' checks related to the
extra_string within a dprintf breakpoint.

This commit:

  1. Adds some asserts to update_dprintf_command_list about the
  breakpoint type, and that the extra_string is not nullptr,

  2. Given that we know extra_string is not nullptr (this is enforced
  when the breakpoint is created), we can simplify
  code_breakpoint::code_breakpoint -- it no longer needs to check for
  the extra_string is nullptr case,

  3. In dprintf_breakpoint::re_set we can remove the assert (this will
  be checked within update_dprintf_command_list, we can also remove
  the redundant 'if' check.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c | 16 +++++-----------
 1 file changed, 5 insertions(+), 11 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 48c44ea27cc..69a6f926b4e 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -8535,6 +8535,9 @@ bp_loc_is_permanent (struct bp_location *loc)
 static void
 update_dprintf_command_list (struct breakpoint *b)
 {
+  gdb_assert (b->type == bp_dprintf);
+  gdb_assert (b->extra_string != nullptr);
+
   const char *dprintf_args = b->extra_string.get ();
   gdb::unique_xmalloc_ptr<char> printf_line = nullptr;
 
@@ -8708,12 +8711,7 @@ code_breakpoint::code_breakpoint (struct gdbarch *gdbarch_,
       /* Dynamic printf requires and uses additional arguments on the
 	 command line, otherwise it's an error.  */
       if (type == bp_dprintf)
-	{
-	  if (extra_string != nullptr)
-	    update_dprintf_command_list (this);
-	  else
-	    error (_("Format string required"));
-	}
+	update_dprintf_command_list (this);
       else if (extra_string != nullptr)
 	error (_("Garbage '%s' at end of command"), extra_string.get ());
     }
@@ -12429,9 +12427,6 @@ dprintf_breakpoint::re_set ()
 {
   re_set_default ();
 
-  /* extra_string should never be non-NULL for dprintf.  */
-  gdb_assert (extra_string != NULL);
-
   /* 1 - connect to target 1, that can run breakpoint commands.
      2 - create a dprintf, which resolves fine.
      3 - disconnect from target 1
@@ -12442,8 +12437,7 @@ dprintf_breakpoint::re_set ()
      answers for target_can_run_breakpoint_commands().
      Given absence of finer grained resetting, we get to do
      it all the time.  */
-  if (extra_string != NULL)
-    update_dprintf_command_list (this);
+  update_dprintf_command_list (this);
 }
 
 /* Implement the "print_recreate" method for dprintf.  */
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv8 05/14] gdb: build dprintf commands just once in code_breakpoint constructor
  2023-12-29  9:26             ` [PATCHv8 00/14] " Andrew Burgess
                                 ` (3 preceding siblings ...)
  2023-12-29  9:26               ` [PATCHv8 04/14] gdb: the extra_string in a dprintf breakpoint is never nullptr Andrew Burgess
@ 2023-12-29  9:27               ` Andrew Burgess
  2023-12-29  9:27               ` [PATCHv8 06/14] gdb: don't display inferior list for pending breakpoints Andrew Burgess
                                 ` (9 subsequent siblings)
  14 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-12-29  9:27 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

I noticed in code_breakpoint::code_breakpoint that we are calling
update_dprintf_command_list once for each breakpoint location, when we
really only need to call this once per breakpoint -- the data updated
by this function, the breakpoint command list -- is per breakpoint,
not per breakpoint location.  Calling update_dprintf_command_list
multiple times is just wasted effort, there's no per location error
checking, we don't even pass the current location to the function.

This commit moves the update_dprintf_command_list call outside of the
per-location loop.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c | 14 +++++++-------
 1 file changed, 7 insertions(+), 7 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 69a6f926b4e..7951b7c5801 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -8707,15 +8707,15 @@ code_breakpoint::code_breakpoint (struct gdbarch *gdbarch_,
       /* Do not set breakpoint locations conditions yet.  As locations
 	 are inserted, they get sorted based on their addresses.  Let
 	 the list stabilize to have reliable location numbers.  */
-
-      /* Dynamic printf requires and uses additional arguments on the
-	 command line, otherwise it's an error.  */
-      if (type == bp_dprintf)
-	update_dprintf_command_list (this);
-      else if (extra_string != nullptr)
-	error (_("Garbage '%s' at end of command"), extra_string.get ());
     }
 
+  /* Dynamic printf requires and uses additional arguments on the
+     command line, otherwise it's an error.  */
+  if (type == bp_dprintf)
+    update_dprintf_command_list (this);
+  else if (extra_string != nullptr)
+    error (_("Garbage '%s' at end of command"), extra_string.get ());
+
   /* The order of the locations is now stable.  Set the location
      condition using the location's number.  */
   int loc_num = 1;
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv8 06/14] gdb: don't display inferior list for pending breakpoints
  2023-12-29  9:26             ` [PATCHv8 00/14] " Andrew Burgess
                                 ` (4 preceding siblings ...)
  2023-12-29  9:27               ` [PATCHv8 05/14] gdb: build dprintf commands just once in code_breakpoint constructor Andrew Burgess
@ 2023-12-29  9:27               ` Andrew Burgess
  2023-12-29  9:27               ` [PATCHv8 07/14] gdb: remove breakpoint_re_set_one Andrew Burgess
                                 ` (8 subsequent siblings)
  14 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-12-29  9:27 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

I noticed that in the 'info breakpoints' output, GDB sometimes prints
the inferior list for pending breakpoints, this doesn't seem right to
me.  A pending breakpoint has no locations (at least, as far as we
display things in the 'info breakpoints' output), so including an
inferior list seems odd.

Here's what I see right now:

  (gdb) info breakpoint 5
  Num     Type           Disp Enb Address            What
  5       breakpoint     keep y   <PENDING>          foo inf 1
  (gdb)

It's the 'inf 1' at the end of the line that I'm objecting too.

To trigger this behaviour we need to be in a multi-inferior debug
session.  The breakpoint must have been non-pending at some point in
the past, and so have a location assigned to it.

The breakpoint becomes pending again as a result of a shared library
being unloaded.  When this happens the location itself is marked
pending (via bp_location::shlib_disabled).

In print_one_breakpoint_location, in order to print the inferior list
we check that the breakpoint has a location, and that we have multiple
inferiors, but we don't check if the location itself is pending.

This commit adds that check, which means the output is now:

  (gdb) info breakpoint 5
  Num     Type           Disp Enb Address            What
  5       breakpoint     keep y   <PENDING>          foo
  (gdb)

Which I think makes more sense -- indeed, the format without the
inferior list is what we display for a pending breakpoint that has
never had any locations assigned, so I think this change in behaviour
makes GDB more consistent.
---
 gdb/breakpoint.c                         |   2 +-
 gdb/testsuite/gdb.multi/pending-bp-lib.c |  22 ++++
 gdb/testsuite/gdb.multi/pending-bp.c     |  66 ++++++++++++
 gdb/testsuite/gdb.multi/pending-bp.exp   | 126 +++++++++++++++++++++++
 4 files changed, 215 insertions(+), 1 deletion(-)
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.exp

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 7951b7c5801..f0724b416d3 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -6597,7 +6597,7 @@ print_one_breakpoint_location (struct breakpoint *b,
 	}
     }
 
-  if (loc != NULL && !header_of_multiple)
+  if (loc != nullptr && !header_of_multiple && !loc->shlib_disabled)
     {
       std::vector<int> inf_nums;
       int mi_only = 1;
diff --git a/gdb/testsuite/gdb.multi/pending-bp-lib.c b/gdb/testsuite/gdb.multi/pending-bp-lib.c
new file mode 100644
index 00000000000..15d1b9833dd
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp-lib.c
@@ -0,0 +1,22 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+int global_var = 0;
+
+void
+foo (int arg)
+{
+  global_var = arg;
+}
diff --git a/gdb/testsuite/gdb.multi/pending-bp.c b/gdb/testsuite/gdb.multi/pending-bp.c
new file mode 100644
index 00000000000..879e0b11ac7
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp.c
@@ -0,0 +1,66 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#include <dlfcn.h>
+#include <stdlib.h>
+
+void
+breakpt (void)
+{
+  /* Nothing.  */
+}
+
+volatile int global_counter = 0;
+
+volatile int call_count = 1;
+
+int
+main (void)
+{
+  void *handle;
+  void (*func)(int);
+
+  /* Some filler work so that we don't initially stop on the breakpt call
+     below.  */
+  ++global_counter;
+
+  breakpt ();	/* Break before open.  */
+
+  /* Now load the shared library.  */
+  handle = dlopen (SHLIB_NAME, RTLD_LAZY);
+  if (handle == NULL)
+    abort ();
+
+  breakpt ();	/* Break after open.  */
+
+  /* Find the function symbol.  */
+  func = (void (*)(int)) dlsym (handle, "foo");
+
+  for (; call_count > 0; --call_count)
+    {
+      /* Call the library function.  */
+      func (1);
+    }
+
+  breakpt ();	/* Break before close.  */
+
+  /* Unload the shared library.  */
+  if (dlclose (handle) != 0)
+    abort ();
+
+  breakpt ();	/* Break after close.  */
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.multi/pending-bp.exp b/gdb/testsuite/gdb.multi/pending-bp.exp
new file mode 100644
index 00000000000..478d8d7c037
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp.exp
@@ -0,0 +1,126 @@
+# Copyright 2023 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+# Tests related to pending breakpoints in a multi-inferior environment.
+
+require allow_shlib_tests !use_gdb_stub
+
+standard_testfile
+
+set libname $testfile-lib
+set srcfile_lib $srcdir/$subdir/$libname.c
+set binfile_lib [standard_output_file $libname.so]
+
+if { [gdb_compile_shlib $srcfile_lib $binfile_lib {}] != "" } {
+    untested "failed to compile shared library 1"
+    return -1
+}
+
+set binfile_lib_target [gdb_download_shlib $binfile_lib]
+
+if { [build_executable "failed to prepare" $testfile $srcfile \
+	  [list debug \
+	       additional_flags=-DSHLIB_NAME=\"$binfile_lib_target\" \
+	       shlib_load]] } {
+    return -1
+}
+
+# Start two inferiors, both running the same test binary.  The arguments
+# INF_1_STOP and INF_2_STOP are source code patterns that are passed to
+# gdb_get_line_number to figure out where each inferior should be stopped.
+#
+# This proc does a clean_restart and leaves inferior 2 selected.  Also the
+# 'breakpoint pending' flag is enabled, so pending breakpoints can be created
+# without GDB prompting the user.
+proc do_test_setup { inf_1_stop inf_2_stop } {
+    clean_restart ${::binfile}
+
+    gdb_locate_shlib $::binfile_lib
+
+    if {![runto_main]} {
+	return false
+    }
+
+    gdb_breakpoint [gdb_get_line_number ${inf_1_stop}] temporary
+    gdb_continue_to_breakpoint "move inferior 1 into position"
+
+    gdb_test "add-inferior -exec ${::binfile}" \
+	"Added inferior 2.*" "add inferior 2"
+    gdb_test "inferior 2" "Switching to inferior 2 .*" "switch to inferior 2"
+
+    if {![runto_main]} {
+	return false
+    }
+
+    gdb_breakpoint [gdb_get_line_number ${inf_2_stop}] temporary
+    gdb_continue_to_breakpoint "move inferior 2 into position"
+
+    gdb_test_no_output "set breakpoint pending on"
+
+    return true
+}
+
+# Check that when a breakpoint is in the pending state, but that breakpoint
+# does have some locations (those locations themselves are pending), GDB
+# doesn't display the inferior list in the 'info breakpoints' output.
+proc_with_prefix test_no_inf_display {} {
+    do_test_setup "Break before open" "Break before open"
+
+    # Create a breakpoint on 'foo'.  As the shared library (that
+    # contains foo) has not been loaded into any inferior yet, then
+    # there will be no locations and the breakpoint will be created
+    # pending.  Pass the 'allow-pending' flag so the gdb_breakpoint
+    # correctly expects the new breakpoint to be pending.
+    gdb_breakpoint "foo" allow-pending
+    set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+		   "get foo breakpoint number"]
+
+    # Check the 'info breakpoints' output; the breakpoint is pending with
+    # no 'inf X' appearing at the end of the line.
+    gdb_test "info breakpoint $bpnum" \
+	"$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	"check info bp before locations have been created"
+
+    # Now select inferior 1 and allow the inferior to run forward to the
+    # point where a breakpoint location for foo will have been created.
+    gdb_test "inferior 1" "Switching to inferior 1 .*"
+    gdb_breakpoint [gdb_get_line_number "Break after open"] temporary
+    gdb_continue_to_breakpoint \
+	"move inferior 1 until a location has been added"
+
+    # Check the 'info breakpoints' output.  Notice we display the inferior
+    # list at the end of the breakpoint line.
+    gdb_test "info breakpoint $bpnum" \
+	"$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex\\s+<foo\[^>\]*>\\s+inf 1" \
+	"check info breakpoints while breakpoint is inserted"
+
+    # Continue inferior 1 until the shared library has been unloaded.  The
+    # breakpoint on 'foo' will return to the pending state.  We will need to
+    # 'continue' twice as the first time will hit the 'foo' breakpoint.
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "hit the breakpoint in foo"
+    gdb_continue_to_breakpoint "after close library"
+
+    # Check the 'info breakpoints' output, check there is no 'inf 1' at the
+    # end of the breakpoint line.
+    gdb_test "info breakpoint $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	     "\\s+breakpoint already hit 1 time"] \
+	"check info breakpoints while breakpoint is pending"
+}
+
+# Run all the tests.
+test_no_inf_display
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv8 07/14] gdb: remove breakpoint_re_set_one
  2023-12-29  9:26             ` [PATCHv8 00/14] " Andrew Burgess
                                 ` (5 preceding siblings ...)
  2023-12-29  9:27               ` [PATCHv8 06/14] gdb: don't display inferior list for pending breakpoints Andrew Burgess
@ 2023-12-29  9:27               ` Andrew Burgess
  2023-12-29  9:27               ` [PATCHv8 08/14] gdb: remove tracepoint_probe_create_sals_from_location_spec Andrew Burgess
                                 ` (7 subsequent siblings)
  14 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-12-29  9:27 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

During a later patch I wanted to reset a single breakpoint, so I
called breakpoint_re_set_one.  However, this is not the right thing to
do.  If we look at breakpoint_re_set then we see that there's a whole
bunch of state that needs to be preserved prior to calling
breakpoint_re_set_one, and after calling breakpoint_re_set_one we
still need to call update_global_location_list.

I could just update the comment on breakpoint_re_set_one to make it
clearer how the function should be used -- or more likely to warn that
the function should only be used as a helper from breakpoint_re_set.

However, breakpoint_re_set_one is only 3 lines long.  So I figure it
might actually be easier to just fold breakpoint_re_set_one into
breakpoint_re_set, then there's no risk of accidentally calling
breakpoint_re_set_one when we shouldn't.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c | 26 ++++++++------------------
 1 file changed, 8 insertions(+), 18 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index f0724b416d3..69c55c833f4 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -13218,17 +13218,6 @@ create_sals_from_location_spec_default (location_spec *locspec,
   parse_breakpoint_sals (locspec, canonical);
 }
 
-/* Reset a breakpoint.  */
-
-static void
-breakpoint_re_set_one (breakpoint *b)
-{
-  input_radix = b->input_radix;
-  set_language (b->language);
-
-  b->re_set ();
-}
-
 /* Re-set breakpoint locations for the current program space.
    Locations bound to other program spaces are left untouched.  */
 
@@ -13240,12 +13229,11 @@ breakpoint_re_set (void)
     scoped_restore save_input_radix = make_scoped_restore (&input_radix);
     scoped_restore_current_pspace_and_thread restore_pspace_thread;
 
-    /* breakpoint_re_set_one sets the current_language to the language
-       of the breakpoint it is resetting (see prepare_re_set_context)
-       before re-evaluating the breakpoint's location.  This change can
-       unfortunately get undone by accident if the language_mode is set
-       to auto, and we either switch frames, or more likely in this context,
-       we select the current frame.
+    /* To ::re_set each breakpoint we set the current_language to the
+       language of the breakpoint before re-evaluating the breakpoint's
+       location.  This change can unfortunately get undone by accident if
+       the language_mode is set to auto, and we either switch frames, or
+       more likely in this context, we select the current frame.
 
        We prevent this by temporarily turning the language_mode to
        language_mode_manual.  We restore it once all breakpoints
@@ -13262,7 +13250,9 @@ breakpoint_re_set (void)
       {
 	try
 	  {
-	    breakpoint_re_set_one (&b);
+	    input_radix = b.input_radix;
+	    set_language (b.language);
+	    b.re_set ();
 	  }
 	catch (const gdb_exception &ex)
 	  {
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv8 08/14] gdb: remove tracepoint_probe_create_sals_from_location_spec
  2023-12-29  9:26             ` [PATCHv8 00/14] " Andrew Burgess
                                 ` (6 preceding siblings ...)
  2023-12-29  9:27               ` [PATCHv8 07/14] gdb: remove breakpoint_re_set_one Andrew Burgess
@ 2023-12-29  9:27               ` Andrew Burgess
  2023-12-29  9:27               ` [PATCHv8 09/14] gdb: make breakpoint_debug_printf global Andrew Burgess
                                 ` (6 subsequent siblings)
  14 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-12-29  9:27 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

The tracepoint_probe_create_sals_from_location_spec function just
forwards all its arguments to
bkpt_probe_create_sals_from_location_spec, and is only used in one
place.

Lets delete tracepoint_probe_create_sals_from_location_spec and
replace it with bkpt_probe_create_sals_from_location_spec.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c | 19 +++----------------
 1 file changed, 3 insertions(+), 16 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 69c55c833f4..232186888ae 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -283,9 +283,6 @@ static bool strace_marker_p (struct breakpoint *b);
 static void bkpt_probe_create_sals_from_location_spec
      (location_spec *locspec,
       struct linespec_result *canonical);
-static void tracepoint_probe_create_sals_from_location_spec
-     (location_spec *locspec,
-      struct linespec_result *canonical);
 
 const struct breakpoint_ops code_breakpoint_ops =
 {
@@ -300,10 +297,11 @@ static const struct breakpoint_ops bkpt_probe_breakpoint_ops =
   create_breakpoints_sal,
 };
 
-/* Tracepoints set on probes.  */
+/* Tracepoints set on probes.  We use the same methods as for breakpoints
+   on probes.  */
 static const struct breakpoint_ops tracepoint_probe_breakpoint_ops =
 {
-  tracepoint_probe_create_sals_from_location_spec,
+  bkpt_probe_create_sals_from_location_spec,
   create_breakpoints_sal,
 };
 
@@ -12411,17 +12409,6 @@ tracepoint::print_recreate (struct ui_file *fp) const
     gdb_printf (fp, "  passcount %d\n", pass_count);
 }
 
-/* Virtual table for tracepoints on static probes.  */
-
-static void
-tracepoint_probe_create_sals_from_location_spec
-  (location_spec *locspec,
-   struct linespec_result *canonical)
-{
-  /* We use the same method for breakpoint on probes.  */
-  bkpt_probe_create_sals_from_location_spec (locspec, canonical);
-}
-
 void
 dprintf_breakpoint::re_set ()
 {
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv8 09/14] gdb: make breakpoint_debug_printf global
  2023-12-29  9:26             ` [PATCHv8 00/14] " Andrew Burgess
                                 ` (7 preceding siblings ...)
  2023-12-29  9:27               ` [PATCHv8 08/14] gdb: remove tracepoint_probe_create_sals_from_location_spec Andrew Burgess
@ 2023-12-29  9:27               ` Andrew Burgess
  2023-12-29  9:27               ` [PATCHv8 10/14] gdb: add another overload of startswith Andrew Burgess
                                 ` (5 subsequent siblings)
  14 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-12-29  9:27 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

This commit makes breakpoint_debug_printf available outside of
breakpoint.c.  In a later commit I'll want to use this macro from
another file.

This is just a refactor, there should be no user visible changes after
this commit.
---
 gdb/breakpoint.c | 9 ++-------
 gdb/breakpoint.h | 8 ++++++++
 2 files changed, 10 insertions(+), 7 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 232186888ae..1fdeae731a0 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -574,13 +574,8 @@ show_always_inserted_mode (struct ui_file *file, int from_tty,
 	      value);
 }
 
-/* True if breakpoint debug output is enabled.  */
-static bool debug_breakpoint = false;
-
-/* Print a "breakpoint" debug statement.  */
-#define breakpoint_debug_printf(fmt, ...) \
-  debug_prefixed_printf_cond (debug_breakpoint, "breakpoint", fmt, \
-			      ##__VA_ARGS__)
+/* See breakpoint.h.  */
+bool debug_breakpoint = false;
 
 /* "show debug breakpoint" implementation.  */
 static void
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index 95f98b59e41..119bab86e7e 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -48,6 +48,14 @@ struct linespec_result;
 struct linespec_sals;
 struct inferior;
 
+/* True if breakpoint debug output is enabled.  */
+extern bool debug_breakpoint;
+
+/* Print a "breakpoint" debug statement.  */
+#define breakpoint_debug_printf(fmt, ...) \
+  debug_prefixed_printf_cond (debug_breakpoint, "breakpoint", fmt, \
+			      ##__VA_ARGS__)
+
 /* Enum for exception-handling support in 'catch throw', 'catch rethrow',
    'catch catch' and the MI equivalent.  */
 
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv8 10/14] gdb: add another overload of startswith
  2023-12-29  9:26             ` [PATCHv8 00/14] " Andrew Burgess
                                 ` (8 preceding siblings ...)
  2023-12-29  9:27               ` [PATCHv8 09/14] gdb: make breakpoint_debug_printf global Andrew Burgess
@ 2023-12-29  9:27               ` Andrew Burgess
  2023-12-29  9:27               ` [PATCHv8 11/14] gdb: create new is_thread_id helper function Andrew Burgess
                                 ` (4 subsequent siblings)
  14 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-12-29  9:27 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

We already have one overload of the startswith function that takes a
std::string_view for both arguments.  A later patch in this series is
going to be improved by having an overload that takes one argument as
a std::string_view and the other argument as a plain 'char *'.

This commit adds the new overload, but doesn't make use of it (yet).
There should be no user visible changes after this commit.
---
 gdbsupport/common-utils.h | 10 ++++++++++
 1 file changed, 10 insertions(+)

diff --git a/gdbsupport/common-utils.h b/gdbsupport/common-utils.h
index 1efc5bbf459..17bd5389351 100644
--- a/gdbsupport/common-utils.h
+++ b/gdbsupport/common-utils.h
@@ -100,6 +100,16 @@ startswith (std::string_view string, std::string_view pattern)
 	  && strncmp (string.data (), pattern.data (), pattern.length ()) == 0);
 }
 
+/* Version of startswith that takes a string_view for only one of its
+   arguments.  Return true if STR starts with PREFIX, otherwise return
+   false.  */
+
+static inline bool
+startswith (const char *str, const std::string_view &prefix)
+{
+  return strncmp (str, prefix.data (), prefix.length ()) == 0;
+}
+
 /* Return true if the strings are equal.  */
 
 static inline bool
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv8 11/14] gdb: create new is_thread_id helper function
  2023-12-29  9:26             ` [PATCHv8 00/14] " Andrew Burgess
                                 ` (9 preceding siblings ...)
  2023-12-29  9:27               ` [PATCHv8 10/14] gdb: add another overload of startswith Andrew Burgess
@ 2023-12-29  9:27               ` Andrew Burgess
  2023-12-29  9:27               ` [PATCHv8 12/14] gdb: parse pending breakpoint thread/task immediately Andrew Burgess
                                 ` (3 subsequent siblings)
  14 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-12-29  9:27 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

This is a refactoring commit that splits the existing parse_thread_id
function into two parts, and then adds a new is_thread_id function.

The core of parse_thread_id is split into parse_thread_id_1, which is
responsible for actually parsing a thread-id.  Then parse_thread_id is
responsible for taking a parsed thread-id and validating that it
references an actually existing inferior thread.

The new is_thread_id function also uses parse_thread_id_1, but doesn't
actually check that the inferior thread exists, instead, this new
function simply checks that a string looks like a thread-id.

This commit does not add a use for is_thread_id, this will be added in
the next commit.

This is a refactoring commit, there should be no user visible changes
after this commit.
---
 gdb/tid-parse.c | 82 +++++++++++++++++++++++++++++++++++++------------
 gdb/tid-parse.h |  8 +++++
 2 files changed, 70 insertions(+), 20 deletions(-)

diff --git a/gdb/tid-parse.c b/gdb/tid-parse.c
index 46c3fccb135..a717a6fa20c 100644
--- a/gdb/tid-parse.c
+++ b/gdb/tid-parse.c
@@ -48,40 +48,43 @@ get_positive_number_trailer (const char **pp, int trailer, const char *string)
   return num;
 }
 
-/* See tid-parse.h.  */
+/* Parse TIDSTR as a per-inferior thread ID, in either INF_NUM.THR_NUM
+   or THR_NUM form, and return a pair, the first item of the pair is
+   INF_NUM and the second item is THR_NUM.
 
-struct thread_info *
-parse_thread_id (const char *tidstr, const char **end)
+   If TIDSTR does not include an INF_NUM component, then the first item in
+   the pair will be 0 (which is an invalid inferior number), this indicates
+   that TIDSTR references the current inferior.
+
+   This function does not validate the INF_NUM and THR_NUM are actually
+   valid numbers, that is, they might reference inferiors or threads that
+   don't actually exist; this function just splits the string into its
+   component parts.
+
+   If there is an error parsing TIDSTR then this function will raise an
+   exception.  */
+
+static std::pair<int, int>
+parse_thread_id_1 (const char *tidstr, const char **end)
 {
   const char *number = tidstr;
   const char *dot, *p1;
-  struct inferior *inf;
-  int thr_num;
-  int explicit_inf_id = 0;
+  int thr_num, inf_num;
 
   dot = strchr (number, '.');
 
   if (dot != NULL)
     {
       /* Parse number to the left of the dot.  */
-      int inf_num;
-
       p1 = number;
       inf_num = get_positive_number_trailer (&p1, '.', number);
       if (inf_num == 0)
 	invalid_thread_id_error (number);
-
-      inf = find_inferior_id (inf_num);
-      if (inf == NULL)
-	error (_("No inferior number '%d'"), inf_num);
-
-      explicit_inf_id = 1;
       p1 = dot + 1;
     }
   else
     {
-      inf = current_inferior ();
-
+      inf_num = 0;
       p1 = number;
     }
 
@@ -89,6 +92,32 @@ parse_thread_id (const char *tidstr, const char **end)
   if (thr_num == 0)
     invalid_thread_id_error (number);
 
+  if (end != nullptr)
+    *end = p1;
+
+  return { inf_num, thr_num };
+}
+
+/* See tid-parse.h.  */
+
+struct thread_info *
+parse_thread_id (const char *tidstr, const char **end)
+{
+  const auto [inf_num, thr_num] = parse_thread_id_1 (tidstr, end);
+
+  inferior *inf;
+  bool explicit_inf_id = false;
+
+  if (inf_num != 0)
+    {
+      inf = find_inferior_id (inf_num);
+      if (inf == nullptr)
+	error (_("No inferior number '%d'"), inf_num);
+      explicit_inf_id = true;
+    }
+  else
+    inf = current_inferior ();
+
   thread_info *tp = nullptr;
   for (thread_info *it : inf->threads ())
     if (it->per_inf_num == thr_num)
@@ -97,7 +126,7 @@ parse_thread_id (const char *tidstr, const char **end)
 	break;
       }
 
-  if (tp == NULL)
+  if (tp == nullptr)
     {
       if (show_inferior_qualified_tids () || explicit_inf_id)
 	error (_("Unknown thread %d.%d."), inf->num, thr_num);
@@ -105,14 +134,27 @@ parse_thread_id (const char *tidstr, const char **end)
 	error (_("Unknown thread %d."), thr_num);
     }
 
-  if (end != NULL)
-    *end = p1;
-
   return tp;
 }
 
 /* See tid-parse.h.  */
 
+bool
+is_thread_id (const char *tidstr, const char **end)
+{
+  try
+    {
+      (void) parse_thread_id_1 (tidstr, end);
+      return true;
+    }
+  catch (const gdb_exception_error &)
+    {
+      return false;
+    }
+}
+
+/* See tid-parse.h.  */
+
 tid_range_parser::tid_range_parser (const char *tidlist,
 				    int default_inferior)
 {
diff --git a/gdb/tid-parse.h b/gdb/tid-parse.h
index 86a49854b72..d2b06b72cbe 100644
--- a/gdb/tid-parse.h
+++ b/gdb/tid-parse.h
@@ -36,6 +36,14 @@ extern void ATTRIBUTE_NORETURN invalid_thread_id_error (const char *string);
    thrown.  */
 struct thread_info *parse_thread_id (const char *tidstr, const char **end);
 
+/* Return true if TIDSTR is pointing to a string that looks like a
+   thread-id.  This doesn't mean that TIDSTR identifies a valid thread, but
+   the string does at least look like a valid thread-id.  If END is not
+   NULL, parse_thread_id stores the address of the first character after
+   the thread-id into *END.  */
+
+bool is_thread_id (const char *tidstr, const char **end);
+
 /* Parse a thread ID or a thread range list.
 
    A range will be of the form
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv8 12/14] gdb: parse pending breakpoint thread/task immediately
  2023-12-29  9:26             ` [PATCHv8 00/14] " Andrew Burgess
                                 ` (10 preceding siblings ...)
  2023-12-29  9:27               ` [PATCHv8 11/14] gdb: create new is_thread_id helper function Andrew Burgess
@ 2023-12-29  9:27               ` Andrew Burgess
  2023-12-29  9:27               ` [PATCHv8 13/14] gdb: don't set breakpoint::pspace in create_breakpoint Andrew Burgess
                                 ` (2 subsequent siblings)
  14 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-12-29  9:27 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Eli Zaretskii

Eli has already approved the docs changes in this commit.

---

The initial motivation for this commit was to allow thread or inferior
specific breakpoints to only be inserted within the appropriate
inferior's program-space.  The benefit of this is that inferiors for
which the breakpoint does not apply will no longer need to stop, and
then resume, for such breakpoints.  This commit does not make this
change, but is a refactor to allow this to happen in a later commit.

The problem we currently have is that when a thread-specific (or
inferior-specific) breakpoint is created, the thread (or inferior)
number is only parsed by calling find_condition_and_thread_for_sals.
This function is only called for non-pending breakpoints, and requires
that we know the locations at which the breakpoint will be placed (for
expression checking in case the breakpoint is also conditional).

A consequence of this is that by the time we figure out the breakpoint
is thread-specific we have already looked up locations in all program
spaces.  This feels wasteful -- if we knew the thread-id earlier then
we could reduce the work GDB does by only looking up locations within
the program space for which the breakpoint applies.

Another consequence of how find_condition_and_thread_for_sals is
called is that pending breakpoints don't currently know they are
thread-specific, nor even that they are conditional!  Additionally, by
delaying parsing the thread-id, pending breakpoints can be created for
non-existent threads, this is different to how non-pending
breakpoints are handled, so I can do this:

  $ gdb -q ./gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp
  Reading symbols from ./gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp...
  (gdb) break foo thread 99
  Function "foo" not defined.
  Make breakpoint pending on future shared library load? (y or [n]) y
  Breakpoint 1 (foo thread 99) pending.
  (gdb) r
  Starting program: /tmp/gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp
  [Thread debugging using libthread_db enabled]
  Using host libthread_db library "/lib64/libthread_db.so.1".
  Error in re-setting breakpoint 1: Unknown thread 99.
  [Inferior 1 (process 3329749) exited normally]
  (gdb)

GDB only checked the validity of 'thread 99' at the point the 'foo'
location became non-pending.  In contrast, if I try this:

  $ gdb -q ./gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp
  Reading symbols from ./gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp...
  (gdb) break main thread 99
  Unknown thread 99.
  (gdb)

GDB immediately checks if 'thread 99' exists.  I think inconsistencies
like this are confusing, and should be fixed if possible.

In this commit the create_breakpoint function is updated so that the
extra_string, which contains the thread, inferior, task, and/or
condition information, is parsed immediately, even for pending
breakpoints.

Obviously, the condition still can't be validated until the breakpoint
becomes non-pending, but the thread, inferior, and task information
can be pulled from the extra-string, and can be validated early on,
even for pending breakpoints.  The -force-condition flag is also
parsed as part of this early parsing change.

There are a couple of benefits to doing this:

1. Printing of breakpoints is more consistent now.  Consider creating
   a conditional breakpoint before this commit:

    (gdb) set breakpoint pending on
    (gdb) break pendingfunc if (0)
    Function "pendingfunc" not defined.
    Breakpoint 1 (pendingfunc if (0)) pending.
    (gdb) break main if (0)
    Breakpoint 2 at 0x401198: file /tmp/hello.c, line 18.
    (gdb) info breakpoints
    Num     Type           Disp Enb Address            What
    1       breakpoint     keep y   <PENDING>          pendingfunc if (0)
    2       breakpoint     keep y   0x0000000000401198 in main at /tmp/hello.c:18
            stop only if (0)
    (gdb)

   And after this commit:

    (gdb) set breakpoint pending on
    (gdb) break pendingfunc if (0)
    Function "pendingfunc" not defined.
    Breakpoint 1 (pendingfunc) pending.
    (gdb) break main if (0)
    Breakpoint 2 at 0x401198: file /home/andrew/tmp/hello.c, line 18.
    (gdb) info breakpoints
    Num     Type           Disp Enb Address            What
    1       breakpoint     keep y   <PENDING>          pendingfunc
            stop only if (0)
    2       breakpoint     keep y   0x0000000000401198 in main at /home/andrew/tmp/hello.c:18
            stop only if (0)
    (gdb)

   Notice that the display of the condition is now the same for the
   pending and non-pending breakpoints.

   The same is true for the thread, inferior, or task information in
   thread, inferior, or task specific breakpoints; this information is
   displayed on its own line rather than being part of the 'What'
   field.

2. We can check that the thread exists as soon as the pending
   breakpoint is created.  Currently there is a weird difference
   between pending and non-pending breakpoints when creating a
   thread-specific breakpoint.

   A pending thread-specific breakpoint only checks its thread when it
   becomes non-pending, at which point the thread the breakpoint was
   intended for might have exited.  Here's the behaviour before this
   commit:

    (gdb) set breakpoint pending on
    (gdb) break foo thread 2
    Function "foo" not defined.
    Breakpoint 2 (foo thread 2) pending.
    (gdb) c
    Continuing.
    [Thread 0x7ffff7c56700 (LWP 2948835) exited]
    Error in re-setting breakpoint 2: Unknown thread 2.
    [Inferior 1 (process 2948832) exited normally]
    (gdb)

   Notice the 'Error in re-setting breakpoint 2: Unknown thread 2.'
   line, this was triggered when GDB tried to make the breakpoint
   non-pending, and GDB discovers that the thread no longer exists.

   Compare that to the behaviour after this commit:

    (gdb) set breakpoint pending on
    (gdb) break foo thread 2
    Function "foo" not defined.
    Breakpoint 2 (foo) pending.
    (gdb) c
    Continuing.
    [Thread 0x7ffff7c56700 (LWP 2949243) exited]
    Thread-specific breakpoint 2 deleted - thread 2 no longer in the thread list.
    [Inferior 1 (process 2949240) exited normally]
    (gdb)

   Now the behaviour for pending breakpoints is identical to
   non-pending breakpoints, the thread specific breakpoint is removed
   as soon as the thread the breakpoint is associated with exits.

   There is an additional change; when the pending breakpoint is
   created prior to this patch we see this line:

     Breakpoint 2 (foo thread 2) pending.

   While after this patch we get this line:

     Breakpoint 2 (foo) pending.

   Notice that 'thread 2' has disappeared.  This might look like a
   regression, but I don't think it is.  That we said 'thread 2'
   before was just a consequence of the lazy parsing of the breakpoint
   specification, while with this patch GDB understands, and has
   parsed away the 'thread 2' bit of the spec.  If folk think the old
   information was useful then this would be trivial to add back in
   code_breakpoint::say_where.

As a result of this commit the breakpoints 'extra_string' field is now
only used by bp_dprintf type breakpoints to hold the printf format and
arguments.  This string should always be empty for other breakpoint
types.  This allows some cleanup in print_breakpoint_location.

In code_breakpoint::code_breakpoint I've changed an error case into an
assert.  This is because the error is now handled earlier in
create_breakpoint.  As a result we know that by this point, the
extra_string will always be nullptr for anything other than a
bp_dprintf style breakpoint.

The find_condition_and_thread_for_sals function is now no longer
needed, this was previously doing the delayed splitting of the extra
string into thread, task, and condition, but this is now all done in
create_breakpoint, so find_condition_and_thread_for_sals can be
deleted, and the code that calls this in
code_breakpoint::location_spec_to_sals can be removed.  With this
update this code would only ever be reached for bp_dprintf style
breakpoints, and in these cases the extra_string should not contain
anything other than format and args.

The most interesting changes are all in create_breakpoint and in the
new file break-cond-parse.c.  We have a new block of code early on in
create_breakpoint that is responsible for splitting the extra_string
into its component parts by calling create_breakpoint_parse_arg_string
a function in the new break-cond-parse.c file.  This means that some
of the later code can be simplified a little.

The new break-cond-parse.c file implements the splitting up the
extra_string and finding all the parts, as well as some self-tests for
the new function.

Finally, now we know all the breakpoint details, these can be stored
within the breakpoint object if we end up creating a deferred
breakpoint.  Additionally, if we are creating a deferred bp_dprintf we
can parse the extra_string to build the printf command.

The implementation here aims to maintain backwards compatibility as
much as possible, this means that:

  1. We support abbreviations of 'thread', 'task', and 'inferior' in
  some places on the breakpoint line.  The handling of abbreviations
  has (before this patch) been a little weird, so this works:

  (gdb) break *main th 1

  And creates a breakpoint at '*main' for thread 1 only, while this
  does not work:

  (gdb) break main th 1

  In this case GDB will try to find the symbol 'main th 1'.  This
  weirdness exists before and after this patch.

  2. The handling of '-force-condition' is odd, if this flag appears
  immediately after a condition then it will be treated as part of the
  condition, e.g.:

  (gdb) break main if 0 -force-condition
  No symbol "force" in current context.

  But we are fine with these alternatives:

  (gdb) break main if 0 thread 1 -force-condition
  (gdb) break main -force-condition if 0

  Again, this is just a quirk of how the breakpoint line used to be
  parsed, but I've maintained this for backward compatibility.  During
  review it was suggested that -force-condition should become an
  actual breakpoint flag (i.e. only valid after the 'break' command
  but before the function name), and I don't think that would be a
  terrible idea, however, that's not currently a trivial change, and I
  think should be done as a separate piece of work.  For now, this
  patch just maintains the current behaviour.

The implementation works by first splitting the breakpoint condition
string (everything after the location specification) into a list of
tokens, each token has a type and a value. (e.g. we have a THREAD
token where the value is the thread-id string).  The list of tokens is
validated, and in some cases, tokens are merged.  Then the values are
extracted from the remaining token list.

Consider this breakpoint command:

  (gdb) break main thread 1 if argc == 2

The condition string passed to create_breakpoint_parse_arg_string is
going to be 'thread 1 if argc == 2', which is then split into the
tokens:

  { THREAD: "1" } { CONDITION: "argc == 2" }

The thread-id (1) and the condition string 'argc == 2' are extracted
from these tokens and returns back to create_breakpoint.

Now consider this breakpoint command:

  (gdb) break some_function if ( some_var == thread )

Here the user wants a breakpoint if 'some_var' is equal to the
variable 'thread'.  However, when this is initially parsed we will
find these tokens:

  { CONDITION: "( some_var == " } { THREAD: ")" }

This is a consequence of how we have to try and figure out the
contents of the 'if' condition without actually parsing the
expression; parsing the expression requires that we know the location
in order to lookup the variables by name, and this can't be done for
pending breakpoints (their location isn't known yet), and one of the
points of this work is that we extract things like thread-id for
pending breakpoints.

And so, it is in this case that token merging takes place.  We check
if the value of a token appearing immediately after the CONDITION
token looks valid.  In this case, does ')' look like a valid
thread-id.  Clearly, in this case ')' does not, and so me merge the
THREAD token into the condition token, giving:

  { CONDITION: "( some_var == thread )" }

Which is what we want.

I'm sure that we might still be able to come up with some edge cases
where the parser makes the wrong choice.  I think long term the best
way to work around these would be to move the thread, inferior, task,
and -force-condition flags to be "real" command options for the break
command.  I am looking into doing this, but can't guarantee if/when
that work would be completed, so this patch should be reviewed assume
that the work will never arrive (though I hope it will).

Reviewed-By: Eli Zaretskii <eliz@gnu.org>
---
 gdb/Makefile.in                               |   2 +
 gdb/NEWS                                      |   4 +
 gdb/break-cond-parse.c                        | 701 ++++++++++++++++++
 gdb/break-cond-parse.h                        |  52 ++
 gdb/breakpoint.c                              | 372 ++--------
 gdb/testsuite/gdb.ada/tasks.exp               |   6 +-
 gdb/testsuite/gdb.base/condbreak.exp          |  57 +-
 gdb/testsuite/gdb.base/pending.exp            |  23 +-
 gdb/testsuite/gdb.linespec/explicit.exp       |   4 +-
 gdb/testsuite/gdb.linespec/keywords.exp       |   8 +-
 gdb/testsuite/gdb.mi/mi-dprintf-pending.exp   |   3 +-
 .../gdb.multi/inferior-specific-bp.exp        |   4 +-
 .../gdb.threads/del-pending-thread-bp-lib.c   |  22 +
 .../gdb.threads/del-pending-thread-bp.c       |  85 +++
 .../gdb.threads/del-pending-thread-bp.exp     | 108 +++
 15 files changed, 1145 insertions(+), 306 deletions(-)
 create mode 100644 gdb/break-cond-parse.c
 create mode 100644 gdb/break-cond-parse.h
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.exp

diff --git a/gdb/Makefile.in b/gdb/Makefile.in
index 195f3a2e2d1..bc6156d247f 100644
--- a/gdb/Makefile.in
+++ b/gdb/Makefile.in
@@ -1028,6 +1028,7 @@ COMMON_SFILES = \
 	break-catch-sig.c \
 	break-catch-syscall.c \
 	break-catch-throw.c \
+	break-cond-parse.c \
 	breakpoint.c \
 	bt-utils.c \
 	btrace.c \
@@ -1296,6 +1297,7 @@ HFILES_NO_SRCDIR = \
 	bfd-target.h \
 	bfin-tdep.h \
 	block.h \
+	break-cond-parse.h \
 	breakpoint.h \
 	bsd-kvm.h \
 	bsd-uthread.h \
diff --git a/gdb/NEWS b/gdb/NEWS
index 4358494a6b6..6f27f7b20c2 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -9,6 +9,10 @@
 * GDB index now contains information about the main function.  This speeds up
   startup when it is being used for some large binaries.
 
+* For breakpoints that are created in the 'pending' state, any
+  'thread' or 'task' keywords are parsed at the time the breakpoint is
+  created, rather than at the time the breakpoint becomes non-pending.
+
 * Changed commands
 
 disassemble
diff --git a/gdb/break-cond-parse.c b/gdb/break-cond-parse.c
new file mode 100644
index 00000000000..eff738f2a7c
--- /dev/null
+++ b/gdb/break-cond-parse.c
@@ -0,0 +1,701 @@
+/* Copyright (C) 2023 Free Software Foundation, Inc.
+
+   This file is part of GDB.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#include "defs.h"
+#include "gdbsupport/gdb_assert.h"
+#include "gdbsupport/selftest.h"
+#include "test-target.h"
+#include "scoped-mock-context.h"
+#include "break-cond-parse.h"
+#include "tid-parse.h"
+#include "ada-lang.h"
+
+/* When parsing tokens from a string, which direction are we parsing?
+
+   Given the following string and pointer 'ptr':
+
+	ABC DEF GHI JKL
+	       ^
+	       ptr
+
+   Parsing 'forward' will return the token 'GHI' and update 'ptr' to point
+   between GHI and JKL.  Parsing 'backward' will return the token 'DEF' and
+   update 'ptr' to point between ABC and DEF.
+*/
+
+enum class parse_direction
+{
+  /* Parse the next token forwards.  */
+  forward,
+
+  /* Parse the previous token backwards.  */
+  backward
+};
+
+/* Find the next token in DIRECTION from *CURR.  */
+
+static std::string_view
+find_next_token (const char **curr, parse_direction direction)
+{
+  const char *tok_start, *tok_end;
+
+  gdb_assert (**curr != '\0');
+
+  if (direction == parse_direction::forward)
+    {
+      *curr = skip_spaces (*curr);
+      tok_start = *curr;
+      *curr = skip_to_space (*curr);
+      tok_end = *curr - 1;
+    }
+  else
+    {
+      gdb_assert (direction == parse_direction::backward);
+
+      while (isspace (**curr))
+	--(*curr);
+
+      tok_end = *curr;
+
+      while (!isspace (**curr))
+	--(*curr);
+
+      tok_start = (*curr) + 1;
+    }
+
+  return std::string_view (tok_start, tok_end - tok_start + 1);
+}
+
+/* A class that represents a complete parsed token.  Each token has a type
+   and a std::string_view into the original breakpoint condition string.  */
+
+struct token
+{
+  /* The types a token might take.  */
+  enum class type
+  {
+    /* These are the token types for the 'if', 'thread', 'inferior', and
+       'task' keywords.  The m_content for these token types is the value
+       passed to the keyword, not the keyword itself.  */
+    CONDITION,
+    THREAD,
+    INFERIOR,
+    TASK,
+
+    /* This is the token used when we find unknown content, the m_content
+       for this token is the rest of the input string.  */
+    REST,
+
+    /* This is the token for the -force-condition token, the m_content for
+       this token contains the keyword itself.  */
+    FORCE
+  };
+
+  token (enum type type, std::string_view content)
+    : m_type (type),
+      m_content (std::move (content))
+  {
+    /* Nothing.  */
+  }
+
+  /* Return a string representing this token.  Only used for debug.  */
+  std::string to_string () const
+  {
+    switch (m_type)
+      {
+      case type::CONDITION:
+	return string_printf ("{ CONDITION: \"%s\" }",
+			      std::string (m_content).c_str ());
+      case type::THREAD:
+	return string_printf ("{ THREAD: \"%s\" }",
+			      std::string (m_content).c_str ());
+      case type::INFERIOR:
+	return string_printf ("{ INFERIOR: \"%s\" }",
+			      std::string (m_content).c_str ());
+      case type::TASK:
+	return string_printf ("{ TASK: \"%s\" }",
+			      std::string (m_content).c_str ());
+      case type::REST:
+	return string_printf ("{ REST: \"%s\" }",
+			      std::string (m_content).c_str ());
+      case type::FORCE:
+	return string_printf ("{ FORCE }");
+      default:
+	return "** unknown **";
+      }
+  }
+
+  /* The type of this token.  */
+  const type &get_type () const
+  {
+    return m_type;
+  }
+
+  /* Return the value of this token.  */
+  const std::string_view &get_value () const
+  {
+    gdb_assert (m_content.size () > 0);
+    return m_content;
+  }
+
+  /* Extend this token with the contents of OTHER.  This only makes sense
+     if OTHER is the next token after this one in the original string,
+     however, enforcing that restriction is left to the caller of this
+     function.
+
+     When OTHER is a keyword/value token, e.g. 'thread 1', the m_content
+     for OTHER will only point to the '1'.  However, as the m_content is a
+     std::string_view, then when we merge the m_content of OTHER into this
+     token we automatically merge in the 'thread' part too, as it
+     naturally sits between this token and OTHER.  */
+
+  void
+  extend (const token &other)
+  {
+    m_content = std::string_view (this->m_content.data (),
+				  (other.m_content.data ()
+				   - this->m_content.data ()
+				   + other.m_content.size ()));
+  }
+
+private:
+  /* The type of this token.  */
+  type m_type;
+
+  /* The important content part of this token.  The extend member function
+     depends on this being a std::string_view.  */
+  std::string_view m_content;
+};
+
+/* Split STR, a breakpoint condition string, into a vector of tokens where
+   each token represents a component of the condition.  Tokens are first
+   parsed from the front of STR until we encounter an 'if' token.  At this
+   point tokens are parsed from the end of STR until we encounter an
+   unknown token, which we assume is the other end of the 'if' condition.
+   If when scanning forward we encounter an unknown token then the
+   remainder of STR is placed into a 'rest' token (the rest of the
+   string), and no backward scan is performed.  */
+
+static std::vector<token>
+parse_all_tokens (const char *str)
+{
+  gdb_assert (str != nullptr);
+
+  std::vector<token> forward_results;
+  std::vector<token> backward_results;
+
+  const char *cond_start = nullptr;
+  const char *cond_end = nullptr;
+  parse_direction direction = parse_direction::forward;
+  std::vector<token> *curr_results = &forward_results;
+  while (*str != '\0')
+    {
+      /* Find the next token.  If moving backward and this token starts at
+	 the same location as the condition then we must have found the
+	 other end of the condition string -- we're done.  */
+      std::string_view t = find_next_token (&str, direction);
+      if (direction == parse_direction::backward && t.data () <= cond_start)
+	{
+	  cond_end = &t.back ();
+	  break;
+	}
+
+      /* We only have a single flag option to check for.  All the other
+	 options take a value so require an additional token to be found.
+	 Additionally, we require that this flag be at least '-f', we
+	 don't allow it to be abbreviated to '-'.  */
+      if (t.length () > 1 && startswith ("-force-condition", t))
+	{
+	  curr_results->emplace_back (token::type::FORCE, t);
+	  continue;
+	}
+
+      /* Maybe the first token was the last token in the string.  If this
+	 is the case then we definitely can't try to extract a value
+	 token.  This also means that the token T is meaningless.  Reset
+	 TOK to point at the start of the unknown content and break out of
+	 the loop.  We'll record the unknown part of the string outside of
+	 the scanning loop (below).  */
+      if (direction == parse_direction::forward && *str == '\0')
+	{
+	  str = t.data ();
+	  break;
+	}
+
+      /* As before, find the next token and, if we are scanning backwards,
+	 check that we have not reached the start of the condition string.  */
+      std::string_view v = find_next_token (&str, direction);
+      if (direction == parse_direction::backward && v.data () <= cond_start)
+	{
+	  /* Use token T here as that must also be part of the condition
+	     string.  */
+	  cond_end = &t.back ();
+	  break;
+	}
+
+      /* When moving backward we will first parse the value token then the
+	 keyword token, so swap them now.  */
+      if (direction == parse_direction::backward)
+	std::swap (t, v);
+
+      /* Check for valid option in token T.  If we find a valid option then
+	 parse the value from the token V.  Except for 'if', that's handled
+	 differently.
+
+	 For the 'if' token we need to capture the entire condition
+	 string, so record the start of the condition string and then
+	 start scanning backwards looking for the end of the condition
+	 string.
+
+	 The order of these checks is important, at least the check for
+	 'thread' must occur before the check for 'task'.  We accept
+	 abbreviations of these token names, and 't' should resolve to
+	 'thread', which will only happen if we check 'thread' first.  */
+      if (direction == parse_direction::forward && startswith ("if", t))
+	{
+	  cond_start = v.data ();
+	  str = str + strlen (str);
+	  gdb_assert (*str == '\0');
+	  --str;
+	  direction = parse_direction::backward;
+	  curr_results = &backward_results;
+	  continue;
+	}
+      else if (startswith ("thread", t))
+	curr_results->emplace_back (token::type::THREAD, v);
+      else if (startswith ("inferior", t))
+	curr_results->emplace_back (token::type::INFERIOR, v);
+      else if (startswith ("task", t))
+	curr_results->emplace_back (token::type::TASK, v);
+      else
+	{
+	  /* An unknown token.  If we are scanning forward then reset TOK
+	     to point at the start of the unknown content, we record this
+	     outside of the scanning loop (below).
+
+	     If we are scanning backward then unknown content is assumed to
+	     be the other end of the condition string, obviously, this is
+	     just a heuristic, we could be looking at a mistyped command
+	     line, but this will be spotted when the condition is
+	     eventually evaluated.
+
+	     Either way, no more scanning is required after this.  */
+	  if (direction == parse_direction::forward)
+	    str = t.data ();
+	  else
+	    {
+	      gdb_assert (direction == parse_direction::backward);
+	      cond_end = &v.back ();
+	    }
+	  break;
+	}
+    }
+
+  if (cond_start != nullptr)
+    {
+      /* If we found the start of a condition string then we should have
+	 switched to backward scan mode, and found the end of the condition
+	 string.  Capture the whole condition string into COND_STRING
+	 now.  */
+      gdb_assert (direction == parse_direction::backward);
+      gdb_assert (cond_end != nullptr);
+
+      std::string_view v (cond_start, cond_end - cond_start + 1);
+
+      forward_results.emplace_back (token::type::CONDITION, v);
+    }
+  else if (*str != '\0')
+    {
+      /* If we didn't have a condition start pointer then we should still
+	 be in forward scanning mode.  If we didn't reach the end of the
+	 input string (TOK is not at the null character) then the rest of
+	 the input string is garbage that we didn't understand.
+
+	 Record the unknown content into REST.  The caller of this function
+	 will report this as an error later on.  We could report the error
+	 here, but we prefer to allow the caller to run other checks, and
+	 prioritise other errors before reporting this problem.  */
+      gdb_assert (direction == parse_direction::forward);
+      gdb_assert (cond_end == nullptr);
+
+      std::string_view v (str, strlen (str));
+
+      forward_results.emplace_back (token::type::REST, v);
+    }
+
+  /* If we have tokens in the BACKWARD_RESULTS vector then this means that
+     we found an 'if' condition (which will be the last thing in the
+     FORWARD_RESULTS vector), and then we started a backward scan.
+
+     The last tokens from the input string (those after the 'if' condition)
+     will be the first tokens added to the BACKWARD_RESULTS vector, so the
+     last items in the BACKWARD_RESULTS vector are those next to the 'if'
+     condition.
+
+     Check the tokens in the BACKWARD_RESULTS vector from back to front.
+     If the tokens look invalid then we assume that they are actually part
+     of the 'if' condition, and merge the token with the 'if' condition.
+     If it turns out that this was incorrect and that instead the user just
+     messed up entering the token value, then this will show as an error
+     when parsing the 'if' condition.
+
+     Doing this allows us to handle things like:
+
+       break function if ( variable == thread )
+
+     Where 'thread' is a local variable within 'function'.  When parsing
+     this we will initially see 'thread )' as a thread token with ')' as
+     the value.  However, the following code will spot that ')' is not a
+     valid thread-id, and so we merge 'thread )' into the 'if' condition
+     string.
+
+     This code also handles the special treatment for '-force-condition',
+     which exists for backwards compatibility reasons.  Traditionally this
+     flag, if it occurred immediately after the 'if' condition, would be
+     treated as part of the 'if' condition.  When the breakpoint condition
+     parsing code was rewritten, this behaviour was retained.  */
+  gdb_assert (backward_results.empty ()
+	      || (forward_results.back ().get_type ()
+		  == token::type::CONDITION));
+  while (!backward_results.empty ())
+    {
+      token &t = backward_results.back ();
+
+      if (t.get_type () == token::type::FORCE)
+	forward_results.back ().extend (std::move (t));
+      else if (t.get_type () == token::type::THREAD)
+	{
+	  const char *end;
+	  std::string v (t.get_value ());
+	  if (is_thread_id (v.c_str (), &end) && *end == '\0')
+	    break;
+	  forward_results.back ().extend (std::move (t));
+	}
+      else if (t.get_type () == token::type::INFERIOR
+	       || t.get_type () == token::type::TASK)
+	{
+	  /* Place the token's value into a null-terminated string, parse
+	     the string as a number and check that the entire string was
+	     parsed.  If this is true then this looks like a valid inferior
+	     or task number, otherwise, assume an invalid id, and merge
+	     this token with the 'if' token.  */
+	  char *end;
+	  std::string v (t.get_value ());
+	  (void) strtol (v.c_str (), &end, 0);
+	  if (end > v.c_str () && *end == '\0')
+	    break;
+	  forward_results.back ().extend (std::move (t));
+	}
+      else
+	gdb_assert_not_reached ("unexpected token type");
+
+      /* If we found an actual valid token above then we will have broken
+	 out of the loop.  We only get here if the token was merged with
+	 the 'if' condition, in which case we can discard the last token
+	 and then check the token before that.  */
+      backward_results.pop_back ();
+    }
+
+  /* If after the above checks we still have some tokens in the
+     BACKWARD_RESULTS vector, then these need to be appended to the
+     FORWARD_RESULTS vector.  However, we first reverse the order so that
+     FORWARD_RESULTS retains the tokens in the order they appeared in the
+     input string.  */
+  if (!backward_results.empty ())
+    forward_results.insert (forward_results.end (),
+			    backward_results.rbegin (),
+			    backward_results.rend ());
+
+  return forward_results;
+}
+
+/* Called when the global debug_breakpoint is true.  Prints VEC to the
+   debug output stream.  */
+
+static void
+dump_condition_tokens (const std::vector<token> &vec)
+{
+  gdb_assert (debug_breakpoint);
+
+  bool first = true;
+  std::string str = "Tokens: ";
+  for (const token &t : vec)
+    {
+      if (!first)
+	str += " ";
+      first = false;
+      str += t.to_string ();
+    }
+  breakpoint_debug_printf ("%s", str.c_str ());
+}
+
+/* See break-cond-parse.h.  */
+
+void
+create_breakpoint_parse_arg_string
+  (const char *str, gdb::unique_xmalloc_ptr<char> *cond_string_ptr,
+   int *thread_ptr, int *inferior_ptr, int *task_ptr,
+   gdb::unique_xmalloc_ptr<char> *rest_ptr, bool *force_ptr)
+{
+  /* Set up the defaults.  */
+  cond_string_ptr->reset ();
+  rest_ptr->reset ();
+  *thread_ptr = -1;
+  *inferior_ptr = -1;
+  *task_ptr = -1;
+  *force_ptr = false;
+
+  if (str == nullptr)
+    return;
+
+  /* Split STR into a series of tokens.  */
+  std::vector<token> tokens = parse_all_tokens (str);
+  if (debug_breakpoint)
+    dump_condition_tokens (tokens);
+
+  /* Temporary variables.  Initialised to the default state, then updated
+     as we parse TOKENS.  If all of TOKENS is parsed successfully then the
+     state from these variables is copied into the output arguments before
+     the function returns.  */
+  int thread = -1, inferior = -1, task = -1;
+  bool force = false;
+  gdb::unique_xmalloc_ptr<char> cond_string, rest;
+
+  for (const token &t : tokens)
+    {
+      switch (t.get_type ())
+	{
+	case token::type::FORCE:
+	  force = true;
+	  break;
+	case token::type::THREAD:
+	  {
+	    if (thread != -1)
+	      error ("You can specify only one thread.");
+	    if (task != -1 || inferior != -1)
+	      error ("You can specify only one of thread, inferior, or task.");
+	    const char *tmptok;
+	    thread_info *thr
+	      = parse_thread_id (std::string (t.get_value ()).c_str (),
+				 &tmptok);
+	    gdb_assert (*tmptok == '\0');
+	    thread = thr->global_num;
+	  }
+	  break;
+	case token::type::INFERIOR:
+	  {
+	    if (inferior != -1)
+	      error ("You can specify only one inferior.");
+	    if (task != -1 || thread != -1)
+	      error ("You can specify only one of thread, inferior, or task.");
+	    char *tmptok;
+	    long inferior_id
+	      = strtol (std::string (t.get_value ()).c_str (), &tmptok, 0);
+	    if (*tmptok != '\0')
+	      error (_("Junk '%s' after inferior keyword."), tmptok);
+	    if (inferior_id > INT_MAX)
+	      error (_("No inferior number '%ld'"), inferior_id);
+	    inferior = static_cast<int> (inferior_id);
+	    struct inferior *inf = find_inferior_id (inferior);
+	    if (inf == nullptr)
+	      error (_("No inferior number '%d'"), inferior);
+	  }
+	  break;
+	case token::type::TASK:
+	  {
+	    if (task != -1)
+	      error ("You can specify only one task.");
+	    if (inferior != -1 || thread != -1)
+	      error ("You can specify only one of thread, inferior, or task.");
+	    char *tmptok;
+	    long task_id
+	      = strtol (std::string (t.get_value ()).c_str (), &tmptok, 0);
+	    if (*tmptok != '\0')
+	      error (_("Junk '%s' after task keyword."), tmptok);
+	    if (task_id > INT_MAX)
+	      error (_("Unknown task %ld"), task_id);
+	    task = static_cast<int> (task_id);
+	    if (!valid_task_id (task))
+	      error (_("Unknown task %d."), task);
+	  }
+	  break;
+	case token::type::CONDITION:
+	  cond_string.reset (savestring (t.get_value ().data (),
+					 t.get_value ().size ()));
+	  break;
+	case token::type::REST:
+	  rest.reset (savestring (t.get_value ().data (),
+				  t.get_value ().size ()));
+	  break;
+	}
+    }
+
+  /* Move results into the output locations.  */
+  *force_ptr = force;
+  *thread_ptr = thread;
+  *inferior_ptr = inferior;
+  *task_ptr = task;
+  rest_ptr->reset (rest.release ());
+  cond_string_ptr->reset (cond_string.release ());
+}
+
+#if GDB_SELF_TEST
+
+namespace selftests {
+
+/* Run a single test of the create_breakpoint_parse_arg_string function.
+   INPUT is passed to create_breakpoint_parse_arg_string while all other
+   arguments are the expected output from
+   create_breakpoint_parse_arg_string.  */
+
+static void
+test (const char *input, const char *condition, int thread = -1,
+      int inferior = -1, int task = -1, bool force = false,
+      const char *rest = nullptr, const char *error_msg = nullptr)
+{
+  gdb::unique_xmalloc_ptr<char> extracted_condition;
+  gdb::unique_xmalloc_ptr<char> extracted_rest;
+  int extracted_thread, extracted_inferior, extracted_task;
+  bool extracted_force_condition;
+  std::string exception_msg, error_str;
+
+  if (error_msg != nullptr)
+    error_str = std::string (error_msg) + "\n";
+
+  try
+    {
+      create_breakpoint_parse_arg_string (input, &extracted_condition,
+					  &extracted_thread,
+					  &extracted_inferior,
+					  &extracted_task, &extracted_rest,
+					  &extracted_force_condition);
+    }
+  catch (const gdb_exception_error &ex)
+    {
+      string_file buf;
+
+      exception_print (&buf, ex);
+      exception_msg = buf.release ();
+    }
+
+  if ((condition == nullptr) != (extracted_condition.get () == nullptr)
+      || (condition != nullptr
+	  && strcmp (condition, extracted_condition.get ()) != 0)
+      || (rest == nullptr) != (extracted_rest.get () == nullptr)
+      || (rest != nullptr && strcmp (rest, extracted_rest.get ()) != 0)
+      || thread != extracted_thread
+      || inferior != extracted_inferior
+      || task != extracted_task
+      || force != extracted_force_condition
+      || exception_msg != error_str)
+    {
+      if (run_verbose ())
+	{
+	  debug_printf ("input: '%s'\n", input);
+	  debug_printf ("condition: '%s'\n", extracted_condition.get ());
+	  debug_printf ("rest: '%s'\n", extracted_rest.get ());
+	  debug_printf ("thread: %d\n", extracted_thread);
+	  debug_printf ("inferior: %d\n", extracted_inferior);
+	  debug_printf ("task: %d\n", extracted_task);
+	  debug_printf ("forced: %s\n",
+			extracted_force_condition ? "true" : "false");
+	  debug_printf ("exception: '%s'\n", exception_msg.c_str ());
+	}
+
+      /* Report the failure.  */
+      SELF_CHECK (false);
+    }
+}
+
+/* Wrapper for test function.  Pass through the default values for all
+   parameters, except the last parameter, which indicates that we expect
+   INPUT to trigger an error.  */
+
+static void
+test_error (const char *input, const char *error_msg)
+{
+  test (input, nullptr, -1, -1, -1, false, nullptr, error_msg);
+}
+
+/* Test the create_breakpoint_parse_arg_string function.  Just wraps
+   multiple calls to the test function above.  */
+
+static void
+create_breakpoint_parse_arg_string_tests ()
+{
+  gdbarch *arch = current_inferior ()->arch ();
+  scoped_restore_current_pspace_and_thread restore;
+  scoped_mock_context<test_target_ops> mock_target (arch);
+
+  int global_thread_num = mock_target.mock_thread.global_num;
+
+  /* Test parsing valid breakpoint condition strings.  */
+  test ("  if blah  ", "blah");
+  test (" if blah thread 1", "blah", global_thread_num);
+  test (" if blah inferior 1", "blah", -1, 1);
+  test (" if blah thread 1  ", "blah", global_thread_num);
+  test ("thread 1 woof", nullptr, global_thread_num, -1, -1, false, "woof");
+  test ("thread 1 X", nullptr, global_thread_num, -1, -1, false, "X");
+  test (" if blah thread 1 -force-condition", "blah", global_thread_num,
+	-1, -1, true);
+  test (" -force-condition if blah thread 1", "blah", global_thread_num,
+	-1, -1, true);
+  test (" -force-condition if blah thread 1  ", "blah", global_thread_num,
+	-1, -1, true);
+  test ("thread 1 -force-condition if blah", "blah", global_thread_num,
+	-1, -1, true);
+  test ("if (A::outer::func ())", "(A::outer::func ())");
+  test ("if ( foo == thread )", "( foo == thread )");
+  test ("if ( foo == thread ) inferior 1", "( foo == thread )", -1, 1);
+  test ("if ( foo == thread ) thread 1", "( foo == thread )",
+	global_thread_num);
+  test ("if foo == thread", "foo == thread");
+  test ("if foo == thread 1", "foo ==", global_thread_num);
+
+  /* Test parsing some invalid breakpoint condition strings.  */
+  test_error ("thread 1 if foo == 123 thread 1",
+	      "You can specify only one thread.");
+  test_error ("thread 1 if foo == 123 inferior 1",
+	      "You can specify only one of thread, inferior, or task.");
+  test_error ("thread 1 if foo == 123 task 1",
+	      "You can specify only one of thread, inferior, or task.");
+  test_error ("inferior 1 if foo == 123 inferior 1",
+	      "You can specify only one inferior.");
+  test_error ("inferior 1 if foo == 123 thread 1",
+	      "You can specify only one of thread, inferior, or task.");
+  test_error ("inferior 1 if foo == 123 task 1",
+	      "You can specify only one of thread, inferior, or task.");
+  test_error ("thread 1.2.3", "Invalid thread ID: 1.2.3");
+  test_error ("thread 1/2", "Invalid thread ID: 1/2");
+  test_error ("thread 1xxx", "Invalid thread ID: 1xxx");
+  test_error ("inferior 1xxx", "Junk 'xxx' after inferior keyword.");
+  test_error ("task 1xxx", "Junk 'xxx' after task keyword.");
+}
+
+} // namespace selftests
+#endif /* GDB_SELF_TEST */
+
+void _initialize_break_cond_parse ();
+void
+_initialize_break_cond_parse ()
+{
+#if GDB_SELF_TEST
+  selftests::register_test
+    ("create_breakpoint_parse_arg_string",
+     selftests::create_breakpoint_parse_arg_string_tests);
+#endif
+}
diff --git a/gdb/break-cond-parse.h b/gdb/break-cond-parse.h
new file mode 100644
index 00000000000..cbee70f4e9e
--- /dev/null
+++ b/gdb/break-cond-parse.h
@@ -0,0 +1,52 @@
+/* Copyright (C) 2023 Free Software Foundation, Inc.
+
+   This file is part of GDB.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#if !defined (BREAK_COND_PARSE_H)
+#define BREAK_COND_PARSE_H 1
+
+/* Given TOK, a string possibly containing a condition, thread, inferior,
+   task and force-condition flag, as accepted by the 'break' command,
+   extract the condition string, thread, inferior, task number, and the
+   force_condition flag, then set *COND_STRING, *THREAD, *INFERIOR, *TASK,
+   and *FORCE.
+
+   As TOK is parsed, if an unknown keyword is encountered before the 'if'
+   keyword then everything starting from the unknown keyword is placed into
+   *REST.
+
+   Both *COND and *REST are initialized to nullptr.  If no 'if' keyword is
+   found then *COND will be returned as nullptr.  If no unknown content is
+   found then *REST is returned as nullptr.
+
+   If no thread is found, *THREAD is set to -1.  If no inferior is found,
+   *INFERIOR is set to -1.  If no task is found, *TASK is set to -1.  If
+   the -force-condition flag is not found then *FORCE is set to false.
+
+   Due to the free-form nature that the string TOK might take (a 'thread'
+   keyword can appear before or after an 'if' condition) then we end up
+   having to check for keywords from both the start of TOK and the end of
+   TOK.
+
+   If TOK is nullptr, or TOK is the empty string, then the output variables
+   are all given their default values.  */
+
+extern void create_breakpoint_parse_arg_string
+  (const char *tok, gdb::unique_xmalloc_ptr<char> *cond_string,
+   int *thread, int *inferior, int *task,
+   gdb::unique_xmalloc_ptr<char> *rest, bool *force);
+
+#endif
diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 1fdeae731a0..4fe125996f0 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -70,6 +70,7 @@
 #include "cli/cli-style.h"
 #include "cli/cli-decode.h"
 #include <unordered_set>
+#include "break-cond-parse.h"
 
 /* readline include files */
 #include "readline/tilde.h"
@@ -6328,20 +6329,7 @@ print_breakpoint_location (const breakpoint *b, const bp_location *loc)
       uiout->field_stream ("at", stb);
     }
   else
-    {
-      uiout->field_string ("pending", b->locspec->to_string ());
-      /* If extra_string is available, it could be holding a condition
-	 or dprintf arguments.  In either case, make sure it is printed,
-	 too, but only for non-MI streams.  */
-      if (!uiout->is_mi_like_p () && b->extra_string != NULL)
-	{
-	  if (b->type == bp_dprintf)
-	    uiout->text (",");
-	  else
-	    uiout->text (" ");
-	  uiout->text (b->extra_string.get ());
-	}
-    }
+    uiout->field_string ("pending", b->locspec->to_string ());
 
   if (loc && is_breakpoint (b)
       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
@@ -8706,8 +8694,8 @@ code_breakpoint::code_breakpoint (struct gdbarch *gdbarch_,
      command line, otherwise it's an error.  */
   if (type == bp_dprintf)
     update_dprintf_command_list (this);
-  else if (extra_string != nullptr)
-    error (_("Garbage '%s' at end of command"), extra_string.get ());
+  else
+    gdb_assert (extra_string == nullptr);
 
   /* The order of the locations is now stable.  Set the location
      condition using the location's number.  */
@@ -8936,197 +8924,6 @@ check_fast_tracepoint_sals (struct gdbarch *gdbarch,
     }
 }
 
-/* Given TOK, a string specification of condition and thread, as accepted
-   by the 'break' command, extract the condition string into *COND_STRING.
-   If no condition string is found then *COND_STRING is set to nullptr.
-
-   If the breakpoint specification has an associated thread, task, or
-   inferior, these are extracted into *THREAD, *TASK, and *INFERIOR
-   respectively, otherwise these arguments are set to -1 (for THREAD and
-   INFERIOR) or 0 (for TASK).
-
-   PC identifies the context at which the condition should be parsed.  */
-
-static void
-find_condition_and_thread (const char *tok, CORE_ADDR pc,
-			   gdb::unique_xmalloc_ptr<char> *cond_string,
-			   int *thread, int *inferior, int *task,
-			   gdb::unique_xmalloc_ptr<char> *rest)
-{
-  cond_string->reset ();
-  *thread = -1;
-  *inferior = -1;
-  *task = -1;
-  rest->reset ();
-  bool force = false;
-
-  while (tok && *tok)
-    {
-      const char *end_tok;
-      int toklen;
-      const char *cond_start = NULL;
-      const char *cond_end = NULL;
-
-      tok = skip_spaces (tok);
-
-      if ((*tok == '"' || *tok == ',') && rest)
-	{
-	  rest->reset (savestring (tok, strlen (tok)));
-	  break;
-	}
-
-      end_tok = skip_to_space (tok);
-
-      toklen = end_tok - tok;
-
-      if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
-	{
-	  tok = cond_start = end_tok + 1;
-	  try
-	    {
-	      parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
-	    }
-	  catch (const gdb_exception_error &)
-	    {
-	      if (!force)
-		throw;
-	      else
-		tok = tok + strlen (tok);
-	    }
-	  cond_end = tok;
-	  cond_string->reset (savestring (cond_start, cond_end - cond_start));
-	}
-      else if (toklen >= 1 && strncmp (tok, "-force-condition", toklen) == 0)
-	{
-	  tok = tok + toklen;
-	  force = true;
-	}
-      else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
-	{
-	  const char *tmptok;
-	  struct thread_info *thr;
-
-	  if (*thread != -1)
-	    error(_("You can specify only one thread."));
-
-	  if (*task != -1)
-	    error (_("You can specify only one of thread or task."));
-
-	  if (*inferior != -1)
-	    error (_("You can specify only one of inferior or thread."));
-
-	  tok = end_tok + 1;
-	  thr = parse_thread_id (tok, &tmptok);
-	  if (tok == tmptok)
-	    error (_("Junk after thread keyword."));
-	  *thread = thr->global_num;
-	  tok = tmptok;
-	}
-      else if (toklen >= 1 && strncmp (tok, "inferior", toklen) == 0)
-	{
-	  if (*inferior != -1)
-	    error(_("You can specify only one inferior."));
-
-	  if (*task != -1)
-	    error (_("You can specify only one of inferior or task."));
-
-	  if (*thread != -1)
-	    error (_("You can specify only one of inferior or thread."));
-
-	  char *tmptok;
-	  tok = end_tok + 1;
-	  *inferior = strtol (tok, &tmptok, 0);
-	  if (tok == tmptok)
-	    error (_("Junk after inferior keyword."));
-	  if (!valid_global_inferior_id (*inferior))
-	    error (_("Unknown inferior number %d."), *inferior);
-	  tok = tmptok;
-	}
-      else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
-	{
-	  char *tmptok;
-
-	  if (*task != -1)
-	    error(_("You can specify only one task."));
-
-	  if (*thread != -1)
-	    error (_("You can specify only one of thread or task."));
-
-	  if (*inferior != -1)
-	    error (_("You can specify only one of inferior or task."));
-
-	  tok = end_tok + 1;
-	  *task = strtol (tok, &tmptok, 0);
-	  if (tok == tmptok)
-	    error (_("Junk after task keyword."));
-	  if (!valid_task_id (*task))
-	    error (_("Unknown task %d."), *task);
-	  tok = tmptok;
-	}
-      else if (rest)
-	{
-	  rest->reset (savestring (tok, strlen (tok)));
-	  break;
-	}
-      else
-	error (_("Junk at end of arguments."));
-    }
-}
-
-/* Call 'find_condition_and_thread' for each sal in SALS until a parse
-   succeeds.  The parsed values are written to COND_STRING, THREAD,
-   TASK, and REST.  See the comment of 'find_condition_and_thread'
-   for the description of these parameters and INPUT.  */
-
-static void
-find_condition_and_thread_for_sals (const std::vector<symtab_and_line> &sals,
-				    const char *input,
-				    gdb::unique_xmalloc_ptr<char> *cond_string,
-				    int *thread, int *inferior, int *task,
-				    gdb::unique_xmalloc_ptr<char> *rest)
-{
-  int num_failures = 0;
-  for (auto &sal : sals)
-    {
-      gdb::unique_xmalloc_ptr<char> cond;
-      int thread_id = -1;
-      int inferior_id = -1;
-      int task_id = -1;
-      gdb::unique_xmalloc_ptr<char> remaining;
-
-      /* Here we want to parse 'arg' to separate condition from thread
-	 number.  But because parsing happens in a context and the
-	 contexts of sals might be different, try each until there is
-	 success.  Finding one successful parse is sufficient for our
-	 goal.  When setting the breakpoint we'll re-parse the
-	 condition in the context of each sal.  */
-      try
-	{
-	  find_condition_and_thread (input, sal.pc, &cond, &thread_id,
-				     &inferior_id, &task_id, &remaining);
-	  *cond_string = std::move (cond);
-	  /* A value of -1 indicates that these fields are unset.  At most
-	     one of these fields should be set (to a value other than -1)
-	     at this point.  */
-	  gdb_assert (((thread_id == -1 ? 1 : 0)
-		       + (task_id == -1 ? 1 : 0)
-		       + (inferior_id == -1 ? 1 : 0)) >= 2);
-	  *thread = thread_id;
-	  *inferior = inferior_id;
-	  *task = task_id;
-	  *rest = std::move (remaining);
-	  break;
-	}
-      catch (const gdb_exception_error &e)
-	{
-	  num_failures++;
-	  /* If no sal remains, do not continue.  */
-	  if (num_failures == sals.size ())
-	    throw;
-	}
-    }
-}
-
 /* Decode a static tracepoint marker spec.  */
 
 static std::vector<symtab_and_line>
@@ -9243,6 +9040,46 @@ create_breakpoint (struct gdbarch *gdbarch,
 	      ? (extra_string != nullptr && !parse_extra)
 	      : (extra_string == nullptr || parse_extra));
 
+  /* Will hold either copies of the similarly named function argument, or
+     will hold a modified version of the function argument, depending on
+     the value of PARSE_EXTRA.  */
+  gdb::unique_xmalloc_ptr<char> cond_string_copy;
+  gdb::unique_xmalloc_ptr<char> extra_string_copy;
+
+  if (parse_extra)
+    {
+      /* Parse EXTRA_STRING splitting the parts out.  */
+      create_breakpoint_parse_arg_string (extra_string, &cond_string_copy,
+					  &thread, &inferior, &task,
+					  &extra_string_copy,
+					  &force_condition);
+
+      /* We could check that EXTRA_STRING_COPY is empty at this point -- it
+	 should be, as we only get here for things that are not bp_dprintf,
+	 however, we prefer to give the location spec parser a chance to
+	 run first, this means the user will get errors about invalid
+	 location spec instead of an error about garbage at the end of the
+	 command line.
+
+	 We still do the EXTRA_STRING_COPY is empty check, just later in
+	 this function.  */
+
+      gdb_assert (thread == -1 || thread > 0);
+      gdb_assert (task == -1 || task > 0);
+      gdb_assert (inferior == -1 || inferior > 0);
+    }
+  else
+    {
+      if (cond_string != nullptr)
+	cond_string_copy.reset (xstrdup (cond_string));
+      if (extra_string != nullptr)
+	extra_string_copy.reset (xstrdup (extra_string));
+    }
+
+  /* Clear these.  Updated values are now held in the *_copy locals.  */
+  cond_string = nullptr;
+  extra_string = nullptr;
+
   try
     {
       ops->create_sals_from_location_spec (locspec, &canonical);
@@ -9278,6 +9115,13 @@ create_breakpoint (struct gdbarch *gdbarch,
 	throw;
     }
 
+  /* Only bp_dprintf breakpoints should have anything in EXTRA_STRING_COPY
+     by this point.  For all other breakpoints this indicates an error.  We
+     could place this check earlier in the function, but we prefer to see
+     errors from the location spec parser before we see this error message.  */
+  if (type_wanted != bp_dprintf && extra_string_copy.get () != nullptr)
+    error (_("Garbage '%s' at end of command"), extra_string_copy.get ());
+
   if (!pending && canonical.lsals.empty ())
     return 0;
 
@@ -9301,63 +9145,31 @@ create_breakpoint (struct gdbarch *gdbarch,
      breakpoint.  */
   if (!pending)
     {
-      gdb::unique_xmalloc_ptr<char> cond_string_copy;
-      gdb::unique_xmalloc_ptr<char> extra_string_copy;
-
-      if (parse_extra)
+      /* Check the validity of the condition.  We should error out if the
+	 condition is invalid at all of the locations and if it is not
+	 forced.  In the PARSE_EXTRA case above, this check is done when
+	 parsing the EXTRA_STRING.  */
+      if (cond_string_copy.get () != nullptr && !force_condition)
 	{
-	  gdb_assert (type_wanted != bp_dprintf);
-
-	  gdb::unique_xmalloc_ptr<char> rest;
-	  gdb::unique_xmalloc_ptr<char> cond;
-
+	  int num_failures = 0;
 	  const linespec_sals &lsal = canonical.lsals[0];
-
-	  find_condition_and_thread_for_sals (lsal.sals, extra_string,
-					      &cond, &thread, &inferior,
-					      &task, &rest);
-
-	  if (rest.get () != nullptr && *(rest.get ()) != '\0')
-	    error (_("Garbage '%s' at end of command"), rest.get ());
-
-	  cond_string_copy = std::move (cond);
-	  extra_string_copy = std::move (rest);
-	}
-      else
-	{
-	  /* Check the validity of the condition.  We should error out
-	     if the condition is invalid at all of the locations and
-	     if it is not forced.  In the PARSE_EXTRA case above, this
-	     check is done when parsing the EXTRA_STRING.  */
-	  if (cond_string != nullptr && !force_condition)
+	  for (const auto &sal : lsal.sals)
 	    {
-	      int num_failures = 0;
-	      const linespec_sals &lsal = canonical.lsals[0];
-	      for (const auto &sal : lsal.sals)
+	      const char *cond = cond_string_copy.get ();
+	      try
 		{
-		  const char *cond = cond_string;
-		  try
-		    {
-		      parse_exp_1 (&cond, sal.pc, block_for_pc (sal.pc), 0);
-		      /* One success is sufficient to keep going.  */
-		      break;
-		    }
-		  catch (const gdb_exception_error &)
-		    {
-		      num_failures++;
-		      /* If this is the last sal, error out.  */
-		      if (num_failures == lsal.sals.size ())
-			throw;
-		    }
+		  parse_exp_1 (&cond, sal.pc, block_for_pc (sal.pc), 0);
+		  /* One success is sufficient to keep going.  */
+		  break;
+		}
+	      catch (const gdb_exception_error &)
+		{
+		  num_failures++;
+		  /* If this is the last sal, error out.  */
+		  if (num_failures == lsal.sals.size ())
+		    throw;
 		}
 	    }
-
-	  /* Create a private copy of condition string.  */
-	  if (cond_string)
-	    cond_string_copy.reset (xstrdup (cond_string));
-	  /* Create a private copy of any extra string.  */
-	  if (extra_string)
-	    extra_string_copy.reset (xstrdup (extra_string));
 	}
 
       ops->create_breakpoints_sal (gdbarch, &canonical,
@@ -9374,21 +9186,16 @@ create_breakpoint (struct gdbarch *gdbarch,
 								 type_wanted);
       b->locspec = locspec->clone ();
 
-      if (parse_extra)
-	b->cond_string = NULL;
-      else
-	{
-	  /* Create a private copy of condition string.  */
-	  b->cond_string.reset (cond_string != NULL
-				? xstrdup (cond_string)
-				: NULL);
-	  b->thread = thread;
-	}
+      /* Create a private copy of the condition string.  */
+      b->cond_string = std::move (cond_string_copy);
+
+      b->thread = thread;
+      b->task = task;
+      b->inferior = inferior;
 
       /* Create a private copy of any extra string.  */
-      b->extra_string.reset (extra_string != NULL
-			     ? xstrdup (extra_string)
-			     : NULL);
+      b->extra_string = std::move (extra_string_copy);
+
       b->ignore_count = ignore_count;
       b->disposition = tempflag ? disp_del : disp_donttouch;
       b->condition_not_parsed = 1;
@@ -9397,9 +9204,12 @@ create_breakpoint (struct gdbarch *gdbarch,
 	   && type_wanted != bp_hardware_breakpoint) || thread != -1)
 	b->pspace = current_program_space;
 
+      if (b->type == bp_dprintf)
+	update_dprintf_command_list (b.get ());
+
       install_breakpoint (internal, std::move (b), 0);
     }
-  
+
   if (canonical.lsals.size () > 1)
     {
       warning (_("Multiple breakpoints were set.\nUse the "
@@ -13128,24 +12938,6 @@ code_breakpoint::location_spec_to_sals (location_spec *locspec,
     {
       for (auto &sal : sals)
 	resolve_sal_pc (&sal);
-      if (condition_not_parsed && extra_string != NULL)
-	{
-	  gdb::unique_xmalloc_ptr<char> local_cond, local_extra;
-	  int local_thread, local_task, local_inferior;
-
-	  find_condition_and_thread_for_sals (sals, extra_string.get (),
-					      &local_cond, &local_thread,
-					      &local_inferior,
-					      &local_task, &local_extra);
-	  gdb_assert (cond_string == nullptr);
-	  if (local_cond != nullptr)
-	    cond_string = std::move (local_cond);
-	  thread = local_thread;
-	  task = local_task;
-	  if (local_extra != nullptr)
-	    extra_string = std::move (local_extra);
-	  condition_not_parsed = 0;
-	}
 
       if (type == bp_static_tracepoint)
 	{
diff --git a/gdb/testsuite/gdb.ada/tasks.exp b/gdb/testsuite/gdb.ada/tasks.exp
index 603d43f7c36..337ee1b6f07 100644
--- a/gdb/testsuite/gdb.ada/tasks.exp
+++ b/gdb/testsuite/gdb.ada/tasks.exp
@@ -55,11 +55,11 @@ gdb_test "watch j task 1 task 3" "You can specify only one task\\."
 
 # Check that attempting to combine 'task' and 'thread' gives an error.
 gdb_test "break break_me task 1 thread 1" \
-    "You can specify only one of thread or task\\."
+    "You can specify only one of thread, inferior, or task\\."
 gdb_test "break break_me thread 1 task 1" \
-    "You can specify only one of thread or task\\."
+    "You can specify only one of thread, inferior, or task\\."
 gdb_test "break break_me inferior 1 task 1" \
-    "You can specify only one of inferior or task\\."
+    "You can specify only one of thread, inferior, or task\\."
 gdb_test "watch j task 1 thread 1" \
     "You can specify only one of thread or task\\."
 gdb_test "watch j thread 1 task 1" \
diff --git a/gdb/testsuite/gdb.base/condbreak.exp b/gdb/testsuite/gdb.base/condbreak.exp
index a5b2a28701b..5a6a42e073b 100644
--- a/gdb/testsuite/gdb.base/condbreak.exp
+++ b/gdb/testsuite/gdb.base/condbreak.exp
@@ -179,6 +179,10 @@ gdb_test "break -q main if (1==1) thread 999" \
     "Unknown thread 999\\."
 gdb_test "break -q main thread 999 if (1==1)" \
     "Unknown thread 999\\."
+gdb_test "break -q main if (1==1) thread 999 -force-condition" \
+    "Unknown thread 999\\."
+gdb_test "break -q main thread 999 if (1==1) -force-condition" \
+    "Unknown thread 999\\."
 
 # Verify that both if and thread can be distinguished from a breakpoint
 # address expression.
@@ -186,20 +190,71 @@ gdb_test "break *main if (1==1) thread 999" \
     "Unknown thread 999\\."
 gdb_test "break *main thread 999 if (1==1)" \
     "Unknown thread 999\\."
+gdb_test "break *main if (1==1) thread 999 -force-condition" \
+    "Unknown thread 999\\."
+gdb_test "break *main thread 999 if (1==1) -force-condition" \
+    "Unknown thread 999\\."
 
 # Similarly for task.
 gdb_test "break *main if (1==1) task 999" \
     "Unknown task 999\\."
 gdb_test "break *main task 999 if (1==1)" \
     "Unknown task 999\\."
+gdb_test "break *main if (1==1) task 999 -force-condition" \
+    "Unknown task 999\\."
+gdb_test "break *main task 999 if (1==1) -force-condition" \
+    "Unknown task 999\\."
 
-# GDB accepts abbreviations for "thread" and "task".
+# GDB accepts abbreviations for "thread", "task" and
+# "-force-condition", when these keywords appear after
+# the breakpoint condition.
 gdb_test "break *main if (1==1) t 999" \
     "Unknown thread 999\\."
 gdb_test "break *main if (1==1) th 999" \
     "Unknown thread 999\\."
 gdb_test "break *main if (1==1) ta 999" \
     "Unknown task 999\\."
+gdb_test "break *main if (1==1) t 999 -force" \
+    "Unknown thread 999\\."
+gdb_test "break *main if (1==1) th 999 -force" \
+    "Unknown thread 999\\."
+gdb_test "break *main if (1==1) ta 999 -force" \
+    "Unknown task 999\\."
+
+# Check the use of abbreviations before the condition.  This works
+# because, when the location spec starts with '*' GDB is able to
+# figure out that the complete location is '*main'.
+gdb_test "break *main t 999 if (1==1)" \
+    "Unknown thread 999\\."
+gdb_test "break *main th 999 if (1==1)" \
+    "Unknown thread 999\\."
+gdb_test "break *main ta 999 if (1==1)" \
+    "Unknown task 999\\."
+gdb_test "break *main t 999 -force if (1==1)" \
+    "Unknown thread 999\\."
+gdb_test "break *main th 999 -force if (1==1)" \
+    "Unknown thread 999\\."
+gdb_test "break *main ta 999 -force if (1==1)" \
+    "Unknown task 999\\."
+
+# However, when the location spec doesn't start with '*' GDB relies on
+# the linespec parser to spot the keyword which marks the end of the
+# linespec, and this parser doesn't check for abbreviations.
+gdb_test "with breakpoint pending off -- break main t 999 if (1==1)" \
+    "Function \"main t 999\" not defined\\."
+gdb_test "with breakpoint pending off -- break main th 999 if (1==1)" \
+    "Function \"main th 999\" not defined\\."
+gdb_test "with breakpoint pending off -- break main ta 999 if (1==1)" \
+    "Function \"main ta 999\" not defined\\."
+
+# GDB does not treat a "-force-condition" flag that appears
+# immediately after the condition as the flag, but instead treats it
+# as " - force - condition", that is, subtraction of the symbol
+# "force" followed by subtraction of symbol "context".  This is really
+# just a quirk of how this used to be implemented, and should maybe be
+# changed in the future.  However, for now GDB retains this behaviour.
+gdb_test "break *main if (1==1) -force-condition" \
+    "No symbol \"force\" in current context\\."
 
 set test "run until breakpoint at marker3"
 gdb_test_multiple "continue" $test {
diff --git a/gdb/testsuite/gdb.base/pending.exp b/gdb/testsuite/gdb.base/pending.exp
index d7d3735000a..645f63bdb16 100644
--- a/gdb/testsuite/gdb.base/pending.exp
+++ b/gdb/testsuite/gdb.base/pending.exp
@@ -170,7 +170,8 @@ gdb_test "info break" \
 \[\t \]+stop only if k == 1.*
 \[\t \]+print k.*
 \[0-9\]+\[\t \]+breakpoint     keep y.* in main at .*$srcfile:$mainline.*
-\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc if x > 3.*" \
+\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc.*
+\\s+stop only if x > 3.*" \
 "multiple pending breakpoints"
 
 
@@ -195,8 +196,10 @@ gdb_test "info break" \
 \[\t \]+stop only if k == 1.*
 \[\t \]+print k.*
 \[0-9\]+\[\t \]+breakpoint     keep y.* in main at .*$srcfile:$mainline.*
-\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc if x > 3.*
-\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp3_loc.*ignore next 2 hits.*" \
+\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc.*
+\\s+stop only if x > 3.*
+\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp3_loc.*
+\\s+ignore next 2 hits.*" \
 "multiple pending breakpoints 2"
 
 #
@@ -267,3 +270,17 @@ gdb_test "info break" \
 \[0-9\]+\[\t \]+breakpoint     keep y.* in main at .*$srcfile:$mainline.*
 \[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*imaginary.*" \
 "verify pending breakpoint after restart"
+
+# Test GDB's parsing of pending breakpoint thread and condition.
+
+gdb_test_no_output "set breakpoint pending on"
+gdb_test "break foo if (unknown_var && another_unknown_var) thread 1" \
+    "Breakpoint $decimal \\(foo\\) pending\\."
+set bpnum [get_integer_valueof "\$bpnum" "*INVALID" \
+	       "get number for foo breakpoint"]
+gdb_test "info breakpoints $bpnum" \
+    [multi_line \
+	 "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	 "\\s+stop only if \\(unknown_var && another_unknown_var\\)" \
+	 "\\s+stop only in thread 1"] \
+    "check pending breakpoint on foo"
diff --git a/gdb/testsuite/gdb.linespec/explicit.exp b/gdb/testsuite/gdb.linespec/explicit.exp
index 668002d9038..8cbefe204ec 100644
--- a/gdb/testsuite/gdb.linespec/explicit.exp
+++ b/gdb/testsuite/gdb.linespec/explicit.exp
@@ -575,7 +575,7 @@ namespace eval $testfile {
 	      allow-pending]} {
 	fail "set $tst"
     } else {
-	gdb_test "info break" ".*PENDING.*myfunction if foofoofoo == 1.*" $tst
+	gdb_test "info break" ".*PENDING.*myfunction\r\n\\s+stop only if foofoofoo == 1.*" $tst
     }
 
     gdb_exit
@@ -586,7 +586,7 @@ namespace eval $testfile {
 	      allow-pending]} {
 	fail "set $tst"
     } else {
-	gdb_test "info break" ".*PENDING.*myfunction if arg == 0" $tst
+	gdb_test "info break" ".*PENDING.*myfunction\r\n\\s+stop only if arg == 0" $tst
 
 	gdb_load [standard_output_file $exefile]
 	gdb_test "info break" \
diff --git a/gdb/testsuite/gdb.linespec/keywords.exp b/gdb/testsuite/gdb.linespec/keywords.exp
index dc66e32237c..7900e3670a7 100644
--- a/gdb/testsuite/gdb.linespec/keywords.exp
+++ b/gdb/testsuite/gdb.linespec/keywords.exp
@@ -55,7 +55,7 @@ with_test_prefix "trailing whitespace" {
 gdb_test "break thread 123" "Unknown thread 123\\."
 gdb_test "break thread foo" "Invalid thread ID: foo"
 gdb_test "break task 123" "Unknown task 123\\."
-gdb_test "break task foo" "Junk after task keyword\\."
+gdb_test "break task foo" "Junk 'foo' after task keyword\\."
 gdb_breakpoint "thread if 0" "message"
 
 # These are also NULL locations, but using a subsequent keyword
@@ -63,9 +63,9 @@ gdb_breakpoint "thread if 0" "message"
 gdb_test "break thread thread" "Invalid thread ID: thread"
 gdb_test "break thread task" "Invalid thread ID: task"
 gdb_test "break thread if" "Invalid thread ID: if"
-gdb_test "break task task" "Junk after task keyword\\."
-gdb_test "break task thread" "Junk after task keyword\\."
-gdb_test "break task if" "Junk after task keyword\\."
+gdb_test "break task task" "Junk 'task' after task keyword\\."
+gdb_test "break task thread" "Junk 'thread' after task keyword\\."
+gdb_test "break task if" "Junk 'if' after task keyword\\."
 
 # Test locations containing keyword followed by keyword.
 gdb_test "break thread thread 123" "Unknown thread 123\\."
diff --git a/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp b/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp
index 28f52938aeb..bb9987a5572 100644
--- a/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp
+++ b/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp
@@ -50,7 +50,8 @@ set bp_location1 [gdb_get_line_number "set breakpoint 1 here"]
 # Set pending dprintf via MI.
 set bp [mi_make_breakpoint_pending -number "1" -type "dprintf" \
 	    -disp "keep" -enabled "y" -pending "pendfunc1" \
-	    -original-location "pendfunc1"]
+	    -original-location "pendfunc1" \
+	    -script {\["printf \\\"hello\\\""\]}]
 mi_gdb_test "-dprintf-insert -f pendfunc1 \"hello\"" \
     ".*\\^done,$bp" "mi set dprintf"
 
diff --git a/gdb/testsuite/gdb.multi/inferior-specific-bp.exp b/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
index 1f6573268da..b8aceabcad6 100644
--- a/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
+++ b/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
@@ -51,9 +51,9 @@ if {![runto_main]} {
 # this should fail.  Try with the keywords in both orders just in case the
 # parser has a bug.
 gdb_test "break foo thread 1.1 inferior 1" \
-    "You can specify only one of inferior or thread\\."
+    "You can specify only one of thread, inferior, or task\\."
 gdb_test "break foo inferior 1 thread 1.1" \
-    "You can specify only one of inferior or thread\\."
+    "You can specify only one of thread, inferior, or task\\."
 
 # Try to create a breakpoint using the 'inferior' keyword multiple times.
 gdb_test "break foo inferior 1 inferior 2" \
diff --git a/gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c b/gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
new file mode 100644
index 00000000000..15d1b9833dd
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
@@ -0,0 +1,22 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+int global_var = 0;
+
+void
+foo (int arg)
+{
+  global_var = arg;
+}
diff --git a/gdb/testsuite/gdb.threads/del-pending-thread-bp.c b/gdb/testsuite/gdb.threads/del-pending-thread-bp.c
new file mode 100644
index 00000000000..6fc76dbf08c
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/del-pending-thread-bp.c
@@ -0,0 +1,85 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#include <dlfcn.h>
+#include <pthread.h>
+#include <stdlib.h>
+
+pthread_barrier_t barrier;
+
+static void
+barrier_wait (pthread_barrier_t *b)
+{
+  int res = pthread_barrier_wait (b);
+  if (res != 0 && res != PTHREAD_BARRIER_SERIAL_THREAD)
+    abort ();
+}
+
+static void *
+thread_worker (void *arg)
+{
+  barrier_wait (&barrier);
+  return NULL;
+}
+
+void
+breakpt (void)
+{
+  /* Nothing.  */
+}
+
+int
+main (void)
+{
+  void *handle;
+  void (*func)(int);
+  pthread_t thread;
+
+  if (pthread_barrier_init (&barrier, NULL, 2) != 0)
+    abort ();
+
+  if (pthread_create (&thread, NULL, thread_worker, NULL) != 0)
+    abort ();
+
+  breakpt ();
+
+  /* Allow the worker thread to complete.  */
+  barrier_wait (&barrier);
+
+  if (pthread_join (thread, NULL) != 0)
+    abort ();
+
+  breakpt ();
+
+  /* Now load the shared library.  */
+  handle = dlopen (SHLIB_NAME, RTLD_LAZY);
+  if (handle == NULL)
+    abort ();
+
+  /* Find the function symbol.  */
+  func = (void (*)(int)) dlsym (handle, "foo");
+
+  /* Call the library function.  */
+  func (1);
+
+  /* Unload the shared library.  */
+  if (dlclose (handle) != 0)
+    abort ();
+
+  breakpt ();
+
+  return 0;
+}
+
diff --git a/gdb/testsuite/gdb.threads/del-pending-thread-bp.exp b/gdb/testsuite/gdb.threads/del-pending-thread-bp.exp
new file mode 100644
index 00000000000..4ed05eaa42d
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/del-pending-thread-bp.exp
@@ -0,0 +1,108 @@
+# Copyright 2023 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+# This test checks that pending thread-specific breakpoints are
+# correctly deleted when the thread the breakpoint is for goes out of
+# scope.
+#
+# We also check that we can't create a pending thread-specific
+# breakpoint for a non-existent thread.
+
+require allow_shlib_tests
+
+standard_testfile
+
+set libname $testfile-lib
+set srcfile_lib $srcdir/$subdir/$libname.c
+set binfile_lib [standard_output_file $libname.so]
+
+if { [gdb_compile_shlib $srcfile_lib $binfile_lib {}] != "" } {
+    untested "failed to compile shared library 1"
+    return -1
+}
+
+set binfile_lib_target [gdb_download_shlib $binfile_lib]
+
+if { [prepare_for_testing "failed to prepare" $testfile $srcfile \
+	  [list debug \
+	       additional_flags=-DSHLIB_NAME=\"$binfile_lib_target\" \
+	       shlib_load pthreads]] } {
+    return -1
+}
+
+gdb_locate_shlib $binfile_lib
+
+if ![runto_main] {
+    return 0
+}
+
+# Run until we have two threads.
+gdb_breakpoint "breakpt"
+gdb_continue_to_breakpoint "first breakpt call"
+
+# Confirm that we have a thread '2'.
+gdb_test "info threads" "\r\n\\s+2\\s+\[^\r\n\]+"
+
+# Create a pending, thread-specific, breakpoint on 'foo'.
+gdb_breakpoint "foo thread 2" allow-pending
+set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+	       "get breakpoint number"]
+
+# Check we can't create a pending thread-specific breakpoint for a
+# non-existent thread.
+gdb_test "with breakpoint pending on -- break foo thread 99" \
+    "Unknown thread 99\\."
+
+# Continue to 'breakpt' again.  Don't use gdb_continue_to_breakpoint
+# as we are looking for the thread exited and breakpoint deleted
+# messages.
+set output [list "Continuing\\."]
+
+if {!([target_info exists gdb_protocol]
+      && ([target_info gdb_protocol] == "remote"
+	  || [target_info gdb_protocol] == "extended-remote"))} {
+    # Due to bug PR gdb/30129 we don't see the thread exited messages
+    # for remote targets.  When this bit of this test can be cleaned
+    # up.
+    lappend output "\\\[Thread \[^\r\n\]+ exited\\\]"
+}
+
+lappend output "Thread-specific breakpoint $bpnum deleted - thread 2 no longer in the thread list\\." \
+    "" \
+    "Thread 1 \[^\r\n\]+, breakpt \\(\\) at \[^\r\n\]+" \
+    "$decimal\\s+\[^\r\n\]+"
+
+gdb_test "continue" \
+    [multi_line {*}$output] \
+    "second breakpt call"
+
+# Confirm breakpoint has been deleted.
+gdb_test "info breakpoints $bpnum" \
+    "No breakpoint or watchpoint matching '$bpnum'\\."
+
+# Continue again.  This will pass through 'foo'.  We should not stop
+# in 'foo', the breakpoint has been deleted.  We should next stop in
+# breakpt again.
+gdb_test "continue" \
+    [multi_line \
+	 "Continuing\\." \
+	 "" \
+	 "Thread 1 \[^\r\n\]+ hit Breakpoint $decimal, breakpt \\(\\) at \[^\r\n\]+" \
+	 "$decimal\\s+\[^\r\n\]+"] \
+    "third breakpt call"
+gdb_test "bt 1" \
+    [multi_line \
+	 "#0\\s+breakpt \\(\\) at \[^\r\n\]+" \
+	 "\\(More stack frames follow\\.\\.\\.\\)"]
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv8 13/14] gdb: don't set breakpoint::pspace in create_breakpoint
  2023-12-29  9:26             ` [PATCHv8 00/14] " Andrew Burgess
                                 ` (11 preceding siblings ...)
  2023-12-29  9:27               ` [PATCHv8 12/14] gdb: parse pending breakpoint thread/task immediately Andrew Burgess
@ 2023-12-29  9:27               ` Andrew Burgess
  2023-12-29  9:27               ` [PATCHv8 14/14] gdb: only insert thread-specific breakpoints in the relevant inferior Andrew Burgess
  2024-03-05 15:21               ` [PATCHv9 00/14] thread-specific breakpoints in just some inferiors Andrew Burgess
  14 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-12-29  9:27 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

I spotted this code within create_breakpoint:

  if ((type_wanted != bp_breakpoint
      && type_wanted != bp_hardware_breakpoint) || thread != -1)
   b->pspace = current_program_space;

this code is only executed when creating a pending breakpoint, and
sets the breakpoint::pspace member variable.

The above code gained the 'thread != -1' clause with this commit:

  commit cc72b2a2da6d6372cbdb1d14639a5fce84e1a325
  Date:   Fri Dec 23 17:06:16 2011 +0000

              Introduce gdb.FinishBreakpoint in Python

While the type_wanted checks were added with this commit:

  commit f8eba3c61629b3c03ac1f33853eab4d8507adb9c
  Date:   Tue Dec 6 18:54:43 2011 +0000

      the "ambiguous linespec" series

Before this breakpoint::pspace was set unconditionally.

If we look at how breakpoint::pspace is used today, some breakpoint
types specifically set this field, either in their constructors, or in
a wrapper function that calls the constructor.  So, the watchpoint
type and its sub-class set this variable, as does the catchpoint type,
and all it's sub-classes.

However, code_breakpoint doesn't specifically set this field within
its constructor, though some sub-classes of
code_breakpoint (ada_catchpoint, exception_catchpoint,
internal_breakpoint, and momentary_breakpoint) do set this field.

When I examine all the places that breakpoint::pspace is used, I
believe that in every place where it is expected that this field is
set, the breakpoint type will be one that specifically sets this
field.

Next, I observe two problems with the existing code.

First, the above code is only hit for pending breakpoints, there's no
equivalent code for non-pending breakpoints.  This opens up the
possibility of GDB entering non-consistent states; if a breakpoint is
first created pending and then later gets a location, the pspace field
will be set, while if the breakpoint is immediately non-pending, then
the pspace field will never be set.

Second, if we look at how breakpoint::pspace is used in the function
breakpoint_program_space_exit, we see that when a program space is
removed, any breakpoint with breakpoint::pspace set to the removed
program space, will be deleted.  This makes sense, but does mean we
need to ensure breakpoint::pspace is only set for breakpoints that
apply to a single program space.

So, if I create a pending dprintf breakpoint (type bp_dprintf) then
the breakpoint::pspace variable will be set even though the dprintf is
not really tied to that one program space.  As a result, when the
matching program space is removed the dprintf is incorrectly removed.

Also, if I create a thread specific breakpoint, then, thanks to the
'thread != -1' clause the wrong program space will be stored in
breakpoint::pspace (the current program space is always used, which
might not be the program space that corresponds to the selected
thread), as a result, the thread specific breakpoint will be deleted
when the matching program space is removed.

If we look at commit cc72b2a2da6d which added the 'thread != -1'
clause, we can see this change was entirely redundant, the
breakpoint::pspace is also set in bpfinishpy_init after
create_breakpoint has been called.  As such, I think we can safely
drop the 'thread != -1' clause.

For the other problems, I'm proposing to be pretty aggressive - I'd
like to drop the breakpoint::pspace assignment completely from
create_breakpoint.  Having looked at how this variable is used, I
believe that it is already set elsewhere in all the cases that it is
needed.  Maybe this code was needed at one time, but I can't see how
it's needed any more.

There's tests to expose the issues I've spotted with this code, and
there's no regressions in testing.
---
 gdb/breakpoint.c                              |   3 -
 gdb/breakpoint.h                              |  18 +-
 .../gdb.multi/pending-bp-del-inferior.c       |  28 +++
 .../gdb.multi/pending-bp-del-inferior.exp     | 216 ++++++++++++++++++
 4 files changed, 259 insertions(+), 6 deletions(-)
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-del-inferior.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 4fe125996f0..e9aa80e3c41 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -9200,9 +9200,6 @@ create_breakpoint (struct gdbarch *gdbarch,
       b->disposition = tempflag ? disp_del : disp_donttouch;
       b->condition_not_parsed = 1;
       b->enable_state = enabled ? bp_enabled : bp_disabled;
-      if ((type_wanted != bp_breakpoint
-	   && type_wanted != bp_hardware_breakpoint) || thread != -1)
-	b->pspace = current_program_space;
 
       if (b->type == bp_dprintf)
 	update_dprintf_command_list (b.get ());
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index 119bab86e7e..526a2464dc7 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -831,9 +831,21 @@ struct breakpoint : public intrusive_list_node<breakpoint>
      equals this.  */
   struct frame_id frame_id = null_frame_id;
 
-  /* The program space used to set the breakpoint.  This is only set
-     for breakpoints which are specific to a program space; for
-     non-thread-specific ordinary breakpoints this is NULL.  */
+  /* The program space used to set the breakpoint.  This is only set for
+     breakpoints that are not type bp_breakpoint or bp_hardware_breakpoint.
+     For thread or inferior specific breakpoints, the breakpoints are
+     managed via the thread and inferior member variables.  */
+
+  /* If not nullptr then this is the program space for which this
+     breakpoint was created.  All watchpoint and catchpoint sub-types set
+     this field, but not all of the code_breakpoint sub-types do;
+     generally, user created breakpoint types don't set this field, though
+     things might be more consistent if they did.
+
+     When this variable is nullptr then a breakpoint might be associated
+     with multiple program spaces, though you need to check the thread,
+     inferior and task variables to see if a breakpoint was created for a
+     specific thread, inferior, or Ada task respectively.  */
   program_space *pspace = NULL;
 
   /* The location specification we used to set the breakpoint.  */
diff --git a/gdb/testsuite/gdb.multi/pending-bp-del-inferior.c b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.c
new file mode 100644
index 00000000000..1d030007819
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.c
@@ -0,0 +1,28 @@
+/* This testcase is part of GDB, the GNU debugger.
+
+   Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+int
+foo (void)
+{
+  return 0;
+}
+
+int
+main (void)
+{
+  return foo ();
+}
diff --git a/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
new file mode 100644
index 00000000000..5fcd1ef2e39
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
@@ -0,0 +1,216 @@
+# Copyright 2023 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+# Setup two inferiors.  Select one inferior and create a pending
+# thread specific breakpoint in the other inferior.
+#
+# Delete the selected inferior (the one for which the thread specific
+# breakpoint doesn't apply), and check that the breakpoint still exists.
+#
+# Repeat this process, but this time, create an inferior specific
+# breakpoint.
+
+# The plain remote target can't do multiple inferiors.
+require !use_gdb_stub
+
+standard_testfile
+
+if {[prepare_for_testing "failed to prepare" $testfile $srcfile]} {
+    return -1
+}
+
+# Setup for the tests.  Create two inferiors, both running the global
+# BINFILE, and proceed to main in both inferiors.  Delete all
+# breakpoints, and check that we do have two threads.
+#
+# Return true after a successful setup, otherwise, return false.
+proc test_setup {} {
+    clean_restart $::binfile
+
+    if {![runto_main]} {
+	return 0
+    }
+
+    gdb_test "add-inferior -exec ${::binfile}" "Added inferior 2.*" \
+	"add inferior 2"
+    gdb_test "inferior 2" "Switching to inferior 2 .*" \
+	"select inferior 2"
+
+    if {![runto_main]} {
+	return 0
+    }
+
+    delete_breakpoints
+
+    gdb_test "info threads" \
+	[multi_line \
+	     "  Id\\s+Target Id\\s+Frame\\s*" \
+	     "  1\\.1\\s+\[^\r\n\]+" \
+	     "\\* 2\\.1\\s+\[^\r\n\]+"] \
+	"check we have the expected threads"
+
+    return 1
+}
+
+# Assuming inferior 2 is already selected, kill the current inferior
+# (inferior 2), select inferior 1, and then remove inferior 2.
+proc kill_and_remove_inferior_2 {} {
+    gdb_test "kill" "" "kill inferior 2" \
+	"Kill the program being debugged.*y or n. $" "y"
+
+    gdb_test "inferior 1" "Switching to inferior 1 .*" \
+	"select inferior 1"
+
+    gdb_test_no_output "remove-inferiors 2"
+}
+
+# Setup two inferiors, then create a breakpoint.  If BP_PENDING is
+# true then the breakpoint will be pending, otherwise, the breakpoint
+# will be non-pending.
+#
+# BP_TYPE is either 'thread' or 'inferior', and indicates if the
+# created breakpoint should be thread or inferior specific.
+#
+# The breakpoint is created while inferior 2 is selected, and the
+# thread/inferior restriction always identifies inferior 1.
+#
+# Then inferior 2 is killed and removed.
+#
+# Finally, check that the breakpoint still exists and correctly refers
+# to inferior 1.
+proc do_bp_test { bp_type bp_pending } {
+    if {![test_setup]} {
+	return
+    }
+
+    if { $bp_pending } {
+	set bp_func "bar"
+    } else {
+	set bp_func "foo"
+    }
+
+    if { $bp_type eq "thread" } {
+	set bp_restriction "thread 1.1"
+    } else {
+	set bp_restriction "inferior 1"
+    }
+
+    gdb_breakpoint "$bp_func $bp_restriction" allow-pending
+    set bp_number [get_integer_valueof "\$bpnum" "INVALID" \
+		       "get b/p number for previous breakpoint"]
+
+    if { $bp_restriction eq "thread 1.1" } {
+	set bp_after_restriction "thread 1"
+    } else {
+	set bp_after_restriction $bp_restriction
+    }
+
+    if { $bp_pending } {
+	set bp_pattern_before \
+	    [multi_line \
+		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+${bp_func}" \
+		 "\\s+stop only in [string_to_regexp $bp_restriction]"]
+	set bp_pattern_after \
+	    [multi_line \
+		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+${bp_func}" \
+		 "\\s+stop only in [string_to_regexp $bp_after_restriction]"]
+    } else {
+	set bp_pattern_before \
+	    [multi_line \
+		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+<MULTIPLE>\\s*" \
+		 "\\s+stop only in [string_to_regexp $bp_restriction]" \
+		 "$bp_number\\.1\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 1" \
+		 "$bp_number\\.2\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 2"]
+
+	set bp_pattern_after \
+	    [multi_line \
+		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+" \
+		 "\\s+stop only in [string_to_regexp $bp_after_restriction]"]
+    }
+
+    gdb_test "info breakpoints" $bp_pattern_before \
+	"info breakpoints before inferior removal"
+
+    kill_and_remove_inferior_2
+
+    gdb_test "info breakpoints" $bp_pattern_after \
+	"info breakpoints after inferior removal"
+}
+
+# Setup two inferiors, then create a dprintf.  If BP_PENDING is
+# true then the dprintf will be pending, otherwise, the dprintf
+# will be non-pending.
+#
+# The dprintf is created while inferior 2 is selected.  Then inferior
+# 2 is killed and removed.
+#
+# Finally, check that the dprintf still exists.
+proc do_dprintf_test { bp_pending } {
+    if {![test_setup]} {
+	return
+    }
+
+    if { $bp_pending } {
+	set bp_func "bar"
+
+	gdb_test "dprintf $bp_func,\"in $bp_func\"" ".*" \
+	    "create dprintf breakpoint" \
+	    "Make dprintf pending on future shared library load\\? \\(y or .n.\\) $" "y"
+    } else {
+	set bp_func "foo"
+
+	gdb_test "dprintf $bp_func,\"in $bp_func\"" ".*" \
+	    "create dprintf breakpoint"
+    }
+
+    set bp_number [get_integer_valueof "\$bpnum" "INVALID" \
+		       "get b/p number for previous breakpoint"]
+
+    if { $bp_pending } {
+	set bp_pattern_before \
+	    [multi_line \
+		 "$bp_number\\s+dprintf\\s+keep\\s+y\\s+<PENDING>\\s+${bp_func}" \
+		 "\\s+printf \"in $bp_func\""]
+	set bp_pattern_after $bp_pattern_before
+    } else {
+	set bp_pattern_before \
+	    [multi_line \
+		 "$bp_number\\s+dprintf\\s+keep\\s+y\\s+<MULTIPLE>\\s*" \
+		 "\\s+printf \"in $bp_func\"" \
+		 "$bp_number\\.1\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 1" \
+		 "$bp_number\\.2\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 2"]
+
+	set bp_pattern_after \
+	    [multi_line \
+		 "$bp_number\\s+dprintf\\s+keep\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+" \
+		 "\\s+printf \"in $bp_func\""]
+    }
+
+    gdb_test "info breakpoints" $bp_pattern_before \
+	"info breakpoints before inferior removal"
+
+    kill_and_remove_inferior_2
+
+    gdb_test "info breakpoints" $bp_pattern_after \
+	"info breakpoints after inferior removal"
+}
+
+foreach_with_prefix bp_pending { true false } {
+    foreach_with_prefix bp_type { thread inferior } {
+	do_bp_test $bp_type $bp_pending
+    }
+
+    do_dprintf_test $bp_pending
+}
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv8 14/14] gdb: only insert thread-specific breakpoints in the relevant inferior
  2023-12-29  9:26             ` [PATCHv8 00/14] " Andrew Burgess
                                 ` (12 preceding siblings ...)
  2023-12-29  9:27               ` [PATCHv8 13/14] gdb: don't set breakpoint::pspace in create_breakpoint Andrew Burgess
@ 2023-12-29  9:27               ` Andrew Burgess
  2024-03-05 15:21               ` [PATCHv9 00/14] thread-specific breakpoints in just some inferiors Andrew Burgess
  14 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2023-12-29  9:27 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Eli Zaretskii

Eli has already approved the docs changes in this commit.

---

This commit updates GDB so that thread or inferior specific
breakpoints are only inserted into the program space in which the
specific thread or inferior is running.

In terms of implementation, getting this basically working is easy
enough, now that a breakpoint's thread or inferior field is setup
prior to GDB looking for locations, we can easily use this information
to find a suitable program_space and pass this to as a filter when
creating the sals.

Or we could if breakpoint_ops::create_sals_from_location_spec allowed
us to pass in a filter program_space.

So, this commit extends breakpoint_ops::create_sals_from_location_spec
to take a program_space argument, and uses this to filter the set of
returned sals.  This accounts for about half the change in this patch.

The second set of changes starts from breakpoint_set_thread and
breakpoint_set_inferior, this is called when the thread or inferior
for a breakpoint changes, e.g. from the Python API.

Previously this call would never result in the locations of a
breakpoint changing, after all, locations were inserted in every
program space, and we just use the thread or inferior variable to
decide when we should stop.  Now though, changing a breakpoint's
thread or inferior can mean we need to figure out a new set of
breakpoint locations.

To support this I've added a new breakpoint_re_set_one function, which
is like breakpoint_re_set, but takes a single breakpoint, and just
updates the locations for that one breakpoint.  We only need to call
this function if the program_space in which a breakpoint's thread (or
inferior) is running actually changes.  If the program_space does
change then we call the new breakpoint_re_set_one function passing in
the program_space which should be used to filter the new locations (or
nullptr to indicate we should set locations in all program spaces).
This filter program_space needs to propagate down to all the re_set
methods, this accounts for the remaining half of the changes in this
patch.

There were a couple of existing tests that created thread or inferior
specific breakpoints and then checked the 'info breakpoints' output,
these needed updating.  These were:

  gdb.mi/user-selected-context-sync.exp
  gdb.multi/bp-thread-specific.exp
  gdb.multi/multi-target-continue.exp
  gdb.multi/multi-target-ping-pong-next.exp
  gdb.multi/tids.exp
  gdb.mi/new-ui-bp-deleted.exp
  gdb.multi/inferior-specific-bp.exp
  gdb.multi/pending-bp-del-inferior.exp

I've also added some additional tests to:

  gdb.multi/pending-bp.exp

I've updated the documentation and added a NEWS entry.

Reviewed-By: Eli Zaretskii <eliz@gnu.org>
---
 gdb/NEWS                                      |   7 +
 gdb/ada-lang.c                                |   6 +-
 gdb/break-catch-throw.c                       |   6 +-
 gdb/breakpoint.c                              | 280 ++++++++++++++----
 gdb/breakpoint.h                              |  29 +-
 gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp    |   8 +-
 .../gdb.mi/user-selected-context-sync.exp     |   4 +-
 .../gdb.multi/bp-thread-specific.exp          |   7 +-
 .../gdb.multi/inferior-specific-bp.exp        |  12 +-
 .../gdb.multi/multi-target-continue.exp       |   2 +-
 .../gdb.multi/multi-target-ping-pong-next.exp |   4 +-
 .../gdb.multi/pending-bp-del-inferior.exp     |   6 +-
 gdb/testsuite/gdb.multi/pending-bp.exp        | 206 +++++++++++++
 gdb/testsuite/gdb.multi/tids.exp              |   6 +-
 14 files changed, 484 insertions(+), 99 deletions(-)

diff --git a/gdb/NEWS b/gdb/NEWS
index 6f27f7b20c2..436a1dfcc33 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -13,6 +13,13 @@
   'thread' or 'task' keywords are parsed at the time the breakpoint is
   created, rather than at the time the breakpoint becomes non-pending.
 
+* Thread-specific breakpoints are only inserted into the program space
+  in which the thread of interest is running.  In most cases program
+  spaces are unique for each inferior, so this means that
+  thread-specific breakpoints will usually only be inserted for the
+  inferior containing the thread of interest.  The breakpoint will
+  be hit no less than before.
+
 * Changed commands
 
 disassemble
diff --git a/gdb/ada-lang.c b/gdb/ada-lang.c
index 411062cad27..62db0f33823 100644
--- a/gdb/ada-lang.c
+++ b/gdb/ada-lang.c
@@ -12019,11 +12019,11 @@ struct ada_catchpoint : public code_breakpoint
     enable_state = enabled ? bp_enabled : bp_disabled;
     language = language_ada;
 
-    re_set ();
+    re_set (pspace);
   }
 
   struct bp_location *allocate_location () override;
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   void check_status (struct bpstat *bs) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   bool print_one (const bp_location **) const override;
@@ -12068,7 +12068,7 @@ static struct symtab_and_line ada_exception_sal
    catchpoint kinds.  */
 
 void
-ada_catchpoint::re_set ()
+ada_catchpoint::re_set (program_space *pspace)
 {
   std::vector<symtab_and_line> sals;
   try
diff --git a/gdb/break-catch-throw.c b/gdb/break-catch-throw.c
index 47d534c5ee8..e661d1624e8 100644
--- a/gdb/break-catch-throw.c
+++ b/gdb/break-catch-throw.c
@@ -82,10 +82,10 @@ struct exception_catchpoint : public code_breakpoint
 				     _("invalid type-matching regexp")))
   {
     pspace = current_program_space;
-    re_set ();
+    re_set (pspace);
   }
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   bool print_one (const bp_location **) const override;
   void print_mention () const override;
@@ -198,7 +198,7 @@ exception_catchpoint::check_status (struct bpstat *bs)
 /* Implement the 're_set' method.  */
 
 void
-exception_catchpoint::re_set ()
+exception_catchpoint::re_set (program_space *pspace)
 {
   std::vector<symtab_and_line> sals;
   struct program_space *filter_pspace = current_program_space;
diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index e9aa80e3c41..87987e4d6ac 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -91,9 +91,12 @@
 static void map_breakpoint_numbers (const char *,
 				    gdb::function_view<void (breakpoint *)>);
 
-static void
-  create_sals_from_location_spec_default (location_spec *locspec,
-					  linespec_result *canonical);
+static void parse_breakpoint_sals (location_spec *locspec,
+				   linespec_result *canonical,
+				   program_space *search_pspace);
+
+static void breakpoint_re_set_one (breakpoint *b,
+				   program_space *filter_pspace);
 
 static void create_breakpoints_sal (struct gdbarch *,
 				    struct linespec_result *,
@@ -283,11 +286,12 @@ static bool strace_marker_p (struct breakpoint *b);
 
 static void bkpt_probe_create_sals_from_location_spec
      (location_spec *locspec,
-      struct linespec_result *canonical);
+      struct linespec_result *canonical,
+      struct program_space *search_pspace);
 
 const struct breakpoint_ops code_breakpoint_ops =
 {
-  create_sals_from_location_spec_default,
+  parse_breakpoint_sals,
   create_breakpoints_sal,
 };
 
@@ -352,7 +356,7 @@ struct internal_breakpoint : public code_breakpoint
     disposition = disp_donttouch;
   }
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   void check_status (struct bpstat *bs) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   void print_mention () const override;
@@ -389,7 +393,7 @@ struct momentary_breakpoint : public code_breakpoint
     gdb_assert (inferior == -1);
   }
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   void check_status (struct bpstat *bs) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   void print_mention () const override;
@@ -400,7 +404,7 @@ struct dprintf_breakpoint : public ordinary_breakpoint
 {
   using ordinary_breakpoint::ordinary_breakpoint;
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   int breakpoint_hit (const struct bp_location *bl,
 		      const address_space *aspace,
 		      CORE_ADDR bp_addr,
@@ -1549,7 +1553,36 @@ breakpoint_set_thread (struct breakpoint *b, int thread)
   int old_thread = b->thread;
   b->thread = thread;
   if (old_thread != thread)
-    notify_breakpoint_modified (b);
+    {
+      /* If THREAD is in a different program_space than OLD_THREAD, or the
+	 breakpoint has switched to or from being thread-specific, then we
+	 need to re-set the locations of this breakpoint.  First, figure
+	 out the program_space for the old and new threads, use a value of
+	 nullptr to indicate the breakpoint is in all program spaces.  */
+      program_space *old_pspace = nullptr;
+      if (old_thread != -1)
+	{
+	  struct thread_info *thr = find_thread_global_id (old_thread);
+	  gdb_assert (thr != nullptr);
+	  old_pspace = thr->inf->pspace;
+	}
+
+      program_space *new_pspace = nullptr;
+      if (thread != -1)
+	{
+	  struct thread_info *thr = find_thread_global_id (thread);
+	  gdb_assert (thr != nullptr);
+	  new_pspace = thr->inf->pspace;
+	}
+
+      /* If the program space has changed for this breakpoint, then
+	 re-evaluate it's locations.  */
+      if (old_pspace != new_pspace)
+	breakpoint_re_set_one (b, new_pspace);
+
+      /* Let others know the breakpoint has changed.  */
+      notify_breakpoint_modified (b);
+    }
 }
 
 /* See breakpoint.h.  */
@@ -1568,7 +1601,34 @@ breakpoint_set_inferior (struct breakpoint *b, int inferior)
   int old_inferior = b->inferior;
   b->inferior = inferior;
   if (old_inferior != inferior)
-    notify_breakpoint_modified (b);
+    {
+      /* If INFERIOR is in a different program_space than OLD_INFERIOR, or
+	 the breakpoint has switch to or from inferior-specific, then we
+	 need to re-set the locations of this breakpoint.  First, figure
+	 out the program_space for the old and new inferiors, use a value
+	 of nullptr to indicate the breakpoint is in all program
+	 spaces.  */
+      program_space *old_pspace = nullptr;
+      if (old_inferior != -1)
+	{
+	  struct inferior *inf = find_inferior_id (old_inferior);
+	  gdb_assert (inf != nullptr);
+	  old_pspace = inf->pspace;
+	}
+
+      program_space *new_pspace = nullptr;
+      if (inferior != -1)
+	{
+	  struct inferior *inf = find_inferior_id (inferior);
+	  gdb_assert (inf != nullptr);
+	  new_pspace = inf->pspace;
+	}
+
+      if (old_pspace != new_pspace)
+	breakpoint_re_set_one (b, new_pspace);
+
+      notify_breakpoint_modified (b);
+    }
 }
 
 /* See breakpoint.h.  */
@@ -8809,7 +8869,8 @@ create_breakpoints_sal (struct gdbarch *gdbarch,
 
 static void
 parse_breakpoint_sals (location_spec *locspec,
-		       struct linespec_result *canonical)
+		       struct linespec_result *canonical,
+		       struct program_space *search_pspace)
 {
   struct symtab_and_line cursal;
 
@@ -8874,7 +8935,7 @@ parse_breakpoint_sals (location_spec *locspec,
 	      && strchr ("+-", spec[0]) != NULL
 	      && spec[1] != '['))
 	{
-	  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, NULL,
+	  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, search_pspace,
 			    get_last_displayed_symtab (),
 			    get_last_displayed_line (),
 			    canonical, NULL, NULL);
@@ -8882,7 +8943,7 @@ parse_breakpoint_sals (location_spec *locspec,
 	}
     }
 
-  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, NULL,
+  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, search_pspace,
 		    cursal.symtab, cursal.line, canonical, NULL, NULL);
 }
 
@@ -8981,6 +9042,39 @@ breakpoint_ops_for_location_spec_type (enum location_spec_type locspec_type,
     }
 }
 
+/* Return the program space to use as a filter when searching for locations
+   of a breakpoint specific to THREAD or INFERIOR.  If THREAD and INFERIOR
+   are both -1, meaning all threads/inferiors, then this function returns
+   nullptr, indicating no program space filtering should be performed.
+   Otherwise, this function returns the program space for the inferior that
+   contains THREAD (when THREAD is not -1), or the program space for
+   INFERIOR (when INFERIOR is not -1).  */
+
+static struct program_space *
+find_program_space_for_breakpoint (int thread, int inferior)
+{
+  if (thread != -1)
+    {
+      gdb_assert (inferior == -1);
+
+      struct thread_info *thr = find_thread_global_id (thread);
+      gdb_assert (thr != nullptr);
+      gdb_assert (thr->inf != nullptr);
+      return thr->inf->pspace;
+    }
+  else if (inferior != -1)
+    {
+      gdb_assert (thread == -1);
+
+      struct inferior *inf = find_inferior_id (inferior);
+      gdb_assert (inf != nullptr);
+
+      return inf->pspace;
+    }
+
+  return nullptr;
+}
+
 /* See breakpoint.h.  */
 
 const struct breakpoint_ops *
@@ -9082,7 +9176,10 @@ create_breakpoint (struct gdbarch *gdbarch,
 
   try
     {
-      ops->create_sals_from_location_spec (locspec, &canonical);
+      struct program_space *search_pspace
+	= find_program_space_for_breakpoint (thread, inferior);
+      ops->create_sals_from_location_spec (locspec, &canonical,
+					   search_pspace);
     }
   catch (const gdb_exception_error &e)
     {
@@ -9555,7 +9652,7 @@ break_range_command (const char *arg, int from_tty)
   arg_start = arg;
   location_spec_up start_locspec
     = string_to_location_spec (&arg, current_language);
-  parse_breakpoint_sals (start_locspec.get (), &canonical_start);
+  parse_breakpoint_sals (start_locspec.get (), &canonical_start, nullptr);
 
   if (arg[0] != ',')
     error (_("Too few arguments."));
@@ -9656,7 +9753,7 @@ watchpoint_exp_is_const (const struct expression *exp)
 /* Implement the "re_set" method for watchpoints.  */
 
 void
-watchpoint::re_set ()
+watchpoint::re_set (struct program_space *pspace)
 {
   /* Watchpoint can be either on expression using entirely global
      variables, or it can be on local variables.
@@ -11767,7 +11864,7 @@ breakpoint::print_recreate (struct ui_file *fp) const
 /* Default breakpoint_ops methods.  */
 
 void
-code_breakpoint::re_set ()
+code_breakpoint::re_set (struct program_space *pspace)
 {
   /* FIXME: is this still reachable?  */
   if (breakpoint_location_spec_empty_p (this))
@@ -11777,7 +11874,7 @@ code_breakpoint::re_set ()
       return;
     }
 
-  re_set_default ();
+  re_set_default (pspace);
 }
 
 int
@@ -11983,7 +12080,7 @@ code_breakpoint::decode_location_spec (location_spec *locspec,
 /* Virtual table for internal breakpoints.  */
 
 void
-internal_breakpoint::re_set ()
+internal_breakpoint::re_set (struct program_space *pspace)
 {
   switch (type)
     {
@@ -12076,7 +12173,7 @@ internal_breakpoint::print_mention () const
 /* Virtual table for momentary breakpoints  */
 
 void
-momentary_breakpoint::re_set ()
+momentary_breakpoint::re_set (struct program_space *pspace)
 {
   /* Keep temporary breakpoints, which can be encountered when we step
      over a dlopen call and solib_add is resetting the breakpoints.
@@ -12117,12 +12214,13 @@ longjmp_breakpoint::~longjmp_breakpoint ()
 
 static void
 bkpt_probe_create_sals_from_location_spec (location_spec *locspec,
-					   struct linespec_result *canonical)
+					   struct linespec_result *canonical,
+					   struct program_space *search_pspace)
 
 {
   struct linespec_sals lsal;
 
-  lsal.sals = parse_probes (locspec, NULL, canonical);
+  lsal.sals = parse_probes (locspec, search_pspace, canonical);
   lsal.canonical = xstrdup (canonical->locspec->to_string ());
   canonical->lsals.push_back (std::move (lsal));
 }
@@ -12212,9 +12310,9 @@ tracepoint::print_recreate (struct ui_file *fp) const
 }
 
 void
-dprintf_breakpoint::re_set ()
+dprintf_breakpoint::re_set (struct program_space *pspace)
 {
-  re_set_default ();
+  re_set_default (pspace);
 
   /* 1 - connect to target 1, that can run breakpoint commands.
      2 - create a dprintf, which resolves fine.
@@ -12268,8 +12366,10 @@ dprintf_breakpoint::after_condition_true (struct bpstat *bs)
    markers (`-m').  */
 
 static void
-strace_marker_create_sals_from_location_spec (location_spec *locspec,
-					      struct linespec_result *canonical)
+strace_marker_create_sals_from_location_spec
+	(location_spec *locspec,
+	 struct linespec_result *canonical,
+	 struct program_space *search_pspace)
 {
   struct linespec_sals lsal;
   const char *arg_start, *arg;
@@ -12784,12 +12884,32 @@ update_breakpoint_locations (code_breakpoint *b,
      all locations are in the same shared library, that was unloaded.
      We'd like to retain the location, so that when the library is
      loaded again, we don't loose the enabled/disabled status of the
-     individual locations.  */
+     individual locations.
+
+     Thread specific breakpoints will also trigger this case if the thread
+     is changed to a different program space, and all of the old locations
+     go out of scope.  In this case we do (currently) discard the old
+     locations -- we assume the change in thread is permanent and the old
+     locations will never come back into scope.  */
   if (all_locations_are_pending (b, filter_pspace) && sals.empty ())
-    return;
+    {
+      if (b->thread != -1)
+	b->clear_locations ();
+      return;
+    }
 
   bp_location_list existing_locations = b->steal_locations (filter_pspace);
 
+  /* If this is a thread-specific breakpoint then any locations left on the
+     breakpoint are for a program space in which the thread of interest
+     does not operate.  This can happen when the user changes the thread of
+     a thread-specific breakpoint.
+
+     We assume that the change in thread is permanent, and that the old
+     locations will never be used again, so discard them now.  */
+  if (b->thread != -1)
+    b->clear_locations ();
+
   for (const auto &sal : sals)
     {
       struct bp_location *new_loc;
@@ -12955,40 +13075,45 @@ code_breakpoint::location_spec_to_sals (location_spec *locspec,
    locations.  */
 
 void
-code_breakpoint::re_set_default ()
+code_breakpoint::re_set_default (struct program_space *filter_pspace)
 {
-  struct program_space *filter_pspace = current_program_space;
   std::vector<symtab_and_line> expanded, expanded_end;
 
-  int found;
-  std::vector<symtab_and_line> sals = location_spec_to_sals (locspec.get (),
-							     filter_pspace,
-							     &found);
-  if (found)
-    expanded = std::move (sals);
-
-  if (locspec_range_end != nullptr)
-    {
-      std::vector<symtab_and_line> sals_end
-	= location_spec_to_sals (locspec_range_end.get (),
-				 filter_pspace, &found);
+  /* If this breakpoint is thread-specific then find the program space in
+     which the specific thread exists.  Otherwise, for breakpoints that are
+     not thread-specific THREAD_PSPACE will be nullptr.  */
+  program_space *bp_pspace
+    = find_program_space_for_breakpoint (this->thread, this->inferior);
+
+  /* If this is not a thread or inferior specific breakpoint, or it is a
+     thread or inferior specific breakpoint but we are looking for new
+     locations in the program space that the specific thread or inferior is
+     running, then look for new locations for this breakpoint.  */
+  if (bp_pspace == nullptr || filter_pspace == bp_pspace)
+    {
+      int found;
+      std::vector<symtab_and_line> sals
+	= location_spec_to_sals (locspec.get (), filter_pspace, &found);
       if (found)
-	expanded_end = std::move (sals_end);
+	expanded = std::move (sals);
+
+      if (locspec_range_end != nullptr)
+	{
+	  std::vector<symtab_and_line> sals_end
+	    = location_spec_to_sals (locspec_range_end.get (),
+				     filter_pspace, &found);
+	  if (found)
+	    expanded_end = std::move (sals_end);
+	}
     }
 
+  /* Update the locations for this breakpoint.  For thread-specific
+     breakpoints this will remove any old locations that are for the wrong
+     program space -- this can happen if the user changes the thread of a
+     thread-specific breakpoint.  */
   update_breakpoint_locations (this, filter_pspace, expanded, expanded_end);
 }
 
-/* Default method for creating SALs from an address string.  It basically
-   calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
-
-static void
-create_sals_from_location_spec_default (location_spec *locspec,
-					struct linespec_result *canonical)
-{
-  parse_breakpoint_sals (locspec, canonical);
-}
-
 /* Re-set breakpoint locations for the current program space.
    Locations bound to other program spaces are left untouched.  */
 
@@ -13023,7 +13148,7 @@ breakpoint_re_set (void)
 	  {
 	    input_radix = b.input_radix;
 	    set_language (b.language);
-	    b.re_set ();
+	    b.re_set (current_program_space);
 	  }
 	catch (const gdb_exception &ex)
 	  {
@@ -13044,6 +13169,53 @@ breakpoint_re_set (void)
   /* Now we can insert.  */
   update_global_location_list (UGLL_MAY_INSERT);
 }
+
+/* Re-set locations for breakpoint B in FILTER_PSPACE.  If FILTER_PSPACE is
+   nullptr then re-set locations for B in all program spaces.  Locations
+   bound to program spaces other than FILTER_PSPACE are left untouched.  */
+
+static void
+breakpoint_re_set_one (breakpoint *b, program_space *filter_pspace)
+{
+  {
+    scoped_restore_current_language save_language;
+    scoped_restore save_input_radix = make_scoped_restore (&input_radix);
+    scoped_restore_current_pspace_and_thread restore_pspace_thread;
+
+    /* To ::re_set each breakpoint we set the current_language to the
+       language of the breakpoint before re-evaluating the breakpoint's
+       location.  This change can unfortunately get undone by accident if
+       the language_mode is set to auto, and we either switch frames, or
+       more likely in this context, we select the current frame.
+
+       We prevent this by temporarily turning the language_mode to
+       language_mode_manual.  We restore it once all breakpoints
+       have been reset.  */
+    scoped_restore save_language_mode = make_scoped_restore (&language_mode);
+    language_mode = language_mode_manual;
+
+    /* Note: we must not try to insert locations until after all
+       breakpoints have been re-set.  Otherwise, e.g., when re-setting
+       breakpoint 1, we'd insert the locations of breakpoint 2, which
+       hadn't been re-set yet, and thus may have stale locations.  */
+
+    try
+      {
+	input_radix = b->input_radix;
+	set_language (b->language);
+	b->re_set (filter_pspace);
+      }
+    catch (const gdb_exception &ex)
+      {
+	exception_fprintf (gdb_stderr, ex,
+			   "Error in re-setting breakpoint %d: ",
+			   b->number);
+      }
+  }
+
+  /* Now we can insert.  */
+  update_global_location_list (UGLL_MAY_INSERT);
+}
 \f
 /* Reset the thread number of this breakpoint:
 
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index 526a2464dc7..8f2b9447531 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -570,15 +570,15 @@ enum print_stop_action
 
 struct breakpoint_ops
 {
-  /* Create SALs from location spec, storing the result in
-     linespec_result.
-
-     For an explanation about the arguments, see the function
-     `create_sals_from_location_spec_default'.
+  /* Create SALs from LOCSPEC, storing the result in linespec_result
+     CANONICAL.  If SEARCH_PSPACE is not nullptr then only results in the
+     corresponding program space are returned.  If SEARCH_PSPACE is nullptr
+     then results for all program spaces are returned.
 
      This function is called inside `create_breakpoint'.  */
   void (*create_sals_from_location_spec) (location_spec *locspec,
-					  struct linespec_result *canonical);
+					  linespec_result *canonical,
+					  program_space *search_pspace);
 
   /* This method will be responsible for creating a breakpoint given its SALs.
      Usually, it just calls `create_breakpoints_sal' (for ordinary
@@ -710,8 +710,15 @@ struct breakpoint : public intrusive_list_node<breakpoint>
 
   /* Reevaluate a breakpoint.  This is necessary after symbols change
      (e.g., an executable or DSO was loaded, or the inferior just
-     started).  */
-  virtual void re_set ()
+     started).
+
+     If not nullptr, then FILTER_PSPACE is the program space in which
+     symbols may have changed, we only need to add new locations in
+     FILTER_PSPACE.
+
+     If FILTER_PSPACE is nullptr then all program spaces may have changed,
+     new locations need to be searched for in every program space.  */
+  virtual void re_set (program_space *filter_pspace)
   {
     /* Nothing to re-set.  */
   }
@@ -955,7 +962,7 @@ struct code_breakpoint : public breakpoint
   /* Add a location for SAL to this breakpoint.  */
   bp_location *add_location (const symtab_and_line &sal);
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   int insert_location (struct bp_location *) override;
   int remove_location (struct bp_location *,
 		       enum remove_bp_reason reason) override;
@@ -977,7 +984,7 @@ struct code_breakpoint : public breakpoint
      struct program_space *search_pspace);
 
   /* Helper method that does the basic work of re_set.  */
-  void re_set_default ();
+  void re_set_default (program_space *pspace);
 
   /* Find the SaL locations corresponding to the given LOCATION.
      On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
@@ -999,7 +1006,7 @@ struct watchpoint : public breakpoint
 {
   using breakpoint::breakpoint;
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   int insert_location (struct bp_location *) override;
   int remove_location (struct bp_location *,
 		       enum remove_bp_reason reason) override;
diff --git a/gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp b/gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp
index 57e69ef6240..3afc1787026 100644
--- a/gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp
+++ b/gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp
@@ -76,8 +76,12 @@ foreach_mi_ui_mode mode {
     set loc2 [make_bp_loc "$::decimal\\.2"]
 
     # Create the inferior-specific breakpoint.
-    mi_create_breakpoint_multi "-g i2 foo" "create breakpoint in inferior 2" \
-	-inferior "2" -locations "\\\[$loc1,$loc2\\\]"
+    mi_create_breakpoint "-g i2 foo" "create breakpoint in inferior 2" \
+	-number "$decimal" \
+	-type "breakpoint" \
+	-enabled "y" \
+	-func "foo" \
+	-inferior "2"
     set bpnum [mi_get_valueof "/d" "\$bpnum" "INVALID"]
 
     if {$mode eq "separate"} {
diff --git a/gdb/testsuite/gdb.mi/user-selected-context-sync.exp b/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
index 4889c31aff3..b39745bdf17 100644
--- a/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
+++ b/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
@@ -370,7 +370,7 @@ proc test_continue_to_start { mode inf } {
 			    "thread $inf.2 stops MI"
 		    } else {
 			mi_expect_stop "breakpoint-hit" "child_sub_function" \
-			    "" "$srcfile" "$decimal" {"" "disp=\"del\"" "locno=\"[0-9]+\""} \
+			    "" "$srcfile" "$decimal" {"" "disp=\"del\""} \
 			    "thread $inf.2 stops MI"
 		    }
 		}
@@ -439,7 +439,7 @@ proc_with_prefix test_setup { mode } {
 
 	with_spawn_id $mi_spawn_id {
 	    mi_expect_stop "breakpoint-hit" "main" "" "$srcfile" "$decimal" \
-		{"" "disp=\"del\"" "locno=\"[0-9]+\""} "main stop"
+		{"" "disp=\"del\""} "main stop"
 	}
 
 	# Consume CLI output.
diff --git a/gdb/testsuite/gdb.multi/bp-thread-specific.exp b/gdb/testsuite/gdb.multi/bp-thread-specific.exp
index 85c08f44a2c..68001e92044 100644
--- a/gdb/testsuite/gdb.multi/bp-thread-specific.exp
+++ b/gdb/testsuite/gdb.multi/bp-thread-specific.exp
@@ -50,7 +50,7 @@ gdb_test "info threads" \
 # locations ('foo' in both inferiors) even though only one of those
 # locations will ever trigger ('foo' in inferior 2).
 gdb_test "break foo thread 2.1" \
-    "Breakpoint $decimal at $hex: foo\\. \\(2 locations\\)"
+    "Breakpoint $decimal at $hex: file \[^\r\n\]+$srcfile, line $decimal\\."
 
 set bpnum [get_integer_valueof "\$bpnum" "INVALID"]
 
@@ -58,10 +58,7 @@ set bpnum [get_integer_valueof "\$bpnum" "INVALID"]
 # earlier breakpoint.  Check that the thread-id used when describing
 # the earlier breakpoints is correct.
 gdb_test "break foo thread 1.1" \
-    [multi_line \
-	 "Note: breakpoint $bpnum \\(thread 2.1\\) also set at pc $hex\\." \
-	 "Note: breakpoint $bpnum \\(thread 2.1\\) also set at pc $hex\\." \
-	 "Breakpoint $decimal at $hex: foo\\. \\(2 locations\\)"]
+    "Breakpoint $decimal at $hex: file \[^\r\n\]+$srcfile, line $decimal\\."
 
 # Save the breakpoints into a file.
 if {[is_remote host]} {
diff --git a/gdb/testsuite/gdb.multi/inferior-specific-bp.exp b/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
index b8aceabcad6..dda167dd39f 100644
--- a/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
+++ b/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
@@ -105,16 +105,8 @@ proc check_info_breakpoints { testname bp_number expected_loc_count } {
 # Create an inferior-specific breakpoint.  Use gdb_test instead of
 # gdb_breakpoint here as we want to check the breakpoint was placed in
 # multiple locations.
-#
-# Currently GDB still places inferior specific breakpoints into every
-# inferior, just like it does with thread specific breakpoints.
-# Hopefully this will change in the future, at which point, this test
-# will need updating.
-#
-# Two of these locations are in inferior 1, while the third is in
-# inferior 2.
 gdb_test "break foo inferior 1" \
-    "Breakpoint $decimal at $hex: foo\\. \\(3 locations\\)"
+    "Breakpoint $decimal at $hex: foo\\. \\(2 locations\\)"
 set bp_number [get_integer_valueof "\$bpnum" "INVALID" \
 		  "get b/p number for inferior specific breakpoint"]
 
@@ -123,7 +115,7 @@ set location_count 0
 set saw_inf_cond false
 
 check_info_breakpoints "first check for inferior specific breakpoint" \
-    $bp_number 3
+    $bp_number 2
 
 # Create a multi-inferior breakpoint to stop at.
 gdb_breakpoint "stop_breakpt" message
diff --git a/gdb/testsuite/gdb.multi/multi-target-continue.exp b/gdb/testsuite/gdb.multi/multi-target-continue.exp
index bf19cc00968..a1bffb7b613 100644
--- a/gdb/testsuite/gdb.multi/multi-target-continue.exp
+++ b/gdb/testsuite/gdb.multi/multi-target-continue.exp
@@ -30,7 +30,7 @@ proc test_continue {non-stop} {
 
     proc set_break {inf} {
 	gdb_test "break function${inf} thread ${inf}.1" \
-	"Breakpoint .* function${inf}\\..*"
+	    "Breakpoint ${::decimal} at ${::hex}: file .*, line ${::decimal}\\."
     }
 
     # Select inferior INF, and then run to a breakpoint on inferior
diff --git a/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp b/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp
index 64645b8ec8a..51fd70b018a 100644
--- a/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp
+++ b/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp
@@ -52,12 +52,12 @@ proc test_ping_pong_next {} {
     gdb_test "thread 1.1" "Switching to thread 1.1 .*"
 
     gdb_test "break $srcfile:$line1 thread 1.1" \
-	"Breakpoint .*$srcfile:$line1\\..*"
+	"Breakpoint .*$srcfile, line $line1\\."
 
     gdb_test "continue" "hit Breakpoint .*"
 
     gdb_test "break $srcfile:$line2 thread 2.1" \
-	"Breakpoint .*$srcfile:$line2\\..*"
+	"Breakpoint .*$srcfile, line $line2\\."
 
     # Now block inferior 1 and issue "next".  We should stop at the
     # breakpoint for inferior 2, given schedlock off.
diff --git a/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
index 5fcd1ef2e39..12c0a84bb02 100644
--- a/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
+++ b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
@@ -129,10 +129,8 @@ proc do_bp_test { bp_type bp_pending } {
     } else {
 	set bp_pattern_before \
 	    [multi_line \
-		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+<MULTIPLE>\\s*" \
-		 "\\s+stop only in [string_to_regexp $bp_restriction]" \
-		 "$bp_number\\.1\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 1" \
-		 "$bp_number\\.2\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 2"]
+		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 1" \
+		 "\\s+stop only in [string_to_regexp $bp_restriction]"]
 
 	set bp_pattern_after \
 	    [multi_line \
diff --git a/gdb/testsuite/gdb.multi/pending-bp.exp b/gdb/testsuite/gdb.multi/pending-bp.exp
index 478d8d7c037..aeb8c2c886e 100644
--- a/gdb/testsuite/gdb.multi/pending-bp.exp
+++ b/gdb/testsuite/gdb.multi/pending-bp.exp
@@ -72,6 +72,48 @@ proc do_test_setup { inf_1_stop inf_2_stop } {
     return true
 }
 
+# Create a breakpoint on the function 'foo' in THREAD.  It is expected
+# that the breakpoint created will be pending, this is checked by
+# running the 'info breakpoints' command.
+#
+# Returns the number for the newly created breakpoint.
+proc do_create_pending_foo_breakpoint { {thread "1.1"} } {
+    gdb_test "break foo thread $thread" \
+	[multi_line \
+	     "Function \"foo\" not defined\\." \
+	     "Breakpoint $::decimal \\(foo\\) pending\."] \
+	"set pending thread-specific breakpoint"
+    set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+		   "get number for thread-specific breakpoint on foo"]
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	     "\\s+stop only in thread [string_to_regexp $thread]"] \
+	"check thread-specific breakpoint is initially pending"
+
+    return $bpnum
+}
+
+# Create a breakpoint on the function 'foo' in THREAD.  It is expected
+# that the breakpoint created will not be pending, this is checked by
+# running the 'info breakpoints' command.
+#
+# Returns the number for the newly created breakpoint.
+proc do_create_foo_breakpoint { {thread "1.1"} } {
+    gdb_test "break foo thread $thread" \
+	"Breakpoint $::decimal at $::hex" \
+	"set thread-specific breakpoint"
+    set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+		   "get number for thread-specific breakpoint on foo"]
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex\\s+<foo\[^>\]*> inf $::decimal" \
+	     "\\s+stop only in thread [string_to_regexp $thread]"] \
+	"check thread-specific breakpoint is initially pending"
+
+    return $bpnum
+}
+
 # Check that when a breakpoint is in the pending state, but that breakpoint
 # does have some locations (those locations themselves are pending), GDB
 # doesn't display the inferior list in the 'info breakpoints' output.
@@ -122,5 +164,169 @@ proc_with_prefix test_no_inf_display {} {
 	"check info breakpoints while breakpoint is pending"
 }
 
+# Setup two inferiors.  In #1 the symbol 'foo' has not yet been
+# loaded, while in #2 the symbol 'foo' has been loaded.
+#
+# Create a thread-specific breakpoint on 'foo' tied to a thread in
+# inferior #1, the breakpoint should be pending -- 'foo' is not yet
+# loaded in #1.
+#
+# Now move inferior #1 forward until 'foo' is loaded, check the
+# breakpoint is no longer pending.
+#
+# Move inferior #1 forward more until 'foo' is unloaded, check that
+# the breakpoint returns to the pending state.
+proc_with_prefix test_pending_toggle { } {
+
+    do_test_setup "Break before open" "Break before close"
+
+    set bpnum [do_create_pending_foo_breakpoint]
+
+    # Now return to inferior 1 and continue until the shared library is
+    # loaded, the breakpoint should become non-pending.
+    gdb_test "inferior 1" "Switching to inferior 1 .*" \
+	"switch back to inferior 1"
+    gdb_continue_to_breakpoint "stop in foo in inferior 1" "foo \\(\\) .*"
+
+    gdb_test "info breakpoint $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex <foo\[^>\]*> inf 1" \
+	     "\\s+stop only in thread 1\\.1" \
+	     "\\s+breakpoint already hit 1 time"] \
+	"check thread-specific breakpoint is no longer pending"
+
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "close library"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	     "\\s+stop only in thread 1\\.1" \
+	     "\\s+breakpoint already hit 1 time"] \
+	"check thread-specific breakpoint is pending again"
+}
+
+# Create a Python variable VAR and set it to the gdb.Breakpoint object
+# corresponding to the breakpoint numbered BPNUM.  If THREAD is not
+# the empty string then THREAD should be an integer, check that
+# gdb.Breakpoint.thread is set to the value of THREAD.  Otherwise, if
+# THREAD is the empty string, check that gdb.Breakpoint.thread is set
+# to None.
+proc py_find_breakpoint { var bpnum {thread ""} } {
+    gdb_test_no_output \
+	"python ${var}=\[b for b in gdb.breakpoints() if b.number == $bpnum\]\[0\]" \
+	"find Python gdb.Breakpoint object"
+    if { $thread ne "" } {
+	gdb_test_no_output "python assert(${var}.thread == ${thread})" \
+	    "check thread attribute is currently correct"
+    } else {
+	gdb_test_no_output "python assert(${var}.thread is None)" \
+	    "check thread attribute is currently correct"
+    }
+}
+
+# Setup two inferiors.  In #1 the symbol 'foo' has not yet been
+# loaded, while in #2 the symbol 'foo' has been loaded.
+#
+# Create a thread-specific breakpoint on 'foo' tied to a thread in
+# inferior #1, the breakpoint should be pending -- 'foo' is not yet
+# loaded in #1.
+#
+# Use Python to change the thread of the thread-specific breakpoint to
+# a thread in inferior #2, at this point the thread should gain a
+# location and become non-pending.
+#
+# Set the thread back to a thread in inferior #1, the breakpoint
+# should return to the pending state.
+proc_with_prefix py_test_toggle_thread {} {
+    do_test_setup "Break before open" "Break after open"
+
+    set bpnum [do_create_pending_foo_breakpoint]
+
+    py_find_breakpoint "bp" $bpnum 1
+
+    gdb_test_no_output "python bp.thread = 2" \
+	"change thread on thread-specific breakpoint"
+    gdb_test "info breakpoint $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex <foo\[^>\]*> inf 2" \
+	     "\\s+stop only in thread 2\\.1"] \
+	"check thread-specific breakpoint now has a location"
+
+    gdb_test_no_output "set call_count = 2" "set call_count in inferior 2"
+    gdb_continue_to_breakpoint "stop at foo in inferior 2" "foo \\(\\) .*"
+
+    gdb_test_no_output "python bp.thread = 1" \
+	"restore thread on thread-specific breakpoint"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	     "\\s+stop only in thread 1\\.1" \
+	     "\\s+breakpoint already hit 1 time"] \
+	"check thread-specific breakpoint has returned to pending"
+
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "stop after close in inferior 2" \
+	".* Break after close\\. .*"
+
+    gdb_test "inferior 1" "Switching to inferior 1 .*" \
+	"switch to inferior 1"
+    gdb_continue_to_breakpoint "stop at foo in inferior 1" "foo \\(\\) .*"
+}
+
+# Setup two inferiors.  Both inferiors have the symbol 'foo'
+# available.
+#
+# Create a thread-specific breakpoint on 'foo' tied to a thread in
+# inferior #1, the breakpoint should not be pending, but will only
+# have a single location, the location in inferior #1.
+#
+# Use Python to change the thread of the thread-specific breakpoint to
+# None.  At this point the breakpoint should gain a second location, a
+# location in inferior #2.
+proc_with_prefix py_test_clear_thread {} {
+    do_test_setup "Break after open" "Break after open"
+
+    set bpnum [do_create_foo_breakpoint]
+
+    py_find_breakpoint "bp" $bpnum 1
+
+    gdb_test_no_output "python bp.thread = None" \
+	"clear thread on thread-specific breakpoint"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "${bpnum}\\s+breakpoint\\s+keep y\\s+<MULTIPLE>\\s*" \
+	     "${bpnum}\\.1\\s+y\\s+${::hex}\\s+<foo\[^>\]*> inf $::decimal" \
+	     "${bpnum}\\.2\\s+y\\s+${::hex}\\s+<foo\[^>\]*> inf $::decimal"] \
+	"check for a location in both inferiors"
+
+    gdb_continue_to_breakpoint "stop at foo in inferior 2" "foo \\(\\) .*"
+    gdb_test_no_output "set call_count = 2" "set call_count in inferior 2"
+
+    gdb_test "inferior 1" "Switching to inferior 1 .*" \
+	"switch to inferior 1"
+    gdb_continue_to_breakpoint "stop at foo in inferior 1" "foo \\(\\) .*"
+    gdb_test_no_output "set call_count = 2" "set call_count in inferior 1"
+
+    gdb_test_no_output "python bp.thread = 2"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "${bpnum}\\s+breakpoint\\s+keep y\\s+${::hex}\\s+<foo\[^>\]*> inf 2" \
+	     "\\s+stop only in thread 2\\.1" \
+	     "\\s+breakpoint already hit 2 times"] \
+	"check for a location only in inferior 2"
+
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "stop after close in inferior 1" \
+	".* Break after close\\. .*"
+
+    gdb_test "inferior 2" "Switching to inferior 2 .*" \
+	"switch back to inferior 2"
+    gdb_continue_to_breakpoint "stop at foo again in inferior 2" \
+	"foo \\(\\) .*"
+}
+
 # Run all the tests.
 test_no_inf_display
+test_pending_toggle
+py_test_toggle_thread
+py_test_clear_thread
diff --git a/gdb/testsuite/gdb.multi/tids.exp b/gdb/testsuite/gdb.multi/tids.exp
index 18fc4970fe7..34c270309de 100644
--- a/gdb/testsuite/gdb.multi/tids.exp
+++ b/gdb/testsuite/gdb.multi/tids.exp
@@ -433,11 +433,13 @@ if { [allow_python_tests] } {
 
 	gdb_py_test_silent_cmd "python bp = gdb.breakpoints()\[0\]" \
 	    "get python breakpoint" 0
-	gdb_test "python bp.thread = 6" "thread = 6" \
+	gdb_test_no_output "python bp.thread = 6" \
 	    "make breakpoint thread-specific with python"
 	# Check that the inferior-qualified ID is correct.
 	gdb_test "info breakpoint" \
-	    "stop only in thread 1.3\r\n.*" \
+	    [multi_line \
+		 "$decimal\\s+\[^\r\n\]+ in thread_function1 at \[^\r\n\]+" \
+		 "\\s+stop only in thread 1\\.3"] \
 	    "thread specific breakpoint right thread"
     }
 }
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv9 00/14] thread-specific breakpoints in just some inferiors
  2023-12-29  9:26             ` [PATCHv8 00/14] " Andrew Burgess
                                 ` (13 preceding siblings ...)
  2023-12-29  9:27               ` [PATCHv8 14/14] gdb: only insert thread-specific breakpoints in the relevant inferior Andrew Burgess
@ 2024-03-05 15:21               ` Andrew Burgess
  2024-03-05 15:21                 ` [PATCHv9 01/14] gdb: create_breakpoint: add asserts and additional comments Andrew Burgess
                                   ` (14 more replies)
  14 siblings, 15 replies; 138+ messages in thread
From: Andrew Burgess @ 2024-03-05 15:21 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

In v9:

  - Rebased onto current upstream/master branch,

  - Minor testsuite fix to account for updated output from GDB,

  - No other changes since v8.

In v8:

  - Rebased onto current upstream/master branch.

  - Reordered the patches a little.  Patches 0 to 8 are unchanged from
    previous.  If there's no objections then I'm planning to merge
    these some point soon as I think these are all good cleanup patches.

  - Patches 9, 10, and 11 are new.  These are also refactoring
    commits, but are all tied pretty tightly to what is now patch 12.

  - Patch 12 is the most important patch.  This has had a complete
    rewrite since V7 in order to address Tom's feedback.  The general
    idea is unchanged; the breakpoint condition string is parsed first
    forwards, and then backwards, but we now have a two phase
    analysis, rather than immediately parsing things like the
    thread-id as we find them.  This resolves this problem:

    (gdb) break some_function if ( 3 == thread )

    Previous GDB would try to match 'thread )' as a thread-id and give
    an error that ')' as invalid.  Now GDB correctly understands that
    the 'thread )' is likely part of the 'if' condition, and parses it
    as such.

  - Patches 13 and 14 are unchanged from V7.  These patches depend on
    the changes in patch 12 so can't be merged without that patch.

In v7:

  - Addressed all the issues except one that Baris pointed out, this
    includes typos, some minor testsuite cleanups, and reformatting an
    assert (but not changing the meaning).

  - As requested, switched to use std::string_view in
    break-parse-cond.c file instead of a custom class, I agree that
    this is an improvement.

  - I've not changed the handling of -force-condition flag.  I replied
    to the review email with my thoughts, TLDR: fixing this would be a
    bigger task which I'd rather leave for ... the future.

  - Rebased and retested.

In v6:

  - Rebased to current master, one minor fix due to the C++17 changes,
    nothing major.  Retested.

In v5:

  - Updates after Lancelot's feedback, including, -force-condition can
    no longer be abbreviated to '-', and can't be used immediately
    after the breakpoint condition.

  - More tests to check some of the edge cases.

In v4:

  - Big update, this series now handles thread-specific and
    inferior-specific breakpoints.

In v3:

  - Rebased on to current upstream/master, this includes all Simon's
    recent breakpoint changes.  Retested with no regressions seen.

In v2:

  - Rebased on current upstream/master and retested,

  - No changes to code or docs.

---

Andrew Burgess (14):
  gdb: create_breakpoint: add asserts and additional comments
  gdb: create_breakpoint: asserts relating to extra_string/parse_extra
  gdb: change 'if' to gdb_assert in update_dprintf_command_list
  gdb: the extra_string in a dprintf breakpoint is never nullptr
  gdb: build dprintf commands just once in code_breakpoint constructor
  gdb: don't display inferior list for pending breakpoints
  gdb: remove breakpoint_re_set_one
  gdb: remove tracepoint_probe_create_sals_from_location_spec
  gdb: make breakpoint_debug_printf global
  gdb: add another overload of startswith
  gdb: create new is_thread_id helper function
  gdb: parse pending breakpoint thread/task immediately
  gdb: don't set breakpoint::pspace in create_breakpoint
  gdb: only insert thread-specific breakpoints in the relevant inferior

 gdb/Makefile.in                               |   2 +
 gdb/NEWS                                      |  11 +
 gdb/ada-lang.c                                |   6 +-
 gdb/break-catch-throw.c                       |   6 +-
 gdb/break-cond-parse.c                        | 701 ++++++++++++++++
 gdb/break-cond-parse.h                        |  52 ++
 gdb/breakpoint.c                              | 773 ++++++++----------
 gdb/breakpoint.h                              | 109 ++-
 gdb/testsuite/gdb.ada/tasks.exp               |   6 +-
 gdb/testsuite/gdb.base/condbreak.exp          |  57 +-
 gdb/testsuite/gdb.base/pending.exp            |  23 +-
 gdb/testsuite/gdb.linespec/explicit.exp       |   4 +-
 gdb/testsuite/gdb.linespec/keywords.exp       |   8 +-
 gdb/testsuite/gdb.mi/mi-dprintf-pending.exp   |   3 +-
 gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp    |   8 +-
 .../gdb.mi/user-selected-context-sync.exp     |   4 +-
 .../gdb.multi/bp-thread-specific.exp          |   7 +-
 .../gdb.multi/inferior-specific-bp.exp        |  16 +-
 .../gdb.multi/multi-target-continue.exp       |   2 +-
 .../gdb.multi/multi-target-ping-pong-next.exp |   4 +-
 .../gdb.multi/pending-bp-del-inferior.c       |  28 +
 .../gdb.multi/pending-bp-del-inferior.exp     | 214 +++++
 gdb/testsuite/gdb.multi/pending-bp-lib.c      |  22 +
 gdb/testsuite/gdb.multi/pending-bp.c          |  66 ++
 gdb/testsuite/gdb.multi/pending-bp.exp        | 332 ++++++++
 gdb/testsuite/gdb.multi/tids.exp              |   6 +-
 .../gdb.threads/del-pending-thread-bp-lib.c   |  22 +
 .../gdb.threads/del-pending-thread-bp.c       |  85 ++
 .../gdb.threads/del-pending-thread-bp.exp     | 108 +++
 gdb/tid-parse.c                               |  82 +-
 gdb/tid-parse.h                               |   8 +
 gdbsupport/common-utils.h                     |  10 +
 32 files changed, 2279 insertions(+), 506 deletions(-)
 create mode 100644 gdb/break-cond-parse.c
 create mode 100644 gdb/break-cond-parse.h
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-del-inferior.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.exp
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.exp


base-commit: a7ea089b0bccb6379e079e2ab764c2012d94b472
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv9 01/14] gdb: create_breakpoint: add asserts and additional comments
  2024-03-05 15:21               ` [PATCHv9 00/14] thread-specific breakpoints in just some inferiors Andrew Burgess
@ 2024-03-05 15:21                 ` Andrew Burgess
  2024-03-31 10:26                   ` Andrew Burgess
  2024-03-05 15:21                 ` [PATCHv9 02/14] gdb: create_breakpoint: asserts relating to extra_string/parse_extra Andrew Burgess
                                   ` (13 subsequent siblings)
  14 siblings, 1 reply; 138+ messages in thread
From: Andrew Burgess @ 2024-03-05 15:21 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

This commit extends the asserts on create_breakpoint (in the header
file), and adds some additional assertions into the definition.

The new assert confirms that when the thread and inferior information
is going to be parsed from the extra_string, then the thread and
inferior arguments should be -1.  That is, the caller of
create_breakpoint should not try to create a thread/inferior specific
breakpoint by *both* specifying thread/inferior *and* asking to parse
the extra_string, it's one or the other.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c |  6 ++++++
 gdb/breakpoint.h | 16 ++++++++++++++++
 2 files changed, 22 insertions(+)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 102bd7fad41..7ade82663f9 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -9219,6 +9219,12 @@ create_breakpoint (struct gdbarch *gdbarch,
   gdb_assert (inferior == -1 || inferior > 0);
   gdb_assert (thread == -1 || inferior == -1);
 
+  /* If PARSE_EXTRA is true then the thread and inferior details will be
+     parsed from the EXTRA_STRING, the THREAD and INFERIOR arguments
+     should be -1.  */
+  gdb_assert (!parse_extra || thread == -1);
+  gdb_assert (!parse_extra || inferior == -1);
+
   gdb_assert (ops != NULL);
 
   /* If extra_string isn't useful, set it to NULL.  */
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index 226e4d06993..2e2fe1d32e5 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -1610,6 +1610,22 @@ enum breakpoint_create_flags
    the FORCE_CONDITION parameter is ignored and the corresponding argument
    is parsed from EXTRA_STRING.
 
+   The THREAD should be a global thread number, the created breakpoint will
+   only apply for that thread.  If the breakpoint should apply for all
+   threads then pass -1.  However, if PARSE_EXTRA is non-zero then the
+   THREAD parameter is ignored and an optional thread number will be parsed
+   from EXTRA_STRING.
+
+   The INFERIOR should be a global inferior number, the created breakpoint
+   will only apply for that inferior.  If the breakpoint should apply for
+   all inferiors then pass -1.  However, if PARSE_EXTRA is non-zero then
+   the INFERIOR parameter is ignored and an optional inferior number will
+   be parsed from EXTRA_STRING.
+
+   At most one of THREAD and INFERIOR should be set to a value other than
+   -1; breakpoints can be thread specific, or inferior specific, but not
+   both.
+
    If INTERNAL is non-zero, the breakpoint number will be allocated
    from the internal breakpoint count.
 
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv9 02/14] gdb: create_breakpoint: asserts relating to extra_string/parse_extra
  2024-03-05 15:21               ` [PATCHv9 00/14] thread-specific breakpoints in just some inferiors Andrew Burgess
  2024-03-05 15:21                 ` [PATCHv9 01/14] gdb: create_breakpoint: add asserts and additional comments Andrew Burgess
@ 2024-03-05 15:21                 ` Andrew Burgess
  2024-03-31 10:26                   ` Andrew Burgess
  2024-03-05 15:21                 ` [PATCHv9 03/14] gdb: change 'if' to gdb_assert in update_dprintf_command_list Andrew Burgess
                                   ` (12 subsequent siblings)
  14 siblings, 1 reply; 138+ messages in thread
From: Andrew Burgess @ 2024-03-05 15:21 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

The goal of this commit is to better define the API for
create_breakpoint especially around the use of extra_string and
parse_extra.  This will be useful in the next commit when I plan to
make some changes to create_breakpoint.

This commit makes one possibly breaking change: until this commit it
was possible to create thread-specific dprintf breakpoint like this:

  (gdb) dprintf call_me, thread 1 "%s", "hello"
  Dprintf 2 at 0x401152: file /tmp/hello.c, line 8.
  (gdb) info breakpoints
  Num     Type           Disp Enb Address            What
  2       dprintf        keep y   0x0000000000401152 in call_me at /tmp/hello.c:8 thread 1
          stop only in thread 1
          printf "%s", "hello"
  (gdb)

This feature of dprintf was not documented, was not tested, and is
slightly different in syntax to how we create thread specific
breakpoints and/or watchpoints -- the thread condition appears after
the first ','.

I believe that this worked at all was simply by luck.  We happen to
pass the parse_extra flag as true from dprintf_command to
create_breakpoint.

So in this commit I made the choice change this.  We now pass
parse_extra as false from dprintf_command to create_breakpoint.  With
this done it is assumed that the only thing in the extra_string is the
dprintf format and arguments.

Beyond this change I've updated the comment on create_breakpoint in
breakpoint.h, and I've then added some asserts into
create_breakpoint as well as moving around some of the error
handling.

 - We now assert on the incoming argument values,

 - I've moved an error check to sit after the call to
   find_condition_and_thread_for_sals, this ensures the extra_string
   was parsed correctly,

In dprintf_command:

 - We now throw an error if there is no format string after the
   dprintf location.  This error was already being thrown, but was
   being caught later in the process.  With this change we catch the
   missing string earlier,

 - And, as mentioned earlier, we pass parse_extra as false when
   calling create_breakpoint,

In create_tracepoint_from_upload:

 - We now throw an error if the parsed location doesn't completely
   consume the addr_str variable.  This error has now effectively
   moved out of create_breakpoint.
---
 gdb/breakpoint.c | 41 ++++++++++++++++++++++++++++-------------
 gdb/breakpoint.h | 44 +++++++++++++++++++++++++++-----------------
 2 files changed, 55 insertions(+), 30 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 7ade82663f9..0482064d057 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -9231,6 +9231,16 @@ create_breakpoint (struct gdbarch *gdbarch,
   if (extra_string != NULL && *extra_string == '\0')
     extra_string = NULL;
 
+  /* A bp_dprintf must always have an accompanying EXTRA_STRING containing
+     the dprintf format and arguments -- PARSE_EXTRA should always be false
+     in this case.
+
+     For all other breakpoint types, EXTRA_STRING should be nullptr unless
+     PARSE_EXTRA is true.  */
+  gdb_assert ((type_wanted == bp_dprintf)
+	      ? (extra_string != nullptr && !parse_extra)
+	      : (extra_string == nullptr || parse_extra));
+
   try
     {
       ops->create_sals_from_location_spec (locspec, &canonical);
@@ -9294,6 +9304,8 @@ create_breakpoint (struct gdbarch *gdbarch,
 
       if (parse_extra)
 	{
+	  gdb_assert (type_wanted != bp_dprintf);
+
 	  gdb::unique_xmalloc_ptr<char> rest;
 	  gdb::unique_xmalloc_ptr<char> cond;
 
@@ -9302,15 +9314,15 @@ create_breakpoint (struct gdbarch *gdbarch,
 	  find_condition_and_thread_for_sals (lsal.sals, extra_string,
 					      &cond, &thread, &inferior,
 					      &task, &rest);
+
+	  if (rest.get () != nullptr && *(rest.get ()) != '\0')
+	    error (_("Garbage '%s' at end of command"), rest.get ());
+
 	  cond_string_copy = std::move (cond);
 	  extra_string_copy = std::move (rest);
 	}
       else
 	{
-	  if (type_wanted != bp_dprintf
-	      && extra_string != NULL && *extra_string != '\0')
-		error (_("Garbage '%s' at end of location"), extra_string);
-
 	  /* Check the validity of the condition.  We should error out
 	     if the condition is invalid at all of the locations and
 	     if it is not forced.  In the PARSE_EXTRA case above, this
@@ -9521,21 +9533,18 @@ dprintf_command (const char *arg, int from_tty)
 
   /* If non-NULL, ARG should have been advanced past the location;
      the next character must be ','.  */
-  if (arg != NULL)
+  if (arg == nullptr || arg[0] != ',' || arg[1] == '\0')
+    error (_("Format string required"));
+  else
     {
-      if (arg[0] != ',' || arg[1] == '\0')
-	error (_("Format string required"));
-      else
-	{
-	  /* Skip the comma.  */
-	  ++arg;
-	}
+      /* Skip the comma.  */
+      ++arg;
     }
 
   create_breakpoint (get_current_arch (),
 		     locspec.get (),
 		     NULL, -1, -1,
-		     arg, false, 1 /* parse arg */,
+		     arg, false, 0 /* parse arg */,
 		     0, bp_dprintf,
 		     0 /* Ignore count */,
 		     pending_break_support,
@@ -14141,6 +14150,12 @@ create_tracepoint_from_upload (struct uploaded_tp *utp)
 
   location_spec_up locspec = string_to_location_spec (&addr_str,
 						      current_language);
+
+
+  gdb_assert (addr_str != nullptr);
+  if (*addr_str != '\0')
+    error (_("Garbage '%s' at end of location"), addr_str);
+
   if (!create_breakpoint (get_current_arch (),
 			  locspec.get (),
 			  utp->cond_string.get (), -1, -1, addr_str,
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index 2e2fe1d32e5..6da04d5ec00 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -1595,32 +1595,42 @@ enum breakpoint_create_flags
    functions for setting a breakpoint at LOCSPEC.
 
    This function has two major modes of operations, selected by the
-   PARSE_EXTRA parameter.
+   PARSE_EXTRA and WANTED_TYPE parameters.
 
-   If PARSE_EXTRA is zero, LOCSPEC is just the breakpoint's location
-   spec, with condition, thread, and extra string specified by the
-   COND_STRING, THREAD, and EXTRA_STRING parameters.
+   When WANTED_TYPE is not bp_dprintf the following rules apply:
 
-   If PARSE_EXTRA is non-zero, this function will attempt to extract
-   the condition, thread, and extra string from EXTRA_STRING, ignoring
-   the similarly named parameters.
+     If PARSE_EXTRA is zero, LOCSPEC is just the breakpoint's location
+     spec, with condition, thread, and extra string specified by the
+     COND_STRING, THREAD, and EXTRA_STRING parameters.
 
-   If FORCE_CONDITION is true, the condition is accepted even when it is
-   invalid at all of the locations.  However, if PARSE_EXTRA is non-zero,
-   the FORCE_CONDITION parameter is ignored and the corresponding argument
-   is parsed from EXTRA_STRING.
+     If PARSE_EXTRA is non-zero, this function will attempt to extract the
+     condition, thread, and extra string from EXTRA_STRING, ignoring the
+     similarly named parameters.
+
+   When WANTED_TYPE is bp_dprintf the following rules apply:
+
+     PARSE_EXTRA must always be zero, LOCSPEC is just the breakpoint's
+     location spec, with condition, thread, and extra string (which
+     contains the dprintf format and arguments) specified by the
+     COND_STRING, THREAD, and EXTRA_STRING parameters.
+
+   If FORCE_CONDITION is true, the condition (in COND_STRING) is accepted
+   even when it is invalid at all of the locations.  However, if
+   PARSE_EXTRA is non-zero and WANTED_TYPE is not bp_dprintf, the
+   FORCE_CONDITION parameter is ignored and the corresponding argument is
+   parsed from EXTRA_STRING.
 
    The THREAD should be a global thread number, the created breakpoint will
    only apply for that thread.  If the breakpoint should apply for all
-   threads then pass -1.  However, if PARSE_EXTRA is non-zero then the
-   THREAD parameter is ignored and an optional thread number will be parsed
-   from EXTRA_STRING.
+   threads then pass -1.  However, if PARSE_EXTRA is non-zero and
+   WANTED_TYPE is not bp_dprintf, then the THREAD parameter is ignored and
+   an optional thread number will be parsed from EXTRA_STRING.
 
    The INFERIOR should be a global inferior number, the created breakpoint
    will only apply for that inferior.  If the breakpoint should apply for
-   all inferiors then pass -1.  However, if PARSE_EXTRA is non-zero then
-   the INFERIOR parameter is ignored and an optional inferior number will
-   be parsed from EXTRA_STRING.
+   all inferiors then pass -1.  However, if PARSE_EXTRA is non-zero and
+   WANTED_TYPE is not bp_dprintf, then the INFERIOR parameter is ignored
+   and an optional inferior number will be parsed from EXTRA_STRING.
 
    At most one of THREAD and INFERIOR should be set to a value other than
    -1; breakpoints can be thread specific, or inferior specific, but not
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv9 03/14] gdb: change 'if' to gdb_assert in update_dprintf_command_list
  2024-03-05 15:21               ` [PATCHv9 00/14] thread-specific breakpoints in just some inferiors Andrew Burgess
  2024-03-05 15:21                 ` [PATCHv9 01/14] gdb: create_breakpoint: add asserts and additional comments Andrew Burgess
  2024-03-05 15:21                 ` [PATCHv9 02/14] gdb: create_breakpoint: asserts relating to extra_string/parse_extra Andrew Burgess
@ 2024-03-05 15:21                 ` Andrew Burgess
  2024-03-31 10:27                   ` Andrew Burgess
  2024-03-05 15:21                 ` [PATCHv9 04/14] gdb: the extra_string in a dprintf breakpoint is never nullptr Andrew Burgess
                                   ` (11 subsequent siblings)
  14 siblings, 1 reply; 138+ messages in thread
From: Andrew Burgess @ 2024-03-05 15:21 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

I noticed in update_dprintf_command_list that we handle the case where
the bp_dprintf style breakpoint doesn't have a format and args string.

However, I don't believe such a situation is possible.  The obvious
approach certainly already catches this case:

  (gdb) dprintf main
  Format string required

If it is possible to create a dprintf breakpoint without a format and
args string then I think we should be catching this case and handling
it at creation time, rather than having GDB just ignore the situation
later on.

And so, I propose that we change the 'if' that ignores the case where
the format/args string is empty, and instead assert that we do always
have a format/args string.  The original code, that handled an empty
format/args string has existed since commit e7e0cddfb0d4, which is
when dprintf support was added to GDB.

If I'm correct and this situation can't ever happen then there should
be no user visible changes after this commit.
---
 gdb/breakpoint.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 0482064d057..a7b516ab26c 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -8528,8 +8528,9 @@ update_dprintf_command_list (struct breakpoint *b)
   const char *dprintf_args = b->extra_string.get ();
   gdb::unique_xmalloc_ptr<char> printf_line = nullptr;
 
-  if (!dprintf_args)
-    return;
+  /* Trying to create a dprintf breakpoint without a format and args
+     string should be detected at creation time.  */
+  gdb_assert (dprintf_args != nullptr);
 
   dprintf_args = skip_spaces (dprintf_args);
 
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv9 04/14] gdb: the extra_string in a dprintf breakpoint is never nullptr
  2024-03-05 15:21               ` [PATCHv9 00/14] thread-specific breakpoints in just some inferiors Andrew Burgess
                                   ` (2 preceding siblings ...)
  2024-03-05 15:21                 ` [PATCHv9 03/14] gdb: change 'if' to gdb_assert in update_dprintf_command_list Andrew Burgess
@ 2024-03-05 15:21                 ` Andrew Burgess
  2024-03-31 10:27                   ` Andrew Burgess
  2024-03-05 15:21                 ` [PATCHv9 05/14] gdb: build dprintf commands just once in code_breakpoint constructor Andrew Burgess
                                   ` (10 subsequent siblings)
  14 siblings, 1 reply; 138+ messages in thread
From: Andrew Burgess @ 2024-03-05 15:21 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Given the changes in the previous couple of commits, this commit
cleans up some of the asserts and 'if' checks related to the
extra_string within a dprintf breakpoint.

This commit:

  1. Adds some asserts to update_dprintf_command_list about the
  breakpoint type, and that the extra_string is not nullptr,

  2. Given that we know extra_string is not nullptr (this is enforced
  when the breakpoint is created), we can simplify
  code_breakpoint::code_breakpoint -- it no longer needs to check for
  the extra_string is nullptr case,

  3. In dprintf_breakpoint::re_set we can remove the assert (this will
  be checked within update_dprintf_command_list, we can also remove
  the redundant 'if' check.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c | 16 +++++-----------
 1 file changed, 5 insertions(+), 11 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index a7b516ab26c..437dd082fde 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -8525,6 +8525,9 @@ bp_loc_is_permanent (struct bp_location *loc)
 static void
 update_dprintf_command_list (struct breakpoint *b)
 {
+  gdb_assert (b->type == bp_dprintf);
+  gdb_assert (b->extra_string != nullptr);
+
   const char *dprintf_args = b->extra_string.get ();
   gdb::unique_xmalloc_ptr<char> printf_line = nullptr;
 
@@ -8698,12 +8701,7 @@ code_breakpoint::code_breakpoint (struct gdbarch *gdbarch_,
       /* Dynamic printf requires and uses additional arguments on the
 	 command line, otherwise it's an error.  */
       if (type == bp_dprintf)
-	{
-	  if (extra_string != nullptr)
-	    update_dprintf_command_list (this);
-	  else
-	    error (_("Format string required"));
-	}
+	update_dprintf_command_list (this);
       else if (extra_string != nullptr)
 	error (_("Garbage '%s' at end of command"), extra_string.get ());
     }
@@ -12419,9 +12417,6 @@ dprintf_breakpoint::re_set ()
 {
   re_set_default ();
 
-  /* extra_string should never be non-NULL for dprintf.  */
-  gdb_assert (extra_string != NULL);
-
   /* 1 - connect to target 1, that can run breakpoint commands.
      2 - create a dprintf, which resolves fine.
      3 - disconnect from target 1
@@ -12432,8 +12427,7 @@ dprintf_breakpoint::re_set ()
      answers for target_can_run_breakpoint_commands().
      Given absence of finer grained resetting, we get to do
      it all the time.  */
-  if (extra_string != NULL)
-    update_dprintf_command_list (this);
+  update_dprintf_command_list (this);
 }
 
 /* Implement the "print_recreate" method for dprintf.  */
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv9 05/14] gdb: build dprintf commands just once in code_breakpoint constructor
  2024-03-05 15:21               ` [PATCHv9 00/14] thread-specific breakpoints in just some inferiors Andrew Burgess
                                   ` (3 preceding siblings ...)
  2024-03-05 15:21                 ` [PATCHv9 04/14] gdb: the extra_string in a dprintf breakpoint is never nullptr Andrew Burgess
@ 2024-03-05 15:21                 ` Andrew Burgess
  2024-03-31 10:27                   ` Andrew Burgess
  2024-03-05 15:21                 ` [PATCHv9 06/14] gdb: don't display inferior list for pending breakpoints Andrew Burgess
                                   ` (9 subsequent siblings)
  14 siblings, 1 reply; 138+ messages in thread
From: Andrew Burgess @ 2024-03-05 15:21 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

I noticed in code_breakpoint::code_breakpoint that we are calling
update_dprintf_command_list once for each breakpoint location, when we
really only need to call this once per breakpoint -- the data updated
by this function, the breakpoint command list -- is per breakpoint,
not per breakpoint location.  Calling update_dprintf_command_list
multiple times is just wasted effort, there's no per location error
checking, we don't even pass the current location to the function.

This commit moves the update_dprintf_command_list call outside of the
per-location loop.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c | 14 +++++++-------
 1 file changed, 7 insertions(+), 7 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 437dd082fde..c9023a13d6c 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -8697,15 +8697,15 @@ code_breakpoint::code_breakpoint (struct gdbarch *gdbarch_,
       /* Do not set breakpoint locations conditions yet.  As locations
 	 are inserted, they get sorted based on their addresses.  Let
 	 the list stabilize to have reliable location numbers.  */
-
-      /* Dynamic printf requires and uses additional arguments on the
-	 command line, otherwise it's an error.  */
-      if (type == bp_dprintf)
-	update_dprintf_command_list (this);
-      else if (extra_string != nullptr)
-	error (_("Garbage '%s' at end of command"), extra_string.get ());
     }
 
+  /* Dynamic printf requires and uses additional arguments on the
+     command line, otherwise it's an error.  */
+  if (type == bp_dprintf)
+    update_dprintf_command_list (this);
+  else if (extra_string != nullptr)
+    error (_("Garbage '%s' at end of command"), extra_string.get ());
+
   /* The order of the locations is now stable.  Set the location
      condition using the location's number.  */
   int loc_num = 1;
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv9 06/14] gdb: don't display inferior list for pending breakpoints
  2024-03-05 15:21               ` [PATCHv9 00/14] thread-specific breakpoints in just some inferiors Andrew Burgess
                                   ` (4 preceding siblings ...)
  2024-03-05 15:21                 ` [PATCHv9 05/14] gdb: build dprintf commands just once in code_breakpoint constructor Andrew Burgess
@ 2024-03-05 15:21                 ` Andrew Burgess
  2024-03-05 15:21                 ` [PATCHv9 07/14] gdb: remove breakpoint_re_set_one Andrew Burgess
                                   ` (8 subsequent siblings)
  14 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2024-03-05 15:21 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

I noticed that in the 'info breakpoints' output, GDB sometimes prints
the inferior list for pending breakpoints, this doesn't seem right to
me.  A pending breakpoint has no locations (at least, as far as we
display things in the 'info breakpoints' output), so including an
inferior list seems odd.

Here's what I see right now:

  (gdb) info breakpoint 5
  Num     Type           Disp Enb Address            What
  5       breakpoint     keep y   <PENDING>          foo inf 1
  (gdb)

It's the 'inf 1' at the end of the line that I'm objecting too.

To trigger this behaviour we need to be in a multi-inferior debug
session.  The breakpoint must have been non-pending at some point in
the past, and so have a location assigned to it.

The breakpoint becomes pending again as a result of a shared library
being unloaded.  When this happens the location itself is marked
pending (via bp_location::shlib_disabled).

In print_one_breakpoint_location, in order to print the inferior list
we check that the breakpoint has a location, and that we have multiple
inferiors, but we don't check if the location itself is pending.

This commit adds that check, which means the output is now:

  (gdb) info breakpoint 5
  Num     Type           Disp Enb Address            What
  5       breakpoint     keep y   <PENDING>          foo
  (gdb)

Which I think makes more sense -- indeed, the format without the
inferior list is what we display for a pending breakpoint that has
never had any locations assigned, so I think this change in behaviour
makes GDB more consistent.
---
 gdb/breakpoint.c                         |   2 +-
 gdb/testsuite/gdb.multi/pending-bp-lib.c |  22 ++++
 gdb/testsuite/gdb.multi/pending-bp.c     |  66 ++++++++++++
 gdb/testsuite/gdb.multi/pending-bp.exp   | 126 +++++++++++++++++++++++
 4 files changed, 215 insertions(+), 1 deletion(-)
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.exp

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index c9023a13d6c..aae1b932a5d 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -6587,7 +6587,7 @@ print_one_breakpoint_location (struct breakpoint *b,
 	}
     }
 
-  if (loc != NULL && !header_of_multiple)
+  if (loc != nullptr && !header_of_multiple && !loc->shlib_disabled)
     {
       std::vector<int> inf_nums;
       int mi_only = 1;
diff --git a/gdb/testsuite/gdb.multi/pending-bp-lib.c b/gdb/testsuite/gdb.multi/pending-bp-lib.c
new file mode 100644
index 00000000000..15d1b9833dd
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp-lib.c
@@ -0,0 +1,22 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+int global_var = 0;
+
+void
+foo (int arg)
+{
+  global_var = arg;
+}
diff --git a/gdb/testsuite/gdb.multi/pending-bp.c b/gdb/testsuite/gdb.multi/pending-bp.c
new file mode 100644
index 00000000000..879e0b11ac7
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp.c
@@ -0,0 +1,66 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#include <dlfcn.h>
+#include <stdlib.h>
+
+void
+breakpt (void)
+{
+  /* Nothing.  */
+}
+
+volatile int global_counter = 0;
+
+volatile int call_count = 1;
+
+int
+main (void)
+{
+  void *handle;
+  void (*func)(int);
+
+  /* Some filler work so that we don't initially stop on the breakpt call
+     below.  */
+  ++global_counter;
+
+  breakpt ();	/* Break before open.  */
+
+  /* Now load the shared library.  */
+  handle = dlopen (SHLIB_NAME, RTLD_LAZY);
+  if (handle == NULL)
+    abort ();
+
+  breakpt ();	/* Break after open.  */
+
+  /* Find the function symbol.  */
+  func = (void (*)(int)) dlsym (handle, "foo");
+
+  for (; call_count > 0; --call_count)
+    {
+      /* Call the library function.  */
+      func (1);
+    }
+
+  breakpt ();	/* Break before close.  */
+
+  /* Unload the shared library.  */
+  if (dlclose (handle) != 0)
+    abort ();
+
+  breakpt ();	/* Break after close.  */
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.multi/pending-bp.exp b/gdb/testsuite/gdb.multi/pending-bp.exp
new file mode 100644
index 00000000000..478d8d7c037
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp.exp
@@ -0,0 +1,126 @@
+# Copyright 2023 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+# Tests related to pending breakpoints in a multi-inferior environment.
+
+require allow_shlib_tests !use_gdb_stub
+
+standard_testfile
+
+set libname $testfile-lib
+set srcfile_lib $srcdir/$subdir/$libname.c
+set binfile_lib [standard_output_file $libname.so]
+
+if { [gdb_compile_shlib $srcfile_lib $binfile_lib {}] != "" } {
+    untested "failed to compile shared library 1"
+    return -1
+}
+
+set binfile_lib_target [gdb_download_shlib $binfile_lib]
+
+if { [build_executable "failed to prepare" $testfile $srcfile \
+	  [list debug \
+	       additional_flags=-DSHLIB_NAME=\"$binfile_lib_target\" \
+	       shlib_load]] } {
+    return -1
+}
+
+# Start two inferiors, both running the same test binary.  The arguments
+# INF_1_STOP and INF_2_STOP are source code patterns that are passed to
+# gdb_get_line_number to figure out where each inferior should be stopped.
+#
+# This proc does a clean_restart and leaves inferior 2 selected.  Also the
+# 'breakpoint pending' flag is enabled, so pending breakpoints can be created
+# without GDB prompting the user.
+proc do_test_setup { inf_1_stop inf_2_stop } {
+    clean_restart ${::binfile}
+
+    gdb_locate_shlib $::binfile_lib
+
+    if {![runto_main]} {
+	return false
+    }
+
+    gdb_breakpoint [gdb_get_line_number ${inf_1_stop}] temporary
+    gdb_continue_to_breakpoint "move inferior 1 into position"
+
+    gdb_test "add-inferior -exec ${::binfile}" \
+	"Added inferior 2.*" "add inferior 2"
+    gdb_test "inferior 2" "Switching to inferior 2 .*" "switch to inferior 2"
+
+    if {![runto_main]} {
+	return false
+    }
+
+    gdb_breakpoint [gdb_get_line_number ${inf_2_stop}] temporary
+    gdb_continue_to_breakpoint "move inferior 2 into position"
+
+    gdb_test_no_output "set breakpoint pending on"
+
+    return true
+}
+
+# Check that when a breakpoint is in the pending state, but that breakpoint
+# does have some locations (those locations themselves are pending), GDB
+# doesn't display the inferior list in the 'info breakpoints' output.
+proc_with_prefix test_no_inf_display {} {
+    do_test_setup "Break before open" "Break before open"
+
+    # Create a breakpoint on 'foo'.  As the shared library (that
+    # contains foo) has not been loaded into any inferior yet, then
+    # there will be no locations and the breakpoint will be created
+    # pending.  Pass the 'allow-pending' flag so the gdb_breakpoint
+    # correctly expects the new breakpoint to be pending.
+    gdb_breakpoint "foo" allow-pending
+    set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+		   "get foo breakpoint number"]
+
+    # Check the 'info breakpoints' output; the breakpoint is pending with
+    # no 'inf X' appearing at the end of the line.
+    gdb_test "info breakpoint $bpnum" \
+	"$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	"check info bp before locations have been created"
+
+    # Now select inferior 1 and allow the inferior to run forward to the
+    # point where a breakpoint location for foo will have been created.
+    gdb_test "inferior 1" "Switching to inferior 1 .*"
+    gdb_breakpoint [gdb_get_line_number "Break after open"] temporary
+    gdb_continue_to_breakpoint \
+	"move inferior 1 until a location has been added"
+
+    # Check the 'info breakpoints' output.  Notice we display the inferior
+    # list at the end of the breakpoint line.
+    gdb_test "info breakpoint $bpnum" \
+	"$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex\\s+<foo\[^>\]*>\\s+inf 1" \
+	"check info breakpoints while breakpoint is inserted"
+
+    # Continue inferior 1 until the shared library has been unloaded.  The
+    # breakpoint on 'foo' will return to the pending state.  We will need to
+    # 'continue' twice as the first time will hit the 'foo' breakpoint.
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "hit the breakpoint in foo"
+    gdb_continue_to_breakpoint "after close library"
+
+    # Check the 'info breakpoints' output, check there is no 'inf 1' at the
+    # end of the breakpoint line.
+    gdb_test "info breakpoint $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	     "\\s+breakpoint already hit 1 time"] \
+	"check info breakpoints while breakpoint is pending"
+}
+
+# Run all the tests.
+test_no_inf_display
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv9 07/14] gdb: remove breakpoint_re_set_one
  2024-03-05 15:21               ` [PATCHv9 00/14] thread-specific breakpoints in just some inferiors Andrew Burgess
                                   ` (5 preceding siblings ...)
  2024-03-05 15:21                 ` [PATCHv9 06/14] gdb: don't display inferior list for pending breakpoints Andrew Burgess
@ 2024-03-05 15:21                 ` Andrew Burgess
  2024-03-05 15:21                 ` [PATCHv9 08/14] gdb: remove tracepoint_probe_create_sals_from_location_spec Andrew Burgess
                                   ` (7 subsequent siblings)
  14 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2024-03-05 15:21 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

During a later patch I wanted to reset a single breakpoint, so I
called breakpoint_re_set_one.  However, this is not the right thing to
do.  If we look at breakpoint_re_set then we see that there's a whole
bunch of state that needs to be preserved prior to calling
breakpoint_re_set_one, and after calling breakpoint_re_set_one we
still need to call update_global_location_list.

I could just update the comment on breakpoint_re_set_one to make it
clearer how the function should be used -- or more likely to warn that
the function should only be used as a helper from breakpoint_re_set.

However, breakpoint_re_set_one is only 3 lines long.  So I figure it
might actually be easier to just fold breakpoint_re_set_one into
breakpoint_re_set, then there's no risk of accidentally calling
breakpoint_re_set_one when we shouldn't.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c | 26 ++++++++------------------
 1 file changed, 8 insertions(+), 18 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index aae1b932a5d..5e97d27bbf5 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -13210,17 +13210,6 @@ create_sals_from_location_spec_default (location_spec *locspec,
   parse_breakpoint_sals (locspec, canonical);
 }
 
-/* Reset a breakpoint.  */
-
-static void
-breakpoint_re_set_one (breakpoint *b)
-{
-  input_radix = b->input_radix;
-  set_language (b->language);
-
-  b->re_set ();
-}
-
 /* Re-set breakpoint locations for the current program space.
    Locations bound to other program spaces are left untouched.  */
 
@@ -13232,12 +13221,11 @@ breakpoint_re_set (void)
     scoped_restore save_input_radix = make_scoped_restore (&input_radix);
     scoped_restore_current_pspace_and_thread restore_pspace_thread;
 
-    /* breakpoint_re_set_one sets the current_language to the language
-       of the breakpoint it is resetting (see prepare_re_set_context)
-       before re-evaluating the breakpoint's location.  This change can
-       unfortunately get undone by accident if the language_mode is set
-       to auto, and we either switch frames, or more likely in this context,
-       we select the current frame.
+    /* To ::re_set each breakpoint we set the current_language to the
+       language of the breakpoint before re-evaluating the breakpoint's
+       location.  This change can unfortunately get undone by accident if
+       the language_mode is set to auto, and we either switch frames, or
+       more likely in this context, we select the current frame.
 
        We prevent this by temporarily turning the language_mode to
        language_mode_manual.  We restore it once all breakpoints
@@ -13254,7 +13242,9 @@ breakpoint_re_set (void)
       {
 	try
 	  {
-	    breakpoint_re_set_one (&b);
+	    input_radix = b.input_radix;
+	    set_language (b.language);
+	    b.re_set ();
 	  }
 	catch (const gdb_exception &ex)
 	  {
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv9 08/14] gdb: remove tracepoint_probe_create_sals_from_location_spec
  2024-03-05 15:21               ` [PATCHv9 00/14] thread-specific breakpoints in just some inferiors Andrew Burgess
                                   ` (6 preceding siblings ...)
  2024-03-05 15:21                 ` [PATCHv9 07/14] gdb: remove breakpoint_re_set_one Andrew Burgess
@ 2024-03-05 15:21                 ` Andrew Burgess
  2024-03-05 15:21                 ` [PATCHv9 09/14] gdb: make breakpoint_debug_printf global Andrew Burgess
                                   ` (6 subsequent siblings)
  14 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2024-03-05 15:21 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

The tracepoint_probe_create_sals_from_location_spec function just
forwards all its arguments to
bkpt_probe_create_sals_from_location_spec, and is only used in one
place.

Lets delete tracepoint_probe_create_sals_from_location_spec and
replace it with bkpt_probe_create_sals_from_location_spec.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c | 19 +++----------------
 1 file changed, 3 insertions(+), 16 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 5e97d27bbf5..bf7c0dc042b 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -283,9 +283,6 @@ static bool strace_marker_p (struct breakpoint *b);
 static void bkpt_probe_create_sals_from_location_spec
      (location_spec *locspec,
       struct linespec_result *canonical);
-static void tracepoint_probe_create_sals_from_location_spec
-     (location_spec *locspec,
-      struct linespec_result *canonical);
 
 const struct breakpoint_ops code_breakpoint_ops =
 {
@@ -300,10 +297,11 @@ static const struct breakpoint_ops bkpt_probe_breakpoint_ops =
   create_breakpoints_sal,
 };
 
-/* Tracepoints set on probes.  */
+/* Tracepoints set on probes.  We use the same methods as for breakpoints
+   on probes.  */
 static const struct breakpoint_ops tracepoint_probe_breakpoint_ops =
 {
-  tracepoint_probe_create_sals_from_location_spec,
+  bkpt_probe_create_sals_from_location_spec,
   create_breakpoints_sal,
 };
 
@@ -12401,17 +12399,6 @@ tracepoint::print_recreate (struct ui_file *fp) const
     gdb_printf (fp, "  passcount %d\n", pass_count);
 }
 
-/* Virtual table for tracepoints on static probes.  */
-
-static void
-tracepoint_probe_create_sals_from_location_spec
-  (location_spec *locspec,
-   struct linespec_result *canonical)
-{
-  /* We use the same method for breakpoint on probes.  */
-  bkpt_probe_create_sals_from_location_spec (locspec, canonical);
-}
-
 void
 dprintf_breakpoint::re_set ()
 {
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv9 09/14] gdb: make breakpoint_debug_printf global
  2024-03-05 15:21               ` [PATCHv9 00/14] thread-specific breakpoints in just some inferiors Andrew Burgess
                                   ` (7 preceding siblings ...)
  2024-03-05 15:21                 ` [PATCHv9 08/14] gdb: remove tracepoint_probe_create_sals_from_location_spec Andrew Burgess
@ 2024-03-05 15:21                 ` Andrew Burgess
  2024-03-05 15:21                 ` [PATCHv9 10/14] gdb: add another overload of startswith Andrew Burgess
                                   ` (5 subsequent siblings)
  14 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2024-03-05 15:21 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

This commit makes breakpoint_debug_printf available outside of
breakpoint.c.  In a later commit I'll want to use this macro from
another file.

This is just a refactor, there should be no user visible changes after
this commit.
---
 gdb/breakpoint.c | 9 ++-------
 gdb/breakpoint.h | 8 ++++++++
 2 files changed, 10 insertions(+), 7 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index bf7c0dc042b..d940786e6d3 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -574,13 +574,8 @@ show_always_inserted_mode (struct ui_file *file, int from_tty,
 	      value);
 }
 
-/* True if breakpoint debug output is enabled.  */
-static bool debug_breakpoint = false;
-
-/* Print a "breakpoint" debug statement.  */
-#define breakpoint_debug_printf(fmt, ...) \
-  debug_prefixed_printf_cond (debug_breakpoint, "breakpoint", fmt, \
-			      ##__VA_ARGS__)
+/* See breakpoint.h.  */
+bool debug_breakpoint = false;
 
 /* "show debug breakpoint" implementation.  */
 static void
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index 6da04d5ec00..24aeaf926ec 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -48,6 +48,14 @@ struct linespec_result;
 struct linespec_sals;
 struct inferior;
 
+/* True if breakpoint debug output is enabled.  */
+extern bool debug_breakpoint;
+
+/* Print a "breakpoint" debug statement.  */
+#define breakpoint_debug_printf(fmt, ...) \
+  debug_prefixed_printf_cond (debug_breakpoint, "breakpoint", fmt, \
+			      ##__VA_ARGS__)
+
 /* Enum for exception-handling support in 'catch throw', 'catch rethrow',
    'catch catch' and the MI equivalent.  */
 
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv9 10/14] gdb: add another overload of startswith
  2024-03-05 15:21               ` [PATCHv9 00/14] thread-specific breakpoints in just some inferiors Andrew Burgess
                                   ` (8 preceding siblings ...)
  2024-03-05 15:21                 ` [PATCHv9 09/14] gdb: make breakpoint_debug_printf global Andrew Burgess
@ 2024-03-05 15:21                 ` Andrew Burgess
  2024-03-05 15:21                 ` [PATCHv9 11/14] gdb: create new is_thread_id helper function Andrew Burgess
                                   ` (4 subsequent siblings)
  14 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2024-03-05 15:21 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

We already have one overload of the startswith function that takes a
std::string_view for both arguments.  A later patch in this series is
going to be improved by having an overload that takes one argument as
a std::string_view and the other argument as a plain 'char *'.

This commit adds the new overload, but doesn't make use of it (yet).
There should be no user visible changes after this commit.
---
 gdbsupport/common-utils.h | 10 ++++++++++
 1 file changed, 10 insertions(+)

diff --git a/gdbsupport/common-utils.h b/gdbsupport/common-utils.h
index 23cd40c0207..2fb22916409 100644
--- a/gdbsupport/common-utils.h
+++ b/gdbsupport/common-utils.h
@@ -100,6 +100,16 @@ startswith (std::string_view string, std::string_view pattern)
 	  && strncmp (string.data (), pattern.data (), pattern.length ()) == 0);
 }
 
+/* Version of startswith that takes a string_view for only one of its
+   arguments.  Return true if STR starts with PREFIX, otherwise return
+   false.  */
+
+static inline bool
+startswith (const char *str, const std::string_view &prefix)
+{
+  return strncmp (str, prefix.data (), prefix.length ()) == 0;
+}
+
 /* Return true if the strings are equal.  */
 
 static inline bool
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv9 11/14] gdb: create new is_thread_id helper function
  2024-03-05 15:21               ` [PATCHv9 00/14] thread-specific breakpoints in just some inferiors Andrew Burgess
                                   ` (9 preceding siblings ...)
  2024-03-05 15:21                 ` [PATCHv9 10/14] gdb: add another overload of startswith Andrew Burgess
@ 2024-03-05 15:21                 ` Andrew Burgess
  2024-03-05 15:21                 ` [PATCHv9 12/14] gdb: parse pending breakpoint thread/task immediately Andrew Burgess
                                   ` (3 subsequent siblings)
  14 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2024-03-05 15:21 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

This is a refactoring commit that splits the existing parse_thread_id
function into two parts, and then adds a new is_thread_id function.

The core of parse_thread_id is split into parse_thread_id_1, which is
responsible for actually parsing a thread-id.  Then parse_thread_id is
responsible for taking a parsed thread-id and validating that it
references an actually existing inferior thread.

The new is_thread_id function also uses parse_thread_id_1, but doesn't
actually check that the inferior thread exists, instead, this new
function simply checks that a string looks like a thread-id.

This commit does not add a use for is_thread_id, this will be added in
the next commit.

This is a refactoring commit, there should be no user visible changes
after this commit.
---
 gdb/tid-parse.c | 82 +++++++++++++++++++++++++++++++++++++------------
 gdb/tid-parse.h |  8 +++++
 2 files changed, 70 insertions(+), 20 deletions(-)

diff --git a/gdb/tid-parse.c b/gdb/tid-parse.c
index aa1480d7cf0..7f85b94eba4 100644
--- a/gdb/tid-parse.c
+++ b/gdb/tid-parse.c
@@ -48,40 +48,43 @@ get_positive_number_trailer (const char **pp, int trailer, const char *string)
   return num;
 }
 
-/* See tid-parse.h.  */
+/* Parse TIDSTR as a per-inferior thread ID, in either INF_NUM.THR_NUM
+   or THR_NUM form, and return a pair, the first item of the pair is
+   INF_NUM and the second item is THR_NUM.
 
-struct thread_info *
-parse_thread_id (const char *tidstr, const char **end)
+   If TIDSTR does not include an INF_NUM component, then the first item in
+   the pair will be 0 (which is an invalid inferior number), this indicates
+   that TIDSTR references the current inferior.
+
+   This function does not validate the INF_NUM and THR_NUM are actually
+   valid numbers, that is, they might reference inferiors or threads that
+   don't actually exist; this function just splits the string into its
+   component parts.
+
+   If there is an error parsing TIDSTR then this function will raise an
+   exception.  */
+
+static std::pair<int, int>
+parse_thread_id_1 (const char *tidstr, const char **end)
 {
   const char *number = tidstr;
   const char *dot, *p1;
-  struct inferior *inf;
-  int thr_num;
-  int explicit_inf_id = 0;
+  int thr_num, inf_num;
 
   dot = strchr (number, '.');
 
   if (dot != NULL)
     {
       /* Parse number to the left of the dot.  */
-      int inf_num;
-
       p1 = number;
       inf_num = get_positive_number_trailer (&p1, '.', number);
       if (inf_num == 0)
 	invalid_thread_id_error (number);
-
-      inf = find_inferior_id (inf_num);
-      if (inf == NULL)
-	error (_("No inferior number '%d'"), inf_num);
-
-      explicit_inf_id = 1;
       p1 = dot + 1;
     }
   else
     {
-      inf = current_inferior ();
-
+      inf_num = 0;
       p1 = number;
     }
 
@@ -89,6 +92,32 @@ parse_thread_id (const char *tidstr, const char **end)
   if (thr_num == 0)
     invalid_thread_id_error (number);
 
+  if (end != nullptr)
+    *end = p1;
+
+  return { inf_num, thr_num };
+}
+
+/* See tid-parse.h.  */
+
+struct thread_info *
+parse_thread_id (const char *tidstr, const char **end)
+{
+  const auto [inf_num, thr_num] = parse_thread_id_1 (tidstr, end);
+
+  inferior *inf;
+  bool explicit_inf_id = false;
+
+  if (inf_num != 0)
+    {
+      inf = find_inferior_id (inf_num);
+      if (inf == nullptr)
+	error (_("No inferior number '%d'"), inf_num);
+      explicit_inf_id = true;
+    }
+  else
+    inf = current_inferior ();
+
   thread_info *tp = nullptr;
   for (thread_info *it : inf->threads ())
     if (it->per_inf_num == thr_num)
@@ -97,7 +126,7 @@ parse_thread_id (const char *tidstr, const char **end)
 	break;
       }
 
-  if (tp == NULL)
+  if (tp == nullptr)
     {
       if (show_inferior_qualified_tids () || explicit_inf_id)
 	error (_("Unknown thread %d.%d."), inf->num, thr_num);
@@ -105,14 +134,27 @@ parse_thread_id (const char *tidstr, const char **end)
 	error (_("Unknown thread %d."), thr_num);
     }
 
-  if (end != NULL)
-    *end = p1;
-
   return tp;
 }
 
 /* See tid-parse.h.  */
 
+bool
+is_thread_id (const char *tidstr, const char **end)
+{
+  try
+    {
+      (void) parse_thread_id_1 (tidstr, end);
+      return true;
+    }
+  catch (const gdb_exception_error &)
+    {
+      return false;
+    }
+}
+
+/* See tid-parse.h.  */
+
 tid_range_parser::tid_range_parser (const char *tidlist,
 				    int default_inferior)
 {
diff --git a/gdb/tid-parse.h b/gdb/tid-parse.h
index b7bd920f48a..bba5ae5118c 100644
--- a/gdb/tid-parse.h
+++ b/gdb/tid-parse.h
@@ -36,6 +36,14 @@ extern void ATTRIBUTE_NORETURN invalid_thread_id_error (const char *string);
    thrown.  */
 struct thread_info *parse_thread_id (const char *tidstr, const char **end);
 
+/* Return true if TIDSTR is pointing to a string that looks like a
+   thread-id.  This doesn't mean that TIDSTR identifies a valid thread, but
+   the string does at least look like a valid thread-id.  If END is not
+   NULL, parse_thread_id stores the address of the first character after
+   the thread-id into *END.  */
+
+bool is_thread_id (const char *tidstr, const char **end);
+
 /* Parse a thread ID or a thread range list.
 
    A range will be of the form
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv9 12/14] gdb: parse pending breakpoint thread/task immediately
  2024-03-05 15:21               ` [PATCHv9 00/14] thread-specific breakpoints in just some inferiors Andrew Burgess
                                   ` (10 preceding siblings ...)
  2024-03-05 15:21                 ` [PATCHv9 11/14] gdb: create new is_thread_id helper function Andrew Burgess
@ 2024-03-05 15:21                 ` Andrew Burgess
  2024-03-05 15:21                 ` [PATCHv9 13/14] gdb: don't set breakpoint::pspace in create_breakpoint Andrew Burgess
                                   ` (2 subsequent siblings)
  14 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2024-03-05 15:21 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Eli Zaretskii

The initial motivation for this commit was to allow thread or inferior
specific breakpoints to only be inserted within the appropriate
inferior's program-space.  The benefit of this is that inferiors for
which the breakpoint does not apply will no longer need to stop, and
then resume, for such breakpoints.  This commit does not make this
change, but is a refactor to allow this to happen in a later commit.

The problem we currently have is that when a thread-specific (or
inferior-specific) breakpoint is created, the thread (or inferior)
number is only parsed by calling find_condition_and_thread_for_sals.
This function is only called for non-pending breakpoints, and requires
that we know the locations at which the breakpoint will be placed (for
expression checking in case the breakpoint is also conditional).

A consequence of this is that by the time we figure out the breakpoint
is thread-specific we have already looked up locations in all program
spaces.  This feels wasteful -- if we knew the thread-id earlier then
we could reduce the work GDB does by only looking up locations within
the program space for which the breakpoint applies.

Another consequence of how find_condition_and_thread_for_sals is
called is that pending breakpoints don't currently know they are
thread-specific, nor even that they are conditional!  Additionally, by
delaying parsing the thread-id, pending breakpoints can be created for
non-existent threads, this is different to how non-pending
breakpoints are handled, so I can do this:

  $ gdb -q ./gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp
  Reading symbols from ./gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp...
  (gdb) break foo thread 99
  Function "foo" not defined.
  Make breakpoint pending on future shared library load? (y or [n]) y
  Breakpoint 1 (foo thread 99) pending.
  (gdb) r
  Starting program: /tmp/gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp
  [Thread debugging using libthread_db enabled]
  Using host libthread_db library "/lib64/libthread_db.so.1".
  Error in re-setting breakpoint 1: Unknown thread 99.
  [Inferior 1 (process 3329749) exited normally]
  (gdb)

GDB only checked the validity of 'thread 99' at the point the 'foo'
location became non-pending.  In contrast, if I try this:

  $ gdb -q ./gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp
  Reading symbols from ./gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp...
  (gdb) break main thread 99
  Unknown thread 99.
  (gdb)

GDB immediately checks if 'thread 99' exists.  I think inconsistencies
like this are confusing, and should be fixed if possible.

In this commit the create_breakpoint function is updated so that the
extra_string, which contains the thread, inferior, task, and/or
condition information, is parsed immediately, even for pending
breakpoints.

Obviously, the condition still can't be validated until the breakpoint
becomes non-pending, but the thread, inferior, and task information
can be pulled from the extra-string, and can be validated early on,
even for pending breakpoints.  The -force-condition flag is also
parsed as part of this early parsing change.

There are a couple of benefits to doing this:

1. Printing of breakpoints is more consistent now.  Consider creating
   a conditional breakpoint before this commit:

    (gdb) set breakpoint pending on
    (gdb) break pendingfunc if (0)
    Function "pendingfunc" not defined.
    Breakpoint 1 (pendingfunc if (0)) pending.
    (gdb) break main if (0)
    Breakpoint 2 at 0x401198: file /tmp/hello.c, line 18.
    (gdb) info breakpoints
    Num     Type           Disp Enb Address            What
    1       breakpoint     keep y   <PENDING>          pendingfunc if (0)
    2       breakpoint     keep y   0x0000000000401198 in main at /tmp/hello.c:18
            stop only if (0)
    (gdb)

   And after this commit:

    (gdb) set breakpoint pending on
    (gdb) break pendingfunc if (0)
    Function "pendingfunc" not defined.
    Breakpoint 1 (pendingfunc) pending.
    (gdb) break main if (0)
    Breakpoint 2 at 0x401198: file /home/andrew/tmp/hello.c, line 18.
    (gdb) info breakpoints
    Num     Type           Disp Enb Address            What
    1       breakpoint     keep y   <PENDING>          pendingfunc
            stop only if (0)
    2       breakpoint     keep y   0x0000000000401198 in main at /home/andrew/tmp/hello.c:18
            stop only if (0)
    (gdb)

   Notice that the display of the condition is now the same for the
   pending and non-pending breakpoints.

   The same is true for the thread, inferior, or task information in
   thread, inferior, or task specific breakpoints; this information is
   displayed on its own line rather than being part of the 'What'
   field.

2. We can check that the thread exists as soon as the pending
   breakpoint is created.  Currently there is a weird difference
   between pending and non-pending breakpoints when creating a
   thread-specific breakpoint.

   A pending thread-specific breakpoint only checks its thread when it
   becomes non-pending, at which point the thread the breakpoint was
   intended for might have exited.  Here's the behaviour before this
   commit:

    (gdb) set breakpoint pending on
    (gdb) break foo thread 2
    Function "foo" not defined.
    Breakpoint 2 (foo thread 2) pending.
    (gdb) c
    Continuing.
    [Thread 0x7ffff7c56700 (LWP 2948835) exited]
    Error in re-setting breakpoint 2: Unknown thread 2.
    [Inferior 1 (process 2948832) exited normally]
    (gdb)

   Notice the 'Error in re-setting breakpoint 2: Unknown thread 2.'
   line, this was triggered when GDB tried to make the breakpoint
   non-pending, and GDB discovers that the thread no longer exists.

   Compare that to the behaviour after this commit:

    (gdb) set breakpoint pending on
    (gdb) break foo thread 2
    Function "foo" not defined.
    Breakpoint 2 (foo) pending.
    (gdb) c
    Continuing.
    [Thread 0x7ffff7c56700 (LWP 2949243) exited]
    Thread-specific breakpoint 2 deleted - thread 2 no longer in the thread list.
    [Inferior 1 (process 2949240) exited normally]
    (gdb)

   Now the behaviour for pending breakpoints is identical to
   non-pending breakpoints, the thread specific breakpoint is removed
   as soon as the thread the breakpoint is associated with exits.

   There is an additional change; when the pending breakpoint is
   created prior to this patch we see this line:

     Breakpoint 2 (foo thread 2) pending.

   While after this patch we get this line:

     Breakpoint 2 (foo) pending.

   Notice that 'thread 2' has disappeared.  This might look like a
   regression, but I don't think it is.  That we said 'thread 2'
   before was just a consequence of the lazy parsing of the breakpoint
   specification, while with this patch GDB understands, and has
   parsed away the 'thread 2' bit of the spec.  If folk think the old
   information was useful then this would be trivial to add back in
   code_breakpoint::say_where.

As a result of this commit the breakpoints 'extra_string' field is now
only used by bp_dprintf type breakpoints to hold the printf format and
arguments.  This string should always be empty for other breakpoint
types.  This allows some cleanup in print_breakpoint_location.

In code_breakpoint::code_breakpoint I've changed an error case into an
assert.  This is because the error is now handled earlier in
create_breakpoint.  As a result we know that by this point, the
extra_string will always be nullptr for anything other than a
bp_dprintf style breakpoint.

The find_condition_and_thread_for_sals function is now no longer
needed, this was previously doing the delayed splitting of the extra
string into thread, task, and condition, but this is now all done in
create_breakpoint, so find_condition_and_thread_for_sals can be
deleted, and the code that calls this in
code_breakpoint::location_spec_to_sals can be removed.  With this
update this code would only ever be reached for bp_dprintf style
breakpoints, and in these cases the extra_string should not contain
anything other than format and args.

The most interesting changes are all in create_breakpoint and in the
new file break-cond-parse.c.  We have a new block of code early on in
create_breakpoint that is responsible for splitting the extra_string
into its component parts by calling create_breakpoint_parse_arg_string
a function in the new break-cond-parse.c file.  This means that some
of the later code can be simplified a little.

The new break-cond-parse.c file implements the splitting up the
extra_string and finding all the parts, as well as some self-tests for
the new function.

Finally, now we know all the breakpoint details, these can be stored
within the breakpoint object if we end up creating a deferred
breakpoint.  Additionally, if we are creating a deferred bp_dprintf we
can parse the extra_string to build the printf command.

The implementation here aims to maintain backwards compatibility as
much as possible, this means that:

  1. We support abbreviations of 'thread', 'task', and 'inferior' in
  some places on the breakpoint line.  The handling of abbreviations
  has (before this patch) been a little weird, so this works:

  (gdb) break *main th 1

  And creates a breakpoint at '*main' for thread 1 only, while this
  does not work:

  (gdb) break main th 1

  In this case GDB will try to find the symbol 'main th 1'.  This
  weirdness exists before and after this patch.

  2. The handling of '-force-condition' is odd, if this flag appears
  immediately after a condition then it will be treated as part of the
  condition, e.g.:

  (gdb) break main if 0 -force-condition
  No symbol "force" in current context.

  But we are fine with these alternatives:

  (gdb) break main if 0 thread 1 -force-condition
  (gdb) break main -force-condition if 0

  Again, this is just a quirk of how the breakpoint line used to be
  parsed, but I've maintained this for backward compatibility.  During
  review it was suggested that -force-condition should become an
  actual breakpoint flag (i.e. only valid after the 'break' command
  but before the function name), and I don't think that would be a
  terrible idea, however, that's not currently a trivial change, and I
  think should be done as a separate piece of work.  For now, this
  patch just maintains the current behaviour.

The implementation works by first splitting the breakpoint condition
string (everything after the location specification) into a list of
tokens, each token has a type and a value. (e.g. we have a THREAD
token where the value is the thread-id string).  The list of tokens is
validated, and in some cases, tokens are merged.  Then the values are
extracted from the remaining token list.

Consider this breakpoint command:

  (gdb) break main thread 1 if argc == 2

The condition string passed to create_breakpoint_parse_arg_string is
going to be 'thread 1 if argc == 2', which is then split into the
tokens:

  { THREAD: "1" } { CONDITION: "argc == 2" }

The thread-id (1) and the condition string 'argc == 2' are extracted
from these tokens and returns back to create_breakpoint.

Now consider this breakpoint command:

  (gdb) break some_function if ( some_var == thread )

Here the user wants a breakpoint if 'some_var' is equal to the
variable 'thread'.  However, when this is initially parsed we will
find these tokens:

  { CONDITION: "( some_var == " } { THREAD: ")" }

This is a consequence of how we have to try and figure out the
contents of the 'if' condition without actually parsing the
expression; parsing the expression requires that we know the location
in order to lookup the variables by name, and this can't be done for
pending breakpoints (their location isn't known yet), and one of the
points of this work is that we extract things like thread-id for
pending breakpoints.

And so, it is in this case that token merging takes place.  We check
if the value of a token appearing immediately after the CONDITION
token looks valid.  In this case, does ')' look like a valid
thread-id.  Clearly, in this case ')' does not, and so me merge the
THREAD token into the condition token, giving:

  { CONDITION: "( some_var == thread )" }

Which is what we want.

I'm sure that we might still be able to come up with some edge cases
where the parser makes the wrong choice.  I think long term the best
way to work around these would be to move the thread, inferior, task,
and -force-condition flags to be "real" command options for the break
command.  I am looking into doing this, but can't guarantee if/when
that work would be completed, so this patch should be reviewed assume
that the work will never arrive (though I hope it will).

Reviewed-By: Eli Zaretskii <eliz@gnu.org>
---
 gdb/Makefile.in                               |   2 +
 gdb/NEWS                                      |   4 +
 gdb/break-cond-parse.c                        | 701 ++++++++++++++++++
 gdb/break-cond-parse.h                        |  52 ++
 gdb/breakpoint.c                              | 372 ++--------
 gdb/testsuite/gdb.ada/tasks.exp               |   6 +-
 gdb/testsuite/gdb.base/condbreak.exp          |  57 +-
 gdb/testsuite/gdb.base/pending.exp            |  23 +-
 gdb/testsuite/gdb.linespec/explicit.exp       |   4 +-
 gdb/testsuite/gdb.linespec/keywords.exp       |   8 +-
 gdb/testsuite/gdb.mi/mi-dprintf-pending.exp   |   3 +-
 .../gdb.multi/inferior-specific-bp.exp        |   4 +-
 .../gdb.threads/del-pending-thread-bp-lib.c   |  22 +
 .../gdb.threads/del-pending-thread-bp.c       |  85 +++
 .../gdb.threads/del-pending-thread-bp.exp     | 108 +++
 15 files changed, 1145 insertions(+), 306 deletions(-)
 create mode 100644 gdb/break-cond-parse.c
 create mode 100644 gdb/break-cond-parse.h
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.exp

diff --git a/gdb/Makefile.in b/gdb/Makefile.in
index 0e0f19c40c9..73dc2ca6637 100644
--- a/gdb/Makefile.in
+++ b/gdb/Makefile.in
@@ -1028,6 +1028,7 @@ COMMON_SFILES = \
 	break-catch-sig.c \
 	break-catch-syscall.c \
 	break-catch-throw.c \
+	break-cond-parse.c \
 	breakpoint.c \
 	bt-utils.c \
 	btrace.c \
@@ -1296,6 +1297,7 @@ HFILES_NO_SRCDIR = \
 	bfd-target.h \
 	bfin-tdep.h \
 	block.h \
+	break-cond-parse.h \
 	breakpoint.h \
 	bsd-kvm.h \
 	bsd-uthread.h \
diff --git a/gdb/NEWS b/gdb/NEWS
index 2638b3e0d9c..c170385a50e 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -13,6 +13,10 @@
   the background, resulting in faster startup.  This can be controlled
   using "maint set dwarf synchronous".
 
+* For breakpoints that are created in the 'pending' state, any
+  'thread' or 'task' keywords are parsed at the time the breakpoint is
+  created, rather than at the time the breakpoint becomes non-pending.
+
 * Changed commands
 
 disassemble
diff --git a/gdb/break-cond-parse.c b/gdb/break-cond-parse.c
new file mode 100644
index 00000000000..eff738f2a7c
--- /dev/null
+++ b/gdb/break-cond-parse.c
@@ -0,0 +1,701 @@
+/* Copyright (C) 2023 Free Software Foundation, Inc.
+
+   This file is part of GDB.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#include "defs.h"
+#include "gdbsupport/gdb_assert.h"
+#include "gdbsupport/selftest.h"
+#include "test-target.h"
+#include "scoped-mock-context.h"
+#include "break-cond-parse.h"
+#include "tid-parse.h"
+#include "ada-lang.h"
+
+/* When parsing tokens from a string, which direction are we parsing?
+
+   Given the following string and pointer 'ptr':
+
+	ABC DEF GHI JKL
+	       ^
+	       ptr
+
+   Parsing 'forward' will return the token 'GHI' and update 'ptr' to point
+   between GHI and JKL.  Parsing 'backward' will return the token 'DEF' and
+   update 'ptr' to point between ABC and DEF.
+*/
+
+enum class parse_direction
+{
+  /* Parse the next token forwards.  */
+  forward,
+
+  /* Parse the previous token backwards.  */
+  backward
+};
+
+/* Find the next token in DIRECTION from *CURR.  */
+
+static std::string_view
+find_next_token (const char **curr, parse_direction direction)
+{
+  const char *tok_start, *tok_end;
+
+  gdb_assert (**curr != '\0');
+
+  if (direction == parse_direction::forward)
+    {
+      *curr = skip_spaces (*curr);
+      tok_start = *curr;
+      *curr = skip_to_space (*curr);
+      tok_end = *curr - 1;
+    }
+  else
+    {
+      gdb_assert (direction == parse_direction::backward);
+
+      while (isspace (**curr))
+	--(*curr);
+
+      tok_end = *curr;
+
+      while (!isspace (**curr))
+	--(*curr);
+
+      tok_start = (*curr) + 1;
+    }
+
+  return std::string_view (tok_start, tok_end - tok_start + 1);
+}
+
+/* A class that represents a complete parsed token.  Each token has a type
+   and a std::string_view into the original breakpoint condition string.  */
+
+struct token
+{
+  /* The types a token might take.  */
+  enum class type
+  {
+    /* These are the token types for the 'if', 'thread', 'inferior', and
+       'task' keywords.  The m_content for these token types is the value
+       passed to the keyword, not the keyword itself.  */
+    CONDITION,
+    THREAD,
+    INFERIOR,
+    TASK,
+
+    /* This is the token used when we find unknown content, the m_content
+       for this token is the rest of the input string.  */
+    REST,
+
+    /* This is the token for the -force-condition token, the m_content for
+       this token contains the keyword itself.  */
+    FORCE
+  };
+
+  token (enum type type, std::string_view content)
+    : m_type (type),
+      m_content (std::move (content))
+  {
+    /* Nothing.  */
+  }
+
+  /* Return a string representing this token.  Only used for debug.  */
+  std::string to_string () const
+  {
+    switch (m_type)
+      {
+      case type::CONDITION:
+	return string_printf ("{ CONDITION: \"%s\" }",
+			      std::string (m_content).c_str ());
+      case type::THREAD:
+	return string_printf ("{ THREAD: \"%s\" }",
+			      std::string (m_content).c_str ());
+      case type::INFERIOR:
+	return string_printf ("{ INFERIOR: \"%s\" }",
+			      std::string (m_content).c_str ());
+      case type::TASK:
+	return string_printf ("{ TASK: \"%s\" }",
+			      std::string (m_content).c_str ());
+      case type::REST:
+	return string_printf ("{ REST: \"%s\" }",
+			      std::string (m_content).c_str ());
+      case type::FORCE:
+	return string_printf ("{ FORCE }");
+      default:
+	return "** unknown **";
+      }
+  }
+
+  /* The type of this token.  */
+  const type &get_type () const
+  {
+    return m_type;
+  }
+
+  /* Return the value of this token.  */
+  const std::string_view &get_value () const
+  {
+    gdb_assert (m_content.size () > 0);
+    return m_content;
+  }
+
+  /* Extend this token with the contents of OTHER.  This only makes sense
+     if OTHER is the next token after this one in the original string,
+     however, enforcing that restriction is left to the caller of this
+     function.
+
+     When OTHER is a keyword/value token, e.g. 'thread 1', the m_content
+     for OTHER will only point to the '1'.  However, as the m_content is a
+     std::string_view, then when we merge the m_content of OTHER into this
+     token we automatically merge in the 'thread' part too, as it
+     naturally sits between this token and OTHER.  */
+
+  void
+  extend (const token &other)
+  {
+    m_content = std::string_view (this->m_content.data (),
+				  (other.m_content.data ()
+				   - this->m_content.data ()
+				   + other.m_content.size ()));
+  }
+
+private:
+  /* The type of this token.  */
+  type m_type;
+
+  /* The important content part of this token.  The extend member function
+     depends on this being a std::string_view.  */
+  std::string_view m_content;
+};
+
+/* Split STR, a breakpoint condition string, into a vector of tokens where
+   each token represents a component of the condition.  Tokens are first
+   parsed from the front of STR until we encounter an 'if' token.  At this
+   point tokens are parsed from the end of STR until we encounter an
+   unknown token, which we assume is the other end of the 'if' condition.
+   If when scanning forward we encounter an unknown token then the
+   remainder of STR is placed into a 'rest' token (the rest of the
+   string), and no backward scan is performed.  */
+
+static std::vector<token>
+parse_all_tokens (const char *str)
+{
+  gdb_assert (str != nullptr);
+
+  std::vector<token> forward_results;
+  std::vector<token> backward_results;
+
+  const char *cond_start = nullptr;
+  const char *cond_end = nullptr;
+  parse_direction direction = parse_direction::forward;
+  std::vector<token> *curr_results = &forward_results;
+  while (*str != '\0')
+    {
+      /* Find the next token.  If moving backward and this token starts at
+	 the same location as the condition then we must have found the
+	 other end of the condition string -- we're done.  */
+      std::string_view t = find_next_token (&str, direction);
+      if (direction == parse_direction::backward && t.data () <= cond_start)
+	{
+	  cond_end = &t.back ();
+	  break;
+	}
+
+      /* We only have a single flag option to check for.  All the other
+	 options take a value so require an additional token to be found.
+	 Additionally, we require that this flag be at least '-f', we
+	 don't allow it to be abbreviated to '-'.  */
+      if (t.length () > 1 && startswith ("-force-condition", t))
+	{
+	  curr_results->emplace_back (token::type::FORCE, t);
+	  continue;
+	}
+
+      /* Maybe the first token was the last token in the string.  If this
+	 is the case then we definitely can't try to extract a value
+	 token.  This also means that the token T is meaningless.  Reset
+	 TOK to point at the start of the unknown content and break out of
+	 the loop.  We'll record the unknown part of the string outside of
+	 the scanning loop (below).  */
+      if (direction == parse_direction::forward && *str == '\0')
+	{
+	  str = t.data ();
+	  break;
+	}
+
+      /* As before, find the next token and, if we are scanning backwards,
+	 check that we have not reached the start of the condition string.  */
+      std::string_view v = find_next_token (&str, direction);
+      if (direction == parse_direction::backward && v.data () <= cond_start)
+	{
+	  /* Use token T here as that must also be part of the condition
+	     string.  */
+	  cond_end = &t.back ();
+	  break;
+	}
+
+      /* When moving backward we will first parse the value token then the
+	 keyword token, so swap them now.  */
+      if (direction == parse_direction::backward)
+	std::swap (t, v);
+
+      /* Check for valid option in token T.  If we find a valid option then
+	 parse the value from the token V.  Except for 'if', that's handled
+	 differently.
+
+	 For the 'if' token we need to capture the entire condition
+	 string, so record the start of the condition string and then
+	 start scanning backwards looking for the end of the condition
+	 string.
+
+	 The order of these checks is important, at least the check for
+	 'thread' must occur before the check for 'task'.  We accept
+	 abbreviations of these token names, and 't' should resolve to
+	 'thread', which will only happen if we check 'thread' first.  */
+      if (direction == parse_direction::forward && startswith ("if", t))
+	{
+	  cond_start = v.data ();
+	  str = str + strlen (str);
+	  gdb_assert (*str == '\0');
+	  --str;
+	  direction = parse_direction::backward;
+	  curr_results = &backward_results;
+	  continue;
+	}
+      else if (startswith ("thread", t))
+	curr_results->emplace_back (token::type::THREAD, v);
+      else if (startswith ("inferior", t))
+	curr_results->emplace_back (token::type::INFERIOR, v);
+      else if (startswith ("task", t))
+	curr_results->emplace_back (token::type::TASK, v);
+      else
+	{
+	  /* An unknown token.  If we are scanning forward then reset TOK
+	     to point at the start of the unknown content, we record this
+	     outside of the scanning loop (below).
+
+	     If we are scanning backward then unknown content is assumed to
+	     be the other end of the condition string, obviously, this is
+	     just a heuristic, we could be looking at a mistyped command
+	     line, but this will be spotted when the condition is
+	     eventually evaluated.
+
+	     Either way, no more scanning is required after this.  */
+	  if (direction == parse_direction::forward)
+	    str = t.data ();
+	  else
+	    {
+	      gdb_assert (direction == parse_direction::backward);
+	      cond_end = &v.back ();
+	    }
+	  break;
+	}
+    }
+
+  if (cond_start != nullptr)
+    {
+      /* If we found the start of a condition string then we should have
+	 switched to backward scan mode, and found the end of the condition
+	 string.  Capture the whole condition string into COND_STRING
+	 now.  */
+      gdb_assert (direction == parse_direction::backward);
+      gdb_assert (cond_end != nullptr);
+
+      std::string_view v (cond_start, cond_end - cond_start + 1);
+
+      forward_results.emplace_back (token::type::CONDITION, v);
+    }
+  else if (*str != '\0')
+    {
+      /* If we didn't have a condition start pointer then we should still
+	 be in forward scanning mode.  If we didn't reach the end of the
+	 input string (TOK is not at the null character) then the rest of
+	 the input string is garbage that we didn't understand.
+
+	 Record the unknown content into REST.  The caller of this function
+	 will report this as an error later on.  We could report the error
+	 here, but we prefer to allow the caller to run other checks, and
+	 prioritise other errors before reporting this problem.  */
+      gdb_assert (direction == parse_direction::forward);
+      gdb_assert (cond_end == nullptr);
+
+      std::string_view v (str, strlen (str));
+
+      forward_results.emplace_back (token::type::REST, v);
+    }
+
+  /* If we have tokens in the BACKWARD_RESULTS vector then this means that
+     we found an 'if' condition (which will be the last thing in the
+     FORWARD_RESULTS vector), and then we started a backward scan.
+
+     The last tokens from the input string (those after the 'if' condition)
+     will be the first tokens added to the BACKWARD_RESULTS vector, so the
+     last items in the BACKWARD_RESULTS vector are those next to the 'if'
+     condition.
+
+     Check the tokens in the BACKWARD_RESULTS vector from back to front.
+     If the tokens look invalid then we assume that they are actually part
+     of the 'if' condition, and merge the token with the 'if' condition.
+     If it turns out that this was incorrect and that instead the user just
+     messed up entering the token value, then this will show as an error
+     when parsing the 'if' condition.
+
+     Doing this allows us to handle things like:
+
+       break function if ( variable == thread )
+
+     Where 'thread' is a local variable within 'function'.  When parsing
+     this we will initially see 'thread )' as a thread token with ')' as
+     the value.  However, the following code will spot that ')' is not a
+     valid thread-id, and so we merge 'thread )' into the 'if' condition
+     string.
+
+     This code also handles the special treatment for '-force-condition',
+     which exists for backwards compatibility reasons.  Traditionally this
+     flag, if it occurred immediately after the 'if' condition, would be
+     treated as part of the 'if' condition.  When the breakpoint condition
+     parsing code was rewritten, this behaviour was retained.  */
+  gdb_assert (backward_results.empty ()
+	      || (forward_results.back ().get_type ()
+		  == token::type::CONDITION));
+  while (!backward_results.empty ())
+    {
+      token &t = backward_results.back ();
+
+      if (t.get_type () == token::type::FORCE)
+	forward_results.back ().extend (std::move (t));
+      else if (t.get_type () == token::type::THREAD)
+	{
+	  const char *end;
+	  std::string v (t.get_value ());
+	  if (is_thread_id (v.c_str (), &end) && *end == '\0')
+	    break;
+	  forward_results.back ().extend (std::move (t));
+	}
+      else if (t.get_type () == token::type::INFERIOR
+	       || t.get_type () == token::type::TASK)
+	{
+	  /* Place the token's value into a null-terminated string, parse
+	     the string as a number and check that the entire string was
+	     parsed.  If this is true then this looks like a valid inferior
+	     or task number, otherwise, assume an invalid id, and merge
+	     this token with the 'if' token.  */
+	  char *end;
+	  std::string v (t.get_value ());
+	  (void) strtol (v.c_str (), &end, 0);
+	  if (end > v.c_str () && *end == '\0')
+	    break;
+	  forward_results.back ().extend (std::move (t));
+	}
+      else
+	gdb_assert_not_reached ("unexpected token type");
+
+      /* If we found an actual valid token above then we will have broken
+	 out of the loop.  We only get here if the token was merged with
+	 the 'if' condition, in which case we can discard the last token
+	 and then check the token before that.  */
+      backward_results.pop_back ();
+    }
+
+  /* If after the above checks we still have some tokens in the
+     BACKWARD_RESULTS vector, then these need to be appended to the
+     FORWARD_RESULTS vector.  However, we first reverse the order so that
+     FORWARD_RESULTS retains the tokens in the order they appeared in the
+     input string.  */
+  if (!backward_results.empty ())
+    forward_results.insert (forward_results.end (),
+			    backward_results.rbegin (),
+			    backward_results.rend ());
+
+  return forward_results;
+}
+
+/* Called when the global debug_breakpoint is true.  Prints VEC to the
+   debug output stream.  */
+
+static void
+dump_condition_tokens (const std::vector<token> &vec)
+{
+  gdb_assert (debug_breakpoint);
+
+  bool first = true;
+  std::string str = "Tokens: ";
+  for (const token &t : vec)
+    {
+      if (!first)
+	str += " ";
+      first = false;
+      str += t.to_string ();
+    }
+  breakpoint_debug_printf ("%s", str.c_str ());
+}
+
+/* See break-cond-parse.h.  */
+
+void
+create_breakpoint_parse_arg_string
+  (const char *str, gdb::unique_xmalloc_ptr<char> *cond_string_ptr,
+   int *thread_ptr, int *inferior_ptr, int *task_ptr,
+   gdb::unique_xmalloc_ptr<char> *rest_ptr, bool *force_ptr)
+{
+  /* Set up the defaults.  */
+  cond_string_ptr->reset ();
+  rest_ptr->reset ();
+  *thread_ptr = -1;
+  *inferior_ptr = -1;
+  *task_ptr = -1;
+  *force_ptr = false;
+
+  if (str == nullptr)
+    return;
+
+  /* Split STR into a series of tokens.  */
+  std::vector<token> tokens = parse_all_tokens (str);
+  if (debug_breakpoint)
+    dump_condition_tokens (tokens);
+
+  /* Temporary variables.  Initialised to the default state, then updated
+     as we parse TOKENS.  If all of TOKENS is parsed successfully then the
+     state from these variables is copied into the output arguments before
+     the function returns.  */
+  int thread = -1, inferior = -1, task = -1;
+  bool force = false;
+  gdb::unique_xmalloc_ptr<char> cond_string, rest;
+
+  for (const token &t : tokens)
+    {
+      switch (t.get_type ())
+	{
+	case token::type::FORCE:
+	  force = true;
+	  break;
+	case token::type::THREAD:
+	  {
+	    if (thread != -1)
+	      error ("You can specify only one thread.");
+	    if (task != -1 || inferior != -1)
+	      error ("You can specify only one of thread, inferior, or task.");
+	    const char *tmptok;
+	    thread_info *thr
+	      = parse_thread_id (std::string (t.get_value ()).c_str (),
+				 &tmptok);
+	    gdb_assert (*tmptok == '\0');
+	    thread = thr->global_num;
+	  }
+	  break;
+	case token::type::INFERIOR:
+	  {
+	    if (inferior != -1)
+	      error ("You can specify only one inferior.");
+	    if (task != -1 || thread != -1)
+	      error ("You can specify only one of thread, inferior, or task.");
+	    char *tmptok;
+	    long inferior_id
+	      = strtol (std::string (t.get_value ()).c_str (), &tmptok, 0);
+	    if (*tmptok != '\0')
+	      error (_("Junk '%s' after inferior keyword."), tmptok);
+	    if (inferior_id > INT_MAX)
+	      error (_("No inferior number '%ld'"), inferior_id);
+	    inferior = static_cast<int> (inferior_id);
+	    struct inferior *inf = find_inferior_id (inferior);
+	    if (inf == nullptr)
+	      error (_("No inferior number '%d'"), inferior);
+	  }
+	  break;
+	case token::type::TASK:
+	  {
+	    if (task != -1)
+	      error ("You can specify only one task.");
+	    if (inferior != -1 || thread != -1)
+	      error ("You can specify only one of thread, inferior, or task.");
+	    char *tmptok;
+	    long task_id
+	      = strtol (std::string (t.get_value ()).c_str (), &tmptok, 0);
+	    if (*tmptok != '\0')
+	      error (_("Junk '%s' after task keyword."), tmptok);
+	    if (task_id > INT_MAX)
+	      error (_("Unknown task %ld"), task_id);
+	    task = static_cast<int> (task_id);
+	    if (!valid_task_id (task))
+	      error (_("Unknown task %d."), task);
+	  }
+	  break;
+	case token::type::CONDITION:
+	  cond_string.reset (savestring (t.get_value ().data (),
+					 t.get_value ().size ()));
+	  break;
+	case token::type::REST:
+	  rest.reset (savestring (t.get_value ().data (),
+				  t.get_value ().size ()));
+	  break;
+	}
+    }
+
+  /* Move results into the output locations.  */
+  *force_ptr = force;
+  *thread_ptr = thread;
+  *inferior_ptr = inferior;
+  *task_ptr = task;
+  rest_ptr->reset (rest.release ());
+  cond_string_ptr->reset (cond_string.release ());
+}
+
+#if GDB_SELF_TEST
+
+namespace selftests {
+
+/* Run a single test of the create_breakpoint_parse_arg_string function.
+   INPUT is passed to create_breakpoint_parse_arg_string while all other
+   arguments are the expected output from
+   create_breakpoint_parse_arg_string.  */
+
+static void
+test (const char *input, const char *condition, int thread = -1,
+      int inferior = -1, int task = -1, bool force = false,
+      const char *rest = nullptr, const char *error_msg = nullptr)
+{
+  gdb::unique_xmalloc_ptr<char> extracted_condition;
+  gdb::unique_xmalloc_ptr<char> extracted_rest;
+  int extracted_thread, extracted_inferior, extracted_task;
+  bool extracted_force_condition;
+  std::string exception_msg, error_str;
+
+  if (error_msg != nullptr)
+    error_str = std::string (error_msg) + "\n";
+
+  try
+    {
+      create_breakpoint_parse_arg_string (input, &extracted_condition,
+					  &extracted_thread,
+					  &extracted_inferior,
+					  &extracted_task, &extracted_rest,
+					  &extracted_force_condition);
+    }
+  catch (const gdb_exception_error &ex)
+    {
+      string_file buf;
+
+      exception_print (&buf, ex);
+      exception_msg = buf.release ();
+    }
+
+  if ((condition == nullptr) != (extracted_condition.get () == nullptr)
+      || (condition != nullptr
+	  && strcmp (condition, extracted_condition.get ()) != 0)
+      || (rest == nullptr) != (extracted_rest.get () == nullptr)
+      || (rest != nullptr && strcmp (rest, extracted_rest.get ()) != 0)
+      || thread != extracted_thread
+      || inferior != extracted_inferior
+      || task != extracted_task
+      || force != extracted_force_condition
+      || exception_msg != error_str)
+    {
+      if (run_verbose ())
+	{
+	  debug_printf ("input: '%s'\n", input);
+	  debug_printf ("condition: '%s'\n", extracted_condition.get ());
+	  debug_printf ("rest: '%s'\n", extracted_rest.get ());
+	  debug_printf ("thread: %d\n", extracted_thread);
+	  debug_printf ("inferior: %d\n", extracted_inferior);
+	  debug_printf ("task: %d\n", extracted_task);
+	  debug_printf ("forced: %s\n",
+			extracted_force_condition ? "true" : "false");
+	  debug_printf ("exception: '%s'\n", exception_msg.c_str ());
+	}
+
+      /* Report the failure.  */
+      SELF_CHECK (false);
+    }
+}
+
+/* Wrapper for test function.  Pass through the default values for all
+   parameters, except the last parameter, which indicates that we expect
+   INPUT to trigger an error.  */
+
+static void
+test_error (const char *input, const char *error_msg)
+{
+  test (input, nullptr, -1, -1, -1, false, nullptr, error_msg);
+}
+
+/* Test the create_breakpoint_parse_arg_string function.  Just wraps
+   multiple calls to the test function above.  */
+
+static void
+create_breakpoint_parse_arg_string_tests ()
+{
+  gdbarch *arch = current_inferior ()->arch ();
+  scoped_restore_current_pspace_and_thread restore;
+  scoped_mock_context<test_target_ops> mock_target (arch);
+
+  int global_thread_num = mock_target.mock_thread.global_num;
+
+  /* Test parsing valid breakpoint condition strings.  */
+  test ("  if blah  ", "blah");
+  test (" if blah thread 1", "blah", global_thread_num);
+  test (" if blah inferior 1", "blah", -1, 1);
+  test (" if blah thread 1  ", "blah", global_thread_num);
+  test ("thread 1 woof", nullptr, global_thread_num, -1, -1, false, "woof");
+  test ("thread 1 X", nullptr, global_thread_num, -1, -1, false, "X");
+  test (" if blah thread 1 -force-condition", "blah", global_thread_num,
+	-1, -1, true);
+  test (" -force-condition if blah thread 1", "blah", global_thread_num,
+	-1, -1, true);
+  test (" -force-condition if blah thread 1  ", "blah", global_thread_num,
+	-1, -1, true);
+  test ("thread 1 -force-condition if blah", "blah", global_thread_num,
+	-1, -1, true);
+  test ("if (A::outer::func ())", "(A::outer::func ())");
+  test ("if ( foo == thread )", "( foo == thread )");
+  test ("if ( foo == thread ) inferior 1", "( foo == thread )", -1, 1);
+  test ("if ( foo == thread ) thread 1", "( foo == thread )",
+	global_thread_num);
+  test ("if foo == thread", "foo == thread");
+  test ("if foo == thread 1", "foo ==", global_thread_num);
+
+  /* Test parsing some invalid breakpoint condition strings.  */
+  test_error ("thread 1 if foo == 123 thread 1",
+	      "You can specify only one thread.");
+  test_error ("thread 1 if foo == 123 inferior 1",
+	      "You can specify only one of thread, inferior, or task.");
+  test_error ("thread 1 if foo == 123 task 1",
+	      "You can specify only one of thread, inferior, or task.");
+  test_error ("inferior 1 if foo == 123 inferior 1",
+	      "You can specify only one inferior.");
+  test_error ("inferior 1 if foo == 123 thread 1",
+	      "You can specify only one of thread, inferior, or task.");
+  test_error ("inferior 1 if foo == 123 task 1",
+	      "You can specify only one of thread, inferior, or task.");
+  test_error ("thread 1.2.3", "Invalid thread ID: 1.2.3");
+  test_error ("thread 1/2", "Invalid thread ID: 1/2");
+  test_error ("thread 1xxx", "Invalid thread ID: 1xxx");
+  test_error ("inferior 1xxx", "Junk 'xxx' after inferior keyword.");
+  test_error ("task 1xxx", "Junk 'xxx' after task keyword.");
+}
+
+} // namespace selftests
+#endif /* GDB_SELF_TEST */
+
+void _initialize_break_cond_parse ();
+void
+_initialize_break_cond_parse ()
+{
+#if GDB_SELF_TEST
+  selftests::register_test
+    ("create_breakpoint_parse_arg_string",
+     selftests::create_breakpoint_parse_arg_string_tests);
+#endif
+}
diff --git a/gdb/break-cond-parse.h b/gdb/break-cond-parse.h
new file mode 100644
index 00000000000..cbee70f4e9e
--- /dev/null
+++ b/gdb/break-cond-parse.h
@@ -0,0 +1,52 @@
+/* Copyright (C) 2023 Free Software Foundation, Inc.
+
+   This file is part of GDB.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#if !defined (BREAK_COND_PARSE_H)
+#define BREAK_COND_PARSE_H 1
+
+/* Given TOK, a string possibly containing a condition, thread, inferior,
+   task and force-condition flag, as accepted by the 'break' command,
+   extract the condition string, thread, inferior, task number, and the
+   force_condition flag, then set *COND_STRING, *THREAD, *INFERIOR, *TASK,
+   and *FORCE.
+
+   As TOK is parsed, if an unknown keyword is encountered before the 'if'
+   keyword then everything starting from the unknown keyword is placed into
+   *REST.
+
+   Both *COND and *REST are initialized to nullptr.  If no 'if' keyword is
+   found then *COND will be returned as nullptr.  If no unknown content is
+   found then *REST is returned as nullptr.
+
+   If no thread is found, *THREAD is set to -1.  If no inferior is found,
+   *INFERIOR is set to -1.  If no task is found, *TASK is set to -1.  If
+   the -force-condition flag is not found then *FORCE is set to false.
+
+   Due to the free-form nature that the string TOK might take (a 'thread'
+   keyword can appear before or after an 'if' condition) then we end up
+   having to check for keywords from both the start of TOK and the end of
+   TOK.
+
+   If TOK is nullptr, or TOK is the empty string, then the output variables
+   are all given their default values.  */
+
+extern void create_breakpoint_parse_arg_string
+  (const char *tok, gdb::unique_xmalloc_ptr<char> *cond_string,
+   int *thread, int *inferior, int *task,
+   gdb::unique_xmalloc_ptr<char> *rest, bool *force);
+
+#endif
diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index d940786e6d3..cc853c3251e 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -70,6 +70,7 @@
 #include "cli/cli-style.h"
 #include "cli/cli-decode.h"
 #include <unordered_set>
+#include "break-cond-parse.h"
 
 /* readline include files */
 #include "readline/tilde.h"
@@ -6318,20 +6319,7 @@ print_breakpoint_location (const breakpoint *b, const bp_location *loc)
       uiout->field_stream ("at", stb);
     }
   else
-    {
-      uiout->field_string ("pending", b->locspec->to_string ());
-      /* If extra_string is available, it could be holding a condition
-	 or dprintf arguments.  In either case, make sure it is printed,
-	 too, but only for non-MI streams.  */
-      if (!uiout->is_mi_like_p () && b->extra_string != NULL)
-	{
-	  if (b->type == bp_dprintf)
-	    uiout->text (",");
-	  else
-	    uiout->text (" ");
-	  uiout->text (b->extra_string.get ());
-	}
-    }
+    uiout->field_string ("pending", b->locspec->to_string ());
 
   if (loc && is_breakpoint (b)
       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
@@ -8696,8 +8684,8 @@ code_breakpoint::code_breakpoint (struct gdbarch *gdbarch_,
      command line, otherwise it's an error.  */
   if (type == bp_dprintf)
     update_dprintf_command_list (this);
-  else if (extra_string != nullptr)
-    error (_("Garbage '%s' at end of command"), extra_string.get ());
+  else
+    gdb_assert (extra_string == nullptr);
 
   /* The order of the locations is now stable.  Set the location
      condition using the location's number.  */
@@ -8926,197 +8914,6 @@ check_fast_tracepoint_sals (struct gdbarch *gdbarch,
     }
 }
 
-/* Given TOK, a string specification of condition and thread, as accepted
-   by the 'break' command, extract the condition string into *COND_STRING.
-   If no condition string is found then *COND_STRING is set to nullptr.
-
-   If the breakpoint specification has an associated thread, task, or
-   inferior, these are extracted into *THREAD, *TASK, and *INFERIOR
-   respectively, otherwise these arguments are set to -1 (for THREAD and
-   INFERIOR) or 0 (for TASK).
-
-   PC identifies the context at which the condition should be parsed.  */
-
-static void
-find_condition_and_thread (const char *tok, CORE_ADDR pc,
-			   gdb::unique_xmalloc_ptr<char> *cond_string,
-			   int *thread, int *inferior, int *task,
-			   gdb::unique_xmalloc_ptr<char> *rest)
-{
-  cond_string->reset ();
-  *thread = -1;
-  *inferior = -1;
-  *task = -1;
-  rest->reset ();
-  bool force = false;
-
-  while (tok && *tok)
-    {
-      const char *end_tok;
-      int toklen;
-      const char *cond_start = NULL;
-      const char *cond_end = NULL;
-
-      tok = skip_spaces (tok);
-
-      if ((*tok == '"' || *tok == ',') && rest)
-	{
-	  rest->reset (savestring (tok, strlen (tok)));
-	  break;
-	}
-
-      end_tok = skip_to_space (tok);
-
-      toklen = end_tok - tok;
-
-      if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
-	{
-	  tok = cond_start = end_tok + 1;
-	  try
-	    {
-	      parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
-	    }
-	  catch (const gdb_exception_error &)
-	    {
-	      if (!force)
-		throw;
-	      else
-		tok = tok + strlen (tok);
-	    }
-	  cond_end = tok;
-	  cond_string->reset (savestring (cond_start, cond_end - cond_start));
-	}
-      else if (toklen >= 1 && strncmp (tok, "-force-condition", toklen) == 0)
-	{
-	  tok = tok + toklen;
-	  force = true;
-	}
-      else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
-	{
-	  const char *tmptok;
-	  struct thread_info *thr;
-
-	  if (*thread != -1)
-	    error(_("You can specify only one thread."));
-
-	  if (*task != -1)
-	    error (_("You can specify only one of thread or task."));
-
-	  if (*inferior != -1)
-	    error (_("You can specify only one of inferior or thread."));
-
-	  tok = end_tok + 1;
-	  thr = parse_thread_id (tok, &tmptok);
-	  if (tok == tmptok)
-	    error (_("Junk after thread keyword."));
-	  *thread = thr->global_num;
-	  tok = tmptok;
-	}
-      else if (toklen >= 1 && strncmp (tok, "inferior", toklen) == 0)
-	{
-	  if (*inferior != -1)
-	    error(_("You can specify only one inferior."));
-
-	  if (*task != -1)
-	    error (_("You can specify only one of inferior or task."));
-
-	  if (*thread != -1)
-	    error (_("You can specify only one of inferior or thread."));
-
-	  char *tmptok;
-	  tok = end_tok + 1;
-	  *inferior = strtol (tok, &tmptok, 0);
-	  if (tok == tmptok)
-	    error (_("Junk after inferior keyword."));
-	  if (!valid_global_inferior_id (*inferior))
-	    error (_("Unknown inferior number %d."), *inferior);
-	  tok = tmptok;
-	}
-      else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
-	{
-	  char *tmptok;
-
-	  if (*task != -1)
-	    error(_("You can specify only one task."));
-
-	  if (*thread != -1)
-	    error (_("You can specify only one of thread or task."));
-
-	  if (*inferior != -1)
-	    error (_("You can specify only one of inferior or task."));
-
-	  tok = end_tok + 1;
-	  *task = strtol (tok, &tmptok, 0);
-	  if (tok == tmptok)
-	    error (_("Junk after task keyword."));
-	  if (!valid_task_id (*task))
-	    error (_("Unknown task %d."), *task);
-	  tok = tmptok;
-	}
-      else if (rest)
-	{
-	  rest->reset (savestring (tok, strlen (tok)));
-	  break;
-	}
-      else
-	error (_("Junk at end of arguments."));
-    }
-}
-
-/* Call 'find_condition_and_thread' for each sal in SALS until a parse
-   succeeds.  The parsed values are written to COND_STRING, THREAD,
-   TASK, and REST.  See the comment of 'find_condition_and_thread'
-   for the description of these parameters and INPUT.  */
-
-static void
-find_condition_and_thread_for_sals (const std::vector<symtab_and_line> &sals,
-				    const char *input,
-				    gdb::unique_xmalloc_ptr<char> *cond_string,
-				    int *thread, int *inferior, int *task,
-				    gdb::unique_xmalloc_ptr<char> *rest)
-{
-  int num_failures = 0;
-  for (auto &sal : sals)
-    {
-      gdb::unique_xmalloc_ptr<char> cond;
-      int thread_id = -1;
-      int inferior_id = -1;
-      int task_id = -1;
-      gdb::unique_xmalloc_ptr<char> remaining;
-
-      /* Here we want to parse 'arg' to separate condition from thread
-	 number.  But because parsing happens in a context and the
-	 contexts of sals might be different, try each until there is
-	 success.  Finding one successful parse is sufficient for our
-	 goal.  When setting the breakpoint we'll re-parse the
-	 condition in the context of each sal.  */
-      try
-	{
-	  find_condition_and_thread (input, sal.pc, &cond, &thread_id,
-				     &inferior_id, &task_id, &remaining);
-	  *cond_string = std::move (cond);
-	  /* A value of -1 indicates that these fields are unset.  At most
-	     one of these fields should be set (to a value other than -1)
-	     at this point.  */
-	  gdb_assert (((thread_id == -1 ? 1 : 0)
-		       + (task_id == -1 ? 1 : 0)
-		       + (inferior_id == -1 ? 1 : 0)) >= 2);
-	  *thread = thread_id;
-	  *inferior = inferior_id;
-	  *task = task_id;
-	  *rest = std::move (remaining);
-	  break;
-	}
-      catch (const gdb_exception_error &e)
-	{
-	  num_failures++;
-	  /* If no sal remains, do not continue.  */
-	  if (num_failures == sals.size ())
-	    throw;
-	}
-    }
-}
-
 /* Decode a static tracepoint marker spec.  */
 
 static std::vector<symtab_and_line>
@@ -9233,6 +9030,46 @@ create_breakpoint (struct gdbarch *gdbarch,
 	      ? (extra_string != nullptr && !parse_extra)
 	      : (extra_string == nullptr || parse_extra));
 
+  /* Will hold either copies of the similarly named function argument, or
+     will hold a modified version of the function argument, depending on
+     the value of PARSE_EXTRA.  */
+  gdb::unique_xmalloc_ptr<char> cond_string_copy;
+  gdb::unique_xmalloc_ptr<char> extra_string_copy;
+
+  if (parse_extra)
+    {
+      /* Parse EXTRA_STRING splitting the parts out.  */
+      create_breakpoint_parse_arg_string (extra_string, &cond_string_copy,
+					  &thread, &inferior, &task,
+					  &extra_string_copy,
+					  &force_condition);
+
+      /* We could check that EXTRA_STRING_COPY is empty at this point -- it
+	 should be, as we only get here for things that are not bp_dprintf,
+	 however, we prefer to give the location spec parser a chance to
+	 run first, this means the user will get errors about invalid
+	 location spec instead of an error about garbage at the end of the
+	 command line.
+
+	 We still do the EXTRA_STRING_COPY is empty check, just later in
+	 this function.  */
+
+      gdb_assert (thread == -1 || thread > 0);
+      gdb_assert (task == -1 || task > 0);
+      gdb_assert (inferior == -1 || inferior > 0);
+    }
+  else
+    {
+      if (cond_string != nullptr)
+	cond_string_copy.reset (xstrdup (cond_string));
+      if (extra_string != nullptr)
+	extra_string_copy.reset (xstrdup (extra_string));
+    }
+
+  /* Clear these.  Updated values are now held in the *_copy locals.  */
+  cond_string = nullptr;
+  extra_string = nullptr;
+
   try
     {
       ops->create_sals_from_location_spec (locspec, &canonical);
@@ -9268,6 +9105,13 @@ create_breakpoint (struct gdbarch *gdbarch,
 	throw;
     }
 
+  /* Only bp_dprintf breakpoints should have anything in EXTRA_STRING_COPY
+     by this point.  For all other breakpoints this indicates an error.  We
+     could place this check earlier in the function, but we prefer to see
+     errors from the location spec parser before we see this error message.  */
+  if (type_wanted != bp_dprintf && extra_string_copy.get () != nullptr)
+    error (_("Garbage '%s' at end of command"), extra_string_copy.get ());
+
   if (!pending && canonical.lsals.empty ())
     return 0;
 
@@ -9291,63 +9135,31 @@ create_breakpoint (struct gdbarch *gdbarch,
      breakpoint.  */
   if (!pending)
     {
-      gdb::unique_xmalloc_ptr<char> cond_string_copy;
-      gdb::unique_xmalloc_ptr<char> extra_string_copy;
-
-      if (parse_extra)
+      /* Check the validity of the condition.  We should error out if the
+	 condition is invalid at all of the locations and if it is not
+	 forced.  In the PARSE_EXTRA case above, this check is done when
+	 parsing the EXTRA_STRING.  */
+      if (cond_string_copy.get () != nullptr && !force_condition)
 	{
-	  gdb_assert (type_wanted != bp_dprintf);
-
-	  gdb::unique_xmalloc_ptr<char> rest;
-	  gdb::unique_xmalloc_ptr<char> cond;
-
+	  int num_failures = 0;
 	  const linespec_sals &lsal = canonical.lsals[0];
-
-	  find_condition_and_thread_for_sals (lsal.sals, extra_string,
-					      &cond, &thread, &inferior,
-					      &task, &rest);
-
-	  if (rest.get () != nullptr && *(rest.get ()) != '\0')
-	    error (_("Garbage '%s' at end of command"), rest.get ());
-
-	  cond_string_copy = std::move (cond);
-	  extra_string_copy = std::move (rest);
-	}
-      else
-	{
-	  /* Check the validity of the condition.  We should error out
-	     if the condition is invalid at all of the locations and
-	     if it is not forced.  In the PARSE_EXTRA case above, this
-	     check is done when parsing the EXTRA_STRING.  */
-	  if (cond_string != nullptr && !force_condition)
+	  for (const auto &sal : lsal.sals)
 	    {
-	      int num_failures = 0;
-	      const linespec_sals &lsal = canonical.lsals[0];
-	      for (const auto &sal : lsal.sals)
+	      const char *cond = cond_string_copy.get ();
+	      try
 		{
-		  const char *cond = cond_string;
-		  try
-		    {
-		      parse_exp_1 (&cond, sal.pc, block_for_pc (sal.pc), 0);
-		      /* One success is sufficient to keep going.  */
-		      break;
-		    }
-		  catch (const gdb_exception_error &)
-		    {
-		      num_failures++;
-		      /* If this is the last sal, error out.  */
-		      if (num_failures == lsal.sals.size ())
-			throw;
-		    }
+		  parse_exp_1 (&cond, sal.pc, block_for_pc (sal.pc), 0);
+		  /* One success is sufficient to keep going.  */
+		  break;
+		}
+	      catch (const gdb_exception_error &)
+		{
+		  num_failures++;
+		  /* If this is the last sal, error out.  */
+		  if (num_failures == lsal.sals.size ())
+		    throw;
 		}
 	    }
-
-	  /* Create a private copy of condition string.  */
-	  if (cond_string)
-	    cond_string_copy.reset (xstrdup (cond_string));
-	  /* Create a private copy of any extra string.  */
-	  if (extra_string)
-	    extra_string_copy.reset (xstrdup (extra_string));
 	}
 
       ops->create_breakpoints_sal (gdbarch, &canonical,
@@ -9364,21 +9176,16 @@ create_breakpoint (struct gdbarch *gdbarch,
 								 type_wanted);
       b->locspec = locspec->clone ();
 
-      if (parse_extra)
-	b->cond_string = NULL;
-      else
-	{
-	  /* Create a private copy of condition string.  */
-	  b->cond_string.reset (cond_string != NULL
-				? xstrdup (cond_string)
-				: NULL);
-	  b->thread = thread;
-	}
+      /* Create a private copy of the condition string.  */
+      b->cond_string = std::move (cond_string_copy);
+
+      b->thread = thread;
+      b->task = task;
+      b->inferior = inferior;
 
       /* Create a private copy of any extra string.  */
-      b->extra_string.reset (extra_string != NULL
-			     ? xstrdup (extra_string)
-			     : NULL);
+      b->extra_string = std::move (extra_string_copy);
+
       b->ignore_count = ignore_count;
       b->disposition = tempflag ? disp_del : disp_donttouch;
       b->condition_not_parsed = 1;
@@ -9387,9 +9194,12 @@ create_breakpoint (struct gdbarch *gdbarch,
 	   && type_wanted != bp_hardware_breakpoint) || thread != -1)
 	b->pspace = current_program_space;
 
+      if (b->type == bp_dprintf)
+	update_dprintf_command_list (b.get ());
+
       install_breakpoint (internal, std::move (b), 0);
     }
-  
+
   if (canonical.lsals.size () > 1)
     {
       warning (_("Multiple breakpoints were set.\nUse the "
@@ -13120,24 +12930,6 @@ code_breakpoint::location_spec_to_sals (location_spec *locspec,
     {
       for (auto &sal : sals)
 	resolve_sal_pc (&sal);
-      if (condition_not_parsed && extra_string != NULL)
-	{
-	  gdb::unique_xmalloc_ptr<char> local_cond, local_extra;
-	  int local_thread, local_task, local_inferior;
-
-	  find_condition_and_thread_for_sals (sals, extra_string.get (),
-					      &local_cond, &local_thread,
-					      &local_inferior,
-					      &local_task, &local_extra);
-	  gdb_assert (cond_string == nullptr);
-	  if (local_cond != nullptr)
-	    cond_string = std::move (local_cond);
-	  thread = local_thread;
-	  task = local_task;
-	  if (local_extra != nullptr)
-	    extra_string = std::move (local_extra);
-	  condition_not_parsed = 0;
-	}
 
       if (type == bp_static_tracepoint)
 	{
diff --git a/gdb/testsuite/gdb.ada/tasks.exp b/gdb/testsuite/gdb.ada/tasks.exp
index 6e588408c9d..ecbfbd5522f 100644
--- a/gdb/testsuite/gdb.ada/tasks.exp
+++ b/gdb/testsuite/gdb.ada/tasks.exp
@@ -55,11 +55,11 @@ gdb_test "watch j task 1 task 3" "You can specify only one task\\."
 
 # Check that attempting to combine 'task' and 'thread' gives an error.
 gdb_test "break break_me task 1 thread 1" \
-    "You can specify only one of thread or task\\."
+    "You can specify only one of thread, inferior, or task\\."
 gdb_test "break break_me thread 1 task 1" \
-    "You can specify only one of thread or task\\."
+    "You can specify only one of thread, inferior, or task\\."
 gdb_test "break break_me inferior 1 task 1" \
-    "You can specify only one of inferior or task\\."
+    "You can specify only one of thread, inferior, or task\\."
 gdb_test "watch j task 1 thread 1" \
     "You can specify only one of thread or task\\."
 gdb_test "watch j thread 1 task 1" \
diff --git a/gdb/testsuite/gdb.base/condbreak.exp b/gdb/testsuite/gdb.base/condbreak.exp
index 65d19b3e7a9..3b619e47bfc 100644
--- a/gdb/testsuite/gdb.base/condbreak.exp
+++ b/gdb/testsuite/gdb.base/condbreak.exp
@@ -179,6 +179,10 @@ gdb_test "break -q main if (1==1) thread 999" \
     "Unknown thread 999\\."
 gdb_test "break -q main thread 999 if (1==1)" \
     "Unknown thread 999\\."
+gdb_test "break -q main if (1==1) thread 999 -force-condition" \
+    "Unknown thread 999\\."
+gdb_test "break -q main thread 999 if (1==1) -force-condition" \
+    "Unknown thread 999\\."
 
 # Verify that both if and thread can be distinguished from a breakpoint
 # address expression.
@@ -186,20 +190,71 @@ gdb_test "break *main if (1==1) thread 999" \
     "Unknown thread 999\\."
 gdb_test "break *main thread 999 if (1==1)" \
     "Unknown thread 999\\."
+gdb_test "break *main if (1==1) thread 999 -force-condition" \
+    "Unknown thread 999\\."
+gdb_test "break *main thread 999 if (1==1) -force-condition" \
+    "Unknown thread 999\\."
 
 # Similarly for task.
 gdb_test "break *main if (1==1) task 999" \
     "Unknown task 999\\."
 gdb_test "break *main task 999 if (1==1)" \
     "Unknown task 999\\."
+gdb_test "break *main if (1==1) task 999 -force-condition" \
+    "Unknown task 999\\."
+gdb_test "break *main task 999 if (1==1) -force-condition" \
+    "Unknown task 999\\."
 
-# GDB accepts abbreviations for "thread" and "task".
+# GDB accepts abbreviations for "thread", "task" and
+# "-force-condition", when these keywords appear after
+# the breakpoint condition.
 gdb_test "break *main if (1==1) t 999" \
     "Unknown thread 999\\."
 gdb_test "break *main if (1==1) th 999" \
     "Unknown thread 999\\."
 gdb_test "break *main if (1==1) ta 999" \
     "Unknown task 999\\."
+gdb_test "break *main if (1==1) t 999 -force" \
+    "Unknown thread 999\\."
+gdb_test "break *main if (1==1) th 999 -force" \
+    "Unknown thread 999\\."
+gdb_test "break *main if (1==1) ta 999 -force" \
+    "Unknown task 999\\."
+
+# Check the use of abbreviations before the condition.  This works
+# because, when the location spec starts with '*' GDB is able to
+# figure out that the complete location is '*main'.
+gdb_test "break *main t 999 if (1==1)" \
+    "Unknown thread 999\\."
+gdb_test "break *main th 999 if (1==1)" \
+    "Unknown thread 999\\."
+gdb_test "break *main ta 999 if (1==1)" \
+    "Unknown task 999\\."
+gdb_test "break *main t 999 -force if (1==1)" \
+    "Unknown thread 999\\."
+gdb_test "break *main th 999 -force if (1==1)" \
+    "Unknown thread 999\\."
+gdb_test "break *main ta 999 -force if (1==1)" \
+    "Unknown task 999\\."
+
+# However, when the location spec doesn't start with '*' GDB relies on
+# the linespec parser to spot the keyword which marks the end of the
+# linespec, and this parser doesn't check for abbreviations.
+gdb_test "with breakpoint pending off -- break main t 999 if (1==1)" \
+    "Function \"main t 999\" not defined\\."
+gdb_test "with breakpoint pending off -- break main th 999 if (1==1)" \
+    "Function \"main th 999\" not defined\\."
+gdb_test "with breakpoint pending off -- break main ta 999 if (1==1)" \
+    "Function \"main ta 999\" not defined\\."
+
+# GDB does not treat a "-force-condition" flag that appears
+# immediately after the condition as the flag, but instead treats it
+# as " - force - condition", that is, subtraction of the symbol
+# "force" followed by subtraction of symbol "context".  This is really
+# just a quirk of how this used to be implemented, and should maybe be
+# changed in the future.  However, for now GDB retains this behaviour.
+gdb_test "break *main if (1==1) -force-condition" \
+    "No symbol \"force\" in current context\\."
 
 set test "run until breakpoint at marker3"
 gdb_test_multiple "continue" $test {
diff --git a/gdb/testsuite/gdb.base/pending.exp b/gdb/testsuite/gdb.base/pending.exp
index 737b0c4e5d0..0cb86377400 100644
--- a/gdb/testsuite/gdb.base/pending.exp
+++ b/gdb/testsuite/gdb.base/pending.exp
@@ -170,7 +170,8 @@ gdb_test "info break" \
 \[\t \]+stop only if k == 1.*
 \[\t \]+print k.*
 \[0-9\]+\[\t \]+breakpoint     keep y.* in main at .*$srcfile:$mainline.*
-\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc if x > 3.*" \
+\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc.*
+\\s+stop only if x > 3.*" \
 "multiple pending breakpoints"
 
 
@@ -195,8 +196,10 @@ gdb_test "info break" \
 \[\t \]+stop only if k == 1.*
 \[\t \]+print k.*
 \[0-9\]+\[\t \]+breakpoint     keep y.* in main at .*$srcfile:$mainline.*
-\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc if x > 3.*
-\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp3_loc.*ignore next 2 hits.*" \
+\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc.*
+\\s+stop only if x > 3.*
+\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp3_loc.*
+\\s+ignore next 2 hits.*" \
 "multiple pending breakpoints 2"
 
 #
@@ -267,3 +270,17 @@ gdb_test "info break" \
 \[0-9\]+\[\t \]+breakpoint     keep y.* in main at .*$srcfile:$mainline.*
 \[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*imaginary.*" \
 "verify pending breakpoint after restart"
+
+# Test GDB's parsing of pending breakpoint thread and condition.
+
+gdb_test_no_output "set breakpoint pending on"
+gdb_test "break foo if (unknown_var && another_unknown_var) thread 1" \
+    "Breakpoint $decimal \\(foo\\) pending\\."
+set bpnum [get_integer_valueof "\$bpnum" "*INVALID" \
+	       "get number for foo breakpoint"]
+gdb_test "info breakpoints $bpnum" \
+    [multi_line \
+	 "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	 "\\s+stop only if \\(unknown_var && another_unknown_var\\)" \
+	 "\\s+stop only in thread 1"] \
+    "check pending breakpoint on foo"
diff --git a/gdb/testsuite/gdb.linespec/explicit.exp b/gdb/testsuite/gdb.linespec/explicit.exp
index 625f9cee0fc..9a11182fae7 100644
--- a/gdb/testsuite/gdb.linespec/explicit.exp
+++ b/gdb/testsuite/gdb.linespec/explicit.exp
@@ -575,7 +575,7 @@ namespace eval $testfile {
 	      allow-pending]} {
 	fail "set $tst"
     } else {
-	gdb_test "info break" ".*PENDING.*myfunction if foofoofoo == 1.*" $tst
+	gdb_test "info break" ".*PENDING.*myfunction\r\n\\s+stop only if foofoofoo == 1.*" $tst
     }
 
     gdb_exit
@@ -586,7 +586,7 @@ namespace eval $testfile {
 	      allow-pending]} {
 	fail "set $tst"
     } else {
-	gdb_test "info break" ".*PENDING.*myfunction if arg == 0" $tst
+	gdb_test "info break" ".*PENDING.*myfunction\r\n\\s+stop only if arg == 0" $tst
 
 	gdb_load [standard_output_file $exefile]
 	gdb_test "info break" \
diff --git a/gdb/testsuite/gdb.linespec/keywords.exp b/gdb/testsuite/gdb.linespec/keywords.exp
index 36a919c8be2..d2596d2b357 100644
--- a/gdb/testsuite/gdb.linespec/keywords.exp
+++ b/gdb/testsuite/gdb.linespec/keywords.exp
@@ -55,7 +55,7 @@ with_test_prefix "trailing whitespace" {
 gdb_test "break thread 123" "Unknown thread 123\\."
 gdb_test "break thread foo" "Invalid thread ID: foo"
 gdb_test "break task 123" "Unknown task 123\\."
-gdb_test "break task foo" "Junk after task keyword\\."
+gdb_test "break task foo" "Junk 'foo' after task keyword\\."
 gdb_breakpoint "thread if 0" "message"
 
 # These are also NULL locations, but using a subsequent keyword
@@ -63,9 +63,9 @@ gdb_breakpoint "thread if 0" "message"
 gdb_test "break thread thread" "Invalid thread ID: thread"
 gdb_test "break thread task" "Invalid thread ID: task"
 gdb_test "break thread if" "Invalid thread ID: if"
-gdb_test "break task task" "Junk after task keyword\\."
-gdb_test "break task thread" "Junk after task keyword\\."
-gdb_test "break task if" "Junk after task keyword\\."
+gdb_test "break task task" "Junk 'task' after task keyword\\."
+gdb_test "break task thread" "Junk 'thread' after task keyword\\."
+gdb_test "break task if" "Junk 'if' after task keyword\\."
 
 # Test locations containing keyword followed by keyword.
 gdb_test "break thread thread 123" "Unknown thread 123\\."
diff --git a/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp b/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp
index fd5684bd2b1..4cf6dec4b41 100644
--- a/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp
+++ b/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp
@@ -50,7 +50,8 @@ set bp_location1 [gdb_get_line_number "set breakpoint 1 here"]
 # Set pending dprintf via MI.
 set bp [mi_make_breakpoint_pending -number "1" -type "dprintf" \
 	    -disp "keep" -enabled "y" -pending "pendfunc1" \
-	    -original-location "pendfunc1"]
+	    -original-location "pendfunc1" \
+	    -script {\["printf \\\"hello\\\""\]}]
 mi_gdb_test "-dprintf-insert -f pendfunc1 \"hello\"" \
     ".*\\^done,$bp" "mi set dprintf"
 
diff --git a/gdb/testsuite/gdb.multi/inferior-specific-bp.exp b/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
index 5cc451b0ecc..46efe6f54bc 100644
--- a/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
+++ b/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
@@ -51,9 +51,9 @@ if {![runto_main]} {
 # this should fail.  Try with the keywords in both orders just in case the
 # parser has a bug.
 gdb_test "break foo thread 1.1 inferior 1" \
-    "You can specify only one of inferior or thread\\."
+    "You can specify only one of thread, inferior, or task\\."
 gdb_test "break foo inferior 1 thread 1.1" \
-    "You can specify only one of inferior or thread\\."
+    "You can specify only one of thread, inferior, or task\\."
 
 # Try to create a breakpoint using the 'inferior' keyword multiple times.
 gdb_test "break foo inferior 1 inferior 2" \
diff --git a/gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c b/gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
new file mode 100644
index 00000000000..15d1b9833dd
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
@@ -0,0 +1,22 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+int global_var = 0;
+
+void
+foo (int arg)
+{
+  global_var = arg;
+}
diff --git a/gdb/testsuite/gdb.threads/del-pending-thread-bp.c b/gdb/testsuite/gdb.threads/del-pending-thread-bp.c
new file mode 100644
index 00000000000..6fc76dbf08c
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/del-pending-thread-bp.c
@@ -0,0 +1,85 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#include <dlfcn.h>
+#include <pthread.h>
+#include <stdlib.h>
+
+pthread_barrier_t barrier;
+
+static void
+barrier_wait (pthread_barrier_t *b)
+{
+  int res = pthread_barrier_wait (b);
+  if (res != 0 && res != PTHREAD_BARRIER_SERIAL_THREAD)
+    abort ();
+}
+
+static void *
+thread_worker (void *arg)
+{
+  barrier_wait (&barrier);
+  return NULL;
+}
+
+void
+breakpt (void)
+{
+  /* Nothing.  */
+}
+
+int
+main (void)
+{
+  void *handle;
+  void (*func)(int);
+  pthread_t thread;
+
+  if (pthread_barrier_init (&barrier, NULL, 2) != 0)
+    abort ();
+
+  if (pthread_create (&thread, NULL, thread_worker, NULL) != 0)
+    abort ();
+
+  breakpt ();
+
+  /* Allow the worker thread to complete.  */
+  barrier_wait (&barrier);
+
+  if (pthread_join (thread, NULL) != 0)
+    abort ();
+
+  breakpt ();
+
+  /* Now load the shared library.  */
+  handle = dlopen (SHLIB_NAME, RTLD_LAZY);
+  if (handle == NULL)
+    abort ();
+
+  /* Find the function symbol.  */
+  func = (void (*)(int)) dlsym (handle, "foo");
+
+  /* Call the library function.  */
+  func (1);
+
+  /* Unload the shared library.  */
+  if (dlclose (handle) != 0)
+    abort ();
+
+  breakpt ();
+
+  return 0;
+}
+
diff --git a/gdb/testsuite/gdb.threads/del-pending-thread-bp.exp b/gdb/testsuite/gdb.threads/del-pending-thread-bp.exp
new file mode 100644
index 00000000000..b919145ed41
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/del-pending-thread-bp.exp
@@ -0,0 +1,108 @@
+# Copyright 2023 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+# This test checks that pending thread-specific breakpoints are
+# correctly deleted when the thread the breakpoint is for goes out of
+# scope.
+#
+# We also check that we can't create a pending thread-specific
+# breakpoint for a non-existent thread.
+
+require allow_shlib_tests
+
+standard_testfile
+
+set libname $testfile-lib
+set srcfile_lib $srcdir/$subdir/$libname.c
+set binfile_lib [standard_output_file $libname.so]
+
+if { [gdb_compile_shlib $srcfile_lib $binfile_lib {}] != "" } {
+    untested "failed to compile shared library 1"
+    return -1
+}
+
+set binfile_lib_target [gdb_download_shlib $binfile_lib]
+
+if { [prepare_for_testing "failed to prepare" $testfile $srcfile \
+	  [list debug \
+	       additional_flags=-DSHLIB_NAME=\"$binfile_lib_target\" \
+	       shlib_load pthreads]] } {
+    return -1
+}
+
+gdb_locate_shlib $binfile_lib
+
+if ![runto_main] {
+    return 0
+}
+
+# Run until we have two threads.
+gdb_breakpoint "breakpt"
+gdb_continue_to_breakpoint "first breakpt call"
+
+# Confirm that we have a thread '2'.
+gdb_test "info threads" "\r\n\\s+2\\s+\[^\r\n\]+"
+
+# Create a pending, thread-specific, breakpoint on 'foo'.
+gdb_breakpoint "foo thread 2" allow-pending
+set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+	       "get breakpoint number"]
+
+# Check we can't create a pending thread-specific breakpoint for a
+# non-existent thread.
+gdb_test "with breakpoint pending on -- break foo thread 99" \
+    "Unknown thread 99\\."
+
+# Continue to 'breakpt' again.  Don't use gdb_continue_to_breakpoint
+# as we are looking for the thread exited and breakpoint deleted
+# messages.
+set output [list "Continuing\\."]
+
+if {!([target_info exists gdb_protocol]
+      && ([target_info gdb_protocol] == "remote"
+	  || [target_info gdb_protocol] == "extended-remote"))} {
+    # Due to bug PR gdb/30129 we don't see the thread exited messages
+    # for remote targets.  When this bit of this test can be cleaned
+    # up.
+    lappend output "\\\[Thread \[^\r\n\]+ exited\\\]"
+}
+
+lappend output "Thread-specific breakpoint $bpnum deleted - thread 2 no longer in the thread list\\." \
+    "" \
+    "Thread 1 \[^\r\n\]+, breakpt \\(\\) at \[^\r\n\]+" \
+    "$decimal\\s+\[^\r\n\]+"
+
+gdb_test "continue" \
+    [multi_line {*}$output] \
+    "second breakpt call"
+
+# Confirm breakpoint has been deleted.
+gdb_test "info breakpoints $bpnum" \
+    "No breakpoint, watchpoint, tracepoint, or catchpoint matching '$bpnum'\\."
+
+# Continue again.  This will pass through 'foo'.  We should not stop
+# in 'foo', the breakpoint has been deleted.  We should next stop in
+# breakpt again.
+gdb_test "continue" \
+    [multi_line \
+	 "Continuing\\." \
+	 "" \
+	 "Thread 1 \[^\r\n\]+ hit Breakpoint $decimal, breakpt \\(\\) at \[^\r\n\]+" \
+	 "$decimal\\s+\[^\r\n\]+"] \
+    "third breakpt call"
+gdb_test "bt 1" \
+    [multi_line \
+	 "#0\\s+breakpt \\(\\) at \[^\r\n\]+" \
+	 "\\(More stack frames follow\\.\\.\\.\\)"]
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv9 13/14] gdb: don't set breakpoint::pspace in create_breakpoint
  2024-03-05 15:21               ` [PATCHv9 00/14] thread-specific breakpoints in just some inferiors Andrew Burgess
                                   ` (11 preceding siblings ...)
  2024-03-05 15:21                 ` [PATCHv9 12/14] gdb: parse pending breakpoint thread/task immediately Andrew Burgess
@ 2024-03-05 15:21                 ` Andrew Burgess
  2024-03-05 15:21                 ` [PATCHv9 14/14] gdb: only insert thread-specific breakpoints in the relevant inferior Andrew Burgess
  2024-03-31 10:31                 ` [PATCHv10 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
  14 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2024-03-05 15:21 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

I spotted this code within create_breakpoint:

  if ((type_wanted != bp_breakpoint
      && type_wanted != bp_hardware_breakpoint) || thread != -1)
   b->pspace = current_program_space;

this code is only executed when creating a pending breakpoint, and
sets the breakpoint::pspace member variable.

The above code gained the 'thread != -1' clause with this commit:

  commit cc72b2a2da6d6372cbdb1d14639a5fce84e1a325
  Date:   Fri Dec 23 17:06:16 2011 +0000

              Introduce gdb.FinishBreakpoint in Python

While the type_wanted checks were added with this commit:

  commit f8eba3c61629b3c03ac1f33853eab4d8507adb9c
  Date:   Tue Dec 6 18:54:43 2011 +0000

      the "ambiguous linespec" series

Before this breakpoint::pspace was set unconditionally.

If we look at how breakpoint::pspace is used today, some breakpoint
types specifically set this field, either in their constructors, or in
a wrapper function that calls the constructor.  So, the watchpoint
type and its sub-class set this variable, as does the catchpoint type,
and all it's sub-classes.

However, code_breakpoint doesn't specifically set this field within
its constructor, though some sub-classes of
code_breakpoint (ada_catchpoint, exception_catchpoint,
internal_breakpoint, and momentary_breakpoint) do set this field.

When I examine all the places that breakpoint::pspace is used, I
believe that in every place where it is expected that this field is
set, the breakpoint type will be one that specifically sets this
field.

Next, I observe two problems with the existing code.

First, the above code is only hit for pending breakpoints, there's no
equivalent code for non-pending breakpoints.  This opens up the
possibility of GDB entering non-consistent states; if a breakpoint is
first created pending and then later gets a location, the pspace field
will be set, while if the breakpoint is immediately non-pending, then
the pspace field will never be set.

Second, if we look at how breakpoint::pspace is used in the function
breakpoint_program_space_exit, we see that when a program space is
removed, any breakpoint with breakpoint::pspace set to the removed
program space, will be deleted.  This makes sense, but does mean we
need to ensure breakpoint::pspace is only set for breakpoints that
apply to a single program space.

So, if I create a pending dprintf breakpoint (type bp_dprintf) then
the breakpoint::pspace variable will be set even though the dprintf is
not really tied to that one program space.  As a result, when the
matching program space is removed the dprintf is incorrectly removed.

Also, if I create a thread specific breakpoint, then, thanks to the
'thread != -1' clause the wrong program space will be stored in
breakpoint::pspace (the current program space is always used, which
might not be the program space that corresponds to the selected
thread), as a result, the thread specific breakpoint will be deleted
when the matching program space is removed.

If we look at commit cc72b2a2da6d which added the 'thread != -1'
clause, we can see this change was entirely redundant, the
breakpoint::pspace is also set in bpfinishpy_init after
create_breakpoint has been called.  As such, I think we can safely
drop the 'thread != -1' clause.

For the other problems, I'm proposing to be pretty aggressive - I'd
like to drop the breakpoint::pspace assignment completely from
create_breakpoint.  Having looked at how this variable is used, I
believe that it is already set elsewhere in all the cases that it is
needed.  Maybe this code was needed at one time, but I can't see how
it's needed any more.

There's tests to expose the issues I've spotted with this code, and
there's no regressions in testing.
---
 gdb/breakpoint.c                              |   3 -
 gdb/breakpoint.h                              |  18 +-
 .../gdb.multi/pending-bp-del-inferior.c       |  28 +++
 .../gdb.multi/pending-bp-del-inferior.exp     | 216 ++++++++++++++++++
 4 files changed, 259 insertions(+), 6 deletions(-)
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-del-inferior.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index cc853c3251e..e1efde66feb 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -9190,9 +9190,6 @@ create_breakpoint (struct gdbarch *gdbarch,
       b->disposition = tempflag ? disp_del : disp_donttouch;
       b->condition_not_parsed = 1;
       b->enable_state = enabled ? bp_enabled : bp_disabled;
-      if ((type_wanted != bp_breakpoint
-	   && type_wanted != bp_hardware_breakpoint) || thread != -1)
-	b->pspace = current_program_space;
 
       if (b->type == bp_dprintf)
 	update_dprintf_command_list (b.get ());
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index 24aeaf926ec..42b49144e79 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -831,9 +831,21 @@ struct breakpoint : public intrusive_list_node<breakpoint>
      equals this.  */
   struct frame_id frame_id = null_frame_id;
 
-  /* The program space used to set the breakpoint.  This is only set
-     for breakpoints which are specific to a program space; for
-     non-thread-specific ordinary breakpoints this is NULL.  */
+  /* The program space used to set the breakpoint.  This is only set for
+     breakpoints that are not type bp_breakpoint or bp_hardware_breakpoint.
+     For thread or inferior specific breakpoints, the breakpoints are
+     managed via the thread and inferior member variables.  */
+
+  /* If not nullptr then this is the program space for which this
+     breakpoint was created.  All watchpoint and catchpoint sub-types set
+     this field, but not all of the code_breakpoint sub-types do;
+     generally, user created breakpoint types don't set this field, though
+     things might be more consistent if they did.
+
+     When this variable is nullptr then a breakpoint might be associated
+     with multiple program spaces, though you need to check the thread,
+     inferior and task variables to see if a breakpoint was created for a
+     specific thread, inferior, or Ada task respectively.  */
   program_space *pspace = NULL;
 
   /* The location specification we used to set the breakpoint.  */
diff --git a/gdb/testsuite/gdb.multi/pending-bp-del-inferior.c b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.c
new file mode 100644
index 00000000000..1d030007819
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.c
@@ -0,0 +1,28 @@
+/* This testcase is part of GDB, the GNU debugger.
+
+   Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+int
+foo (void)
+{
+  return 0;
+}
+
+int
+main (void)
+{
+  return foo ();
+}
diff --git a/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
new file mode 100644
index 00000000000..5fcd1ef2e39
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
@@ -0,0 +1,216 @@
+# Copyright 2023 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+# Setup two inferiors.  Select one inferior and create a pending
+# thread specific breakpoint in the other inferior.
+#
+# Delete the selected inferior (the one for which the thread specific
+# breakpoint doesn't apply), and check that the breakpoint still exists.
+#
+# Repeat this process, but this time, create an inferior specific
+# breakpoint.
+
+# The plain remote target can't do multiple inferiors.
+require !use_gdb_stub
+
+standard_testfile
+
+if {[prepare_for_testing "failed to prepare" $testfile $srcfile]} {
+    return -1
+}
+
+# Setup for the tests.  Create two inferiors, both running the global
+# BINFILE, and proceed to main in both inferiors.  Delete all
+# breakpoints, and check that we do have two threads.
+#
+# Return true after a successful setup, otherwise, return false.
+proc test_setup {} {
+    clean_restart $::binfile
+
+    if {![runto_main]} {
+	return 0
+    }
+
+    gdb_test "add-inferior -exec ${::binfile}" "Added inferior 2.*" \
+	"add inferior 2"
+    gdb_test "inferior 2" "Switching to inferior 2 .*" \
+	"select inferior 2"
+
+    if {![runto_main]} {
+	return 0
+    }
+
+    delete_breakpoints
+
+    gdb_test "info threads" \
+	[multi_line \
+	     "  Id\\s+Target Id\\s+Frame\\s*" \
+	     "  1\\.1\\s+\[^\r\n\]+" \
+	     "\\* 2\\.1\\s+\[^\r\n\]+"] \
+	"check we have the expected threads"
+
+    return 1
+}
+
+# Assuming inferior 2 is already selected, kill the current inferior
+# (inferior 2), select inferior 1, and then remove inferior 2.
+proc kill_and_remove_inferior_2 {} {
+    gdb_test "kill" "" "kill inferior 2" \
+	"Kill the program being debugged.*y or n. $" "y"
+
+    gdb_test "inferior 1" "Switching to inferior 1 .*" \
+	"select inferior 1"
+
+    gdb_test_no_output "remove-inferiors 2"
+}
+
+# Setup two inferiors, then create a breakpoint.  If BP_PENDING is
+# true then the breakpoint will be pending, otherwise, the breakpoint
+# will be non-pending.
+#
+# BP_TYPE is either 'thread' or 'inferior', and indicates if the
+# created breakpoint should be thread or inferior specific.
+#
+# The breakpoint is created while inferior 2 is selected, and the
+# thread/inferior restriction always identifies inferior 1.
+#
+# Then inferior 2 is killed and removed.
+#
+# Finally, check that the breakpoint still exists and correctly refers
+# to inferior 1.
+proc do_bp_test { bp_type bp_pending } {
+    if {![test_setup]} {
+	return
+    }
+
+    if { $bp_pending } {
+	set bp_func "bar"
+    } else {
+	set bp_func "foo"
+    }
+
+    if { $bp_type eq "thread" } {
+	set bp_restriction "thread 1.1"
+    } else {
+	set bp_restriction "inferior 1"
+    }
+
+    gdb_breakpoint "$bp_func $bp_restriction" allow-pending
+    set bp_number [get_integer_valueof "\$bpnum" "INVALID" \
+		       "get b/p number for previous breakpoint"]
+
+    if { $bp_restriction eq "thread 1.1" } {
+	set bp_after_restriction "thread 1"
+    } else {
+	set bp_after_restriction $bp_restriction
+    }
+
+    if { $bp_pending } {
+	set bp_pattern_before \
+	    [multi_line \
+		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+${bp_func}" \
+		 "\\s+stop only in [string_to_regexp $bp_restriction]"]
+	set bp_pattern_after \
+	    [multi_line \
+		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+${bp_func}" \
+		 "\\s+stop only in [string_to_regexp $bp_after_restriction]"]
+    } else {
+	set bp_pattern_before \
+	    [multi_line \
+		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+<MULTIPLE>\\s*" \
+		 "\\s+stop only in [string_to_regexp $bp_restriction]" \
+		 "$bp_number\\.1\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 1" \
+		 "$bp_number\\.2\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 2"]
+
+	set bp_pattern_after \
+	    [multi_line \
+		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+" \
+		 "\\s+stop only in [string_to_regexp $bp_after_restriction]"]
+    }
+
+    gdb_test "info breakpoints" $bp_pattern_before \
+	"info breakpoints before inferior removal"
+
+    kill_and_remove_inferior_2
+
+    gdb_test "info breakpoints" $bp_pattern_after \
+	"info breakpoints after inferior removal"
+}
+
+# Setup two inferiors, then create a dprintf.  If BP_PENDING is
+# true then the dprintf will be pending, otherwise, the dprintf
+# will be non-pending.
+#
+# The dprintf is created while inferior 2 is selected.  Then inferior
+# 2 is killed and removed.
+#
+# Finally, check that the dprintf still exists.
+proc do_dprintf_test { bp_pending } {
+    if {![test_setup]} {
+	return
+    }
+
+    if { $bp_pending } {
+	set bp_func "bar"
+
+	gdb_test "dprintf $bp_func,\"in $bp_func\"" ".*" \
+	    "create dprintf breakpoint" \
+	    "Make dprintf pending on future shared library load\\? \\(y or .n.\\) $" "y"
+    } else {
+	set bp_func "foo"
+
+	gdb_test "dprintf $bp_func,\"in $bp_func\"" ".*" \
+	    "create dprintf breakpoint"
+    }
+
+    set bp_number [get_integer_valueof "\$bpnum" "INVALID" \
+		       "get b/p number for previous breakpoint"]
+
+    if { $bp_pending } {
+	set bp_pattern_before \
+	    [multi_line \
+		 "$bp_number\\s+dprintf\\s+keep\\s+y\\s+<PENDING>\\s+${bp_func}" \
+		 "\\s+printf \"in $bp_func\""]
+	set bp_pattern_after $bp_pattern_before
+    } else {
+	set bp_pattern_before \
+	    [multi_line \
+		 "$bp_number\\s+dprintf\\s+keep\\s+y\\s+<MULTIPLE>\\s*" \
+		 "\\s+printf \"in $bp_func\"" \
+		 "$bp_number\\.1\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 1" \
+		 "$bp_number\\.2\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 2"]
+
+	set bp_pattern_after \
+	    [multi_line \
+		 "$bp_number\\s+dprintf\\s+keep\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+" \
+		 "\\s+printf \"in $bp_func\""]
+    }
+
+    gdb_test "info breakpoints" $bp_pattern_before \
+	"info breakpoints before inferior removal"
+
+    kill_and_remove_inferior_2
+
+    gdb_test "info breakpoints" $bp_pattern_after \
+	"info breakpoints after inferior removal"
+}
+
+foreach_with_prefix bp_pending { true false } {
+    foreach_with_prefix bp_type { thread inferior } {
+	do_bp_test $bp_type $bp_pending
+    }
+
+    do_dprintf_test $bp_pending
+}
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv9 14/14] gdb: only insert thread-specific breakpoints in the relevant inferior
  2024-03-05 15:21               ` [PATCHv9 00/14] thread-specific breakpoints in just some inferiors Andrew Burgess
                                   ` (12 preceding siblings ...)
  2024-03-05 15:21                 ` [PATCHv9 13/14] gdb: don't set breakpoint::pspace in create_breakpoint Andrew Burgess
@ 2024-03-05 15:21                 ` Andrew Burgess
  2024-03-05 15:49                   ` Willgerodt, Felix
  2024-03-31 10:31                 ` [PATCHv10 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
  14 siblings, 1 reply; 138+ messages in thread
From: Andrew Burgess @ 2024-03-05 15:21 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Eli Zaretskii

This commit updates GDB so that thread or inferior specific
breakpoints are only inserted into the program space in which the
specific thread or inferior is running.

In terms of implementation, getting this basically working is easy
enough, now that a breakpoint's thread or inferior field is setup
prior to GDB looking for locations, we can easily use this information
to find a suitable program_space and pass this to as a filter when
creating the sals.

Or we could if breakpoint_ops::create_sals_from_location_spec allowed
us to pass in a filter program_space.

So, this commit extends breakpoint_ops::create_sals_from_location_spec
to take a program_space argument, and uses this to filter the set of
returned sals.  This accounts for about half the change in this patch.

The second set of changes starts from breakpoint_set_thread and
breakpoint_set_inferior, this is called when the thread or inferior
for a breakpoint changes, e.g. from the Python API.

Previously this call would never result in the locations of a
breakpoint changing, after all, locations were inserted in every
program space, and we just use the thread or inferior variable to
decide when we should stop.  Now though, changing a breakpoint's
thread or inferior can mean we need to figure out a new set of
breakpoint locations.

To support this I've added a new breakpoint_re_set_one function, which
is like breakpoint_re_set, but takes a single breakpoint, and just
updates the locations for that one breakpoint.  We only need to call
this function if the program_space in which a breakpoint's thread (or
inferior) is running actually changes.  If the program_space does
change then we call the new breakpoint_re_set_one function passing in
the program_space which should be used to filter the new locations (or
nullptr to indicate we should set locations in all program spaces).
This filter program_space needs to propagate down to all the re_set
methods, this accounts for the remaining half of the changes in this
patch.

There were a couple of existing tests that created thread or inferior
specific breakpoints and then checked the 'info breakpoints' output,
these needed updating.  These were:

  gdb.mi/user-selected-context-sync.exp
  gdb.multi/bp-thread-specific.exp
  gdb.multi/multi-target-continue.exp
  gdb.multi/multi-target-ping-pong-next.exp
  gdb.multi/tids.exp
  gdb.mi/new-ui-bp-deleted.exp
  gdb.multi/inferior-specific-bp.exp
  gdb.multi/pending-bp-del-inferior.exp

I've also added some additional tests to:

  gdb.multi/pending-bp.exp

I've updated the documentation and added a NEWS entry.

Reviewed-By: Eli Zaretskii <eliz@gnu.org>
---
 gdb/NEWS                                      |   7 +
 gdb/ada-lang.c                                |   6 +-
 gdb/break-catch-throw.c                       |   6 +-
 gdb/breakpoint.c                              | 280 ++++++++++++++----
 gdb/breakpoint.h                              |  29 +-
 gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp    |   8 +-
 .../gdb.mi/user-selected-context-sync.exp     |   4 +-
 .../gdb.multi/bp-thread-specific.exp          |   7 +-
 .../gdb.multi/inferior-specific-bp.exp        |  12 +-
 .../gdb.multi/multi-target-continue.exp       |   2 +-
 .../gdb.multi/multi-target-ping-pong-next.exp |   4 +-
 .../gdb.multi/pending-bp-del-inferior.exp     |   6 +-
 gdb/testsuite/gdb.multi/pending-bp.exp        | 206 +++++++++++++
 gdb/testsuite/gdb.multi/tids.exp              |   6 +-
 14 files changed, 484 insertions(+), 99 deletions(-)

diff --git a/gdb/NEWS b/gdb/NEWS
index c170385a50e..2a888d64e4d 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -17,6 +17,13 @@
   'thread' or 'task' keywords are parsed at the time the breakpoint is
   created, rather than at the time the breakpoint becomes non-pending.
 
+* Thread-specific breakpoints are only inserted into the program space
+  in which the thread of interest is running.  In most cases program
+  spaces are unique for each inferior, so this means that
+  thread-specific breakpoints will usually only be inserted for the
+  inferior containing the thread of interest.  The breakpoint will
+  be hit no less than before.
+
 * Changed commands
 
 disassemble
diff --git a/gdb/ada-lang.c b/gdb/ada-lang.c
index 1c26ebf7b30..c88acdf4035 100644
--- a/gdb/ada-lang.c
+++ b/gdb/ada-lang.c
@@ -12010,11 +12010,11 @@ struct ada_catchpoint : public code_breakpoint
     enable_state = enabled ? bp_enabled : bp_disabled;
     language = language_ada;
 
-    re_set ();
+    re_set (pspace);
   }
 
   struct bp_location *allocate_location () override;
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   void check_status (struct bpstat *bs) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   bool print_one (const bp_location **) const override;
@@ -12059,7 +12059,7 @@ static struct symtab_and_line ada_exception_sal
    catchpoint kinds.  */
 
 void
-ada_catchpoint::re_set ()
+ada_catchpoint::re_set (program_space *pspace)
 {
   std::vector<symtab_and_line> sals;
   try
diff --git a/gdb/break-catch-throw.c b/gdb/break-catch-throw.c
index d053bd5fbe0..7191d1b38fa 100644
--- a/gdb/break-catch-throw.c
+++ b/gdb/break-catch-throw.c
@@ -82,10 +82,10 @@ struct exception_catchpoint : public code_breakpoint
 				     _("invalid type-matching regexp")))
   {
     pspace = current_program_space;
-    re_set ();
+    re_set (pspace);
   }
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   bool print_one (const bp_location **) const override;
   void print_mention () const override;
@@ -198,7 +198,7 @@ exception_catchpoint::check_status (struct bpstat *bs)
 /* Implement the 're_set' method.  */
 
 void
-exception_catchpoint::re_set ()
+exception_catchpoint::re_set (program_space *pspace)
 {
   std::vector<symtab_and_line> sals;
   struct program_space *filter_pspace = current_program_space;
diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index e1efde66feb..a190f2a78bf 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -91,9 +91,12 @@
 static void map_breakpoint_numbers (const char *,
 				    gdb::function_view<void (breakpoint *)>);
 
-static void
-  create_sals_from_location_spec_default (location_spec *locspec,
-					  linespec_result *canonical);
+static void parse_breakpoint_sals (location_spec *locspec,
+				   linespec_result *canonical,
+				   program_space *search_pspace);
+
+static void breakpoint_re_set_one (breakpoint *b,
+				   program_space *filter_pspace);
 
 static void create_breakpoints_sal (struct gdbarch *,
 				    struct linespec_result *,
@@ -283,11 +286,12 @@ static bool strace_marker_p (struct breakpoint *b);
 
 static void bkpt_probe_create_sals_from_location_spec
      (location_spec *locspec,
-      struct linespec_result *canonical);
+      struct linespec_result *canonical,
+      struct program_space *search_pspace);
 
 const struct breakpoint_ops code_breakpoint_ops =
 {
-  create_sals_from_location_spec_default,
+  parse_breakpoint_sals,
   create_breakpoints_sal,
 };
 
@@ -352,7 +356,7 @@ struct internal_breakpoint : public code_breakpoint
     disposition = disp_donttouch;
   }
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   void check_status (struct bpstat *bs) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   void print_mention () const override;
@@ -389,7 +393,7 @@ struct momentary_breakpoint : public code_breakpoint
     gdb_assert (inferior == -1);
   }
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   void check_status (struct bpstat *bs) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   void print_mention () const override;
@@ -400,7 +404,7 @@ struct dprintf_breakpoint : public ordinary_breakpoint
 {
   using ordinary_breakpoint::ordinary_breakpoint;
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   int breakpoint_hit (const struct bp_location *bl,
 		      const address_space *aspace,
 		      CORE_ADDR bp_addr,
@@ -1549,7 +1553,36 @@ breakpoint_set_thread (struct breakpoint *b, int thread)
   int old_thread = b->thread;
   b->thread = thread;
   if (old_thread != thread)
-    notify_breakpoint_modified (b);
+    {
+      /* If THREAD is in a different program_space than OLD_THREAD, or the
+	 breakpoint has switched to or from being thread-specific, then we
+	 need to re-set the locations of this breakpoint.  First, figure
+	 out the program_space for the old and new threads, use a value of
+	 nullptr to indicate the breakpoint is in all program spaces.  */
+      program_space *old_pspace = nullptr;
+      if (old_thread != -1)
+	{
+	  struct thread_info *thr = find_thread_global_id (old_thread);
+	  gdb_assert (thr != nullptr);
+	  old_pspace = thr->inf->pspace;
+	}
+
+      program_space *new_pspace = nullptr;
+      if (thread != -1)
+	{
+	  struct thread_info *thr = find_thread_global_id (thread);
+	  gdb_assert (thr != nullptr);
+	  new_pspace = thr->inf->pspace;
+	}
+
+      /* If the program space has changed for this breakpoint, then
+	 re-evaluate it's locations.  */
+      if (old_pspace != new_pspace)
+	breakpoint_re_set_one (b, new_pspace);
+
+      /* Let others know the breakpoint has changed.  */
+      notify_breakpoint_modified (b);
+    }
 }
 
 /* See breakpoint.h.  */
@@ -1568,7 +1601,34 @@ breakpoint_set_inferior (struct breakpoint *b, int inferior)
   int old_inferior = b->inferior;
   b->inferior = inferior;
   if (old_inferior != inferior)
-    notify_breakpoint_modified (b);
+    {
+      /* If INFERIOR is in a different program_space than OLD_INFERIOR, or
+	 the breakpoint has switch to or from inferior-specific, then we
+	 need to re-set the locations of this breakpoint.  First, figure
+	 out the program_space for the old and new inferiors, use a value
+	 of nullptr to indicate the breakpoint is in all program
+	 spaces.  */
+      program_space *old_pspace = nullptr;
+      if (old_inferior != -1)
+	{
+	  struct inferior *inf = find_inferior_id (old_inferior);
+	  gdb_assert (inf != nullptr);
+	  old_pspace = inf->pspace;
+	}
+
+      program_space *new_pspace = nullptr;
+      if (inferior != -1)
+	{
+	  struct inferior *inf = find_inferior_id (inferior);
+	  gdb_assert (inf != nullptr);
+	  new_pspace = inf->pspace;
+	}
+
+      if (old_pspace != new_pspace)
+	breakpoint_re_set_one (b, new_pspace);
+
+      notify_breakpoint_modified (b);
+    }
 }
 
 /* See breakpoint.h.  */
@@ -8799,7 +8859,8 @@ create_breakpoints_sal (struct gdbarch *gdbarch,
 
 static void
 parse_breakpoint_sals (location_spec *locspec,
-		       struct linespec_result *canonical)
+		       struct linespec_result *canonical,
+		       struct program_space *search_pspace)
 {
   struct symtab_and_line cursal;
 
@@ -8864,7 +8925,7 @@ parse_breakpoint_sals (location_spec *locspec,
 	      && strchr ("+-", spec[0]) != NULL
 	      && spec[1] != '['))
 	{
-	  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, NULL,
+	  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, search_pspace,
 			    get_last_displayed_symtab (),
 			    get_last_displayed_line (),
 			    canonical, NULL, NULL);
@@ -8872,7 +8933,7 @@ parse_breakpoint_sals (location_spec *locspec,
 	}
     }
 
-  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, NULL,
+  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, search_pspace,
 		    cursal.symtab, cursal.line, canonical, NULL, NULL);
 }
 
@@ -8971,6 +9032,39 @@ breakpoint_ops_for_location_spec_type (enum location_spec_type locspec_type,
     }
 }
 
+/* Return the program space to use as a filter when searching for locations
+   of a breakpoint specific to THREAD or INFERIOR.  If THREAD and INFERIOR
+   are both -1, meaning all threads/inferiors, then this function returns
+   nullptr, indicating no program space filtering should be performed.
+   Otherwise, this function returns the program space for the inferior that
+   contains THREAD (when THREAD is not -1), or the program space for
+   INFERIOR (when INFERIOR is not -1).  */
+
+static struct program_space *
+find_program_space_for_breakpoint (int thread, int inferior)
+{
+  if (thread != -1)
+    {
+      gdb_assert (inferior == -1);
+
+      struct thread_info *thr = find_thread_global_id (thread);
+      gdb_assert (thr != nullptr);
+      gdb_assert (thr->inf != nullptr);
+      return thr->inf->pspace;
+    }
+  else if (inferior != -1)
+    {
+      gdb_assert (thread == -1);
+
+      struct inferior *inf = find_inferior_id (inferior);
+      gdb_assert (inf != nullptr);
+
+      return inf->pspace;
+    }
+
+  return nullptr;
+}
+
 /* See breakpoint.h.  */
 
 const struct breakpoint_ops *
@@ -9072,7 +9166,10 @@ create_breakpoint (struct gdbarch *gdbarch,
 
   try
     {
-      ops->create_sals_from_location_spec (locspec, &canonical);
+      struct program_space *search_pspace
+	= find_program_space_for_breakpoint (thread, inferior);
+      ops->create_sals_from_location_spec (locspec, &canonical,
+					   search_pspace);
     }
   catch (const gdb_exception_error &e)
     {
@@ -9545,7 +9642,7 @@ break_range_command (const char *arg, int from_tty)
   arg_start = arg;
   location_spec_up start_locspec
     = string_to_location_spec (&arg, current_language);
-  parse_breakpoint_sals (start_locspec.get (), &canonical_start);
+  parse_breakpoint_sals (start_locspec.get (), &canonical_start, nullptr);
 
   if (arg[0] != ',')
     error (_("Too few arguments."));
@@ -9646,7 +9743,7 @@ watchpoint_exp_is_const (const struct expression *exp)
 /* Implement the "re_set" method for watchpoints.  */
 
 void
-watchpoint::re_set ()
+watchpoint::re_set (struct program_space *pspace)
 {
   /* Watchpoint can be either on expression using entirely global
      variables, or it can be on local variables.
@@ -11757,7 +11854,7 @@ breakpoint::print_recreate (struct ui_file *fp) const
 /* Default breakpoint_ops methods.  */
 
 void
-code_breakpoint::re_set ()
+code_breakpoint::re_set (struct program_space *pspace)
 {
   /* FIXME: is this still reachable?  */
   if (breakpoint_location_spec_empty_p (this))
@@ -11767,7 +11864,7 @@ code_breakpoint::re_set ()
       return;
     }
 
-  re_set_default ();
+  re_set_default (pspace);
 }
 
 int
@@ -11973,7 +12070,7 @@ code_breakpoint::decode_location_spec (location_spec *locspec,
 /* Virtual table for internal breakpoints.  */
 
 void
-internal_breakpoint::re_set ()
+internal_breakpoint::re_set (struct program_space *pspace)
 {
   switch (type)
     {
@@ -12066,7 +12163,7 @@ internal_breakpoint::print_mention () const
 /* Virtual table for momentary breakpoints  */
 
 void
-momentary_breakpoint::re_set ()
+momentary_breakpoint::re_set (struct program_space *pspace)
 {
   /* Keep temporary breakpoints, which can be encountered when we step
      over a dlopen call and solib_add is resetting the breakpoints.
@@ -12107,12 +12204,13 @@ longjmp_breakpoint::~longjmp_breakpoint ()
 
 static void
 bkpt_probe_create_sals_from_location_spec (location_spec *locspec,
-					   struct linespec_result *canonical)
+					   struct linespec_result *canonical,
+					   struct program_space *search_pspace)
 
 {
   struct linespec_sals lsal;
 
-  lsal.sals = parse_probes (locspec, NULL, canonical);
+  lsal.sals = parse_probes (locspec, search_pspace, canonical);
   lsal.canonical = xstrdup (canonical->locspec->to_string ());
   canonical->lsals.push_back (std::move (lsal));
 }
@@ -12202,9 +12300,9 @@ tracepoint::print_recreate (struct ui_file *fp) const
 }
 
 void
-dprintf_breakpoint::re_set ()
+dprintf_breakpoint::re_set (struct program_space *pspace)
 {
-  re_set_default ();
+  re_set_default (pspace);
 
   /* 1 - connect to target 1, that can run breakpoint commands.
      2 - create a dprintf, which resolves fine.
@@ -12258,8 +12356,10 @@ dprintf_breakpoint::after_condition_true (struct bpstat *bs)
    markers (`-m').  */
 
 static void
-strace_marker_create_sals_from_location_spec (location_spec *locspec,
-					      struct linespec_result *canonical)
+strace_marker_create_sals_from_location_spec
+	(location_spec *locspec,
+	 struct linespec_result *canonical,
+	 struct program_space *search_pspace)
 {
   struct linespec_sals lsal;
   const char *arg_start, *arg;
@@ -12776,12 +12876,32 @@ update_breakpoint_locations (code_breakpoint *b,
      all locations are in the same shared library, that was unloaded.
      We'd like to retain the location, so that when the library is
      loaded again, we don't loose the enabled/disabled status of the
-     individual locations.  */
+     individual locations.
+
+     Thread specific breakpoints will also trigger this case if the thread
+     is changed to a different program space, and all of the old locations
+     go out of scope.  In this case we do (currently) discard the old
+     locations -- we assume the change in thread is permanent and the old
+     locations will never come back into scope.  */
   if (all_locations_are_pending (b, filter_pspace) && sals.empty ())
-    return;
+    {
+      if (b->thread != -1)
+	b->clear_locations ();
+      return;
+    }
 
   bp_location_list existing_locations = b->steal_locations (filter_pspace);
 
+  /* If this is a thread-specific breakpoint then any locations left on the
+     breakpoint are for a program space in which the thread of interest
+     does not operate.  This can happen when the user changes the thread of
+     a thread-specific breakpoint.
+
+     We assume that the change in thread is permanent, and that the old
+     locations will never be used again, so discard them now.  */
+  if (b->thread != -1)
+    b->clear_locations ();
+
   for (const auto &sal : sals)
     {
       struct bp_location *new_loc;
@@ -12947,40 +13067,45 @@ code_breakpoint::location_spec_to_sals (location_spec *locspec,
    locations.  */
 
 void
-code_breakpoint::re_set_default ()
+code_breakpoint::re_set_default (struct program_space *filter_pspace)
 {
-  struct program_space *filter_pspace = current_program_space;
   std::vector<symtab_and_line> expanded, expanded_end;
 
-  int found;
-  std::vector<symtab_and_line> sals = location_spec_to_sals (locspec.get (),
-							     filter_pspace,
-							     &found);
-  if (found)
-    expanded = std::move (sals);
-
-  if (locspec_range_end != nullptr)
-    {
-      std::vector<symtab_and_line> sals_end
-	= location_spec_to_sals (locspec_range_end.get (),
-				 filter_pspace, &found);
+  /* If this breakpoint is thread-specific then find the program space in
+     which the specific thread exists.  Otherwise, for breakpoints that are
+     not thread-specific THREAD_PSPACE will be nullptr.  */
+  program_space *bp_pspace
+    = find_program_space_for_breakpoint (this->thread, this->inferior);
+
+  /* If this is not a thread or inferior specific breakpoint, or it is a
+     thread or inferior specific breakpoint but we are looking for new
+     locations in the program space that the specific thread or inferior is
+     running, then look for new locations for this breakpoint.  */
+  if (bp_pspace == nullptr || filter_pspace == bp_pspace)
+    {
+      int found;
+      std::vector<symtab_and_line> sals
+	= location_spec_to_sals (locspec.get (), filter_pspace, &found);
       if (found)
-	expanded_end = std::move (sals_end);
+	expanded = std::move (sals);
+
+      if (locspec_range_end != nullptr)
+	{
+	  std::vector<symtab_and_line> sals_end
+	    = location_spec_to_sals (locspec_range_end.get (),
+				     filter_pspace, &found);
+	  if (found)
+	    expanded_end = std::move (sals_end);
+	}
     }
 
+  /* Update the locations for this breakpoint.  For thread-specific
+     breakpoints this will remove any old locations that are for the wrong
+     program space -- this can happen if the user changes the thread of a
+     thread-specific breakpoint.  */
   update_breakpoint_locations (this, filter_pspace, expanded, expanded_end);
 }
 
-/* Default method for creating SALs from an address string.  It basically
-   calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
-
-static void
-create_sals_from_location_spec_default (location_spec *locspec,
-					struct linespec_result *canonical)
-{
-  parse_breakpoint_sals (locspec, canonical);
-}
-
 /* Re-set breakpoint locations for the current program space.
    Locations bound to other program spaces are left untouched.  */
 
@@ -13015,7 +13140,7 @@ breakpoint_re_set (void)
 	  {
 	    input_radix = b.input_radix;
 	    set_language (b.language);
-	    b.re_set ();
+	    b.re_set (current_program_space);
 	  }
 	catch (const gdb_exception &ex)
 	  {
@@ -13036,6 +13161,53 @@ breakpoint_re_set (void)
   /* Now we can insert.  */
   update_global_location_list (UGLL_MAY_INSERT);
 }
+
+/* Re-set locations for breakpoint B in FILTER_PSPACE.  If FILTER_PSPACE is
+   nullptr then re-set locations for B in all program spaces.  Locations
+   bound to program spaces other than FILTER_PSPACE are left untouched.  */
+
+static void
+breakpoint_re_set_one (breakpoint *b, program_space *filter_pspace)
+{
+  {
+    scoped_restore_current_language save_language;
+    scoped_restore save_input_radix = make_scoped_restore (&input_radix);
+    scoped_restore_current_pspace_and_thread restore_pspace_thread;
+
+    /* To ::re_set each breakpoint we set the current_language to the
+       language of the breakpoint before re-evaluating the breakpoint's
+       location.  This change can unfortunately get undone by accident if
+       the language_mode is set to auto, and we either switch frames, or
+       more likely in this context, we select the current frame.
+
+       We prevent this by temporarily turning the language_mode to
+       language_mode_manual.  We restore it once all breakpoints
+       have been reset.  */
+    scoped_restore save_language_mode = make_scoped_restore (&language_mode);
+    language_mode = language_mode_manual;
+
+    /* Note: we must not try to insert locations until after all
+       breakpoints have been re-set.  Otherwise, e.g., when re-setting
+       breakpoint 1, we'd insert the locations of breakpoint 2, which
+       hadn't been re-set yet, and thus may have stale locations.  */
+
+    try
+      {
+	input_radix = b->input_radix;
+	set_language (b->language);
+	b->re_set (filter_pspace);
+      }
+    catch (const gdb_exception &ex)
+      {
+	exception_fprintf (gdb_stderr, ex,
+			   "Error in re-setting breakpoint %d: ",
+			   b->number);
+      }
+  }
+
+  /* Now we can insert.  */
+  update_global_location_list (UGLL_MAY_INSERT);
+}
 \f
 /* Reset the thread number of this breakpoint:
 
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index 42b49144e79..dea55deb314 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -570,15 +570,15 @@ enum print_stop_action
 
 struct breakpoint_ops
 {
-  /* Create SALs from location spec, storing the result in
-     linespec_result.
-
-     For an explanation about the arguments, see the function
-     `create_sals_from_location_spec_default'.
+  /* Create SALs from LOCSPEC, storing the result in linespec_result
+     CANONICAL.  If SEARCH_PSPACE is not nullptr then only results in the
+     corresponding program space are returned.  If SEARCH_PSPACE is nullptr
+     then results for all program spaces are returned.
 
      This function is called inside `create_breakpoint'.  */
   void (*create_sals_from_location_spec) (location_spec *locspec,
-					  struct linespec_result *canonical);
+					  linespec_result *canonical,
+					  program_space *search_pspace);
 
   /* This method will be responsible for creating a breakpoint given its SALs.
      Usually, it just calls `create_breakpoints_sal' (for ordinary
@@ -710,8 +710,15 @@ struct breakpoint : public intrusive_list_node<breakpoint>
 
   /* Reevaluate a breakpoint.  This is necessary after symbols change
      (e.g., an executable or DSO was loaded, or the inferior just
-     started).  */
-  virtual void re_set ()
+     started).
+
+     If not nullptr, then FILTER_PSPACE is the program space in which
+     symbols may have changed, we only need to add new locations in
+     FILTER_PSPACE.
+
+     If FILTER_PSPACE is nullptr then all program spaces may have changed,
+     new locations need to be searched for in every program space.  */
+  virtual void re_set (program_space *filter_pspace)
   {
     /* Nothing to re-set.  */
   }
@@ -955,7 +962,7 @@ struct code_breakpoint : public breakpoint
   /* Add a location for SAL to this breakpoint.  */
   bp_location *add_location (const symtab_and_line &sal);
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   int insert_location (struct bp_location *) override;
   int remove_location (struct bp_location *,
 		       enum remove_bp_reason reason) override;
@@ -977,7 +984,7 @@ struct code_breakpoint : public breakpoint
      struct program_space *search_pspace);
 
   /* Helper method that does the basic work of re_set.  */
-  void re_set_default ();
+  void re_set_default (program_space *pspace);
 
   /* Find the SaL locations corresponding to the given LOCATION.
      On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
@@ -999,7 +1006,7 @@ struct watchpoint : public breakpoint
 {
   using breakpoint::breakpoint;
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   int insert_location (struct bp_location *) override;
   int remove_location (struct bp_location *,
 		       enum remove_bp_reason reason) override;
diff --git a/gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp b/gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp
index f736994d234..938e6deec05 100644
--- a/gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp
+++ b/gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp
@@ -76,8 +76,12 @@ foreach_mi_ui_mode mode {
     set loc2 [make_bp_loc "$::decimal\\.2"]
 
     # Create the inferior-specific breakpoint.
-    mi_create_breakpoint_multi "-g i2 foo" "create breakpoint in inferior 2" \
-	-inferior "2" -locations "\\\[$loc1,$loc2\\\]"
+    mi_create_breakpoint "-g i2 foo" "create breakpoint in inferior 2" \
+	-number "$decimal" \
+	-type "breakpoint" \
+	-enabled "y" \
+	-func "foo" \
+	-inferior "2"
     set bpnum [mi_get_valueof "/d" "\$bpnum" "INVALID"]
 
     if {$mode eq "separate"} {
diff --git a/gdb/testsuite/gdb.mi/user-selected-context-sync.exp b/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
index 93b91b42f92..ed331aff873 100644
--- a/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
+++ b/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
@@ -370,7 +370,7 @@ proc test_continue_to_start { mode inf } {
 			    "thread $inf.2 stops MI"
 		    } else {
 			mi_expect_stop "breakpoint-hit" "child_sub_function" \
-			    "" "$srcfile" "$decimal" {"" "disp=\"del\"" "locno=\"[0-9]+\""} \
+			    "" "$srcfile" "$decimal" {"" "disp=\"del\""} \
 			    "thread $inf.2 stops MI"
 		    }
 		}
@@ -439,7 +439,7 @@ proc_with_prefix test_setup { mode } {
 
 	with_spawn_id $mi_spawn_id {
 	    mi_expect_stop "breakpoint-hit" "main" "" "$srcfile" "$decimal" \
-		{"" "disp=\"del\"" "locno=\"[0-9]+\""} "main stop"
+		{"" "disp=\"del\""} "main stop"
 	}
 
 	# Consume CLI output.
diff --git a/gdb/testsuite/gdb.multi/bp-thread-specific.exp b/gdb/testsuite/gdb.multi/bp-thread-specific.exp
index 7635e84b913..c1d87521ee9 100644
--- a/gdb/testsuite/gdb.multi/bp-thread-specific.exp
+++ b/gdb/testsuite/gdb.multi/bp-thread-specific.exp
@@ -50,7 +50,7 @@ gdb_test "info threads" \
 # locations ('foo' in both inferiors) even though only one of those
 # locations will ever trigger ('foo' in inferior 2).
 gdb_test "break foo thread 2.1" \
-    "Breakpoint $decimal at $hex: foo\\. \\(2 locations\\)"
+    "Breakpoint $decimal at $hex: file \[^\r\n\]+$srcfile, line $decimal\\."
 
 set bpnum [get_integer_valueof "\$bpnum" "INVALID"]
 
@@ -58,10 +58,7 @@ set bpnum [get_integer_valueof "\$bpnum" "INVALID"]
 # earlier breakpoint.  Check that the thread-id used when describing
 # the earlier breakpoints is correct.
 gdb_test "break foo thread 1.1" \
-    [multi_line \
-	 "Note: breakpoint $bpnum \\(thread 2.1\\) also set at pc $hex\\." \
-	 "Note: breakpoint $bpnum \\(thread 2.1\\) also set at pc $hex\\." \
-	 "Breakpoint $decimal at $hex: foo\\. \\(2 locations\\)"]
+    "Breakpoint $decimal at $hex: file \[^\r\n\]+$srcfile, line $decimal\\."
 
 # Save the breakpoints into a file.
 if {[is_remote host]} {
diff --git a/gdb/testsuite/gdb.multi/inferior-specific-bp.exp b/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
index 46efe6f54bc..52f84183589 100644
--- a/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
+++ b/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
@@ -105,16 +105,8 @@ proc check_info_breakpoints { testname bp_number expected_loc_count } {
 # Create an inferior-specific breakpoint.  Use gdb_test instead of
 # gdb_breakpoint here as we want to check the breakpoint was placed in
 # multiple locations.
-#
-# Currently GDB still places inferior specific breakpoints into every
-# inferior, just like it does with thread specific breakpoints.
-# Hopefully this will change in the future, at which point, this test
-# will need updating.
-#
-# Two of these locations are in inferior 1, while the third is in
-# inferior 2.
 gdb_test "break foo inferior 1" \
-    "Breakpoint $decimal at $hex: foo\\. \\(3 locations\\)"
+    "Breakpoint $decimal at $hex: foo\\. \\(2 locations\\)"
 set bp_number [get_integer_valueof "\$bpnum" "INVALID" \
 		  "get b/p number for inferior specific breakpoint"]
 
@@ -123,7 +115,7 @@ set location_count 0
 set saw_inf_cond false
 
 check_info_breakpoints "first check for inferior specific breakpoint" \
-    $bp_number 3
+    $bp_number 2
 
 # Create a multi-inferior breakpoint to stop at.
 gdb_breakpoint "stop_breakpt" message
diff --git a/gdb/testsuite/gdb.multi/multi-target-continue.exp b/gdb/testsuite/gdb.multi/multi-target-continue.exp
index d2201061713..d4b2fc28133 100644
--- a/gdb/testsuite/gdb.multi/multi-target-continue.exp
+++ b/gdb/testsuite/gdb.multi/multi-target-continue.exp
@@ -30,7 +30,7 @@ proc test_continue {non-stop} {
 
     proc set_break {inf} {
 	gdb_test "break function${inf} thread ${inf}.1" \
-	"Breakpoint .* function${inf}\\..*"
+	    "Breakpoint ${::decimal} at ${::hex}: file .*, line ${::decimal}\\."
     }
 
     # Select inferior INF, and then run to a breakpoint on inferior
diff --git a/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp b/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp
index 0aff708c0f3..36f9d24a917 100644
--- a/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp
+++ b/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp
@@ -52,12 +52,12 @@ proc test_ping_pong_next {} {
     gdb_test "thread 1.1" "Switching to thread 1.1 .*"
 
     gdb_test "break $srcfile:$line1 thread 1.1" \
-	"Breakpoint .*$srcfile:$line1\\..*"
+	"Breakpoint .*$srcfile, line $line1\\."
 
     gdb_test "continue" "hit Breakpoint .*"
 
     gdb_test "break $srcfile:$line2 thread 2.1" \
-	"Breakpoint .*$srcfile:$line2\\..*"
+	"Breakpoint .*$srcfile, line $line2\\."
 
     # Now block inferior 1 and issue "next".  We should stop at the
     # breakpoint for inferior 2, given schedlock off.
diff --git a/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
index 5fcd1ef2e39..12c0a84bb02 100644
--- a/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
+++ b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
@@ -129,10 +129,8 @@ proc do_bp_test { bp_type bp_pending } {
     } else {
 	set bp_pattern_before \
 	    [multi_line \
-		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+<MULTIPLE>\\s*" \
-		 "\\s+stop only in [string_to_regexp $bp_restriction]" \
-		 "$bp_number\\.1\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 1" \
-		 "$bp_number\\.2\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 2"]
+		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 1" \
+		 "\\s+stop only in [string_to_regexp $bp_restriction]"]
 
 	set bp_pattern_after \
 	    [multi_line \
diff --git a/gdb/testsuite/gdb.multi/pending-bp.exp b/gdb/testsuite/gdb.multi/pending-bp.exp
index 478d8d7c037..aeb8c2c886e 100644
--- a/gdb/testsuite/gdb.multi/pending-bp.exp
+++ b/gdb/testsuite/gdb.multi/pending-bp.exp
@@ -72,6 +72,48 @@ proc do_test_setup { inf_1_stop inf_2_stop } {
     return true
 }
 
+# Create a breakpoint on the function 'foo' in THREAD.  It is expected
+# that the breakpoint created will be pending, this is checked by
+# running the 'info breakpoints' command.
+#
+# Returns the number for the newly created breakpoint.
+proc do_create_pending_foo_breakpoint { {thread "1.1"} } {
+    gdb_test "break foo thread $thread" \
+	[multi_line \
+	     "Function \"foo\" not defined\\." \
+	     "Breakpoint $::decimal \\(foo\\) pending\."] \
+	"set pending thread-specific breakpoint"
+    set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+		   "get number for thread-specific breakpoint on foo"]
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	     "\\s+stop only in thread [string_to_regexp $thread]"] \
+	"check thread-specific breakpoint is initially pending"
+
+    return $bpnum
+}
+
+# Create a breakpoint on the function 'foo' in THREAD.  It is expected
+# that the breakpoint created will not be pending, this is checked by
+# running the 'info breakpoints' command.
+#
+# Returns the number for the newly created breakpoint.
+proc do_create_foo_breakpoint { {thread "1.1"} } {
+    gdb_test "break foo thread $thread" \
+	"Breakpoint $::decimal at $::hex" \
+	"set thread-specific breakpoint"
+    set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+		   "get number for thread-specific breakpoint on foo"]
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex\\s+<foo\[^>\]*> inf $::decimal" \
+	     "\\s+stop only in thread [string_to_regexp $thread]"] \
+	"check thread-specific breakpoint is initially pending"
+
+    return $bpnum
+}
+
 # Check that when a breakpoint is in the pending state, but that breakpoint
 # does have some locations (those locations themselves are pending), GDB
 # doesn't display the inferior list in the 'info breakpoints' output.
@@ -122,5 +164,169 @@ proc_with_prefix test_no_inf_display {} {
 	"check info breakpoints while breakpoint is pending"
 }
 
+# Setup two inferiors.  In #1 the symbol 'foo' has not yet been
+# loaded, while in #2 the symbol 'foo' has been loaded.
+#
+# Create a thread-specific breakpoint on 'foo' tied to a thread in
+# inferior #1, the breakpoint should be pending -- 'foo' is not yet
+# loaded in #1.
+#
+# Now move inferior #1 forward until 'foo' is loaded, check the
+# breakpoint is no longer pending.
+#
+# Move inferior #1 forward more until 'foo' is unloaded, check that
+# the breakpoint returns to the pending state.
+proc_with_prefix test_pending_toggle { } {
+
+    do_test_setup "Break before open" "Break before close"
+
+    set bpnum [do_create_pending_foo_breakpoint]
+
+    # Now return to inferior 1 and continue until the shared library is
+    # loaded, the breakpoint should become non-pending.
+    gdb_test "inferior 1" "Switching to inferior 1 .*" \
+	"switch back to inferior 1"
+    gdb_continue_to_breakpoint "stop in foo in inferior 1" "foo \\(\\) .*"
+
+    gdb_test "info breakpoint $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex <foo\[^>\]*> inf 1" \
+	     "\\s+stop only in thread 1\\.1" \
+	     "\\s+breakpoint already hit 1 time"] \
+	"check thread-specific breakpoint is no longer pending"
+
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "close library"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	     "\\s+stop only in thread 1\\.1" \
+	     "\\s+breakpoint already hit 1 time"] \
+	"check thread-specific breakpoint is pending again"
+}
+
+# Create a Python variable VAR and set it to the gdb.Breakpoint object
+# corresponding to the breakpoint numbered BPNUM.  If THREAD is not
+# the empty string then THREAD should be an integer, check that
+# gdb.Breakpoint.thread is set to the value of THREAD.  Otherwise, if
+# THREAD is the empty string, check that gdb.Breakpoint.thread is set
+# to None.
+proc py_find_breakpoint { var bpnum {thread ""} } {
+    gdb_test_no_output \
+	"python ${var}=\[b for b in gdb.breakpoints() if b.number == $bpnum\]\[0\]" \
+	"find Python gdb.Breakpoint object"
+    if { $thread ne "" } {
+	gdb_test_no_output "python assert(${var}.thread == ${thread})" \
+	    "check thread attribute is currently correct"
+    } else {
+	gdb_test_no_output "python assert(${var}.thread is None)" \
+	    "check thread attribute is currently correct"
+    }
+}
+
+# Setup two inferiors.  In #1 the symbol 'foo' has not yet been
+# loaded, while in #2 the symbol 'foo' has been loaded.
+#
+# Create a thread-specific breakpoint on 'foo' tied to a thread in
+# inferior #1, the breakpoint should be pending -- 'foo' is not yet
+# loaded in #1.
+#
+# Use Python to change the thread of the thread-specific breakpoint to
+# a thread in inferior #2, at this point the thread should gain a
+# location and become non-pending.
+#
+# Set the thread back to a thread in inferior #1, the breakpoint
+# should return to the pending state.
+proc_with_prefix py_test_toggle_thread {} {
+    do_test_setup "Break before open" "Break after open"
+
+    set bpnum [do_create_pending_foo_breakpoint]
+
+    py_find_breakpoint "bp" $bpnum 1
+
+    gdb_test_no_output "python bp.thread = 2" \
+	"change thread on thread-specific breakpoint"
+    gdb_test "info breakpoint $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex <foo\[^>\]*> inf 2" \
+	     "\\s+stop only in thread 2\\.1"] \
+	"check thread-specific breakpoint now has a location"
+
+    gdb_test_no_output "set call_count = 2" "set call_count in inferior 2"
+    gdb_continue_to_breakpoint "stop at foo in inferior 2" "foo \\(\\) .*"
+
+    gdb_test_no_output "python bp.thread = 1" \
+	"restore thread on thread-specific breakpoint"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	     "\\s+stop only in thread 1\\.1" \
+	     "\\s+breakpoint already hit 1 time"] \
+	"check thread-specific breakpoint has returned to pending"
+
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "stop after close in inferior 2" \
+	".* Break after close\\. .*"
+
+    gdb_test "inferior 1" "Switching to inferior 1 .*" \
+	"switch to inferior 1"
+    gdb_continue_to_breakpoint "stop at foo in inferior 1" "foo \\(\\) .*"
+}
+
+# Setup two inferiors.  Both inferiors have the symbol 'foo'
+# available.
+#
+# Create a thread-specific breakpoint on 'foo' tied to a thread in
+# inferior #1, the breakpoint should not be pending, but will only
+# have a single location, the location in inferior #1.
+#
+# Use Python to change the thread of the thread-specific breakpoint to
+# None.  At this point the breakpoint should gain a second location, a
+# location in inferior #2.
+proc_with_prefix py_test_clear_thread {} {
+    do_test_setup "Break after open" "Break after open"
+
+    set bpnum [do_create_foo_breakpoint]
+
+    py_find_breakpoint "bp" $bpnum 1
+
+    gdb_test_no_output "python bp.thread = None" \
+	"clear thread on thread-specific breakpoint"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "${bpnum}\\s+breakpoint\\s+keep y\\s+<MULTIPLE>\\s*" \
+	     "${bpnum}\\.1\\s+y\\s+${::hex}\\s+<foo\[^>\]*> inf $::decimal" \
+	     "${bpnum}\\.2\\s+y\\s+${::hex}\\s+<foo\[^>\]*> inf $::decimal"] \
+	"check for a location in both inferiors"
+
+    gdb_continue_to_breakpoint "stop at foo in inferior 2" "foo \\(\\) .*"
+    gdb_test_no_output "set call_count = 2" "set call_count in inferior 2"
+
+    gdb_test "inferior 1" "Switching to inferior 1 .*" \
+	"switch to inferior 1"
+    gdb_continue_to_breakpoint "stop at foo in inferior 1" "foo \\(\\) .*"
+    gdb_test_no_output "set call_count = 2" "set call_count in inferior 1"
+
+    gdb_test_no_output "python bp.thread = 2"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "${bpnum}\\s+breakpoint\\s+keep y\\s+${::hex}\\s+<foo\[^>\]*> inf 2" \
+	     "\\s+stop only in thread 2\\.1" \
+	     "\\s+breakpoint already hit 2 times"] \
+	"check for a location only in inferior 2"
+
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "stop after close in inferior 1" \
+	".* Break after close\\. .*"
+
+    gdb_test "inferior 2" "Switching to inferior 2 .*" \
+	"switch back to inferior 2"
+    gdb_continue_to_breakpoint "stop at foo again in inferior 2" \
+	"foo \\(\\) .*"
+}
+
 # Run all the tests.
 test_no_inf_display
+test_pending_toggle
+py_test_toggle_thread
+py_test_clear_thread
diff --git a/gdb/testsuite/gdb.multi/tids.exp b/gdb/testsuite/gdb.multi/tids.exp
index 573b02fdd42..4f788844ee4 100644
--- a/gdb/testsuite/gdb.multi/tids.exp
+++ b/gdb/testsuite/gdb.multi/tids.exp
@@ -433,11 +433,13 @@ if { [allow_python_tests] } {
 
 	gdb_py_test_silent_cmd "python bp = gdb.breakpoints()\[0\]" \
 	    "get python breakpoint" 0
-	gdb_test "python bp.thread = 6" "thread = 6" \
+	gdb_test_no_output "python bp.thread = 6" \
 	    "make breakpoint thread-specific with python"
 	# Check that the inferior-qualified ID is correct.
 	gdb_test "info breakpoint" \
-	    "stop only in thread 1.3\r\n.*" \
+	    [multi_line \
+		 "$decimal\\s+\[^\r\n\]+ in thread_function1 at \[^\r\n\]+" \
+		 "\\s+stop only in thread 1\\.3"] \
 	    "thread specific breakpoint right thread"
     }
 }
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* RE: [PATCHv9 14/14] gdb: only insert thread-specific breakpoints in the relevant inferior
  2024-03-05 15:21                 ` [PATCHv9 14/14] gdb: only insert thread-specific breakpoints in the relevant inferior Andrew Burgess
@ 2024-03-05 15:49                   ` Willgerodt, Felix
  2024-03-06 14:11                     ` Andrew Burgess
  0 siblings, 1 reply; 138+ messages in thread
From: Willgerodt, Felix @ 2024-03-05 15:49 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches; +Cc: Eli Zaretskii

> -----Original Message-----
> From: Andrew Burgess <aburgess@redhat.com>
> Sent: Dienstag, 5. März 2024 16:22
> To: gdb-patches@sourceware.org
> Cc: Andrew Burgess <aburgess@redhat.com>; Eli Zaretskii <eliz@gnu.org>
> Subject: [PATCHv9 14/14] gdb: only insert thread-specific breakpoints in the
> relevant inferior
> 
> This commit updates GDB so that thread or inferior specific
> breakpoints are only inserted into the program space in which the
> specific thread or inferior is running.
> 
> In terms of implementation, getting this basically working is easy
> enough, now that a breakpoint's thread or inferior field is setup
> prior to GDB looking for locations, we can easily use this information
> to find a suitable program_space and pass this to as a filter when
> creating the sals.
> 
> Or we could if breakpoint_ops::create_sals_from_location_spec allowed
> us to pass in a filter program_space.
> 
> So, this commit extends breakpoint_ops::create_sals_from_location_spec
> to take a program_space argument, and uses this to filter the set of
> returned sals.  This accounts for about half the change in this patch.
> 
> The second set of changes starts from breakpoint_set_thread and
> breakpoint_set_inferior, this is called when the thread or inferior
> for a breakpoint changes, e.g. from the Python API.
> 
> Previously this call would never result in the locations of a
> breakpoint changing, after all, locations were inserted in every
> program space, and we just use the thread or inferior variable to
> decide when we should stop.  Now though, changing a breakpoint's
> thread or inferior can mean we need to figure out a new set of
> breakpoint locations.
> 
> To support this I've added a new breakpoint_re_set_one function, which
> is like breakpoint_re_set, but takes a single breakpoint, and just
> updates the locations for that one breakpoint.  We only need to call
> this function if the program_space in which a breakpoint's thread (or
> inferior) is running actually changes.  If the program_space does
> change then we call the new breakpoint_re_set_one function passing in
> the program_space which should be used to filter the new locations (or
> nullptr to indicate we should set locations in all program spaces).
> This filter program_space needs to propagate down to all the re_set
> methods, this accounts for the remaining half of the changes in this
> patch.
> 
> There were a couple of existing tests that created thread or inferior
> specific breakpoints and then checked the 'info breakpoints' output,
> these needed updating.  These were:
> 
>   gdb.mi/user-selected-context-sync.exp
>   gdb.multi/bp-thread-specific.exp
>   gdb.multi/multi-target-continue.exp
>   gdb.multi/multi-target-ping-pong-next.exp
>   gdb.multi/tids.exp
>   gdb.mi/new-ui-bp-deleted.exp
>   gdb.multi/inferior-specific-bp.exp
>   gdb.multi/pending-bp-del-inferior.exp
> 
> I've also added some additional tests to:
> 
>   gdb.multi/pending-bp.exp
> 
> I've updated the documentation and added a NEWS entry.
> 
> Reviewed-By: Eli Zaretskii <eliz@gnu.org>
> ---
>  gdb/NEWS                                      |   7 +
>  gdb/ada-lang.c                                |   6 +-
>  gdb/break-catch-throw.c                       |   6 +-
>  gdb/breakpoint.c                              | 280 ++++++++++++++----
>  gdb/breakpoint.h                              |  29 +-
>  gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp    |   8 +-
>  .../gdb.mi/user-selected-context-sync.exp     |   4 +-
>  .../gdb.multi/bp-thread-specific.exp          |   7 +-
>  .../gdb.multi/inferior-specific-bp.exp        |  12 +-
>  .../gdb.multi/multi-target-continue.exp       |   2 +-
>  .../gdb.multi/multi-target-ping-pong-next.exp |   4 +-
>  .../gdb.multi/pending-bp-del-inferior.exp     |   6 +-
>  gdb/testsuite/gdb.multi/pending-bp.exp        | 206 +++++++++++++
>  gdb/testsuite/gdb.multi/tids.exp              |   6 +-
>  14 files changed, 484 insertions(+), 99 deletions(-)
> 
> diff --git a/gdb/NEWS b/gdb/NEWS
> index c170385a50e..2a888d64e4d 100644
> --- a/gdb/NEWS
> +++ b/gdb/NEWS
> @@ -17,6 +17,13 @@
>    'thread' or 'task' keywords are parsed at the time the breakpoint is
>    created, rather than at the time the breakpoint becomes non-pending.
> 
> +* Thread-specific breakpoints are only inserted into the program space
> +  in which the thread of interest is running.  In most cases program
> +  spaces are unique for each inferior, so this means that
> +  thread-specific breakpoints will usually only be inserted for the
> +  inferior containing the thread of interest.  The breakpoint will
> +  be hit no less than before.
> +
>  * Changed commands
> 
>  disassemble
> diff --git a/gdb/ada-lang.c b/gdb/ada-lang.c
> index 1c26ebf7b30..c88acdf4035 100644
> --- a/gdb/ada-lang.c
> +++ b/gdb/ada-lang.c
> @@ -12010,11 +12010,11 @@ struct ada_catchpoint : public
> code_breakpoint
>      enable_state = enabled ? bp_enabled : bp_disabled;
>      language = language_ada;
> 
> -    re_set ();
> +    re_set (pspace);
>    }
> 
>    struct bp_location *allocate_location () override;
> -  void re_set () override;
> +  void re_set (program_space *pspace) override;
>    void check_status (struct bpstat *bs) override;
>    enum print_stop_action print_it (const bpstat *bs) const override;
>    bool print_one (const bp_location **) const override;
> @@ -12059,7 +12059,7 @@ static struct symtab_and_line ada_exception_sal
>     catchpoint kinds.  */
> 
>  void
> -ada_catchpoint::re_set ()
> +ada_catchpoint::re_set (program_space *pspace)
>  {
>    std::vector<symtab_and_line> sals;
>    try
> diff --git a/gdb/break-catch-throw.c b/gdb/break-catch-throw.c
> index d053bd5fbe0..7191d1b38fa 100644
> --- a/gdb/break-catch-throw.c
> +++ b/gdb/break-catch-throw.c
> @@ -82,10 +82,10 @@ struct exception_catchpoint : public code_breakpoint
>  				     _("invalid type-matching regexp")))
>    {
>      pspace = current_program_space;
> -    re_set ();
> +    re_set (pspace);
>    }
> 
> -  void re_set () override;
> +  void re_set (program_space *pspace) override;
>    enum print_stop_action print_it (const bpstat *bs) const override;
>    bool print_one (const bp_location **) const override;
>    void print_mention () const override;
> @@ -198,7 +198,7 @@ exception_catchpoint::check_status (struct bpstat
> *bs)
>  /* Implement the 're_set' method.  */
> 
>  void
> -exception_catchpoint::re_set ()
> +exception_catchpoint::re_set (program_space *pspace)
>  {
>    std::vector<symtab_and_line> sals;
>    struct program_space *filter_pspace = current_program_space;
> diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
> index e1efde66feb..a190f2a78bf 100644
> --- a/gdb/breakpoint.c
> +++ b/gdb/breakpoint.c
> @@ -91,9 +91,12 @@
>  static void map_breakpoint_numbers (const char *,
>  				    gdb::function_view<void (breakpoint *)>);
> 
> -static void
> -  create_sals_from_location_spec_default (location_spec *locspec,
> -					  linespec_result *canonical);
> +static void parse_breakpoint_sals (location_spec *locspec,
> +				   linespec_result *canonical,
> +				   program_space *search_pspace);
> +
> +static void breakpoint_re_set_one (breakpoint *b,
> +				   program_space *filter_pspace);
> 
>  static void create_breakpoints_sal (struct gdbarch *,
>  				    struct linespec_result *,
> @@ -283,11 +286,12 @@ static bool strace_marker_p (struct breakpoint *b);
> 
>  static void bkpt_probe_create_sals_from_location_spec
>       (location_spec *locspec,
> -      struct linespec_result *canonical);
> +      struct linespec_result *canonical,
> +      struct program_space *search_pspace);
> 
>  const struct breakpoint_ops code_breakpoint_ops =
>  {
> -  create_sals_from_location_spec_default,
> +  parse_breakpoint_sals,
>    create_breakpoints_sal,
>  };
> 
> @@ -352,7 +356,7 @@ struct internal_breakpoint : public code_breakpoint
>      disposition = disp_donttouch;
>    }
> 
> -  void re_set () override;
> +  void re_set (program_space *pspace) override;
>    void check_status (struct bpstat *bs) override;
>    enum print_stop_action print_it (const bpstat *bs) const override;
>    void print_mention () const override;
> @@ -389,7 +393,7 @@ struct momentary_breakpoint : public
> code_breakpoint
>      gdb_assert (inferior == -1);
>    }
> 
> -  void re_set () override;
> +  void re_set (program_space *pspace) override;
>    void check_status (struct bpstat *bs) override;
>    enum print_stop_action print_it (const bpstat *bs) const override;
>    void print_mention () const override;
> @@ -400,7 +404,7 @@ struct dprintf_breakpoint : public
> ordinary_breakpoint
>  {
>    using ordinary_breakpoint::ordinary_breakpoint;
> 
> -  void re_set () override;
> +  void re_set (program_space *pspace) override;
>    int breakpoint_hit (const struct bp_location *bl,
>  		      const address_space *aspace,
>  		      CORE_ADDR bp_addr,
> @@ -1549,7 +1553,36 @@ breakpoint_set_thread (struct breakpoint *b, int
> thread)
>    int old_thread = b->thread;
>    b->thread = thread;
>    if (old_thread != thread)
> -    notify_breakpoint_modified (b);
> +    {
> +      /* If THREAD is in a different program_space than OLD_THREAD, or the
> +	 breakpoint has switched to or from being thread-specific, then we
> +	 need to re-set the locations of this breakpoint.  First, figure
> +	 out the program_space for the old and new threads, use a value of
> +	 nullptr to indicate the breakpoint is in all program spaces.  */
> +      program_space *old_pspace = nullptr;
> +      if (old_thread != -1)
> +	{
> +	  struct thread_info *thr = find_thread_global_id (old_thread);
> +	  gdb_assert (thr != nullptr);
> +	  old_pspace = thr->inf->pspace;
> +	}
> +
> +      program_space *new_pspace = nullptr;
> +      if (thread != -1)
> +	{
> +	  struct thread_info *thr = find_thread_global_id (thread);
> +	  gdb_assert (thr != nullptr);
> +	  new_pspace = thr->inf->pspace;
> +	}
> +
> +      /* If the program space has changed for this breakpoint, then
> +	 re-evaluate it's locations.  */
> +      if (old_pspace != new_pspace)
> +	breakpoint_re_set_one (b, new_pspace);
> +
> +      /* Let others know the breakpoint has changed.  */
> +      notify_breakpoint_modified (b);
> +    }
>  }
> 
>  /* See breakpoint.h.  */
> @@ -1568,7 +1601,34 @@ breakpoint_set_inferior (struct breakpoint *b, int
> inferior)
>    int old_inferior = b->inferior;
>    b->inferior = inferior;
>    if (old_inferior != inferior)
> -    notify_breakpoint_modified (b);
> +    {
> +      /* If INFERIOR is in a different program_space than OLD_INFERIOR, or
> +	 the breakpoint has switch to or from inferior-specific, then we
> +	 need to re-set the locations of this breakpoint.  First, figure
> +	 out the program_space for the old and new inferiors, use a value
> +	 of nullptr to indicate the breakpoint is in all program
> +	 spaces.  */
> +      program_space *old_pspace = nullptr;
> +      if (old_inferior != -1)
> +	{
> +	  struct inferior *inf = find_inferior_id (old_inferior);
> +	  gdb_assert (inf != nullptr);
> +	  old_pspace = inf->pspace;
> +	}
> +
> +      program_space *new_pspace = nullptr;
> +      if (inferior != -1)
> +	{
> +	  struct inferior *inf = find_inferior_id (inferior);
> +	  gdb_assert (inf != nullptr);
> +	  new_pspace = inf->pspace;
> +	}
> +
> +      if (old_pspace != new_pspace)
> +	breakpoint_re_set_one (b, new_pspace);
> +
> +      notify_breakpoint_modified (b);
> +    }
>  }
> 
>  /* See breakpoint.h.  */
> @@ -8799,7 +8859,8 @@ create_breakpoints_sal (struct gdbarch *gdbarch,
> 
>  static void
>  parse_breakpoint_sals (location_spec *locspec,
> -		       struct linespec_result *canonical)
> +		       struct linespec_result *canonical,
> +		       struct program_space *search_pspace)
>  {
>    struct symtab_and_line cursal;
> 
> @@ -8864,7 +8925,7 @@ parse_breakpoint_sals (location_spec *locspec,
>  	      && strchr ("+-", spec[0]) != NULL
>  	      && spec[1] != '['))
>  	{
> -	  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, NULL,
> +	  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE,
> search_pspace,
>  			    get_last_displayed_symtab (),
>  			    get_last_displayed_line (),
>  			    canonical, NULL, NULL);
> @@ -8872,7 +8933,7 @@ parse_breakpoint_sals (location_spec *locspec,
>  	}
>      }
> 
> -  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, NULL,
> +  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, search_pspace,
>  		    cursal.symtab, cursal.line, canonical, NULL, NULL);
>  }
> 
> @@ -8971,6 +9032,39 @@ breakpoint_ops_for_location_spec_type (enum
> location_spec_type locspec_type,
>      }
>  }
> 
> +/* Return the program space to use as a filter when searching for locations
> +   of a breakpoint specific to THREAD or INFERIOR.  If THREAD and INFERIOR
> +   are both -1, meaning all threads/inferiors, then this function returns
> +   nullptr, indicating no program space filtering should be performed.
> +   Otherwise, this function returns the program space for the inferior that
> +   contains THREAD (when THREAD is not -1), or the program space for
> +   INFERIOR (when INFERIOR is not -1).  */
> +
> +static struct program_space *
> +find_program_space_for_breakpoint (int thread, int inferior)
> +{
> +  if (thread != -1)
> +    {
> +      gdb_assert (inferior == -1);
> +
> +      struct thread_info *thr = find_thread_global_id (thread);
> +      gdb_assert (thr != nullptr);
> +      gdb_assert (thr->inf != nullptr);
> +      return thr->inf->pspace;
> +    }
> +  else if (inferior != -1)
> +    {
> +      gdb_assert (thread == -1);
> +
> +      struct inferior *inf = find_inferior_id (inferior);
> +      gdb_assert (inf != nullptr);
> +
> +      return inf->pspace;
> +    }
> +
> +  return nullptr;
> +}
> +
>  /* See breakpoint.h.  */
> 
>  const struct breakpoint_ops *
> @@ -9072,7 +9166,10 @@ create_breakpoint (struct gdbarch *gdbarch,
> 
>    try
>      {
> -      ops->create_sals_from_location_spec (locspec, &canonical);
> +      struct program_space *search_pspace
> +	= find_program_space_for_breakpoint (thread, inferior);
> +      ops->create_sals_from_location_spec (locspec, &canonical,
> +					   search_pspace);
>      }
>    catch (const gdb_exception_error &e)
>      {
> @@ -9545,7 +9642,7 @@ break_range_command (const char *arg, int
> from_tty)
>    arg_start = arg;
>    location_spec_up start_locspec
>      = string_to_location_spec (&arg, current_language);
> -  parse_breakpoint_sals (start_locspec.get (), &canonical_start);
> +  parse_breakpoint_sals (start_locspec.get (), &canonical_start, nullptr);
> 
>    if (arg[0] != ',')
>      error (_("Too few arguments."));
> @@ -9646,7 +9743,7 @@ watchpoint_exp_is_const (const struct expression
> *exp)
>  /* Implement the "re_set" method for watchpoints.  */
> 
>  void
> -watchpoint::re_set ()
> +watchpoint::re_set (struct program_space *pspace)
>  {
>    /* Watchpoint can be either on expression using entirely global
>       variables, or it can be on local variables.
> @@ -11757,7 +11854,7 @@ breakpoint::print_recreate (struct ui_file *fp)
> const
>  /* Default breakpoint_ops methods.  */
> 
>  void
> -code_breakpoint::re_set ()
> +code_breakpoint::re_set (struct program_space *pspace)
>  {
>    /* FIXME: is this still reachable?  */
>    if (breakpoint_location_spec_empty_p (this))
> @@ -11767,7 +11864,7 @@ code_breakpoint::re_set ()
>        return;
>      }
> 
> -  re_set_default ();
> +  re_set_default (pspace);
>  }
> 
>  int
> @@ -11973,7 +12070,7 @@ code_breakpoint::decode_location_spec
> (location_spec *locspec,
>  /* Virtual table for internal breakpoints.  */
> 
>  void
> -internal_breakpoint::re_set ()
> +internal_breakpoint::re_set (struct program_space *pspace)
>  {
>    switch (type)
>      {
> @@ -12066,7 +12163,7 @@ internal_breakpoint::print_mention () const
>  /* Virtual table for momentary breakpoints  */
> 
>  void
> -momentary_breakpoint::re_set ()
> +momentary_breakpoint::re_set (struct program_space *pspace)
>  {
>    /* Keep temporary breakpoints, which can be encountered when we step
>       over a dlopen call and solib_add is resetting the breakpoints.
> @@ -12107,12 +12204,13 @@ longjmp_breakpoint::~longjmp_breakpoint ()
> 
>  static void
>  bkpt_probe_create_sals_from_location_spec (location_spec *locspec,
> -					   struct linespec_result *canonical)
> +					   struct linespec_result *canonical,
> +					   struct program_space
> *search_pspace)
> 
>  {
>    struct linespec_sals lsal;
> 
> -  lsal.sals = parse_probes (locspec, NULL, canonical);
> +  lsal.sals = parse_probes (locspec, search_pspace, canonical);
>    lsal.canonical = xstrdup (canonical->locspec->to_string ());
>    canonical->lsals.push_back (std::move (lsal));
>  }
> @@ -12202,9 +12300,9 @@ tracepoint::print_recreate (struct ui_file *fp)
> const
>  }
> 
>  void
> -dprintf_breakpoint::re_set ()
> +dprintf_breakpoint::re_set (struct program_space *pspace)
>  {
> -  re_set_default ();
> +  re_set_default (pspace);
> 
>    /* 1 - connect to target 1, that can run breakpoint commands.
>       2 - create a dprintf, which resolves fine.
> @@ -12258,8 +12356,10 @@ dprintf_breakpoint::after_condition_true
> (struct bpstat *bs)
>     markers (`-m').  */
> 
>  static void
> -strace_marker_create_sals_from_location_spec (location_spec *locspec,
> -					      struct linespec_result *canonical)
> +strace_marker_create_sals_from_location_spec
> +	(location_spec *locspec,
> +	 struct linespec_result *canonical,
> +	 struct program_space *search_pspace)
>  {
>    struct linespec_sals lsal;
>    const char *arg_start, *arg;
> @@ -12776,12 +12876,32 @@ update_breakpoint_locations
> (code_breakpoint *b,
>       all locations are in the same shared library, that was unloaded.
>       We'd like to retain the location, so that when the library is
>       loaded again, we don't loose the enabled/disabled status of the
> -     individual locations.  */
> +     individual locations.
> +
> +     Thread specific breakpoints will also trigger this case if the thread
> +     is changed to a different program space, and all of the old locations
> +     go out of scope.  In this case we do (currently) discard the old
> +     locations -- we assume the change in thread is permanent and the old
> +     locations will never come back into scope.  */
>    if (all_locations_are_pending (b, filter_pspace) && sals.empty ())
> -    return;
> +    {
> +      if (b->thread != -1)
> +	b->clear_locations ();
> +      return;
> +    }
> 
>    bp_location_list existing_locations = b->steal_locations (filter_pspace);
> 
> +  /* If this is a thread-specific breakpoint then any locations left on the
> +     breakpoint are for a program space in which the thread of interest
> +     does not operate.  This can happen when the user changes the thread of
> +     a thread-specific breakpoint.
> +
> +     We assume that the change in thread is permanent, and that the old
> +     locations will never be used again, so discard them now.  */
> +  if (b->thread != -1)
> +    b->clear_locations ();
> +
>    for (const auto &sal : sals)
>      {
>        struct bp_location *new_loc;
> @@ -12947,40 +13067,45 @@ code_breakpoint::location_spec_to_sals
> (location_spec *locspec,
>     locations.  */
> 
>  void
> -code_breakpoint::re_set_default ()
> +code_breakpoint::re_set_default (struct program_space *filter_pspace)
>  {
> -  struct program_space *filter_pspace = current_program_space;
>    std::vector<symtab_and_line> expanded, expanded_end;
> 
> -  int found;
> -  std::vector<symtab_and_line> sals = location_spec_to_sals (locspec.get (),
> -							     filter_pspace,
> -							     &found);
> -  if (found)
> -    expanded = std::move (sals);
> -
> -  if (locspec_range_end != nullptr)
> -    {
> -      std::vector<symtab_and_line> sals_end
> -	= location_spec_to_sals (locspec_range_end.get (),
> -				 filter_pspace, &found);
> +  /* If this breakpoint is thread-specific then find the program space in
> +     which the specific thread exists.  Otherwise, for breakpoints that are
> +     not thread-specific THREAD_PSPACE will be nullptr.  */
> +  program_space *bp_pspace
> +    = find_program_space_for_breakpoint (this->thread, this->inferior);
> +
> +  /* If this is not a thread or inferior specific breakpoint, or it is a
> +     thread or inferior specific breakpoint but we are looking for new
> +     locations in the program space that the specific thread or inferior is
> +     running, then look for new locations for this breakpoint.  */
> +  if (bp_pspace == nullptr || filter_pspace == bp_pspace)
> +    {
> +      int found;
> +      std::vector<symtab_and_line> sals
> +	= location_spec_to_sals (locspec.get (), filter_pspace, &found);
>        if (found)
> -	expanded_end = std::move (sals_end);
> +	expanded = std::move (sals);
> +
> +      if (locspec_range_end != nullptr)
> +	{
> +	  std::vector<symtab_and_line> sals_end
> +	    = location_spec_to_sals (locspec_range_end.get (),
> +				     filter_pspace, &found);
> +	  if (found)
> +	    expanded_end = std::move (sals_end);
> +	}
>      }
> 
> +  /* Update the locations for this breakpoint.  For thread-specific
> +     breakpoints this will remove any old locations that are for the wrong
> +     program space -- this can happen if the user changes the thread of a
> +     thread-specific breakpoint.  */
>    update_breakpoint_locations (this, filter_pspace, expanded,
> expanded_end);
>  }
> 
> -/* Default method for creating SALs from an address string.  It basically
> -   calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
> -
> -static void
> -create_sals_from_location_spec_default (location_spec *locspec,
> -					struct linespec_result *canonical)
> -{
> -  parse_breakpoint_sals (locspec, canonical);
> -}
> -
>  /* Re-set breakpoint locations for the current program space.
>     Locations bound to other program spaces are left untouched.  */
> 
> @@ -13015,7 +13140,7 @@ breakpoint_re_set (void)
>  	  {
>  	    input_radix = b.input_radix;
>  	    set_language (b.language);
> -	    b.re_set ();
> +	    b.re_set (current_program_space);
>  	  }
>  	catch (const gdb_exception &ex)
>  	  {
> @@ -13036,6 +13161,53 @@ breakpoint_re_set (void)
>    /* Now we can insert.  */
>    update_global_location_list (UGLL_MAY_INSERT);
>  }
> +
> +/* Re-set locations for breakpoint B in FILTER_PSPACE.  If FILTER_PSPACE is
> +   nullptr then re-set locations for B in all program spaces.  Locations
> +   bound to program spaces other than FILTER_PSPACE are left untouched.  */
> +
> +static void
> +breakpoint_re_set_one (breakpoint *b, program_space *filter_pspace)
> +{
> +  {
> +    scoped_restore_current_language save_language;
> +    scoped_restore save_input_radix = make_scoped_restore (&input_radix);
> +    scoped_restore_current_pspace_and_thread restore_pspace_thread;
> +
> +    /* To ::re_set each breakpoint we set the current_language to the
> +       language of the breakpoint before re-evaluating the breakpoint's
> +       location.  This change can unfortunately get undone by accident if
> +       the language_mode is set to auto, and we either switch frames, or
> +       more likely in this context, we select the current frame.
> +
> +       We prevent this by temporarily turning the language_mode to
> +       language_mode_manual.  We restore it once all breakpoints
> +       have been reset.  */
> +    scoped_restore save_language_mode = make_scoped_restore
> (&language_mode);
> +    language_mode = language_mode_manual;
> +
> +    /* Note: we must not try to insert locations until after all
> +       breakpoints have been re-set.  Otherwise, e.g., when re-setting
> +       breakpoint 1, we'd insert the locations of breakpoint 2, which
> +       hadn't been re-set yet, and thus may have stale locations.  */
> +
> +    try
> +      {
> +	input_radix = b->input_radix;
> +	set_language (b->language);
> +	b->re_set (filter_pspace);
> +      }
> +    catch (const gdb_exception &ex)
> +      {
> +	exception_fprintf (gdb_stderr, ex,
> +			   "Error in re-setting breakpoint %d: ",
> +			   b->number);
> +      }
> +  }
> +
> +  /* Now we can insert.  */
> +  update_global_location_list (UGLL_MAY_INSERT);
> +}
> 
> 
> 
>  /* Reset the thread number of this breakpoint:
> 
> diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
> index 42b49144e79..dea55deb314 100644
> --- a/gdb/breakpoint.h
> +++ b/gdb/breakpoint.h
> @@ -570,15 +570,15 @@ enum print_stop_action
> 
>  struct breakpoint_ops
>  {
> -  /* Create SALs from location spec, storing the result in
> -     linespec_result.
> -
> -     For an explanation about the arguments, see the function
> -     `create_sals_from_location_spec_default'.
> +  /* Create SALs from LOCSPEC, storing the result in linespec_result
> +     CANONICAL.  If SEARCH_PSPACE is not nullptr then only results in the
> +     corresponding program space are returned.  If SEARCH_PSPACE is nullptr
> +     then results for all program spaces are returned.
> 
>       This function is called inside `create_breakpoint'.  */
>    void (*create_sals_from_location_spec) (location_spec *locspec,
> -					  struct linespec_result *canonical);
> +					  linespec_result *canonical,
> +					  program_space *search_pspace);
> 
>    /* This method will be responsible for creating a breakpoint given its SALs.
>       Usually, it just calls `create_breakpoints_sal' (for ordinary
> @@ -710,8 +710,15 @@ struct breakpoint : public
> intrusive_list_node<breakpoint>
> 
>    /* Reevaluate a breakpoint.  This is necessary after symbols change
>       (e.g., an executable or DSO was loaded, or the inferior just
> -     started).  */
> -  virtual void re_set ()
> +     started).
> +
> +     If not nullptr, then FILTER_PSPACE is the program space in which
> +     symbols may have changed, we only need to add new locations in
> +     FILTER_PSPACE.
> +
> +     If FILTER_PSPACE is nullptr then all program spaces may have changed,
> +     new locations need to be searched for in every program space.  */
> +  virtual void re_set (program_space *filter_pspace)
>    {
>      /* Nothing to re-set.  */
>    }
> @@ -955,7 +962,7 @@ struct code_breakpoint : public breakpoint
>    /* Add a location for SAL to this breakpoint.  */
>    bp_location *add_location (const symtab_and_line &sal);
> 
> -  void re_set () override;
> +  void re_set (program_space *pspace) override;
>    int insert_location (struct bp_location *) override;
>    int remove_location (struct bp_location *,
>  		       enum remove_bp_reason reason) override;
> @@ -977,7 +984,7 @@ struct code_breakpoint : public breakpoint
>       struct program_space *search_pspace);
> 
>    /* Helper method that does the basic work of re_set.  */
> -  void re_set_default ();
> +  void re_set_default (program_space *pspace);
> 
>    /* Find the SaL locations corresponding to the given LOCATION.
>       On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
> @@ -999,7 +1006,7 @@ struct watchpoint : public breakpoint
>  {
>    using breakpoint::breakpoint;
> 
> -  void re_set () override;
> +  void re_set (program_space *pspace) override;
>    int insert_location (struct bp_location *) override;
>    int remove_location (struct bp_location *,
>  		       enum remove_bp_reason reason) override;
> diff --git a/gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp
> b/gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp
> index f736994d234..938e6deec05 100644
> --- a/gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp
> +++ b/gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp
> @@ -76,8 +76,12 @@ foreach_mi_ui_mode mode {
>      set loc2 [make_bp_loc "$::decimal\\.2"]
> 
>      # Create the inferior-specific breakpoint.
> -    mi_create_breakpoint_multi "-g i2 foo" "create breakpoint in inferior 2" \
> -	-inferior "2" -locations "\\\[$loc1,$loc2\\\]"
> +    mi_create_breakpoint "-g i2 foo" "create breakpoint in inferior 2" \
> +	-number "$decimal" \
> +	-type "breakpoint" \
> +	-enabled "y" \
> +	-func "foo" \
> +	-inferior "2"
>      set bpnum [mi_get_valueof "/d" "\$bpnum" "INVALID"]
> 
>      if {$mode eq "separate"} {
> diff --git a/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
> b/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
> index 93b91b42f92..ed331aff873 100644
> --- a/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
> +++ b/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
> @@ -370,7 +370,7 @@ proc test_continue_to_start { mode inf } {
>  			    "thread $inf.2 stops MI"
>  		    } else {
>  			mi_expect_stop "breakpoint-hit"
> "child_sub_function" \
> -			    "" "$srcfile" "$decimal" {"" "disp=\"del\""
> "locno=\"[0-9]+\""} \
> +			    "" "$srcfile" "$decimal" {"" "disp=\"del\""} \
>  			    "thread $inf.2 stops MI"
>  		    }

Hi Andrew,

For what it is worth: At some point I had backported your v8 on the
gdb 14 branch to play around with it and see if it fixes a downstream
problem I had. It didn't, but I tested your v8 a bit and didn't find any
issues with it on gdb 14.

While doing that I saw that we probably can just get rid of the
if else in this testcase here now. Sorry for not commenting this earlier.

Regards,
Felix
Intel Deutschland GmbH
Registered Address: Am Campeon 10, 85579 Neubiberg, Germany
Tel: +49 89 99 8853-0, www.intel.de <http://www.intel.de>
Managing Directors: Christin Eisenschmid, Sharon Heck, Tiffany Doon Silva  
Chairperson of the Supervisory Board: Nicole Lau
Registered Office: Munich
Commercial Register: Amtsgericht Muenchen HRB 186928

^ permalink raw reply	[flat|nested] 138+ messages in thread

* RE: [PATCHv9 14/14] gdb: only insert thread-specific breakpoints in the relevant inferior
  2024-03-05 15:49                   ` Willgerodt, Felix
@ 2024-03-06 14:11                     ` Andrew Burgess
  0 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2024-03-06 14:11 UTC (permalink / raw)
  To: Willgerodt, Felix, gdb-patches; +Cc: Eli Zaretskii

"Willgerodt, Felix" <felix.willgerodt@intel.com> writes:

>> -----Original Message-----
>> From: Andrew Burgess <aburgess@redhat.com>
>> Sent: Dienstag, 5. März 2024 16:22
>> To: gdb-patches@sourceware.org
>> Cc: Andrew Burgess <aburgess@redhat.com>; Eli Zaretskii <eliz@gnu.org>
>> Subject: [PATCHv9 14/14] gdb: only insert thread-specific breakpoints in the
>> relevant inferior
>> 
>> This commit updates GDB so that thread or inferior specific
>> breakpoints are only inserted into the program space in which the
>> specific thread or inferior is running.
>> 
>> In terms of implementation, getting this basically working is easy
>> enough, now that a breakpoint's thread or inferior field is setup
>> prior to GDB looking for locations, we can easily use this information
>> to find a suitable program_space and pass this to as a filter when
>> creating the sals.
>> 
>> Or we could if breakpoint_ops::create_sals_from_location_spec allowed
>> us to pass in a filter program_space.
>> 
>> So, this commit extends breakpoint_ops::create_sals_from_location_spec
>> to take a program_space argument, and uses this to filter the set of
>> returned sals.  This accounts for about half the change in this patch.
>> 
>> The second set of changes starts from breakpoint_set_thread and
>> breakpoint_set_inferior, this is called when the thread or inferior
>> for a breakpoint changes, e.g. from the Python API.
>> 
>> Previously this call would never result in the locations of a
>> breakpoint changing, after all, locations were inserted in every
>> program space, and we just use the thread or inferior variable to
>> decide when we should stop.  Now though, changing a breakpoint's
>> thread or inferior can mean we need to figure out a new set of
>> breakpoint locations.
>> 
>> To support this I've added a new breakpoint_re_set_one function, which
>> is like breakpoint_re_set, but takes a single breakpoint, and just
>> updates the locations for that one breakpoint.  We only need to call
>> this function if the program_space in which a breakpoint's thread (or
>> inferior) is running actually changes.  If the program_space does
>> change then we call the new breakpoint_re_set_one function passing in
>> the program_space which should be used to filter the new locations (or
>> nullptr to indicate we should set locations in all program spaces).
>> This filter program_space needs to propagate down to all the re_set
>> methods, this accounts for the remaining half of the changes in this
>> patch.
>> 
>> There were a couple of existing tests that created thread or inferior
>> specific breakpoints and then checked the 'info breakpoints' output,
>> these needed updating.  These were:
>> 
>>   gdb.mi/user-selected-context-sync.exp
>>   gdb.multi/bp-thread-specific.exp
>>   gdb.multi/multi-target-continue.exp
>>   gdb.multi/multi-target-ping-pong-next.exp
>>   gdb.multi/tids.exp
>>   gdb.mi/new-ui-bp-deleted.exp
>>   gdb.multi/inferior-specific-bp.exp
>>   gdb.multi/pending-bp-del-inferior.exp
>> 
>> I've also added some additional tests to:
>> 
>>   gdb.multi/pending-bp.exp
>> 
>> I've updated the documentation and added a NEWS entry.
>> 
>> Reviewed-By: Eli Zaretskii <eliz@gnu.org>
>> ---
>>  gdb/NEWS                                      |   7 +
>>  gdb/ada-lang.c                                |   6 +-
>>  gdb/break-catch-throw.c                       |   6 +-
>>  gdb/breakpoint.c                              | 280 ++++++++++++++----
>>  gdb/breakpoint.h                              |  29 +-
>>  gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp    |   8 +-
>>  .../gdb.mi/user-selected-context-sync.exp     |   4 +-
>>  .../gdb.multi/bp-thread-specific.exp          |   7 +-
>>  .../gdb.multi/inferior-specific-bp.exp        |  12 +-
>>  .../gdb.multi/multi-target-continue.exp       |   2 +-
>>  .../gdb.multi/multi-target-ping-pong-next.exp |   4 +-
>>  .../gdb.multi/pending-bp-del-inferior.exp     |   6 +-
>>  gdb/testsuite/gdb.multi/pending-bp.exp        | 206 +++++++++++++
>>  gdb/testsuite/gdb.multi/tids.exp              |   6 +-
>>  14 files changed, 484 insertions(+), 99 deletions(-)
>> 
>> diff --git a/gdb/NEWS b/gdb/NEWS
>> index c170385a50e..2a888d64e4d 100644
>> --- a/gdb/NEWS
>> +++ b/gdb/NEWS
>> @@ -17,6 +17,13 @@
>>    'thread' or 'task' keywords are parsed at the time the breakpoint is
>>    created, rather than at the time the breakpoint becomes non-pending.
>> 
>> +* Thread-specific breakpoints are only inserted into the program space
>> +  in which the thread of interest is running.  In most cases program
>> +  spaces are unique for each inferior, so this means that
>> +  thread-specific breakpoints will usually only be inserted for the
>> +  inferior containing the thread of interest.  The breakpoint will
>> +  be hit no less than before.
>> +
>>  * Changed commands
>> 
>>  disassemble
>> diff --git a/gdb/ada-lang.c b/gdb/ada-lang.c
>> index 1c26ebf7b30..c88acdf4035 100644
>> --- a/gdb/ada-lang.c
>> +++ b/gdb/ada-lang.c
>> @@ -12010,11 +12010,11 @@ struct ada_catchpoint : public
>> code_breakpoint
>>      enable_state = enabled ? bp_enabled : bp_disabled;
>>      language = language_ada;
>> 
>> -    re_set ();
>> +    re_set (pspace);
>>    }
>> 
>>    struct bp_location *allocate_location () override;
>> -  void re_set () override;
>> +  void re_set (program_space *pspace) override;
>>    void check_status (struct bpstat *bs) override;
>>    enum print_stop_action print_it (const bpstat *bs) const override;
>>    bool print_one (const bp_location **) const override;
>> @@ -12059,7 +12059,7 @@ static struct symtab_and_line ada_exception_sal
>>     catchpoint kinds.  */
>> 
>>  void
>> -ada_catchpoint::re_set ()
>> +ada_catchpoint::re_set (program_space *pspace)
>>  {
>>    std::vector<symtab_and_line> sals;
>>    try
>> diff --git a/gdb/break-catch-throw.c b/gdb/break-catch-throw.c
>> index d053bd5fbe0..7191d1b38fa 100644
>> --- a/gdb/break-catch-throw.c
>> +++ b/gdb/break-catch-throw.c
>> @@ -82,10 +82,10 @@ struct exception_catchpoint : public code_breakpoint
>>  				     _("invalid type-matching regexp")))
>>    {
>>      pspace = current_program_space;
>> -    re_set ();
>> +    re_set (pspace);
>>    }
>> 
>> -  void re_set () override;
>> +  void re_set (program_space *pspace) override;
>>    enum print_stop_action print_it (const bpstat *bs) const override;
>>    bool print_one (const bp_location **) const override;
>>    void print_mention () const override;
>> @@ -198,7 +198,7 @@ exception_catchpoint::check_status (struct bpstat
>> *bs)
>>  /* Implement the 're_set' method.  */
>> 
>>  void
>> -exception_catchpoint::re_set ()
>> +exception_catchpoint::re_set (program_space *pspace)
>>  {
>>    std::vector<symtab_and_line> sals;
>>    struct program_space *filter_pspace = current_program_space;
>> diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
>> index e1efde66feb..a190f2a78bf 100644
>> --- a/gdb/breakpoint.c
>> +++ b/gdb/breakpoint.c
>> @@ -91,9 +91,12 @@
>>  static void map_breakpoint_numbers (const char *,
>>  				    gdb::function_view<void (breakpoint *)>);
>> 
>> -static void
>> -  create_sals_from_location_spec_default (location_spec *locspec,
>> -					  linespec_result *canonical);
>> +static void parse_breakpoint_sals (location_spec *locspec,
>> +				   linespec_result *canonical,
>> +				   program_space *search_pspace);
>> +
>> +static void breakpoint_re_set_one (breakpoint *b,
>> +				   program_space *filter_pspace);
>> 
>>  static void create_breakpoints_sal (struct gdbarch *,
>>  				    struct linespec_result *,
>> @@ -283,11 +286,12 @@ static bool strace_marker_p (struct breakpoint *b);
>> 
>>  static void bkpt_probe_create_sals_from_location_spec
>>       (location_spec *locspec,
>> -      struct linespec_result *canonical);
>> +      struct linespec_result *canonical,
>> +      struct program_space *search_pspace);
>> 
>>  const struct breakpoint_ops code_breakpoint_ops =
>>  {
>> -  create_sals_from_location_spec_default,
>> +  parse_breakpoint_sals,
>>    create_breakpoints_sal,
>>  };
>> 
>> @@ -352,7 +356,7 @@ struct internal_breakpoint : public code_breakpoint
>>      disposition = disp_donttouch;
>>    }
>> 
>> -  void re_set () override;
>> +  void re_set (program_space *pspace) override;
>>    void check_status (struct bpstat *bs) override;
>>    enum print_stop_action print_it (const bpstat *bs) const override;
>>    void print_mention () const override;
>> @@ -389,7 +393,7 @@ struct momentary_breakpoint : public
>> code_breakpoint
>>      gdb_assert (inferior == -1);
>>    }
>> 
>> -  void re_set () override;
>> +  void re_set (program_space *pspace) override;
>>    void check_status (struct bpstat *bs) override;
>>    enum print_stop_action print_it (const bpstat *bs) const override;
>>    void print_mention () const override;
>> @@ -400,7 +404,7 @@ struct dprintf_breakpoint : public
>> ordinary_breakpoint
>>  {
>>    using ordinary_breakpoint::ordinary_breakpoint;
>> 
>> -  void re_set () override;
>> +  void re_set (program_space *pspace) override;
>>    int breakpoint_hit (const struct bp_location *bl,
>>  		      const address_space *aspace,
>>  		      CORE_ADDR bp_addr,
>> @@ -1549,7 +1553,36 @@ breakpoint_set_thread (struct breakpoint *b, int
>> thread)
>>    int old_thread = b->thread;
>>    b->thread = thread;
>>    if (old_thread != thread)
>> -    notify_breakpoint_modified (b);
>> +    {
>> +      /* If THREAD is in a different program_space than OLD_THREAD, or the
>> +	 breakpoint has switched to or from being thread-specific, then we
>> +	 need to re-set the locations of this breakpoint.  First, figure
>> +	 out the program_space for the old and new threads, use a value of
>> +	 nullptr to indicate the breakpoint is in all program spaces.  */
>> +      program_space *old_pspace = nullptr;
>> +      if (old_thread != -1)
>> +	{
>> +	  struct thread_info *thr = find_thread_global_id (old_thread);
>> +	  gdb_assert (thr != nullptr);
>> +	  old_pspace = thr->inf->pspace;
>> +	}
>> +
>> +      program_space *new_pspace = nullptr;
>> +      if (thread != -1)
>> +	{
>> +	  struct thread_info *thr = find_thread_global_id (thread);
>> +	  gdb_assert (thr != nullptr);
>> +	  new_pspace = thr->inf->pspace;
>> +	}
>> +
>> +      /* If the program space has changed for this breakpoint, then
>> +	 re-evaluate it's locations.  */
>> +      if (old_pspace != new_pspace)
>> +	breakpoint_re_set_one (b, new_pspace);
>> +
>> +      /* Let others know the breakpoint has changed.  */
>> +      notify_breakpoint_modified (b);
>> +    }
>>  }
>> 
>>  /* See breakpoint.h.  */
>> @@ -1568,7 +1601,34 @@ breakpoint_set_inferior (struct breakpoint *b, int
>> inferior)
>>    int old_inferior = b->inferior;
>>    b->inferior = inferior;
>>    if (old_inferior != inferior)
>> -    notify_breakpoint_modified (b);
>> +    {
>> +      /* If INFERIOR is in a different program_space than OLD_INFERIOR, or
>> +	 the breakpoint has switch to or from inferior-specific, then we
>> +	 need to re-set the locations of this breakpoint.  First, figure
>> +	 out the program_space for the old and new inferiors, use a value
>> +	 of nullptr to indicate the breakpoint is in all program
>> +	 spaces.  */
>> +      program_space *old_pspace = nullptr;
>> +      if (old_inferior != -1)
>> +	{
>> +	  struct inferior *inf = find_inferior_id (old_inferior);
>> +	  gdb_assert (inf != nullptr);
>> +	  old_pspace = inf->pspace;
>> +	}
>> +
>> +      program_space *new_pspace = nullptr;
>> +      if (inferior != -1)
>> +	{
>> +	  struct inferior *inf = find_inferior_id (inferior);
>> +	  gdb_assert (inf != nullptr);
>> +	  new_pspace = inf->pspace;
>> +	}
>> +
>> +      if (old_pspace != new_pspace)
>> +	breakpoint_re_set_one (b, new_pspace);
>> +
>> +      notify_breakpoint_modified (b);
>> +    }
>>  }
>> 
>>  /* See breakpoint.h.  */
>> @@ -8799,7 +8859,8 @@ create_breakpoints_sal (struct gdbarch *gdbarch,
>> 
>>  static void
>>  parse_breakpoint_sals (location_spec *locspec,
>> -		       struct linespec_result *canonical)
>> +		       struct linespec_result *canonical,
>> +		       struct program_space *search_pspace)
>>  {
>>    struct symtab_and_line cursal;
>> 
>> @@ -8864,7 +8925,7 @@ parse_breakpoint_sals (location_spec *locspec,
>>  	      && strchr ("+-", spec[0]) != NULL
>>  	      && spec[1] != '['))
>>  	{
>> -	  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, NULL,
>> +	  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE,
>> search_pspace,
>>  			    get_last_displayed_symtab (),
>>  			    get_last_displayed_line (),
>>  			    canonical, NULL, NULL);
>> @@ -8872,7 +8933,7 @@ parse_breakpoint_sals (location_spec *locspec,
>>  	}
>>      }
>> 
>> -  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, NULL,
>> +  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, search_pspace,
>>  		    cursal.symtab, cursal.line, canonical, NULL, NULL);
>>  }
>> 
>> @@ -8971,6 +9032,39 @@ breakpoint_ops_for_location_spec_type (enum
>> location_spec_type locspec_type,
>>      }
>>  }
>> 
>> +/* Return the program space to use as a filter when searching for locations
>> +   of a breakpoint specific to THREAD or INFERIOR.  If THREAD and INFERIOR
>> +   are both -1, meaning all threads/inferiors, then this function returns
>> +   nullptr, indicating no program space filtering should be performed.
>> +   Otherwise, this function returns the program space for the inferior that
>> +   contains THREAD (when THREAD is not -1), or the program space for
>> +   INFERIOR (when INFERIOR is not -1).  */
>> +
>> +static struct program_space *
>> +find_program_space_for_breakpoint (int thread, int inferior)
>> +{
>> +  if (thread != -1)
>> +    {
>> +      gdb_assert (inferior == -1);
>> +
>> +      struct thread_info *thr = find_thread_global_id (thread);
>> +      gdb_assert (thr != nullptr);
>> +      gdb_assert (thr->inf != nullptr);
>> +      return thr->inf->pspace;
>> +    }
>> +  else if (inferior != -1)
>> +    {
>> +      gdb_assert (thread == -1);
>> +
>> +      struct inferior *inf = find_inferior_id (inferior);
>> +      gdb_assert (inf != nullptr);
>> +
>> +      return inf->pspace;
>> +    }
>> +
>> +  return nullptr;
>> +}
>> +
>>  /* See breakpoint.h.  */
>> 
>>  const struct breakpoint_ops *
>> @@ -9072,7 +9166,10 @@ create_breakpoint (struct gdbarch *gdbarch,
>> 
>>    try
>>      {
>> -      ops->create_sals_from_location_spec (locspec, &canonical);
>> +      struct program_space *search_pspace
>> +	= find_program_space_for_breakpoint (thread, inferior);
>> +      ops->create_sals_from_location_spec (locspec, &canonical,
>> +					   search_pspace);
>>      }
>>    catch (const gdb_exception_error &e)
>>      {
>> @@ -9545,7 +9642,7 @@ break_range_command (const char *arg, int
>> from_tty)
>>    arg_start = arg;
>>    location_spec_up start_locspec
>>      = string_to_location_spec (&arg, current_language);
>> -  parse_breakpoint_sals (start_locspec.get (), &canonical_start);
>> +  parse_breakpoint_sals (start_locspec.get (), &canonical_start, nullptr);
>> 
>>    if (arg[0] != ',')
>>      error (_("Too few arguments."));
>> @@ -9646,7 +9743,7 @@ watchpoint_exp_is_const (const struct expression
>> *exp)
>>  /* Implement the "re_set" method for watchpoints.  */
>> 
>>  void
>> -watchpoint::re_set ()
>> +watchpoint::re_set (struct program_space *pspace)
>>  {
>>    /* Watchpoint can be either on expression using entirely global
>>       variables, or it can be on local variables.
>> @@ -11757,7 +11854,7 @@ breakpoint::print_recreate (struct ui_file *fp)
>> const
>>  /* Default breakpoint_ops methods.  */
>> 
>>  void
>> -code_breakpoint::re_set ()
>> +code_breakpoint::re_set (struct program_space *pspace)
>>  {
>>    /* FIXME: is this still reachable?  */
>>    if (breakpoint_location_spec_empty_p (this))
>> @@ -11767,7 +11864,7 @@ code_breakpoint::re_set ()
>>        return;
>>      }
>> 
>> -  re_set_default ();
>> +  re_set_default (pspace);
>>  }
>> 
>>  int
>> @@ -11973,7 +12070,7 @@ code_breakpoint::decode_location_spec
>> (location_spec *locspec,
>>  /* Virtual table for internal breakpoints.  */
>> 
>>  void
>> -internal_breakpoint::re_set ()
>> +internal_breakpoint::re_set (struct program_space *pspace)
>>  {
>>    switch (type)
>>      {
>> @@ -12066,7 +12163,7 @@ internal_breakpoint::print_mention () const
>>  /* Virtual table for momentary breakpoints  */
>> 
>>  void
>> -momentary_breakpoint::re_set ()
>> +momentary_breakpoint::re_set (struct program_space *pspace)
>>  {
>>    /* Keep temporary breakpoints, which can be encountered when we step
>>       over a dlopen call and solib_add is resetting the breakpoints.
>> @@ -12107,12 +12204,13 @@ longjmp_breakpoint::~longjmp_breakpoint ()
>> 
>>  static void
>>  bkpt_probe_create_sals_from_location_spec (location_spec *locspec,
>> -					   struct linespec_result *canonical)
>> +					   struct linespec_result *canonical,
>> +					   struct program_space
>> *search_pspace)
>> 
>>  {
>>    struct linespec_sals lsal;
>> 
>> -  lsal.sals = parse_probes (locspec, NULL, canonical);
>> +  lsal.sals = parse_probes (locspec, search_pspace, canonical);
>>    lsal.canonical = xstrdup (canonical->locspec->to_string ());
>>    canonical->lsals.push_back (std::move (lsal));
>>  }
>> @@ -12202,9 +12300,9 @@ tracepoint::print_recreate (struct ui_file *fp)
>> const
>>  }
>> 
>>  void
>> -dprintf_breakpoint::re_set ()
>> +dprintf_breakpoint::re_set (struct program_space *pspace)
>>  {
>> -  re_set_default ();
>> +  re_set_default (pspace);
>> 
>>    /* 1 - connect to target 1, that can run breakpoint commands.
>>       2 - create a dprintf, which resolves fine.
>> @@ -12258,8 +12356,10 @@ dprintf_breakpoint::after_condition_true
>> (struct bpstat *bs)
>>     markers (`-m').  */
>> 
>>  static void
>> -strace_marker_create_sals_from_location_spec (location_spec *locspec,
>> -					      struct linespec_result *canonical)
>> +strace_marker_create_sals_from_location_spec
>> +	(location_spec *locspec,
>> +	 struct linespec_result *canonical,
>> +	 struct program_space *search_pspace)
>>  {
>>    struct linespec_sals lsal;
>>    const char *arg_start, *arg;
>> @@ -12776,12 +12876,32 @@ update_breakpoint_locations
>> (code_breakpoint *b,
>>       all locations are in the same shared library, that was unloaded.
>>       We'd like to retain the location, so that when the library is
>>       loaded again, we don't loose the enabled/disabled status of the
>> -     individual locations.  */
>> +     individual locations.
>> +
>> +     Thread specific breakpoints will also trigger this case if the thread
>> +     is changed to a different program space, and all of the old locations
>> +     go out of scope.  In this case we do (currently) discard the old
>> +     locations -- we assume the change in thread is permanent and the old
>> +     locations will never come back into scope.  */
>>    if (all_locations_are_pending (b, filter_pspace) && sals.empty ())
>> -    return;
>> +    {
>> +      if (b->thread != -1)
>> +	b->clear_locations ();
>> +      return;
>> +    }
>> 
>>    bp_location_list existing_locations = b->steal_locations (filter_pspace);
>> 
>> +  /* If this is a thread-specific breakpoint then any locations left on the
>> +     breakpoint are for a program space in which the thread of interest
>> +     does not operate.  This can happen when the user changes the thread of
>> +     a thread-specific breakpoint.
>> +
>> +     We assume that the change in thread is permanent, and that the old
>> +     locations will never be used again, so discard them now.  */
>> +  if (b->thread != -1)
>> +    b->clear_locations ();
>> +
>>    for (const auto &sal : sals)
>>      {
>>        struct bp_location *new_loc;
>> @@ -12947,40 +13067,45 @@ code_breakpoint::location_spec_to_sals
>> (location_spec *locspec,
>>     locations.  */
>> 
>>  void
>> -code_breakpoint::re_set_default ()
>> +code_breakpoint::re_set_default (struct program_space *filter_pspace)
>>  {
>> -  struct program_space *filter_pspace = current_program_space;
>>    std::vector<symtab_and_line> expanded, expanded_end;
>> 
>> -  int found;
>> -  std::vector<symtab_and_line> sals = location_spec_to_sals (locspec.get (),
>> -							     filter_pspace,
>> -							     &found);
>> -  if (found)
>> -    expanded = std::move (sals);
>> -
>> -  if (locspec_range_end != nullptr)
>> -    {
>> -      std::vector<symtab_and_line> sals_end
>> -	= location_spec_to_sals (locspec_range_end.get (),
>> -				 filter_pspace, &found);
>> +  /* If this breakpoint is thread-specific then find the program space in
>> +     which the specific thread exists.  Otherwise, for breakpoints that are
>> +     not thread-specific THREAD_PSPACE will be nullptr.  */
>> +  program_space *bp_pspace
>> +    = find_program_space_for_breakpoint (this->thread, this->inferior);
>> +
>> +  /* If this is not a thread or inferior specific breakpoint, or it is a
>> +     thread or inferior specific breakpoint but we are looking for new
>> +     locations in the program space that the specific thread or inferior is
>> +     running, then look for new locations for this breakpoint.  */
>> +  if (bp_pspace == nullptr || filter_pspace == bp_pspace)
>> +    {
>> +      int found;
>> +      std::vector<symtab_and_line> sals
>> +	= location_spec_to_sals (locspec.get (), filter_pspace, &found);
>>        if (found)
>> -	expanded_end = std::move (sals_end);
>> +	expanded = std::move (sals);
>> +
>> +      if (locspec_range_end != nullptr)
>> +	{
>> +	  std::vector<symtab_and_line> sals_end
>> +	    = location_spec_to_sals (locspec_range_end.get (),
>> +				     filter_pspace, &found);
>> +	  if (found)
>> +	    expanded_end = std::move (sals_end);
>> +	}
>>      }
>> 
>> +  /* Update the locations for this breakpoint.  For thread-specific
>> +     breakpoints this will remove any old locations that are for the wrong
>> +     program space -- this can happen if the user changes the thread of a
>> +     thread-specific breakpoint.  */
>>    update_breakpoint_locations (this, filter_pspace, expanded,
>> expanded_end);
>>  }
>> 
>> -/* Default method for creating SALs from an address string.  It basically
>> -   calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
>> -
>> -static void
>> -create_sals_from_location_spec_default (location_spec *locspec,
>> -					struct linespec_result *canonical)
>> -{
>> -  parse_breakpoint_sals (locspec, canonical);
>> -}
>> -
>>  /* Re-set breakpoint locations for the current program space.
>>     Locations bound to other program spaces are left untouched.  */
>> 
>> @@ -13015,7 +13140,7 @@ breakpoint_re_set (void)
>>  	  {
>>  	    input_radix = b.input_radix;
>>  	    set_language (b.language);
>> -	    b.re_set ();
>> +	    b.re_set (current_program_space);
>>  	  }
>>  	catch (const gdb_exception &ex)
>>  	  {
>> @@ -13036,6 +13161,53 @@ breakpoint_re_set (void)
>>    /* Now we can insert.  */
>>    update_global_location_list (UGLL_MAY_INSERT);
>>  }
>> +
>> +/* Re-set locations for breakpoint B in FILTER_PSPACE.  If FILTER_PSPACE is
>> +   nullptr then re-set locations for B in all program spaces.  Locations
>> +   bound to program spaces other than FILTER_PSPACE are left untouched.  */
>> +
>> +static void
>> +breakpoint_re_set_one (breakpoint *b, program_space *filter_pspace)
>> +{
>> +  {
>> +    scoped_restore_current_language save_language;
>> +    scoped_restore save_input_radix = make_scoped_restore (&input_radix);
>> +    scoped_restore_current_pspace_and_thread restore_pspace_thread;
>> +
>> +    /* To ::re_set each breakpoint we set the current_language to the
>> +       language of the breakpoint before re-evaluating the breakpoint's
>> +       location.  This change can unfortunately get undone by accident if
>> +       the language_mode is set to auto, and we either switch frames, or
>> +       more likely in this context, we select the current frame.
>> +
>> +       We prevent this by temporarily turning the language_mode to
>> +       language_mode_manual.  We restore it once all breakpoints
>> +       have been reset.  */
>> +    scoped_restore save_language_mode = make_scoped_restore
>> (&language_mode);
>> +    language_mode = language_mode_manual;
>> +
>> +    /* Note: we must not try to insert locations until after all
>> +       breakpoints have been re-set.  Otherwise, e.g., when re-setting
>> +       breakpoint 1, we'd insert the locations of breakpoint 2, which
>> +       hadn't been re-set yet, and thus may have stale locations.  */
>> +
>> +    try
>> +      {
>> +	input_radix = b->input_radix;
>> +	set_language (b->language);
>> +	b->re_set (filter_pspace);
>> +      }
>> +    catch (const gdb_exception &ex)
>> +      {
>> +	exception_fprintf (gdb_stderr, ex,
>> +			   "Error in re-setting breakpoint %d: ",
>> +			   b->number);
>> +      }
>> +  }
>> +
>> +  /* Now we can insert.  */
>> +  update_global_location_list (UGLL_MAY_INSERT);
>> +}
>> 
>> 
>> 
>>  /* Reset the thread number of this breakpoint:
>> 
>> diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
>> index 42b49144e79..dea55deb314 100644
>> --- a/gdb/breakpoint.h
>> +++ b/gdb/breakpoint.h
>> @@ -570,15 +570,15 @@ enum print_stop_action
>> 
>>  struct breakpoint_ops
>>  {
>> -  /* Create SALs from location spec, storing the result in
>> -     linespec_result.
>> -
>> -     For an explanation about the arguments, see the function
>> -     `create_sals_from_location_spec_default'.
>> +  /* Create SALs from LOCSPEC, storing the result in linespec_result
>> +     CANONICAL.  If SEARCH_PSPACE is not nullptr then only results in the
>> +     corresponding program space are returned.  If SEARCH_PSPACE is nullptr
>> +     then results for all program spaces are returned.
>> 
>>       This function is called inside `create_breakpoint'.  */
>>    void (*create_sals_from_location_spec) (location_spec *locspec,
>> -					  struct linespec_result *canonical);
>> +					  linespec_result *canonical,
>> +					  program_space *search_pspace);
>> 
>>    /* This method will be responsible for creating a breakpoint given its SALs.
>>       Usually, it just calls `create_breakpoints_sal' (for ordinary
>> @@ -710,8 +710,15 @@ struct breakpoint : public
>> intrusive_list_node<breakpoint>
>> 
>>    /* Reevaluate a breakpoint.  This is necessary after symbols change
>>       (e.g., an executable or DSO was loaded, or the inferior just
>> -     started).  */
>> -  virtual void re_set ()
>> +     started).
>> +
>> +     If not nullptr, then FILTER_PSPACE is the program space in which
>> +     symbols may have changed, we only need to add new locations in
>> +     FILTER_PSPACE.
>> +
>> +     If FILTER_PSPACE is nullptr then all program spaces may have changed,
>> +     new locations need to be searched for in every program space.  */
>> +  virtual void re_set (program_space *filter_pspace)
>>    {
>>      /* Nothing to re-set.  */
>>    }
>> @@ -955,7 +962,7 @@ struct code_breakpoint : public breakpoint
>>    /* Add a location for SAL to this breakpoint.  */
>>    bp_location *add_location (const symtab_and_line &sal);
>> 
>> -  void re_set () override;
>> +  void re_set (program_space *pspace) override;
>>    int insert_location (struct bp_location *) override;
>>    int remove_location (struct bp_location *,
>>  		       enum remove_bp_reason reason) override;
>> @@ -977,7 +984,7 @@ struct code_breakpoint : public breakpoint
>>       struct program_space *search_pspace);
>> 
>>    /* Helper method that does the basic work of re_set.  */
>> -  void re_set_default ();
>> +  void re_set_default (program_space *pspace);
>> 
>>    /* Find the SaL locations corresponding to the given LOCATION.
>>       On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
>> @@ -999,7 +1006,7 @@ struct watchpoint : public breakpoint
>>  {
>>    using breakpoint::breakpoint;
>> 
>> -  void re_set () override;
>> +  void re_set (program_space *pspace) override;
>>    int insert_location (struct bp_location *) override;
>>    int remove_location (struct bp_location *,
>>  		       enum remove_bp_reason reason) override;
>> diff --git a/gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp
>> b/gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp
>> index f736994d234..938e6deec05 100644
>> --- a/gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp
>> +++ b/gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp
>> @@ -76,8 +76,12 @@ foreach_mi_ui_mode mode {
>>      set loc2 [make_bp_loc "$::decimal\\.2"]
>> 
>>      # Create the inferior-specific breakpoint.
>> -    mi_create_breakpoint_multi "-g i2 foo" "create breakpoint in inferior 2" \
>> -	-inferior "2" -locations "\\\[$loc1,$loc2\\\]"
>> +    mi_create_breakpoint "-g i2 foo" "create breakpoint in inferior 2" \
>> +	-number "$decimal" \
>> +	-type "breakpoint" \
>> +	-enabled "y" \
>> +	-func "foo" \
>> +	-inferior "2"
>>      set bpnum [mi_get_valueof "/d" "\$bpnum" "INVALID"]
>> 
>>      if {$mode eq "separate"} {
>> diff --git a/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
>> b/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
>> index 93b91b42f92..ed331aff873 100644
>> --- a/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
>> +++ b/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
>> @@ -370,7 +370,7 @@ proc test_continue_to_start { mode inf } {
>>  			    "thread $inf.2 stops MI"
>>  		    } else {
>>  			mi_expect_stop "breakpoint-hit"
>> "child_sub_function" \
>> -			    "" "$srcfile" "$decimal" {"" "disp=\"del\""
>> "locno=\"[0-9]+\""} \
>> +			    "" "$srcfile" "$decimal" {"" "disp=\"del\""} \
>>  			    "thread $inf.2 stops MI"
>>  		    }
>
> Hi Andrew,
>
> For what it is worth: At some point I had backported your v8 on the
> gdb 14 branch to play around with it and see if it fixes a downstream
> problem I had. It didn't, but I tested your v8 a bit and didn't find any
> issues with it on gdb 14.

If your downstream issue is in the same area, do you think this
indicates an oversight / issue with this series as it currently stands?

You say downstream issue, so I guess it doesn't impact upstream GDB.  So
there's likely no easy way I could investigate to see if this series
could be made to help you?

> While doing that I saw that we probably can just get rid of the
> if else in this testcase here now. Sorry for not commenting this
> earlier.

Good catch.  The updated patch is below.

Thanks,
Andrew

---

commit 81af4bd48799027180954a1ff9483b8c9aa77023
Author: Andrew Burgess <aburgess@redhat.com>
Date:   Fri Mar 3 19:03:15 2023 +0000

    gdb: only insert thread-specific breakpoints in the relevant inferior
    
    This commit updates GDB so that thread or inferior specific
    breakpoints are only inserted into the program space in which the
    specific thread or inferior is running.
    
    In terms of implementation, getting this basically working is easy
    enough, now that a breakpoint's thread or inferior field is setup
    prior to GDB looking for locations, we can easily use this information
    to find a suitable program_space and pass this to as a filter when
    creating the sals.
    
    Or we could if breakpoint_ops::create_sals_from_location_spec allowed
    us to pass in a filter program_space.
    
    So, this commit extends breakpoint_ops::create_sals_from_location_spec
    to take a program_space argument, and uses this to filter the set of
    returned sals.  This accounts for about half the change in this patch.
    
    The second set of changes starts from breakpoint_set_thread and
    breakpoint_set_inferior, this is called when the thread or inferior
    for a breakpoint changes, e.g. from the Python API.
    
    Previously this call would never result in the locations of a
    breakpoint changing, after all, locations were inserted in every
    program space, and we just use the thread or inferior variable to
    decide when we should stop.  Now though, changing a breakpoint's
    thread or inferior can mean we need to figure out a new set of
    breakpoint locations.
    
    To support this I've added a new breakpoint_re_set_one function, which
    is like breakpoint_re_set, but takes a single breakpoint, and just
    updates the locations for that one breakpoint.  We only need to call
    this function if the program_space in which a breakpoint's thread (or
    inferior) is running actually changes.  If the program_space does
    change then we call the new breakpoint_re_set_one function passing in
    the program_space which should be used to filter the new locations (or
    nullptr to indicate we should set locations in all program spaces).
    This filter program_space needs to propagate down to all the re_set
    methods, this accounts for the remaining half of the changes in this
    patch.
    
    There were a couple of existing tests that created thread or inferior
    specific breakpoints and then checked the 'info breakpoints' output,
    these needed updating.  These were:
    
      gdb.mi/user-selected-context-sync.exp
      gdb.multi/bp-thread-specific.exp
      gdb.multi/multi-target-continue.exp
      gdb.multi/multi-target-ping-pong-next.exp
      gdb.multi/tids.exp
      gdb.mi/new-ui-bp-deleted.exp
      gdb.multi/inferior-specific-bp.exp
      gdb.multi/pending-bp-del-inferior.exp
    
    I've also added some additional tests to:
    
      gdb.multi/pending-bp.exp
    
    I've updated the documentation and added a NEWS entry.
    
    Reviewed-By: Eli Zaretskii <eliz@gnu.org>

diff --git a/gdb/NEWS b/gdb/NEWS
index c170385a50e..2a888d64e4d 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -17,6 +17,13 @@
   'thread' or 'task' keywords are parsed at the time the breakpoint is
   created, rather than at the time the breakpoint becomes non-pending.
 
+* Thread-specific breakpoints are only inserted into the program space
+  in which the thread of interest is running.  In most cases program
+  spaces are unique for each inferior, so this means that
+  thread-specific breakpoints will usually only be inserted for the
+  inferior containing the thread of interest.  The breakpoint will
+  be hit no less than before.
+
 * Changed commands
 
 disassemble
diff --git a/gdb/ada-lang.c b/gdb/ada-lang.c
index 1c26ebf7b30..c88acdf4035 100644
--- a/gdb/ada-lang.c
+++ b/gdb/ada-lang.c
@@ -12010,11 +12010,11 @@ struct ada_catchpoint : public code_breakpoint
     enable_state = enabled ? bp_enabled : bp_disabled;
     language = language_ada;
 
-    re_set ();
+    re_set (pspace);
   }
 
   struct bp_location *allocate_location () override;
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   void check_status (struct bpstat *bs) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   bool print_one (const bp_location **) const override;
@@ -12059,7 +12059,7 @@ static struct symtab_and_line ada_exception_sal
    catchpoint kinds.  */
 
 void
-ada_catchpoint::re_set ()
+ada_catchpoint::re_set (program_space *pspace)
 {
   std::vector<symtab_and_line> sals;
   try
diff --git a/gdb/break-catch-throw.c b/gdb/break-catch-throw.c
index d053bd5fbe0..7191d1b38fa 100644
--- a/gdb/break-catch-throw.c
+++ b/gdb/break-catch-throw.c
@@ -82,10 +82,10 @@ struct exception_catchpoint : public code_breakpoint
 				     _("invalid type-matching regexp")))
   {
     pspace = current_program_space;
-    re_set ();
+    re_set (pspace);
   }
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   bool print_one (const bp_location **) const override;
   void print_mention () const override;
@@ -198,7 +198,7 @@ exception_catchpoint::check_status (struct bpstat *bs)
 /* Implement the 're_set' method.  */
 
 void
-exception_catchpoint::re_set ()
+exception_catchpoint::re_set (program_space *pspace)
 {
   std::vector<symtab_and_line> sals;
   struct program_space *filter_pspace = current_program_space;
diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index e1efde66feb..a190f2a78bf 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -91,9 +91,12 @@
 static void map_breakpoint_numbers (const char *,
 				    gdb::function_view<void (breakpoint *)>);
 
-static void
-  create_sals_from_location_spec_default (location_spec *locspec,
-					  linespec_result *canonical);
+static void parse_breakpoint_sals (location_spec *locspec,
+				   linespec_result *canonical,
+				   program_space *search_pspace);
+
+static void breakpoint_re_set_one (breakpoint *b,
+				   program_space *filter_pspace);
 
 static void create_breakpoints_sal (struct gdbarch *,
 				    struct linespec_result *,
@@ -283,11 +286,12 @@ static bool strace_marker_p (struct breakpoint *b);
 
 static void bkpt_probe_create_sals_from_location_spec
      (location_spec *locspec,
-      struct linespec_result *canonical);
+      struct linespec_result *canonical,
+      struct program_space *search_pspace);
 
 const struct breakpoint_ops code_breakpoint_ops =
 {
-  create_sals_from_location_spec_default,
+  parse_breakpoint_sals,
   create_breakpoints_sal,
 };
 
@@ -352,7 +356,7 @@ struct internal_breakpoint : public code_breakpoint
     disposition = disp_donttouch;
   }
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   void check_status (struct bpstat *bs) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   void print_mention () const override;
@@ -389,7 +393,7 @@ struct momentary_breakpoint : public code_breakpoint
     gdb_assert (inferior == -1);
   }
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   void check_status (struct bpstat *bs) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   void print_mention () const override;
@@ -400,7 +404,7 @@ struct dprintf_breakpoint : public ordinary_breakpoint
 {
   using ordinary_breakpoint::ordinary_breakpoint;
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   int breakpoint_hit (const struct bp_location *bl,
 		      const address_space *aspace,
 		      CORE_ADDR bp_addr,
@@ -1549,7 +1553,36 @@ breakpoint_set_thread (struct breakpoint *b, int thread)
   int old_thread = b->thread;
   b->thread = thread;
   if (old_thread != thread)
-    notify_breakpoint_modified (b);
+    {
+      /* If THREAD is in a different program_space than OLD_THREAD, or the
+	 breakpoint has switched to or from being thread-specific, then we
+	 need to re-set the locations of this breakpoint.  First, figure
+	 out the program_space for the old and new threads, use a value of
+	 nullptr to indicate the breakpoint is in all program spaces.  */
+      program_space *old_pspace = nullptr;
+      if (old_thread != -1)
+	{
+	  struct thread_info *thr = find_thread_global_id (old_thread);
+	  gdb_assert (thr != nullptr);
+	  old_pspace = thr->inf->pspace;
+	}
+
+      program_space *new_pspace = nullptr;
+      if (thread != -1)
+	{
+	  struct thread_info *thr = find_thread_global_id (thread);
+	  gdb_assert (thr != nullptr);
+	  new_pspace = thr->inf->pspace;
+	}
+
+      /* If the program space has changed for this breakpoint, then
+	 re-evaluate it's locations.  */
+      if (old_pspace != new_pspace)
+	breakpoint_re_set_one (b, new_pspace);
+
+      /* Let others know the breakpoint has changed.  */
+      notify_breakpoint_modified (b);
+    }
 }
 
 /* See breakpoint.h.  */
@@ -1568,7 +1601,34 @@ breakpoint_set_inferior (struct breakpoint *b, int inferior)
   int old_inferior = b->inferior;
   b->inferior = inferior;
   if (old_inferior != inferior)
-    notify_breakpoint_modified (b);
+    {
+      /* If INFERIOR is in a different program_space than OLD_INFERIOR, or
+	 the breakpoint has switch to or from inferior-specific, then we
+	 need to re-set the locations of this breakpoint.  First, figure
+	 out the program_space for the old and new inferiors, use a value
+	 of nullptr to indicate the breakpoint is in all program
+	 spaces.  */
+      program_space *old_pspace = nullptr;
+      if (old_inferior != -1)
+	{
+	  struct inferior *inf = find_inferior_id (old_inferior);
+	  gdb_assert (inf != nullptr);
+	  old_pspace = inf->pspace;
+	}
+
+      program_space *new_pspace = nullptr;
+      if (inferior != -1)
+	{
+	  struct inferior *inf = find_inferior_id (inferior);
+	  gdb_assert (inf != nullptr);
+	  new_pspace = inf->pspace;
+	}
+
+      if (old_pspace != new_pspace)
+	breakpoint_re_set_one (b, new_pspace);
+
+      notify_breakpoint_modified (b);
+    }
 }
 
 /* See breakpoint.h.  */
@@ -8799,7 +8859,8 @@ create_breakpoints_sal (struct gdbarch *gdbarch,
 
 static void
 parse_breakpoint_sals (location_spec *locspec,
-		       struct linespec_result *canonical)
+		       struct linespec_result *canonical,
+		       struct program_space *search_pspace)
 {
   struct symtab_and_line cursal;
 
@@ -8864,7 +8925,7 @@ parse_breakpoint_sals (location_spec *locspec,
 	      && strchr ("+-", spec[0]) != NULL
 	      && spec[1] != '['))
 	{
-	  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, NULL,
+	  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, search_pspace,
 			    get_last_displayed_symtab (),
 			    get_last_displayed_line (),
 			    canonical, NULL, NULL);
@@ -8872,7 +8933,7 @@ parse_breakpoint_sals (location_spec *locspec,
 	}
     }
 
-  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, NULL,
+  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, search_pspace,
 		    cursal.symtab, cursal.line, canonical, NULL, NULL);
 }
 
@@ -8971,6 +9032,39 @@ breakpoint_ops_for_location_spec_type (enum location_spec_type locspec_type,
     }
 }
 
+/* Return the program space to use as a filter when searching for locations
+   of a breakpoint specific to THREAD or INFERIOR.  If THREAD and INFERIOR
+   are both -1, meaning all threads/inferiors, then this function returns
+   nullptr, indicating no program space filtering should be performed.
+   Otherwise, this function returns the program space for the inferior that
+   contains THREAD (when THREAD is not -1), or the program space for
+   INFERIOR (when INFERIOR is not -1).  */
+
+static struct program_space *
+find_program_space_for_breakpoint (int thread, int inferior)
+{
+  if (thread != -1)
+    {
+      gdb_assert (inferior == -1);
+
+      struct thread_info *thr = find_thread_global_id (thread);
+      gdb_assert (thr != nullptr);
+      gdb_assert (thr->inf != nullptr);
+      return thr->inf->pspace;
+    }
+  else if (inferior != -1)
+    {
+      gdb_assert (thread == -1);
+
+      struct inferior *inf = find_inferior_id (inferior);
+      gdb_assert (inf != nullptr);
+
+      return inf->pspace;
+    }
+
+  return nullptr;
+}
+
 /* See breakpoint.h.  */
 
 const struct breakpoint_ops *
@@ -9072,7 +9166,10 @@ create_breakpoint (struct gdbarch *gdbarch,
 
   try
     {
-      ops->create_sals_from_location_spec (locspec, &canonical);
+      struct program_space *search_pspace
+	= find_program_space_for_breakpoint (thread, inferior);
+      ops->create_sals_from_location_spec (locspec, &canonical,
+					   search_pspace);
     }
   catch (const gdb_exception_error &e)
     {
@@ -9545,7 +9642,7 @@ break_range_command (const char *arg, int from_tty)
   arg_start = arg;
   location_spec_up start_locspec
     = string_to_location_spec (&arg, current_language);
-  parse_breakpoint_sals (start_locspec.get (), &canonical_start);
+  parse_breakpoint_sals (start_locspec.get (), &canonical_start, nullptr);
 
   if (arg[0] != ',')
     error (_("Too few arguments."));
@@ -9646,7 +9743,7 @@ watchpoint_exp_is_const (const struct expression *exp)
 /* Implement the "re_set" method for watchpoints.  */
 
 void
-watchpoint::re_set ()
+watchpoint::re_set (struct program_space *pspace)
 {
   /* Watchpoint can be either on expression using entirely global
      variables, or it can be on local variables.
@@ -11757,7 +11854,7 @@ breakpoint::print_recreate (struct ui_file *fp) const
 /* Default breakpoint_ops methods.  */
 
 void
-code_breakpoint::re_set ()
+code_breakpoint::re_set (struct program_space *pspace)
 {
   /* FIXME: is this still reachable?  */
   if (breakpoint_location_spec_empty_p (this))
@@ -11767,7 +11864,7 @@ code_breakpoint::re_set ()
       return;
     }
 
-  re_set_default ();
+  re_set_default (pspace);
 }
 
 int
@@ -11973,7 +12070,7 @@ code_breakpoint::decode_location_spec (location_spec *locspec,
 /* Virtual table for internal breakpoints.  */
 
 void
-internal_breakpoint::re_set ()
+internal_breakpoint::re_set (struct program_space *pspace)
 {
   switch (type)
     {
@@ -12066,7 +12163,7 @@ internal_breakpoint::print_mention () const
 /* Virtual table for momentary breakpoints  */
 
 void
-momentary_breakpoint::re_set ()
+momentary_breakpoint::re_set (struct program_space *pspace)
 {
   /* Keep temporary breakpoints, which can be encountered when we step
      over a dlopen call and solib_add is resetting the breakpoints.
@@ -12107,12 +12204,13 @@ longjmp_breakpoint::~longjmp_breakpoint ()
 
 static void
 bkpt_probe_create_sals_from_location_spec (location_spec *locspec,
-					   struct linespec_result *canonical)
+					   struct linespec_result *canonical,
+					   struct program_space *search_pspace)
 
 {
   struct linespec_sals lsal;
 
-  lsal.sals = parse_probes (locspec, NULL, canonical);
+  lsal.sals = parse_probes (locspec, search_pspace, canonical);
   lsal.canonical = xstrdup (canonical->locspec->to_string ());
   canonical->lsals.push_back (std::move (lsal));
 }
@@ -12202,9 +12300,9 @@ tracepoint::print_recreate (struct ui_file *fp) const
 }
 
 void
-dprintf_breakpoint::re_set ()
+dprintf_breakpoint::re_set (struct program_space *pspace)
 {
-  re_set_default ();
+  re_set_default (pspace);
 
   /* 1 - connect to target 1, that can run breakpoint commands.
      2 - create a dprintf, which resolves fine.
@@ -12258,8 +12356,10 @@ dprintf_breakpoint::after_condition_true (struct bpstat *bs)
    markers (`-m').  */
 
 static void
-strace_marker_create_sals_from_location_spec (location_spec *locspec,
-					      struct linespec_result *canonical)
+strace_marker_create_sals_from_location_spec
+	(location_spec *locspec,
+	 struct linespec_result *canonical,
+	 struct program_space *search_pspace)
 {
   struct linespec_sals lsal;
   const char *arg_start, *arg;
@@ -12776,12 +12876,32 @@ update_breakpoint_locations (code_breakpoint *b,
      all locations are in the same shared library, that was unloaded.
      We'd like to retain the location, so that when the library is
      loaded again, we don't loose the enabled/disabled status of the
-     individual locations.  */
+     individual locations.
+
+     Thread specific breakpoints will also trigger this case if the thread
+     is changed to a different program space, and all of the old locations
+     go out of scope.  In this case we do (currently) discard the old
+     locations -- we assume the change in thread is permanent and the old
+     locations will never come back into scope.  */
   if (all_locations_are_pending (b, filter_pspace) && sals.empty ())
-    return;
+    {
+      if (b->thread != -1)
+	b->clear_locations ();
+      return;
+    }
 
   bp_location_list existing_locations = b->steal_locations (filter_pspace);
 
+  /* If this is a thread-specific breakpoint then any locations left on the
+     breakpoint are for a program space in which the thread of interest
+     does not operate.  This can happen when the user changes the thread of
+     a thread-specific breakpoint.
+
+     We assume that the change in thread is permanent, and that the old
+     locations will never be used again, so discard them now.  */
+  if (b->thread != -1)
+    b->clear_locations ();
+
   for (const auto &sal : sals)
     {
       struct bp_location *new_loc;
@@ -12947,40 +13067,45 @@ code_breakpoint::location_spec_to_sals (location_spec *locspec,
    locations.  */
 
 void
-code_breakpoint::re_set_default ()
+code_breakpoint::re_set_default (struct program_space *filter_pspace)
 {
-  struct program_space *filter_pspace = current_program_space;
   std::vector<symtab_and_line> expanded, expanded_end;
 
-  int found;
-  std::vector<symtab_and_line> sals = location_spec_to_sals (locspec.get (),
-							     filter_pspace,
-							     &found);
-  if (found)
-    expanded = std::move (sals);
-
-  if (locspec_range_end != nullptr)
-    {
-      std::vector<symtab_and_line> sals_end
-	= location_spec_to_sals (locspec_range_end.get (),
-				 filter_pspace, &found);
+  /* If this breakpoint is thread-specific then find the program space in
+     which the specific thread exists.  Otherwise, for breakpoints that are
+     not thread-specific THREAD_PSPACE will be nullptr.  */
+  program_space *bp_pspace
+    = find_program_space_for_breakpoint (this->thread, this->inferior);
+
+  /* If this is not a thread or inferior specific breakpoint, or it is a
+     thread or inferior specific breakpoint but we are looking for new
+     locations in the program space that the specific thread or inferior is
+     running, then look for new locations for this breakpoint.  */
+  if (bp_pspace == nullptr || filter_pspace == bp_pspace)
+    {
+      int found;
+      std::vector<symtab_and_line> sals
+	= location_spec_to_sals (locspec.get (), filter_pspace, &found);
       if (found)
-	expanded_end = std::move (sals_end);
+	expanded = std::move (sals);
+
+      if (locspec_range_end != nullptr)
+	{
+	  std::vector<symtab_and_line> sals_end
+	    = location_spec_to_sals (locspec_range_end.get (),
+				     filter_pspace, &found);
+	  if (found)
+	    expanded_end = std::move (sals_end);
+	}
     }
 
+  /* Update the locations for this breakpoint.  For thread-specific
+     breakpoints this will remove any old locations that are for the wrong
+     program space -- this can happen if the user changes the thread of a
+     thread-specific breakpoint.  */
   update_breakpoint_locations (this, filter_pspace, expanded, expanded_end);
 }
 
-/* Default method for creating SALs from an address string.  It basically
-   calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
-
-static void
-create_sals_from_location_spec_default (location_spec *locspec,
-					struct linespec_result *canonical)
-{
-  parse_breakpoint_sals (locspec, canonical);
-}
-
 /* Re-set breakpoint locations for the current program space.
    Locations bound to other program spaces are left untouched.  */
 
@@ -13015,7 +13140,7 @@ breakpoint_re_set (void)
 	  {
 	    input_radix = b.input_radix;
 	    set_language (b.language);
-	    b.re_set ();
+	    b.re_set (current_program_space);
 	  }
 	catch (const gdb_exception &ex)
 	  {
@@ -13036,6 +13161,53 @@ breakpoint_re_set (void)
   /* Now we can insert.  */
   update_global_location_list (UGLL_MAY_INSERT);
 }
+
+/* Re-set locations for breakpoint B in FILTER_PSPACE.  If FILTER_PSPACE is
+   nullptr then re-set locations for B in all program spaces.  Locations
+   bound to program spaces other than FILTER_PSPACE are left untouched.  */
+
+static void
+breakpoint_re_set_one (breakpoint *b, program_space *filter_pspace)
+{
+  {
+    scoped_restore_current_language save_language;
+    scoped_restore save_input_radix = make_scoped_restore (&input_radix);
+    scoped_restore_current_pspace_and_thread restore_pspace_thread;
+
+    /* To ::re_set each breakpoint we set the current_language to the
+       language of the breakpoint before re-evaluating the breakpoint's
+       location.  This change can unfortunately get undone by accident if
+       the language_mode is set to auto, and we either switch frames, or
+       more likely in this context, we select the current frame.
+
+       We prevent this by temporarily turning the language_mode to
+       language_mode_manual.  We restore it once all breakpoints
+       have been reset.  */
+    scoped_restore save_language_mode = make_scoped_restore (&language_mode);
+    language_mode = language_mode_manual;
+
+    /* Note: we must not try to insert locations until after all
+       breakpoints have been re-set.  Otherwise, e.g., when re-setting
+       breakpoint 1, we'd insert the locations of breakpoint 2, which
+       hadn't been re-set yet, and thus may have stale locations.  */
+
+    try
+      {
+	input_radix = b->input_radix;
+	set_language (b->language);
+	b->re_set (filter_pspace);
+      }
+    catch (const gdb_exception &ex)
+      {
+	exception_fprintf (gdb_stderr, ex,
+			   "Error in re-setting breakpoint %d: ",
+			   b->number);
+      }
+  }
+
+  /* Now we can insert.  */
+  update_global_location_list (UGLL_MAY_INSERT);
+}
 \f
 /* Reset the thread number of this breakpoint:
 
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index 42b49144e79..dea55deb314 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -570,15 +570,15 @@ enum print_stop_action
 
 struct breakpoint_ops
 {
-  /* Create SALs from location spec, storing the result in
-     linespec_result.
-
-     For an explanation about the arguments, see the function
-     `create_sals_from_location_spec_default'.
+  /* Create SALs from LOCSPEC, storing the result in linespec_result
+     CANONICAL.  If SEARCH_PSPACE is not nullptr then only results in the
+     corresponding program space are returned.  If SEARCH_PSPACE is nullptr
+     then results for all program spaces are returned.
 
      This function is called inside `create_breakpoint'.  */
   void (*create_sals_from_location_spec) (location_spec *locspec,
-					  struct linespec_result *canonical);
+					  linespec_result *canonical,
+					  program_space *search_pspace);
 
   /* This method will be responsible for creating a breakpoint given its SALs.
      Usually, it just calls `create_breakpoints_sal' (for ordinary
@@ -710,8 +710,15 @@ struct breakpoint : public intrusive_list_node<breakpoint>
 
   /* Reevaluate a breakpoint.  This is necessary after symbols change
      (e.g., an executable or DSO was loaded, or the inferior just
-     started).  */
-  virtual void re_set ()
+     started).
+
+     If not nullptr, then FILTER_PSPACE is the program space in which
+     symbols may have changed, we only need to add new locations in
+     FILTER_PSPACE.
+
+     If FILTER_PSPACE is nullptr then all program spaces may have changed,
+     new locations need to be searched for in every program space.  */
+  virtual void re_set (program_space *filter_pspace)
   {
     /* Nothing to re-set.  */
   }
@@ -955,7 +962,7 @@ struct code_breakpoint : public breakpoint
   /* Add a location for SAL to this breakpoint.  */
   bp_location *add_location (const symtab_and_line &sal);
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   int insert_location (struct bp_location *) override;
   int remove_location (struct bp_location *,
 		       enum remove_bp_reason reason) override;
@@ -977,7 +984,7 @@ struct code_breakpoint : public breakpoint
      struct program_space *search_pspace);
 
   /* Helper method that does the basic work of re_set.  */
-  void re_set_default ();
+  void re_set_default (program_space *pspace);
 
   /* Find the SaL locations corresponding to the given LOCATION.
      On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
@@ -999,7 +1006,7 @@ struct watchpoint : public breakpoint
 {
   using breakpoint::breakpoint;
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   int insert_location (struct bp_location *) override;
   int remove_location (struct bp_location *,
 		       enum remove_bp_reason reason) override;
diff --git a/gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp b/gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp
index f736994d234..938e6deec05 100644
--- a/gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp
+++ b/gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp
@@ -76,8 +76,12 @@ foreach_mi_ui_mode mode {
     set loc2 [make_bp_loc "$::decimal\\.2"]
 
     # Create the inferior-specific breakpoint.
-    mi_create_breakpoint_multi "-g i2 foo" "create breakpoint in inferior 2" \
-	-inferior "2" -locations "\\\[$loc1,$loc2\\\]"
+    mi_create_breakpoint "-g i2 foo" "create breakpoint in inferior 2" \
+	-number "$decimal" \
+	-type "breakpoint" \
+	-enabled "y" \
+	-func "foo" \
+	-inferior "2"
     set bpnum [mi_get_valueof "/d" "\$bpnum" "INVALID"]
 
     if {$mode eq "separate"} {
diff --git a/gdb/testsuite/gdb.mi/user-selected-context-sync.exp b/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
index 93b91b42f92..e168a5eee45 100644
--- a/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
+++ b/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
@@ -364,15 +364,9 @@ proc test_continue_to_start { mode inf } {
 
 		# Consume MI output.
 		with_spawn_id $mi_spawn_id {
-		    if { $inf == 1} {
-			mi_expect_stop "breakpoint-hit" "child_sub_function" \
-			    "" "$srcfile" "$decimal" {"" "disp=\"del\""} \
-			    "thread $inf.2 stops MI"
-		    } else {
-			mi_expect_stop "breakpoint-hit" "child_sub_function" \
-			    "" "$srcfile" "$decimal" {"" "disp=\"del\"" "locno=\"[0-9]+\""} \
-			    "thread $inf.2 stops MI"
-		    }
+		    mi_expect_stop "breakpoint-hit" "child_sub_function" \
+			"" "$srcfile" "$decimal" {"" "disp=\"del\""} \
+			"thread $inf.2 stops MI"
 		}
 	    }
 	}
@@ -439,7 +433,7 @@ proc_with_prefix test_setup { mode } {
 
 	with_spawn_id $mi_spawn_id {
 	    mi_expect_stop "breakpoint-hit" "main" "" "$srcfile" "$decimal" \
-		{"" "disp=\"del\"" "locno=\"[0-9]+\""} "main stop"
+		{"" "disp=\"del\""} "main stop"
 	}
 
 	# Consume CLI output.
diff --git a/gdb/testsuite/gdb.multi/bp-thread-specific.exp b/gdb/testsuite/gdb.multi/bp-thread-specific.exp
index 7635e84b913..c1d87521ee9 100644
--- a/gdb/testsuite/gdb.multi/bp-thread-specific.exp
+++ b/gdb/testsuite/gdb.multi/bp-thread-specific.exp
@@ -50,7 +50,7 @@ gdb_test "info threads" \
 # locations ('foo' in both inferiors) even though only one of those
 # locations will ever trigger ('foo' in inferior 2).
 gdb_test "break foo thread 2.1" \
-    "Breakpoint $decimal at $hex: foo\\. \\(2 locations\\)"
+    "Breakpoint $decimal at $hex: file \[^\r\n\]+$srcfile, line $decimal\\."
 
 set bpnum [get_integer_valueof "\$bpnum" "INVALID"]
 
@@ -58,10 +58,7 @@ set bpnum [get_integer_valueof "\$bpnum" "INVALID"]
 # earlier breakpoint.  Check that the thread-id used when describing
 # the earlier breakpoints is correct.
 gdb_test "break foo thread 1.1" \
-    [multi_line \
-	 "Note: breakpoint $bpnum \\(thread 2.1\\) also set at pc $hex\\." \
-	 "Note: breakpoint $bpnum \\(thread 2.1\\) also set at pc $hex\\." \
-	 "Breakpoint $decimal at $hex: foo\\. \\(2 locations\\)"]
+    "Breakpoint $decimal at $hex: file \[^\r\n\]+$srcfile, line $decimal\\."
 
 # Save the breakpoints into a file.
 if {[is_remote host]} {
diff --git a/gdb/testsuite/gdb.multi/inferior-specific-bp.exp b/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
index 46efe6f54bc..52f84183589 100644
--- a/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
+++ b/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
@@ -105,16 +105,8 @@ proc check_info_breakpoints { testname bp_number expected_loc_count } {
 # Create an inferior-specific breakpoint.  Use gdb_test instead of
 # gdb_breakpoint here as we want to check the breakpoint was placed in
 # multiple locations.
-#
-# Currently GDB still places inferior specific breakpoints into every
-# inferior, just like it does with thread specific breakpoints.
-# Hopefully this will change in the future, at which point, this test
-# will need updating.
-#
-# Two of these locations are in inferior 1, while the third is in
-# inferior 2.
 gdb_test "break foo inferior 1" \
-    "Breakpoint $decimal at $hex: foo\\. \\(3 locations\\)"
+    "Breakpoint $decimal at $hex: foo\\. \\(2 locations\\)"
 set bp_number [get_integer_valueof "\$bpnum" "INVALID" \
 		  "get b/p number for inferior specific breakpoint"]
 
@@ -123,7 +115,7 @@ set location_count 0
 set saw_inf_cond false
 
 check_info_breakpoints "first check for inferior specific breakpoint" \
-    $bp_number 3
+    $bp_number 2
 
 # Create a multi-inferior breakpoint to stop at.
 gdb_breakpoint "stop_breakpt" message
diff --git a/gdb/testsuite/gdb.multi/multi-target-continue.exp b/gdb/testsuite/gdb.multi/multi-target-continue.exp
index d2201061713..d4b2fc28133 100644
--- a/gdb/testsuite/gdb.multi/multi-target-continue.exp
+++ b/gdb/testsuite/gdb.multi/multi-target-continue.exp
@@ -30,7 +30,7 @@ proc test_continue {non-stop} {
 
     proc set_break {inf} {
 	gdb_test "break function${inf} thread ${inf}.1" \
-	"Breakpoint .* function${inf}\\..*"
+	    "Breakpoint ${::decimal} at ${::hex}: file .*, line ${::decimal}\\."
     }
 
     # Select inferior INF, and then run to a breakpoint on inferior
diff --git a/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp b/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp
index 0aff708c0f3..36f9d24a917 100644
--- a/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp
+++ b/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp
@@ -52,12 +52,12 @@ proc test_ping_pong_next {} {
     gdb_test "thread 1.1" "Switching to thread 1.1 .*"
 
     gdb_test "break $srcfile:$line1 thread 1.1" \
-	"Breakpoint .*$srcfile:$line1\\..*"
+	"Breakpoint .*$srcfile, line $line1\\."
 
     gdb_test "continue" "hit Breakpoint .*"
 
     gdb_test "break $srcfile:$line2 thread 2.1" \
-	"Breakpoint .*$srcfile:$line2\\..*"
+	"Breakpoint .*$srcfile, line $line2\\."
 
     # Now block inferior 1 and issue "next".  We should stop at the
     # breakpoint for inferior 2, given schedlock off.
diff --git a/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
index 5fcd1ef2e39..12c0a84bb02 100644
--- a/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
+++ b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
@@ -129,10 +129,8 @@ proc do_bp_test { bp_type bp_pending } {
     } else {
 	set bp_pattern_before \
 	    [multi_line \
-		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+<MULTIPLE>\\s*" \
-		 "\\s+stop only in [string_to_regexp $bp_restriction]" \
-		 "$bp_number\\.1\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 1" \
-		 "$bp_number\\.2\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 2"]
+		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 1" \
+		 "\\s+stop only in [string_to_regexp $bp_restriction]"]
 
 	set bp_pattern_after \
 	    [multi_line \
diff --git a/gdb/testsuite/gdb.multi/pending-bp.exp b/gdb/testsuite/gdb.multi/pending-bp.exp
index 478d8d7c037..aeb8c2c886e 100644
--- a/gdb/testsuite/gdb.multi/pending-bp.exp
+++ b/gdb/testsuite/gdb.multi/pending-bp.exp
@@ -72,6 +72,48 @@ proc do_test_setup { inf_1_stop inf_2_stop } {
     return true
 }
 
+# Create a breakpoint on the function 'foo' in THREAD.  It is expected
+# that the breakpoint created will be pending, this is checked by
+# running the 'info breakpoints' command.
+#
+# Returns the number for the newly created breakpoint.
+proc do_create_pending_foo_breakpoint { {thread "1.1"} } {
+    gdb_test "break foo thread $thread" \
+	[multi_line \
+	     "Function \"foo\" not defined\\." \
+	     "Breakpoint $::decimal \\(foo\\) pending\."] \
+	"set pending thread-specific breakpoint"
+    set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+		   "get number for thread-specific breakpoint on foo"]
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	     "\\s+stop only in thread [string_to_regexp $thread]"] \
+	"check thread-specific breakpoint is initially pending"
+
+    return $bpnum
+}
+
+# Create a breakpoint on the function 'foo' in THREAD.  It is expected
+# that the breakpoint created will not be pending, this is checked by
+# running the 'info breakpoints' command.
+#
+# Returns the number for the newly created breakpoint.
+proc do_create_foo_breakpoint { {thread "1.1"} } {
+    gdb_test "break foo thread $thread" \
+	"Breakpoint $::decimal at $::hex" \
+	"set thread-specific breakpoint"
+    set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+		   "get number for thread-specific breakpoint on foo"]
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex\\s+<foo\[^>\]*> inf $::decimal" \
+	     "\\s+stop only in thread [string_to_regexp $thread]"] \
+	"check thread-specific breakpoint is initially pending"
+
+    return $bpnum
+}
+
 # Check that when a breakpoint is in the pending state, but that breakpoint
 # does have some locations (those locations themselves are pending), GDB
 # doesn't display the inferior list in the 'info breakpoints' output.
@@ -122,5 +164,169 @@ proc_with_prefix test_no_inf_display {} {
 	"check info breakpoints while breakpoint is pending"
 }
 
+# Setup two inferiors.  In #1 the symbol 'foo' has not yet been
+# loaded, while in #2 the symbol 'foo' has been loaded.
+#
+# Create a thread-specific breakpoint on 'foo' tied to a thread in
+# inferior #1, the breakpoint should be pending -- 'foo' is not yet
+# loaded in #1.
+#
+# Now move inferior #1 forward until 'foo' is loaded, check the
+# breakpoint is no longer pending.
+#
+# Move inferior #1 forward more until 'foo' is unloaded, check that
+# the breakpoint returns to the pending state.
+proc_with_prefix test_pending_toggle { } {
+
+    do_test_setup "Break before open" "Break before close"
+
+    set bpnum [do_create_pending_foo_breakpoint]
+
+    # Now return to inferior 1 and continue until the shared library is
+    # loaded, the breakpoint should become non-pending.
+    gdb_test "inferior 1" "Switching to inferior 1 .*" \
+	"switch back to inferior 1"
+    gdb_continue_to_breakpoint "stop in foo in inferior 1" "foo \\(\\) .*"
+
+    gdb_test "info breakpoint $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex <foo\[^>\]*> inf 1" \
+	     "\\s+stop only in thread 1\\.1" \
+	     "\\s+breakpoint already hit 1 time"] \
+	"check thread-specific breakpoint is no longer pending"
+
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "close library"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	     "\\s+stop only in thread 1\\.1" \
+	     "\\s+breakpoint already hit 1 time"] \
+	"check thread-specific breakpoint is pending again"
+}
+
+# Create a Python variable VAR and set it to the gdb.Breakpoint object
+# corresponding to the breakpoint numbered BPNUM.  If THREAD is not
+# the empty string then THREAD should be an integer, check that
+# gdb.Breakpoint.thread is set to the value of THREAD.  Otherwise, if
+# THREAD is the empty string, check that gdb.Breakpoint.thread is set
+# to None.
+proc py_find_breakpoint { var bpnum {thread ""} } {
+    gdb_test_no_output \
+	"python ${var}=\[b for b in gdb.breakpoints() if b.number == $bpnum\]\[0\]" \
+	"find Python gdb.Breakpoint object"
+    if { $thread ne "" } {
+	gdb_test_no_output "python assert(${var}.thread == ${thread})" \
+	    "check thread attribute is currently correct"
+    } else {
+	gdb_test_no_output "python assert(${var}.thread is None)" \
+	    "check thread attribute is currently correct"
+    }
+}
+
+# Setup two inferiors.  In #1 the symbol 'foo' has not yet been
+# loaded, while in #2 the symbol 'foo' has been loaded.
+#
+# Create a thread-specific breakpoint on 'foo' tied to a thread in
+# inferior #1, the breakpoint should be pending -- 'foo' is not yet
+# loaded in #1.
+#
+# Use Python to change the thread of the thread-specific breakpoint to
+# a thread in inferior #2, at this point the thread should gain a
+# location and become non-pending.
+#
+# Set the thread back to a thread in inferior #1, the breakpoint
+# should return to the pending state.
+proc_with_prefix py_test_toggle_thread {} {
+    do_test_setup "Break before open" "Break after open"
+
+    set bpnum [do_create_pending_foo_breakpoint]
+
+    py_find_breakpoint "bp" $bpnum 1
+
+    gdb_test_no_output "python bp.thread = 2" \
+	"change thread on thread-specific breakpoint"
+    gdb_test "info breakpoint $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex <foo\[^>\]*> inf 2" \
+	     "\\s+stop only in thread 2\\.1"] \
+	"check thread-specific breakpoint now has a location"
+
+    gdb_test_no_output "set call_count = 2" "set call_count in inferior 2"
+    gdb_continue_to_breakpoint "stop at foo in inferior 2" "foo \\(\\) .*"
+
+    gdb_test_no_output "python bp.thread = 1" \
+	"restore thread on thread-specific breakpoint"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	     "\\s+stop only in thread 1\\.1" \
+	     "\\s+breakpoint already hit 1 time"] \
+	"check thread-specific breakpoint has returned to pending"
+
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "stop after close in inferior 2" \
+	".* Break after close\\. .*"
+
+    gdb_test "inferior 1" "Switching to inferior 1 .*" \
+	"switch to inferior 1"
+    gdb_continue_to_breakpoint "stop at foo in inferior 1" "foo \\(\\) .*"
+}
+
+# Setup two inferiors.  Both inferiors have the symbol 'foo'
+# available.
+#
+# Create a thread-specific breakpoint on 'foo' tied to a thread in
+# inferior #1, the breakpoint should not be pending, but will only
+# have a single location, the location in inferior #1.
+#
+# Use Python to change the thread of the thread-specific breakpoint to
+# None.  At this point the breakpoint should gain a second location, a
+# location in inferior #2.
+proc_with_prefix py_test_clear_thread {} {
+    do_test_setup "Break after open" "Break after open"
+
+    set bpnum [do_create_foo_breakpoint]
+
+    py_find_breakpoint "bp" $bpnum 1
+
+    gdb_test_no_output "python bp.thread = None" \
+	"clear thread on thread-specific breakpoint"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "${bpnum}\\s+breakpoint\\s+keep y\\s+<MULTIPLE>\\s*" \
+	     "${bpnum}\\.1\\s+y\\s+${::hex}\\s+<foo\[^>\]*> inf $::decimal" \
+	     "${bpnum}\\.2\\s+y\\s+${::hex}\\s+<foo\[^>\]*> inf $::decimal"] \
+	"check for a location in both inferiors"
+
+    gdb_continue_to_breakpoint "stop at foo in inferior 2" "foo \\(\\) .*"
+    gdb_test_no_output "set call_count = 2" "set call_count in inferior 2"
+
+    gdb_test "inferior 1" "Switching to inferior 1 .*" \
+	"switch to inferior 1"
+    gdb_continue_to_breakpoint "stop at foo in inferior 1" "foo \\(\\) .*"
+    gdb_test_no_output "set call_count = 2" "set call_count in inferior 1"
+
+    gdb_test_no_output "python bp.thread = 2"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "${bpnum}\\s+breakpoint\\s+keep y\\s+${::hex}\\s+<foo\[^>\]*> inf 2" \
+	     "\\s+stop only in thread 2\\.1" \
+	     "\\s+breakpoint already hit 2 times"] \
+	"check for a location only in inferior 2"
+
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "stop after close in inferior 1" \
+	".* Break after close\\. .*"
+
+    gdb_test "inferior 2" "Switching to inferior 2 .*" \
+	"switch back to inferior 2"
+    gdb_continue_to_breakpoint "stop at foo again in inferior 2" \
+	"foo \\(\\) .*"
+}
+
 # Run all the tests.
 test_no_inf_display
+test_pending_toggle
+py_test_toggle_thread
+py_test_clear_thread
diff --git a/gdb/testsuite/gdb.multi/tids.exp b/gdb/testsuite/gdb.multi/tids.exp
index 573b02fdd42..4f788844ee4 100644
--- a/gdb/testsuite/gdb.multi/tids.exp
+++ b/gdb/testsuite/gdb.multi/tids.exp
@@ -433,11 +433,13 @@ if { [allow_python_tests] } {
 
 	gdb_py_test_silent_cmd "python bp = gdb.breakpoints()\[0\]" \
 	    "get python breakpoint" 0
-	gdb_test "python bp.thread = 6" "thread = 6" \
+	gdb_test_no_output "python bp.thread = 6" \
 	    "make breakpoint thread-specific with python"
 	# Check that the inferior-qualified ID is correct.
 	gdb_test "info breakpoint" \
-	    "stop only in thread 1.3\r\n.*" \
+	    [multi_line \
+		 "$decimal\\s+\[^\r\n\]+ in thread_function1 at \[^\r\n\]+" \
+		 "\\s+stop only in thread 1\\.3"] \
 	    "thread specific breakpoint right thread"
     }
 }


^ permalink raw reply	[flat|nested] 138+ messages in thread

* Re: [PATCHv9 01/14] gdb: create_breakpoint: add asserts and additional comments
  2024-03-05 15:21                 ` [PATCHv9 01/14] gdb: create_breakpoint: add asserts and additional comments Andrew Burgess
@ 2024-03-31 10:26                   ` Andrew Burgess
  0 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2024-03-31 10:26 UTC (permalink / raw)
  To: gdb-patches

Andrew Burgess <aburgess@redhat.com> writes:

> This commit extends the asserts on create_breakpoint (in the header
> file), and adds some additional assertions into the definition.
>
> The new assert confirms that when the thread and inferior information
> is going to be parsed from the extra_string, then the thread and
> inferior arguments should be -1.  That is, the caller of
> create_breakpoint should not try to create a thread/inferior specific
> breakpoint by *both* specifying thread/inferior *and* asking to parse
> the extra_string, it's one or the other.
>
> There should be no user visible changes after this commit.

I've gone ahead and committed this patch.

Thanks,
Andrew



> ---
>  gdb/breakpoint.c |  6 ++++++
>  gdb/breakpoint.h | 16 ++++++++++++++++
>  2 files changed, 22 insertions(+)
>
> diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
> index 102bd7fad41..7ade82663f9 100644
> --- a/gdb/breakpoint.c
> +++ b/gdb/breakpoint.c
> @@ -9219,6 +9219,12 @@ create_breakpoint (struct gdbarch *gdbarch,
>    gdb_assert (inferior == -1 || inferior > 0);
>    gdb_assert (thread == -1 || inferior == -1);
>  
> +  /* If PARSE_EXTRA is true then the thread and inferior details will be
> +     parsed from the EXTRA_STRING, the THREAD and INFERIOR arguments
> +     should be -1.  */
> +  gdb_assert (!parse_extra || thread == -1);
> +  gdb_assert (!parse_extra || inferior == -1);
> +
>    gdb_assert (ops != NULL);
>  
>    /* If extra_string isn't useful, set it to NULL.  */
> diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
> index 226e4d06993..2e2fe1d32e5 100644
> --- a/gdb/breakpoint.h
> +++ b/gdb/breakpoint.h
> @@ -1610,6 +1610,22 @@ enum breakpoint_create_flags
>     the FORCE_CONDITION parameter is ignored and the corresponding argument
>     is parsed from EXTRA_STRING.
>  
> +   The THREAD should be a global thread number, the created breakpoint will
> +   only apply for that thread.  If the breakpoint should apply for all
> +   threads then pass -1.  However, if PARSE_EXTRA is non-zero then the
> +   THREAD parameter is ignored and an optional thread number will be parsed
> +   from EXTRA_STRING.
> +
> +   The INFERIOR should be a global inferior number, the created breakpoint
> +   will only apply for that inferior.  If the breakpoint should apply for
> +   all inferiors then pass -1.  However, if PARSE_EXTRA is non-zero then
> +   the INFERIOR parameter is ignored and an optional inferior number will
> +   be parsed from EXTRA_STRING.
> +
> +   At most one of THREAD and INFERIOR should be set to a value other than
> +   -1; breakpoints can be thread specific, or inferior specific, but not
> +   both.
> +
>     If INTERNAL is non-zero, the breakpoint number will be allocated
>     from the internal breakpoint count.
>  
> -- 
> 2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* Re: [PATCHv9 02/14] gdb: create_breakpoint: asserts relating to extra_string/parse_extra
  2024-03-05 15:21                 ` [PATCHv9 02/14] gdb: create_breakpoint: asserts relating to extra_string/parse_extra Andrew Burgess
@ 2024-03-31 10:26                   ` Andrew Burgess
  0 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2024-03-31 10:26 UTC (permalink / raw)
  To: gdb-patches

Andrew Burgess <aburgess@redhat.com> writes:

> The goal of this commit is to better define the API for
> create_breakpoint especially around the use of extra_string and
> parse_extra.  This will be useful in the next commit when I plan to
> make some changes to create_breakpoint.
>
> This commit makes one possibly breaking change: until this commit it
> was possible to create thread-specific dprintf breakpoint like this:
>
>   (gdb) dprintf call_me, thread 1 "%s", "hello"
>   Dprintf 2 at 0x401152: file /tmp/hello.c, line 8.
>   (gdb) info breakpoints
>   Num     Type           Disp Enb Address            What
>   2       dprintf        keep y   0x0000000000401152 in call_me at /tmp/hello.c:8 thread 1
>           stop only in thread 1
>           printf "%s", "hello"
>   (gdb)
>
> This feature of dprintf was not documented, was not tested, and is
> slightly different in syntax to how we create thread specific
> breakpoints and/or watchpoints -- the thread condition appears after
> the first ','.
>
> I believe that this worked at all was simply by luck.  We happen to
> pass the parse_extra flag as true from dprintf_command to
> create_breakpoint.
>
> So in this commit I made the choice change this.  We now pass
> parse_extra as false from dprintf_command to create_breakpoint.  With
> this done it is assumed that the only thing in the extra_string is the
> dprintf format and arguments.
>
> Beyond this change I've updated the comment on create_breakpoint in
> breakpoint.h, and I've then added some asserts into
> create_breakpoint as well as moving around some of the error
> handling.
>
>  - We now assert on the incoming argument values,
>
>  - I've moved an error check to sit after the call to
>    find_condition_and_thread_for_sals, this ensures the extra_string
>    was parsed correctly,
>
> In dprintf_command:
>
>  - We now throw an error if there is no format string after the
>    dprintf location.  This error was already being thrown, but was
>    being caught later in the process.  With this change we catch the
>    missing string earlier,
>
>  - And, as mentioned earlier, we pass parse_extra as false when
>    calling create_breakpoint,
>
> In create_tracepoint_from_upload:
>
>  - We now throw an error if the parsed location doesn't completely
>    consume the addr_str variable.  This error has now effectively
>    moved out of create_breakpoint.

I've gone ahead and committed this patch.

Thanks,
Andrew


^ permalink raw reply	[flat|nested] 138+ messages in thread

* Re: [PATCHv9 03/14] gdb: change 'if' to gdb_assert in update_dprintf_command_list
  2024-03-05 15:21                 ` [PATCHv9 03/14] gdb: change 'if' to gdb_assert in update_dprintf_command_list Andrew Burgess
@ 2024-03-31 10:27                   ` Andrew Burgess
  0 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2024-03-31 10:27 UTC (permalink / raw)
  To: gdb-patches

Andrew Burgess <aburgess@redhat.com> writes:

> I noticed in update_dprintf_command_list that we handle the case where
> the bp_dprintf style breakpoint doesn't have a format and args string.
>
> However, I don't believe such a situation is possible.  The obvious
> approach certainly already catches this case:
>
>   (gdb) dprintf main
>   Format string required
>
> If it is possible to create a dprintf breakpoint without a format and
> args string then I think we should be catching this case and handling
> it at creation time, rather than having GDB just ignore the situation
> later on.
>
> And so, I propose that we change the 'if' that ignores the case where
> the format/args string is empty, and instead assert that we do always
> have a format/args string.  The original code, that handled an empty
> format/args string has existed since commit e7e0cddfb0d4, which is
> when dprintf support was added to GDB.
>
> If I'm correct and this situation can't ever happen then there should
> be no user visible changes after this commit.

I've gone ahead and committed this patch.

Thanks,
Andrew


^ permalink raw reply	[flat|nested] 138+ messages in thread

* Re: [PATCHv9 04/14] gdb: the extra_string in a dprintf breakpoint is never nullptr
  2024-03-05 15:21                 ` [PATCHv9 04/14] gdb: the extra_string in a dprintf breakpoint is never nullptr Andrew Burgess
@ 2024-03-31 10:27                   ` Andrew Burgess
  0 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2024-03-31 10:27 UTC (permalink / raw)
  To: gdb-patches

Andrew Burgess <aburgess@redhat.com> writes:

> Given the changes in the previous couple of commits, this commit
> cleans up some of the asserts and 'if' checks related to the
> extra_string within a dprintf breakpoint.
>
> This commit:
>
>   1. Adds some asserts to update_dprintf_command_list about the
>   breakpoint type, and that the extra_string is not nullptr,
>
>   2. Given that we know extra_string is not nullptr (this is enforced
>   when the breakpoint is created), we can simplify
>   code_breakpoint::code_breakpoint -- it no longer needs to check for
>   the extra_string is nullptr case,
>
>   3. In dprintf_breakpoint::re_set we can remove the assert (this will
>   be checked within update_dprintf_command_list, we can also remove
>   the redundant 'if' check.
>
> There should be no user visible changes after this commit.

I've gone ahead and committed this patch.

Thanks,
Andrew


^ permalink raw reply	[flat|nested] 138+ messages in thread

* Re: [PATCHv9 05/14] gdb: build dprintf commands just once in code_breakpoint constructor
  2024-03-05 15:21                 ` [PATCHv9 05/14] gdb: build dprintf commands just once in code_breakpoint constructor Andrew Burgess
@ 2024-03-31 10:27                   ` Andrew Burgess
  0 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2024-03-31 10:27 UTC (permalink / raw)
  To: gdb-patches

Andrew Burgess <aburgess@redhat.com> writes:

> I noticed in code_breakpoint::code_breakpoint that we are calling
> update_dprintf_command_list once for each breakpoint location, when we
> really only need to call this once per breakpoint -- the data updated
> by this function, the breakpoint command list -- is per breakpoint,
> not per breakpoint location.  Calling update_dprintf_command_list
> multiple times is just wasted effort, there's no per location error
> checking, we don't even pass the current location to the function.
>
> This commit moves the update_dprintf_command_list call outside of the
> per-location loop.
>
> There should be no user visible changes after this commit.

I've gone ahead and committed this patch.

Thanks,
Andrew


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv10 0/9] thread-specific breakpoints in just some inferiors
  2024-03-05 15:21               ` [PATCHv9 00/14] thread-specific breakpoints in just some inferiors Andrew Burgess
                                   ` (13 preceding siblings ...)
  2024-03-05 15:21                 ` [PATCHv9 14/14] gdb: only insert thread-specific breakpoints in the relevant inferior Andrew Burgess
@ 2024-03-31 10:31                 ` Andrew Burgess
  2024-03-31 10:31                   ` [PATCHv10 1/9] gdb: don't display inferior list for pending breakpoints Andrew Burgess
                                     ` (8 more replies)
  14 siblings, 9 replies; 138+ messages in thread
From: Andrew Burgess @ 2024-03-31 10:31 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

In v10:

  - I merged the first 5 patches.  These were mostly just adding extra
    asserts, or minor refactoring and cleanup that didn't change GDB's
    behaviour.  Patch #2 did have a minor behaviour change, but this
    was just removing some (I think) unintended behaviour,

  - Rebased onto current upstream/master branch,

  - No other changes since v9.

In v9:

  - Rebased onto current upstream/master branch,

  - Minor testsuite fix to account for updated output from GDB,

  - No other changes since v8.

In v8:

  - Rebased onto current upstream/master branch.

  - Reordered the patches a little.  Patches 0 to 8 are unchanged from
    previous.  If there's no objections then I'm planning to merge
    these some point soon as I think these are all good cleanup patches.

  - Patches 9, 10, and 11 are new.  These are also refactoring
    commits, but are all tied pretty tightly to what is now patch 12.

  - Patch 12 is the most important patch.  This has had a complete
    rewrite since V7 in order to address Tom's feedback.  The general
    idea is unchanged; the breakpoint condition string is parsed first
    forwards, and then backwards, but we now have a two phase
    analysis, rather than immediately parsing things like the
    thread-id as we find them.  This resolves this problem:

    (gdb) break some_function if ( 3 == thread )

    Previous GDB would try to match 'thread )' as a thread-id and give
    an error that ')' as invalid.  Now GDB correctly understands that
    the 'thread )' is likely part of the 'if' condition, and parses it
    as such.

  - Patches 13 and 14 are unchanged from V7.  These patches depend on
    the changes in patch 12 so can't be merged without that patch.

In v7:

  - Addressed all the issues except one that Baris pointed out, this
    includes typos, some minor testsuite cleanups, and reformatting an
    assert (but not changing the meaning).

  - As requested, switched to use std::string_view in
    break-parse-cond.c file instead of a custom class, I agree that
    this is an improvement.

  - I've not changed the handling of -force-condition flag.  I replied
    to the review email with my thoughts, TLDR: fixing this would be a
    bigger task which I'd rather leave for ... the future.

  - Rebased and retested.

In v6:

  - Rebased to current master, one minor fix due to the C++17 changes,
    nothing major.  Retested.

In v5:

  - Updates after Lancelot's feedback, including, -force-condition can
    no longer be abbreviated to '-', and can't be used immediately
    after the breakpoint condition.

  - More tests to check some of the edge cases.

In v4:

  - Big update, this series now handles thread-specific and
    inferior-specific breakpoints.

In v3:

  - Rebased on to current upstream/master, this includes all Simon's
    recent breakpoint changes.  Retested with no regressions seen.

In v2:

  - Rebased on current upstream/master and retested,

  - No changes to code or docs.

---

Andrew Burgess (9):
  gdb: don't display inferior list for pending breakpoints
  gdb: remove breakpoint_re_set_one
  gdb: remove tracepoint_probe_create_sals_from_location_spec
  gdb: make breakpoint_debug_printf global
  gdb: add another overload of startswith
  gdb: create new is_thread_id helper function
  gdb: parse pending breakpoint thread/task immediately
  gdb: don't set breakpoint::pspace in create_breakpoint
  gdb: only insert thread-specific breakpoints in the relevant inferior

 gdb/Makefile.in                               |   2 +
 gdb/NEWS                                      |  11 +
 gdb/ada-lang.c                                |   6 +-
 gdb/break-catch-throw.c                       |   6 +-
 gdb/break-cond-parse.c                        | 701 +++++++++++++++++
 gdb/break-cond-parse.h                        |  52 ++
 gdb/breakpoint.c                              | 709 ++++++++----------
 gdb/breakpoint.h                              |  55 +-
 gdb/testsuite/gdb.ada/tasks.exp               |   6 +-
 gdb/testsuite/gdb.base/condbreak.exp          |  57 +-
 gdb/testsuite/gdb.base/pending.exp            |  23 +-
 gdb/testsuite/gdb.linespec/explicit.exp       |   4 +-
 gdb/testsuite/gdb.linespec/keywords.exp       |   8 +-
 gdb/testsuite/gdb.mi/mi-dprintf-pending.exp   |   3 +-
 gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp    |   8 +-
 .../gdb.mi/user-selected-context-sync.exp     |  14 +-
 .../gdb.multi/bp-thread-specific.exp          |   7 +-
 .../gdb.multi/inferior-specific-bp.exp        |  16 +-
 .../gdb.multi/multi-target-continue.exp       |   2 +-
 .../gdb.multi/multi-target-ping-pong-next.exp |   4 +-
 .../gdb.multi/pending-bp-del-inferior.c       |  28 +
 .../gdb.multi/pending-bp-del-inferior.exp     | 214 ++++++
 gdb/testsuite/gdb.multi/pending-bp-lib.c      |  22 +
 gdb/testsuite/gdb.multi/pending-bp.c          |  66 ++
 gdb/testsuite/gdb.multi/pending-bp.exp        | 332 ++++++++
 gdb/testsuite/gdb.multi/tids.exp              |   6 +-
 .../gdb.threads/del-pending-thread-bp-lib.c   |  22 +
 .../gdb.threads/del-pending-thread-bp.c       |  85 +++
 .../gdb.threads/del-pending-thread-bp.exp     | 108 +++
 gdb/tid-parse.c                               |  82 +-
 gdb/tid-parse.h                               |   8 +
 gdbsupport/common-utils.h                     |  10 +
 32 files changed, 2201 insertions(+), 476 deletions(-)
 create mode 100644 gdb/break-cond-parse.c
 create mode 100644 gdb/break-cond-parse.h
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-del-inferior.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.exp
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.exp


base-commit: 8b4141cdb03e48826e2935529be7fd7499f9d815
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv10 1/9] gdb: don't display inferior list for pending breakpoints
  2024-03-31 10:31                 ` [PATCHv10 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
@ 2024-03-31 10:31                   ` Andrew Burgess
  2024-03-31 10:31                   ` [PATCHv10 2/9] gdb: remove breakpoint_re_set_one Andrew Burgess
                                     ` (7 subsequent siblings)
  8 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2024-03-31 10:31 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

I noticed that in the 'info breakpoints' output, GDB sometimes prints
the inferior list for pending breakpoints, this doesn't seem right to
me.  A pending breakpoint has no locations (at least, as far as we
display things in the 'info breakpoints' output), so including an
inferior list seems odd.

Here's what I see right now:

  (gdb) info breakpoint 5
  Num     Type           Disp Enb Address            What
  5       breakpoint     keep y   <PENDING>          foo inf 1
  (gdb)

It's the 'inf 1' at the end of the line that I'm objecting too.

To trigger this behaviour we need to be in a multi-inferior debug
session.  The breakpoint must have been non-pending at some point in
the past, and so have a location assigned to it.

The breakpoint becomes pending again as a result of a shared library
being unloaded.  When this happens the location itself is marked
pending (via bp_location::shlib_disabled).

In print_one_breakpoint_location, in order to print the inferior list
we check that the breakpoint has a location, and that we have multiple
inferiors, but we don't check if the location itself is pending.

This commit adds that check, which means the output is now:

  (gdb) info breakpoint 5
  Num     Type           Disp Enb Address            What
  5       breakpoint     keep y   <PENDING>          foo
  (gdb)

Which I think makes more sense -- indeed, the format without the
inferior list is what we display for a pending breakpoint that has
never had any locations assigned, so I think this change in behaviour
makes GDB more consistent.
---
 gdb/breakpoint.c                         |   2 +-
 gdb/testsuite/gdb.multi/pending-bp-lib.c |  22 ++++
 gdb/testsuite/gdb.multi/pending-bp.c     |  66 ++++++++++++
 gdb/testsuite/gdb.multi/pending-bp.exp   | 126 +++++++++++++++++++++++
 4 files changed, 215 insertions(+), 1 deletion(-)
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp.exp

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index ea89c40ce26..fef7f9a82a4 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -6588,7 +6588,7 @@ print_one_breakpoint_location (struct breakpoint *b,
 	}
     }
 
-  if (loc != NULL && !header_of_multiple)
+  if (loc != nullptr && !header_of_multiple && !loc->shlib_disabled)
     {
       std::vector<int> inf_nums;
       int mi_only = 1;
diff --git a/gdb/testsuite/gdb.multi/pending-bp-lib.c b/gdb/testsuite/gdb.multi/pending-bp-lib.c
new file mode 100644
index 00000000000..15d1b9833dd
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp-lib.c
@@ -0,0 +1,22 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+int global_var = 0;
+
+void
+foo (int arg)
+{
+  global_var = arg;
+}
diff --git a/gdb/testsuite/gdb.multi/pending-bp.c b/gdb/testsuite/gdb.multi/pending-bp.c
new file mode 100644
index 00000000000..879e0b11ac7
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp.c
@@ -0,0 +1,66 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#include <dlfcn.h>
+#include <stdlib.h>
+
+void
+breakpt (void)
+{
+  /* Nothing.  */
+}
+
+volatile int global_counter = 0;
+
+volatile int call_count = 1;
+
+int
+main (void)
+{
+  void *handle;
+  void (*func)(int);
+
+  /* Some filler work so that we don't initially stop on the breakpt call
+     below.  */
+  ++global_counter;
+
+  breakpt ();	/* Break before open.  */
+
+  /* Now load the shared library.  */
+  handle = dlopen (SHLIB_NAME, RTLD_LAZY);
+  if (handle == NULL)
+    abort ();
+
+  breakpt ();	/* Break after open.  */
+
+  /* Find the function symbol.  */
+  func = (void (*)(int)) dlsym (handle, "foo");
+
+  for (; call_count > 0; --call_count)
+    {
+      /* Call the library function.  */
+      func (1);
+    }
+
+  breakpt ();	/* Break before close.  */
+
+  /* Unload the shared library.  */
+  if (dlclose (handle) != 0)
+    abort ();
+
+  breakpt ();	/* Break after close.  */
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.multi/pending-bp.exp b/gdb/testsuite/gdb.multi/pending-bp.exp
new file mode 100644
index 00000000000..478d8d7c037
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp.exp
@@ -0,0 +1,126 @@
+# Copyright 2023 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+# Tests related to pending breakpoints in a multi-inferior environment.
+
+require allow_shlib_tests !use_gdb_stub
+
+standard_testfile
+
+set libname $testfile-lib
+set srcfile_lib $srcdir/$subdir/$libname.c
+set binfile_lib [standard_output_file $libname.so]
+
+if { [gdb_compile_shlib $srcfile_lib $binfile_lib {}] != "" } {
+    untested "failed to compile shared library 1"
+    return -1
+}
+
+set binfile_lib_target [gdb_download_shlib $binfile_lib]
+
+if { [build_executable "failed to prepare" $testfile $srcfile \
+	  [list debug \
+	       additional_flags=-DSHLIB_NAME=\"$binfile_lib_target\" \
+	       shlib_load]] } {
+    return -1
+}
+
+# Start two inferiors, both running the same test binary.  The arguments
+# INF_1_STOP and INF_2_STOP are source code patterns that are passed to
+# gdb_get_line_number to figure out where each inferior should be stopped.
+#
+# This proc does a clean_restart and leaves inferior 2 selected.  Also the
+# 'breakpoint pending' flag is enabled, so pending breakpoints can be created
+# without GDB prompting the user.
+proc do_test_setup { inf_1_stop inf_2_stop } {
+    clean_restart ${::binfile}
+
+    gdb_locate_shlib $::binfile_lib
+
+    if {![runto_main]} {
+	return false
+    }
+
+    gdb_breakpoint [gdb_get_line_number ${inf_1_stop}] temporary
+    gdb_continue_to_breakpoint "move inferior 1 into position"
+
+    gdb_test "add-inferior -exec ${::binfile}" \
+	"Added inferior 2.*" "add inferior 2"
+    gdb_test "inferior 2" "Switching to inferior 2 .*" "switch to inferior 2"
+
+    if {![runto_main]} {
+	return false
+    }
+
+    gdb_breakpoint [gdb_get_line_number ${inf_2_stop}] temporary
+    gdb_continue_to_breakpoint "move inferior 2 into position"
+
+    gdb_test_no_output "set breakpoint pending on"
+
+    return true
+}
+
+# Check that when a breakpoint is in the pending state, but that breakpoint
+# does have some locations (those locations themselves are pending), GDB
+# doesn't display the inferior list in the 'info breakpoints' output.
+proc_with_prefix test_no_inf_display {} {
+    do_test_setup "Break before open" "Break before open"
+
+    # Create a breakpoint on 'foo'.  As the shared library (that
+    # contains foo) has not been loaded into any inferior yet, then
+    # there will be no locations and the breakpoint will be created
+    # pending.  Pass the 'allow-pending' flag so the gdb_breakpoint
+    # correctly expects the new breakpoint to be pending.
+    gdb_breakpoint "foo" allow-pending
+    set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+		   "get foo breakpoint number"]
+
+    # Check the 'info breakpoints' output; the breakpoint is pending with
+    # no 'inf X' appearing at the end of the line.
+    gdb_test "info breakpoint $bpnum" \
+	"$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	"check info bp before locations have been created"
+
+    # Now select inferior 1 and allow the inferior to run forward to the
+    # point where a breakpoint location for foo will have been created.
+    gdb_test "inferior 1" "Switching to inferior 1 .*"
+    gdb_breakpoint [gdb_get_line_number "Break after open"] temporary
+    gdb_continue_to_breakpoint \
+	"move inferior 1 until a location has been added"
+
+    # Check the 'info breakpoints' output.  Notice we display the inferior
+    # list at the end of the breakpoint line.
+    gdb_test "info breakpoint $bpnum" \
+	"$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex\\s+<foo\[^>\]*>\\s+inf 1" \
+	"check info breakpoints while breakpoint is inserted"
+
+    # Continue inferior 1 until the shared library has been unloaded.  The
+    # breakpoint on 'foo' will return to the pending state.  We will need to
+    # 'continue' twice as the first time will hit the 'foo' breakpoint.
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "hit the breakpoint in foo"
+    gdb_continue_to_breakpoint "after close library"
+
+    # Check the 'info breakpoints' output, check there is no 'inf 1' at the
+    # end of the breakpoint line.
+    gdb_test "info breakpoint $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	     "\\s+breakpoint already hit 1 time"] \
+	"check info breakpoints while breakpoint is pending"
+}
+
+# Run all the tests.
+test_no_inf_display
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv10 2/9] gdb: remove breakpoint_re_set_one
  2024-03-31 10:31                 ` [PATCHv10 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
  2024-03-31 10:31                   ` [PATCHv10 1/9] gdb: don't display inferior list for pending breakpoints Andrew Burgess
@ 2024-03-31 10:31                   ` Andrew Burgess
  2024-03-31 10:31                   ` [PATCHv10 3/9] gdb: remove tracepoint_probe_create_sals_from_location_spec Andrew Burgess
                                     ` (6 subsequent siblings)
  8 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2024-03-31 10:31 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

During a later patch I wanted to reset a single breakpoint, so I
called breakpoint_re_set_one.  However, this is not the right thing to
do.  If we look at breakpoint_re_set then we see that there's a whole
bunch of state that needs to be preserved prior to calling
breakpoint_re_set_one, and after calling breakpoint_re_set_one we
still need to call update_global_location_list.

I could just update the comment on breakpoint_re_set_one to make it
clearer how the function should be used -- or more likely to warn that
the function should only be used as a helper from breakpoint_re_set.

However, breakpoint_re_set_one is only 3 lines long.  So I figure it
might actually be easier to just fold breakpoint_re_set_one into
breakpoint_re_set, then there's no risk of accidentally calling
breakpoint_re_set_one when we shouldn't.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c | 26 ++++++++------------------
 1 file changed, 8 insertions(+), 18 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index fef7f9a82a4..93645f534f2 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -13211,17 +13211,6 @@ create_sals_from_location_spec_default (location_spec *locspec,
   parse_breakpoint_sals (locspec, canonical);
 }
 
-/* Reset a breakpoint.  */
-
-static void
-breakpoint_re_set_one (breakpoint *b)
-{
-  input_radix = b->input_radix;
-  set_language (b->language);
-
-  b->re_set ();
-}
-
 /* Re-set breakpoint locations for the current program space.
    Locations bound to other program spaces are left untouched.  */
 
@@ -13233,12 +13222,11 @@ breakpoint_re_set (void)
     scoped_restore save_input_radix = make_scoped_restore (&input_radix);
     scoped_restore_current_pspace_and_thread restore_pspace_thread;
 
-    /* breakpoint_re_set_one sets the current_language to the language
-       of the breakpoint it is resetting (see prepare_re_set_context)
-       before re-evaluating the breakpoint's location.  This change can
-       unfortunately get undone by accident if the language_mode is set
-       to auto, and we either switch frames, or more likely in this context,
-       we select the current frame.
+    /* To ::re_set each breakpoint we set the current_language to the
+       language of the breakpoint before re-evaluating the breakpoint's
+       location.  This change can unfortunately get undone by accident if
+       the language_mode is set to auto, and we either switch frames, or
+       more likely in this context, we select the current frame.
 
        We prevent this by temporarily turning the language_mode to
        language_mode_manual.  We restore it once all breakpoints
@@ -13255,7 +13243,9 @@ breakpoint_re_set (void)
       {
 	try
 	  {
-	    breakpoint_re_set_one (&b);
+	    input_radix = b.input_radix;
+	    set_language (b.language);
+	    b.re_set ();
 	  }
 	catch (const gdb_exception &ex)
 	  {
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv10 3/9] gdb: remove tracepoint_probe_create_sals_from_location_spec
  2024-03-31 10:31                 ` [PATCHv10 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
  2024-03-31 10:31                   ` [PATCHv10 1/9] gdb: don't display inferior list for pending breakpoints Andrew Burgess
  2024-03-31 10:31                   ` [PATCHv10 2/9] gdb: remove breakpoint_re_set_one Andrew Burgess
@ 2024-03-31 10:31                   ` Andrew Burgess
  2024-03-31 10:31                   ` [PATCHv10 4/9] gdb: make breakpoint_debug_printf global Andrew Burgess
                                     ` (5 subsequent siblings)
  8 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2024-03-31 10:31 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

The tracepoint_probe_create_sals_from_location_spec function just
forwards all its arguments to
bkpt_probe_create_sals_from_location_spec, and is only used in one
place.

Lets delete tracepoint_probe_create_sals_from_location_spec and
replace it with bkpt_probe_create_sals_from_location_spec.

There should be no user visible changes after this commit.
---
 gdb/breakpoint.c | 19 +++----------------
 1 file changed, 3 insertions(+), 16 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 93645f534f2..afa8e49569a 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -282,9 +282,6 @@ static bool strace_marker_p (struct breakpoint *b);
 static void bkpt_probe_create_sals_from_location_spec
      (location_spec *locspec,
       struct linespec_result *canonical);
-static void tracepoint_probe_create_sals_from_location_spec
-     (location_spec *locspec,
-      struct linespec_result *canonical);
 
 const struct breakpoint_ops code_breakpoint_ops =
 {
@@ -299,10 +296,11 @@ static const struct breakpoint_ops bkpt_probe_breakpoint_ops =
   create_breakpoints_sal,
 };
 
-/* Tracepoints set on probes.  */
+/* Tracepoints set on probes.  We use the same methods as for breakpoints
+   on probes.  */
 static const struct breakpoint_ops tracepoint_probe_breakpoint_ops =
 {
-  tracepoint_probe_create_sals_from_location_spec,
+  bkpt_probe_create_sals_from_location_spec,
   create_breakpoints_sal,
 };
 
@@ -12402,17 +12400,6 @@ tracepoint::print_recreate (struct ui_file *fp) const
     gdb_printf (fp, "  passcount %d\n", pass_count);
 }
 
-/* Virtual table for tracepoints on static probes.  */
-
-static void
-tracepoint_probe_create_sals_from_location_spec
-  (location_spec *locspec,
-   struct linespec_result *canonical)
-{
-  /* We use the same method for breakpoint on probes.  */
-  bkpt_probe_create_sals_from_location_spec (locspec, canonical);
-}
-
 void
 dprintf_breakpoint::re_set ()
 {
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv10 4/9] gdb: make breakpoint_debug_printf global
  2024-03-31 10:31                 ` [PATCHv10 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
                                     ` (2 preceding siblings ...)
  2024-03-31 10:31                   ` [PATCHv10 3/9] gdb: remove tracepoint_probe_create_sals_from_location_spec Andrew Burgess
@ 2024-03-31 10:31                   ` Andrew Burgess
  2024-03-31 10:31                   ` [PATCHv10 5/9] gdb: add another overload of startswith Andrew Burgess
                                     ` (4 subsequent siblings)
  8 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2024-03-31 10:31 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

This commit makes breakpoint_debug_printf available outside of
breakpoint.c.  In a later commit I'll want to use this macro from
another file.

This is just a refactor, there should be no user visible changes after
this commit.
---
 gdb/breakpoint.c | 9 ++-------
 gdb/breakpoint.h | 8 ++++++++
 2 files changed, 10 insertions(+), 7 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index afa8e49569a..8a2a0cc7100 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -573,13 +573,8 @@ show_always_inserted_mode (struct ui_file *file, int from_tty,
 	      value);
 }
 
-/* True if breakpoint debug output is enabled.  */
-static bool debug_breakpoint = false;
-
-/* Print a "breakpoint" debug statement.  */
-#define breakpoint_debug_printf(fmt, ...) \
-  debug_prefixed_printf_cond (debug_breakpoint, "breakpoint", fmt, \
-			      ##__VA_ARGS__)
+/* See breakpoint.h.  */
+bool debug_breakpoint = false;
 
 /* "show debug breakpoint" implementation.  */
 static void
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index 6da04d5ec00..24aeaf926ec 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -48,6 +48,14 @@ struct linespec_result;
 struct linespec_sals;
 struct inferior;
 
+/* True if breakpoint debug output is enabled.  */
+extern bool debug_breakpoint;
+
+/* Print a "breakpoint" debug statement.  */
+#define breakpoint_debug_printf(fmt, ...) \
+  debug_prefixed_printf_cond (debug_breakpoint, "breakpoint", fmt, \
+			      ##__VA_ARGS__)
+
 /* Enum for exception-handling support in 'catch throw', 'catch rethrow',
    'catch catch' and the MI equivalent.  */
 
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv10 5/9] gdb: add another overload of startswith
  2024-03-31 10:31                 ` [PATCHv10 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
                                     ` (3 preceding siblings ...)
  2024-03-31 10:31                   ` [PATCHv10 4/9] gdb: make breakpoint_debug_printf global Andrew Burgess
@ 2024-03-31 10:31                   ` Andrew Burgess
  2024-03-31 10:31                   ` [PATCHv10 6/9] gdb: create new is_thread_id helper function Andrew Burgess
                                     ` (3 subsequent siblings)
  8 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2024-03-31 10:31 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

We already have one overload of the startswith function that takes a
std::string_view for both arguments.  A later patch in this series is
going to be improved by having an overload that takes one argument as
a std::string_view and the other argument as a plain 'char *'.

This commit adds the new overload, but doesn't make use of it (yet).
There should be no user visible changes after this commit.
---
 gdbsupport/common-utils.h | 10 ++++++++++
 1 file changed, 10 insertions(+)

diff --git a/gdbsupport/common-utils.h b/gdbsupport/common-utils.h
index 23cd40c0207..2fb22916409 100644
--- a/gdbsupport/common-utils.h
+++ b/gdbsupport/common-utils.h
@@ -100,6 +100,16 @@ startswith (std::string_view string, std::string_view pattern)
 	  && strncmp (string.data (), pattern.data (), pattern.length ()) == 0);
 }
 
+/* Version of startswith that takes a string_view for only one of its
+   arguments.  Return true if STR starts with PREFIX, otherwise return
+   false.  */
+
+static inline bool
+startswith (const char *str, const std::string_view &prefix)
+{
+  return strncmp (str, prefix.data (), prefix.length ()) == 0;
+}
+
 /* Return true if the strings are equal.  */
 
 static inline bool
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv10 6/9] gdb: create new is_thread_id helper function
  2024-03-31 10:31                 ` [PATCHv10 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
                                     ` (4 preceding siblings ...)
  2024-03-31 10:31                   ` [PATCHv10 5/9] gdb: add another overload of startswith Andrew Burgess
@ 2024-03-31 10:31                   ` Andrew Burgess
  2024-03-31 10:31                   ` [PATCHv10 7/9] gdb: parse pending breakpoint thread/task immediately Andrew Burgess
                                     ` (2 subsequent siblings)
  8 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2024-03-31 10:31 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

This is a refactoring commit that splits the existing parse_thread_id
function into two parts, and then adds a new is_thread_id function.

The core of parse_thread_id is split into parse_thread_id_1, which is
responsible for actually parsing a thread-id.  Then parse_thread_id is
responsible for taking a parsed thread-id and validating that it
references an actually existing inferior thread.

The new is_thread_id function also uses parse_thread_id_1, but doesn't
actually check that the inferior thread exists, instead, this new
function simply checks that a string looks like a thread-id.

This commit does not add a use for is_thread_id, this will be added in
the next commit.

This is a refactoring commit, there should be no user visible changes
after this commit.
---
 gdb/tid-parse.c | 82 +++++++++++++++++++++++++++++++++++++------------
 gdb/tid-parse.h |  8 +++++
 2 files changed, 70 insertions(+), 20 deletions(-)

diff --git a/gdb/tid-parse.c b/gdb/tid-parse.c
index 623f55e14b3..cff1a5f3d2b 100644
--- a/gdb/tid-parse.c
+++ b/gdb/tid-parse.c
@@ -47,40 +47,43 @@ get_positive_number_trailer (const char **pp, int trailer, const char *string)
   return num;
 }
 
-/* See tid-parse.h.  */
+/* Parse TIDSTR as a per-inferior thread ID, in either INF_NUM.THR_NUM
+   or THR_NUM form, and return a pair, the first item of the pair is
+   INF_NUM and the second item is THR_NUM.
 
-struct thread_info *
-parse_thread_id (const char *tidstr, const char **end)
+   If TIDSTR does not include an INF_NUM component, then the first item in
+   the pair will be 0 (which is an invalid inferior number), this indicates
+   that TIDSTR references the current inferior.
+
+   This function does not validate the INF_NUM and THR_NUM are actually
+   valid numbers, that is, they might reference inferiors or threads that
+   don't actually exist; this function just splits the string into its
+   component parts.
+
+   If there is an error parsing TIDSTR then this function will raise an
+   exception.  */
+
+static std::pair<int, int>
+parse_thread_id_1 (const char *tidstr, const char **end)
 {
   const char *number = tidstr;
   const char *dot, *p1;
-  struct inferior *inf;
-  int thr_num;
-  int explicit_inf_id = 0;
+  int thr_num, inf_num;
 
   dot = strchr (number, '.');
 
   if (dot != NULL)
     {
       /* Parse number to the left of the dot.  */
-      int inf_num;
-
       p1 = number;
       inf_num = get_positive_number_trailer (&p1, '.', number);
       if (inf_num == 0)
 	invalid_thread_id_error (number);
-
-      inf = find_inferior_id (inf_num);
-      if (inf == NULL)
-	error (_("No inferior number '%d'"), inf_num);
-
-      explicit_inf_id = 1;
       p1 = dot + 1;
     }
   else
     {
-      inf = current_inferior ();
-
+      inf_num = 0;
       p1 = number;
     }
 
@@ -88,6 +91,32 @@ parse_thread_id (const char *tidstr, const char **end)
   if (thr_num == 0)
     invalid_thread_id_error (number);
 
+  if (end != nullptr)
+    *end = p1;
+
+  return { inf_num, thr_num };
+}
+
+/* See tid-parse.h.  */
+
+struct thread_info *
+parse_thread_id (const char *tidstr, const char **end)
+{
+  const auto [inf_num, thr_num] = parse_thread_id_1 (tidstr, end);
+
+  inferior *inf;
+  bool explicit_inf_id = false;
+
+  if (inf_num != 0)
+    {
+      inf = find_inferior_id (inf_num);
+      if (inf == nullptr)
+	error (_("No inferior number '%d'"), inf_num);
+      explicit_inf_id = true;
+    }
+  else
+    inf = current_inferior ();
+
   thread_info *tp = nullptr;
   for (thread_info *it : inf->threads ())
     if (it->per_inf_num == thr_num)
@@ -96,7 +125,7 @@ parse_thread_id (const char *tidstr, const char **end)
 	break;
       }
 
-  if (tp == NULL)
+  if (tp == nullptr)
     {
       if (show_inferior_qualified_tids () || explicit_inf_id)
 	error (_("Unknown thread %d.%d."), inf->num, thr_num);
@@ -104,14 +133,27 @@ parse_thread_id (const char *tidstr, const char **end)
 	error (_("Unknown thread %d."), thr_num);
     }
 
-  if (end != NULL)
-    *end = p1;
-
   return tp;
 }
 
 /* See tid-parse.h.  */
 
+bool
+is_thread_id (const char *tidstr, const char **end)
+{
+  try
+    {
+      (void) parse_thread_id_1 (tidstr, end);
+      return true;
+    }
+  catch (const gdb_exception_error &)
+    {
+      return false;
+    }
+}
+
+/* See tid-parse.h.  */
+
 tid_range_parser::tid_range_parser (const char *tidlist,
 				    int default_inferior)
 {
diff --git a/gdb/tid-parse.h b/gdb/tid-parse.h
index b7bd920f48a..bba5ae5118c 100644
--- a/gdb/tid-parse.h
+++ b/gdb/tid-parse.h
@@ -36,6 +36,14 @@ extern void ATTRIBUTE_NORETURN invalid_thread_id_error (const char *string);
    thrown.  */
 struct thread_info *parse_thread_id (const char *tidstr, const char **end);
 
+/* Return true if TIDSTR is pointing to a string that looks like a
+   thread-id.  This doesn't mean that TIDSTR identifies a valid thread, but
+   the string does at least look like a valid thread-id.  If END is not
+   NULL, parse_thread_id stores the address of the first character after
+   the thread-id into *END.  */
+
+bool is_thread_id (const char *tidstr, const char **end);
+
 /* Parse a thread ID or a thread range list.
 
    A range will be of the form
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv10 7/9] gdb: parse pending breakpoint thread/task immediately
  2024-03-31 10:31                 ` [PATCHv10 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
                                     ` (5 preceding siblings ...)
  2024-03-31 10:31                   ` [PATCHv10 6/9] gdb: create new is_thread_id helper function Andrew Burgess
@ 2024-03-31 10:31                   ` Andrew Burgess
  2024-03-31 10:31                   ` [PATCHv10 8/9] gdb: don't set breakpoint::pspace in create_breakpoint Andrew Burgess
  2024-03-31 10:31                   ` [PATCHv10 9/9] gdb: only insert thread-specific breakpoints in the relevant inferior Andrew Burgess
  8 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2024-03-31 10:31 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Eli Zaretskii

The initial motivation for this commit was to allow thread or inferior
specific breakpoints to only be inserted within the appropriate
inferior's program-space.  The benefit of this is that inferiors for
which the breakpoint does not apply will no longer need to stop, and
then resume, for such breakpoints.  This commit does not make this
change, but is a refactor to allow this to happen in a later commit.

The problem we currently have is that when a thread-specific (or
inferior-specific) breakpoint is created, the thread (or inferior)
number is only parsed by calling find_condition_and_thread_for_sals.
This function is only called for non-pending breakpoints, and requires
that we know the locations at which the breakpoint will be placed (for
expression checking in case the breakpoint is also conditional).

A consequence of this is that by the time we figure out the breakpoint
is thread-specific we have already looked up locations in all program
spaces.  This feels wasteful -- if we knew the thread-id earlier then
we could reduce the work GDB does by only looking up locations within
the program space for which the breakpoint applies.

Another consequence of how find_condition_and_thread_for_sals is
called is that pending breakpoints don't currently know they are
thread-specific, nor even that they are conditional!  Additionally, by
delaying parsing the thread-id, pending breakpoints can be created for
non-existent threads, this is different to how non-pending
breakpoints are handled, so I can do this:

  $ gdb -q ./gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp
  Reading symbols from ./gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp...
  (gdb) break foo thread 99
  Function "foo" not defined.
  Make breakpoint pending on future shared library load? (y or [n]) y
  Breakpoint 1 (foo thread 99) pending.
  (gdb) r
  Starting program: /tmp/gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp
  [Thread debugging using libthread_db enabled]
  Using host libthread_db library "/lib64/libthread_db.so.1".
  Error in re-setting breakpoint 1: Unknown thread 99.
  [Inferior 1 (process 3329749) exited normally]
  (gdb)

GDB only checked the validity of 'thread 99' at the point the 'foo'
location became non-pending.  In contrast, if I try this:

  $ gdb -q ./gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp
  Reading symbols from ./gdb/testsuite/outputs/gdb.multi/pending-bp/pending-bp...
  (gdb) break main thread 99
  Unknown thread 99.
  (gdb)

GDB immediately checks if 'thread 99' exists.  I think inconsistencies
like this are confusing, and should be fixed if possible.

In this commit the create_breakpoint function is updated so that the
extra_string, which contains the thread, inferior, task, and/or
condition information, is parsed immediately, even for pending
breakpoints.

Obviously, the condition still can't be validated until the breakpoint
becomes non-pending, but the thread, inferior, and task information
can be pulled from the extra-string, and can be validated early on,
even for pending breakpoints.  The -force-condition flag is also
parsed as part of this early parsing change.

There are a couple of benefits to doing this:

1. Printing of breakpoints is more consistent now.  Consider creating
   a conditional breakpoint before this commit:

    (gdb) set breakpoint pending on
    (gdb) break pendingfunc if (0)
    Function "pendingfunc" not defined.
    Breakpoint 1 (pendingfunc if (0)) pending.
    (gdb) break main if (0)
    Breakpoint 2 at 0x401198: file /tmp/hello.c, line 18.
    (gdb) info breakpoints
    Num     Type           Disp Enb Address            What
    1       breakpoint     keep y   <PENDING>          pendingfunc if (0)
    2       breakpoint     keep y   0x0000000000401198 in main at /tmp/hello.c:18
            stop only if (0)
    (gdb)

   And after this commit:

    (gdb) set breakpoint pending on
    (gdb) break pendingfunc if (0)
    Function "pendingfunc" not defined.
    Breakpoint 1 (pendingfunc) pending.
    (gdb) break main if (0)
    Breakpoint 2 at 0x401198: file /home/andrew/tmp/hello.c, line 18.
    (gdb) info breakpoints
    Num     Type           Disp Enb Address            What
    1       breakpoint     keep y   <PENDING>          pendingfunc
            stop only if (0)
    2       breakpoint     keep y   0x0000000000401198 in main at /home/andrew/tmp/hello.c:18
            stop only if (0)
    (gdb)

   Notice that the display of the condition is now the same for the
   pending and non-pending breakpoints.

   The same is true for the thread, inferior, or task information in
   thread, inferior, or task specific breakpoints; this information is
   displayed on its own line rather than being part of the 'What'
   field.

2. We can check that the thread exists as soon as the pending
   breakpoint is created.  Currently there is a weird difference
   between pending and non-pending breakpoints when creating a
   thread-specific breakpoint.

   A pending thread-specific breakpoint only checks its thread when it
   becomes non-pending, at which point the thread the breakpoint was
   intended for might have exited.  Here's the behaviour before this
   commit:

    (gdb) set breakpoint pending on
    (gdb) break foo thread 2
    Function "foo" not defined.
    Breakpoint 2 (foo thread 2) pending.
    (gdb) c
    Continuing.
    [Thread 0x7ffff7c56700 (LWP 2948835) exited]
    Error in re-setting breakpoint 2: Unknown thread 2.
    [Inferior 1 (process 2948832) exited normally]
    (gdb)

   Notice the 'Error in re-setting breakpoint 2: Unknown thread 2.'
   line, this was triggered when GDB tried to make the breakpoint
   non-pending, and GDB discovers that the thread no longer exists.

   Compare that to the behaviour after this commit:

    (gdb) set breakpoint pending on
    (gdb) break foo thread 2
    Function "foo" not defined.
    Breakpoint 2 (foo) pending.
    (gdb) c
    Continuing.
    [Thread 0x7ffff7c56700 (LWP 2949243) exited]
    Thread-specific breakpoint 2 deleted - thread 2 no longer in the thread list.
    [Inferior 1 (process 2949240) exited normally]
    (gdb)

   Now the behaviour for pending breakpoints is identical to
   non-pending breakpoints, the thread specific breakpoint is removed
   as soon as the thread the breakpoint is associated with exits.

   There is an additional change; when the pending breakpoint is
   created prior to this patch we see this line:

     Breakpoint 2 (foo thread 2) pending.

   While after this patch we get this line:

     Breakpoint 2 (foo) pending.

   Notice that 'thread 2' has disappeared.  This might look like a
   regression, but I don't think it is.  That we said 'thread 2'
   before was just a consequence of the lazy parsing of the breakpoint
   specification, while with this patch GDB understands, and has
   parsed away the 'thread 2' bit of the spec.  If folk think the old
   information was useful then this would be trivial to add back in
   code_breakpoint::say_where.

As a result of this commit the breakpoints 'extra_string' field is now
only used by bp_dprintf type breakpoints to hold the printf format and
arguments.  This string should always be empty for other breakpoint
types.  This allows some cleanup in print_breakpoint_location.

In code_breakpoint::code_breakpoint I've changed an error case into an
assert.  This is because the error is now handled earlier in
create_breakpoint.  As a result we know that by this point, the
extra_string will always be nullptr for anything other than a
bp_dprintf style breakpoint.

The find_condition_and_thread_for_sals function is now no longer
needed, this was previously doing the delayed splitting of the extra
string into thread, task, and condition, but this is now all done in
create_breakpoint, so find_condition_and_thread_for_sals can be
deleted, and the code that calls this in
code_breakpoint::location_spec_to_sals can be removed.  With this
update this code would only ever be reached for bp_dprintf style
breakpoints, and in these cases the extra_string should not contain
anything other than format and args.

The most interesting changes are all in create_breakpoint and in the
new file break-cond-parse.c.  We have a new block of code early on in
create_breakpoint that is responsible for splitting the extra_string
into its component parts by calling create_breakpoint_parse_arg_string
a function in the new break-cond-parse.c file.  This means that some
of the later code can be simplified a little.

The new break-cond-parse.c file implements the splitting up the
extra_string and finding all the parts, as well as some self-tests for
the new function.

Finally, now we know all the breakpoint details, these can be stored
within the breakpoint object if we end up creating a deferred
breakpoint.  Additionally, if we are creating a deferred bp_dprintf we
can parse the extra_string to build the printf command.

The implementation here aims to maintain backwards compatibility as
much as possible, this means that:

  1. We support abbreviations of 'thread', 'task', and 'inferior' in
  some places on the breakpoint line.  The handling of abbreviations
  has (before this patch) been a little weird, so this works:

  (gdb) break *main th 1

  And creates a breakpoint at '*main' for thread 1 only, while this
  does not work:

  (gdb) break main th 1

  In this case GDB will try to find the symbol 'main th 1'.  This
  weirdness exists before and after this patch.

  2. The handling of '-force-condition' is odd, if this flag appears
  immediately after a condition then it will be treated as part of the
  condition, e.g.:

  (gdb) break main if 0 -force-condition
  No symbol "force" in current context.

  But we are fine with these alternatives:

  (gdb) break main if 0 thread 1 -force-condition
  (gdb) break main -force-condition if 0

  Again, this is just a quirk of how the breakpoint line used to be
  parsed, but I've maintained this for backward compatibility.  During
  review it was suggested that -force-condition should become an
  actual breakpoint flag (i.e. only valid after the 'break' command
  but before the function name), and I don't think that would be a
  terrible idea, however, that's not currently a trivial change, and I
  think should be done as a separate piece of work.  For now, this
  patch just maintains the current behaviour.

The implementation works by first splitting the breakpoint condition
string (everything after the location specification) into a list of
tokens, each token has a type and a value. (e.g. we have a THREAD
token where the value is the thread-id string).  The list of tokens is
validated, and in some cases, tokens are merged.  Then the values are
extracted from the remaining token list.

Consider this breakpoint command:

  (gdb) break main thread 1 if argc == 2

The condition string passed to create_breakpoint_parse_arg_string is
going to be 'thread 1 if argc == 2', which is then split into the
tokens:

  { THREAD: "1" } { CONDITION: "argc == 2" }

The thread-id (1) and the condition string 'argc == 2' are extracted
from these tokens and returns back to create_breakpoint.

Now consider this breakpoint command:

  (gdb) break some_function if ( some_var == thread )

Here the user wants a breakpoint if 'some_var' is equal to the
variable 'thread'.  However, when this is initially parsed we will
find these tokens:

  { CONDITION: "( some_var == " } { THREAD: ")" }

This is a consequence of how we have to try and figure out the
contents of the 'if' condition without actually parsing the
expression; parsing the expression requires that we know the location
in order to lookup the variables by name, and this can't be done for
pending breakpoints (their location isn't known yet), and one of the
points of this work is that we extract things like thread-id for
pending breakpoints.

And so, it is in this case that token merging takes place.  We check
if the value of a token appearing immediately after the CONDITION
token looks valid.  In this case, does ')' look like a valid
thread-id.  Clearly, in this case ')' does not, and so me merge the
THREAD token into the condition token, giving:

  { CONDITION: "( some_var == thread )" }

Which is what we want.

I'm sure that we might still be able to come up with some edge cases
where the parser makes the wrong choice.  I think long term the best
way to work around these would be to move the thread, inferior, task,
and -force-condition flags to be "real" command options for the break
command.  I am looking into doing this, but can't guarantee if/when
that work would be completed, so this patch should be reviewed assume
that the work will never arrive (though I hope it will).

Reviewed-By: Eli Zaretskii <eliz@gnu.org>
---
 gdb/Makefile.in                               |   2 +
 gdb/NEWS                                      |   4 +
 gdb/break-cond-parse.c                        | 701 ++++++++++++++++++
 gdb/break-cond-parse.h                        |  52 ++
 gdb/breakpoint.c                              | 372 ++--------
 gdb/testsuite/gdb.ada/tasks.exp               |   6 +-
 gdb/testsuite/gdb.base/condbreak.exp          |  57 +-
 gdb/testsuite/gdb.base/pending.exp            |  23 +-
 gdb/testsuite/gdb.linespec/explicit.exp       |   4 +-
 gdb/testsuite/gdb.linespec/keywords.exp       |   8 +-
 gdb/testsuite/gdb.mi/mi-dprintf-pending.exp   |   3 +-
 .../gdb.multi/inferior-specific-bp.exp        |   4 +-
 .../gdb.threads/del-pending-thread-bp-lib.c   |  22 +
 .../gdb.threads/del-pending-thread-bp.c       |  85 +++
 .../gdb.threads/del-pending-thread-bp.exp     | 108 +++
 15 files changed, 1145 insertions(+), 306 deletions(-)
 create mode 100644 gdb/break-cond-parse.c
 create mode 100644 gdb/break-cond-parse.h
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.c
 create mode 100644 gdb/testsuite/gdb.threads/del-pending-thread-bp.exp

diff --git a/gdb/Makefile.in b/gdb/Makefile.in
index a9f641c0659..031a50e40c7 100644
--- a/gdb/Makefile.in
+++ b/gdb/Makefile.in
@@ -1049,6 +1049,7 @@ COMMON_SFILES = \
 	break-catch-sig.c \
 	break-catch-syscall.c \
 	break-catch-throw.c \
+	break-cond-parse.c \
 	breakpoint.c \
 	bt-utils.c \
 	btrace.c \
@@ -1317,6 +1318,7 @@ HFILES_NO_SRCDIR = \
 	bfd-target.h \
 	bfin-tdep.h \
 	block.h \
+	break-cond-parse.h \
 	breakpoint.h \
 	bsd-kvm.h \
 	bsd-uthread.h \
diff --git a/gdb/NEWS b/gdb/NEWS
index feb3a37393a..fa2d1427ded 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -16,6 +16,10 @@
   the background, resulting in faster startup.  This can be controlled
   using "maint set dwarf synchronous".
 
+* For breakpoints that are created in the 'pending' state, any
+  'thread' or 'task' keywords are parsed at the time the breakpoint is
+  created, rather than at the time the breakpoint becomes non-pending.
+
 * Changed commands
 
 disassemble
diff --git a/gdb/break-cond-parse.c b/gdb/break-cond-parse.c
new file mode 100644
index 00000000000..eff738f2a7c
--- /dev/null
+++ b/gdb/break-cond-parse.c
@@ -0,0 +1,701 @@
+/* Copyright (C) 2023 Free Software Foundation, Inc.
+
+   This file is part of GDB.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#include "defs.h"
+#include "gdbsupport/gdb_assert.h"
+#include "gdbsupport/selftest.h"
+#include "test-target.h"
+#include "scoped-mock-context.h"
+#include "break-cond-parse.h"
+#include "tid-parse.h"
+#include "ada-lang.h"
+
+/* When parsing tokens from a string, which direction are we parsing?
+
+   Given the following string and pointer 'ptr':
+
+	ABC DEF GHI JKL
+	       ^
+	       ptr
+
+   Parsing 'forward' will return the token 'GHI' and update 'ptr' to point
+   between GHI and JKL.  Parsing 'backward' will return the token 'DEF' and
+   update 'ptr' to point between ABC and DEF.
+*/
+
+enum class parse_direction
+{
+  /* Parse the next token forwards.  */
+  forward,
+
+  /* Parse the previous token backwards.  */
+  backward
+};
+
+/* Find the next token in DIRECTION from *CURR.  */
+
+static std::string_view
+find_next_token (const char **curr, parse_direction direction)
+{
+  const char *tok_start, *tok_end;
+
+  gdb_assert (**curr != '\0');
+
+  if (direction == parse_direction::forward)
+    {
+      *curr = skip_spaces (*curr);
+      tok_start = *curr;
+      *curr = skip_to_space (*curr);
+      tok_end = *curr - 1;
+    }
+  else
+    {
+      gdb_assert (direction == parse_direction::backward);
+
+      while (isspace (**curr))
+	--(*curr);
+
+      tok_end = *curr;
+
+      while (!isspace (**curr))
+	--(*curr);
+
+      tok_start = (*curr) + 1;
+    }
+
+  return std::string_view (tok_start, tok_end - tok_start + 1);
+}
+
+/* A class that represents a complete parsed token.  Each token has a type
+   and a std::string_view into the original breakpoint condition string.  */
+
+struct token
+{
+  /* The types a token might take.  */
+  enum class type
+  {
+    /* These are the token types for the 'if', 'thread', 'inferior', and
+       'task' keywords.  The m_content for these token types is the value
+       passed to the keyword, not the keyword itself.  */
+    CONDITION,
+    THREAD,
+    INFERIOR,
+    TASK,
+
+    /* This is the token used when we find unknown content, the m_content
+       for this token is the rest of the input string.  */
+    REST,
+
+    /* This is the token for the -force-condition token, the m_content for
+       this token contains the keyword itself.  */
+    FORCE
+  };
+
+  token (enum type type, std::string_view content)
+    : m_type (type),
+      m_content (std::move (content))
+  {
+    /* Nothing.  */
+  }
+
+  /* Return a string representing this token.  Only used for debug.  */
+  std::string to_string () const
+  {
+    switch (m_type)
+      {
+      case type::CONDITION:
+	return string_printf ("{ CONDITION: \"%s\" }",
+			      std::string (m_content).c_str ());
+      case type::THREAD:
+	return string_printf ("{ THREAD: \"%s\" }",
+			      std::string (m_content).c_str ());
+      case type::INFERIOR:
+	return string_printf ("{ INFERIOR: \"%s\" }",
+			      std::string (m_content).c_str ());
+      case type::TASK:
+	return string_printf ("{ TASK: \"%s\" }",
+			      std::string (m_content).c_str ());
+      case type::REST:
+	return string_printf ("{ REST: \"%s\" }",
+			      std::string (m_content).c_str ());
+      case type::FORCE:
+	return string_printf ("{ FORCE }");
+      default:
+	return "** unknown **";
+      }
+  }
+
+  /* The type of this token.  */
+  const type &get_type () const
+  {
+    return m_type;
+  }
+
+  /* Return the value of this token.  */
+  const std::string_view &get_value () const
+  {
+    gdb_assert (m_content.size () > 0);
+    return m_content;
+  }
+
+  /* Extend this token with the contents of OTHER.  This only makes sense
+     if OTHER is the next token after this one in the original string,
+     however, enforcing that restriction is left to the caller of this
+     function.
+
+     When OTHER is a keyword/value token, e.g. 'thread 1', the m_content
+     for OTHER will only point to the '1'.  However, as the m_content is a
+     std::string_view, then when we merge the m_content of OTHER into this
+     token we automatically merge in the 'thread' part too, as it
+     naturally sits between this token and OTHER.  */
+
+  void
+  extend (const token &other)
+  {
+    m_content = std::string_view (this->m_content.data (),
+				  (other.m_content.data ()
+				   - this->m_content.data ()
+				   + other.m_content.size ()));
+  }
+
+private:
+  /* The type of this token.  */
+  type m_type;
+
+  /* The important content part of this token.  The extend member function
+     depends on this being a std::string_view.  */
+  std::string_view m_content;
+};
+
+/* Split STR, a breakpoint condition string, into a vector of tokens where
+   each token represents a component of the condition.  Tokens are first
+   parsed from the front of STR until we encounter an 'if' token.  At this
+   point tokens are parsed from the end of STR until we encounter an
+   unknown token, which we assume is the other end of the 'if' condition.
+   If when scanning forward we encounter an unknown token then the
+   remainder of STR is placed into a 'rest' token (the rest of the
+   string), and no backward scan is performed.  */
+
+static std::vector<token>
+parse_all_tokens (const char *str)
+{
+  gdb_assert (str != nullptr);
+
+  std::vector<token> forward_results;
+  std::vector<token> backward_results;
+
+  const char *cond_start = nullptr;
+  const char *cond_end = nullptr;
+  parse_direction direction = parse_direction::forward;
+  std::vector<token> *curr_results = &forward_results;
+  while (*str != '\0')
+    {
+      /* Find the next token.  If moving backward and this token starts at
+	 the same location as the condition then we must have found the
+	 other end of the condition string -- we're done.  */
+      std::string_view t = find_next_token (&str, direction);
+      if (direction == parse_direction::backward && t.data () <= cond_start)
+	{
+	  cond_end = &t.back ();
+	  break;
+	}
+
+      /* We only have a single flag option to check for.  All the other
+	 options take a value so require an additional token to be found.
+	 Additionally, we require that this flag be at least '-f', we
+	 don't allow it to be abbreviated to '-'.  */
+      if (t.length () > 1 && startswith ("-force-condition", t))
+	{
+	  curr_results->emplace_back (token::type::FORCE, t);
+	  continue;
+	}
+
+      /* Maybe the first token was the last token in the string.  If this
+	 is the case then we definitely can't try to extract a value
+	 token.  This also means that the token T is meaningless.  Reset
+	 TOK to point at the start of the unknown content and break out of
+	 the loop.  We'll record the unknown part of the string outside of
+	 the scanning loop (below).  */
+      if (direction == parse_direction::forward && *str == '\0')
+	{
+	  str = t.data ();
+	  break;
+	}
+
+      /* As before, find the next token and, if we are scanning backwards,
+	 check that we have not reached the start of the condition string.  */
+      std::string_view v = find_next_token (&str, direction);
+      if (direction == parse_direction::backward && v.data () <= cond_start)
+	{
+	  /* Use token T here as that must also be part of the condition
+	     string.  */
+	  cond_end = &t.back ();
+	  break;
+	}
+
+      /* When moving backward we will first parse the value token then the
+	 keyword token, so swap them now.  */
+      if (direction == parse_direction::backward)
+	std::swap (t, v);
+
+      /* Check for valid option in token T.  If we find a valid option then
+	 parse the value from the token V.  Except for 'if', that's handled
+	 differently.
+
+	 For the 'if' token we need to capture the entire condition
+	 string, so record the start of the condition string and then
+	 start scanning backwards looking for the end of the condition
+	 string.
+
+	 The order of these checks is important, at least the check for
+	 'thread' must occur before the check for 'task'.  We accept
+	 abbreviations of these token names, and 't' should resolve to
+	 'thread', which will only happen if we check 'thread' first.  */
+      if (direction == parse_direction::forward && startswith ("if", t))
+	{
+	  cond_start = v.data ();
+	  str = str + strlen (str);
+	  gdb_assert (*str == '\0');
+	  --str;
+	  direction = parse_direction::backward;
+	  curr_results = &backward_results;
+	  continue;
+	}
+      else if (startswith ("thread", t))
+	curr_results->emplace_back (token::type::THREAD, v);
+      else if (startswith ("inferior", t))
+	curr_results->emplace_back (token::type::INFERIOR, v);
+      else if (startswith ("task", t))
+	curr_results->emplace_back (token::type::TASK, v);
+      else
+	{
+	  /* An unknown token.  If we are scanning forward then reset TOK
+	     to point at the start of the unknown content, we record this
+	     outside of the scanning loop (below).
+
+	     If we are scanning backward then unknown content is assumed to
+	     be the other end of the condition string, obviously, this is
+	     just a heuristic, we could be looking at a mistyped command
+	     line, but this will be spotted when the condition is
+	     eventually evaluated.
+
+	     Either way, no more scanning is required after this.  */
+	  if (direction == parse_direction::forward)
+	    str = t.data ();
+	  else
+	    {
+	      gdb_assert (direction == parse_direction::backward);
+	      cond_end = &v.back ();
+	    }
+	  break;
+	}
+    }
+
+  if (cond_start != nullptr)
+    {
+      /* If we found the start of a condition string then we should have
+	 switched to backward scan mode, and found the end of the condition
+	 string.  Capture the whole condition string into COND_STRING
+	 now.  */
+      gdb_assert (direction == parse_direction::backward);
+      gdb_assert (cond_end != nullptr);
+
+      std::string_view v (cond_start, cond_end - cond_start + 1);
+
+      forward_results.emplace_back (token::type::CONDITION, v);
+    }
+  else if (*str != '\0')
+    {
+      /* If we didn't have a condition start pointer then we should still
+	 be in forward scanning mode.  If we didn't reach the end of the
+	 input string (TOK is not at the null character) then the rest of
+	 the input string is garbage that we didn't understand.
+
+	 Record the unknown content into REST.  The caller of this function
+	 will report this as an error later on.  We could report the error
+	 here, but we prefer to allow the caller to run other checks, and
+	 prioritise other errors before reporting this problem.  */
+      gdb_assert (direction == parse_direction::forward);
+      gdb_assert (cond_end == nullptr);
+
+      std::string_view v (str, strlen (str));
+
+      forward_results.emplace_back (token::type::REST, v);
+    }
+
+  /* If we have tokens in the BACKWARD_RESULTS vector then this means that
+     we found an 'if' condition (which will be the last thing in the
+     FORWARD_RESULTS vector), and then we started a backward scan.
+
+     The last tokens from the input string (those after the 'if' condition)
+     will be the first tokens added to the BACKWARD_RESULTS vector, so the
+     last items in the BACKWARD_RESULTS vector are those next to the 'if'
+     condition.
+
+     Check the tokens in the BACKWARD_RESULTS vector from back to front.
+     If the tokens look invalid then we assume that they are actually part
+     of the 'if' condition, and merge the token with the 'if' condition.
+     If it turns out that this was incorrect and that instead the user just
+     messed up entering the token value, then this will show as an error
+     when parsing the 'if' condition.
+
+     Doing this allows us to handle things like:
+
+       break function if ( variable == thread )
+
+     Where 'thread' is a local variable within 'function'.  When parsing
+     this we will initially see 'thread )' as a thread token with ')' as
+     the value.  However, the following code will spot that ')' is not a
+     valid thread-id, and so we merge 'thread )' into the 'if' condition
+     string.
+
+     This code also handles the special treatment for '-force-condition',
+     which exists for backwards compatibility reasons.  Traditionally this
+     flag, if it occurred immediately after the 'if' condition, would be
+     treated as part of the 'if' condition.  When the breakpoint condition
+     parsing code was rewritten, this behaviour was retained.  */
+  gdb_assert (backward_results.empty ()
+	      || (forward_results.back ().get_type ()
+		  == token::type::CONDITION));
+  while (!backward_results.empty ())
+    {
+      token &t = backward_results.back ();
+
+      if (t.get_type () == token::type::FORCE)
+	forward_results.back ().extend (std::move (t));
+      else if (t.get_type () == token::type::THREAD)
+	{
+	  const char *end;
+	  std::string v (t.get_value ());
+	  if (is_thread_id (v.c_str (), &end) && *end == '\0')
+	    break;
+	  forward_results.back ().extend (std::move (t));
+	}
+      else if (t.get_type () == token::type::INFERIOR
+	       || t.get_type () == token::type::TASK)
+	{
+	  /* Place the token's value into a null-terminated string, parse
+	     the string as a number and check that the entire string was
+	     parsed.  If this is true then this looks like a valid inferior
+	     or task number, otherwise, assume an invalid id, and merge
+	     this token with the 'if' token.  */
+	  char *end;
+	  std::string v (t.get_value ());
+	  (void) strtol (v.c_str (), &end, 0);
+	  if (end > v.c_str () && *end == '\0')
+	    break;
+	  forward_results.back ().extend (std::move (t));
+	}
+      else
+	gdb_assert_not_reached ("unexpected token type");
+
+      /* If we found an actual valid token above then we will have broken
+	 out of the loop.  We only get here if the token was merged with
+	 the 'if' condition, in which case we can discard the last token
+	 and then check the token before that.  */
+      backward_results.pop_back ();
+    }
+
+  /* If after the above checks we still have some tokens in the
+     BACKWARD_RESULTS vector, then these need to be appended to the
+     FORWARD_RESULTS vector.  However, we first reverse the order so that
+     FORWARD_RESULTS retains the tokens in the order they appeared in the
+     input string.  */
+  if (!backward_results.empty ())
+    forward_results.insert (forward_results.end (),
+			    backward_results.rbegin (),
+			    backward_results.rend ());
+
+  return forward_results;
+}
+
+/* Called when the global debug_breakpoint is true.  Prints VEC to the
+   debug output stream.  */
+
+static void
+dump_condition_tokens (const std::vector<token> &vec)
+{
+  gdb_assert (debug_breakpoint);
+
+  bool first = true;
+  std::string str = "Tokens: ";
+  for (const token &t : vec)
+    {
+      if (!first)
+	str += " ";
+      first = false;
+      str += t.to_string ();
+    }
+  breakpoint_debug_printf ("%s", str.c_str ());
+}
+
+/* See break-cond-parse.h.  */
+
+void
+create_breakpoint_parse_arg_string
+  (const char *str, gdb::unique_xmalloc_ptr<char> *cond_string_ptr,
+   int *thread_ptr, int *inferior_ptr, int *task_ptr,
+   gdb::unique_xmalloc_ptr<char> *rest_ptr, bool *force_ptr)
+{
+  /* Set up the defaults.  */
+  cond_string_ptr->reset ();
+  rest_ptr->reset ();
+  *thread_ptr = -1;
+  *inferior_ptr = -1;
+  *task_ptr = -1;
+  *force_ptr = false;
+
+  if (str == nullptr)
+    return;
+
+  /* Split STR into a series of tokens.  */
+  std::vector<token> tokens = parse_all_tokens (str);
+  if (debug_breakpoint)
+    dump_condition_tokens (tokens);
+
+  /* Temporary variables.  Initialised to the default state, then updated
+     as we parse TOKENS.  If all of TOKENS is parsed successfully then the
+     state from these variables is copied into the output arguments before
+     the function returns.  */
+  int thread = -1, inferior = -1, task = -1;
+  bool force = false;
+  gdb::unique_xmalloc_ptr<char> cond_string, rest;
+
+  for (const token &t : tokens)
+    {
+      switch (t.get_type ())
+	{
+	case token::type::FORCE:
+	  force = true;
+	  break;
+	case token::type::THREAD:
+	  {
+	    if (thread != -1)
+	      error ("You can specify only one thread.");
+	    if (task != -1 || inferior != -1)
+	      error ("You can specify only one of thread, inferior, or task.");
+	    const char *tmptok;
+	    thread_info *thr
+	      = parse_thread_id (std::string (t.get_value ()).c_str (),
+				 &tmptok);
+	    gdb_assert (*tmptok == '\0');
+	    thread = thr->global_num;
+	  }
+	  break;
+	case token::type::INFERIOR:
+	  {
+	    if (inferior != -1)
+	      error ("You can specify only one inferior.");
+	    if (task != -1 || thread != -1)
+	      error ("You can specify only one of thread, inferior, or task.");
+	    char *tmptok;
+	    long inferior_id
+	      = strtol (std::string (t.get_value ()).c_str (), &tmptok, 0);
+	    if (*tmptok != '\0')
+	      error (_("Junk '%s' after inferior keyword."), tmptok);
+	    if (inferior_id > INT_MAX)
+	      error (_("No inferior number '%ld'"), inferior_id);
+	    inferior = static_cast<int> (inferior_id);
+	    struct inferior *inf = find_inferior_id (inferior);
+	    if (inf == nullptr)
+	      error (_("No inferior number '%d'"), inferior);
+	  }
+	  break;
+	case token::type::TASK:
+	  {
+	    if (task != -1)
+	      error ("You can specify only one task.");
+	    if (inferior != -1 || thread != -1)
+	      error ("You can specify only one of thread, inferior, or task.");
+	    char *tmptok;
+	    long task_id
+	      = strtol (std::string (t.get_value ()).c_str (), &tmptok, 0);
+	    if (*tmptok != '\0')
+	      error (_("Junk '%s' after task keyword."), tmptok);
+	    if (task_id > INT_MAX)
+	      error (_("Unknown task %ld"), task_id);
+	    task = static_cast<int> (task_id);
+	    if (!valid_task_id (task))
+	      error (_("Unknown task %d."), task);
+	  }
+	  break;
+	case token::type::CONDITION:
+	  cond_string.reset (savestring (t.get_value ().data (),
+					 t.get_value ().size ()));
+	  break;
+	case token::type::REST:
+	  rest.reset (savestring (t.get_value ().data (),
+				  t.get_value ().size ()));
+	  break;
+	}
+    }
+
+  /* Move results into the output locations.  */
+  *force_ptr = force;
+  *thread_ptr = thread;
+  *inferior_ptr = inferior;
+  *task_ptr = task;
+  rest_ptr->reset (rest.release ());
+  cond_string_ptr->reset (cond_string.release ());
+}
+
+#if GDB_SELF_TEST
+
+namespace selftests {
+
+/* Run a single test of the create_breakpoint_parse_arg_string function.
+   INPUT is passed to create_breakpoint_parse_arg_string while all other
+   arguments are the expected output from
+   create_breakpoint_parse_arg_string.  */
+
+static void
+test (const char *input, const char *condition, int thread = -1,
+      int inferior = -1, int task = -1, bool force = false,
+      const char *rest = nullptr, const char *error_msg = nullptr)
+{
+  gdb::unique_xmalloc_ptr<char> extracted_condition;
+  gdb::unique_xmalloc_ptr<char> extracted_rest;
+  int extracted_thread, extracted_inferior, extracted_task;
+  bool extracted_force_condition;
+  std::string exception_msg, error_str;
+
+  if (error_msg != nullptr)
+    error_str = std::string (error_msg) + "\n";
+
+  try
+    {
+      create_breakpoint_parse_arg_string (input, &extracted_condition,
+					  &extracted_thread,
+					  &extracted_inferior,
+					  &extracted_task, &extracted_rest,
+					  &extracted_force_condition);
+    }
+  catch (const gdb_exception_error &ex)
+    {
+      string_file buf;
+
+      exception_print (&buf, ex);
+      exception_msg = buf.release ();
+    }
+
+  if ((condition == nullptr) != (extracted_condition.get () == nullptr)
+      || (condition != nullptr
+	  && strcmp (condition, extracted_condition.get ()) != 0)
+      || (rest == nullptr) != (extracted_rest.get () == nullptr)
+      || (rest != nullptr && strcmp (rest, extracted_rest.get ()) != 0)
+      || thread != extracted_thread
+      || inferior != extracted_inferior
+      || task != extracted_task
+      || force != extracted_force_condition
+      || exception_msg != error_str)
+    {
+      if (run_verbose ())
+	{
+	  debug_printf ("input: '%s'\n", input);
+	  debug_printf ("condition: '%s'\n", extracted_condition.get ());
+	  debug_printf ("rest: '%s'\n", extracted_rest.get ());
+	  debug_printf ("thread: %d\n", extracted_thread);
+	  debug_printf ("inferior: %d\n", extracted_inferior);
+	  debug_printf ("task: %d\n", extracted_task);
+	  debug_printf ("forced: %s\n",
+			extracted_force_condition ? "true" : "false");
+	  debug_printf ("exception: '%s'\n", exception_msg.c_str ());
+	}
+
+      /* Report the failure.  */
+      SELF_CHECK (false);
+    }
+}
+
+/* Wrapper for test function.  Pass through the default values for all
+   parameters, except the last parameter, which indicates that we expect
+   INPUT to trigger an error.  */
+
+static void
+test_error (const char *input, const char *error_msg)
+{
+  test (input, nullptr, -1, -1, -1, false, nullptr, error_msg);
+}
+
+/* Test the create_breakpoint_parse_arg_string function.  Just wraps
+   multiple calls to the test function above.  */
+
+static void
+create_breakpoint_parse_arg_string_tests ()
+{
+  gdbarch *arch = current_inferior ()->arch ();
+  scoped_restore_current_pspace_and_thread restore;
+  scoped_mock_context<test_target_ops> mock_target (arch);
+
+  int global_thread_num = mock_target.mock_thread.global_num;
+
+  /* Test parsing valid breakpoint condition strings.  */
+  test ("  if blah  ", "blah");
+  test (" if blah thread 1", "blah", global_thread_num);
+  test (" if blah inferior 1", "blah", -1, 1);
+  test (" if blah thread 1  ", "blah", global_thread_num);
+  test ("thread 1 woof", nullptr, global_thread_num, -1, -1, false, "woof");
+  test ("thread 1 X", nullptr, global_thread_num, -1, -1, false, "X");
+  test (" if blah thread 1 -force-condition", "blah", global_thread_num,
+	-1, -1, true);
+  test (" -force-condition if blah thread 1", "blah", global_thread_num,
+	-1, -1, true);
+  test (" -force-condition if blah thread 1  ", "blah", global_thread_num,
+	-1, -1, true);
+  test ("thread 1 -force-condition if blah", "blah", global_thread_num,
+	-1, -1, true);
+  test ("if (A::outer::func ())", "(A::outer::func ())");
+  test ("if ( foo == thread )", "( foo == thread )");
+  test ("if ( foo == thread ) inferior 1", "( foo == thread )", -1, 1);
+  test ("if ( foo == thread ) thread 1", "( foo == thread )",
+	global_thread_num);
+  test ("if foo == thread", "foo == thread");
+  test ("if foo == thread 1", "foo ==", global_thread_num);
+
+  /* Test parsing some invalid breakpoint condition strings.  */
+  test_error ("thread 1 if foo == 123 thread 1",
+	      "You can specify only one thread.");
+  test_error ("thread 1 if foo == 123 inferior 1",
+	      "You can specify only one of thread, inferior, or task.");
+  test_error ("thread 1 if foo == 123 task 1",
+	      "You can specify only one of thread, inferior, or task.");
+  test_error ("inferior 1 if foo == 123 inferior 1",
+	      "You can specify only one inferior.");
+  test_error ("inferior 1 if foo == 123 thread 1",
+	      "You can specify only one of thread, inferior, or task.");
+  test_error ("inferior 1 if foo == 123 task 1",
+	      "You can specify only one of thread, inferior, or task.");
+  test_error ("thread 1.2.3", "Invalid thread ID: 1.2.3");
+  test_error ("thread 1/2", "Invalid thread ID: 1/2");
+  test_error ("thread 1xxx", "Invalid thread ID: 1xxx");
+  test_error ("inferior 1xxx", "Junk 'xxx' after inferior keyword.");
+  test_error ("task 1xxx", "Junk 'xxx' after task keyword.");
+}
+
+} // namespace selftests
+#endif /* GDB_SELF_TEST */
+
+void _initialize_break_cond_parse ();
+void
+_initialize_break_cond_parse ()
+{
+#if GDB_SELF_TEST
+  selftests::register_test
+    ("create_breakpoint_parse_arg_string",
+     selftests::create_breakpoint_parse_arg_string_tests);
+#endif
+}
diff --git a/gdb/break-cond-parse.h b/gdb/break-cond-parse.h
new file mode 100644
index 00000000000..cbee70f4e9e
--- /dev/null
+++ b/gdb/break-cond-parse.h
@@ -0,0 +1,52 @@
+/* Copyright (C) 2023 Free Software Foundation, Inc.
+
+   This file is part of GDB.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#if !defined (BREAK_COND_PARSE_H)
+#define BREAK_COND_PARSE_H 1
+
+/* Given TOK, a string possibly containing a condition, thread, inferior,
+   task and force-condition flag, as accepted by the 'break' command,
+   extract the condition string, thread, inferior, task number, and the
+   force_condition flag, then set *COND_STRING, *THREAD, *INFERIOR, *TASK,
+   and *FORCE.
+
+   As TOK is parsed, if an unknown keyword is encountered before the 'if'
+   keyword then everything starting from the unknown keyword is placed into
+   *REST.
+
+   Both *COND and *REST are initialized to nullptr.  If no 'if' keyword is
+   found then *COND will be returned as nullptr.  If no unknown content is
+   found then *REST is returned as nullptr.
+
+   If no thread is found, *THREAD is set to -1.  If no inferior is found,
+   *INFERIOR is set to -1.  If no task is found, *TASK is set to -1.  If
+   the -force-condition flag is not found then *FORCE is set to false.
+
+   Due to the free-form nature that the string TOK might take (a 'thread'
+   keyword can appear before or after an 'if' condition) then we end up
+   having to check for keywords from both the start of TOK and the end of
+   TOK.
+
+   If TOK is nullptr, or TOK is the empty string, then the output variables
+   are all given their default values.  */
+
+extern void create_breakpoint_parse_arg_string
+  (const char *tok, gdb::unique_xmalloc_ptr<char> *cond_string,
+   int *thread, int *inferior, int *task,
+   gdb::unique_xmalloc_ptr<char> *rest, bool *force);
+
+#endif
diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 8a2a0cc7100..7bcdaa7ddf1 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -69,6 +69,7 @@
 #include "cli/cli-style.h"
 #include "cli/cli-decode.h"
 #include <unordered_set>
+#include "break-cond-parse.h"
 
 /* readline include files */
 #include "readline/tilde.h"
@@ -6319,20 +6320,7 @@ print_breakpoint_location (const breakpoint *b, const bp_location *loc)
       uiout->field_stream ("at", stb);
     }
   else
-    {
-      uiout->field_string ("pending", b->locspec->to_string ());
-      /* If extra_string is available, it could be holding a condition
-	 or dprintf arguments.  In either case, make sure it is printed,
-	 too, but only for non-MI streams.  */
-      if (!uiout->is_mi_like_p () && b->extra_string != NULL)
-	{
-	  if (b->type == bp_dprintf)
-	    uiout->text (",");
-	  else
-	    uiout->text (" ");
-	  uiout->text (b->extra_string.get ());
-	}
-    }
+    uiout->field_string ("pending", b->locspec->to_string ());
 
   if (loc && is_breakpoint (b)
       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
@@ -8697,8 +8685,8 @@ code_breakpoint::code_breakpoint (struct gdbarch *gdbarch_,
      command line, otherwise it's an error.  */
   if (type == bp_dprintf)
     update_dprintf_command_list (this);
-  else if (extra_string != nullptr)
-    error (_("Garbage '%s' at end of command"), extra_string.get ());
+  else
+    gdb_assert (extra_string == nullptr);
 
   /* The order of the locations is now stable.  Set the location
      condition using the location's number.  */
@@ -8927,197 +8915,6 @@ check_fast_tracepoint_sals (struct gdbarch *gdbarch,
     }
 }
 
-/* Given TOK, a string specification of condition and thread, as accepted
-   by the 'break' command, extract the condition string into *COND_STRING.
-   If no condition string is found then *COND_STRING is set to nullptr.
-
-   If the breakpoint specification has an associated thread, task, or
-   inferior, these are extracted into *THREAD, *TASK, and *INFERIOR
-   respectively, otherwise these arguments are set to -1 (for THREAD and
-   INFERIOR) or 0 (for TASK).
-
-   PC identifies the context at which the condition should be parsed.  */
-
-static void
-find_condition_and_thread (const char *tok, CORE_ADDR pc,
-			   gdb::unique_xmalloc_ptr<char> *cond_string,
-			   int *thread, int *inferior, int *task,
-			   gdb::unique_xmalloc_ptr<char> *rest)
-{
-  cond_string->reset ();
-  *thread = -1;
-  *inferior = -1;
-  *task = -1;
-  rest->reset ();
-  bool force = false;
-
-  while (tok && *tok)
-    {
-      const char *end_tok;
-      int toklen;
-      const char *cond_start = NULL;
-      const char *cond_end = NULL;
-
-      tok = skip_spaces (tok);
-
-      if ((*tok == '"' || *tok == ',') && rest)
-	{
-	  rest->reset (savestring (tok, strlen (tok)));
-	  break;
-	}
-
-      end_tok = skip_to_space (tok);
-
-      toklen = end_tok - tok;
-
-      if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
-	{
-	  tok = cond_start = end_tok + 1;
-	  try
-	    {
-	      parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
-	    }
-	  catch (const gdb_exception_error &)
-	    {
-	      if (!force)
-		throw;
-	      else
-		tok = tok + strlen (tok);
-	    }
-	  cond_end = tok;
-	  cond_string->reset (savestring (cond_start, cond_end - cond_start));
-	}
-      else if (toklen >= 1 && strncmp (tok, "-force-condition", toklen) == 0)
-	{
-	  tok = tok + toklen;
-	  force = true;
-	}
-      else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
-	{
-	  const char *tmptok;
-	  struct thread_info *thr;
-
-	  if (*thread != -1)
-	    error(_("You can specify only one thread."));
-
-	  if (*task != -1)
-	    error (_("You can specify only one of thread or task."));
-
-	  if (*inferior != -1)
-	    error (_("You can specify only one of inferior or thread."));
-
-	  tok = end_tok + 1;
-	  thr = parse_thread_id (tok, &tmptok);
-	  if (tok == tmptok)
-	    error (_("Junk after thread keyword."));
-	  *thread = thr->global_num;
-	  tok = tmptok;
-	}
-      else if (toklen >= 1 && strncmp (tok, "inferior", toklen) == 0)
-	{
-	  if (*inferior != -1)
-	    error(_("You can specify only one inferior."));
-
-	  if (*task != -1)
-	    error (_("You can specify only one of inferior or task."));
-
-	  if (*thread != -1)
-	    error (_("You can specify only one of inferior or thread."));
-
-	  char *tmptok;
-	  tok = end_tok + 1;
-	  *inferior = strtol (tok, &tmptok, 0);
-	  if (tok == tmptok)
-	    error (_("Junk after inferior keyword."));
-	  if (!valid_global_inferior_id (*inferior))
-	    error (_("Unknown inferior number %d."), *inferior);
-	  tok = tmptok;
-	}
-      else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
-	{
-	  char *tmptok;
-
-	  if (*task != -1)
-	    error(_("You can specify only one task."));
-
-	  if (*thread != -1)
-	    error (_("You can specify only one of thread or task."));
-
-	  if (*inferior != -1)
-	    error (_("You can specify only one of inferior or task."));
-
-	  tok = end_tok + 1;
-	  *task = strtol (tok, &tmptok, 0);
-	  if (tok == tmptok)
-	    error (_("Junk after task keyword."));
-	  if (!valid_task_id (*task))
-	    error (_("Unknown task %d."), *task);
-	  tok = tmptok;
-	}
-      else if (rest)
-	{
-	  rest->reset (savestring (tok, strlen (tok)));
-	  break;
-	}
-      else
-	error (_("Junk at end of arguments."));
-    }
-}
-
-/* Call 'find_condition_and_thread' for each sal in SALS until a parse
-   succeeds.  The parsed values are written to COND_STRING, THREAD,
-   TASK, and REST.  See the comment of 'find_condition_and_thread'
-   for the description of these parameters and INPUT.  */
-
-static void
-find_condition_and_thread_for_sals (const std::vector<symtab_and_line> &sals,
-				    const char *input,
-				    gdb::unique_xmalloc_ptr<char> *cond_string,
-				    int *thread, int *inferior, int *task,
-				    gdb::unique_xmalloc_ptr<char> *rest)
-{
-  int num_failures = 0;
-  for (auto &sal : sals)
-    {
-      gdb::unique_xmalloc_ptr<char> cond;
-      int thread_id = -1;
-      int inferior_id = -1;
-      int task_id = -1;
-      gdb::unique_xmalloc_ptr<char> remaining;
-
-      /* Here we want to parse 'arg' to separate condition from thread
-	 number.  But because parsing happens in a context and the
-	 contexts of sals might be different, try each until there is
-	 success.  Finding one successful parse is sufficient for our
-	 goal.  When setting the breakpoint we'll re-parse the
-	 condition in the context of each sal.  */
-      try
-	{
-	  find_condition_and_thread (input, sal.pc, &cond, &thread_id,
-				     &inferior_id, &task_id, &remaining);
-	  *cond_string = std::move (cond);
-	  /* A value of -1 indicates that these fields are unset.  At most
-	     one of these fields should be set (to a value other than -1)
-	     at this point.  */
-	  gdb_assert (((thread_id == -1 ? 1 : 0)
-		       + (task_id == -1 ? 1 : 0)
-		       + (inferior_id == -1 ? 1 : 0)) >= 2);
-	  *thread = thread_id;
-	  *inferior = inferior_id;
-	  *task = task_id;
-	  *rest = std::move (remaining);
-	  break;
-	}
-      catch (const gdb_exception_error &e)
-	{
-	  num_failures++;
-	  /* If no sal remains, do not continue.  */
-	  if (num_failures == sals.size ())
-	    throw;
-	}
-    }
-}
-
 /* Decode a static tracepoint marker spec.  */
 
 static std::vector<symtab_and_line>
@@ -9234,6 +9031,46 @@ create_breakpoint (struct gdbarch *gdbarch,
 	      ? (extra_string != nullptr && !parse_extra)
 	      : (extra_string == nullptr || parse_extra));
 
+  /* Will hold either copies of the similarly named function argument, or
+     will hold a modified version of the function argument, depending on
+     the value of PARSE_EXTRA.  */
+  gdb::unique_xmalloc_ptr<char> cond_string_copy;
+  gdb::unique_xmalloc_ptr<char> extra_string_copy;
+
+  if (parse_extra)
+    {
+      /* Parse EXTRA_STRING splitting the parts out.  */
+      create_breakpoint_parse_arg_string (extra_string, &cond_string_copy,
+					  &thread, &inferior, &task,
+					  &extra_string_copy,
+					  &force_condition);
+
+      /* We could check that EXTRA_STRING_COPY is empty at this point -- it
+	 should be, as we only get here for things that are not bp_dprintf,
+	 however, we prefer to give the location spec parser a chance to
+	 run first, this means the user will get errors about invalid
+	 location spec instead of an error about garbage at the end of the
+	 command line.
+
+	 We still do the EXTRA_STRING_COPY is empty check, just later in
+	 this function.  */
+
+      gdb_assert (thread == -1 || thread > 0);
+      gdb_assert (task == -1 || task > 0);
+      gdb_assert (inferior == -1 || inferior > 0);
+    }
+  else
+    {
+      if (cond_string != nullptr)
+	cond_string_copy.reset (xstrdup (cond_string));
+      if (extra_string != nullptr)
+	extra_string_copy.reset (xstrdup (extra_string));
+    }
+
+  /* Clear these.  Updated values are now held in the *_copy locals.  */
+  cond_string = nullptr;
+  extra_string = nullptr;
+
   try
     {
       ops->create_sals_from_location_spec (locspec, &canonical);
@@ -9269,6 +9106,13 @@ create_breakpoint (struct gdbarch *gdbarch,
 	throw;
     }
 
+  /* Only bp_dprintf breakpoints should have anything in EXTRA_STRING_COPY
+     by this point.  For all other breakpoints this indicates an error.  We
+     could place this check earlier in the function, but we prefer to see
+     errors from the location spec parser before we see this error message.  */
+  if (type_wanted != bp_dprintf && extra_string_copy.get () != nullptr)
+    error (_("Garbage '%s' at end of command"), extra_string_copy.get ());
+
   if (!pending && canonical.lsals.empty ())
     return 0;
 
@@ -9292,63 +9136,31 @@ create_breakpoint (struct gdbarch *gdbarch,
      breakpoint.  */
   if (!pending)
     {
-      gdb::unique_xmalloc_ptr<char> cond_string_copy;
-      gdb::unique_xmalloc_ptr<char> extra_string_copy;
-
-      if (parse_extra)
+      /* Check the validity of the condition.  We should error out if the
+	 condition is invalid at all of the locations and if it is not
+	 forced.  In the PARSE_EXTRA case above, this check is done when
+	 parsing the EXTRA_STRING.  */
+      if (cond_string_copy.get () != nullptr && !force_condition)
 	{
-	  gdb_assert (type_wanted != bp_dprintf);
-
-	  gdb::unique_xmalloc_ptr<char> rest;
-	  gdb::unique_xmalloc_ptr<char> cond;
-
+	  int num_failures = 0;
 	  const linespec_sals &lsal = canonical.lsals[0];
-
-	  find_condition_and_thread_for_sals (lsal.sals, extra_string,
-					      &cond, &thread, &inferior,
-					      &task, &rest);
-
-	  if (rest.get () != nullptr && *(rest.get ()) != '\0')
-	    error (_("Garbage '%s' at end of command"), rest.get ());
-
-	  cond_string_copy = std::move (cond);
-	  extra_string_copy = std::move (rest);
-	}
-      else
-	{
-	  /* Check the validity of the condition.  We should error out
-	     if the condition is invalid at all of the locations and
-	     if it is not forced.  In the PARSE_EXTRA case above, this
-	     check is done when parsing the EXTRA_STRING.  */
-	  if (cond_string != nullptr && !force_condition)
+	  for (const auto &sal : lsal.sals)
 	    {
-	      int num_failures = 0;
-	      const linespec_sals &lsal = canonical.lsals[0];
-	      for (const auto &sal : lsal.sals)
+	      const char *cond = cond_string_copy.get ();
+	      try
 		{
-		  const char *cond = cond_string;
-		  try
-		    {
-		      parse_exp_1 (&cond, sal.pc, block_for_pc (sal.pc), 0);
-		      /* One success is sufficient to keep going.  */
-		      break;
-		    }
-		  catch (const gdb_exception_error &)
-		    {
-		      num_failures++;
-		      /* If this is the last sal, error out.  */
-		      if (num_failures == lsal.sals.size ())
-			throw;
-		    }
+		  parse_exp_1 (&cond, sal.pc, block_for_pc (sal.pc), 0);
+		  /* One success is sufficient to keep going.  */
+		  break;
+		}
+	      catch (const gdb_exception_error &)
+		{
+		  num_failures++;
+		  /* If this is the last sal, error out.  */
+		  if (num_failures == lsal.sals.size ())
+		    throw;
 		}
 	    }
-
-	  /* Create a private copy of condition string.  */
-	  if (cond_string)
-	    cond_string_copy.reset (xstrdup (cond_string));
-	  /* Create a private copy of any extra string.  */
-	  if (extra_string)
-	    extra_string_copy.reset (xstrdup (extra_string));
 	}
 
       ops->create_breakpoints_sal (gdbarch, &canonical,
@@ -9365,21 +9177,16 @@ create_breakpoint (struct gdbarch *gdbarch,
 								 type_wanted);
       b->locspec = locspec->clone ();
 
-      if (parse_extra)
-	b->cond_string = NULL;
-      else
-	{
-	  /* Create a private copy of condition string.  */
-	  b->cond_string.reset (cond_string != NULL
-				? xstrdup (cond_string)
-				: NULL);
-	  b->thread = thread;
-	}
+      /* Create a private copy of the condition string.  */
+      b->cond_string = std::move (cond_string_copy);
+
+      b->thread = thread;
+      b->task = task;
+      b->inferior = inferior;
 
       /* Create a private copy of any extra string.  */
-      b->extra_string.reset (extra_string != NULL
-			     ? xstrdup (extra_string)
-			     : NULL);
+      b->extra_string = std::move (extra_string_copy);
+
       b->ignore_count = ignore_count;
       b->disposition = tempflag ? disp_del : disp_donttouch;
       b->condition_not_parsed = 1;
@@ -9388,9 +9195,12 @@ create_breakpoint (struct gdbarch *gdbarch,
 	   && type_wanted != bp_hardware_breakpoint) || thread != -1)
 	b->pspace = current_program_space;
 
+      if (b->type == bp_dprintf)
+	update_dprintf_command_list (b.get ());
+
       install_breakpoint (internal, std::move (b), 0);
     }
-  
+
   if (canonical.lsals.size () > 1)
     {
       warning (_("Multiple breakpoints were set.\nUse the "
@@ -13121,24 +12931,6 @@ code_breakpoint::location_spec_to_sals (location_spec *locspec,
     {
       for (auto &sal : sals)
 	resolve_sal_pc (&sal);
-      if (condition_not_parsed && extra_string != NULL)
-	{
-	  gdb::unique_xmalloc_ptr<char> local_cond, local_extra;
-	  int local_thread, local_task, local_inferior;
-
-	  find_condition_and_thread_for_sals (sals, extra_string.get (),
-					      &local_cond, &local_thread,
-					      &local_inferior,
-					      &local_task, &local_extra);
-	  gdb_assert (cond_string == nullptr);
-	  if (local_cond != nullptr)
-	    cond_string = std::move (local_cond);
-	  thread = local_thread;
-	  task = local_task;
-	  if (local_extra != nullptr)
-	    extra_string = std::move (local_extra);
-	  condition_not_parsed = 0;
-	}
 
       if (type == bp_static_tracepoint)
 	{
diff --git a/gdb/testsuite/gdb.ada/tasks.exp b/gdb/testsuite/gdb.ada/tasks.exp
index 6e588408c9d..ecbfbd5522f 100644
--- a/gdb/testsuite/gdb.ada/tasks.exp
+++ b/gdb/testsuite/gdb.ada/tasks.exp
@@ -55,11 +55,11 @@ gdb_test "watch j task 1 task 3" "You can specify only one task\\."
 
 # Check that attempting to combine 'task' and 'thread' gives an error.
 gdb_test "break break_me task 1 thread 1" \
-    "You can specify only one of thread or task\\."
+    "You can specify only one of thread, inferior, or task\\."
 gdb_test "break break_me thread 1 task 1" \
-    "You can specify only one of thread or task\\."
+    "You can specify only one of thread, inferior, or task\\."
 gdb_test "break break_me inferior 1 task 1" \
-    "You can specify only one of inferior or task\\."
+    "You can specify only one of thread, inferior, or task\\."
 gdb_test "watch j task 1 thread 1" \
     "You can specify only one of thread or task\\."
 gdb_test "watch j thread 1 task 1" \
diff --git a/gdb/testsuite/gdb.base/condbreak.exp b/gdb/testsuite/gdb.base/condbreak.exp
index 65d19b3e7a9..3b619e47bfc 100644
--- a/gdb/testsuite/gdb.base/condbreak.exp
+++ b/gdb/testsuite/gdb.base/condbreak.exp
@@ -179,6 +179,10 @@ gdb_test "break -q main if (1==1) thread 999" \
     "Unknown thread 999\\."
 gdb_test "break -q main thread 999 if (1==1)" \
     "Unknown thread 999\\."
+gdb_test "break -q main if (1==1) thread 999 -force-condition" \
+    "Unknown thread 999\\."
+gdb_test "break -q main thread 999 if (1==1) -force-condition" \
+    "Unknown thread 999\\."
 
 # Verify that both if and thread can be distinguished from a breakpoint
 # address expression.
@@ -186,20 +190,71 @@ gdb_test "break *main if (1==1) thread 999" \
     "Unknown thread 999\\."
 gdb_test "break *main thread 999 if (1==1)" \
     "Unknown thread 999\\."
+gdb_test "break *main if (1==1) thread 999 -force-condition" \
+    "Unknown thread 999\\."
+gdb_test "break *main thread 999 if (1==1) -force-condition" \
+    "Unknown thread 999\\."
 
 # Similarly for task.
 gdb_test "break *main if (1==1) task 999" \
     "Unknown task 999\\."
 gdb_test "break *main task 999 if (1==1)" \
     "Unknown task 999\\."
+gdb_test "break *main if (1==1) task 999 -force-condition" \
+    "Unknown task 999\\."
+gdb_test "break *main task 999 if (1==1) -force-condition" \
+    "Unknown task 999\\."
 
-# GDB accepts abbreviations for "thread" and "task".
+# GDB accepts abbreviations for "thread", "task" and
+# "-force-condition", when these keywords appear after
+# the breakpoint condition.
 gdb_test "break *main if (1==1) t 999" \
     "Unknown thread 999\\."
 gdb_test "break *main if (1==1) th 999" \
     "Unknown thread 999\\."
 gdb_test "break *main if (1==1) ta 999" \
     "Unknown task 999\\."
+gdb_test "break *main if (1==1) t 999 -force" \
+    "Unknown thread 999\\."
+gdb_test "break *main if (1==1) th 999 -force" \
+    "Unknown thread 999\\."
+gdb_test "break *main if (1==1) ta 999 -force" \
+    "Unknown task 999\\."
+
+# Check the use of abbreviations before the condition.  This works
+# because, when the location spec starts with '*' GDB is able to
+# figure out that the complete location is '*main'.
+gdb_test "break *main t 999 if (1==1)" \
+    "Unknown thread 999\\."
+gdb_test "break *main th 999 if (1==1)" \
+    "Unknown thread 999\\."
+gdb_test "break *main ta 999 if (1==1)" \
+    "Unknown task 999\\."
+gdb_test "break *main t 999 -force if (1==1)" \
+    "Unknown thread 999\\."
+gdb_test "break *main th 999 -force if (1==1)" \
+    "Unknown thread 999\\."
+gdb_test "break *main ta 999 -force if (1==1)" \
+    "Unknown task 999\\."
+
+# However, when the location spec doesn't start with '*' GDB relies on
+# the linespec parser to spot the keyword which marks the end of the
+# linespec, and this parser doesn't check for abbreviations.
+gdb_test "with breakpoint pending off -- break main t 999 if (1==1)" \
+    "Function \"main t 999\" not defined\\."
+gdb_test "with breakpoint pending off -- break main th 999 if (1==1)" \
+    "Function \"main th 999\" not defined\\."
+gdb_test "with breakpoint pending off -- break main ta 999 if (1==1)" \
+    "Function \"main ta 999\" not defined\\."
+
+# GDB does not treat a "-force-condition" flag that appears
+# immediately after the condition as the flag, but instead treats it
+# as " - force - condition", that is, subtraction of the symbol
+# "force" followed by subtraction of symbol "context".  This is really
+# just a quirk of how this used to be implemented, and should maybe be
+# changed in the future.  However, for now GDB retains this behaviour.
+gdb_test "break *main if (1==1) -force-condition" \
+    "No symbol \"force\" in current context\\."
 
 set test "run until breakpoint at marker3"
 gdb_test_multiple "continue" $test {
diff --git a/gdb/testsuite/gdb.base/pending.exp b/gdb/testsuite/gdb.base/pending.exp
index 737b0c4e5d0..0cb86377400 100644
--- a/gdb/testsuite/gdb.base/pending.exp
+++ b/gdb/testsuite/gdb.base/pending.exp
@@ -170,7 +170,8 @@ gdb_test "info break" \
 \[\t \]+stop only if k == 1.*
 \[\t \]+print k.*
 \[0-9\]+\[\t \]+breakpoint     keep y.* in main at .*$srcfile:$mainline.*
-\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc if x > 3.*" \
+\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc.*
+\\s+stop only if x > 3.*" \
 "multiple pending breakpoints"
 
 
@@ -195,8 +196,10 @@ gdb_test "info break" \
 \[\t \]+stop only if k == 1.*
 \[\t \]+print k.*
 \[0-9\]+\[\t \]+breakpoint     keep y.* in main at .*$srcfile:$mainline.*
-\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc if x > 3.*
-\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp3_loc.*ignore next 2 hits.*" \
+\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp2_loc.*
+\\s+stop only if x > 3.*
+\[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*pendshr.c:$bp3_loc.*
+\\s+ignore next 2 hits.*" \
 "multiple pending breakpoints 2"
 
 #
@@ -267,3 +270,17 @@ gdb_test "info break" \
 \[0-9\]+\[\t \]+breakpoint     keep y.* in main at .*$srcfile:$mainline.*
 \[0-9\]+\[\t \]+breakpoint     keep y.*PENDING.*imaginary.*" \
 "verify pending breakpoint after restart"
+
+# Test GDB's parsing of pending breakpoint thread and condition.
+
+gdb_test_no_output "set breakpoint pending on"
+gdb_test "break foo if (unknown_var && another_unknown_var) thread 1" \
+    "Breakpoint $decimal \\(foo\\) pending\\."
+set bpnum [get_integer_valueof "\$bpnum" "*INVALID" \
+	       "get number for foo breakpoint"]
+gdb_test "info breakpoints $bpnum" \
+    [multi_line \
+	 "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	 "\\s+stop only if \\(unknown_var && another_unknown_var\\)" \
+	 "\\s+stop only in thread 1"] \
+    "check pending breakpoint on foo"
diff --git a/gdb/testsuite/gdb.linespec/explicit.exp b/gdb/testsuite/gdb.linespec/explicit.exp
index 625f9cee0fc..9a11182fae7 100644
--- a/gdb/testsuite/gdb.linespec/explicit.exp
+++ b/gdb/testsuite/gdb.linespec/explicit.exp
@@ -575,7 +575,7 @@ namespace eval $testfile {
 	      allow-pending]} {
 	fail "set $tst"
     } else {
-	gdb_test "info break" ".*PENDING.*myfunction if foofoofoo == 1.*" $tst
+	gdb_test "info break" ".*PENDING.*myfunction\r\n\\s+stop only if foofoofoo == 1.*" $tst
     }
 
     gdb_exit
@@ -586,7 +586,7 @@ namespace eval $testfile {
 	      allow-pending]} {
 	fail "set $tst"
     } else {
-	gdb_test "info break" ".*PENDING.*myfunction if arg == 0" $tst
+	gdb_test "info break" ".*PENDING.*myfunction\r\n\\s+stop only if arg == 0" $tst
 
 	gdb_load [standard_output_file $exefile]
 	gdb_test "info break" \
diff --git a/gdb/testsuite/gdb.linespec/keywords.exp b/gdb/testsuite/gdb.linespec/keywords.exp
index 36a919c8be2..d2596d2b357 100644
--- a/gdb/testsuite/gdb.linespec/keywords.exp
+++ b/gdb/testsuite/gdb.linespec/keywords.exp
@@ -55,7 +55,7 @@ with_test_prefix "trailing whitespace" {
 gdb_test "break thread 123" "Unknown thread 123\\."
 gdb_test "break thread foo" "Invalid thread ID: foo"
 gdb_test "break task 123" "Unknown task 123\\."
-gdb_test "break task foo" "Junk after task keyword\\."
+gdb_test "break task foo" "Junk 'foo' after task keyword\\."
 gdb_breakpoint "thread if 0" "message"
 
 # These are also NULL locations, but using a subsequent keyword
@@ -63,9 +63,9 @@ gdb_breakpoint "thread if 0" "message"
 gdb_test "break thread thread" "Invalid thread ID: thread"
 gdb_test "break thread task" "Invalid thread ID: task"
 gdb_test "break thread if" "Invalid thread ID: if"
-gdb_test "break task task" "Junk after task keyword\\."
-gdb_test "break task thread" "Junk after task keyword\\."
-gdb_test "break task if" "Junk after task keyword\\."
+gdb_test "break task task" "Junk 'task' after task keyword\\."
+gdb_test "break task thread" "Junk 'thread' after task keyword\\."
+gdb_test "break task if" "Junk 'if' after task keyword\\."
 
 # Test locations containing keyword followed by keyword.
 gdb_test "break thread thread 123" "Unknown thread 123\\."
diff --git a/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp b/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp
index fd5684bd2b1..4cf6dec4b41 100644
--- a/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp
+++ b/gdb/testsuite/gdb.mi/mi-dprintf-pending.exp
@@ -50,7 +50,8 @@ set bp_location1 [gdb_get_line_number "set breakpoint 1 here"]
 # Set pending dprintf via MI.
 set bp [mi_make_breakpoint_pending -number "1" -type "dprintf" \
 	    -disp "keep" -enabled "y" -pending "pendfunc1" \
-	    -original-location "pendfunc1"]
+	    -original-location "pendfunc1" \
+	    -script {\["printf \\\"hello\\\""\]}]
 mi_gdb_test "-dprintf-insert -f pendfunc1 \"hello\"" \
     ".*\\^done,$bp" "mi set dprintf"
 
diff --git a/gdb/testsuite/gdb.multi/inferior-specific-bp.exp b/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
index 5cc451b0ecc..46efe6f54bc 100644
--- a/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
+++ b/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
@@ -51,9 +51,9 @@ if {![runto_main]} {
 # this should fail.  Try with the keywords in both orders just in case the
 # parser has a bug.
 gdb_test "break foo thread 1.1 inferior 1" \
-    "You can specify only one of inferior or thread\\."
+    "You can specify only one of thread, inferior, or task\\."
 gdb_test "break foo inferior 1 thread 1.1" \
-    "You can specify only one of inferior or thread\\."
+    "You can specify only one of thread, inferior, or task\\."
 
 # Try to create a breakpoint using the 'inferior' keyword multiple times.
 gdb_test "break foo inferior 1 inferior 2" \
diff --git a/gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c b/gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
new file mode 100644
index 00000000000..15d1b9833dd
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/del-pending-thread-bp-lib.c
@@ -0,0 +1,22 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+int global_var = 0;
+
+void
+foo (int arg)
+{
+  global_var = arg;
+}
diff --git a/gdb/testsuite/gdb.threads/del-pending-thread-bp.c b/gdb/testsuite/gdb.threads/del-pending-thread-bp.c
new file mode 100644
index 00000000000..6fc76dbf08c
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/del-pending-thread-bp.c
@@ -0,0 +1,85 @@
+/* Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#include <dlfcn.h>
+#include <pthread.h>
+#include <stdlib.h>
+
+pthread_barrier_t barrier;
+
+static void
+barrier_wait (pthread_barrier_t *b)
+{
+  int res = pthread_barrier_wait (b);
+  if (res != 0 && res != PTHREAD_BARRIER_SERIAL_THREAD)
+    abort ();
+}
+
+static void *
+thread_worker (void *arg)
+{
+  barrier_wait (&barrier);
+  return NULL;
+}
+
+void
+breakpt (void)
+{
+  /* Nothing.  */
+}
+
+int
+main (void)
+{
+  void *handle;
+  void (*func)(int);
+  pthread_t thread;
+
+  if (pthread_barrier_init (&barrier, NULL, 2) != 0)
+    abort ();
+
+  if (pthread_create (&thread, NULL, thread_worker, NULL) != 0)
+    abort ();
+
+  breakpt ();
+
+  /* Allow the worker thread to complete.  */
+  barrier_wait (&barrier);
+
+  if (pthread_join (thread, NULL) != 0)
+    abort ();
+
+  breakpt ();
+
+  /* Now load the shared library.  */
+  handle = dlopen (SHLIB_NAME, RTLD_LAZY);
+  if (handle == NULL)
+    abort ();
+
+  /* Find the function symbol.  */
+  func = (void (*)(int)) dlsym (handle, "foo");
+
+  /* Call the library function.  */
+  func (1);
+
+  /* Unload the shared library.  */
+  if (dlclose (handle) != 0)
+    abort ();
+
+  breakpt ();
+
+  return 0;
+}
+
diff --git a/gdb/testsuite/gdb.threads/del-pending-thread-bp.exp b/gdb/testsuite/gdb.threads/del-pending-thread-bp.exp
new file mode 100644
index 00000000000..b919145ed41
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/del-pending-thread-bp.exp
@@ -0,0 +1,108 @@
+# Copyright 2023 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+# This test checks that pending thread-specific breakpoints are
+# correctly deleted when the thread the breakpoint is for goes out of
+# scope.
+#
+# We also check that we can't create a pending thread-specific
+# breakpoint for a non-existent thread.
+
+require allow_shlib_tests
+
+standard_testfile
+
+set libname $testfile-lib
+set srcfile_lib $srcdir/$subdir/$libname.c
+set binfile_lib [standard_output_file $libname.so]
+
+if { [gdb_compile_shlib $srcfile_lib $binfile_lib {}] != "" } {
+    untested "failed to compile shared library 1"
+    return -1
+}
+
+set binfile_lib_target [gdb_download_shlib $binfile_lib]
+
+if { [prepare_for_testing "failed to prepare" $testfile $srcfile \
+	  [list debug \
+	       additional_flags=-DSHLIB_NAME=\"$binfile_lib_target\" \
+	       shlib_load pthreads]] } {
+    return -1
+}
+
+gdb_locate_shlib $binfile_lib
+
+if ![runto_main] {
+    return 0
+}
+
+# Run until we have two threads.
+gdb_breakpoint "breakpt"
+gdb_continue_to_breakpoint "first breakpt call"
+
+# Confirm that we have a thread '2'.
+gdb_test "info threads" "\r\n\\s+2\\s+\[^\r\n\]+"
+
+# Create a pending, thread-specific, breakpoint on 'foo'.
+gdb_breakpoint "foo thread 2" allow-pending
+set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+	       "get breakpoint number"]
+
+# Check we can't create a pending thread-specific breakpoint for a
+# non-existent thread.
+gdb_test "with breakpoint pending on -- break foo thread 99" \
+    "Unknown thread 99\\."
+
+# Continue to 'breakpt' again.  Don't use gdb_continue_to_breakpoint
+# as we are looking for the thread exited and breakpoint deleted
+# messages.
+set output [list "Continuing\\."]
+
+if {!([target_info exists gdb_protocol]
+      && ([target_info gdb_protocol] == "remote"
+	  || [target_info gdb_protocol] == "extended-remote"))} {
+    # Due to bug PR gdb/30129 we don't see the thread exited messages
+    # for remote targets.  When this bit of this test can be cleaned
+    # up.
+    lappend output "\\\[Thread \[^\r\n\]+ exited\\\]"
+}
+
+lappend output "Thread-specific breakpoint $bpnum deleted - thread 2 no longer in the thread list\\." \
+    "" \
+    "Thread 1 \[^\r\n\]+, breakpt \\(\\) at \[^\r\n\]+" \
+    "$decimal\\s+\[^\r\n\]+"
+
+gdb_test "continue" \
+    [multi_line {*}$output] \
+    "second breakpt call"
+
+# Confirm breakpoint has been deleted.
+gdb_test "info breakpoints $bpnum" \
+    "No breakpoint, watchpoint, tracepoint, or catchpoint matching '$bpnum'\\."
+
+# Continue again.  This will pass through 'foo'.  We should not stop
+# in 'foo', the breakpoint has been deleted.  We should next stop in
+# breakpt again.
+gdb_test "continue" \
+    [multi_line \
+	 "Continuing\\." \
+	 "" \
+	 "Thread 1 \[^\r\n\]+ hit Breakpoint $decimal, breakpt \\(\\) at \[^\r\n\]+" \
+	 "$decimal\\s+\[^\r\n\]+"] \
+    "third breakpt call"
+gdb_test "bt 1" \
+    [multi_line \
+	 "#0\\s+breakpt \\(\\) at \[^\r\n\]+" \
+	 "\\(More stack frames follow\\.\\.\\.\\)"]
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv10 8/9] gdb: don't set breakpoint::pspace in create_breakpoint
  2024-03-31 10:31                 ` [PATCHv10 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
                                     ` (6 preceding siblings ...)
  2024-03-31 10:31                   ` [PATCHv10 7/9] gdb: parse pending breakpoint thread/task immediately Andrew Burgess
@ 2024-03-31 10:31                   ` Andrew Burgess
  2024-03-31 10:31                   ` [PATCHv10 9/9] gdb: only insert thread-specific breakpoints in the relevant inferior Andrew Burgess
  8 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2024-03-31 10:31 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

I spotted this code within create_breakpoint:

  if ((type_wanted != bp_breakpoint
      && type_wanted != bp_hardware_breakpoint) || thread != -1)
   b->pspace = current_program_space;

this code is only executed when creating a pending breakpoint, and
sets the breakpoint::pspace member variable.

The above code gained the 'thread != -1' clause with this commit:

  commit cc72b2a2da6d6372cbdb1d14639a5fce84e1a325
  Date:   Fri Dec 23 17:06:16 2011 +0000

              Introduce gdb.FinishBreakpoint in Python

While the type_wanted checks were added with this commit:

  commit f8eba3c61629b3c03ac1f33853eab4d8507adb9c
  Date:   Tue Dec 6 18:54:43 2011 +0000

      the "ambiguous linespec" series

Before this breakpoint::pspace was set unconditionally.

If we look at how breakpoint::pspace is used today, some breakpoint
types specifically set this field, either in their constructors, or in
a wrapper function that calls the constructor.  So, the watchpoint
type and its sub-class set this variable, as does the catchpoint type,
and all it's sub-classes.

However, code_breakpoint doesn't specifically set this field within
its constructor, though some sub-classes of
code_breakpoint (ada_catchpoint, exception_catchpoint,
internal_breakpoint, and momentary_breakpoint) do set this field.

When I examine all the places that breakpoint::pspace is used, I
believe that in every place where it is expected that this field is
set, the breakpoint type will be one that specifically sets this
field.

Next, I observe two problems with the existing code.

First, the above code is only hit for pending breakpoints, there's no
equivalent code for non-pending breakpoints.  This opens up the
possibility of GDB entering non-consistent states; if a breakpoint is
first created pending and then later gets a location, the pspace field
will be set, while if the breakpoint is immediately non-pending, then
the pspace field will never be set.

Second, if we look at how breakpoint::pspace is used in the function
breakpoint_program_space_exit, we see that when a program space is
removed, any breakpoint with breakpoint::pspace set to the removed
program space, will be deleted.  This makes sense, but does mean we
need to ensure breakpoint::pspace is only set for breakpoints that
apply to a single program space.

So, if I create a pending dprintf breakpoint (type bp_dprintf) then
the breakpoint::pspace variable will be set even though the dprintf is
not really tied to that one program space.  As a result, when the
matching program space is removed the dprintf is incorrectly removed.

Also, if I create a thread specific breakpoint, then, thanks to the
'thread != -1' clause the wrong program space will be stored in
breakpoint::pspace (the current program space is always used, which
might not be the program space that corresponds to the selected
thread), as a result, the thread specific breakpoint will be deleted
when the matching program space is removed.

If we look at commit cc72b2a2da6d which added the 'thread != -1'
clause, we can see this change was entirely redundant, the
breakpoint::pspace is also set in bpfinishpy_init after
create_breakpoint has been called.  As such, I think we can safely
drop the 'thread != -1' clause.

For the other problems, I'm proposing to be pretty aggressive - I'd
like to drop the breakpoint::pspace assignment completely from
create_breakpoint.  Having looked at how this variable is used, I
believe that it is already set elsewhere in all the cases that it is
needed.  Maybe this code was needed at one time, but I can't see how
it's needed any more.

There's tests to expose the issues I've spotted with this code, and
there's no regressions in testing.
---
 gdb/breakpoint.c                              |   3 -
 gdb/breakpoint.h                              |  18 +-
 .../gdb.multi/pending-bp-del-inferior.c       |  28 +++
 .../gdb.multi/pending-bp-del-inferior.exp     | 216 ++++++++++++++++++
 4 files changed, 259 insertions(+), 6 deletions(-)
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-del-inferior.c
 create mode 100644 gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 7bcdaa7ddf1..5e9a030536e 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -9191,9 +9191,6 @@ create_breakpoint (struct gdbarch *gdbarch,
       b->disposition = tempflag ? disp_del : disp_donttouch;
       b->condition_not_parsed = 1;
       b->enable_state = enabled ? bp_enabled : bp_disabled;
-      if ((type_wanted != bp_breakpoint
-	   && type_wanted != bp_hardware_breakpoint) || thread != -1)
-	b->pspace = current_program_space;
 
       if (b->type == bp_dprintf)
 	update_dprintf_command_list (b.get ());
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index 24aeaf926ec..42b49144e79 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -831,9 +831,21 @@ struct breakpoint : public intrusive_list_node<breakpoint>
      equals this.  */
   struct frame_id frame_id = null_frame_id;
 
-  /* The program space used to set the breakpoint.  This is only set
-     for breakpoints which are specific to a program space; for
-     non-thread-specific ordinary breakpoints this is NULL.  */
+  /* The program space used to set the breakpoint.  This is only set for
+     breakpoints that are not type bp_breakpoint or bp_hardware_breakpoint.
+     For thread or inferior specific breakpoints, the breakpoints are
+     managed via the thread and inferior member variables.  */
+
+  /* If not nullptr then this is the program space for which this
+     breakpoint was created.  All watchpoint and catchpoint sub-types set
+     this field, but not all of the code_breakpoint sub-types do;
+     generally, user created breakpoint types don't set this field, though
+     things might be more consistent if they did.
+
+     When this variable is nullptr then a breakpoint might be associated
+     with multiple program spaces, though you need to check the thread,
+     inferior and task variables to see if a breakpoint was created for a
+     specific thread, inferior, or Ada task respectively.  */
   program_space *pspace = NULL;
 
   /* The location specification we used to set the breakpoint.  */
diff --git a/gdb/testsuite/gdb.multi/pending-bp-del-inferior.c b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.c
new file mode 100644
index 00000000000..1d030007819
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.c
@@ -0,0 +1,28 @@
+/* This testcase is part of GDB, the GNU debugger.
+
+   Copyright 2023 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+int
+foo (void)
+{
+  return 0;
+}
+
+int
+main (void)
+{
+  return foo ();
+}
diff --git a/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
new file mode 100644
index 00000000000..5fcd1ef2e39
--- /dev/null
+++ b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
@@ -0,0 +1,216 @@
+# Copyright 2023 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+# Setup two inferiors.  Select one inferior and create a pending
+# thread specific breakpoint in the other inferior.
+#
+# Delete the selected inferior (the one for which the thread specific
+# breakpoint doesn't apply), and check that the breakpoint still exists.
+#
+# Repeat this process, but this time, create an inferior specific
+# breakpoint.
+
+# The plain remote target can't do multiple inferiors.
+require !use_gdb_stub
+
+standard_testfile
+
+if {[prepare_for_testing "failed to prepare" $testfile $srcfile]} {
+    return -1
+}
+
+# Setup for the tests.  Create two inferiors, both running the global
+# BINFILE, and proceed to main in both inferiors.  Delete all
+# breakpoints, and check that we do have two threads.
+#
+# Return true after a successful setup, otherwise, return false.
+proc test_setup {} {
+    clean_restart $::binfile
+
+    if {![runto_main]} {
+	return 0
+    }
+
+    gdb_test "add-inferior -exec ${::binfile}" "Added inferior 2.*" \
+	"add inferior 2"
+    gdb_test "inferior 2" "Switching to inferior 2 .*" \
+	"select inferior 2"
+
+    if {![runto_main]} {
+	return 0
+    }
+
+    delete_breakpoints
+
+    gdb_test "info threads" \
+	[multi_line \
+	     "  Id\\s+Target Id\\s+Frame\\s*" \
+	     "  1\\.1\\s+\[^\r\n\]+" \
+	     "\\* 2\\.1\\s+\[^\r\n\]+"] \
+	"check we have the expected threads"
+
+    return 1
+}
+
+# Assuming inferior 2 is already selected, kill the current inferior
+# (inferior 2), select inferior 1, and then remove inferior 2.
+proc kill_and_remove_inferior_2 {} {
+    gdb_test "kill" "" "kill inferior 2" \
+	"Kill the program being debugged.*y or n. $" "y"
+
+    gdb_test "inferior 1" "Switching to inferior 1 .*" \
+	"select inferior 1"
+
+    gdb_test_no_output "remove-inferiors 2"
+}
+
+# Setup two inferiors, then create a breakpoint.  If BP_PENDING is
+# true then the breakpoint will be pending, otherwise, the breakpoint
+# will be non-pending.
+#
+# BP_TYPE is either 'thread' or 'inferior', and indicates if the
+# created breakpoint should be thread or inferior specific.
+#
+# The breakpoint is created while inferior 2 is selected, and the
+# thread/inferior restriction always identifies inferior 1.
+#
+# Then inferior 2 is killed and removed.
+#
+# Finally, check that the breakpoint still exists and correctly refers
+# to inferior 1.
+proc do_bp_test { bp_type bp_pending } {
+    if {![test_setup]} {
+	return
+    }
+
+    if { $bp_pending } {
+	set bp_func "bar"
+    } else {
+	set bp_func "foo"
+    }
+
+    if { $bp_type eq "thread" } {
+	set bp_restriction "thread 1.1"
+    } else {
+	set bp_restriction "inferior 1"
+    }
+
+    gdb_breakpoint "$bp_func $bp_restriction" allow-pending
+    set bp_number [get_integer_valueof "\$bpnum" "INVALID" \
+		       "get b/p number for previous breakpoint"]
+
+    if { $bp_restriction eq "thread 1.1" } {
+	set bp_after_restriction "thread 1"
+    } else {
+	set bp_after_restriction $bp_restriction
+    }
+
+    if { $bp_pending } {
+	set bp_pattern_before \
+	    [multi_line \
+		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+${bp_func}" \
+		 "\\s+stop only in [string_to_regexp $bp_restriction]"]
+	set bp_pattern_after \
+	    [multi_line \
+		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+${bp_func}" \
+		 "\\s+stop only in [string_to_regexp $bp_after_restriction]"]
+    } else {
+	set bp_pattern_before \
+	    [multi_line \
+		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+<MULTIPLE>\\s*" \
+		 "\\s+stop only in [string_to_regexp $bp_restriction]" \
+		 "$bp_number\\.1\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 1" \
+		 "$bp_number\\.2\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 2"]
+
+	set bp_pattern_after \
+	    [multi_line \
+		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+" \
+		 "\\s+stop only in [string_to_regexp $bp_after_restriction]"]
+    }
+
+    gdb_test "info breakpoints" $bp_pattern_before \
+	"info breakpoints before inferior removal"
+
+    kill_and_remove_inferior_2
+
+    gdb_test "info breakpoints" $bp_pattern_after \
+	"info breakpoints after inferior removal"
+}
+
+# Setup two inferiors, then create a dprintf.  If BP_PENDING is
+# true then the dprintf will be pending, otherwise, the dprintf
+# will be non-pending.
+#
+# The dprintf is created while inferior 2 is selected.  Then inferior
+# 2 is killed and removed.
+#
+# Finally, check that the dprintf still exists.
+proc do_dprintf_test { bp_pending } {
+    if {![test_setup]} {
+	return
+    }
+
+    if { $bp_pending } {
+	set bp_func "bar"
+
+	gdb_test "dprintf $bp_func,\"in $bp_func\"" ".*" \
+	    "create dprintf breakpoint" \
+	    "Make dprintf pending on future shared library load\\? \\(y or .n.\\) $" "y"
+    } else {
+	set bp_func "foo"
+
+	gdb_test "dprintf $bp_func,\"in $bp_func\"" ".*" \
+	    "create dprintf breakpoint"
+    }
+
+    set bp_number [get_integer_valueof "\$bpnum" "INVALID" \
+		       "get b/p number for previous breakpoint"]
+
+    if { $bp_pending } {
+	set bp_pattern_before \
+	    [multi_line \
+		 "$bp_number\\s+dprintf\\s+keep\\s+y\\s+<PENDING>\\s+${bp_func}" \
+		 "\\s+printf \"in $bp_func\""]
+	set bp_pattern_after $bp_pattern_before
+    } else {
+	set bp_pattern_before \
+	    [multi_line \
+		 "$bp_number\\s+dprintf\\s+keep\\s+y\\s+<MULTIPLE>\\s*" \
+		 "\\s+printf \"in $bp_func\"" \
+		 "$bp_number\\.1\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 1" \
+		 "$bp_number\\.2\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 2"]
+
+	set bp_pattern_after \
+	    [multi_line \
+		 "$bp_number\\s+dprintf\\s+keep\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+" \
+		 "\\s+printf \"in $bp_func\""]
+    }
+
+    gdb_test "info breakpoints" $bp_pattern_before \
+	"info breakpoints before inferior removal"
+
+    kill_and_remove_inferior_2
+
+    gdb_test "info breakpoints" $bp_pattern_after \
+	"info breakpoints after inferior removal"
+}
+
+foreach_with_prefix bp_pending { true false } {
+    foreach_with_prefix bp_type { thread inferior } {
+	do_bp_test $bp_type $bp_pending
+    }
+
+    do_dprintf_test $bp_pending
+}
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

* [PATCHv10 9/9] gdb: only insert thread-specific breakpoints in the relevant inferior
  2024-03-31 10:31                 ` [PATCHv10 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
                                     ` (7 preceding siblings ...)
  2024-03-31 10:31                   ` [PATCHv10 8/9] gdb: don't set breakpoint::pspace in create_breakpoint Andrew Burgess
@ 2024-03-31 10:31                   ` Andrew Burgess
  8 siblings, 0 replies; 138+ messages in thread
From: Andrew Burgess @ 2024-03-31 10:31 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Eli Zaretskii

This commit updates GDB so that thread or inferior specific
breakpoints are only inserted into the program space in which the
specific thread or inferior is running.

In terms of implementation, getting this basically working is easy
enough, now that a breakpoint's thread or inferior field is setup
prior to GDB looking for locations, we can easily use this information
to find a suitable program_space and pass this to as a filter when
creating the sals.

Or we could if breakpoint_ops::create_sals_from_location_spec allowed
us to pass in a filter program_space.

So, this commit extends breakpoint_ops::create_sals_from_location_spec
to take a program_space argument, and uses this to filter the set of
returned sals.  This accounts for about half the change in this patch.

The second set of changes starts from breakpoint_set_thread and
breakpoint_set_inferior, this is called when the thread or inferior
for a breakpoint changes, e.g. from the Python API.

Previously this call would never result in the locations of a
breakpoint changing, after all, locations were inserted in every
program space, and we just use the thread or inferior variable to
decide when we should stop.  Now though, changing a breakpoint's
thread or inferior can mean we need to figure out a new set of
breakpoint locations.

To support this I've added a new breakpoint_re_set_one function, which
is like breakpoint_re_set, but takes a single breakpoint, and just
updates the locations for that one breakpoint.  We only need to call
this function if the program_space in which a breakpoint's thread (or
inferior) is running actually changes.  If the program_space does
change then we call the new breakpoint_re_set_one function passing in
the program_space which should be used to filter the new locations (or
nullptr to indicate we should set locations in all program spaces).
This filter program_space needs to propagate down to all the re_set
methods, this accounts for the remaining half of the changes in this
patch.

There were a couple of existing tests that created thread or inferior
specific breakpoints and then checked the 'info breakpoints' output,
these needed updating.  These were:

  gdb.mi/user-selected-context-sync.exp
  gdb.multi/bp-thread-specific.exp
  gdb.multi/multi-target-continue.exp
  gdb.multi/multi-target-ping-pong-next.exp
  gdb.multi/tids.exp
  gdb.mi/new-ui-bp-deleted.exp
  gdb.multi/inferior-specific-bp.exp
  gdb.multi/pending-bp-del-inferior.exp

I've also added some additional tests to:

  gdb.multi/pending-bp.exp

I've updated the documentation and added a NEWS entry.

Reviewed-By: Eli Zaretskii <eliz@gnu.org>
---
 gdb/NEWS                                      |   7 +
 gdb/ada-lang.c                                |   6 +-
 gdb/break-catch-throw.c                       |   6 +-
 gdb/breakpoint.c                              | 280 ++++++++++++++----
 gdb/breakpoint.h                              |  29 +-
 gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp    |   8 +-
 .../gdb.mi/user-selected-context-sync.exp     |  14 +-
 .../gdb.multi/bp-thread-specific.exp          |   7 +-
 .../gdb.multi/inferior-specific-bp.exp        |  12 +-
 .../gdb.multi/multi-target-continue.exp       |   2 +-
 .../gdb.multi/multi-target-ping-pong-next.exp |   4 +-
 .../gdb.multi/pending-bp-del-inferior.exp     |   6 +-
 gdb/testsuite/gdb.multi/pending-bp.exp        | 206 +++++++++++++
 gdb/testsuite/gdb.multi/tids.exp              |   6 +-
 14 files changed, 486 insertions(+), 107 deletions(-)

diff --git a/gdb/NEWS b/gdb/NEWS
index fa2d1427ded..8ccc9e1199d 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -20,6 +20,13 @@
   'thread' or 'task' keywords are parsed at the time the breakpoint is
   created, rather than at the time the breakpoint becomes non-pending.
 
+* Thread-specific breakpoints are only inserted into the program space
+  in which the thread of interest is running.  In most cases program
+  spaces are unique for each inferior, so this means that
+  thread-specific breakpoints will usually only be inserted for the
+  inferior containing the thread of interest.  The breakpoint will
+  be hit no less than before.
+
 * Changed commands
 
 disassemble
diff --git a/gdb/ada-lang.c b/gdb/ada-lang.c
index c9f12d72b70..8492ad06306 100644
--- a/gdb/ada-lang.c
+++ b/gdb/ada-lang.c
@@ -12051,11 +12051,11 @@ struct ada_catchpoint : public code_breakpoint
     enable_state = enabled ? bp_enabled : bp_disabled;
     language = language_ada;
 
-    re_set ();
+    re_set (pspace);
   }
 
   struct bp_location *allocate_location () override;
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   void check_status (struct bpstat *bs) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   bool print_one (const bp_location **) const override;
@@ -12100,7 +12100,7 @@ static struct symtab_and_line ada_exception_sal
    catchpoint kinds.  */
 
 void
-ada_catchpoint::re_set ()
+ada_catchpoint::re_set (program_space *pspace)
 {
   std::vector<symtab_and_line> sals;
   try
diff --git a/gdb/break-catch-throw.c b/gdb/break-catch-throw.c
index ce614ac8fe3..c24f38d6272 100644
--- a/gdb/break-catch-throw.c
+++ b/gdb/break-catch-throw.c
@@ -81,10 +81,10 @@ struct exception_catchpoint : public code_breakpoint
 				     _("invalid type-matching regexp")))
   {
     pspace = current_program_space;
-    re_set ();
+    re_set (pspace);
   }
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   bool print_one (const bp_location **) const override;
   void print_mention () const override;
@@ -197,7 +197,7 @@ exception_catchpoint::check_status (struct bpstat *bs)
 /* Implement the 're_set' method.  */
 
 void
-exception_catchpoint::re_set ()
+exception_catchpoint::re_set (program_space *pspace)
 {
   std::vector<symtab_and_line> sals;
   struct program_space *filter_pspace = current_program_space;
diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 5e9a030536e..3bc92ceb865 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -90,9 +90,12 @@
 static void map_breakpoint_numbers (const char *,
 				    gdb::function_view<void (breakpoint *)>);
 
-static void
-  create_sals_from_location_spec_default (location_spec *locspec,
-					  linespec_result *canonical);
+static void parse_breakpoint_sals (location_spec *locspec,
+				   linespec_result *canonical,
+				   program_space *search_pspace);
+
+static void breakpoint_re_set_one (breakpoint *b,
+				   program_space *filter_pspace);
 
 static void create_breakpoints_sal (struct gdbarch *,
 				    struct linespec_result *,
@@ -282,11 +285,12 @@ static bool strace_marker_p (struct breakpoint *b);
 
 static void bkpt_probe_create_sals_from_location_spec
      (location_spec *locspec,
-      struct linespec_result *canonical);
+      struct linespec_result *canonical,
+      struct program_space *search_pspace);
 
 const struct breakpoint_ops code_breakpoint_ops =
 {
-  create_sals_from_location_spec_default,
+  parse_breakpoint_sals,
   create_breakpoints_sal,
 };
 
@@ -351,7 +355,7 @@ struct internal_breakpoint : public code_breakpoint
     disposition = disp_donttouch;
   }
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   void check_status (struct bpstat *bs) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   void print_mention () const override;
@@ -388,7 +392,7 @@ struct momentary_breakpoint : public code_breakpoint
     gdb_assert (inferior == -1);
   }
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   void check_status (struct bpstat *bs) override;
   enum print_stop_action print_it (const bpstat *bs) const override;
   void print_mention () const override;
@@ -399,7 +403,7 @@ struct dprintf_breakpoint : public ordinary_breakpoint
 {
   using ordinary_breakpoint::ordinary_breakpoint;
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   int breakpoint_hit (const struct bp_location *bl,
 		      const address_space *aspace,
 		      CORE_ADDR bp_addr,
@@ -1548,7 +1552,36 @@ breakpoint_set_thread (struct breakpoint *b, int thread)
   int old_thread = b->thread;
   b->thread = thread;
   if (old_thread != thread)
-    notify_breakpoint_modified (b);
+    {
+      /* If THREAD is in a different program_space than OLD_THREAD, or the
+	 breakpoint has switched to or from being thread-specific, then we
+	 need to re-set the locations of this breakpoint.  First, figure
+	 out the program_space for the old and new threads, use a value of
+	 nullptr to indicate the breakpoint is in all program spaces.  */
+      program_space *old_pspace = nullptr;
+      if (old_thread != -1)
+	{
+	  struct thread_info *thr = find_thread_global_id (old_thread);
+	  gdb_assert (thr != nullptr);
+	  old_pspace = thr->inf->pspace;
+	}
+
+      program_space *new_pspace = nullptr;
+      if (thread != -1)
+	{
+	  struct thread_info *thr = find_thread_global_id (thread);
+	  gdb_assert (thr != nullptr);
+	  new_pspace = thr->inf->pspace;
+	}
+
+      /* If the program space has changed for this breakpoint, then
+	 re-evaluate it's locations.  */
+      if (old_pspace != new_pspace)
+	breakpoint_re_set_one (b, new_pspace);
+
+      /* Let others know the breakpoint has changed.  */
+      notify_breakpoint_modified (b);
+    }
 }
 
 /* See breakpoint.h.  */
@@ -1567,7 +1600,34 @@ breakpoint_set_inferior (struct breakpoint *b, int inferior)
   int old_inferior = b->inferior;
   b->inferior = inferior;
   if (old_inferior != inferior)
-    notify_breakpoint_modified (b);
+    {
+      /* If INFERIOR is in a different program_space than OLD_INFERIOR, or
+	 the breakpoint has switch to or from inferior-specific, then we
+	 need to re-set the locations of this breakpoint.  First, figure
+	 out the program_space for the old and new inferiors, use a value
+	 of nullptr to indicate the breakpoint is in all program
+	 spaces.  */
+      program_space *old_pspace = nullptr;
+      if (old_inferior != -1)
+	{
+	  struct inferior *inf = find_inferior_id (old_inferior);
+	  gdb_assert (inf != nullptr);
+	  old_pspace = inf->pspace;
+	}
+
+      program_space *new_pspace = nullptr;
+      if (inferior != -1)
+	{
+	  struct inferior *inf = find_inferior_id (inferior);
+	  gdb_assert (inf != nullptr);
+	  new_pspace = inf->pspace;
+	}
+
+      if (old_pspace != new_pspace)
+	breakpoint_re_set_one (b, new_pspace);
+
+      notify_breakpoint_modified (b);
+    }
 }
 
 /* See breakpoint.h.  */
@@ -8800,7 +8860,8 @@ create_breakpoints_sal (struct gdbarch *gdbarch,
 
 static void
 parse_breakpoint_sals (location_spec *locspec,
-		       struct linespec_result *canonical)
+		       struct linespec_result *canonical,
+		       struct program_space *search_pspace)
 {
   struct symtab_and_line cursal;
 
@@ -8865,7 +8926,7 @@ parse_breakpoint_sals (location_spec *locspec,
 	      && strchr ("+-", spec[0]) != NULL
 	      && spec[1] != '['))
 	{
-	  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, NULL,
+	  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, search_pspace,
 			    get_last_displayed_symtab (),
 			    get_last_displayed_line (),
 			    canonical, NULL, NULL);
@@ -8873,7 +8934,7 @@ parse_breakpoint_sals (location_spec *locspec,
 	}
     }
 
-  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, NULL,
+  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, search_pspace,
 		    cursal.symtab, cursal.line, canonical, NULL, NULL);
 }
 
@@ -8972,6 +9033,39 @@ breakpoint_ops_for_location_spec_type (enum location_spec_type locspec_type,
     }
 }
 
+/* Return the program space to use as a filter when searching for locations
+   of a breakpoint specific to THREAD or INFERIOR.  If THREAD and INFERIOR
+   are both -1, meaning all threads/inferiors, then this function returns
+   nullptr, indicating no program space filtering should be performed.
+   Otherwise, this function returns the program space for the inferior that
+   contains THREAD (when THREAD is not -1), or the program space for
+   INFERIOR (when INFERIOR is not -1).  */
+
+static struct program_space *
+find_program_space_for_breakpoint (int thread, int inferior)
+{
+  if (thread != -1)
+    {
+      gdb_assert (inferior == -1);
+
+      struct thread_info *thr = find_thread_global_id (thread);
+      gdb_assert (thr != nullptr);
+      gdb_assert (thr->inf != nullptr);
+      return thr->inf->pspace;
+    }
+  else if (inferior != -1)
+    {
+      gdb_assert (thread == -1);
+
+      struct inferior *inf = find_inferior_id (inferior);
+      gdb_assert (inf != nullptr);
+
+      return inf->pspace;
+    }
+
+  return nullptr;
+}
+
 /* See breakpoint.h.  */
 
 const struct breakpoint_ops *
@@ -9073,7 +9167,10 @@ create_breakpoint (struct gdbarch *gdbarch,
 
   try
     {
-      ops->create_sals_from_location_spec (locspec, &canonical);
+      struct program_space *search_pspace
+	= find_program_space_for_breakpoint (thread, inferior);
+      ops->create_sals_from_location_spec (locspec, &canonical,
+					   search_pspace);
     }
   catch (const gdb_exception_error &e)
     {
@@ -9546,7 +9643,7 @@ break_range_command (const char *arg, int from_tty)
   arg_start = arg;
   location_spec_up start_locspec
     = string_to_location_spec (&arg, current_language);
-  parse_breakpoint_sals (start_locspec.get (), &canonical_start);
+  parse_breakpoint_sals (start_locspec.get (), &canonical_start, nullptr);
 
   if (arg[0] != ',')
     error (_("Too few arguments."));
@@ -9647,7 +9744,7 @@ watchpoint_exp_is_const (const struct expression *exp)
 /* Implement the "re_set" method for watchpoints.  */
 
 void
-watchpoint::re_set ()
+watchpoint::re_set (struct program_space *pspace)
 {
   /* Watchpoint can be either on expression using entirely global
      variables, or it can be on local variables.
@@ -11758,7 +11855,7 @@ breakpoint::print_recreate (struct ui_file *fp) const
 /* Default breakpoint_ops methods.  */
 
 void
-code_breakpoint::re_set ()
+code_breakpoint::re_set (struct program_space *pspace)
 {
   /* FIXME: is this still reachable?  */
   if (breakpoint_location_spec_empty_p (this))
@@ -11768,7 +11865,7 @@ code_breakpoint::re_set ()
       return;
     }
 
-  re_set_default ();
+  re_set_default (pspace);
 }
 
 int
@@ -11974,7 +12071,7 @@ code_breakpoint::decode_location_spec (location_spec *locspec,
 /* Virtual table for internal breakpoints.  */
 
 void
-internal_breakpoint::re_set ()
+internal_breakpoint::re_set (struct program_space *pspace)
 {
   switch (type)
     {
@@ -12067,7 +12164,7 @@ internal_breakpoint::print_mention () const
 /* Virtual table for momentary breakpoints  */
 
 void
-momentary_breakpoint::re_set ()
+momentary_breakpoint::re_set (struct program_space *pspace)
 {
   /* Keep temporary breakpoints, which can be encountered when we step
      over a dlopen call and solib_add is resetting the breakpoints.
@@ -12108,12 +12205,13 @@ longjmp_breakpoint::~longjmp_breakpoint ()
 
 static void
 bkpt_probe_create_sals_from_location_spec (location_spec *locspec,
-					   struct linespec_result *canonical)
+					   struct linespec_result *canonical,
+					   struct program_space *search_pspace)
 
 {
   struct linespec_sals lsal;
 
-  lsal.sals = parse_probes (locspec, NULL, canonical);
+  lsal.sals = parse_probes (locspec, search_pspace, canonical);
   lsal.canonical = xstrdup (canonical->locspec->to_string ());
   canonical->lsals.push_back (std::move (lsal));
 }
@@ -12203,9 +12301,9 @@ tracepoint::print_recreate (struct ui_file *fp) const
 }
 
 void
-dprintf_breakpoint::re_set ()
+dprintf_breakpoint::re_set (struct program_space *pspace)
 {
-  re_set_default ();
+  re_set_default (pspace);
 
   /* 1 - connect to target 1, that can run breakpoint commands.
      2 - create a dprintf, which resolves fine.
@@ -12259,8 +12357,10 @@ dprintf_breakpoint::after_condition_true (struct bpstat *bs)
    markers (`-m').  */
 
 static void
-strace_marker_create_sals_from_location_spec (location_spec *locspec,
-					      struct linespec_result *canonical)
+strace_marker_create_sals_from_location_spec
+	(location_spec *locspec,
+	 struct linespec_result *canonical,
+	 struct program_space *search_pspace)
 {
   struct linespec_sals lsal;
   const char *arg_start, *arg;
@@ -12777,12 +12877,32 @@ update_breakpoint_locations (code_breakpoint *b,
      all locations are in the same shared library, that was unloaded.
      We'd like to retain the location, so that when the library is
      loaded again, we don't loose the enabled/disabled status of the
-     individual locations.  */
+     individual locations.
+
+     Thread specific breakpoints will also trigger this case if the thread
+     is changed to a different program space, and all of the old locations
+     go out of scope.  In this case we do (currently) discard the old
+     locations -- we assume the change in thread is permanent and the old
+     locations will never come back into scope.  */
   if (all_locations_are_pending (b, filter_pspace) && sals.empty ())
-    return;
+    {
+      if (b->thread != -1)
+	b->clear_locations ();
+      return;
+    }
 
   bp_location_list existing_locations = b->steal_locations (filter_pspace);
 
+  /* If this is a thread-specific breakpoint then any locations left on the
+     breakpoint are for a program space in which the thread of interest
+     does not operate.  This can happen when the user changes the thread of
+     a thread-specific breakpoint.
+
+     We assume that the change in thread is permanent, and that the old
+     locations will never be used again, so discard them now.  */
+  if (b->thread != -1)
+    b->clear_locations ();
+
   for (const auto &sal : sals)
     {
       struct bp_location *new_loc;
@@ -12948,40 +13068,45 @@ code_breakpoint::location_spec_to_sals (location_spec *locspec,
    locations.  */
 
 void
-code_breakpoint::re_set_default ()
+code_breakpoint::re_set_default (struct program_space *filter_pspace)
 {
-  struct program_space *filter_pspace = current_program_space;
   std::vector<symtab_and_line> expanded, expanded_end;
 
-  int found;
-  std::vector<symtab_and_line> sals = location_spec_to_sals (locspec.get (),
-							     filter_pspace,
-							     &found);
-  if (found)
-    expanded = std::move (sals);
-
-  if (locspec_range_end != nullptr)
-    {
-      std::vector<symtab_and_line> sals_end
-	= location_spec_to_sals (locspec_range_end.get (),
-				 filter_pspace, &found);
+  /* If this breakpoint is thread-specific then find the program space in
+     which the specific thread exists.  Otherwise, for breakpoints that are
+     not thread-specific THREAD_PSPACE will be nullptr.  */
+  program_space *bp_pspace
+    = find_program_space_for_breakpoint (this->thread, this->inferior);
+
+  /* If this is not a thread or inferior specific breakpoint, or it is a
+     thread or inferior specific breakpoint but we are looking for new
+     locations in the program space that the specific thread or inferior is
+     running, then look for new locations for this breakpoint.  */
+  if (bp_pspace == nullptr || filter_pspace == bp_pspace)
+    {
+      int found;
+      std::vector<symtab_and_line> sals
+	= location_spec_to_sals (locspec.get (), filter_pspace, &found);
       if (found)
-	expanded_end = std::move (sals_end);
+	expanded = std::move (sals);
+
+      if (locspec_range_end != nullptr)
+	{
+	  std::vector<symtab_and_line> sals_end
+	    = location_spec_to_sals (locspec_range_end.get (),
+				     filter_pspace, &found);
+	  if (found)
+	    expanded_end = std::move (sals_end);
+	}
     }
 
+  /* Update the locations for this breakpoint.  For thread-specific
+     breakpoints this will remove any old locations that are for the wrong
+     program space -- this can happen if the user changes the thread of a
+     thread-specific breakpoint.  */
   update_breakpoint_locations (this, filter_pspace, expanded, expanded_end);
 }
 
-/* Default method for creating SALs from an address string.  It basically
-   calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
-
-static void
-create_sals_from_location_spec_default (location_spec *locspec,
-					struct linespec_result *canonical)
-{
-  parse_breakpoint_sals (locspec, canonical);
-}
-
 /* Re-set breakpoint locations for the current program space.
    Locations bound to other program spaces are left untouched.  */
 
@@ -13016,7 +13141,7 @@ breakpoint_re_set (void)
 	  {
 	    input_radix = b.input_radix;
 	    set_language (b.language);
-	    b.re_set ();
+	    b.re_set (current_program_space);
 	  }
 	catch (const gdb_exception &ex)
 	  {
@@ -13037,6 +13162,53 @@ breakpoint_re_set (void)
   /* Now we can insert.  */
   update_global_location_list (UGLL_MAY_INSERT);
 }
+
+/* Re-set locations for breakpoint B in FILTER_PSPACE.  If FILTER_PSPACE is
+   nullptr then re-set locations for B in all program spaces.  Locations
+   bound to program spaces other than FILTER_PSPACE are left untouched.  */
+
+static void
+breakpoint_re_set_one (breakpoint *b, program_space *filter_pspace)
+{
+  {
+    scoped_restore_current_language save_language;
+    scoped_restore save_input_radix = make_scoped_restore (&input_radix);
+    scoped_restore_current_pspace_and_thread restore_pspace_thread;
+
+    /* To ::re_set each breakpoint we set the current_language to the
+       language of the breakpoint before re-evaluating the breakpoint's
+       location.  This change can unfortunately get undone by accident if
+       the language_mode is set to auto, and we either switch frames, or
+       more likely in this context, we select the current frame.
+
+       We prevent this by temporarily turning the language_mode to
+       language_mode_manual.  We restore it once all breakpoints
+       have been reset.  */
+    scoped_restore save_language_mode = make_scoped_restore (&language_mode);
+    language_mode = language_mode_manual;
+
+    /* Note: we must not try to insert locations until after all
+       breakpoints have been re-set.  Otherwise, e.g., when re-setting
+       breakpoint 1, we'd insert the locations of breakpoint 2, which
+       hadn't been re-set yet, and thus may have stale locations.  */
+
+    try
+      {
+	input_radix = b->input_radix;
+	set_language (b->language);
+	b->re_set (filter_pspace);
+      }
+    catch (const gdb_exception &ex)
+      {
+	exception_fprintf (gdb_stderr, ex,
+			   "Error in re-setting breakpoint %d: ",
+			   b->number);
+      }
+  }
+
+  /* Now we can insert.  */
+  update_global_location_list (UGLL_MAY_INSERT);
+}
 \f
 /* Reset the thread number of this breakpoint:
 
diff --git a/gdb/breakpoint.h b/gdb/breakpoint.h
index 42b49144e79..dea55deb314 100644
--- a/gdb/breakpoint.h
+++ b/gdb/breakpoint.h
@@ -570,15 +570,15 @@ enum print_stop_action
 
 struct breakpoint_ops
 {
-  /* Create SALs from location spec, storing the result in
-     linespec_result.
-
-     For an explanation about the arguments, see the function
-     `create_sals_from_location_spec_default'.
+  /* Create SALs from LOCSPEC, storing the result in linespec_result
+     CANONICAL.  If SEARCH_PSPACE is not nullptr then only results in the
+     corresponding program space are returned.  If SEARCH_PSPACE is nullptr
+     then results for all program spaces are returned.
 
      This function is called inside `create_breakpoint'.  */
   void (*create_sals_from_location_spec) (location_spec *locspec,
-					  struct linespec_result *canonical);
+					  linespec_result *canonical,
+					  program_space *search_pspace);
 
   /* This method will be responsible for creating a breakpoint given its SALs.
      Usually, it just calls `create_breakpoints_sal' (for ordinary
@@ -710,8 +710,15 @@ struct breakpoint : public intrusive_list_node<breakpoint>
 
   /* Reevaluate a breakpoint.  This is necessary after symbols change
      (e.g., an executable or DSO was loaded, or the inferior just
-     started).  */
-  virtual void re_set ()
+     started).
+
+     If not nullptr, then FILTER_PSPACE is the program space in which
+     symbols may have changed, we only need to add new locations in
+     FILTER_PSPACE.
+
+     If FILTER_PSPACE is nullptr then all program spaces may have changed,
+     new locations need to be searched for in every program space.  */
+  virtual void re_set (program_space *filter_pspace)
   {
     /* Nothing to re-set.  */
   }
@@ -955,7 +962,7 @@ struct code_breakpoint : public breakpoint
   /* Add a location for SAL to this breakpoint.  */
   bp_location *add_location (const symtab_and_line &sal);
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   int insert_location (struct bp_location *) override;
   int remove_location (struct bp_location *,
 		       enum remove_bp_reason reason) override;
@@ -977,7 +984,7 @@ struct code_breakpoint : public breakpoint
      struct program_space *search_pspace);
 
   /* Helper method that does the basic work of re_set.  */
-  void re_set_default ();
+  void re_set_default (program_space *pspace);
 
   /* Find the SaL locations corresponding to the given LOCATION.
      On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
@@ -999,7 +1006,7 @@ struct watchpoint : public breakpoint
 {
   using breakpoint::breakpoint;
 
-  void re_set () override;
+  void re_set (program_space *pspace) override;
   int insert_location (struct bp_location *) override;
   int remove_location (struct bp_location *,
 		       enum remove_bp_reason reason) override;
diff --git a/gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp b/gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp
index f736994d234..938e6deec05 100644
--- a/gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp
+++ b/gdb/testsuite/gdb.mi/new-ui-bp-deleted.exp
@@ -76,8 +76,12 @@ foreach_mi_ui_mode mode {
     set loc2 [make_bp_loc "$::decimal\\.2"]
 
     # Create the inferior-specific breakpoint.
-    mi_create_breakpoint_multi "-g i2 foo" "create breakpoint in inferior 2" \
-	-inferior "2" -locations "\\\[$loc1,$loc2\\\]"
+    mi_create_breakpoint "-g i2 foo" "create breakpoint in inferior 2" \
+	-number "$decimal" \
+	-type "breakpoint" \
+	-enabled "y" \
+	-func "foo" \
+	-inferior "2"
     set bpnum [mi_get_valueof "/d" "\$bpnum" "INVALID"]
 
     if {$mode eq "separate"} {
diff --git a/gdb/testsuite/gdb.mi/user-selected-context-sync.exp b/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
index 93b91b42f92..e168a5eee45 100644
--- a/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
+++ b/gdb/testsuite/gdb.mi/user-selected-context-sync.exp
@@ -364,15 +364,9 @@ proc test_continue_to_start { mode inf } {
 
 		# Consume MI output.
 		with_spawn_id $mi_spawn_id {
-		    if { $inf == 1} {
-			mi_expect_stop "breakpoint-hit" "child_sub_function" \
-			    "" "$srcfile" "$decimal" {"" "disp=\"del\""} \
-			    "thread $inf.2 stops MI"
-		    } else {
-			mi_expect_stop "breakpoint-hit" "child_sub_function" \
-			    "" "$srcfile" "$decimal" {"" "disp=\"del\"" "locno=\"[0-9]+\""} \
-			    "thread $inf.2 stops MI"
-		    }
+		    mi_expect_stop "breakpoint-hit" "child_sub_function" \
+			"" "$srcfile" "$decimal" {"" "disp=\"del\""} \
+			"thread $inf.2 stops MI"
 		}
 	    }
 	}
@@ -439,7 +433,7 @@ proc_with_prefix test_setup { mode } {
 
 	with_spawn_id $mi_spawn_id {
 	    mi_expect_stop "breakpoint-hit" "main" "" "$srcfile" "$decimal" \
-		{"" "disp=\"del\"" "locno=\"[0-9]+\""} "main stop"
+		{"" "disp=\"del\""} "main stop"
 	}
 
 	# Consume CLI output.
diff --git a/gdb/testsuite/gdb.multi/bp-thread-specific.exp b/gdb/testsuite/gdb.multi/bp-thread-specific.exp
index 7635e84b913..c1d87521ee9 100644
--- a/gdb/testsuite/gdb.multi/bp-thread-specific.exp
+++ b/gdb/testsuite/gdb.multi/bp-thread-specific.exp
@@ -50,7 +50,7 @@ gdb_test "info threads" \
 # locations ('foo' in both inferiors) even though only one of those
 # locations will ever trigger ('foo' in inferior 2).
 gdb_test "break foo thread 2.1" \
-    "Breakpoint $decimal at $hex: foo\\. \\(2 locations\\)"
+    "Breakpoint $decimal at $hex: file \[^\r\n\]+$srcfile, line $decimal\\."
 
 set bpnum [get_integer_valueof "\$bpnum" "INVALID"]
 
@@ -58,10 +58,7 @@ set bpnum [get_integer_valueof "\$bpnum" "INVALID"]
 # earlier breakpoint.  Check that the thread-id used when describing
 # the earlier breakpoints is correct.
 gdb_test "break foo thread 1.1" \
-    [multi_line \
-	 "Note: breakpoint $bpnum \\(thread 2.1\\) also set at pc $hex\\." \
-	 "Note: breakpoint $bpnum \\(thread 2.1\\) also set at pc $hex\\." \
-	 "Breakpoint $decimal at $hex: foo\\. \\(2 locations\\)"]
+    "Breakpoint $decimal at $hex: file \[^\r\n\]+$srcfile, line $decimal\\."
 
 # Save the breakpoints into a file.
 if {[is_remote host]} {
diff --git a/gdb/testsuite/gdb.multi/inferior-specific-bp.exp b/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
index 46efe6f54bc..52f84183589 100644
--- a/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
+++ b/gdb/testsuite/gdb.multi/inferior-specific-bp.exp
@@ -105,16 +105,8 @@ proc check_info_breakpoints { testname bp_number expected_loc_count } {
 # Create an inferior-specific breakpoint.  Use gdb_test instead of
 # gdb_breakpoint here as we want to check the breakpoint was placed in
 # multiple locations.
-#
-# Currently GDB still places inferior specific breakpoints into every
-# inferior, just like it does with thread specific breakpoints.
-# Hopefully this will change in the future, at which point, this test
-# will need updating.
-#
-# Two of these locations are in inferior 1, while the third is in
-# inferior 2.
 gdb_test "break foo inferior 1" \
-    "Breakpoint $decimal at $hex: foo\\. \\(3 locations\\)"
+    "Breakpoint $decimal at $hex: foo\\. \\(2 locations\\)"
 set bp_number [get_integer_valueof "\$bpnum" "INVALID" \
 		  "get b/p number for inferior specific breakpoint"]
 
@@ -123,7 +115,7 @@ set location_count 0
 set saw_inf_cond false
 
 check_info_breakpoints "first check for inferior specific breakpoint" \
-    $bp_number 3
+    $bp_number 2
 
 # Create a multi-inferior breakpoint to stop at.
 gdb_breakpoint "stop_breakpt" message
diff --git a/gdb/testsuite/gdb.multi/multi-target-continue.exp b/gdb/testsuite/gdb.multi/multi-target-continue.exp
index d2201061713..d4b2fc28133 100644
--- a/gdb/testsuite/gdb.multi/multi-target-continue.exp
+++ b/gdb/testsuite/gdb.multi/multi-target-continue.exp
@@ -30,7 +30,7 @@ proc test_continue {non-stop} {
 
     proc set_break {inf} {
 	gdb_test "break function${inf} thread ${inf}.1" \
-	"Breakpoint .* function${inf}\\..*"
+	    "Breakpoint ${::decimal} at ${::hex}: file .*, line ${::decimal}\\."
     }
 
     # Select inferior INF, and then run to a breakpoint on inferior
diff --git a/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp b/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp
index 0aff708c0f3..36f9d24a917 100644
--- a/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp
+++ b/gdb/testsuite/gdb.multi/multi-target-ping-pong-next.exp
@@ -52,12 +52,12 @@ proc test_ping_pong_next {} {
     gdb_test "thread 1.1" "Switching to thread 1.1 .*"
 
     gdb_test "break $srcfile:$line1 thread 1.1" \
-	"Breakpoint .*$srcfile:$line1\\..*"
+	"Breakpoint .*$srcfile, line $line1\\."
 
     gdb_test "continue" "hit Breakpoint .*"
 
     gdb_test "break $srcfile:$line2 thread 2.1" \
-	"Breakpoint .*$srcfile:$line2\\..*"
+	"Breakpoint .*$srcfile, line $line2\\."
 
     # Now block inferior 1 and issue "next".  We should stop at the
     # breakpoint for inferior 2, given schedlock off.
diff --git a/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
index 5fcd1ef2e39..12c0a84bb02 100644
--- a/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
+++ b/gdb/testsuite/gdb.multi/pending-bp-del-inferior.exp
@@ -129,10 +129,8 @@ proc do_bp_test { bp_type bp_pending } {
     } else {
 	set bp_pattern_before \
 	    [multi_line \
-		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+<MULTIPLE>\\s*" \
-		 "\\s+stop only in [string_to_regexp $bp_restriction]" \
-		 "$bp_number\\.1\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 1" \
-		 "$bp_number\\.2\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 2"]
+		 "$bp_number\\s+breakpoint\\s+keep\\s+y\\s+$::hex in $bp_func at \[^\r\n\]+ inf 1" \
+		 "\\s+stop only in [string_to_regexp $bp_restriction]"]
 
 	set bp_pattern_after \
 	    [multi_line \
diff --git a/gdb/testsuite/gdb.multi/pending-bp.exp b/gdb/testsuite/gdb.multi/pending-bp.exp
index 478d8d7c037..aeb8c2c886e 100644
--- a/gdb/testsuite/gdb.multi/pending-bp.exp
+++ b/gdb/testsuite/gdb.multi/pending-bp.exp
@@ -72,6 +72,48 @@ proc do_test_setup { inf_1_stop inf_2_stop } {
     return true
 }
 
+# Create a breakpoint on the function 'foo' in THREAD.  It is expected
+# that the breakpoint created will be pending, this is checked by
+# running the 'info breakpoints' command.
+#
+# Returns the number for the newly created breakpoint.
+proc do_create_pending_foo_breakpoint { {thread "1.1"} } {
+    gdb_test "break foo thread $thread" \
+	[multi_line \
+	     "Function \"foo\" not defined\\." \
+	     "Breakpoint $::decimal \\(foo\\) pending\."] \
+	"set pending thread-specific breakpoint"
+    set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+		   "get number for thread-specific breakpoint on foo"]
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	     "\\s+stop only in thread [string_to_regexp $thread]"] \
+	"check thread-specific breakpoint is initially pending"
+
+    return $bpnum
+}
+
+# Create a breakpoint on the function 'foo' in THREAD.  It is expected
+# that the breakpoint created will not be pending, this is checked by
+# running the 'info breakpoints' command.
+#
+# Returns the number for the newly created breakpoint.
+proc do_create_foo_breakpoint { {thread "1.1"} } {
+    gdb_test "break foo thread $thread" \
+	"Breakpoint $::decimal at $::hex" \
+	"set thread-specific breakpoint"
+    set bpnum [get_integer_valueof "\$bpnum" "*INVALID*" \
+		   "get number for thread-specific breakpoint on foo"]
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex\\s+<foo\[^>\]*> inf $::decimal" \
+	     "\\s+stop only in thread [string_to_regexp $thread]"] \
+	"check thread-specific breakpoint is initially pending"
+
+    return $bpnum
+}
+
 # Check that when a breakpoint is in the pending state, but that breakpoint
 # does have some locations (those locations themselves are pending), GDB
 # doesn't display the inferior list in the 'info breakpoints' output.
@@ -122,5 +164,169 @@ proc_with_prefix test_no_inf_display {} {
 	"check info breakpoints while breakpoint is pending"
 }
 
+# Setup two inferiors.  In #1 the symbol 'foo' has not yet been
+# loaded, while in #2 the symbol 'foo' has been loaded.
+#
+# Create a thread-specific breakpoint on 'foo' tied to a thread in
+# inferior #1, the breakpoint should be pending -- 'foo' is not yet
+# loaded in #1.
+#
+# Now move inferior #1 forward until 'foo' is loaded, check the
+# breakpoint is no longer pending.
+#
+# Move inferior #1 forward more until 'foo' is unloaded, check that
+# the breakpoint returns to the pending state.
+proc_with_prefix test_pending_toggle { } {
+
+    do_test_setup "Break before open" "Break before close"
+
+    set bpnum [do_create_pending_foo_breakpoint]
+
+    # Now return to inferior 1 and continue until the shared library is
+    # loaded, the breakpoint should become non-pending.
+    gdb_test "inferior 1" "Switching to inferior 1 .*" \
+	"switch back to inferior 1"
+    gdb_continue_to_breakpoint "stop in foo in inferior 1" "foo \\(\\) .*"
+
+    gdb_test "info breakpoint $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex <foo\[^>\]*> inf 1" \
+	     "\\s+stop only in thread 1\\.1" \
+	     "\\s+breakpoint already hit 1 time"] \
+	"check thread-specific breakpoint is no longer pending"
+
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "close library"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	     "\\s+stop only in thread 1\\.1" \
+	     "\\s+breakpoint already hit 1 time"] \
+	"check thread-specific breakpoint is pending again"
+}
+
+# Create a Python variable VAR and set it to the gdb.Breakpoint object
+# corresponding to the breakpoint numbered BPNUM.  If THREAD is not
+# the empty string then THREAD should be an integer, check that
+# gdb.Breakpoint.thread is set to the value of THREAD.  Otherwise, if
+# THREAD is the empty string, check that gdb.Breakpoint.thread is set
+# to None.
+proc py_find_breakpoint { var bpnum {thread ""} } {
+    gdb_test_no_output \
+	"python ${var}=\[b for b in gdb.breakpoints() if b.number == $bpnum\]\[0\]" \
+	"find Python gdb.Breakpoint object"
+    if { $thread ne "" } {
+	gdb_test_no_output "python assert(${var}.thread == ${thread})" \
+	    "check thread attribute is currently correct"
+    } else {
+	gdb_test_no_output "python assert(${var}.thread is None)" \
+	    "check thread attribute is currently correct"
+    }
+}
+
+# Setup two inferiors.  In #1 the symbol 'foo' has not yet been
+# loaded, while in #2 the symbol 'foo' has been loaded.
+#
+# Create a thread-specific breakpoint on 'foo' tied to a thread in
+# inferior #1, the breakpoint should be pending -- 'foo' is not yet
+# loaded in #1.
+#
+# Use Python to change the thread of the thread-specific breakpoint to
+# a thread in inferior #2, at this point the thread should gain a
+# location and become non-pending.
+#
+# Set the thread back to a thread in inferior #1, the breakpoint
+# should return to the pending state.
+proc_with_prefix py_test_toggle_thread {} {
+    do_test_setup "Break before open" "Break after open"
+
+    set bpnum [do_create_pending_foo_breakpoint]
+
+    py_find_breakpoint "bp" $bpnum 1
+
+    gdb_test_no_output "python bp.thread = 2" \
+	"change thread on thread-specific breakpoint"
+    gdb_test "info breakpoint $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+$::hex <foo\[^>\]*> inf 2" \
+	     "\\s+stop only in thread 2\\.1"] \
+	"check thread-specific breakpoint now has a location"
+
+    gdb_test_no_output "set call_count = 2" "set call_count in inferior 2"
+    gdb_continue_to_breakpoint "stop at foo in inferior 2" "foo \\(\\) .*"
+
+    gdb_test_no_output "python bp.thread = 1" \
+	"restore thread on thread-specific breakpoint"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "$bpnum\\s+breakpoint\\s+keep\\s+y\\s+<PENDING>\\s+foo" \
+	     "\\s+stop only in thread 1\\.1" \
+	     "\\s+breakpoint already hit 1 time"] \
+	"check thread-specific breakpoint has returned to pending"
+
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "stop after close in inferior 2" \
+	".* Break after close\\. .*"
+
+    gdb_test "inferior 1" "Switching to inferior 1 .*" \
+	"switch to inferior 1"
+    gdb_continue_to_breakpoint "stop at foo in inferior 1" "foo \\(\\) .*"
+}
+
+# Setup two inferiors.  Both inferiors have the symbol 'foo'
+# available.
+#
+# Create a thread-specific breakpoint on 'foo' tied to a thread in
+# inferior #1, the breakpoint should not be pending, but will only
+# have a single location, the location in inferior #1.
+#
+# Use Python to change the thread of the thread-specific breakpoint to
+# None.  At this point the breakpoint should gain a second location, a
+# location in inferior #2.
+proc_with_prefix py_test_clear_thread {} {
+    do_test_setup "Break after open" "Break after open"
+
+    set bpnum [do_create_foo_breakpoint]
+
+    py_find_breakpoint "bp" $bpnum 1
+
+    gdb_test_no_output "python bp.thread = None" \
+	"clear thread on thread-specific breakpoint"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "${bpnum}\\s+breakpoint\\s+keep y\\s+<MULTIPLE>\\s*" \
+	     "${bpnum}\\.1\\s+y\\s+${::hex}\\s+<foo\[^>\]*> inf $::decimal" \
+	     "${bpnum}\\.2\\s+y\\s+${::hex}\\s+<foo\[^>\]*> inf $::decimal"] \
+	"check for a location in both inferiors"
+
+    gdb_continue_to_breakpoint "stop at foo in inferior 2" "foo \\(\\) .*"
+    gdb_test_no_output "set call_count = 2" "set call_count in inferior 2"
+
+    gdb_test "inferior 1" "Switching to inferior 1 .*" \
+	"switch to inferior 1"
+    gdb_continue_to_breakpoint "stop at foo in inferior 1" "foo \\(\\) .*"
+    gdb_test_no_output "set call_count = 2" "set call_count in inferior 1"
+
+    gdb_test_no_output "python bp.thread = 2"
+    gdb_test "info breakpoints $bpnum" \
+	[multi_line \
+	     "${bpnum}\\s+breakpoint\\s+keep y\\s+${::hex}\\s+<foo\[^>\]*> inf 2" \
+	     "\\s+stop only in thread 2\\.1" \
+	     "\\s+breakpoint already hit 2 times"] \
+	"check for a location only in inferior 2"
+
+    gdb_breakpoint [gdb_get_line_number "Break after close"] temporary
+    gdb_continue_to_breakpoint "stop after close in inferior 1" \
+	".* Break after close\\. .*"
+
+    gdb_test "inferior 2" "Switching to inferior 2 .*" \
+	"switch back to inferior 2"
+    gdb_continue_to_breakpoint "stop at foo again in inferior 2" \
+	"foo \\(\\) .*"
+}
+
 # Run all the tests.
 test_no_inf_display
+test_pending_toggle
+py_test_toggle_thread
+py_test_clear_thread
diff --git a/gdb/testsuite/gdb.multi/tids.exp b/gdb/testsuite/gdb.multi/tids.exp
index 573b02fdd42..4f788844ee4 100644
--- a/gdb/testsuite/gdb.multi/tids.exp
+++ b/gdb/testsuite/gdb.multi/tids.exp
@@ -433,11 +433,13 @@ if { [allow_python_tests] } {
 
 	gdb_py_test_silent_cmd "python bp = gdb.breakpoints()\[0\]" \
 	    "get python breakpoint" 0
-	gdb_test "python bp.thread = 6" "thread = 6" \
+	gdb_test_no_output "python bp.thread = 6" \
 	    "make breakpoint thread-specific with python"
 	# Check that the inferior-qualified ID is correct.
 	gdb_test "info breakpoint" \
-	    "stop only in thread 1.3\r\n.*" \
+	    [multi_line \
+		 "$decimal\\s+\[^\r\n\]+ in thread_function1 at \[^\r\n\]+" \
+		 "\\s+stop only in thread 1\\.3"] \
 	    "thread specific breakpoint right thread"
     }
 }
-- 
2.25.4


^ permalink raw reply	[flat|nested] 138+ messages in thread

end of thread, other threads:[~2024-03-31 10:32 UTC | newest]

Thread overview: 138+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2023-04-28 23:35 [PATCH 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
2023-04-28 23:35 ` [PATCH 1/9] gdb: create_breakpoint: assert for a valid thread-id Andrew Burgess
2023-04-28 23:35 ` [PATCH 2/9] gdb: create_breakpoint: asserts relating to extra_string/parse_extra Andrew Burgess
2023-04-28 23:35 ` [PATCH 3/9] gdb: change 'if' to gdb_assert in update_dprintf_command_list Andrew Burgess
2023-04-28 23:35 ` [PATCH 4/9] gdb: build dprintf commands just once in code_breakpoint constructor Andrew Burgess
2023-04-28 23:35 ` [PATCH 5/9] gdb: don't display inferior list for pending breakpoints Andrew Burgess
2023-04-28 23:35 ` [PATCH 6/9] gdb: parse pending breakpoint thread/task immediately Andrew Burgess
2023-04-29  6:01   ` Eli Zaretskii
2023-04-28 23:35 ` [PATCH 7/9] gdb: remove breakpoint_re_set_one Andrew Burgess
2023-04-28 23:35 ` [PATCH 8/9] gdb: remove tracepoint_probe_create_sals_from_location_spec Andrew Burgess
2023-04-28 23:35 ` [PATCH 9/9] gdb: only insert thread-specific breakpoints in the relevant inferior Andrew Burgess
2023-04-29  6:02   ` Eli Zaretskii
2023-05-15 19:27 ` [PATCHv2 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
2023-05-15 19:27   ` [PATCHv2 1/9] gdb: create_breakpoint: assert for a valid thread-id Andrew Burgess
2023-05-15 19:27   ` [PATCHv2 2/9] gdb: create_breakpoint: asserts relating to extra_string/parse_extra Andrew Burgess
2023-05-15 19:27   ` [PATCHv2 3/9] gdb: change 'if' to gdb_assert in update_dprintf_command_list Andrew Burgess
2023-05-15 19:27   ` [PATCHv2 4/9] gdb: build dprintf commands just once in code_breakpoint constructor Andrew Burgess
2023-05-15 19:27   ` [PATCHv2 5/9] gdb: don't display inferior list for pending breakpoints Andrew Burgess
2023-05-15 19:27   ` [PATCHv2 6/9] gdb: parse pending breakpoint thread/task immediately Andrew Burgess
2023-05-15 19:27   ` [PATCHv2 7/9] gdb: remove breakpoint_re_set_one Andrew Burgess
2023-05-15 19:27   ` [PATCHv2 8/9] gdb: remove tracepoint_probe_create_sals_from_location_spec Andrew Burgess
2023-05-15 19:27   ` [PATCHv2 9/9] gdb: only insert thread-specific breakpoints in the relevant inferior Andrew Burgess
2023-05-30 20:46   ` [PATCHv3 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
2023-05-30 20:46     ` [PATCHv3 1/9] gdb: create_breakpoint: assert for a valid thread-id Andrew Burgess
2023-05-30 20:46     ` [PATCHv3 2/9] gdb: create_breakpoint: asserts relating to extra_string/parse_extra Andrew Burgess
2023-05-30 20:46     ` [PATCHv3 3/9] gdb: change 'if' to gdb_assert in update_dprintf_command_list Andrew Burgess
2023-05-30 20:46     ` [PATCHv3 4/9] gdb: build dprintf commands just once in code_breakpoint constructor Andrew Burgess
2023-05-30 20:46     ` [PATCHv3 5/9] gdb: don't display inferior list for pending breakpoints Andrew Burgess
2023-05-30 20:46     ` [PATCHv3 6/9] gdb: parse pending breakpoint thread/task immediately Andrew Burgess
2023-05-30 20:46     ` [PATCHv3 7/9] gdb: remove breakpoint_re_set_one Andrew Burgess
2023-05-30 20:46     ` [PATCHv3 8/9] gdb: remove tracepoint_probe_create_sals_from_location_spec Andrew Burgess
2023-05-30 20:46     ` [PATCHv3 9/9] gdb: only insert thread-specific breakpoints in the relevant inferior Andrew Burgess
2023-08-23 15:59     ` [PATCHv4 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
2023-08-23 15:59       ` [PATCHv4 01/10] gdb: create_breakpoint: add asserts and additional comments Andrew Burgess
2023-08-23 15:59       ` [PATCHv4 02/10] gdb: create_breakpoint: asserts relating to extra_string/parse_extra Andrew Burgess
2023-08-23 15:59       ` [PATCHv4 03/10] gdb: change 'if' to gdb_assert in update_dprintf_command_list Andrew Burgess
2023-08-23 15:59       ` [PATCHv4 04/10] gdb: build dprintf commands just once in code_breakpoint constructor Andrew Burgess
2023-08-23 15:59       ` [PATCHv4 05/10] gdb: don't display inferior list for pending breakpoints Andrew Burgess
2023-08-23 15:59       ` [PATCHv4 06/10] gdb: parse pending breakpoint thread/task immediately Andrew Burgess
2023-08-23 16:32         ` Eli Zaretskii
2023-09-06 22:06         ` Lancelot SIX
2023-10-02 15:02           ` Andrew Burgess
2023-08-23 15:59       ` [PATCHv4 07/10] gdb: don't set breakpoint::pspace for in create_breakpoint Andrew Burgess
2023-08-23 15:59       ` [PATCHv4 08/10] gdb: remove breakpoint_re_set_one Andrew Burgess
2023-08-23 15:59       ` [PATCHv4 09/10] gdb: remove tracepoint_probe_create_sals_from_location_spec Andrew Burgess
2023-08-23 15:59       ` [PATCHv4 10/10] gdb: only insert thread-specific breakpoints in the relevant inferior Andrew Burgess
2023-10-03 21:29       ` [PATCHv5 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
2023-10-03 21:29         ` [PATCHv5 01/10] gdb: create_breakpoint: add asserts and additional comments Andrew Burgess
2023-10-03 21:29         ` [PATCHv5 02/10] gdb: create_breakpoint: asserts relating to extra_string/parse_extra Andrew Burgess
2023-10-03 21:29         ` [PATCHv5 03/10] gdb: change 'if' to gdb_assert in update_dprintf_command_list Andrew Burgess
2023-10-03 21:29         ` [PATCHv5 04/10] gdb: build dprintf commands just once in code_breakpoint constructor Andrew Burgess
2023-10-03 21:29         ` [PATCHv5 05/10] gdb: don't display inferior list for pending breakpoints Andrew Burgess
2023-10-03 21:29         ` [PATCHv5 06/10] gdb: parse pending breakpoint thread/task immediately Andrew Burgess
2023-10-03 21:29         ` [PATCHv5 07/10] gdb: don't set breakpoint::pspace for in create_breakpoint Andrew Burgess
2023-10-03 21:29         ` [PATCHv5 08/10] gdb: remove breakpoint_re_set_one Andrew Burgess
2023-10-03 21:29         ` [PATCHv5 09/10] gdb: remove tracepoint_probe_create_sals_from_location_spec Andrew Burgess
2023-12-02 10:42         ` [PATCHv6 00/10] thread-specific breakpoints in just some inferiors Andrew Burgess
2023-12-02 10:42           ` [PATCHv6 01/10] gdb: create_breakpoint: add asserts and additional comments Andrew Burgess
2023-12-04 19:21             ` Aktemur, Tankut Baris
2023-12-02 10:42           ` [PATCHv6 02/10] gdb: create_breakpoint: asserts relating to extra_string/parse_extra Andrew Burgess
2023-12-04 19:40             ` Aktemur, Tankut Baris
2023-12-02 10:42           ` [PATCHv6 03/10] gdb: change 'if' to gdb_assert in update_dprintf_command_list Andrew Burgess
2023-12-02 10:42           ` [PATCHv6 04/10] gdb: build dprintf commands just once in code_breakpoint constructor Andrew Burgess
2023-12-05  8:17             ` Aktemur, Tankut Baris
2023-12-02 10:42           ` [PATCHv6 05/10] gdb: don't display inferior list for pending breakpoints Andrew Burgess
2023-12-05  8:35             ` Aktemur, Tankut Baris
2023-12-02 10:42           ` [PATCHv6 06/10] gdb: parse pending breakpoint thread/task immediately Andrew Burgess
2023-12-05 15:09             ` Aktemur, Tankut Baris
2023-12-13 13:51               ` Andrew Burgess
2023-12-27 12:23                 ` Aktemur, Tankut Baris
2023-12-02 10:42           ` [PATCHv6 07/10] gdb: don't set breakpoint::pspace for in create_breakpoint Andrew Burgess
2023-12-05 16:05             ` Aktemur, Tankut Baris
2023-12-02 10:42           ` [PATCHv6 08/10] gdb: remove breakpoint_re_set_one Andrew Burgess
2023-12-02 10:42           ` [PATCHv6 09/10] gdb: remove tracepoint_probe_create_sals_from_location_spec Andrew Burgess
2023-12-02 10:42           ` [PATCHv6 10/10] gdb: only insert thread-specific breakpoints in the relevant inferior Andrew Burgess
2023-12-13 22:38           ` [PATCHv7 00/11] thread-specific breakpoints in just some inferiors Andrew Burgess
2023-12-13 22:38             ` [PATCHv7 01/11] gdb: create_breakpoint: add asserts and additional comments Andrew Burgess
2023-12-13 22:38             ` [PATCHv7 02/11] gdb: create_breakpoint: asserts relating to extra_string/parse_extra Andrew Burgess
2023-12-15 20:08               ` Tom Tromey
2023-12-13 22:38             ` [PATCHv7 03/11] gdb: change 'if' to gdb_assert in update_dprintf_command_list Andrew Burgess
2023-12-13 22:38             ` [PATCHv7 04/11] gdb: the extra_string in a dprintf breakpoint is never nullptr Andrew Burgess
2023-12-13 22:38             ` [PATCHv7 05/11] gdb: build dprintf commands just once in code_breakpoint constructor Andrew Burgess
2023-12-13 22:38             ` [PATCHv7 06/11] gdb: don't display inferior list for pending breakpoints Andrew Burgess
2023-12-13 22:38             ` [PATCHv7 07/11] gdb: parse pending breakpoint thread/task immediately Andrew Burgess
2023-12-15 20:53               ` Tom Tromey
2023-12-18 11:33                 ` Andrew Burgess
2023-12-13 22:38             ` [PATCHv7 08/11] gdb: don't set breakpoint::pspace for in create_breakpoint Andrew Burgess
2023-12-13 22:38             ` [PATCHv7 09/11] gdb: remove breakpoint_re_set_one Andrew Burgess
2023-12-13 22:38             ` [PATCHv7 10/11] gdb: remove tracepoint_probe_create_sals_from_location_spec Andrew Burgess
2023-12-13 22:38             ` [PATCHv7 11/11] gdb: only insert thread-specific breakpoints in the relevant inferior Andrew Burgess
2023-12-15 20:54             ` [PATCHv7 00/11] thread-specific breakpoints in just some inferiors Tom Tromey
2023-12-29  9:26             ` [PATCHv8 00/14] " Andrew Burgess
2023-12-29  9:26               ` [PATCHv8 01/14] gdb: create_breakpoint: add asserts and additional comments Andrew Burgess
2023-12-29  9:26               ` [PATCHv8 02/14] gdb: create_breakpoint: asserts relating to extra_string/parse_extra Andrew Burgess
2023-12-29  9:26               ` [PATCHv8 03/14] gdb: change 'if' to gdb_assert in update_dprintf_command_list Andrew Burgess
2023-12-29  9:26               ` [PATCHv8 04/14] gdb: the extra_string in a dprintf breakpoint is never nullptr Andrew Burgess
2023-12-29  9:27               ` [PATCHv8 05/14] gdb: build dprintf commands just once in code_breakpoint constructor Andrew Burgess
2023-12-29  9:27               ` [PATCHv8 06/14] gdb: don't display inferior list for pending breakpoints Andrew Burgess
2023-12-29  9:27               ` [PATCHv8 07/14] gdb: remove breakpoint_re_set_one Andrew Burgess
2023-12-29  9:27               ` [PATCHv8 08/14] gdb: remove tracepoint_probe_create_sals_from_location_spec Andrew Burgess
2023-12-29  9:27               ` [PATCHv8 09/14] gdb: make breakpoint_debug_printf global Andrew Burgess
2023-12-29  9:27               ` [PATCHv8 10/14] gdb: add another overload of startswith Andrew Burgess
2023-12-29  9:27               ` [PATCHv8 11/14] gdb: create new is_thread_id helper function Andrew Burgess
2023-12-29  9:27               ` [PATCHv8 12/14] gdb: parse pending breakpoint thread/task immediately Andrew Burgess
2023-12-29  9:27               ` [PATCHv8 13/14] gdb: don't set breakpoint::pspace in create_breakpoint Andrew Burgess
2023-12-29  9:27               ` [PATCHv8 14/14] gdb: only insert thread-specific breakpoints in the relevant inferior Andrew Burgess
2024-03-05 15:21               ` [PATCHv9 00/14] thread-specific breakpoints in just some inferiors Andrew Burgess
2024-03-05 15:21                 ` [PATCHv9 01/14] gdb: create_breakpoint: add asserts and additional comments Andrew Burgess
2024-03-31 10:26                   ` Andrew Burgess
2024-03-05 15:21                 ` [PATCHv9 02/14] gdb: create_breakpoint: asserts relating to extra_string/parse_extra Andrew Burgess
2024-03-31 10:26                   ` Andrew Burgess
2024-03-05 15:21                 ` [PATCHv9 03/14] gdb: change 'if' to gdb_assert in update_dprintf_command_list Andrew Burgess
2024-03-31 10:27                   ` Andrew Burgess
2024-03-05 15:21                 ` [PATCHv9 04/14] gdb: the extra_string in a dprintf breakpoint is never nullptr Andrew Burgess
2024-03-31 10:27                   ` Andrew Burgess
2024-03-05 15:21                 ` [PATCHv9 05/14] gdb: build dprintf commands just once in code_breakpoint constructor Andrew Burgess
2024-03-31 10:27                   ` Andrew Burgess
2024-03-05 15:21                 ` [PATCHv9 06/14] gdb: don't display inferior list for pending breakpoints Andrew Burgess
2024-03-05 15:21                 ` [PATCHv9 07/14] gdb: remove breakpoint_re_set_one Andrew Burgess
2024-03-05 15:21                 ` [PATCHv9 08/14] gdb: remove tracepoint_probe_create_sals_from_location_spec Andrew Burgess
2024-03-05 15:21                 ` [PATCHv9 09/14] gdb: make breakpoint_debug_printf global Andrew Burgess
2024-03-05 15:21                 ` [PATCHv9 10/14] gdb: add another overload of startswith Andrew Burgess
2024-03-05 15:21                 ` [PATCHv9 11/14] gdb: create new is_thread_id helper function Andrew Burgess
2024-03-05 15:21                 ` [PATCHv9 12/14] gdb: parse pending breakpoint thread/task immediately Andrew Burgess
2024-03-05 15:21                 ` [PATCHv9 13/14] gdb: don't set breakpoint::pspace in create_breakpoint Andrew Burgess
2024-03-05 15:21                 ` [PATCHv9 14/14] gdb: only insert thread-specific breakpoints in the relevant inferior Andrew Burgess
2024-03-05 15:49                   ` Willgerodt, Felix
2024-03-06 14:11                     ` Andrew Burgess
2024-03-31 10:31                 ` [PATCHv10 0/9] thread-specific breakpoints in just some inferiors Andrew Burgess
2024-03-31 10:31                   ` [PATCHv10 1/9] gdb: don't display inferior list for pending breakpoints Andrew Burgess
2024-03-31 10:31                   ` [PATCHv10 2/9] gdb: remove breakpoint_re_set_one Andrew Burgess
2024-03-31 10:31                   ` [PATCHv10 3/9] gdb: remove tracepoint_probe_create_sals_from_location_spec Andrew Burgess
2024-03-31 10:31                   ` [PATCHv10 4/9] gdb: make breakpoint_debug_printf global Andrew Burgess
2024-03-31 10:31                   ` [PATCHv10 5/9] gdb: add another overload of startswith Andrew Burgess
2024-03-31 10:31                   ` [PATCHv10 6/9] gdb: create new is_thread_id helper function Andrew Burgess
2024-03-31 10:31                   ` [PATCHv10 7/9] gdb: parse pending breakpoint thread/task immediately Andrew Burgess
2024-03-31 10:31                   ` [PATCHv10 8/9] gdb: don't set breakpoint::pspace in create_breakpoint Andrew Burgess
2024-03-31 10:31                   ` [PATCHv10 9/9] gdb: only insert thread-specific breakpoints in the relevant inferior Andrew Burgess

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).