public inbox for gdb-patches@sourceware.org
 help / color / mirror / Atom feed
* [PATCH 00/12] Infcalls from B/P conditions in multi-threaded inferiors
@ 2022-10-21  8:43 Andrew Burgess
  2022-10-21  8:43 ` [PATCH 01/12] gdb: int to bool conversion for normal_stop Andrew Burgess
                   ` (12 more replies)
  0 siblings, 13 replies; 202+ messages in thread
From: Andrew Burgess @ 2022-10-21  8:43 UTC (permalink / raw)
  To: gdb-patches

This series aims to fix PR gdb/28942, GDB's inability to use inferior
function calls from breakpoint conditions in multi-threaded inferiors.

This work draws on the work done in this patch:

  https://sourceware.org/pipermail/gdb-patches/2021-March/176654.html

Some of the changes in that series can be found in patch 10 in this
series.

There's a lot of patches here, but the work is really made of several
mini-series:

  Patches 01 and 02 are trivial cleanup and debug output patches.
  These could probably be committed as obvious.

  Patch 03 improves the error message GDB gives when there is an error
  while evaluating a breakpoint condition.

  Patches 04, 05, and 06 are some gdbserver cleanup and then a
  gdbserver bug fix.

  Patches 07 and 08 are two further improvements for how the error is
  reported when a GDB fails to evaluate a breakpoint condition.

  Patches 09 and 10 actually fix using inferior function calls from
  breakpoint conditions in multi-threaded inferiors.

  Patch 11 is some new functionality to hopefully make GDB more robust
  when using inferior function calls, especially from a breakpoint
  condition.  This patch is optional, we could stop at patch 10 if the
  ideas in this patch are not acceptable.

  Patch 12 is an adjustment for remote targets when not running in
  non-stop mode to improve how stops are reported to the user.  Like
  patch 11, this work is optional.  We could stop at either patch 10
  or patch 11 if the work in this patch is not acceptable.

Thanks,
Andrew

---

Andrew Burgess (12):
  gdb: int to bool conversion for normal_stop
  gdb/infrun: add debug print in print_signal_received_reason
  gdb: include breakpoint number in testing condition error message
  gdbserver: add comments to read_inferior_memory function
  gdbserver: allows agent_mem_read to return an error code
  gdbserver: allow agent expressions to fail with invalid memory access
  gdb: avoid repeated signal reporting during failed conditional
    breakpoint
  gdb: don't always print breakpoint location after failed condition
    check
  Revert "gdb: remove unnecessary parameter wait_ptid from
    do_target_wait"
  gdb: fix b/p conditions with infcalls in multi-threaded inferiors
  gdb: add timeouts for inferior function calls
  gdb/remote: avoid SIGINT after calling remote_target::stop

 gdb/NEWS                                      |  16 ++
 gdb/breakpoint.c                              |  17 +-
 gdb/doc/gdb.texinfo                           |  45 ++++
 gdb/gdbthread.h                               |   3 +
 gdb/infcall.c                                 | 174 +++++++++++++
 gdb/infcmd.c                                  |   2 +-
 gdb/infrun.c                                  |  60 +++--
 gdb/infrun.h                                  |   4 +-
 gdb/remote.c                                  |  17 ++
 gdb/testsuite/gdb.base/bp-cond-failure.c      |  30 +++
 gdb/testsuite/gdb.base/bp-cond-failure.exp    |  81 ++++++
 .../gdb.base/catch-signal-siginfo-cond.exp    |   2 +-
 gdb/testsuite/gdb.base/gnu-ifunc.exp          |   2 +-
 gdb/testsuite/gdb.base/help.exp               |   2 +-
 gdb/testsuite/gdb.base/infcall-failure.c      |  48 ++++
 gdb/testsuite/gdb.base/infcall-failure.exp    | 182 ++++++++++++++
 gdb/testsuite/gdb.base/infcall-timeout.c      |  36 +++
 gdb/testsuite/gdb.base/infcall-timeout.exp    |  74 ++++++
 .../gdb.python/py-finish-breakpoint.exp       |   2 +-
 .../infcall-from-bp-cond-other-thread-event.c | 135 ++++++++++
 ...nfcall-from-bp-cond-other-thread-event.exp | 175 +++++++++++++
 .../gdb.threads/infcall-from-bp-cond-simple.c |  89 +++++++
 .../infcall-from-bp-cond-simple.exp           | 236 ++++++++++++++++++
 .../gdb.threads/infcall-from-bp-cond-single.c | 139 +++++++++++
 .../infcall-from-bp-cond-single.exp           | 119 +++++++++
 .../infcall-from-bp-cond-timeout.c            | 169 +++++++++++++
 .../infcall-from-bp-cond-timeout.exp          | 121 +++++++++
 gdb/testsuite/lib/gdb.exp                     |   8 +
 gdbserver/ax.cc                               |  12 +-
 gdbserver/ax.h                                |   3 +-
 gdbserver/target.cc                           |   2 +
 gdbserver/target.h                            |   3 +
 gdbserver/tracepoint.cc                       |  13 +-
 gdbserver/tracepoint.h                        |   9 +-
 34 files changed, 1992 insertions(+), 38 deletions(-)
 create mode 100644 gdb/testsuite/gdb.base/bp-cond-failure.c
 create mode 100644 gdb/testsuite/gdb.base/bp-cond-failure.exp
 create mode 100644 gdb/testsuite/gdb.base/infcall-failure.c
 create mode 100644 gdb/testsuite/gdb.base/infcall-failure.exp
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.c
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp

-- 
2.25.4


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

* [PATCH 01/12] gdb: int to bool conversion for normal_stop
  2022-10-21  8:43 [PATCH 00/12] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
@ 2022-10-21  8:43 ` Andrew Burgess
  2022-11-04 12:20   ` Lancelot SIX
  2022-10-21  8:43 ` [PATCH 02/12] gdb/infrun: add debug print in print_signal_received_reason Andrew Burgess
                   ` (11 subsequent siblings)
  12 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2022-10-21  8:43 UTC (permalink / raw)
  To: gdb-patches

Change the return type of normal_stop (infrun.c) from int to bool.
Update callers.

There should be no user visible changes after this commit.
---
 gdb/infcmd.c | 2 +-
 gdb/infrun.c | 6 +++---
 gdb/infrun.h | 2 +-
 3 files changed, 5 insertions(+), 5 deletions(-)

diff --git a/gdb/infcmd.c b/gdb/infcmd.c
index d729732c81c..6af11ac0cb6 100644
--- a/gdb/infcmd.c
+++ b/gdb/infcmd.c
@@ -873,7 +873,7 @@ step_1 (int skip_subroutines, int single_inst, const char *count_string)
     proceed ((CORE_ADDR) -1, GDB_SIGNAL_DEFAULT);
   else
     {
-      int proceeded;
+      bool proceeded;
 
       /* Stepped into an inline frame.  Pretend that we've
 	 stopped.  */
diff --git a/gdb/infrun.c b/gdb/infrun.c
index cdfe02393f5..39840ef32c8 100644
--- a/gdb/infrun.c
+++ b/gdb/infrun.c
@@ -8614,7 +8614,7 @@ stop_context::changed () const
 
 /* See infrun.h.  */
 
-int
+bool
 normal_stop (void)
 {
   struct target_waitstatus last;
@@ -8774,7 +8774,7 @@ normal_stop (void)
      the observers would print a stop for the wrong
      thread/inferior.  */
   if (saved_context.changed ())
-    return 1;
+    return true;
 
   /* Notify observers about the stop.  This is where the interpreters
      print the stop event.  */
@@ -8796,7 +8796,7 @@ normal_stop (void)
 	breakpoint_auto_delete (inferior_thread ()->control.stop_bpstat);
     }
 
-  return 0;
+  return false;
 }
 \f
 int
diff --git a/gdb/infrun.h b/gdb/infrun.h
index c711b9b21cc..11a18583e68 100644
--- a/gdb/infrun.h
+++ b/gdb/infrun.h
@@ -149,7 +149,7 @@ extern process_stratum_target *user_visible_resume_target (ptid_t resume_ptid);
    appropriate messages, remove breakpoints, give terminal our modes,
    and run the stop hook.  Returns true if the stop hook proceeded the
    target, false otherwise.  */
-extern int normal_stop (void);
+extern bool normal_stop (void);
 
 /* Return the cached copy of the last target/ptid/waitstatus returned
    by target_wait().  The data is actually cached by handle_inferior_event(),
-- 
2.25.4


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

* [PATCH 02/12] gdb/infrun: add debug print in print_signal_received_reason
  2022-10-21  8:43 [PATCH 00/12] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
  2022-10-21  8:43 ` [PATCH 01/12] gdb: int to bool conversion for normal_stop Andrew Burgess
@ 2022-10-21  8:43 ` Andrew Burgess
  2023-01-13 16:38   ` Andrew Burgess
  2022-10-21  8:43 ` [PATCH 03/12] gdb: include breakpoint number in testing condition error message Andrew Burgess
                   ` (10 subsequent siblings)
  12 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2022-10-21  8:43 UTC (permalink / raw)
  To: gdb-patches

It would have helped me to see an infrun debug line being printed from
print_signal_received_reason, so I'm adding one.
---
 gdb/infrun.c | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/gdb/infrun.c b/gdb/infrun.c
index 39840ef32c8..c28bf28a4d9 100644
--- a/gdb/infrun.c
+++ b/gdb/infrun.c
@@ -8393,6 +8393,8 @@ print_signal_received_reason (struct ui_out *uiout, enum gdb_signal siggnal)
 {
   struct thread_info *thr = inferior_thread ();
 
+  infrun_debug_printf ("signal = %s", gdb_signal_to_string (siggnal));
+
   annotate_signal ();
 
   if (uiout->is_mi_like_p ())
-- 
2.25.4


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

* [PATCH 03/12] gdb: include breakpoint number in testing condition error message
  2022-10-21  8:43 [PATCH 00/12] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
  2022-10-21  8:43 ` [PATCH 01/12] gdb: int to bool conversion for normal_stop Andrew Burgess
  2022-10-21  8:43 ` [PATCH 02/12] gdb/infrun: add debug print in print_signal_received_reason Andrew Burgess
@ 2022-10-21  8:43 ` Andrew Burgess
  2022-10-21  8:43 ` [PATCH 04/12] gdbserver: add comments to read_inferior_memory function Andrew Burgess
                   ` (9 subsequent siblings)
  12 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2022-10-21  8:43 UTC (permalink / raw)
  To: gdb-patches

When GDB fails to test the condition of a conditional breakpoint, for
whatever reason, the error message looks like this:

  (gdb) break foo if (*(int *) 0) == 1
  Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
  (gdb) r
  Starting program: /tmp/bpcond
  Error in testing breakpoint condition:
  Cannot access memory at address 0x0

  Breakpoint 1, foo () at bpcond.c:11
  11	  int a = 32;
  (gdb)

The line I'm interested in for this commit is this one:

  Error in testing breakpoint condition:

In the case above we can figure out that the problematic breakpoint
was #1 because in the final line of the message GDB reports the stop a
breakpoint #1.

However, in the next few patches I plan to change this.  In some cases
I don't think it makes sense for GDB to report the stop as being at
breakpoint #1, consider this case:

  (gdb) list some_func
  1	int
  2	some_func ()
  3	{
  4	  int *p = 0;
  5	  return *p;
  6	}
  7
  8	void
  9	foo ()
  10	{
  (gdb) break foo if (some_func ())
  Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
  (gdb) r
  Starting program: /tmp/bpcond

  Program received signal SIGSEGV, Segmentation fault.
  0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  Error in testing breakpoint condition:
  The program being debugged was signaled while in a function called from GDB.
  GDB remains in the frame where the signal was received.
  To change this behavior use "set unwindonsignal on".
  Evaluation of the expression containing the function
  (some_func) will be abandoned.
  When the function is done executing, GDB will silently stop.

  Program received signal SIGSEGV, Segmentation fault.

  Breakpoint 1, 0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  (gdb)

Notice that, the final lines of output report the stop as being at
breakpoint #1, even though we are actually located within some_func.

I find this behaviour confusing, and propose that this should be
changed.  However, if I make that change then every reference to
breakpoint #1 will be lost from the error message.

So, in this commit, in preparation for the later commits, I propose to
change the 'Error in testing breakpoint condition:' line to this:

  Error in testing condition for breakpoint NUMBER:

where NUMBER will be filled in as appropriate.  Here's the first
example with the updated error:

  (gdb) break foo if (*(int *) 0) == 0
  Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
  (gdb) r
  Starting program: /tmp/bpcond
  Error in testing condition for breakpoint 1:
  Cannot access memory at address 0x0

  Breakpoint 1, foo () at bpcond.c:11
  11	  int a = 32;
  (gdb)

The breakpoint number does now appear twice in the output, but I don't
see that as a negative.

This commit just changes the one line of the error, and updates the
few tests that either included the old error in comments, or actually
checked for the error in the expected output.

As the only test that checked the line I modified is a Python test,
I've added a new test that doesn't rely on Python that checks the
error message in detail.

While working on the new test, I spotted that it would fail when run
with native-gdbserver and native-extended-gdbserver target boards.
This turns out to be due to a gdbserver bug.  To avoid cluttering this
commit I've added a work around to the new test script so that the
test passes for the remote boards, in the next few commits I will fix
gdbserver, and update the test script to remove the work around.
---
 gdb/breakpoint.c                              |  3 +-
 gdb/testsuite/gdb.base/bp-cond-failure.c      | 30 +++++++
 gdb/testsuite/gdb.base/bp-cond-failure.exp    | 83 +++++++++++++++++++
 .../gdb.base/catch-signal-siginfo-cond.exp    |  2 +-
 gdb/testsuite/gdb.base/gnu-ifunc.exp          |  2 +-
 .../gdb.python/py-finish-breakpoint.exp       |  2 +-
 gdb/testsuite/lib/gdb.exp                     |  8 ++
 7 files changed, 126 insertions(+), 4 deletions(-)
 create mode 100644 gdb/testsuite/gdb.base/bp-cond-failure.c
 create mode 100644 gdb/testsuite/gdb.base/bp-cond-failure.exp

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 91e13a03360..4f5a27a6fe8 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -5412,7 +5412,8 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
 	  catch (const gdb_exception &ex)
 	    {
 	      exception_fprintf (gdb_stderr, ex,
-				 "Error in testing breakpoint condition:\n");
+				 "Error in testing condition for breakpoint %d:\n",
+				 b->number);
 	    }
 	}
       else
diff --git a/gdb/testsuite/gdb.base/bp-cond-failure.c b/gdb/testsuite/gdb.base/bp-cond-failure.c
new file mode 100644
index 00000000000..be9d1fdcf2d
--- /dev/null
+++ b/gdb/testsuite/gdb.base/bp-cond-failure.c
@@ -0,0 +1,30 @@
+/* Copyright 2022 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/>.  */
+
+int
+foo ()
+{
+  return 0;	/* Breakpoint here.  */
+}
+
+int
+main ()
+{
+  int res = foo ();
+
+  return res;
+}
diff --git a/gdb/testsuite/gdb.base/bp-cond-failure.exp b/gdb/testsuite/gdb.base/bp-cond-failure.exp
new file mode 100644
index 00000000000..6f89771d187
--- /dev/null
+++ b/gdb/testsuite/gdb.base/bp-cond-failure.exp
@@ -0,0 +1,83 @@
+# Copyright 2022 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/>.
+
+# Check the format of the error message given when a breakpoint
+# condition fails.
+#
+# In this case the breakpoint condition does not make use of inferior
+# function calls, instead, the expression used for the breakpoint
+# condition will throw an error when evaluated.
+#
+# We check that the correct breakpoint number appears in the error
+# message, and that the error is reported at the correct source
+# location.
+
+standard_testfile
+
+if { [prepare_for_testing "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug}] == -1 } {
+    return
+}
+
+# This test relies on reading address zero triggering a SIGSEGV.
+if { [is_address_zero_readable] } {
+    return
+}
+
+# Where the breakpoint will be placed.
+set bp_line [gdb_get_line_number "Breakpoint here"]
+
+proc run_test { cond_eval } {
+    clean_restart ${::binfile}
+
+    if {![runto_main]} {
+	fail "run to main"
+	return -1
+    }
+
+    if { $cond_eval != "auto" } {
+	gdb_test_no_output "set breakpoint condition-evaluation ${cond_eval}"
+    }
+
+    # Setup the conditional breakpoint and record its number.
+    gdb_breakpoint "${::srcfile}:${::bp_line} if (*(int *) 0) == 0"
+    set bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*"]
+
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     "Error in testing condition for breakpoint ${bp_num}:" \
+	     "Cannot access memory at address 0x0" \
+	     "" \
+	     "Breakpoint ${bp_num}, foo \\(\\) at \[^\r\n\]+:${::bp_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Breakpoint here\[^\r\n\]+"]
+}
+
+# If we're using a remote target then conditions could be evaulated
+# locally on the host, or on the remote target.  Otherwise, conditions
+# are always evaluated locally (which is what auto will select).
+#
+# NOTE: 'target' is not included here for remote targets as a
+# gdbserver bug prevents the test from passing.  This will be fixed in
+# the next commit, and this test updated.
+if { [gdb_is_remote_or_extended_remote_target] } {
+    set cond_eval_modes { "host" }
+} else {
+    set cond_eval_modes { "auto" }
+}
+
+foreach_with_prefix cond_eval $cond_eval_modes {
+    run_test $cond_eval
+}
diff --git a/gdb/testsuite/gdb.base/catch-signal-siginfo-cond.exp b/gdb/testsuite/gdb.base/catch-signal-siginfo-cond.exp
index 85a55b29ea5..d5fdbae2409 100644
--- a/gdb/testsuite/gdb.base/catch-signal-siginfo-cond.exp
+++ b/gdb/testsuite/gdb.base/catch-signal-siginfo-cond.exp
@@ -18,7 +18,7 @@
 #
 # (gdb) continue
 # Continuing.
-# Error in testing breakpoint condition:
+# Error in testing condition for breakpoint NUM:
 # Selected thread is running.
 #
 # Catchpoint 3 (signal SIGUSR1), 0x0000003615e35877 in __GI_raise (sig=10) at raise.c:56
diff --git a/gdb/testsuite/gdb.base/gnu-ifunc.exp b/gdb/testsuite/gdb.base/gnu-ifunc.exp
index 3fbf237c71c..cbdcbbf07b4 100644
--- a/gdb/testsuite/gdb.base/gnu-ifunc.exp
+++ b/gdb/testsuite/gdb.base/gnu-ifunc.exp
@@ -282,7 +282,7 @@ proc misc_tests {resolver_attr resolver_debug final_debug} {
 
     # Also test a former patch regression:
     # Continuing.
-    # Error in testing breakpoint condition:
+    # Error in testing condition for breakpoint NUM:
     # Attempt to take address of value not located in memory.
     #
     # Breakpoint 2, main () at ./gdb.base/gnu-ifunc.c:33
diff --git a/gdb/testsuite/gdb.python/py-finish-breakpoint.exp b/gdb/testsuite/gdb.python/py-finish-breakpoint.exp
index c525337990e..d873fd5cd0f 100644
--- a/gdb/testsuite/gdb.python/py-finish-breakpoint.exp
+++ b/gdb/testsuite/gdb.python/py-finish-breakpoint.exp
@@ -193,7 +193,7 @@ with_test_prefix "finish in normal frame" {
     gdb_test "python TestBreakpoint()" "TestBreakpoint init" "set BP in condition"
 
     gdb_test "continue" \
-	"test don't stop: 1.*test don't stop: 2.*test stop.*Error in testing breakpoint condition.*The program being debugged stopped while in a function called from GDB.*" \
+	"test don't stop: 1.*test don't stop: 2.*test stop.*Error in testing condition for breakpoint ${::decimal}.*The program being debugged stopped while in a function called from GDB.*" \
 	"stop in condition function"
 
     gdb_test "continue" "Continuing.*" "finish condition evaluation"
diff --git a/gdb/testsuite/lib/gdb.exp b/gdb/testsuite/lib/gdb.exp
index c510ab25365..528e97bf099 100644
--- a/gdb/testsuite/lib/gdb.exp
+++ b/gdb/testsuite/lib/gdb.exp
@@ -9122,5 +9122,13 @@ gdb_caching_proc have_epilogue_line_info {
     }
 }
 
+# Return true if we are currently testing the 'remote' or
+# 'extended-remote' targets.
+proc gdb_is_remote_or_extended_remote_target {} {
+    return [target_info exists gdb_protocol]
+	   && ([target_info gdb_protocol] == "remote"
+	       || [target_info gdb_protocol] == "extended-remote")
+}
+
 # Always load compatibility stuff.
 load_lib future.exp
-- 
2.25.4


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

* [PATCH 04/12] gdbserver: add comments to read_inferior_memory function
  2022-10-21  8:43 [PATCH 00/12] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                   ` (2 preceding siblings ...)
  2022-10-21  8:43 ` [PATCH 03/12] gdb: include breakpoint number in testing condition error message Andrew Burgess
@ 2022-10-21  8:43 ` Andrew Burgess
  2023-01-13 16:42   ` Andrew Burgess
  2022-10-21  8:43 ` [PATCH 05/12] gdbserver: allows agent_mem_read to return an error code Andrew Burgess
                   ` (8 subsequent siblings)
  12 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2022-10-21  8:43 UTC (permalink / raw)
  To: gdb-patches

Just adding some comments to the gdbserver read_inferior_memory
function.  No actual code changes.
---
 gdbserver/target.cc     | 2 ++
 gdbserver/target.h      | 3 +++
 gdbserver/tracepoint.cc | 2 ++
 3 files changed, 7 insertions(+)

diff --git a/gdbserver/target.cc b/gdbserver/target.cc
index adcfe6e7bcc..6b29c99a61b 100644
--- a/gdbserver/target.cc
+++ b/gdbserver/target.cc
@@ -79,6 +79,8 @@ set_desired_process ()
   return proc != nullptr;
 }
 
+/* See target.h.  */
+
 int
 read_inferior_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
 {
diff --git a/gdbserver/target.h b/gdbserver/target.h
index 6c536a30778..a49d7d4bac0 100644
--- a/gdbserver/target.h
+++ b/gdbserver/target.h
@@ -697,6 +697,9 @@ target_thread_pending_child (thread_info *thread)
   return the_target->thread_pending_child (thread);
 }
 
+/* Read LEN bytes from MEMADDR in the buffer MYADDR.  Return 0 if the read
+   is successful, otherwise, return a non-zero error code.  */
+
 int read_inferior_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len);
 
 /* Set GDBserver's current thread to the thread the client requested
diff --git a/gdbserver/tracepoint.cc b/gdbserver/tracepoint.cc
index 18b2b0b3d77..efcdfe12beb 100644
--- a/gdbserver/tracepoint.cc
+++ b/gdbserver/tracepoint.cc
@@ -344,6 +344,8 @@ tracepoint_look_up_symbols (void)
    GDBserver side.  */
 
 #ifdef IN_PROCESS_AGENT
+/* See target.h.  */
+
 int
 read_inferior_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
 {
-- 
2.25.4


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

* [PATCH 05/12] gdbserver: allows agent_mem_read to return an error code
  2022-10-21  8:43 [PATCH 00/12] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                   ` (3 preceding siblings ...)
  2022-10-21  8:43 ` [PATCH 04/12] gdbserver: add comments to read_inferior_memory function Andrew Burgess
@ 2022-10-21  8:43 ` Andrew Burgess
  2022-10-21  8:43 ` [PATCH 06/12] gdbserver: allow agent expressions to fail with invalid memory access Andrew Burgess
                   ` (7 subsequent siblings)
  12 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2022-10-21  8:43 UTC (permalink / raw)
  To: gdb-patches

Currently the gdbserver function agent_mem_read ignores any errors
from calling read_inferior_memory.  This means that if there is an
attempt to access invalid memory then this will appear to succeed.

In this I update agent_mem_read so that if read_inferior_memory fails,
agent_mem_read will return an error code.

However, non of the callers of agent_mem_read actually check the
return value, so this commit will have no effect on anything.  In the
next commit I will update the users of agent_mem_read to check for the
error code.

I've also updated the header comments on agent_mem_read to better
reflect what the function does, and its possible return values.
---
 gdbserver/tracepoint.cc | 11 ++++-------
 gdbserver/tracepoint.h  |  9 +++++++--
 2 files changed, 11 insertions(+), 9 deletions(-)

diff --git a/gdbserver/tracepoint.cc b/gdbserver/tracepoint.cc
index efcdfe12beb..74774759d3a 100644
--- a/gdbserver/tracepoint.cc
+++ b/gdbserver/tracepoint.cc
@@ -4923,8 +4923,7 @@ condition_true_at_tracepoint (struct tracepoint_hit_ctx *ctx,
   return (value ? 1 : 0);
 }
 
-/* Do memory copies for bytecodes.  */
-/* Do the recording of memory blocks for actions and bytecodes.  */
+/* See tracepoint.h.  */
 
 int
 agent_mem_read (struct eval_agent_expr_context *ctx,
@@ -4936,10 +4935,7 @@ agent_mem_read (struct eval_agent_expr_context *ctx,
 
   /* If a 'to' buffer is specified, use it.  */
   if (to != NULL)
-    {
-      read_inferior_memory (from, to, len);
-      return 0;
-    }
+    return read_inferior_memory (from, to, len);
 
   /* Otherwise, create a new memory block in the trace buffer.  */
   while (remaining > 0)
@@ -4960,7 +4956,8 @@ agent_mem_read (struct eval_agent_expr_context *ctx,
       memcpy (mspace, &blocklen, sizeof (blocklen));
       mspace += sizeof (blocklen);
       /* Record the memory block proper.  */
-      read_inferior_memory (from, mspace, blocklen);
+      if (read_inferior_memory (from, mspace, blocklen) != 0)
+	return 1;
       trace_debug ("%d bytes recorded", blocklen);
       remaining -= blocklen;
       from += blocklen;
diff --git a/gdbserver/tracepoint.h b/gdbserver/tracepoint.h
index bbffb6228f4..afab22b214d 100644
--- a/gdbserver/tracepoint.h
+++ b/gdbserver/tracepoint.h
@@ -161,8 +161,13 @@ void gdb_agent_about_to_close (int pid);
 struct traceframe;
 struct eval_agent_expr_context;
 
-/* Do memory copies for bytecodes.  */
-/* Do the recording of memory blocks for actions and bytecodes.  */
+/* When TO is not NULL, do memory copies for bytecodes, read LEN bytes
+   starting at address FROM, and place the result in the buffer TO.
+   Return 0 on success, otherwise a non-zero error code.
+
+   When TO is NULL, do the recording of memory blocks for actions and
+   bytecodes into a new traceframe block.  Return 0 on success, otherwise,
+   return 1 if there is an error.  */
 
 int agent_mem_read (struct eval_agent_expr_context *ctx,
 		    unsigned char *to, CORE_ADDR from,
-- 
2.25.4


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

* [PATCH 06/12] gdbserver: allow agent expressions to fail with invalid memory access
  2022-10-21  8:43 [PATCH 00/12] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                   ` (4 preceding siblings ...)
  2022-10-21  8:43 ` [PATCH 05/12] gdbserver: allows agent_mem_read to return an error code Andrew Burgess
@ 2022-10-21  8:43 ` Andrew Burgess
  2022-10-21  8:43 ` [PATCH 07/12] gdb: avoid repeated signal reporting during failed conditional breakpoint Andrew Burgess
                   ` (6 subsequent siblings)
  12 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2022-10-21  8:43 UTC (permalink / raw)
  To: gdb-patches

This commit extends gdbserver to take account of a failed memory
access from agent_mem_read, and to return a new eval_result_type
expr_eval_invalid_memory_access.

I have only updated the agent_mem_read calls related directly to
reading memory, I have not updated any of the calls related to
tracepoint data collection.  This is just because I'm not familiar
with that area of gdb/gdbserver, and I don't want to break anything,
so leaving the existing behaviour as is seems like the safest
approach.

I've then update gdb.base/bp-cond-failure.exp to test evaluating the
breakpoints on the target, and have also extended the test so that it
checks for different sizes of memory access.
---
 gdb/testsuite/gdb.base/bp-cond-failure.exp | 16 +++++++---------
 gdbserver/ax.cc                            | 12 ++++++++----
 gdbserver/ax.h                             |  3 ++-
 3 files changed, 17 insertions(+), 14 deletions(-)

diff --git a/gdb/testsuite/gdb.base/bp-cond-failure.exp b/gdb/testsuite/gdb.base/bp-cond-failure.exp
index 6f89771d187..aa39b638592 100644
--- a/gdb/testsuite/gdb.base/bp-cond-failure.exp
+++ b/gdb/testsuite/gdb.base/bp-cond-failure.exp
@@ -39,7 +39,7 @@ if { [is_address_zero_readable] } {
 # Where the breakpoint will be placed.
 set bp_line [gdb_get_line_number "Breakpoint here"]
 
-proc run_test { cond_eval } {
+proc run_test { cond_eval access_type } {
     clean_restart ${::binfile}
 
     if {![runto_main]} {
@@ -52,7 +52,7 @@ proc run_test { cond_eval } {
     }
 
     # Setup the conditional breakpoint and record its number.
-    gdb_breakpoint "${::srcfile}:${::bp_line} if (*(int *) 0) == 0"
+    gdb_breakpoint "${::srcfile}:${::bp_line} if (*(${access_type} *) 0) == 0"
     set bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*"]
 
     gdb_test "continue" \
@@ -68,16 +68,14 @@ proc run_test { cond_eval } {
 # If we're using a remote target then conditions could be evaulated
 # locally on the host, or on the remote target.  Otherwise, conditions
 # are always evaluated locally (which is what auto will select).
-#
-# NOTE: 'target' is not included here for remote targets as a
-# gdbserver bug prevents the test from passing.  This will be fixed in
-# the next commit, and this test updated.
 if { [gdb_is_remote_or_extended_remote_target] } {
-    set cond_eval_modes { "host" }
+    set cond_eval_modes { "host" "target" }
 } else {
     set cond_eval_modes { "auto" }
 }
 
-foreach_with_prefix cond_eval $cond_eval_modes {
-    run_test $cond_eval
+foreach_with_prefix access_type { "char" "short" "int" "long long" } {
+    foreach_with_prefix cond_eval $cond_eval_modes {
+	run_test $cond_eval $access_type
+    }
 }
diff --git a/gdbserver/ax.cc b/gdbserver/ax.cc
index 365bd2195b2..377ac9682a6 100644
--- a/gdbserver/ax.cc
+++ b/gdbserver/ax.cc
@@ -1112,22 +1112,26 @@ gdb_eval_agent_expr (struct eval_agent_expr_context *ctx,
 	  break;
 
 	case gdb_agent_op_ref8:
-	  agent_mem_read (ctx, cnv.u8.bytes, (CORE_ADDR) top, 1);
+	  if (agent_mem_read (ctx, cnv.u8.bytes, (CORE_ADDR) top, 1) != 0)
+	    return expr_eval_invalid_memory_access;
 	  top = cnv.u8.val;
 	  break;
 
 	case gdb_agent_op_ref16:
-	  agent_mem_read (ctx, cnv.u16.bytes, (CORE_ADDR) top, 2);
+	  if (agent_mem_read (ctx, cnv.u16.bytes, (CORE_ADDR) top, 2) != 0)
+	    return expr_eval_invalid_memory_access;
 	  top = cnv.u16.val;
 	  break;
 
 	case gdb_agent_op_ref32:
-	  agent_mem_read (ctx, cnv.u32.bytes, (CORE_ADDR) top, 4);
+	  if (agent_mem_read (ctx, cnv.u32.bytes, (CORE_ADDR) top, 4) != 0)
+	    return expr_eval_invalid_memory_access;
 	  top = cnv.u32.val;
 	  break;
 
 	case gdb_agent_op_ref64:
-	  agent_mem_read (ctx, cnv.u64.bytes, (CORE_ADDR) top, 8);
+	  if (agent_mem_read (ctx, cnv.u64.bytes, (CORE_ADDR) top, 8) != 0)
+	    return expr_eval_invalid_memory_access;
 	  top = cnv.u64.val;
 	  break;
 
diff --git a/gdbserver/ax.h b/gdbserver/ax.h
index b4062bf24a8..aad9e11078d 100644
--- a/gdbserver/ax.h
+++ b/gdbserver/ax.h
@@ -41,7 +41,8 @@ enum eval_result_type
     expr_eval_unhandled_opcode,
     expr_eval_unrecognized_opcode,
     expr_eval_divide_by_zero,
-    expr_eval_invalid_goto
+    expr_eval_invalid_goto,
+    expr_eval_invalid_memory_access
   };
 
 struct agent_expr
-- 
2.25.4


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

* [PATCH 07/12] gdb: avoid repeated signal reporting during failed conditional breakpoint
  2022-10-21  8:43 [PATCH 00/12] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                   ` (5 preceding siblings ...)
  2022-10-21  8:43 ` [PATCH 06/12] gdbserver: allow agent expressions to fail with invalid memory access Andrew Burgess
@ 2022-10-21  8:43 ` Andrew Burgess
  2022-10-21  8:43 ` [PATCH 08/12] gdb: don't always print breakpoint location after failed condition check Andrew Burgess
                   ` (5 subsequent siblings)
  12 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2022-10-21  8:43 UTC (permalink / raw)
  To: gdb-patches

Consider the following case:

  (gdb) list some_func
  1	int
  2	some_func ()
  3	{
  4	  int *p = 0;
  5	  return *p;
  6	}
  7
  8	void
  9	foo ()
  10	{
  (gdb) break foo if (some_func ())
  Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
  (gdb) r
  Starting program: /tmp/bpcond

  Program received signal SIGSEGV, Segmentation fault.
  0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  Error in testing breakpoint condition:
  The program being debugged was signaled while in a function called from GDB.
  GDB remains in the frame where the signal was received.
  To change this behavior use "set unwindonsignal on".
  Evaluation of the expression containing the function
  (some_func) will be abandoned.
  When the function is done executing, GDB will silently stop.

  Program received signal SIGSEGV, Segmentation fault.

  Breakpoint 1, 0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  (gdb)

Notice that this line:

  Program received signal SIGSEGV, Segmentation fault.

Appears twice in the output.  The first time is followed by the
current location.  The second time is a little odd, why do we print
that?

Printing that line is controlled, in part, by a global variable,
stopped_by_random_signal.  This variable is reset to zero in
handle_signal_stop, and is set if/when GDB figures out that the
inferior stopped due to some random signal.

The problem is, in our case, GDB first stops at the breakpoint for
foo, and enters handle_signal_stop and the stopped_by_random_signal
global is reset to 0.

Later within handle_signal_stop GDB calls bpstat_stop_status, it is
within this function (via bpstat_check_breakpoint_conditions) that the
breakpoint condition is checked, and, we end up calling the inferior
function (some_func in our example above).

In our case above the thread performing the inferior function call
segfaults in some_func.  GDB catches the SIGSEGV and handles the stop,
this causes us to reenter handle_signal_stop.  The global variable
stopped_by_random_signal is updated, this time it is set to true
because the thread stopped due to SIGSEGV.  As a result of this we
print the first instance of the line (as seen above in the example).

Finally we unwind GDB's call stack, the inferior function call is
complete, and we return to the original handle_signal_stop.  However,
the stopped_by_random_signal global is still carrying the value as
computed for the inferior function call's stop, which is why we now
print a second instance of the line, as seen in the example.

To prevent this, I propose adding a scoped_restore before we start an
inferior function call, this will save and restore the global
stopped_by_random_signal value.

With this done, the output from our example is now this:

 (gdb) list some_func
  1	int
  2	some_func ()
  3	{
  4	  int *p = 0;
  5	  return *p;
  6	}
  7
  8	void
  9	foo ()
  10	{
  (gdb) break foo if (some_func ())
  Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
  (gdb) r
  Starting program: /tmp/bpcond

  Program received signal SIGSEGV, Segmentation fault.
  0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  Error in testing condition for breakpoint 1:
  The program being debugged stopped while in a function called from GDB.
  Evaluation of the expression containing the function
  (some_func) will be abandoned.
  When the function is done executing, GDB will silently stop.

  Breakpoint 1, 0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  (gdb)

We now only see the 'Program received signal SIGSEGV, ...' line once,
which I think makes more sense.

Finally, I'm aware that the last few lines, that report the stop as
being at 'Breakpoint 1', when this is not where the thread is actually
located anymore, is not great.  I'll address that in the next commit.
---
 gdb/infcall.c                              |   9 +
 gdb/testsuite/gdb.base/infcall-failure.c   |  48 ++++++
 gdb/testsuite/gdb.base/infcall-failure.exp | 184 +++++++++++++++++++++
 3 files changed, 241 insertions(+)
 create mode 100644 gdb/testsuite/gdb.base/infcall-failure.c
 create mode 100644 gdb/testsuite/gdb.base/infcall-failure.exp

diff --git a/gdb/infcall.c b/gdb/infcall.c
index e2de045d7b7..4957eee0b85 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -1299,6 +1299,15 @@ call_function_by_hand_dummy (struct value *function,
   /* Register a clean-up for unwind_on_terminating_exception_breakpoint.  */
   SCOPE_EXIT { delete_std_terminate_breakpoint (); };
 
+  /* The stopped_by_random_signal variable is global.  If we are here
+     as part of a breakpoint condition check then the global will have
+     already been setup as part of the original breakpoint stop.  By
+     making the inferior call the global will be changed when GDB
+     handles the stop after the inferior call.  Avoid confusion by
+     restoring the current value after the inferior call.  */
+  scoped_restore restore_stopped_by_random_signal
+    = make_scoped_restore (&stopped_by_random_signal, 0);
+
   /* - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP -
      If you're looking to implement asynchronous dummy-frames, then
      just below is the place to chop this function in two..  */
diff --git a/gdb/testsuite/gdb.base/infcall-failure.c b/gdb/testsuite/gdb.base/infcall-failure.c
new file mode 100644
index 00000000000..00f4369e164
--- /dev/null
+++ b/gdb/testsuite/gdb.base/infcall-failure.c
@@ -0,0 +1,48 @@
+/* Copyright 2022 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/>.  */
+
+/* A function that segfaults (assuming that reads of address zero are
+   prohibited), this is used from within a breakpoint condition.  */
+int
+func_segfault ()
+{
+  volatile int *p = 0;
+  return *p;	/* Segfault here.  */
+}
+
+/* A function in which we will place a breakpoint.  This function is itself
+   then used from within a breakpoint condition.  */
+int
+func_bp ()
+{
+  int res = 0;	/* Second breakpoint.  */
+  return res;
+}
+
+int
+foo ()
+{
+  return 0;	/* First breakpoint.  */
+}
+
+int
+main ()
+{
+  int res = foo ();
+
+  return res;
+}
diff --git a/gdb/testsuite/gdb.base/infcall-failure.exp b/gdb/testsuite/gdb.base/infcall-failure.exp
new file mode 100644
index 00000000000..2dcdda34b4d
--- /dev/null
+++ b/gdb/testsuite/gdb.base/infcall-failure.exp
@@ -0,0 +1,184 @@
+# Copyright 2022 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/>.
+
+# Some simple tests of inferior function calls from breakpoint
+# conditions, in a single-threaded inferior.
+#
+# Test what happens when the inferior function (from a breakpoint
+# condition) either hits a nested breakpoint, or segfaults.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug}] == -1 } {
+    return
+}
+
+set bp_1_line [gdb_get_line_number "First breakpoint"]
+set bp_2_line [gdb_get_line_number "Second breakpoint"]
+set segv_line [gdb_get_line_number "Segfault here"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto
+# main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if {![runto_main]} {
+	fail "run to main"
+	return -1
+    }
+
+    return 0
+}
+
+# Start GDB according to ASYNC_P and NON_STOP_P, then setup a
+# conditional breakpoint.  The breakpoint condition includes an
+# inferior function call that will itself hit a breakpoint.  Check how
+# GDB reports this to the user.
+proc_with_prefix run_cond_hits_breakpoint_test { async_p non_stop_p } {
+    if { [start_gdb_and_runto_main $async_p $non_stop_p] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint and record its number.
+    gdb_breakpoint "${::srcfile}:${::bp_1_line} if (func_bp ())"
+    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		     "get number of first breakpoint"]
+
+    # Setup a breakpoint inside func_bp.
+    gdb_breakpoint "${::srcfile}:${::bp_2_line}"
+    set bp_2_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		     "get number of second breakpoint"]
+
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     "" \
+	     "Breakpoint ${bp_2_num}, func_bp \\(\\) at \[^\r\n\]+:${::bp_2_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Second breakpoint\[^\r\n\]+" \
+	     "Error in testing condition for breakpoint ${bp_1_num}:" \
+	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(func_bp\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\." \
+	     "" \
+	     "Breakpoint ${bp_1_num}, \[^\r\n\]+" \
+	     "${::decimal}\\s+\[^\r\n\]+Second breakpoint\[^\r\n\]+"]
+}
+
+# Start GDB according to ASYNC_P and NON_STOP_P, then call an inferior
+# function.  The inferior function being called will itself have a
+# breakpoint within it.  Check how GDB reports this to the user.
+proc_with_prefix run_call_hits_breakpoint_test { async_p non_stop_p } {
+    if { [start_gdb_and_runto_main $async_p $non_stop_p] == -1 } {
+	return
+    }
+
+    # Setup a breakpoint inside func_bp.
+    gdb_breakpoint "${::srcfile}:${::bp_2_line}"
+    set bp_2_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of second breakpoint"]
+
+
+    gdb_test "call func_bp ()" \
+	[multi_line \
+	     "" \
+	     "Breakpoint ${bp_2_num}, func_bp \\(\\) at \[^\r\n\]+:${::bp_2_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Second breakpoint\[^\r\n\]+" \
+	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(func_bp\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+}
+
+# Start GDB according to ASYNC_P and NON_STOP_P, then setup a
+# conditional breakpoint.  The breakpoint condition includes an
+# inferior function call that segfaults.  Check how GDB reports this
+# to the user.
+proc_with_prefix run_cond_hits_segfault_test { async_p non_stop_p } {
+    if { [start_gdb_and_runto_main $async_p $non_stop_p] == -1 } {
+	return
+    }
+
+    # This test relies on the inferior segfaulting when trying to
+    # access address zero.
+    if { [is_address_zero_readable] } {
+	return
+    }
+
+    # Setup the conditional breakpoint and record its number.
+    gdb_breakpoint "${::srcfile}:${::bp_1_line} if (func_segfault ())"
+    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		     "get number of first breakpoint"]
+
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     "" \
+	     "Program received signal SIGSEGV, Segmentation fault\\." \
+	     "${::hex} in func_segfault \\(\\) at \[^\r\n\]+:${::segv_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
+	     "Error in testing condition for breakpoint ${bp_1_num}:" \
+	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(func_segfault\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\." \
+	     "" \
+	     "Breakpoint ${bp_1_num}, \[^\r\n\]+" \
+	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"]
+}
+
+# Start GDB according to ASYNC_P and NON_STOP_P, then call an inferior
+# function.  The inferior function will segfault.  Check how GDB
+# reports this to the user.
+proc_with_prefix run_call_hits_segfault_test { async_p non_stop_p } {
+    if { [start_gdb_and_runto_main $async_p $non_stop_p] == -1 } {
+	return
+    }
+
+    # This test relies on the inferior segfaulting when trying to
+    # access address zero.
+    if { [is_address_zero_readable] } {
+	return
+    }
+
+    gdb_test "call func_segfault ()" \
+	[multi_line \
+	     "" \
+	     "Program received signal SIGSEGV, Segmentation fault\\." \
+	     "${::hex} in func_segfault \\(\\) at \[^\r\n\]+:${::segv_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
+	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(func_segfault\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	run_cond_hits_breakpoint_test $target_async $target_non_stop
+	run_call_hits_breakpoint_test $target_async $target_non_stop
+
+	run_cond_hits_segfault_test $target_async $target_non_stop
+	run_call_hits_segfault_test $target_async $target_non_stop
+    }
+}
-- 
2.25.4


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

* [PATCH 08/12] gdb: don't always print breakpoint location after failed condition check
  2022-10-21  8:43 [PATCH 00/12] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                   ` (6 preceding siblings ...)
  2022-10-21  8:43 ` [PATCH 07/12] gdb: avoid repeated signal reporting during failed conditional breakpoint Andrew Burgess
@ 2022-10-21  8:43 ` Andrew Burgess
  2022-10-21  8:43 ` [PATCH 09/12] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
                   ` (4 subsequent siblings)
  12 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2022-10-21  8:43 UTC (permalink / raw)
  To: gdb-patches

Consider the following session:

  (gdb) list some_func
  1	int
  2	some_func ()
  3	{
  4	  int *p = 0;
  5	  return *p;
  6	}
  7
  8	void
  9	foo ()
  10	{
  (gdb) break foo if (some_func ())
  Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
  (gdb) r
  Starting program: /tmp/bpcond

  Program received signal SIGSEGV, Segmentation fault.
  0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  Error in testing condition for breakpoint 1:
  The program being debugged stopped while in a function called from GDB.
  Evaluation of the expression containing the function
  (some_func) will be abandoned.
  When the function is done executing, GDB will silently stop.

  Breakpoint 1, 0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  (gdb)

What happens here is the breakpoint condition includes a call to an
inferior function, and the inferior function segfaults.  We can see
that GDB reports the segfault, and then gives an error message that
indicates that an inferior function call was interrupted.

After this GDB appears to report that it is stopped at Breakpoint 1,
inside some_func.

I find this second stop report a little confusing.  Yes, GDB has
stopped as a result of hitting breakpoint 1, but, I think the message
as it currently is might give the impression that the thread is
actually stopped at a location of breakpoint 1, which is not the case.

Also, I find the second stop message draws attention away from
the "Program received signal SIGSEGV, Segmentation fault" stop
message, and this second stop might be thought of as replacing in
someway the earlier message.

In short, I think that the in the situation above, I think things
would be clearer if the second stop message were not reported at all,
so the output should (I think) look like this:

  (gdb) list some_func
  1	int
  2	some_func ()
  3	{
  4	  int *p = 0;
  5	  return *p;
  6	}
  7
  8	void
  9	foo ()
  10	{
  (gdb) break foo if (some_func ())
  Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
  (gdb) r
  Starting program: /tmp/bpcond

  Program received signal SIGSEGV, Segmentation fault.
  0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  Error in testing condition for breakpoint 1:
  The program being debugged stopped while in a function called from GDB.
  Evaluation of the expression containing the function
  (some_func) will be abandoned.
  When the function is done executing, GDB will silently stop.
  (gdb)

The user can still find the number of the breakpoint that triggered
the initial stop in this line:

  Error in testing condition for breakpoint 1:

But there's now only one stop reason reported, the SIGSEGV, which I
think is much clearer.

To achieve this change I set the bpstat::print field when:

  (a) a breakpoint condition evaluation failed, and

  (b) the $pc of the thread changed during condition evaluation.

I've updated the existing tests that checked the error message printed
when a breakpoint condition evaluation failed.
---
 gdb/breakpoint.c                           | 12 ++++++++++++
 gdb/testsuite/gdb.base/infcall-failure.exp | 18 ++++++++----------
 2 files changed, 20 insertions(+), 10 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 4f5a27a6fe8..606b2d191f4 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -5403,6 +5403,7 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
 	  else
 	    within_current_scope = 0;
 	}
+      CORE_ADDR pc_before_check = get_frame_pc (get_selected_frame (nullptr));
       if (within_current_scope)
 	{
 	  try
@@ -5414,6 +5415,17 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
 	      exception_fprintf (gdb_stderr, ex,
 				 "Error in testing condition for breakpoint %d:\n",
 				 b->number);
+
+	      /* If the pc value changed as a result of evaluating the
+		 condition then we probably stopped within an inferior
+		 function call due to some unexpected stop, e.g. the thread
+		 hit another breakpoint, or the thread received an
+		 unexpected signal.  In this case we don't want to also
+		 print the information about this breakpoint.  */
+	      CORE_ADDR pc_after_check
+		= get_frame_pc (get_selected_frame (nullptr));
+	      if (pc_before_check != pc_after_check)
+		bs->print = 0;
 	    }
 	}
       else
diff --git a/gdb/testsuite/gdb.base/infcall-failure.exp b/gdb/testsuite/gdb.base/infcall-failure.exp
index 2dcdda34b4d..8fa2c407fc5 100644
--- a/gdb/testsuite/gdb.base/infcall-failure.exp
+++ b/gdb/testsuite/gdb.base/infcall-failure.exp
@@ -79,10 +79,7 @@ proc_with_prefix run_cond_hits_breakpoint_test { async_p non_stop_p } {
 	     "The program being debugged stopped while in a function called from GDB\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(func_bp\\) will be abandoned\\." \
-	     "When the function is done executing, GDB will silently stop\\." \
-	     "" \
-	     "Breakpoint ${bp_1_num}, \[^\r\n\]+" \
-	     "${::decimal}\\s+\[^\r\n\]+Second breakpoint\[^\r\n\]+"]
+	     "When the function is done executing, GDB will silently stop\\."]
 }
 
 # Start GDB according to ASYNC_P and NON_STOP_P, then call an inferior
@@ -138,13 +135,12 @@ proc_with_prefix run_cond_hits_segfault_test { async_p non_stop_p } {
 	     "${::hex} in func_segfault \\(\\) at \[^\r\n\]+:${::segv_line}" \
 	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
 	     "Error in testing condition for breakpoint ${bp_1_num}:" \
-	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "The program being debugged was signaled while in a function called from GDB\\." \
+	     "GDB remains in the frame where the signal was received\\." \
+	     "To change this behavior use \"set unwindonsignal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(func_segfault\\) will be abandoned\\." \
-	     "When the function is done executing, GDB will silently stop\\." \
-	     "" \
-	     "Breakpoint ${bp_1_num}, \[^\r\n\]+" \
-	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"]
+	     "When the function is done executing, GDB will silently stop\\."]
 }
 
 # Start GDB according to ASYNC_P and NON_STOP_P, then call an inferior
@@ -167,7 +163,9 @@ proc_with_prefix run_call_hits_segfault_test { async_p non_stop_p } {
 	     "Program received signal SIGSEGV, Segmentation fault\\." \
 	     "${::hex} in func_segfault \\(\\) at \[^\r\n\]+:${::segv_line}" \
 	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
-	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "The program being debugged was signaled while in a function called from GDB\\." \
+	     "GDB remains in the frame where the signal was received\\." \
+	     "To change this behavior use \"set unwindonsignal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(func_segfault\\) will be abandoned\\." \
 	     "When the function is done executing, GDB will silently stop\\."]
-- 
2.25.4


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

* [PATCH 09/12] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait"
  2022-10-21  8:43 [PATCH 00/12] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                   ` (7 preceding siblings ...)
  2022-10-21  8:43 ` [PATCH 08/12] gdb: don't always print breakpoint location after failed condition check Andrew Burgess
@ 2022-10-21  8:43 ` Andrew Burgess
  2022-10-21  8:43 ` [PATCH 10/12] gdb: fix b/p conditions with infcalls in multi-threaded inferiors Andrew Burgess
                   ` (3 subsequent siblings)
  12 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2022-10-21  8:43 UTC (permalink / raw)
  To: gdb-patches

This reverts commit ac0d67ed1dcf470bad6a3bc4800c2ddc9bedecca.

There was nothing wrong with the commit which I'm reverting here, but
it removed some functionality that will be needed for a later commit;
that is, the ability for GDB to ask for events from a specific ptid_t
via the do_target_wait function.

In a follow up commit, this functionality will be used to implement
inferior function calls in multi-threaded inferiors.
---
 gdb/infrun.c | 12 +++++++-----
 1 file changed, 7 insertions(+), 5 deletions(-)

diff --git a/gdb/infrun.c b/gdb/infrun.c
index c28bf28a4d9..b23c3e3918e 100644
--- a/gdb/infrun.c
+++ b/gdb/infrun.c
@@ -3770,7 +3770,8 @@ do_target_wait_1 (inferior *inf, ptid_t ptid,
    more events.  Polls for events from all inferiors/targets.  */
 
 static bool
-do_target_wait (execution_control_state *ecs, target_wait_flags options)
+do_target_wait (ptid_t wait_ptid, execution_control_state *ecs,
+		target_wait_flags options)
 {
   int num_inferiors = 0;
   int random_selector;
@@ -3780,9 +3781,10 @@ do_target_wait (execution_control_state *ecs, target_wait_flags options)
      polling the rest of the inferior list starting from that one in a
      circular fashion until the whole list is polled once.  */
 
-  auto inferior_matches = [] (inferior *inf)
+  auto inferior_matches = [&wait_ptid] (inferior *inf)
     {
-      return inf->process_target () != nullptr;
+      return (inf->process_target () != NULL
+	      && ptid_t (inf->pid).matches (wait_ptid));
     };
 
   /* First see how many matching inferiors we have.  */
@@ -3821,7 +3823,7 @@ do_target_wait (execution_control_state *ecs, target_wait_flags options)
 
   auto do_wait = [&] (inferior *inf)
   {
-    ecs->ptid = do_target_wait_1 (inf, minus_one_ptid, &ecs->ws, options);
+    ecs->ptid = do_target_wait_1 (inf, wait_ptid, &ecs->ws, options);
     ecs->target = inf->process_target ();
     return (ecs->ws.kind () != TARGET_WAITKIND_IGNORE);
   };
@@ -4200,7 +4202,7 @@ fetch_inferior_event ()
        the event.  */
     scoped_disable_commit_resumed disable_commit_resumed ("handling event");
 
-    if (!do_target_wait (ecs, TARGET_WNOHANG))
+    if (!do_target_wait (minus_one_ptid, ecs, TARGET_WNOHANG))
       {
 	infrun_debug_printf ("do_target_wait returned no event");
 	disable_commit_resumed.reset_and_commit ();
-- 
2.25.4


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

* [PATCH 10/12] gdb: fix b/p conditions with infcalls in multi-threaded inferiors
  2022-10-21  8:43 [PATCH 00/12] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                   ` (8 preceding siblings ...)
  2022-10-21  8:43 ` [PATCH 09/12] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
@ 2022-10-21  8:43 ` Andrew Burgess
  2022-10-21  8:43 ` [PATCH 11/12] gdb: add timeouts for inferior function calls Andrew Burgess
                   ` (2 subsequent siblings)
  12 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2022-10-21  8:43 UTC (permalink / raw)
  To: gdb-patches

This commit fixes bug PR 28942, that is, creating a conditional
breakpoint in a multi-threaded inferior, where the breakpoint
condition includes an inferior function call.

Currently, when a user tries to create such a breakpoint, then GDB
will fail with:

  (gdb) break infcall-from-bp-cond-single.c:61 if (return_true ())
  Breakpoint 2 at 0x4011fa: file /tmp/build/gdb/testsuite/../../../src/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c, line 61.
  (gdb) continue
  Continuing.
  [New Thread 0x7ffff7c5d700 (LWP 2460150)]
  [New Thread 0x7ffff745c700 (LWP 2460151)]
  [New Thread 0x7ffff6c5b700 (LWP 2460152)]
  [New Thread 0x7ffff645a700 (LWP 2460153)]
  [New Thread 0x7ffff5c59700 (LWP 2460154)]
  Error in testing breakpoint condition:
  Couldn't get registers: No such process.
  An error occurred while in a function called from GDB.
  Evaluation of the expression containing the function
  (return_true) will be abandoned.
  When the function is done executing, GDB will silently stop.
  Selected thread is running.
  (gdb)

Or, in some cases, like this:

  (gdb) break infcall-from-bp-cond-simple.c:56 if (is_matching_tid (arg, 1))
  Breakpoint 2 at 0x401194: file /tmp/build/gdb/testsuite/../../../src/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c, line 56.
  (gdb) continue
  Continuing.
  [New Thread 0x7ffff7c5d700 (LWP 2461106)]
  [New Thread 0x7ffff745c700 (LWP 2461107)]
  ../../src.release/gdb/nat/x86-linux-dregs.c:146: internal-error: x86_linux_update_debug_registers: Assertion `lwp_is_stopped (lwp)' failed.
  A problem internal to GDB has been detected,
  further debugging may prove unreliable.

The precise error depends on the exact thread state; so there's race
conditions depending on which threads have fully started, and which
have not.  But the underlying problem is always the same; when GDB
tries to execute the inferior function call from within the breakpoint
condition, GDB will, incorrectly, try to resume threads that are
already running - GDB doesn't realise that some threads might already
be running.

The solution proposed in this patch requires an additional member
variable thread_info::in_cond_eval.  This flag is set to true (in
breakpoint.c) when GDB is evaluating a breakpoint condition.

In user_visible_resume_ptid (infrun.c), when the in_cond_eval flag is
true, then GDB will only try to resume the current thread, that is,
the thread for which the breakpoint condition is being evaluated.
This solves the problem of GDB trying to resume threads that are
already running.

The next problem is that inferior function calls are assumed to be
synchronous, that is, GDB doesn't expect to start an inferior function
call in thread #1, then receive a stop from thread #2 for some other,
unrelated reason.  To prevent GDB responding to an event from another
thread, we update fetch_inferior_event and do_target_wait in infrun.c,
so that, when an inferior function call (on behalf of a breakpoint
condition) is in progress, we only wait for events from the current
thread (the one evaluating the condition).

The fix in do_target_wait is because previously, we only ever waited
for the general any-thread, minus_one_ptid, for which matching
against the inferior::pid would always succeed.  However, now we might
wait against a specific ptid value, in which case we need to ensure we
only compare the pid part of the ptid.

In fetch_inferior_event, after receiving the event, we only want to
stop all the other threads, and call inferior_event_handler with
INF_EXEC_COMPLETE, if we are not evaluating a conditional breakpoint.
If we are, then all the other threads should be left doing whatever
they were before.  The inferior_event_handler call will be performed
once the breakpoint condition has finished being evaluated, and GDB
decides to stop or not.

The final problem that needs solving relates to GDB's commit-resume
mechanism, this allows GDB to collect resume requests into a single
packet in order to reduce traffic to a remote target.

The problem is that the commit-resume mechanism will not send any
resume requests for an inferior if there are already events pending on
the GDB side.

Imagine an inferior with two threads.  Both threads hit a breakpoint,
maybe the same conditional breakpoint.  At this point there are two
pending events, one for each thread.

GDB selects one of the events and spots that this is a conditional
breakpoint, GDB evaluates the condition.

The condition includes an inferior function call, so GDB sets up for
the call and resumes the one thread, the resume request is added to
the commit-resume queue.

When the commit-resume queue is committed GDB sees that there is a
pending event from another thread, and so doesn't send any resume
requests to the actual target, GDB is assuming that when we wait we
will select the event from the other thread.

However, as this is an inferior function call for a condition
evaluation, we will not select the event from the other thread, we
only care about events from the thread that is evaluating the
condition - and the resume for this thread was never sent to the
target.

And so, GDB hangs, waiting for an event from a thread that was never
fully resumed.

To fix this issue I have added the concept of "forcing" the
commit-resume queue.  When enabling commit resume, if the force flag
is true, then any resumes will be committed to the target, even if
there are other threads with pending events.

A note on authorship: this patch was based on some work done by
Natalia Saiapova and Tankut Baris Aktemur from Intel[1].  I have made
some changes to their work in this version.

Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=28942

[1] https://sourceware.org/pipermail/gdb-patches/2020-October/172454.html

Co-authored-by: Natalia Saiapova <natalia.saiapova@intel.com>
Co-authored-by: Tankut Baris Aktemur <tankut.baris.aktemur@intel.com>
---
 gdb/breakpoint.c                              |   2 +
 gdb/gdbthread.h                               |   3 +
 gdb/infcall.c                                 |   6 +
 gdb/infrun.c                                  |  46 +++-
 gdb/infrun.h                                  |   2 +-
 .../infcall-from-bp-cond-other-thread-event.c | 135 ++++++++++
 ...nfcall-from-bp-cond-other-thread-event.exp | 175 +++++++++++++
 .../gdb.threads/infcall-from-bp-cond-simple.c |  89 +++++++
 .../infcall-from-bp-cond-simple.exp           | 236 ++++++++++++++++++
 .../gdb.threads/infcall-from-bp-cond-single.c | 139 +++++++++++
 .../infcall-from-bp-cond-single.exp           | 119 +++++++++
 11 files changed, 940 insertions(+), 12 deletions(-)
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 606b2d191f4..4adc8c4306a 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -5408,6 +5408,8 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
 	{
 	  try
 	    {
+	      scoped_restore reset_in_cond_eval
+		= make_scoped_restore (&thread->control.in_cond_eval, true);
 	      condition_result = breakpoint_cond_eval (cond);
 	    }
 	  catch (const gdb_exception &ex)
diff --git a/gdb/gdbthread.h b/gdb/gdbthread.h
index 1a33eb61221..c88b57ebeec 100644
--- a/gdb/gdbthread.h
+++ b/gdb/gdbthread.h
@@ -171,6 +171,9 @@ struct thread_control_state
      command.  This is used to decide whether "set scheduler-locking
      step" behaves like "on" or "off".  */
   int stepping_command = 0;
+
+  /* True if the thread is evaluating a BP condition.  */
+  bool in_cond_eval = false;
 };
 
 /* Inferior thread specific part of `struct infcall_suspend_state'.  */
diff --git a/gdb/infcall.c b/gdb/infcall.c
index 4957eee0b85..99ca5792dd3 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -647,6 +647,12 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
 
       proceed (real_pc, GDB_SIGNAL_0);
 
+      /* Enable commit resume, but pass true for the force flag.  This
+	 ensures any thread we set running in proceed will actually be
+	 committed to the target, even if some other thread in the current
+	 target has a pending event.  */
+      scoped_enable_commit_resumed enable ("infcall", true);
+
       infrun_debug_show_threads ("non-exited threads after proceed for inferior-call",
 				 all_non_exited_threads ());
 
diff --git a/gdb/infrun.c b/gdb/infrun.c
index b23c3e3918e..f0fe860c68c 100644
--- a/gdb/infrun.c
+++ b/gdb/infrun.c
@@ -2176,6 +2176,14 @@ user_visible_resume_ptid (int step)
 	 mode.  */
       resume_ptid = inferior_ptid;
     }
+  else if (inferior_ptid != null_ptid
+	   && inferior_thread ()->control.in_cond_eval)
+    {
+      /* The inferior thread is evaluating a BP condition.  Other threads
+	 might be stopped or running and we do not want to change their
+	 state, thus, resume only the current thread.  */
+      resume_ptid = inferior_ptid;
+    }
   else if (!sched_multi && target_supports_multi_process ())
     {
       /* Resume all threads of the current process (and none of other
@@ -2888,7 +2896,7 @@ schedlock_applies (struct thread_info *tp)
    pending events.  */
 
 static void
-maybe_set_commit_resumed_all_targets ()
+maybe_set_commit_resumed_all_targets (bool force_p)
 {
   scoped_restore_current_thread restore_thread;
 
@@ -2917,7 +2925,7 @@ maybe_set_commit_resumed_all_targets ()
 	 status to report, handle it before requiring the target to
 	 commit its resumed threads: handling the status might lead to
 	 resuming more threads.  */
-      if (proc_target->has_resumed_with_pending_wait_status ())
+      if (!force_p && proc_target->has_resumed_with_pending_wait_status ())
 	{
 	  infrun_debug_printf ("not requesting commit-resumed for target %s, a"
 			       " thread has a pending waitstatus",
@@ -2927,7 +2935,7 @@ maybe_set_commit_resumed_all_targets ()
 
       switch_to_inferior_no_thread (inf);
 
-      if (target_has_pending_events ())
+      if (!force_p && target_has_pending_events ())
 	{
 	  infrun_debug_printf ("not requesting commit-resumed for target %s, "
 			       "target has pending events",
@@ -3020,7 +3028,7 @@ scoped_disable_commit_resumed::reset ()
     {
       /* This is the outermost instance, re-enable
          COMMIT_RESUMED_STATE on the targets where it's possible.  */
-      maybe_set_commit_resumed_all_targets ();
+      maybe_set_commit_resumed_all_targets (false);
     }
   else
     {
@@ -3053,7 +3061,7 @@ scoped_disable_commit_resumed::reset_and_commit ()
 /* See infrun.h.  */
 
 scoped_enable_commit_resumed::scoped_enable_commit_resumed
-  (const char *reason)
+  (const char *reason, bool force_p)
   : m_reason (reason),
     m_prev_enable_commit_resumed (enable_commit_resumed)
 {
@@ -3065,7 +3073,7 @@ scoped_enable_commit_resumed::scoped_enable_commit_resumed
 
       /* Re-enable COMMIT_RESUMED_STATE on the targets where it's
 	 possible.  */
-      maybe_set_commit_resumed_all_targets ();
+      maybe_set_commit_resumed_all_targets (force_p);
 
       maybe_call_commit_resumed_all_targets ();
     }
@@ -3781,10 +3789,11 @@ do_target_wait (ptid_t wait_ptid, execution_control_state *ecs,
      polling the rest of the inferior list starting from that one in a
      circular fashion until the whole list is polled once.  */
 
-  auto inferior_matches = [&wait_ptid] (inferior *inf)
+  ptid_t wait_ptid_pid {wait_ptid.pid ()};
+  auto inferior_matches = [&wait_ptid_pid] (inferior *inf)
     {
       return (inf->process_target () != NULL
-	      && ptid_t (inf->pid).matches (wait_ptid));
+	      && ptid_t (inf->pid).matches (wait_ptid_pid));
     };
 
   /* First see how many matching inferiors we have.  */
@@ -4202,7 +4211,17 @@ fetch_inferior_event ()
        the event.  */
     scoped_disable_commit_resumed disable_commit_resumed ("handling event");
 
-    if (!do_target_wait (minus_one_ptid, ecs, TARGET_WNOHANG))
+    /* Is the current thread performing an inferior function call as part
+       of a breakpoint condition evaluation?  */
+    bool in_cond_eval = (inferior_ptid != null_ptid
+			 && inferior_thread ()->control.in_cond_eval);
+
+    /* If the thread is in the middle of the condition evaluation, wait for
+       an event from the current thread, otherwise, wait for an event from
+       any thread.  */
+    ptid_t waiton_ptid = in_cond_eval ? inferior_ptid : minus_one_ptid;
+
+    if (!do_target_wait (waiton_ptid, ecs, TARGET_WNOHANG))
       {
 	infrun_debug_printf ("do_target_wait returned no event");
 	disable_commit_resumed.reset_and_commit ();
@@ -4254,7 +4273,12 @@ fetch_inferior_event ()
 	    bool should_notify_stop = true;
 	    int proceeded = 0;
 
-	    stop_all_threads_if_all_stop_mode ();
+	    /* If the thread that stopped just completed an inferior
+	       function call as part of a condition evaluation, then we
+	       don't want to stop all the other threads.  */
+	    if (ecs->event_thread == nullptr
+		|| !ecs->event_thread->control.in_cond_eval)
+	      stop_all_threads_if_all_stop_mode ();
 
 	    clean_up_just_stopped_threads_fsms (ecs);
 
@@ -4269,7 +4293,7 @@ fetch_inferior_event ()
 		  proceeded = normal_stop ();
 	      }
 
-	    if (!proceeded)
+	    if (!proceeded && !in_cond_eval)
 	      {
 		inferior_event_handler (INF_EXEC_COMPLETE);
 		cmd_done = 1;
diff --git a/gdb/infrun.h b/gdb/infrun.h
index 11a18583e68..0d1b95d6c2d 100644
--- a/gdb/infrun.h
+++ b/gdb/infrun.h
@@ -395,7 +395,7 @@ extern void maybe_call_commit_resumed_all_targets ();
 
 struct scoped_enable_commit_resumed
 {
-  explicit scoped_enable_commit_resumed (const char *reason);
+  explicit scoped_enable_commit_resumed (const char *reason, bool force_p = false);
   ~scoped_enable_commit_resumed ();
 
   DISABLE_COPY_AND_ASSIGN (scoped_enable_commit_resumed);
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
new file mode 100644
index 00000000000..a6abdeb29a6
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
@@ -0,0 +1,135 @@
+/* Copyright 2022 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 <pthread.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <sched.h>
+
+#define NUM_THREADS 2
+
+pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+
+/* Some global variables to poke, just for something to do.  */
+volatile int global_var_0 = 0;
+volatile int global_var_1 = 0;
+
+/* This flag is updated from GDB.  */
+volatile int raise_signal = 0;
+
+/* Implement the breakpoint condition function.  Release the other thread
+   and try to give the other thread a chance to run.  Then return ANSWER.  */
+int
+condition_core_func (int answer)
+{
+  /* This unlock should release the other thread.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  /* And this yield and sleep should (hopefully) give the other thread a
+     chance to run.  This isn't guaranteed of course, but once the other
+     thread does run it should hit a breakpoint, which GDB should
+     (temporarily) ignore, so there's no easy way for us to know the other
+     thread has done what it needs to, thus, yielding and sleeping is the
+     best we can do.  */
+  sched_yield ();
+  sleep (2);
+
+  return answer;
+}
+
+void
+stop_marker ()
+{
+  int a = 100;	/* Final breakpoint here.  */
+}
+
+/* A breakpoint condition function that always returns true.  */
+int
+condition_true_func ()
+{
+  return condition_core_func (1);
+}
+
+/* A breakpoint condition function that always returns false.  */
+int
+condition_false_func ()
+{
+  return condition_core_func (0);
+}
+
+void *
+worker_func (void *arg)
+{
+  volatile int *ptr = 0;
+  int tid = *((int *) arg);
+
+  switch (tid)
+    {
+    case 0:
+      global_var_0 = 11;	/* First thread breakpoint.  */
+      break;
+
+    case 1:
+      if (pthread_mutex_lock (&mutex) != 0)
+	abort ();
+      if (raise_signal)
+	global_var_1 = *ptr;	/* Signal here.  */
+      else
+	global_var_1 = 99;	/* Other thread breakpoint.  */
+      break;
+
+    default:
+      abort ();
+    }
+
+  return NULL;
+}
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+
+  /* Set an alarm, just in case the test deadlocks.  */
+  alarm (300);
+
+  /* We want the mutex to start locked.  */
+  if (pthread_mutex_lock (&mutex) != 0)
+    abort ();
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      void *retval;
+      pthread_join (threads[i], &retval);
+    }
+
+  /* Unlock once we're done, just for cleanliness.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
new file mode 100644
index 00000000000..0c8ef728009
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
@@ -0,0 +1,175 @@
+# Copyright 2022 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/>.
+
+# Test for conditional breakpoints where the breakpoint condition includes
+# an inferior function call.
+#
+# The tests in this script are testing what happens when an event arrives in
+# another thread while GDB is waiting for the inferior function call (in the
+# breakpoint condition) to finish.
+#
+# The expectation is that GDB will queue events for other threads and wait
+# for the inferior function call to complete, if the condition is true, then
+# the conditional breakpoint should be reported first.  The other thread
+# event should of course, not get lost, and should be reported as soon as
+# the user tries to continue the inferior.
+#
+# If the conditional breakpoint ends up not being taken (the condition is
+# false), then the other thread event should be reported immediately.
+#
+# This script tests what happens when the other thread event is (a) the
+# other thread hitting a breakpoint, and (b) the other thread taking a
+# signal (SIGSEGV in this case).
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] == -1 } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "First thread breakpoint"]
+set other_bp_line [gdb_get_line_number "Other thread breakpoint"]
+set final_bp_line [gdb_get_line_number "Final breakpoint here"]
+set signal_line [gdb_get_line_number "Signal here"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if {![runto_main]} {
+	fail "run to main"
+	return -1
+    }
+
+    return 0
+}
+
+# Run a test of GDB's conditional breakpoints, where the conditions include
+# inferior function calls.  While the inferior function call is executing
+# another thread will hit a breakpoint (when OTHER_THREAD_SIGNAL is false),
+# or receive a signal (when OTHER_THREAD_SIGNAL is true).  GDB should report
+# the conditional breakpoint first (if the condition is true), and then
+# report the second thread event once the inferior is continued again.
+#
+# When STOP_AT_COND is true then the conditional breakpoint will have a
+# condition that evaluates to true (and the GDB will stop at the
+# breakpoint), otherwise, the condition will evaluate to false (and GDB will
+# not stop at the breakpoint).
+proc run_condition_test { stop_at_cond other_thread_signal \
+			      target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint.
+    if { $stop_at_cond } {
+	set cond_func "condition_true_func"
+    } else {
+	set cond_func "condition_false_func"
+    }
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (${cond_func} ())"
+    set cond_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			"get number for conditional breakpoint"]
+
+    if { $other_thread_signal } {
+	# Arrange for the other thread to raise a signal while GDB is
+	# evaluating the breakpoint condition.
+	gdb_test_no_output "set raise_signal = 1"
+    } else {
+	# And a breakpoint that will be hit by another thread only once the
+	# breakpoint condition starts to be evaluated.
+	gdb_breakpoint "${::srcfile}:${::other_bp_line}"
+	set other_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			      "get number for other breakpoint"]
+    }
+
+    # A final breakpoint once the test has completed.
+    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
+    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			  "get number for final breakpoint"]
+
+    if { $stop_at_cond } {
+	# Continue.  The first breakpoint we hit should be the conditional
+	# breakpoint.  The other thread will have hit its breakpoint, but
+	# that will have been deferred until the conditional breakpoint is
+	# reported.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${cond_bp_num}, worker_func \[^\r\n\]+:${::cond_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+First thread breakpoint\[^\r\n\]+"] \
+	    "hit the conditional breakpoint"
+    }
+
+    if { $other_thread_signal } {
+	# Now continue again, the other thread will now report that it
+	# received a signal.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" received signal SIGSEGV, Segmentation fault\\." \
+		 "\\\[Switching to Thread \[^\r\n\]+\\\]" \
+		 "${::hex} in worker_func \[^\r\n\]+:${::signal_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Signal here\[^\r\n\]+"] \
+	    "received signal in other thread"
+    } else {
+	# Now continue again, the other thread will now report its
+	# breakpoint.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${other_bp_num}, worker_func \[^\r\n\]+:${::other_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Other thread breakpoint\[^\r\n\]+"] \
+	    "hit the breakpoint in other thread"
+
+	# Run to the stop marker.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${final_bp_num}, stop_marker \[^\r\n\]+:${::final_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Final breakpoint here\[^\r\n\]+"] \
+	    "hit the final breakpoint"
+    }
+
+    gdb_exit
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	foreach_with_prefix other_thread_signal { true false } {
+	    foreach_with_prefix stop_at_cond { true false } {
+		run_condition_test $stop_at_cond $other_thread_signal \
+		    $target_async $target_non_stop
+	    }
+	}
+    }
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
new file mode 100644
index 00000000000..f2a24a52b01
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
@@ -0,0 +1,89 @@
+/* Copyright 2022 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 <pthread.h>
+#include <unistd.h>
+
+#define NUM_THREADS 3
+
+int
+is_matching_tid (int *tid_ptr, int tid_value)
+{
+  return *tid_ptr == tid_value;
+}
+
+int
+return_true ()
+{
+  return 1;
+}
+
+int
+return_false ()
+{
+  return 0;
+}
+
+int
+function_that_segfaults ()
+{
+  int *p = 0;
+  *p = 1;	/* Segfault happens here.   */
+}
+
+int
+function_with_breakpoint ()
+{
+  return 1;	/* Nested breakpoint.  */
+}
+
+void *
+worker_func (void *arg)
+{
+  int a = 42;	/* Breakpoint here.  */
+}
+
+void
+stop_marker ()
+{
+  int b = 99;	/* Stop marker.  */
+}
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+
+  alarm (300);
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      void *retval;
+      pthread_join (threads[i], &retval);
+    }
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
new file mode 100644
index 00000000000..8d94d24f9b3
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
@@ -0,0 +1,236 @@
+# Copyright 2022 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/>.
+
+# Some simple tests of inferior function calls from breakpoint
+# conditions, in multi-threaded inferiors.
+#
+# This test sets up a multi-threaded inferior, and places a breakpoint
+# at a location that many of the threads will reach.  We repeat the
+# test with different conditions, sometimes a single thread should
+# stop at the breakpoint, sometimes multiple threads should stop, and
+# sometime no threads should stop.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] == -1 } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "Breakpoint here"]
+set stop_bp_line [gdb_get_line_number "Stop marker"]
+set nested_bp_line [gdb_get_line_number "Nested breakpoint"]
+set segv_line [gdb_get_line_number "Segfault happens here"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if {![runto_main]} {
+	fail "run to main"
+	return -1
+    }
+
+    return 0
+}
+
+# Run a test of GDB's conditional breakpoints, where the conditions include
+# inferior function calls.
+#
+# CONDITION is combined (with &&) to some additional logic, and used as the
+# breakpoint condition.
+#
+# N_EXPECTED_HITS is the number of threads that we expect to stop due to
+# CONDITON.
+#
+# MESSAGE is used as a test name prefix.
+proc run_condition_test { message n_expected_hits condition \
+			      target_async target_non_stop } {
+    with_test_prefix $message {
+
+	if { [start_gdb_and_runto_main $target_async \
+		  $target_non_stop] == -1 } {
+	    return
+	}
+
+	# Use this convenience variable to track how often the
+	# breakpoint condition has been evaluated, this should be once
+	# per thread.
+	gdb_test "set \$n_cond_eval = 0"
+
+	# Setup the conditional breakpoint.
+	gdb_breakpoint \
+	    "${::srcfile}:${::cond_bp_line} if ((++\$n_cond_eval) ${condition})"
+
+	# And a breakpoint that we hit when the test is over, this one is
+	# not conditional.  Only the main thread gets here once all the
+	# other threads have finished.
+	gdb_breakpoint "${::srcfile}:${::stop_bp_line}"
+
+	# The number of times we stop at the conditional breakpoint.
+	set n_hit_condition 0
+
+	# Now keep 'continue'-ing GDB until all the threads have finished
+	# and we reach the stop_marker breakpoint.
+	gdb_test_multiple "continue" "spot all breakpoint hits" {
+	    -re " worker_func \[^\r\n\]+${::srcfile}:${::cond_bp_line}\r\n${::decimal}\\s+\[^\r\n\]+Breakpoint here\[^\r\n\]+\r\n${::gdb_prompt} $" {
+		incr n_hit_condition
+		send_gdb "continue\n"
+		exp_continue
+	    }
+
+	    -re " stop_marker \[^\r\n\]+${::srcfile}:${::stop_bp_line}\r\n${::decimal}\\s+\[^\r\n\]+Stop marker\[^\r\n\]+\r\n${::gdb_prompt} $" {
+		pass $gdb_test_name
+	    }
+	}
+
+	gdb_assert { $n_hit_condition == $n_expected_hits } \
+	    "stopped at breakpoint the expected number of times"
+
+	# Ensure the breakpoint condition was evaluated once per thread.
+	gdb_test "print \$n_cond_eval" "= 3" "condition was evaluated twice"
+    }
+}
+
+# Check that after handling a conditional breakpoint (where the condition
+# includes an inferior call), it is still possible to kill the running
+# inferior, and then restart the inferior.
+#
+# At once point doing this would result in GDB giving an assertion error.
+proc_with_prefix run_kill_and_restart_test { target_async target_non_stop } {
+    # This test relies on the 'start' command, which is not possible with
+    # the plain 'remote' target.
+    if {[target_info gdb_protocol] == "remote"} {
+	return
+    }
+
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint.
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 1))"
+    gdb_continue_to_breakpoint "worker_func"
+
+    # Now kill the program being debugged.
+    gdb_test "kill" "" "kill process" \
+	"Kill the program being debugged.*y or n. $" "y"
+
+    # Check we can restart the inferior.  At one point this would trigger an
+    # assertion.
+    gdb_test "start" ".*"
+}
+
+# Create a conditional breakpoint which includes a call to a function that
+# segfaults.  Run GDB and check what happens when the inferior segfaults
+# during the inferior call.
+proc_with_prefix run_bp_cond_segfaults { target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # This test relies on the inferior segfaulting when trying to
+    # access address zero.
+    if { [is_address_zero_readable] } {
+	return
+    }
+
+    # Setup the conditional breakpoint, include a call to
+    # 'function_that_segfaults', which triggers the segfault.
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 0) && function_that_segfaults ())"
+    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of conditional breakpoint"]
+
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     ".*" \
+	     "Thread ${::decimal} \"infcall-from-bp\" received signal SIGSEGV, Segmentation fault\\." \
+	     "${::hex} in function_that_segfaults \\(\\) at \[^\r\n\]+:${::segv_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Segfault happens here\[^\r\n\]+" \
+	     "Error in testing condition for breakpoint ${bp_1_num}:" \
+	     "The program being debugged was signaled while in a function called from GDB\\." \
+	     "GDB remains in the frame where the signal was received\\." \
+	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(function_that_segfaults\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+}
+
+# Create a conditional breakpoint which includes a call to a function that
+# itself has a breakpoint set within it.  Run GDB and check what happens
+# when GDB hits the nested breakpoint.
+proc_with_prefix run_bp_cond_hits_breakpoint { target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint, include a call to
+    # 'function_with_breakpoint' in which we will shortly place a
+    # breakpoint.
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 0) && function_with_breakpoint ())"
+    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of conditional breakpoint"]
+
+    gdb_breakpoint "${::srcfile}:${::nested_bp_line}"
+    set bp_2_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of nested breakpoint"]
+
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     ".*" \
+	     "Thread ${::decimal} \"infcall-from-bp\" hit Breakpoint ${bp_2_num}, function_with_breakpoint \\(\\) at \[^\r\n\]+:${::nested_bp_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Nested breakpoint\[^\r\n\]+" \
+	     "Error in testing condition for breakpoint ${bp_1_num}:" \
+	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(function_with_breakpoint\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	run_condition_test "exactly one thread is hit" \
+	    1 "&& is_matching_tid (arg, 1)" \
+	    $target_async $target_non_stop
+	run_condition_test "exactly two threads are hit" \
+	    2 "&& (is_matching_tid (arg, 0) || is_matching_tid (arg, 2))" \
+	    $target_async $target_non_stop
+	run_condition_test "all three threads are hit" \
+	    3 "|| return_true ()" \
+	    $target_async $target_non_stop
+	run_condition_test "no thread is hit" \
+	    0 "&& return_false ()" \
+	    $target_async $target_non_stop
+
+	run_kill_and_restart_test $target_async $target_non_stop
+	run_bp_cond_segfaults $target_async $target_non_stop
+	run_bp_cond_hits_breakpoint $target_async $target_non_stop
+    }
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
new file mode 100644
index 00000000000..c87f1f2bfc6
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
@@ -0,0 +1,139 @@
+/* Copyright 2022 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 <pthread.h>
+#include <unistd.h>
+#include <semaphore.h>
+#include <stdlib.h>
+
+#define NUM_THREADS 5
+
+/* Semaphores, used to track when threads have started, and to control
+   when the threads finish.  */
+sem_t startup_semaphore;
+sem_t finish_semaphore;
+
+/* Mutex to control when the first worker thread hit a breakpoint
+   location.  */
+pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+
+/* Global variable to poke, just so threads have something to do.  */
+volatile int global_var = 0;
+
+int
+return_true ()
+{
+  return 1;
+}
+
+int
+return_false ()
+{
+  return 0;
+}
+
+void *
+worker_func (void *arg)
+{
+  int tid = *((int *) arg);
+
+  switch (tid)
+    {
+    case 0:
+      /* Wait for MUTEX to become available, then pass through the
+	 conditional breakpoint location.  */
+      if (pthread_mutex_lock (&mutex) != 0)
+	abort ();
+      global_var = 99;	/* Conditional breakpoint here.  */
+      if (pthread_mutex_unlock (&mutex) != 0)
+	abort ();
+      break;
+
+    default:
+      /* Notify the main thread that the thread has started, then wait for
+	 the main thread to tell us to finish.  */
+      sem_post (&startup_semaphore);
+      if (sem_wait (&finish_semaphore) != 0)
+	abort ();
+      break;
+    }
+}
+
+void
+stop_marker ()
+{
+  global_var = 99;	/* Stop marker.  */
+}
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+  void *retval;
+
+  /* An alarm, just in case the thread deadlocks.  */
+  alarm (300);
+
+  /* Semaphore initialization.  */
+  if (sem_init (&startup_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&finish_semaphore, 0, 0) != 0)
+    abort ();
+
+  /* Lock MUTEX, this prevents the first worker thread from rushing ahead.  */
+  if (pthread_mutex_lock (&mutex) != 0)
+    abort ();
+
+  /* Worker thread creation.  */
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  /* Wait for every thread (other than the first) to tell us it has started
+     up.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    {
+      if (sem_wait (&startup_semaphore) != 0)
+	abort ();
+    }
+
+  /* Unlock the first thread so it can proceed.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  /* Wait for the first thread only.  */
+  pthread_join (threads[0], &retval);
+
+  /* Now post FINISH_SEMAPHORE to allow all the other threads to finish.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    sem_post (&finish_semaphore);
+
+  /* Now wait for the remaining threads to complete.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    pthread_join (threads[i], &retval);
+
+  /* Semaphore cleanup.  */
+  sem_destroy (&finish_semaphore);
+  sem_destroy (&startup_semaphore);
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
new file mode 100644
index 00000000000..aa1e94190cd
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
@@ -0,0 +1,119 @@
+# Copyright 2022 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 reprocuces bug gdb/28942, performing an inferior function
+# call from a breakpoint condition in a multi-threaded inferior.
+#
+# The important part of this test is that, when the conditional
+# breakpoint is hit, and the condition (which includes an inferior
+# function call) is evaluated, the other threads are running.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] == -1 } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "Conditional breakpoint here"]
+set final_bp_line [gdb_get_line_number "Stop marker"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if {![runto_main]} {
+	fail "run to main"
+	return -1
+    }
+
+    return 0
+}
+
+# Run a test of GDB's conditional breakpoints, where the conditions include
+# inferior function calls.
+#
+# CONDITION is combined (with &&) to some additional logic, and used as the
+# breakpoint condition.
+#
+# N_EXPECTED_HITS is the number of threads that we expect to stop due to
+# CONDITON.
+#
+# MESSAGE is used as a test name prefix.
+proc run_condition_test { stop_at_cond \
+			      target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint.
+    if { $stop_at_cond } {
+	set cond_func "return_true"
+    } else {
+	set cond_func "return_false"
+    }
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (${cond_func} ())"
+    set cond_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			"get number for conditional breakpoint"]
+
+    # And a breakpoint that we hit when the test is over, this one is
+    # not conditional.
+    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
+    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			  "get number for final breakpoint"]
+
+    if { $stop_at_cond } {
+	# Continue.  The first breakpoint we hit should be the conditional
+	# breakpoint.  The other thread will have hit its breakpoint, but
+	# that will have been deferred until the conditional breakpoint is
+	# reported.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${cond_bp_num}, worker_func \[^\r\n\]+:${::cond_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Conditional breakpoint here\[^\r\n\]+"] \
+	    "hit the conditional breakpoint"
+    }
+
+    # Run to the stop marker.
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     ".*" \
+	     "" \
+	     "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${final_bp_num}, stop_marker \[^\r\n\]+:${::final_bp_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Stop marker\[^\r\n\]+"] \
+	"hit the final breakpoint"
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	foreach_with_prefix stop_at_cond { true false } {
+	    run_condition_test $stop_at_cond \
+		$target_async $target_non_stop
+	}
+    }
+}
-- 
2.25.4


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

* [PATCH 11/12] gdb: add timeouts for inferior function calls
  2022-10-21  8:43 [PATCH 00/12] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                   ` (9 preceding siblings ...)
  2022-10-21  8:43 ` [PATCH 10/12] gdb: fix b/p conditions with infcalls in multi-threaded inferiors Andrew Burgess
@ 2022-10-21  8:43 ` Andrew Burgess
  2022-10-21 11:08   ` Eli Zaretskii
  2022-11-04 23:17   ` Lancelot SIX
  2022-10-21  8:43 ` [PATCH 12/12] gdb/remote: avoid SIGINT after calling remote_target::stop Andrew Burgess
  2023-01-18 16:17 ` [PATCHv2 00/13] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
  12 siblings, 2 replies; 202+ messages in thread
From: Andrew Burgess @ 2022-10-21  8:43 UTC (permalink / raw)
  To: gdb-patches

In the previous commits I have been working on improving inferior
function call support.  One thing that worries me about using inferior
function calls from a conditional breakpoint is: what happens if the
inferior function call fails?

If the failure is obvious, e.g. the thread performing the call
crashes, or hits a breakpoint, then this case is already well handled,
and the error is reported to the user.

But what if the thread performing the inferior call just deadlocks?
If the user made the call from a 'print' or 'call' command, then the
user might have some expectation of when the function call should
complete, and, when this time limit is exceeded, the user
will (hopefully) interrupt GDB and regain control of the debug
session.

But, when the inferior function call is from a breakpoint condition it
is much harder to understand that GDB is deadlocked within an inferior
call.  Maybe the breakpoint hasn't been hit yet?  Or maybe the
condition was always false?  Or maybe GDB is deadlocked in an inferior
call?  The only way to know for sure is to periodically interrupt GDB,
check on all the threads, and then continue.

Additionally, the focus of the previous commit was inferior function
calls, from a conditional breakpoint, in a multi-threaded inferior.
This opens up a whole new set of potential failure conditions.  For
example, what if the function called relies on interaction with some
other thread, and the other thread crashes?  Or hits a breakpoint?
Given how inferior function calls work - in a synchronous manor, a
stop event in some other thread is going to be ignored when the
inferior function call is being done as part of a breakpoint
condition, and this means that GDB could get stuck waiting for the
original condition thread, which will now never complete.

In this commit I propose a solution to this problem.  A timeout.  For
targets that support async-mode we can install an event-loop timer
before starting the inferior function call.  When the timer expires we
will stop the thread performing the inferior function call.  With this
mechanism in place a user can be sure that any inferior call they make
will either complete, or timeout eventually.

Adding a timer like this is obviously a change in behaviour for the
more common 'call' and 'print' uses of inferior function calls, so, in
this patch, I propose having two different timers.  One I call the
'direct-call-timeout', which is used for 'call' and 'print' commands.
This timeout is by default set to unlimited, which, not surprisingly,
means there is no timeout in place.

A second timer, which I've called 'indirect-call-timeout', is used for
inferior function calls from breakpoint conditions.  This timeout has
a default value of 300 seconds.  This is still a pretty substantial
time to be waiting for a single inferior call to complete, but I
didn't want to be too aggressive with the value I selected.  A user
can, of course, still use Ctrl-c to interrupt an inferior function
call, but this limit will ensure that GDB will stop at some point.

The new commands added by this commit are:

  set direct-call-timeout SECONDS
  show direct-call-timeout
  set indirect-call-timeout SECONDS
  show indirect-call-timeout

These new timeouts do depend on async-mode, so, if async-mode is
disabled (maint set target-async off), or not supported (e.g. target
sim), then the timeout is treated as unlimited (that is, no timeout is
set).

For targets that "fake" non-async mode, e.g. Linux native, where
non-async mode is really just async mode, but then we park the target
in a sissuspend, we could easily fix things so that the timeouts still
work, however, for targets that really are not async aware, like the
simulator, fixing things so that timeouts work correctly would be a
much bigger task - that effort would be better spent just making the
target async-aware.  And so, I'm happy for now that this feature will
only work on async targets.

The two new show commands will display slightly different text if the
current target is a non-async target, which should allow users to
understand what's going on.

There's a somewhat random test adjustment needed in gdb.base/help.exp,
the test uses a regexp with the apropos command, and expects to find a
single result.  Turns out the new settings I added also matched the
regexp, which broke the test.  I've updated the regexp a little to
exclude my new settings.
---
 gdb/NEWS                                      |  16 ++
 gdb/doc/gdb.texinfo                           |  45 +++++
 gdb/infcall.c                                 | 159 ++++++++++++++++
 gdb/testsuite/gdb.base/help.exp               |   2 +-
 gdb/testsuite/gdb.base/infcall-timeout.c      |  36 ++++
 gdb/testsuite/gdb.base/infcall-timeout.exp    |  81 +++++++++
 .../infcall-from-bp-cond-timeout.c            | 169 ++++++++++++++++++
 .../infcall-from-bp-cond-timeout.exp          | 128 +++++++++++++
 8 files changed, 635 insertions(+), 1 deletion(-)
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.c
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp

diff --git a/gdb/NEWS b/gdb/NEWS
index 8b519a648f7..596f38f5c2f 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -115,6 +115,22 @@ set debug infcall on|off
 show debug infcall
   Print additional debug messages about inferior function calls.
 
+set direct-call-timeout SECONDS
+show direct-call-timeout
+set indirect-call-timeout SECONDS
+show indirect-call-timeout
+  These new settings can be used to limit how long GDB will wait for
+  an inferior function call to complete.  The direct timeout is used
+  for inferior function calls from e.g. 'call' and 'print' commands,
+  while the indirect timeout is used for inferior function calls from
+  within a conditional breakpoint expression.
+
+  The default for the direct timeout is unlimited, while the default
+  for the indirect timeout is 300 seconds.
+
+  These timeouts will only have an effect for targets that are
+  operating in async mode.
+
 * Changed commands
 
 document user-defined
diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index ea66f4ee42d..1724bad673e 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -20630,6 +20630,51 @@
 
 @end table
 
+When calling a function within a program, it is possible that the
+program could enter a state from which the called function may never
+return.  If this happens then @value{GDBN} will appear to hang.
+Should this happen then it is possible to interrupt the running
+program by typing the interrupt character (often @kbd{Ctrl-c}).
+
+On some targets @value{GDBN} can also place a timeout on any function
+calls made into the program.  If the timeout expires and the function
+call is still going, then @value{GDBN} will interrupt the program
+automatically.
+
+@table @code
+@item set direct-call-timeout @var{seconds}
+@kindex set direct-call-timeout
+@cindex timeout for called functions
+Set the timeout used when calling functions in the program to
+@var{seconds}, which should be an integer greater than zero, or the
+special value @code{unlimited}, which indicates no timeout should be
+used.  The default for this setting is @code{unlimited}.
+
+This setting only works for targets that support asynchronous
+execution (@pxref{Background Execution}), for any other target the
+setting is treated as @code{unlimited}.
+@end table
+
+It is also possible to call functions within the program from the
+condition of a conditional breakpoint (@pxref{Conditions, ,Break
+Conditions}).  A different setting controls the timeout used for
+functions made from a breakpoint condition.
+
+@table @code
+@item set indirect-call-timeout @var{seconds}
+@kindex set indirect-call-timeout
+@cindex timeout for called functions
+Set the timeout used when calling functions in the program from a
+breakpoint condition to @var{seconds}, which should be an integer
+greater than zero, or the special value @code{unlimited}, which
+indicates no timeout should be used.  The default for this setting is
+@code{300} seconds.
+
+This setting only works for targets that support asynchronous
+execution (@pxref{Background Execution}), for any other target the
+setting is treated as @code{unlimited}.
+@end table
+
 @subsection Calling functions with no debug info
 
 @cindex no debug info functions
diff --git a/gdb/infcall.c b/gdb/infcall.c
index 99ca5792dd3..4eca505250b 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -95,6 +95,53 @@ show_may_call_functions_p (struct ui_file *file, int from_tty,
 	      value);
 }
 
+/* A timeout (in seconds) for direct inferior calls.  A direct inferior
+   call is one the user triggers from the prompt, e.g. with a 'call' or
+   'print' command.  Compare with the definition of indirect calls below.  */
+
+static unsigned int direct_call_timeout = UINT_MAX;
+
+/* Implement 'show direct-call-timeout'.  */
+
+static void
+show_direct_call_timeout (struct ui_file *file, int from_tty,
+			  struct cmd_list_element *c, const char *value)
+{
+  if (target_has_execution () && !target_can_async_p ())
+    gdb_printf (file, _("Current target does not support async mode, timeout "
+			"for direct inferior calls is \"unlimited\".\n"));
+  else if (direct_call_timeout == UINT_MAX)
+    gdb_printf (file, _("Timeout for direct inferior function calls "
+			"is \"unlimited\".\n"));
+  else
+    gdb_printf (file, _("Timeout for direct inferior function calls "
+			"is \"%s seconds\".\n"), value);
+}
+
+/* A timeout (in seconds) for indirect inferior calls.  An indirect inferior
+   call is one that originates from within GDB, for example, when
+   evaluating an expression for a conditional breakpoint.  Compare with
+   the definition of direct calls above.  */
+
+static unsigned int indirect_call_timeout = 300;
+
+/* Implement 'show indirect-call-timeout'.  */
+
+static void
+show_indirect_call_timeout (struct ui_file *file, int from_tty,
+			  struct cmd_list_element *c, const char *value)
+{
+  if (target_has_execution () && !target_can_async_p ())
+    gdb_printf (file, _("Current target does not support async mode, timeout "
+			"for indirect inferior calls is \"unlimited\".\n"));
+  else if (indirect_call_timeout == UINT_MAX)
+    gdb_printf (file, _("Timeout for indirect inferior function calls "
+			"is \"unlimited\".\n"));
+  else
+    gdb_printf (file, _("Timeout for indirect inferior function calls "
+			"is \"%s seconds\".\n"), value);
+}
+
 /* How you should pass arguments to a function depends on whether it
    was defined in K&R style or prototype style.  If you define a
    function using the K&R syntax that takes a `float' argument, then
@@ -595,6 +642,85 @@ call_thread_fsm::should_notify_stop ()
   return true;
 }
 
+/* A class to control creation of a timer that will interrupt a thread
+   during an inferior call.  */
+struct infcall_timer_controller
+{
+  /* Setup an event-loop timer that will interrupt PTID if the inferior
+     call takes too long.  DIRECT_CALL_P is true when this inferior call is
+     a result of the user using a 'print' or 'call' command, and false when
+     this inferior call is a result of e.g. a conditional breakpoint
+     expression, this is used to select which timeout to use.  */
+  infcall_timer_controller (ptid_t ptid, bool direct_call_p)
+    : m_ptid (ptid)
+  {
+    unsigned int timeout
+      = direct_call_p ? direct_call_timeout : indirect_call_timeout;
+    if (timeout < UINT_MAX && target_can_async_p ())
+      {
+	int ms = timeout * 1000;
+	int id = create_timer (ms, infcall_timer_controller::timed_out, this);
+	m_timer_id.emplace (id);
+	infcall_debug_printf ("Setting up infcall timeout timer for "
+			      "ptid %s: %d milliseconds",
+			      m_ptid.to_string ().c_str (), ms);
+      }
+  }
+
+  /* Destructor.  Ensure that the timer is removed from the event loop.  */
+  ~infcall_timer_controller ()
+  {
+    /* If the timer has already triggered, then it will have already been
+       deleted from the event loop.  If the timer has not triggered, then
+       delete it now.  */
+    if (m_timer_id.has_value () && !m_triggered)
+      delete_timer (*m_timer_id);
+
+    /* Just for clarity, discard the timer id now.  */
+    m_timer_id.reset ();
+  }
+
+  /* Return true if there was a timer in place, and the timer triggered,
+     otherwise, return false.  */
+  bool triggered_p ()
+  {
+    gdb_assert (!m_triggered || m_timer_id.has_value ());
+    return m_triggered;
+  }
+
+private:
+  /* The thread we should interrupt.  */
+  ptid_t m_ptid;
+
+  /* Set true when the timer is triggered.  */
+  bool m_triggered = false;
+
+  /* Given a value when a timer is in place.  */
+  gdb::optional<int> m_timer_id;
+
+  /* Callback for the timer, forwards to ::trigger below.  */
+  static void
+  timed_out (gdb_client_data context)
+  {
+    infcall_timer_controller *ctrl
+      = static_cast<infcall_timer_controller *> (context);
+    ctrl->trigger ();
+  }
+
+  /* Called when the timer goes off.  Stop thread m_ptid.  */
+  void
+  trigger ()
+  {
+    m_triggered = true;
+
+    scoped_disable_commit_resumed disable_commit_resumed ("infcall timeout");
+
+    infcall_debug_printf ("Stopping thread %s",
+			  m_ptid.to_string ().c_str ());
+    target_stop (m_ptid);
+  }
+};
+
 /* Subroutine of call_function_by_hand to simplify it.
    Start up the inferior and wait for it to stop.
    Return the exception if there's an error, or an exception with
@@ -656,10 +782,19 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
       infrun_debug_show_threads ("non-exited threads after proceed for inferior-call",
 				 all_non_exited_threads ());
 
+      /* Setup a timer (if possible, and if the settings allow) to prevent
+	 the inferior call running forever.  */
+      bool direct_call_p = !call_thread->control.in_cond_eval;
+      infcall_timer_controller infcall_timer (inferior_ptid, direct_call_p);
+
       /* Inferior function calls are always synchronous, even if the
 	 target supports asynchronous execution.  */
       wait_sync_command_done ();
 
+      /* If the timer triggered then the inferior call failed.  */
+      if (infcall_timer.triggered_p ())
+	error (_("timeout waiting for inferior function to complete"));
+
       infcall_debug_printf ("inferior call completed successfully");
     }
   catch (gdb_exception &e)
@@ -1649,6 +1784,30 @@ The default is to unwind the frame."),
 			   show_unwind_on_terminating_exception_p,
 			   &setlist, &showlist);
 
+  add_setshow_uinteger_cmd ("direct-call-timeout", no_class,
+			    &direct_call_timeout, _("\
+Set the timeout, for direct calls to inferior function calls."), _("\
+Show the timeout, for direct calls to inferior function calls."), _("\
+If running on a target that supports, and is running in, async mode\n\
+then this timeout is used for any inferior function calls triggered\n\
+directly from the prompt, e.g. from a 'call' or 'print' command.  The\n\
+timeout is specified in seconds."),
+			    nullptr,
+			    show_direct_call_timeout,
+			    &setlist, &showlist);
+
+  add_setshow_uinteger_cmd ("indirect-call-timeout", no_class,
+			    &indirect_call_timeout, _("\
+Set the timeout, for indirect calls to inferior function calls."), _("\
+Show the timeout, for indirect calls to inferior function calls."), _("\
+If running on a target that supports, and is running in, async mode\n\
+then this timeout is used for any inferior function calls triggered\n\
+indirectly, e.g. when evaluating a conditional breakpoint expression.\n\
+The timeout is specified in seconds."),
+			    nullptr,
+			    show_indirect_call_timeout,
+			    &setlist, &showlist);
+
   add_setshow_boolean_cmd
     ("infcall", class_maintenance, &debug_infcall,
      _("Set inferior call debugging."),
diff --git a/gdb/testsuite/gdb.base/help.exp b/gdb/testsuite/gdb.base/help.exp
index 5ee8ce0726d..54b0be32cf8 100644
--- a/gdb/testsuite/gdb.base/help.exp
+++ b/gdb/testsuite/gdb.base/help.exp
@@ -121,7 +121,7 @@ gdb_test "help info bogus-gdb-command" "Undefined info command: \"bogus-gdb-comm
 gdb_test "help gotcha" "Undefined command: \"gotcha\"\.  Try \"help\"\."
 
 # Test apropos regex.
-gdb_test "apropos \\\(print\[\^\[ bsiedf\\\".-\]\\\)" "handle -- Specify how to handle signals\."
+gdb_test "apropos \\\(print\[\^\[ bsiedf\\\"'.-\]\\\)" "handle -- Specify how to handle signals\."
 # Test apropos >1 word string.
 gdb_test "apropos handle signal" "handle -- Specify how to handle signals\."
 # Test apropos apropos.
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.c b/gdb/testsuite/gdb.base/infcall-timeout.c
new file mode 100644
index 00000000000..895e8a36d59
--- /dev/null
+++ b/gdb/testsuite/gdb.base/infcall-timeout.c
@@ -0,0 +1,36 @@
+/* Copyright 2022 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 <unistd.h>
+
+/* This function is called from GDB.  */
+int
+function_that_never_returns ()
+{
+  while (1)
+    sleep (1);
+
+  return 0;
+}
+
+int
+main ()
+{
+  alarm (300);
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.exp b/gdb/testsuite/gdb.base/infcall-timeout.exp
new file mode 100644
index 00000000000..2bca092aaf8
--- /dev/null
+++ b/gdb/testsuite/gdb.base/infcall-timeout.exp
@@ -0,0 +1,81 @@
+# Copyright 2022 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/>.
+
+# Test GDB's direct-call-timeout setting, that is, ensure that if an
+# inferior function call, invoked from e.g. a 'print' command, takes
+# too long, then GDB can interrupt it, and return control to the user.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug}] == -1 } {
+    return
+}
+
+# Start GDB according to TARGET_ASYNC and TARGET_NON_STOP, then adjust
+# the direct-call-timeout, and make an inferior function call that
+# will never return.  GDB should eventually timeout and stop the
+# inferior.
+proc_with_prefix run_test { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if {![runto_main]} {
+	fail "run to main"
+	return
+    }
+
+    gdb_test_no_output "set direct-call-timeout 5"
+
+    # When non-stop mode is off we get slightly different output from GDB.
+    if { [gdb_is_remote_or_extended_remote_target] && $target_non_stop == "off" } {
+	set stopped_line_pattern "Program received signal SIGINT, Interrupt\\."
+    } else {
+	set stopped_line_pattern "Program stopped\\."
+    }
+
+    gdb_test "print function_that_never_returns ()" \
+	[multi_line \
+	     $stopped_line_pattern \
+	     ".*" \
+	     "timeout waiting for inferior function to complete" \
+	     "An error occurred while in a function called from GDB\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(function_that_never_returns\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+
+    gdb_test "bt" ".* function_that_never_returns .*<function called from gdb>.*"
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+
+    if { $target_async == "off" } {
+	# GDB can't timeout while waiting for a thread if the target
+	# runs with async-mode turned off; once the target is running
+	# GDB is effectively blocked until the target stops for some
+	# reason.
+	continue
+    }
+
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	run_test $target_async $target_non_stop
+    }
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
new file mode 100644
index 00000000000..3bd91d7377d
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
@@ -0,0 +1,169 @@
+/* This testcase is part of GDB, the GNU debugger.
+
+   Copyright 2022 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 <stdio.h>
+#include <pthread.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <semaphore.h>
+
+#define NUM_THREADS 5
+
+/* Semaphores, used to track when threads have started, and to control
+   when the threads finish.  */
+sem_t startup_semaphore;
+sem_t finish_semaphore;
+sem_t thread_1_semaphore;
+sem_t thread_2_semaphore;
+
+/* Mutex to control when the first worker thread hit a breakpoint
+   location.  */
+pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+
+/* Global variable to poke, just so threads have something to do.  */
+volatile int global_var = 0;
+
+int
+condition_func ()
+{
+  /* Let thread 2 run.  */
+  if (sem_post (&thread_2_semaphore) != 0)
+    abort ();
+
+  /* Wait for thread 2 to complete its actions.  */
+  if (sem_wait (&thread_1_semaphore) != 0)
+    abort ();
+
+  return 1;
+}
+
+void
+do_segfault ()
+{
+  volatile int *p = 0;
+  *p = 0;	/* Segfault here.  */
+}
+
+void *
+worker_func (void *arg)
+{
+  int tid = *((int *) arg);
+
+  /* Let the main thread know that this worker has started.  */
+  if (sem_post (&startup_semaphore) != 0)
+    abort ();
+
+  switch (tid)
+    {
+    case 0:
+      /* Wait for MUTEX to become available, then pass through the
+	 conditional breakpoint location.  */
+      if (pthread_mutex_lock (&mutex) != 0)
+	abort ();
+      global_var = 99;	/* Conditional breakpoint here.  */
+      if (pthread_mutex_unlock (&mutex) != 0)
+	abort ();
+      break;
+
+    case 1:
+      if (sem_wait (&thread_2_semaphore) != 0)
+	abort ();
+      do_segfault ();
+      if (sem_post (&thread_1_semaphore) != 0)
+	abort ();
+
+      /* Fall through.  */
+    default:
+      /* Wait until we are allowed to finish.  */
+      if (sem_wait (&finish_semaphore) != 0)
+	abort ();
+      break;
+    }
+}
+
+void
+stop_marker ()
+{
+  global_var = 99;	/* Stop marker.  */
+}
+
+/* The main program entry point.  */
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+  void *retval;
+
+  /* An alarm, just in case the thread deadlocks.  */
+  alarm (300);
+
+  /* Semaphore initialization.  */
+  if (sem_init (&startup_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&finish_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&thread_1_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&thread_2_semaphore, 0, 0) != 0)
+    abort ();
+
+  /* Lock MUTEX, this prevents the first worker thread from rushing ahead.  */
+  if (pthread_mutex_lock (&mutex) != 0)
+    abort ();
+
+  /* Worker thread creation.  */
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  /* Wait for every thread to start.  */
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      if (sem_wait (&startup_semaphore) != 0)
+	abort ();
+    }
+
+  /* Unlock the first thread so it can proceed.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  /* Wait for the first thread only.  */
+  pthread_join (threads[0], &retval);
+
+  /* Now post FINISH_SEMAPHORE to allow all the other threads to finish.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    sem_post (&finish_semaphore);
+
+  /* Now wait for the remaining threads to complete.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    pthread_join (threads[i], &retval);
+
+  /* Semaphore cleanup.  */
+  sem_destroy (&finish_semaphore);
+  sem_destroy (&startup_semaphore);
+  sem_destroy (&thread_1_semaphore);
+  sem_destroy (&thread_2_semaphore);
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
new file mode 100644
index 00000000000..17beba75db0
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
@@ -0,0 +1,128 @@
+# Copyright 2020 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 inferior calls executed from a breakpoint condition in
+# a multi-threaded program.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "Conditional breakpoint here"]
+set final_bp_line [gdb_get_line_number "Stop marker"]
+set segfault_line [gdb_get_line_number "Segfault here"]
+
+proc run_test { other_thread_bp target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if {![runto_main]} {
+	fail "run to main"
+	return
+    }
+
+    # The default timeout for indirect inferior calls (e.g. inferior
+    # calls for conditional breakpoint expressions) is pretty high.
+    # We don't want the test to take too long, so reduce this.
+    #
+    # However, the test relies on a second thread hitting some event
+    # (either a breakpoint or signal) before this timeout expires.
+    #
+    # There is a chance that on a really slow system this might not
+    # happen, in which case the test might fail.
+    #
+    # However, we still allocate 5 seconds, which feels like it should
+    # be enough time in most cases.
+    gdb_test_no_output "set indirect-call-timeout 5"
+
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (condition_func ())"
+    set bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		    "get number for conditional breakpoint"]
+
+    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
+    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			  "get number for final breakpoint"]
+
+    if { $other_thread_bp } {
+	gdb_breakpoint "${::srcfile}:${::segfault_line}"
+	set segfault_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+				 "get number for segfault breakpoint"]
+    }
+
+    # When non-stop mode is off we get slightly different output from GDB.
+    if { [gdb_is_remote_or_extended_remote_target] && $target_non_stop == "off" } {
+	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" received signal SIGINT, Interrupt\\."
+    } else {
+	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\."
+    }
+
+    gdb_test "continue" \
+	[multi_line \
+	     $stopped_line_pattern \
+	     ".*" \
+	     "Error in testing condition for breakpoint ${bp_num}:" \
+	     "timeout waiting for inferior function to complete" \
+	     "An error occurred while in a function called from GDB\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(condition_func\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."] \
+	"expected timeout waiting for inferior call to complete"
+
+    if { $other_thread_bp } {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${segfault_bp_num}, do_segfault \[^\r\n\]+:${::segfault_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"] \
+	    "hit the segfault breakpoint"
+    } else {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "Thread ${::decimal} \"infcall-from-bp\" received signal SIGSEGV, Segmentation fault\\." \
+		 "\\\[Switching to Thread \[^\r\n\]+\\\]" \
+		 "${::hex} in do_segfault \\(\\) at \[^\r\n\]+:${::segfault_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"] \
+	    "hit the segfault"
+    }
+}
+
+foreach_with_prefix target_async {"on" "off" } {
+
+    if { $target_async == "off" } {
+	# GDB can't timeout while waiting for a thread if the target
+	# runs with async-mode turned off; once the target is running
+	# GDB is effectively blocked until the target stops for some
+	# reason.
+	continue
+    }
+
+    foreach_with_prefix target_non_stop {"off" "on"} {
+	foreach_with_prefix other_thread_bp { true false } {
+	    run_test $other_thread_bp $target_async $target_non_stop
+	}
+    }
+}
-- 
2.25.4


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

* [PATCH 12/12] gdb/remote: avoid SIGINT after calling remote_target::stop
  2022-10-21  8:43 [PATCH 00/12] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                   ` (10 preceding siblings ...)
  2022-10-21  8:43 ` [PATCH 11/12] gdb: add timeouts for inferior function calls Andrew Burgess
@ 2022-10-21  8:43 ` Andrew Burgess
  2023-01-18 16:17 ` [PATCHv2 00/13] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
  12 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2022-10-21  8:43 UTC (permalink / raw)
  To: gdb-patches

Currently, if the remote target is not running in non-stop mode, then,
when GDB calls remote_target::stop, we end up sending an interrupt
packet \x03 to the remote target.

If the user interrupts the inferior from the GDB prompt (e.g. by
typing Ctrl-c), then GDB calls remote_target::interrupt, which also
ends up sending the interrupt packet.

The problem here is that both of these mechanisms end up sending the
interrupt packet, which means, when the target stops with a SIGINT,
and this is reported back to GDB, we have no choice but to report this
to the user as a SIGINT stop event.

Now maybe this is the correct thing to do, after all the target has
been stopped with SIGINT.  However, this leads to an unfortunate
change in behaviour.

When running in non-stop mode, and remote_target::stop is called, the
target will be stopped with a vCont packet, and this stop is then
reported back to GDB as GDB_SIGNAL_0, this will cause GDB to print a
message like:

  Program stopped.

Or:

  Thread NN "binary name" stopped.

In contrast, when non-stop mode is off, we get messages like:

  Program received SIGINT, Segmentation fault.

Or:

  Thread NN "binary name" received SIGINT, Segmentation fault.

In this commit I propose a mechanism where we can track that a stop
has been requested for a particular thread through
remote_target::stop, then, when the stop arrives, we can convert the
SIGINT to a GDB_SIGNAL_0.  With this done GDB will now display the
"stopped" based messages rather than the "received SIGINT" messages.

Two of the tests added in the previous commit exposed this issue.  In
the previous commit the tests looked for either of the above
patterns.  In this commit I've updated these tests to only look for
the "stopped" based messages.
---
 gdb/remote.c                                    | 17 +++++++++++++++++
 gdb/testsuite/gdb.base/infcall-timeout.exp      |  9 +--------
 .../infcall-from-bp-cond-timeout.exp            |  9 +--------
 3 files changed, 19 insertions(+), 16 deletions(-)

diff --git a/gdb/remote.c b/gdb/remote.c
index 17c2d17c8fe..141f7d3656f 100644
--- a/gdb/remote.c
+++ b/gdb/remote.c
@@ -1139,6 +1139,10 @@ struct remote_thread_info : public private_thread_info
   std::string name;
   int core = -1;
 
+  /* Only used when not in non-stop mode.  Set to true when a stop is
+     requested for the thread.  */
+  bool stop_requested = false;
+
   /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
      sequence of bytes.  */
   gdb::byte_vector thread_handle;
@@ -7112,6 +7116,12 @@ remote_target::stop (ptid_t ptid)
       /* We don't currently have a way to transparently pause the
 	 remote target in all-stop mode.  Interrupt it instead.  */
       remote_interrupt_as ();
+
+      /* Record that this thread's stop is a result of GDB asking for the
+	 stop, rather than the user asking for an interrupt.  We can use
+	 this information to adjust the waitstatus when it arrives.  */
+      remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
+      remote_thr->stop_requested = true;
     }
 }
 
@@ -8095,9 +8105,16 @@ remote_target::process_stop_reply (struct stop_reply *stop_reply,
 	  /* If the target works in non-stop mode, a stop-reply indicates that
 	     only this thread stopped.  */
 	  remote_thr->set_not_resumed ();
+	  gdb_assert (!remote_thr->stop_requested);
 	}
       else
 	{
+	  if (status->kind () == TARGET_WAITKIND_STOPPED
+	      && status->sig () == GDB_SIGNAL_INT
+	      && remote_thr->stop_requested)
+	    status->set_stopped (GDB_SIGNAL_0);
+	  remote_thr->stop_requested = false;
+
 	  /* If the target works in all-stop mode, a stop-reply indicates that
 	     all the target's threads stopped.  */
 	  for (thread_info *tp : all_non_exited_threads (this))
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.exp b/gdb/testsuite/gdb.base/infcall-timeout.exp
index 2bca092aaf8..64b294b2f98 100644
--- a/gdb/testsuite/gdb.base/infcall-timeout.exp
+++ b/gdb/testsuite/gdb.base/infcall-timeout.exp
@@ -45,16 +45,9 @@ proc_with_prefix run_test { target_async target_non_stop } {
 
     gdb_test_no_output "set direct-call-timeout 5"
 
-    # When non-stop mode is off we get slightly different output from GDB.
-    if { [gdb_is_remote_or_extended_remote_target] && $target_non_stop == "off" } {
-	set stopped_line_pattern "Program received signal SIGINT, Interrupt\\."
-    } else {
-	set stopped_line_pattern "Program stopped\\."
-    }
-
     gdb_test "print function_that_never_returns ()" \
 	[multi_line \
-	     $stopped_line_pattern \
+	     "Program stopped\\." \
 	     ".*" \
 	     "timeout waiting for inferior function to complete" \
 	     "An error occurred while in a function called from GDB\\." \
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
index 17beba75db0..bbeb49eb41e 100644
--- a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
@@ -69,16 +69,9 @@ proc run_test { other_thread_bp target_async target_non_stop } {
 				 "get number for segfault breakpoint"]
     }
 
-    # When non-stop mode is off we get slightly different output from GDB.
-    if { [gdb_is_remote_or_extended_remote_target] && $target_non_stop == "off" } {
-	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" received signal SIGINT, Interrupt\\."
-    } else {
-	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\."
-    }
-
     gdb_test "continue" \
 	[multi_line \
-	     $stopped_line_pattern \
+	     "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\." \
 	     ".*" \
 	     "Error in testing condition for breakpoint ${bp_num}:" \
 	     "timeout waiting for inferior function to complete" \
-- 
2.25.4


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

* Re: [PATCH 11/12] gdb: add timeouts for inferior function calls
  2022-10-21  8:43 ` [PATCH 11/12] gdb: add timeouts for inferior function calls Andrew Burgess
@ 2022-10-21 11:08   ` Eli Zaretskii
  2023-01-14 11:00     ` Andrew Burgess
  2022-11-04 23:17   ` Lancelot SIX
  1 sibling, 1 reply; 202+ messages in thread
From: Eli Zaretskii @ 2022-10-21 11:08 UTC (permalink / raw)
  To: Andrew Burgess; +Cc: gdb-patches

> Date: Fri, 21 Oct 2022 09:43:47 +0100
> From: Andrew Burgess via Gdb-patches <gdb-patches@sourceware.org>
> 
> --- a/gdb/NEWS
> +++ b/gdb/NEWS
> @@ -115,6 +115,22 @@ set debug infcall on|off
>  show debug infcall
>    Print additional debug messages about inferior function calls.
>  
> +set direct-call-timeout SECONDS
> +show direct-call-timeout
> +set indirect-call-timeout SECONDS
> +show indirect-call-timeout
> +  These new settings can be used to limit how long GDB will wait for
> +  an inferior function call to complete.  The direct timeout is used
> +  for inferior function calls from e.g. 'call' and 'print' commands,
> +  while the indirect timeout is used for inferior function calls from
> +  within a conditional breakpoint expression.
> +
> +  The default for the direct timeout is unlimited, while the default
> +  for the indirect timeout is 300 seconds.

IMO, 300 seconds is way too long a wait for a breakpoint condition.
It should be a matter of a few seconds at most, IMO.

> +  These timeouts will only have an effect for targets that are
> +  operating in async mode.

This should tell what happens on targets that don't support async
mode.

> +When calling a function within a program, it is possible that the
> +program could enter a state from which the called function may never
> +return.  If this happens then @value{GDBN} will appear to hang.
> +Should this happen then it is possible to interrupt the running
> +program by typing the interrupt character (often @kbd{Ctrl-c}).
> +
> +On some targets @value{GDBN} can also place a timeout on any function
> +calls made into the program.

Instead of "some targets", which leaves those targets unspecified, we
should say "targets that support async mode", with a cross-reference
to where that is described.  We should give the user a means to
determine whether the particular target does or doesn't need/support
this timeout feature.

>                              If the timeout expires and the function
> +call is still going, then @value{GDBN} will interrupt the program
> +automatically.

And what does this mean for the value returned by the interrupted
call?  This is important for the breakpoint condition use case, for
example.

> +
> +@table @code
> +@item set direct-call-timeout @var{seconds}
> +@kindex set direct-call-timeout
> +@cindex timeout for called functions
> +Set the timeout used when calling functions in the program to
> +@var{seconds}, which should be an integer greater than zero, or the
> +special value @code{unlimited}, which indicates no timeout should be
> +used.  The default for this setting is @code{unlimited}.

Why integer in seconds? don't we want to be able to support shorter
timeouts, like 100 msec?  Most inferior calls should take much less
than a second, so a second resolution is not the best idea, IMO.  It
could, for example, make running a program with such a breakpoint
unbearably slow.

> +This setting only works for targets that support asynchronous
> +execution (@pxref{Background Execution}), for any other target the
> +setting is treated as @code{unlimited}.

This should be moved to the beginning of the description, as mentioned
above.  In addition, saying "treated as 'unlimited'" is not clear
enough in this context, because actually no timeout is applicable at
all, and GDB will wait indefinitely for the call to return.  We should
tell this explicitly.

> +It is also possible to call functions within the program from the
> +condition of a conditional breakpoint (@pxref{Conditions, ,Break
> +Conditions}).  A different setting controls the timeout used for
> +functions made from a breakpoint condition.
   ^^^^^^^^^^^^^^
"function calls made..."

> +@item set indirect-call-timeout @var{seconds}
> +@kindex set indirect-call-timeout
> +@cindex timeout for called functions
> +Set the timeout used when calling functions in the program from a
> +breakpoint condition to @var{seconds}, which should be an integer
> +greater than zero, or the special value @code{unlimited}, which
> +indicates no timeout should be used.  The default for this setting is
> +@code{300} seconds.

Here 300 seconds is definitely too long.

> +  add_setshow_uinteger_cmd ("direct-call-timeout", no_class,
> +			    &direct_call_timeout, _("\
> +Set the timeout, for direct calls to inferior function calls."), _("\
> +Show the timeout, for direct calls to inferior function calls."), _("\
> +If running on a target that supports, and is running in, async mode\n\
> +then this timeout is used for any inferior function calls triggered\n\
> +directly from the prompt, e.g. from a 'call' or 'print' command.  The\n\
> +timeout is specified in seconds."),
> +			    nullptr,
> +			    show_direct_call_timeout,
> +			    &setlist, &showlist);
> +
> +  add_setshow_uinteger_cmd ("indirect-call-timeout", no_class,
> +			    &indirect_call_timeout, _("\
> +Set the timeout, for indirect calls to inferior function calls."), _("\
> +Show the timeout, for indirect calls to inferior function calls."), _("\
> +If running on a target that supports, and is running in, async mode\n\
> +then this timeout is used for any inferior function calls triggered\n\
> +indirectly, e.g. when evaluating a conditional breakpoint expression.\n\
> +The timeout is specified in seconds."),

These doc strings explain what is a "direct" vs "indirect" call by way
of "e.g.".  But that leaves the issue not well-defined, because it
begs the question: what are the other cases that are considered
"direct" or "indirect"?

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

* Re: [PATCH 01/12] gdb: int to bool conversion for normal_stop
  2022-10-21  8:43 ` [PATCH 01/12] gdb: int to bool conversion for normal_stop Andrew Burgess
@ 2022-11-04 12:20   ` Lancelot SIX
  2023-01-13 16:35     ` Andrew Burgess
  0 siblings, 1 reply; 202+ messages in thread
From: Lancelot SIX @ 2022-11-04 12:20 UTC (permalink / raw)
  To: Andrew Burgess; +Cc: gdb-patches

Hi Andrew,

I believe there is one more callsite which can be updated in
infrun.c:fetch_inferior_event:

    diff --git a/gdb/infrun.c b/gdb/infrun.c
    index 3660272ef11..666c1c17f15 100644
    --- a/gdb/infrun.c
    +++ b/gdb/infrun.c
    @@ -4248,7 +4248,7 @@ fetch_inferior_event ()
            else
              {
                bool should_notify_stop = true;
    -           int proceeded = 0;
    +           bool proceeded = false;
    
                stop_all_threads_if_all_stop_mode ();

Otherwise, this looks good to me.

Best,
Lancelot.


On Fri, Oct 21, 2022 at 09:43:37AM +0100, Andrew Burgess via Gdb-patches wrote:
> Change the return type of normal_stop (infrun.c) from int to bool.
> Update callers.
> 
> There should be no user visible changes after this commit.
> ---
>  gdb/infcmd.c | 2 +-
>  gdb/infrun.c | 6 +++---
>  gdb/infrun.h | 2 +-
>  3 files changed, 5 insertions(+), 5 deletions(-)
> 
> diff --git a/gdb/infcmd.c b/gdb/infcmd.c
> index d729732c81c..6af11ac0cb6 100644
> --- a/gdb/infcmd.c
> +++ b/gdb/infcmd.c
> @@ -873,7 +873,7 @@ step_1 (int skip_subroutines, int single_inst, const char *count_string)
>      proceed ((CORE_ADDR) -1, GDB_SIGNAL_DEFAULT);
>    else
>      {
> -      int proceeded;
> +      bool proceeded;
>  
>        /* Stepped into an inline frame.  Pretend that we've
>  	 stopped.  */
> diff --git a/gdb/infrun.c b/gdb/infrun.c
> index cdfe02393f5..39840ef32c8 100644
> --- a/gdb/infrun.c
> +++ b/gdb/infrun.c
> @@ -8614,7 +8614,7 @@ stop_context::changed () const
>  
>  /* See infrun.h.  */
>  
> -int
> +bool
>  normal_stop (void)
>  {
>    struct target_waitstatus last;
> @@ -8774,7 +8774,7 @@ normal_stop (void)
>       the observers would print a stop for the wrong
>       thread/inferior.  */
>    if (saved_context.changed ())
> -    return 1;
> +    return true;
>  
>    /* Notify observers about the stop.  This is where the interpreters
>       print the stop event.  */
> @@ -8796,7 +8796,7 @@ normal_stop (void)
>  	breakpoint_auto_delete (inferior_thread ()->control.stop_bpstat);
>      }
>  
> -  return 0;
> +  return false;
>  }
>  \f
>  int
> diff --git a/gdb/infrun.h b/gdb/infrun.h
> index c711b9b21cc..11a18583e68 100644
> --- a/gdb/infrun.h
> +++ b/gdb/infrun.h
> @@ -149,7 +149,7 @@ extern process_stratum_target *user_visible_resume_target (ptid_t resume_ptid);
>     appropriate messages, remove breakpoints, give terminal our modes,
>     and run the stop hook.  Returns true if the stop hook proceeded the
>     target, false otherwise.  */
> -extern int normal_stop (void);
> +extern bool normal_stop (void);
>  
>  /* Return the cached copy of the last target/ptid/waitstatus returned
>     by target_wait().  The data is actually cached by handle_inferior_event(),
> -- 
> 2.25.4
> 

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

* Re: [PATCH 11/12] gdb: add timeouts for inferior function calls
  2022-10-21  8:43 ` [PATCH 11/12] gdb: add timeouts for inferior function calls Andrew Burgess
  2022-10-21 11:08   ` Eli Zaretskii
@ 2022-11-04 23:17   ` Lancelot SIX
  2023-01-13 16:49     ` Andrew Burgess
  1 sibling, 1 reply; 202+ messages in thread
From: Lancelot SIX @ 2022-11-04 23:17 UTC (permalink / raw)
  To: Andrew Burgess; +Cc: gdb-patches

Hi,

> In this commit I propose a solution to this problem.  A timeout.  For
> targets that support async-mode we can install an event-loop timer
> before starting the inferior function call.  When the timer expires we
> will stop the thread performing the inferior function call.  With this
> mechanism in place a user can be sure that any inferior call they make
> will either complete, or timeout eventually.
> 
> Adding a timer like this is obviously a change in behaviour for the
> more common 'call' and 'print' uses of inferior function calls, so, in
> this patch, I propose having two different timers.  One I call the
> 'direct-call-timeout', which is used for 'call' and 'print' commands.
> This timeout is by default set to unlimited, which, not surprisingly,
> means there is no timeout in place.
> 
> A second timer, which I've called 'indirect-call-timeout', is used for
> inferior function calls from breakpoint conditions.  This timeout has
> a default value of 300 seconds.  This is still a pretty substantial
> time to be waiting for a single inferior call to complete, but I
> didn't want to be too aggressive with the value I selected.  A user
> can, of course, still use Ctrl-c to interrupt an inferior function
> call, but this limit will ensure that GDB will stop at some point.
> 

I do see the use of the indirect call timeouts, and I find it a good
solution for the problem you are trying to solve. I am however not sure
I see much usecase for the direct one.  It looks to me that using Ctrl-C
serves this purpose well already.  Do you have a use case in mind where
this can come in handy?  Scripting and automation maybe?

It seems to me that only having the setting for the indirect call
timeout would make the interface simpler.

That being said, once you have implemented the mechanism for the
"indirect" calls, "direct" call timeout implementation comes for free.
I guess this was your reasoning.

Lancelot.

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

* Re: [PATCH 01/12] gdb: int to bool conversion for normal_stop
  2022-11-04 12:20   ` Lancelot SIX
@ 2023-01-13 16:35     ` Andrew Burgess
  0 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-01-13 16:35 UTC (permalink / raw)
  To: Lancelot SIX; +Cc: gdb-patches

Lancelot SIX <lsix@lancelotsix.com> writes:

> Hi Andrew,
>
> I believe there is one more callsite which can be updated in
> infrun.c:fetch_inferior_event:
>
>     diff --git a/gdb/infrun.c b/gdb/infrun.c
>     index 3660272ef11..666c1c17f15 100644
>     --- a/gdb/infrun.c
>     +++ b/gdb/infrun.c
>     @@ -4248,7 +4248,7 @@ fetch_inferior_event ()
>             else
>               {
>                 bool should_notify_stop = true;
>     -           int proceeded = 0;
>     +           bool proceeded = false;
>     
>                 stop_all_threads_if_all_stop_mode ();
>
> Otherwise, this looks good to me.

Thanks, I made this update and pushed this patch.  The final version
that I pushed is below.

Thanks,
Andrew

---

commit 8dd08de7e48850496321548099ef86d3275679b9
Author: Andrew Burgess <aburgess@redhat.com>
Date:   Mon Oct 17 15:01:24 2022 +0100

    gdb: int to bool conversion for normal_stop
    
    Change the return type of normal_stop (infrun.c) from int to bool.
    Update callers.
    
    I've also converted the (void) to () in the function declaration and
    definition, given I was changing those lines anyway.
    
    There should be no user visible changes after this commit.

diff --git a/gdb/infcmd.c b/gdb/infcmd.c
index 0497ad05091..7d5ec77ff57 100644
--- a/gdb/infcmd.c
+++ b/gdb/infcmd.c
@@ -885,12 +885,10 @@ step_1 (int skip_subroutines, int single_inst, const char *count_string)
     proceed ((CORE_ADDR) -1, GDB_SIGNAL_DEFAULT);
   else
     {
-      int proceeded;
-
       /* Stepped into an inline frame.  Pretend that we've
 	 stopped.  */
       thr->thread_fsm ()->clean_up (thr);
-      proceeded = normal_stop ();
+      bool proceeded = normal_stop ();
       if (!proceeded)
 	inferior_event_handler (INF_EXEC_COMPLETE);
       all_uis_check_sync_execution_done ();
diff --git a/gdb/infrun.c b/gdb/infrun.c
index 181d961d80d..1a2ef2d078b 100644
--- a/gdb/infrun.c
+++ b/gdb/infrun.c
@@ -4219,7 +4219,7 @@ fetch_inferior_event ()
 	else
 	  {
 	    bool should_notify_stop = true;
-	    int proceeded = 0;
+	    bool proceeded = false;
 
 	    stop_all_threads_if_all_stop_mode ();
 
@@ -8582,8 +8582,8 @@ stop_context::changed () const
 
 /* See infrun.h.  */
 
-int
-normal_stop (void)
+bool
+normal_stop ()
 {
   struct target_waitstatus last;
 
@@ -8742,7 +8742,7 @@ normal_stop (void)
      the observers would print a stop for the wrong
      thread/inferior.  */
   if (saved_context.changed ())
-    return 1;
+    return true;
 
   /* Notify observers about the stop.  This is where the interpreters
      print the stop event.  */
@@ -8764,7 +8764,7 @@ normal_stop (void)
 	breakpoint_auto_delete (inferior_thread ()->control.stop_bpstat);
     }
 
-  return 0;
+  return false;
 }
 \f
 int
diff --git a/gdb/infrun.h b/gdb/infrun.h
index 19e68155ec4..43fd1b44f5a 100644
--- a/gdb/infrun.h
+++ b/gdb/infrun.h
@@ -149,7 +149,7 @@ extern process_stratum_target *user_visible_resume_target (ptid_t resume_ptid);
    appropriate messages, remove breakpoints, give terminal our modes,
    and run the stop hook.  Returns true if the stop hook proceeded the
    target, false otherwise.  */
-extern int normal_stop (void);
+extern bool normal_stop ();
 
 /* Return the cached copy of the last target/ptid/waitstatus returned
    by target_wait().  The data is actually cached by handle_inferior_event(),


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

* Re: [PATCH 02/12] gdb/infrun: add debug print in print_signal_received_reason
  2022-10-21  8:43 ` [PATCH 02/12] gdb/infrun: add debug print in print_signal_received_reason Andrew Burgess
@ 2023-01-13 16:38   ` Andrew Burgess
  0 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-01-13 16:38 UTC (permalink / raw)
  To: gdb-patches

Andrew Burgess <aburgess@redhat.com> writes:

> It would have helped me to see an infrun debug line being printed from
> print_signal_received_reason, so I'm adding one.

I've gone ahead and pushed this patch, it's only adding a single debug
line so I don't think anyone will complain.

Thanks,
Andrew


> ---
>  gdb/infrun.c | 2 ++
>  1 file changed, 2 insertions(+)
>
> diff --git a/gdb/infrun.c b/gdb/infrun.c
> index 39840ef32c8..c28bf28a4d9 100644
> --- a/gdb/infrun.c
> +++ b/gdb/infrun.c
> @@ -8393,6 +8393,8 @@ print_signal_received_reason (struct ui_out *uiout, enum gdb_signal siggnal)
>  {
>    struct thread_info *thr = inferior_thread ();
>  
> +  infrun_debug_printf ("signal = %s", gdb_signal_to_string (siggnal));
> +
>    annotate_signal ();
>  
>    if (uiout->is_mi_like_p ())
> -- 
> 2.25.4


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

* Re: [PATCH 04/12] gdbserver: add comments to read_inferior_memory function
  2022-10-21  8:43 ` [PATCH 04/12] gdbserver: add comments to read_inferior_memory function Andrew Burgess
@ 2023-01-13 16:42   ` Andrew Burgess
  0 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-01-13 16:42 UTC (permalink / raw)
  To: gdb-patches

Andrew Burgess <aburgess@redhat.com> writes:

> Just adding some comments to the gdbserver read_inferior_memory
> function.  No actual code changes.

I've gone ahead and pushed this.  I'm reasonably sure the comments I've
added are correct, I'm happy to update them if anyone disagrees.

Thanks,
Andrew


> ---
>  gdbserver/target.cc     | 2 ++
>  gdbserver/target.h      | 3 +++
>  gdbserver/tracepoint.cc | 2 ++
>  3 files changed, 7 insertions(+)
>
> diff --git a/gdbserver/target.cc b/gdbserver/target.cc
> index adcfe6e7bcc..6b29c99a61b 100644
> --- a/gdbserver/target.cc
> +++ b/gdbserver/target.cc
> @@ -79,6 +79,8 @@ set_desired_process ()
>    return proc != nullptr;
>  }
>  
> +/* See target.h.  */
> +
>  int
>  read_inferior_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
>  {
> diff --git a/gdbserver/target.h b/gdbserver/target.h
> index 6c536a30778..a49d7d4bac0 100644
> --- a/gdbserver/target.h
> +++ b/gdbserver/target.h
> @@ -697,6 +697,9 @@ target_thread_pending_child (thread_info *thread)
>    return the_target->thread_pending_child (thread);
>  }
>  
> +/* Read LEN bytes from MEMADDR in the buffer MYADDR.  Return 0 if the read
> +   is successful, otherwise, return a non-zero error code.  */
> +
>  int read_inferior_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len);
>  
>  /* Set GDBserver's current thread to the thread the client requested
> diff --git a/gdbserver/tracepoint.cc b/gdbserver/tracepoint.cc
> index 18b2b0b3d77..efcdfe12beb 100644
> --- a/gdbserver/tracepoint.cc
> +++ b/gdbserver/tracepoint.cc
> @@ -344,6 +344,8 @@ tracepoint_look_up_symbols (void)
>     GDBserver side.  */
>  
>  #ifdef IN_PROCESS_AGENT
> +/* See target.h.  */
> +
>  int
>  read_inferior_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
>  {
> -- 
> 2.25.4


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

* Re: [PATCH 11/12] gdb: add timeouts for inferior function calls
  2022-11-04 23:17   ` Lancelot SIX
@ 2023-01-13 16:49     ` Andrew Burgess
  2023-01-16  9:44       ` Lancelot SIX
  0 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2023-01-13 16:49 UTC (permalink / raw)
  To: Lancelot SIX; +Cc: gdb-patches

Lancelot SIX <lsix@lancelotsix.com> writes:

> Hi,
>
>> In this commit I propose a solution to this problem.  A timeout.  For
>> targets that support async-mode we can install an event-loop timer
>> before starting the inferior function call.  When the timer expires we
>> will stop the thread performing the inferior function call.  With this
>> mechanism in place a user can be sure that any inferior call they make
>> will either complete, or timeout eventually.
>> 
>> Adding a timer like this is obviously a change in behaviour for the
>> more common 'call' and 'print' uses of inferior function calls, so, in
>> this patch, I propose having two different timers.  One I call the
>> 'direct-call-timeout', which is used for 'call' and 'print' commands.
>> This timeout is by default set to unlimited, which, not surprisingly,
>> means there is no timeout in place.
>> 
>> A second timer, which I've called 'indirect-call-timeout', is used for
>> inferior function calls from breakpoint conditions.  This timeout has
>> a default value of 300 seconds.  This is still a pretty substantial
>> time to be waiting for a single inferior call to complete, but I
>> didn't want to be too aggressive with the value I selected.  A user
>> can, of course, still use Ctrl-c to interrupt an inferior function
>> call, but this limit will ensure that GDB will stop at some point.
>> 
>
> I do see the use of the indirect call timeouts, and I find it a good
> solution for the problem you are trying to solve. I am however not sure
> I see much usecase for the direct one.  It looks to me that using Ctrl-C
> serves this purpose well already.  Do you have a use case in mind where
> this can come in handy?  Scripting and automation maybe?
>
> It seems to me that only having the setting for the indirect call
> timeout would make the interface simpler.
>
> That being said, once you have implemented the mechanism for the
> "indirect" calls, "direct" call timeout implementation comes for free.
> I guess this was your reasoning.

That was indeed why I provided both - it pretty much came for free.
Like you say, it might offer some benefits in a GDB scripting setup.

If you feel really strongly then I can drop it, but I don't feel it adds
much additional maintenance overhead.

Thanks,
Andrew


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

* Re: [PATCH 11/12] gdb: add timeouts for inferior function calls
  2022-10-21 11:08   ` Eli Zaretskii
@ 2023-01-14 11:00     ` Andrew Burgess
  2023-01-14 11:48       ` Eli Zaretskii
  0 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2023-01-14 11:00 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: gdb-patches


Eli,

Thanks for all your feedback, sorry it has taken me so long to get back
to this series.  I'm working through most of your points, but I there
was one issue that I wanted to follow up on, see inline below.

Eli Zaretskii <eliz@gnu.org> writes:

>> Date: Fri, 21 Oct 2022 09:43:47 +0100
>> From: Andrew Burgess via Gdb-patches <gdb-patches@sourceware.org>
>> 
>> --- a/gdb/NEWS
>> +++ b/gdb/NEWS
>> @@ -115,6 +115,22 @@ set debug infcall on|off
>>  show debug infcall
>>    Print additional debug messages about inferior function calls.
>>  
>> +set direct-call-timeout SECONDS
>> +show direct-call-timeout
>> +set indirect-call-timeout SECONDS
>> +show indirect-call-timeout
>> +  These new settings can be used to limit how long GDB will wait for
>> +  an inferior function call to complete.  The direct timeout is used
>> +  for inferior function calls from e.g. 'call' and 'print' commands,
>> +  while the indirect timeout is used for inferior function calls from
>> +  within a conditional breakpoint expression.
>> +
>> +  The default for the direct timeout is unlimited, while the default
>> +  for the indirect timeout is 300 seconds.
>
> IMO, 300 seconds is way too long a wait for a breakpoint condition.
> It should be a matter of a few seconds at most, IMO.
>
>> +  These timeouts will only have an effect for targets that are
>> +  operating in async mode.
>
> This should tell what happens on targets that don't support async
> mode.
>
>> +When calling a function within a program, it is possible that the
>> +program could enter a state from which the called function may never
>> +return.  If this happens then @value{GDBN} will appear to hang.
>> +Should this happen then it is possible to interrupt the running
>> +program by typing the interrupt character (often @kbd{Ctrl-c}).
>> +
>> +On some targets @value{GDBN} can also place a timeout on any function
>> +calls made into the program.
>
> Instead of "some targets", which leaves those targets unspecified, we
> should say "targets that support async mode", with a cross-reference
> to where that is described.  We should give the user a means to
> determine whether the particular target does or doesn't need/support
> this timeout feature.
>
>>                              If the timeout expires and the function
>> +call is still going, then @value{GDBN} will interrupt the program
>> +automatically.
>
> And what does this mean for the value returned by the interrupted
> call?  This is important for the breakpoint condition use case, for
> example.
>
>> +
>> +@table @code
>> +@item set direct-call-timeout @var{seconds}
>> +@kindex set direct-call-timeout
>> +@cindex timeout for called functions
>> +Set the timeout used when calling functions in the program to
>> +@var{seconds}, which should be an integer greater than zero, or the
>> +special value @code{unlimited}, which indicates no timeout should be
>> +used.  The default for this setting is @code{unlimited}.
>
> Why integer in seconds? don't we want to be able to support shorter
> timeouts, like 100 msec?  Most inferior calls should take much less
> than a second, so a second resolution is not the best idea, IMO.  It
> could, for example, make running a program with such a breakpoint
> unbearably slow.

Remember, this timeout is a safety net intended to catch situations
where either due to a bug in the inferior, or due to user error, the
breakpoint condition is never going to complete.

As such I don't think we should be trying to trim this value down as low
as possible, I just don't see any additional value, in fact, I see doing
so adding more risk that the user will hit invalid timeouts.

If you wanted to be super aggressive with the timeout, and you set it to
1 second, but you still expect your inferior calls to complete in
100msec, then the timeout being 1 second will not slow you down in any
way.  But, if for some reason your inferior call deadlocks, you'll end
up waiting that complete second before GDB gives up.

I can't imagine a use case where a user will be debugging by having an
inferior function call repeatedly timeout, and that's the only way that
having such a large timeout would be unbearable

That all said, the underlying timer mechanism does use msec, so if you
feel strongly that we should be able to have sub-second timeouts, then
it's trivial to switch over, though I do think that the default should
be multiple seconds (I've reduced the default to 30 seconds based on
your other feedback), as I'd like GDB's default behaviour to allow for
debugging slower, remote targets, where that timeout has to allow for
packets sent to the remote target, and slower remote targets.

Thanks,
Andrew

>
>> +This setting only works for targets that support asynchronous
>> +execution (@pxref{Background Execution}), for any other target the
>> +setting is treated as @code{unlimited}.
>
> This should be moved to the beginning of the description, as mentioned
> above.  In addition, saying "treated as 'unlimited'" is not clear
> enough in this context, because actually no timeout is applicable at
> all, and GDB will wait indefinitely for the call to return.  We should
> tell this explicitly.
>
>> +It is also possible to call functions within the program from the
>> +condition of a conditional breakpoint (@pxref{Conditions, ,Break
>> +Conditions}).  A different setting controls the timeout used for
>> +functions made from a breakpoint condition.
>    ^^^^^^^^^^^^^^
> "function calls made..."
>
>> +@item set indirect-call-timeout @var{seconds}
>> +@kindex set indirect-call-timeout
>> +@cindex timeout for called functions
>> +Set the timeout used when calling functions in the program from a
>> +breakpoint condition to @var{seconds}, which should be an integer
>> +greater than zero, or the special value @code{unlimited}, which
>> +indicates no timeout should be used.  The default for this setting is
>> +@code{300} seconds.
>
> Here 300 seconds is definitely too long.
>
>> +  add_setshow_uinteger_cmd ("direct-call-timeout", no_class,
>> +			    &direct_call_timeout, _("\
>> +Set the timeout, for direct calls to inferior function calls."), _("\
>> +Show the timeout, for direct calls to inferior function calls."), _("\
>> +If running on a target that supports, and is running in, async mode\n\
>> +then this timeout is used for any inferior function calls triggered\n\
>> +directly from the prompt, e.g. from a 'call' or 'print' command.  The\n\
>> +timeout is specified in seconds."),
>> +			    nullptr,
>> +			    show_direct_call_timeout,
>> +			    &setlist, &showlist);
>> +
>> +  add_setshow_uinteger_cmd ("indirect-call-timeout", no_class,
>> +			    &indirect_call_timeout, _("\
>> +Set the timeout, for indirect calls to inferior function calls."), _("\
>> +Show the timeout, for indirect calls to inferior function calls."), _("\
>> +If running on a target that supports, and is running in, async mode\n\
>> +then this timeout is used for any inferior function calls triggered\n\
>> +indirectly, e.g. when evaluating a conditional breakpoint expression.\n\
>> +The timeout is specified in seconds."),
>
> These doc strings explain what is a "direct" vs "indirect" call by way
> of "e.g.".  But that leaves the issue not well-defined, because it
> begs the question: what are the other cases that are considered
> "direct" or "indirect"?


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

* Re: [PATCH 11/12] gdb: add timeouts for inferior function calls
  2023-01-14 11:00     ` Andrew Burgess
@ 2023-01-14 11:48       ` Eli Zaretskii
  2023-01-16 17:22         ` Andrew Burgess
  0 siblings, 1 reply; 202+ messages in thread
From: Eli Zaretskii @ 2023-01-14 11:48 UTC (permalink / raw)
  To: Andrew Burgess; +Cc: gdb-patches

> From: Andrew Burgess <aburgess@redhat.com>
> Cc: gdb-patches@sourceware.org
> Date: Sat, 14 Jan 2023 11:00:32 +0000
> 
> >> +@table @code
> >> +@item set direct-call-timeout @var{seconds}
> >> +@kindex set direct-call-timeout
> >> +@cindex timeout for called functions
> >> +Set the timeout used when calling functions in the program to
> >> +@var{seconds}, which should be an integer greater than zero, or the
> >> +special value @code{unlimited}, which indicates no timeout should be
> >> +used.  The default for this setting is @code{unlimited}.
> >
> > Why integer in seconds? don't we want to be able to support shorter
> > timeouts, like 100 msec?  Most inferior calls should take much less
> > than a second, so a second resolution is not the best idea, IMO.  It
> > could, for example, make running a program with such a breakpoint
> > unbearably slow.
> 
> Remember, this timeout is a safety net intended to catch situations
> where either due to a bug in the inferior, or due to user error, the
> breakpoint condition is never going to complete.
> 
> As such I don't think we should be trying to trim this value down as low
> as possible, I just don't see any additional value, in fact, I see doing
> so adding more risk that the user will hit invalid timeouts.
> 
> If you wanted to be super aggressive with the timeout, and you set it to
> 1 second, but you still expect your inferior calls to complete in
> 100msec, then the timeout being 1 second will not slow you down in any
> way.  But, if for some reason your inferior call deadlocks, you'll end
> up waiting that complete second before GDB gives up.
> 
> I can't imagine a use case where a user will be debugging by having an
> inferior function call repeatedly timeout, and that's the only way that
> having such a large timeout would be unbearable

Suppose we have an inferior call as part of the breakpoint command
conditions, and suppose that breakpoint is hit very frequently.  What
do we want to happen in this case?  Do we want:

  . GDB to silently keep calling the inferior and waiting for it to time out?
  . GDB to announce the timeout and stop the first time it happens?
  . something else?

I thought we wanted the 1st alternative, in which case waiting for a
second could make the run very slow, since an inferior call should
take, like, microseconds in almost all cases?

But if we intend GDB to stop and not continue in this case, then yes,
1 sec could be appropriate.

Or maybe I'm missing something regarding how this feature is supposed
to be used?

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

* Re: [PATCH 11/12] gdb: add timeouts for inferior function calls
  2023-01-13 16:49     ` Andrew Burgess
@ 2023-01-16  9:44       ` Lancelot SIX
  0 siblings, 0 replies; 202+ messages in thread
From: Lancelot SIX @ 2023-01-16  9:44 UTC (permalink / raw)
  To: Andrew Burgess; +Cc: gdb-patches

Hi,

> > It seems to me that only having the setting for the indirect call
> > timeout would make the interface simpler.
> >
> > That being said, once you have implemented the mechanism for the
> > "indirect" calls, "direct" call timeout implementation comes for free.
> > I guess this was your reasoning.
> 
> That was indeed why I provided both - it pretty much came for free.
> Like you say, it might offer some benefits in a GDB scripting setup.
> 
> If you feel really strongly then I can drop it, but I don't feel it adds
> much additional maintenance overhead.

That's OK with me, as you say the extra maintenance overhead is close to
none.

Best,
Lancelot.

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

* Re: [PATCH 11/12] gdb: add timeouts for inferior function calls
  2023-01-14 11:48       ` Eli Zaretskii
@ 2023-01-16 17:22         ` Andrew Burgess
  2023-01-16 17:27           ` Eli Zaretskii
  0 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2023-01-16 17:22 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: gdb-patches

Eli Zaretskii <eliz@gnu.org> writes:

>> From: Andrew Burgess <aburgess@redhat.com>
>> Cc: gdb-patches@sourceware.org
>> Date: Sat, 14 Jan 2023 11:00:32 +0000
>> 
>> >> +@table @code
>> >> +@item set direct-call-timeout @var{seconds}
>> >> +@kindex set direct-call-timeout
>> >> +@cindex timeout for called functions
>> >> +Set the timeout used when calling functions in the program to
>> >> +@var{seconds}, which should be an integer greater than zero, or the
>> >> +special value @code{unlimited}, which indicates no timeout should be
>> >> +used.  The default for this setting is @code{unlimited}.
>> >
>> > Why integer in seconds? don't we want to be able to support shorter
>> > timeouts, like 100 msec?  Most inferior calls should take much less
>> > than a second, so a second resolution is not the best idea, IMO.  It
>> > could, for example, make running a program with such a breakpoint
>> > unbearably slow.
>> 
>> Remember, this timeout is a safety net intended to catch situations
>> where either due to a bug in the inferior, or due to user error, the
>> breakpoint condition is never going to complete.
>> 
>> As such I don't think we should be trying to trim this value down as low
>> as possible, I just don't see any additional value, in fact, I see doing
>> so adding more risk that the user will hit invalid timeouts.
>> 
>> If you wanted to be super aggressive with the timeout, and you set it to
>> 1 second, but you still expect your inferior calls to complete in
>> 100msec, then the timeout being 1 second will not slow you down in any
>> way.  But, if for some reason your inferior call deadlocks, you'll end
>> up waiting that complete second before GDB gives up.
>> 
>> I can't imagine a use case where a user will be debugging by having an
>> inferior function call repeatedly timeout, and that's the only way that
>> having such a large timeout would be unbearable
>
> Suppose we have an inferior call as part of the breakpoint command
> conditions, and suppose that breakpoint is hit very frequently.  What
> do we want to happen in this case?  Do we want:
>
>   . GDB to silently keep calling the inferior and waiting for it to time out?
>   . GDB to announce the timeout and stop the first time it happens?
>   . something else?
>
> I thought we wanted the 1st alternative, in which case waiting for a
> second could make the run very slow, since an inferior call should
> take, like, microseconds in almost all cases?
>
> But if we intend GDB to stop and not continue in this case, then yes,
> 1 sec could be appropriate.

I guess my attempt at documenting this is not great :/

We are getting option #2, GDB will stop and report the timeout, here's
how it will look to the user:

  (gdb) set indirect-call-timeout 1
  (gdb) break breakpt()  if (deadlock() == 0)
  Breakpoint 1 at 0x401169: file test.cc, line 35.
  (gdb) r
  Starting program: /tmp/inf-call-timeout/test 
  
  Program stopped.
  0x00007ffff7b3d1e7 in nanosleep () from /lib64/libc.so.6
  Error in testing condition for breakpoint 1:
  timeout waiting for inferior function to complete
  An error occurred while in a function called from GDB.
  Evaluation of the expression containing the function
  (deadlock()) will be abandoned.
  When the function is done executing, GDB will silently stop.
  (gdb) bt
  #0  0x00007ffff7b3d1e7 in nanosleep () from /lib64/libc.so.6
  #1  0x00007ffff7b3d11e in sleep () from /lib64/libc.so.6
  #2  0x000000000040113f in deadlock_inner () at test.cc:13
  #3  0x000000000040114e in deadlock () at test.cc:20
  #4  <function called from gdb>
  #5  breakpt () at test.cc:35
  #6  0x0000000000401175 in main () at test.cc:40
  (gdb)

Here's why I think this is the right behaviour:

If we automatically unwound the stack once the timeout was detected,
then surely the only correct choice would be for the breakpoint
condition to trigger.  We can't say for sure that the condition didn't
trigger, so we should stop.  This is similar to how if I do say:

   (gdb) break foo if (*some_null_pointer == 1234)

Then GDB will immediately stop at this breakpoint with a message saying
that it was unable to access "*some_null_pointer"; the condition caused
a stop not because the condition was true, but because GDB failed to
evaluate the condition.  I think the same logic applies to a timeout in
this case.

However, for the timeout case I've left the context of the timeout on
the stack, in my example above frames #0 to #4 are all related to the
inferior function call.

I think this is useful, if the inferior is somehow deadlocked during the
inferior function call then it might be useful that the user can
investigate the current state and try to figure out what's gone wrong.

Hopefully this explains why I think a minimum 1 second timeout is
acceptable, I wonder, with the explanation above, how you feel about
this now?

I'll take another pass at the documentation, and try to make it clearer,
obviously I didn't do a good job of explaining what I'm trying to do.

Thanks,
Andrew


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

* Re: [PATCH 11/12] gdb: add timeouts for inferior function calls
  2023-01-16 17:22         ` Andrew Burgess
@ 2023-01-16 17:27           ` Eli Zaretskii
  0 siblings, 0 replies; 202+ messages in thread
From: Eli Zaretskii @ 2023-01-16 17:27 UTC (permalink / raw)
  To: Andrew Burgess; +Cc: gdb-patches

> From: Andrew Burgess <aburgess@redhat.com>
> Cc: gdb-patches@sourceware.org
> Date: Mon, 16 Jan 2023 17:22:04 +0000
> 
> Hopefully this explains why I think a minimum 1 second timeout is
> acceptable, I wonder, with the explanation above, how you feel about
> this now?

If GDB is going to stop on the first timeout, then I'm okay with the
rest, we just need to make it clear in the manual.

Thanks.

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

* [PATCHv2 00/13] Infcalls from B/P conditions in multi-threaded inferiors
  2022-10-21  8:43 [PATCH 00/12] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                   ` (11 preceding siblings ...)
  2022-10-21  8:43 ` [PATCH 12/12] gdb/remote: avoid SIGINT after calling remote_target::stop Andrew Burgess
@ 2023-01-18 16:17 ` Andrew Burgess
  2023-01-18 16:17   ` [PATCHv2 01/13] gdb/doc: extended documentation for inferior function calls Andrew Burgess
                     ` (14 more replies)
  12 siblings, 15 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-01-18 16:17 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Thanks for the feedback on V1.  I merged a couple of the really minor
patches from the V1 series, but after the feedback I'm some new
patches in the v2 series.

In V2:

  - Rebased onto something closer to HEAD of master,

  - Patches #1, #2, #12, and #13 are new in this series,
  
  - Patches #3 to #9, and #11 are unchanged since their V1 iteration,
  
  - Patches #10 has changed slightly in implementation since v1, and
    the docs have been significantly updated.

---

Andrew Burgess (13):
  gdb/doc: extended documentation for inferior function calls
  gdb/doc: extend the documentation for conditional breakpoints
  gdb: include breakpoint number in testing condition error message
  gdbserver: allows agent_mem_read to return an error code
  gdbserver: allow agent expressions to fail with invalid memory access
  gdb: avoid repeated signal reporting during failed conditional
    breakpoint
  gdb: don't always print breakpoint location after failed condition
    check
  Revert "gdb: remove unnecessary parameter wait_ptid from
    do_target_wait"
  gdb: fix b/p conditions with infcalls in multi-threaded inferiors
  gdb: add timeouts for inferior function calls
  gdb/remote: avoid SIGINT after calling remote_target::stop
  gdb: introduce unwind-on-timeout setting
  gdb: rename unwindonsignal to unwind-on-signal

 gdb/NEWS                                      |  38 +++
 gdb/breakpoint.c                              |  17 +-
 gdb/doc/gdb.texinfo                           | 136 +++++++-
 gdb/gdbthread.h                               |   3 +
 gdb/infcall.c                                 | 294 +++++++++++++++++-
 gdb/infrun.c                                  |  52 +++-
 gdb/infrun.h                                  |   2 +-
 gdb/remote.c                                  |  17 +
 gdb/testsuite/gdb.base/bp-cond-failure.c      |  30 ++
 gdb/testsuite/gdb.base/bp-cond-failure.exp    |  81 +++++
 gdb/testsuite/gdb.base/callfuncs.exp          |   4 +-
 .../gdb.base/catch-signal-siginfo-cond.exp    |   2 +-
 gdb/testsuite/gdb.base/gnu-ifunc.exp          |   2 +-
 gdb/testsuite/gdb.base/help.exp               |   2 +-
 gdb/testsuite/gdb.base/infcall-failure.c      |  48 +++
 gdb/testsuite/gdb.base/infcall-failure.exp    | 182 +++++++++++
 gdb/testsuite/gdb.base/infcall-timeout.c      |  36 +++
 gdb/testsuite/gdb.base/infcall-timeout.exp    |  98 ++++++
 gdb/testsuite/gdb.base/unwindonsignal.exp     |  36 ++-
 gdb/testsuite/gdb.compile/compile-cplus.exp   |   2 +-
 gdb/testsuite/gdb.compile/compile.exp         |   2 +-
 gdb/testsuite/gdb.cp/gdb2495.exp              |  16 +-
 gdb/testsuite/gdb.fortran/function-calls.exp  |   2 +-
 gdb/testsuite/gdb.mi/mi-syn-frame.exp         |   2 +-
 .../gdb.python/py-finish-breakpoint.exp       |   2 +-
 .../infcall-from-bp-cond-other-thread-event.c | 135 ++++++++
 ...nfcall-from-bp-cond-other-thread-event.exp | 175 +++++++++++
 .../gdb.threads/infcall-from-bp-cond-simple.c |  89 ++++++
 .../infcall-from-bp-cond-simple.exp           | 236 ++++++++++++++
 .../gdb.threads/infcall-from-bp-cond-single.c | 139 +++++++++
 .../infcall-from-bp-cond-single.exp           | 119 +++++++
 .../infcall-from-bp-cond-timeout.c            | 169 ++++++++++
 .../infcall-from-bp-cond-timeout.exp          | 174 +++++++++++
 .../gdb.threads/thread-unwindonsignal.exp     |   8 +-
 gdb/testsuite/lib/gdb.exp                     |   8 +
 gdbserver/ax.cc                               |  12 +-
 gdbserver/ax.h                                |   3 +-
 gdbserver/tracepoint.cc                       |  11 +-
 gdbserver/tracepoint.h                        |   9 +-
 39 files changed, 2317 insertions(+), 76 deletions(-)
 create mode 100644 gdb/testsuite/gdb.base/bp-cond-failure.c
 create mode 100644 gdb/testsuite/gdb.base/bp-cond-failure.exp
 create mode 100644 gdb/testsuite/gdb.base/infcall-failure.c
 create mode 100644 gdb/testsuite/gdb.base/infcall-failure.exp
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.c
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp


base-commit: ac37b79cc440e37fc704d425a6e450afb3c7ee89
-- 
2.25.4


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

* [PATCHv2 01/13] gdb/doc: extended documentation for inferior function calls
  2023-01-18 16:17 ` [PATCHv2 00/13] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
@ 2023-01-18 16:17   ` Andrew Burgess
  2023-01-18 17:20     ` Eli Zaretskii
  2023-01-19  9:00     ` Aktemur, Tankut Baris
  2023-01-18 16:17   ` [PATCHv2 02/13] gdb/doc: extend the documentation for conditional breakpoints Andrew Burgess
                     ` (13 subsequent siblings)
  14 siblings, 2 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-01-18 16:17 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

I noticed that the documentation for inferior function calls doesn't
say much about what happens if/when an inferior function call is
interrupted, i.e. it doesn't describe what the dummy frame looks like
on the stack, or how GDB behaves when the inferior is continued and
reaches the dummy frame.

This commit aims to add some of this missing information.
---
 gdb/doc/gdb.texinfo | 30 ++++++++++++++++++++++++++++++
 1 file changed, 30 insertions(+)

diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index 9c0018ea5c1..e05813ff502 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -20731,6 +20731,36 @@
 
 @end table
 
+When calling a function within a program, it is possible that the
+program could enter a state from which the called function may never
+return.  If this happens then it is possible to interrupt the function
+call by typing the interrupt character (often @kbd{Ctrl-c}).
+
+If a called function is interrupted for any reason, and the stack is
+not unwound (due to @code{set unwind-on-terminating-exception on} or
+@code{set unwindonsignal on}), then the dummy-frame, created by
+@value{GDBN} to facilitate the call to the program function, will be
+visible in the backtrace, for example frame @code{#3} in the following
+backtrace:
+
+@smallexample
+(@value{GDBP}) backtrace
+#0  0x00007ffff7b3d1e7 in nanosleep () from /lib64/libc.so.6
+#1  0x00007ffff7b3d11e in sleep () from /lib64/libc.so.6
+#2  0x000000000040113f in deadlock () at test.cc:13
+#3  <function called from gdb>
+#4  breakpt () at test.cc:20
+#5  0x0000000000401151 in main () at test.cc:25
+@end smallexample
+
+At this point it is possible to examine the state of the inferior just
+like any other stop.
+
+Depending on why the function was interrupted then it may be possible
+to resume the inferior (using commands like @code{continue},
+@code{step}, etc).  In this case, when the inferior finally returns to
+the dummy-frame, @value{GDBN} will once again halt the inferior.
+
 @subsection Calling functions with no debug info
 
 @cindex no debug info functions
-- 
2.25.4


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

* [PATCHv2 02/13] gdb/doc: extend the documentation for conditional breakpoints
  2023-01-18 16:17 ` [PATCHv2 00/13] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
  2023-01-18 16:17   ` [PATCHv2 01/13] gdb/doc: extended documentation for inferior function calls Andrew Burgess
@ 2023-01-18 16:17   ` Andrew Burgess
  2023-01-18 17:22     ` Eli Zaretskii
  2023-01-19  9:04     ` Aktemur, Tankut Baris
  2023-01-18 16:17   ` [PATCHv2 03/13] gdb: include breakpoint number in testing condition error message Andrew Burgess
                     ` (12 subsequent siblings)
  14 siblings, 2 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-01-18 16:17 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

This documentation update adds more text to describe what happens if a
conditional breakpoint calls an inferior function, and the inferior
function is interrupted for some reason.
---
 gdb/doc/gdb.texinfo | 11 +++++++++++
 1 file changed, 11 insertions(+)

diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index e05813ff502..6ea173b5d0b 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -5713,6 +5713,17 @@
 purpose of performing side effects when a breakpoint is reached
 (@pxref{Break Commands, ,Breakpoint Command Lists}).
 
+If a breakpoint condition calls a function in your program, then it is
+possible that your program could stop for some reason while in the
+called function.  For example, @value{GDBN} might hit a breakpoint in
+the called function, or the called function may receive a signal
+(e.g.@ a @code{SIGSEGV}) as a result of some undefined behaviour, if
+this happens then @value{GDBN} will stop.  Depending on the settings
+@code{unwindonsignal} and @code{unwind-on-terminating-exception}
+(@pxref{Calling,,Calling Program Functions}) @value{GDBN} may unwind
+the stack back to the breakpoint location, or may leave the program at
+the frame where the stop occurred.
+
 Breakpoint conditions can also be evaluated on the target's side if
 the target supports it.  Instead of evaluating the conditions locally,
 @value{GDBN} encodes the expression into an agent expression
-- 
2.25.4


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

* [PATCHv2 03/13] gdb: include breakpoint number in testing condition error message
  2023-01-18 16:17 ` [PATCHv2 00/13] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
  2023-01-18 16:17   ` [PATCHv2 01/13] gdb/doc: extended documentation for inferior function calls Andrew Burgess
  2023-01-18 16:17   ` [PATCHv2 02/13] gdb/doc: extend the documentation for conditional breakpoints Andrew Burgess
@ 2023-01-18 16:17   ` Andrew Burgess
  2023-01-19  9:54     ` Aktemur, Tankut Baris
  2023-01-19 10:54     ` Aktemur, Tankut Baris
  2023-01-18 16:18   ` [PATCHv2 04/13] gdbserver: allows agent_mem_read to return an error code Andrew Burgess
                     ` (11 subsequent siblings)
  14 siblings, 2 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-01-18 16:17 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

When GDB fails to test the condition of a conditional breakpoint, for
whatever reason, the error message looks like this:

  (gdb) break foo if (*(int *) 0) == 1
  Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
  (gdb) r
  Starting program: /tmp/bpcond
  Error in testing breakpoint condition:
  Cannot access memory at address 0x0

  Breakpoint 1, foo () at bpcond.c:11
  11	  int a = 32;
  (gdb)

The line I'm interested in for this commit is this one:

  Error in testing breakpoint condition:

In the case above we can figure out that the problematic breakpoint
was #1 because in the final line of the message GDB reports the stop a
breakpoint #1.

However, in the next few patches I plan to change this.  In some cases
I don't think it makes sense for GDB to report the stop as being at
breakpoint #1, consider this case:

  (gdb) list some_func
  1	int
  2	some_func ()
  3	{
  4	  int *p = 0;
  5	  return *p;
  6	}
  7
  8	void
  9	foo ()
  10	{
  (gdb) break foo if (some_func ())
  Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
  (gdb) r
  Starting program: /tmp/bpcond

  Program received signal SIGSEGV, Segmentation fault.
  0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  Error in testing breakpoint condition:
  The program being debugged was signaled while in a function called from GDB.
  GDB remains in the frame where the signal was received.
  To change this behavior use "set unwindonsignal on".
  Evaluation of the expression containing the function
  (some_func) will be abandoned.
  When the function is done executing, GDB will silently stop.

  Program received signal SIGSEGV, Segmentation fault.

  Breakpoint 1, 0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  (gdb)

Notice that, the final lines of output report the stop as being at
breakpoint #1, even though we are actually located within some_func.

I find this behaviour confusing, and propose that this should be
changed.  However, if I make that change then every reference to
breakpoint #1 will be lost from the error message.

So, in this commit, in preparation for the later commits, I propose to
change the 'Error in testing breakpoint condition:' line to this:

  Error in testing condition for breakpoint NUMBER:

where NUMBER will be filled in as appropriate.  Here's the first
example with the updated error:

  (gdb) break foo if (*(int *) 0) == 0
  Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
  (gdb) r
  Starting program: /tmp/bpcond
  Error in testing condition for breakpoint 1:
  Cannot access memory at address 0x0

  Breakpoint 1, foo () at bpcond.c:11
  11	  int a = 32;
  (gdb)

The breakpoint number does now appear twice in the output, but I don't
see that as a negative.

This commit just changes the one line of the error, and updates the
few tests that either included the old error in comments, or actually
checked for the error in the expected output.

As the only test that checked the line I modified is a Python test,
I've added a new test that doesn't rely on Python that checks the
error message in detail.

While working on the new test, I spotted that it would fail when run
with native-gdbserver and native-extended-gdbserver target boards.
This turns out to be due to a gdbserver bug.  To avoid cluttering this
commit I've added a work around to the new test script so that the
test passes for the remote boards, in the next few commits I will fix
gdbserver, and update the test script to remove the work around.
---
 gdb/breakpoint.c                              |  3 +-
 gdb/testsuite/gdb.base/bp-cond-failure.c      | 30 +++++++
 gdb/testsuite/gdb.base/bp-cond-failure.exp    | 83 +++++++++++++++++++
 .../gdb.base/catch-signal-siginfo-cond.exp    |  2 +-
 gdb/testsuite/gdb.base/gnu-ifunc.exp          |  2 +-
 .../gdb.python/py-finish-breakpoint.exp       |  2 +-
 gdb/testsuite/lib/gdb.exp                     |  8 ++
 7 files changed, 126 insertions(+), 4 deletions(-)
 create mode 100644 gdb/testsuite/gdb.base/bp-cond-failure.c
 create mode 100644 gdb/testsuite/gdb.base/bp-cond-failure.exp

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 00cc2ab401c..eecaeefed3e 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -5542,7 +5542,8 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
 	  catch (const gdb_exception &ex)
 	    {
 	      exception_fprintf (gdb_stderr, ex,
-				 "Error in testing breakpoint condition:\n");
+				 "Error in testing condition for breakpoint %d:\n",
+				 b->number);
 	    }
 	}
       else
diff --git a/gdb/testsuite/gdb.base/bp-cond-failure.c b/gdb/testsuite/gdb.base/bp-cond-failure.c
new file mode 100644
index 00000000000..be9d1fdcf2d
--- /dev/null
+++ b/gdb/testsuite/gdb.base/bp-cond-failure.c
@@ -0,0 +1,30 @@
+/* Copyright 2022 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/>.  */
+
+int
+foo ()
+{
+  return 0;	/* Breakpoint here.  */
+}
+
+int
+main ()
+{
+  int res = foo ();
+
+  return res;
+}
diff --git a/gdb/testsuite/gdb.base/bp-cond-failure.exp b/gdb/testsuite/gdb.base/bp-cond-failure.exp
new file mode 100644
index 00000000000..6f89771d187
--- /dev/null
+++ b/gdb/testsuite/gdb.base/bp-cond-failure.exp
@@ -0,0 +1,83 @@
+# Copyright 2022 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/>.
+
+# Check the format of the error message given when a breakpoint
+# condition fails.
+#
+# In this case the breakpoint condition does not make use of inferior
+# function calls, instead, the expression used for the breakpoint
+# condition will throw an error when evaluated.
+#
+# We check that the correct breakpoint number appears in the error
+# message, and that the error is reported at the correct source
+# location.
+
+standard_testfile
+
+if { [prepare_for_testing "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug}] == -1 } {
+    return
+}
+
+# This test relies on reading address zero triggering a SIGSEGV.
+if { [is_address_zero_readable] } {
+    return
+}
+
+# Where the breakpoint will be placed.
+set bp_line [gdb_get_line_number "Breakpoint here"]
+
+proc run_test { cond_eval } {
+    clean_restart ${::binfile}
+
+    if {![runto_main]} {
+	fail "run to main"
+	return -1
+    }
+
+    if { $cond_eval != "auto" } {
+	gdb_test_no_output "set breakpoint condition-evaluation ${cond_eval}"
+    }
+
+    # Setup the conditional breakpoint and record its number.
+    gdb_breakpoint "${::srcfile}:${::bp_line} if (*(int *) 0) == 0"
+    set bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*"]
+
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     "Error in testing condition for breakpoint ${bp_num}:" \
+	     "Cannot access memory at address 0x0" \
+	     "" \
+	     "Breakpoint ${bp_num}, foo \\(\\) at \[^\r\n\]+:${::bp_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Breakpoint here\[^\r\n\]+"]
+}
+
+# If we're using a remote target then conditions could be evaulated
+# locally on the host, or on the remote target.  Otherwise, conditions
+# are always evaluated locally (which is what auto will select).
+#
+# NOTE: 'target' is not included here for remote targets as a
+# gdbserver bug prevents the test from passing.  This will be fixed in
+# the next commit, and this test updated.
+if { [gdb_is_remote_or_extended_remote_target] } {
+    set cond_eval_modes { "host" }
+} else {
+    set cond_eval_modes { "auto" }
+}
+
+foreach_with_prefix cond_eval $cond_eval_modes {
+    run_test $cond_eval
+}
diff --git a/gdb/testsuite/gdb.base/catch-signal-siginfo-cond.exp b/gdb/testsuite/gdb.base/catch-signal-siginfo-cond.exp
index 182b2f25faa..f400fc03b28 100644
--- a/gdb/testsuite/gdb.base/catch-signal-siginfo-cond.exp
+++ b/gdb/testsuite/gdb.base/catch-signal-siginfo-cond.exp
@@ -18,7 +18,7 @@
 #
 # (gdb) continue
 # Continuing.
-# Error in testing breakpoint condition:
+# Error in testing condition for breakpoint NUM:
 # Selected thread is running.
 #
 # Catchpoint 3 (signal SIGUSR1), 0x0000003615e35877 in __GI_raise (sig=10) at raise.c:56
diff --git a/gdb/testsuite/gdb.base/gnu-ifunc.exp b/gdb/testsuite/gdb.base/gnu-ifunc.exp
index 0a435806409..22462bea233 100644
--- a/gdb/testsuite/gdb.base/gnu-ifunc.exp
+++ b/gdb/testsuite/gdb.base/gnu-ifunc.exp
@@ -281,7 +281,7 @@ proc misc_tests {resolver_attr resolver_debug final_debug} {
 
     # Also test a former patch regression:
     # Continuing.
-    # Error in testing breakpoint condition:
+    # Error in testing condition for breakpoint NUM:
     # Attempt to take address of value not located in memory.
     #
     # Breakpoint 2, main () at ./gdb.base/gnu-ifunc.c:33
diff --git a/gdb/testsuite/gdb.python/py-finish-breakpoint.exp b/gdb/testsuite/gdb.python/py-finish-breakpoint.exp
index b6bd7a63c8f..e5a46874afd 100644
--- a/gdb/testsuite/gdb.python/py-finish-breakpoint.exp
+++ b/gdb/testsuite/gdb.python/py-finish-breakpoint.exp
@@ -188,7 +188,7 @@ with_test_prefix "finish in normal frame" {
     gdb_test "python TestBreakpoint()" "TestBreakpoint init" "set BP in condition"
 
     gdb_test "continue" \
-	"test don't stop: 1.*test don't stop: 2.*test stop.*Error in testing breakpoint condition.*The program being debugged stopped while in a function called from GDB.*" \
+	"test don't stop: 1.*test don't stop: 2.*test stop.*Error in testing condition for breakpoint ${::decimal}.*The program being debugged stopped while in a function called from GDB.*" \
 	"stop in condition function"
 
     gdb_test "continue" "Continuing.*" "finish condition evaluation"
diff --git a/gdb/testsuite/lib/gdb.exp b/gdb/testsuite/lib/gdb.exp
index 68337bd235c..f51332b0177 100644
--- a/gdb/testsuite/lib/gdb.exp
+++ b/gdb/testsuite/lib/gdb.exp
@@ -9332,5 +9332,13 @@ proc has_dependency { file dep } {
     return [regexp $dep $output]
 }
 
+# Return true if we are currently testing the 'remote' or
+# 'extended-remote' targets.
+proc gdb_is_remote_or_extended_remote_target {} {
+    return [target_info exists gdb_protocol]
+	   && ([target_info gdb_protocol] == "remote"
+	       || [target_info gdb_protocol] == "extended-remote")
+}
+
 # Always load compatibility stuff.
 load_lib future.exp
-- 
2.25.4


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

* [PATCHv2 04/13] gdbserver: allows agent_mem_read to return an error code
  2023-01-18 16:17 ` [PATCHv2 00/13] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                     ` (2 preceding siblings ...)
  2023-01-18 16:17   ` [PATCHv2 03/13] gdb: include breakpoint number in testing condition error message Andrew Burgess
@ 2023-01-18 16:18   ` Andrew Burgess
  2023-01-19  9:59     ` Aktemur, Tankut Baris
  2023-01-18 16:18   ` [PATCHv2 05/13] gdbserver: allow agent expressions to fail with invalid memory access Andrew Burgess
                     ` (10 subsequent siblings)
  14 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2023-01-18 16:18 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Currently the gdbserver function agent_mem_read ignores any errors
from calling read_inferior_memory.  This means that if there is an
attempt to access invalid memory then this will appear to succeed.

In this I update agent_mem_read so that if read_inferior_memory fails,
agent_mem_read will return an error code.

However, non of the callers of agent_mem_read actually check the
return value, so this commit will have no effect on anything.  In the
next commit I will update the users of agent_mem_read to check for the
error code.

I've also updated the header comments on agent_mem_read to better
reflect what the function does, and its possible return values.
---
 gdbserver/tracepoint.cc | 11 ++++-------
 gdbserver/tracepoint.h  |  9 +++++++--
 2 files changed, 11 insertions(+), 9 deletions(-)

diff --git a/gdbserver/tracepoint.cc b/gdbserver/tracepoint.cc
index 37a9a8c5b7c..60918fc0678 100644
--- a/gdbserver/tracepoint.cc
+++ b/gdbserver/tracepoint.cc
@@ -4914,8 +4914,7 @@ condition_true_at_tracepoint (struct tracepoint_hit_ctx *ctx,
   return (value ? 1 : 0);
 }
 
-/* Do memory copies for bytecodes.  */
-/* Do the recording of memory blocks for actions and bytecodes.  */
+/* See tracepoint.h.  */
 
 int
 agent_mem_read (struct eval_agent_expr_context *ctx,
@@ -4927,10 +4926,7 @@ agent_mem_read (struct eval_agent_expr_context *ctx,
 
   /* If a 'to' buffer is specified, use it.  */
   if (to != NULL)
-    {
-      read_inferior_memory (from, to, len);
-      return 0;
-    }
+    return read_inferior_memory (from, to, len);
 
   /* Otherwise, create a new memory block in the trace buffer.  */
   while (remaining > 0)
@@ -4951,7 +4947,8 @@ agent_mem_read (struct eval_agent_expr_context *ctx,
       memcpy (mspace, &blocklen, sizeof (blocklen));
       mspace += sizeof (blocklen);
       /* Record the memory block proper.  */
-      read_inferior_memory (from, mspace, blocklen);
+      if (read_inferior_memory (from, mspace, blocklen) != 0)
+	return 1;
       trace_debug ("%d bytes recorded", blocklen);
       remaining -= blocklen;
       from += blocklen;
diff --git a/gdbserver/tracepoint.h b/gdbserver/tracepoint.h
index a30f540d130..e424dc9dfb8 100644
--- a/gdbserver/tracepoint.h
+++ b/gdbserver/tracepoint.h
@@ -161,8 +161,13 @@ void gdb_agent_about_to_close (int pid);
 struct traceframe;
 struct eval_agent_expr_context;
 
-/* Do memory copies for bytecodes.  */
-/* Do the recording of memory blocks for actions and bytecodes.  */
+/* When TO is not NULL, do memory copies for bytecodes, read LEN bytes
+   starting at address FROM, and place the result in the buffer TO.
+   Return 0 on success, otherwise a non-zero error code.
+
+   When TO is NULL, do the recording of memory blocks for actions and
+   bytecodes into a new traceframe block.  Return 0 on success, otherwise,
+   return 1 if there is an error.  */
 
 int agent_mem_read (struct eval_agent_expr_context *ctx,
 		    unsigned char *to, CORE_ADDR from,
-- 
2.25.4


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

* [PATCHv2 05/13] gdbserver: allow agent expressions to fail with invalid memory access
  2023-01-18 16:17 ` [PATCHv2 00/13] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                     ` (3 preceding siblings ...)
  2023-01-18 16:18   ` [PATCHv2 04/13] gdbserver: allows agent_mem_read to return an error code Andrew Burgess
@ 2023-01-18 16:18   ` Andrew Burgess
  2023-01-19 10:13     ` Aktemur, Tankut Baris
  2023-01-18 16:18   ` [PATCHv2 06/13] gdb: avoid repeated signal reporting during failed conditional breakpoint Andrew Burgess
                     ` (9 subsequent siblings)
  14 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2023-01-18 16:18 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

This commit extends gdbserver to take account of a failed memory
access from agent_mem_read, and to return a new eval_result_type
expr_eval_invalid_memory_access.

I have only updated the agent_mem_read calls related directly to
reading memory, I have not updated any of the calls related to
tracepoint data collection.  This is just because I'm not familiar
with that area of gdb/gdbserver, and I don't want to break anything,
so leaving the existing behaviour as is seems like the safest
approach.

I've then update gdb.base/bp-cond-failure.exp to test evaluating the
breakpoints on the target, and have also extended the test so that it
checks for different sizes of memory access.
---
 gdb/testsuite/gdb.base/bp-cond-failure.exp | 16 +++++++---------
 gdbserver/ax.cc                            | 12 ++++++++----
 gdbserver/ax.h                             |  3 ++-
 3 files changed, 17 insertions(+), 14 deletions(-)

diff --git a/gdb/testsuite/gdb.base/bp-cond-failure.exp b/gdb/testsuite/gdb.base/bp-cond-failure.exp
index 6f89771d187..aa39b638592 100644
--- a/gdb/testsuite/gdb.base/bp-cond-failure.exp
+++ b/gdb/testsuite/gdb.base/bp-cond-failure.exp
@@ -39,7 +39,7 @@ if { [is_address_zero_readable] } {
 # Where the breakpoint will be placed.
 set bp_line [gdb_get_line_number "Breakpoint here"]
 
-proc run_test { cond_eval } {
+proc run_test { cond_eval access_type } {
     clean_restart ${::binfile}
 
     if {![runto_main]} {
@@ -52,7 +52,7 @@ proc run_test { cond_eval } {
     }
 
     # Setup the conditional breakpoint and record its number.
-    gdb_breakpoint "${::srcfile}:${::bp_line} if (*(int *) 0) == 0"
+    gdb_breakpoint "${::srcfile}:${::bp_line} if (*(${access_type} *) 0) == 0"
     set bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*"]
 
     gdb_test "continue" \
@@ -68,16 +68,14 @@ proc run_test { cond_eval } {
 # If we're using a remote target then conditions could be evaulated
 # locally on the host, or on the remote target.  Otherwise, conditions
 # are always evaluated locally (which is what auto will select).
-#
-# NOTE: 'target' is not included here for remote targets as a
-# gdbserver bug prevents the test from passing.  This will be fixed in
-# the next commit, and this test updated.
 if { [gdb_is_remote_or_extended_remote_target] } {
-    set cond_eval_modes { "host" }
+    set cond_eval_modes { "host" "target" }
 } else {
     set cond_eval_modes { "auto" }
 }
 
-foreach_with_prefix cond_eval $cond_eval_modes {
-    run_test $cond_eval
+foreach_with_prefix access_type { "char" "short" "int" "long long" } {
+    foreach_with_prefix cond_eval $cond_eval_modes {
+	run_test $cond_eval $access_type
+    }
 }
diff --git a/gdbserver/ax.cc b/gdbserver/ax.cc
index 38ebfbbd750..fba5b4ad0fc 100644
--- a/gdbserver/ax.cc
+++ b/gdbserver/ax.cc
@@ -1112,22 +1112,26 @@ gdb_eval_agent_expr (struct eval_agent_expr_context *ctx,
 	  break;
 
 	case gdb_agent_op_ref8:
-	  agent_mem_read (ctx, cnv.u8.bytes, (CORE_ADDR) top, 1);
+	  if (agent_mem_read (ctx, cnv.u8.bytes, (CORE_ADDR) top, 1) != 0)
+	    return expr_eval_invalid_memory_access;
 	  top = cnv.u8.val;
 	  break;
 
 	case gdb_agent_op_ref16:
-	  agent_mem_read (ctx, cnv.u16.bytes, (CORE_ADDR) top, 2);
+	  if (agent_mem_read (ctx, cnv.u16.bytes, (CORE_ADDR) top, 2) != 0)
+	    return expr_eval_invalid_memory_access;
 	  top = cnv.u16.val;
 	  break;
 
 	case gdb_agent_op_ref32:
-	  agent_mem_read (ctx, cnv.u32.bytes, (CORE_ADDR) top, 4);
+	  if (agent_mem_read (ctx, cnv.u32.bytes, (CORE_ADDR) top, 4) != 0)
+	    return expr_eval_invalid_memory_access;
 	  top = cnv.u32.val;
 	  break;
 
 	case gdb_agent_op_ref64:
-	  agent_mem_read (ctx, cnv.u64.bytes, (CORE_ADDR) top, 8);
+	  if (agent_mem_read (ctx, cnv.u64.bytes, (CORE_ADDR) top, 8) != 0)
+	    return expr_eval_invalid_memory_access;
 	  top = cnv.u64.val;
 	  break;
 
diff --git a/gdbserver/ax.h b/gdbserver/ax.h
index 8e64a7a593e..c98e36a83c6 100644
--- a/gdbserver/ax.h
+++ b/gdbserver/ax.h
@@ -41,7 +41,8 @@ enum eval_result_type
     expr_eval_unhandled_opcode,
     expr_eval_unrecognized_opcode,
     expr_eval_divide_by_zero,
-    expr_eval_invalid_goto
+    expr_eval_invalid_goto,
+    expr_eval_invalid_memory_access
   };
 
 struct agent_expr
-- 
2.25.4


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

* [PATCHv2 06/13] gdb: avoid repeated signal reporting during failed conditional breakpoint
  2023-01-18 16:17 ` [PATCHv2 00/13] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                     ` (4 preceding siblings ...)
  2023-01-18 16:18   ` [PATCHv2 05/13] gdbserver: allow agent expressions to fail with invalid memory access Andrew Burgess
@ 2023-01-18 16:18   ` Andrew Burgess
  2023-01-19 10:33     ` Aktemur, Tankut Baris
  2023-01-18 16:18   ` [PATCHv2 07/13] gdb: don't always print breakpoint location after failed condition check Andrew Burgess
                     ` (8 subsequent siblings)
  14 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2023-01-18 16:18 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Consider the following case:

  (gdb) list some_func
  1	int
  2	some_func ()
  3	{
  4	  int *p = 0;
  5	  return *p;
  6	}
  7
  8	void
  9	foo ()
  10	{
  (gdb) break foo if (some_func ())
  Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
  (gdb) r
  Starting program: /tmp/bpcond

  Program received signal SIGSEGV, Segmentation fault.
  0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  Error in testing breakpoint condition:
  The program being debugged was signaled while in a function called from GDB.
  GDB remains in the frame where the signal was received.
  To change this behavior use "set unwindonsignal on".
  Evaluation of the expression containing the function
  (some_func) will be abandoned.
  When the function is done executing, GDB will silently stop.

  Program received signal SIGSEGV, Segmentation fault.

  Breakpoint 1, 0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  (gdb)

Notice that this line:

  Program received signal SIGSEGV, Segmentation fault.

Appears twice in the output.  The first time is followed by the
current location.  The second time is a little odd, why do we print
that?

Printing that line is controlled, in part, by a global variable,
stopped_by_random_signal.  This variable is reset to zero in
handle_signal_stop, and is set if/when GDB figures out that the
inferior stopped due to some random signal.

The problem is, in our case, GDB first stops at the breakpoint for
foo, and enters handle_signal_stop and the stopped_by_random_signal
global is reset to 0.

Later within handle_signal_stop GDB calls bpstat_stop_status, it is
within this function (via bpstat_check_breakpoint_conditions) that the
breakpoint condition is checked, and, we end up calling the inferior
function (some_func in our example above).

In our case above the thread performing the inferior function call
segfaults in some_func.  GDB catches the SIGSEGV and handles the stop,
this causes us to reenter handle_signal_stop.  The global variable
stopped_by_random_signal is updated, this time it is set to true
because the thread stopped due to SIGSEGV.  As a result of this we
print the first instance of the line (as seen above in the example).

Finally we unwind GDB's call stack, the inferior function call is
complete, and we return to the original handle_signal_stop.  However,
the stopped_by_random_signal global is still carrying the value as
computed for the inferior function call's stop, which is why we now
print a second instance of the line, as seen in the example.

To prevent this, I propose adding a scoped_restore before we start an
inferior function call, this will save and restore the global
stopped_by_random_signal value.

With this done, the output from our example is now this:

 (gdb) list some_func
  1	int
  2	some_func ()
  3	{
  4	  int *p = 0;
  5	  return *p;
  6	}
  7
  8	void
  9	foo ()
  10	{
  (gdb) break foo if (some_func ())
  Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
  (gdb) r
  Starting program: /tmp/bpcond

  Program received signal SIGSEGV, Segmentation fault.
  0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  Error in testing condition for breakpoint 1:
  The program being debugged stopped while in a function called from GDB.
  Evaluation of the expression containing the function
  (some_func) will be abandoned.
  When the function is done executing, GDB will silently stop.

  Breakpoint 1, 0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  (gdb)

We now only see the 'Program received signal SIGSEGV, ...' line once,
which I think makes more sense.

Finally, I'm aware that the last few lines, that report the stop as
being at 'Breakpoint 1', when this is not where the thread is actually
located anymore, is not great.  I'll address that in the next commit.
---
 gdb/infcall.c                              |   9 +
 gdb/testsuite/gdb.base/infcall-failure.c   |  48 ++++++
 gdb/testsuite/gdb.base/infcall-failure.exp | 184 +++++++++++++++++++++
 3 files changed, 241 insertions(+)
 create mode 100644 gdb/testsuite/gdb.base/infcall-failure.c
 create mode 100644 gdb/testsuite/gdb.base/infcall-failure.exp

diff --git a/gdb/infcall.c b/gdb/infcall.c
index e09904f9a35..e1b785e437b 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -1296,6 +1296,15 @@ call_function_by_hand_dummy (struct value *function,
   /* Register a clean-up for unwind_on_terminating_exception_breakpoint.  */
   SCOPE_EXIT { delete_std_terminate_breakpoint (); };
 
+  /* The stopped_by_random_signal variable is global.  If we are here
+     as part of a breakpoint condition check then the global will have
+     already been setup as part of the original breakpoint stop.  By
+     making the inferior call the global will be changed when GDB
+     handles the stop after the inferior call.  Avoid confusion by
+     restoring the current value after the inferior call.  */
+  scoped_restore restore_stopped_by_random_signal
+    = make_scoped_restore (&stopped_by_random_signal, 0);
+
   /* - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP -
      If you're looking to implement asynchronous dummy-frames, then
      just below is the place to chop this function in two..  */
diff --git a/gdb/testsuite/gdb.base/infcall-failure.c b/gdb/testsuite/gdb.base/infcall-failure.c
new file mode 100644
index 00000000000..00f4369e164
--- /dev/null
+++ b/gdb/testsuite/gdb.base/infcall-failure.c
@@ -0,0 +1,48 @@
+/* Copyright 2022 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/>.  */
+
+/* A function that segfaults (assuming that reads of address zero are
+   prohibited), this is used from within a breakpoint condition.  */
+int
+func_segfault ()
+{
+  volatile int *p = 0;
+  return *p;	/* Segfault here.  */
+}
+
+/* A function in which we will place a breakpoint.  This function is itself
+   then used from within a breakpoint condition.  */
+int
+func_bp ()
+{
+  int res = 0;	/* Second breakpoint.  */
+  return res;
+}
+
+int
+foo ()
+{
+  return 0;	/* First breakpoint.  */
+}
+
+int
+main ()
+{
+  int res = foo ();
+
+  return res;
+}
diff --git a/gdb/testsuite/gdb.base/infcall-failure.exp b/gdb/testsuite/gdb.base/infcall-failure.exp
new file mode 100644
index 00000000000..2dcdda34b4d
--- /dev/null
+++ b/gdb/testsuite/gdb.base/infcall-failure.exp
@@ -0,0 +1,184 @@
+# Copyright 2022 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/>.
+
+# Some simple tests of inferior function calls from breakpoint
+# conditions, in a single-threaded inferior.
+#
+# Test what happens when the inferior function (from a breakpoint
+# condition) either hits a nested breakpoint, or segfaults.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug}] == -1 } {
+    return
+}
+
+set bp_1_line [gdb_get_line_number "First breakpoint"]
+set bp_2_line [gdb_get_line_number "Second breakpoint"]
+set segv_line [gdb_get_line_number "Segfault here"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto
+# main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if {![runto_main]} {
+	fail "run to main"
+	return -1
+    }
+
+    return 0
+}
+
+# Start GDB according to ASYNC_P and NON_STOP_P, then setup a
+# conditional breakpoint.  The breakpoint condition includes an
+# inferior function call that will itself hit a breakpoint.  Check how
+# GDB reports this to the user.
+proc_with_prefix run_cond_hits_breakpoint_test { async_p non_stop_p } {
+    if { [start_gdb_and_runto_main $async_p $non_stop_p] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint and record its number.
+    gdb_breakpoint "${::srcfile}:${::bp_1_line} if (func_bp ())"
+    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		     "get number of first breakpoint"]
+
+    # Setup a breakpoint inside func_bp.
+    gdb_breakpoint "${::srcfile}:${::bp_2_line}"
+    set bp_2_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		     "get number of second breakpoint"]
+
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     "" \
+	     "Breakpoint ${bp_2_num}, func_bp \\(\\) at \[^\r\n\]+:${::bp_2_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Second breakpoint\[^\r\n\]+" \
+	     "Error in testing condition for breakpoint ${bp_1_num}:" \
+	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(func_bp\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\." \
+	     "" \
+	     "Breakpoint ${bp_1_num}, \[^\r\n\]+" \
+	     "${::decimal}\\s+\[^\r\n\]+Second breakpoint\[^\r\n\]+"]
+}
+
+# Start GDB according to ASYNC_P and NON_STOP_P, then call an inferior
+# function.  The inferior function being called will itself have a
+# breakpoint within it.  Check how GDB reports this to the user.
+proc_with_prefix run_call_hits_breakpoint_test { async_p non_stop_p } {
+    if { [start_gdb_and_runto_main $async_p $non_stop_p] == -1 } {
+	return
+    }
+
+    # Setup a breakpoint inside func_bp.
+    gdb_breakpoint "${::srcfile}:${::bp_2_line}"
+    set bp_2_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of second breakpoint"]
+
+
+    gdb_test "call func_bp ()" \
+	[multi_line \
+	     "" \
+	     "Breakpoint ${bp_2_num}, func_bp \\(\\) at \[^\r\n\]+:${::bp_2_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Second breakpoint\[^\r\n\]+" \
+	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(func_bp\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+}
+
+# Start GDB according to ASYNC_P and NON_STOP_P, then setup a
+# conditional breakpoint.  The breakpoint condition includes an
+# inferior function call that segfaults.  Check how GDB reports this
+# to the user.
+proc_with_prefix run_cond_hits_segfault_test { async_p non_stop_p } {
+    if { [start_gdb_and_runto_main $async_p $non_stop_p] == -1 } {
+	return
+    }
+
+    # This test relies on the inferior segfaulting when trying to
+    # access address zero.
+    if { [is_address_zero_readable] } {
+	return
+    }
+
+    # Setup the conditional breakpoint and record its number.
+    gdb_breakpoint "${::srcfile}:${::bp_1_line} if (func_segfault ())"
+    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		     "get number of first breakpoint"]
+
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     "" \
+	     "Program received signal SIGSEGV, Segmentation fault\\." \
+	     "${::hex} in func_segfault \\(\\) at \[^\r\n\]+:${::segv_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
+	     "Error in testing condition for breakpoint ${bp_1_num}:" \
+	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(func_segfault\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\." \
+	     "" \
+	     "Breakpoint ${bp_1_num}, \[^\r\n\]+" \
+	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"]
+}
+
+# Start GDB according to ASYNC_P and NON_STOP_P, then call an inferior
+# function.  The inferior function will segfault.  Check how GDB
+# reports this to the user.
+proc_with_prefix run_call_hits_segfault_test { async_p non_stop_p } {
+    if { [start_gdb_and_runto_main $async_p $non_stop_p] == -1 } {
+	return
+    }
+
+    # This test relies on the inferior segfaulting when trying to
+    # access address zero.
+    if { [is_address_zero_readable] } {
+	return
+    }
+
+    gdb_test "call func_segfault ()" \
+	[multi_line \
+	     "" \
+	     "Program received signal SIGSEGV, Segmentation fault\\." \
+	     "${::hex} in func_segfault \\(\\) at \[^\r\n\]+:${::segv_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
+	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(func_segfault\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	run_cond_hits_breakpoint_test $target_async $target_non_stop
+	run_call_hits_breakpoint_test $target_async $target_non_stop
+
+	run_cond_hits_segfault_test $target_async $target_non_stop
+	run_call_hits_segfault_test $target_async $target_non_stop
+    }
+}
-- 
2.25.4


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

* [PATCHv2 07/13] gdb: don't always print breakpoint location after failed condition check
  2023-01-18 16:17 ` [PATCHv2 00/13] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                     ` (5 preceding siblings ...)
  2023-01-18 16:18   ` [PATCHv2 06/13] gdb: avoid repeated signal reporting during failed conditional breakpoint Andrew Burgess
@ 2023-01-18 16:18   ` Andrew Burgess
  2023-01-19 10:49     ` Aktemur, Tankut Baris
  2023-01-18 16:18   ` [PATCHv2 08/13] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
                     ` (7 subsequent siblings)
  14 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2023-01-18 16:18 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Consider the following session:

  (gdb) list some_func
  1	int
  2	some_func ()
  3	{
  4	  int *p = 0;
  5	  return *p;
  6	}
  7
  8	void
  9	foo ()
  10	{
  (gdb) break foo if (some_func ())
  Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
  (gdb) r
  Starting program: /tmp/bpcond

  Program received signal SIGSEGV, Segmentation fault.
  0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  Error in testing condition for breakpoint 1:
  The program being debugged stopped while in a function called from GDB.
  Evaluation of the expression containing the function
  (some_func) will be abandoned.
  When the function is done executing, GDB will silently stop.

  Breakpoint 1, 0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  (gdb)

What happens here is the breakpoint condition includes a call to an
inferior function, and the inferior function segfaults.  We can see
that GDB reports the segfault, and then gives an error message that
indicates that an inferior function call was interrupted.

After this GDB appears to report that it is stopped at Breakpoint 1,
inside some_func.

I find this second stop report a little confusing.  Yes, GDB has
stopped as a result of hitting breakpoint 1, but, I think the message
as it currently is might give the impression that the thread is
actually stopped at a location of breakpoint 1, which is not the case.

Also, I find the second stop message draws attention away from
the "Program received signal SIGSEGV, Segmentation fault" stop
message, and this second stop might be thought of as replacing in
someway the earlier message.

In short, I think that the in the situation above, I think things
would be clearer if the second stop message were not reported at all,
so the output should (I think) look like this:

  (gdb) list some_func
  1	int
  2	some_func ()
  3	{
  4	  int *p = 0;
  5	  return *p;
  6	}
  7
  8	void
  9	foo ()
  10	{
  (gdb) break foo if (some_func ())
  Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
  (gdb) r
  Starting program: /tmp/bpcond

  Program received signal SIGSEGV, Segmentation fault.
  0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  Error in testing condition for breakpoint 1:
  The program being debugged stopped while in a function called from GDB.
  Evaluation of the expression containing the function
  (some_func) will be abandoned.
  When the function is done executing, GDB will silently stop.
  (gdb)

The user can still find the number of the breakpoint that triggered
the initial stop in this line:

  Error in testing condition for breakpoint 1:

But there's now only one stop reason reported, the SIGSEGV, which I
think is much clearer.

To achieve this change I set the bpstat::print field when:

  (a) a breakpoint condition evaluation failed, and

  (b) the $pc of the thread changed during condition evaluation.

I've updated the existing tests that checked the error message printed
when a breakpoint condition evaluation failed.
---
 gdb/breakpoint.c                           | 12 ++++++++++++
 gdb/testsuite/gdb.base/infcall-failure.exp | 18 ++++++++----------
 2 files changed, 20 insertions(+), 10 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index eecaeefed3e..c4fec7e8e55 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -5533,6 +5533,7 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
 	  else
 	    within_current_scope = false;
 	}
+      CORE_ADDR pc_before_check = get_frame_pc (get_selected_frame (nullptr));
       if (within_current_scope)
 	{
 	  try
@@ -5544,6 +5545,17 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
 	      exception_fprintf (gdb_stderr, ex,
 				 "Error in testing condition for breakpoint %d:\n",
 				 b->number);
+
+	      /* If the pc value changed as a result of evaluating the
+		 condition then we probably stopped within an inferior
+		 function call due to some unexpected stop, e.g. the thread
+		 hit another breakpoint, or the thread received an
+		 unexpected signal.  In this case we don't want to also
+		 print the information about this breakpoint.  */
+	      CORE_ADDR pc_after_check
+		= get_frame_pc (get_selected_frame (nullptr));
+	      if (pc_before_check != pc_after_check)
+		bs->print = 0;
 	    }
 	}
       else
diff --git a/gdb/testsuite/gdb.base/infcall-failure.exp b/gdb/testsuite/gdb.base/infcall-failure.exp
index 2dcdda34b4d..8fa2c407fc5 100644
--- a/gdb/testsuite/gdb.base/infcall-failure.exp
+++ b/gdb/testsuite/gdb.base/infcall-failure.exp
@@ -79,10 +79,7 @@ proc_with_prefix run_cond_hits_breakpoint_test { async_p non_stop_p } {
 	     "The program being debugged stopped while in a function called from GDB\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(func_bp\\) will be abandoned\\." \
-	     "When the function is done executing, GDB will silently stop\\." \
-	     "" \
-	     "Breakpoint ${bp_1_num}, \[^\r\n\]+" \
-	     "${::decimal}\\s+\[^\r\n\]+Second breakpoint\[^\r\n\]+"]
+	     "When the function is done executing, GDB will silently stop\\."]
 }
 
 # Start GDB according to ASYNC_P and NON_STOP_P, then call an inferior
@@ -138,13 +135,12 @@ proc_with_prefix run_cond_hits_segfault_test { async_p non_stop_p } {
 	     "${::hex} in func_segfault \\(\\) at \[^\r\n\]+:${::segv_line}" \
 	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
 	     "Error in testing condition for breakpoint ${bp_1_num}:" \
-	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "The program being debugged was signaled while in a function called from GDB\\." \
+	     "GDB remains in the frame where the signal was received\\." \
+	     "To change this behavior use \"set unwindonsignal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(func_segfault\\) will be abandoned\\." \
-	     "When the function is done executing, GDB will silently stop\\." \
-	     "" \
-	     "Breakpoint ${bp_1_num}, \[^\r\n\]+" \
-	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"]
+	     "When the function is done executing, GDB will silently stop\\."]
 }
 
 # Start GDB according to ASYNC_P and NON_STOP_P, then call an inferior
@@ -167,7 +163,9 @@ proc_with_prefix run_call_hits_segfault_test { async_p non_stop_p } {
 	     "Program received signal SIGSEGV, Segmentation fault\\." \
 	     "${::hex} in func_segfault \\(\\) at \[^\r\n\]+:${::segv_line}" \
 	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
-	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "The program being debugged was signaled while in a function called from GDB\\." \
+	     "GDB remains in the frame where the signal was received\\." \
+	     "To change this behavior use \"set unwindonsignal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(func_segfault\\) will be abandoned\\." \
 	     "When the function is done executing, GDB will silently stop\\."]
-- 
2.25.4


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

* [PATCHv2 08/13] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait"
  2023-01-18 16:17 ` [PATCHv2 00/13] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                     ` (6 preceding siblings ...)
  2023-01-18 16:18   ` [PATCHv2 07/13] gdb: don't always print breakpoint location after failed condition check Andrew Burgess
@ 2023-01-18 16:18   ` Andrew Burgess
  2023-01-19 11:05     ` Aktemur, Tankut Baris
  2023-01-18 16:18   ` [PATCHv2 09/13] gdb: fix b/p conditions with infcalls in multi-threaded inferiors Andrew Burgess
                     ` (6 subsequent siblings)
  14 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2023-01-18 16:18 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

This reverts commit ac0d67ed1dcf470bad6a3bc4800c2ddc9bedecca.

There was nothing wrong with the commit which I'm reverting here, but
it removed some functionality that will be needed for a later commit;
that is, the ability for GDB to ask for events from a specific ptid_t
via the do_target_wait function.

In a follow up commit, this functionality will be used to implement
inferior function calls in multi-threaded inferiors.
---
 gdb/infrun.c | 12 +++++++-----
 1 file changed, 7 insertions(+), 5 deletions(-)

diff --git a/gdb/infrun.c b/gdb/infrun.c
index edfb5ab0a91..5af8635a1ab 100644
--- a/gdb/infrun.c
+++ b/gdb/infrun.c
@@ -3741,7 +3741,8 @@ do_target_wait_1 (inferior *inf, ptid_t ptid,
    more events.  Polls for events from all inferiors/targets.  */
 
 static bool
-do_target_wait (execution_control_state *ecs, target_wait_flags options)
+do_target_wait (ptid_t wait_ptid, execution_control_state *ecs,
+		target_wait_flags options)
 {
   int num_inferiors = 0;
   int random_selector;
@@ -3751,9 +3752,10 @@ do_target_wait (execution_control_state *ecs, target_wait_flags options)
      polling the rest of the inferior list starting from that one in a
      circular fashion until the whole list is polled once.  */
 
-  auto inferior_matches = [] (inferior *inf)
+  auto inferior_matches = [&wait_ptid] (inferior *inf)
     {
-      return inf->process_target () != nullptr;
+      return (inf->process_target () != NULL
+	      && ptid_t (inf->pid).matches (wait_ptid));
     };
 
   /* First see how many matching inferiors we have.  */
@@ -3792,7 +3794,7 @@ do_target_wait (execution_control_state *ecs, target_wait_flags options)
 
   auto do_wait = [&] (inferior *inf)
   {
-    ecs->ptid = do_target_wait_1 (inf, minus_one_ptid, &ecs->ws, options);
+    ecs->ptid = do_target_wait_1 (inf, wait_ptid, &ecs->ws, options);
     ecs->target = inf->process_target ();
     return (ecs->ws.kind () != TARGET_WAITKIND_IGNORE);
   };
@@ -4169,7 +4171,7 @@ fetch_inferior_event ()
        the event.  */
     scoped_disable_commit_resumed disable_commit_resumed ("handling event");
 
-    if (!do_target_wait (&ecs, TARGET_WNOHANG))
+    if (!do_target_wait (minus_one_ptid, &ecs, TARGET_WNOHANG))
       {
 	infrun_debug_printf ("do_target_wait returned no event");
 	disable_commit_resumed.reset_and_commit ();
-- 
2.25.4


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

* [PATCHv2 09/13] gdb: fix b/p conditions with infcalls in multi-threaded inferiors
  2023-01-18 16:17 ` [PATCHv2 00/13] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                     ` (7 preceding siblings ...)
  2023-01-18 16:18   ` [PATCHv2 08/13] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
@ 2023-01-18 16:18   ` Andrew Burgess
  2023-01-20  7:13     ` Aktemur, Tankut Baris
  2023-01-18 16:18   ` [PATCHv2 10/13] gdb: add timeouts for inferior function calls Andrew Burgess
                     ` (5 subsequent siblings)
  14 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2023-01-18 16:18 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Natalia Saiapova, Tankut Baris Aktemur

This commit fixes bug PR 28942, that is, creating a conditional
breakpoint in a multi-threaded inferior, where the breakpoint
condition includes an inferior function call.

Currently, when a user tries to create such a breakpoint, then GDB
will fail with:

  (gdb) break infcall-from-bp-cond-single.c:61 if (return_true ())
  Breakpoint 2 at 0x4011fa: file /tmp/build/gdb/testsuite/../../../src/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c, line 61.
  (gdb) continue
  Continuing.
  [New Thread 0x7ffff7c5d700 (LWP 2460150)]
  [New Thread 0x7ffff745c700 (LWP 2460151)]
  [New Thread 0x7ffff6c5b700 (LWP 2460152)]
  [New Thread 0x7ffff645a700 (LWP 2460153)]
  [New Thread 0x7ffff5c59700 (LWP 2460154)]
  Error in testing breakpoint condition:
  Couldn't get registers: No such process.
  An error occurred while in a function called from GDB.
  Evaluation of the expression containing the function
  (return_true) will be abandoned.
  When the function is done executing, GDB will silently stop.
  Selected thread is running.
  (gdb)

Or, in some cases, like this:

  (gdb) break infcall-from-bp-cond-simple.c:56 if (is_matching_tid (arg, 1))
  Breakpoint 2 at 0x401194: file /tmp/build/gdb/testsuite/../../../src/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c, line 56.
  (gdb) continue
  Continuing.
  [New Thread 0x7ffff7c5d700 (LWP 2461106)]
  [New Thread 0x7ffff745c700 (LWP 2461107)]
  ../../src.release/gdb/nat/x86-linux-dregs.c:146: internal-error: x86_linux_update_debug_registers: Assertion `lwp_is_stopped (lwp)' failed.
  A problem internal to GDB has been detected,
  further debugging may prove unreliable.

The precise error depends on the exact thread state; so there's race
conditions depending on which threads have fully started, and which
have not.  But the underlying problem is always the same; when GDB
tries to execute the inferior function call from within the breakpoint
condition, GDB will, incorrectly, try to resume threads that are
already running - GDB doesn't realise that some threads might already
be running.

The solution proposed in this patch requires an additional member
variable thread_info::in_cond_eval.  This flag is set to true (in
breakpoint.c) when GDB is evaluating a breakpoint condition.

In user_visible_resume_ptid (infrun.c), when the in_cond_eval flag is
true, then GDB will only try to resume the current thread, that is,
the thread for which the breakpoint condition is being evaluated.
This solves the problem of GDB trying to resume threads that are
already running.

The next problem is that inferior function calls are assumed to be
synchronous, that is, GDB doesn't expect to start an inferior function
call in thread #1, then receive a stop from thread #2 for some other,
unrelated reason.  To prevent GDB responding to an event from another
thread, we update fetch_inferior_event and do_target_wait in infrun.c,
so that, when an inferior function call (on behalf of a breakpoint
condition) is in progress, we only wait for events from the current
thread (the one evaluating the condition).

The fix in do_target_wait is because previously, we only ever waited
for the general any-thread, minus_one_ptid, for which matching
against the inferior::pid would always succeed.  However, now we might
wait against a specific ptid value, in which case we need to ensure we
only compare the pid part of the ptid.

In fetch_inferior_event, after receiving the event, we only want to
stop all the other threads, and call inferior_event_handler with
INF_EXEC_COMPLETE, if we are not evaluating a conditional breakpoint.
If we are, then all the other threads should be left doing whatever
they were before.  The inferior_event_handler call will be performed
once the breakpoint condition has finished being evaluated, and GDB
decides to stop or not.

The final problem that needs solving relates to GDB's commit-resume
mechanism, this allows GDB to collect resume requests into a single
packet in order to reduce traffic to a remote target.

The problem is that the commit-resume mechanism will not send any
resume requests for an inferior if there are already events pending on
the GDB side.

Imagine an inferior with two threads.  Both threads hit a breakpoint,
maybe the same conditional breakpoint.  At this point there are two
pending events, one for each thread.

GDB selects one of the events and spots that this is a conditional
breakpoint, GDB evaluates the condition.

The condition includes an inferior function call, so GDB sets up for
the call and resumes the one thread, the resume request is added to
the commit-resume queue.

When the commit-resume queue is committed GDB sees that there is a
pending event from another thread, and so doesn't send any resume
requests to the actual target, GDB is assuming that when we wait we
will select the event from the other thread.

However, as this is an inferior function call for a condition
evaluation, we will not select the event from the other thread, we
only care about events from the thread that is evaluating the
condition - and the resume for this thread was never sent to the
target.

And so, GDB hangs, waiting for an event from a thread that was never
fully resumed.

To fix this issue I have added the concept of "forcing" the
commit-resume queue.  When enabling commit resume, if the force flag
is true, then any resumes will be committed to the target, even if
there are other threads with pending events.

A note on authorship: this patch was based on some work done by
Natalia Saiapova and Tankut Baris Aktemur from Intel[1].  I have made
some changes to their work in this version.

Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=28942

[1] https://sourceware.org/pipermail/gdb-patches/2020-October/172454.html

Co-authored-by: Natalia Saiapova <natalia.saiapova@intel.com>
Co-authored-by: Tankut Baris Aktemur <tankut.baris.aktemur@intel.com>
---
 gdb/breakpoint.c                              |   2 +
 gdb/gdbthread.h                               |   3 +
 gdb/infcall.c                                 |   6 +
 gdb/infrun.c                                  |  46 +++-
 gdb/infrun.h                                  |   2 +-
 .../infcall-from-bp-cond-other-thread-event.c | 135 ++++++++++
 ...nfcall-from-bp-cond-other-thread-event.exp | 175 +++++++++++++
 .../gdb.threads/infcall-from-bp-cond-simple.c |  89 +++++++
 .../infcall-from-bp-cond-simple.exp           | 236 ++++++++++++++++++
 .../gdb.threads/infcall-from-bp-cond-single.c | 139 +++++++++++
 .../infcall-from-bp-cond-single.exp           | 119 +++++++++
 11 files changed, 940 insertions(+), 12 deletions(-)
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index c4fec7e8e55..0cb4382ba5b 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -5538,6 +5538,8 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
 	{
 	  try
 	    {
+	      scoped_restore reset_in_cond_eval
+		= make_scoped_restore (&thread->control.in_cond_eval, true);
 	      condition_result = breakpoint_cond_eval (cond);
 	    }
 	  catch (const gdb_exception &ex)
diff --git a/gdb/gdbthread.h b/gdb/gdbthread.h
index 11d69fceab0..b0421bac95f 100644
--- a/gdb/gdbthread.h
+++ b/gdb/gdbthread.h
@@ -171,6 +171,9 @@ struct thread_control_state
      command.  This is used to decide whether "set scheduler-locking
      step" behaves like "on" or "off".  */
   int stepping_command = 0;
+
+  /* True if the thread is evaluating a BP condition.  */
+  bool in_cond_eval = false;
 };
 
 /* Inferior thread specific part of `struct infcall_suspend_state'.  */
diff --git a/gdb/infcall.c b/gdb/infcall.c
index e1b785e437b..8a48909bc2c 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -641,6 +641,12 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
 
       proceed (real_pc, GDB_SIGNAL_0);
 
+      /* Enable commit resume, but pass true for the force flag.  This
+	 ensures any thread we set running in proceed will actually be
+	 committed to the target, even if some other thread in the current
+	 target has a pending event.  */
+      scoped_enable_commit_resumed enable ("infcall", true);
+
       infrun_debug_show_threads ("non-exited threads after proceed for inferior-call",
 				 all_non_exited_threads ());
 
diff --git a/gdb/infrun.c b/gdb/infrun.c
index 5af8635a1ab..861be6eae2f 100644
--- a/gdb/infrun.c
+++ b/gdb/infrun.c
@@ -2149,6 +2149,14 @@ user_visible_resume_ptid (int step)
 	 mode.  */
       resume_ptid = inferior_ptid;
     }
+  else if (inferior_ptid != null_ptid
+	   && inferior_thread ()->control.in_cond_eval)
+    {
+      /* The inferior thread is evaluating a BP condition.  Other threads
+	 might be stopped or running and we do not want to change their
+	 state, thus, resume only the current thread.  */
+      resume_ptid = inferior_ptid;
+    }
   else if (!sched_multi && target_supports_multi_process ())
     {
       /* Resume all threads of the current process (and none of other
@@ -2861,7 +2869,7 @@ schedlock_applies (struct thread_info *tp)
    pending events.  */
 
 static void
-maybe_set_commit_resumed_all_targets ()
+maybe_set_commit_resumed_all_targets (bool force_p)
 {
   scoped_restore_current_thread restore_thread;
 
@@ -2890,7 +2898,7 @@ maybe_set_commit_resumed_all_targets ()
 	 status to report, handle it before requiring the target to
 	 commit its resumed threads: handling the status might lead to
 	 resuming more threads.  */
-      if (proc_target->has_resumed_with_pending_wait_status ())
+      if (!force_p && proc_target->has_resumed_with_pending_wait_status ())
 	{
 	  infrun_debug_printf ("not requesting commit-resumed for target %s, a"
 			       " thread has a pending waitstatus",
@@ -2900,7 +2908,7 @@ maybe_set_commit_resumed_all_targets ()
 
       switch_to_inferior_no_thread (inf);
 
-      if (target_has_pending_events ())
+      if (!force_p && target_has_pending_events ())
 	{
 	  infrun_debug_printf ("not requesting commit-resumed for target %s, "
 			       "target has pending events",
@@ -2993,7 +3001,7 @@ scoped_disable_commit_resumed::reset ()
     {
       /* This is the outermost instance, re-enable
          COMMIT_RESUMED_STATE on the targets where it's possible.  */
-      maybe_set_commit_resumed_all_targets ();
+      maybe_set_commit_resumed_all_targets (false);
     }
   else
     {
@@ -3026,7 +3034,7 @@ scoped_disable_commit_resumed::reset_and_commit ()
 /* See infrun.h.  */
 
 scoped_enable_commit_resumed::scoped_enable_commit_resumed
-  (const char *reason)
+  (const char *reason, bool force_p)
   : m_reason (reason),
     m_prev_enable_commit_resumed (enable_commit_resumed)
 {
@@ -3038,7 +3046,7 @@ scoped_enable_commit_resumed::scoped_enable_commit_resumed
 
       /* Re-enable COMMIT_RESUMED_STATE on the targets where it's
 	 possible.  */
-      maybe_set_commit_resumed_all_targets ();
+      maybe_set_commit_resumed_all_targets (force_p);
 
       maybe_call_commit_resumed_all_targets ();
     }
@@ -3752,10 +3760,11 @@ do_target_wait (ptid_t wait_ptid, execution_control_state *ecs,
      polling the rest of the inferior list starting from that one in a
      circular fashion until the whole list is polled once.  */
 
-  auto inferior_matches = [&wait_ptid] (inferior *inf)
+  ptid_t wait_ptid_pid {wait_ptid.pid ()};
+  auto inferior_matches = [&wait_ptid_pid] (inferior *inf)
     {
       return (inf->process_target () != NULL
-	      && ptid_t (inf->pid).matches (wait_ptid));
+	      && ptid_t (inf->pid).matches (wait_ptid_pid));
     };
 
   /* First see how many matching inferiors we have.  */
@@ -4171,7 +4180,17 @@ fetch_inferior_event ()
        the event.  */
     scoped_disable_commit_resumed disable_commit_resumed ("handling event");
 
-    if (!do_target_wait (minus_one_ptid, &ecs, TARGET_WNOHANG))
+    /* Is the current thread performing an inferior function call as part
+       of a breakpoint condition evaluation?  */
+    bool in_cond_eval = (inferior_ptid != null_ptid
+			 && inferior_thread ()->control.in_cond_eval);
+
+    /* If the thread is in the middle of the condition evaluation, wait for
+       an event from the current thread, otherwise, wait for an event from
+       any thread.  */
+    ptid_t waiton_ptid = in_cond_eval ? inferior_ptid : minus_one_ptid;
+
+    if (!do_target_wait (waiton_ptid, &ecs, TARGET_WNOHANG))
       {
 	infrun_debug_printf ("do_target_wait returned no event");
 	disable_commit_resumed.reset_and_commit ();
@@ -4223,7 +4242,12 @@ fetch_inferior_event ()
 	    bool should_notify_stop = true;
 	    bool proceeded = false;
 
-	    stop_all_threads_if_all_stop_mode ();
+	    /* If the thread that stopped just completed an inferior
+	       function call as part of a condition evaluation, then we
+	       don't want to stop all the other threads.  */
+	    if (ecs.event_thread == nullptr
+		|| !ecs.event_thread->control.in_cond_eval)
+	      stop_all_threads_if_all_stop_mode ();
 
 	    clean_up_just_stopped_threads_fsms (&ecs);
 
@@ -4238,7 +4262,7 @@ fetch_inferior_event ()
 		  proceeded = normal_stop ();
 	      }
 
-	    if (!proceeded)
+	    if (!proceeded && !in_cond_eval)
 	      {
 		inferior_event_handler (INF_EXEC_COMPLETE);
 		cmd_done = 1;
diff --git a/gdb/infrun.h b/gdb/infrun.h
index 43fd1b44f5a..ced2ec5843c 100644
--- a/gdb/infrun.h
+++ b/gdb/infrun.h
@@ -395,7 +395,7 @@ extern void maybe_call_commit_resumed_all_targets ();
 
 struct scoped_enable_commit_resumed
 {
-  explicit scoped_enable_commit_resumed (const char *reason);
+  explicit scoped_enable_commit_resumed (const char *reason, bool force_p = false);
   ~scoped_enable_commit_resumed ();
 
   DISABLE_COPY_AND_ASSIGN (scoped_enable_commit_resumed);
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
new file mode 100644
index 00000000000..a6abdeb29a6
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
@@ -0,0 +1,135 @@
+/* Copyright 2022 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 <pthread.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <sched.h>
+
+#define NUM_THREADS 2
+
+pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+
+/* Some global variables to poke, just for something to do.  */
+volatile int global_var_0 = 0;
+volatile int global_var_1 = 0;
+
+/* This flag is updated from GDB.  */
+volatile int raise_signal = 0;
+
+/* Implement the breakpoint condition function.  Release the other thread
+   and try to give the other thread a chance to run.  Then return ANSWER.  */
+int
+condition_core_func (int answer)
+{
+  /* This unlock should release the other thread.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  /* And this yield and sleep should (hopefully) give the other thread a
+     chance to run.  This isn't guaranteed of course, but once the other
+     thread does run it should hit a breakpoint, which GDB should
+     (temporarily) ignore, so there's no easy way for us to know the other
+     thread has done what it needs to, thus, yielding and sleeping is the
+     best we can do.  */
+  sched_yield ();
+  sleep (2);
+
+  return answer;
+}
+
+void
+stop_marker ()
+{
+  int a = 100;	/* Final breakpoint here.  */
+}
+
+/* A breakpoint condition function that always returns true.  */
+int
+condition_true_func ()
+{
+  return condition_core_func (1);
+}
+
+/* A breakpoint condition function that always returns false.  */
+int
+condition_false_func ()
+{
+  return condition_core_func (0);
+}
+
+void *
+worker_func (void *arg)
+{
+  volatile int *ptr = 0;
+  int tid = *((int *) arg);
+
+  switch (tid)
+    {
+    case 0:
+      global_var_0 = 11;	/* First thread breakpoint.  */
+      break;
+
+    case 1:
+      if (pthread_mutex_lock (&mutex) != 0)
+	abort ();
+      if (raise_signal)
+	global_var_1 = *ptr;	/* Signal here.  */
+      else
+	global_var_1 = 99;	/* Other thread breakpoint.  */
+      break;
+
+    default:
+      abort ();
+    }
+
+  return NULL;
+}
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+
+  /* Set an alarm, just in case the test deadlocks.  */
+  alarm (300);
+
+  /* We want the mutex to start locked.  */
+  if (pthread_mutex_lock (&mutex) != 0)
+    abort ();
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      void *retval;
+      pthread_join (threads[i], &retval);
+    }
+
+  /* Unlock once we're done, just for cleanliness.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
new file mode 100644
index 00000000000..0c8ef728009
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
@@ -0,0 +1,175 @@
+# Copyright 2022 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/>.
+
+# Test for conditional breakpoints where the breakpoint condition includes
+# an inferior function call.
+#
+# The tests in this script are testing what happens when an event arrives in
+# another thread while GDB is waiting for the inferior function call (in the
+# breakpoint condition) to finish.
+#
+# The expectation is that GDB will queue events for other threads and wait
+# for the inferior function call to complete, if the condition is true, then
+# the conditional breakpoint should be reported first.  The other thread
+# event should of course, not get lost, and should be reported as soon as
+# the user tries to continue the inferior.
+#
+# If the conditional breakpoint ends up not being taken (the condition is
+# false), then the other thread event should be reported immediately.
+#
+# This script tests what happens when the other thread event is (a) the
+# other thread hitting a breakpoint, and (b) the other thread taking a
+# signal (SIGSEGV in this case).
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] == -1 } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "First thread breakpoint"]
+set other_bp_line [gdb_get_line_number "Other thread breakpoint"]
+set final_bp_line [gdb_get_line_number "Final breakpoint here"]
+set signal_line [gdb_get_line_number "Signal here"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if {![runto_main]} {
+	fail "run to main"
+	return -1
+    }
+
+    return 0
+}
+
+# Run a test of GDB's conditional breakpoints, where the conditions include
+# inferior function calls.  While the inferior function call is executing
+# another thread will hit a breakpoint (when OTHER_THREAD_SIGNAL is false),
+# or receive a signal (when OTHER_THREAD_SIGNAL is true).  GDB should report
+# the conditional breakpoint first (if the condition is true), and then
+# report the second thread event once the inferior is continued again.
+#
+# When STOP_AT_COND is true then the conditional breakpoint will have a
+# condition that evaluates to true (and the GDB will stop at the
+# breakpoint), otherwise, the condition will evaluate to false (and GDB will
+# not stop at the breakpoint).
+proc run_condition_test { stop_at_cond other_thread_signal \
+			      target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint.
+    if { $stop_at_cond } {
+	set cond_func "condition_true_func"
+    } else {
+	set cond_func "condition_false_func"
+    }
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (${cond_func} ())"
+    set cond_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			"get number for conditional breakpoint"]
+
+    if { $other_thread_signal } {
+	# Arrange for the other thread to raise a signal while GDB is
+	# evaluating the breakpoint condition.
+	gdb_test_no_output "set raise_signal = 1"
+    } else {
+	# And a breakpoint that will be hit by another thread only once the
+	# breakpoint condition starts to be evaluated.
+	gdb_breakpoint "${::srcfile}:${::other_bp_line}"
+	set other_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			      "get number for other breakpoint"]
+    }
+
+    # A final breakpoint once the test has completed.
+    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
+    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			  "get number for final breakpoint"]
+
+    if { $stop_at_cond } {
+	# Continue.  The first breakpoint we hit should be the conditional
+	# breakpoint.  The other thread will have hit its breakpoint, but
+	# that will have been deferred until the conditional breakpoint is
+	# reported.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${cond_bp_num}, worker_func \[^\r\n\]+:${::cond_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+First thread breakpoint\[^\r\n\]+"] \
+	    "hit the conditional breakpoint"
+    }
+
+    if { $other_thread_signal } {
+	# Now continue again, the other thread will now report that it
+	# received a signal.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" received signal SIGSEGV, Segmentation fault\\." \
+		 "\\\[Switching to Thread \[^\r\n\]+\\\]" \
+		 "${::hex} in worker_func \[^\r\n\]+:${::signal_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Signal here\[^\r\n\]+"] \
+	    "received signal in other thread"
+    } else {
+	# Now continue again, the other thread will now report its
+	# breakpoint.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${other_bp_num}, worker_func \[^\r\n\]+:${::other_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Other thread breakpoint\[^\r\n\]+"] \
+	    "hit the breakpoint in other thread"
+
+	# Run to the stop marker.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${final_bp_num}, stop_marker \[^\r\n\]+:${::final_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Final breakpoint here\[^\r\n\]+"] \
+	    "hit the final breakpoint"
+    }
+
+    gdb_exit
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	foreach_with_prefix other_thread_signal { true false } {
+	    foreach_with_prefix stop_at_cond { true false } {
+		run_condition_test $stop_at_cond $other_thread_signal \
+		    $target_async $target_non_stop
+	    }
+	}
+    }
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
new file mode 100644
index 00000000000..f2a24a52b01
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
@@ -0,0 +1,89 @@
+/* Copyright 2022 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 <pthread.h>
+#include <unistd.h>
+
+#define NUM_THREADS 3
+
+int
+is_matching_tid (int *tid_ptr, int tid_value)
+{
+  return *tid_ptr == tid_value;
+}
+
+int
+return_true ()
+{
+  return 1;
+}
+
+int
+return_false ()
+{
+  return 0;
+}
+
+int
+function_that_segfaults ()
+{
+  int *p = 0;
+  *p = 1;	/* Segfault happens here.   */
+}
+
+int
+function_with_breakpoint ()
+{
+  return 1;	/* Nested breakpoint.  */
+}
+
+void *
+worker_func (void *arg)
+{
+  int a = 42;	/* Breakpoint here.  */
+}
+
+void
+stop_marker ()
+{
+  int b = 99;	/* Stop marker.  */
+}
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+
+  alarm (300);
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      void *retval;
+      pthread_join (threads[i], &retval);
+    }
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
new file mode 100644
index 00000000000..8d94d24f9b3
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
@@ -0,0 +1,236 @@
+# Copyright 2022 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/>.
+
+# Some simple tests of inferior function calls from breakpoint
+# conditions, in multi-threaded inferiors.
+#
+# This test sets up a multi-threaded inferior, and places a breakpoint
+# at a location that many of the threads will reach.  We repeat the
+# test with different conditions, sometimes a single thread should
+# stop at the breakpoint, sometimes multiple threads should stop, and
+# sometime no threads should stop.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] == -1 } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "Breakpoint here"]
+set stop_bp_line [gdb_get_line_number "Stop marker"]
+set nested_bp_line [gdb_get_line_number "Nested breakpoint"]
+set segv_line [gdb_get_line_number "Segfault happens here"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if {![runto_main]} {
+	fail "run to main"
+	return -1
+    }
+
+    return 0
+}
+
+# Run a test of GDB's conditional breakpoints, where the conditions include
+# inferior function calls.
+#
+# CONDITION is combined (with &&) to some additional logic, and used as the
+# breakpoint condition.
+#
+# N_EXPECTED_HITS is the number of threads that we expect to stop due to
+# CONDITON.
+#
+# MESSAGE is used as a test name prefix.
+proc run_condition_test { message n_expected_hits condition \
+			      target_async target_non_stop } {
+    with_test_prefix $message {
+
+	if { [start_gdb_and_runto_main $target_async \
+		  $target_non_stop] == -1 } {
+	    return
+	}
+
+	# Use this convenience variable to track how often the
+	# breakpoint condition has been evaluated, this should be once
+	# per thread.
+	gdb_test "set \$n_cond_eval = 0"
+
+	# Setup the conditional breakpoint.
+	gdb_breakpoint \
+	    "${::srcfile}:${::cond_bp_line} if ((++\$n_cond_eval) ${condition})"
+
+	# And a breakpoint that we hit when the test is over, this one is
+	# not conditional.  Only the main thread gets here once all the
+	# other threads have finished.
+	gdb_breakpoint "${::srcfile}:${::stop_bp_line}"
+
+	# The number of times we stop at the conditional breakpoint.
+	set n_hit_condition 0
+
+	# Now keep 'continue'-ing GDB until all the threads have finished
+	# and we reach the stop_marker breakpoint.
+	gdb_test_multiple "continue" "spot all breakpoint hits" {
+	    -re " worker_func \[^\r\n\]+${::srcfile}:${::cond_bp_line}\r\n${::decimal}\\s+\[^\r\n\]+Breakpoint here\[^\r\n\]+\r\n${::gdb_prompt} $" {
+		incr n_hit_condition
+		send_gdb "continue\n"
+		exp_continue
+	    }
+
+	    -re " stop_marker \[^\r\n\]+${::srcfile}:${::stop_bp_line}\r\n${::decimal}\\s+\[^\r\n\]+Stop marker\[^\r\n\]+\r\n${::gdb_prompt} $" {
+		pass $gdb_test_name
+	    }
+	}
+
+	gdb_assert { $n_hit_condition == $n_expected_hits } \
+	    "stopped at breakpoint the expected number of times"
+
+	# Ensure the breakpoint condition was evaluated once per thread.
+	gdb_test "print \$n_cond_eval" "= 3" "condition was evaluated twice"
+    }
+}
+
+# Check that after handling a conditional breakpoint (where the condition
+# includes an inferior call), it is still possible to kill the running
+# inferior, and then restart the inferior.
+#
+# At once point doing this would result in GDB giving an assertion error.
+proc_with_prefix run_kill_and_restart_test { target_async target_non_stop } {
+    # This test relies on the 'start' command, which is not possible with
+    # the plain 'remote' target.
+    if {[target_info gdb_protocol] == "remote"} {
+	return
+    }
+
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint.
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 1))"
+    gdb_continue_to_breakpoint "worker_func"
+
+    # Now kill the program being debugged.
+    gdb_test "kill" "" "kill process" \
+	"Kill the program being debugged.*y or n. $" "y"
+
+    # Check we can restart the inferior.  At one point this would trigger an
+    # assertion.
+    gdb_test "start" ".*"
+}
+
+# Create a conditional breakpoint which includes a call to a function that
+# segfaults.  Run GDB and check what happens when the inferior segfaults
+# during the inferior call.
+proc_with_prefix run_bp_cond_segfaults { target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # This test relies on the inferior segfaulting when trying to
+    # access address zero.
+    if { [is_address_zero_readable] } {
+	return
+    }
+
+    # Setup the conditional breakpoint, include a call to
+    # 'function_that_segfaults', which triggers the segfault.
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 0) && function_that_segfaults ())"
+    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of conditional breakpoint"]
+
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     ".*" \
+	     "Thread ${::decimal} \"infcall-from-bp\" received signal SIGSEGV, Segmentation fault\\." \
+	     "${::hex} in function_that_segfaults \\(\\) at \[^\r\n\]+:${::segv_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Segfault happens here\[^\r\n\]+" \
+	     "Error in testing condition for breakpoint ${bp_1_num}:" \
+	     "The program being debugged was signaled while in a function called from GDB\\." \
+	     "GDB remains in the frame where the signal was received\\." \
+	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(function_that_segfaults\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+}
+
+# Create a conditional breakpoint which includes a call to a function that
+# itself has a breakpoint set within it.  Run GDB and check what happens
+# when GDB hits the nested breakpoint.
+proc_with_prefix run_bp_cond_hits_breakpoint { target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint, include a call to
+    # 'function_with_breakpoint' in which we will shortly place a
+    # breakpoint.
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 0) && function_with_breakpoint ())"
+    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of conditional breakpoint"]
+
+    gdb_breakpoint "${::srcfile}:${::nested_bp_line}"
+    set bp_2_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of nested breakpoint"]
+
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     ".*" \
+	     "Thread ${::decimal} \"infcall-from-bp\" hit Breakpoint ${bp_2_num}, function_with_breakpoint \\(\\) at \[^\r\n\]+:${::nested_bp_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Nested breakpoint\[^\r\n\]+" \
+	     "Error in testing condition for breakpoint ${bp_1_num}:" \
+	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(function_with_breakpoint\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	run_condition_test "exactly one thread is hit" \
+	    1 "&& is_matching_tid (arg, 1)" \
+	    $target_async $target_non_stop
+	run_condition_test "exactly two threads are hit" \
+	    2 "&& (is_matching_tid (arg, 0) || is_matching_tid (arg, 2))" \
+	    $target_async $target_non_stop
+	run_condition_test "all three threads are hit" \
+	    3 "|| return_true ()" \
+	    $target_async $target_non_stop
+	run_condition_test "no thread is hit" \
+	    0 "&& return_false ()" \
+	    $target_async $target_non_stop
+
+	run_kill_and_restart_test $target_async $target_non_stop
+	run_bp_cond_segfaults $target_async $target_non_stop
+	run_bp_cond_hits_breakpoint $target_async $target_non_stop
+    }
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
new file mode 100644
index 00000000000..c87f1f2bfc6
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
@@ -0,0 +1,139 @@
+/* Copyright 2022 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 <pthread.h>
+#include <unistd.h>
+#include <semaphore.h>
+#include <stdlib.h>
+
+#define NUM_THREADS 5
+
+/* Semaphores, used to track when threads have started, and to control
+   when the threads finish.  */
+sem_t startup_semaphore;
+sem_t finish_semaphore;
+
+/* Mutex to control when the first worker thread hit a breakpoint
+   location.  */
+pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+
+/* Global variable to poke, just so threads have something to do.  */
+volatile int global_var = 0;
+
+int
+return_true ()
+{
+  return 1;
+}
+
+int
+return_false ()
+{
+  return 0;
+}
+
+void *
+worker_func (void *arg)
+{
+  int tid = *((int *) arg);
+
+  switch (tid)
+    {
+    case 0:
+      /* Wait for MUTEX to become available, then pass through the
+	 conditional breakpoint location.  */
+      if (pthread_mutex_lock (&mutex) != 0)
+	abort ();
+      global_var = 99;	/* Conditional breakpoint here.  */
+      if (pthread_mutex_unlock (&mutex) != 0)
+	abort ();
+      break;
+
+    default:
+      /* Notify the main thread that the thread has started, then wait for
+	 the main thread to tell us to finish.  */
+      sem_post (&startup_semaphore);
+      if (sem_wait (&finish_semaphore) != 0)
+	abort ();
+      break;
+    }
+}
+
+void
+stop_marker ()
+{
+  global_var = 99;	/* Stop marker.  */
+}
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+  void *retval;
+
+  /* An alarm, just in case the thread deadlocks.  */
+  alarm (300);
+
+  /* Semaphore initialization.  */
+  if (sem_init (&startup_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&finish_semaphore, 0, 0) != 0)
+    abort ();
+
+  /* Lock MUTEX, this prevents the first worker thread from rushing ahead.  */
+  if (pthread_mutex_lock (&mutex) != 0)
+    abort ();
+
+  /* Worker thread creation.  */
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  /* Wait for every thread (other than the first) to tell us it has started
+     up.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    {
+      if (sem_wait (&startup_semaphore) != 0)
+	abort ();
+    }
+
+  /* Unlock the first thread so it can proceed.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  /* Wait for the first thread only.  */
+  pthread_join (threads[0], &retval);
+
+  /* Now post FINISH_SEMAPHORE to allow all the other threads to finish.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    sem_post (&finish_semaphore);
+
+  /* Now wait for the remaining threads to complete.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    pthread_join (threads[i], &retval);
+
+  /* Semaphore cleanup.  */
+  sem_destroy (&finish_semaphore);
+  sem_destroy (&startup_semaphore);
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
new file mode 100644
index 00000000000..aa1e94190cd
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
@@ -0,0 +1,119 @@
+# Copyright 2022 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 reprocuces bug gdb/28942, performing an inferior function
+# call from a breakpoint condition in a multi-threaded inferior.
+#
+# The important part of this test is that, when the conditional
+# breakpoint is hit, and the condition (which includes an inferior
+# function call) is evaluated, the other threads are running.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] == -1 } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "Conditional breakpoint here"]
+set final_bp_line [gdb_get_line_number "Stop marker"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if {![runto_main]} {
+	fail "run to main"
+	return -1
+    }
+
+    return 0
+}
+
+# Run a test of GDB's conditional breakpoints, where the conditions include
+# inferior function calls.
+#
+# CONDITION is combined (with &&) to some additional logic, and used as the
+# breakpoint condition.
+#
+# N_EXPECTED_HITS is the number of threads that we expect to stop due to
+# CONDITON.
+#
+# MESSAGE is used as a test name prefix.
+proc run_condition_test { stop_at_cond \
+			      target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint.
+    if { $stop_at_cond } {
+	set cond_func "return_true"
+    } else {
+	set cond_func "return_false"
+    }
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (${cond_func} ())"
+    set cond_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			"get number for conditional breakpoint"]
+
+    # And a breakpoint that we hit when the test is over, this one is
+    # not conditional.
+    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
+    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			  "get number for final breakpoint"]
+
+    if { $stop_at_cond } {
+	# Continue.  The first breakpoint we hit should be the conditional
+	# breakpoint.  The other thread will have hit its breakpoint, but
+	# that will have been deferred until the conditional breakpoint is
+	# reported.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${cond_bp_num}, worker_func \[^\r\n\]+:${::cond_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Conditional breakpoint here\[^\r\n\]+"] \
+	    "hit the conditional breakpoint"
+    }
+
+    # Run to the stop marker.
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     ".*" \
+	     "" \
+	     "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${final_bp_num}, stop_marker \[^\r\n\]+:${::final_bp_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Stop marker\[^\r\n\]+"] \
+	"hit the final breakpoint"
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	foreach_with_prefix stop_at_cond { true false } {
+	    run_condition_test $stop_at_cond \
+		$target_async $target_non_stop
+	}
+    }
+}
-- 
2.25.4


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

* [PATCHv2 10/13] gdb: add timeouts for inferior function calls
  2023-01-18 16:17 ` [PATCHv2 00/13] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                     ` (8 preceding siblings ...)
  2023-01-18 16:18   ` [PATCHv2 09/13] gdb: fix b/p conditions with infcalls in multi-threaded inferiors Andrew Burgess
@ 2023-01-18 16:18   ` Andrew Burgess
  2023-01-18 17:30     ` Eli Zaretskii
  2023-01-20  8:50     ` Aktemur, Tankut Baris
  2023-01-18 16:18   ` [PATCHv2 11/13] gdb/remote: avoid SIGINT after calling remote_target::stop Andrew Burgess
                     ` (4 subsequent siblings)
  14 siblings, 2 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-01-18 16:18 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

In the previous commits I have been working on improving inferior
function call support.  One thing that worries me about using inferior
function calls from a conditional breakpoint is: what happens if the
inferior function call fails?

If the failure is obvious, e.g. the thread performing the call
crashes, or hits a breakpoint, then this case is already well handled,
and the error is reported to the user.

But what if the thread performing the inferior call just deadlocks?
If the user made the call from a 'print' or 'call' command, then the
user might have some expectation of when the function call should
complete, and, when this time limit is exceeded, the user
will (hopefully) interrupt GDB and regain control of the debug
session.

But, when the inferior function call is from a breakpoint condition it
is much harder to understand that GDB is deadlocked within an inferior
call.  Maybe the breakpoint hasn't been hit yet?  Or maybe the
condition was always false?  Or maybe GDB is deadlocked in an inferior
call?  The only way to know for sure is to periodically interrupt GDB,
check on all the threads, and then continue.

Additionally, the focus of the previous commit was inferior function
calls, from a conditional breakpoint, in a multi-threaded inferior.
This opens up a whole new set of potential failure conditions.  For
example, what if the function called relies on interaction with some
other thread, and the other thread crashes?  Or hits a breakpoint?
Given how inferior function calls work - in a synchronous manor, a
stop event in some other thread is going to be ignored when the
inferior function call is being done as part of a breakpoint
condition, and this means that GDB could get stuck waiting for the
original condition thread, which will now never complete.

In this commit I propose a solution to this problem.  A timeout.  For
targets that support async-mode we can install an event-loop timer
before starting the inferior function call.  When the timer expires we
will stop the thread performing the inferior function call.  With this
mechanism in place a user can be sure that any inferior call they make
will either complete, or timeout eventually.

Adding a timer like this is obviously a change in behaviour for the
more common 'call' and 'print' uses of inferior function calls, so, in
this patch, I propose having two different timers.  One I call the
'direct-call-timeout', which is used for 'call' and 'print' commands.
This timeout is by default set to unlimited, which, not surprisingly,
means there is no timeout in place.

A second timer, which I've called 'indirect-call-timeout', is used for
inferior function calls from breakpoint conditions.  This timeout has
a default value of 300 seconds.  This is still a pretty substantial
time to be waiting for a single inferior call to complete, but I
didn't want to be too aggressive with the value I selected.  A user
can, of course, still use Ctrl-c to interrupt an inferior function
call, but this limit will ensure that GDB will stop at some point.

The new commands added by this commit are:

  set direct-call-timeout SECONDS
  show direct-call-timeout
  set indirect-call-timeout SECONDS
  show indirect-call-timeout

These new timeouts do depend on async-mode, so, if async-mode is
disabled (maint set target-async off), or not supported (e.g. target
sim), then the timeout is treated as unlimited (that is, no timeout is
set).

For targets that "fake" non-async mode, e.g. Linux native, where
non-async mode is really just async mode, but then we park the target
in a sissuspend, we could easily fix things so that the timeouts still
work, however, for targets that really are not async aware, like the
simulator, fixing things so that timeouts work correctly would be a
much bigger task - that effort would be better spent just making the
target async-aware.  And so, I'm happy for now that this feature will
only work on async targets.

The two new show commands will display slightly different text if the
current target is a non-async target, which should allow users to
understand what's going on.

There's a somewhat random test adjustment needed in gdb.base/help.exp,
the test uses a regexp with the apropos command, and expects to find a
single result.  Turns out the new settings I added also matched the
regexp, which broke the test.  I've updated the regexp a little to
exclude my new settings.
---
 gdb/NEWS                                      |  18 ++
 gdb/doc/gdb.texinfo                           |  66 ++++++
 gdb/infcall.c                                 | 210 +++++++++++++++++-
 gdb/testsuite/gdb.base/help.exp               |   2 +-
 gdb/testsuite/gdb.base/infcall-timeout.c      |  36 +++
 gdb/testsuite/gdb.base/infcall-timeout.exp    |  82 +++++++
 .../infcall-from-bp-cond-timeout.c            | 169 ++++++++++++++
 .../infcall-from-bp-cond-timeout.exp          | 156 +++++++++++++
 8 files changed, 734 insertions(+), 5 deletions(-)
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.c
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp

diff --git a/gdb/NEWS b/gdb/NEWS
index c0aac212e30..2689569a8f3 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -17,6 +17,24 @@ maintenance print record-instruction [ N ]
   prints how GDB would undo the N-th previous instruction, and if N is
   positive, it prints how GDB will redo the N-th following instruction.
 
+set direct-call-timeout SECONDS
+show direct-call-timeout
+set indirect-call-timeout SECONDS
+show indirect-call-timeout
+  These new settings can be used to limit how long GDB will wait for
+  an inferior function call to complete.  The direct timeout is used
+  for inferior function calls from e.g. 'call' and 'print' commands,
+  while the indirect timeout is used for inferior function calls from
+  within a conditional breakpoint expression.
+
+  The default for the direct timeout is unlimited, while the default
+  for the indirect timeout is 30 seconds.
+
+  These timeouts will only have an effect for targets that are
+  operating in async mode.  For non-async targets the timeouts are
+  ignored, GDB will wait indefinitely for an inferior function to
+  complete, unless interrupted by the user using Ctrl-C.
+
 * MI changes
 
 ** mi now reports 'no-history' as a stop reason when hitting the end of the
diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index 6ea173b5d0b..9eb8b1db00e 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -20772,6 +20772,72 @@
 @code{step}, etc).  In this case, when the inferior finally returns to
 the dummy-frame, @value{GDBN} will once again halt the inferior.
 
+On targets that support asynchronous execution (@pxref{Background
+Execution}) @value{GDBN} can place a timeout on any functions called
+from @value{GDBN}.  If the timeout expires and the function call is
+still ongoing, then @value{GDBN} will interrupt the program.
+
+For targets that don't support asynchronous execution
+(@pxref{Background Execution}) then timeouts for functions called from
+@value{GDBN} are not supported, the timeout settings described below
+will be treated as @code{unlimited}, meaning @value{GDBN} will wait
+indefinitely for function call to complete, unless interrupted by the
+user using @kbd{Ctrl-C}.
+
+@table @code
+@item set direct-call-timeout @var{seconds}
+@kindex set direct-call-timeout
+@cindex timeout for called functions
+Set the timeout used when calling functions in the program to
+@var{seconds}, which should be an integer greater than zero, or the
+special value @code{unlimited}, which indicates no timeout should be
+used.  The default for this setting is @code{unlimited}.
+
+This setting is used when the user calls a function directly from the
+command prompt, for example with a @code{call} or @code{print}
+command.
+
+This setting only works for targets that support asynchronous
+execution (@pxref{Background Execution}), for any other target the
+setting is treated as @code{unlimited}.
+
+@item show direct-call-timeout
+@kindex show direct-call-timeout
+@cindex timeout for called functions
+Show the timeout used when calling functions in the program with a
+@code{call} or @code{print} command.
+@end table
+
+It is also possible to call functions within the program from the
+condition of a conditional breakpoint (@pxref{Conditions, ,Break
+Conditions}).  A different setting controls the timeout used for
+function calls made from a breakpoint condition.
+
+@table @code
+@item set indirect-call-timeout @var{seconds}
+@kindex set indirect-call-timeout
+@cindex timeout for called functions
+Set the timeout used when calling functions in the program from a
+breakpoint or watchpoint condition to @var{seconds}, which should be
+an integer greater than zero, or the special value @code{unlimited},
+which indicates no timeout should be used.  The default for this
+setting is @code{30} seconds.
+
+This setting only works for targets that support asynchronous
+execution (@pxref{Background Execution}), for any other target the
+setting is treated as @code{unlimited}.
+
+If a function called from a breakpoint or watchpoint condition times
+out, then @value{GDBN} will stop at the point where the timeout
+occurred.  The breakpoint condition evaluation will be abandoned.
+
+@item show indirect-call-timeout
+@kindex show indirect-call-timeout
+@cindex timeout for called functions
+Show the timeout used when calling functions in the program from a
+breakpoint or watchpoint condition.
+@end table
+
 @subsection Calling functions with no debug info
 
 @cindex no debug info functions
diff --git a/gdb/infcall.c b/gdb/infcall.c
index 8a48909bc2c..9afca4f5bc6 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -95,6 +95,53 @@ show_may_call_functions_p (struct ui_file *file, int from_tty,
 	      value);
 }
 
+/* A timeout (in seconds) for direct inferior calls.  A direct inferior
+   call is one the user triggers from the prompt, e.g. with a 'call' or
+   'print' command.  Compare with the definition of indirect calls below.  */
+
+static unsigned int direct_call_timeout = UINT_MAX;
+
+/* Implement 'show direct-call-timeout'.  */
+
+static void
+show_direct_call_timeout (struct ui_file *file, int from_tty,
+			  struct cmd_list_element *c, const char *value)
+{
+  if (target_has_execution () && !target_can_async_p ())
+    gdb_printf (file, _("Current target does not support async mode, timeout "
+			"for direct inferior calls is \"unlimited\".\n"));
+  else if (direct_call_timeout == UINT_MAX)
+    gdb_printf (file, _("Timeout for direct inferior function calls "
+			"is \"unlimited\".\n"));
+  else
+    gdb_printf (file, _("Timeout for direct inferior function calls "
+			"is \"%s seconds\".\n"), value);
+}
+
+/* A timeout (in seconds) for indirect inferior calls.  An indirect inferior
+   call is one that originates from within GDB, for example, when
+   evaluating an expression for a conditional breakpoint.  Compare with
+   the definition of direct calls above.  */
+
+static unsigned int indirect_call_timeout = 30;
+
+/* Implement 'show indirect-call-timeout'.  */
+
+static void
+show_indirect_call_timeout (struct ui_file *file, int from_tty,
+			  struct cmd_list_element *c, const char *value)
+{
+  if (target_has_execution () && !target_can_async_p ())
+    gdb_printf (file, _("Current target does not support async mode, timeout "
+			"for indirect inferior calls is \"unlimited\".\n"));
+  else if (indirect_call_timeout == UINT_MAX)
+    gdb_printf (file, _("Timeout for indirect inferior function calls "
+			"is \"unlimited\".\n"));
+  else
+    gdb_printf (file, _("Timeout for indirect inferior function calls "
+			"is \"%s seconds\".\n"), value);
+}
+
 /* How you should pass arguments to a function depends on whether it
    was defined in K&R style or prototype style.  If you define a
    function using the K&R syntax that takes a `float' argument, then
@@ -589,6 +636,85 @@ call_thread_fsm::should_notify_stop ()
   return true;
 }
 
+/* A class to control creation of a timer that will interrupt a thread
+   during an inferior call.  */
+struct infcall_timer_controller
+{
+  /* Setup an event-loop timer that will interrupt PTID if the inferior
+     call takes too long.  DIRECT_CALL_P is true when this inferior call is
+     a result of the user using a 'print' or 'call' command, and false when
+     this inferior call is a result of e.g. a conditional breakpoint
+     expression, this is used to select which timeout to use.  */
+  infcall_timer_controller (ptid_t ptid, bool direct_call_p)
+    : m_ptid (ptid)
+  {
+    unsigned int timeout
+      = direct_call_p ? direct_call_timeout : indirect_call_timeout;
+    if (timeout < UINT_MAX && target_can_async_p ())
+      {
+	int ms = timeout * 1000;
+	int id = create_timer (ms, infcall_timer_controller::timed_out, this);
+	m_timer_id.emplace (id);
+	infcall_debug_printf ("Setting up infcall timeout timer for "
+			      "ptid %s: %d milliseconds",
+			      m_ptid.to_string ().c_str (), ms);
+      }
+  }
+
+  /* Destructor.  Ensure that the timer is removed from the event loop.  */
+  ~infcall_timer_controller ()
+  {
+    /* If the timer has already triggered, then it will have already been
+       deleted from the event loop.  If the timer has not triggered, then
+       delete it now.  */
+    if (m_timer_id.has_value () && !m_triggered)
+      delete_timer (*m_timer_id);
+
+    /* Just for clarity, discard the timer id now.  */
+    m_timer_id.reset ();
+  }
+
+  /* Return true if there was a timer in place, and the timer triggered,
+     otherwise, return false.  */
+  bool triggered_p ()
+  {
+    gdb_assert (!m_triggered || m_timer_id.has_value ());
+    return m_triggered;
+  }
+
+private:
+  /* The thread we should interrupt.  */
+  ptid_t m_ptid;
+
+  /* Set true when the timer is triggered.  */
+  bool m_triggered = false;
+
+  /* Given a value when a timer is in place.  */
+  gdb::optional<int> m_timer_id;
+
+  /* Callback for the timer, forwards to ::trigger below.  */
+  static void
+  timed_out (gdb_client_data context)
+  {
+    infcall_timer_controller *ctrl
+      = static_cast<infcall_timer_controller *> (context);
+    ctrl->trigger ();
+  }
+
+  /* Called when the timer goes off.  Stop thread m_ptid.  */
+  void
+  trigger ()
+  {
+    m_triggered = true;
+
+    scoped_disable_commit_resumed disable_commit_resumed ("infcall timeout");
+
+    infcall_debug_printf ("Stopping thread %s",
+			  m_ptid.to_string ().c_str ());
+    target_stop (m_ptid);
+  }
+};
+
 /* Subroutine of call_function_by_hand to simplify it.
    Start up the inferior and wait for it to stop.
    Return the exception if there's an error, or an exception with
@@ -599,13 +725,15 @@ call_thread_fsm::should_notify_stop ()
 
 static struct gdb_exception
 run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
-		   struct thread_info *call_thread, CORE_ADDR real_pc)
+		   struct thread_info *call_thread, CORE_ADDR real_pc,
+		   bool *timed_out_p)
 {
   INFCALL_SCOPED_DEBUG_ENTER_EXIT;
 
   struct gdb_exception caught_error;
   ptid_t call_thread_ptid = call_thread->ptid;
   int was_running = call_thread->state == THREAD_RUNNING;
+  *timed_out_p = false;
 
   infcall_debug_printf ("call function at %s in thread %s, was_running = %d",
 			core_addr_to_string (real_pc),
@@ -650,11 +778,23 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
       infrun_debug_show_threads ("non-exited threads after proceed for inferior-call",
 				 all_non_exited_threads ());
 
+      /* Setup a timer (if possible, and if the settings allow) to prevent
+	 the inferior call running forever.  */
+      bool direct_call_p = !call_thread->control.in_cond_eval;
+      infcall_timer_controller infcall_timer (inferior_ptid, direct_call_p);
+
       /* Inferior function calls are always synchronous, even if the
 	 target supports asynchronous execution.  */
       wait_sync_command_done ();
 
-      infcall_debug_printf ("inferior call completed successfully");
+      /* If the timer triggered then the inferior call failed.  */
+      if (infcall_timer.triggered_p ())
+	{
+	  infcall_debug_printf ("inferior call timed out");
+	  *timed_out_p = true;
+	}
+      else
+	infcall_debug_printf ("inferior call completed successfully");
     }
   catch (gdb_exception &e)
     {
@@ -1311,6 +1451,10 @@ call_function_by_hand_dummy (struct value *function,
   scoped_restore restore_stopped_by_random_signal
     = make_scoped_restore (&stopped_by_random_signal, 0);
 
+  /* Set to true by the call to run_inferior_call below if the inferior
+     call is artificially interrupted by GDB due to taking too long.  */
+  bool timed_out_p = false;
+
   /* - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP -
      If you're looking to implement asynchronous dummy-frames, then
      just below is the place to chop this function in two..  */
@@ -1337,7 +1481,8 @@ call_function_by_hand_dummy (struct value *function,
 			      struct_addr);
     {
       std::unique_ptr<call_thread_fsm> sm_up (sm);
-      e = run_inferior_call (std::move (sm_up), call_thread.get (), real_pc);
+      e = run_inferior_call (std::move (sm_up), call_thread.get (), real_pc,
+			     &timed_out_p);
     }
 
     if (e.reason < 0)
@@ -1489,7 +1634,10 @@ When the function is done executing, GDB will silently stop."),
       std::string name = get_function_name (funaddr, name_buf,
 					    sizeof (name_buf));
 
-      if (stopped_by_random_signal)
+      /* If the inferior call timed out then it will have been interrupted
+	 by a signal, but we want to report this differently to the user,
+	 which is done later in this function.  */
+      if (stopped_by_random_signal && !timed_out_p)
 	{
 	  /* We stopped inside the FUNCTION because of a random
 	     signal.  Further execution of the FUNCTION is not
@@ -1533,6 +1681,36 @@ GDB remains in the frame where the signal was received.\n\
 To change this behavior use \"set unwindonsignal on\".\n\
 Evaluation of the expression containing the function\n\
 (%s) will be abandoned.\n\
+When the function is done executing, GDB will silently stop."),
+		     name.c_str ());
+	    }
+	}
+
+      if (timed_out_p)
+	{
+	  /* A timeout results in a signal being sent to the inferior.  */
+	  gdb_assert (stopped_by_random_signal);
+
+	  /* Indentation is weird here.  A later patch is going to move the
+	    following block into an if/else, so I'm leaving the indentation
+	    here to minimise the later patch.
+
+	    Also, the error message used below refers to 'set
+	    unwind-on-timeout' which doesn't exist yet.  This will be added
+	    in a later commit, I'm leaving this in for now to minimise the
+	    churn caused by the commit that adds unwind-on-timeout.  */
+	    {
+	      /* The user wants to stay in the frame where we stopped
+		 (default).  Discard inferior status, we're not at the same
+		 point we started at.  */
+	      discard_infcall_control_state (inf_status.release ());
+
+	      error (_("\
+The program being debugged timed out while in a function called from GDB.\n\
+GDB remains in the frame where the timeout occurred.\n\
+To change this behavior use \"set unwind-on-timeout on\".\n\
+Evaluation of the expression containing the function\n\
+(%s) will be abandoned.\n\
 When the function is done executing, GDB will silently stop."),
 		     name.c_str ());
 	    }
@@ -1646,6 +1824,30 @@ The default is to unwind the frame."),
 			   show_unwind_on_terminating_exception_p,
 			   &setlist, &showlist);
 
+  add_setshow_uinteger_cmd ("direct-call-timeout", no_class,
+			    &direct_call_timeout, _("\
+Set the timeout, for direct calls to inferior function calls."), _("\
+Show the timeout, for direct calls to inferior function calls."), _("\
+If running on a target that supports, and is running in, async mode\n\
+then this timeout is used for any inferior function calls triggered\n\
+directly from the prompt, i.e. from a 'call' or 'print' command.  The\n\
+timeout is specified in seconds."),
+			    nullptr,
+			    show_direct_call_timeout,
+			    &setlist, &showlist);
+
+  add_setshow_uinteger_cmd ("indirect-call-timeout", no_class,
+			    &indirect_call_timeout, _("\
+Set the timeout, for indirect calls to inferior function calls."), _("\
+Show the timeout, for indirect calls to inferior function calls."), _("\
+If running on a target that supports, and is running in, async mode\n\
+then this timeout is used for any inferior function calls triggered\n\
+indirectly, i.e. being made as part of a breakpoint, or watchpoint,\n\
+condition expression.  The timeout is specified in seconds."),
+			    nullptr,
+			    show_indirect_call_timeout,
+			    &setlist, &showlist);
+
   add_setshow_boolean_cmd
     ("infcall", class_maintenance, &debug_infcall,
      _("Set inferior call debugging."),
diff --git a/gdb/testsuite/gdb.base/help.exp b/gdb/testsuite/gdb.base/help.exp
index 87919a819ab..504bf90cc15 100644
--- a/gdb/testsuite/gdb.base/help.exp
+++ b/gdb/testsuite/gdb.base/help.exp
@@ -121,7 +121,7 @@ gdb_test "help info bogus-gdb-command" "Undefined info command: \"bogus-gdb-comm
 gdb_test "help gotcha" "Undefined command: \"gotcha\"\.  Try \"help\"\."
 
 # Test apropos regex.
-gdb_test "apropos \\\(print\[\^\[ bsiedf\\\".-\]\\\)" "handle -- Specify how to handle signals\."
+gdb_test "apropos \\\(print\[\^\[ bsiedf\\\"'.-\]\\\)" "handle -- Specify how to handle signals\."
 # Test apropos >1 word string.
 gdb_test "apropos handle signal" "handle -- Specify how to handle signals\."
 # Test apropos apropos.
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.c b/gdb/testsuite/gdb.base/infcall-timeout.c
new file mode 100644
index 00000000000..895e8a36d59
--- /dev/null
+++ b/gdb/testsuite/gdb.base/infcall-timeout.c
@@ -0,0 +1,36 @@
+/* Copyright 2022 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 <unistd.h>
+
+/* This function is called from GDB.  */
+int
+function_that_never_returns ()
+{
+  while (1)
+    sleep (1);
+
+  return 0;
+}
+
+int
+main ()
+{
+  alarm (300);
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.exp b/gdb/testsuite/gdb.base/infcall-timeout.exp
new file mode 100644
index 00000000000..a5b0111ed04
--- /dev/null
+++ b/gdb/testsuite/gdb.base/infcall-timeout.exp
@@ -0,0 +1,82 @@
+# Copyright 2022 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/>.
+
+# Test GDB's direct-call-timeout setting, that is, ensure that if an
+# inferior function call, invoked from e.g. a 'print' command, takes
+# too long, then GDB can interrupt it, and return control to the user.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug}] == -1 } {
+    return
+}
+
+# Start GDB according to TARGET_ASYNC and TARGET_NON_STOP, then adjust
+# the direct-call-timeout, and make an inferior function call that
+# will never return.  GDB should eventually timeout and stop the
+# inferior.
+proc_with_prefix run_test { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if {![runto_main]} {
+	fail "run to main"
+	return
+    }
+
+    gdb_test_no_output "set direct-call-timeout 5"
+
+    # When non-stop mode is off we get slightly different output from GDB.
+    if { [gdb_is_remote_or_extended_remote_target] && $target_non_stop == "off" } {
+	set stopped_line_pattern "Program received signal SIGINT, Interrupt\\."
+    } else {
+	set stopped_line_pattern "Program stopped\\."
+    }
+
+    gdb_test "print function_that_never_returns ()" \
+	[multi_line \
+	     $stopped_line_pattern \
+	     ".*" \
+	     "The program being debugged timed out while in a function called from GDB\\." \
+	     "GDB remains in the frame where the timeout occurred\\." \
+	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(function_that_never_returns\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+
+    gdb_test "bt" ".* function_that_never_returns .*<function called from gdb>.*"
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+
+    if { $target_async == "off" } {
+	# GDB can't timeout while waiting for a thread if the target
+	# runs with async-mode turned off; once the target is running
+	# GDB is effectively blocked until the target stops for some
+	# reason.
+	continue
+    }
+
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	run_test $target_async $target_non_stop
+    }
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
new file mode 100644
index 00000000000..3bd91d7377d
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
@@ -0,0 +1,169 @@
+/* This testcase is part of GDB, the GNU debugger.
+
+   Copyright 2022 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 <stdio.h>
+#include <pthread.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <semaphore.h>
+
+#define NUM_THREADS 5
+
+/* Semaphores, used to track when threads have started, and to control
+   when the threads finish.  */
+sem_t startup_semaphore;
+sem_t finish_semaphore;
+sem_t thread_1_semaphore;
+sem_t thread_2_semaphore;
+
+/* Mutex to control when the first worker thread hit a breakpoint
+   location.  */
+pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+
+/* Global variable to poke, just so threads have something to do.  */
+volatile int global_var = 0;
+
+int
+condition_func ()
+{
+  /* Let thread 2 run.  */
+  if (sem_post (&thread_2_semaphore) != 0)
+    abort ();
+
+  /* Wait for thread 2 to complete its actions.  */
+  if (sem_wait (&thread_1_semaphore) != 0)
+    abort ();
+
+  return 1;
+}
+
+void
+do_segfault ()
+{
+  volatile int *p = 0;
+  *p = 0;	/* Segfault here.  */
+}
+
+void *
+worker_func (void *arg)
+{
+  int tid = *((int *) arg);
+
+  /* Let the main thread know that this worker has started.  */
+  if (sem_post (&startup_semaphore) != 0)
+    abort ();
+
+  switch (tid)
+    {
+    case 0:
+      /* Wait for MUTEX to become available, then pass through the
+	 conditional breakpoint location.  */
+      if (pthread_mutex_lock (&mutex) != 0)
+	abort ();
+      global_var = 99;	/* Conditional breakpoint here.  */
+      if (pthread_mutex_unlock (&mutex) != 0)
+	abort ();
+      break;
+
+    case 1:
+      if (sem_wait (&thread_2_semaphore) != 0)
+	abort ();
+      do_segfault ();
+      if (sem_post (&thread_1_semaphore) != 0)
+	abort ();
+
+      /* Fall through.  */
+    default:
+      /* Wait until we are allowed to finish.  */
+      if (sem_wait (&finish_semaphore) != 0)
+	abort ();
+      break;
+    }
+}
+
+void
+stop_marker ()
+{
+  global_var = 99;	/* Stop marker.  */
+}
+
+/* The main program entry point.  */
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+  void *retval;
+
+  /* An alarm, just in case the thread deadlocks.  */
+  alarm (300);
+
+  /* Semaphore initialization.  */
+  if (sem_init (&startup_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&finish_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&thread_1_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&thread_2_semaphore, 0, 0) != 0)
+    abort ();
+
+  /* Lock MUTEX, this prevents the first worker thread from rushing ahead.  */
+  if (pthread_mutex_lock (&mutex) != 0)
+    abort ();
+
+  /* Worker thread creation.  */
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  /* Wait for every thread to start.  */
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      if (sem_wait (&startup_semaphore) != 0)
+	abort ();
+    }
+
+  /* Unlock the first thread so it can proceed.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  /* Wait for the first thread only.  */
+  pthread_join (threads[0], &retval);
+
+  /* Now post FINISH_SEMAPHORE to allow all the other threads to finish.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    sem_post (&finish_semaphore);
+
+  /* Now wait for the remaining threads to complete.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    pthread_join (threads[i], &retval);
+
+  /* Semaphore cleanup.  */
+  sem_destroy (&finish_semaphore);
+  sem_destroy (&startup_semaphore);
+  sem_destroy (&thread_1_semaphore);
+  sem_destroy (&thread_2_semaphore);
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
new file mode 100644
index 00000000000..3341ff33f19
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
@@ -0,0 +1,156 @@
+# Copyright 2020 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 inferior calls executed from a breakpoint condition in
+# a multi-threaded program.
+#
+# This test has the inferior function call timeout, and checks how GDB
+# handles this situation.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "Conditional breakpoint here"]
+set final_bp_line [gdb_get_line_number "Stop marker"]
+set segfault_line [gdb_get_line_number "Segfault here"]
+
+# Setup GDB based on TARGET_ASYNC and TARGET_NON_STOP.  Setup some
+# breakpoints in the inferior, one of which has an inferior call
+# within its condition.
+#
+# Continue GDB, the breakpoint with inferior call will be hit, but the
+# inferior call will never return.  We expect GDB to timeout.
+#
+# The reason that the inferior call never completes is that a second
+# thread, on which the inferior call relies, either hits a breakpoint
+# (when OTHER_THREAD_BP is true), or crashes (when OTHER_THREAD_BP is
+# false).
+proc run_test { target_async target_non_stop other_thread_bp } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if {![runto_main]} {
+	fail "run to main"
+	return
+    }
+
+    # The default timeout for indirect inferior calls (e.g. inferior
+    # calls for conditional breakpoint expressions) is pretty high.
+    # We don't want the test to take too long, so reduce this.
+    #
+    # However, the test relies on a second thread hitting some event
+    # (either a breakpoint or signal) before this timeout expires.
+    #
+    # There is a chance that on a really slow system this might not
+    # happen, in which case the test might fail.
+    #
+    # However, we still allocate 5 seconds, which feels like it should
+    # be enough time in most cases, but maybe we need to do something
+    # smarter here?  Possibly we could have some initial run where the
+    # inferior doesn't timeout, but does do the same interaction
+    # between threads, we could time that, and use that as the basis
+    # for this timeout.  For now though, we just hope 5 seconds is
+    # enough.
+    gdb_test_no_output "set indirect-call-timeout 5"
+
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (condition_func ())"
+    set bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		    "get number for conditional breakpoint"]
+
+    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
+    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			  "get number for final breakpoint"]
+
+    # The thread performing an inferior call relies on a second
+    # thread.  The second thread will segfault unless it hits a
+    # breakpoint first.  In either case the initial thread will not
+    # complete its inferior call.
+    if { $other_thread_bp } {
+	gdb_breakpoint "${::srcfile}:${::segfault_line}"
+	set segfault_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+				 "get number for segfault breakpoint"]
+    }
+
+    # When non-stop mode is off we get slightly different output from GDB.
+    if { [gdb_is_remote_or_extended_remote_target] && $target_non_stop == "off" } {
+	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" received signal SIGINT, Interrupt\\."
+    } else {
+	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\."
+    }
+
+    gdb_test "continue" \
+	[multi_line \
+	     $stopped_line_pattern \
+	     ".*" \
+	     "Error in testing condition for breakpoint ${bp_num}:" \
+	     "The program being debugged timed out while in a function called from GDB\\." \
+	     "GDB remains in the frame where the timeout occurred\\." \
+	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(condition_func\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."] \
+	"expected timeout waiting for inferior call to complete"
+
+    # Remember that other thread that either crashed (with a segfault)
+    # or hit a breakpoint?  Now that the inferior call has timed out,
+    # if we try to resume then we should see the pending event from
+    # that other thread.
+    if { $other_thread_bp } {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${segfault_bp_num}, do_segfault \[^\r\n\]+:${::segfault_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"] \
+	    "hit the segfault breakpoint"
+    } else {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "Thread ${::decimal} \"infcall-from-bp\" received signal SIGSEGV, Segmentation fault\\." \
+		 "\\\[Switching to Thread \[^\r\n\]+\\\]" \
+		 "${::hex} in do_segfault \\(\\) at \[^\r\n\]+:${::segfault_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"] \
+	    "hit the segfault"
+    }
+}
+
+foreach_with_prefix target_async {"on" "off" } {
+
+    if { $target_async == "off" } {
+	# GDB can't timeout while waiting for a thread if the target
+	# runs with async-mode turned off; once the target is running
+	# GDB is effectively blocked until the target stops for some
+	# reason.
+	continue
+    }
+
+    foreach_with_prefix target_non_stop {"off" "on"} {
+	foreach_with_prefix other_thread_bp { true false } {
+	    run_test $target_async $target_non_stop $other_thread_bp
+	}
+    }
+}
-- 
2.25.4


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

* [PATCHv2 11/13] gdb/remote: avoid SIGINT after calling remote_target::stop
  2023-01-18 16:17 ` [PATCHv2 00/13] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                     ` (9 preceding siblings ...)
  2023-01-18 16:18   ` [PATCHv2 10/13] gdb: add timeouts for inferior function calls Andrew Burgess
@ 2023-01-18 16:18   ` Andrew Burgess
  2023-01-20  9:14     ` Aktemur, Tankut Baris
  2023-01-18 16:18   ` [PATCHv2 12/13] gdb: introduce unwind-on-timeout setting Andrew Burgess
                     ` (3 subsequent siblings)
  14 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2023-01-18 16:18 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Currently, if the remote target is not running in non-stop mode, then,
when GDB calls remote_target::stop, we end up sending an interrupt
packet \x03 to the remote target.

If the user interrupts the inferior from the GDB prompt (e.g. by
typing Ctrl-c), then GDB calls remote_target::interrupt, which also
ends up sending the interrupt packet.

The problem here is that both of these mechanisms end up sending the
interrupt packet, which means, when the target stops with a SIGINT,
and this is reported back to GDB, we have no choice but to report this
to the user as a SIGINT stop event.

Now maybe this is the correct thing to do, after all the target has
been stopped with SIGINT.  However, this leads to an unfortunate
change in behaviour.

When running in non-stop mode, and remote_target::stop is called, the
target will be stopped with a vCont packet, and this stop is then
reported back to GDB as GDB_SIGNAL_0, this will cause GDB to print a
message like:

  Program stopped.

Or:

  Thread NN "binary name" stopped.

In contrast, when non-stop mode is off, we get messages like:

  Program received SIGINT, Segmentation fault.

Or:

  Thread NN "binary name" received SIGINT, Segmentation fault.

In this commit I propose a mechanism where we can track that a stop
has been requested for a particular thread through
remote_target::stop, then, when the stop arrives, we can convert the
SIGINT to a GDB_SIGNAL_0.  With this done GDB will now display the
"stopped" based messages rather than the "received SIGINT" messages.

Two of the tests added in the previous commit exposed this issue.  In
the previous commit the tests looked for either of the above
patterns.  In this commit I've updated these tests to only look for
the "stopped" based messages.
---
 gdb/remote.c                                    | 17 +++++++++++++++++
 gdb/testsuite/gdb.base/infcall-timeout.exp      |  9 +--------
 .../infcall-from-bp-cond-timeout.exp            |  9 +--------
 3 files changed, 19 insertions(+), 16 deletions(-)

diff --git a/gdb/remote.c b/gdb/remote.c
index 218bca30d04..61781a24820 100644
--- a/gdb/remote.c
+++ b/gdb/remote.c
@@ -1139,6 +1139,10 @@ struct remote_thread_info : public private_thread_info
   std::string name;
   int core = -1;
 
+  /* Only used when not in non-stop mode.  Set to true when a stop is
+     requested for the thread.  */
+  bool stop_requested = false;
+
   /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
      sequence of bytes.  */
   gdb::byte_vector thread_handle;
@@ -7114,6 +7118,12 @@ remote_target::stop (ptid_t ptid)
       /* We don't currently have a way to transparently pause the
 	 remote target in all-stop mode.  Interrupt it instead.  */
       remote_interrupt_as ();
+
+      /* Record that this thread's stop is a result of GDB asking for the
+	 stop, rather than the user asking for an interrupt.  We can use
+	 this information to adjust the waitstatus when it arrives.  */
+      remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
+      remote_thr->stop_requested = true;
     }
 }
 
@@ -8097,9 +8107,16 @@ remote_target::process_stop_reply (struct stop_reply *stop_reply,
 	  /* If the target works in non-stop mode, a stop-reply indicates that
 	     only this thread stopped.  */
 	  remote_thr->set_not_resumed ();
+	  gdb_assert (!remote_thr->stop_requested);
 	}
       else
 	{
+	  if (status->kind () == TARGET_WAITKIND_STOPPED
+	      && status->sig () == GDB_SIGNAL_INT
+	      && remote_thr->stop_requested)
+	    status->set_stopped (GDB_SIGNAL_0);
+	  remote_thr->stop_requested = false;
+
 	  /* If the target works in all-stop mode, a stop-reply indicates that
 	     all the target's threads stopped.  */
 	  for (thread_info *tp : all_non_exited_threads (this))
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.exp b/gdb/testsuite/gdb.base/infcall-timeout.exp
index a5b0111ed04..bd6b2bfac3e 100644
--- a/gdb/testsuite/gdb.base/infcall-timeout.exp
+++ b/gdb/testsuite/gdb.base/infcall-timeout.exp
@@ -45,16 +45,9 @@ proc_with_prefix run_test { target_async target_non_stop } {
 
     gdb_test_no_output "set direct-call-timeout 5"
 
-    # When non-stop mode is off we get slightly different output from GDB.
-    if { [gdb_is_remote_or_extended_remote_target] && $target_non_stop == "off" } {
-	set stopped_line_pattern "Program received signal SIGINT, Interrupt\\."
-    } else {
-	set stopped_line_pattern "Program stopped\\."
-    }
-
     gdb_test "print function_that_never_returns ()" \
 	[multi_line \
-	     $stopped_line_pattern \
+	     "Program stopped\\." \
 	     ".*" \
 	     "The program being debugged timed out while in a function called from GDB\\." \
 	     "GDB remains in the frame where the timeout occurred\\." \
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
index 3341ff33f19..9ba38e6896a 100644
--- a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
@@ -92,16 +92,9 @@ proc run_test { target_async target_non_stop other_thread_bp } {
 				 "get number for segfault breakpoint"]
     }
 
-    # When non-stop mode is off we get slightly different output from GDB.
-    if { [gdb_is_remote_or_extended_remote_target] && $target_non_stop == "off" } {
-	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" received signal SIGINT, Interrupt\\."
-    } else {
-	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\."
-    }
-
     gdb_test "continue" \
 	[multi_line \
-	     $stopped_line_pattern \
+	     "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\." \
 	     ".*" \
 	     "Error in testing condition for breakpoint ${bp_num}:" \
 	     "The program being debugged timed out while in a function called from GDB\\." \
-- 
2.25.4


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

* [PATCHv2 12/13] gdb: introduce unwind-on-timeout setting
  2023-01-18 16:17 ` [PATCHv2 00/13] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                     ` (10 preceding siblings ...)
  2023-01-18 16:18   ` [PATCHv2 11/13] gdb/remote: avoid SIGINT after calling remote_target::stop Andrew Burgess
@ 2023-01-18 16:18   ` Andrew Burgess
  2023-01-18 17:33     ` Eli Zaretskii
  2023-01-20  9:26     ` Aktemur, Tankut Baris
  2023-01-18 16:18   ` [PATCHv2 13/13] gdb: rename unwindonsignal to unwind-on-signal Andrew Burgess
                     ` (2 subsequent siblings)
  14 siblings, 2 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-01-18 16:18 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Now that inferior function calls can timeout (see the recent
introduction of direct-call-timeout and indirect-call-timeout), this
commit adds a new setting unwind-on-timeout.

This new setting is just like the existing unwindonsignal and
unwind-on-terminating-exception, but the new setting will cause GDB to
unwind the stack if an inferior function call times out.

The existing inferior function call timeout tests have been updated to
cover the new setting.
---
 gdb/NEWS                                      |  9 +++
 gdb/doc/gdb.texinfo                           | 33 +++++++---
 gdb/infcall.c                                 | 62 ++++++++++++++++---
 gdb/testsuite/gdb.base/infcall-timeout.exp    | 49 +++++++++++----
 .../infcall-from-bp-cond-timeout.exp          | 55 +++++++++++-----
 5 files changed, 164 insertions(+), 44 deletions(-)

diff --git a/gdb/NEWS b/gdb/NEWS
index 2689569a8f3..511a750407a 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -35,6 +35,15 @@ show indirect-call-timeout
   ignored, GDB will wait indefinitely for an inferior function to
   complete, unless interrupted by the user using Ctrl-C.
 
+set unwind-on-timeout on|off
+show unwind-on-timeout
+  These commands control whether GDB should unwind the stack when a
+  timeout occurs during an inferior function call.  The default is
+  off, in which case the inferior will remain in the frame where the
+  timeout occurred.  When on GDB will unwind the stack remocing the
+  dummy frame that was added for the inferior call, and restoring the
+  inferior state to how it was before the inferior call started.
+
 * MI changes
 
 ** mi now reports 'no-history' as a stop reason when hitting the end of the
diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index 9eb8b1db00e..aa88221677e 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -5719,10 +5719,10 @@
 the called function, or the called function may receive a signal
 (e.g.@ a @code{SIGSEGV}) as a result of some undefined behaviour, if
 this happens then @value{GDBN} will stop.  Depending on the settings
-@code{unwindonsignal} and @code{unwind-on-terminating-exception}
-(@pxref{Calling,,Calling Program Functions}) @value{GDBN} may unwind
-the stack back to the breakpoint location, or may leave the program at
-the frame where the stop occurred.
+@code{unwindonsignal}, @code{unwind-on-terminating-exception}, and
+@code{unwind-on-timeout} (@pxref{Calling,,Calling Program Functions})
+@value{GDBN} may unwind the stack back to the breakpoint location, or
+may leave the program at the frame where the stop occurred.
 
 Breakpoint conditions can also be evaluated on the target's side if
 the target supports it.  Instead of evaluating the conditions locally,
@@ -20718,6 +20718,21 @@
 Show the current setting of stack unwinding in the functions called by
 @value{GDBN}.
 
+@item set unwind-on-timeout
+@kindex set unwind-on-timeout
+@cindex unwind stack in called functions when timing out
+@cindex call dummy stack unwinding on timeout.
+Set unwinding of the stack if a function called from @value{GDBN}
+times out.  If set to @code{off} (the default), @value{GDBN} stops in
+the frame where the timeout occurred.  If set to @code{on},
+@value{GDBN} unwinds the stack it created for the call and restores
+the context to what it was before the call.
+
+@item show unwind-on-timeout
+@kindex show unwind-on-timeout
+Show whether @value{GDBN} will unwind the stack if a function called
+from @value{GDBN} times out.
+
 @item set may-call-functions
 @kindex set may-call-functions
 @cindex disabling calling functions in the program
@@ -20748,11 +20763,11 @@
 call by typing the interrupt character (often @kbd{Ctrl-c}).
 
 If a called function is interrupted for any reason, and the stack is
-not unwound (due to @code{set unwind-on-terminating-exception on} or
-@code{set unwindonsignal on}), then the dummy-frame, created by
-@value{GDBN} to facilitate the call to the program function, will be
-visible in the backtrace, for example frame @code{#3} in the following
-backtrace:
+not unwound (due to @code{set unwind-on-terminating-exception on},
+@code{set unwind-on-timeout}, or @code{set unwindonsignal on}), then
+the dummy-frame, created by @value{GDBN} to facilitate the call to the
+program function, will be visible in the backtrace, for example frame
+@code{#3} in the following backtrace:
 
 @smallexample
 (@value{GDBP}) backtrace
diff --git a/gdb/infcall.c b/gdb/infcall.c
index 9afca4f5bc6..272e3cccf87 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -217,6 +217,27 @@ show_unwind_on_terminating_exception_p (struct ui_file *file, int from_tty,
 	      value);
 }
 
+/* This boolean tells what gdb should do if a signal is received while
+   in a function called from gdb (call dummy).  If set, gdb unwinds
+   the stack and restore the context to what as it was before the
+   call.
+
+   The default is to stop in the frame where the signal was received.  */
+
+static bool unwind_on_timeout_p = false;
+
+/* Implement 'show unwind-on-timeout'.  */
+
+static void
+show_unwind_on_timeout_p (struct ui_file *file, int from_tty,
+			  struct cmd_list_element *c, const char *value)
+{
+  gdb_printf (file,
+	      _("Unwinding of stack if a timeout occurs "
+		"while in a call dummy is %s.\n"),
+	      value);
+}
+
 /* Perform the standard coercions that are specified
    for arguments to be passed to C, Ada or Fortran functions.
 
@@ -1691,14 +1712,27 @@ When the function is done executing, GDB will silently stop."),
 	  /* A timeout results in a signal being sent to the inferior.  */
 	  gdb_assert (stopped_by_random_signal);
 
-	  /* Indentation is weird here.  A later patch is going to move the
-	    following block into an if/else, so I'm leaving the indentation
-	    here to minimise the later patch.
+	  if (unwind_on_timeout_p)
+	    {
+	      /* The user wants the context restored.  */
+
+	      /* We must get back to the frame we were before the
+		 dummy call.  */
+	      dummy_frame_pop (dummy_id, call_thread.get ());
+
+	      /* We also need to restore inferior status to that before the
+		 dummy call.  */
+	      restore_infcall_control_state (inf_status.release ());
 
-	    Also, the error message used below refers to 'set
-	    unwind-on-timeout' which doesn't exist yet.  This will be added
-	    in a later commit, I'm leaving this in for now to minimise the
-	    churn caused by the commit that adds unwind-on-timeout.  */
+	      error (_("\
+The program being debugged timed out while in a function called from GDB.\n\
+GDB has restored the context to what it was before the call.\n\
+To change this behavior use \"set unwind-on-timeout off\".\n\
+Evaluation of the expression containing the function\n\
+(%s) will be abandoned."),
+		     name.c_str ());
+	    }
+	  else
 	    {
 	      /* The user wants to stay in the frame where we stopped
 		 (default).  Discard inferior status, we're not at the same
@@ -1824,6 +1858,20 @@ The default is to unwind the frame."),
 			   show_unwind_on_terminating_exception_p,
 			   &setlist, &showlist);
 
+  add_setshow_boolean_cmd ("unwind-on-timeout", no_class,
+			   &unwind_on_timeout_p, _("\
+Set unwinding of stack if a timeout occurs while in a call dummy."), _("\
+Show unwinding of stack if a timeout occurs while in a call dummy."),
+			   _("\
+The unwind on timeout flag lets the user determine what gdb should do if\n\
+gdb times out while in a function called from gdb.  If set, gdb unwinds\n\
+the stack and restores the context to what it was before the call.  If\n\
+unset, gdb leaves the inferior in the frame where the timeout occurred.\n\
+The default is to stop in the frame where the timeout occurred."),
+			   NULL,
+			   show_unwind_on_timeout_p,
+			   &setlist, &showlist);
+
   add_setshow_uinteger_cmd ("direct-call-timeout", no_class,
 			    &direct_call_timeout, _("\
 Set the timeout, for direct calls to inferior function calls."), _("\
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.exp b/gdb/testsuite/gdb.base/infcall-timeout.exp
index bd6b2bfac3e..a4d9fd6ee61 100644
--- a/gdb/testsuite/gdb.base/infcall-timeout.exp
+++ b/gdb/testsuite/gdb.base/infcall-timeout.exp
@@ -28,7 +28,11 @@ if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
 # the direct-call-timeout, and make an inferior function call that
 # will never return.  GDB should eventually timeout and stop the
 # inferior.
-proc_with_prefix run_test { target_async target_non_stop } {
+#
+# When UNWIND is "off" the inferior wil be left in the frame where the
+# timeout occurs, otherwise, when UNWIND is "on", GDB should unwind
+# back to the frame where the inferior call was made.
+proc_with_prefix run_test { target_async target_non_stop unwind } {
     save_vars { ::GDBFLAGS } {
 	append ::GDBFLAGS \
 	    " -ex \"maint set target-non-stop $target_non_stop\""
@@ -44,19 +48,36 @@ proc_with_prefix run_test { target_async target_non_stop } {
     }
 
     gdb_test_no_output "set direct-call-timeout 5"
+    gdb_test_no_output "set unwind-on-timeout $unwind"
+
+    if { $unwind } {
+	gdb_test "print function_that_never_returns ()" \
+	    [multi_line \
+		 "Program stopped\\." \
+		 ".*" \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB has restored the context to what it was before the call\\." \
+		 "To change this behavior use \"set unwind-on-timeout off\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(function_that_never_returns\\) will be abandoned\\."]
 
-    gdb_test "print function_that_never_returns ()" \
-	[multi_line \
-	     "Program stopped\\." \
-	     ".*" \
-	     "The program being debugged timed out while in a function called from GDB\\." \
-	     "GDB remains in the frame where the timeout occurred\\." \
-	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
-	     "Evaluation of the expression containing the function" \
-	     "\\(function_that_never_returns\\) will be abandoned\\." \
-	     "When the function is done executing, GDB will silently stop\\."]
+	gdb_test "bt" \
+	    "#0\\s+main \\(\\).*"
+    } else {
+	gdb_test "print function_that_never_returns ()" \
+	    [multi_line \
+		 "Program stopped\\." \
+		 ".*" \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB remains in the frame where the timeout occurred\\." \
+		 "To change this behavior use \"set unwind-on-timeout on\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(function_that_never_returns\\) will be abandoned\\." \
+		 "When the function is done executing, GDB will silently stop\\."]
 
-    gdb_test "bt" ".* function_that_never_returns .*<function called from gdb>.*"
+	gdb_test "bt" \
+	    ".* function_that_never_returns .*<function called from gdb>.*"
+    }
 }
 
 foreach_with_prefix target_async { "on" "off" } {
@@ -70,6 +91,8 @@ foreach_with_prefix target_async { "on" "off" } {
     }
 
     foreach_with_prefix target_non_stop { "on" "off" } {
-	run_test $target_async $target_non_stop
+	foreach_with_prefix unwind { "on" "off" } {
+	    run_test $target_async $target_non_stop $unwind
+	}
     }
 }
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
index 9ba38e6896a..847a850673d 100644
--- a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
@@ -41,7 +41,12 @@ set segfault_line [gdb_get_line_number "Segfault here"]
 # thread, on which the inferior call relies, either hits a breakpoint
 # (when OTHER_THREAD_BP is true), or crashes (when OTHER_THREAD_BP is
 # false).
-proc run_test { target_async target_non_stop other_thread_bp } {
+#
+# When UNWIND is "on" GDB will unwind the thread which performed the
+# inferior function call back to the state where the inferior call was
+# made (when the inferior call times out).  Otherwise, when UNWIND is
+# "off", the inferior is left in the frame where the timeout occurred.
+proc run_test { target_async target_non_stop other_thread_bp unwind } {
     save_vars { ::GDBFLAGS } {
 	append ::GDBFLAGS " -ex \"maint set target-non-stop $target_non_stop\""
 	append ::GDBFLAGS " -ex \"maintenance set target-async ${target_async}\""
@@ -72,6 +77,7 @@ proc run_test { target_async target_non_stop other_thread_bp } {
     # for this timeout.  For now though, we just hope 5 seconds is
     # enough.
     gdb_test_no_output "set indirect-call-timeout 5"
+    gdb_test_no_output "set unwind-on-timeout $unwind"
 
     gdb_breakpoint \
 	"${::srcfile}:${::cond_bp_line} if (condition_func ())"
@@ -92,18 +98,35 @@ proc run_test { target_async target_non_stop other_thread_bp } {
 				 "get number for segfault breakpoint"]
     }
 
-    gdb_test "continue" \
-	[multi_line \
-	     "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\." \
-	     ".*" \
-	     "Error in testing condition for breakpoint ${bp_num}:" \
-	     "The program being debugged timed out while in a function called from GDB\\." \
-	     "GDB remains in the frame where the timeout occurred\\." \
-	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
-	     "Evaluation of the expression containing the function" \
-	     "\\(condition_func\\) will be abandoned\\." \
-	     "When the function is done executing, GDB will silently stop\\."] \
-	"expected timeout waiting for inferior call to complete"
+    if { $unwind } {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\." \
+		 ".*" \
+		 "Error in testing condition for breakpoint ${bp_num}:" \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB has restored the context to what it was before the call\\." \
+		 "To change this behavior use \"set unwind-on-timeout off\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(condition_func\\) will be abandoned\\." \
+		 "" \
+		 "Thread ${::decimal}\[^\r\n\]*hit Breakpoint ${bp_num}, \[^\r\n\]+" \
+		 "\[^\r\n\]+ Conditional breakpoint here\\. \[^\r\n\]+"] \
+	    "expected timeout waiting for inferior call to complete"
+    } else {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\." \
+		 ".*" \
+		 "Error in testing condition for breakpoint ${bp_num}:" \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB remains in the frame where the timeout occurred\\." \
+		 "To change this behavior use \"set unwind-on-timeout on\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(condition_func\\) will be abandoned\\." \
+		 "When the function is done executing, GDB will silently stop\\."] \
+	    "expected timeout waiting for inferior call to complete"
+    }
 
     # Remember that other thread that either crashed (with a segfault)
     # or hit a breakpoint?  Now that the inferior call has timed out,
@@ -142,8 +165,10 @@ foreach_with_prefix target_async {"on" "off" } {
     }
 
     foreach_with_prefix target_non_stop {"off" "on"} {
-	foreach_with_prefix other_thread_bp { true false } {
-	    run_test $target_async $target_non_stop $other_thread_bp
+	foreach_with_prefix unwind {"off" "on"} {
+	    foreach_with_prefix other_thread_bp { true false } {
+		run_test $target_async $target_non_stop $other_thread_bp $unwind
+	    }
 	}
     }
 }
-- 
2.25.4


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

* [PATCHv2 13/13] gdb: rename unwindonsignal to unwind-on-signal
  2023-01-18 16:17 ` [PATCHv2 00/13] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                     ` (11 preceding siblings ...)
  2023-01-18 16:18   ` [PATCHv2 12/13] gdb: introduce unwind-on-timeout setting Andrew Burgess
@ 2023-01-18 16:18   ` Andrew Burgess
  2023-01-18 17:35     ` Eli Zaretskii
  2023-01-20  9:34   ` [PATCHv2 00/13] Infcalls from B/P conditions in multi-threaded inferiors Aktemur, Tankut Baris
  2023-01-31 17:27   ` [PATCHv3 " Andrew Burgess
  14 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2023-01-18 16:18 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

We now have unwind-on-timeout and unwind-on-terminating-exception, and
then the odd one out unwindonsignal.

I'm not a great fan of these squashed together command names, so in
this commit I propose renaming this to unwind-on-signal.

Obviously I've added the hidden alias unwindonsignal so any existing
GDB scripts will keep working.

There's one test that I've extended to test the alias works, but in
most of the other test scripts I've changed over to use the new name.

The docs are updated to reference the new name.
---
 gdb/NEWS                                      | 11 ++++++
 gdb/doc/gdb.texinfo                           | 16 ++++++---
 gdb/infcall.c                                 | 21 ++++++-----
 gdb/testsuite/gdb.base/callfuncs.exp          |  4 +--
 gdb/testsuite/gdb.base/infcall-failure.exp    |  4 +--
 gdb/testsuite/gdb.base/unwindonsignal.exp     | 36 +++++++++++++------
 gdb/testsuite/gdb.compile/compile-cplus.exp   |  2 +-
 gdb/testsuite/gdb.compile/compile.exp         |  2 +-
 gdb/testsuite/gdb.cp/gdb2495.exp              | 16 ++++-----
 gdb/testsuite/gdb.fortran/function-calls.exp  |  2 +-
 gdb/testsuite/gdb.mi/mi-syn-frame.exp         |  2 +-
 .../infcall-from-bp-cond-simple.exp           |  2 +-
 .../gdb.threads/thread-unwindonsignal.exp     |  8 ++---
 13 files changed, 83 insertions(+), 43 deletions(-)

diff --git a/gdb/NEWS b/gdb/NEWS
index 511a750407a..77d85392bcb 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -44,6 +44,17 @@ show unwind-on-timeout
   dummy frame that was added for the inferior call, and restoring the
   inferior state to how it was before the inferior call started.
 
+set unwind-on-signal on|off
+show unwind-on-signal
+  These new commands replaces the existing set/show unwindonsignal.  The
+  old command is maintained as an alias.
+
+* Changed commands
+
+set unwindonsignal on|off
+show unwindonsignal
+  These commands are now aliases for the new set/show unwind-on-signal.
+
 * MI changes
 
 ** mi now reports 'no-history' as a stop reason when hitting the end of the
diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index aa88221677e..6f1775c4843 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -20673,7 +20673,7 @@
 It is possible for the function you call via the @code{print} or
 @code{call} command to generate a signal (e.g., if there's a bug in
 the function, or if you passed it incorrect arguments).  What happens
-in that case is controlled by the @code{set unwindonsignal} command.
+in that case is controlled by the @code{set unwind-on-signal} command.
 
 Similarly, with a C@t{++} program it is possible for the function you
 call via the @code{print} or @code{call} command to generate an
@@ -20686,7 +20686,8 @@
 @code{set unwind-on-terminating-exception} command.
 
 @table @code
-@item set unwindonsignal
+@item set unwind-on-signal
+@kindex set unwind-on-signal
 @kindex set unwindonsignal
 @cindex unwind stack in called functions
 @cindex call dummy stack unwinding
@@ -20697,11 +20698,18 @@
 default), @value{GDBN} stops in the frame where the signal was
 received.
 
-@item show unwindonsignal
+The command @code{set unwindonsignal} is an alias for this command,
+and is maintained for backward compatibility.
+
+@item show unwind-on-signal
+@kindex show unwind-on-signal
 @kindex show unwindonsignal
 Show the current setting of stack unwinding in the functions called by
 @value{GDBN}.
 
+The command @code{show unwindonsignal} is an alias for this command,
+and is maintained for backward compatibility.
+
 @item set unwind-on-terminating-exception
 @kindex set unwind-on-terminating-exception
 @cindex unwind stack in called functions with unhandled exceptions
@@ -20764,7 +20772,7 @@
 
 If a called function is interrupted for any reason, and the stack is
 not unwound (due to @code{set unwind-on-terminating-exception on},
-@code{set unwind-on-timeout}, or @code{set unwindonsignal on}), then
+@code{set unwind-on-timeout}, or @code{set unwind-on-signal on}), then
 the dummy-frame, created by @value{GDBN} to facilitate the call to the
 program function, will be visible in the backtrace, for example frame
 @code{#3} in the following backtrace:
diff --git a/gdb/infcall.c b/gdb/infcall.c
index 272e3cccf87..f98fe160347 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -1681,7 +1681,7 @@ When the function is done executing, GDB will silently stop."),
 	      error (_("\
 The program being debugged was signaled while in a function called from GDB.\n\
 GDB has restored the context to what it was before the call.\n\
-To change this behavior use \"set unwindonsignal off\".\n\
+To change this behavior use \"set unwind-on-signal off\".\n\
 Evaluation of the expression containing the function\n\
 (%s) will be abandoned."),
 		     name.c_str ());
@@ -1699,7 +1699,7 @@ Evaluation of the expression containing the function\n\
 	      error (_("\
 The program being debugged was signaled while in a function called from GDB.\n\
 GDB remains in the frame where the signal was received.\n\
-To change this behavior use \"set unwindonsignal on\".\n\
+To change this behavior use \"set unwind-on-signal on\".\n\
 Evaluation of the expression containing the function\n\
 (%s) will be abandoned.\n\
 When the function is done executing, GDB will silently stop."),
@@ -1831,17 +1831,22 @@ The default is to perform the conversion."),
 			   show_coerce_float_to_double_p,
 			   &setlist, &showlist);
 
-  add_setshow_boolean_cmd ("unwindonsignal", no_class,
-			   &unwind_on_signal_p, _("\
+  set_show_commands setshow_unwind_on_signal_cmds
+    = add_setshow_boolean_cmd ("unwind-on-signal", no_class,
+			       &unwind_on_signal_p, _("\
 Set unwinding of stack if a signal is received while in a call dummy."), _("\
 Show unwinding of stack if a signal is received while in a call dummy."), _("\
-The unwindonsignal lets the user determine what gdb should do if a signal\n\
+The unwind-on-signal lets the user determine what gdb should do if a signal\n\
 is received while in a function called from gdb (call dummy).  If set, gdb\n\
 unwinds the stack and restore the context to what as it was before the call.\n\
 The default is to stop in the frame where the signal was received."),
-			   NULL,
-			   show_unwind_on_signal_p,
-			   &setlist, &showlist);
+			       NULL,
+			       show_unwind_on_signal_p,
+			       &setlist, &showlist);
+  add_alias_cmd ("unwindonsignal", setshow_unwind_on_signal_cmds.set,
+		 no_class, 1, &setlist);
+  add_alias_cmd ("unwindonsignal", setshow_unwind_on_signal_cmds.show,
+		 no_class, 1, &showlist);
 
   add_setshow_boolean_cmd ("unwind-on-terminating-exception", no_class,
 			   &unwind_on_terminating_exception_p, _("\
diff --git a/gdb/testsuite/gdb.base/callfuncs.exp b/gdb/testsuite/gdb.base/callfuncs.exp
index df67c772e41..da994789d88 100644
--- a/gdb/testsuite/gdb.base/callfuncs.exp
+++ b/gdb/testsuite/gdb.base/callfuncs.exp
@@ -49,7 +49,7 @@ proc do_function_calls {prototypes} {
 
     # If any of these calls segv we don't want to affect subsequent tests.
     # E.g., we want to ensure register values are restored.
-    gdb_test_no_output "set unwindonsignal on"
+    gdb_test_no_output "set unwind-on-signal on"
 
     gdb_test "p t_char_values(0,0)" " = 0"
     gdb_test "p t_char_values('a','b')" " = 1"
@@ -240,7 +240,7 @@ proc do_function_calls {prototypes} {
     	"call inferior func with struct - returns char *"
 
     # Restore default value.
-    gdb_test_no_output "set unwindonsignal off"
+    gdb_test_no_output "set unwind-on-signal off"
 }
 
 # Procedure to get current content of all registers.
diff --git a/gdb/testsuite/gdb.base/infcall-failure.exp b/gdb/testsuite/gdb.base/infcall-failure.exp
index 8fa2c407fc5..cf50a3baf0a 100644
--- a/gdb/testsuite/gdb.base/infcall-failure.exp
+++ b/gdb/testsuite/gdb.base/infcall-failure.exp
@@ -137,7 +137,7 @@ proc_with_prefix run_cond_hits_segfault_test { async_p non_stop_p } {
 	     "Error in testing condition for breakpoint ${bp_1_num}:" \
 	     "The program being debugged was signaled while in a function called from GDB\\." \
 	     "GDB remains in the frame where the signal was received\\." \
-	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "To change this behavior use \"set unwind-on-signal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(func_segfault\\) will be abandoned\\." \
 	     "When the function is done executing, GDB will silently stop\\."]
@@ -165,7 +165,7 @@ proc_with_prefix run_call_hits_segfault_test { async_p non_stop_p } {
 	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
 	     "The program being debugged was signaled while in a function called from GDB\\." \
 	     "GDB remains in the frame where the signal was received\\." \
-	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "To change this behavior use \"set unwind-on-signal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(func_segfault\\) will be abandoned\\." \
 	     "When the function is done executing, GDB will silently stop\\."]
diff --git a/gdb/testsuite/gdb.base/unwindonsignal.exp b/gdb/testsuite/gdb.base/unwindonsignal.exp
index 8470634e502..41a4de8b472 100644
--- a/gdb/testsuite/gdb.base/unwindonsignal.exp
+++ b/gdb/testsuite/gdb.base/unwindonsignal.exp
@@ -40,35 +40,51 @@ gdb_test "break stop_here" "Breakpoint \[0-9\]* at .*"
 gdb_test "continue" "Continuing.*Breakpoint \[0-9\]*, stop_here.*" \
     "continue to breakpoint at stop_here"
 
-# Turn on unwindonsignal.
-gdb_test_no_output "set unwindonsignal on" \
-	"setting unwindonsignal"
+# Turn on unwind-on-signal.
+gdb_test_no_output "set unwind-on-signal on" \
+	"setting unwind-on-signal"
 
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
 	"Unwinding of stack .* is on." \
-	"showing unwindonsignal"
+	"showing unwind-on-signal"
+
+# For backward compatibility we maintain a 'unwindonsignal' alias for
+# 'unwind-on-signal', check it now.
+gdb_test "show unwindonsignal" \
+    "Unwinding of stack .* is on\\." \
+    "showing unwindonsignal alias"
+
+gdb_test_no_output "set unwindonsignal off" \
+    "setting unwindonsignal alias to off"
+
+gdb_test "show unwind-on-signal" \
+    "Unwinding of stack .* is off\\." \
+    "showing unwind-on-signal after setting via alias"
+
+gdb_test_no_output "set unwindonsignal on" \
+    "setting unwindonsignal alias to on"
 
 # Call function (causing the program to get a signal), and see if gdb handles
 # it properly.
 if {[gdb_test "call gen_signal ()"  \
 	 "\[\r\n\]*The program being debugged was signaled.*" \
-	 "unwindonsignal, inferior function call signaled"] != 0} {
+	 "inferior function call signaled"] != 0} {
     return 0
 }
 
 # Verify the stack got unwound.
 gdb_test "bt" \
     "#0 *\[x0-9a-f in\]*stop_here \\(.*\\) at .*#1 *\[x0-9a-f in\]*main \\(.*\\) at .*" \
-	"unwindonsignal, stack unwound"
+	"stack unwound"
 
 # Verify the dummy frame got removed from dummy_frame_stack.
 gdb_test_multiple "maint print dummy-frames" \
-	"unwindonsignal, dummy frame removed" {
+	"unwind-on-signal, dummy frame removed" {
     -re "\[\r\n\]*.*stack=.*code=.*\[\r\n\]+$gdb_prompt $" {
-	fail "unwindonsignal, dummy frame removed"
+	fail $gdb_test_name
     }
     -re "\[\r\n\]+$gdb_prompt $" {
-	pass "unwindonsignal, dummy frame removed"
+	pass $gdb_test_name
     }
 }
 
diff --git a/gdb/testsuite/gdb.compile/compile-cplus.exp b/gdb/testsuite/gdb.compile/compile-cplus.exp
index 0b7cb59727a..4960e03408e 100644
--- a/gdb/testsuite/gdb.compile/compile-cplus.exp
+++ b/gdb/testsuite/gdb.compile/compile-cplus.exp
@@ -129,7 +129,7 @@ gdb_test "return" "\r\n#0  main .*" "return" \
 	 "Make _gdb_expr\\(__gdb_regs\\*\\) return now\\? \\(y or n\\) " "y"
 gdb_test "info sym $infcall_pc" "\r\nNo symbol matches .*" "info sym not found"
 
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 gdb_test "compile code *(volatile int *) 0 = 0;" \
     "The program being debugged was signaled while in a function called from GDB\\.\r\nGDB has restored the context to what it was before the call\\.\r\n.*" \
     "compile code segfault second"
diff --git a/gdb/testsuite/gdb.compile/compile.exp b/gdb/testsuite/gdb.compile/compile.exp
index 9fdd36719ae..a9717088c05 100644
--- a/gdb/testsuite/gdb.compile/compile.exp
+++ b/gdb/testsuite/gdb.compile/compile.exp
@@ -159,7 +159,7 @@ gdb_test "return" "\r\n#0  main .*" "return" \
 	 "Make _gdb_expr return now\\? \\(y or n\\) " "y"
 gdb_test "info sym $infcall_pc" "\r\nNo symbol matches .*" "info sym not found"
 
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 gdb_test "compile code *(volatile int *) 0 = 0;" \
     "The program being debugged was signaled while in a function called from GDB\\.\r\nGDB has restored the context to what it was before the call\\.\r\n.*" \
     "compile code segfault second"
diff --git a/gdb/testsuite/gdb.cp/gdb2495.exp b/gdb/testsuite/gdb.cp/gdb2495.exp
index 0cb8bdd0ada..af94d959d83 100644
--- a/gdb/testsuite/gdb.cp/gdb2495.exp
+++ b/gdb/testsuite/gdb.cp/gdb2495.exp
@@ -104,29 +104,29 @@ if {![runto_main]} {
 # behaviour; it should not.  Test both on and off states.
 
 # Turn on unwind on signal behaviour.
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 
 # Check that it is turned on.
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
     "signal is received while in a call dummy is on.*" \
     "turn on unwind on signal"
 
 # Check to see if new behaviour interferes with
 # normal signal handling in inferior function calls.
 gdb_test "p exceptions.raise_signal(1)" \
-    "To change this behavior use \"set unwindonsignal off\".*" \
-    "check for unwindonsignal off message"
+    "To change this behavior use \"set unwind-on-signal off\".*" \
+    "check for unwind-on-signal off message"
 
 # And reverse - turn off again.
-gdb_test_no_output "set unwindonsignal off"
+gdb_test_no_output "set unwind-on-signal off"
 
 # Check that it is actually turned off.
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
     "signal is received while in a call dummy is off.*" \
     "turn off unwind on signal"
 
 # Check to see if new behaviour interferes with
 # normal signal handling in inferior function calls.
 gdb_test "p exceptions.raise_signal(1)" \
-    "To change this behavior use \"set unwindonsignal on\".*" \
-    "check for unwindonsignal on message"
+    "To change this behavior use \"set unwind-on-signal on\".*" \
+    "check for unwind-on-signal on message"
diff --git a/gdb/testsuite/gdb.fortran/function-calls.exp b/gdb/testsuite/gdb.fortran/function-calls.exp
index f9a1efc241f..c4d1f232576 100644
--- a/gdb/testsuite/gdb.fortran/function-calls.exp
+++ b/gdb/testsuite/gdb.fortran/function-calls.exp
@@ -44,7 +44,7 @@ if {![runto [gdb_get_line_number "post_init"]]} {
 }
 
 # Use inspired by gdb.base/callfuncs.exp.
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 
 # Baseline: function and subroutine call with no arguments.
 gdb_test "p no_arg()" " = .TRUE."
diff --git a/gdb/testsuite/gdb.mi/mi-syn-frame.exp b/gdb/testsuite/gdb.mi/mi-syn-frame.exp
index 409fac623a7..f65d57028a5 100644
--- a/gdb/testsuite/gdb.mi/mi-syn-frame.exp
+++ b/gdb/testsuite/gdb.mi/mi-syn-frame.exp
@@ -97,7 +97,7 @@ mi_gdb_test "409-stack-list-frames 0 0" \
 # 
 
 mi_gdb_test "410-data-evaluate-expression bar()" \
-  ".*410\\^error,msg=\"The program being debugged was signaled while in a function called from GDB.\\\\nGDB remains in the frame where the signal was received.\\\\nTo change this behavior use \\\\\"set unwindonsignal on\\\\\".\\\\nEvaluation of the expression containing the function\\\\n\\(bar\\) will be abandoned.\\\\nWhen the function is done executing, GDB will silently stop.\"" \
+  ".*410\\^error,msg=\"The program being debugged was signaled while in a function called from GDB.\\\\nGDB remains in the frame where the signal was received.\\\\nTo change this behavior use \\\\\"set unwind-on-signal on\\\\\".\\\\nEvaluation of the expression containing the function\\\\n\\(bar\\) will be abandoned.\\\\nWhen the function is done executing, GDB will silently stop.\"" \
   "call inferior function which raises exception"
 
 mi_gdb_test "411-stack-list-frames" "411\\^done,stack=\\\[frame=\{level=\"0\",addr=\"$hex\",func=\"bar\",file=\".*mi-syn-frame.c\",fullname=\"${fullname_syntax}${srcfile}\",line=\"$decimal\",arch=\"$any\"},frame=\{level=\"1\",addr=\"$hex\",func=\"<function called from gdb>\"\},frame=\{level=\"2\",addr=\"$hex\",func=\"main\",file=\".*mi-syn-frame.c\",fullname=\"${fullname_syntax}${srcfile}\",line=\"$decimal\",arch=\"$any\"}.*\\\]" "backtrace from inferior function at exception"
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
index 8d94d24f9b3..402d8f7de69 100644
--- a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
@@ -174,7 +174,7 @@ proc_with_prefix run_bp_cond_segfaults { target_async target_non_stop } {
 	     "Error in testing condition for breakpoint ${bp_1_num}:" \
 	     "The program being debugged was signaled while in a function called from GDB\\." \
 	     "GDB remains in the frame where the signal was received\\." \
-	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "To change this behavior use \"set unwind-on-signal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(function_that_segfaults\\) will be abandoned\\." \
 	     "When the function is done executing, GDB will silently stop\\."]
diff --git a/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp b/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp
index 0b08723fffa..2fa210c506f 100644
--- a/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp
+++ b/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp
@@ -13,7 +13,7 @@
 # You should have received a copy of the GNU General Public License
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-# Test use of unwindonsignal when a hand function call that gets interrupted
+# Test use of unwind-on-signal when a hand function call that gets interrupted
 # by a signal in another thread.
 
 set NR_THREADS 4
@@ -52,12 +52,12 @@ gdb_test "continue" \
 # We want the main thread (hand_call_with_signal) and
 # thread 1 (sigabrt_handler) to both run.
 
-# Do turn on unwindonsignal.
+# Do turn on unwind-on-signal.
 # We want to test gdb handling of the current thread changing when
 # unwindonsignal is in effect.
-gdb_test_no_output "set unwindonsignal on" \
+gdb_test_no_output "set unwind-on-signal on" \
 	"setting unwindonsignal"
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
 	"Unwinding of stack .* is on." \
 	"showing unwindonsignal"
 
-- 
2.25.4


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

* Re: [PATCHv2 01/13] gdb/doc: extended documentation for inferior function calls
  2023-01-18 16:17   ` [PATCHv2 01/13] gdb/doc: extended documentation for inferior function calls Andrew Burgess
@ 2023-01-18 17:20     ` Eli Zaretskii
  2023-03-16 17:15       ` Andrew Burgess
  2023-01-19  9:00     ` Aktemur, Tankut Baris
  1 sibling, 1 reply; 202+ messages in thread
From: Eli Zaretskii @ 2023-01-18 17:20 UTC (permalink / raw)
  To: Andrew Burgess; +Cc: gdb-patches

> Cc: Andrew Burgess <aburgess@redhat.com>
> Date: Wed, 18 Jan 2023 16:17:57 +0000
> From: Andrew Burgess via Gdb-patches <gdb-patches@sourceware.org>
> 
> I noticed that the documentation for inferior function calls doesn't
> say much about what happens if/when an inferior function call is
> interrupted, i.e. it doesn't describe what the dummy frame looks like
> on the stack, or how GDB behaves when the inferior is continued and
> reaches the dummy frame.
> 
> This commit aims to add some of this missing information.

Thanks.

> +If a called function is interrupted for any reason, and the stack is
> +not unwound (due to @code{set unwind-on-terminating-exception on} or
> +@code{set unwindonsignal on}),

Please add here a cross-reference to here these settings are described
in the manual.

Otherwise, this is OK.

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

* Re: [PATCHv2 02/13] gdb/doc: extend the documentation for conditional breakpoints
  2023-01-18 16:17   ` [PATCHv2 02/13] gdb/doc: extend the documentation for conditional breakpoints Andrew Burgess
@ 2023-01-18 17:22     ` Eli Zaretskii
  2023-01-19  9:04     ` Aktemur, Tankut Baris
  1 sibling, 0 replies; 202+ messages in thread
From: Eli Zaretskii @ 2023-01-18 17:22 UTC (permalink / raw)
  To: Andrew Burgess; +Cc: gdb-patches

> Cc: Andrew Burgess <aburgess@redhat.com>
> Date: Wed, 18 Jan 2023 16:17:58 +0000
> From: Andrew Burgess via Gdb-patches <gdb-patches@sourceware.org>
> 
> This documentation update adds more text to describe what happens if a
> conditional breakpoint calls an inferior function, and the inferior
> function is interrupted for some reason.
> ---
>  gdb/doc/gdb.texinfo | 11 +++++++++++
>  1 file changed, 11 insertions(+)

This is okay, thanks.

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

* Re: [PATCHv2 10/13] gdb: add timeouts for inferior function calls
  2023-01-18 16:18   ` [PATCHv2 10/13] gdb: add timeouts for inferior function calls Andrew Burgess
@ 2023-01-18 17:30     ` Eli Zaretskii
  2023-01-20  8:50     ` Aktemur, Tankut Baris
  1 sibling, 0 replies; 202+ messages in thread
From: Eli Zaretskii @ 2023-01-18 17:30 UTC (permalink / raw)
  To: Andrew Burgess; +Cc: gdb-patches

> Cc: Andrew Burgess <aburgess@redhat.com>
> Date: Wed, 18 Jan 2023 16:18:06 +0000
> From: Andrew Burgess via Gdb-patches <gdb-patches@sourceware.org>
> 
> diff --git a/gdb/NEWS b/gdb/NEWS
> index c0aac212e30..2689569a8f3 100644
> --- a/gdb/NEWS
> +++ b/gdb/NEWS
> @@ -17,6 +17,24 @@ maintenance print record-instruction [ N ]
>    prints how GDB would undo the N-th previous instruction, and if N is
>    positive, it prints how GDB will redo the N-th following instruction.
>  
> +set direct-call-timeout SECONDS
> +show direct-call-timeout
> +set indirect-call-timeout SECONDS
> +show indirect-call-timeout
> +  These new settings can be used to limit how long GDB will wait for
> +  an inferior function call to complete.  The direct timeout is used
> +  for inferior function calls from e.g. 'call' and 'print' commands,
> +  while the indirect timeout is used for inferior function calls from
> +  within a conditional breakpoint expression.
> +
> +  The default for the direct timeout is unlimited, while the default
> +  for the indirect timeout is 30 seconds.
> +
> +  These timeouts will only have an effect for targets that are
> +  operating in async mode.  For non-async targets the timeouts are
> +  ignored, GDB will wait indefinitely for an inferior function to
> +  complete, unless interrupted by the user using Ctrl-C.

This part is OK.

> +This setting is used when the user calls a function directly from the
> +command prompt, for example with a @code{call} or @code{print}
> +command.

Please add here cross-references to where these commands are
described.

> +This setting only works for targets that support asynchronous
> +execution (@pxref{Background Execution}), for any other target the
> +setting is treated as @code{unlimited}.

This is a repetition of what you already wrote above.  I don't think
we need to repeat this so close to the previous location.

> +This setting only works for targets that support asynchronous
> +execution (@pxref{Background Execution}), for any other target the
> +setting is treated as @code{unlimited}.

And this is another unneeded repetition.

> +  add_setshow_uinteger_cmd ("direct-call-timeout", no_class,
> +			    &direct_call_timeout, _("\
> +Set the timeout, for direct calls to inferior function calls."), _("\
> +Show the timeout, for direct calls to inferior function calls."), _("\

"direct calls to inferior function calls" sounds awkwardly.  I guess
you wanted to remove the second instance of "calls"?

> +  add_setshow_uinteger_cmd ("indirect-call-timeout", no_class,
> +			    &indirect_call_timeout, _("\
> +Set the timeout, for indirect calls to inferior function calls."), _("\
> +Show the timeout, for indirect calls to inferior function calls."), _("\

Likewise here.

Thanks.

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

* Re: [PATCHv2 12/13] gdb: introduce unwind-on-timeout setting
  2023-01-18 16:18   ` [PATCHv2 12/13] gdb: introduce unwind-on-timeout setting Andrew Burgess
@ 2023-01-18 17:33     ` Eli Zaretskii
  2023-01-20  9:26     ` Aktemur, Tankut Baris
  1 sibling, 0 replies; 202+ messages in thread
From: Eli Zaretskii @ 2023-01-18 17:33 UTC (permalink / raw)
  To: Andrew Burgess; +Cc: gdb-patches

> Cc: Andrew Burgess <aburgess@redhat.com>
> Date: Wed, 18 Jan 2023 16:18:08 +0000
> From: Andrew Burgess via Gdb-patches <gdb-patches@sourceware.org>
> 
> +set unwind-on-timeout on|off
> +show unwind-on-timeout
> +  These commands control whether GDB should unwind the stack when a
> +  timeout occurs during an inferior function call.  The default is
> +  off, in which case the inferior will remain in the frame where the
> +  timeout occurred.  When on GDB will unwind the stack remocing the
                               ^                          ^^^^^^^^
A comma is missing there.  Also, a typo: "remocing".

The documentation parts are OK with those nits fixed.  Thanks.

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

* Re: [PATCHv2 13/13] gdb: rename unwindonsignal to unwind-on-signal
  2023-01-18 16:18   ` [PATCHv2 13/13] gdb: rename unwindonsignal to unwind-on-signal Andrew Burgess
@ 2023-01-18 17:35     ` Eli Zaretskii
  0 siblings, 0 replies; 202+ messages in thread
From: Eli Zaretskii @ 2023-01-18 17:35 UTC (permalink / raw)
  To: Andrew Burgess; +Cc: gdb-patches

> Cc: Andrew Burgess <aburgess@redhat.com>
> Date: Wed, 18 Jan 2023 16:18:09 +0000
> From: Andrew Burgess via Gdb-patches <gdb-patches@sourceware.org>
> 
> We now have unwind-on-timeout and unwind-on-terminating-exception, and
> then the odd one out unwindonsignal.
> 
> I'm not a great fan of these squashed together command names, so in
> this commit I propose renaming this to unwind-on-signal.
> 
> Obviously I've added the hidden alias unwindonsignal so any existing
> GDB scripts will keep working.
> 
> There's one test that I've extended to test the alias works, but in
> most of the other test scripts I've changed over to use the new name.
> 
> The docs are updated to reference the new name.
> ---
>  gdb/NEWS                                      | 11 ++++++
>  gdb/doc/gdb.texinfo                           | 16 ++++++---
>  gdb/infcall.c                                 | 21 ++++++-----
>  gdb/testsuite/gdb.base/callfuncs.exp          |  4 +--
>  gdb/testsuite/gdb.base/infcall-failure.exp    |  4 +--
>  gdb/testsuite/gdb.base/unwindonsignal.exp     | 36 +++++++++++++------
>  gdb/testsuite/gdb.compile/compile-cplus.exp   |  2 +-
>  gdb/testsuite/gdb.compile/compile.exp         |  2 +-
>  gdb/testsuite/gdb.cp/gdb2495.exp              | 16 ++++-----
>  gdb/testsuite/gdb.fortran/function-calls.exp  |  2 +-
>  gdb/testsuite/gdb.mi/mi-syn-frame.exp         |  2 +-
>  .../infcall-from-bp-cond-simple.exp           |  2 +-
>  .../gdb.threads/thread-unwindonsignal.exp     |  8 ++---
>  13 files changed, 83 insertions(+), 43 deletions(-)

These are mechanical renames, right?  I don't think they need a review
and approval.

Thanks.

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

* RE: [PATCHv2 01/13] gdb/doc: extended documentation for inferior function calls
  2023-01-18 16:17   ` [PATCHv2 01/13] gdb/doc: extended documentation for inferior function calls Andrew Burgess
  2023-01-18 17:20     ` Eli Zaretskii
@ 2023-01-19  9:00     ` Aktemur, Tankut Baris
  1 sibling, 0 replies; 202+ messages in thread
From: Aktemur, Tankut Baris @ 2023-01-19  9:00 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

On Wednesday, January 18, 2023 5:18 PM, Andrew Burgess wrote:
> I noticed that the documentation for inferior function calls doesn't
> say much about what happens if/when an inferior function call is
> interrupted, i.e. it doesn't describe what the dummy frame looks like
> on the stack, or how GDB behaves when the inferior is continued and
> reaches the dummy frame.
> 
> This commit aims to add some of this missing information.
> ---
>  gdb/doc/gdb.texinfo | 30 ++++++++++++++++++++++++++++++
>  1 file changed, 30 insertions(+)
> 
> diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
> index 9c0018ea5c1..e05813ff502 100644
> --- a/gdb/doc/gdb.texinfo
> +++ b/gdb/doc/gdb.texinfo
> @@ -20731,6 +20731,36 @@
> 
>  @end table
> 
> +When calling a function within a program, it is possible that the
> +program could enter a state from which the called function may never
> +return.  If this happens then it is possible to interrupt the function
> +call by typing the interrupt character (often @kbd{Ctrl-c}).

It may help, as a reminder to the reader, to additionally state that 
the called function may hit a breakpoint.  That's another interesting
(and arguably common) reason for why an infcall could stop.

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] 202+ messages in thread

* RE: [PATCHv2 02/13] gdb/doc: extend the documentation for conditional breakpoints
  2023-01-18 16:17   ` [PATCHv2 02/13] gdb/doc: extend the documentation for conditional breakpoints Andrew Burgess
  2023-01-18 17:22     ` Eli Zaretskii
@ 2023-01-19  9:04     ` Aktemur, Tankut Baris
  2023-01-19 10:07       ` Eli Zaretskii
  1 sibling, 1 reply; 202+ messages in thread
From: Aktemur, Tankut Baris @ 2023-01-19  9:04 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

On Wednesday, January 18, 2023 5:18 PM, Andrew Burgess wrote:
> This documentation update adds more text to describe what happens if a
> conditional breakpoint calls an inferior function, and the inferior
> function is interrupted for some reason.
> ---
>  gdb/doc/gdb.texinfo | 11 +++++++++++
>  1 file changed, 11 insertions(+)
> 
> diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
> index e05813ff502..6ea173b5d0b 100644
> --- a/gdb/doc/gdb.texinfo
> +++ b/gdb/doc/gdb.texinfo
> @@ -5713,6 +5713,17 @@
>  purpose of performing side effects when a breakpoint is reached
>  (@pxref{Break Commands, ,Breakpoint Command Lists}).
> 
> +If a breakpoint condition calls a function in your program, then it is
> +possible that your program could stop for some reason while in the
> +called function.  For example, @value{GDBN} might hit a breakpoint in
> +the called function, or the called function may receive a signal
> +(e.g.@ a @code{SIGSEGV}) as a result of some undefined behaviour, if

It seems to me like this could be "... behaviour. If ...".

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] 202+ messages in thread

* RE: [PATCHv2 03/13] gdb: include breakpoint number in testing condition error message
  2023-01-18 16:17   ` [PATCHv2 03/13] gdb: include breakpoint number in testing condition error message Andrew Burgess
@ 2023-01-19  9:54     ` Aktemur, Tankut Baris
  2023-01-19 10:54     ` Aktemur, Tankut Baris
  1 sibling, 0 replies; 202+ messages in thread
From: Aktemur, Tankut Baris @ 2023-01-19  9:54 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

On Wednesday, January 18, 2023 5:18 PM, Andrew Burgess wrote:
> When GDB fails to test the condition of a conditional breakpoint, for
> whatever reason, the error message looks like this:
> 
>   (gdb) break foo if (*(int *) 0) == 1
>   Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
>   (gdb) r
>   Starting program: /tmp/bpcond
>   Error in testing breakpoint condition:
>   Cannot access memory at address 0x0
> 
>   Breakpoint 1, foo () at bpcond.c:11
>   11	  int a = 32;
>   (gdb)
> 
> The line I'm interested in for this commit is this one:
> 
>   Error in testing breakpoint condition:
> 
> In the case above we can figure out that the problematic breakpoint
> was #1 because in the final line of the message GDB reports the stop a
> breakpoint #1.
...
> diff --git a/gdb/testsuite/gdb.base/bp-cond-failure.c b/gdb/testsuite/gdb.base/bp-cond-
> failure.c
> new file mode 100644
> index 00000000000..be9d1fdcf2d
> --- /dev/null
> +++ b/gdb/testsuite/gdb.base/bp-cond-failure.c
> @@ -0,0 +1,30 @@
> +/* Copyright 2022 Free Software Foundation, Inc.

The year now has to be 2022-2023, I believe.  There is one more case
below.

...
> diff --git a/gdb/testsuite/gdb.base/bp-cond-failure.exp b/gdb/testsuite/gdb.base/bp-cond-
> failure.exp
> new file mode 100644
> index 00000000000..6f89771d187
> --- /dev/null
> +++ b/gdb/testsuite/gdb.base/bp-cond-failure.exp
> @@ -0,0 +1,83 @@
> +# Copyright 2022 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/>.
> +
> +# Check the format of the error message given when a breakpoint
> +# condition fails.
> +#
> +# In this case the breakpoint condition does not make use of inferior
> +# function calls, instead, the expression used for the breakpoint
> +# condition will throw an error when evaluated.
> +#
> +# We check that the correct breakpoint number appears in the error
> +# message, and that the error is reported at the correct source
> +# location.
> +
> +standard_testfile
> +
> +if { [prepare_for_testing "failed to prepare" ${binfile} "${srcfile}" \
> +	  {debug}] == -1 } {
> +    return
> +}
> +
> +# This test relies on reading address zero triggering a SIGSEGV.
> +if { [is_address_zero_readable] } {
> +    return
> +}
> +
> +# Where the breakpoint will be placed.
> +set bp_line [gdb_get_line_number "Breakpoint here"]
> +
> +proc run_test { cond_eval } {
> +    clean_restart ${::binfile}
> +
> +    if {![runto_main]} {

The other if-statements in this file put spaces around the condition.

> +	fail "run to main"
> +	return -1
> +    }
> +
> +    if { $cond_eval != "auto" } {

AFAIK, for string comparison, `eq` and `ne` are the recommended operators to use.

> +	gdb_test_no_output "set breakpoint condition-evaluation ${cond_eval}"
> +    }
> +
> +    # Setup the conditional breakpoint and record its number.
> +    gdb_breakpoint "${::srcfile}:${::bp_line} if (*(int *) 0) == 0"
> +    set bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*"]
> +
> +    gdb_test "continue" \
> +	[multi_line \
> +	     "Continuing\\." \
> +	     "Error in testing condition for breakpoint ${bp_num}:" \
> +	     "Cannot access memory at address 0x0" \
> +	     "" \
> +	     "Breakpoint ${bp_num}, foo \\(\\) at \[^\r\n\]+:${::bp_line}" \
> +	     "${::decimal}\\s+\[^\r\n\]+Breakpoint here\[^\r\n\]+"]
> +}
> +
> +# If we're using a remote target then conditions could be evaulated
> +# locally on the host, or on the remote target.  Otherwise, conditions
> +# are always evaluated locally (which is what auto will select).
> +#
> +# NOTE: 'target' is not included here for remote targets as a
> +# gdbserver bug prevents the test from passing.  This will be fixed in
> +# the next commit, and this test updated.
> +if { [gdb_is_remote_or_extended_remote_target] } {
> +    set cond_eval_modes { "host" }
> +} else {
> +    set cond_eval_modes { "auto" }
> +}
> +
> +foreach_with_prefix cond_eval $cond_eval_modes {
> +    run_test $cond_eval
> +}
> diff --git a/gdb/testsuite/gdb.base/catch-signal-siginfo-cond.exp
> b/gdb/testsuite/gdb.base/catch-signal-siginfo-cond.exp
> index 182b2f25faa..f400fc03b28 100644
> --- a/gdb/testsuite/gdb.base/catch-signal-siginfo-cond.exp
> +++ b/gdb/testsuite/gdb.base/catch-signal-siginfo-cond.exp
> @@ -18,7 +18,7 @@
>  #
>  # (gdb) continue
>  # Continuing.
> -# Error in testing breakpoint condition:
> +# Error in testing condition for breakpoint NUM:
>  # Selected thread is running.
>  #
>  # Catchpoint 3 (signal SIGUSR1), 0x0000003615e35877 in __GI_raise (sig=10) at raise.c:56
> diff --git a/gdb/testsuite/gdb.base/gnu-ifunc.exp b/gdb/testsuite/gdb.base/gnu-ifunc.exp
> index 0a435806409..22462bea233 100644
> --- a/gdb/testsuite/gdb.base/gnu-ifunc.exp
> +++ b/gdb/testsuite/gdb.base/gnu-ifunc.exp
> @@ -281,7 +281,7 @@ proc misc_tests {resolver_attr resolver_debug final_debug} {
> 
>      # Also test a former patch regression:
>      # Continuing.
> -    # Error in testing breakpoint condition:
> +    # Error in testing condition for breakpoint NUM:
>      # Attempt to take address of value not located in memory.
>      #
>      # Breakpoint 2, main () at ./gdb.base/gnu-ifunc.c:33
> diff --git a/gdb/testsuite/gdb.python/py-finish-breakpoint.exp
> b/gdb/testsuite/gdb.python/py-finish-breakpoint.exp
> index b6bd7a63c8f..e5a46874afd 100644
> --- a/gdb/testsuite/gdb.python/py-finish-breakpoint.exp
> +++ b/gdb/testsuite/gdb.python/py-finish-breakpoint.exp
> @@ -188,7 +188,7 @@ with_test_prefix "finish in normal frame" {
>      gdb_test "python TestBreakpoint()" "TestBreakpoint init" "set BP in condition"
> 
>      gdb_test "continue" \
> -	"test don't stop: 1.*test don't stop: 2.*test stop.*Error in testing breakpoint
> condition.*The program being debugged stopped while in a function called from GDB.*" \
> +	"test don't stop: 1.*test don't stop: 2.*test stop.*Error in testing condition for
> breakpoint ${::decimal}.*The program being debugged stopped while in a function called from
> GDB.*" \
>  	"stop in condition function"
> 
>      gdb_test "continue" "Continuing.*" "finish condition evaluation"
> diff --git a/gdb/testsuite/lib/gdb.exp b/gdb/testsuite/lib/gdb.exp
> index 68337bd235c..f51332b0177 100644
> --- a/gdb/testsuite/lib/gdb.exp
> +++ b/gdb/testsuite/lib/gdb.exp
> @@ -9332,5 +9332,13 @@ proc has_dependency { file dep } {
>      return [regexp $dep $output]
>  }
> 
> +# Return true if we are currently testing the 'remote' or
> +# 'extended-remote' targets.
> +proc gdb_is_remote_or_extended_remote_target {} {
> +    return [target_info exists gdb_protocol]
> +	   && ([target_info gdb_protocol] == "remote"
> +	       || [target_info gdb_protocol] == "extended-remote")

Here, the same comment about `eq` and `ne` for string comparison.

> +}
> +
>  # Always load compatibility stuff.
>  load_lib future.exp
> --
> 2.25.4


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] 202+ messages in thread

* RE: [PATCHv2 04/13] gdbserver: allows agent_mem_read to return an error code
  2023-01-18 16:18   ` [PATCHv2 04/13] gdbserver: allows agent_mem_read to return an error code Andrew Burgess
@ 2023-01-19  9:59     ` Aktemur, Tankut Baris
  0 siblings, 0 replies; 202+ messages in thread
From: Aktemur, Tankut Baris @ 2023-01-19  9:59 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

On Wednesday, January 18, 2023 5:18 PM, Andrew Burgess wrote:
> Currently the gdbserver function agent_mem_read ignores any errors
> from calling read_inferior_memory.  This means that if there is an
> attempt to access invalid memory then this will appear to succeed.
> 
> In this I update agent_mem_read so that if read_inferior_memory fails,

Did you mean "In this *patch* I update"?

> agent_mem_read will return an error code.
> 
> However, non of the callers of agent_mem_read actually check the

non -> none

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] 202+ messages in thread

* Re: [PATCHv2 02/13] gdb/doc: extend the documentation for conditional breakpoints
  2023-01-19  9:04     ` Aktemur, Tankut Baris
@ 2023-01-19 10:07       ` Eli Zaretskii
  0 siblings, 0 replies; 202+ messages in thread
From: Eli Zaretskii @ 2023-01-19 10:07 UTC (permalink / raw)
  To: Aktemur, Tankut Baris; +Cc: aburgess, gdb-patches

> Date: Thu, 19 Jan 2023 09:04:03 +0000
> From: "Aktemur, Tankut Baris via Gdb-patches" <gdb-patches@sourceware.org>
> 
> > +If a breakpoint condition calls a function in your program, then it is
> > +possible that your program could stop for some reason while in the
> > +called function.  For example, @value{GDBN} might hit a breakpoint in
> > +the called function, or the called function may receive a signal
> > +(e.g.@ a @code{SIGSEGV}) as a result of some undefined behaviour, if
> 
> It seems to me like this could be "... behaviour. If ...".

And in any case it should be "behavior", as we use US English
spelling.

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

* RE: [PATCHv2 05/13] gdbserver: allow agent expressions to fail with invalid memory access
  2023-01-18 16:18   ` [PATCHv2 05/13] gdbserver: allow agent expressions to fail with invalid memory access Andrew Burgess
@ 2023-01-19 10:13     ` Aktemur, Tankut Baris
  0 siblings, 0 replies; 202+ messages in thread
From: Aktemur, Tankut Baris @ 2023-01-19 10:13 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

On Wednesday, January 18, 2023 5:18 PM, Andrew Burgess wrote:
> This commit extends gdbserver to take account of a failed memory
> access from agent_mem_read, and to return a new eval_result_type
> expr_eval_invalid_memory_access.
> 
> I have only updated the agent_mem_read calls related directly to
> reading memory, I have not updated any of the calls related to
> tracepoint data collection.  This is just because I'm not familiar
> with that area of gdb/gdbserver, and I don't want to break anything,
> so leaving the existing behaviour as is seems like the safest

is -> it

> approach.
> 
> I've then update gdb.base/bp-cond-failure.exp to test evaluating the

update -> updated

> breakpoints on the target, and have also extended the test so that it
> checks for different sizes of memory access.
> ---
>  gdb/testsuite/gdb.base/bp-cond-failure.exp | 16 +++++++---------
>  gdbserver/ax.cc                            | 12 ++++++++----
>  gdbserver/ax.h                             |  3 ++-
>  3 files changed, 17 insertions(+), 14 deletions(-)
> 
> diff --git a/gdb/testsuite/gdb.base/bp-cond-failure.exp b/gdb/testsuite/gdb.base/bp-cond-
> failure.exp
> index 6f89771d187..aa39b638592 100644
> --- a/gdb/testsuite/gdb.base/bp-cond-failure.exp
> +++ b/gdb/testsuite/gdb.base/bp-cond-failure.exp
> @@ -39,7 +39,7 @@ if { [is_address_zero_readable] } {
>  # Where the breakpoint will be placed.
>  set bp_line [gdb_get_line_number "Breakpoint here"]
> 
> -proc run_test { cond_eval } {
> +proc run_test { cond_eval access_type } {
>      clean_restart ${::binfile}
> 
>      if {![runto_main]} {
> @@ -52,7 +52,7 @@ proc run_test { cond_eval } {
>      }
> 
>      # Setup the conditional breakpoint and record its number.
> -    gdb_breakpoint "${::srcfile}:${::bp_line} if (*(int *) 0) == 0"
> +    gdb_breakpoint "${::srcfile}:${::bp_line} if (*(${access_type} *) 0) == 0"
>      set bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*"]
> 
>      gdb_test "continue" \
> @@ -68,16 +68,14 @@ proc run_test { cond_eval } {
>  # If we're using a remote target then conditions could be evaulated
>  # locally on the host, or on the remote target.  Otherwise, conditions
>  # are always evaluated locally (which is what auto will select).
> -#
> -# NOTE: 'target' is not included here for remote targets as a
> -# gdbserver bug prevents the test from passing.  This will be fixed in
> -# the next commit, and this test updated.
>  if { [gdb_is_remote_or_extended_remote_target] } {
> -    set cond_eval_modes { "host" }
> +    set cond_eval_modes { "host" "target" }

If this test were executed against a gdbserver build that does not support
condition evaluation, would we get failures?  To that regard, would it be safer
to define the modes as { "host" "auto" }?

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] 202+ messages in thread

* RE: [PATCHv2 06/13] gdb: avoid repeated signal reporting during failed conditional breakpoint
  2023-01-18 16:18   ` [PATCHv2 06/13] gdb: avoid repeated signal reporting during failed conditional breakpoint Andrew Burgess
@ 2023-01-19 10:33     ` Aktemur, Tankut Baris
  0 siblings, 0 replies; 202+ messages in thread
From: Aktemur, Tankut Baris @ 2023-01-19 10:33 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

On Wednesday, January 18, 2023 5:18 PM, Andrew Burgess wrote:
> Consider the following case:
> 
>   (gdb) list some_func
>   1	int
>   2	some_func ()
>   3	{
>   4	  int *p = 0;
>   5	  return *p;
>   6	}
>   7
>   8	void
>   9	foo ()
>   10	{
>   (gdb) break foo if (some_func ())
>   Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
>   (gdb) r
>   Starting program: /tmp/bpcond
> 
>   Program received signal SIGSEGV, Segmentation fault.
>   0x0000000000401116 in some_func () at bpcond.c:5
>   5	  return *p;
>   Error in testing breakpoint condition:
>   The program being debugged was signaled while in a function called from GDB.
>   GDB remains in the frame where the signal was received.
>   To change this behavior use "set unwindonsignal on".
>   Evaluation of the expression containing the function
>   (some_func) will be abandoned.
>   When the function is done executing, GDB will silently stop.
> 
>   Program received signal SIGSEGV, Segmentation fault.
> 
>   Breakpoint 1, 0x0000000000401116 in some_func () at bpcond.c:5
>   5	  return *p;
>   (gdb)
> 
> Notice that this line:
> 
>   Program received signal SIGSEGV, Segmentation fault.
> 
> Appears twice in the output.  The first time is followed by the
> current location.  The second time is a little odd, why do we print
> that?
> 
> Printing that line is controlled, in part, by a global variable,
> stopped_by_random_signal.  This variable is reset to zero in
> handle_signal_stop, and is set if/when GDB figures out that the
> inferior stopped due to some random signal.
> 
> The problem is, in our case, GDB first stops at the breakpoint for
> foo, and enters handle_signal_stop and the stopped_by_random_signal
> global is reset to 0.
> 
> Later within handle_signal_stop GDB calls bpstat_stop_status, it is
> within this function (via bpstat_check_breakpoint_conditions) that the
> breakpoint condition is checked, and, we end up calling the inferior
> function (some_func in our example above).
> 
> In our case above the thread performing the inferior function call
> segfaults in some_func.  GDB catches the SIGSEGV and handles the stop,
> this causes us to reenter handle_signal_stop.  The global variable
> stopped_by_random_signal is updated, this time it is set to true
> because the thread stopped due to SIGSEGV.  As a result of this we
> print the first instance of the line (as seen above in the example).
> 
> Finally we unwind GDB's call stack, the inferior function call is
> complete, and we return to the original handle_signal_stop.  However,
> the stopped_by_random_signal global is still carrying the value as
> computed for the inferior function call's stop, which is why we now
> print a second instance of the line, as seen in the example.
> 
> To prevent this, I propose adding a scoped_restore before we start an
> inferior function call, this will save and restore the global
> stopped_by_random_signal value.

Nit: It'd read better, I think, if this read
"... function call. This will save ..."
 
> With this done, the output from our example is now this:
> 
>  (gdb) list some_func
>   1	int
>   2	some_func ()
>   3	{
>   4	  int *p = 0;
>   5	  return *p;
>   6	}
>   7
>   8	void
>   9	foo ()
>   10	{
>   (gdb) break foo if (some_func ())
>   Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
>   (gdb) r
>   Starting program: /tmp/bpcond
> 
>   Program received signal SIGSEGV, Segmentation fault.
>   0x0000000000401116 in some_func () at bpcond.c:5
>   5	  return *p;
>   Error in testing condition for breakpoint 1:
>   The program being debugged stopped while in a function called from GDB.
>   Evaluation of the expression containing the function
>   (some_func) will be abandoned.
>   When the function is done executing, GDB will silently stop.
> 
>   Breakpoint 1, 0x0000000000401116 in some_func () at bpcond.c:5
>   5	  return *p;
>   (gdb)
> 
> We now only see the 'Program received signal SIGSEGV, ...' line once,
> which I think makes more sense.
> 
> Finally, I'm aware that the last few lines, that report the stop as
> being at 'Breakpoint 1', when this is not where the thread is actually
> located anymore, is not great.  I'll address that in the next commit.
> ---
>  gdb/infcall.c                              |   9 +
>  gdb/testsuite/gdb.base/infcall-failure.c   |  48 ++++++
>  gdb/testsuite/gdb.base/infcall-failure.exp | 184 +++++++++++++++++++++
>  3 files changed, 241 insertions(+)
>  create mode 100644 gdb/testsuite/gdb.base/infcall-failure.c
>  create mode 100644 gdb/testsuite/gdb.base/infcall-failure.exp
> 
> diff --git a/gdb/infcall.c b/gdb/infcall.c
> index e09904f9a35..e1b785e437b 100644
> --- a/gdb/infcall.c
> +++ b/gdb/infcall.c
> @@ -1296,6 +1296,15 @@ call_function_by_hand_dummy (struct value *function,
>    /* Register a clean-up for unwind_on_terminating_exception_breakpoint.  */
>    SCOPE_EXIT { delete_std_terminate_breakpoint (); };
> 
> +  /* The stopped_by_random_signal variable is global.  If we are here
> +     as part of a breakpoint condition check then the global will have
> +     already been setup as part of the original breakpoint stop.  By
> +     making the inferior call the global will be changed when GDB
> +     handles the stop after the inferior call.  Avoid confusion by
> +     restoring the current value after the inferior call.  */
> +  scoped_restore restore_stopped_by_random_signal
> +    = make_scoped_restore (&stopped_by_random_signal, 0);
> +
>    /* - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP -
>       If you're looking to implement asynchronous dummy-frames, then
>       just below is the place to chop this function in two..  */
> diff --git a/gdb/testsuite/gdb.base/infcall-failure.c b/gdb/testsuite/gdb.base/infcall-
> failure.c
> new file mode 100644
> index 00000000000..00f4369e164
> --- /dev/null
> +++ b/gdb/testsuite/gdb.base/infcall-failure.c
> @@ -0,0 +1,48 @@
> +/* Copyright 2022 Free Software Foundation, Inc.

2022-2023?

> +
> +   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/>.  */
> +
> +/* A function that segfaults (assuming that reads of address zero are
> +   prohibited), this is used from within a breakpoint condition.  */
> +int
> +func_segfault ()
> +{
> +  volatile int *p = 0;
> +  return *p;	/* Segfault here.  */
> +}
> +
> +/* A function in which we will place a breakpoint.  This function is itself
> +   then used from within a breakpoint condition.  */
> +int
> +func_bp ()
> +{
> +  int res = 0;	/* Second breakpoint.  */
> +  return res;
> +}
> +
> +int
> +foo ()
> +{
> +  return 0;	/* First breakpoint.  */
> +}
> +
> +int
> +main ()
> +{
> +  int res = foo ();
> +
> +  return res;
> +}
> diff --git a/gdb/testsuite/gdb.base/infcall-failure.exp b/gdb/testsuite/gdb.base/infcall-
> failure.exp
> new file mode 100644
> index 00000000000..2dcdda34b4d
> --- /dev/null
> +++ b/gdb/testsuite/gdb.base/infcall-failure.exp
> @@ -0,0 +1,184 @@
> +# Copyright 2022 Free Software Foundation, Inc.

2022-2023?

> +
> +# 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/>.
> +
> +# Some simple tests of inferior function calls from breakpoint
> +# conditions, in a single-threaded inferior.
> +#
> +# Test what happens when the inferior function (from a breakpoint
> +# condition) either hits a nested breakpoint, or segfaults.
> +
> +standard_testfile
> +
> +if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
> +	  {debug}] == -1 } {
> +    return
> +}
> +
> +set bp_1_line [gdb_get_line_number "First breakpoint"]
> +set bp_2_line [gdb_get_line_number "Second breakpoint"]
> +set segv_line [gdb_get_line_number "Segfault here"]
> +
> +# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto
> +# main.
> +proc start_gdb_and_runto_main { target_async target_non_stop } {
> +    save_vars { ::GDBFLAGS } {
> +	append ::GDBFLAGS \
> +	    " -ex \"maint set target-non-stop $target_non_stop\""
> +	append ::GDBFLAGS \
> +	    " -ex \"maintenance set target-async ${target_async}\""
> +
> +	clean_restart ${::binfile}
> +    }
> +
> +    if {![runto_main]} {

Other if-statements in this file put spaces around the condition.

> +	fail "run to main"

Commit 4dfef5be6812dd7abfbc8f18e9c0384f2522b511 ("gdb/testsuite: make
runto_main not pass no-message to runto") eliminated the need to emit a 
fail explicitly. 

> +	return -1
> +    }
> +
> +    return 0
> +}
> +
> +# Start GDB according to ASYNC_P and NON_STOP_P, then setup a
> +# conditional breakpoint.  The breakpoint condition includes an
> +# inferior function call that will itself hit a breakpoint.  Check how
> +# GDB reports this to the user.
> +proc_with_prefix run_cond_hits_breakpoint_test { async_p non_stop_p } {
> +    if { [start_gdb_and_runto_main $async_p $non_stop_p] == -1 } {
> +	return
> +    }
> +
> +    # Setup the conditional breakpoint and record its number.
> +    gdb_breakpoint "${::srcfile}:${::bp_1_line} if (func_bp ())"
> +    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
> +		     "get number of first breakpoint"]
> +
> +    # Setup a breakpoint inside func_bp.
> +    gdb_breakpoint "${::srcfile}:${::bp_2_line}"
> +    set bp_2_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
> +		     "get number of second breakpoint"]
> +
> +    gdb_test "continue" \
> +	[multi_line \
> +	     "Continuing\\." \
> +	     "" \
> +	     "Breakpoint ${bp_2_num}, func_bp \\(\\) at \[^\r\n\]+:${::bp_2_line}" \
> +	     "${::decimal}\\s+\[^\r\n\]+Second breakpoint\[^\r\n\]+" \
> +	     "Error in testing condition for breakpoint ${bp_1_num}:" \
> +	     "The program being debugged stopped while in a function called from GDB\\." \
> +	     "Evaluation of the expression containing the function" \
> +	     "\\(func_bp\\) will be abandoned\\." \
> +	     "When the function is done executing, GDB will silently stop\\." \
> +	     "" \
> +	     "Breakpoint ${bp_1_num}, \[^\r\n\]+" \
> +	     "${::decimal}\\s+\[^\r\n\]+Second breakpoint\[^\r\n\]+"]
> +}
> +
> +# Start GDB according to ASYNC_P and NON_STOP_P, then call an inferior
> +# function.  The inferior function being called will itself have a
> +# breakpoint within it.  Check how GDB reports this to the user.
> +proc_with_prefix run_call_hits_breakpoint_test { async_p non_stop_p } {
> +    if { [start_gdb_and_runto_main $async_p $non_stop_p] == -1 } {
> +	return
> +    }
> +
> +    # Setup a breakpoint inside func_bp.
> +    gdb_breakpoint "${::srcfile}:${::bp_2_line}"
> +    set bp_2_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
> +		      "get number of second breakpoint"]
> +
> +
> +    gdb_test "call func_bp ()" \
> +	[multi_line \
> +	     "" \
> +	     "Breakpoint ${bp_2_num}, func_bp \\(\\) at \[^\r\n\]+:${::bp_2_line}" \
> +	     "${::decimal}\\s+\[^\r\n\]+Second breakpoint\[^\r\n\]+" \
> +	     "The program being debugged stopped while in a function called from GDB\\." \
> +	     "Evaluation of the expression containing the function" \
> +	     "\\(func_bp\\) will be abandoned\\." \
> +	     "When the function is done executing, GDB will silently stop\\."]
> +}
> +
> +# Start GDB according to ASYNC_P and NON_STOP_P, then setup a
> +# conditional breakpoint.  The breakpoint condition includes an
> +# inferior function call that segfaults.  Check how GDB reports this
> +# to the user.
> +proc_with_prefix run_cond_hits_segfault_test { async_p non_stop_p } {
> +    if { [start_gdb_and_runto_main $async_p $non_stop_p] == -1 } {
> +	return
> +    }
> +
> +    # This test relies on the inferior segfaulting when trying to
> +    # access address zero.
> +    if { [is_address_zero_readable] } {

Maybe emit an UNTESTED in this case?

> +	return
> +    }
> +
> +    # Setup the conditional breakpoint and record its number.
> +    gdb_breakpoint "${::srcfile}:${::bp_1_line} if (func_segfault ())"
> +    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
> +		     "get number of first breakpoint"]
> +
> +    gdb_test "continue" \
> +	[multi_line \
> +	     "Continuing\\." \
> +	     "" \
> +	     "Program received signal SIGSEGV, Segmentation fault\\." \
> +	     "${::hex} in func_segfault \\(\\) at \[^\r\n\]+:${::segv_line}" \
> +	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
> +	     "Error in testing condition for breakpoint ${bp_1_num}:" \
> +	     "The program being debugged stopped while in a function called from GDB\\." \
> +	     "Evaluation of the expression containing the function" \
> +	     "\\(func_segfault\\) will be abandoned\\." \
> +	     "When the function is done executing, GDB will silently stop\\." \
> +	     "" \
> +	     "Breakpoint ${bp_1_num}, \[^\r\n\]+" \
> +	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"]
> +}
> +
> +# Start GDB according to ASYNC_P and NON_STOP_P, then call an inferior
> +# function.  The inferior function will segfault.  Check how GDB
> +# reports this to the user.
> +proc_with_prefix run_call_hits_segfault_test { async_p non_stop_p } {
> +    if { [start_gdb_and_runto_main $async_p $non_stop_p] == -1 } {
> +	return
> +    }
> +
> +    # This test relies on the inferior segfaulting when trying to
> +    # access address zero.
> +    if { [is_address_zero_readable] } {

Here, too.

> +	return
> +    }
> +
> +    gdb_test "call func_segfault ()" \
> +	[multi_line \
> +	     "" \
> +	     "Program received signal SIGSEGV, Segmentation fault\\." \
> +	     "${::hex} in func_segfault \\(\\) at \[^\r\n\]+:${::segv_line}" \
> +	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
> +	     "The program being debugged stopped while in a function called from GDB\\." \
> +	     "Evaluation of the expression containing the function" \
> +	     "\\(func_segfault\\) will be abandoned\\." \
> +	     "When the function is done executing, GDB will silently stop\\."]
> +}
> +
> +foreach_with_prefix target_async { "on" "off" } {
> +    foreach_with_prefix target_non_stop { "on" "off" } {
> +	run_cond_hits_breakpoint_test $target_async $target_non_stop
> +	run_call_hits_breakpoint_test $target_async $target_non_stop
> +
> +	run_cond_hits_segfault_test $target_async $target_non_stop
> +	run_call_hits_segfault_test $target_async $target_non_stop
> +    }
> +}
> --
> 2.25.4

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] 202+ messages in thread

* RE: [PATCHv2 07/13] gdb: don't always print breakpoint location after failed condition check
  2023-01-18 16:18   ` [PATCHv2 07/13] gdb: don't always print breakpoint location after failed condition check Andrew Burgess
@ 2023-01-19 10:49     ` Aktemur, Tankut Baris
  0 siblings, 0 replies; 202+ messages in thread
From: Aktemur, Tankut Baris @ 2023-01-19 10:49 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

On Wednesday, January 18, 2023 5:18 PM, Andrew Burgess wrote:
> Consider the following session:
> 
>   (gdb) list some_func
>   1	int
>   2	some_func ()
>   3	{
>   4	  int *p = 0;
>   5	  return *p;
>   6	}
>   7
>   8	void
>   9	foo ()
>   10	{
>   (gdb) break foo if (some_func ())
>   Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
>   (gdb) r
>   Starting program: /tmp/bpcond
> 
>   Program received signal SIGSEGV, Segmentation fault.
>   0x0000000000401116 in some_func () at bpcond.c:5
>   5	  return *p;
>   Error in testing condition for breakpoint 1:
>   The program being debugged stopped while in a function called from GDB.
>   Evaluation of the expression containing the function
>   (some_func) will be abandoned.
>   When the function is done executing, GDB will silently stop.
> 
>   Breakpoint 1, 0x0000000000401116 in some_func () at bpcond.c:5
>   5	  return *p;
>   (gdb)
> 
> What happens here is the breakpoint condition includes a call to an
> inferior function, and the inferior function segfaults.  We can see
> that GDB reports the segfault, and then gives an error message that
> indicates that an inferior function call was interrupted.
> 
> After this GDB appears to report that it is stopped at Breakpoint 1,
> inside some_func.
> 
> I find this second stop report a little confusing.  Yes, GDB has
> stopped as a result of hitting breakpoint 1, but, I think the message
> as it currently is might give the impression that the thread is

Something is missing in this sentence, I think.  Did you mean
"I think the message it currently prints might give..."?

> actually stopped at a location of breakpoint 1, which is not the case.
> 
> Also, I find the second stop message draws attention away from
> the "Program received signal SIGSEGV, Segmentation fault" stop
> message, and this second stop might be thought of as replacing in
> someway the earlier message.
> 
> In short, I think that the in the situation above, I think things

Please consider revising this as 
"In short, in the situation above, I think things".

> would be clearer if the second stop message were not reported at all,
> so the output should (I think) look like this:
> 
>   (gdb) list some_func
>   1	int
>   2	some_func ()
>   3	{
>   4	  int *p = 0;
>   5	  return *p;
>   6	}
>   7
>   8	void
>   9	foo ()
>   10	{
>   (gdb) break foo if (some_func ())
>   Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
>   (gdb) r
>   Starting program: /tmp/bpcond
> 
>   Program received signal SIGSEGV, Segmentation fault.
>   0x0000000000401116 in some_func () at bpcond.c:5
>   5	  return *p;
>   Error in testing condition for breakpoint 1:
>   The program being debugged stopped while in a function called from GDB.
>   Evaluation of the expression containing the function
>   (some_func) will be abandoned.
>   When the function is done executing, GDB will silently stop.
>   (gdb)
> 
> The user can still find the number of the breakpoint that triggered
> the initial stop in this line:
> 
>   Error in testing condition for breakpoint 1:
> 
> But there's now only one stop reason reported, the SIGSEGV, which I
> think is much clearer.

FWIW, I agree to this.

> To achieve this change I set the bpstat::print field when:
> 
>   (a) a breakpoint condition evaluation failed, and
> 
>   (b) the $pc of the thread changed during condition evaluation.
> 
> I've updated the existing tests that checked the error message printed
> when a breakpoint condition evaluation failed.
> ---
>  gdb/breakpoint.c                           | 12 ++++++++++++
>  gdb/testsuite/gdb.base/infcall-failure.exp | 18 ++++++++----------
>  2 files changed, 20 insertions(+), 10 deletions(-)
> 
> diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
> index eecaeefed3e..c4fec7e8e55 100644
> --- a/gdb/breakpoint.c
> +++ b/gdb/breakpoint.c
> @@ -5533,6 +5533,7 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
>  	  else
>  	    within_current_scope = false;
>  	}
> +      CORE_ADDR pc_before_check = get_frame_pc (get_selected_frame (nullptr));
>        if (within_current_scope)
>  	{
>  	  try
> @@ -5544,6 +5545,17 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
>  	      exception_fprintf (gdb_stderr, ex,
>  				 "Error in testing condition for breakpoint %d:\n",
>  				 b->number);
> +
> +	      /* If the pc value changed as a result of evaluating the
> +		 condition then we probably stopped within an inferior
> +		 function call due to some unexpected stop, e.g. the thread
> +		 hit another breakpoint, or the thread received an
> +		 unexpected signal.  In this case we don't want to also
> +		 print the information about this breakpoint.  */
> +	      CORE_ADDR pc_after_check
> +		= get_frame_pc (get_selected_frame (nullptr));
> +	      if (pc_before_check != pc_after_check)
> +		bs->print = 0;
>  	    }
>  	}
>        else
> diff --git a/gdb/testsuite/gdb.base/infcall-failure.exp b/gdb/testsuite/gdb.base/infcall-
> failure.exp
> index 2dcdda34b4d..8fa2c407fc5 100644
> --- a/gdb/testsuite/gdb.base/infcall-failure.exp
> +++ b/gdb/testsuite/gdb.base/infcall-failure.exp
> @@ -79,10 +79,7 @@ proc_with_prefix run_cond_hits_breakpoint_test { async_p non_stop_p } {
>  	     "The program being debugged stopped while in a function called from GDB\\." \
>  	     "Evaluation of the expression containing the function" \
>  	     "\\(func_bp\\) will be abandoned\\." \
> -	     "When the function is done executing, GDB will silently stop\\." \
> -	     "" \
> -	     "Breakpoint ${bp_1_num}, \[^\r\n\]+" \
> -	     "${::decimal}\\s+\[^\r\n\]+Second breakpoint\[^\r\n\]+"]
> +	     "When the function is done executing, GDB will silently stop\\."]
>  }
> 
>  # Start GDB according to ASYNC_P and NON_STOP_P, then call an inferior
> @@ -138,13 +135,12 @@ proc_with_prefix run_cond_hits_segfault_test { async_p non_stop_p } {
>  	     "${::hex} in func_segfault \\(\\) at \[^\r\n\]+:${::segv_line}" \
>  	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
>  	     "Error in testing condition for breakpoint ${bp_1_num}:" \
> -	     "The program being debugged stopped while in a function called from GDB\\." \
> +	     "The program being debugged was signaled while in a function called from GDB\\."
> \
> +	     "GDB remains in the frame where the signal was received\\." \
> +	     "To change this behavior use \"set unwindonsignal on\"\\." \
>  	     "Evaluation of the expression containing the function" \
>  	     "\\(func_segfault\\) will be abandoned\\." \
> -	     "When the function is done executing, GDB will silently stop\\." \
> -	     "" \
> -	     "Breakpoint ${bp_1_num}, \[^\r\n\]+" \
> -	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"]
> +	     "When the function is done executing, GDB will silently stop\\."]
>  }
> 
>  # Start GDB according to ASYNC_P and NON_STOP_P, then call an inferior
> @@ -167,7 +163,9 @@ proc_with_prefix run_call_hits_segfault_test { async_p non_stop_p } {
>  	     "Program received signal SIGSEGV, Segmentation fault\\." \
>  	     "${::hex} in func_segfault \\(\\) at \[^\r\n\]+:${::segv_line}" \
>  	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
> -	     "The program being debugged stopped while in a function called from GDB\\." \
> +	     "The program being debugged was signaled while in a function called from GDB\\."
> \
> +	     "GDB remains in the frame where the signal was received\\." \
> +	     "To change this behavior use \"set unwindonsignal on\"\\." \
>  	     "Evaluation of the expression containing the function" \
>  	     "\\(func_segfault\\) will be abandoned\\." \
>  	     "When the function is done executing, GDB will silently stop\\."]
> --
> 2.25.4

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] 202+ messages in thread

* RE: [PATCHv2 03/13] gdb: include breakpoint number in testing condition error message
  2023-01-18 16:17   ` [PATCHv2 03/13] gdb: include breakpoint number in testing condition error message Andrew Burgess
  2023-01-19  9:54     ` Aktemur, Tankut Baris
@ 2023-01-19 10:54     ` Aktemur, Tankut Baris
  2023-01-19 11:34       ` Eli Zaretskii
  1 sibling, 1 reply; 202+ messages in thread
From: Aktemur, Tankut Baris @ 2023-01-19 10:54 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches, Eli Zaretskii

On Wednesday, January 18, 2023 5:18 PM, Andrew Burgess wrote:
...
> So, in this commit, in preparation for the later commits, I propose to
> change the 'Error in testing breakpoint condition:' line to this:
> 
>   Error in testing condition for breakpoint NUMBER:

Here, because we're now referring to a particular breakpoint, 
I believe the spelling should be "condition for Breakpoint NUMBER:",
with uppercase 'B'.  Maybe Eli can comment on this, too.

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] 202+ messages in thread

* RE: [PATCHv2 08/13] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait"
  2023-01-18 16:18   ` [PATCHv2 08/13] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
@ 2023-01-19 11:05     ` Aktemur, Tankut Baris
  0 siblings, 0 replies; 202+ messages in thread
From: Aktemur, Tankut Baris @ 2023-01-19 11:05 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

On Wednesday, January 18, 2023 5:18 PM, Andrew Burgess wrote:
> This reverts commit ac0d67ed1dcf470bad6a3bc4800c2ddc9bedecca.
> 
> There was nothing wrong with the commit which I'm reverting here, but
> it removed some functionality that will be needed for a later commit;
> that is, the ability for GDB to ask for events from a specific ptid_t
> via the do_target_wait function.
> 
> In a follow up commit, this functionality will be used to implement
> inferior function calls in multi-threaded inferiors.
> ---
>  gdb/infrun.c | 12 +++++++-----
>  1 file changed, 7 insertions(+), 5 deletions(-)
> 
> diff --git a/gdb/infrun.c b/gdb/infrun.c
> index edfb5ab0a91..5af8635a1ab 100644
> --- a/gdb/infrun.c
> +++ b/gdb/infrun.c
> @@ -3741,7 +3741,8 @@ do_target_wait_1 (inferior *inf, ptid_t ptid,
>     more events.  Polls for events from all inferiors/targets.  */
> 
>  static bool
> -do_target_wait (execution_control_state *ecs, target_wait_flags options)
> +do_target_wait (ptid_t wait_ptid, execution_control_state *ecs,
> +		target_wait_flags options)
>  {
>    int num_inferiors = 0;
>    int random_selector;
> @@ -3751,9 +3752,10 @@ do_target_wait (execution_control_state *ecs, target_wait_flags
> options)
>       polling the rest of the inferior list starting from that one in a
>       circular fashion until the whole list is polled once.  */
> 
> -  auto inferior_matches = [] (inferior *inf)
> +  auto inferior_matches = [&wait_ptid] (inferior *inf)
>      {
> -      return inf->process_target () != nullptr;
> +      return (inf->process_target () != NULL

Can we please preserve nullptr instead of reverting back to NULL?

> +	      && ptid_t (inf->pid).matches (wait_ptid));
>      };
> 
>    /* First see how many matching inferiors we have.  */
> @@ -3792,7 +3794,7 @@ do_target_wait (execution_control_state *ecs, target_wait_flags
> options)
> 
>    auto do_wait = [&] (inferior *inf)
>    {
> -    ecs->ptid = do_target_wait_1 (inf, minus_one_ptid, &ecs->ws, options);
> +    ecs->ptid = do_target_wait_1 (inf, wait_ptid, &ecs->ws, options);
>      ecs->target = inf->process_target ();
>      return (ecs->ws.kind () != TARGET_WAITKIND_IGNORE);
>    };
> @@ -4169,7 +4171,7 @@ fetch_inferior_event ()
>         the event.  */
>      scoped_disable_commit_resumed disable_commit_resumed ("handling event");
> 
> -    if (!do_target_wait (&ecs, TARGET_WNOHANG))
> +    if (!do_target_wait (minus_one_ptid, &ecs, TARGET_WNOHANG))
>        {
>  	infrun_debug_printf ("do_target_wait returned no event");
>  	disable_commit_resumed.reset_and_commit ();
> --
> 2.25.4

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] 202+ messages in thread

* Re: [PATCHv2 03/13] gdb: include breakpoint number in testing condition error message
  2023-01-19 10:54     ` Aktemur, Tankut Baris
@ 2023-01-19 11:34       ` Eli Zaretskii
  2023-01-20  9:46         ` Aktemur, Tankut Baris
  0 siblings, 1 reply; 202+ messages in thread
From: Eli Zaretskii @ 2023-01-19 11:34 UTC (permalink / raw)
  To: Aktemur, Tankut Baris; +Cc: aburgess, gdb-patches

> From: "Aktemur, Tankut Baris" <tankut.baris.aktemur@intel.com>
> Date: Thu, 19 Jan 2023 10:54:16 +0000
> 
> On Wednesday, January 18, 2023 5:18 PM, Andrew Burgess wrote:
> ...
> > So, in this commit, in preparation for the later commits, I propose to
> > change the 'Error in testing breakpoint condition:' line to this:
> > 
> >   Error in testing condition for breakpoint NUMBER:
> 
> Here, because we're now referring to a particular breakpoint, 
> I believe the spelling should be "condition for Breakpoint NUMBER:",
> with uppercase 'B'.  Maybe Eli can comment on this, too.

No, capitalized "Breakpoint" would read wrong English-wise in that
case.

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

* RE: [PATCHv2 09/13] gdb: fix b/p conditions with infcalls in multi-threaded inferiors
  2023-01-18 16:18   ` [PATCHv2 09/13] gdb: fix b/p conditions with infcalls in multi-threaded inferiors Andrew Burgess
@ 2023-01-20  7:13     ` Aktemur, Tankut Baris
  0 siblings, 0 replies; 202+ messages in thread
From: Aktemur, Tankut Baris @ 2023-01-20  7:13 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches; +Cc: Saiapova, Natalia

On Wednesday, January 18, 2023 5:18 PM, Andrew Burgess wrote:
> This commit fixes bug PR 28942, that is, creating a conditional
> breakpoint in a multi-threaded inferior, where the breakpoint
> condition includes an inferior function call.
> 
> Currently, when a user tries to create such a breakpoint, then GDB
> will fail with:
> 
>   (gdb) break infcall-from-bp-cond-single.c:61 if (return_true ())
>   Breakpoint 2 at 0x4011fa: file
> /tmp/build/gdb/testsuite/../../../src/gdb/testsuite/gdb.threads/infcall-from-bp-cond-
> single.c, line 61.
>   (gdb) continue
>   Continuing.
>   [New Thread 0x7ffff7c5d700 (LWP 2460150)]
>   [New Thread 0x7ffff745c700 (LWP 2460151)]
>   [New Thread 0x7ffff6c5b700 (LWP 2460152)]
>   [New Thread 0x7ffff645a700 (LWP 2460153)]
>   [New Thread 0x7ffff5c59700 (LWP 2460154)]
>   Error in testing breakpoint condition:
>   Couldn't get registers: No such process.
>   An error occurred while in a function called from GDB.
>   Evaluation of the expression containing the function
>   (return_true) will be abandoned.
>   When the function is done executing, GDB will silently stop.
>   Selected thread is running.
>   (gdb)
> 
> Or, in some cases, like this:
> 
>   (gdb) break infcall-from-bp-cond-simple.c:56 if (is_matching_tid (arg, 1))
>   Breakpoint 2 at 0x401194: file
> /tmp/build/gdb/testsuite/../../../src/gdb/testsuite/gdb.threads/infcall-from-bp-cond-
> simple.c, line 56.
>   (gdb) continue
>   Continuing.
>   [New Thread 0x7ffff7c5d700 (LWP 2461106)]
>   [New Thread 0x7ffff745c700 (LWP 2461107)]
>   ../../src.release/gdb/nat/x86-linux-dregs.c:146: internal-error:
> x86_linux_update_debug_registers: Assertion `lwp_is_stopped (lwp)' failed.
>   A problem internal to GDB has been detected,
>   further debugging may prove unreliable.
> 
> The precise error depends on the exact thread state; so there's race
> conditions depending on which threads have fully started, and which
> have not.  But the underlying problem is always the same; when GDB
> tries to execute the inferior function call from within the breakpoint
> condition, GDB will, incorrectly, try to resume threads that are
> already running - GDB doesn't realise that some threads might already
> be running.
> 
> The solution proposed in this patch requires an additional member
> variable thread_info::in_cond_eval.  This flag is set to true (in
> breakpoint.c) when GDB is evaluating a breakpoint condition.
> 
> In user_visible_resume_ptid (infrun.c), when the in_cond_eval flag is
> true, then GDB will only try to resume the current thread, that is,
> the thread for which the breakpoint condition is being evaluated.
> This solves the problem of GDB trying to resume threads that are
> already running.
> 
> The next problem is that inferior function calls are assumed to be
> synchronous, that is, GDB doesn't expect to start an inferior function
> call in thread #1, then receive a stop from thread #2 for some other,
> unrelated reason.  To prevent GDB responding to an event from another
> thread, we update fetch_inferior_event and do_target_wait in infrun.c,
> so that, when an inferior function call (on behalf of a breakpoint
> condition) is in progress, we only wait for events from the current
> thread (the one evaluating the condition).
> 
> The fix in do_target_wait is because previously, we only ever waited
> for the general any-thread, minus_one_ptid, for which matching

Is there something missing in this sentence?

> against the inferior::pid would always succeed.  However, now we might
> wait against a specific ptid value, in which case we need to ensure we
> only compare the pid part of the ptid.
> 
> In fetch_inferior_event, after receiving the event, we only want to
> stop all the other threads, and call inferior_event_handler with
> INF_EXEC_COMPLETE, if we are not evaluating a conditional breakpoint.
> If we are, then all the other threads should be left doing whatever
> they were before.  The inferior_event_handler call will be performed
> once the breakpoint condition has finished being evaluated, and GDB
> decides to stop or not.
> 
> The final problem that needs solving relates to GDB's commit-resume
> mechanism, this allows GDB to collect resume requests into a single

"this allows" -> "which allows"

> packet in order to reduce traffic to a remote target.
> 
> The problem is that the commit-resume mechanism will not send any
> resume requests for an inferior if there are already events pending on
> the GDB side.
> 
> Imagine an inferior with two threads.  Both threads hit a breakpoint,
> maybe the same conditional breakpoint.  At this point there are two
> pending events, one for each thread.
> 
> GDB selects one of the events and spots that this is a conditional
> breakpoint, GDB evaluates the condition.
> 
> The condition includes an inferior function call, so GDB sets up for
> the call and resumes the one thread, the resume request is added to
> the commit-resume queue.
> 
> When the commit-resume queue is committed GDB sees that there is a
> pending event from another thread, and so doesn't send any resume
> requests to the actual target, GDB is assuming that when we wait we
> will select the event from the other thread.
> 
> However, as this is an inferior function call for a condition
> evaluation, we will not select the event from the other thread, we
> only care about events from the thread that is evaluating the
> condition - and the resume for this thread was never sent to the
> target.
> 
> And so, GDB hangs, waiting for an event from a thread that was never
> fully resumed.
> 
> To fix this issue I have added the concept of "forcing" the
> commit-resume queue.  When enabling commit resume, if the force flag
> is true, then any resumes will be committed to the target, even if
> there are other threads with pending events.
> 
> A note on authorship: this patch was based on some work done by
> Natalia Saiapova and Tankut Baris Aktemur from Intel[1].  I have made
> some changes to their work in this version.

Thank you very much for taking it further.

> Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=28942
> 
> [1] https://sourceware.org/pipermail/gdb-patches/2020-October/172454.html
> 
> Co-authored-by: Natalia Saiapova <natalia.saiapova@intel.com>
> Co-authored-by: Tankut Baris Aktemur <tankut.baris.aktemur@intel.com>
> ---
>  gdb/breakpoint.c                              |   2 +
>  gdb/gdbthread.h                               |   3 +
>  gdb/infcall.c                                 |   6 +
>  gdb/infrun.c                                  |  46 +++-
>  gdb/infrun.h                                  |   2 +-
>  .../infcall-from-bp-cond-other-thread-event.c | 135 ++++++++++
>  ...nfcall-from-bp-cond-other-thread-event.exp | 175 +++++++++++++
>  .../gdb.threads/infcall-from-bp-cond-simple.c |  89 +++++++
>  .../infcall-from-bp-cond-simple.exp           | 236 ++++++++++++++++++
>  .../gdb.threads/infcall-from-bp-cond-single.c | 139 +++++++++++
>  .../infcall-from-bp-cond-single.exp           | 119 +++++++++
>  11 files changed, 940 insertions(+), 12 deletions(-)
>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
> 
> diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
> index c4fec7e8e55..0cb4382ba5b 100644
> --- a/gdb/breakpoint.c
> +++ b/gdb/breakpoint.c
> @@ -5538,6 +5538,8 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
>  	{
>  	  try
>  	    {
> +	      scoped_restore reset_in_cond_eval
> +		= make_scoped_restore (&thread->control.in_cond_eval, true);
>  	      condition_result = breakpoint_cond_eval (cond);
>  	    }
>  	  catch (const gdb_exception &ex)
> diff --git a/gdb/gdbthread.h b/gdb/gdbthread.h
> index 11d69fceab0..b0421bac95f 100644
> --- a/gdb/gdbthread.h
> +++ b/gdb/gdbthread.h
> @@ -171,6 +171,9 @@ struct thread_control_state
>       command.  This is used to decide whether "set scheduler-locking
>       step" behaves like "on" or "off".  */
>    int stepping_command = 0;
> +
> +  /* True if the thread is evaluating a BP condition.  */
> +  bool in_cond_eval = false;
>  };
> 
>  /* Inferior thread specific part of `struct infcall_suspend_state'.  */
> diff --git a/gdb/infcall.c b/gdb/infcall.c
> index e1b785e437b..8a48909bc2c 100644
> --- a/gdb/infcall.c
> +++ b/gdb/infcall.c
> @@ -641,6 +641,12 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
> 
>        proceed (real_pc, GDB_SIGNAL_0);
> 
> +      /* Enable commit resume, but pass true for the force flag.  This
> +	 ensures any thread we set running in proceed will actually be
> +	 committed to the target, even if some other thread in the current
> +	 target has a pending event.  */
> +      scoped_enable_commit_resumed enable ("infcall", true);
> +
>        infrun_debug_show_threads ("non-exited threads after proceed for inferior-call",
>  				 all_non_exited_threads ());
> 
> diff --git a/gdb/infrun.c b/gdb/infrun.c
> index 5af8635a1ab..861be6eae2f 100644
> --- a/gdb/infrun.c
> +++ b/gdb/infrun.c
> @@ -2149,6 +2149,14 @@ user_visible_resume_ptid (int step)
>  	 mode.  */
>        resume_ptid = inferior_ptid;
>      }
> +  else if (inferior_ptid != null_ptid
> +	   && inferior_thread ()->control.in_cond_eval)
> +    {
> +      /* The inferior thread is evaluating a BP condition.  Other threads
> +	 might be stopped or running and we do not want to change their
> +	 state, thus, resume only the current thread.  */
> +      resume_ptid = inferior_ptid;
> +    }
>    else if (!sched_multi && target_supports_multi_process ())
>      {
>        /* Resume all threads of the current process (and none of other
> @@ -2861,7 +2869,7 @@ schedlock_applies (struct thread_info *tp)
>     pending events.  */
> 
>  static void
> -maybe_set_commit_resumed_all_targets ()
> +maybe_set_commit_resumed_all_targets (bool force_p)
>  {
>    scoped_restore_current_thread restore_thread;
> 
> @@ -2890,7 +2898,7 @@ maybe_set_commit_resumed_all_targets ()
>  	 status to report, handle it before requiring the target to
>  	 commit its resumed threads: handling the status might lead to
>  	 resuming more threads.  */
> -      if (proc_target->has_resumed_with_pending_wait_status ())
> +      if (!force_p && proc_target->has_resumed_with_pending_wait_status ())
>  	{
>  	  infrun_debug_printf ("not requesting commit-resumed for target %s, a"
>  			       " thread has a pending waitstatus",
> @@ -2900,7 +2908,7 @@ maybe_set_commit_resumed_all_targets ()
> 
>        switch_to_inferior_no_thread (inf);
> 
> -      if (target_has_pending_events ())
> +      if (!force_p && target_has_pending_events ())
>  	{
>  	  infrun_debug_printf ("not requesting commit-resumed for target %s, "
>  			       "target has pending events",
> @@ -2993,7 +3001,7 @@ scoped_disable_commit_resumed::reset ()
>      {
>        /* This is the outermost instance, re-enable
>           COMMIT_RESUMED_STATE on the targets where it's possible.  */
> -      maybe_set_commit_resumed_all_targets ();
> +      maybe_set_commit_resumed_all_targets (false);
>      }
>    else
>      {
> @@ -3026,7 +3034,7 @@ scoped_disable_commit_resumed::reset_and_commit ()
>  /* See infrun.h.  */
> 
>  scoped_enable_commit_resumed::scoped_enable_commit_resumed
> -  (const char *reason)
> +  (const char *reason, bool force_p)
>    : m_reason (reason),
>      m_prev_enable_commit_resumed (enable_commit_resumed)
>  {
> @@ -3038,7 +3046,7 @@ scoped_enable_commit_resumed::scoped_enable_commit_resumed
> 
>        /* Re-enable COMMIT_RESUMED_STATE on the targets where it's
>  	 possible.  */
> -      maybe_set_commit_resumed_all_targets ();
> +      maybe_set_commit_resumed_all_targets (force_p);
> 
>        maybe_call_commit_resumed_all_targets ();
>      }
> @@ -3752,10 +3760,11 @@ do_target_wait (ptid_t wait_ptid, execution_control_state *ecs,
>       polling the rest of the inferior list starting from that one in a
>       circular fashion until the whole list is polled once.  */
> 
> -  auto inferior_matches = [&wait_ptid] (inferior *inf)
> +  ptid_t wait_ptid_pid {wait_ptid.pid ()};
> +  auto inferior_matches = [&wait_ptid_pid] (inferior *inf)
>      {
>        return (inf->process_target () != NULL
> -	      && ptid_t (inf->pid).matches (wait_ptid));
> +	      && ptid_t (inf->pid).matches (wait_ptid_pid));
>      };
> 
>    /* First see how many matching inferiors we have.  */
> @@ -4171,7 +4180,17 @@ fetch_inferior_event ()
>         the event.  */
>      scoped_disable_commit_resumed disable_commit_resumed ("handling event");
> 
> -    if (!do_target_wait (minus_one_ptid, &ecs, TARGET_WNOHANG))
> +    /* Is the current thread performing an inferior function call as part
> +       of a breakpoint condition evaluation?  */
> +    bool in_cond_eval = (inferior_ptid != null_ptid
> +			 && inferior_thread ()->control.in_cond_eval);
> +
> +    /* If the thread is in the middle of the condition evaluation, wait for
> +       an event from the current thread, otherwise, wait for an event from

Nit: ... current thread. Otherwise, ...

> +       any thread.  */
> +    ptid_t waiton_ptid = in_cond_eval ? inferior_ptid : minus_one_ptid;
> +
> +    if (!do_target_wait (waiton_ptid, &ecs, TARGET_WNOHANG))
>        {
>  	infrun_debug_printf ("do_target_wait returned no event");
>  	disable_commit_resumed.reset_and_commit ();
> @@ -4223,7 +4242,12 @@ fetch_inferior_event ()
>  	    bool should_notify_stop = true;
>  	    bool proceeded = false;
> 
> -	    stop_all_threads_if_all_stop_mode ();
> +	    /* If the thread that stopped just completed an inferior
> +	       function call as part of a condition evaluation, then we
> +	       don't want to stop all the other threads.  */
> +	    if (ecs.event_thread == nullptr
> +		|| !ecs.event_thread->control.in_cond_eval)
> +	      stop_all_threads_if_all_stop_mode ();
> 
>  	    clean_up_just_stopped_threads_fsms (&ecs);
> 
> @@ -4238,7 +4262,7 @@ fetch_inferior_event ()
>  		  proceeded = normal_stop ();
>  	      }
> 
> -	    if (!proceeded)
> +	    if (!proceeded && !in_cond_eval)
>  	      {
>  		inferior_event_handler (INF_EXEC_COMPLETE);
>  		cmd_done = 1;
> diff --git a/gdb/infrun.h b/gdb/infrun.h
> index 43fd1b44f5a..ced2ec5843c 100644
> --- a/gdb/infrun.h
> +++ b/gdb/infrun.h
> @@ -395,7 +395,7 @@ extern void maybe_call_commit_resumed_all_targets ();
> 
>  struct scoped_enable_commit_resumed
>  {
> -  explicit scoped_enable_commit_resumed (const char *reason);
> +  explicit scoped_enable_commit_resumed (const char *reason, bool force_p = false);
>    ~scoped_enable_commit_resumed ();
> 
>    DISABLE_COPY_AND_ASSIGN (scoped_enable_commit_resumed);
> diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
> b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
> new file mode 100644
> index 00000000000..a6abdeb29a6
> --- /dev/null
> +++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
> @@ -0,0 +1,135 @@
> +/* Copyright 2022 Free Software Foundation, Inc.

2022-2023?  More instances below.

> +
> +   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 <pthread.h>
> +#include <unistd.h>
> +#include <stdlib.h>
> +#include <sched.h>
> +
> +#define NUM_THREADS 2
> +
> +pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
> +
> +/* Some global variables to poke, just for something to do.  */
> +volatile int global_var_0 = 0;
> +volatile int global_var_1 = 0;
> +
> +/* This flag is updated from GDB.  */
> +volatile int raise_signal = 0;
> +
> +/* Implement the breakpoint condition function.  Release the other thread
> +   and try to give the other thread a chance to run.  Then return ANSWER.  */
> +int
> +condition_core_func (int answer)
> +{
> +  /* This unlock should release the other thread.  */
> +  if (pthread_mutex_unlock (&mutex) != 0)
> +    abort ();
> +
> +  /* And this yield and sleep should (hopefully) give the other thread a
> +     chance to run.  This isn't guaranteed of course, but once the other
> +     thread does run it should hit a breakpoint, which GDB should
> +     (temporarily) ignore, so there's no easy way for us to know the other
> +     thread has done what it needs to, thus, yielding and sleeping is the
> +     best we can do.  */
> +  sched_yield ();
> +  sleep (2);
> +
> +  return answer;
> +}
> +
> +void
> +stop_marker ()
> +{
> +  int a = 100;	/* Final breakpoint here.  */
> +}
> +
> +/* A breakpoint condition function that always returns true.  */
> +int
> +condition_true_func ()
> +{
> +  return condition_core_func (1);
> +}
> +
> +/* A breakpoint condition function that always returns false.  */
> +int
> +condition_false_func ()
> +{
> +  return condition_core_func (0);
> +}
> +
> +void *
> +worker_func (void *arg)
> +{
> +  volatile int *ptr = 0;
> +  int tid = *((int *) arg);
> +
> +  switch (tid)
> +    {
> +    case 0:
> +      global_var_0 = 11;	/* First thread breakpoint.  */
> +      break;
> +
> +    case 1:
> +      if (pthread_mutex_lock (&mutex) != 0)
> +	abort ();
> +      if (raise_signal)
> +	global_var_1 = *ptr;	/* Signal here.  */
> +      else
> +	global_var_1 = 99;	/* Other thread breakpoint.  */
> +      break;
> +
> +    default:
> +      abort ();
> +    }
> +
> +  return NULL;
> +}
> +
> +int
> +main ()
> +{
> +  pthread_t threads[NUM_THREADS];
> +  int args[NUM_THREADS];
> +
> +  /* Set an alarm, just in case the test deadlocks.  */
> +  alarm (300);
> +
> +  /* We want the mutex to start locked.  */
> +  if (pthread_mutex_lock (&mutex) != 0)
> +    abort ();
> +
> +  for (int i = 0; i < NUM_THREADS; i++)
> +    {
> +      args[i] = i;
> +      pthread_create (&threads[i], NULL, worker_func, &args[i]);
> +    }
> +
> +  for (int i = 0; i < NUM_THREADS; i++)
> +    {
> +      void *retval;
> +      pthread_join (threads[i], &retval);
> +    }
> +
> +  /* Unlock once we're done, just for cleanliness.  */
> +  if (pthread_mutex_unlock (&mutex) != 0)
> +    abort ();
> +
> +  stop_marker ();
> +
> +  return 0;
> +}
> diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
> b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
> new file mode 100644
> index 00000000000..0c8ef728009
> --- /dev/null
> +++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
> @@ -0,0 +1,175 @@
> +# Copyright 2022 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/>.
> +
> +# Test for conditional breakpoints where the breakpoint condition includes
> +# an inferior function call.
> +#
> +# The tests in this script are testing what happens when an event arrives in
> +# another thread while GDB is waiting for the inferior function call (in the
> +# breakpoint condition) to finish.
> +#
> +# The expectation is that GDB will queue events for other threads and wait
> +# for the inferior function call to complete, if the condition is true, then
> +# the conditional breakpoint should be reported first.  The other thread
> +# event should of course, not get lost, and should be reported as soon as
> +# the user tries to continue the inferior.
> +#
> +# If the conditional breakpoint ends up not being taken (the condition is
> +# false), then the other thread event should be reported immediately.
> +#
> +# This script tests what happens when the other thread event is (a) the
> +# other thread hitting a breakpoint, and (b) the other thread taking a
> +# signal (SIGSEGV in this case).
> +
> +standard_testfile
> +
> +if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
> +	  {debug pthreads}] == -1 } {
> +    return
> +}
> +
> +set cond_bp_line [gdb_get_line_number "First thread breakpoint"]
> +set other_bp_line [gdb_get_line_number "Other thread breakpoint"]
> +set final_bp_line [gdb_get_line_number "Final breakpoint here"]
> +set signal_line [gdb_get_line_number "Signal here"]
> +
> +# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
> +proc start_gdb_and_runto_main { target_async target_non_stop } {
> +    save_vars { ::GDBFLAGS } {
> +	append ::GDBFLAGS \
> +	    " -ex \"maint set target-non-stop $target_non_stop\""
> +	append ::GDBFLAGS \
> +	    " -ex \"maintenance set target-async ${target_async}\""
> +
> +	clean_restart ${::binfile}
> +    }
> +
> +    if {![runto_main]} {
> +	fail "run to main"

Similar comments that I wrote in previous patches:
The other if-statements in this file put spaces around the condition.
We don't need to emit an explicit fail.

There are instances in the other test files below, too.

> +	return -1
> +    }
> +
> +    return 0
> +}
> +
> +# Run a test of GDB's conditional breakpoints, where the conditions include
> +# inferior function calls.  While the inferior function call is executing
> +# another thread will hit a breakpoint (when OTHER_THREAD_SIGNAL is false),
> +# or receive a signal (when OTHER_THREAD_SIGNAL is true).  GDB should report
> +# the conditional breakpoint first (if the condition is true), and then
> +# report the second thread event once the inferior is continued again.
> +#
> +# When STOP_AT_COND is true then the conditional breakpoint will have a
> +# condition that evaluates to true (and the GDB will stop at the
> +# breakpoint), otherwise, the condition will evaluate to false (and GDB will
> +# not stop at the breakpoint).
> +proc run_condition_test { stop_at_cond other_thread_signal \
> +			      target_async target_non_stop } {
> +    if { [start_gdb_and_runto_main $target_async \
> +	      $target_non_stop] == -1 } {
> +	return
> +    }
> +
> +    # Setup the conditional breakpoint.
> +    if { $stop_at_cond } {
> +	set cond_func "condition_true_func"
> +    } else {
> +	set cond_func "condition_false_func"
> +    }
> +    gdb_breakpoint \
> +	"${::srcfile}:${::cond_bp_line} if (${cond_func} ())"
> +    set cond_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
> +			"get number for conditional breakpoint"]
> +
> +    if { $other_thread_signal } {
> +	# Arrange for the other thread to raise a signal while GDB is
> +	# evaluating the breakpoint condition.
> +	gdb_test_no_output "set raise_signal = 1"
> +    } else {
> +	# And a breakpoint that will be hit by another thread only once the
> +	# breakpoint condition starts to be evaluated.
> +	gdb_breakpoint "${::srcfile}:${::other_bp_line}"
> +	set other_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
> +			      "get number for other breakpoint"]
> +    }
> +
> +    # A final breakpoint once the test has completed.
> +    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
> +    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
> +			  "get number for final breakpoint"]
> +
> +    if { $stop_at_cond } {
> +	# Continue.  The first breakpoint we hit should be the conditional
> +	# breakpoint.  The other thread will have hit its breakpoint, but
> +	# that will have been deferred until the conditional breakpoint is
> +	# reported.
> +	gdb_test "continue" \
> +	    [multi_line \
> +		 "Continuing\\." \
> +		 ".*" \
> +		 "" \
> +		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${cond_bp_num},
> worker_func \[^\r\n\]+:${::cond_bp_line}" \
> +		 "${::decimal}\\s+\[^\r\n\]+First thread breakpoint\[^\r\n\]+"] \
> +	    "hit the conditional breakpoint"
> +    }
> +
> +    if { $other_thread_signal } {
> +	# Now continue again, the other thread will now report that it
> +	# received a signal.
> +	gdb_test "continue" \
> +	    [multi_line \
> +		 "Continuing\\." \
> +		 ".*" \
> +		 "Thread ${::decimal} \"\[^\"\r\n\]+\" received signal SIGSEGV, Segmentation
> fault\\." \
> +		 "\\\[Switching to Thread \[^\r\n\]+\\\]" \
> +		 "${::hex} in worker_func \[^\r\n\]+:${::signal_line}" \
> +		 "${::decimal}\\s+\[^\r\n\]+Signal here\[^\r\n\]+"] \
> +	    "received signal in other thread"
> +    } else {
> +	# Now continue again, the other thread will now report its
> +	# breakpoint.
> +	gdb_test "continue" \
> +	    [multi_line \
> +		 "Continuing\\." \
> +		 ".*" \
> +		 "" \
> +		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${other_bp_num},
> worker_func \[^\r\n\]+:${::other_bp_line}" \
> +		 "${::decimal}\\s+\[^\r\n\]+Other thread breakpoint\[^\r\n\]+"] \
> +	    "hit the breakpoint in other thread"
> +
> +	# Run to the stop marker.
> +	gdb_test "continue" \
> +	    [multi_line \
> +		 "Continuing\\." \
> +		 ".*" \
> +		 "" \
> +		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${final_bp_num},
> stop_marker \[^\r\n\]+:${::final_bp_line}" \
> +		 "${::decimal}\\s+\[^\r\n\]+Final breakpoint here\[^\r\n\]+"] \
> +	    "hit the final breakpoint"
> +    }
> +
> +    gdb_exit

Do we need this?  We already do clean_restart.

> +}
> +
> +foreach_with_prefix target_async { "on" "off" } {
> +    foreach_with_prefix target_non_stop { "on" "off" } {
> +	foreach_with_prefix other_thread_signal { true false } {
> +	    foreach_with_prefix stop_at_cond { true false } {
> +		run_condition_test $stop_at_cond $other_thread_signal \
> +		    $target_async $target_non_stop
> +	    }
> +	}
> +    }
> +}
> diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
> b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
> new file mode 100644
> index 00000000000..f2a24a52b01
> --- /dev/null
> +++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
> @@ -0,0 +1,89 @@
> +/* Copyright 2022 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 <pthread.h>
> +#include <unistd.h>
> +
> +#define NUM_THREADS 3
> +
> +int
> +is_matching_tid (int *tid_ptr, int tid_value)
> +{
> +  return *tid_ptr == tid_value;
> +}
> +
> +int
> +return_true ()
> +{
> +  return 1;
> +}
> +
> +int
> +return_false ()
> +{
> +  return 0;
> +}
> +
> +int
> +function_that_segfaults ()
> +{
> +  int *p = 0;
> +  *p = 1;	/* Segfault happens here.   */
> +}
> +
> +int
> +function_with_breakpoint ()
> +{
> +  return 1;	/* Nested breakpoint.  */
> +}
> +
> +void *
> +worker_func (void *arg)
> +{
> +  int a = 42;	/* Breakpoint here.  */
> +}
> +
> +void
> +stop_marker ()
> +{
> +  int b = 99;	/* Stop marker.  */
> +}
> +
> +int
> +main ()
> +{
> +  pthread_t threads[NUM_THREADS];
> +  int args[NUM_THREADS];
> +
> +  alarm (300);
> +
> +  for (int i = 0; i < NUM_THREADS; i++)
> +    {
> +      args[i] = i;
> +      pthread_create (&threads[i], NULL, worker_func, &args[i]);
> +    }
> +
> +  for (int i = 0; i < NUM_THREADS; i++)
> +    {
> +      void *retval;
> +      pthread_join (threads[i], &retval);
> +    }
> +
> +  stop_marker ();
> +
> +  return 0;
> +}
> diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
> b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
> new file mode 100644
> index 00000000000..8d94d24f9b3
> --- /dev/null
> +++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
> @@ -0,0 +1,236 @@
> +# Copyright 2022 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/>.
> +
> +# Some simple tests of inferior function calls from breakpoint
> +# conditions, in multi-threaded inferiors.
> +#
> +# This test sets up a multi-threaded inferior, and places a breakpoint
> +# at a location that many of the threads will reach.  We repeat the
> +# test with different conditions, sometimes a single thread should
> +# stop at the breakpoint, sometimes multiple threads should stop, and
> +# sometime no threads should stop.
> +
> +standard_testfile
> +
> +if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
> +	  {debug pthreads}] == -1 } {
> +    return
> +}
> +
> +set cond_bp_line [gdb_get_line_number "Breakpoint here"]
> +set stop_bp_line [gdb_get_line_number "Stop marker"]
> +set nested_bp_line [gdb_get_line_number "Nested breakpoint"]
> +set segv_line [gdb_get_line_number "Segfault happens here"]
> +
> +# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
> +proc start_gdb_and_runto_main { target_async target_non_stop } {
> +    save_vars { ::GDBFLAGS } {
> +	append ::GDBFLAGS \
> +	    " -ex \"maint set target-non-stop $target_non_stop\""
> +	append ::GDBFLAGS \
> +	    " -ex \"maintenance set target-async ${target_async}\""
> +
> +	clean_restart ${::binfile}
> +    }
> +
> +    if {![runto_main]} {
> +	fail "run to main"
> +	return -1
> +    }
> +
> +    return 0
> +}
> +
> +# Run a test of GDB's conditional breakpoints, where the conditions include
> +# inferior function calls.
> +#
> +# CONDITION is combined (with &&) to some additional logic, and used as the
> +# breakpoint condition.
> +#
> +# N_EXPECTED_HITS is the number of threads that we expect to stop due to
> +# CONDITON.
> +#
> +# MESSAGE is used as a test name prefix.
> +proc run_condition_test { message n_expected_hits condition \
> +			      target_async target_non_stop } {
> +    with_test_prefix $message {
> +
> +	if { [start_gdb_and_runto_main $target_async \
> +		  $target_non_stop] == -1 } {
> +	    return
> +	}
> +
> +	# Use this convenience variable to track how often the
> +	# breakpoint condition has been evaluated, this should be once

Nit: ... evaluated. This ...

> +	# per thread.
> +	gdb_test "set \$n_cond_eval = 0"
> +
> +	# Setup the conditional breakpoint.
> +	gdb_breakpoint \
> +	    "${::srcfile}:${::cond_bp_line} if ((++\$n_cond_eval) ${condition})"

IMHO, it would be cleaner if '&&' was done here and the user of this proc
did not have to include it in the 'condition' argument.
Update: I had written the comment as above, but later I saw you pass a "|| ..."
condition, too.  So, I think the comment at the procedure header was misleading
and can be revised.

> +
> +	# And a breakpoint that we hit when the test is over, this one is
> +	# not conditional.  Only the main thread gets here once all the
> +	# other threads have finished.
> +	gdb_breakpoint "${::srcfile}:${::stop_bp_line}"
> +
> +	# The number of times we stop at the conditional breakpoint.
> +	set n_hit_condition 0
> +
> +	# Now keep 'continue'-ing GDB until all the threads have finished
> +	# and we reach the stop_marker breakpoint.
> +	gdb_test_multiple "continue" "spot all breakpoint hits" {
> +	    -re " worker_func
> \[^\r\n\]+${::srcfile}:${::cond_bp_line}\r\n${::decimal}\\s+\[^\r\n\]+Breakpoint
> here\[^\r\n\]+\r\n${::gdb_prompt} $" {
> +		incr n_hit_condition
> +		send_gdb "continue\n"
> +		exp_continue
> +	    }
> +
> +	    -re " stop_marker
> \[^\r\n\]+${::srcfile}:${::stop_bp_line}\r\n${::decimal}\\s+\[^\r\n\]+Stop
> marker\[^\r\n\]+\r\n${::gdb_prompt} $" {
> +		pass $gdb_test_name
> +	    }
> +	}
> +
> +	gdb_assert { $n_hit_condition == $n_expected_hits } \
> +	    "stopped at breakpoint the expected number of times"
> +
> +	# Ensure the breakpoint condition was evaluated once per thread.
> +	gdb_test "print \$n_cond_eval" "= 3" "condition was evaluated twice"

twice -> three times

> +    }
> +}
> +
> +# Check that after handling a conditional breakpoint (where the condition
> +# includes an inferior call), it is still possible to kill the running
> +# inferior, and then restart the inferior.
> +#
> +# At once point doing this would result in GDB giving an assertion error.
> +proc_with_prefix run_kill_and_restart_test { target_async target_non_stop } {
> +    # This test relies on the 'start' command, which is not possible with
> +    # the plain 'remote' target.
> +    if {[target_info gdb_protocol] == "remote"} {
> +	return
> +    }
> +
> +    if { [start_gdb_and_runto_main $target_async \
> +	      $target_non_stop] == -1 } {
> +	return
> +    }
> +
> +    # Setup the conditional breakpoint.
> +    gdb_breakpoint \
> +	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 1))"
> +    gdb_continue_to_breakpoint "worker_func"
> +
> +    # Now kill the program being debugged.
> +    gdb_test "kill" "" "kill process" \
> +	"Kill the program being debugged.*y or n. $" "y"
> +
> +    # Check we can restart the inferior.  At one point this would trigger an
> +    # assertion.
> +    gdb_test "start" ".*"
> +}
> +
> +# Create a conditional breakpoint which includes a call to a function that
> +# segfaults.  Run GDB and check what happens when the inferior segfaults
> +# during the inferior call.
> +proc_with_prefix run_bp_cond_segfaults { target_async target_non_stop } {
> +    if { [start_gdb_and_runto_main $target_async \
> +	      $target_non_stop] == -1 } {
> +	return
> +    }
> +
> +    # This test relies on the inferior segfaulting when trying to
> +    # access address zero.
> +    if { [is_address_zero_readable] } {
> +	return
> +    }
> +
> +    # Setup the conditional breakpoint, include a call to
> +    # 'function_that_segfaults', which triggers the segfault.
> +    gdb_breakpoint \
> +	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 0) &&
> function_that_segfaults ())"
> +    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
> +		      "get number of conditional breakpoint"]
> +
> +    gdb_test "continue" \
> +	[multi_line \
> +	     "Continuing\\." \
> +	     ".*" \
> +	     "Thread ${::decimal} \"infcall-from-bp\" received signal SIGSEGV, Segmentation
> fault\\." \
> +	     "${::hex} in function_that_segfaults \\(\\) at \[^\r\n\]+:${::segv_line}" \
> +	     "${::decimal}\\s+\[^\r\n\]+Segfault happens here\[^\r\n\]+" \
> +	     "Error in testing condition for breakpoint ${bp_1_num}:" \
> +	     "The program being debugged was signaled while in a function called from GDB\\."
> \
> +	     "GDB remains in the frame where the signal was received\\." \
> +	     "To change this behavior use \"set unwindonsignal on\"\\." \
> +	     "Evaluation of the expression containing the function" \
> +	     "\\(function_that_segfaults\\) will be abandoned\\." \
> +	     "When the function is done executing, GDB will silently stop\\."]
> +}
> +
> +# Create a conditional breakpoint which includes a call to a function that
> +# itself has a breakpoint set within it.  Run GDB and check what happens
> +# when GDB hits the nested breakpoint.
> +proc_with_prefix run_bp_cond_hits_breakpoint { target_async target_non_stop } {
> +    if { [start_gdb_and_runto_main $target_async \
> +	      $target_non_stop] == -1 } {
> +	return
> +    }
> +
> +    # Setup the conditional breakpoint, include a call to
> +    # 'function_with_breakpoint' in which we will shortly place a
> +    # breakpoint.
> +    gdb_breakpoint \
> +	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 0) &&
> function_with_breakpoint ())"
> +    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
> +		      "get number of conditional breakpoint"]
> +
> +    gdb_breakpoint "${::srcfile}:${::nested_bp_line}"
> +    set bp_2_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
> +		      "get number of nested breakpoint"]
> +
> +    gdb_test "continue" \
> +	[multi_line \
> +	     "Continuing\\." \
> +	     ".*" \
> +	     "Thread ${::decimal} \"infcall-from-bp\" hit Breakpoint ${bp_2_num},
> function_with_breakpoint \\(\\) at \[^\r\n\]+:${::nested_bp_line}" \
> +	     "${::decimal}\\s+\[^\r\n\]+Nested breakpoint\[^\r\n\]+" \
> +	     "Error in testing condition for breakpoint ${bp_1_num}:" \
> +	     "The program being debugged stopped while in a function called from GDB\\." \
> +	     "Evaluation of the expression containing the function" \
> +	     "\\(function_with_breakpoint\\) will be abandoned\\." \
> +	     "When the function is done executing, GDB will silently stop\\."]
> +}
> +
> +foreach_with_prefix target_async { "on" "off" } {
> +    foreach_with_prefix target_non_stop { "on" "off" } {
> +	run_condition_test "exactly one thread is hit" \
> +	    1 "&& is_matching_tid (arg, 1)" \
> +	    $target_async $target_non_stop
> +	run_condition_test "exactly two threads are hit" \
> +	    2 "&& (is_matching_tid (arg, 0) || is_matching_tid (arg, 2))" \
> +	    $target_async $target_non_stop
> +	run_condition_test "all three threads are hit" \
> +	    3 "|| return_true ()" \
> +	    $target_async $target_non_stop
> +	run_condition_test "no thread is hit" \
> +	    0 "&& return_false ()" \
> +	    $target_async $target_non_stop
> +
> +	run_kill_and_restart_test $target_async $target_non_stop
> +	run_bp_cond_segfaults $target_async $target_non_stop
> +	run_bp_cond_hits_breakpoint $target_async $target_non_stop
> +    }
> +}
> diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
> b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
> new file mode 100644
> index 00000000000..c87f1f2bfc6
> --- /dev/null
> +++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
> @@ -0,0 +1,139 @@
> +/* Copyright 2022 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 <pthread.h>
> +#include <unistd.h>
> +#include <semaphore.h>
> +#include <stdlib.h>
> +
> +#define NUM_THREADS 5
> +
> +/* Semaphores, used to track when threads have started, and to control
> +   when the threads finish.  */
> +sem_t startup_semaphore;
> +sem_t finish_semaphore;
> +
> +/* Mutex to control when the first worker thread hit a breakpoint
> +   location.  */
> +pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
> +
> +/* Global variable to poke, just so threads have something to do.  */
> +volatile int global_var = 0;
> +
> +int
> +return_true ()
> +{
> +  return 1;
> +}
> +
> +int
> +return_false ()
> +{
> +  return 0;
> +}
> +
> +void *
> +worker_func (void *arg)
> +{
> +  int tid = *((int *) arg);
> +
> +  switch (tid)
> +    {
> +    case 0:
> +      /* Wait for MUTEX to become available, then pass through the
> +	 conditional breakpoint location.  */
> +      if (pthread_mutex_lock (&mutex) != 0)
> +	abort ();
> +      global_var = 99;	/* Conditional breakpoint here.  */
> +      if (pthread_mutex_unlock (&mutex) != 0)
> +	abort ();
> +      break;
> +
> +    default:
> +      /* Notify the main thread that the thread has started, then wait for
> +	 the main thread to tell us to finish.  */
> +      sem_post (&startup_semaphore);
> +      if (sem_wait (&finish_semaphore) != 0)
> +	abort ();
> +      break;
> +    }
> +}
> +
> +void
> +stop_marker ()
> +{
> +  global_var = 99;	/* Stop marker.  */
> +}
> +
> +int
> +main ()
> +{
> +  pthread_t threads[NUM_THREADS];
> +  int args[NUM_THREADS];
> +  void *retval;
> +
> +  /* An alarm, just in case the thread deadlocks.  */
> +  alarm (300);
> +
> +  /* Semaphore initialization.  */
> +  if (sem_init (&startup_semaphore, 0, 0) != 0)
> +    abort ();
> +  if (sem_init (&finish_semaphore, 0, 0) != 0)
> +    abort ();
> +
> +  /* Lock MUTEX, this prevents the first worker thread from rushing ahead.  */
> +  if (pthread_mutex_lock (&mutex) != 0)
> +    abort ();
> +
> +  /* Worker thread creation.  */
> +  for (int i = 0; i < NUM_THREADS; i++)
> +    {
> +      args[i] = i;
> +      pthread_create (&threads[i], NULL, worker_func, &args[i]);
> +    }
> +
> +  /* Wait for every thread (other than the first) to tell us it has started
> +     up.  */
> +  for (int i = 1; i < NUM_THREADS; i++)
> +    {
> +      if (sem_wait (&startup_semaphore) != 0)
> +	abort ();
> +    }
> +
> +  /* Unlock the first thread so it can proceed.  */
> +  if (pthread_mutex_unlock (&mutex) != 0)
> +    abort ();
> +
> +  /* Wait for the first thread only.  */
> +  pthread_join (threads[0], &retval);
> +
> +  /* Now post FINISH_SEMAPHORE to allow all the other threads to finish.  */
> +  for (int i = 1; i < NUM_THREADS; i++)
> +    sem_post (&finish_semaphore);
> +
> +  /* Now wait for the remaining threads to complete.  */
> +  for (int i = 1; i < NUM_THREADS; i++)
> +    pthread_join (threads[i], &retval);
> +
> +  /* Semaphore cleanup.  */
> +  sem_destroy (&finish_semaphore);
> +  sem_destroy (&startup_semaphore);
> +
> +  stop_marker ();
> +
> +  return 0;
> +}
> diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
> b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
> new file mode 100644
> index 00000000000..aa1e94190cd
> --- /dev/null
> +++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
> @@ -0,0 +1,119 @@
> +# Copyright 2022 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 reprocuces bug gdb/28942, performing an inferior function
> +# call from a breakpoint condition in a multi-threaded inferior.
> +#
> +# The important part of this test is that, when the conditional
> +# breakpoint is hit, and the condition (which includes an inferior
> +# function call) is evaluated, the other threads are running.
> +
> +standard_testfile
> +
> +if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
> +	  {debug pthreads}] == -1 } {
> +    return
> +}
> +
> +set cond_bp_line [gdb_get_line_number "Conditional breakpoint here"]
> +set final_bp_line [gdb_get_line_number "Stop marker"]
> +
> +# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
> +proc start_gdb_and_runto_main { target_async target_non_stop } {
> +    save_vars { ::GDBFLAGS } {
> +	append ::GDBFLAGS \
> +	    " -ex \"maint set target-non-stop $target_non_stop\""
> +	append ::GDBFLAGS \
> +	    " -ex \"maintenance set target-async ${target_async}\""
> +
> +	clean_restart ${::binfile}
> +    }
> +
> +    if {![runto_main]} {
> +	fail "run to main"
> +	return -1
> +    }
> +
> +    return 0
> +}
> +
> +# Run a test of GDB's conditional breakpoints, where the conditions include
> +# inferior function calls.
> +#
> +# CONDITION is combined (with &&) to some additional logic, and used as the
> +# breakpoint condition.

There is no conjunction with '&&' this time.  The comment seems incorrect.

> +#
> +# N_EXPECTED_HITS is the number of threads that we expect to stop due to
> +# CONDITON.
> +#
> +# MESSAGE is used as a test name prefix.
> +proc run_condition_test { stop_at_cond \
> +			      target_async target_non_stop } {
> +    if { [start_gdb_and_runto_main $target_async \
> +	      $target_non_stop] == -1 } {
> +	return
> +    }
> +
> +    # Setup the conditional breakpoint.
> +    if { $stop_at_cond } {
> +	set cond_func "return_true"
> +    } else {
> +	set cond_func "return_false"
> +    }
> +    gdb_breakpoint \
> +	"${::srcfile}:${::cond_bp_line} if (${cond_func} ())"
> +    set cond_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
> +			"get number for conditional breakpoint"]
> +
> +    # And a breakpoint that we hit when the test is over, this one is
> +    # not conditional.
> +    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
> +    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
> +			  "get number for final breakpoint"]
> +
> +    if { $stop_at_cond } {
> +	# Continue.  The first breakpoint we hit should be the conditional
> +	# breakpoint.  The other thread will have hit its breakpoint, but
> +	# that will have been deferred until the conditional breakpoint is
> +	# reported.
> +	gdb_test "continue" \
> +	    [multi_line \
> +		 "Continuing\\." \
> +		 ".*" \
> +		 "" \
> +		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${cond_bp_num},
> worker_func \[^\r\n\]+:${::cond_bp_line}" \
> +		 "${::decimal}\\s+\[^\r\n\]+Conditional breakpoint here\[^\r\n\]+"] \
> +	    "hit the conditional breakpoint"
> +    }
> +
> +    # Run to the stop marker.
> +    gdb_test "continue" \
> +	[multi_line \
> +	     "Continuing\\." \
> +	     ".*" \
> +	     "" \
> +	     "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${final_bp_num},
> stop_marker \[^\r\n\]+:${::final_bp_line}" \
> +	     "${::decimal}\\s+\[^\r\n\]+Stop marker\[^\r\n\]+"] \
> +	"hit the final breakpoint"
> +}
> +
> +foreach_with_prefix target_async { "on" "off" } {
> +    foreach_with_prefix target_non_stop { "on" "off" } {
> +	foreach_with_prefix stop_at_cond { true false } {
> +	    run_condition_test $stop_at_cond \
> +		$target_async $target_non_stop
> +	}
> +    }
> +}
> --
> 2.25.4

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] 202+ messages in thread

* RE: [PATCHv2 10/13] gdb: add timeouts for inferior function calls
  2023-01-18 16:18   ` [PATCHv2 10/13] gdb: add timeouts for inferior function calls Andrew Burgess
  2023-01-18 17:30     ` Eli Zaretskii
@ 2023-01-20  8:50     ` Aktemur, Tankut Baris
  1 sibling, 0 replies; 202+ messages in thread
From: Aktemur, Tankut Baris @ 2023-01-20  8:50 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

On Wednesday, January 18, 2023 5:18 PM, Andrew Burgess wrote:
> In the previous commits I have been working on improving inferior
> function call support.  One thing that worries me about using inferior
> function calls from a conditional breakpoint is: what happens if the
> inferior function call fails?
> 
> If the failure is obvious, e.g. the thread performing the call
> crashes, or hits a breakpoint, then this case is already well handled,
> and the error is reported to the user.
> 
> But what if the thread performing the inferior call just deadlocks?
> If the user made the call from a 'print' or 'call' command, then the
> user might have some expectation of when the function call should
> complete, and, when this time limit is exceeded, the user
> will (hopefully) interrupt GDB and regain control of the debug
> session.
> 
> But, when the inferior function call is from a breakpoint condition it
> is much harder to understand that GDB is deadlocked within an inferior
> call.  Maybe the breakpoint hasn't been hit yet?  Or maybe the
> condition was always false?  Or maybe GDB is deadlocked in an inferior
> call?  The only way to know for sure is to periodically interrupt GDB,
> check on all the threads, and then continue.
> 
> Additionally, the focus of the previous commit was inferior function
> calls, from a conditional breakpoint, in a multi-threaded inferior.
> This opens up a whole new set of potential failure conditions.  For
> example, what if the function called relies on interaction with some
> other thread, and the other thread crashes?  Or hits a breakpoint?
> Given how inferior function calls work - in a synchronous manor, a

manor -> manner

> stop event in some other thread is going to be ignored when the
> inferior function call is being done as part of a breakpoint
> condition, and this means that GDB could get stuck waiting for the
> original condition thread, which will now never complete.
> 
> In this commit I propose a solution to this problem.  A timeout.  For
> targets that support async-mode we can install an event-loop timer
> before starting the inferior function call.  When the timer expires we
> will stop the thread performing the inferior function call.  With this
> mechanism in place a user can be sure that any inferior call they make
> will either complete, or timeout eventually.
> 
> Adding a timer like this is obviously a change in behaviour for the
> more common 'call' and 'print' uses of inferior function calls, so, in
> this patch, I propose having two different timers.  One I call the
> 'direct-call-timeout', which is used for 'call' and 'print' commands.
> This timeout is by default set to unlimited, which, not surprisingly,
> means there is no timeout in place.
> 
> A second timer, which I've called 'indirect-call-timeout', is used for
> inferior function calls from breakpoint conditions.  This timeout has
> a default value of 300 seconds.  This is still a pretty substantial
> time to be waiting for a single inferior call to complete, but I
> didn't want to be too aggressive with the value I selected.  A user
> can, of course, still use Ctrl-c to interrupt an inferior function
> call, but this limit will ensure that GDB will stop at some point.
> 
> The new commands added by this commit are:
> 
>   set direct-call-timeout SECONDS
>   show direct-call-timeout
>   set indirect-call-timeout SECONDS
>   show indirect-call-timeout
> 
> These new timeouts do depend on async-mode, so, if async-mode is
> disabled (maint set target-async off), or not supported (e.g. target
> sim), then the timeout is treated as unlimited (that is, no timeout is
> set).
> 
> For targets that "fake" non-async mode, e.g. Linux native, where
> non-async mode is really just async mode, but then we park the target
> in a sissuspend, we could easily fix things so that the timeouts still
> work, however, for targets that really are not async aware, like the
> simulator, fixing things so that timeouts work correctly would be a
> much bigger task - that effort would be better spent just making the
> target async-aware.  And so, I'm happy for now that this feature will
> only work on async targets.
> 
> The two new show commands will display slightly different text if the
> current target is a non-async target, which should allow users to
> understand what's going on.
> 
> There's a somewhat random test adjustment needed in gdb.base/help.exp,
> the test uses a regexp with the apropos command, and expects to find a
> single result.  Turns out the new settings I added also matched the
> regexp, which broke the test.  I've updated the regexp a little to
> exclude my new settings.
> ---
>  gdb/NEWS                                      |  18 ++
>  gdb/doc/gdb.texinfo                           |  66 ++++++
>  gdb/infcall.c                                 | 210 +++++++++++++++++-
>  gdb/testsuite/gdb.base/help.exp               |   2 +-
>  gdb/testsuite/gdb.base/infcall-timeout.c      |  36 +++
>  gdb/testsuite/gdb.base/infcall-timeout.exp    |  82 +++++++
>  .../infcall-from-bp-cond-timeout.c            | 169 ++++++++++++++
>  .../infcall-from-bp-cond-timeout.exp          | 156 +++++++++++++
>  8 files changed, 734 insertions(+), 5 deletions(-)
>  create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.c
>  create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.exp
>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
> 
> diff --git a/gdb/NEWS b/gdb/NEWS
> index c0aac212e30..2689569a8f3 100644
> --- a/gdb/NEWS
> +++ b/gdb/NEWS
> @@ -17,6 +17,24 @@ maintenance print record-instruction [ N ]
>    prints how GDB would undo the N-th previous instruction, and if N is
>    positive, it prints how GDB will redo the N-th following instruction.
> 
> +set direct-call-timeout SECONDS
> +show direct-call-timeout
> +set indirect-call-timeout SECONDS
> +show indirect-call-timeout
> +  These new settings can be used to limit how long GDB will wait for
> +  an inferior function call to complete.  The direct timeout is used
> +  for inferior function calls from e.g. 'call' and 'print' commands,
> +  while the indirect timeout is used for inferior function calls from
> +  within a conditional breakpoint expression.
> +
> +  The default for the direct timeout is unlimited, while the default
> +  for the indirect timeout is 30 seconds.
> +
> +  These timeouts will only have an effect for targets that are
> +  operating in async mode.  For non-async targets the timeouts are
> +  ignored, GDB will wait indefinitely for an inferior function to
> +  complete, unless interrupted by the user using Ctrl-C.
> +
>  * MI changes
> 
>  ** mi now reports 'no-history' as a stop reason when hitting the end of the
> diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
> index 6ea173b5d0b..9eb8b1db00e 100644
> --- a/gdb/doc/gdb.texinfo
> +++ b/gdb/doc/gdb.texinfo
> @@ -20772,6 +20772,72 @@
>  @code{step}, etc).  In this case, when the inferior finally returns to
>  the dummy-frame, @value{GDBN} will once again halt the inferior.
> 
> +On targets that support asynchronous execution (@pxref{Background
> +Execution}) @value{GDBN} can place a timeout on any functions called
> +from @value{GDBN}.  If the timeout expires and the function call is
> +still ongoing, then @value{GDBN} will interrupt the program.
> +
> +For targets that don't support asynchronous execution
> +(@pxref{Background Execution}) then timeouts for functions called from
> +@value{GDBN} are not supported, the timeout settings described below
> +will be treated as @code{unlimited}, meaning @value{GDBN} will wait
> +indefinitely for function call to complete, unless interrupted by the
> +user using @kbd{Ctrl-C}.
> +
> +@table @code
> +@item set direct-call-timeout @var{seconds}
> +@kindex set direct-call-timeout
> +@cindex timeout for called functions
> +Set the timeout used when calling functions in the program to
> +@var{seconds}, which should be an integer greater than zero, or the
> +special value @code{unlimited}, which indicates no timeout should be
> +used.  The default for this setting is @code{unlimited}.
> +
> +This setting is used when the user calls a function directly from the
> +command prompt, for example with a @code{call} or @code{print}
> +command.
> +
> +This setting only works for targets that support asynchronous
> +execution (@pxref{Background Execution}), for any other target the
> +setting is treated as @code{unlimited}.
> +
> +@item show direct-call-timeout
> +@kindex show direct-call-timeout
> +@cindex timeout for called functions
> +Show the timeout used when calling functions in the program with a
> +@code{call} or @code{print} command.
> +@end table
> +
> +It is also possible to call functions within the program from the
> +condition of a conditional breakpoint (@pxref{Conditions, ,Break
> +Conditions}).  A different setting controls the timeout used for
> +function calls made from a breakpoint condition.
> +
> +@table @code
> +@item set indirect-call-timeout @var{seconds}
> +@kindex set indirect-call-timeout
> +@cindex timeout for called functions
> +Set the timeout used when calling functions in the program from a
> +breakpoint or watchpoint condition to @var{seconds}, which should be
> +an integer greater than zero, or the special value @code{unlimited},
> +which indicates no timeout should be used.  The default for this
> +setting is @code{30} seconds.
> +
> +This setting only works for targets that support asynchronous
> +execution (@pxref{Background Execution}), for any other target the
> +setting is treated as @code{unlimited}.
> +
> +If a function called from a breakpoint or watchpoint condition times
> +out, then @value{GDBN} will stop at the point where the timeout
> +occurred.  The breakpoint condition evaluation will be abandoned.
> +
> +@item show indirect-call-timeout
> +@kindex show indirect-call-timeout
> +@cindex timeout for called functions
> +Show the timeout used when calling functions in the program from a
> +breakpoint or watchpoint condition.
> +@end table
> +
>  @subsection Calling functions with no debug info
> 
>  @cindex no debug info functions
> diff --git a/gdb/infcall.c b/gdb/infcall.c
> index 8a48909bc2c..9afca4f5bc6 100644
> --- a/gdb/infcall.c
> +++ b/gdb/infcall.c
> @@ -95,6 +95,53 @@ show_may_call_functions_p (struct ui_file *file, int from_tty,
>  	      value);
>  }
> 
> +/* A timeout (in seconds) for direct inferior calls.  A direct inferior
> +   call is one the user triggers from the prompt, e.g. with a 'call' or
> +   'print' command.  Compare with the definition of indirect calls below.  */
> +
> +static unsigned int direct_call_timeout = UINT_MAX;
> +
> +/* Implement 'show direct-call-timeout'.  */
> +
> +static void
> +show_direct_call_timeout (struct ui_file *file, int from_tty,
> +			  struct cmd_list_element *c, const char *value)
> +{
> +  if (target_has_execution () && !target_can_async_p ())
> +    gdb_printf (file, _("Current target does not support async mode, timeout "
> +			"for direct inferior calls is \"unlimited\".\n"));
> +  else if (direct_call_timeout == UINT_MAX)
> +    gdb_printf (file, _("Timeout for direct inferior function calls "
> +			"is \"unlimited\".\n"));
> +  else
> +    gdb_printf (file, _("Timeout for direct inferior function calls "
> +			"is \"%s seconds\".\n"), value);
> +}
> +
> +/* A timeout (in seconds) for indirect inferior calls.  An indirect inferior
> +   call is one that originates from within GDB, for example, when
> +   evaluating an expression for a conditional breakpoint.  Compare with
> +   the definition of direct calls above.  */
> +
> +static unsigned int indirect_call_timeout = 30;
> +
> +/* Implement 'show indirect-call-timeout'.  */
> +
> +static void
> +show_indirect_call_timeout (struct ui_file *file, int from_tty,
> +			  struct cmd_list_element *c, const char *value)
> +{
> +  if (target_has_execution () && !target_can_async_p ())
> +    gdb_printf (file, _("Current target does not support async mode, timeout "
> +			"for indirect inferior calls is \"unlimited\".\n"));
> +  else if (indirect_call_timeout == UINT_MAX)
> +    gdb_printf (file, _("Timeout for indirect inferior function calls "
> +			"is \"unlimited\".\n"));
> +  else
> +    gdb_printf (file, _("Timeout for indirect inferior function calls "
> +			"is \"%s seconds\".\n"), value);
> +}
> +
>  /* How you should pass arguments to a function depends on whether it
>     was defined in K&R style or prototype style.  If you define a
>     function using the K&R syntax that takes a `float' argument, then
> @@ -589,6 +636,85 @@ call_thread_fsm::should_notify_stop ()
>    return true;
>  }
> 
> +/* A class to control creation of a timer that will interrupt a thread
> +   during an inferior call.  */
> +struct infcall_timer_controller
> +{
> +  /* Setup an event-loop timer that will interrupt PTID if the inferior
> +     call takes too long.  DIRECT_CALL_P is true when this inferior call is
> +     a result of the user using a 'print' or 'call' command, and false when
> +     this inferior call is a result of e.g. a conditional breakpoint
> +     expression, this is used to select which timeout to use.  */
> +  infcall_timer_controller (ptid_t ptid, bool direct_call_p)
> +    : m_ptid (ptid)
> +  {
> +    unsigned int timeout
> +      = direct_call_p ? direct_call_timeout : indirect_call_timeout;
> +    if (timeout < UINT_MAX && target_can_async_p ())
> +      {
> +	int ms = timeout * 1000;
> +	int id = create_timer (ms, infcall_timer_controller::timed_out, this);
> +	m_timer_id.emplace (id);
> +	infcall_debug_printf ("Setting up infcall timeout timer for "
> +			      "ptid %s: %d milliseconds",
> +			      m_ptid.to_string ().c_str (), ms);
> +      }
> +  }
> +
> +  /* Destructor.  Ensure that the timer is removed from the event loop.  */
> +  ~infcall_timer_controller ()
> +  {
> +    /* If the timer has already triggered, then it will have already been
> +       deleted from the event loop.  If the timer has not triggered, then
> +       delete it now.  */
> +    if (m_timer_id.has_value () && !m_triggered)
> +      delete_timer (*m_timer_id);
> +
> +    /* Just for clarity, discard the timer id now.  */
> +    m_timer_id.reset ();
> +  }
> +
> +  /* Return true if there was a timer in place, and the timer triggered,
> +     otherwise, return false.  */
> +  bool triggered_p ()
> +  {
> +    gdb_assert (!m_triggered || m_timer_id.has_value ());
> +    return m_triggered;
> +  }
> +
> +private:
> +  /* The thread we should interrupt.  */
> +  ptid_t m_ptid;
> +
> +  /* Set true when the timer is triggered.  */
> +  bool m_triggered = false;
> +
> +  /* Given a value when a timer is in place.  */
> +  gdb::optional<int> m_timer_id;
> +
> +  /* Callback for the timer, forwards to ::trigger below.  */
> +  static void
> +  timed_out (gdb_client_data context)
> +  {
> +    infcall_timer_controller *ctrl
> +      = static_cast<infcall_timer_controller *> (context);
> +    ctrl->trigger ();
> +  }
> +
> +  /* Called when the timer goes off.  Stop thread m_ptid.  */
> +  void
> +  trigger ()
> +  {
> +    m_triggered = true;
> +
> +    scoped_disable_commit_resumed disable_commit_resumed ("infcall timeout");
> +
> +    infcall_debug_printf ("Stopping thread %s",
> +			  m_ptid.to_string ().c_str ());
> +    target_stop (m_ptid);
> +  }
> +};
> +
>  /* Subroutine of call_function_by_hand to simplify it.
>     Start up the inferior and wait for it to stop.
>     Return the exception if there's an error, or an exception with
> @@ -599,13 +725,15 @@ call_thread_fsm::should_notify_stop ()
> 
>  static struct gdb_exception
>  run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
> -		   struct thread_info *call_thread, CORE_ADDR real_pc)
> +		   struct thread_info *call_thread, CORE_ADDR real_pc,
> +		   bool *timed_out_p)
>  {
>    INFCALL_SCOPED_DEBUG_ENTER_EXIT;
> 
>    struct gdb_exception caught_error;
>    ptid_t call_thread_ptid = call_thread->ptid;
>    int was_running = call_thread->state == THREAD_RUNNING;
> +  *timed_out_p = false;
> 
>    infcall_debug_printf ("call function at %s in thread %s, was_running = %d",
>  			core_addr_to_string (real_pc),
> @@ -650,11 +778,23 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
>        infrun_debug_show_threads ("non-exited threads after proceed for inferior-call",
>  				 all_non_exited_threads ());
> 
> +      /* Setup a timer (if possible, and if the settings allow) to prevent
> +	 the inferior call running forever.  */
> +      bool direct_call_p = !call_thread->control.in_cond_eval;
> +      infcall_timer_controller infcall_timer (inferior_ptid, direct_call_p);
> +
>        /* Inferior function calls are always synchronous, even if the
>  	 target supports asynchronous execution.  */
>        wait_sync_command_done ();
> 
> -      infcall_debug_printf ("inferior call completed successfully");
> +      /* If the timer triggered then the inferior call failed.  */
> +      if (infcall_timer.triggered_p ())
> +	{
> +	  infcall_debug_printf ("inferior call timed out");
> +	  *timed_out_p = true;
> +	}
> +      else
> +	infcall_debug_printf ("inferior call completed successfully");
>      }
>    catch (gdb_exception &e)
>      {
> @@ -1311,6 +1451,10 @@ call_function_by_hand_dummy (struct value *function,
>    scoped_restore restore_stopped_by_random_signal
>      = make_scoped_restore (&stopped_by_random_signal, 0);
> 
> +  /* Set to true by the call to run_inferior_call below if the inferior
> +     call is artificially interrupted by GDB due to taking too long.  */
> +  bool timed_out_p = false;
> +
>    /* - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP -
>       If you're looking to implement asynchronous dummy-frames, then
>       just below is the place to chop this function in two..  */
> @@ -1337,7 +1481,8 @@ call_function_by_hand_dummy (struct value *function,
>  			      struct_addr);
>      {
>        std::unique_ptr<call_thread_fsm> sm_up (sm);
> -      e = run_inferior_call (std::move (sm_up), call_thread.get (), real_pc);
> +      e = run_inferior_call (std::move (sm_up), call_thread.get (), real_pc,
> +			     &timed_out_p);
>      }
> 
>      if (e.reason < 0)
> @@ -1489,7 +1634,10 @@ When the function is done executing, GDB will silently stop."),
>        std::string name = get_function_name (funaddr, name_buf,
>  					    sizeof (name_buf));
> 
> -      if (stopped_by_random_signal)
> +      /* If the inferior call timed out then it will have been interrupted
> +	 by a signal, but we want to report this differently to the user,
> +	 which is done later in this function.  */
> +      if (stopped_by_random_signal && !timed_out_p)
>  	{
>  	  /* We stopped inside the FUNCTION because of a random
>  	     signal.  Further execution of the FUNCTION is not
> @@ -1533,6 +1681,36 @@ GDB remains in the frame where the signal was received.\n\
>  To change this behavior use \"set unwindonsignal on\".\n\
>  Evaluation of the expression containing the function\n\
>  (%s) will be abandoned.\n\
> +When the function is done executing, GDB will silently stop."),
> +		     name.c_str ());
> +	    }
> +	}
> +
> +      if (timed_out_p)
> +	{
> +	  /* A timeout results in a signal being sent to the inferior.  */
> +	  gdb_assert (stopped_by_random_signal);
> +
> +	  /* Indentation is weird here.  A later patch is going to move the
> +	    following block into an if/else, so I'm leaving the indentation
> +	    here to minimise the later patch.
> +
> +	    Also, the error message used below refers to 'set
> +	    unwind-on-timeout' which doesn't exist yet.  This will be added
> +	    in a later commit, I'm leaving this in for now to minimise the
> +	    churn caused by the commit that adds unwind-on-timeout.  */
> +	    {
> +	      /* The user wants to stay in the frame where we stopped
> +		 (default).  Discard inferior status, we're not at the same
> +		 point we started at.  */
> +	      discard_infcall_control_state (inf_status.release ());
> +
> +	      error (_("\
> +The program being debugged timed out while in a function called from GDB.\n\
> +GDB remains in the frame where the timeout occurred.\n\
> +To change this behavior use \"set unwind-on-timeout on\".\n\
> +Evaluation of the expression containing the function\n\
> +(%s) will be abandoned.\n\
>  When the function is done executing, GDB will silently stop."),
>  		     name.c_str ());
>  	    }
> @@ -1646,6 +1824,30 @@ The default is to unwind the frame."),
>  			   show_unwind_on_terminating_exception_p,
>  			   &setlist, &showlist);
> 
> +  add_setshow_uinteger_cmd ("direct-call-timeout", no_class,
> +			    &direct_call_timeout, _("\
> +Set the timeout, for direct calls to inferior function calls."), _("\
> +Show the timeout, for direct calls to inferior function calls."), _("\
> +If running on a target that supports, and is running in, async mode\n\
> +then this timeout is used for any inferior function calls triggered\n\
> +directly from the prompt, i.e. from a 'call' or 'print' command.  The\n\
> +timeout is specified in seconds."),
> +			    nullptr,
> +			    show_direct_call_timeout,
> +			    &setlist, &showlist);
> +
> +  add_setshow_uinteger_cmd ("indirect-call-timeout", no_class,
> +			    &indirect_call_timeout, _("\
> +Set the timeout, for indirect calls to inferior function calls."), _("\
> +Show the timeout, for indirect calls to inferior function calls."), _("\
> +If running on a target that supports, and is running in, async mode\n\
> +then this timeout is used for any inferior function calls triggered\n\
> +indirectly, i.e. being made as part of a breakpoint, or watchpoint,\n\
> +condition expression.  The timeout is specified in seconds."),
> +			    nullptr,
> +			    show_indirect_call_timeout,
> +			    &setlist, &showlist);
> +
>    add_setshow_boolean_cmd
>      ("infcall", class_maintenance, &debug_infcall,
>       _("Set inferior call debugging."),
> diff --git a/gdb/testsuite/gdb.base/help.exp b/gdb/testsuite/gdb.base/help.exp
> index 87919a819ab..504bf90cc15 100644
> --- a/gdb/testsuite/gdb.base/help.exp
> +++ b/gdb/testsuite/gdb.base/help.exp
> @@ -121,7 +121,7 @@ gdb_test "help info bogus-gdb-command" "Undefined info command: \"bogus-
> gdb-comm
>  gdb_test "help gotcha" "Undefined command: \"gotcha\"\.  Try \"help\"\."
> 
>  # Test apropos regex.
> -gdb_test "apropos \\\(print\[\^\[ bsiedf\\\".-\]\\\)" "handle -- Specify how to handle
> signals\."
> +gdb_test "apropos \\\(print\[\^\[ bsiedf\\\"'.-\]\\\)" "handle -- Specify how to handle
> signals\."
>  # Test apropos >1 word string.
>  gdb_test "apropos handle signal" "handle -- Specify how to handle signals\."
>  # Test apropos apropos.
> diff --git a/gdb/testsuite/gdb.base/infcall-timeout.c b/gdb/testsuite/gdb.base/infcall-
> timeout.c
> new file mode 100644
> index 00000000000..895e8a36d59
> --- /dev/null
> +++ b/gdb/testsuite/gdb.base/infcall-timeout.c
> @@ -0,0 +1,36 @@
> +/* Copyright 2022 Free Software Foundation, Inc.

2022-2023?

> +
> +   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 <unistd.h>
> +
> +/* This function is called from GDB.  */
> +int
> +function_that_never_returns ()
> +{
> +  while (1)
> +    sleep (1);
> +
> +  return 0;
> +}
> +
> +int
> +main ()
> +{
> +  alarm (300);
> +
> +  return 0;
> +}
> diff --git a/gdb/testsuite/gdb.base/infcall-timeout.exp b/gdb/testsuite/gdb.base/infcall-
> timeout.exp
> new file mode 100644
> index 00000000000..a5b0111ed04
> --- /dev/null
> +++ b/gdb/testsuite/gdb.base/infcall-timeout.exp
> @@ -0,0 +1,82 @@
> +# Copyright 2022 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/>.
> +
> +# Test GDB's direct-call-timeout setting, that is, ensure that if an
> +# inferior function call, invoked from e.g. a 'print' command, takes
> +# too long, then GDB can interrupt it, and return control to the user.
> +
> +standard_testfile
> +
> +if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
> +	  {debug}] == -1 } {
> +    return
> +}
> +
> +# Start GDB according to TARGET_ASYNC and TARGET_NON_STOP, then adjust
> +# the direct-call-timeout, and make an inferior function call that
> +# will never return.  GDB should eventually timeout and stop the
> +# inferior.
> +proc_with_prefix run_test { target_async target_non_stop } {
> +    save_vars { ::GDBFLAGS } {
> +	append ::GDBFLAGS \
> +	    " -ex \"maint set target-non-stop $target_non_stop\""
> +	append ::GDBFLAGS \
> +	    " -ex \"maintenance set target-async ${target_async}\""
> +
> +	clean_restart ${::binfile}
> +    }
> +
> +    if {![runto_main]} {
> +	fail "run to main"
> +	return
> +    }
> +
> +    gdb_test_no_output "set direct-call-timeout 5"
> +
> +    # When non-stop mode is off we get slightly different output from GDB.
> +    if { [gdb_is_remote_or_extended_remote_target] && $target_non_stop == "off" } {

Use 'eq' instead of '==' for string comparison?
Or maybe even just '!$target_non_stop', since "off" is treated as a boolean false.

> +	set stopped_line_pattern "Program received signal SIGINT, Interrupt\\."
> +    } else {
> +	set stopped_line_pattern "Program stopped\\."
> +    }
> +
> +    gdb_test "print function_that_never_returns ()" \
> +	[multi_line \
> +	     $stopped_line_pattern \
> +	     ".*" \
> +	     "The program being debugged timed out while in a function called from GDB\\." \
> +	     "GDB remains in the frame where the timeout occurred\\." \
> +	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
> +	     "Evaluation of the expression containing the function" \
> +	     "\\(function_that_never_returns\\) will be abandoned\\." \
> +	     "When the function is done executing, GDB will silently stop\\."]
> +
> +    gdb_test "bt" ".* function_that_never_returns .*<function called from gdb>.*"
> +}
> +
> +foreach_with_prefix target_async { "on" "off" } {
> +
> +    if { $target_async == "off" } {

Same comment about string comparison here, too.

> +	# GDB can't timeout while waiting for a thread if the target
> +	# runs with async-mode turned off; once the target is running
> +	# GDB is effectively blocked until the target stops for some
> +	# reason.
> +	continue
> +    }
> +
> +    foreach_with_prefix target_non_stop { "on" "off" } {
> +	run_test $target_async $target_non_stop
> +    }
> +}
> diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
> b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
> new file mode 100644
> index 00000000000..3bd91d7377d
> --- /dev/null
> +++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
> @@ -0,0 +1,169 @@
> +/* This testcase is part of GDB, the GNU debugger.
> +
> +   Copyright 2022 Free Software Foundation, Inc.

2022-2023?

> +
> +   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 <stdio.h>
> +#include <pthread.h>
> +#include <unistd.h>
> +#include <stdlib.h>
> +#include <errno.h>
> +#include <semaphore.h>
> +
> +#define NUM_THREADS 5
> +
> +/* Semaphores, used to track when threads have started, and to control
> +   when the threads finish.  */
> +sem_t startup_semaphore;
> +sem_t finish_semaphore;
> +sem_t thread_1_semaphore;
> +sem_t thread_2_semaphore;
> +
> +/* Mutex to control when the first worker thread hit a breakpoint
> +   location.  */
> +pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
> +
> +/* Global variable to poke, just so threads have something to do.  */
> +volatile int global_var = 0;
> +
> +int
> +condition_func ()
> +{
> +  /* Let thread 2 run.  */
> +  if (sem_post (&thread_2_semaphore) != 0)
> +    abort ();
> +
> +  /* Wait for thread 2 to complete its actions.  */
> +  if (sem_wait (&thread_1_semaphore) != 0)
> +    abort ();
> +
> +  return 1;
> +}
> +
> +void
> +do_segfault ()
> +{
> +  volatile int *p = 0;
> +  *p = 0;	/* Segfault here.  */
> +}
> +
> +void *
> +worker_func (void *arg)
> +{
> +  int tid = *((int *) arg);
> +
> +  /* Let the main thread know that this worker has started.  */
> +  if (sem_post (&startup_semaphore) != 0)
> +    abort ();
> +
> +  switch (tid)
> +    {
> +    case 0:
> +      /* Wait for MUTEX to become available, then pass through the
> +	 conditional breakpoint location.  */
> +      if (pthread_mutex_lock (&mutex) != 0)
> +	abort ();
> +      global_var = 99;	/* Conditional breakpoint here.  */
> +      if (pthread_mutex_unlock (&mutex) != 0)
> +	abort ();
> +      break;
> +
> +    case 1:
> +      if (sem_wait (&thread_2_semaphore) != 0)
> +	abort ();
> +      do_segfault ();
> +      if (sem_post (&thread_1_semaphore) != 0)
> +	abort ();
> +
> +      /* Fall through.  */
> +    default:
> +      /* Wait until we are allowed to finish.  */
> +      if (sem_wait (&finish_semaphore) != 0)
> +	abort ();
> +      break;
> +    }
> +}
> +
> +void
> +stop_marker ()
> +{
> +  global_var = 99;	/* Stop marker.  */
> +}
> +
> +/* The main program entry point.  */
> +
> +int
> +main ()
> +{
> +  pthread_t threads[NUM_THREADS];
> +  int args[NUM_THREADS];
> +  void *retval;
> +
> +  /* An alarm, just in case the thread deadlocks.  */
> +  alarm (300);
> +
> +  /* Semaphore initialization.  */
> +  if (sem_init (&startup_semaphore, 0, 0) != 0)
> +    abort ();
> +  if (sem_init (&finish_semaphore, 0, 0) != 0)
> +    abort ();
> +  if (sem_init (&thread_1_semaphore, 0, 0) != 0)
> +    abort ();
> +  if (sem_init (&thread_2_semaphore, 0, 0) != 0)
> +    abort ();
> +
> +  /* Lock MUTEX, this prevents the first worker thread from rushing ahead.  */
> +  if (pthread_mutex_lock (&mutex) != 0)
> +    abort ();
> +
> +  /* Worker thread creation.  */
> +  for (int i = 0; i < NUM_THREADS; i++)
> +    {
> +      args[i] = i;
> +      pthread_create (&threads[i], NULL, worker_func, &args[i]);
> +    }
> +
> +  /* Wait for every thread to start.  */
> +  for (int i = 0; i < NUM_THREADS; i++)
> +    {
> +      if (sem_wait (&startup_semaphore) != 0)
> +	abort ();
> +    }
> +
> +  /* Unlock the first thread so it can proceed.  */
> +  if (pthread_mutex_unlock (&mutex) != 0)
> +    abort ();
> +
> +  /* Wait for the first thread only.  */
> +  pthread_join (threads[0], &retval);
> +
> +  /* Now post FINISH_SEMAPHORE to allow all the other threads to finish.  */
> +  for (int i = 1; i < NUM_THREADS; i++)
> +    sem_post (&finish_semaphore);
> +
> +  /* Now wait for the remaining threads to complete.  */
> +  for (int i = 1; i < NUM_THREADS; i++)
> +    pthread_join (threads[i], &retval);
> +
> +  /* Semaphore cleanup.  */
> +  sem_destroy (&finish_semaphore);
> +  sem_destroy (&startup_semaphore);
> +  sem_destroy (&thread_1_semaphore);
> +  sem_destroy (&thread_2_semaphore);
> +
> +  stop_marker ();
> +
> +  return 0;
> +}
> diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
> b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
> new file mode 100644
> index 00000000000..3341ff33f19
> --- /dev/null
> +++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
> @@ -0,0 +1,156 @@
> +# Copyright 2020 Free Software Foundation, Inc.

Please note the copyright year.

> +
> +# 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 inferior calls executed from a breakpoint condition in
> +# a multi-threaded program.
> +#
> +# This test has the inferior function call timeout, and checks how GDB
> +# handles this situation.
> +
> +standard_testfile
> +
> +if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
> +	  {debug pthreads}] } {
> +    return
> +}
> +
> +set cond_bp_line [gdb_get_line_number "Conditional breakpoint here"]
> +set final_bp_line [gdb_get_line_number "Stop marker"]
> +set segfault_line [gdb_get_line_number "Segfault here"]
> +
> +# Setup GDB based on TARGET_ASYNC and TARGET_NON_STOP.  Setup some
> +# breakpoints in the inferior, one of which has an inferior call
> +# within its condition.
> +#
> +# Continue GDB, the breakpoint with inferior call will be hit, but the
> +# inferior call will never return.  We expect GDB to timeout.
> +#
> +# The reason that the inferior call never completes is that a second
> +# thread, on which the inferior call relies, either hits a breakpoint
> +# (when OTHER_THREAD_BP is true), or crashes (when OTHER_THREAD_BP is
> +# false).
> +proc run_test { target_async target_non_stop other_thread_bp } {
> +    save_vars { ::GDBFLAGS } {
> +	append ::GDBFLAGS " -ex \"maint set target-non-stop $target_non_stop\""
> +	append ::GDBFLAGS " -ex \"maintenance set target-async ${target_async}\""
> +
> +	clean_restart ${::binfile}
> +    }
> +
> +    if {![runto_main]} {
> +	fail "run to main"
> +	return
> +    }
> +
> +    # The default timeout for indirect inferior calls (e.g. inferior
> +    # calls for conditional breakpoint expressions) is pretty high.
> +    # We don't want the test to take too long, so reduce this.
> +    #
> +    # However, the test relies on a second thread hitting some event
> +    # (either a breakpoint or signal) before this timeout expires.
> +    #
> +    # There is a chance that on a really slow system this might not
> +    # happen, in which case the test might fail.
> +    #
> +    # However, we still allocate 5 seconds, which feels like it should
> +    # be enough time in most cases, but maybe we need to do something
> +    # smarter here?  Possibly we could have some initial run where the
> +    # inferior doesn't timeout, but does do the same interaction

Typo: "does do"

> +    # between threads, we could time that, and use that as the basis
> +    # for this timeout.  For now though, we just hope 5 seconds is
> +    # enough.
> +    gdb_test_no_output "set indirect-call-timeout 5"
> +
> +    gdb_breakpoint \
> +	"${::srcfile}:${::cond_bp_line} if (condition_func ())"
> +    set bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
> +		    "get number for conditional breakpoint"]
> +
> +    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
> +    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
> +			  "get number for final breakpoint"]
> +
> +    # The thread performing an inferior call relies on a second
> +    # thread.  The second thread will segfault unless it hits a
> +    # breakpoint first.  In either case the initial thread will not
> +    # complete its inferior call.
> +    if { $other_thread_bp } {
> +	gdb_breakpoint "${::srcfile}:${::segfault_line}"
> +	set segfault_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
> +				 "get number for segfault breakpoint"]
> +    }
> +
> +    # When non-stop mode is off we get slightly different output from GDB.
> +    if { [gdb_is_remote_or_extended_remote_target] && $target_non_stop == "off" } {

String comparison comment applies here, too.

> +	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" received signal
> SIGINT, Interrupt\\."
> +    } else {
> +	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\."
> +    }
> +
> +    gdb_test "continue" \
> +	[multi_line \
> +	     $stopped_line_pattern \
> +	     ".*" \
> +	     "Error in testing condition for breakpoint ${bp_num}:" \
> +	     "The program being debugged timed out while in a function called from GDB\\." \
> +	     "GDB remains in the frame where the timeout occurred\\." \
> +	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
> +	     "Evaluation of the expression containing the function" \
> +	     "\\(condition_func\\) will be abandoned\\." \
> +	     "When the function is done executing, GDB will silently stop\\."] \
> +	"expected timeout waiting for inferior call to complete"
> +
> +    # Remember that other thread that either crashed (with a segfault)
> +    # or hit a breakpoint?  Now that the inferior call has timed out,
> +    # if we try to resume then we should see the pending event from
> +    # that other thread.
> +    if { $other_thread_bp } {
> +	gdb_test "continue" \
> +	    [multi_line \
> +		 "Continuing\\." \
> +		 ".*" \
> +		 "" \
> +		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${segfault_bp_num},
> do_segfault \[^\r\n\]+:${::segfault_line}" \
> +		 "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"] \
> +	    "hit the segfault breakpoint"
> +    } else {
> +	gdb_test "continue" \
> +	    [multi_line \
> +		 "Continuing\\." \
> +		 ".*" \
> +		 "Thread ${::decimal} \"infcall-from-bp\" received signal SIGSEGV,
> Segmentation fault\\." \
> +		 "\\\[Switching to Thread \[^\r\n\]+\\\]" \
> +		 "${::hex} in do_segfault \\(\\) at \[^\r\n\]+:${::segfault_line}" \
> +		 "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"] \
> +	    "hit the segfault"
> +    }
> +}
> +
> +foreach_with_prefix target_async {"on" "off" } {
> +
> +    if { $target_async == "off" } {

And here, again.

> +	# GDB can't timeout while waiting for a thread if the target
> +	# runs with async-mode turned off; once the target is running
> +	# GDB is effectively blocked until the target stops for some
> +	# reason.
> +	continue
> +    }
> +
> +    foreach_with_prefix target_non_stop {"off" "on"} {
> +	foreach_with_prefix other_thread_bp { true false } {
> +	    run_test $target_async $target_non_stop $other_thread_bp
> +	}
> +    }
> +}
> --
> 2.25.4

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] 202+ messages in thread

* RE: [PATCHv2 11/13] gdb/remote: avoid SIGINT after calling remote_target::stop
  2023-01-18 16:18   ` [PATCHv2 11/13] gdb/remote: avoid SIGINT after calling remote_target::stop Andrew Burgess
@ 2023-01-20  9:14     ` Aktemur, Tankut Baris
  0 siblings, 0 replies; 202+ messages in thread
From: Aktemur, Tankut Baris @ 2023-01-20  9:14 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

On Wednesday, January 18, 2023 5:18 PM, Andrew Burgess wrote:
> Currently, if the remote target is not running in non-stop mode, then,
> when GDB calls remote_target::stop, we end up sending an interrupt
> packet \x03 to the remote target.
> 
> If the user interrupts the inferior from the GDB prompt (e.g. by
> typing Ctrl-c), then GDB calls remote_target::interrupt, which also
> ends up sending the interrupt packet.
> 
> The problem here is that both of these mechanisms end up sending the
> interrupt packet, which means, when the target stops with a SIGINT,
> and this is reported back to GDB, we have no choice but to report this
> to the user as a SIGINT stop event.
> 
> Now maybe this is the correct thing to do, after all the target has
> been stopped with SIGINT.  However, this leads to an unfortunate
> change in behaviour.
> 
> When running in non-stop mode, and remote_target::stop is called, the
> target will be stopped with a vCont packet, and this stop is then
> reported back to GDB as GDB_SIGNAL_0, this will cause GDB to print a
> message like:
> 
>   Program stopped.
> 
> Or:
> 
>   Thread NN "binary name" stopped.
> 
> In contrast, when non-stop mode is off, we get messages like:
> 
>   Program received SIGINT, Segmentation fault.
> 
> Or:
> 
>   Thread NN "binary name" received SIGINT, Segmentation fault.
> 
> In this commit I propose a mechanism where we can track that a stop
> has been requested for a particular thread through
> remote_target::stop, then, when the stop arrives, we can convert the
> SIGINT to a GDB_SIGNAL_0.  With this done GDB will now display the
> "stopped" based messages rather than the "received SIGINT" messages.
> 
> Two of the tests added in the previous commit exposed this issue.  In
> the previous commit the tests looked for either of the above
> patterns.  In this commit I've updated these tests to only look for
> the "stopped" based messages.
> ---
>  gdb/remote.c                                    | 17 +++++++++++++++++
>  gdb/testsuite/gdb.base/infcall-timeout.exp      |  9 +--------
>  .../infcall-from-bp-cond-timeout.exp            |  9 +--------
>  3 files changed, 19 insertions(+), 16 deletions(-)
> 
> diff --git a/gdb/remote.c b/gdb/remote.c
> index 218bca30d04..61781a24820 100644
> --- a/gdb/remote.c
> +++ b/gdb/remote.c
> @@ -1139,6 +1139,10 @@ struct remote_thread_info : public private_thread_info
>    std::string name;
>    int core = -1;
> 
> +  /* Only used when not in non-stop mode.  Set to true when a stop is
> +     requested for the thread.  */
> +  bool stop_requested = false;

The thread_info struct already has a `stop_requested` field.  Why can't we use it?

>    /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
>       sequence of bytes.  */
>    gdb::byte_vector thread_handle;
> @@ -7114,6 +7118,12 @@ remote_target::stop (ptid_t ptid)
>        /* We don't currently have a way to transparently pause the
>  	 remote target in all-stop mode.  Interrupt it instead.  */
>        remote_interrupt_as ();
> +
> +      /* Record that this thread's stop is a result of GDB asking for the
> +	 stop, rather than the user asking for an interrupt.  We can use
> +	 this information to adjust the waitstatus when it arrives.  */
> +      remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
> +      remote_thr->stop_requested = true;
>      }
>  }
> 
> @@ -8097,9 +8107,16 @@ remote_target::process_stop_reply (struct stop_reply *stop_reply,
>  	  /* If the target works in non-stop mode, a stop-reply indicates that
>  	     only this thread stopped.  */
>  	  remote_thr->set_not_resumed ();
> +	  gdb_assert (!remote_thr->stop_requested);
>  	}
>        else
>  	{
> +	  if (status->kind () == TARGET_WAITKIND_STOPPED
> +	      && status->sig () == GDB_SIGNAL_INT
> +	      && remote_thr->stop_requested)
> +	    status->set_stopped (GDB_SIGNAL_0);
> +	  remote_thr->stop_requested = false;
> +
>  	  /* If the target works in all-stop mode, a stop-reply indicates that
>  	     all the target's threads stopped.  */
>  	  for (thread_info *tp : all_non_exited_threads (this))
> diff --git a/gdb/testsuite/gdb.base/infcall-timeout.exp b/gdb/testsuite/gdb.base/infcall-
> timeout.exp
> index a5b0111ed04..bd6b2bfac3e 100644
> --- a/gdb/testsuite/gdb.base/infcall-timeout.exp
> +++ b/gdb/testsuite/gdb.base/infcall-timeout.exp
> @@ -45,16 +45,9 @@ proc_with_prefix run_test { target_async target_non_stop } {
> 
>      gdb_test_no_output "set direct-call-timeout 5"
> 
> -    # When non-stop mode is off we get slightly different output from GDB.
> -    if { [gdb_is_remote_or_extended_remote_target] && $target_non_stop == "off" } {
> -	set stopped_line_pattern "Program received signal SIGINT, Interrupt\\."
> -    } else {
> -	set stopped_line_pattern "Program stopped\\."
> -    }
> -
>      gdb_test "print function_that_never_returns ()" \
>  	[multi_line \
> -	     $stopped_line_pattern \
> +	     "Program stopped\\." \
>  	     ".*" \
>  	     "The program being debugged timed out while in a function called from GDB\\." \
>  	     "GDB remains in the frame where the timeout occurred\\." \
> diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
> b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
> index 3341ff33f19..9ba38e6896a 100644
> --- a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
> +++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
> @@ -92,16 +92,9 @@ proc run_test { target_async target_non_stop other_thread_bp } {
>  				 "get number for segfault breakpoint"]
>      }
> 
> -    # When non-stop mode is off we get slightly different output from GDB.
> -    if { [gdb_is_remote_or_extended_remote_target] && $target_non_stop == "off" } {
> -	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" received signal
> SIGINT, Interrupt\\."
> -    } else {
> -	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\."
> -    }
> -
>      gdb_test "continue" \
>  	[multi_line \
> -	     $stopped_line_pattern \
> +	     "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\." \
>  	     ".*" \
>  	     "Error in testing condition for breakpoint ${bp_num}:" \
>  	     "The program being debugged timed out while in a function called from GDB\\." \
> --
> 2.25.4

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] 202+ messages in thread

* RE: [PATCHv2 12/13] gdb: introduce unwind-on-timeout setting
  2023-01-18 16:18   ` [PATCHv2 12/13] gdb: introduce unwind-on-timeout setting Andrew Burgess
  2023-01-18 17:33     ` Eli Zaretskii
@ 2023-01-20  9:26     ` Aktemur, Tankut Baris
  1 sibling, 0 replies; 202+ messages in thread
From: Aktemur, Tankut Baris @ 2023-01-20  9:26 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

On Wednesday, January 18, 2023 5:18 PM, Andrew Burgess wrote:
> Now that inferior function calls can timeout (see the recent
> introduction of direct-call-timeout and indirect-call-timeout), this
> commit adds a new setting unwind-on-timeout.
> 
> This new setting is just like the existing unwindonsignal and
> unwind-on-terminating-exception, but the new setting will cause GDB to
> unwind the stack if an inferior function call times out.
> 
> The existing inferior function call timeout tests have been updated to
> cover the new setting.
> ---
>  gdb/NEWS                                      |  9 +++
>  gdb/doc/gdb.texinfo                           | 33 +++++++---
>  gdb/infcall.c                                 | 62 ++++++++++++++++---
>  gdb/testsuite/gdb.base/infcall-timeout.exp    | 49 +++++++++++----
>  .../infcall-from-bp-cond-timeout.exp          | 55 +++++++++++-----
>  5 files changed, 164 insertions(+), 44 deletions(-)
> 
> diff --git a/gdb/NEWS b/gdb/NEWS
> index 2689569a8f3..511a750407a 100644
> --- a/gdb/NEWS
> +++ b/gdb/NEWS
> @@ -35,6 +35,15 @@ show indirect-call-timeout
>    ignored, GDB will wait indefinitely for an inferior function to
>    complete, unless interrupted by the user using Ctrl-C.
> 
> +set unwind-on-timeout on|off
> +show unwind-on-timeout
> +  These commands control whether GDB should unwind the stack when a
> +  timeout occurs during an inferior function call.  The default is
> +  off, in which case the inferior will remain in the frame where the
> +  timeout occurred.  When on GDB will unwind the stack remocing the
> +  dummy frame that was added for the inferior call, and restoring the
> +  inferior state to how it was before the inferior call started.
> +
>  * MI changes
> 
>  ** mi now reports 'no-history' as a stop reason when hitting the end of the
> diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
> index 9eb8b1db00e..aa88221677e 100644
> --- a/gdb/doc/gdb.texinfo
> +++ b/gdb/doc/gdb.texinfo
> @@ -5719,10 +5719,10 @@
>  the called function, or the called function may receive a signal
>  (e.g.@ a @code{SIGSEGV}) as a result of some undefined behaviour, if
>  this happens then @value{GDBN} will stop.  Depending on the settings
> -@code{unwindonsignal} and @code{unwind-on-terminating-exception}
> -(@pxref{Calling,,Calling Program Functions}) @value{GDBN} may unwind
> -the stack back to the breakpoint location, or may leave the program at
> -the frame where the stop occurred.
> +@code{unwindonsignal}, @code{unwind-on-terminating-exception}, and
> +@code{unwind-on-timeout} (@pxref{Calling,,Calling Program Functions})
> +@value{GDBN} may unwind the stack back to the breakpoint location, or
> +may leave the program at the frame where the stop occurred.
> 
>  Breakpoint conditions can also be evaluated on the target's side if
>  the target supports it.  Instead of evaluating the conditions locally,
> @@ -20718,6 +20718,21 @@
>  Show the current setting of stack unwinding in the functions called by
>  @value{GDBN}.
> 
> +@item set unwind-on-timeout
> +@kindex set unwind-on-timeout
> +@cindex unwind stack in called functions when timing out
> +@cindex call dummy stack unwinding on timeout.
> +Set unwinding of the stack if a function called from @value{GDBN}
> +times out.  If set to @code{off} (the default), @value{GDBN} stops in
> +the frame where the timeout occurred.  If set to @code{on},
> +@value{GDBN} unwinds the stack it created for the call and restores
> +the context to what it was before the call.
> +
> +@item show unwind-on-timeout
> +@kindex show unwind-on-timeout
> +Show whether @value{GDBN} will unwind the stack if a function called
> +from @value{GDBN} times out.
> +
>  @item set may-call-functions
>  @kindex set may-call-functions
>  @cindex disabling calling functions in the program
> @@ -20748,11 +20763,11 @@
>  call by typing the interrupt character (often @kbd{Ctrl-c}).
> 
>  If a called function is interrupted for any reason, and the stack is
> -not unwound (due to @code{set unwind-on-terminating-exception on} or
> -@code{set unwindonsignal on}), then the dummy-frame, created by
> -@value{GDBN} to facilitate the call to the program function, will be
> -visible in the backtrace, for example frame @code{#3} in the following
> -backtrace:
> +not unwound (due to @code{set unwind-on-terminating-exception on},
> +@code{set unwind-on-timeout}, or @code{set unwindonsignal on}), then
> +the dummy-frame, created by @value{GDBN} to facilitate the call to the
> +program function, will be visible in the backtrace, for example frame
> +@code{#3} in the following backtrace:
> 
>  @smallexample
>  (@value{GDBP}) backtrace
> diff --git a/gdb/infcall.c b/gdb/infcall.c
> index 9afca4f5bc6..272e3cccf87 100644
> --- a/gdb/infcall.c
> +++ b/gdb/infcall.c
> @@ -217,6 +217,27 @@ show_unwind_on_terminating_exception_p (struct ui_file *file, int
> from_tty,
>  	      value);
>  }
> 
> +/* This boolean tells what gdb should do if a signal is received while
> +   in a function called from gdb (call dummy).  If set, gdb unwinds

In a former review comment, I was asked to use "GDB" (all uppercase)
as the spelling.

> +   the stack and restore the context to what as it was before the

restore -> restores
And "as" should be removed.

> +   call.
> +
> +   The default is to stop in the frame where the signal was received.  */
> +
> +static bool unwind_on_timeout_p = false;
> +
> +/* Implement 'show unwind-on-timeout'.  */
> +
> +static void
> +show_unwind_on_timeout_p (struct ui_file *file, int from_tty,
> +			  struct cmd_list_element *c, const char *value)
> +{
> +  gdb_printf (file,
> +	      _("Unwinding of stack if a timeout occurs "
> +		"while in a call dummy is %s.\n"),
> +	      value);
> +}
> +
>  /* Perform the standard coercions that are specified
>     for arguments to be passed to C, Ada or Fortran functions.
> 
> @@ -1691,14 +1712,27 @@ When the function is done executing, GDB will silently stop."),
>  	  /* A timeout results in a signal being sent to the inferior.  */
>  	  gdb_assert (stopped_by_random_signal);
> 
> -	  /* Indentation is weird here.  A later patch is going to move the
> -	    following block into an if/else, so I'm leaving the indentation
> -	    here to minimise the later patch.
> +	  if (unwind_on_timeout_p)
> +	    {
> +	      /* The user wants the context restored.  */
> +
> +	      /* We must get back to the frame we were before the
> +		 dummy call.  */
> +	      dummy_frame_pop (dummy_id, call_thread.get ());
> +
> +	      /* We also need to restore inferior status to that before the
> +		 dummy call.  */
> +	      restore_infcall_control_state (inf_status.release ());
> 
> -	    Also, the error message used below refers to 'set
> -	    unwind-on-timeout' which doesn't exist yet.  This will be added
> -	    in a later commit, I'm leaving this in for now to minimise the
> -	    churn caused by the commit that adds unwind-on-timeout.  */
> +	      error (_("\
> +The program being debugged timed out while in a function called from GDB.\n\
> +GDB has restored the context to what it was before the call.\n\
> +To change this behavior use \"set unwind-on-timeout off\".\n\
> +Evaluation of the expression containing the function\n\
> +(%s) will be abandoned."),
> +		     name.c_str ());
> +	    }
> +	  else
>  	    {
>  	      /* The user wants to stay in the frame where we stopped
>  		 (default).  Discard inferior status, we're not at the same
> @@ -1824,6 +1858,20 @@ The default is to unwind the frame."),
>  			   show_unwind_on_terminating_exception_p,
>  			   &setlist, &showlist);
> 
> +  add_setshow_boolean_cmd ("unwind-on-timeout", no_class,
> +			   &unwind_on_timeout_p, _("\
> +Set unwinding of stack if a timeout occurs while in a call dummy."), _("\
> +Show unwinding of stack if a timeout occurs while in a call dummy."),
> +			   _("\
> +The unwind on timeout flag lets the user determine what gdb should do if\n\
> +gdb times out while in a function called from gdb.  If set, gdb unwinds\n\
> +the stack and restores the context to what it was before the call.  If\n\
> +unset, gdb leaves the inferior in the frame where the timeout occurred.\n\
> +The default is to stop in the frame where the timeout occurred."),
> +			   NULL,
> +			   show_unwind_on_timeout_p,
> +			   &setlist, &showlist);
> +
>    add_setshow_uinteger_cmd ("direct-call-timeout", no_class,
>  			    &direct_call_timeout, _("\
>  Set the timeout, for direct calls to inferior function calls."), _("\
> diff --git a/gdb/testsuite/gdb.base/infcall-timeout.exp b/gdb/testsuite/gdb.base/infcall-
> timeout.exp
> index bd6b2bfac3e..a4d9fd6ee61 100644
> --- a/gdb/testsuite/gdb.base/infcall-timeout.exp
> +++ b/gdb/testsuite/gdb.base/infcall-timeout.exp
> @@ -28,7 +28,11 @@ if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
>  # the direct-call-timeout, and make an inferior function call that
>  # will never return.  GDB should eventually timeout and stop the
>  # inferior.
> -proc_with_prefix run_test { target_async target_non_stop } {
> +#
> +# When UNWIND is "off" the inferior wil be left in the frame where the
> +# timeout occurs, otherwise, when UNWIND is "on", GDB should unwind
> +# back to the frame where the inferior call was made.
> +proc_with_prefix run_test { target_async target_non_stop unwind } {
>      save_vars { ::GDBFLAGS } {
>  	append ::GDBFLAGS \
>  	    " -ex \"maint set target-non-stop $target_non_stop\""
> @@ -44,19 +48,36 @@ proc_with_prefix run_test { target_async target_non_stop } {
>      }
> 
>      gdb_test_no_output "set direct-call-timeout 5"
> +    gdb_test_no_output "set unwind-on-timeout $unwind"
> +
> +    if { $unwind } {
> +	gdb_test "print function_that_never_returns ()" \
> +	    [multi_line \
> +		 "Program stopped\\." \
> +		 ".*" \
> +		 "The program being debugged timed out while in a function called from GDB\\."
> \
> +		 "GDB has restored the context to what it was before the call\\." \
> +		 "To change this behavior use \"set unwind-on-timeout off\"\\." \
> +		 "Evaluation of the expression containing the function" \
> +		 "\\(function_that_never_returns\\) will be abandoned\\."]
> 
> -    gdb_test "print function_that_never_returns ()" \
> -	[multi_line \
> -	     "Program stopped\\." \
> -	     ".*" \
> -	     "The program being debugged timed out while in a function called from GDB\\." \
> -	     "GDB remains in the frame where the timeout occurred\\." \
> -	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
> -	     "Evaluation of the expression containing the function" \
> -	     "\\(function_that_never_returns\\) will be abandoned\\." \
> -	     "When the function is done executing, GDB will silently stop\\."]
> +	gdb_test "bt" \
> +	    "#0\\s+main \\(\\).*"
> +    } else {
> +	gdb_test "print function_that_never_returns ()" \
> +	    [multi_line \
> +		 "Program stopped\\." \
> +		 ".*" \
> +		 "The program being debugged timed out while in a function called from GDB\\."
> \
> +		 "GDB remains in the frame where the timeout occurred\\." \
> +		 "To change this behavior use \"set unwind-on-timeout on\"\\." \
> +		 "Evaluation of the expression containing the function" \
> +		 "\\(function_that_never_returns\\) will be abandoned\\." \
> +		 "When the function is done executing, GDB will silently stop\\."]
> 
> -    gdb_test "bt" ".* function_that_never_returns .*<function called from gdb>.*"
> +	gdb_test "bt" \
> +	    ".* function_that_never_returns .*<function called from gdb>.*"
> +    }
>  }
> 
>  foreach_with_prefix target_async { "on" "off" } {
> @@ -70,6 +91,8 @@ foreach_with_prefix target_async { "on" "off" } {
>      }
> 
>      foreach_with_prefix target_non_stop { "on" "off" } {
> -	run_test $target_async $target_non_stop
> +	foreach_with_prefix unwind { "on" "off" } {
> +	    run_test $target_async $target_non_stop $unwind
> +	}
>      }
>  }
> diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
> b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
> index 9ba38e6896a..847a850673d 100644
> --- a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
> +++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
> @@ -41,7 +41,12 @@ set segfault_line [gdb_get_line_number "Segfault here"]
>  # thread, on which the inferior call relies, either hits a breakpoint
>  # (when OTHER_THREAD_BP is true), or crashes (when OTHER_THREAD_BP is
>  # false).
> -proc run_test { target_async target_non_stop other_thread_bp } {
> +#
> +# When UNWIND is "on" GDB will unwind the thread which performed the
> +# inferior function call back to the state where the inferior call was
> +# made (when the inferior call times out).  Otherwise, when UNWIND is
> +# "off", the inferior is left in the frame where the timeout occurred.
> +proc run_test { target_async target_non_stop other_thread_bp unwind } {
>      save_vars { ::GDBFLAGS } {
>  	append ::GDBFLAGS " -ex \"maint set target-non-stop $target_non_stop\""
>  	append ::GDBFLAGS " -ex \"maintenance set target-async ${target_async}\""
> @@ -72,6 +77,7 @@ proc run_test { target_async target_non_stop other_thread_bp } {
>      # for this timeout.  For now though, we just hope 5 seconds is
>      # enough.
>      gdb_test_no_output "set indirect-call-timeout 5"
> +    gdb_test_no_output "set unwind-on-timeout $unwind"
> 
>      gdb_breakpoint \
>  	"${::srcfile}:${::cond_bp_line} if (condition_func ())"
> @@ -92,18 +98,35 @@ proc run_test { target_async target_non_stop other_thread_bp } {
>  				 "get number for segfault breakpoint"]
>      }
> 
> -    gdb_test "continue" \
> -	[multi_line \
> -	     "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\." \
> -	     ".*" \
> -	     "Error in testing condition for breakpoint ${bp_num}:" \
> -	     "The program being debugged timed out while in a function called from GDB\\." \
> -	     "GDB remains in the frame where the timeout occurred\\." \
> -	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
> -	     "Evaluation of the expression containing the function" \
> -	     "\\(condition_func\\) will be abandoned\\." \
> -	     "When the function is done executing, GDB will silently stop\\."] \
> -	"expected timeout waiting for inferior call to complete"
> +    if { $unwind } {
> +	gdb_test "continue" \
> +	    [multi_line \
> +		 "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\." \
> +		 ".*" \
> +		 "Error in testing condition for breakpoint ${bp_num}:" \
> +		 "The program being debugged timed out while in a function called from GDB\\."
> \
> +		 "GDB has restored the context to what it was before the call\\." \
> +		 "To change this behavior use \"set unwind-on-timeout off\"\\." \
> +		 "Evaluation of the expression containing the function" \
> +		 "\\(condition_func\\) will be abandoned\\." \
> +		 "" \
> +		 "Thread ${::decimal}\[^\r\n\]*hit Breakpoint ${bp_num}, \[^\r\n\]+" \
> +		 "\[^\r\n\]+ Conditional breakpoint here\\. \[^\r\n\]+"] \
> +	    "expected timeout waiting for inferior call to complete"
> +    } else {
> +	gdb_test "continue" \
> +	    [multi_line \
> +		 "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\." \
> +		 ".*" \
> +		 "Error in testing condition for breakpoint ${bp_num}:" \
> +		 "The program being debugged timed out while in a function called from GDB\\."
> \
> +		 "GDB remains in the frame where the timeout occurred\\." \
> +		 "To change this behavior use \"set unwind-on-timeout on\"\\." \
> +		 "Evaluation of the expression containing the function" \
> +		 "\\(condition_func\\) will be abandoned\\." \
> +		 "When the function is done executing, GDB will silently stop\\."] \
> +	    "expected timeout waiting for inferior call to complete"
> +    }
> 
>      # Remember that other thread that either crashed (with a segfault)
>      # or hit a breakpoint?  Now that the inferior call has timed out,
> @@ -142,8 +165,10 @@ foreach_with_prefix target_async {"on" "off" } {
>      }
> 
>      foreach_with_prefix target_non_stop {"off" "on"} {
> -	foreach_with_prefix other_thread_bp { true false } {
> -	    run_test $target_async $target_non_stop $other_thread_bp
> +	foreach_with_prefix unwind {"off" "on"} {
> +	    foreach_with_prefix other_thread_bp { true false } {
> +		run_test $target_async $target_non_stop $other_thread_bp $unwind
> +	    }
>  	}
>      }
>  }
> --
> 2.25.4

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] 202+ messages in thread

* RE: [PATCHv2 00/13] Infcalls from B/P conditions in multi-threaded inferiors
  2023-01-18 16:17 ` [PATCHv2 00/13] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                     ` (12 preceding siblings ...)
  2023-01-18 16:18   ` [PATCHv2 13/13] gdb: rename unwindonsignal to unwind-on-signal Andrew Burgess
@ 2023-01-20  9:34   ` Aktemur, Tankut Baris
  2023-01-25 15:53     ` Andrew Burgess
  2023-01-31 17:27   ` [PATCHv3 " Andrew Burgess
  14 siblings, 1 reply; 202+ messages in thread
From: Aktemur, Tankut Baris @ 2023-01-20  9:34 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

On Wednesday, January 18, 2023 5:18 PM, Andrew Burgess wrote:
> Thanks for the feedback on V1.  I merged a couple of the really minor
> patches from the V1 series, but after the feedback I'm some new
> patches in the v2 series.
> 
> In V2:
> 
>   - Rebased onto something closer to HEAD of master,
> 
>   - Patches #1, #2, #12, and #13 are new in this series,
> 
>   - Patches #3 to #9, and #11 are unchanged since their V1 iteration,
> 
>   - Patches #10 has changed slightly in implementation since v1, and
>     the docs have been significantly updated.

I've looked at the series and posted my comments.  Thanks for doing this.

Is there a chance to push the branch to somewhere?  Git am does not 
work very well for my setup.

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] 202+ messages in thread

* RE: [PATCHv2 03/13] gdb: include breakpoint number in testing condition error message
  2023-01-19 11:34       ` Eli Zaretskii
@ 2023-01-20  9:46         ` Aktemur, Tankut Baris
  2023-01-25 16:49           ` Andrew Burgess
  0 siblings, 1 reply; 202+ messages in thread
From: Aktemur, Tankut Baris @ 2023-01-20  9:46 UTC (permalink / raw)
  To: Eli Zaretskii, gdb-patches; +Cc: aburgess

On Thursday, January 19, 2023 12:34 PM, Eli Zaretskii wrote:
> > From: "Aktemur, Tankut Baris" <tankut.baris.aktemur@intel.com>
> > Date: Thu, 19 Jan 2023 10:54:16 +0000
> >
> > On Wednesday, January 18, 2023 5:18 PM, Andrew Burgess wrote:
> > ...
> > > So, in this commit, in preparation for the later commits, I propose to
> > > change the 'Error in testing breakpoint condition:' line to this:
> > >
> > >   Error in testing condition for breakpoint NUMBER:
> >
> > Here, because we're now referring to a particular breakpoint,
> > I believe the spelling should be "condition for Breakpoint NUMBER:",
> > with uppercase 'B'.  Maybe Eli can comment on this, too.
> 
> No, capitalized "Breakpoint" would read wrong English-wise in that
> case.

For me to better understand the rule, wouldn't it be the same as
"see in figure 5" vs. "see in Figure 5", or "given in section 2.1"
vs. "given in Section 2.1"?

-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] 202+ messages in thread

* RE: [PATCHv2 00/13] Infcalls from B/P conditions in multi-threaded inferiors
  2023-01-20  9:34   ` [PATCHv2 00/13] Infcalls from B/P conditions in multi-threaded inferiors Aktemur, Tankut Baris
@ 2023-01-25 15:53     ` Andrew Burgess
  2023-02-16 11:09       ` Aktemur, Tankut Baris
  0 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2023-01-25 15:53 UTC (permalink / raw)
  To: Aktemur, Tankut Baris, gdb-patches

"Aktemur, Tankut Baris" <tankut.baris.aktemur@intel.com> writes:

> On Wednesday, January 18, 2023 5:18 PM, Andrew Burgess wrote:
>> Thanks for the feedback on V1.  I merged a couple of the really minor
>> patches from the V1 series, but after the feedback I'm some new
>> patches in the v2 series.
>> 
>> In V2:
>> 
>>   - Rebased onto something closer to HEAD of master,
>> 
>>   - Patches #1, #2, #12, and #13 are new in this series,
>> 
>>   - Patches #3 to #9, and #11 are unchanged since their V1 iteration,
>> 
>>   - Patches #10 has changed slightly in implementation since v1, and
>>     the docs have been significantly updated.
>
> I've looked at the series and posted my comments.  Thanks for doing this.
>
> Is there a chance to push the branch to somewhere?  Git am does not 
> work very well for my setup.

Hi!

Thanks for looking through,  I've pushed the branch to
users/aburgess/bp-inferior-calls.  I'll go through your feedback and
make any updates needed and force push this branch.

Thanks,
Andrew


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

* RE: [PATCHv2 03/13] gdb: include breakpoint number in testing condition error message
  2023-01-20  9:46         ` Aktemur, Tankut Baris
@ 2023-01-25 16:49           ` Andrew Burgess
  2023-01-25 17:09             ` Eli Zaretskii
  0 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2023-01-25 16:49 UTC (permalink / raw)
  To: Aktemur, Tankut Baris, Eli Zaretskii, gdb-patches

"Aktemur, Tankut Baris" <tankut.baris.aktemur@intel.com> writes:

> On Thursday, January 19, 2023 12:34 PM, Eli Zaretskii wrote:
>> > From: "Aktemur, Tankut Baris" <tankut.baris.aktemur@intel.com>
>> > Date: Thu, 19 Jan 2023 10:54:16 +0000
>> >
>> > On Wednesday, January 18, 2023 5:18 PM, Andrew Burgess wrote:
>> > ...
>> > > So, in this commit, in preparation for the later commits, I propose to
>> > > change the 'Error in testing breakpoint condition:' line to this:
>> > >
>> > >   Error in testing condition for breakpoint NUMBER:
>> >
>> > Here, because we're now referring to a particular breakpoint,
>> > I believe the spelling should be "condition for Breakpoint NUMBER:",
>> > with uppercase 'B'.  Maybe Eli can comment on this, too.
>> 
>> No, capitalized "Breakpoint" would read wrong English-wise in that
>> case.
>
> For me to better understand the rule, wouldn't it be the same as
> "see in figure 5" vs. "see in Figure 5", or "given in section 2.1"
> vs. "given in Section 2.1"?

Given the number of corrections I get for my doc edits, this should be
taken with a pinch of salt, but ...

... in the examples you give "Figure 5" and "Section 2.1" would be the
actual name of a thing, e.g. there will be a figure somewhere with the
title "Figure 5" and a section somewhere titled "Section 2.1", thus the
capitalisation is correct because you're referencing a named thing.

In the breakpoint case, what we're referencing isn't _named_ Breakpoint
5, it just is the 5th breakpoint.

At least, that's what I'd do unless told different :)

Thanks,
Andrew


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

* Re: [PATCHv2 03/13] gdb: include breakpoint number in testing condition error message
  2023-01-25 16:49           ` Andrew Burgess
@ 2023-01-25 17:09             ` Eli Zaretskii
  0 siblings, 0 replies; 202+ messages in thread
From: Eli Zaretskii @ 2023-01-25 17:09 UTC (permalink / raw)
  To: Andrew Burgess; +Cc: tankut.baris.aktemur, gdb-patches

> From: Andrew Burgess <aburgess@redhat.com>
> Date: Wed, 25 Jan 2023 16:49:11 +0000
> 
> "Aktemur, Tankut Baris" <tankut.baris.aktemur@intel.com> writes:
> 
> >> No, capitalized "Breakpoint" would read wrong English-wise in that
> >> case.
> >
> > For me to better understand the rule, wouldn't it be the same as
> > "see in figure 5" vs. "see in Figure 5", or "given in section 2.1"
> > vs. "given in Section 2.1"?
> 
> Given the number of corrections I get for my doc edits, this should be
> taken with a pinch of salt, but ...
> 
> ... in the examples you give "Figure 5" and "Section 2.1" would be the
> actual name of a thing, e.g. there will be a figure somewhere with the
> title "Figure 5" and a section somewhere titled "Section 2.1", thus the
> capitalisation is correct because you're referencing a named thing.
> 
> In the breakpoint case, what we're referencing isn't _named_ Breakpoint
> 5, it just is the 5th breakpoint.

Yes, that's correct.  "Breakpoint" is not a proper name here, it's
just a word.

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

* [PATCHv3 00/13] Infcalls from B/P conditions in multi-threaded inferiors
  2023-01-18 16:17 ` [PATCHv2 00/13] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                     ` (13 preceding siblings ...)
  2023-01-20  9:34   ` [PATCHv2 00/13] Infcalls from B/P conditions in multi-threaded inferiors Aktemur, Tankut Baris
@ 2023-01-31 17:27   ` Andrew Burgess
  2023-01-31 17:27     ` [PATCHv3 01/13] gdb/doc: extended documentation for inferior function calls Andrew Burgess
                       ` (13 more replies)
  14 siblings, 14 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-01-31 17:27 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

In v3:

  - Updates for review feedback, biggest changes in #10 and #11, but
    minor changes to most patches.

In V2:

  - Rebased onto something closer to HEAD of master,

  - Patches #1, #2, #12, and #13 are new in this series,

  - Patches #3 to #9, and #11 are unchanged since their V1 iteration,

  - Patches #10 has changed slightly in implementation since v1, and
    the docs have been significantly updated.

---

Andrew Burgess (13):
  gdb/doc: extended documentation for inferior function calls
  gdb/doc: extend the documentation for conditional breakpoints
  gdb: include breakpoint number in testing condition error message
  gdbserver: allows agent_mem_read to return an error code
  gdbserver: allow agent expressions to fail with invalid memory access
  gdb: avoid repeated signal reporting during failed conditional
    breakpoint
  gdb: don't always print breakpoint location after failed condition
    check
  Revert "gdb: remove unnecessary parameter wait_ptid from
    do_target_wait"
  gdb: fix b/p conditions with infcalls in multi-threaded inferiors
  gdb: add timeouts for inferior function calls
  gdb/remote: avoid SIGINT after calling remote_target::stop
  gdb: introduce unwind-on-timeout setting
  gdb: rename unwindonsignal to unwind-on-signal

 gdb/NEWS                                      |  38 +++
 gdb/breakpoint.c                              |  17 +-
 gdb/doc/gdb.texinfo                           | 138 +++++++-
 gdb/gdbthread.h                               |   3 +
 gdb/infcall.c                                 | 305 +++++++++++++++++-
 gdb/infrun.c                                  |  70 +++-
 gdb/infrun.h                                  |   3 +-
 gdb/remote.c                                  |  10 +
 gdb/testsuite/gdb.base/bp-cond-failure.c      |  30 ++
 gdb/testsuite/gdb.base/bp-cond-failure.exp    | 107 ++++++
 gdb/testsuite/gdb.base/callfuncs.exp          |   4 +-
 .../gdb.base/catch-signal-siginfo-cond.exp    |   2 +-
 gdb/testsuite/gdb.base/gnu-ifunc.exp          |   2 +-
 gdb/testsuite/gdb.base/help.exp               |   2 +-
 gdb/testsuite/gdb.base/infcall-failure.c      |  48 +++
 gdb/testsuite/gdb.base/infcall-failure.exp    | 183 +++++++++++
 gdb/testsuite/gdb.base/infcall-timeout.c      |  36 +++
 gdb/testsuite/gdb.base/infcall-timeout.exp    |  98 ++++++
 gdb/testsuite/gdb.base/unwindonsignal.exp     |  36 ++-
 gdb/testsuite/gdb.compile/compile-cplus.exp   |   2 +-
 gdb/testsuite/gdb.compile/compile.exp         |   2 +-
 gdb/testsuite/gdb.cp/gdb2495.exp              |  16 +-
 gdb/testsuite/gdb.fortran/function-calls.exp  |   2 +-
 gdb/testsuite/gdb.mi/mi-syn-frame.exp         |   2 +-
 .../gdb.python/py-finish-breakpoint.exp       |   2 +-
 .../infcall-from-bp-cond-other-thread-event.c | 135 ++++++++
 ...nfcall-from-bp-cond-other-thread-event.exp | 175 ++++++++++
 .../gdb.threads/infcall-from-bp-cond-simple.c |  89 +++++
 .../infcall-from-bp-cond-simple.exp           | 236 ++++++++++++++
 .../gdb.threads/infcall-from-bp-cond-single.c | 139 ++++++++
 .../infcall-from-bp-cond-single.exp           | 118 +++++++
 .../infcall-from-bp-cond-timeout.c            | 169 ++++++++++
 .../infcall-from-bp-cond-timeout.exp          | 174 ++++++++++
 .../gdb.threads/thread-unwindonsignal.exp     |   8 +-
 gdbserver/ax.cc                               |  12 +-
 gdbserver/ax.h                                |   3 +-
 gdbserver/tracepoint.cc                       |  11 +-
 gdbserver/tracepoint.h                        |   9 +-
 38 files changed, 2357 insertions(+), 79 deletions(-)
 create mode 100644 gdb/testsuite/gdb.base/bp-cond-failure.c
 create mode 100644 gdb/testsuite/gdb.base/bp-cond-failure.exp
 create mode 100644 gdb/testsuite/gdb.base/infcall-failure.c
 create mode 100644 gdb/testsuite/gdb.base/infcall-failure.exp
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.c
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp


base-commit: 0fcf99b8ab5ccbde30fa7d36742e670cd4df48ef
-- 
2.25.4


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

* [PATCHv3 01/13] gdb/doc: extended documentation for inferior function calls
  2023-01-31 17:27   ` [PATCHv3 " Andrew Burgess
@ 2023-01-31 17:27     ` Andrew Burgess
  2023-01-31 17:27     ` [PATCHv3 02/13] gdb/doc: extend the documentation for conditional breakpoints Andrew Burgess
                       ` (12 subsequent siblings)
  13 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-01-31 17:27 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

I noticed that the documentation for inferior function calls doesn't
say much about what happens if/when an inferior function call is
interrupted, i.e. it doesn't describe what the dummy frame looks like
on the stack, or how GDB behaves when the inferior is continued and
reaches the dummy frame.

This commit aims to add some of this missing information.
---
 gdb/doc/gdb.texinfo | 32 ++++++++++++++++++++++++++++++++
 1 file changed, 32 insertions(+)

diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index 03033c7f9e3..682f85387e5 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -20708,6 +20708,7 @@
 in that case is controlled by the
 @code{set unwind-on-terminating-exception} command.
 
+@anchor{stack unwind settings}
 @table @code
 @item set unwindonsignal
 @kindex set unwindonsignal
@@ -20765,6 +20766,37 @@
 
 @end table
 
+When calling a function within a program, it is possible that the
+program could enter a state from which the called function may never
+return.  If this happens then it is possible to interrupt the function
+call by typing the interrupt character (often @kbd{Ctrl-c}).
+
+If a called function is interrupted for any reason, including hitting
+a breakpoint, or triggering a watchpoint, and the stack is not unwound
+due to @code{set unwind-on-terminating-exception on} or @code{set
+unwindonsignal on} (@pxref{stack unwind settings}),
+then the dummy-frame, created by @value{GDBN} to facilitate the call
+to the program function, will be visible in the backtrace, for example
+frame @code{#3} in the following backtrace:
+
+@smallexample
+(@value{GDBP}) backtrace
+#0  0x00007ffff7b3d1e7 in nanosleep () from /lib64/libc.so.6
+#1  0x00007ffff7b3d11e in sleep () from /lib64/libc.so.6
+#2  0x000000000040113f in deadlock () at test.cc:13
+#3  <function called from gdb>
+#4  breakpt () at test.cc:20
+#5  0x0000000000401151 in main () at test.cc:25
+@end smallexample
+
+At this point it is possible to examine the state of the inferior just
+like any other stop.
+
+Depending on why the function was interrupted then it may be possible
+to resume the inferior (using commands like @code{continue},
+@code{step}, etc).  In this case, when the inferior finally returns to
+the dummy-frame, @value{GDBN} will once again halt the inferior.
+
 @subsection Calling functions with no debug info
 
 @cindex no debug info functions
-- 
2.25.4


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

* [PATCHv3 02/13] gdb/doc: extend the documentation for conditional breakpoints
  2023-01-31 17:27   ` [PATCHv3 " Andrew Burgess
  2023-01-31 17:27     ` [PATCHv3 01/13] gdb/doc: extended documentation for inferior function calls Andrew Burgess
@ 2023-01-31 17:27     ` Andrew Burgess
  2023-01-31 18:07       ` Eli Zaretskii
  2023-01-31 17:27     ` [PATCHv3 03/13] gdb: include breakpoint number in testing condition error message Andrew Burgess
                       ` (11 subsequent siblings)
  13 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2023-01-31 17:27 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

This documentation update adds more text to describe what happens if a
conditional breakpoint calls an inferior function, and the inferior
function is interrupted for some reason.
---
 gdb/doc/gdb.texinfo | 11 +++++++++++
 1 file changed, 11 insertions(+)

diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index 682f85387e5..dd8267f448f 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -5713,6 +5713,17 @@
 purpose of performing side effects when a breakpoint is reached
 (@pxref{Break Commands, ,Breakpoint Command Lists}).
 
+If a breakpoint condition calls a function in your program, then it is
+possible that your program could stop for some reason while in the
+called function.  For example, @value{GDBN} might hit a breakpoint in
+the called function, or the called function may receive a signal
+(e.g.@ a @code{SIGSEGV}) as a result of some undefined behavior.  If
+this happens then @value{GDBN} will stop.  Depending on the settings
+@code{unwindonsignal} and @code{unwind-on-terminating-exception}
+(@pxref{Calling,,Calling Program Functions}) @value{GDBN} may unwind
+the stack back to the breakpoint location, or may leave the program at
+the frame where the stop occurred.
+
 Breakpoint conditions can also be evaluated on the target's side if
 the target supports it.  Instead of evaluating the conditions locally,
 @value{GDBN} encodes the expression into an agent expression
-- 
2.25.4


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

* [PATCHv3 03/13] gdb: include breakpoint number in testing condition error message
  2023-01-31 17:27   ` [PATCHv3 " Andrew Burgess
  2023-01-31 17:27     ` [PATCHv3 01/13] gdb/doc: extended documentation for inferior function calls Andrew Burgess
  2023-01-31 17:27     ` [PATCHv3 02/13] gdb/doc: extend the documentation for conditional breakpoints Andrew Burgess
@ 2023-01-31 17:27     ` Andrew Burgess
  2023-02-16 10:15       ` Aktemur, Tankut Baris
  2023-01-31 17:27     ` [PATCHv3 04/13] gdbserver: allows agent_mem_read to return an error code Andrew Burgess
                       ` (10 subsequent siblings)
  13 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2023-01-31 17:27 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

When GDB fails to test the condition of a conditional breakpoint, for
whatever reason, the error message looks like this:

  (gdb) break foo if (*(int *) 0) == 1
  Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
  (gdb) r
  Starting program: /tmp/bpcond
  Error in testing breakpoint condition:
  Cannot access memory at address 0x0

  Breakpoint 1, foo () at bpcond.c:11
  11	  int a = 32;
  (gdb)

The line I'm interested in for this commit is this one:

  Error in testing breakpoint condition:

In the case above we can figure out that the problematic breakpoint
was #1 because in the final line of the message GDB reports the stop a
breakpoint #1.

However, in the next few patches I plan to change this.  In some cases
I don't think it makes sense for GDB to report the stop as being at
breakpoint #1, consider this case:

  (gdb) list some_func
  1	int
  2	some_func ()
  3	{
  4	  int *p = 0;
  5	  return *p;
  6	}
  7
  8	void
  9	foo ()
  10	{
  (gdb) break foo if (some_func ())
  Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
  (gdb) r
  Starting program: /tmp/bpcond

  Program received signal SIGSEGV, Segmentation fault.
  0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  Error in testing breakpoint condition:
  The program being debugged was signaled while in a function called from GDB.
  GDB remains in the frame where the signal was received.
  To change this behavior use "set unwindonsignal on".
  Evaluation of the expression containing the function
  (some_func) will be abandoned.
  When the function is done executing, GDB will silently stop.

  Program received signal SIGSEGV, Segmentation fault.

  Breakpoint 1, 0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  (gdb)

Notice that, the final lines of output report the stop as being at
breakpoint #1, even though we are actually located within some_func.

I find this behaviour confusing, and propose that this should be
changed.  However, if I make that change then every reference to
breakpoint #1 will be lost from the error message.

So, in this commit, in preparation for the later commits, I propose to
change the 'Error in testing breakpoint condition:' line to this:

  Error in testing condition for breakpoint NUMBER:

where NUMBER will be filled in as appropriate.  Here's the first
example with the updated error:

  (gdb) break foo if (*(int *) 0) == 0
  Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
  (gdb) r
  Starting program: /tmp/bpcond
  Error in testing condition for breakpoint 1:
  Cannot access memory at address 0x0

  Breakpoint 1, foo () at bpcond.c:11
  11	  int a = 32;
  (gdb)

The breakpoint number does now appear twice in the output, but I don't
see that as a negative.

This commit just changes the one line of the error, and updates the
few tests that either included the old error in comments, or actually
checked for the error in the expected output.

As the only test that checked the line I modified is a Python test,
I've added a new test that doesn't rely on Python that checks the
error message in detail.

While working on the new test, I spotted that it would fail when run
with native-gdbserver and native-extended-gdbserver target boards.
This turns out to be due to a gdbserver bug.  To avoid cluttering this
commit I've added a work around to the new test script so that the
test passes for the remote boards, in the next few commits I will fix
gdbserver, and update the test script to remove the work around.
---
 gdb/breakpoint.c                              |   3 +-
 gdb/testsuite/gdb.base/bp-cond-failure.c      |  30 +++++
 gdb/testsuite/gdb.base/bp-cond-failure.exp    | 114 ++++++++++++++++++
 .../gdb.base/catch-signal-siginfo-cond.exp    |   2 +-
 gdb/testsuite/gdb.base/gnu-ifunc.exp          |   2 +-
 .../gdb.python/py-finish-breakpoint.exp       |   2 +-
 6 files changed, 149 insertions(+), 4 deletions(-)
 create mode 100644 gdb/testsuite/gdb.base/bp-cond-failure.c
 create mode 100644 gdb/testsuite/gdb.base/bp-cond-failure.exp

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 00cc2ab401c..eecaeefed3e 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -5542,7 +5542,8 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
 	  catch (const gdb_exception &ex)
 	    {
 	      exception_fprintf (gdb_stderr, ex,
-				 "Error in testing breakpoint condition:\n");
+				 "Error in testing condition for breakpoint %d:\n",
+				 b->number);
 	    }
 	}
       else
diff --git a/gdb/testsuite/gdb.base/bp-cond-failure.c b/gdb/testsuite/gdb.base/bp-cond-failure.c
new file mode 100644
index 00000000000..2a9974b47ce
--- /dev/null
+++ b/gdb/testsuite/gdb.base/bp-cond-failure.c
@@ -0,0 +1,30 @@
+/* Copyright 2022-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/>.  */
+
+int
+foo ()
+{
+  return 0;	/* Breakpoint here.  */
+}
+
+int
+main ()
+{
+  int res = foo ();
+
+  return res;
+}
diff --git a/gdb/testsuite/gdb.base/bp-cond-failure.exp b/gdb/testsuite/gdb.base/bp-cond-failure.exp
new file mode 100644
index 00000000000..9388b8cf582
--- /dev/null
+++ b/gdb/testsuite/gdb.base/bp-cond-failure.exp
@@ -0,0 +1,114 @@
+# Copyright 2022-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/>.
+
+# Check the format of the error message given when a breakpoint
+# condition fails.
+#
+# In this case the breakpoint condition does not make use of inferior
+# function calls, instead, the expression used for the breakpoint
+# condition will throw an error when evaluated.
+#
+# We check that the correct breakpoint number appears in the error
+# message, and that the error is reported at the correct source
+# location.
+
+standard_testfile
+
+if { [prepare_for_testing "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug}] == -1 } {
+    return
+}
+
+# Run to main so that we connect to the target if using 'target
+# remote'.  This means that the is_address_zero_readable, and the
+# 'show breakpoint condition-evaluation' checks below will be
+# performed with the remote connection in place.
+if { ![runto_main] } {
+    fail "run to main"
+    return -1
+}
+
+# This test relies on reading address zero triggering a SIGSEGV.
+if { [is_address_zero_readable] } {
+    return
+}
+
+# Where the breakpoint will be placed.
+set bp_line [gdb_get_line_number "Breakpoint here"]
+
+proc run_test { cond_eval } {
+    clean_restart ${::binfile}
+
+    if { ![runto_main] } {
+	fail "run to main"
+	return -1
+    }
+
+    if { $cond_eval ne "auto" } {
+	gdb_test_no_output "set breakpoint condition-evaluation ${cond_eval}"
+    }
+
+    # Setup the conditional breakpoint and record its number.
+    gdb_breakpoint "${::srcfile}:${::bp_line} if (*(int *) 0) == 0"
+    set bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*"]
+
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     "Error in testing condition for breakpoint ${bp_num}:" \
+	     "Cannot access memory at address 0x0" \
+	     "" \
+	     "Breakpoint ${bp_num}, foo \\(\\) at \[^\r\n\]+:${::bp_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Breakpoint here\[^\r\n\]+"]
+}
+
+# If we're using a remote target then conditions could be evaulated
+# locally on the host, or on the remote target.  Otherwise, conditions
+# are always evaluated locally.
+#
+# Using "auto" will select the target if the target supports condition
+# evaluation, otherwise, the local host will be used.
+#
+# So, we always include "auto", but then we look at the output of
+# 'show breakpoint condition-evaluation', if this tells us that "auto"
+# is using the target, then we specifically add "host" to the list of
+# modes to check.
+
+set cond_eval_modes { "auto" }
+
+gdb_test_multiple "show breakpoint condition-evaluation" "" {
+    -re -wrap "Breakpoint condition evaluation mode is auto \\(currently target\\)\\." {
+
+	## NOTE: Instead of testing with "auto" and "host" in this
+	## case we only test with "host".  This is because a GDB bug
+	## prevents the "auto" (a.k.a. target) mode from working.
+	##
+	## Don't worry, this will be fixed in a later commit, and this
+	## comment will be removed at that time.
+	##
+	## lappend cond_eval_modes "host"
+
+	set cond_eval_modes { "host" }
+	pass $gdb_test_name
+    }
+
+    -re -wrap "Breakpoint condition evaluation mode is auto \\(currently host\\)\\." {
+	pass $gdb_test_name
+    }
+}
+
+foreach_with_prefix cond_eval $cond_eval_modes {
+    run_test $cond_eval
+}
diff --git a/gdb/testsuite/gdb.base/catch-signal-siginfo-cond.exp b/gdb/testsuite/gdb.base/catch-signal-siginfo-cond.exp
index 182b2f25faa..f400fc03b28 100644
--- a/gdb/testsuite/gdb.base/catch-signal-siginfo-cond.exp
+++ b/gdb/testsuite/gdb.base/catch-signal-siginfo-cond.exp
@@ -18,7 +18,7 @@
 #
 # (gdb) continue
 # Continuing.
-# Error in testing breakpoint condition:
+# Error in testing condition for breakpoint NUM:
 # Selected thread is running.
 #
 # Catchpoint 3 (signal SIGUSR1), 0x0000003615e35877 in __GI_raise (sig=10) at raise.c:56
diff --git a/gdb/testsuite/gdb.base/gnu-ifunc.exp b/gdb/testsuite/gdb.base/gnu-ifunc.exp
index 0a435806409..22462bea233 100644
--- a/gdb/testsuite/gdb.base/gnu-ifunc.exp
+++ b/gdb/testsuite/gdb.base/gnu-ifunc.exp
@@ -281,7 +281,7 @@ proc misc_tests {resolver_attr resolver_debug final_debug} {
 
     # Also test a former patch regression:
     # Continuing.
-    # Error in testing breakpoint condition:
+    # Error in testing condition for breakpoint NUM:
     # Attempt to take address of value not located in memory.
     #
     # Breakpoint 2, main () at ./gdb.base/gnu-ifunc.c:33
diff --git a/gdb/testsuite/gdb.python/py-finish-breakpoint.exp b/gdb/testsuite/gdb.python/py-finish-breakpoint.exp
index b6bd7a63c8f..e5a46874afd 100644
--- a/gdb/testsuite/gdb.python/py-finish-breakpoint.exp
+++ b/gdb/testsuite/gdb.python/py-finish-breakpoint.exp
@@ -188,7 +188,7 @@ with_test_prefix "finish in normal frame" {
     gdb_test "python TestBreakpoint()" "TestBreakpoint init" "set BP in condition"
 
     gdb_test "continue" \
-	"test don't stop: 1.*test don't stop: 2.*test stop.*Error in testing breakpoint condition.*The program being debugged stopped while in a function called from GDB.*" \
+	"test don't stop: 1.*test don't stop: 2.*test stop.*Error in testing condition for breakpoint ${::decimal}.*The program being debugged stopped while in a function called from GDB.*" \
 	"stop in condition function"
 
     gdb_test "continue" "Continuing.*" "finish condition evaluation"
-- 
2.25.4


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

* [PATCHv3 04/13] gdbserver: allows agent_mem_read to return an error code
  2023-01-31 17:27   ` [PATCHv3 " Andrew Burgess
                       ` (2 preceding siblings ...)
  2023-01-31 17:27     ` [PATCHv3 03/13] gdb: include breakpoint number in testing condition error message Andrew Burgess
@ 2023-01-31 17:27     ` Andrew Burgess
  2023-01-31 17:27     ` [PATCHv3 05/13] gdbserver: allow agent expressions to fail with invalid memory access Andrew Burgess
                       ` (9 subsequent siblings)
  13 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-01-31 17:27 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Currently the gdbserver function agent_mem_read ignores any errors
from calling read_inferior_memory.  This means that if there is an
attempt to access invalid memory then this will appear to succeed.

In this patch I update agent_mem_read so that if read_inferior_memory
fails, agent_mem_read will return an error code.

However, none of the callers of agent_mem_read actually check the
return value, so this commit will have no effect on anything.  In the
next commit I will update the users of agent_mem_read to check for the
error code.

I've also updated the header comments on agent_mem_read to better
reflect what the function does, and its possible return values.
---
 gdbserver/tracepoint.cc | 11 ++++-------
 gdbserver/tracepoint.h  |  9 +++++++--
 2 files changed, 11 insertions(+), 9 deletions(-)

diff --git a/gdbserver/tracepoint.cc b/gdbserver/tracepoint.cc
index 37a9a8c5b7c..60918fc0678 100644
--- a/gdbserver/tracepoint.cc
+++ b/gdbserver/tracepoint.cc
@@ -4914,8 +4914,7 @@ condition_true_at_tracepoint (struct tracepoint_hit_ctx *ctx,
   return (value ? 1 : 0);
 }
 
-/* Do memory copies for bytecodes.  */
-/* Do the recording of memory blocks for actions and bytecodes.  */
+/* See tracepoint.h.  */
 
 int
 agent_mem_read (struct eval_agent_expr_context *ctx,
@@ -4927,10 +4926,7 @@ agent_mem_read (struct eval_agent_expr_context *ctx,
 
   /* If a 'to' buffer is specified, use it.  */
   if (to != NULL)
-    {
-      read_inferior_memory (from, to, len);
-      return 0;
-    }
+    return read_inferior_memory (from, to, len);
 
   /* Otherwise, create a new memory block in the trace buffer.  */
   while (remaining > 0)
@@ -4951,7 +4947,8 @@ agent_mem_read (struct eval_agent_expr_context *ctx,
       memcpy (mspace, &blocklen, sizeof (blocklen));
       mspace += sizeof (blocklen);
       /* Record the memory block proper.  */
-      read_inferior_memory (from, mspace, blocklen);
+      if (read_inferior_memory (from, mspace, blocklen) != 0)
+	return 1;
       trace_debug ("%d bytes recorded", blocklen);
       remaining -= blocklen;
       from += blocklen;
diff --git a/gdbserver/tracepoint.h b/gdbserver/tracepoint.h
index a30f540d130..e424dc9dfb8 100644
--- a/gdbserver/tracepoint.h
+++ b/gdbserver/tracepoint.h
@@ -161,8 +161,13 @@ void gdb_agent_about_to_close (int pid);
 struct traceframe;
 struct eval_agent_expr_context;
 
-/* Do memory copies for bytecodes.  */
-/* Do the recording of memory blocks for actions and bytecodes.  */
+/* When TO is not NULL, do memory copies for bytecodes, read LEN bytes
+   starting at address FROM, and place the result in the buffer TO.
+   Return 0 on success, otherwise a non-zero error code.
+
+   When TO is NULL, do the recording of memory blocks for actions and
+   bytecodes into a new traceframe block.  Return 0 on success, otherwise,
+   return 1 if there is an error.  */
 
 int agent_mem_read (struct eval_agent_expr_context *ctx,
 		    unsigned char *to, CORE_ADDR from,
-- 
2.25.4


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

* [PATCHv3 05/13] gdbserver: allow agent expressions to fail with invalid memory access
  2023-01-31 17:27   ` [PATCHv3 " Andrew Burgess
                       ` (3 preceding siblings ...)
  2023-01-31 17:27     ` [PATCHv3 04/13] gdbserver: allows agent_mem_read to return an error code Andrew Burgess
@ 2023-01-31 17:27     ` Andrew Burgess
  2023-02-16 10:29       ` Aktemur, Tankut Baris
  2023-01-31 17:27     ` [PATCHv3 06/13] gdb: avoid repeated signal reporting during failed conditional breakpoint Andrew Burgess
                       ` (8 subsequent siblings)
  13 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2023-01-31 17:27 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

This commit extends gdbserver to take account of a failed memory
access from agent_mem_read, and to return a new eval_result_type
expr_eval_invalid_memory_access.

I have only updated the agent_mem_read calls related directly to
reading memory, I have not updated any of the calls related to
tracepoint data collection.  This is just because I'm not familiar
with that area of gdb/gdbserver, and I don't want to break anything,
so leaving the existing behaviour as it is seems like the safest
approach.

I've then updated gdb.base/bp-cond-failure.exp to test evaluating the
breakpoints on the target, and have also extended the test so that it
checks for different sizes of memory access.
---
 gdb/testsuite/gdb.base/bp-cond-failure.exp | 21 +++++++--------------
 gdbserver/ax.cc                            | 12 ++++++++----
 gdbserver/ax.h                             |  3 ++-
 3 files changed, 17 insertions(+), 19 deletions(-)

diff --git a/gdb/testsuite/gdb.base/bp-cond-failure.exp b/gdb/testsuite/gdb.base/bp-cond-failure.exp
index 9388b8cf582..d67c68c46a1 100644
--- a/gdb/testsuite/gdb.base/bp-cond-failure.exp
+++ b/gdb/testsuite/gdb.base/bp-cond-failure.exp
@@ -48,7 +48,7 @@ if { [is_address_zero_readable] } {
 # Where the breakpoint will be placed.
 set bp_line [gdb_get_line_number "Breakpoint here"]
 
-proc run_test { cond_eval } {
+proc run_test { cond_eval access_type } {
     clean_restart ${::binfile}
 
     if { ![runto_main] } {
@@ -61,7 +61,7 @@ proc run_test { cond_eval } {
     }
 
     # Setup the conditional breakpoint and record its number.
-    gdb_breakpoint "${::srcfile}:${::bp_line} if (*(int *) 0) == 0"
+    gdb_breakpoint "${::srcfile}:${::bp_line} if (*(${access_type} *) 0) == 0"
     set bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*"]
 
     gdb_test "continue" \
@@ -90,16 +90,7 @@ set cond_eval_modes { "auto" }
 
 gdb_test_multiple "show breakpoint condition-evaluation" "" {
     -re -wrap "Breakpoint condition evaluation mode is auto \\(currently target\\)\\." {
-
-	## NOTE: Instead of testing with "auto" and "host" in this
-	## case we only test with "host".  This is because a GDB bug
-	## prevents the "auto" (a.k.a. target) mode from working.
-	##
-	## Don't worry, this will be fixed in a later commit, and this
-	## comment will be removed at that time.
-	##
-	## lappend cond_eval_modes "host"
-
+	lappend cond_eval_modes "host"
 	set cond_eval_modes { "host" }
 	pass $gdb_test_name
     }
@@ -109,6 +100,8 @@ gdb_test_multiple "show breakpoint condition-evaluation" "" {
     }
 }
 
-foreach_with_prefix cond_eval $cond_eval_modes {
-    run_test $cond_eval
+foreach_with_prefix access_type { "char" "short" "int" "long long" } {
+    foreach_with_prefix cond_eval $cond_eval_modes {
+	run_test $cond_eval $access_type
+    }
 }
diff --git a/gdbserver/ax.cc b/gdbserver/ax.cc
index 38ebfbbd750..fba5b4ad0fc 100644
--- a/gdbserver/ax.cc
+++ b/gdbserver/ax.cc
@@ -1112,22 +1112,26 @@ gdb_eval_agent_expr (struct eval_agent_expr_context *ctx,
 	  break;
 
 	case gdb_agent_op_ref8:
-	  agent_mem_read (ctx, cnv.u8.bytes, (CORE_ADDR) top, 1);
+	  if (agent_mem_read (ctx, cnv.u8.bytes, (CORE_ADDR) top, 1) != 0)
+	    return expr_eval_invalid_memory_access;
 	  top = cnv.u8.val;
 	  break;
 
 	case gdb_agent_op_ref16:
-	  agent_mem_read (ctx, cnv.u16.bytes, (CORE_ADDR) top, 2);
+	  if (agent_mem_read (ctx, cnv.u16.bytes, (CORE_ADDR) top, 2) != 0)
+	    return expr_eval_invalid_memory_access;
 	  top = cnv.u16.val;
 	  break;
 
 	case gdb_agent_op_ref32:
-	  agent_mem_read (ctx, cnv.u32.bytes, (CORE_ADDR) top, 4);
+	  if (agent_mem_read (ctx, cnv.u32.bytes, (CORE_ADDR) top, 4) != 0)
+	    return expr_eval_invalid_memory_access;
 	  top = cnv.u32.val;
 	  break;
 
 	case gdb_agent_op_ref64:
-	  agent_mem_read (ctx, cnv.u64.bytes, (CORE_ADDR) top, 8);
+	  if (agent_mem_read (ctx, cnv.u64.bytes, (CORE_ADDR) top, 8) != 0)
+	    return expr_eval_invalid_memory_access;
 	  top = cnv.u64.val;
 	  break;
 
diff --git a/gdbserver/ax.h b/gdbserver/ax.h
index 8e64a7a593e..c98e36a83c6 100644
--- a/gdbserver/ax.h
+++ b/gdbserver/ax.h
@@ -41,7 +41,8 @@ enum eval_result_type
     expr_eval_unhandled_opcode,
     expr_eval_unrecognized_opcode,
     expr_eval_divide_by_zero,
-    expr_eval_invalid_goto
+    expr_eval_invalid_goto,
+    expr_eval_invalid_memory_access
   };
 
 struct agent_expr
-- 
2.25.4


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

* [PATCHv3 06/13] gdb: avoid repeated signal reporting during failed conditional breakpoint
  2023-01-31 17:27   ` [PATCHv3 " Andrew Burgess
                       ` (4 preceding siblings ...)
  2023-01-31 17:27     ` [PATCHv3 05/13] gdbserver: allow agent expressions to fail with invalid memory access Andrew Burgess
@ 2023-01-31 17:27     ` Andrew Burgess
  2023-01-31 17:27     ` [PATCHv3 07/13] gdb: don't always print breakpoint location after failed condition check Andrew Burgess
                       ` (7 subsequent siblings)
  13 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-01-31 17:27 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Consider the following case:

  (gdb) list some_func
  1	int
  2	some_func ()
  3	{
  4	  int *p = 0;
  5	  return *p;
  6	}
  7
  8	void
  9	foo ()
  10	{
  (gdb) break foo if (some_func ())
  Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
  (gdb) r
  Starting program: /tmp/bpcond

  Program received signal SIGSEGV, Segmentation fault.
  0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  Error in testing breakpoint condition:
  The program being debugged was signaled while in a function called from GDB.
  GDB remains in the frame where the signal was received.
  To change this behavior use "set unwindonsignal on".
  Evaluation of the expression containing the function
  (some_func) will be abandoned.
  When the function is done executing, GDB will silently stop.

  Program received signal SIGSEGV, Segmentation fault.

  Breakpoint 1, 0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  (gdb)

Notice that this line:

  Program received signal SIGSEGV, Segmentation fault.

Appears twice in the output.  The first time is followed by the
current location.  The second time is a little odd, why do we print
that?

Printing that line is controlled, in part, by a global variable,
stopped_by_random_signal.  This variable is reset to zero in
handle_signal_stop, and is set if/when GDB figures out that the
inferior stopped due to some random signal.

The problem is, in our case, GDB first stops at the breakpoint for
foo, and enters handle_signal_stop and the stopped_by_random_signal
global is reset to 0.

Later within handle_signal_stop GDB calls bpstat_stop_status, it is
within this function (via bpstat_check_breakpoint_conditions) that the
breakpoint condition is checked, and, we end up calling the inferior
function (some_func in our example above).

In our case above the thread performing the inferior function call
segfaults in some_func.  GDB catches the SIGSEGV and handles the stop,
this causes us to reenter handle_signal_stop.  The global variable
stopped_by_random_signal is updated, this time it is set to true
because the thread stopped due to SIGSEGV.  As a result of this we
print the first instance of the line (as seen above in the example).

Finally we unwind GDB's call stack, the inferior function call is
complete, and we return to the original handle_signal_stop.  However,
the stopped_by_random_signal global is still carrying the value as
computed for the inferior function call's stop, which is why we now
print a second instance of the line, as seen in the example.

To prevent this, I propose adding a scoped_restore before we start an
inferior function call.  This will save and restore the global
stopped_by_random_signal value.

With this done, the output from our example is now this:

 (gdb) list some_func
  1	int
  2	some_func ()
  3	{
  4	  int *p = 0;
  5	  return *p;
  6	}
  7
  8	void
  9	foo ()
  10	{
  (gdb) break foo if (some_func ())
  Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
  (gdb) r
  Starting program: /tmp/bpcond

  Program received signal SIGSEGV, Segmentation fault.
  0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  Error in testing condition for breakpoint 1:
  The program being debugged stopped while in a function called from GDB.
  Evaluation of the expression containing the function
  (some_func) will be abandoned.
  When the function is done executing, GDB will silently stop.

  Breakpoint 1, 0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  (gdb)

We now only see the 'Program received signal SIGSEGV, ...' line once,
which I think makes more sense.

Finally, I'm aware that the last few lines, that report the stop as
being at 'Breakpoint 1', when this is not where the thread is actually
located anymore, is not great.  I'll address that in the next commit.
---
 gdb/infcall.c                              |   9 +
 gdb/testsuite/gdb.base/infcall-failure.c   |  48 ++++++
 gdb/testsuite/gdb.base/infcall-failure.exp | 185 +++++++++++++++++++++
 3 files changed, 242 insertions(+)
 create mode 100644 gdb/testsuite/gdb.base/infcall-failure.c
 create mode 100644 gdb/testsuite/gdb.base/infcall-failure.exp

diff --git a/gdb/infcall.c b/gdb/infcall.c
index 4c2a4e4f400..8ebc3453072 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -1293,6 +1293,15 @@ call_function_by_hand_dummy (struct value *function,
   /* Register a clean-up for unwind_on_terminating_exception_breakpoint.  */
   SCOPE_EXIT { delete_std_terminate_breakpoint (); };
 
+  /* The stopped_by_random_signal variable is global.  If we are here
+     as part of a breakpoint condition check then the global will have
+     already been setup as part of the original breakpoint stop.  By
+     making the inferior call the global will be changed when GDB
+     handles the stop after the inferior call.  Avoid confusion by
+     restoring the current value after the inferior call.  */
+  scoped_restore restore_stopped_by_random_signal
+    = make_scoped_restore (&stopped_by_random_signal, 0);
+
   /* - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP -
      If you're looking to implement asynchronous dummy-frames, then
      just below is the place to chop this function in two..  */
diff --git a/gdb/testsuite/gdb.base/infcall-failure.c b/gdb/testsuite/gdb.base/infcall-failure.c
new file mode 100644
index 00000000000..fae012b2cda
--- /dev/null
+++ b/gdb/testsuite/gdb.base/infcall-failure.c
@@ -0,0 +1,48 @@
+/* Copyright 2022-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/>.  */
+
+/* A function that segfaults (assuming that reads of address zero are
+   prohibited), this is used from within a breakpoint condition.  */
+int
+func_segfault ()
+{
+  volatile int *p = 0;
+  return *p;	/* Segfault here.  */
+}
+
+/* A function in which we will place a breakpoint.  This function is itself
+   then used from within a breakpoint condition.  */
+int
+func_bp ()
+{
+  int res = 0;	/* Second breakpoint.  */
+  return res;
+}
+
+int
+foo ()
+{
+  return 0;	/* First breakpoint.  */
+}
+
+int
+main ()
+{
+  int res = foo ();
+
+  return res;
+}
diff --git a/gdb/testsuite/gdb.base/infcall-failure.exp b/gdb/testsuite/gdb.base/infcall-failure.exp
new file mode 100644
index 00000000000..214a64f8de3
--- /dev/null
+++ b/gdb/testsuite/gdb.base/infcall-failure.exp
@@ -0,0 +1,185 @@
+# Copyright 2022-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/>.
+
+# Some simple tests of inferior function calls from breakpoint
+# conditions, in a single-threaded inferior.
+#
+# Test what happens when the inferior function (from a breakpoint
+# condition) either hits a nested breakpoint, or segfaults.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug}] == -1 } {
+    return
+}
+
+set bp_1_line [gdb_get_line_number "First breakpoint"]
+set bp_2_line [gdb_get_line_number "Second breakpoint"]
+set segv_line [gdb_get_line_number "Segfault here"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto
+# main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if { ![runto_main] } {
+	return -1
+    }
+
+    return 0
+}
+
+# Start GDB according to ASYNC_P and NON_STOP_P, then setup a
+# conditional breakpoint.  The breakpoint condition includes an
+# inferior function call that will itself hit a breakpoint.  Check how
+# GDB reports this to the user.
+proc_with_prefix run_cond_hits_breakpoint_test { async_p non_stop_p } {
+    if { [start_gdb_and_runto_main $async_p $non_stop_p] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint and record its number.
+    gdb_breakpoint "${::srcfile}:${::bp_1_line} if (func_bp ())"
+    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		     "get number of first breakpoint"]
+
+    # Setup a breakpoint inside func_bp.
+    gdb_breakpoint "${::srcfile}:${::bp_2_line}"
+    set bp_2_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		     "get number of second breakpoint"]
+
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     "" \
+	     "Breakpoint ${bp_2_num}, func_bp \\(\\) at \[^\r\n\]+:${::bp_2_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Second breakpoint\[^\r\n\]+" \
+	     "Error in testing condition for breakpoint ${bp_1_num}:" \
+	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(func_bp\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\." \
+	     "" \
+	     "Breakpoint ${bp_1_num}, \[^\r\n\]+" \
+	     "${::decimal}\\s+\[^\r\n\]+Second breakpoint\[^\r\n\]+"]
+}
+
+# Start GDB according to ASYNC_P and NON_STOP_P, then call an inferior
+# function.  The inferior function being called will itself have a
+# breakpoint within it.  Check how GDB reports this to the user.
+proc_with_prefix run_call_hits_breakpoint_test { async_p non_stop_p } {
+    if { [start_gdb_and_runto_main $async_p $non_stop_p] == -1 } {
+	return
+    }
+
+    # Setup a breakpoint inside func_bp.
+    gdb_breakpoint "${::srcfile}:${::bp_2_line}"
+    set bp_2_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of second breakpoint"]
+
+
+    gdb_test "call func_bp ()" \
+	[multi_line \
+	     "" \
+	     "Breakpoint ${bp_2_num}, func_bp \\(\\) at \[^\r\n\]+:${::bp_2_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Second breakpoint\[^\r\n\]+" \
+	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(func_bp\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+}
+
+# Start GDB according to ASYNC_P and NON_STOP_P, then setup a
+# conditional breakpoint.  The breakpoint condition includes an
+# inferior function call that segfaults.  Check how GDB reports this
+# to the user.
+proc_with_prefix run_cond_hits_segfault_test { async_p non_stop_p } {
+    if { [start_gdb_and_runto_main $async_p $non_stop_p] == -1 } {
+	return
+    }
+
+    # This test relies on the inferior segfaulting when trying to
+    # access address zero.
+    if { [is_address_zero_readable] } {
+	unsupported "address zero is readable"
+	return
+    }
+
+    # Setup the conditional breakpoint and record its number.
+    gdb_breakpoint "${::srcfile}:${::bp_1_line} if (func_segfault ())"
+    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		     "get number of first breakpoint"]
+
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     "" \
+	     "Program received signal SIGSEGV, Segmentation fault\\." \
+	     "${::hex} in func_segfault \\(\\) at \[^\r\n\]+:${::segv_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
+	     "Error in testing condition for breakpoint ${bp_1_num}:" \
+	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(func_segfault\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\." \
+	     "" \
+	     "Breakpoint ${bp_1_num}, \[^\r\n\]+" \
+	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"]
+}
+
+# Start GDB according to ASYNC_P and NON_STOP_P, then call an inferior
+# function.  The inferior function will segfault.  Check how GDB
+# reports this to the user.
+proc_with_prefix run_call_hits_segfault_test { async_p non_stop_p } {
+    if { [start_gdb_and_runto_main $async_p $non_stop_p] == -1 } {
+	return
+    }
+
+    # This test relies on the inferior segfaulting when trying to
+    # access address zero.
+    if { [is_address_zero_readable] } {
+	unsupported "address zero is readable"
+	return
+    }
+
+    gdb_test "call func_segfault ()" \
+	[multi_line \
+	     "" \
+	     "Program received signal SIGSEGV, Segmentation fault\\." \
+	     "${::hex} in func_segfault \\(\\) at \[^\r\n\]+:${::segv_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
+	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(func_segfault\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	run_cond_hits_breakpoint_test $target_async $target_non_stop
+	run_call_hits_breakpoint_test $target_async $target_non_stop
+
+	run_cond_hits_segfault_test $target_async $target_non_stop
+	run_call_hits_segfault_test $target_async $target_non_stop
+    }
+}
-- 
2.25.4


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

* [PATCHv3 07/13] gdb: don't always print breakpoint location after failed condition check
  2023-01-31 17:27   ` [PATCHv3 " Andrew Burgess
                       ` (5 preceding siblings ...)
  2023-01-31 17:27     ` [PATCHv3 06/13] gdb: avoid repeated signal reporting during failed conditional breakpoint Andrew Burgess
@ 2023-01-31 17:27     ` Andrew Burgess
  2023-01-31 17:27     ` [PATCHv3 08/13] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
                       ` (6 subsequent siblings)
  13 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-01-31 17:27 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Consider the following session:

  (gdb) list some_func
  1	int
  2	some_func ()
  3	{
  4	  int *p = 0;
  5	  return *p;
  6	}
  7
  8	void
  9	foo ()
  10	{
  (gdb) break foo if (some_func ())
  Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
  (gdb) r
  Starting program: /tmp/bpcond

  Program received signal SIGSEGV, Segmentation fault.
  0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  Error in testing condition for breakpoint 1:
  The program being debugged stopped while in a function called from GDB.
  Evaluation of the expression containing the function
  (some_func) will be abandoned.
  When the function is done executing, GDB will silently stop.

  Breakpoint 1, 0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  (gdb)

What happens here is the breakpoint condition includes a call to an
inferior function, and the inferior function segfaults.  We can see
that GDB reports the segfault, and then gives an error message that
indicates that an inferior function call was interrupted.

After this GDB appears to report that it is stopped at Breakpoint 1,
inside some_func.

I find this second stop report a little confusing.  While it is true
that GDB stopped as a result of hitting breakpoint 1, I think the
message GDB currently prints might give the impression that GDB is
actually stopped at a location of breakpoint 1, which is not the case.

Also, I find the second stop message draws attention away from
the "Program received signal SIGSEGV, Segmentation fault" stop
message, and this second stop might be thought of as replacing in
someway the earlier message.

In short, I think things would be clearer if the second stop message
were not reported at all, so the output should, I think, look like
this:

  (gdb) list some_func
  1	int
  2	some_func ()
  3	{
  4	  int *p = 0;
  5	  return *p;
  6	}
  7
  8	void
  9	foo ()
  10	{
  (gdb) break foo if (some_func ())
  Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
  (gdb) r
  Starting program: /tmp/bpcond

  Program received signal SIGSEGV, Segmentation fault.
  0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  Error in testing condition for breakpoint 1:
  The program being debugged stopped while in a function called from GDB.
  Evaluation of the expression containing the function
  (some_func) will be abandoned.
  When the function is done executing, GDB will silently stop.
  (gdb)

The user can still find the number of the breakpoint that triggered
the initial stop in this line:

  Error in testing condition for breakpoint 1:

But there's now only one stop reason reported, the SIGSEGV, which I
think is much clearer.

To achieve this change I set the bpstat::print field when:

  (a) a breakpoint condition evaluation failed, and

  (b) the $pc of the thread changed during condition evaluation.

I've updated the existing tests that checked the error message printed
when a breakpoint condition evaluation failed.
---
 gdb/breakpoint.c                           | 12 ++++++++++++
 gdb/testsuite/gdb.base/infcall-failure.exp | 18 ++++++++----------
 2 files changed, 20 insertions(+), 10 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index eecaeefed3e..c4fec7e8e55 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -5533,6 +5533,7 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
 	  else
 	    within_current_scope = false;
 	}
+      CORE_ADDR pc_before_check = get_frame_pc (get_selected_frame (nullptr));
       if (within_current_scope)
 	{
 	  try
@@ -5544,6 +5545,17 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
 	      exception_fprintf (gdb_stderr, ex,
 				 "Error in testing condition for breakpoint %d:\n",
 				 b->number);
+
+	      /* If the pc value changed as a result of evaluating the
+		 condition then we probably stopped within an inferior
+		 function call due to some unexpected stop, e.g. the thread
+		 hit another breakpoint, or the thread received an
+		 unexpected signal.  In this case we don't want to also
+		 print the information about this breakpoint.  */
+	      CORE_ADDR pc_after_check
+		= get_frame_pc (get_selected_frame (nullptr));
+	      if (pc_before_check != pc_after_check)
+		bs->print = 0;
 	    }
 	}
       else
diff --git a/gdb/testsuite/gdb.base/infcall-failure.exp b/gdb/testsuite/gdb.base/infcall-failure.exp
index 214a64f8de3..5ad179a089d 100644
--- a/gdb/testsuite/gdb.base/infcall-failure.exp
+++ b/gdb/testsuite/gdb.base/infcall-failure.exp
@@ -78,10 +78,7 @@ proc_with_prefix run_cond_hits_breakpoint_test { async_p non_stop_p } {
 	     "The program being debugged stopped while in a function called from GDB\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(func_bp\\) will be abandoned\\." \
-	     "When the function is done executing, GDB will silently stop\\." \
-	     "" \
-	     "Breakpoint ${bp_1_num}, \[^\r\n\]+" \
-	     "${::decimal}\\s+\[^\r\n\]+Second breakpoint\[^\r\n\]+"]
+	     "When the function is done executing, GDB will silently stop\\."]
 }
 
 # Start GDB according to ASYNC_P and NON_STOP_P, then call an inferior
@@ -138,13 +135,12 @@ proc_with_prefix run_cond_hits_segfault_test { async_p non_stop_p } {
 	     "${::hex} in func_segfault \\(\\) at \[^\r\n\]+:${::segv_line}" \
 	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
 	     "Error in testing condition for breakpoint ${bp_1_num}:" \
-	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "The program being debugged was signaled while in a function called from GDB\\." \
+	     "GDB remains in the frame where the signal was received\\." \
+	     "To change this behavior use \"set unwindonsignal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(func_segfault\\) will be abandoned\\." \
-	     "When the function is done executing, GDB will silently stop\\." \
-	     "" \
-	     "Breakpoint ${bp_1_num}, \[^\r\n\]+" \
-	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"]
+	     "When the function is done executing, GDB will silently stop\\."]
 }
 
 # Start GDB according to ASYNC_P and NON_STOP_P, then call an inferior
@@ -168,7 +164,9 @@ proc_with_prefix run_call_hits_segfault_test { async_p non_stop_p } {
 	     "Program received signal SIGSEGV, Segmentation fault\\." \
 	     "${::hex} in func_segfault \\(\\) at \[^\r\n\]+:${::segv_line}" \
 	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
-	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "The program being debugged was signaled while in a function called from GDB\\." \
+	     "GDB remains in the frame where the signal was received\\." \
+	     "To change this behavior use \"set unwindonsignal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(func_segfault\\) will be abandoned\\." \
 	     "When the function is done executing, GDB will silently stop\\."]
-- 
2.25.4


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

* [PATCHv3 08/13] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait"
  2023-01-31 17:27   ` [PATCHv3 " Andrew Burgess
                       ` (6 preceding siblings ...)
  2023-01-31 17:27     ` [PATCHv3 07/13] gdb: don't always print breakpoint location after failed condition check Andrew Burgess
@ 2023-01-31 17:27     ` Andrew Burgess
  2023-01-31 17:27     ` [PATCHv3 09/13] gdb: fix b/p conditions with infcalls in multi-threaded inferiors Andrew Burgess
                       ` (5 subsequent siblings)
  13 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-01-31 17:27 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

This reverts commit ac0d67ed1dcf470bad6a3bc4800c2ddc9bedecca.

There was nothing wrong with the commit which I'm reverting here, but
it removed some functionality that will be needed for a later commit;
that is, the ability for GDB to ask for events from a specific ptid_t
via the do_target_wait function.

In a follow up commit, this functionality will be used to implement
inferior function calls in multi-threaded inferiors.

This is not a straight revert of the above commit.  Reverting the
above commit replaces a 'nullptr' with 'NULL', I've gone in and
changed that, preserving the 'nullptr'.
---
 gdb/infrun.c | 12 +++++++-----
 1 file changed, 7 insertions(+), 5 deletions(-)

diff --git a/gdb/infrun.c b/gdb/infrun.c
index edfb5ab0a91..f97349f47d2 100644
--- a/gdb/infrun.c
+++ b/gdb/infrun.c
@@ -3741,7 +3741,8 @@ do_target_wait_1 (inferior *inf, ptid_t ptid,
    more events.  Polls for events from all inferiors/targets.  */
 
 static bool
-do_target_wait (execution_control_state *ecs, target_wait_flags options)
+do_target_wait (ptid_t wait_ptid, execution_control_state *ecs,
+		target_wait_flags options)
 {
   int num_inferiors = 0;
   int random_selector;
@@ -3751,9 +3752,10 @@ do_target_wait (execution_control_state *ecs, target_wait_flags options)
      polling the rest of the inferior list starting from that one in a
      circular fashion until the whole list is polled once.  */
 
-  auto inferior_matches = [] (inferior *inf)
+  auto inferior_matches = [&wait_ptid] (inferior *inf)
     {
-      return inf->process_target () != nullptr;
+      return (inf->process_target () != nullptr
+	      && ptid_t (inf->pid).matches (wait_ptid));
     };
 
   /* First see how many matching inferiors we have.  */
@@ -3792,7 +3794,7 @@ do_target_wait (execution_control_state *ecs, target_wait_flags options)
 
   auto do_wait = [&] (inferior *inf)
   {
-    ecs->ptid = do_target_wait_1 (inf, minus_one_ptid, &ecs->ws, options);
+    ecs->ptid = do_target_wait_1 (inf, wait_ptid, &ecs->ws, options);
     ecs->target = inf->process_target ();
     return (ecs->ws.kind () != TARGET_WAITKIND_IGNORE);
   };
@@ -4169,7 +4171,7 @@ fetch_inferior_event ()
        the event.  */
     scoped_disable_commit_resumed disable_commit_resumed ("handling event");
 
-    if (!do_target_wait (&ecs, TARGET_WNOHANG))
+    if (!do_target_wait (minus_one_ptid, &ecs, TARGET_WNOHANG))
       {
 	infrun_debug_printf ("do_target_wait returned no event");
 	disable_commit_resumed.reset_and_commit ();
-- 
2.25.4


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

* [PATCHv3 09/13] gdb: fix b/p conditions with infcalls in multi-threaded inferiors
  2023-01-31 17:27   ` [PATCHv3 " Andrew Burgess
                       ` (7 preceding siblings ...)
  2023-01-31 17:27     ` [PATCHv3 08/13] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
@ 2023-01-31 17:27     ` Andrew Burgess
  2023-02-16 10:47       ` Aktemur, Tankut Baris
  2023-01-31 17:27     ` [PATCHv3 10/13] gdb: add timeouts for inferior function calls Andrew Burgess
                       ` (4 subsequent siblings)
  13 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2023-01-31 17:27 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Natalia Saiapova, Tankut Baris Aktemur

This commit fixes bug PR 28942, that is, creating a conditional
breakpoint in a multi-threaded inferior, where the breakpoint
condition includes an inferior function call.

Currently, when a user tries to create such a breakpoint, then GDB
will fail with:

  (gdb) break infcall-from-bp-cond-single.c:61 if (return_true ())
  Breakpoint 2 at 0x4011fa: file /tmp/build/gdb/testsuite/../../../src/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c, line 61.
  (gdb) continue
  Continuing.
  [New Thread 0x7ffff7c5d700 (LWP 2460150)]
  [New Thread 0x7ffff745c700 (LWP 2460151)]
  [New Thread 0x7ffff6c5b700 (LWP 2460152)]
  [New Thread 0x7ffff645a700 (LWP 2460153)]
  [New Thread 0x7ffff5c59700 (LWP 2460154)]
  Error in testing breakpoint condition:
  Couldn't get registers: No such process.
  An error occurred while in a function called from GDB.
  Evaluation of the expression containing the function
  (return_true) will be abandoned.
  When the function is done executing, GDB will silently stop.
  Selected thread is running.
  (gdb)

Or, in some cases, like this:

  (gdb) break infcall-from-bp-cond-simple.c:56 if (is_matching_tid (arg, 1))
  Breakpoint 2 at 0x401194: file /tmp/build/gdb/testsuite/../../../src/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c, line 56.
  (gdb) continue
  Continuing.
  [New Thread 0x7ffff7c5d700 (LWP 2461106)]
  [New Thread 0x7ffff745c700 (LWP 2461107)]
  ../../src.release/gdb/nat/x86-linux-dregs.c:146: internal-error: x86_linux_update_debug_registers: Assertion `lwp_is_stopped (lwp)' failed.
  A problem internal to GDB has been detected,
  further debugging may prove unreliable.

The precise error depends on the exact thread state; so there's race
conditions depending on which threads have fully started, and which
have not.  But the underlying problem is always the same; when GDB
tries to execute the inferior function call from within the breakpoint
condition, GDB will, incorrectly, try to resume threads that are
already running - GDB doesn't realise that some threads might already
be running.

The solution proposed in this patch requires an additional member
variable thread_info::in_cond_eval.  This flag is set to true (in
breakpoint.c) when GDB is evaluating a breakpoint condition.

In user_visible_resume_ptid (infrun.c), when the in_cond_eval flag is
true, then GDB will only try to resume the current thread, that is,
the thread for which the breakpoint condition is being evaluated.
This solves the problem of GDB trying to resume threads that are
already running.

The next problem is that inferior function calls are assumed to be
synchronous, that is, GDB doesn't expect to start an inferior function
call in thread #1, then receive a stop from thread #2 for some other,
unrelated reason.  To prevent GDB responding to an event from another
thread, we update fetch_inferior_event and do_target_wait in infrun.c,
so that, when an inferior function call (on behalf of a breakpoint
condition) is in progress, we only wait for events from the current
thread (the one evaluating the condition).

In do_target_wait I had to change the inferior_matches lambda
function, which is used to select which inferior to wait on.
Previously the logic was this:

   auto inferior_matches = [&wait_ptid] (inferior *inf)
     {
       return (inf->process_target () != nullptr
               && ptid_t (inf->pid).matches (wait_ptid));
     };

This compares the pid of the inferior against the complete ptid we
want to wait on.  Before this commit wait_ptid was only ever
minus_one_ptid (which is special, and means any process), and so every
inferior would match.

After this commit though wait_ptid might represent a specific thread
in a specific inferior.  If we compare the pid of the inferior to a
specific ptid then these will not match.  The fix is to compare
against the pid extracted from the wait_ptid, not against the complete
wait_ptid itself.

In fetch_inferior_event, after receiving the event, we only want to
stop all the other threads, and call inferior_event_handler with
INF_EXEC_COMPLETE, if we are not evaluating a conditional breakpoint.
If we are, then all the other threads should be left doing whatever
they were before.  The inferior_event_handler call will be performed
once the breakpoint condition has finished being evaluated, and GDB
decides to stop or not.

The final problem that needs solving relates to GDB's commit-resume
mechanism, which allows GDB to collect resume requests into a single
packet in order to reduce traffic to a remote target.

The problem is that the commit-resume mechanism will not send any
resume requests for an inferior if there are already events pending on
the GDB side.

Imagine an inferior with two threads.  Both threads hit a breakpoint,
maybe the same conditional breakpoint.  At this point there are two
pending events, one for each thread.

GDB selects one of the events and spots that this is a conditional
breakpoint, GDB evaluates the condition.

The condition includes an inferior function call, so GDB sets up for
the call and resumes the one thread, the resume request is added to
the commit-resume queue.

When the commit-resume queue is committed GDB sees that there is a
pending event from another thread, and so doesn't send any resume
requests to the actual target, GDB is assuming that when we wait we
will select the event from the other thread.

However, as this is an inferior function call for a condition
evaluation, we will not select the event from the other thread, we
only care about events from the thread that is evaluating the
condition - and the resume for this thread was never sent to the
target.

And so, GDB hangs, waiting for an event from a thread that was never
fully resumed.

To fix this issue I have added the concept of "forcing" the
commit-resume queue.  When enabling commit resume, if the force flag
is true, then any resumes will be committed to the target, even if
there are other threads with pending events.

A note on authorship: this patch was based on some work done by
Natalia Saiapova and Tankut Baris Aktemur from Intel[1].  I have made
some changes to their work in this version.

Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=28942

[1] https://sourceware.org/pipermail/gdb-patches/2020-October/172454.html

Co-authored-by: Natalia Saiapova <natalia.saiapova@intel.com>
Co-authored-by: Tankut Baris Aktemur <tankut.baris.aktemur@intel.com>
---
 gdb/breakpoint.c                              |   2 +
 gdb/gdbthread.h                               |   3 +
 gdb/infcall.c                                 |   6 +
 gdb/infrun.c                                  |  64 +++--
 gdb/infrun.h                                  |   3 +-
 .../infcall-from-bp-cond-other-thread-event.c | 135 ++++++++++
 ...nfcall-from-bp-cond-other-thread-event.exp | 175 +++++++++++++
 .../gdb.threads/infcall-from-bp-cond-simple.c |  89 +++++++
 .../infcall-from-bp-cond-simple.exp           | 236 ++++++++++++++++++
 .../gdb.threads/infcall-from-bp-cond-single.c | 139 +++++++++++
 .../infcall-from-bp-cond-single.exp           | 118 +++++++++
 11 files changed, 955 insertions(+), 15 deletions(-)
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index c4fec7e8e55..0cb4382ba5b 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -5538,6 +5538,8 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
 	{
 	  try
 	    {
+	      scoped_restore reset_in_cond_eval
+		= make_scoped_restore (&thread->control.in_cond_eval, true);
 	      condition_result = breakpoint_cond_eval (cond);
 	    }
 	  catch (const gdb_exception &ex)
diff --git a/gdb/gdbthread.h b/gdb/gdbthread.h
index c0f27a8a66e..736d5d50b5f 100644
--- a/gdb/gdbthread.h
+++ b/gdb/gdbthread.h
@@ -171,6 +171,9 @@ struct thread_control_state
      command.  This is used to decide whether "set scheduler-locking
      step" behaves like "on" or "off".  */
   int stepping_command = 0;
+
+  /* True if the thread is evaluating a BP condition.  */
+  bool in_cond_eval = false;
 };
 
 /* Inferior thread specific part of `struct infcall_suspend_state'.  */
diff --git a/gdb/infcall.c b/gdb/infcall.c
index 8ebc3453072..34838dea1bd 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -641,6 +641,12 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
 
       proceed (real_pc, GDB_SIGNAL_0);
 
+      /* Enable commit resume, but pass true for the force flag.  This
+	 ensures any thread we set running in proceed will actually be
+	 committed to the target, even if some other thread in the current
+	 target has a pending event.  */
+      scoped_enable_commit_resumed enable ("infcall", true);
+
       infrun_debug_show_threads ("non-exited threads after proceed for inferior-call",
 				 all_non_exited_threads ());
 
diff --git a/gdb/infrun.c b/gdb/infrun.c
index f97349f47d2..77a9a5bb7a8 100644
--- a/gdb/infrun.c
+++ b/gdb/infrun.c
@@ -2149,6 +2149,14 @@ user_visible_resume_ptid (int step)
 	 mode.  */
       resume_ptid = inferior_ptid;
     }
+  else if (inferior_ptid != null_ptid
+	   && inferior_thread ()->control.in_cond_eval)
+    {
+      /* The inferior thread is evaluating a BP condition.  Other threads
+	 might be stopped or running and we do not want to change their
+	 state, thus, resume only the current thread.  */
+      resume_ptid = inferior_ptid;
+    }
   else if (!sched_multi && target_supports_multi_process ())
     {
       /* Resume all threads of the current process (and none of other
@@ -2856,12 +2864,24 @@ schedlock_applies (struct thread_info *tp)
 					    execution_direction)));
 }
 
-/* Set process_stratum_target::COMMIT_RESUMED_STATE in all target
-   stacks that have threads executing and don't have threads with
-   pending events.  */
+/* When FORCE_P is false, set process_stratum_target::COMMIT_RESUMED_STATE
+   in all target stacks that have threads executing and don't have threads
+   with pending events.
+
+   When FORCE_P is true, set process_stratum_target::COMMIT_RESUMED_STATE
+   in all target stacks that have threads executing regardless of whether
+   there are pending events or not.
+
+    Passing FORCE_P as false makes sense when GDB is going to wait for
+    events from all threads and will therefore spot the pending events.
+    However, if GDB is only going to wait for events from select threads
+    (i.e. when performing an inferior call) then a pending event on some
+    other thread will not be spotted, and if we fail to commit the resume
+    state for the thread performing the inferior call, then the inferior
+    call will never complete (or even start).  */
 
 static void
-maybe_set_commit_resumed_all_targets ()
+maybe_set_commit_resumed_all_targets (bool force_p)
 {
   scoped_restore_current_thread restore_thread;
 
@@ -2890,7 +2910,7 @@ maybe_set_commit_resumed_all_targets ()
 	 status to report, handle it before requiring the target to
 	 commit its resumed threads: handling the status might lead to
 	 resuming more threads.  */
-      if (proc_target->has_resumed_with_pending_wait_status ())
+      if (!force_p && proc_target->has_resumed_with_pending_wait_status ())
 	{
 	  infrun_debug_printf ("not requesting commit-resumed for target %s, a"
 			       " thread has a pending waitstatus",
@@ -2900,7 +2920,7 @@ maybe_set_commit_resumed_all_targets ()
 
       switch_to_inferior_no_thread (inf);
 
-      if (target_has_pending_events ())
+      if (!force_p && target_has_pending_events ())
 	{
 	  infrun_debug_printf ("not requesting commit-resumed for target %s, "
 			       "target has pending events",
@@ -2993,7 +3013,7 @@ scoped_disable_commit_resumed::reset ()
     {
       /* This is the outermost instance, re-enable
          COMMIT_RESUMED_STATE on the targets where it's possible.  */
-      maybe_set_commit_resumed_all_targets ();
+      maybe_set_commit_resumed_all_targets (false);
     }
   else
     {
@@ -3026,7 +3046,7 @@ scoped_disable_commit_resumed::reset_and_commit ()
 /* See infrun.h.  */
 
 scoped_enable_commit_resumed::scoped_enable_commit_resumed
-  (const char *reason)
+  (const char *reason, bool force_p)
   : m_reason (reason),
     m_prev_enable_commit_resumed (enable_commit_resumed)
 {
@@ -3038,7 +3058,7 @@ scoped_enable_commit_resumed::scoped_enable_commit_resumed
 
       /* Re-enable COMMIT_RESUMED_STATE on the targets where it's
 	 possible.  */
-      maybe_set_commit_resumed_all_targets ();
+      maybe_set_commit_resumed_all_targets (force_p);
 
       maybe_call_commit_resumed_all_targets ();
     }
@@ -3752,10 +3772,11 @@ do_target_wait (ptid_t wait_ptid, execution_control_state *ecs,
      polling the rest of the inferior list starting from that one in a
      circular fashion until the whole list is polled once.  */
 
-  auto inferior_matches = [&wait_ptid] (inferior *inf)
+  ptid_t wait_ptid_pid {wait_ptid.pid ()};
+  auto inferior_matches = [&wait_ptid_pid] (inferior *inf)
     {
       return (inf->process_target () != nullptr
-	      && ptid_t (inf->pid).matches (wait_ptid));
+	      && ptid_t (inf->pid).matches (wait_ptid_pid));
     };
 
   /* First see how many matching inferiors we have.  */
@@ -4171,7 +4192,17 @@ fetch_inferior_event ()
        the event.  */
     scoped_disable_commit_resumed disable_commit_resumed ("handling event");
 
-    if (!do_target_wait (minus_one_ptid, &ecs, TARGET_WNOHANG))
+    /* Is the current thread performing an inferior function call as part
+       of a breakpoint condition evaluation?  */
+    bool in_cond_eval = (inferior_ptid != null_ptid
+			 && inferior_thread ()->control.in_cond_eval);
+
+    /* If the thread is in the middle of the condition evaluation, wait for
+       an event from the current thread.  Otherwise, wait for an event from
+       any thread.  */
+    ptid_t waiton_ptid = in_cond_eval ? inferior_ptid : minus_one_ptid;
+
+    if (!do_target_wait (waiton_ptid, &ecs, TARGET_WNOHANG))
       {
 	infrun_debug_printf ("do_target_wait returned no event");
 	disable_commit_resumed.reset_and_commit ();
@@ -4223,7 +4254,12 @@ fetch_inferior_event ()
 	    bool should_notify_stop = true;
 	    bool proceeded = false;
 
-	    stop_all_threads_if_all_stop_mode ();
+	    /* If the thread that stopped just completed an inferior
+	       function call as part of a condition evaluation, then we
+	       don't want to stop all the other threads.  */
+	    if (ecs.event_thread == nullptr
+		|| !ecs.event_thread->control.in_cond_eval)
+	      stop_all_threads_if_all_stop_mode ();
 
 	    clean_up_just_stopped_threads_fsms (&ecs);
 
@@ -4238,7 +4274,7 @@ fetch_inferior_event ()
 		  proceeded = normal_stop ();
 	      }
 
-	    if (!proceeded)
+	    if (!proceeded && !in_cond_eval)
 	      {
 		inferior_event_handler (INF_EXEC_COMPLETE);
 		cmd_done = 1;
diff --git a/gdb/infrun.h b/gdb/infrun.h
index 43fd1b44f5a..a78b5feb4a9 100644
--- a/gdb/infrun.h
+++ b/gdb/infrun.h
@@ -395,7 +395,8 @@ extern void maybe_call_commit_resumed_all_targets ();
 
 struct scoped_enable_commit_resumed
 {
-  explicit scoped_enable_commit_resumed (const char *reason);
+  explicit scoped_enable_commit_resumed (const char *reason,
+					 bool force_p = false);
   ~scoped_enable_commit_resumed ();
 
   DISABLE_COPY_AND_ASSIGN (scoped_enable_commit_resumed);
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
new file mode 100644
index 00000000000..e2a8ccb4ebe
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
@@ -0,0 +1,135 @@
+/* Copyright 2022-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 <pthread.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <sched.h>
+
+#define NUM_THREADS 2
+
+pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+
+/* Some global variables to poke, just for something to do.  */
+volatile int global_var_0 = 0;
+volatile int global_var_1 = 0;
+
+/* This flag is updated from GDB.  */
+volatile int raise_signal = 0;
+
+/* Implement the breakpoint condition function.  Release the other thread
+   and try to give the other thread a chance to run.  Then return ANSWER.  */
+int
+condition_core_func (int answer)
+{
+  /* This unlock should release the other thread.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  /* And this yield and sleep should (hopefully) give the other thread a
+     chance to run.  This isn't guaranteed of course, but once the other
+     thread does run it should hit a breakpoint, which GDB should
+     (temporarily) ignore, so there's no easy way for us to know the other
+     thread has done what it needs to, thus, yielding and sleeping is the
+     best we can do.  */
+  sched_yield ();
+  sleep (2);
+
+  return answer;
+}
+
+void
+stop_marker ()
+{
+  int a = 100;	/* Final breakpoint here.  */
+}
+
+/* A breakpoint condition function that always returns true.  */
+int
+condition_true_func ()
+{
+  return condition_core_func (1);
+}
+
+/* A breakpoint condition function that always returns false.  */
+int
+condition_false_func ()
+{
+  return condition_core_func (0);
+}
+
+void *
+worker_func (void *arg)
+{
+  volatile int *ptr = 0;
+  int tid = *((int *) arg);
+
+  switch (tid)
+    {
+    case 0:
+      global_var_0 = 11;	/* First thread breakpoint.  */
+      break;
+
+    case 1:
+      if (pthread_mutex_lock (&mutex) != 0)
+	abort ();
+      if (raise_signal)
+	global_var_1 = *ptr;	/* Signal here.  */
+      else
+	global_var_1 = 99;	/* Other thread breakpoint.  */
+      break;
+
+    default:
+      abort ();
+    }
+
+  return NULL;
+}
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+
+  /* Set an alarm, just in case the test deadlocks.  */
+  alarm (300);
+
+  /* We want the mutex to start locked.  */
+  if (pthread_mutex_lock (&mutex) != 0)
+    abort ();
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      void *retval;
+      pthread_join (threads[i], &retval);
+    }
+
+  /* Unlock once we're done, just for cleanliness.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
new file mode 100644
index 00000000000..fe9aeea97f7
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
@@ -0,0 +1,175 @@
+# Copyright 2022-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/>.
+
+# Test for conditional breakpoints where the breakpoint condition includes
+# an inferior function call.
+#
+# The tests in this script are testing what happens when an event arrives in
+# another thread while GDB is waiting for the inferior function call (in the
+# breakpoint condition) to finish.
+#
+# The expectation is that GDB will queue events for other threads and wait
+# for the inferior function call to complete, if the condition is true, then
+# the conditional breakpoint should be reported first.  The other thread
+# event should of course, not get lost, and should be reported as soon as
+# the user tries to continue the inferior.
+#
+# If the conditional breakpoint ends up not being taken (the condition is
+# false), then the other thread event should be reported immediately.
+#
+# This script tests what happens when the other thread event is (a) the
+# other thread hitting a breakpoint, and (b) the other thread taking a
+# signal (SIGSEGV in this case).
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] == -1 } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "First thread breakpoint"]
+set other_bp_line [gdb_get_line_number "Other thread breakpoint"]
+set final_bp_line [gdb_get_line_number "Final breakpoint here"]
+set signal_line [gdb_get_line_number "Signal here"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if { ![runto_main] } {
+	fail "run to main"
+	return -1
+    }
+
+    return 0
+}
+
+# Run a test of GDB's conditional breakpoints, where the conditions include
+# inferior function calls.  While the inferior function call is executing
+# another thread will hit a breakpoint (when OTHER_THREAD_SIGNAL is false),
+# or receive a signal (when OTHER_THREAD_SIGNAL is true).  GDB should report
+# the conditional breakpoint first (if the condition is true), and then
+# report the second thread event once the inferior is continued again.
+#
+# When STOP_AT_COND is true then the conditional breakpoint will have a
+# condition that evaluates to true (and the GDB will stop at the
+# breakpoint), otherwise, the condition will evaluate to false (and GDB will
+# not stop at the breakpoint).
+proc run_condition_test { stop_at_cond other_thread_signal \
+			      target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint.
+    if { $stop_at_cond } {
+	set cond_func "condition_true_func"
+    } else {
+	set cond_func "condition_false_func"
+    }
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (${cond_func} ())"
+    set cond_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			"get number for conditional breakpoint"]
+
+    if { $other_thread_signal } {
+	# Arrange for the other thread to raise a signal while GDB is
+	# evaluating the breakpoint condition.
+	gdb_test_no_output "set raise_signal = 1"
+    } else {
+	# And a breakpoint that will be hit by another thread only once the
+	# breakpoint condition starts to be evaluated.
+	gdb_breakpoint "${::srcfile}:${::other_bp_line}"
+	set other_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			      "get number for other breakpoint"]
+    }
+
+    # A final breakpoint once the test has completed.
+    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
+    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			  "get number for final breakpoint"]
+
+    if { $stop_at_cond } {
+	# Continue.  The first breakpoint we hit should be the conditional
+	# breakpoint.  The other thread will have hit its breakpoint, but
+	# that will have been deferred until the conditional breakpoint is
+	# reported.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${cond_bp_num}, worker_func \[^\r\n\]+:${::cond_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+First thread breakpoint\[^\r\n\]+"] \
+	    "hit the conditional breakpoint"
+    }
+
+    if { $other_thread_signal } {
+	# Now continue again, the other thread will now report that it
+	# received a signal.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" received signal SIGSEGV, Segmentation fault\\." \
+		 "\\\[Switching to Thread \[^\r\n\]+\\\]" \
+		 "${::hex} in worker_func \[^\r\n\]+:${::signal_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Signal here\[^\r\n\]+"] \
+	    "received signal in other thread"
+    } else {
+	# Now continue again, the other thread will now report its
+	# breakpoint.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${other_bp_num}, worker_func \[^\r\n\]+:${::other_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Other thread breakpoint\[^\r\n\]+"] \
+	    "hit the breakpoint in other thread"
+
+	# Run to the stop marker.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${final_bp_num}, stop_marker \[^\r\n\]+:${::final_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Final breakpoint here\[^\r\n\]+"] \
+	    "hit the final breakpoint"
+    }
+
+    gdb_exit
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	foreach_with_prefix other_thread_signal { true false } {
+	    foreach_with_prefix stop_at_cond { true false } {
+		run_condition_test $stop_at_cond $other_thread_signal \
+		    $target_async $target_non_stop
+	    }
+	}
+    }
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
new file mode 100644
index 00000000000..9d746d8be49
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
@@ -0,0 +1,89 @@
+/* Copyright 2022-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 <pthread.h>
+#include <unistd.h>
+
+#define NUM_THREADS 3
+
+int
+is_matching_tid (int *tid_ptr, int tid_value)
+{
+  return *tid_ptr == tid_value;
+}
+
+int
+return_true ()
+{
+  return 1;
+}
+
+int
+return_false ()
+{
+  return 0;
+}
+
+int
+function_that_segfaults ()
+{
+  int *p = 0;
+  *p = 1;	/* Segfault happens here.   */
+}
+
+int
+function_with_breakpoint ()
+{
+  return 1;	/* Nested breakpoint.  */
+}
+
+void *
+worker_func (void *arg)
+{
+  int a = 42;	/* Breakpoint here.  */
+}
+
+void
+stop_marker ()
+{
+  int b = 99;	/* Stop marker.  */
+}
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+
+  alarm (300);
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      void *retval;
+      pthread_join (threads[i], &retval);
+    }
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
new file mode 100644
index 00000000000..a101abbfe9b
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
@@ -0,0 +1,236 @@
+# Copyright 2022-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/>.
+
+# Some simple tests of inferior function calls from breakpoint
+# conditions, in multi-threaded inferiors.
+#
+# This test sets up a multi-threaded inferior, and places a breakpoint
+# at a location that many of the threads will reach.  We repeat the
+# test with different conditions, sometimes a single thread should
+# stop at the breakpoint, sometimes multiple threads should stop, and
+# sometime no threads should stop.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] == -1 } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "Breakpoint here"]
+set stop_bp_line [gdb_get_line_number "Stop marker"]
+set nested_bp_line [gdb_get_line_number "Nested breakpoint"]
+set segv_line [gdb_get_line_number "Segfault happens here"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if { ![runto_main] } {
+	fail "run to main"
+	return -1
+    }
+
+    return 0
+}
+
+# Run a test of GDB's conditional breakpoints, where the conditions include
+# inferior function calls.
+#
+# CONDITION is the expression to be used as the breakpoint condition.
+#
+# N_EXPECTED_HITS is the number of threads that we expect to stop due to
+# CONDITON.
+#
+# MESSAGE is used as a test name prefix.
+proc run_condition_test { message n_expected_hits condition \
+			      target_async target_non_stop } {
+    with_test_prefix $message {
+
+	if { [start_gdb_and_runto_main $target_async \
+		  $target_non_stop] == -1 } {
+	    return
+	}
+
+	# Use this convenience variable to track how often the
+	# breakpoint condition has been evaluated.  This should be
+	# once per thread.
+	gdb_test "set \$n_cond_eval = 0"
+
+	# Setup the conditional breakpoint.
+	gdb_breakpoint \
+	    "${::srcfile}:${::cond_bp_line} if ((++\$n_cond_eval) && (${condition}))"
+
+	# And a breakpoint that we hit when the test is over, this one is
+	# not conditional.  Only the main thread gets here once all the
+	# other threads have finished.
+	gdb_breakpoint "${::srcfile}:${::stop_bp_line}"
+
+	# The number of times we stop at the conditional breakpoint.
+	set n_hit_condition 0
+
+	# Now keep 'continue'-ing GDB until all the threads have finished
+	# and we reach the stop_marker breakpoint.
+	gdb_test_multiple "continue" "spot all breakpoint hits" {
+	    -re " worker_func \[^\r\n\]+${::srcfile}:${::cond_bp_line}\r\n${::decimal}\\s+\[^\r\n\]+Breakpoint here\[^\r\n\]+\r\n${::gdb_prompt} $" {
+		incr n_hit_condition
+		send_gdb "continue\n"
+		exp_continue
+	    }
+
+	    -re " stop_marker \[^\r\n\]+${::srcfile}:${::stop_bp_line}\r\n${::decimal}\\s+\[^\r\n\]+Stop marker\[^\r\n\]+\r\n${::gdb_prompt} $" {
+		pass $gdb_test_name
+	    }
+	}
+
+	gdb_assert { $n_hit_condition == $n_expected_hits } \
+	    "stopped at breakpoint the expected number of times"
+
+	# Ensure the breakpoint condition was evaluated once per thread.
+	gdb_test "print \$n_cond_eval" "= 3" \
+	    "condition was evaluated in each thread"
+    }
+}
+
+# Check that after handling a conditional breakpoint (where the condition
+# includes an inferior call), it is still possible to kill the running
+# inferior, and then restart the inferior.
+#
+# At once point doing this would result in GDB giving an assertion error.
+proc_with_prefix run_kill_and_restart_test { target_async target_non_stop } {
+    # This test relies on the 'start' command, which is not possible with
+    # the plain 'remote' target.
+    if { [target_info gdb_protocol] == "remote" } {
+	return
+    }
+
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint.
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 1))"
+    gdb_continue_to_breakpoint "worker_func"
+
+    # Now kill the program being debugged.
+    gdb_test "kill" "" "kill process" \
+	"Kill the program being debugged.*y or n. $" "y"
+
+    # Check we can restart the inferior.  At one point this would trigger an
+    # assertion.
+    gdb_test "start" ".*"
+}
+
+# Create a conditional breakpoint which includes a call to a function that
+# segfaults.  Run GDB and check what happens when the inferior segfaults
+# during the inferior call.
+proc_with_prefix run_bp_cond_segfaults { target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # This test relies on the inferior segfaulting when trying to
+    # access address zero.
+    if { [is_address_zero_readable] } {
+	return
+    }
+
+    # Setup the conditional breakpoint, include a call to
+    # 'function_that_segfaults', which triggers the segfault.
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 0) && function_that_segfaults ())"
+    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of conditional breakpoint"]
+
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     ".*" \
+	     "Thread ${::decimal} \"infcall-from-bp\" received signal SIGSEGV, Segmentation fault\\." \
+	     "${::hex} in function_that_segfaults \\(\\) at \[^\r\n\]+:${::segv_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Segfault happens here\[^\r\n\]+" \
+	     "Error in testing condition for breakpoint ${bp_1_num}:" \
+	     "The program being debugged was signaled while in a function called from GDB\\." \
+	     "GDB remains in the frame where the signal was received\\." \
+	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(function_that_segfaults\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+}
+
+# Create a conditional breakpoint which includes a call to a function that
+# itself has a breakpoint set within it.  Run GDB and check what happens
+# when GDB hits the nested breakpoint.
+proc_with_prefix run_bp_cond_hits_breakpoint { target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint, include a call to
+    # 'function_with_breakpoint' in which we will shortly place a
+    # breakpoint.
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 0) && function_with_breakpoint ())"
+    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of conditional breakpoint"]
+
+    gdb_breakpoint "${::srcfile}:${::nested_bp_line}"
+    set bp_2_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of nested breakpoint"]
+
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     ".*" \
+	     "Thread ${::decimal} \"infcall-from-bp\" hit Breakpoint ${bp_2_num}, function_with_breakpoint \\(\\) at \[^\r\n\]+:${::nested_bp_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Nested breakpoint\[^\r\n\]+" \
+	     "Error in testing condition for breakpoint ${bp_1_num}:" \
+	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(function_with_breakpoint\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	run_condition_test "exactly one thread is hit" \
+	    1 "is_matching_tid (arg, 1)" \
+	    $target_async $target_non_stop
+	run_condition_test "exactly two threads are hit" \
+	    2 "(is_matching_tid (arg, 0) || is_matching_tid (arg, 2))" \
+	    $target_async $target_non_stop
+	run_condition_test "all three threads are hit" \
+	    3 "return_true ()" \
+	    $target_async $target_non_stop
+	run_condition_test "no thread is hit" \
+	    0 "return_false ()" \
+	    $target_async $target_non_stop
+
+	run_kill_and_restart_test $target_async $target_non_stop
+	run_bp_cond_segfaults $target_async $target_non_stop
+	run_bp_cond_hits_breakpoint $target_async $target_non_stop
+    }
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
new file mode 100644
index 00000000000..835c72f03cf
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
@@ -0,0 +1,139 @@
+/* Copyright 2022-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 <pthread.h>
+#include <unistd.h>
+#include <semaphore.h>
+#include <stdlib.h>
+
+#define NUM_THREADS 5
+
+/* Semaphores, used to track when threads have started, and to control
+   when the threads finish.  */
+sem_t startup_semaphore;
+sem_t finish_semaphore;
+
+/* Mutex to control when the first worker thread hit a breakpoint
+   location.  */
+pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+
+/* Global variable to poke, just so threads have something to do.  */
+volatile int global_var = 0;
+
+int
+return_true ()
+{
+  return 1;
+}
+
+int
+return_false ()
+{
+  return 0;
+}
+
+void *
+worker_func (void *arg)
+{
+  int tid = *((int *) arg);
+
+  switch (tid)
+    {
+    case 0:
+      /* Wait for MUTEX to become available, then pass through the
+	 conditional breakpoint location.  */
+      if (pthread_mutex_lock (&mutex) != 0)
+	abort ();
+      global_var = 99;	/* Conditional breakpoint here.  */
+      if (pthread_mutex_unlock (&mutex) != 0)
+	abort ();
+      break;
+
+    default:
+      /* Notify the main thread that the thread has started, then wait for
+	 the main thread to tell us to finish.  */
+      sem_post (&startup_semaphore);
+      if (sem_wait (&finish_semaphore) != 0)
+	abort ();
+      break;
+    }
+}
+
+void
+stop_marker ()
+{
+  global_var = 99;	/* Stop marker.  */
+}
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+  void *retval;
+
+  /* An alarm, just in case the thread deadlocks.  */
+  alarm (300);
+
+  /* Semaphore initialization.  */
+  if (sem_init (&startup_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&finish_semaphore, 0, 0) != 0)
+    abort ();
+
+  /* Lock MUTEX, this prevents the first worker thread from rushing ahead.  */
+  if (pthread_mutex_lock (&mutex) != 0)
+    abort ();
+
+  /* Worker thread creation.  */
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  /* Wait for every thread (other than the first) to tell us it has started
+     up.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    {
+      if (sem_wait (&startup_semaphore) != 0)
+	abort ();
+    }
+
+  /* Unlock the first thread so it can proceed.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  /* Wait for the first thread only.  */
+  pthread_join (threads[0], &retval);
+
+  /* Now post FINISH_SEMAPHORE to allow all the other threads to finish.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    sem_post (&finish_semaphore);
+
+  /* Now wait for the remaining threads to complete.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    pthread_join (threads[i], &retval);
+
+  /* Semaphore cleanup.  */
+  sem_destroy (&finish_semaphore);
+  sem_destroy (&startup_semaphore);
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
new file mode 100644
index 00000000000..9690f0ac3a3
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
@@ -0,0 +1,118 @@
+# Copyright 2022-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 reprocuces bug gdb/28942, performing an inferior function
+# call from a breakpoint condition in a multi-threaded inferior.
+#
+# The important part of this test is that, when the conditional
+# breakpoint is hit, and the condition (which includes an inferior
+# function call) is evaluated, the other threads are running.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] == -1 } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "Conditional breakpoint here"]
+set final_bp_line [gdb_get_line_number "Stop marker"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if { ![runto_main] } {
+	fail "run to main"
+	return -1
+    }
+
+    return 0
+}
+
+# Run a test of GDB's conditional breakpoints, where the conditions include
+# inferior function calls.
+#
+# TARGET_ASYNC and TARGET_NON_STOP are used when starting up GDB.
+#
+# When STOP_AT_COND is true the breakpoint condtion will evaluate to
+# true, and GDB will stop at the breakpoint.  Otherwise, the
+# breakpoint condition will evaluate to false and GDB will not stop at
+# the breakpoint.
+proc run_condition_test { stop_at_cond \
+			      target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint.
+    if { $stop_at_cond } {
+	set cond_func "return_true"
+    } else {
+	set cond_func "return_false"
+    }
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (${cond_func} ())"
+    set cond_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			"get number for conditional breakpoint"]
+
+    # And a breakpoint that we hit when the test is over, this one is
+    # not conditional.
+    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
+    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			  "get number for final breakpoint"]
+
+    if { $stop_at_cond } {
+	# Continue.  The first breakpoint we hit should be the conditional
+	# breakpoint.  The other thread will have hit its breakpoint, but
+	# that will have been deferred until the conditional breakpoint is
+	# reported.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${cond_bp_num}, worker_func \[^\r\n\]+:${::cond_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Conditional breakpoint here\[^\r\n\]+"] \
+	    "hit the conditional breakpoint"
+    }
+
+    # Run to the stop marker.
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     ".*" \
+	     "" \
+	     "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${final_bp_num}, stop_marker \[^\r\n\]+:${::final_bp_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Stop marker\[^\r\n\]+"] \
+	"hit the final breakpoint"
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	foreach_with_prefix stop_at_cond { true false } {
+	    run_condition_test $stop_at_cond \
+		$target_async $target_non_stop
+	}
+    }
+}
-- 
2.25.4


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

* [PATCHv3 10/13] gdb: add timeouts for inferior function calls
  2023-01-31 17:27   ` [PATCHv3 " Andrew Burgess
                       ` (8 preceding siblings ...)
  2023-01-31 17:27     ` [PATCHv3 09/13] gdb: fix b/p conditions with infcalls in multi-threaded inferiors Andrew Burgess
@ 2023-01-31 17:27     ` Andrew Burgess
  2023-01-31 18:11       ` Eli Zaretskii
  2023-02-16 10:53       ` Aktemur, Tankut Baris
  2023-01-31 17:27     ` [PATCHv3 11/13] gdb/remote: avoid SIGINT after calling remote_target::stop Andrew Burgess
                       ` (3 subsequent siblings)
  13 siblings, 2 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-01-31 17:27 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

In the previous commits I have been working on improving inferior
function call support.  One thing that worries me about using inferior
function calls from a conditional breakpoint is: what happens if the
inferior function call fails?

If the failure is obvious, e.g. the thread performing the call
crashes, or hits a breakpoint, then this case is already well handled,
and the error is reported to the user.

But what if the thread performing the inferior call just deadlocks?
If the user made the call from a 'print' or 'call' command, then the
user might have some expectation of when the function call should
complete, and, when this time limit is exceeded, the user
will (hopefully) interrupt GDB and regain control of the debug
session.

But, when the inferior function call is from a breakpoint condition it
is much harder to understand that GDB is deadlocked within an inferior
call.  Maybe the breakpoint hasn't been hit yet?  Or maybe the
condition was always false?  Or maybe GDB is deadlocked in an inferior
call?  The only way to know for sure is to periodically interrupt GDB,
check on all the threads, and then continue.

Additionally, the focus of the previous commit was inferior function
calls, from a conditional breakpoint, in a multi-threaded inferior.
This opens up a whole new set of potential failure conditions.  For
example, what if the function called relies on interaction with some
other thread, and the other thread crashes?  Or hits a breakpoint?
Given how inferior function calls work (in a synchronous manor), a
stop event in some other thread is going to be ignored while the
inferior function call is being executed as part of a breakpoint
condition, and this means that GDB could get stuck waiting for the
original condition thread, which will now never complete.

In this commit I propose a solution to this problem.  A timeout.  For
targets that support async-mode we can install an event-loop timer
before starting the inferior function call.  When the timer expires we
will stop the thread performing the inferior function call.  With this
mechanism in place a user can be sure that any inferior call they make
will either complete, or timeout eventually.

Adding a timer like this is obviously a change in behaviour for the
more common 'call' and 'print' uses of inferior function calls, so, in
this patch, I propose having two different timers.  One I call the
'direct-call-timeout', which is used for 'call' and 'print' commands.
This timeout is by default set to unlimited, which, not surprisingly,
means there is no timeout in place.

A second timer, which I've called 'indirect-call-timeout', is used for
inferior function calls from breakpoint conditions.  This timeout has
a default value of 30 seconds.  This is a reasonably long time to
wait, and hopefully should be enough in most cases to allow the
inferior call to complete.  An inferior call that takes more than 30
seconds, which is installed on a breakpoint condition is really going
to slow down the debug session, so hopefully this is not a common use
case.

The user is, of course, free to reduce, or increase the timeout value,
and can always use Ctrl-c to interrupt an inferior function call, but
this timeout will ensure that GDB will stop at some point.

The new commands added by this commit are:

  set direct-call-timeout SECONDS
  show direct-call-timeout
  set indirect-call-timeout SECONDS
  show indirect-call-timeout

These new timeouts do depend on async-mode, so, if async-mode is
disabled (maint set target-async off), or not supported (e.g. target
sim), then the timeout is treated as unlimited (that is, no timeout is
set).

For targets that "fake" non-async mode, e.g. Linux native, where
non-async mode is really just async mode, but then we park the target
in a sissuspend, we could easily fix things so that the timeouts still
work, however, for targets that really are not async aware, like the
simulator, fixing things so that timeouts work correctly would be a
much bigger task - that effort would be better spent just making the
target async-aware.  And so, I'm happy for now that this feature will
only work on async targets.

The two new show commands will display slightly different text if the
current target is a non-async target, which should allow users to
understand what's going on.

There's a somewhat random test adjustment needed in gdb.base/help.exp,
the test uses a regexp with the apropos command, and expects to find a
single result.  Turns out the new settings I added also matched the
regexp, which broke the test.  I've updated the regexp a little to
exclude my new settings.

In infcall.c you'll notice the thread_info::stop_requested flag being
set when a timeout occurs.  This flag setting is not required as part
of this commit, but will be needed in a later commit.  However, it
seemed like setting this flag fitted better with this commit, which is
why the change is added here.
---
 gdb/NEWS                                      |  18 ++
 gdb/doc/gdb.texinfo                           |  66 ++++++
 gdb/infcall.c                                 | 221 +++++++++++++++++-
 gdb/testsuite/gdb.base/help.exp               |   2 +-
 gdb/testsuite/gdb.base/infcall-timeout.c      |  36 +++
 gdb/testsuite/gdb.base/infcall-timeout.exp    |  82 +++++++
 .../infcall-from-bp-cond-timeout.c            | 169 ++++++++++++++
 .../infcall-from-bp-cond-timeout.exp          | 156 +++++++++++++
 8 files changed, 745 insertions(+), 5 deletions(-)
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.c
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp

diff --git a/gdb/NEWS b/gdb/NEWS
index 445d28efed9..835bf7f8680 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -38,6 +38,24 @@ maintenance print record-instruction [ N ]
   prints how GDB would undo the N-th previous instruction, and if N is
   positive, it prints how GDB will redo the N-th following instruction.
 
+set direct-call-timeout SECONDS
+show direct-call-timeout
+set indirect-call-timeout SECONDS
+show indirect-call-timeout
+  These new settings can be used to limit how long GDB will wait for
+  an inferior function call to complete.  The direct timeout is used
+  for inferior function calls from e.g. 'call' and 'print' commands,
+  while the indirect timeout is used for inferior function calls from
+  within a conditional breakpoint expression.
+
+  The default for the direct timeout is unlimited, while the default
+  for the indirect timeout is 30 seconds.
+
+  These timeouts will only have an effect for targets that are
+  operating in async mode.  For non-async targets the timeouts are
+  ignored, GDB will wait indefinitely for an inferior function to
+  complete, unless interrupted by the user using Ctrl-C.
+
 * MI changes
 
 ** mi now reports 'no-history' as a stop reason when hitting the end of the
diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index dd8267f448f..f5d460eb9e5 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -20808,6 +20808,72 @@
 @code{step}, etc).  In this case, when the inferior finally returns to
 the dummy-frame, @value{GDBN} will once again halt the inferior.
 
+On targets that support asynchronous execution (@pxref{Background
+Execution}) @value{GDBN} can place a timeout on any functions called
+from @value{GDBN}.  If the timeout expires and the function call is
+still ongoing, then @value{GDBN} will interrupt the program.
+
+For targets that don't support asynchronous execution
+(@pxref{Background Execution}) then timeouts for functions called from
+@value{GDBN} are not supported, the timeout settings described below
+will be treated as @code{unlimited}, meaning @value{GDBN} will wait
+indefinitely for function call to complete, unless interrupted by the
+user using @kbd{Ctrl-C}.
+
+@table @code
+@item set direct-call-timeout @var{seconds}
+@kindex set direct-call-timeout
+@cindex timeout for called functions
+Set the timeout used when calling functions in the program to
+@var{seconds}, which should be an integer greater than zero, or the
+special value @code{unlimited}, which indicates no timeout should be
+used.  The default for this setting is @code{unlimited}.
+
+This setting is used when the user calls a function directly from the
+command prompt, for example with a @code{call} or @code{print}
+command.
+
+This setting only works for targets that support asynchronous
+execution (@pxref{Background Execution}), for any other target the
+setting is treated as @code{unlimited}.
+
+@item show direct-call-timeout
+@kindex show direct-call-timeout
+@cindex timeout for called functions
+Show the timeout used when calling functions in the program with a
+@code{call} or @code{print} command.
+@end table
+
+It is also possible to call functions within the program from the
+condition of a conditional breakpoint (@pxref{Conditions, ,Break
+Conditions}).  A different setting controls the timeout used for
+function calls made from a breakpoint condition.
+
+@table @code
+@item set indirect-call-timeout @var{seconds}
+@kindex set indirect-call-timeout
+@cindex timeout for called functions
+Set the timeout used when calling functions in the program from a
+breakpoint or watchpoint condition to @var{seconds}, which should be
+an integer greater than zero, or the special value @code{unlimited},
+which indicates no timeout should be used.  The default for this
+setting is @code{30} seconds.
+
+This setting only works for targets that support asynchronous
+execution (@pxref{Background Execution}), for any other target the
+setting is treated as @code{unlimited}.
+
+If a function called from a breakpoint or watchpoint condition times
+out, then @value{GDBN} will stop at the point where the timeout
+occurred.  The breakpoint condition evaluation will be abandoned.
+
+@item show indirect-call-timeout
+@kindex show indirect-call-timeout
+@cindex timeout for called functions
+Show the timeout used when calling functions in the program from a
+breakpoint or watchpoint condition.
+@end table
+
 @subsection Calling functions with no debug info
 
 @cindex no debug info functions
diff --git a/gdb/infcall.c b/gdb/infcall.c
index 34838dea1bd..92f49a64e3e 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -95,6 +95,53 @@ show_may_call_functions_p (struct ui_file *file, int from_tty,
 	      value);
 }
 
+/* A timeout (in seconds) for direct inferior calls.  A direct inferior
+   call is one the user triggers from the prompt, e.g. with a 'call' or
+   'print' command.  Compare with the definition of indirect calls below.  */
+
+static unsigned int direct_call_timeout = UINT_MAX;
+
+/* Implement 'show direct-call-timeout'.  */
+
+static void
+show_direct_call_timeout (struct ui_file *file, int from_tty,
+			  struct cmd_list_element *c, const char *value)
+{
+  if (target_has_execution () && !target_can_async_p ())
+    gdb_printf (file, _("Current target does not support async mode, timeout "
+			"for direct inferior calls is \"unlimited\".\n"));
+  else if (direct_call_timeout == UINT_MAX)
+    gdb_printf (file, _("Timeout for direct inferior function calls "
+			"is \"unlimited\".\n"));
+  else
+    gdb_printf (file, _("Timeout for direct inferior function calls "
+			"is \"%s seconds\".\n"), value);
+}
+
+/* A timeout (in seconds) for indirect inferior calls.  An indirect inferior
+   call is one that originates from within GDB, for example, when
+   evaluating an expression for a conditional breakpoint.  Compare with
+   the definition of direct calls above.  */
+
+static unsigned int indirect_call_timeout = 30;
+
+/* Implement 'show indirect-call-timeout'.  */
+
+static void
+show_indirect_call_timeout (struct ui_file *file, int from_tty,
+			  struct cmd_list_element *c, const char *value)
+{
+  if (target_has_execution () && !target_can_async_p ())
+    gdb_printf (file, _("Current target does not support async mode, timeout "
+			"for indirect inferior calls is \"unlimited\".\n"));
+  else if (indirect_call_timeout == UINT_MAX)
+    gdb_printf (file, _("Timeout for indirect inferior function calls "
+			"is \"unlimited\".\n"));
+  else
+    gdb_printf (file, _("Timeout for indirect inferior function calls "
+			"is \"%s seconds\".\n"), value);
+}
+
 /* How you should pass arguments to a function depends on whether it
    was defined in K&R style or prototype style.  If you define a
    function using the K&R syntax that takes a `float' argument, then
@@ -589,6 +636,86 @@ call_thread_fsm::should_notify_stop ()
   return true;
 }
 
+/* A class to control creation of a timer that will interrupt a thread
+   during an inferior call.  */
+struct infcall_timer_controller
+{
+  /* Setup an event-loop timer that will interrupt PTID if the inferior
+     call takes too long.  DIRECT_CALL_P is true when this inferior call is
+     a result of the user using a 'print' or 'call' command, and false when
+     this inferior call is a result of e.g. a conditional breakpoint
+     expression, this is used to select which timeout to use.  */
+  infcall_timer_controller (thread_info *thr, bool direct_call_p)
+    : m_thread (thr)
+  {
+    unsigned int timeout
+      = direct_call_p ? direct_call_timeout : indirect_call_timeout;
+    if (timeout < UINT_MAX && target_can_async_p ())
+      {
+	int ms = timeout * 1000;
+	int id = create_timer (ms, infcall_timer_controller::timed_out, this);
+	m_timer_id.emplace (id);
+	infcall_debug_printf ("Setting up infcall timeout timer for "
+			      "ptid %s: %d milliseconds",
+			      m_thread->ptid.to_string ().c_str (), ms);
+      }
+  }
+
+  /* Destructor.  Ensure that the timer is removed from the event loop.  */
+  ~infcall_timer_controller ()
+  {
+    /* If the timer has already triggered, then it will have already been
+       deleted from the event loop.  If the timer has not triggered, then
+       delete it now.  */
+    if (m_timer_id.has_value () && !m_triggered)
+      delete_timer (*m_timer_id);
+
+    /* Just for clarity, discard the timer id now.  */
+    m_timer_id.reset ();
+  }
+
+  /* Return true if there was a timer in place, and the timer triggered,
+     otherwise, return false.  */
+  bool triggered_p ()
+  {
+    gdb_assert (!m_triggered || m_timer_id.has_value ());
+    return m_triggered;
+  }
+
+private:
+  /* The thread we should interrupt.  */
+  thread_info *m_thread;
+
+  /* Set true when the timer is triggered.  */
+  bool m_triggered = false;
+
+  /* Given a value when a timer is in place.  */
+  gdb::optional<int> m_timer_id;
+
+  /* Callback for the timer, forwards to ::trigger below.  */
+  static void
+  timed_out (gdb_client_data context)
+  {
+    infcall_timer_controller *ctrl
+      = static_cast<infcall_timer_controller *> (context);
+    ctrl->trigger ();
+  }
+
+  /* Called when the timer goes off.  Stop thread m_thread.  */
+  void
+  trigger ()
+  {
+    m_triggered = true;
+
+    scoped_disable_commit_resumed disable_commit_resumed ("infcall timeout");
+
+    infcall_debug_printf ("Stopping thread %s",
+			  m_thread->ptid.to_string ().c_str ());
+    target_stop (m_thread->ptid);
+    m_thread->stop_requested = true;
+  }
+};
+
 /* Subroutine of call_function_by_hand to simplify it.
    Start up the inferior and wait for it to stop.
    Return the exception if there's an error, or an exception with
@@ -599,13 +726,15 @@ call_thread_fsm::should_notify_stop ()
 
 static struct gdb_exception
 run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
-		   struct thread_info *call_thread, CORE_ADDR real_pc)
+		   struct thread_info *call_thread, CORE_ADDR real_pc,
+		   bool *timed_out_p)
 {
   INFCALL_SCOPED_DEBUG_ENTER_EXIT;
 
   struct gdb_exception caught_error;
   ptid_t call_thread_ptid = call_thread->ptid;
   int was_running = call_thread->state == THREAD_RUNNING;
+  *timed_out_p = false;
 
   infcall_debug_printf ("call function at %s in thread %s, was_running = %d",
 			core_addr_to_string (real_pc),
@@ -617,6 +746,16 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
   scoped_restore restore_in_infcall
     = make_scoped_restore (&call_thread->control.in_infcall, 1);
 
+  /* If the thread making the inferior call stops with a time out then the
+     stop_requested flag will be set.  However, we don't want changes to
+     this flag to leak back to our caller, we might be here to handle an
+     inferior call from a breakpoint condition, so leaving this flag set
+     would appear that the breakpoint stop was actually a requested stop,
+     which is not true, and will cause GDB to print extra messages to the
+     output.  */
+  scoped_restore restore_stop_requested
+    = make_scoped_restore (&call_thread->stop_requested, false);
+
   clear_proceed_status (0);
 
   /* Associate the FSM with the thread after clear_proceed_status
@@ -650,11 +789,23 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
       infrun_debug_show_threads ("non-exited threads after proceed for inferior-call",
 				 all_non_exited_threads ());
 
+      /* Setup a timer (if possible, and if the settings allow) to prevent
+	 the inferior call running forever.  */
+      bool direct_call_p = !call_thread->control.in_cond_eval;
+      infcall_timer_controller infcall_timer (call_thread, direct_call_p);
+
       /* Inferior function calls are always synchronous, even if the
 	 target supports asynchronous execution.  */
       wait_sync_command_done ();
 
-      infcall_debug_printf ("inferior call completed successfully");
+      /* If the timer triggered then the inferior call failed.  */
+      if (infcall_timer.triggered_p ())
+	{
+	  infcall_debug_printf ("inferior call timed out");
+	  *timed_out_p = true;
+	}
+      else
+	infcall_debug_printf ("inferior call completed successfully");
     }
   catch (gdb_exception &e)
     {
@@ -1308,6 +1459,10 @@ call_function_by_hand_dummy (struct value *function,
   scoped_restore restore_stopped_by_random_signal
     = make_scoped_restore (&stopped_by_random_signal, 0);
 
+  /* Set to true by the call to run_inferior_call below if the inferior
+     call is artificially interrupted by GDB due to taking too long.  */
+  bool timed_out_p = false;
+
   /* - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP -
      If you're looking to implement asynchronous dummy-frames, then
      just below is the place to chop this function in two..  */
@@ -1334,7 +1489,8 @@ call_function_by_hand_dummy (struct value *function,
 			      struct_addr);
     {
       std::unique_ptr<call_thread_fsm> sm_up (sm);
-      e = run_inferior_call (std::move (sm_up), call_thread.get (), real_pc);
+      e = run_inferior_call (std::move (sm_up), call_thread.get (), real_pc,
+			     &timed_out_p);
     }
 
     if (e.reason < 0)
@@ -1486,7 +1642,10 @@ When the function is done executing, GDB will silently stop."),
       std::string name = get_function_name (funaddr, name_buf,
 					    sizeof (name_buf));
 
-      if (stopped_by_random_signal)
+      /* If the inferior call timed out then it will have been interrupted
+	 by a signal, but we want to report this differently to the user,
+	 which is done later in this function.  */
+      if (stopped_by_random_signal && !timed_out_p)
 	{
 	  /* We stopped inside the FUNCTION because of a random
 	     signal.  Further execution of the FUNCTION is not
@@ -1530,6 +1689,36 @@ GDB remains in the frame where the signal was received.\n\
 To change this behavior use \"set unwindonsignal on\".\n\
 Evaluation of the expression containing the function\n\
 (%s) will be abandoned.\n\
+When the function is done executing, GDB will silently stop."),
+		     name.c_str ());
+	    }
+	}
+
+      if (timed_out_p)
+	{
+	  /* A timeout results in a signal being sent to the inferior.  */
+	  gdb_assert (stopped_by_random_signal);
+
+	  /* Indentation is weird here.  A later patch is going to move the
+	    following block into an if/else, so I'm leaving the indentation
+	    here to minimise the later patch.
+
+	    Also, the error message used below refers to 'set
+	    unwind-on-timeout' which doesn't exist yet.  This will be added
+	    in a later commit, I'm leaving this in for now to minimise the
+	    churn caused by the commit that adds unwind-on-timeout.  */
+	    {
+	      /* The user wants to stay in the frame where we stopped
+		 (default).  Discard inferior status, we're not at the same
+		 point we started at.  */
+	      discard_infcall_control_state (inf_status.release ());
+
+	      error (_("\
+The program being debugged timed out while in a function called from GDB.\n\
+GDB remains in the frame where the timeout occurred.\n\
+To change this behavior use \"set unwind-on-timeout on\".\n\
+Evaluation of the expression containing the function\n\
+(%s) will be abandoned.\n\
 When the function is done executing, GDB will silently stop."),
 		     name.c_str ());
 	    }
@@ -1643,6 +1832,30 @@ The default is to unwind the frame."),
 			   show_unwind_on_terminating_exception_p,
 			   &setlist, &showlist);
 
+  add_setshow_uinteger_cmd ("direct-call-timeout", no_class,
+			    &direct_call_timeout, _("\
+Set the timeout, for direct calls to inferior function calls."), _("\
+Show the timeout, for direct calls to inferior function calls."), _("\
+If running on a target that supports, and is running in, async mode\n\
+then this timeout is used for any inferior function calls triggered\n\
+directly from the prompt, i.e. from a 'call' or 'print' command.  The\n\
+timeout is specified in seconds."),
+			    nullptr,
+			    show_direct_call_timeout,
+			    &setlist, &showlist);
+
+  add_setshow_uinteger_cmd ("indirect-call-timeout", no_class,
+			    &indirect_call_timeout, _("\
+Set the timeout, for indirect calls to inferior function calls."), _("\
+Show the timeout, for indirect calls to inferior function calls."), _("\
+If running on a target that supports, and is running in, async mode\n\
+then this timeout is used for any inferior function calls triggered\n\
+indirectly, i.e. being made as part of a breakpoint, or watchpoint,\n\
+condition expression.  The timeout is specified in seconds."),
+			    nullptr,
+			    show_indirect_call_timeout,
+			    &setlist, &showlist);
+
   add_setshow_boolean_cmd
     ("infcall", class_maintenance, &debug_infcall,
      _("Set inferior call debugging."),
diff --git a/gdb/testsuite/gdb.base/help.exp b/gdb/testsuite/gdb.base/help.exp
index 87919a819ab..504bf90cc15 100644
--- a/gdb/testsuite/gdb.base/help.exp
+++ b/gdb/testsuite/gdb.base/help.exp
@@ -121,7 +121,7 @@ gdb_test "help info bogus-gdb-command" "Undefined info command: \"bogus-gdb-comm
 gdb_test "help gotcha" "Undefined command: \"gotcha\"\.  Try \"help\"\."
 
 # Test apropos regex.
-gdb_test "apropos \\\(print\[\^\[ bsiedf\\\".-\]\\\)" "handle -- Specify how to handle signals\."
+gdb_test "apropos \\\(print\[\^\[ bsiedf\\\"'.-\]\\\)" "handle -- Specify how to handle signals\."
 # Test apropos >1 word string.
 gdb_test "apropos handle signal" "handle -- Specify how to handle signals\."
 # Test apropos apropos.
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.c b/gdb/testsuite/gdb.base/infcall-timeout.c
new file mode 100644
index 00000000000..895e8a36d59
--- /dev/null
+++ b/gdb/testsuite/gdb.base/infcall-timeout.c
@@ -0,0 +1,36 @@
+/* Copyright 2022 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 <unistd.h>
+
+/* This function is called from GDB.  */
+int
+function_that_never_returns ()
+{
+  while (1)
+    sleep (1);
+
+  return 0;
+}
+
+int
+main ()
+{
+  alarm (300);
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.exp b/gdb/testsuite/gdb.base/infcall-timeout.exp
new file mode 100644
index 00000000000..a5b0111ed04
--- /dev/null
+++ b/gdb/testsuite/gdb.base/infcall-timeout.exp
@@ -0,0 +1,82 @@
+# Copyright 2022 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/>.
+
+# Test GDB's direct-call-timeout setting, that is, ensure that if an
+# inferior function call, invoked from e.g. a 'print' command, takes
+# too long, then GDB can interrupt it, and return control to the user.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug}] == -1 } {
+    return
+}
+
+# Start GDB according to TARGET_ASYNC and TARGET_NON_STOP, then adjust
+# the direct-call-timeout, and make an inferior function call that
+# will never return.  GDB should eventually timeout and stop the
+# inferior.
+proc_with_prefix run_test { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if {![runto_main]} {
+	fail "run to main"
+	return
+    }
+
+    gdb_test_no_output "set direct-call-timeout 5"
+
+    # When non-stop mode is off we get slightly different output from GDB.
+    if { [gdb_is_remote_or_extended_remote_target] && $target_non_stop == "off" } {
+	set stopped_line_pattern "Program received signal SIGINT, Interrupt\\."
+    } else {
+	set stopped_line_pattern "Program stopped\\."
+    }
+
+    gdb_test "print function_that_never_returns ()" \
+	[multi_line \
+	     $stopped_line_pattern \
+	     ".*" \
+	     "The program being debugged timed out while in a function called from GDB\\." \
+	     "GDB remains in the frame where the timeout occurred\\." \
+	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(function_that_never_returns\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+
+    gdb_test "bt" ".* function_that_never_returns .*<function called from gdb>.*"
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+
+    if { $target_async == "off" } {
+	# GDB can't timeout while waiting for a thread if the target
+	# runs with async-mode turned off; once the target is running
+	# GDB is effectively blocked until the target stops for some
+	# reason.
+	continue
+    }
+
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	run_test $target_async $target_non_stop
+    }
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
new file mode 100644
index 00000000000..3bd91d7377d
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
@@ -0,0 +1,169 @@
+/* This testcase is part of GDB, the GNU debugger.
+
+   Copyright 2022 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 <stdio.h>
+#include <pthread.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <semaphore.h>
+
+#define NUM_THREADS 5
+
+/* Semaphores, used to track when threads have started, and to control
+   when the threads finish.  */
+sem_t startup_semaphore;
+sem_t finish_semaphore;
+sem_t thread_1_semaphore;
+sem_t thread_2_semaphore;
+
+/* Mutex to control when the first worker thread hit a breakpoint
+   location.  */
+pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+
+/* Global variable to poke, just so threads have something to do.  */
+volatile int global_var = 0;
+
+int
+condition_func ()
+{
+  /* Let thread 2 run.  */
+  if (sem_post (&thread_2_semaphore) != 0)
+    abort ();
+
+  /* Wait for thread 2 to complete its actions.  */
+  if (sem_wait (&thread_1_semaphore) != 0)
+    abort ();
+
+  return 1;
+}
+
+void
+do_segfault ()
+{
+  volatile int *p = 0;
+  *p = 0;	/* Segfault here.  */
+}
+
+void *
+worker_func (void *arg)
+{
+  int tid = *((int *) arg);
+
+  /* Let the main thread know that this worker has started.  */
+  if (sem_post (&startup_semaphore) != 0)
+    abort ();
+
+  switch (tid)
+    {
+    case 0:
+      /* Wait for MUTEX to become available, then pass through the
+	 conditional breakpoint location.  */
+      if (pthread_mutex_lock (&mutex) != 0)
+	abort ();
+      global_var = 99;	/* Conditional breakpoint here.  */
+      if (pthread_mutex_unlock (&mutex) != 0)
+	abort ();
+      break;
+
+    case 1:
+      if (sem_wait (&thread_2_semaphore) != 0)
+	abort ();
+      do_segfault ();
+      if (sem_post (&thread_1_semaphore) != 0)
+	abort ();
+
+      /* Fall through.  */
+    default:
+      /* Wait until we are allowed to finish.  */
+      if (sem_wait (&finish_semaphore) != 0)
+	abort ();
+      break;
+    }
+}
+
+void
+stop_marker ()
+{
+  global_var = 99;	/* Stop marker.  */
+}
+
+/* The main program entry point.  */
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+  void *retval;
+
+  /* An alarm, just in case the thread deadlocks.  */
+  alarm (300);
+
+  /* Semaphore initialization.  */
+  if (sem_init (&startup_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&finish_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&thread_1_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&thread_2_semaphore, 0, 0) != 0)
+    abort ();
+
+  /* Lock MUTEX, this prevents the first worker thread from rushing ahead.  */
+  if (pthread_mutex_lock (&mutex) != 0)
+    abort ();
+
+  /* Worker thread creation.  */
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  /* Wait for every thread to start.  */
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      if (sem_wait (&startup_semaphore) != 0)
+	abort ();
+    }
+
+  /* Unlock the first thread so it can proceed.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  /* Wait for the first thread only.  */
+  pthread_join (threads[0], &retval);
+
+  /* Now post FINISH_SEMAPHORE to allow all the other threads to finish.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    sem_post (&finish_semaphore);
+
+  /* Now wait for the remaining threads to complete.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    pthread_join (threads[i], &retval);
+
+  /* Semaphore cleanup.  */
+  sem_destroy (&finish_semaphore);
+  sem_destroy (&startup_semaphore);
+  sem_destroy (&thread_1_semaphore);
+  sem_destroy (&thread_2_semaphore);
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
new file mode 100644
index 00000000000..3341ff33f19
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
@@ -0,0 +1,156 @@
+# Copyright 2020 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 inferior calls executed from a breakpoint condition in
+# a multi-threaded program.
+#
+# This test has the inferior function call timeout, and checks how GDB
+# handles this situation.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "Conditional breakpoint here"]
+set final_bp_line [gdb_get_line_number "Stop marker"]
+set segfault_line [gdb_get_line_number "Segfault here"]
+
+# Setup GDB based on TARGET_ASYNC and TARGET_NON_STOP.  Setup some
+# breakpoints in the inferior, one of which has an inferior call
+# within its condition.
+#
+# Continue GDB, the breakpoint with inferior call will be hit, but the
+# inferior call will never return.  We expect GDB to timeout.
+#
+# The reason that the inferior call never completes is that a second
+# thread, on which the inferior call relies, either hits a breakpoint
+# (when OTHER_THREAD_BP is true), or crashes (when OTHER_THREAD_BP is
+# false).
+proc run_test { target_async target_non_stop other_thread_bp } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if {![runto_main]} {
+	fail "run to main"
+	return
+    }
+
+    # The default timeout for indirect inferior calls (e.g. inferior
+    # calls for conditional breakpoint expressions) is pretty high.
+    # We don't want the test to take too long, so reduce this.
+    #
+    # However, the test relies on a second thread hitting some event
+    # (either a breakpoint or signal) before this timeout expires.
+    #
+    # There is a chance that on a really slow system this might not
+    # happen, in which case the test might fail.
+    #
+    # However, we still allocate 5 seconds, which feels like it should
+    # be enough time in most cases, but maybe we need to do something
+    # smarter here?  Possibly we could have some initial run where the
+    # inferior doesn't timeout, but does do the same interaction
+    # between threads, we could time that, and use that as the basis
+    # for this timeout.  For now though, we just hope 5 seconds is
+    # enough.
+    gdb_test_no_output "set indirect-call-timeout 5"
+
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (condition_func ())"
+    set bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		    "get number for conditional breakpoint"]
+
+    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
+    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			  "get number for final breakpoint"]
+
+    # The thread performing an inferior call relies on a second
+    # thread.  The second thread will segfault unless it hits a
+    # breakpoint first.  In either case the initial thread will not
+    # complete its inferior call.
+    if { $other_thread_bp } {
+	gdb_breakpoint "${::srcfile}:${::segfault_line}"
+	set segfault_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+				 "get number for segfault breakpoint"]
+    }
+
+    # When non-stop mode is off we get slightly different output from GDB.
+    if { [gdb_is_remote_or_extended_remote_target] && $target_non_stop == "off" } {
+	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" received signal SIGINT, Interrupt\\."
+    } else {
+	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\."
+    }
+
+    gdb_test "continue" \
+	[multi_line \
+	     $stopped_line_pattern \
+	     ".*" \
+	     "Error in testing condition for breakpoint ${bp_num}:" \
+	     "The program being debugged timed out while in a function called from GDB\\." \
+	     "GDB remains in the frame where the timeout occurred\\." \
+	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(condition_func\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."] \
+	"expected timeout waiting for inferior call to complete"
+
+    # Remember that other thread that either crashed (with a segfault)
+    # or hit a breakpoint?  Now that the inferior call has timed out,
+    # if we try to resume then we should see the pending event from
+    # that other thread.
+    if { $other_thread_bp } {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${segfault_bp_num}, do_segfault \[^\r\n\]+:${::segfault_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"] \
+	    "hit the segfault breakpoint"
+    } else {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "Thread ${::decimal} \"infcall-from-bp\" received signal SIGSEGV, Segmentation fault\\." \
+		 "\\\[Switching to Thread \[^\r\n\]+\\\]" \
+		 "${::hex} in do_segfault \\(\\) at \[^\r\n\]+:${::segfault_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"] \
+	    "hit the segfault"
+    }
+}
+
+foreach_with_prefix target_async {"on" "off" } {
+
+    if { $target_async == "off" } {
+	# GDB can't timeout while waiting for a thread if the target
+	# runs with async-mode turned off; once the target is running
+	# GDB is effectively blocked until the target stops for some
+	# reason.
+	continue
+    }
+
+    foreach_with_prefix target_non_stop {"off" "on"} {
+	foreach_with_prefix other_thread_bp { true false } {
+	    run_test $target_async $target_non_stop $other_thread_bp
+	}
+    }
+}
-- 
2.25.4


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

* [PATCHv3 11/13] gdb/remote: avoid SIGINT after calling remote_target::stop
  2023-01-31 17:27   ` [PATCHv3 " Andrew Burgess
                       ` (9 preceding siblings ...)
  2023-01-31 17:27     ` [PATCHv3 10/13] gdb: add timeouts for inferior function calls Andrew Burgess
@ 2023-01-31 17:27     ` Andrew Burgess
  2023-01-31 17:27     ` [PATCHv3 12/13] gdb: introduce unwind-on-timeout setting Andrew Burgess
                       ` (2 subsequent siblings)
  13 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-01-31 17:27 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Currently, if the remote target is not running in non-stop mode, then,
when GDB calls remote_target::stop, we end up sending an interrupt
packet \x03 to the remote target.

If the user interrupts the inferior from the GDB prompt (e.g. by
typing Ctrl-c), then GDB calls remote_target::interrupt, which also
ends up sending the interrupt packet.

The problem here is that both of these mechanisms end up sending the
interrupt packet, which means, when the target stops with a SIGINT,
and this is reported back to GDB, we have no choice but to report this
to the user as a SIGINT stop event.

Now maybe this is the correct thing to do, after all the target has
been stopped with SIGINT.  However, this leads to an unfortunate
change in behaviour when comparing non-stop vs all-stop mode.

When running in non-stop mode, and remote_target::stop is called, the
target will be stopped with a vCont packet, and this stop is then
reported back to GDB as GDB_SIGNAL_0, this will cause GDB to print a
message like:

  Program stopped.

Or:

  Thread NN "binary name" stopped.

In contrast, when non-stop mode is off, we get messages like:

  Program received SIGINT, Segmentation fault.

Or:

  Thread NN "binary name" received SIGINT, Segmentation fault.

In this commit I propose making use of thread_info::stop_requested
within remote.c to know if the stop was triggered by GDB (and the
SIGINT should be hidden) or if the stop was a user interrupt, and the
SIGINT should be printed.

In remote_target::process_stop_reply if the inferior stopped with
SIGINT and the thread_info::stop_requested flag is set, then we change
the stop signal to GDB_SIGNAL_0.

Two of the tests added in the previous commit exposed this issue.  In
the previous commit the tests looked for either of the above
patterns.  In this commit I've updated these tests to only look for
the "stopped" based messages.

This commit is the reason why the previous commit took care to set the
thread_info::stop_requested flag in infcall.c.
---
 gdb/remote.c                                           | 10 ++++++++++
 gdb/testsuite/gdb.base/infcall-timeout.exp             |  9 +--------
 .../gdb.threads/infcall-from-bp-cond-timeout.exp       |  9 +--------
 3 files changed, 12 insertions(+), 16 deletions(-)

diff --git a/gdb/remote.c b/gdb/remote.c
index ba7a7520cb4..604d75b9689 100644
--- a/gdb/remote.c
+++ b/gdb/remote.c
@@ -8275,6 +8275,16 @@ remote_target::process_stop_reply (struct stop_reply *stop_reply,
 	}
       else
 	{
+	  /* If this stop was actually requested by GDB then we can hide
+	     the SIGINT from the user.  */
+	  if (status->kind () == TARGET_WAITKIND_STOPPED
+	      && status->sig () == GDB_SIGNAL_INT)
+	    {
+	      thread_info *thr = find_thread_ptid (this, ptid);
+	      if (thr->stop_requested)
+		status->set_stopped (GDB_SIGNAL_0);
+	    }
+
 	  /* If the target works in all-stop mode, a stop-reply indicates that
 	     all the target's threads stopped.  */
 	  for (thread_info *tp : all_non_exited_threads (this))
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.exp b/gdb/testsuite/gdb.base/infcall-timeout.exp
index a5b0111ed04..bd6b2bfac3e 100644
--- a/gdb/testsuite/gdb.base/infcall-timeout.exp
+++ b/gdb/testsuite/gdb.base/infcall-timeout.exp
@@ -45,16 +45,9 @@ proc_with_prefix run_test { target_async target_non_stop } {
 
     gdb_test_no_output "set direct-call-timeout 5"
 
-    # When non-stop mode is off we get slightly different output from GDB.
-    if { [gdb_is_remote_or_extended_remote_target] && $target_non_stop == "off" } {
-	set stopped_line_pattern "Program received signal SIGINT, Interrupt\\."
-    } else {
-	set stopped_line_pattern "Program stopped\\."
-    }
-
     gdb_test "print function_that_never_returns ()" \
 	[multi_line \
-	     $stopped_line_pattern \
+	     "Program stopped\\." \
 	     ".*" \
 	     "The program being debugged timed out while in a function called from GDB\\." \
 	     "GDB remains in the frame where the timeout occurred\\." \
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
index 3341ff33f19..9ba38e6896a 100644
--- a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
@@ -92,16 +92,9 @@ proc run_test { target_async target_non_stop other_thread_bp } {
 				 "get number for segfault breakpoint"]
     }
 
-    # When non-stop mode is off we get slightly different output from GDB.
-    if { [gdb_is_remote_or_extended_remote_target] && $target_non_stop == "off" } {
-	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" received signal SIGINT, Interrupt\\."
-    } else {
-	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\."
-    }
-
     gdb_test "continue" \
 	[multi_line \
-	     $stopped_line_pattern \
+	     "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\." \
 	     ".*" \
 	     "Error in testing condition for breakpoint ${bp_num}:" \
 	     "The program being debugged timed out while in a function called from GDB\\." \
-- 
2.25.4


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

* [PATCHv3 12/13] gdb: introduce unwind-on-timeout setting
  2023-01-31 17:27   ` [PATCHv3 " Andrew Burgess
                       ` (10 preceding siblings ...)
  2023-01-31 17:27     ` [PATCHv3 11/13] gdb/remote: avoid SIGINT after calling remote_target::stop Andrew Burgess
@ 2023-01-31 17:27     ` Andrew Burgess
  2023-01-31 18:09       ` Eli Zaretskii
  2023-02-16 11:01       ` Aktemur, Tankut Baris
  2023-01-31 17:27     ` [PATCHv3 13/13] gdb: rename unwindonsignal to unwind-on-signal Andrew Burgess
  2023-02-28 16:42     ` [PATCHv4 00/12] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
  13 siblings, 2 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-01-31 17:27 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Now that inferior function calls can timeout (see the recent
introduction of direct-call-timeout and indirect-call-timeout), this
commit adds a new setting unwind-on-timeout.

This new setting is just like the existing unwindonsignal and
unwind-on-terminating-exception, but the new setting will cause GDB to
unwind the stack if an inferior function call times out.

The existing inferior function call timeout tests have been updated to
cover the new setting.
---
 gdb/NEWS                                      |  9 +++
 gdb/doc/gdb.texinfo                           | 33 +++++++---
 gdb/infcall.c                                 | 62 ++++++++++++++++---
 gdb/testsuite/gdb.base/infcall-timeout.exp    | 49 +++++++++++----
 .../infcall-from-bp-cond-timeout.exp          | 55 +++++++++++-----
 5 files changed, 164 insertions(+), 44 deletions(-)

diff --git a/gdb/NEWS b/gdb/NEWS
index 835bf7f8680..9907f802e09 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -56,6 +56,15 @@ show indirect-call-timeout
   ignored, GDB will wait indefinitely for an inferior function to
   complete, unless interrupted by the user using Ctrl-C.
 
+set unwind-on-timeout on|off
+show unwind-on-timeout
+  These commands control whether GDB should unwind the stack when a
+  timeout occurs during an inferior function call.  The default is
+  off, in which case the inferior will remain in the frame where the
+  timeout occurred.  When on, GDB will unwind the stack removing the
+  dummy frame that was added for the inferior call, and restoring the
+  inferior state to how it was before the inferior call started.
+
 * MI changes
 
 ** mi now reports 'no-history' as a stop reason when hitting the end of the
diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index f5d460eb9e5..9ddc01d833f 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -5719,10 +5719,10 @@
 the called function, or the called function may receive a signal
 (e.g.@ a @code{SIGSEGV}) as a result of some undefined behavior.  If
 this happens then @value{GDBN} will stop.  Depending on the settings
-@code{unwindonsignal} and @code{unwind-on-terminating-exception}
-(@pxref{Calling,,Calling Program Functions}) @value{GDBN} may unwind
-the stack back to the breakpoint location, or may leave the program at
-the frame where the stop occurred.
+@code{unwindonsignal}, @code{unwind-on-terminating-exception}, and
+@code{unwind-on-timeout} (@pxref{Calling,,Calling Program Functions})
+@value{GDBN} may unwind the stack back to the breakpoint location, or
+may leave the program at the frame where the stop occurred.
 
 Breakpoint conditions can also be evaluated on the target's side if
 the target supports it.  Instead of evaluating the conditions locally,
@@ -20753,6 +20753,21 @@
 Show the current setting of stack unwinding in the functions called by
 @value{GDBN}.
 
+@item set unwind-on-timeout
+@kindex set unwind-on-timeout
+@cindex unwind stack in called functions when timing out
+@cindex call dummy stack unwinding on timeout.
+Set unwinding of the stack if a function called from @value{GDBN}
+times out.  If set to @code{off} (the default), @value{GDBN} stops in
+the frame where the timeout occurred.  If set to @code{on},
+@value{GDBN} unwinds the stack it created for the call and restores
+the context to what it was before the call.
+
+@item show unwind-on-timeout
+@kindex show unwind-on-timeout
+Show whether @value{GDBN} will unwind the stack if a function called
+from @value{GDBN} times out.
+
 @item set may-call-functions
 @kindex set may-call-functions
 @cindex disabling calling functions in the program
@@ -20784,11 +20799,11 @@
 
 If a called function is interrupted for any reason, including hitting
 a breakpoint, or triggering a watchpoint, and the stack is not unwound
-due to @code{set unwind-on-terminating-exception on} or @code{set
-unwindonsignal on} (@pxref{stack unwind settings}),
-then the dummy-frame, created by @value{GDBN} to facilitate the call
-to the program function, will be visible in the backtrace, for example
-frame @code{#3} in the following backtrace:
+due to @code{set unwind-on-terminating-exception on}, @code{set
+unwind-on-timeout on}, or @code{set unwindonsignal on} (@pxref{stack
+unwind settings}), then the dummy-frame, created by @value{GDBN} to
+facilitate the call to the program function, will be visible in the
+backtrace, for example frame @code{#3} in the following backtrace:
 
 @smallexample
 (@value{GDBP}) backtrace
diff --git a/gdb/infcall.c b/gdb/infcall.c
index 92f49a64e3e..20d63ba4627 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -217,6 +217,27 @@ show_unwind_on_terminating_exception_p (struct ui_file *file, int from_tty,
 	      value);
 }
 
+/* This boolean tells GDB what to do if an inferior function, called from
+   GDB, times out.  If true GDB unwinds the stack and restores the context
+   to what it was before the call.  When false GDB leaves the thread as it
+   is at the point of the timeout.
+
+   The default is to stop in the frame where the time out occurred.  */
+
+static bool unwind_on_timeout_p = false;
+
+/* Implement 'show unwind-on-timeout'.  */
+
+static void
+show_unwind_on_timeout_p (struct ui_file *file, int from_tty,
+			  struct cmd_list_element *c, const char *value)
+{
+  gdb_printf (file,
+	      _("Unwinding of stack if a timeout occurs "
+		"while in a call dummy is %s.\n"),
+	      value);
+}
+
 /* Perform the standard coercions that are specified
    for arguments to be passed to C, Ada or Fortran functions.
 
@@ -1699,14 +1720,27 @@ When the function is done executing, GDB will silently stop."),
 	  /* A timeout results in a signal being sent to the inferior.  */
 	  gdb_assert (stopped_by_random_signal);
 
-	  /* Indentation is weird here.  A later patch is going to move the
-	    following block into an if/else, so I'm leaving the indentation
-	    here to minimise the later patch.
+	  if (unwind_on_timeout_p)
+	    {
+	      /* The user wants the context restored.  */
+
+	      /* We must get back to the frame we were before the
+		 dummy call.  */
+	      dummy_frame_pop (dummy_id, call_thread.get ());
 
-	    Also, the error message used below refers to 'set
-	    unwind-on-timeout' which doesn't exist yet.  This will be added
-	    in a later commit, I'm leaving this in for now to minimise the
-	    churn caused by the commit that adds unwind-on-timeout.  */
+	      /* We also need to restore inferior status to that before the
+		 dummy call.  */
+	      restore_infcall_control_state (inf_status.release ());
+
+	      error (_("\
+The program being debugged timed out while in a function called from GDB.\n\
+GDB has restored the context to what it was before the call.\n\
+To change this behavior use \"set unwind-on-timeout off\".\n\
+Evaluation of the expression containing the function\n\
+(%s) will be abandoned."),
+		     name.c_str ());
+	    }
+	  else
 	    {
 	      /* The user wants to stay in the frame where we stopped
 		 (default).  Discard inferior status, we're not at the same
@@ -1832,6 +1866,20 @@ The default is to unwind the frame."),
 			   show_unwind_on_terminating_exception_p,
 			   &setlist, &showlist);
 
+  add_setshow_boolean_cmd ("unwind-on-timeout", no_class,
+			   &unwind_on_timeout_p, _("\
+Set unwinding of stack if a timeout occurs while in a call dummy."), _("\
+Show unwinding of stack if a timeout occurs while in a call dummy."),
+			   _("\
+The unwind on timeout flag lets the user determine what gdb should do if\n\
+gdb times out while in a function called from gdb.  If set, gdb unwinds\n\
+the stack and restores the context to what it was before the call.  If\n\
+unset, gdb leaves the inferior in the frame where the timeout occurred.\n\
+The default is to stop in the frame where the timeout occurred."),
+			   NULL,
+			   show_unwind_on_timeout_p,
+			   &setlist, &showlist);
+
   add_setshow_uinteger_cmd ("direct-call-timeout", no_class,
 			    &direct_call_timeout, _("\
 Set the timeout, for direct calls to inferior function calls."), _("\
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.exp b/gdb/testsuite/gdb.base/infcall-timeout.exp
index bd6b2bfac3e..a4d9fd6ee61 100644
--- a/gdb/testsuite/gdb.base/infcall-timeout.exp
+++ b/gdb/testsuite/gdb.base/infcall-timeout.exp
@@ -28,7 +28,11 @@ if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
 # the direct-call-timeout, and make an inferior function call that
 # will never return.  GDB should eventually timeout and stop the
 # inferior.
-proc_with_prefix run_test { target_async target_non_stop } {
+#
+# When UNWIND is "off" the inferior wil be left in the frame where the
+# timeout occurs, otherwise, when UNWIND is "on", GDB should unwind
+# back to the frame where the inferior call was made.
+proc_with_prefix run_test { target_async target_non_stop unwind } {
     save_vars { ::GDBFLAGS } {
 	append ::GDBFLAGS \
 	    " -ex \"maint set target-non-stop $target_non_stop\""
@@ -44,19 +48,36 @@ proc_with_prefix run_test { target_async target_non_stop } {
     }
 
     gdb_test_no_output "set direct-call-timeout 5"
+    gdb_test_no_output "set unwind-on-timeout $unwind"
+
+    if { $unwind } {
+	gdb_test "print function_that_never_returns ()" \
+	    [multi_line \
+		 "Program stopped\\." \
+		 ".*" \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB has restored the context to what it was before the call\\." \
+		 "To change this behavior use \"set unwind-on-timeout off\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(function_that_never_returns\\) will be abandoned\\."]
 
-    gdb_test "print function_that_never_returns ()" \
-	[multi_line \
-	     "Program stopped\\." \
-	     ".*" \
-	     "The program being debugged timed out while in a function called from GDB\\." \
-	     "GDB remains in the frame where the timeout occurred\\." \
-	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
-	     "Evaluation of the expression containing the function" \
-	     "\\(function_that_never_returns\\) will be abandoned\\." \
-	     "When the function is done executing, GDB will silently stop\\."]
+	gdb_test "bt" \
+	    "#0\\s+main \\(\\).*"
+    } else {
+	gdb_test "print function_that_never_returns ()" \
+	    [multi_line \
+		 "Program stopped\\." \
+		 ".*" \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB remains in the frame where the timeout occurred\\." \
+		 "To change this behavior use \"set unwind-on-timeout on\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(function_that_never_returns\\) will be abandoned\\." \
+		 "When the function is done executing, GDB will silently stop\\."]
 
-    gdb_test "bt" ".* function_that_never_returns .*<function called from gdb>.*"
+	gdb_test "bt" \
+	    ".* function_that_never_returns .*<function called from gdb>.*"
+    }
 }
 
 foreach_with_prefix target_async { "on" "off" } {
@@ -70,6 +91,8 @@ foreach_with_prefix target_async { "on" "off" } {
     }
 
     foreach_with_prefix target_non_stop { "on" "off" } {
-	run_test $target_async $target_non_stop
+	foreach_with_prefix unwind { "on" "off" } {
+	    run_test $target_async $target_non_stop $unwind
+	}
     }
 }
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
index 9ba38e6896a..847a850673d 100644
--- a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
@@ -41,7 +41,12 @@ set segfault_line [gdb_get_line_number "Segfault here"]
 # thread, on which the inferior call relies, either hits a breakpoint
 # (when OTHER_THREAD_BP is true), or crashes (when OTHER_THREAD_BP is
 # false).
-proc run_test { target_async target_non_stop other_thread_bp } {
+#
+# When UNWIND is "on" GDB will unwind the thread which performed the
+# inferior function call back to the state where the inferior call was
+# made (when the inferior call times out).  Otherwise, when UNWIND is
+# "off", the inferior is left in the frame where the timeout occurred.
+proc run_test { target_async target_non_stop other_thread_bp unwind } {
     save_vars { ::GDBFLAGS } {
 	append ::GDBFLAGS " -ex \"maint set target-non-stop $target_non_stop\""
 	append ::GDBFLAGS " -ex \"maintenance set target-async ${target_async}\""
@@ -72,6 +77,7 @@ proc run_test { target_async target_non_stop other_thread_bp } {
     # for this timeout.  For now though, we just hope 5 seconds is
     # enough.
     gdb_test_no_output "set indirect-call-timeout 5"
+    gdb_test_no_output "set unwind-on-timeout $unwind"
 
     gdb_breakpoint \
 	"${::srcfile}:${::cond_bp_line} if (condition_func ())"
@@ -92,18 +98,35 @@ proc run_test { target_async target_non_stop other_thread_bp } {
 				 "get number for segfault breakpoint"]
     }
 
-    gdb_test "continue" \
-	[multi_line \
-	     "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\." \
-	     ".*" \
-	     "Error in testing condition for breakpoint ${bp_num}:" \
-	     "The program being debugged timed out while in a function called from GDB\\." \
-	     "GDB remains in the frame where the timeout occurred\\." \
-	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
-	     "Evaluation of the expression containing the function" \
-	     "\\(condition_func\\) will be abandoned\\." \
-	     "When the function is done executing, GDB will silently stop\\."] \
-	"expected timeout waiting for inferior call to complete"
+    if { $unwind } {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\." \
+		 ".*" \
+		 "Error in testing condition for breakpoint ${bp_num}:" \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB has restored the context to what it was before the call\\." \
+		 "To change this behavior use \"set unwind-on-timeout off\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(condition_func\\) will be abandoned\\." \
+		 "" \
+		 "Thread ${::decimal}\[^\r\n\]*hit Breakpoint ${bp_num}, \[^\r\n\]+" \
+		 "\[^\r\n\]+ Conditional breakpoint here\\. \[^\r\n\]+"] \
+	    "expected timeout waiting for inferior call to complete"
+    } else {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\." \
+		 ".*" \
+		 "Error in testing condition for breakpoint ${bp_num}:" \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB remains in the frame where the timeout occurred\\." \
+		 "To change this behavior use \"set unwind-on-timeout on\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(condition_func\\) will be abandoned\\." \
+		 "When the function is done executing, GDB will silently stop\\."] \
+	    "expected timeout waiting for inferior call to complete"
+    }
 
     # Remember that other thread that either crashed (with a segfault)
     # or hit a breakpoint?  Now that the inferior call has timed out,
@@ -142,8 +165,10 @@ foreach_with_prefix target_async {"on" "off" } {
     }
 
     foreach_with_prefix target_non_stop {"off" "on"} {
-	foreach_with_prefix other_thread_bp { true false } {
-	    run_test $target_async $target_non_stop $other_thread_bp
+	foreach_with_prefix unwind {"off" "on"} {
+	    foreach_with_prefix other_thread_bp { true false } {
+		run_test $target_async $target_non_stop $other_thread_bp $unwind
+	    }
 	}
     }
 }
-- 
2.25.4


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

* [PATCHv3 13/13] gdb: rename unwindonsignal to unwind-on-signal
  2023-01-31 17:27   ` [PATCHv3 " Andrew Burgess
                       ` (11 preceding siblings ...)
  2023-01-31 17:27     ` [PATCHv3 12/13] gdb: introduce unwind-on-timeout setting Andrew Burgess
@ 2023-01-31 17:27     ` Andrew Burgess
  2023-01-31 18:12       ` Eli Zaretskii
  2023-02-28 16:42     ` [PATCHv4 00/12] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
  13 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2023-01-31 17:27 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

We now have unwind-on-timeout and unwind-on-terminating-exception, and
then the odd one out unwindonsignal.

I'm not a great fan of these squashed together command names, so in
this commit I propose renaming this to unwind-on-signal.

Obviously I've added the hidden alias unwindonsignal so any existing
GDB scripts will keep working.

There's one test that I've extended to test the alias works, but in
most of the other test scripts I've changed over to use the new name.

The docs are updated to reference the new name.
---
 gdb/NEWS                                      | 11 ++++++
 gdb/doc/gdb.texinfo                           | 16 ++++++---
 gdb/infcall.c                                 | 21 ++++++-----
 gdb/testsuite/gdb.base/callfuncs.exp          |  4 +--
 gdb/testsuite/gdb.base/infcall-failure.exp    |  4 +--
 gdb/testsuite/gdb.base/unwindonsignal.exp     | 36 +++++++++++++------
 gdb/testsuite/gdb.compile/compile-cplus.exp   |  2 +-
 gdb/testsuite/gdb.compile/compile.exp         |  2 +-
 gdb/testsuite/gdb.cp/gdb2495.exp              | 16 ++++-----
 gdb/testsuite/gdb.fortran/function-calls.exp  |  2 +-
 gdb/testsuite/gdb.mi/mi-syn-frame.exp         |  2 +-
 .../infcall-from-bp-cond-simple.exp           |  2 +-
 .../gdb.threads/thread-unwindonsignal.exp     |  8 ++---
 13 files changed, 83 insertions(+), 43 deletions(-)

diff --git a/gdb/NEWS b/gdb/NEWS
index 9907f802e09..cf178102822 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -65,6 +65,17 @@ show unwind-on-timeout
   dummy frame that was added for the inferior call, and restoring the
   inferior state to how it was before the inferior call started.
 
+set unwind-on-signal on|off
+show unwind-on-signal
+  These new commands replaces the existing set/show unwindonsignal.  The
+  old command is maintained as an alias.
+
+* Changed commands
+
+set unwindonsignal on|off
+show unwindonsignal
+  These commands are now aliases for the new set/show unwind-on-signal.
+
 * MI changes
 
 ** mi now reports 'no-history' as a stop reason when hitting the end of the
diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index 9ddc01d833f..9bfa20b1339 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -20707,7 +20707,7 @@
 It is possible for the function you call via the @code{print} or
 @code{call} command to generate a signal (e.g., if there's a bug in
 the function, or if you passed it incorrect arguments).  What happens
-in that case is controlled by the @code{set unwindonsignal} command.
+in that case is controlled by the @code{set unwind-on-signal} command.
 
 Similarly, with a C@t{++} program it is possible for the function you
 call via the @code{print} or @code{call} command to generate an
@@ -20721,7 +20721,8 @@
 
 @anchor{stack unwind settings}
 @table @code
-@item set unwindonsignal
+@item set unwind-on-signal
+@kindex set unwind-on-signal
 @kindex set unwindonsignal
 @cindex unwind stack in called functions
 @cindex call dummy stack unwinding
@@ -20732,11 +20733,18 @@
 default), @value{GDBN} stops in the frame where the signal was
 received.
 
-@item show unwindonsignal
+The command @code{set unwindonsignal} is an alias for this command,
+and is maintained for backward compatibility.
+
+@item show unwind-on-signal
+@kindex show unwind-on-signal
 @kindex show unwindonsignal
 Show the current setting of stack unwinding in the functions called by
 @value{GDBN}.
 
+The command @code{show unwindonsignal} is an alias for this command,
+and is maintained for backward compatibility.
+
 @item set unwind-on-terminating-exception
 @kindex set unwind-on-terminating-exception
 @cindex unwind stack in called functions with unhandled exceptions
@@ -20800,7 +20808,7 @@
 If a called function is interrupted for any reason, including hitting
 a breakpoint, or triggering a watchpoint, and the stack is not unwound
 due to @code{set unwind-on-terminating-exception on}, @code{set
-unwind-on-timeout on}, or @code{set unwindonsignal on} (@pxref{stack
+unwind-on-timeout on}, or @code{set unwind-on-signal on} (@pxref{stack
 unwind settings}), then the dummy-frame, created by @value{GDBN} to
 facilitate the call to the program function, will be visible in the
 backtrace, for example frame @code{#3} in the following backtrace:
diff --git a/gdb/infcall.c b/gdb/infcall.c
index 20d63ba4627..71f93784c69 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -1689,7 +1689,7 @@ When the function is done executing, GDB will silently stop."),
 	      error (_("\
 The program being debugged was signaled while in a function called from GDB.\n\
 GDB has restored the context to what it was before the call.\n\
-To change this behavior use \"set unwindonsignal off\".\n\
+To change this behavior use \"set unwind-on-signal off\".\n\
 Evaluation of the expression containing the function\n\
 (%s) will be abandoned."),
 		     name.c_str ());
@@ -1707,7 +1707,7 @@ Evaluation of the expression containing the function\n\
 	      error (_("\
 The program being debugged was signaled while in a function called from GDB.\n\
 GDB remains in the frame where the signal was received.\n\
-To change this behavior use \"set unwindonsignal on\".\n\
+To change this behavior use \"set unwind-on-signal on\".\n\
 Evaluation of the expression containing the function\n\
 (%s) will be abandoned.\n\
 When the function is done executing, GDB will silently stop."),
@@ -1839,17 +1839,22 @@ The default is to perform the conversion."),
 			   show_coerce_float_to_double_p,
 			   &setlist, &showlist);
 
-  add_setshow_boolean_cmd ("unwindonsignal", no_class,
-			   &unwind_on_signal_p, _("\
+  set_show_commands setshow_unwind_on_signal_cmds
+    = add_setshow_boolean_cmd ("unwind-on-signal", no_class,
+			       &unwind_on_signal_p, _("\
 Set unwinding of stack if a signal is received while in a call dummy."), _("\
 Show unwinding of stack if a signal is received while in a call dummy."), _("\
-The unwindonsignal lets the user determine what gdb should do if a signal\n\
+The unwind-on-signal lets the user determine what gdb should do if a signal\n\
 is received while in a function called from gdb (call dummy).  If set, gdb\n\
 unwinds the stack and restore the context to what as it was before the call.\n\
 The default is to stop in the frame where the signal was received."),
-			   NULL,
-			   show_unwind_on_signal_p,
-			   &setlist, &showlist);
+			       NULL,
+			       show_unwind_on_signal_p,
+			       &setlist, &showlist);
+  add_alias_cmd ("unwindonsignal", setshow_unwind_on_signal_cmds.set,
+		 no_class, 1, &setlist);
+  add_alias_cmd ("unwindonsignal", setshow_unwind_on_signal_cmds.show,
+		 no_class, 1, &showlist);
 
   add_setshow_boolean_cmd ("unwind-on-terminating-exception", no_class,
 			   &unwind_on_terminating_exception_p, _("\
diff --git a/gdb/testsuite/gdb.base/callfuncs.exp b/gdb/testsuite/gdb.base/callfuncs.exp
index 9bbf108ac0e..0a1a9bd9391 100644
--- a/gdb/testsuite/gdb.base/callfuncs.exp
+++ b/gdb/testsuite/gdb.base/callfuncs.exp
@@ -49,7 +49,7 @@ proc do_function_calls {prototypes} {
 
     # If any of these calls segv we don't want to affect subsequent tests.
     # E.g., we want to ensure register values are restored.
-    gdb_test_no_output "set unwindonsignal on"
+    gdb_test_no_output "set unwind-on-signal on"
 
     gdb_test "p t_char_values(0,0)" " = 0"
     gdb_test "p t_char_values('a','b')" " = 1"
@@ -240,7 +240,7 @@ proc do_function_calls {prototypes} {
     	"call inferior func with struct - returns char *"
 
     # Restore default value.
-    gdb_test_no_output "set unwindonsignal off"
+    gdb_test_no_output "set unwind-on-signal off"
 }
 
 # Procedure to get current content of all registers.
diff --git a/gdb/testsuite/gdb.base/infcall-failure.exp b/gdb/testsuite/gdb.base/infcall-failure.exp
index 5ad179a089d..e2e71649dac 100644
--- a/gdb/testsuite/gdb.base/infcall-failure.exp
+++ b/gdb/testsuite/gdb.base/infcall-failure.exp
@@ -137,7 +137,7 @@ proc_with_prefix run_cond_hits_segfault_test { async_p non_stop_p } {
 	     "Error in testing condition for breakpoint ${bp_1_num}:" \
 	     "The program being debugged was signaled while in a function called from GDB\\." \
 	     "GDB remains in the frame where the signal was received\\." \
-	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "To change this behavior use \"set unwind-on-signal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(func_segfault\\) will be abandoned\\." \
 	     "When the function is done executing, GDB will silently stop\\."]
@@ -166,7 +166,7 @@ proc_with_prefix run_call_hits_segfault_test { async_p non_stop_p } {
 	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
 	     "The program being debugged was signaled while in a function called from GDB\\." \
 	     "GDB remains in the frame where the signal was received\\." \
-	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "To change this behavior use \"set unwind-on-signal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(func_segfault\\) will be abandoned\\." \
 	     "When the function is done executing, GDB will silently stop\\."]
diff --git a/gdb/testsuite/gdb.base/unwindonsignal.exp b/gdb/testsuite/gdb.base/unwindonsignal.exp
index d10d1fe244d..c17b5742ea8 100644
--- a/gdb/testsuite/gdb.base/unwindonsignal.exp
+++ b/gdb/testsuite/gdb.base/unwindonsignal.exp
@@ -40,34 +40,50 @@ gdb_test "break stop_here" "Breakpoint \[0-9\]* at .*"
 gdb_test "continue" "Continuing.*Breakpoint \[0-9\]*, stop_here.*" \
     "continue to breakpoint at stop_here"
 
-# Turn on unwindonsignal.
-gdb_test_no_output "set unwindonsignal on" \
-	"setting unwindonsignal"
+# Turn on unwind-on-signal.
+gdb_test_no_output "set unwind-on-signal on" \
+	"setting unwind-on-signal"
 
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
 	"Unwinding of stack .* is on." \
-	"showing unwindonsignal"
+	"showing unwind-on-signal"
+
+# For backward compatibility we maintain a 'unwindonsignal' alias for
+# 'unwind-on-signal', check it now.
+gdb_test "show unwindonsignal" \
+    "Unwinding of stack .* is on\\." \
+    "showing unwindonsignal alias"
+
+gdb_test_no_output "set unwindonsignal off" \
+    "setting unwindonsignal alias to off"
+
+gdb_test "show unwind-on-signal" \
+    "Unwinding of stack .* is off\\." \
+    "showing unwind-on-signal after setting via alias"
+
+gdb_test_no_output "set unwindonsignal on" \
+    "setting unwindonsignal alias to on"
 
 # Call function (causing the program to get a signal), and see if gdb handles
 # it properly.
 if {[gdb_test "call gen_signal ()"  \
 	 "\[\r\n\]*The program being debugged was signaled.*" \
-	 "unwindonsignal, inferior function call signaled"] != 0} {
+	 "inferior function call signaled"] != 0} {
     return 0
 }
 
 # Verify the stack got unwound.
 gdb_test "bt" \
     "#0 *\[x0-9a-f in\]*stop_here \\(.*\\) at .*#1 *\[x0-9a-f in\]*main \\(.*\\) at .*" \
-	"unwindonsignal, stack unwound"
+	"stack unwound"
 
 # Verify the dummy frame got removed from dummy_frame_stack.
 gdb_test_multiple "maint print dummy-frames" \
-	"unwindonsignal, dummy frame removed" {
+	"unwind-on-signal, dummy frame removed" {
     -re "\[\r\n\]*.*stack=.*code=.*\[\r\n\]+$gdb_prompt $" {
-	fail "unwindonsignal, dummy frame removed"
+	fail $gdb_test_name
     }
     -re "\[\r\n\]+$gdb_prompt $" {
-	pass "unwindonsignal, dummy frame removed"
+	pass $gdb_test_name
     }
 }
diff --git a/gdb/testsuite/gdb.compile/compile-cplus.exp b/gdb/testsuite/gdb.compile/compile-cplus.exp
index 489236a8b49..3bb4fa17284 100644
--- a/gdb/testsuite/gdb.compile/compile-cplus.exp
+++ b/gdb/testsuite/gdb.compile/compile-cplus.exp
@@ -129,7 +129,7 @@ gdb_test "return" "\r\n#0  main .*" "return" \
 	 "Make _gdb_expr\\(__gdb_regs\\*\\) return now\\? \\(y or n\\) " "y"
 gdb_test "info sym $infcall_pc" "\r\nNo symbol matches .*" "info sym not found"
 
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 gdb_test "compile code *(volatile int *) 0 = 0;" \
     "The program being debugged was signaled while in a function called from GDB\\.\r\nGDB has restored the context to what it was before the call\\.\r\n.*" \
     "compile code segfault second"
diff --git a/gdb/testsuite/gdb.compile/compile.exp b/gdb/testsuite/gdb.compile/compile.exp
index f3d87cd2605..8822aab2e81 100644
--- a/gdb/testsuite/gdb.compile/compile.exp
+++ b/gdb/testsuite/gdb.compile/compile.exp
@@ -159,7 +159,7 @@ gdb_test "return" "\r\n#0  main .*" "return" \
 	 "Make _gdb_expr return now\\? \\(y or n\\) " "y"
 gdb_test "info sym $infcall_pc" "\r\nNo symbol matches .*" "info sym not found"
 
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 gdb_test "compile code *(volatile int *) 0 = 0;" \
     "The program being debugged was signaled while in a function called from GDB\\.\r\nGDB has restored the context to what it was before the call\\.\r\n.*" \
     "compile code segfault second"
diff --git a/gdb/testsuite/gdb.cp/gdb2495.exp b/gdb/testsuite/gdb.cp/gdb2495.exp
index 0cb8bdd0ada..af94d959d83 100644
--- a/gdb/testsuite/gdb.cp/gdb2495.exp
+++ b/gdb/testsuite/gdb.cp/gdb2495.exp
@@ -104,29 +104,29 @@ if {![runto_main]} {
 # behaviour; it should not.  Test both on and off states.
 
 # Turn on unwind on signal behaviour.
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 
 # Check that it is turned on.
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
     "signal is received while in a call dummy is on.*" \
     "turn on unwind on signal"
 
 # Check to see if new behaviour interferes with
 # normal signal handling in inferior function calls.
 gdb_test "p exceptions.raise_signal(1)" \
-    "To change this behavior use \"set unwindonsignal off\".*" \
-    "check for unwindonsignal off message"
+    "To change this behavior use \"set unwind-on-signal off\".*" \
+    "check for unwind-on-signal off message"
 
 # And reverse - turn off again.
-gdb_test_no_output "set unwindonsignal off"
+gdb_test_no_output "set unwind-on-signal off"
 
 # Check that it is actually turned off.
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
     "signal is received while in a call dummy is off.*" \
     "turn off unwind on signal"
 
 # Check to see if new behaviour interferes with
 # normal signal handling in inferior function calls.
 gdb_test "p exceptions.raise_signal(1)" \
-    "To change this behavior use \"set unwindonsignal on\".*" \
-    "check for unwindonsignal on message"
+    "To change this behavior use \"set unwind-on-signal on\".*" \
+    "check for unwind-on-signal on message"
diff --git a/gdb/testsuite/gdb.fortran/function-calls.exp b/gdb/testsuite/gdb.fortran/function-calls.exp
index f9a1efc241f..c4d1f232576 100644
--- a/gdb/testsuite/gdb.fortran/function-calls.exp
+++ b/gdb/testsuite/gdb.fortran/function-calls.exp
@@ -44,7 +44,7 @@ if {![runto [gdb_get_line_number "post_init"]]} {
 }
 
 # Use inspired by gdb.base/callfuncs.exp.
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 
 # Baseline: function and subroutine call with no arguments.
 gdb_test "p no_arg()" " = .TRUE."
diff --git a/gdb/testsuite/gdb.mi/mi-syn-frame.exp b/gdb/testsuite/gdb.mi/mi-syn-frame.exp
index 5b3e60f4f34..f026746931d 100644
--- a/gdb/testsuite/gdb.mi/mi-syn-frame.exp
+++ b/gdb/testsuite/gdb.mi/mi-syn-frame.exp
@@ -97,7 +97,7 @@ mi_gdb_test "409-stack-list-frames 0 0" \
 # 
 
 mi_gdb_test "410-data-evaluate-expression bar()" \
-  ".*410\\^error,msg=\"The program being debugged was signaled while in a function called from GDB.\\\\nGDB remains in the frame where the signal was received.\\\\nTo change this behavior use \\\\\"set unwindonsignal on\\\\\".\\\\nEvaluation of the expression containing the function\\\\n\\(bar\\) will be abandoned.\\\\nWhen the function is done executing, GDB will silently stop.\"" \
+  ".*410\\^error,msg=\"The program being debugged was signaled while in a function called from GDB.\\\\nGDB remains in the frame where the signal was received.\\\\nTo change this behavior use \\\\\"set unwind-on-signal on\\\\\".\\\\nEvaluation of the expression containing the function\\\\n\\(bar\\) will be abandoned.\\\\nWhen the function is done executing, GDB will silently stop.\"" \
   "call inferior function which raises exception"
 
 mi_gdb_test "411-stack-list-frames" "411\\^done,stack=\\\[frame=\{level=\"0\",addr=\"$hex\",func=\"bar\",file=\".*mi-syn-frame.c\",fullname=\"${fullname_syntax}${srcfile}\",line=\"$decimal\",arch=\"$any\"},frame=\{level=\"1\",addr=\"$hex\",func=\"<function called from gdb>\"\},frame=\{level=\"2\",addr=\"$hex\",func=\"main\",file=\".*mi-syn-frame.c\",fullname=\"${fullname_syntax}${srcfile}\",line=\"$decimal\",arch=\"$any\"}.*\\\]" "backtrace from inferior function at exception"
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
index a101abbfe9b..157d56f7009 100644
--- a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
@@ -174,7 +174,7 @@ proc_with_prefix run_bp_cond_segfaults { target_async target_non_stop } {
 	     "Error in testing condition for breakpoint ${bp_1_num}:" \
 	     "The program being debugged was signaled while in a function called from GDB\\." \
 	     "GDB remains in the frame where the signal was received\\." \
-	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "To change this behavior use \"set unwind-on-signal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(function_that_segfaults\\) will be abandoned\\." \
 	     "When the function is done executing, GDB will silently stop\\."]
diff --git a/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp b/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp
index b3e3288ba69..636e6539bda 100644
--- a/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp
+++ b/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp
@@ -13,7 +13,7 @@
 # You should have received a copy of the GNU General Public License
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-# Test use of unwindonsignal when a hand function call that gets interrupted
+# Test use of unwind-on-signal when a hand function call that gets interrupted
 # by a signal in another thread.
 
 set NR_THREADS 4
@@ -52,12 +52,12 @@ gdb_test "continue" \
 # We want the main thread (hand_call_with_signal) and
 # thread 1 (sigabrt_handler) to both run.
 
-# Do turn on unwindonsignal.
+# Do turn on unwind-on-signal.
 # We want to test gdb handling of the current thread changing when
 # unwindonsignal is in effect.
-gdb_test_no_output "set unwindonsignal on" \
+gdb_test_no_output "set unwind-on-signal on" \
 	"setting unwindonsignal"
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
 	"Unwinding of stack .* is on." \
 	"showing unwindonsignal"
 
-- 
2.25.4


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

* Re: [PATCHv3 02/13] gdb/doc: extend the documentation for conditional breakpoints
  2023-01-31 17:27     ` [PATCHv3 02/13] gdb/doc: extend the documentation for conditional breakpoints Andrew Burgess
@ 2023-01-31 18:07       ` Eli Zaretskii
  2023-02-01 17:47         ` Andrew Burgess
  0 siblings, 1 reply; 202+ messages in thread
From: Eli Zaretskii @ 2023-01-31 18:07 UTC (permalink / raw)
  To: Andrew Burgess; +Cc: gdb-patches

> Cc: Andrew Burgess <aburgess@redhat.com>
> Date: Tue, 31 Jan 2023 17:27:07 +0000
> From: Andrew Burgess via Gdb-patches <gdb-patches@sourceware.org>
> 
> +If a breakpoint condition calls a function in your program, then it is
> +possible that your program could stop for some reason while in the
> +called function.  For example, @value{GDBN} might hit a breakpoint in
> +the called function, or the called function may receive a signal
> +(e.g.@ a @code{SIGSEGV}) as a result of some undefined behavior.  If
> +this happens then @value{GDBN} will stop.  Depending on the settings
> +@code{unwindonsignal} and @code{unwind-on-terminating-exception}
> +(@pxref{Calling,,Calling Program Functions}) @value{GDBN} may unwind
> +the stack back to the breakpoint location, or may leave the program at
> +the frame where the stop occurred.

This is okay, but should we perhaps tell the reader how to deal with
these calamities?  I presume there's something to say, otherwise why
do we describe these situations?

Thanks.

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

* Re: [PATCHv3 12/13] gdb: introduce unwind-on-timeout setting
  2023-01-31 17:27     ` [PATCHv3 12/13] gdb: introduce unwind-on-timeout setting Andrew Burgess
@ 2023-01-31 18:09       ` Eli Zaretskii
  2023-02-16 11:01       ` Aktemur, Tankut Baris
  1 sibling, 0 replies; 202+ messages in thread
From: Eli Zaretskii @ 2023-01-31 18:09 UTC (permalink / raw)
  To: Andrew Burgess; +Cc: gdb-patches

> Cc: Andrew Burgess <aburgess@redhat.com>
> Date: Tue, 31 Jan 2023 17:27:17 +0000
> From: Andrew Burgess via Gdb-patches <gdb-patches@sourceware.org>
> 
> Now that inferior function calls can timeout (see the recent
> introduction of direct-call-timeout and indirect-call-timeout), this
> commit adds a new setting unwind-on-timeout.
> 
> This new setting is just like the existing unwindonsignal and
> unwind-on-terminating-exception, but the new setting will cause GDB to
> unwind the stack if an inferior function call times out.
> 
> The existing inferior function call timeout tests have been updated to
> cover the new setting.
> ---
>  gdb/NEWS                                      |  9 +++
>  gdb/doc/gdb.texinfo                           | 33 +++++++---
>  gdb/infcall.c                                 | 62 ++++++++++++++++---
>  gdb/testsuite/gdb.base/infcall-timeout.exp    | 49 +++++++++++----
>  .../infcall-from-bp-cond-timeout.exp          | 55 +++++++++++-----
>  5 files changed, 164 insertions(+), 44 deletions(-)

OK for the documentation parts, thanks.

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

* Re: [PATCHv3 10/13] gdb: add timeouts for inferior function calls
  2023-01-31 17:27     ` [PATCHv3 10/13] gdb: add timeouts for inferior function calls Andrew Burgess
@ 2023-01-31 18:11       ` Eli Zaretskii
  2023-02-01 17:50         ` Andrew Burgess
  2023-02-16 10:53       ` Aktemur, Tankut Baris
  1 sibling, 1 reply; 202+ messages in thread
From: Eli Zaretskii @ 2023-01-31 18:11 UTC (permalink / raw)
  To: Andrew Burgess; +Cc: gdb-patches

> Cc: Andrew Burgess <aburgess@redhat.com>
> Date: Tue, 31 Jan 2023 17:27:15 +0000
> From: Andrew Burgess via Gdb-patches <gdb-patches@sourceware.org>
> 
>  gdb/NEWS                                      |  18 ++
>  gdb/doc/gdb.texinfo                           |  66 ++++++
>  gdb/infcall.c                                 | 221 +++++++++++++++++-
>  gdb/testsuite/gdb.base/help.exp               |   2 +-
>  gdb/testsuite/gdb.base/infcall-timeout.c      |  36 +++
>  gdb/testsuite/gdb.base/infcall-timeout.exp    |  82 +++++++
>  .../infcall-from-bp-cond-timeout.c            | 169 ++++++++++++++
>  .../infcall-from-bp-cond-timeout.exp          | 156 +++++++++++++
>  8 files changed, 745 insertions(+), 5 deletions(-)
>  create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.c
>  create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.exp
>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp

The documentation parts were already approved, right?

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

* Re: [PATCHv3 13/13] gdb: rename unwindonsignal to unwind-on-signal
  2023-01-31 17:27     ` [PATCHv3 13/13] gdb: rename unwindonsignal to unwind-on-signal Andrew Burgess
@ 2023-01-31 18:12       ` Eli Zaretskii
  0 siblings, 0 replies; 202+ messages in thread
From: Eli Zaretskii @ 2023-01-31 18:12 UTC (permalink / raw)
  To: Andrew Burgess; +Cc: gdb-patches

> Cc: Andrew Burgess <aburgess@redhat.com>
> Date: Tue, 31 Jan 2023 17:27:18 +0000
> From: Andrew Burgess via Gdb-patches <gdb-patches@sourceware.org>
> 
> We now have unwind-on-timeout and unwind-on-terminating-exception, and
> then the odd one out unwindonsignal.
> 
> I'm not a great fan of these squashed together command names, so in
> this commit I propose renaming this to unwind-on-signal.
> 
> Obviously I've added the hidden alias unwindonsignal so any existing
> GDB scripts will keep working.
> 
> There's one test that I've extended to test the alias works, but in
> most of the other test scripts I've changed over to use the new name.
> 
> The docs are updated to reference the new name.
> ---
>  gdb/NEWS                                      | 11 ++++++
>  gdb/doc/gdb.texinfo                           | 16 ++++++---
>  gdb/infcall.c                                 | 21 ++++++-----
>  gdb/testsuite/gdb.base/callfuncs.exp          |  4 +--
>  gdb/testsuite/gdb.base/infcall-failure.exp    |  4 +--
>  gdb/testsuite/gdb.base/unwindonsignal.exp     | 36 +++++++++++++------
>  gdb/testsuite/gdb.compile/compile-cplus.exp   |  2 +-
>  gdb/testsuite/gdb.compile/compile.exp         |  2 +-
>  gdb/testsuite/gdb.cp/gdb2495.exp              | 16 ++++-----
>  gdb/testsuite/gdb.fortran/function-calls.exp  |  2 +-
>  gdb/testsuite/gdb.mi/mi-syn-frame.exp         |  2 +-
>  .../infcall-from-bp-cond-simple.exp           |  2 +-
>  .../gdb.threads/thread-unwindonsignal.exp     |  8 ++---
>  13 files changed, 83 insertions(+), 43 deletions(-)

Since this is just a mechanical renaming, it is obviously okay in the
documentation parts.

Thanks.

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

* Re: [PATCHv3 02/13] gdb/doc: extend the documentation for conditional breakpoints
  2023-01-31 18:07       ` Eli Zaretskii
@ 2023-02-01 17:47         ` Andrew Burgess
  2023-02-01 18:25           ` Eli Zaretskii
  0 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2023-02-01 17:47 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: gdb-patches

Eli Zaretskii <eliz@gnu.org> writes:

>> Cc: Andrew Burgess <aburgess@redhat.com>
>> Date: Tue, 31 Jan 2023 17:27:07 +0000
>> From: Andrew Burgess via Gdb-patches <gdb-patches@sourceware.org>
>> 
>> +If a breakpoint condition calls a function in your program, then it is
>> +possible that your program could stop for some reason while in the
>> +called function.  For example, @value{GDBN} might hit a breakpoint in
>> +the called function, or the called function may receive a signal
>> +(e.g.@ a @code{SIGSEGV}) as a result of some undefined behavior.  If
>> +this happens then @value{GDBN} will stop.  Depending on the settings
>> +@code{unwindonsignal} and @code{unwind-on-terminating-exception}
>> +(@pxref{Calling,,Calling Program Functions}) @value{GDBN} may unwind
>> +the stack back to the breakpoint location, or may leave the program at
>> +the frame where the stop occurred.
>
> This is okay, but should we perhaps tell the reader how to deal with
> these calamities?  I presume there's something to say, otherwise why
> do we describe these situations?

How about if I add an extra sentence at the end of the paragraph to say
that it is possible to continue debugging from the point where GDB
stops, like this (new text starts "If @value{GDBN} remains in the..."):

  If a breakpoint condition calls a function in your program, then it is
  possible that your program could stop for some reason while in the
  called function.  For example, @value{GDBN} might hit a breakpoint in
  the called function, or the called function may receive a signal
  (e.g.@ a @code{SIGSEGV}) as a result of some undefined behavior.  If
  this happens then @value{GDBN} will stop.  Depending on the settings
  @code{unwindonsignal} and @code{unwind-on-terminating-exception}
  (@pxref{Calling,,Calling Program Functions}) @value{GDBN} may unwind
  the stack back to the breakpoint location, or may leave the program at
  the frame where the stop occurred.  If @value{GDBN} remains in the
  frame where the stop occurred then you can debug the inferior from
  this point to understand why the called function failed.

Does this address your concerns?

Thanks,
Andrew


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

* Re: [PATCHv3 10/13] gdb: add timeouts for inferior function calls
  2023-01-31 18:11       ` Eli Zaretskii
@ 2023-02-01 17:50         ` Andrew Burgess
  2023-02-01 18:29           ` Eli Zaretskii
  0 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2023-02-01 17:50 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: gdb-patches

Eli Zaretskii <eliz@gnu.org> writes:

>> Cc: Andrew Burgess <aburgess@redhat.com>
>> Date: Tue, 31 Jan 2023 17:27:15 +0000
>> From: Andrew Burgess via Gdb-patches <gdb-patches@sourceware.org>
>> 
>>  gdb/NEWS                                      |  18 ++
>>  gdb/doc/gdb.texinfo                           |  66 ++++++
>>  gdb/infcall.c                                 | 221 +++++++++++++++++-
>>  gdb/testsuite/gdb.base/help.exp               |   2 +-
>>  gdb/testsuite/gdb.base/infcall-timeout.c      |  36 +++
>>  gdb/testsuite/gdb.base/infcall-timeout.exp    |  82 +++++++
>>  .../infcall-from-bp-cond-timeout.c            | 169 ++++++++++++++
>>  .../infcall-from-bp-cond-timeout.exp          | 156 +++++++++++++
>>  8 files changed, 745 insertions(+), 5 deletions(-)
>>  create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.c
>>  create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.exp
>>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
>>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
>
> The documentation parts were already approved, right?

Yeah, sorry for repeatedly spamming your inbox with this stuff.  This
patch can't be merged until the earlier ones have landed, and some of
them had significant changes.

Is there a good way that I can tag patches to let you know that a
particular patches doesn't need a doc re-review?  I do always feel
pretty guilty when I see you've re-looked at a patch you already
approved.

Thanks,
Andrew


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

* Re: [PATCHv3 02/13] gdb/doc: extend the documentation for conditional breakpoints
  2023-02-01 17:47         ` Andrew Burgess
@ 2023-02-01 18:25           ` Eli Zaretskii
  2023-02-02 13:34             ` Andrew Burgess
  0 siblings, 1 reply; 202+ messages in thread
From: Eli Zaretskii @ 2023-02-01 18:25 UTC (permalink / raw)
  To: Andrew Burgess; +Cc: gdb-patches

> From: Andrew Burgess <aburgess@redhat.com>
> Cc: gdb-patches@sourceware.org
> Date: Wed, 01 Feb 2023 17:47:52 +0000
> 
>   If a breakpoint condition calls a function in your program, then it is
>   possible that your program could stop for some reason while in the
>   called function.  For example, @value{GDBN} might hit a breakpoint in
>   the called function, or the called function may receive a signal
>   (e.g.@ a @code{SIGSEGV}) as a result of some undefined behavior.  If
>   this happens then @value{GDBN} will stop.  Depending on the settings
>   @code{unwindonsignal} and @code{unwind-on-terminating-exception}
>   (@pxref{Calling,,Calling Program Functions}) @value{GDBN} may unwind
>   the stack back to the breakpoint location, or may leave the program at
>   the frame where the stop occurred.  If @value{GDBN} remains in the
>   frame where the stop occurred then you can debug the inferior from
>   this point to understand why the called function failed.
> 
> Does this address your concerns?

Some.  But I also think that the text should more explicitly explain
that the various values of the unwind-* options are there precisely to
tailor what happens to the needs of the debugging session.  The text
is now written as purely descriptional: if you set the option this
way, what will happen is so-and-so.  It would be better, I think, to
turn the table and say: if you want to debug the called function when
this happen, set the option to this value; OTOH if you want ignore
that and continue debugging the inferior, set the option to that other
value.  Does this make sense?

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

* Re: [PATCHv3 10/13] gdb: add timeouts for inferior function calls
  2023-02-01 17:50         ` Andrew Burgess
@ 2023-02-01 18:29           ` Eli Zaretskii
  0 siblings, 0 replies; 202+ messages in thread
From: Eli Zaretskii @ 2023-02-01 18:29 UTC (permalink / raw)
  To: Andrew Burgess; +Cc: gdb-patches

> From: Andrew Burgess <aburgess@redhat.com>
> Cc: gdb-patches@sourceware.org
> Date: Wed, 01 Feb 2023 17:50:05 +0000
> 
> Eli Zaretskii <eliz@gnu.org> writes:
> 
> >> Cc: Andrew Burgess <aburgess@redhat.com>
> >> Date: Tue, 31 Jan 2023 17:27:15 +0000
> >> From: Andrew Burgess via Gdb-patches <gdb-patches@sourceware.org>
> >> 
> >>  gdb/NEWS                                      |  18 ++
> >>  gdb/doc/gdb.texinfo                           |  66 ++++++
> >>  gdb/infcall.c                                 | 221 +++++++++++++++++-
> >>  gdb/testsuite/gdb.base/help.exp               |   2 +-
> >>  gdb/testsuite/gdb.base/infcall-timeout.c      |  36 +++
> >>  gdb/testsuite/gdb.base/infcall-timeout.exp    |  82 +++++++
> >>  .../infcall-from-bp-cond-timeout.c            | 169 ++++++++++++++
> >>  .../infcall-from-bp-cond-timeout.exp          | 156 +++++++++++++
> >>  8 files changed, 745 insertions(+), 5 deletions(-)
> >>  create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.c
> >>  create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.exp
> >>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
> >>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
> >
> > The documentation parts were already approved, right?
> 
> Yeah, sorry for repeatedly spamming your inbox with this stuff.  This
> patch can't be merged until the earlier ones have landed, and some of
> them had significant changes.
> 
> Is there a good way that I can tag patches to let you know that a
> particular patches doesn't need a doc re-review?  I do always feel
> pretty guilty when I see you've re-looked at a patch you already
> approved.

Just say early enough in the body of the email that the documentation
parts were already approved.

TIA

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

* Re: [PATCHv3 02/13] gdb/doc: extend the documentation for conditional breakpoints
  2023-02-01 18:25           ` Eli Zaretskii
@ 2023-02-02 13:34             ` Andrew Burgess
  0 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-02-02 13:34 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: gdb-patches

Eli Zaretskii <eliz@gnu.org> writes:

>> From: Andrew Burgess <aburgess@redhat.com>
>> Cc: gdb-patches@sourceware.org
>> Date: Wed, 01 Feb 2023 17:47:52 +0000
>> 
>>   If a breakpoint condition calls a function in your program, then it is
>>   possible that your program could stop for some reason while in the
>>   called function.  For example, @value{GDBN} might hit a breakpoint in
>>   the called function, or the called function may receive a signal
>>   (e.g.@ a @code{SIGSEGV}) as a result of some undefined behavior.  If
>>   this happens then @value{GDBN} will stop.  Depending on the settings
>>   @code{unwindonsignal} and @code{unwind-on-terminating-exception}
>>   (@pxref{Calling,,Calling Program Functions}) @value{GDBN} may unwind
>>   the stack back to the breakpoint location, or may leave the program at
>>   the frame where the stop occurred.  If @value{GDBN} remains in the
>>   frame where the stop occurred then you can debug the inferior from
>>   this point to understand why the called function failed.
>> 
>> Does this address your concerns?
>
> Some.  But I also think that the text should more explicitly explain
> that the various values of the unwind-* options are there precisely to
> tailor what happens to the needs of the debugging session.  The text
> is now written as purely descriptional: if you set the option this
> way, what will happen is so-and-so.  It would be better, I think, to
> turn the table and say: if you want to debug the called function when
> this happen, set the option to this value; OTOH if you want ignore
> that and continue debugging the inferior, set the option to that other
> value.  Does this make sense?

OK thanks.

I spent some time thinking about what I was trying to say here, and in
the end I'm not convinced I'm actually adding much value with this
change.  I think the previous patch, and the doc changes in later
commits probably contains enough information.

So, for now at least, I'm going to propose dropping just hist patch from
the series.

Thanks,
Andrew


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

* RE: [PATCHv3 03/13] gdb: include breakpoint number in testing condition error message
  2023-01-31 17:27     ` [PATCHv3 03/13] gdb: include breakpoint number in testing condition error message Andrew Burgess
@ 2023-02-16 10:15       ` Aktemur, Tankut Baris
  0 siblings, 0 replies; 202+ messages in thread
From: Aktemur, Tankut Baris @ 2023-02-16 10:15 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

On Tuesday, January 31, 2023 6:27 PM, Andrew Burgess wrote:
> When GDB fails to test the condition of a conditional breakpoint, for
> whatever reason, the error message looks like this:
> 
>   (gdb) break foo if (*(int *) 0) == 1
>   Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
>   (gdb) r
>   Starting program: /tmp/bpcond
>   Error in testing breakpoint condition:
>   Cannot access memory at address 0x0
> 
>   Breakpoint 1, foo () at bpcond.c:11
>   11	  int a = 32;
>   (gdb)
> 
> The line I'm interested in for this commit is this one:
> 
>   Error in testing breakpoint condition:
> 
> In the case above we can figure out that the problematic breakpoint
> was #1 because in the final line of the message GDB reports the stop a
> breakpoint #1.
> 
> However, in the next few patches I plan to change this.  In some cases
> I don't think it makes sense for GDB to report the stop as being at
> breakpoint #1, consider this case:
> 
>   (gdb) list some_func
>   1	int
>   2	some_func ()
>   3	{
>   4	  int *p = 0;
>   5	  return *p;
>   6	}
>   7
>   8	void
>   9	foo ()
>   10	{
>   (gdb) break foo if (some_func ())
>   Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
>   (gdb) r
>   Starting program: /tmp/bpcond
> 
>   Program received signal SIGSEGV, Segmentation fault.
>   0x0000000000401116 in some_func () at bpcond.c:5
>   5	  return *p;
>   Error in testing breakpoint condition:
>   The program being debugged was signaled while in a function called from GDB.
>   GDB remains in the frame where the signal was received.
>   To change this behavior use "set unwindonsignal on".
>   Evaluation of the expression containing the function
>   (some_func) will be abandoned.
>   When the function is done executing, GDB will silently stop.
> 
>   Program received signal SIGSEGV, Segmentation fault.
> 
>   Breakpoint 1, 0x0000000000401116 in some_func () at bpcond.c:5
>   5	  return *p;
>   (gdb)
> 
> Notice that, the final lines of output report the stop as being at
> breakpoint #1, even though we are actually located within some_func.
> 
> I find this behaviour confusing, and propose that this should be
> changed.  However, if I make that change then every reference to
> breakpoint #1 will be lost from the error message.
> 
> So, in this commit, in preparation for the later commits, I propose to
> change the 'Error in testing breakpoint condition:' line to this:
> 
>   Error in testing condition for breakpoint NUMBER:
> 
> where NUMBER will be filled in as appropriate.  Here's the first
> example with the updated error:
> 
>   (gdb) break foo if (*(int *) 0) == 0
>   Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
>   (gdb) r
>   Starting program: /tmp/bpcond
>   Error in testing condition for breakpoint 1:
>   Cannot access memory at address 0x0
> 
>   Breakpoint 1, foo () at bpcond.c:11
>   11	  int a = 32;
>   (gdb)
> 
> The breakpoint number does now appear twice in the output, but I don't
> see that as a negative.
> 
> This commit just changes the one line of the error, and updates the
> few tests that either included the old error in comments, or actually
> checked for the error in the expected output.
> 
> As the only test that checked the line I modified is a Python test,
> I've added a new test that doesn't rely on Python that checks the
> error message in detail.
> 
> While working on the new test, I spotted that it would fail when run
> with native-gdbserver and native-extended-gdbserver target boards.
> This turns out to be due to a gdbserver bug.  To avoid cluttering this
> commit I've added a work around to the new test script so that the
> test passes for the remote boards, in the next few commits I will fix
> gdbserver, and update the test script to remove the work around.
> ---
>  gdb/breakpoint.c                              |   3 +-
>  gdb/testsuite/gdb.base/bp-cond-failure.c      |  30 +++++
>  gdb/testsuite/gdb.base/bp-cond-failure.exp    | 114 ++++++++++++++++++
>  .../gdb.base/catch-signal-siginfo-cond.exp    |   2 +-
>  gdb/testsuite/gdb.base/gnu-ifunc.exp          |   2 +-
>  .../gdb.python/py-finish-breakpoint.exp       |   2 +-
>  6 files changed, 149 insertions(+), 4 deletions(-)
>  create mode 100644 gdb/testsuite/gdb.base/bp-cond-failure.c
>  create mode 100644 gdb/testsuite/gdb.base/bp-cond-failure.exp
> 
> diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
> index 00cc2ab401c..eecaeefed3e 100644
> --- a/gdb/breakpoint.c
> +++ b/gdb/breakpoint.c
> @@ -5542,7 +5542,8 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
>  	  catch (const gdb_exception &ex)
>  	    {
>  	      exception_fprintf (gdb_stderr, ex,
> -				 "Error in testing breakpoint condition:\n");
> +				 "Error in testing condition for breakpoint %d:\n",
> +				 b->number);
>  	    }
>  	}
>        else
> diff --git a/gdb/testsuite/gdb.base/bp-cond-failure.c b/gdb/testsuite/gdb.base/bp-cond-
> failure.c
> new file mode 100644
> index 00000000000..2a9974b47ce
> --- /dev/null
> +++ b/gdb/testsuite/gdb.base/bp-cond-failure.c
> @@ -0,0 +1,30 @@
> +/* Copyright 2022-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/>.  */
> +
> +int
> +foo ()
> +{
> +  return 0;	/* Breakpoint here.  */
> +}
> +
> +int
> +main ()
> +{
> +  int res = foo ();
> +
> +  return res;
> +}
> diff --git a/gdb/testsuite/gdb.base/bp-cond-failure.exp b/gdb/testsuite/gdb.base/bp-cond-
> failure.exp
> new file mode 100644
> index 00000000000..9388b8cf582
> --- /dev/null
> +++ b/gdb/testsuite/gdb.base/bp-cond-failure.exp
> @@ -0,0 +1,114 @@
> +# Copyright 2022-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/>.
> +
> +# Check the format of the error message given when a breakpoint
> +# condition fails.
> +#
> +# In this case the breakpoint condition does not make use of inferior
> +# function calls, instead, the expression used for the breakpoint
> +# condition will throw an error when evaluated.
> +#
> +# We check that the correct breakpoint number appears in the error
> +# message, and that the error is reported at the correct source
> +# location.
> +
> +standard_testfile
> +
> +if { [prepare_for_testing "failed to prepare" ${binfile} "${srcfile}" \
> +	  {debug}] == -1 } {
> +    return
> +}
> +
> +# Run to main so that we connect to the target if using 'target
> +# remote'.  This means that the is_address_zero_readable, and the
> +# 'show breakpoint condition-evaluation' checks below will be
> +# performed with the remote connection in place.
> +if { ![runto_main] } {
> +    fail "run to main"

This fail can be removed.

> +    return -1
> +}
> +
> +# This test relies on reading address zero triggering a SIGSEGV.
> +if { [is_address_zero_readable] } {
> +    return
> +}
> +
> +# Where the breakpoint will be placed.
> +set bp_line [gdb_get_line_number "Breakpoint here"]
> +
> +proc run_test { cond_eval } {
> +    clean_restart ${::binfile}
> +
> +    if { ![runto_main] } {
> +	fail "run to main"

This one, too.

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] 202+ messages in thread

* RE: [PATCHv3 05/13] gdbserver: allow agent expressions to fail with invalid memory access
  2023-01-31 17:27     ` [PATCHv3 05/13] gdbserver: allow agent expressions to fail with invalid memory access Andrew Burgess
@ 2023-02-16 10:29       ` Aktemur, Tankut Baris
  0 siblings, 0 replies; 202+ messages in thread
From: Aktemur, Tankut Baris @ 2023-02-16 10:29 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

On Tuesday, January 31, 2023 6:27 PM, Andrew Burgess wrote:
> This commit extends gdbserver to take account of a failed memory
> access from agent_mem_read, and to return a new eval_result_type
> expr_eval_invalid_memory_access.
> 
> I have only updated the agent_mem_read calls related directly to
> reading memory, I have not updated any of the calls related to
> tracepoint data collection.  This is just because I'm not familiar
> with that area of gdb/gdbserver, and I don't want to break anything,
> so leaving the existing behaviour as it is seems like the safest

"it is" -> "it"

> approach.
> 
> I've then updated gdb.base/bp-cond-failure.exp to test evaluating the
> breakpoints on the target, and have also extended the test so that it
> checks for different sizes of memory access.
> ---
>  gdb/testsuite/gdb.base/bp-cond-failure.exp | 21 +++++++--------------
>  gdbserver/ax.cc                            | 12 ++++++++----
>  gdbserver/ax.h                             |  3 ++-
>  3 files changed, 17 insertions(+), 19 deletions(-)
> 
> diff --git a/gdb/testsuite/gdb.base/bp-cond-failure.exp b/gdb/testsuite/gdb.base/bp-cond-
> failure.exp
> index 9388b8cf582..d67c68c46a1 100644
> --- a/gdb/testsuite/gdb.base/bp-cond-failure.exp
> +++ b/gdb/testsuite/gdb.base/bp-cond-failure.exp
> @@ -48,7 +48,7 @@ if { [is_address_zero_readable] } {
>  # Where the breakpoint will be placed.
>  set bp_line [gdb_get_line_number "Breakpoint here"]
> 
> -proc run_test { cond_eval } {
> +proc run_test { cond_eval access_type } {
>      clean_restart ${::binfile}
> 
>      if { ![runto_main] } {
> @@ -61,7 +61,7 @@ proc run_test { cond_eval } {
>      }
> 
>      # Setup the conditional breakpoint and record its number.
> -    gdb_breakpoint "${::srcfile}:${::bp_line} if (*(int *) 0) == 0"
> +    gdb_breakpoint "${::srcfile}:${::bp_line} if (*(${access_type} *) 0) == 0"
>      set bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*"]
> 
>      gdb_test "continue" \
> @@ -90,16 +90,7 @@ set cond_eval_modes { "auto" }
> 
>  gdb_test_multiple "show breakpoint condition-evaluation" "" {
>      -re -wrap "Breakpoint condition evaluation mode is auto \\(currently target\\)\\." {
> -
> -	## NOTE: Instead of testing with "auto" and "host" in this
> -	## case we only test with "host".  This is because a GDB bug
> -	## prevents the "auto" (a.k.a. target) mode from working.
> -	##
> -	## Don't worry, this will be fixed in a later commit, and this
> -	## comment will be removed at that time.
> -	##
> -	## lappend cond_eval_modes "host"
> -
> +	lappend cond_eval_modes "host"
>  	set cond_eval_modes { "host" }

We do lappend but then set the variable.  Did you mean to remove the second line?

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] 202+ messages in thread

* RE: [PATCHv3 09/13] gdb: fix b/p conditions with infcalls in multi-threaded inferiors
  2023-01-31 17:27     ` [PATCHv3 09/13] gdb: fix b/p conditions with infcalls in multi-threaded inferiors Andrew Burgess
@ 2023-02-16 10:47       ` Aktemur, Tankut Baris
  0 siblings, 0 replies; 202+ messages in thread
From: Aktemur, Tankut Baris @ 2023-02-16 10:47 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches; +Cc: Saiapova, Natalia

On Tuesday, January 31, 2023 6:27 PM, Andrew Burgess wrote:
> This commit fixes bug PR 28942, that is, creating a conditional
> breakpoint in a multi-threaded inferior, where the breakpoint
> condition includes an inferior function call.
...
> diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
> b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
> new file mode 100644
> index 00000000000..fe9aeea97f7
> --- /dev/null
> +++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
> @@ -0,0 +1,175 @@
> +# Copyright 2022-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/>.
> +
> +# Test for conditional breakpoints where the breakpoint condition includes
> +# an inferior function call.
> +#
> +# The tests in this script are testing what happens when an event arrives in
> +# another thread while GDB is waiting for the inferior function call (in the
> +# breakpoint condition) to finish.
> +#
> +# The expectation is that GDB will queue events for other threads and wait
> +# for the inferior function call to complete, if the condition is true, then
> +# the conditional breakpoint should be reported first.  The other thread
> +# event should of course, not get lost, and should be reported as soon as
> +# the user tries to continue the inferior.
> +#
> +# If the conditional breakpoint ends up not being taken (the condition is
> +# false), then the other thread event should be reported immediately.
> +#
> +# This script tests what happens when the other thread event is (a) the
> +# other thread hitting a breakpoint, and (b) the other thread taking a
> +# signal (SIGSEGV in this case).
> +
> +standard_testfile
> +
> +if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
> +	  {debug pthreads}] == -1 } {
> +    return
> +}
> +
> +set cond_bp_line [gdb_get_line_number "First thread breakpoint"]
> +set other_bp_line [gdb_get_line_number "Other thread breakpoint"]
> +set final_bp_line [gdb_get_line_number "Final breakpoint here"]
> +set signal_line [gdb_get_line_number "Signal here"]
> +
> +# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
> +proc start_gdb_and_runto_main { target_async target_non_stop } {
> +    save_vars { ::GDBFLAGS } {
> +	append ::GDBFLAGS \
> +	    " -ex \"maint set target-non-stop $target_non_stop\""
> +	append ::GDBFLAGS \
> +	    " -ex \"maintenance set target-async ${target_async}\""
> +
> +	clean_restart ${::binfile}
> +    }
> +
> +    if { ![runto_main] } {
> +	fail "run to main"

The 'fail' can be removed.  There are other instances in the rest of the patch.

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] 202+ messages in thread

* RE: [PATCHv3 10/13] gdb: add timeouts for inferior function calls
  2023-01-31 17:27     ` [PATCHv3 10/13] gdb: add timeouts for inferior function calls Andrew Burgess
  2023-01-31 18:11       ` Eli Zaretskii
@ 2023-02-16 10:53       ` Aktemur, Tankut Baris
  1 sibling, 0 replies; 202+ messages in thread
From: Aktemur, Tankut Baris @ 2023-02-16 10:53 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

On Tuesday, January 31, 2023 6:27 PM, Andrew Burgess wrote:
> In the previous commits I have been working on improving inferior
> function call support.  One thing that worries me about using inferior
> function calls from a conditional breakpoint is: what happens if the
> inferior function call fails?

Could you please see the comments I had posted for v2 of this patch?
It seems those findings still exist in v3.
https://patchwork.sourceware.org/project/gdb/patch/9008dc2605a09477a5978381c107a33f8b6760a9.1674058360.git.aburgess@redhat.com/#136680

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] 202+ messages in thread

* RE: [PATCHv3 12/13] gdb: introduce unwind-on-timeout setting
  2023-01-31 17:27     ` [PATCHv3 12/13] gdb: introduce unwind-on-timeout setting Andrew Burgess
  2023-01-31 18:09       ` Eli Zaretskii
@ 2023-02-16 11:01       ` Aktemur, Tankut Baris
  1 sibling, 0 replies; 202+ messages in thread
From: Aktemur, Tankut Baris @ 2023-02-16 11:01 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

On Tuesday, January 31, 2023 6:27 PM, Andrew Burgess wrote:
> Now that inferior function calls can timeout (see the recent
> introduction of direct-call-timeout and indirect-call-timeout), this
> commit adds a new setting unwind-on-timeout.
> 
> This new setting is just like the existing unwindonsignal and
> unwind-on-terminating-exception, but the new setting will cause GDB to
> unwind the stack if an inferior function call times out.
> 
> The existing inferior function call timeout tests have been updated to
> cover the new setting.
> ---
>  gdb/NEWS                                      |  9 +++
>  gdb/doc/gdb.texinfo                           | 33 +++++++---
>  gdb/infcall.c                                 | 62 ++++++++++++++++---
>  gdb/testsuite/gdb.base/infcall-timeout.exp    | 49 +++++++++++----
>  .../infcall-from-bp-cond-timeout.exp          | 55 +++++++++++-----
>  5 files changed, 164 insertions(+), 44 deletions(-)
> 
...
> diff --git a/gdb/infcall.c b/gdb/infcall.c
> index 92f49a64e3e..20d63ba4627 100644
> --- a/gdb/infcall.c
> +++ b/gdb/infcall.c
> @@ -217,6 +217,27 @@ show_unwind_on_terminating_exception_p (struct ui_file *file, int
> from_tty,
>  	      value);
>  }
> 
> +/* This boolean tells GDB what to do if an inferior function, called from
> +   GDB, times out.  If true GDB unwinds the stack and restores the context

Nit: comma after "If true".

> +   to what it was before the call.  When false GDB leaves the thread as it

Nit: comma after "When false".

> +   is at the point of the timeout.
> +
> +   The default is to stop in the frame where the time out occurred.  */

"time out" -> "timeout".

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] 202+ messages in thread

* RE: [PATCHv2 00/13] Infcalls from B/P conditions in multi-threaded inferiors
  2023-01-25 15:53     ` Andrew Burgess
@ 2023-02-16 11:09       ` Aktemur, Tankut Baris
  0 siblings, 0 replies; 202+ messages in thread
From: Aktemur, Tankut Baris @ 2023-02-16 11:09 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

On Wednesday, January 25, 2023 4:54 PM, Andrew Burgess wrote:
> Hi!
> 
> Thanks for looking through,  I've pushed the branch to
> users/aburgess/bp-inferior-calls.  I'll go through your feedback and
> make any updates needed and force push this branch.
> 
> Thanks,
> Andrew

Thank you.  I think the branch still contains v2, not v3, but there were only minor
behavioral changes between the two versions.  So, that should be fine.
I built GDB from your branch and played around a bit, including running the newly
added tests.  I didn't notice any problems.  I posted some minor things for some
of the v3 patches.

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] 202+ messages in thread

* [PATCHv4 00/12] Infcalls from B/P conditions in multi-threaded inferiors
  2023-01-31 17:27   ` [PATCHv3 " Andrew Burgess
                       ` (12 preceding siblings ...)
  2023-01-31 17:27     ` [PATCHv3 13/13] gdb: rename unwindonsignal to unwind-on-signal Andrew Burgess
@ 2023-02-28 16:42     ` Andrew Burgess
  2023-02-28 16:42       ` [PATCHv4 01/12] gdb/doc: extended documentation for inferior function calls Andrew Burgess
                         ` (12 more replies)
  13 siblings, 13 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-02-28 16:42 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

In v4:

  - I believe all the docs changes have been reviewed and approved by Eli,

  - Rebased onto current master,

  - Dropped patch #2 from the V3 series,

  - I have addressed all the issues Baris pointed out, including the
    fixes for the patch #9 ('gdb: add timeouts for inferior function
    calls'), which I forgot to do in V3.

In v3:

  - Updates for review feedback, biggest changes in #10 and #11, but
    minor changes to most patches.

In V2:

  - Rebased onto something closer to HEAD of master,

  - Patches #1, #2, #12, and #13 are new in this series,

  - Patches #3 to #9, and #11 are unchanged since their V1 iteration,

  - Patches #10 has changed slightly in implementation since v1, and
    the docs have been significantly updated.

---

Andrew Burgess (12):
  gdb/doc: extended documentation for inferior function calls
  gdb: include breakpoint number in testing condition error message
  gdbserver: allows agent_mem_read to return an error code
  gdbserver: allow agent expressions to fail with invalid memory access
  gdb: avoid repeated signal reporting during failed conditional
    breakpoint
  gdb: don't always print breakpoint location after failed condition
    check
  Revert "gdb: remove unnecessary parameter wait_ptid from
    do_target_wait"
  gdb: fix b/p conditions with infcalls in multi-threaded inferiors
  gdb: add timeouts for inferior function calls
  gdb/remote: avoid SIGINT after calling remote_target::stop
  gdb: introduce unwind-on-timeout setting
  gdb: rename unwindonsignal to unwind-on-signal

 gdb/NEWS                                      |  38 +++
 gdb/breakpoint.c                              |  17 +-
 gdb/doc/gdb.texinfo                           | 127 +++++++-
 gdb/gdbthread.h                               |   3 +
 gdb/infcall.c                                 | 305 +++++++++++++++++-
 gdb/infrun.c                                  |  70 +++-
 gdb/infrun.h                                  |   3 +-
 gdb/remote.c                                  |  10 +
 gdb/testsuite/gdb.base/bp-cond-failure.c      |  30 ++
 gdb/testsuite/gdb.base/bp-cond-failure.exp    | 104 ++++++
 gdb/testsuite/gdb.base/callfuncs.exp          |   4 +-
 .../gdb.base/catch-signal-siginfo-cond.exp    |   2 +-
 gdb/testsuite/gdb.base/gnu-ifunc.exp          |   2 +-
 gdb/testsuite/gdb.base/help.exp               |   2 +-
 gdb/testsuite/gdb.base/infcall-failure.c      |  48 +++
 gdb/testsuite/gdb.base/infcall-failure.exp    | 183 +++++++++++
 gdb/testsuite/gdb.base/infcall-timeout.c      |  36 +++
 gdb/testsuite/gdb.base/infcall-timeout.exp    |  98 ++++++
 gdb/testsuite/gdb.base/unwindonsignal.exp     |  36 ++-
 gdb/testsuite/gdb.compile/compile-cplus.exp   |   2 +-
 gdb/testsuite/gdb.compile/compile.exp         |   2 +-
 gdb/testsuite/gdb.cp/gdb2495.exp              |  16 +-
 gdb/testsuite/gdb.fortran/function-calls.exp  |   2 +-
 gdb/testsuite/gdb.mi/mi-syn-frame.exp         |   2 +-
 .../gdb.python/py-finish-breakpoint.exp       |   2 +-
 .../infcall-from-bp-cond-other-thread-event.c | 135 ++++++++
 ...nfcall-from-bp-cond-other-thread-event.exp | 174 ++++++++++
 .../gdb.threads/infcall-from-bp-cond-simple.c |  89 +++++
 .../infcall-from-bp-cond-simple.exp           | 235 ++++++++++++++
 .../gdb.threads/infcall-from-bp-cond-single.c | 139 ++++++++
 .../infcall-from-bp-cond-single.exp           | 117 +++++++
 .../infcall-from-bp-cond-timeout.c            | 169 ++++++++++
 .../infcall-from-bp-cond-timeout.exp          | 174 ++++++++++
 .../gdb.threads/thread-unwindonsignal.exp     |   8 +-
 gdbserver/ax.cc                               |  12 +-
 gdbserver/ax.h                                |   3 +-
 gdbserver/tracepoint.cc                       |  11 +-
 gdbserver/tracepoint.h                        |   9 +-
 38 files changed, 2340 insertions(+), 79 deletions(-)
 create mode 100644 gdb/testsuite/gdb.base/bp-cond-failure.c
 create mode 100644 gdb/testsuite/gdb.base/bp-cond-failure.exp
 create mode 100644 gdb/testsuite/gdb.base/infcall-failure.c
 create mode 100644 gdb/testsuite/gdb.base/infcall-failure.exp
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.c
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp


base-commit: 2968b79fca38cf18e8eef360c36de7a6e3846d3c
-- 
2.25.4


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

* [PATCHv4 01/12] gdb/doc: extended documentation for inferior function calls
  2023-02-28 16:42     ` [PATCHv4 00/12] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
@ 2023-02-28 16:42       ` Andrew Burgess
  2024-03-21  9:03         ` Tom de Vries
  2023-02-28 16:42       ` [PATCHv4 02/12] gdb: include breakpoint number in testing condition error message Andrew Burgess
                         ` (11 subsequent siblings)
  12 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2023-02-28 16:42 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Eli already approved these docs changes:

  https://sourceware.org/pipermail/gdb-patches/2023-January/195869.html

---

I noticed that the documentation for inferior function calls doesn't
say much about what happens if/when an inferior function call is
interrupted, i.e. it doesn't describe what the dummy frame looks like
on the stack, or how GDB behaves when the inferior is continued and
reaches the dummy frame.

This commit aims to add some of this missing information.
---
 gdb/doc/gdb.texinfo | 32 ++++++++++++++++++++++++++++++++
 1 file changed, 32 insertions(+)

diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index c1ca45521ea..1170a2dacc3 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -20779,6 +20779,7 @@
 in that case is controlled by the
 @code{set unwind-on-terminating-exception} command.
 
+@anchor{stack unwind settings}
 @table @code
 @item set unwindonsignal
 @kindex set unwindonsignal
@@ -20836,6 +20837,37 @@
 
 @end table
 
+When calling a function within a program, it is possible that the
+program could enter a state from which the called function may never
+return.  If this happens then it is possible to interrupt the function
+call by typing the interrupt character (often @kbd{Ctrl-c}).
+
+If a called function is interrupted for any reason, including hitting
+a breakpoint, or triggering a watchpoint, and the stack is not unwound
+due to @code{set unwind-on-terminating-exception on} or @code{set
+unwindonsignal on} (@pxref{stack unwind settings}),
+then the dummy-frame, created by @value{GDBN} to facilitate the call
+to the program function, will be visible in the backtrace, for example
+frame @code{#3} in the following backtrace:
+
+@smallexample
+(@value{GDBP}) backtrace
+#0  0x00007ffff7b3d1e7 in nanosleep () from /lib64/libc.so.6
+#1  0x00007ffff7b3d11e in sleep () from /lib64/libc.so.6
+#2  0x000000000040113f in deadlock () at test.cc:13
+#3  <function called from gdb>
+#4  breakpt () at test.cc:20
+#5  0x0000000000401151 in main () at test.cc:25
+@end smallexample
+
+At this point it is possible to examine the state of the inferior just
+like any other stop.
+
+Depending on why the function was interrupted then it may be possible
+to resume the inferior (using commands like @code{continue},
+@code{step}, etc).  In this case, when the inferior finally returns to
+the dummy-frame, @value{GDBN} will once again halt the inferior.
+
 @subsection Calling functions with no debug info
 
 @cindex no debug info functions
-- 
2.25.4


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

* [PATCHv4 02/12] gdb: include breakpoint number in testing condition error message
  2023-02-28 16:42     ` [PATCHv4 00/12] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
  2023-02-28 16:42       ` [PATCHv4 01/12] gdb/doc: extended documentation for inferior function calls Andrew Burgess
@ 2023-02-28 16:42       ` Andrew Burgess
  2023-02-28 16:42       ` [PATCHv4 03/12] gdbserver: allows agent_mem_read to return an error code Andrew Burgess
                         ` (10 subsequent siblings)
  12 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-02-28 16:42 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

When GDB fails to test the condition of a conditional breakpoint, for
whatever reason, the error message looks like this:

  (gdb) break foo if (*(int *) 0) == 1
  Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
  (gdb) r
  Starting program: /tmp/bpcond
  Error in testing breakpoint condition:
  Cannot access memory at address 0x0

  Breakpoint 1, foo () at bpcond.c:11
  11	  int a = 32;
  (gdb)

The line I'm interested in for this commit is this one:

  Error in testing breakpoint condition:

In the case above we can figure out that the problematic breakpoint
was #1 because in the final line of the message GDB reports the stop a
breakpoint #1.

However, in the next few patches I plan to change this.  In some cases
I don't think it makes sense for GDB to report the stop as being at
breakpoint #1, consider this case:

  (gdb) list some_func
  1	int
  2	some_func ()
  3	{
  4	  int *p = 0;
  5	  return *p;
  6	}
  7
  8	void
  9	foo ()
  10	{
  (gdb) break foo if (some_func ())
  Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
  (gdb) r
  Starting program: /tmp/bpcond

  Program received signal SIGSEGV, Segmentation fault.
  0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  Error in testing breakpoint condition:
  The program being debugged was signaled while in a function called from GDB.
  GDB remains in the frame where the signal was received.
  To change this behavior use "set unwindonsignal on".
  Evaluation of the expression containing the function
  (some_func) will be abandoned.
  When the function is done executing, GDB will silently stop.

  Program received signal SIGSEGV, Segmentation fault.

  Breakpoint 1, 0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  (gdb)

Notice that, the final lines of output report the stop as being at
breakpoint #1, even though we are actually located within some_func.

I find this behaviour confusing, and propose that this should be
changed.  However, if I make that change then every reference to
breakpoint #1 will be lost from the error message.

So, in this commit, in preparation for the later commits, I propose to
change the 'Error in testing breakpoint condition:' line to this:

  Error in testing condition for breakpoint NUMBER:

where NUMBER will be filled in as appropriate.  Here's the first
example with the updated error:

  (gdb) break foo if (*(int *) 0) == 0
  Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
  (gdb) r
  Starting program: /tmp/bpcond
  Error in testing condition for breakpoint 1:
  Cannot access memory at address 0x0

  Breakpoint 1, foo () at bpcond.c:11
  11	  int a = 32;
  (gdb)

The breakpoint number does now appear twice in the output, but I don't
see that as a negative.

This commit just changes the one line of the error, and updates the
few tests that either included the old error in comments, or actually
checked for the error in the expected output.

As the only test that checked the line I modified is a Python test,
I've added a new test that doesn't rely on Python that checks the
error message in detail.

While working on the new test, I spotted that it would fail when run
with native-gdbserver and native-extended-gdbserver target boards.
This turns out to be due to a gdbserver bug.  To avoid cluttering this
commit I've added a work around to the new test script so that the
test passes for the remote boards, in the next few commits I will fix
gdbserver, and update the test script to remove the work around.
---
 gdb/breakpoint.c                              |   3 +-
 gdb/testsuite/gdb.base/bp-cond-failure.c      |  30 +++++
 gdb/testsuite/gdb.base/bp-cond-failure.exp    | 112 ++++++++++++++++++
 .../gdb.base/catch-signal-siginfo-cond.exp    |   2 +-
 gdb/testsuite/gdb.base/gnu-ifunc.exp          |   2 +-
 .../gdb.python/py-finish-breakpoint.exp       |   2 +-
 6 files changed, 147 insertions(+), 4 deletions(-)
 create mode 100644 gdb/testsuite/gdb.base/bp-cond-failure.c
 create mode 100644 gdb/testsuite/gdb.base/bp-cond-failure.exp

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index a42d26fd25a..c04b2e05d87 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -5543,7 +5543,8 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
 	  catch (const gdb_exception_error &ex)
 	    {
 	      exception_fprintf (gdb_stderr, ex,
-				 "Error in testing breakpoint condition:\n");
+				 "Error in testing condition for breakpoint %d:\n",
+				 b->number);
 	    }
 	}
       else
diff --git a/gdb/testsuite/gdb.base/bp-cond-failure.c b/gdb/testsuite/gdb.base/bp-cond-failure.c
new file mode 100644
index 00000000000..2a9974b47ce
--- /dev/null
+++ b/gdb/testsuite/gdb.base/bp-cond-failure.c
@@ -0,0 +1,30 @@
+/* Copyright 2022-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/>.  */
+
+int
+foo ()
+{
+  return 0;	/* Breakpoint here.  */
+}
+
+int
+main ()
+{
+  int res = foo ();
+
+  return res;
+}
diff --git a/gdb/testsuite/gdb.base/bp-cond-failure.exp b/gdb/testsuite/gdb.base/bp-cond-failure.exp
new file mode 100644
index 00000000000..b528ccce4ad
--- /dev/null
+++ b/gdb/testsuite/gdb.base/bp-cond-failure.exp
@@ -0,0 +1,112 @@
+# Copyright 2022-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/>.
+
+# Check the format of the error message given when a breakpoint
+# condition fails.
+#
+# In this case the breakpoint condition does not make use of inferior
+# function calls, instead, the expression used for the breakpoint
+# condition will throw an error when evaluated.
+#
+# We check that the correct breakpoint number appears in the error
+# message, and that the error is reported at the correct source
+# location.
+
+standard_testfile
+
+if { [prepare_for_testing "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug}] == -1 } {
+    return
+}
+
+# Run to main so that we connect to the target if using 'target
+# remote'.  This means that the is_address_zero_readable, and the
+# 'show breakpoint condition-evaluation' checks below will be
+# performed with the remote connection in place.
+if { ![runto_main] } {
+    return -1
+}
+
+# This test relies on reading address zero triggering a SIGSEGV.
+if { [is_address_zero_readable] } {
+    return
+}
+
+# Where the breakpoint will be placed.
+set bp_line [gdb_get_line_number "Breakpoint here"]
+
+proc run_test { cond_eval } {
+    clean_restart ${::binfile}
+
+    if { ![runto_main] } {
+	return -1
+    }
+
+    if { $cond_eval ne "auto" } {
+	gdb_test_no_output "set breakpoint condition-evaluation ${cond_eval}"
+    }
+
+    # Setup the conditional breakpoint and record its number.
+    gdb_breakpoint "${::srcfile}:${::bp_line} if (*(int *) 0) == 0"
+    set bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*"]
+
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     "Error in testing condition for breakpoint ${bp_num}:" \
+	     "Cannot access memory at address 0x0" \
+	     "" \
+	     "Breakpoint ${bp_num}, foo \\(\\) at \[^\r\n\]+:${::bp_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Breakpoint here\[^\r\n\]+"]
+}
+
+# If we're using a remote target then conditions could be evaulated
+# locally on the host, or on the remote target.  Otherwise, conditions
+# are always evaluated locally.
+#
+# Using "auto" will select the target if the target supports condition
+# evaluation, otherwise, the local host will be used.
+#
+# So, we always include "auto", but then we look at the output of
+# 'show breakpoint condition-evaluation', if this tells us that "auto"
+# is using the target, then we specifically add "host" to the list of
+# modes to check.
+
+set cond_eval_modes { "auto" }
+
+gdb_test_multiple "show breakpoint condition-evaluation" "" {
+    -re -wrap "Breakpoint condition evaluation mode is auto \\(currently target\\)\\." {
+
+	## NOTE: Instead of testing with "auto" and "host" in this
+	## case we only test with "host".  This is because a GDB bug
+	## prevents the "auto" (a.k.a. target) mode from working.
+	##
+	## Don't worry, this will be fixed in a later commit, and this
+	## comment will be removed at that time.
+	##
+	## lappend cond_eval_modes "host"
+
+	set cond_eval_modes { "host" }
+	pass $gdb_test_name
+    }
+
+    -re -wrap "Breakpoint condition evaluation mode is auto \\(currently host\\)\\." {
+	pass $gdb_test_name
+    }
+}
+
+foreach_with_prefix cond_eval $cond_eval_modes {
+    run_test $cond_eval
+}
diff --git a/gdb/testsuite/gdb.base/catch-signal-siginfo-cond.exp b/gdb/testsuite/gdb.base/catch-signal-siginfo-cond.exp
index 182b2f25faa..f400fc03b28 100644
--- a/gdb/testsuite/gdb.base/catch-signal-siginfo-cond.exp
+++ b/gdb/testsuite/gdb.base/catch-signal-siginfo-cond.exp
@@ -18,7 +18,7 @@
 #
 # (gdb) continue
 # Continuing.
-# Error in testing breakpoint condition:
+# Error in testing condition for breakpoint NUM:
 # Selected thread is running.
 #
 # Catchpoint 3 (signal SIGUSR1), 0x0000003615e35877 in __GI_raise (sig=10) at raise.c:56
diff --git a/gdb/testsuite/gdb.base/gnu-ifunc.exp b/gdb/testsuite/gdb.base/gnu-ifunc.exp
index 0a435806409..22462bea233 100644
--- a/gdb/testsuite/gdb.base/gnu-ifunc.exp
+++ b/gdb/testsuite/gdb.base/gnu-ifunc.exp
@@ -281,7 +281,7 @@ proc misc_tests {resolver_attr resolver_debug final_debug} {
 
     # Also test a former patch regression:
     # Continuing.
-    # Error in testing breakpoint condition:
+    # Error in testing condition for breakpoint NUM:
     # Attempt to take address of value not located in memory.
     #
     # Breakpoint 2, main () at ./gdb.base/gnu-ifunc.c:33
diff --git a/gdb/testsuite/gdb.python/py-finish-breakpoint.exp b/gdb/testsuite/gdb.python/py-finish-breakpoint.exp
index b6bd7a63c8f..e5a46874afd 100644
--- a/gdb/testsuite/gdb.python/py-finish-breakpoint.exp
+++ b/gdb/testsuite/gdb.python/py-finish-breakpoint.exp
@@ -188,7 +188,7 @@ with_test_prefix "finish in normal frame" {
     gdb_test "python TestBreakpoint()" "TestBreakpoint init" "set BP in condition"
 
     gdb_test "continue" \
-	"test don't stop: 1.*test don't stop: 2.*test stop.*Error in testing breakpoint condition.*The program being debugged stopped while in a function called from GDB.*" \
+	"test don't stop: 1.*test don't stop: 2.*test stop.*Error in testing condition for breakpoint ${::decimal}.*The program being debugged stopped while in a function called from GDB.*" \
 	"stop in condition function"
 
     gdb_test "continue" "Continuing.*" "finish condition evaluation"
-- 
2.25.4


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

* [PATCHv4 03/12] gdbserver: allows agent_mem_read to return an error code
  2023-02-28 16:42     ` [PATCHv4 00/12] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
  2023-02-28 16:42       ` [PATCHv4 01/12] gdb/doc: extended documentation for inferior function calls Andrew Burgess
  2023-02-28 16:42       ` [PATCHv4 02/12] gdb: include breakpoint number in testing condition error message Andrew Burgess
@ 2023-02-28 16:42       ` Andrew Burgess
  2023-02-28 16:42       ` [PATCHv4 04/12] gdbserver: allow agent expressions to fail with invalid memory access Andrew Burgess
                         ` (9 subsequent siblings)
  12 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-02-28 16:42 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Currently the gdbserver function agent_mem_read ignores any errors
from calling read_inferior_memory.  This means that if there is an
attempt to access invalid memory then this will appear to succeed.

In this patch I update agent_mem_read so that if read_inferior_memory
fails, agent_mem_read will return an error code.

However, none of the callers of agent_mem_read actually check the
return value, so this commit will have no effect on anything.  In the
next commit I will update the users of agent_mem_read to check for the
error code.

I've also updated the header comments on agent_mem_read to better
reflect what the function does, and its possible return values.
---
 gdbserver/tracepoint.cc | 11 ++++-------
 gdbserver/tracepoint.h  |  9 +++++++--
 2 files changed, 11 insertions(+), 9 deletions(-)

diff --git a/gdbserver/tracepoint.cc b/gdbserver/tracepoint.cc
index 3f60989e4c7..125a384ffb3 100644
--- a/gdbserver/tracepoint.cc
+++ b/gdbserver/tracepoint.cc
@@ -4914,8 +4914,7 @@ condition_true_at_tracepoint (struct tracepoint_hit_ctx *ctx,
   return (value ? 1 : 0);
 }
 
-/* Do memory copies for bytecodes.  */
-/* Do the recording of memory blocks for actions and bytecodes.  */
+/* See tracepoint.h.  */
 
 int
 agent_mem_read (struct eval_agent_expr_context *ctx,
@@ -4927,10 +4926,7 @@ agent_mem_read (struct eval_agent_expr_context *ctx,
 
   /* If a 'to' buffer is specified, use it.  */
   if (to != NULL)
-    {
-      read_inferior_memory (from, to, len);
-      return 0;
-    }
+    return read_inferior_memory (from, to, len);
 
   /* Otherwise, create a new memory block in the trace buffer.  */
   while (remaining > 0)
@@ -4951,7 +4947,8 @@ agent_mem_read (struct eval_agent_expr_context *ctx,
       memcpy (mspace, &blocklen, sizeof (blocklen));
       mspace += sizeof (blocklen);
       /* Record the memory block proper.  */
-      read_inferior_memory (from, mspace, blocklen);
+      if (read_inferior_memory (from, mspace, blocklen) != 0)
+	return 1;
       trace_debug ("%d bytes recorded", blocklen);
       remaining -= blocklen;
       from += blocklen;
diff --git a/gdbserver/tracepoint.h b/gdbserver/tracepoint.h
index 060d44d0033..1f40d7b5177 100644
--- a/gdbserver/tracepoint.h
+++ b/gdbserver/tracepoint.h
@@ -161,8 +161,13 @@ void gdb_agent_about_to_close (int pid);
 struct traceframe;
 struct eval_agent_expr_context;
 
-/* Do memory copies for bytecodes.  */
-/* Do the recording of memory blocks for actions and bytecodes.  */
+/* When TO is not NULL, do memory copies for bytecodes, read LEN bytes
+   starting at address FROM, and place the result in the buffer TO.
+   Return 0 on success, otherwise a non-zero error code.
+
+   When TO is NULL, do the recording of memory blocks for actions and
+   bytecodes into a new traceframe block.  Return 0 on success, otherwise,
+   return 1 if there is an error.  */
 
 int agent_mem_read (struct eval_agent_expr_context *ctx,
 		    unsigned char *to, CORE_ADDR from,
-- 
2.25.4


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

* [PATCHv4 04/12] gdbserver: allow agent expressions to fail with invalid memory access
  2023-02-28 16:42     ` [PATCHv4 00/12] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                         ` (2 preceding siblings ...)
  2023-02-28 16:42       ` [PATCHv4 03/12] gdbserver: allows agent_mem_read to return an error code Andrew Burgess
@ 2023-02-28 16:42       ` Andrew Burgess
  2023-02-28 16:42       ` [PATCHv4 05/12] gdb: avoid repeated signal reporting during failed conditional breakpoint Andrew Burgess
                         ` (8 subsequent siblings)
  12 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-02-28 16:42 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

This commit extends gdbserver to take account of a failed memory
access from agent_mem_read, and to return a new eval_result_type
expr_eval_invalid_memory_access.

I have only updated the agent_mem_read calls related directly to
reading memory, I have not updated any of the calls related to
tracepoint data collection.  This is just because I'm not familiar
with that area of gdb/gdbserver, and I don't want to break anything,
so leaving the existing behaviour untouched seems like the safest
approach.

I've then updated gdb.base/bp-cond-failure.exp to test evaluating the
breakpoints on the target, and have also extended the test so that it
checks for different sizes of memory access.
---
 gdb/testsuite/gdb.base/bp-cond-failure.exp | 22 +++++++---------------
 gdbserver/ax.cc                            | 12 ++++++++----
 gdbserver/ax.h                             |  3 ++-
 3 files changed, 17 insertions(+), 20 deletions(-)

diff --git a/gdb/testsuite/gdb.base/bp-cond-failure.exp b/gdb/testsuite/gdb.base/bp-cond-failure.exp
index b528ccce4ad..cb572203772 100644
--- a/gdb/testsuite/gdb.base/bp-cond-failure.exp
+++ b/gdb/testsuite/gdb.base/bp-cond-failure.exp
@@ -47,7 +47,7 @@ if { [is_address_zero_readable] } {
 # Where the breakpoint will be placed.
 set bp_line [gdb_get_line_number "Breakpoint here"]
 
-proc run_test { cond_eval } {
+proc run_test { cond_eval access_type } {
     clean_restart ${::binfile}
 
     if { ![runto_main] } {
@@ -59,7 +59,7 @@ proc run_test { cond_eval } {
     }
 
     # Setup the conditional breakpoint and record its number.
-    gdb_breakpoint "${::srcfile}:${::bp_line} if (*(int *) 0) == 0"
+    gdb_breakpoint "${::srcfile}:${::bp_line} if (*(${access_type} *) 0) == 0"
     set bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*"]
 
     gdb_test "continue" \
@@ -88,17 +88,7 @@ set cond_eval_modes { "auto" }
 
 gdb_test_multiple "show breakpoint condition-evaluation" "" {
     -re -wrap "Breakpoint condition evaluation mode is auto \\(currently target\\)\\." {
-
-	## NOTE: Instead of testing with "auto" and "host" in this
-	## case we only test with "host".  This is because a GDB bug
-	## prevents the "auto" (a.k.a. target) mode from working.
-	##
-	## Don't worry, this will be fixed in a later commit, and this
-	## comment will be removed at that time.
-	##
-	## lappend cond_eval_modes "host"
-
-	set cond_eval_modes { "host" }
+	lappend cond_eval_modes "host"
 	pass $gdb_test_name
     }
 
@@ -107,6 +97,8 @@ gdb_test_multiple "show breakpoint condition-evaluation" "" {
     }
 }
 
-foreach_with_prefix cond_eval $cond_eval_modes {
-    run_test $cond_eval
+foreach_with_prefix access_type { "char" "short" "int" "long long" } {
+    foreach_with_prefix cond_eval $cond_eval_modes {
+	run_test $cond_eval $access_type
+    }
 }
diff --git a/gdbserver/ax.cc b/gdbserver/ax.cc
index 38ebfbbd750..fba5b4ad0fc 100644
--- a/gdbserver/ax.cc
+++ b/gdbserver/ax.cc
@@ -1112,22 +1112,26 @@ gdb_eval_agent_expr (struct eval_agent_expr_context *ctx,
 	  break;
 
 	case gdb_agent_op_ref8:
-	  agent_mem_read (ctx, cnv.u8.bytes, (CORE_ADDR) top, 1);
+	  if (agent_mem_read (ctx, cnv.u8.bytes, (CORE_ADDR) top, 1) != 0)
+	    return expr_eval_invalid_memory_access;
 	  top = cnv.u8.val;
 	  break;
 
 	case gdb_agent_op_ref16:
-	  agent_mem_read (ctx, cnv.u16.bytes, (CORE_ADDR) top, 2);
+	  if (agent_mem_read (ctx, cnv.u16.bytes, (CORE_ADDR) top, 2) != 0)
+	    return expr_eval_invalid_memory_access;
 	  top = cnv.u16.val;
 	  break;
 
 	case gdb_agent_op_ref32:
-	  agent_mem_read (ctx, cnv.u32.bytes, (CORE_ADDR) top, 4);
+	  if (agent_mem_read (ctx, cnv.u32.bytes, (CORE_ADDR) top, 4) != 0)
+	    return expr_eval_invalid_memory_access;
 	  top = cnv.u32.val;
 	  break;
 
 	case gdb_agent_op_ref64:
-	  agent_mem_read (ctx, cnv.u64.bytes, (CORE_ADDR) top, 8);
+	  if (agent_mem_read (ctx, cnv.u64.bytes, (CORE_ADDR) top, 8) != 0)
+	    return expr_eval_invalid_memory_access;
 	  top = cnv.u64.val;
 	  break;
 
diff --git a/gdbserver/ax.h b/gdbserver/ax.h
index 8e64a7a593e..c98e36a83c6 100644
--- a/gdbserver/ax.h
+++ b/gdbserver/ax.h
@@ -41,7 +41,8 @@ enum eval_result_type
     expr_eval_unhandled_opcode,
     expr_eval_unrecognized_opcode,
     expr_eval_divide_by_zero,
-    expr_eval_invalid_goto
+    expr_eval_invalid_goto,
+    expr_eval_invalid_memory_access
   };
 
 struct agent_expr
-- 
2.25.4


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

* [PATCHv4 05/12] gdb: avoid repeated signal reporting during failed conditional breakpoint
  2023-02-28 16:42     ` [PATCHv4 00/12] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                         ` (3 preceding siblings ...)
  2023-02-28 16:42       ` [PATCHv4 04/12] gdbserver: allow agent expressions to fail with invalid memory access Andrew Burgess
@ 2023-02-28 16:42       ` Andrew Burgess
  2023-02-28 16:42       ` [PATCHv4 06/12] gdb: don't always print breakpoint location after failed condition check Andrew Burgess
                         ` (7 subsequent siblings)
  12 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-02-28 16:42 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Consider the following case:

  (gdb) list some_func
  1	int
  2	some_func ()
  3	{
  4	  int *p = 0;
  5	  return *p;
  6	}
  7
  8	void
  9	foo ()
  10	{
  (gdb) break foo if (some_func ())
  Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
  (gdb) r
  Starting program: /tmp/bpcond

  Program received signal SIGSEGV, Segmentation fault.
  0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  Error in testing breakpoint condition:
  The program being debugged was signaled while in a function called from GDB.
  GDB remains in the frame where the signal was received.
  To change this behavior use "set unwindonsignal on".
  Evaluation of the expression containing the function
  (some_func) will be abandoned.
  When the function is done executing, GDB will silently stop.

  Program received signal SIGSEGV, Segmentation fault.

  Breakpoint 1, 0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  (gdb)

Notice that this line:

  Program received signal SIGSEGV, Segmentation fault.

Appears twice in the output.  The first time is followed by the
current location.  The second time is a little odd, why do we print
that?

Printing that line is controlled, in part, by a global variable,
stopped_by_random_signal.  This variable is reset to zero in
handle_signal_stop, and is set if/when GDB figures out that the
inferior stopped due to some random signal.

The problem is, in our case, GDB first stops at the breakpoint for
foo, and enters handle_signal_stop and the stopped_by_random_signal
global is reset to 0.

Later within handle_signal_stop GDB calls bpstat_stop_status, it is
within this function (via bpstat_check_breakpoint_conditions) that the
breakpoint condition is checked, and, we end up calling the inferior
function (some_func in our example above).

In our case above the thread performing the inferior function call
segfaults in some_func.  GDB catches the SIGSEGV and handles the stop,
this causes us to reenter handle_signal_stop.  The global variable
stopped_by_random_signal is updated, this time it is set to true
because the thread stopped due to SIGSEGV.  As a result of this we
print the first instance of the line (as seen above in the example).

Finally we unwind GDB's call stack, the inferior function call is
complete, and we return to the original handle_signal_stop.  However,
the stopped_by_random_signal global is still carrying the value as
computed for the inferior function call's stop, which is why we now
print a second instance of the line, as seen in the example.

To prevent this, I propose adding a scoped_restore before we start an
inferior function call.  This will save and restore the global
stopped_by_random_signal value.

With this done, the output from our example is now this:

 (gdb) list some_func
  1	int
  2	some_func ()
  3	{
  4	  int *p = 0;
  5	  return *p;
  6	}
  7
  8	void
  9	foo ()
  10	{
  (gdb) break foo if (some_func ())
  Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
  (gdb) r
  Starting program: /tmp/bpcond

  Program received signal SIGSEGV, Segmentation fault.
  0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  Error in testing condition for breakpoint 1:
  The program being debugged stopped while in a function called from GDB.
  Evaluation of the expression containing the function
  (some_func) will be abandoned.
  When the function is done executing, GDB will silently stop.

  Breakpoint 1, 0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  (gdb)

We now only see the 'Program received signal SIGSEGV, ...' line once,
which I think makes more sense.

Finally, I'm aware that the last few lines, that report the stop as
being at 'Breakpoint 1', when this is not where the thread is actually
located anymore, is not great.  I'll address that in the next commit.
---
 gdb/infcall.c                              |   9 +
 gdb/testsuite/gdb.base/infcall-failure.c   |  48 ++++++
 gdb/testsuite/gdb.base/infcall-failure.exp | 185 +++++++++++++++++++++
 3 files changed, 242 insertions(+)
 create mode 100644 gdb/testsuite/gdb.base/infcall-failure.c
 create mode 100644 gdb/testsuite/gdb.base/infcall-failure.exp

diff --git a/gdb/infcall.c b/gdb/infcall.c
index 9ed17bf4f8b..e6cc6ed1a21 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -1293,6 +1293,15 @@ call_function_by_hand_dummy (struct value *function,
   /* Register a clean-up for unwind_on_terminating_exception_breakpoint.  */
   SCOPE_EXIT { delete_std_terminate_breakpoint (); };
 
+  /* The stopped_by_random_signal variable is global.  If we are here
+     as part of a breakpoint condition check then the global will have
+     already been setup as part of the original breakpoint stop.  By
+     making the inferior call the global will be changed when GDB
+     handles the stop after the inferior call.  Avoid confusion by
+     restoring the current value after the inferior call.  */
+  scoped_restore restore_stopped_by_random_signal
+    = make_scoped_restore (&stopped_by_random_signal, 0);
+
   /* - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP -
      If you're looking to implement asynchronous dummy-frames, then
      just below is the place to chop this function in two..  */
diff --git a/gdb/testsuite/gdb.base/infcall-failure.c b/gdb/testsuite/gdb.base/infcall-failure.c
new file mode 100644
index 00000000000..fae012b2cda
--- /dev/null
+++ b/gdb/testsuite/gdb.base/infcall-failure.c
@@ -0,0 +1,48 @@
+/* Copyright 2022-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/>.  */
+
+/* A function that segfaults (assuming that reads of address zero are
+   prohibited), this is used from within a breakpoint condition.  */
+int
+func_segfault ()
+{
+  volatile int *p = 0;
+  return *p;	/* Segfault here.  */
+}
+
+/* A function in which we will place a breakpoint.  This function is itself
+   then used from within a breakpoint condition.  */
+int
+func_bp ()
+{
+  int res = 0;	/* Second breakpoint.  */
+  return res;
+}
+
+int
+foo ()
+{
+  return 0;	/* First breakpoint.  */
+}
+
+int
+main ()
+{
+  int res = foo ();
+
+  return res;
+}
diff --git a/gdb/testsuite/gdb.base/infcall-failure.exp b/gdb/testsuite/gdb.base/infcall-failure.exp
new file mode 100644
index 00000000000..214a64f8de3
--- /dev/null
+++ b/gdb/testsuite/gdb.base/infcall-failure.exp
@@ -0,0 +1,185 @@
+# Copyright 2022-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/>.
+
+# Some simple tests of inferior function calls from breakpoint
+# conditions, in a single-threaded inferior.
+#
+# Test what happens when the inferior function (from a breakpoint
+# condition) either hits a nested breakpoint, or segfaults.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug}] == -1 } {
+    return
+}
+
+set bp_1_line [gdb_get_line_number "First breakpoint"]
+set bp_2_line [gdb_get_line_number "Second breakpoint"]
+set segv_line [gdb_get_line_number "Segfault here"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto
+# main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if { ![runto_main] } {
+	return -1
+    }
+
+    return 0
+}
+
+# Start GDB according to ASYNC_P and NON_STOP_P, then setup a
+# conditional breakpoint.  The breakpoint condition includes an
+# inferior function call that will itself hit a breakpoint.  Check how
+# GDB reports this to the user.
+proc_with_prefix run_cond_hits_breakpoint_test { async_p non_stop_p } {
+    if { [start_gdb_and_runto_main $async_p $non_stop_p] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint and record its number.
+    gdb_breakpoint "${::srcfile}:${::bp_1_line} if (func_bp ())"
+    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		     "get number of first breakpoint"]
+
+    # Setup a breakpoint inside func_bp.
+    gdb_breakpoint "${::srcfile}:${::bp_2_line}"
+    set bp_2_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		     "get number of second breakpoint"]
+
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     "" \
+	     "Breakpoint ${bp_2_num}, func_bp \\(\\) at \[^\r\n\]+:${::bp_2_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Second breakpoint\[^\r\n\]+" \
+	     "Error in testing condition for breakpoint ${bp_1_num}:" \
+	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(func_bp\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\." \
+	     "" \
+	     "Breakpoint ${bp_1_num}, \[^\r\n\]+" \
+	     "${::decimal}\\s+\[^\r\n\]+Second breakpoint\[^\r\n\]+"]
+}
+
+# Start GDB according to ASYNC_P and NON_STOP_P, then call an inferior
+# function.  The inferior function being called will itself have a
+# breakpoint within it.  Check how GDB reports this to the user.
+proc_with_prefix run_call_hits_breakpoint_test { async_p non_stop_p } {
+    if { [start_gdb_and_runto_main $async_p $non_stop_p] == -1 } {
+	return
+    }
+
+    # Setup a breakpoint inside func_bp.
+    gdb_breakpoint "${::srcfile}:${::bp_2_line}"
+    set bp_2_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of second breakpoint"]
+
+
+    gdb_test "call func_bp ()" \
+	[multi_line \
+	     "" \
+	     "Breakpoint ${bp_2_num}, func_bp \\(\\) at \[^\r\n\]+:${::bp_2_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Second breakpoint\[^\r\n\]+" \
+	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(func_bp\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+}
+
+# Start GDB according to ASYNC_P and NON_STOP_P, then setup a
+# conditional breakpoint.  The breakpoint condition includes an
+# inferior function call that segfaults.  Check how GDB reports this
+# to the user.
+proc_with_prefix run_cond_hits_segfault_test { async_p non_stop_p } {
+    if { [start_gdb_and_runto_main $async_p $non_stop_p] == -1 } {
+	return
+    }
+
+    # This test relies on the inferior segfaulting when trying to
+    # access address zero.
+    if { [is_address_zero_readable] } {
+	unsupported "address zero is readable"
+	return
+    }
+
+    # Setup the conditional breakpoint and record its number.
+    gdb_breakpoint "${::srcfile}:${::bp_1_line} if (func_segfault ())"
+    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		     "get number of first breakpoint"]
+
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     "" \
+	     "Program received signal SIGSEGV, Segmentation fault\\." \
+	     "${::hex} in func_segfault \\(\\) at \[^\r\n\]+:${::segv_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
+	     "Error in testing condition for breakpoint ${bp_1_num}:" \
+	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(func_segfault\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\." \
+	     "" \
+	     "Breakpoint ${bp_1_num}, \[^\r\n\]+" \
+	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"]
+}
+
+# Start GDB according to ASYNC_P and NON_STOP_P, then call an inferior
+# function.  The inferior function will segfault.  Check how GDB
+# reports this to the user.
+proc_with_prefix run_call_hits_segfault_test { async_p non_stop_p } {
+    if { [start_gdb_and_runto_main $async_p $non_stop_p] == -1 } {
+	return
+    }
+
+    # This test relies on the inferior segfaulting when trying to
+    # access address zero.
+    if { [is_address_zero_readable] } {
+	unsupported "address zero is readable"
+	return
+    }
+
+    gdb_test "call func_segfault ()" \
+	[multi_line \
+	     "" \
+	     "Program received signal SIGSEGV, Segmentation fault\\." \
+	     "${::hex} in func_segfault \\(\\) at \[^\r\n\]+:${::segv_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
+	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(func_segfault\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	run_cond_hits_breakpoint_test $target_async $target_non_stop
+	run_call_hits_breakpoint_test $target_async $target_non_stop
+
+	run_cond_hits_segfault_test $target_async $target_non_stop
+	run_call_hits_segfault_test $target_async $target_non_stop
+    }
+}
-- 
2.25.4


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

* [PATCHv4 06/12] gdb: don't always print breakpoint location after failed condition check
  2023-02-28 16:42     ` [PATCHv4 00/12] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                         ` (4 preceding siblings ...)
  2023-02-28 16:42       ` [PATCHv4 05/12] gdb: avoid repeated signal reporting during failed conditional breakpoint Andrew Burgess
@ 2023-02-28 16:42       ` Andrew Burgess
  2023-02-28 16:42       ` [PATCHv4 07/12] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
                         ` (6 subsequent siblings)
  12 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-02-28 16:42 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Consider the following session:

  (gdb) list some_func
  1	int
  2	some_func ()
  3	{
  4	  int *p = 0;
  5	  return *p;
  6	}
  7
  8	void
  9	foo ()
  10	{
  (gdb) break foo if (some_func ())
  Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
  (gdb) r
  Starting program: /tmp/bpcond

  Program received signal SIGSEGV, Segmentation fault.
  0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  Error in testing condition for breakpoint 1:
  The program being debugged stopped while in a function called from GDB.
  Evaluation of the expression containing the function
  (some_func) will be abandoned.
  When the function is done executing, GDB will silently stop.

  Breakpoint 1, 0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  (gdb)

What happens here is the breakpoint condition includes a call to an
inferior function, and the inferior function segfaults.  We can see
that GDB reports the segfault, and then gives an error message that
indicates that an inferior function call was interrupted.

After this GDB appears to report that it is stopped at Breakpoint 1,
inside some_func.

I find this second stop report a little confusing.  While it is true
that GDB stopped as a result of hitting breakpoint 1, I think the
message GDB currently prints might give the impression that GDB is
actually stopped at a location of breakpoint 1, which is not the case.

Also, I find the second stop message draws attention away from
the "Program received signal SIGSEGV, Segmentation fault" stop
message, and this second stop might be thought of as replacing in
someway the earlier message.

In short, I think things would be clearer if the second stop message
were not reported at all, so the output should, I think, look like
this:

  (gdb) list some_func
  1	int
  2	some_func ()
  3	{
  4	  int *p = 0;
  5	  return *p;
  6	}
  7
  8	void
  9	foo ()
  10	{
  (gdb) break foo if (some_func ())
  Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
  (gdb) r
  Starting program: /tmp/bpcond

  Program received signal SIGSEGV, Segmentation fault.
  0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  Error in testing condition for breakpoint 1:
  The program being debugged stopped while in a function called from GDB.
  Evaluation of the expression containing the function
  (some_func) will be abandoned.
  When the function is done executing, GDB will silently stop.
  (gdb)

The user can still find the number of the breakpoint that triggered
the initial stop in this line:

  Error in testing condition for breakpoint 1:

But there's now only one stop reason reported, the SIGSEGV, which I
think is much clearer.

To achieve this change I set the bpstat::print field when:

  (a) a breakpoint condition evaluation failed, and

  (b) the $pc of the thread changed during condition evaluation.

I've updated the existing tests that checked the error message printed
when a breakpoint condition evaluation failed.
---
 gdb/breakpoint.c                           | 12 ++++++++++++
 gdb/testsuite/gdb.base/infcall-failure.exp | 18 ++++++++----------
 2 files changed, 20 insertions(+), 10 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index c04b2e05d87..89a0ffeabb9 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -5534,6 +5534,7 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
 	  else
 	    within_current_scope = false;
 	}
+      CORE_ADDR pc_before_check = get_frame_pc (get_selected_frame (nullptr));
       if (within_current_scope)
 	{
 	  try
@@ -5545,6 +5546,17 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
 	      exception_fprintf (gdb_stderr, ex,
 				 "Error in testing condition for breakpoint %d:\n",
 				 b->number);
+
+	      /* If the pc value changed as a result of evaluating the
+		 condition then we probably stopped within an inferior
+		 function call due to some unexpected stop, e.g. the thread
+		 hit another breakpoint, or the thread received an
+		 unexpected signal.  In this case we don't want to also
+		 print the information about this breakpoint.  */
+	      CORE_ADDR pc_after_check
+		= get_frame_pc (get_selected_frame (nullptr));
+	      if (pc_before_check != pc_after_check)
+		bs->print = 0;
 	    }
 	}
       else
diff --git a/gdb/testsuite/gdb.base/infcall-failure.exp b/gdb/testsuite/gdb.base/infcall-failure.exp
index 214a64f8de3..5ad179a089d 100644
--- a/gdb/testsuite/gdb.base/infcall-failure.exp
+++ b/gdb/testsuite/gdb.base/infcall-failure.exp
@@ -78,10 +78,7 @@ proc_with_prefix run_cond_hits_breakpoint_test { async_p non_stop_p } {
 	     "The program being debugged stopped while in a function called from GDB\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(func_bp\\) will be abandoned\\." \
-	     "When the function is done executing, GDB will silently stop\\." \
-	     "" \
-	     "Breakpoint ${bp_1_num}, \[^\r\n\]+" \
-	     "${::decimal}\\s+\[^\r\n\]+Second breakpoint\[^\r\n\]+"]
+	     "When the function is done executing, GDB will silently stop\\."]
 }
 
 # Start GDB according to ASYNC_P and NON_STOP_P, then call an inferior
@@ -138,13 +135,12 @@ proc_with_prefix run_cond_hits_segfault_test { async_p non_stop_p } {
 	     "${::hex} in func_segfault \\(\\) at \[^\r\n\]+:${::segv_line}" \
 	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
 	     "Error in testing condition for breakpoint ${bp_1_num}:" \
-	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "The program being debugged was signaled while in a function called from GDB\\." \
+	     "GDB remains in the frame where the signal was received\\." \
+	     "To change this behavior use \"set unwindonsignal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(func_segfault\\) will be abandoned\\." \
-	     "When the function is done executing, GDB will silently stop\\." \
-	     "" \
-	     "Breakpoint ${bp_1_num}, \[^\r\n\]+" \
-	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"]
+	     "When the function is done executing, GDB will silently stop\\."]
 }
 
 # Start GDB according to ASYNC_P and NON_STOP_P, then call an inferior
@@ -168,7 +164,9 @@ proc_with_prefix run_call_hits_segfault_test { async_p non_stop_p } {
 	     "Program received signal SIGSEGV, Segmentation fault\\." \
 	     "${::hex} in func_segfault \\(\\) at \[^\r\n\]+:${::segv_line}" \
 	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
-	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "The program being debugged was signaled while in a function called from GDB\\." \
+	     "GDB remains in the frame where the signal was received\\." \
+	     "To change this behavior use \"set unwindonsignal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(func_segfault\\) will be abandoned\\." \
 	     "When the function is done executing, GDB will silently stop\\."]
-- 
2.25.4


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

* [PATCHv4 07/12] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait"
  2023-02-28 16:42     ` [PATCHv4 00/12] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                         ` (5 preceding siblings ...)
  2023-02-28 16:42       ` [PATCHv4 06/12] gdb: don't always print breakpoint location after failed condition check Andrew Burgess
@ 2023-02-28 16:42       ` Andrew Burgess
  2023-02-28 16:42       ` [PATCHv4 08/12] gdb: fix b/p conditions with infcalls in multi-threaded inferiors Andrew Burgess
                         ` (5 subsequent siblings)
  12 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-02-28 16:42 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

This reverts commit ac0d67ed1dcf470bad6a3bc4800c2ddc9bedecca.

There was nothing wrong with the commit which I'm reverting here, but
it removed some functionality that will be needed for a later commit;
that is, the ability for GDB to ask for events from a specific ptid_t
via the do_target_wait function.

In a follow up commit, this functionality will be used to implement
inferior function calls in multi-threaded inferiors.

This is not a straight revert of the above commit.  Reverting the
above commit replaces a 'nullptr' with 'NULL', I've gone in and
changed that, preserving the 'nullptr'.
---
 gdb/infrun.c | 12 +++++++-----
 1 file changed, 7 insertions(+), 5 deletions(-)

diff --git a/gdb/infrun.c b/gdb/infrun.c
index ab77300f1ff..aa1c9e94bda 100644
--- a/gdb/infrun.c
+++ b/gdb/infrun.c
@@ -3830,7 +3830,8 @@ do_target_wait_1 (inferior *inf, ptid_t ptid,
    more events.  Polls for events from all inferiors/targets.  */
 
 static bool
-do_target_wait (execution_control_state *ecs, target_wait_flags options)
+do_target_wait (ptid_t wait_ptid, execution_control_state *ecs,
+		target_wait_flags options)
 {
   int num_inferiors = 0;
   int random_selector;
@@ -3840,9 +3841,10 @@ do_target_wait (execution_control_state *ecs, target_wait_flags options)
      polling the rest of the inferior list starting from that one in a
      circular fashion until the whole list is polled once.  */
 
-  auto inferior_matches = [] (inferior *inf)
+  auto inferior_matches = [&wait_ptid] (inferior *inf)
     {
-      return inf->process_target () != nullptr;
+      return (inf->process_target () != nullptr
+	      && ptid_t (inf->pid).matches (wait_ptid));
     };
 
   /* First see how many matching inferiors we have.  */
@@ -3881,7 +3883,7 @@ do_target_wait (execution_control_state *ecs, target_wait_flags options)
 
   auto do_wait = [&] (inferior *inf)
   {
-    ecs->ptid = do_target_wait_1 (inf, minus_one_ptid, &ecs->ws, options);
+    ecs->ptid = do_target_wait_1 (inf, wait_ptid, &ecs->ws, options);
     ecs->target = inf->process_target ();
     return (ecs->ws.kind () != TARGET_WAITKIND_IGNORE);
   };
@@ -4311,7 +4313,7 @@ fetch_inferior_event ()
        the event.  */
     scoped_disable_commit_resumed disable_commit_resumed ("handling event");
 
-    if (!do_target_wait (&ecs, TARGET_WNOHANG))
+    if (!do_target_wait (minus_one_ptid, &ecs, TARGET_WNOHANG))
       {
 	infrun_debug_printf ("do_target_wait returned no event");
 	disable_commit_resumed.reset_and_commit ();
-- 
2.25.4


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

* [PATCHv4 08/12] gdb: fix b/p conditions with infcalls in multi-threaded inferiors
  2023-02-28 16:42     ` [PATCHv4 00/12] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                         ` (6 preceding siblings ...)
  2023-02-28 16:42       ` [PATCHv4 07/12] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
@ 2023-02-28 16:42       ` Andrew Burgess
  2023-02-28 16:42       ` [PATCHv4 09/12] gdb: add timeouts for inferior function calls Andrew Burgess
                         ` (4 subsequent siblings)
  12 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-02-28 16:42 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Natalia Saiapova, Tankut Baris Aktemur

This commit fixes bug PR 28942, that is, creating a conditional
breakpoint in a multi-threaded inferior, where the breakpoint
condition includes an inferior function call.

Currently, when a user tries to create such a breakpoint, then GDB
will fail with:

  (gdb) break infcall-from-bp-cond-single.c:61 if (return_true ())
  Breakpoint 2 at 0x4011fa: file /tmp/build/gdb/testsuite/../../../src/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c, line 61.
  (gdb) continue
  Continuing.
  [New Thread 0x7ffff7c5d700 (LWP 2460150)]
  [New Thread 0x7ffff745c700 (LWP 2460151)]
  [New Thread 0x7ffff6c5b700 (LWP 2460152)]
  [New Thread 0x7ffff645a700 (LWP 2460153)]
  [New Thread 0x7ffff5c59700 (LWP 2460154)]
  Error in testing breakpoint condition:
  Couldn't get registers: No such process.
  An error occurred while in a function called from GDB.
  Evaluation of the expression containing the function
  (return_true) will be abandoned.
  When the function is done executing, GDB will silently stop.
  Selected thread is running.
  (gdb)

Or, in some cases, like this:

  (gdb) break infcall-from-bp-cond-simple.c:56 if (is_matching_tid (arg, 1))
  Breakpoint 2 at 0x401194: file /tmp/build/gdb/testsuite/../../../src/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c, line 56.
  (gdb) continue
  Continuing.
  [New Thread 0x7ffff7c5d700 (LWP 2461106)]
  [New Thread 0x7ffff745c700 (LWP 2461107)]
  ../../src.release/gdb/nat/x86-linux-dregs.c:146: internal-error: x86_linux_update_debug_registers: Assertion `lwp_is_stopped (lwp)' failed.
  A problem internal to GDB has been detected,
  further debugging may prove unreliable.

The precise error depends on the exact thread state; so there's race
conditions depending on which threads have fully started, and which
have not.  But the underlying problem is always the same; when GDB
tries to execute the inferior function call from within the breakpoint
condition, GDB will, incorrectly, try to resume threads that are
already running - GDB doesn't realise that some threads might already
be running.

The solution proposed in this patch requires an additional member
variable thread_info::in_cond_eval.  This flag is set to true (in
breakpoint.c) when GDB is evaluating a breakpoint condition.

In user_visible_resume_ptid (infrun.c), when the in_cond_eval flag is
true, then GDB will only try to resume the current thread, that is,
the thread for which the breakpoint condition is being evaluated.
This solves the problem of GDB trying to resume threads that are
already running.

The next problem is that inferior function calls are assumed to be
synchronous, that is, GDB doesn't expect to start an inferior function
call in thread #1, then receive a stop from thread #2 for some other,
unrelated reason.  To prevent GDB responding to an event from another
thread, we update fetch_inferior_event and do_target_wait in infrun.c,
so that, when an inferior function call (on behalf of a breakpoint
condition) is in progress, we only wait for events from the current
thread (the one evaluating the condition).

In do_target_wait I had to change the inferior_matches lambda
function, which is used to select which inferior to wait on.
Previously the logic was this:

   auto inferior_matches = [&wait_ptid] (inferior *inf)
     {
       return (inf->process_target () != nullptr
               && ptid_t (inf->pid).matches (wait_ptid));
     };

This compares the pid of the inferior against the complete ptid we
want to wait on.  Before this commit wait_ptid was only ever
minus_one_ptid (which is special, and means any process), and so every
inferior would match.

After this commit though wait_ptid might represent a specific thread
in a specific inferior.  If we compare the pid of the inferior to a
specific ptid then these will not match.  The fix is to compare
against the pid extracted from the wait_ptid, not against the complete
wait_ptid itself.

In fetch_inferior_event, after receiving the event, we only want to
stop all the other threads, and call inferior_event_handler with
INF_EXEC_COMPLETE, if we are not evaluating a conditional breakpoint.
If we are, then all the other threads should be left doing whatever
they were before.  The inferior_event_handler call will be performed
once the breakpoint condition has finished being evaluated, and GDB
decides to stop or not.

The final problem that needs solving relates to GDB's commit-resume
mechanism, which allows GDB to collect resume requests into a single
packet in order to reduce traffic to a remote target.

The problem is that the commit-resume mechanism will not send any
resume requests for an inferior if there are already events pending on
the GDB side.

Imagine an inferior with two threads.  Both threads hit a breakpoint,
maybe the same conditional breakpoint.  At this point there are two
pending events, one for each thread.

GDB selects one of the events and spots that this is a conditional
breakpoint, GDB evaluates the condition.

The condition includes an inferior function call, so GDB sets up for
the call and resumes the one thread, the resume request is added to
the commit-resume queue.

When the commit-resume queue is committed GDB sees that there is a
pending event from another thread, and so doesn't send any resume
requests to the actual target, GDB is assuming that when we wait we
will select the event from the other thread.

However, as this is an inferior function call for a condition
evaluation, we will not select the event from the other thread, we
only care about events from the thread that is evaluating the
condition - and the resume for this thread was never sent to the
target.

And so, GDB hangs, waiting for an event from a thread that was never
fully resumed.

To fix this issue I have added the concept of "forcing" the
commit-resume queue.  When enabling commit resume, if the force flag
is true, then any resumes will be committed to the target, even if
there are other threads with pending events.

A note on authorship: this patch was based on some work done by
Natalia Saiapova and Tankut Baris Aktemur from Intel[1].  I have made
some changes to their work in this version.

Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=28942

[1] https://sourceware.org/pipermail/gdb-patches/2020-October/172454.html

Co-authored-by: Natalia Saiapova <natalia.saiapova@intel.com>
Co-authored-by: Tankut Baris Aktemur <tankut.baris.aktemur@intel.com>
---
 gdb/breakpoint.c                              |   2 +
 gdb/gdbthread.h                               |   3 +
 gdb/infcall.c                                 |   6 +
 gdb/infrun.c                                  |  64 +++--
 gdb/infrun.h                                  |   3 +-
 .../infcall-from-bp-cond-other-thread-event.c | 135 ++++++++++
 ...nfcall-from-bp-cond-other-thread-event.exp | 174 +++++++++++++
 .../gdb.threads/infcall-from-bp-cond-simple.c |  89 +++++++
 .../infcall-from-bp-cond-simple.exp           | 235 ++++++++++++++++++
 .../gdb.threads/infcall-from-bp-cond-single.c | 139 +++++++++++
 .../infcall-from-bp-cond-single.exp           | 117 +++++++++
 11 files changed, 952 insertions(+), 15 deletions(-)
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 89a0ffeabb9..eb1379ea6f1 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -5539,6 +5539,8 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
 	{
 	  try
 	    {
+	      scoped_restore reset_in_cond_eval
+		= make_scoped_restore (&thread->control.in_cond_eval, true);
 	      condition_result = breakpoint_cond_eval (cond);
 	    }
 	  catch (const gdb_exception_error &ex)
diff --git a/gdb/gdbthread.h b/gdb/gdbthread.h
index c0f27a8a66e..736d5d50b5f 100644
--- a/gdb/gdbthread.h
+++ b/gdb/gdbthread.h
@@ -171,6 +171,9 @@ struct thread_control_state
      command.  This is used to decide whether "set scheduler-locking
      step" behaves like "on" or "off".  */
   int stepping_command = 0;
+
+  /* True if the thread is evaluating a BP condition.  */
+  bool in_cond_eval = false;
 };
 
 /* Inferior thread specific part of `struct infcall_suspend_state'.  */
diff --git a/gdb/infcall.c b/gdb/infcall.c
index e6cc6ed1a21..4fb8ab07db0 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -641,6 +641,12 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
 
       proceed (real_pc, GDB_SIGNAL_0);
 
+      /* Enable commit resume, but pass true for the force flag.  This
+	 ensures any thread we set running in proceed will actually be
+	 committed to the target, even if some other thread in the current
+	 target has a pending event.  */
+      scoped_enable_commit_resumed enable ("infcall", true);
+
       infrun_debug_show_threads ("non-exited threads after proceed for inferior-call",
 				 all_non_exited_threads ());
 
diff --git a/gdb/infrun.c b/gdb/infrun.c
index aa1c9e94bda..b53c2c7dece 100644
--- a/gdb/infrun.c
+++ b/gdb/infrun.c
@@ -2219,6 +2219,14 @@ user_visible_resume_ptid (int step)
 	 mode.  */
       resume_ptid = inferior_ptid;
     }
+  else if (inferior_ptid != null_ptid
+	   && inferior_thread ()->control.in_cond_eval)
+    {
+      /* The inferior thread is evaluating a BP condition.  Other threads
+	 might be stopped or running and we do not want to change their
+	 state, thus, resume only the current thread.  */
+      resume_ptid = inferior_ptid;
+    }
   else if (!sched_multi && target_supports_multi_process ())
     {
       /* Resume all threads of the current process (and none of other
@@ -2953,12 +2961,24 @@ schedlock_applies (struct thread_info *tp)
 					    execution_direction)));
 }
 
-/* Set process_stratum_target::COMMIT_RESUMED_STATE in all target
-   stacks that have threads executing and don't have threads with
-   pending events.  */
+/* When FORCE_P is false, set process_stratum_target::COMMIT_RESUMED_STATE
+   in all target stacks that have threads executing and don't have threads
+   with pending events.
+
+   When FORCE_P is true, set process_stratum_target::COMMIT_RESUMED_STATE
+   in all target stacks that have threads executing regardless of whether
+   there are pending events or not.
+
+    Passing FORCE_P as false makes sense when GDB is going to wait for
+    events from all threads and will therefore spot the pending events.
+    However, if GDB is only going to wait for events from select threads
+    (i.e. when performing an inferior call) then a pending event on some
+    other thread will not be spotted, and if we fail to commit the resume
+    state for the thread performing the inferior call, then the inferior
+    call will never complete (or even start).  */
 
 static void
-maybe_set_commit_resumed_all_targets ()
+maybe_set_commit_resumed_all_targets (bool force_p)
 {
   scoped_restore_current_thread restore_thread;
 
@@ -2987,7 +3007,7 @@ maybe_set_commit_resumed_all_targets ()
 	 status to report, handle it before requiring the target to
 	 commit its resumed threads: handling the status might lead to
 	 resuming more threads.  */
-      if (proc_target->has_resumed_with_pending_wait_status ())
+      if (!force_p && proc_target->has_resumed_with_pending_wait_status ())
 	{
 	  infrun_debug_printf ("not requesting commit-resumed for target %s, a"
 			       " thread has a pending waitstatus",
@@ -2997,7 +3017,7 @@ maybe_set_commit_resumed_all_targets ()
 
       switch_to_inferior_no_thread (inf);
 
-      if (target_has_pending_events ())
+      if (!force_p && target_has_pending_events ())
 	{
 	  infrun_debug_printf ("not requesting commit-resumed for target %s, "
 			       "target has pending events",
@@ -3090,7 +3110,7 @@ scoped_disable_commit_resumed::reset ()
     {
       /* This is the outermost instance, re-enable
          COMMIT_RESUMED_STATE on the targets where it's possible.  */
-      maybe_set_commit_resumed_all_targets ();
+      maybe_set_commit_resumed_all_targets (false);
     }
   else
     {
@@ -3123,7 +3143,7 @@ scoped_disable_commit_resumed::reset_and_commit ()
 /* See infrun.h.  */
 
 scoped_enable_commit_resumed::scoped_enable_commit_resumed
-  (const char *reason)
+  (const char *reason, bool force_p)
   : m_reason (reason),
     m_prev_enable_commit_resumed (enable_commit_resumed)
 {
@@ -3135,7 +3155,7 @@ scoped_enable_commit_resumed::scoped_enable_commit_resumed
 
       /* Re-enable COMMIT_RESUMED_STATE on the targets where it's
 	 possible.  */
-      maybe_set_commit_resumed_all_targets ();
+      maybe_set_commit_resumed_all_targets (force_p);
 
       maybe_call_commit_resumed_all_targets ();
     }
@@ -3841,10 +3861,11 @@ do_target_wait (ptid_t wait_ptid, execution_control_state *ecs,
      polling the rest of the inferior list starting from that one in a
      circular fashion until the whole list is polled once.  */
 
-  auto inferior_matches = [&wait_ptid] (inferior *inf)
+  ptid_t wait_ptid_pid {wait_ptid.pid ()};
+  auto inferior_matches = [&wait_ptid_pid] (inferior *inf)
     {
       return (inf->process_target () != nullptr
-	      && ptid_t (inf->pid).matches (wait_ptid));
+	      && ptid_t (inf->pid).matches (wait_ptid_pid));
     };
 
   /* First see how many matching inferiors we have.  */
@@ -4313,7 +4334,17 @@ fetch_inferior_event ()
        the event.  */
     scoped_disable_commit_resumed disable_commit_resumed ("handling event");
 
-    if (!do_target_wait (minus_one_ptid, &ecs, TARGET_WNOHANG))
+    /* Is the current thread performing an inferior function call as part
+       of a breakpoint condition evaluation?  */
+    bool in_cond_eval = (inferior_ptid != null_ptid
+			 && inferior_thread ()->control.in_cond_eval);
+
+    /* If the thread is in the middle of the condition evaluation, wait for
+       an event from the current thread.  Otherwise, wait for an event from
+       any thread.  */
+    ptid_t waiton_ptid = in_cond_eval ? inferior_ptid : minus_one_ptid;
+
+    if (!do_target_wait (waiton_ptid, &ecs, TARGET_WNOHANG))
       {
 	infrun_debug_printf ("do_target_wait returned no event");
 	disable_commit_resumed.reset_and_commit ();
@@ -4365,7 +4396,12 @@ fetch_inferior_event ()
 	    bool should_notify_stop = true;
 	    bool proceeded = false;
 
-	    stop_all_threads_if_all_stop_mode ();
+	    /* If the thread that stopped just completed an inferior
+	       function call as part of a condition evaluation, then we
+	       don't want to stop all the other threads.  */
+	    if (ecs.event_thread == nullptr
+		|| !ecs.event_thread->control.in_cond_eval)
+	      stop_all_threads_if_all_stop_mode ();
 
 	    clean_up_just_stopped_threads_fsms (&ecs);
 
@@ -4380,7 +4416,7 @@ fetch_inferior_event ()
 		  proceeded = normal_stop ();
 	      }
 
-	    if (!proceeded)
+	    if (!proceeded && !in_cond_eval)
 	      {
 		inferior_event_handler (INF_EXEC_COMPLETE);
 		cmd_done = 1;
diff --git a/gdb/infrun.h b/gdb/infrun.h
index 5219063586d..f9d68e3db8b 100644
--- a/gdb/infrun.h
+++ b/gdb/infrun.h
@@ -402,7 +402,8 @@ extern void maybe_call_commit_resumed_all_targets ();
 
 struct scoped_enable_commit_resumed
 {
-  explicit scoped_enable_commit_resumed (const char *reason);
+  explicit scoped_enable_commit_resumed (const char *reason,
+					 bool force_p = false);
   ~scoped_enable_commit_resumed ();
 
   DISABLE_COPY_AND_ASSIGN (scoped_enable_commit_resumed);
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
new file mode 100644
index 00000000000..e2a8ccb4ebe
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
@@ -0,0 +1,135 @@
+/* Copyright 2022-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 <pthread.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <sched.h>
+
+#define NUM_THREADS 2
+
+pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+
+/* Some global variables to poke, just for something to do.  */
+volatile int global_var_0 = 0;
+volatile int global_var_1 = 0;
+
+/* This flag is updated from GDB.  */
+volatile int raise_signal = 0;
+
+/* Implement the breakpoint condition function.  Release the other thread
+   and try to give the other thread a chance to run.  Then return ANSWER.  */
+int
+condition_core_func (int answer)
+{
+  /* This unlock should release the other thread.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  /* And this yield and sleep should (hopefully) give the other thread a
+     chance to run.  This isn't guaranteed of course, but once the other
+     thread does run it should hit a breakpoint, which GDB should
+     (temporarily) ignore, so there's no easy way for us to know the other
+     thread has done what it needs to, thus, yielding and sleeping is the
+     best we can do.  */
+  sched_yield ();
+  sleep (2);
+
+  return answer;
+}
+
+void
+stop_marker ()
+{
+  int a = 100;	/* Final breakpoint here.  */
+}
+
+/* A breakpoint condition function that always returns true.  */
+int
+condition_true_func ()
+{
+  return condition_core_func (1);
+}
+
+/* A breakpoint condition function that always returns false.  */
+int
+condition_false_func ()
+{
+  return condition_core_func (0);
+}
+
+void *
+worker_func (void *arg)
+{
+  volatile int *ptr = 0;
+  int tid = *((int *) arg);
+
+  switch (tid)
+    {
+    case 0:
+      global_var_0 = 11;	/* First thread breakpoint.  */
+      break;
+
+    case 1:
+      if (pthread_mutex_lock (&mutex) != 0)
+	abort ();
+      if (raise_signal)
+	global_var_1 = *ptr;	/* Signal here.  */
+      else
+	global_var_1 = 99;	/* Other thread breakpoint.  */
+      break;
+
+    default:
+      abort ();
+    }
+
+  return NULL;
+}
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+
+  /* Set an alarm, just in case the test deadlocks.  */
+  alarm (300);
+
+  /* We want the mutex to start locked.  */
+  if (pthread_mutex_lock (&mutex) != 0)
+    abort ();
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      void *retval;
+      pthread_join (threads[i], &retval);
+    }
+
+  /* Unlock once we're done, just for cleanliness.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
new file mode 100644
index 00000000000..6d4e1e13ab2
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
@@ -0,0 +1,174 @@
+# Copyright 2022-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/>.
+
+# Test for conditional breakpoints where the breakpoint condition includes
+# an inferior function call.
+#
+# The tests in this script are testing what happens when an event arrives in
+# another thread while GDB is waiting for the inferior function call (in the
+# breakpoint condition) to finish.
+#
+# The expectation is that GDB will queue events for other threads and wait
+# for the inferior function call to complete, if the condition is true, then
+# the conditional breakpoint should be reported first.  The other thread
+# event should of course, not get lost, and should be reported as soon as
+# the user tries to continue the inferior.
+#
+# If the conditional breakpoint ends up not being taken (the condition is
+# false), then the other thread event should be reported immediately.
+#
+# This script tests what happens when the other thread event is (a) the
+# other thread hitting a breakpoint, and (b) the other thread taking a
+# signal (SIGSEGV in this case).
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] == -1 } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "First thread breakpoint"]
+set other_bp_line [gdb_get_line_number "Other thread breakpoint"]
+set final_bp_line [gdb_get_line_number "Final breakpoint here"]
+set signal_line [gdb_get_line_number "Signal here"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if { ![runto_main] } {
+	return -1
+    }
+
+    return 0
+}
+
+# Run a test of GDB's conditional breakpoints, where the conditions include
+# inferior function calls.  While the inferior function call is executing
+# another thread will hit a breakpoint (when OTHER_THREAD_SIGNAL is false),
+# or receive a signal (when OTHER_THREAD_SIGNAL is true).  GDB should report
+# the conditional breakpoint first (if the condition is true), and then
+# report the second thread event once the inferior is continued again.
+#
+# When STOP_AT_COND is true then the conditional breakpoint will have a
+# condition that evaluates to true (and the GDB will stop at the
+# breakpoint), otherwise, the condition will evaluate to false (and GDB will
+# not stop at the breakpoint).
+proc run_condition_test { stop_at_cond other_thread_signal \
+			      target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint.
+    if { $stop_at_cond } {
+	set cond_func "condition_true_func"
+    } else {
+	set cond_func "condition_false_func"
+    }
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (${cond_func} ())"
+    set cond_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			"get number for conditional breakpoint"]
+
+    if { $other_thread_signal } {
+	# Arrange for the other thread to raise a signal while GDB is
+	# evaluating the breakpoint condition.
+	gdb_test_no_output "set raise_signal = 1"
+    } else {
+	# And a breakpoint that will be hit by another thread only once the
+	# breakpoint condition starts to be evaluated.
+	gdb_breakpoint "${::srcfile}:${::other_bp_line}"
+	set other_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			      "get number for other breakpoint"]
+    }
+
+    # A final breakpoint once the test has completed.
+    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
+    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			  "get number for final breakpoint"]
+
+    if { $stop_at_cond } {
+	# Continue.  The first breakpoint we hit should be the conditional
+	# breakpoint.  The other thread will have hit its breakpoint, but
+	# that will have been deferred until the conditional breakpoint is
+	# reported.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${cond_bp_num}, worker_func \[^\r\n\]+:${::cond_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+First thread breakpoint\[^\r\n\]+"] \
+	    "hit the conditional breakpoint"
+    }
+
+    if { $other_thread_signal } {
+	# Now continue again, the other thread will now report that it
+	# received a signal.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" received signal SIGSEGV, Segmentation fault\\." \
+		 "\\\[Switching to Thread \[^\r\n\]+\\\]" \
+		 "${::hex} in worker_func \[^\r\n\]+:${::signal_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Signal here\[^\r\n\]+"] \
+	    "received signal in other thread"
+    } else {
+	# Now continue again, the other thread will now report its
+	# breakpoint.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${other_bp_num}, worker_func \[^\r\n\]+:${::other_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Other thread breakpoint\[^\r\n\]+"] \
+	    "hit the breakpoint in other thread"
+
+	# Run to the stop marker.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${final_bp_num}, stop_marker \[^\r\n\]+:${::final_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Final breakpoint here\[^\r\n\]+"] \
+	    "hit the final breakpoint"
+    }
+
+    gdb_exit
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	foreach_with_prefix other_thread_signal { true false } {
+	    foreach_with_prefix stop_at_cond { true false } {
+		run_condition_test $stop_at_cond $other_thread_signal \
+		    $target_async $target_non_stop
+	    }
+	}
+    }
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
new file mode 100644
index 00000000000..9d746d8be49
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
@@ -0,0 +1,89 @@
+/* Copyright 2022-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 <pthread.h>
+#include <unistd.h>
+
+#define NUM_THREADS 3
+
+int
+is_matching_tid (int *tid_ptr, int tid_value)
+{
+  return *tid_ptr == tid_value;
+}
+
+int
+return_true ()
+{
+  return 1;
+}
+
+int
+return_false ()
+{
+  return 0;
+}
+
+int
+function_that_segfaults ()
+{
+  int *p = 0;
+  *p = 1;	/* Segfault happens here.   */
+}
+
+int
+function_with_breakpoint ()
+{
+  return 1;	/* Nested breakpoint.  */
+}
+
+void *
+worker_func (void *arg)
+{
+  int a = 42;	/* Breakpoint here.  */
+}
+
+void
+stop_marker ()
+{
+  int b = 99;	/* Stop marker.  */
+}
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+
+  alarm (300);
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      void *retval;
+      pthread_join (threads[i], &retval);
+    }
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
new file mode 100644
index 00000000000..37e1b64d9a4
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
@@ -0,0 +1,235 @@
+# Copyright 2022-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/>.
+
+# Some simple tests of inferior function calls from breakpoint
+# conditions, in multi-threaded inferiors.
+#
+# This test sets up a multi-threaded inferior, and places a breakpoint
+# at a location that many of the threads will reach.  We repeat the
+# test with different conditions, sometimes a single thread should
+# stop at the breakpoint, sometimes multiple threads should stop, and
+# sometime no threads should stop.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] == -1 } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "Breakpoint here"]
+set stop_bp_line [gdb_get_line_number "Stop marker"]
+set nested_bp_line [gdb_get_line_number "Nested breakpoint"]
+set segv_line [gdb_get_line_number "Segfault happens here"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if { ![runto_main] } {
+	return -1
+    }
+
+    return 0
+}
+
+# Run a test of GDB's conditional breakpoints, where the conditions include
+# inferior function calls.
+#
+# CONDITION is the expression to be used as the breakpoint condition.
+#
+# N_EXPECTED_HITS is the number of threads that we expect to stop due to
+# CONDITON.
+#
+# MESSAGE is used as a test name prefix.
+proc run_condition_test { message n_expected_hits condition \
+			      target_async target_non_stop } {
+    with_test_prefix $message {
+
+	if { [start_gdb_and_runto_main $target_async \
+		  $target_non_stop] == -1 } {
+	    return
+	}
+
+	# Use this convenience variable to track how often the
+	# breakpoint condition has been evaluated.  This should be
+	# once per thread.
+	gdb_test "set \$n_cond_eval = 0"
+
+	# Setup the conditional breakpoint.
+	gdb_breakpoint \
+	    "${::srcfile}:${::cond_bp_line} if ((++\$n_cond_eval) && (${condition}))"
+
+	# And a breakpoint that we hit when the test is over, this one is
+	# not conditional.  Only the main thread gets here once all the
+	# other threads have finished.
+	gdb_breakpoint "${::srcfile}:${::stop_bp_line}"
+
+	# The number of times we stop at the conditional breakpoint.
+	set n_hit_condition 0
+
+	# Now keep 'continue'-ing GDB until all the threads have finished
+	# and we reach the stop_marker breakpoint.
+	gdb_test_multiple "continue" "spot all breakpoint hits" {
+	    -re " worker_func \[^\r\n\]+${::srcfile}:${::cond_bp_line}\r\n${::decimal}\\s+\[^\r\n\]+Breakpoint here\[^\r\n\]+\r\n${::gdb_prompt} $" {
+		incr n_hit_condition
+		send_gdb "continue\n"
+		exp_continue
+	    }
+
+	    -re " stop_marker \[^\r\n\]+${::srcfile}:${::stop_bp_line}\r\n${::decimal}\\s+\[^\r\n\]+Stop marker\[^\r\n\]+\r\n${::gdb_prompt} $" {
+		pass $gdb_test_name
+	    }
+	}
+
+	gdb_assert { $n_hit_condition == $n_expected_hits } \
+	    "stopped at breakpoint the expected number of times"
+
+	# Ensure the breakpoint condition was evaluated once per thread.
+	gdb_test "print \$n_cond_eval" "= 3" \
+	    "condition was evaluated in each thread"
+    }
+}
+
+# Check that after handling a conditional breakpoint (where the condition
+# includes an inferior call), it is still possible to kill the running
+# inferior, and then restart the inferior.
+#
+# At once point doing this would result in GDB giving an assertion error.
+proc_with_prefix run_kill_and_restart_test { target_async target_non_stop } {
+    # This test relies on the 'start' command, which is not possible with
+    # the plain 'remote' target.
+    if { [target_info gdb_protocol] == "remote" } {
+	return
+    }
+
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint.
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 1))"
+    gdb_continue_to_breakpoint "worker_func"
+
+    # Now kill the program being debugged.
+    gdb_test "kill" "" "kill process" \
+	"Kill the program being debugged.*y or n. $" "y"
+
+    # Check we can restart the inferior.  At one point this would trigger an
+    # assertion.
+    gdb_test "start" ".*"
+}
+
+# Create a conditional breakpoint which includes a call to a function that
+# segfaults.  Run GDB and check what happens when the inferior segfaults
+# during the inferior call.
+proc_with_prefix run_bp_cond_segfaults { target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # This test relies on the inferior segfaulting when trying to
+    # access address zero.
+    if { [is_address_zero_readable] } {
+	return
+    }
+
+    # Setup the conditional breakpoint, include a call to
+    # 'function_that_segfaults', which triggers the segfault.
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 0) && function_that_segfaults ())"
+    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of conditional breakpoint"]
+
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     ".*" \
+	     "Thread ${::decimal} \"infcall-from-bp\" received signal SIGSEGV, Segmentation fault\\." \
+	     "${::hex} in function_that_segfaults \\(\\) at \[^\r\n\]+:${::segv_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Segfault happens here\[^\r\n\]+" \
+	     "Error in testing condition for breakpoint ${bp_1_num}:" \
+	     "The program being debugged was signaled while in a function called from GDB\\." \
+	     "GDB remains in the frame where the signal was received\\." \
+	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(function_that_segfaults\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+}
+
+# Create a conditional breakpoint which includes a call to a function that
+# itself has a breakpoint set within it.  Run GDB and check what happens
+# when GDB hits the nested breakpoint.
+proc_with_prefix run_bp_cond_hits_breakpoint { target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint, include a call to
+    # 'function_with_breakpoint' in which we will shortly place a
+    # breakpoint.
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 0) && function_with_breakpoint ())"
+    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of conditional breakpoint"]
+
+    gdb_breakpoint "${::srcfile}:${::nested_bp_line}"
+    set bp_2_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of nested breakpoint"]
+
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     ".*" \
+	     "Thread ${::decimal} \"infcall-from-bp\" hit Breakpoint ${bp_2_num}, function_with_breakpoint \\(\\) at \[^\r\n\]+:${::nested_bp_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Nested breakpoint\[^\r\n\]+" \
+	     "Error in testing condition for breakpoint ${bp_1_num}:" \
+	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(function_with_breakpoint\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	run_condition_test "exactly one thread is hit" \
+	    1 "is_matching_tid (arg, 1)" \
+	    $target_async $target_non_stop
+	run_condition_test "exactly two threads are hit" \
+	    2 "(is_matching_tid (arg, 0) || is_matching_tid (arg, 2))" \
+	    $target_async $target_non_stop
+	run_condition_test "all three threads are hit" \
+	    3 "return_true ()" \
+	    $target_async $target_non_stop
+	run_condition_test "no thread is hit" \
+	    0 "return_false ()" \
+	    $target_async $target_non_stop
+
+	run_kill_and_restart_test $target_async $target_non_stop
+	run_bp_cond_segfaults $target_async $target_non_stop
+	run_bp_cond_hits_breakpoint $target_async $target_non_stop
+    }
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
new file mode 100644
index 00000000000..835c72f03cf
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
@@ -0,0 +1,139 @@
+/* Copyright 2022-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 <pthread.h>
+#include <unistd.h>
+#include <semaphore.h>
+#include <stdlib.h>
+
+#define NUM_THREADS 5
+
+/* Semaphores, used to track when threads have started, and to control
+   when the threads finish.  */
+sem_t startup_semaphore;
+sem_t finish_semaphore;
+
+/* Mutex to control when the first worker thread hit a breakpoint
+   location.  */
+pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+
+/* Global variable to poke, just so threads have something to do.  */
+volatile int global_var = 0;
+
+int
+return_true ()
+{
+  return 1;
+}
+
+int
+return_false ()
+{
+  return 0;
+}
+
+void *
+worker_func (void *arg)
+{
+  int tid = *((int *) arg);
+
+  switch (tid)
+    {
+    case 0:
+      /* Wait for MUTEX to become available, then pass through the
+	 conditional breakpoint location.  */
+      if (pthread_mutex_lock (&mutex) != 0)
+	abort ();
+      global_var = 99;	/* Conditional breakpoint here.  */
+      if (pthread_mutex_unlock (&mutex) != 0)
+	abort ();
+      break;
+
+    default:
+      /* Notify the main thread that the thread has started, then wait for
+	 the main thread to tell us to finish.  */
+      sem_post (&startup_semaphore);
+      if (sem_wait (&finish_semaphore) != 0)
+	abort ();
+      break;
+    }
+}
+
+void
+stop_marker ()
+{
+  global_var = 99;	/* Stop marker.  */
+}
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+  void *retval;
+
+  /* An alarm, just in case the thread deadlocks.  */
+  alarm (300);
+
+  /* Semaphore initialization.  */
+  if (sem_init (&startup_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&finish_semaphore, 0, 0) != 0)
+    abort ();
+
+  /* Lock MUTEX, this prevents the first worker thread from rushing ahead.  */
+  if (pthread_mutex_lock (&mutex) != 0)
+    abort ();
+
+  /* Worker thread creation.  */
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  /* Wait for every thread (other than the first) to tell us it has started
+     up.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    {
+      if (sem_wait (&startup_semaphore) != 0)
+	abort ();
+    }
+
+  /* Unlock the first thread so it can proceed.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  /* Wait for the first thread only.  */
+  pthread_join (threads[0], &retval);
+
+  /* Now post FINISH_SEMAPHORE to allow all the other threads to finish.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    sem_post (&finish_semaphore);
+
+  /* Now wait for the remaining threads to complete.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    pthread_join (threads[i], &retval);
+
+  /* Semaphore cleanup.  */
+  sem_destroy (&finish_semaphore);
+  sem_destroy (&startup_semaphore);
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
new file mode 100644
index 00000000000..787dee3aa8e
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
@@ -0,0 +1,117 @@
+# Copyright 2022-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 reprocuces bug gdb/28942, performing an inferior function
+# call from a breakpoint condition in a multi-threaded inferior.
+#
+# The important part of this test is that, when the conditional
+# breakpoint is hit, and the condition (which includes an inferior
+# function call) is evaluated, the other threads are running.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] == -1 } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "Conditional breakpoint here"]
+set final_bp_line [gdb_get_line_number "Stop marker"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if { ![runto_main] } {
+	return -1
+    }
+
+    return 0
+}
+
+# Run a test of GDB's conditional breakpoints, where the conditions include
+# inferior function calls.
+#
+# TARGET_ASYNC and TARGET_NON_STOP are used when starting up GDB.
+#
+# When STOP_AT_COND is true the breakpoint condtion will evaluate to
+# true, and GDB will stop at the breakpoint.  Otherwise, the
+# breakpoint condition will evaluate to false and GDB will not stop at
+# the breakpoint.
+proc run_condition_test { stop_at_cond \
+			      target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint.
+    if { $stop_at_cond } {
+	set cond_func "return_true"
+    } else {
+	set cond_func "return_false"
+    }
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (${cond_func} ())"
+    set cond_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			"get number for conditional breakpoint"]
+
+    # And a breakpoint that we hit when the test is over, this one is
+    # not conditional.
+    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
+    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			  "get number for final breakpoint"]
+
+    if { $stop_at_cond } {
+	# Continue.  The first breakpoint we hit should be the conditional
+	# breakpoint.  The other thread will have hit its breakpoint, but
+	# that will have been deferred until the conditional breakpoint is
+	# reported.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${cond_bp_num}, worker_func \[^\r\n\]+:${::cond_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Conditional breakpoint here\[^\r\n\]+"] \
+	    "hit the conditional breakpoint"
+    }
+
+    # Run to the stop marker.
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     ".*" \
+	     "" \
+	     "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${final_bp_num}, stop_marker \[^\r\n\]+:${::final_bp_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Stop marker\[^\r\n\]+"] \
+	"hit the final breakpoint"
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	foreach_with_prefix stop_at_cond { true false } {
+	    run_condition_test $stop_at_cond \
+		$target_async $target_non_stop
+	}
+    }
+}
-- 
2.25.4


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

* [PATCHv4 09/12] gdb: add timeouts for inferior function calls
  2023-02-28 16:42     ` [PATCHv4 00/12] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                         ` (7 preceding siblings ...)
  2023-02-28 16:42       ` [PATCHv4 08/12] gdb: fix b/p conditions with infcalls in multi-threaded inferiors Andrew Burgess
@ 2023-02-28 16:42       ` Andrew Burgess
  2023-02-28 16:42       ` [PATCHv4 10/12] gdb/remote: avoid SIGINT after calling remote_target::stop Andrew Burgess
                         ` (3 subsequent siblings)
  12 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-02-28 16:42 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Eli already approved the docs part:
  https://sourceware.org/pipermail/gdb-patches/2023-January/196462.html

---

In the previous commits I have been working on improving inferior
function call support.  One thing that worries me about using inferior
function calls from a conditional breakpoint is: what happens if the
inferior function call fails?

If the failure is obvious, e.g. the thread performing the call
crashes, or hits a breakpoint, then this case is already well handled,
and the error is reported to the user.

But what if the thread performing the inferior call just deadlocks?
If the user made the call from a 'print' or 'call' command, then the
user might have some expectation of when the function call should
complete, and, when this time limit is exceeded, the user
will (hopefully) interrupt GDB and regain control of the debug
session.

But, when the inferior function call is from a breakpoint condition it
is much harder to understand that GDB is deadlocked within an inferior
call.  Maybe the breakpoint hasn't been hit yet?  Or maybe the
condition was always false?  Or maybe GDB is deadlocked in an inferior
call?  The only way to know for sure is to periodically interrupt GDB,
check on all the threads, and then continue.

Additionally, the focus of the previous commit was inferior function
calls, from a conditional breakpoint, in a multi-threaded inferior.
This opens up a whole new set of potential failure conditions.  For
example, what if the function called relies on interaction with some
other thread, and the other thread crashes?  Or hits a breakpoint?
Given how inferior function calls work (in a synchronous manner), a
stop event in some other thread is going to be ignored while the
inferior function call is being executed as part of a breakpoint
condition, and this means that GDB could get stuck waiting for the
original condition thread, which will now never complete.

In this commit I propose a solution to this problem.  A timeout.  For
targets that support async-mode we can install an event-loop timer
before starting the inferior function call.  When the timer expires we
will stop the thread performing the inferior function call.  With this
mechanism in place a user can be sure that any inferior call they make
will either complete, or timeout eventually.

Adding a timer like this is obviously a change in behaviour for the
more common 'call' and 'print' uses of inferior function calls, so, in
this patch, I propose having two different timers.  One I call the
'direct-call-timeout', which is used for 'call' and 'print' commands.
This timeout is by default set to unlimited, which, not surprisingly,
means there is no timeout in place.

A second timer, which I've called 'indirect-call-timeout', is used for
inferior function calls from breakpoint conditions.  This timeout has
a default value of 30 seconds.  This is a reasonably long time to
wait, and hopefully should be enough in most cases to allow the
inferior call to complete.  An inferior call that takes more than 30
seconds, which is installed on a breakpoint condition is really going
to slow down the debug session, so hopefully this is not a common use
case.

The user is, of course, free to reduce, or increase the timeout value,
and can always use Ctrl-c to interrupt an inferior function call, but
this timeout will ensure that GDB will stop at some point.

The new commands added by this commit are:

  set direct-call-timeout SECONDS
  show direct-call-timeout
  set indirect-call-timeout SECONDS
  show indirect-call-timeout

These new timeouts do depend on async-mode, so, if async-mode is
disabled (maint set target-async off), or not supported (e.g. target
sim), then the timeout is treated as unlimited (that is, no timeout is
set).

For targets that "fake" non-async mode, e.g. Linux native, where
non-async mode is really just async mode, but then we park the target
in a sissuspend, we could easily fix things so that the timeouts still
work, however, for targets that really are not async aware, like the
simulator, fixing things so that timeouts work correctly would be a
much bigger task - that effort would be better spent just making the
target async-aware.  And so, I'm happy for now that this feature will
only work on async targets.

The two new show commands will display slightly different text if the
current target is a non-async target, which should allow users to
understand what's going on.

There's a somewhat random test adjustment needed in gdb.base/help.exp,
the test uses a regexp with the apropos command, and expects to find a
single result.  Turns out the new settings I added also matched the
regexp, which broke the test.  I've updated the regexp a little to
exclude my new settings.

In infcall.c you'll notice the thread_info::stop_requested flag being
set when a timeout occurs.  This flag setting is not required as part
of this commit, but will be needed in a later commit.  However, it
seemed like setting this flag fitted better with this commit, which is
why the change is added here.
---
 gdb/NEWS                                      |  18 ++
 gdb/doc/gdb.texinfo                           |  66 ++++++
 gdb/infcall.c                                 | 221 +++++++++++++++++-
 gdb/testsuite/gdb.base/help.exp               |   2 +-
 gdb/testsuite/gdb.base/infcall-timeout.c      |  36 +++
 gdb/testsuite/gdb.base/infcall-timeout.exp    |  82 +++++++
 .../infcall-from-bp-cond-timeout.c            | 169 ++++++++++++++
 .../infcall-from-bp-cond-timeout.exp          | 156 +++++++++++++
 8 files changed, 745 insertions(+), 5 deletions(-)
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.c
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp

diff --git a/gdb/NEWS b/gdb/NEWS
index bea604d7e75..a8827cddd61 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -78,6 +78,24 @@ maintenance info frame-unwinders
    $2 = 1
    (gdb) break func if $_shell("some command") == 0
 
+set direct-call-timeout SECONDS
+show direct-call-timeout
+set indirect-call-timeout SECONDS
+show indirect-call-timeout
+  These new settings can be used to limit how long GDB will wait for
+  an inferior function call to complete.  The direct timeout is used
+  for inferior function calls from e.g. 'call' and 'print' commands,
+  while the indirect timeout is used for inferior function calls from
+  within a conditional breakpoint expression.
+
+  The default for the direct timeout is unlimited, while the default
+  for the indirect timeout is 30 seconds.
+
+  These timeouts will only have an effect for targets that are
+  operating in async mode.  For non-async targets the timeouts are
+  ignored, GDB will wait indefinitely for an inferior function to
+  complete, unless interrupted by the user using Ctrl-C.
+
 * MI changes
 
 ** mi now reports 'no-history' as a stop reason when hitting the end of the
diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index 1170a2dacc3..5cc8b0e811c 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -20868,6 +20868,72 @@
 @code{step}, etc).  In this case, when the inferior finally returns to
 the dummy-frame, @value{GDBN} will once again halt the inferior.
 
+On targets that support asynchronous execution (@pxref{Background
+Execution}) @value{GDBN} can place a timeout on any functions called
+from @value{GDBN}.  If the timeout expires and the function call is
+still ongoing, then @value{GDBN} will interrupt the program.
+
+For targets that don't support asynchronous execution
+(@pxref{Background Execution}) then timeouts for functions called from
+@value{GDBN} are not supported, the timeout settings described below
+will be treated as @code{unlimited}, meaning @value{GDBN} will wait
+indefinitely for function call to complete, unless interrupted by the
+user using @kbd{Ctrl-C}.
+
+@table @code
+@item set direct-call-timeout @var{seconds}
+@kindex set direct-call-timeout
+@cindex timeout for called functions
+Set the timeout used when calling functions in the program to
+@var{seconds}, which should be an integer greater than zero, or the
+special value @code{unlimited}, which indicates no timeout should be
+used.  The default for this setting is @code{unlimited}.
+
+This setting is used when the user calls a function directly from the
+command prompt, for example with a @code{call} or @code{print}
+command.
+
+This setting only works for targets that support asynchronous
+execution (@pxref{Background Execution}), for any other target the
+setting is treated as @code{unlimited}.
+
+@item show direct-call-timeout
+@kindex show direct-call-timeout
+@cindex timeout for called functions
+Show the timeout used when calling functions in the program with a
+@code{call} or @code{print} command.
+@end table
+
+It is also possible to call functions within the program from the
+condition of a conditional breakpoint (@pxref{Conditions, ,Break
+Conditions}).  A different setting controls the timeout used for
+function calls made from a breakpoint condition.
+
+@table @code
+@item set indirect-call-timeout @var{seconds}
+@kindex set indirect-call-timeout
+@cindex timeout for called functions
+Set the timeout used when calling functions in the program from a
+breakpoint or watchpoint condition to @var{seconds}, which should be
+an integer greater than zero, or the special value @code{unlimited},
+which indicates no timeout should be used.  The default for this
+setting is @code{30} seconds.
+
+This setting only works for targets that support asynchronous
+execution (@pxref{Background Execution}), for any other target the
+setting is treated as @code{unlimited}.
+
+If a function called from a breakpoint or watchpoint condition times
+out, then @value{GDBN} will stop at the point where the timeout
+occurred.  The breakpoint condition evaluation will be abandoned.
+
+@item show indirect-call-timeout
+@kindex show indirect-call-timeout
+@cindex timeout for called functions
+Show the timeout used when calling functions in the program from a
+breakpoint or watchpoint condition.
+@end table
+
 @subsection Calling functions with no debug info
 
 @cindex no debug info functions
diff --git a/gdb/infcall.c b/gdb/infcall.c
index 4fb8ab07db0..bb57faf700f 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -95,6 +95,53 @@ show_may_call_functions_p (struct ui_file *file, int from_tty,
 	      value);
 }
 
+/* A timeout (in seconds) for direct inferior calls.  A direct inferior
+   call is one the user triggers from the prompt, e.g. with a 'call' or
+   'print' command.  Compare with the definition of indirect calls below.  */
+
+static unsigned int direct_call_timeout = UINT_MAX;
+
+/* Implement 'show direct-call-timeout'.  */
+
+static void
+show_direct_call_timeout (struct ui_file *file, int from_tty,
+			  struct cmd_list_element *c, const char *value)
+{
+  if (target_has_execution () && !target_can_async_p ())
+    gdb_printf (file, _("Current target does not support async mode, timeout "
+			"for direct inferior calls is \"unlimited\".\n"));
+  else if (direct_call_timeout == UINT_MAX)
+    gdb_printf (file, _("Timeout for direct inferior function calls "
+			"is \"unlimited\".\n"));
+  else
+    gdb_printf (file, _("Timeout for direct inferior function calls "
+			"is \"%s seconds\".\n"), value);
+}
+
+/* A timeout (in seconds) for indirect inferior calls.  An indirect inferior
+   call is one that originates from within GDB, for example, when
+   evaluating an expression for a conditional breakpoint.  Compare with
+   the definition of direct calls above.  */
+
+static unsigned int indirect_call_timeout = 30;
+
+/* Implement 'show indirect-call-timeout'.  */
+
+static void
+show_indirect_call_timeout (struct ui_file *file, int from_tty,
+			  struct cmd_list_element *c, const char *value)
+{
+  if (target_has_execution () && !target_can_async_p ())
+    gdb_printf (file, _("Current target does not support async mode, timeout "
+			"for indirect inferior calls is \"unlimited\".\n"));
+  else if (indirect_call_timeout == UINT_MAX)
+    gdb_printf (file, _("Timeout for indirect inferior function calls "
+			"is \"unlimited\".\n"));
+  else
+    gdb_printf (file, _("Timeout for indirect inferior function calls "
+			"is \"%s seconds\".\n"), value);
+}
+
 /* How you should pass arguments to a function depends on whether it
    was defined in K&R style or prototype style.  If you define a
    function using the K&R syntax that takes a `float' argument, then
@@ -589,6 +636,86 @@ call_thread_fsm::should_notify_stop ()
   return true;
 }
 
+/* A class to control creation of a timer that will interrupt a thread
+   during an inferior call.  */
+struct infcall_timer_controller
+{
+  /* Setup an event-loop timer that will interrupt PTID if the inferior
+     call takes too long.  DIRECT_CALL_P is true when this inferior call is
+     a result of the user using a 'print' or 'call' command, and false when
+     this inferior call is a result of e.g. a conditional breakpoint
+     expression, this is used to select which timeout to use.  */
+  infcall_timer_controller (thread_info *thr, bool direct_call_p)
+    : m_thread (thr)
+  {
+    unsigned int timeout
+      = direct_call_p ? direct_call_timeout : indirect_call_timeout;
+    if (timeout < UINT_MAX && target_can_async_p ())
+      {
+	int ms = timeout * 1000;
+	int id = create_timer (ms, infcall_timer_controller::timed_out, this);
+	m_timer_id.emplace (id);
+	infcall_debug_printf ("Setting up infcall timeout timer for "
+			      "ptid %s: %d milliseconds",
+			      m_thread->ptid.to_string ().c_str (), ms);
+      }
+  }
+
+  /* Destructor.  Ensure that the timer is removed from the event loop.  */
+  ~infcall_timer_controller ()
+  {
+    /* If the timer has already triggered, then it will have already been
+       deleted from the event loop.  If the timer has not triggered, then
+       delete it now.  */
+    if (m_timer_id.has_value () && !m_triggered)
+      delete_timer (*m_timer_id);
+
+    /* Just for clarity, discard the timer id now.  */
+    m_timer_id.reset ();
+  }
+
+  /* Return true if there was a timer in place, and the timer triggered,
+     otherwise, return false.  */
+  bool triggered_p ()
+  {
+    gdb_assert (!m_triggered || m_timer_id.has_value ());
+    return m_triggered;
+  }
+
+private:
+  /* The thread we should interrupt.  */
+  thread_info *m_thread;
+
+  /* Set true when the timer is triggered.  */
+  bool m_triggered = false;
+
+  /* Given a value when a timer is in place.  */
+  gdb::optional<int> m_timer_id;
+
+  /* Callback for the timer, forwards to ::trigger below.  */
+  static void
+  timed_out (gdb_client_data context)
+  {
+    infcall_timer_controller *ctrl
+      = static_cast<infcall_timer_controller *> (context);
+    ctrl->trigger ();
+  }
+
+  /* Called when the timer goes off.  Stop thread m_thread.  */
+  void
+  trigger ()
+  {
+    m_triggered = true;
+
+    scoped_disable_commit_resumed disable_commit_resumed ("infcall timeout");
+
+    infcall_debug_printf ("Stopping thread %s",
+			  m_thread->ptid.to_string ().c_str ());
+    target_stop (m_thread->ptid);
+    m_thread->stop_requested = true;
+  }
+};
+
 /* Subroutine of call_function_by_hand to simplify it.
    Start up the inferior and wait for it to stop.
    Return the exception if there's an error, or an exception with
@@ -599,13 +726,15 @@ call_thread_fsm::should_notify_stop ()
 
 static struct gdb_exception
 run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
-		   struct thread_info *call_thread, CORE_ADDR real_pc)
+		   struct thread_info *call_thread, CORE_ADDR real_pc,
+		   bool *timed_out_p)
 {
   INFCALL_SCOPED_DEBUG_ENTER_EXIT;
 
   struct gdb_exception caught_error;
   ptid_t call_thread_ptid = call_thread->ptid;
   int was_running = call_thread->state == THREAD_RUNNING;
+  *timed_out_p = false;
 
   infcall_debug_printf ("call function at %s in thread %s, was_running = %d",
 			core_addr_to_string (real_pc),
@@ -617,6 +746,16 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
   scoped_restore restore_in_infcall
     = make_scoped_restore (&call_thread->control.in_infcall, 1);
 
+  /* If the thread making the inferior call stops with a time out then the
+     stop_requested flag will be set.  However, we don't want changes to
+     this flag to leak back to our caller, we might be here to handle an
+     inferior call from a breakpoint condition, so leaving this flag set
+     would appear that the breakpoint stop was actually a requested stop,
+     which is not true, and will cause GDB to print extra messages to the
+     output.  */
+  scoped_restore restore_stop_requested
+    = make_scoped_restore (&call_thread->stop_requested, false);
+
   clear_proceed_status (0);
 
   /* Associate the FSM with the thread after clear_proceed_status
@@ -650,11 +789,23 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
       infrun_debug_show_threads ("non-exited threads after proceed for inferior-call",
 				 all_non_exited_threads ());
 
+      /* Setup a timer (if possible, and if the settings allow) to prevent
+	 the inferior call running forever.  */
+      bool direct_call_p = !call_thread->control.in_cond_eval;
+      infcall_timer_controller infcall_timer (call_thread, direct_call_p);
+
       /* Inferior function calls are always synchronous, even if the
 	 target supports asynchronous execution.  */
       wait_sync_command_done ();
 
-      infcall_debug_printf ("inferior call completed successfully");
+      /* If the timer triggered then the inferior call failed.  */
+      if (infcall_timer.triggered_p ())
+	{
+	  infcall_debug_printf ("inferior call timed out");
+	  *timed_out_p = true;
+	}
+      else
+	infcall_debug_printf ("inferior call completed successfully");
     }
   catch (gdb_exception &e)
     {
@@ -1308,6 +1459,10 @@ call_function_by_hand_dummy (struct value *function,
   scoped_restore restore_stopped_by_random_signal
     = make_scoped_restore (&stopped_by_random_signal, 0);
 
+  /* Set to true by the call to run_inferior_call below if the inferior
+     call is artificially interrupted by GDB due to taking too long.  */
+  bool timed_out_p = false;
+
   /* - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP -
      If you're looking to implement asynchronous dummy-frames, then
      just below is the place to chop this function in two..  */
@@ -1334,7 +1489,8 @@ call_function_by_hand_dummy (struct value *function,
 			      struct_addr);
     {
       std::unique_ptr<call_thread_fsm> sm_up (sm);
-      e = run_inferior_call (std::move (sm_up), call_thread.get (), real_pc);
+      e = run_inferior_call (std::move (sm_up), call_thread.get (), real_pc,
+			     &timed_out_p);
     }
 
     if (e.reason < 0)
@@ -1486,7 +1642,10 @@ When the function is done executing, GDB will silently stop."),
       std::string name = get_function_name (funaddr, name_buf,
 					    sizeof (name_buf));
 
-      if (stopped_by_random_signal)
+      /* If the inferior call timed out then it will have been interrupted
+	 by a signal, but we want to report this differently to the user,
+	 which is done later in this function.  */
+      if (stopped_by_random_signal && !timed_out_p)
 	{
 	  /* We stopped inside the FUNCTION because of a random
 	     signal.  Further execution of the FUNCTION is not
@@ -1530,6 +1689,36 @@ GDB remains in the frame where the signal was received.\n\
 To change this behavior use \"set unwindonsignal on\".\n\
 Evaluation of the expression containing the function\n\
 (%s) will be abandoned.\n\
+When the function is done executing, GDB will silently stop."),
+		     name.c_str ());
+	    }
+	}
+
+      if (timed_out_p)
+	{
+	  /* A timeout results in a signal being sent to the inferior.  */
+	  gdb_assert (stopped_by_random_signal);
+
+	  /* Indentation is weird here.  A later patch is going to move the
+	    following block into an if/else, so I'm leaving the indentation
+	    here to minimise the later patch.
+
+	    Also, the error message used below refers to 'set
+	    unwind-on-timeout' which doesn't exist yet.  This will be added
+	    in a later commit, I'm leaving this in for now to minimise the
+	    churn caused by the commit that adds unwind-on-timeout.  */
+	    {
+	      /* The user wants to stay in the frame where we stopped
+		 (default).  Discard inferior status, we're not at the same
+		 point we started at.  */
+	      discard_infcall_control_state (inf_status.release ());
+
+	      error (_("\
+The program being debugged timed out while in a function called from GDB.\n\
+GDB remains in the frame where the timeout occurred.\n\
+To change this behavior use \"set unwind-on-timeout on\".\n\
+Evaluation of the expression containing the function\n\
+(%s) will be abandoned.\n\
 When the function is done executing, GDB will silently stop."),
 		     name.c_str ());
 	    }
@@ -1643,6 +1832,30 @@ The default is to unwind the frame."),
 			   show_unwind_on_terminating_exception_p,
 			   &setlist, &showlist);
 
+  add_setshow_uinteger_cmd ("direct-call-timeout", no_class,
+			    &direct_call_timeout, _("\
+Set the timeout, for direct calls to inferior function calls."), _("\
+Show the timeout, for direct calls to inferior function calls."), _("\
+If running on a target that supports, and is running in, async mode\n\
+then this timeout is used for any inferior function calls triggered\n\
+directly from the prompt, i.e. from a 'call' or 'print' command.  The\n\
+timeout is specified in seconds."),
+			    nullptr,
+			    show_direct_call_timeout,
+			    &setlist, &showlist);
+
+  add_setshow_uinteger_cmd ("indirect-call-timeout", no_class,
+			    &indirect_call_timeout, _("\
+Set the timeout, for indirect calls to inferior function calls."), _("\
+Show the timeout, for indirect calls to inferior function calls."), _("\
+If running on a target that supports, and is running in, async mode\n\
+then this timeout is used for any inferior function calls triggered\n\
+indirectly, i.e. being made as part of a breakpoint, or watchpoint,\n\
+condition expression.  The timeout is specified in seconds."),
+			    nullptr,
+			    show_indirect_call_timeout,
+			    &setlist, &showlist);
+
   add_setshow_boolean_cmd
     ("infcall", class_maintenance, &debug_infcall,
      _("Set inferior call debugging."),
diff --git a/gdb/testsuite/gdb.base/help.exp b/gdb/testsuite/gdb.base/help.exp
index 87919a819ab..504bf90cc15 100644
--- a/gdb/testsuite/gdb.base/help.exp
+++ b/gdb/testsuite/gdb.base/help.exp
@@ -121,7 +121,7 @@ gdb_test "help info bogus-gdb-command" "Undefined info command: \"bogus-gdb-comm
 gdb_test "help gotcha" "Undefined command: \"gotcha\"\.  Try \"help\"\."
 
 # Test apropos regex.
-gdb_test "apropos \\\(print\[\^\[ bsiedf\\\".-\]\\\)" "handle -- Specify how to handle signals\."
+gdb_test "apropos \\\(print\[\^\[ bsiedf\\\"'.-\]\\\)" "handle -- Specify how to handle signals\."
 # Test apropos >1 word string.
 gdb_test "apropos handle signal" "handle -- Specify how to handle signals\."
 # Test apropos apropos.
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.c b/gdb/testsuite/gdb.base/infcall-timeout.c
new file mode 100644
index 00000000000..12774ca2599
--- /dev/null
+++ b/gdb/testsuite/gdb.base/infcall-timeout.c
@@ -0,0 +1,36 @@
+/* Copyright 2022-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 <unistd.h>
+
+/* This function is called from GDB.  */
+int
+function_that_never_returns ()
+{
+  while (1)
+    sleep (1);
+
+  return 0;
+}
+
+int
+main ()
+{
+  alarm (300);
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.exp b/gdb/testsuite/gdb.base/infcall-timeout.exp
new file mode 100644
index 00000000000..5e9cdc2fa0e
--- /dev/null
+++ b/gdb/testsuite/gdb.base/infcall-timeout.exp
@@ -0,0 +1,82 @@
+# Copyright 2022-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/>.
+
+# Test GDB's direct-call-timeout setting, that is, ensure that if an
+# inferior function call, invoked from e.g. a 'print' command, takes
+# too long, then GDB can interrupt it, and return control to the user.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug}] == -1 } {
+    return
+}
+
+# Start GDB according to TARGET_ASYNC and TARGET_NON_STOP, then adjust
+# the direct-call-timeout, and make an inferior function call that
+# will never return.  GDB should eventually timeout and stop the
+# inferior.
+proc_with_prefix run_test { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if {![runto_main]} {
+	fail "run to main"
+	return
+    }
+
+    gdb_test_no_output "set direct-call-timeout 5"
+
+    # When non-stop mode is off we get slightly different output from GDB.
+    if { [gdb_is_remote_or_extended_remote_target] && !$target_non_stop } {
+	set stopped_line_pattern "Program received signal SIGINT, Interrupt\\."
+    } else {
+	set stopped_line_pattern "Program stopped\\."
+    }
+
+    gdb_test "print function_that_never_returns ()" \
+	[multi_line \
+	     $stopped_line_pattern \
+	     ".*" \
+	     "The program being debugged timed out while in a function called from GDB\\." \
+	     "GDB remains in the frame where the timeout occurred\\." \
+	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(function_that_never_returns\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+
+    gdb_test "bt" ".* function_that_never_returns .*<function called from gdb>.*"
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+
+    if { !$target_async } {
+	# GDB can't timeout while waiting for a thread if the target
+	# runs with async-mode turned off; once the target is running
+	# GDB is effectively blocked until the target stops for some
+	# reason.
+	continue
+    }
+
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	run_test $target_async $target_non_stop
+    }
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
new file mode 100644
index 00000000000..4da4245746e
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
@@ -0,0 +1,169 @@
+/* This testcase is part of GDB, the GNU debugger.
+
+   Copyright 2022-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 <stdio.h>
+#include <pthread.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <semaphore.h>
+
+#define NUM_THREADS 5
+
+/* Semaphores, used to track when threads have started, and to control
+   when the threads finish.  */
+sem_t startup_semaphore;
+sem_t finish_semaphore;
+sem_t thread_1_semaphore;
+sem_t thread_2_semaphore;
+
+/* Mutex to control when the first worker thread hit a breakpoint
+   location.  */
+pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+
+/* Global variable to poke, just so threads have something to do.  */
+volatile int global_var = 0;
+
+int
+condition_func ()
+{
+  /* Let thread 2 run.  */
+  if (sem_post (&thread_2_semaphore) != 0)
+    abort ();
+
+  /* Wait for thread 2 to complete its actions.  */
+  if (sem_wait (&thread_1_semaphore) != 0)
+    abort ();
+
+  return 1;
+}
+
+void
+do_segfault ()
+{
+  volatile int *p = 0;
+  *p = 0;	/* Segfault here.  */
+}
+
+void *
+worker_func (void *arg)
+{
+  int tid = *((int *) arg);
+
+  /* Let the main thread know that this worker has started.  */
+  if (sem_post (&startup_semaphore) != 0)
+    abort ();
+
+  switch (tid)
+    {
+    case 0:
+      /* Wait for MUTEX to become available, then pass through the
+	 conditional breakpoint location.  */
+      if (pthread_mutex_lock (&mutex) != 0)
+	abort ();
+      global_var = 99;	/* Conditional breakpoint here.  */
+      if (pthread_mutex_unlock (&mutex) != 0)
+	abort ();
+      break;
+
+    case 1:
+      if (sem_wait (&thread_2_semaphore) != 0)
+	abort ();
+      do_segfault ();
+      if (sem_post (&thread_1_semaphore) != 0)
+	abort ();
+
+      /* Fall through.  */
+    default:
+      /* Wait until we are allowed to finish.  */
+      if (sem_wait (&finish_semaphore) != 0)
+	abort ();
+      break;
+    }
+}
+
+void
+stop_marker ()
+{
+  global_var = 99;	/* Stop marker.  */
+}
+
+/* The main program entry point.  */
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+  void *retval;
+
+  /* An alarm, just in case the thread deadlocks.  */
+  alarm (300);
+
+  /* Semaphore initialization.  */
+  if (sem_init (&startup_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&finish_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&thread_1_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&thread_2_semaphore, 0, 0) != 0)
+    abort ();
+
+  /* Lock MUTEX, this prevents the first worker thread from rushing ahead.  */
+  if (pthread_mutex_lock (&mutex) != 0)
+    abort ();
+
+  /* Worker thread creation.  */
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  /* Wait for every thread to start.  */
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      if (sem_wait (&startup_semaphore) != 0)
+	abort ();
+    }
+
+  /* Unlock the first thread so it can proceed.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  /* Wait for the first thread only.  */
+  pthread_join (threads[0], &retval);
+
+  /* Now post FINISH_SEMAPHORE to allow all the other threads to finish.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    sem_post (&finish_semaphore);
+
+  /* Now wait for the remaining threads to complete.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    pthread_join (threads[i], &retval);
+
+  /* Semaphore cleanup.  */
+  sem_destroy (&finish_semaphore);
+  sem_destroy (&startup_semaphore);
+  sem_destroy (&thread_1_semaphore);
+  sem_destroy (&thread_2_semaphore);
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
new file mode 100644
index 00000000000..4159288a39c
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
@@ -0,0 +1,156 @@
+# Copyright 2022-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 inferior calls executed from a breakpoint condition in
+# a multi-threaded program.
+#
+# This test has the inferior function call timeout, and checks how GDB
+# handles this situation.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "Conditional breakpoint here"]
+set final_bp_line [gdb_get_line_number "Stop marker"]
+set segfault_line [gdb_get_line_number "Segfault here"]
+
+# Setup GDB based on TARGET_ASYNC and TARGET_NON_STOP.  Setup some
+# breakpoints in the inferior, one of which has an inferior call
+# within its condition.
+#
+# Continue GDB, the breakpoint with inferior call will be hit, but the
+# inferior call will never return.  We expect GDB to timeout.
+#
+# The reason that the inferior call never completes is that a second
+# thread, on which the inferior call relies, either hits a breakpoint
+# (when OTHER_THREAD_BP is true), or crashes (when OTHER_THREAD_BP is
+# false).
+proc run_test { target_async target_non_stop other_thread_bp } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if {![runto_main]} {
+	fail "run to main"
+	return
+    }
+
+    # The default timeout for indirect inferior calls (e.g. inferior
+    # calls for conditional breakpoint expressions) is pretty high.
+    # We don't want the test to take too long, so reduce this.
+    #
+    # However, the test relies on a second thread hitting some event
+    # (either a breakpoint or signal) before this timeout expires.
+    #
+    # There is a chance that on a really slow system this might not
+    # happen, in which case the test might fail.
+    #
+    # However, we still allocate 5 seconds, which feels like it should
+    # be enough time in most cases, but maybe we need to do something
+    # smarter here?  Possibly we could have some initial run where the
+    # inferior doesn't timeout, but does perform the same interaction
+    # between threads, we could time that, and use that as the basis
+    # for this timeout.  For now though, we just hope 5 seconds is
+    # enough.
+    gdb_test_no_output "set indirect-call-timeout 5"
+
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (condition_func ())"
+    set bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		    "get number for conditional breakpoint"]
+
+    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
+    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			  "get number for final breakpoint"]
+
+    # The thread performing an inferior call relies on a second
+    # thread.  The second thread will segfault unless it hits a
+    # breakpoint first.  In either case the initial thread will not
+    # complete its inferior call.
+    if { $other_thread_bp } {
+	gdb_breakpoint "${::srcfile}:${::segfault_line}"
+	set segfault_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+				 "get number for segfault breakpoint"]
+    }
+
+    # When non-stop mode is off we get slightly different output from GDB.
+    if { [gdb_is_remote_or_extended_remote_target] && !$target_non_stop} {
+	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" received signal SIGINT, Interrupt\\."
+    } else {
+	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\."
+    }
+
+    gdb_test "continue" \
+	[multi_line \
+	     $stopped_line_pattern \
+	     ".*" \
+	     "Error in testing condition for breakpoint ${bp_num}:" \
+	     "The program being debugged timed out while in a function called from GDB\\." \
+	     "GDB remains in the frame where the timeout occurred\\." \
+	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(condition_func\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."] \
+	"expected timeout waiting for inferior call to complete"
+
+    # Remember that other thread that either crashed (with a segfault)
+    # or hit a breakpoint?  Now that the inferior call has timed out,
+    # if we try to resume then we should see the pending event from
+    # that other thread.
+    if { $other_thread_bp } {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${segfault_bp_num}, do_segfault \[^\r\n\]+:${::segfault_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"] \
+	    "hit the segfault breakpoint"
+    } else {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "Thread ${::decimal} \"infcall-from-bp\" received signal SIGSEGV, Segmentation fault\\." \
+		 "\\\[Switching to Thread \[^\r\n\]+\\\]" \
+		 "${::hex} in do_segfault \\(\\) at \[^\r\n\]+:${::segfault_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"] \
+	    "hit the segfault"
+    }
+}
+
+foreach_with_prefix target_async {"on" "off" } {
+
+    if { !$target_async } {
+	# GDB can't timeout while waiting for a thread if the target
+	# runs with async-mode turned off; once the target is running
+	# GDB is effectively blocked until the target stops for some
+	# reason.
+	continue
+    }
+
+    foreach_with_prefix target_non_stop {"off" "on"} {
+	foreach_with_prefix other_thread_bp { true false } {
+	    run_test $target_async $target_non_stop $other_thread_bp
+	}
+    }
+}
-- 
2.25.4


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

* [PATCHv4 10/12] gdb/remote: avoid SIGINT after calling remote_target::stop
  2023-02-28 16:42     ` [PATCHv4 00/12] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                         ` (8 preceding siblings ...)
  2023-02-28 16:42       ` [PATCHv4 09/12] gdb: add timeouts for inferior function calls Andrew Burgess
@ 2023-02-28 16:42       ` Andrew Burgess
  2023-02-28 16:42       ` [PATCHv4 11/12] gdb: introduce unwind-on-timeout setting Andrew Burgess
                         ` (2 subsequent siblings)
  12 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-02-28 16:42 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Currently, if the remote target is not running in non-stop mode, then,
when GDB calls remote_target::stop, we end up sending an interrupt
packet \x03 to the remote target.

If the user interrupts the inferior from the GDB prompt (e.g. by
typing Ctrl-c), then GDB calls remote_target::interrupt, which also
ends up sending the interrupt packet.

The problem here is that both of these mechanisms end up sending the
interrupt packet, which means, when the target stops with a SIGINT,
and this is reported back to GDB, we have no choice but to report this
to the user as a SIGINT stop event.

Now maybe this is the correct thing to do, after all the target has
been stopped with SIGINT.  However, this leads to an unfortunate
change in behaviour when comparing non-stop vs all-stop mode.

When running in non-stop mode, and remote_target::stop is called, the
target will be stopped with a vCont packet, and this stop is then
reported back to GDB as GDB_SIGNAL_0, this will cause GDB to print a
message like:

  Program stopped.

Or:

  Thread NN "binary name" stopped.

In contrast, when non-stop mode is off, we get messages like:

  Program received SIGINT, Segmentation fault.

Or:

  Thread NN "binary name" received SIGINT, Segmentation fault.

In this commit I propose making use of thread_info::stop_requested
within remote.c to know if the stop was triggered by GDB (and the
SIGINT should be hidden) or if the stop was a user interrupt, and the
SIGINT should be printed.

In remote_target::process_stop_reply if the inferior stopped with
SIGINT and the thread_info::stop_requested flag is set, then we change
the stop signal to GDB_SIGNAL_0.

Two of the tests added in the previous commit exposed this issue.  In
the previous commit the tests looked for either of the above
patterns.  In this commit I've updated these tests to only look for
the "stopped" based messages.

This commit is the reason why the previous commit took care to set the
thread_info::stop_requested flag in infcall.c.
---
 gdb/remote.c                                           | 10 ++++++++++
 gdb/testsuite/gdb.base/infcall-timeout.exp             |  9 +--------
 .../gdb.threads/infcall-from-bp-cond-timeout.exp       |  9 +--------
 3 files changed, 12 insertions(+), 16 deletions(-)

diff --git a/gdb/remote.c b/gdb/remote.c
index ba7a7520cb4..604d75b9689 100644
--- a/gdb/remote.c
+++ b/gdb/remote.c
@@ -8275,6 +8275,16 @@ remote_target::process_stop_reply (struct stop_reply *stop_reply,
 	}
       else
 	{
+	  /* If this stop was actually requested by GDB then we can hide
+	     the SIGINT from the user.  */
+	  if (status->kind () == TARGET_WAITKIND_STOPPED
+	      && status->sig () == GDB_SIGNAL_INT)
+	    {
+	      thread_info *thr = find_thread_ptid (this, ptid);
+	      if (thr->stop_requested)
+		status->set_stopped (GDB_SIGNAL_0);
+	    }
+
 	  /* If the target works in all-stop mode, a stop-reply indicates that
 	     all the target's threads stopped.  */
 	  for (thread_info *tp : all_non_exited_threads (this))
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.exp b/gdb/testsuite/gdb.base/infcall-timeout.exp
index 5e9cdc2fa0e..beb488ffd1e 100644
--- a/gdb/testsuite/gdb.base/infcall-timeout.exp
+++ b/gdb/testsuite/gdb.base/infcall-timeout.exp
@@ -45,16 +45,9 @@ proc_with_prefix run_test { target_async target_non_stop } {
 
     gdb_test_no_output "set direct-call-timeout 5"
 
-    # When non-stop mode is off we get slightly different output from GDB.
-    if { [gdb_is_remote_or_extended_remote_target] && !$target_non_stop } {
-	set stopped_line_pattern "Program received signal SIGINT, Interrupt\\."
-    } else {
-	set stopped_line_pattern "Program stopped\\."
-    }
-
     gdb_test "print function_that_never_returns ()" \
 	[multi_line \
-	     $stopped_line_pattern \
+	     "Program stopped\\." \
 	     ".*" \
 	     "The program being debugged timed out while in a function called from GDB\\." \
 	     "GDB remains in the frame where the timeout occurred\\." \
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
index 4159288a39c..74f7def7dce 100644
--- a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
@@ -92,16 +92,9 @@ proc run_test { target_async target_non_stop other_thread_bp } {
 				 "get number for segfault breakpoint"]
     }
 
-    # When non-stop mode is off we get slightly different output from GDB.
-    if { [gdb_is_remote_or_extended_remote_target] && !$target_non_stop} {
-	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" received signal SIGINT, Interrupt\\."
-    } else {
-	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\."
-    }
-
     gdb_test "continue" \
 	[multi_line \
-	     $stopped_line_pattern \
+	     "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\." \
 	     ".*" \
 	     "Error in testing condition for breakpoint ${bp_num}:" \
 	     "The program being debugged timed out while in a function called from GDB\\." \
-- 
2.25.4


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

* [PATCHv4 11/12] gdb: introduce unwind-on-timeout setting
  2023-02-28 16:42     ` [PATCHv4 00/12] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                         ` (9 preceding siblings ...)
  2023-02-28 16:42       ` [PATCHv4 10/12] gdb/remote: avoid SIGINT after calling remote_target::stop Andrew Burgess
@ 2023-02-28 16:42       ` Andrew Burgess
  2023-02-28 16:42       ` [PATCHv4 12/12] gdb: rename unwindonsignal to unwind-on-signal Andrew Burgess
  2023-03-16 17:36       ` [PATCHv5 00/11] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
  12 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-02-28 16:42 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Eli already approved the docs part:
  https://sourceware.org/pipermail/gdb-patches/2023-January/195873.html

---

Now that inferior function calls can timeout (see the recent
introduction of direct-call-timeout and indirect-call-timeout), this
commit adds a new setting unwind-on-timeout.

This new setting is just like the existing unwindonsignal and
unwind-on-terminating-exception, but the new setting will cause GDB to
unwind the stack if an inferior function call times out.

The existing inferior function call timeout tests have been updated to
cover the new setting.
---
 gdb/NEWS                                      |  9 +++
 gdb/doc/gdb.texinfo                           | 25 ++++++--
 gdb/infcall.c                                 | 62 ++++++++++++++++---
 gdb/testsuite/gdb.base/infcall-timeout.exp    | 49 +++++++++++----
 .../infcall-from-bp-cond-timeout.exp          | 55 +++++++++++-----
 5 files changed, 160 insertions(+), 40 deletions(-)

diff --git a/gdb/NEWS b/gdb/NEWS
index a8827cddd61..edf30ff70f9 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -96,6 +96,15 @@ show indirect-call-timeout
   ignored, GDB will wait indefinitely for an inferior function to
   complete, unless interrupted by the user using Ctrl-C.
 
+set unwind-on-timeout on|off
+show unwind-on-timeout
+  These commands control whether GDB should unwind the stack when a
+  timeout occurs during an inferior function call.  The default is
+  off, in which case the inferior will remain in the frame where the
+  timeout occurred.  When on, GDB will unwind the stack removing the
+  dummy frame that was added for the inferior call, and restoring the
+  inferior state to how it was before the inferior call started.
+
 * MI changes
 
 ** mi now reports 'no-history' as a stop reason when hitting the end of the
diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index 5cc8b0e811c..f73deedadfa 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -20813,6 +20813,21 @@
 Show the current setting of stack unwinding in the functions called by
 @value{GDBN}.
 
+@item set unwind-on-timeout
+@kindex set unwind-on-timeout
+@cindex unwind stack in called functions when timing out
+@cindex call dummy stack unwinding on timeout.
+Set unwinding of the stack if a function called from @value{GDBN}
+times out.  If set to @code{off} (the default), @value{GDBN} stops in
+the frame where the timeout occurred.  If set to @code{on},
+@value{GDBN} unwinds the stack it created for the call and restores
+the context to what it was before the call.
+
+@item show unwind-on-timeout
+@kindex show unwind-on-timeout
+Show whether @value{GDBN} will unwind the stack if a function called
+from @value{GDBN} times out.
+
 @item set may-call-functions
 @kindex set may-call-functions
 @cindex disabling calling functions in the program
@@ -20844,11 +20859,11 @@
 
 If a called function is interrupted for any reason, including hitting
 a breakpoint, or triggering a watchpoint, and the stack is not unwound
-due to @code{set unwind-on-terminating-exception on} or @code{set
-unwindonsignal on} (@pxref{stack unwind settings}),
-then the dummy-frame, created by @value{GDBN} to facilitate the call
-to the program function, will be visible in the backtrace, for example
-frame @code{#3} in the following backtrace:
+due to @code{set unwind-on-terminating-exception on}, @code{set
+unwind-on-timeout on}, or @code{set unwindonsignal on} (@pxref{stack
+unwind settings}), then the dummy-frame, created by @value{GDBN} to
+facilitate the call to the program function, will be visible in the
+backtrace, for example frame @code{#3} in the following backtrace:
 
 @smallexample
 (@value{GDBP}) backtrace
diff --git a/gdb/infcall.c b/gdb/infcall.c
index bb57faf700f..1f0fb4f1d59 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -217,6 +217,27 @@ show_unwind_on_terminating_exception_p (struct ui_file *file, int from_tty,
 	      value);
 }
 
+/* This boolean tells GDB what to do if an inferior function, called from
+   GDB, times out.  If true, GDB unwinds the stack and restores the context
+   to what it was before the call.  When false, GDB leaves the thread as it
+   is at the point of the timeout.
+
+   The default is to stop in the frame where the timeout occurred.  */
+
+static bool unwind_on_timeout_p = false;
+
+/* Implement 'show unwind-on-timeout'.  */
+
+static void
+show_unwind_on_timeout_p (struct ui_file *file, int from_tty,
+			  struct cmd_list_element *c, const char *value)
+{
+  gdb_printf (file,
+	      _("Unwinding of stack if a timeout occurs "
+		"while in a call dummy is %s.\n"),
+	      value);
+}
+
 /* Perform the standard coercions that are specified
    for arguments to be passed to C, Ada or Fortran functions.
 
@@ -1699,14 +1720,27 @@ When the function is done executing, GDB will silently stop."),
 	  /* A timeout results in a signal being sent to the inferior.  */
 	  gdb_assert (stopped_by_random_signal);
 
-	  /* Indentation is weird here.  A later patch is going to move the
-	    following block into an if/else, so I'm leaving the indentation
-	    here to minimise the later patch.
+	  if (unwind_on_timeout_p)
+	    {
+	      /* The user wants the context restored.  */
+
+	      /* We must get back to the frame we were before the
+		 dummy call.  */
+	      dummy_frame_pop (dummy_id, call_thread.get ());
 
-	    Also, the error message used below refers to 'set
-	    unwind-on-timeout' which doesn't exist yet.  This will be added
-	    in a later commit, I'm leaving this in for now to minimise the
-	    churn caused by the commit that adds unwind-on-timeout.  */
+	      /* We also need to restore inferior status to that before the
+		 dummy call.  */
+	      restore_infcall_control_state (inf_status.release ());
+
+	      error (_("\
+The program being debugged timed out while in a function called from GDB.\n\
+GDB has restored the context to what it was before the call.\n\
+To change this behavior use \"set unwind-on-timeout off\".\n\
+Evaluation of the expression containing the function\n\
+(%s) will be abandoned."),
+		     name.c_str ());
+	    }
+	  else
 	    {
 	      /* The user wants to stay in the frame where we stopped
 		 (default).  Discard inferior status, we're not at the same
@@ -1832,6 +1866,20 @@ The default is to unwind the frame."),
 			   show_unwind_on_terminating_exception_p,
 			   &setlist, &showlist);
 
+  add_setshow_boolean_cmd ("unwind-on-timeout", no_class,
+			   &unwind_on_timeout_p, _("\
+Set unwinding of stack if a timeout occurs while in a call dummy."), _("\
+Show unwinding of stack if a timeout occurs while in a call dummy."),
+			   _("\
+The unwind on timeout flag lets the user determine what gdb should do if\n\
+gdb times out while in a function called from gdb.  If set, gdb unwinds\n\
+the stack and restores the context to what it was before the call.  If\n\
+unset, gdb leaves the inferior in the frame where the timeout occurred.\n\
+The default is to stop in the frame where the timeout occurred."),
+			   NULL,
+			   show_unwind_on_timeout_p,
+			   &setlist, &showlist);
+
   add_setshow_uinteger_cmd ("direct-call-timeout", no_class,
 			    &direct_call_timeout, _("\
 Set the timeout, for direct calls to inferior function calls."), _("\
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.exp b/gdb/testsuite/gdb.base/infcall-timeout.exp
index beb488ffd1e..d063abc9077 100644
--- a/gdb/testsuite/gdb.base/infcall-timeout.exp
+++ b/gdb/testsuite/gdb.base/infcall-timeout.exp
@@ -28,7 +28,11 @@ if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
 # the direct-call-timeout, and make an inferior function call that
 # will never return.  GDB should eventually timeout and stop the
 # inferior.
-proc_with_prefix run_test { target_async target_non_stop } {
+#
+# When UNWIND is "off" the inferior wil be left in the frame where the
+# timeout occurs, otherwise, when UNWIND is "on", GDB should unwind
+# back to the frame where the inferior call was made.
+proc_with_prefix run_test { target_async target_non_stop unwind } {
     save_vars { ::GDBFLAGS } {
 	append ::GDBFLAGS \
 	    " -ex \"maint set target-non-stop $target_non_stop\""
@@ -44,19 +48,36 @@ proc_with_prefix run_test { target_async target_non_stop } {
     }
 
     gdb_test_no_output "set direct-call-timeout 5"
+    gdb_test_no_output "set unwind-on-timeout $unwind"
+
+    if { $unwind } {
+	gdb_test "print function_that_never_returns ()" \
+	    [multi_line \
+		 "Program stopped\\." \
+		 ".*" \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB has restored the context to what it was before the call\\." \
+		 "To change this behavior use \"set unwind-on-timeout off\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(function_that_never_returns\\) will be abandoned\\."]
 
-    gdb_test "print function_that_never_returns ()" \
-	[multi_line \
-	     "Program stopped\\." \
-	     ".*" \
-	     "The program being debugged timed out while in a function called from GDB\\." \
-	     "GDB remains in the frame where the timeout occurred\\." \
-	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
-	     "Evaluation of the expression containing the function" \
-	     "\\(function_that_never_returns\\) will be abandoned\\." \
-	     "When the function is done executing, GDB will silently stop\\."]
+	gdb_test "bt" \
+	    "#0\\s+main \\(\\).*"
+    } else {
+	gdb_test "print function_that_never_returns ()" \
+	    [multi_line \
+		 "Program stopped\\." \
+		 ".*" \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB remains in the frame where the timeout occurred\\." \
+		 "To change this behavior use \"set unwind-on-timeout on\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(function_that_never_returns\\) will be abandoned\\." \
+		 "When the function is done executing, GDB will silently stop\\."]
 
-    gdb_test "bt" ".* function_that_never_returns .*<function called from gdb>.*"
+	gdb_test "bt" \
+	    ".* function_that_never_returns .*<function called from gdb>.*"
+    }
 }
 
 foreach_with_prefix target_async { "on" "off" } {
@@ -70,6 +91,8 @@ foreach_with_prefix target_async { "on" "off" } {
     }
 
     foreach_with_prefix target_non_stop { "on" "off" } {
-	run_test $target_async $target_non_stop
+	foreach_with_prefix unwind { "on" "off" } {
+	    run_test $target_async $target_non_stop $unwind
+	}
     }
 }
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
index 74f7def7dce..f399b5420a2 100644
--- a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
@@ -41,7 +41,12 @@ set segfault_line [gdb_get_line_number "Segfault here"]
 # thread, on which the inferior call relies, either hits a breakpoint
 # (when OTHER_THREAD_BP is true), or crashes (when OTHER_THREAD_BP is
 # false).
-proc run_test { target_async target_non_stop other_thread_bp } {
+#
+# When UNWIND is "on" GDB will unwind the thread which performed the
+# inferior function call back to the state where the inferior call was
+# made (when the inferior call times out).  Otherwise, when UNWIND is
+# "off", the inferior is left in the frame where the timeout occurred.
+proc run_test { target_async target_non_stop other_thread_bp unwind } {
     save_vars { ::GDBFLAGS } {
 	append ::GDBFLAGS " -ex \"maint set target-non-stop $target_non_stop\""
 	append ::GDBFLAGS " -ex \"maintenance set target-async ${target_async}\""
@@ -72,6 +77,7 @@ proc run_test { target_async target_non_stop other_thread_bp } {
     # for this timeout.  For now though, we just hope 5 seconds is
     # enough.
     gdb_test_no_output "set indirect-call-timeout 5"
+    gdb_test_no_output "set unwind-on-timeout $unwind"
 
     gdb_breakpoint \
 	"${::srcfile}:${::cond_bp_line} if (condition_func ())"
@@ -92,18 +98,35 @@ proc run_test { target_async target_non_stop other_thread_bp } {
 				 "get number for segfault breakpoint"]
     }
 
-    gdb_test "continue" \
-	[multi_line \
-	     "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\." \
-	     ".*" \
-	     "Error in testing condition for breakpoint ${bp_num}:" \
-	     "The program being debugged timed out while in a function called from GDB\\." \
-	     "GDB remains in the frame where the timeout occurred\\." \
-	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
-	     "Evaluation of the expression containing the function" \
-	     "\\(condition_func\\) will be abandoned\\." \
-	     "When the function is done executing, GDB will silently stop\\."] \
-	"expected timeout waiting for inferior call to complete"
+    if { $unwind } {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\." \
+		 ".*" \
+		 "Error in testing condition for breakpoint ${bp_num}:" \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB has restored the context to what it was before the call\\." \
+		 "To change this behavior use \"set unwind-on-timeout off\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(condition_func\\) will be abandoned\\." \
+		 "" \
+		 "Thread ${::decimal}\[^\r\n\]*hit Breakpoint ${bp_num}, \[^\r\n\]+" \
+		 "\[^\r\n\]+ Conditional breakpoint here\\. \[^\r\n\]+"] \
+	    "expected timeout waiting for inferior call to complete"
+    } else {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\." \
+		 ".*" \
+		 "Error in testing condition for breakpoint ${bp_num}:" \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB remains in the frame where the timeout occurred\\." \
+		 "To change this behavior use \"set unwind-on-timeout on\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(condition_func\\) will be abandoned\\." \
+		 "When the function is done executing, GDB will silently stop\\."] \
+	    "expected timeout waiting for inferior call to complete"
+    }
 
     # Remember that other thread that either crashed (with a segfault)
     # or hit a breakpoint?  Now that the inferior call has timed out,
@@ -142,8 +165,10 @@ foreach_with_prefix target_async {"on" "off" } {
     }
 
     foreach_with_prefix target_non_stop {"off" "on"} {
-	foreach_with_prefix other_thread_bp { true false } {
-	    run_test $target_async $target_non_stop $other_thread_bp
+	foreach_with_prefix unwind {"off" "on"} {
+	    foreach_with_prefix other_thread_bp { true false } {
+		run_test $target_async $target_non_stop $other_thread_bp $unwind
+	    }
 	}
     }
 }
-- 
2.25.4


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

* [PATCHv4 12/12] gdb: rename unwindonsignal to unwind-on-signal
  2023-02-28 16:42     ` [PATCHv4 00/12] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                         ` (10 preceding siblings ...)
  2023-02-28 16:42       ` [PATCHv4 11/12] gdb: introduce unwind-on-timeout setting Andrew Burgess
@ 2023-02-28 16:42       ` Andrew Burgess
  2023-03-16 17:36       ` [PATCHv5 00/11] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
  12 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-02-28 16:42 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Eli already approved the docs part:
  https://sourceware.org/pipermail/gdb-patches/2023-January/195874.html

---

We now have unwind-on-timeout and unwind-on-terminating-exception, and
then the odd one out unwindonsignal.

I'm not a great fan of these squashed together command names, so in
this commit I propose renaming this to unwind-on-signal.

Obviously I've added the hidden alias unwindonsignal so any existing
GDB scripts will keep working.

There's one test that I've extended to test the alias works, but in
most of the other test scripts I've changed over to use the new name.

The docs are updated to reference the new name.
---
 gdb/NEWS                                      | 11 ++++++
 gdb/doc/gdb.texinfo                           | 16 ++++++---
 gdb/infcall.c                                 | 21 ++++++-----
 gdb/testsuite/gdb.base/callfuncs.exp          |  4 +--
 gdb/testsuite/gdb.base/infcall-failure.exp    |  4 +--
 gdb/testsuite/gdb.base/unwindonsignal.exp     | 36 +++++++++++++------
 gdb/testsuite/gdb.compile/compile-cplus.exp   |  2 +-
 gdb/testsuite/gdb.compile/compile.exp         |  2 +-
 gdb/testsuite/gdb.cp/gdb2495.exp              | 16 ++++-----
 gdb/testsuite/gdb.fortran/function-calls.exp  |  2 +-
 gdb/testsuite/gdb.mi/mi-syn-frame.exp         |  2 +-
 .../infcall-from-bp-cond-simple.exp           |  2 +-
 .../gdb.threads/thread-unwindonsignal.exp     |  8 ++---
 13 files changed, 83 insertions(+), 43 deletions(-)

diff --git a/gdb/NEWS b/gdb/NEWS
index edf30ff70f9..96ee5704931 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -105,6 +105,17 @@ show unwind-on-timeout
   dummy frame that was added for the inferior call, and restoring the
   inferior state to how it was before the inferior call started.
 
+set unwind-on-signal on|off
+show unwind-on-signal
+  These new commands replaces the existing set/show unwindonsignal.  The
+  old command is maintained as an alias.
+
+* Changed commands
+
+set unwindonsignal on|off
+show unwindonsignal
+  These commands are now aliases for the new set/show unwind-on-signal.
+
 * MI changes
 
 ** mi now reports 'no-history' as a stop reason when hitting the end of the
diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index f73deedadfa..d677bc9be3a 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -20767,7 +20767,7 @@
 It is possible for the function you call via the @code{print} or
 @code{call} command to generate a signal (e.g., if there's a bug in
 the function, or if you passed it incorrect arguments).  What happens
-in that case is controlled by the @code{set unwindonsignal} command.
+in that case is controlled by the @code{set unwind-on-signal} command.
 
 Similarly, with a C@t{++} program it is possible for the function you
 call via the @code{print} or @code{call} command to generate an
@@ -20781,7 +20781,8 @@
 
 @anchor{stack unwind settings}
 @table @code
-@item set unwindonsignal
+@item set unwind-on-signal
+@kindex set unwind-on-signal
 @kindex set unwindonsignal
 @cindex unwind stack in called functions
 @cindex call dummy stack unwinding
@@ -20792,11 +20793,18 @@
 default), @value{GDBN} stops in the frame where the signal was
 received.
 
-@item show unwindonsignal
+The command @code{set unwindonsignal} is an alias for this command,
+and is maintained for backward compatibility.
+
+@item show unwind-on-signal
+@kindex show unwind-on-signal
 @kindex show unwindonsignal
 Show the current setting of stack unwinding in the functions called by
 @value{GDBN}.
 
+The command @code{show unwindonsignal} is an alias for this command,
+and is maintained for backward compatibility.
+
 @item set unwind-on-terminating-exception
 @kindex set unwind-on-terminating-exception
 @cindex unwind stack in called functions with unhandled exceptions
@@ -20860,7 +20868,7 @@
 If a called function is interrupted for any reason, including hitting
 a breakpoint, or triggering a watchpoint, and the stack is not unwound
 due to @code{set unwind-on-terminating-exception on}, @code{set
-unwind-on-timeout on}, or @code{set unwindonsignal on} (@pxref{stack
+unwind-on-timeout on}, or @code{set unwind-on-signal on} (@pxref{stack
 unwind settings}), then the dummy-frame, created by @value{GDBN} to
 facilitate the call to the program function, will be visible in the
 backtrace, for example frame @code{#3} in the following backtrace:
diff --git a/gdb/infcall.c b/gdb/infcall.c
index 1f0fb4f1d59..73b19afe613 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -1689,7 +1689,7 @@ When the function is done executing, GDB will silently stop."),
 	      error (_("\
 The program being debugged was signaled while in a function called from GDB.\n\
 GDB has restored the context to what it was before the call.\n\
-To change this behavior use \"set unwindonsignal off\".\n\
+To change this behavior use \"set unwind-on-signal off\".\n\
 Evaluation of the expression containing the function\n\
 (%s) will be abandoned."),
 		     name.c_str ());
@@ -1707,7 +1707,7 @@ Evaluation of the expression containing the function\n\
 	      error (_("\
 The program being debugged was signaled while in a function called from GDB.\n\
 GDB remains in the frame where the signal was received.\n\
-To change this behavior use \"set unwindonsignal on\".\n\
+To change this behavior use \"set unwind-on-signal on\".\n\
 Evaluation of the expression containing the function\n\
 (%s) will be abandoned.\n\
 When the function is done executing, GDB will silently stop."),
@@ -1839,17 +1839,22 @@ The default is to perform the conversion."),
 			   show_coerce_float_to_double_p,
 			   &setlist, &showlist);
 
-  add_setshow_boolean_cmd ("unwindonsignal", no_class,
-			   &unwind_on_signal_p, _("\
+  set_show_commands setshow_unwind_on_signal_cmds
+    = add_setshow_boolean_cmd ("unwind-on-signal", no_class,
+			       &unwind_on_signal_p, _("\
 Set unwinding of stack if a signal is received while in a call dummy."), _("\
 Show unwinding of stack if a signal is received while in a call dummy."), _("\
-The unwindonsignal lets the user determine what gdb should do if a signal\n\
+The unwind-on-signal lets the user determine what gdb should do if a signal\n\
 is received while in a function called from gdb (call dummy).  If set, gdb\n\
 unwinds the stack and restore the context to what as it was before the call.\n\
 The default is to stop in the frame where the signal was received."),
-			   NULL,
-			   show_unwind_on_signal_p,
-			   &setlist, &showlist);
+			       NULL,
+			       show_unwind_on_signal_p,
+			       &setlist, &showlist);
+  add_alias_cmd ("unwindonsignal", setshow_unwind_on_signal_cmds.set,
+		 no_class, 1, &setlist);
+  add_alias_cmd ("unwindonsignal", setshow_unwind_on_signal_cmds.show,
+		 no_class, 1, &showlist);
 
   add_setshow_boolean_cmd ("unwind-on-terminating-exception", no_class,
 			   &unwind_on_terminating_exception_p, _("\
diff --git a/gdb/testsuite/gdb.base/callfuncs.exp b/gdb/testsuite/gdb.base/callfuncs.exp
index 9bbf108ac0e..0a1a9bd9391 100644
--- a/gdb/testsuite/gdb.base/callfuncs.exp
+++ b/gdb/testsuite/gdb.base/callfuncs.exp
@@ -49,7 +49,7 @@ proc do_function_calls {prototypes} {
 
     # If any of these calls segv we don't want to affect subsequent tests.
     # E.g., we want to ensure register values are restored.
-    gdb_test_no_output "set unwindonsignal on"
+    gdb_test_no_output "set unwind-on-signal on"
 
     gdb_test "p t_char_values(0,0)" " = 0"
     gdb_test "p t_char_values('a','b')" " = 1"
@@ -240,7 +240,7 @@ proc do_function_calls {prototypes} {
     	"call inferior func with struct - returns char *"
 
     # Restore default value.
-    gdb_test_no_output "set unwindonsignal off"
+    gdb_test_no_output "set unwind-on-signal off"
 }
 
 # Procedure to get current content of all registers.
diff --git a/gdb/testsuite/gdb.base/infcall-failure.exp b/gdb/testsuite/gdb.base/infcall-failure.exp
index 5ad179a089d..e2e71649dac 100644
--- a/gdb/testsuite/gdb.base/infcall-failure.exp
+++ b/gdb/testsuite/gdb.base/infcall-failure.exp
@@ -137,7 +137,7 @@ proc_with_prefix run_cond_hits_segfault_test { async_p non_stop_p } {
 	     "Error in testing condition for breakpoint ${bp_1_num}:" \
 	     "The program being debugged was signaled while in a function called from GDB\\." \
 	     "GDB remains in the frame where the signal was received\\." \
-	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "To change this behavior use \"set unwind-on-signal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(func_segfault\\) will be abandoned\\." \
 	     "When the function is done executing, GDB will silently stop\\."]
@@ -166,7 +166,7 @@ proc_with_prefix run_call_hits_segfault_test { async_p non_stop_p } {
 	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
 	     "The program being debugged was signaled while in a function called from GDB\\." \
 	     "GDB remains in the frame where the signal was received\\." \
-	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "To change this behavior use \"set unwind-on-signal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(func_segfault\\) will be abandoned\\." \
 	     "When the function is done executing, GDB will silently stop\\."]
diff --git a/gdb/testsuite/gdb.base/unwindonsignal.exp b/gdb/testsuite/gdb.base/unwindonsignal.exp
index d10d1fe244d..c17b5742ea8 100644
--- a/gdb/testsuite/gdb.base/unwindonsignal.exp
+++ b/gdb/testsuite/gdb.base/unwindonsignal.exp
@@ -40,34 +40,50 @@ gdb_test "break stop_here" "Breakpoint \[0-9\]* at .*"
 gdb_test "continue" "Continuing.*Breakpoint \[0-9\]*, stop_here.*" \
     "continue to breakpoint at stop_here"
 
-# Turn on unwindonsignal.
-gdb_test_no_output "set unwindonsignal on" \
-	"setting unwindonsignal"
+# Turn on unwind-on-signal.
+gdb_test_no_output "set unwind-on-signal on" \
+	"setting unwind-on-signal"
 
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
 	"Unwinding of stack .* is on." \
-	"showing unwindonsignal"
+	"showing unwind-on-signal"
+
+# For backward compatibility we maintain a 'unwindonsignal' alias for
+# 'unwind-on-signal', check it now.
+gdb_test "show unwindonsignal" \
+    "Unwinding of stack .* is on\\." \
+    "showing unwindonsignal alias"
+
+gdb_test_no_output "set unwindonsignal off" \
+    "setting unwindonsignal alias to off"
+
+gdb_test "show unwind-on-signal" \
+    "Unwinding of stack .* is off\\." \
+    "showing unwind-on-signal after setting via alias"
+
+gdb_test_no_output "set unwindonsignal on" \
+    "setting unwindonsignal alias to on"
 
 # Call function (causing the program to get a signal), and see if gdb handles
 # it properly.
 if {[gdb_test "call gen_signal ()"  \
 	 "\[\r\n\]*The program being debugged was signaled.*" \
-	 "unwindonsignal, inferior function call signaled"] != 0} {
+	 "inferior function call signaled"] != 0} {
     return 0
 }
 
 # Verify the stack got unwound.
 gdb_test "bt" \
     "#0 *\[x0-9a-f in\]*stop_here \\(.*\\) at .*#1 *\[x0-9a-f in\]*main \\(.*\\) at .*" \
-	"unwindonsignal, stack unwound"
+	"stack unwound"
 
 # Verify the dummy frame got removed from dummy_frame_stack.
 gdb_test_multiple "maint print dummy-frames" \
-	"unwindonsignal, dummy frame removed" {
+	"unwind-on-signal, dummy frame removed" {
     -re "\[\r\n\]*.*stack=.*code=.*\[\r\n\]+$gdb_prompt $" {
-	fail "unwindonsignal, dummy frame removed"
+	fail $gdb_test_name
     }
     -re "\[\r\n\]+$gdb_prompt $" {
-	pass "unwindonsignal, dummy frame removed"
+	pass $gdb_test_name
     }
 }
diff --git a/gdb/testsuite/gdb.compile/compile-cplus.exp b/gdb/testsuite/gdb.compile/compile-cplus.exp
index 4e887daeb29..22eebb44953 100644
--- a/gdb/testsuite/gdb.compile/compile-cplus.exp
+++ b/gdb/testsuite/gdb.compile/compile-cplus.exp
@@ -129,7 +129,7 @@ gdb_test "return" "\r\n#0  main .*" "return" \
 	 "Make _gdb_expr\\(__gdb_regs\\*\\) return now\\? \\(y or n\\) " "y"
 gdb_test "info sym $infcall_pc" "\r\nNo symbol matches .*" "info sym not found"
 
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 gdb_test "compile code *(volatile int *) 0 = 0;" \
     "The program being debugged was signaled while in a function called from GDB\\.\r\nGDB has restored the context to what it was before the call\\.\r\n.*" \
     "compile code segfault second"
diff --git a/gdb/testsuite/gdb.compile/compile.exp b/gdb/testsuite/gdb.compile/compile.exp
index f3d87cd2605..8822aab2e81 100644
--- a/gdb/testsuite/gdb.compile/compile.exp
+++ b/gdb/testsuite/gdb.compile/compile.exp
@@ -159,7 +159,7 @@ gdb_test "return" "\r\n#0  main .*" "return" \
 	 "Make _gdb_expr return now\\? \\(y or n\\) " "y"
 gdb_test "info sym $infcall_pc" "\r\nNo symbol matches .*" "info sym not found"
 
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 gdb_test "compile code *(volatile int *) 0 = 0;" \
     "The program being debugged was signaled while in a function called from GDB\\.\r\nGDB has restored the context to what it was before the call\\.\r\n.*" \
     "compile code segfault second"
diff --git a/gdb/testsuite/gdb.cp/gdb2495.exp b/gdb/testsuite/gdb.cp/gdb2495.exp
index 0cb8bdd0ada..af94d959d83 100644
--- a/gdb/testsuite/gdb.cp/gdb2495.exp
+++ b/gdb/testsuite/gdb.cp/gdb2495.exp
@@ -104,29 +104,29 @@ if {![runto_main]} {
 # behaviour; it should not.  Test both on and off states.
 
 # Turn on unwind on signal behaviour.
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 
 # Check that it is turned on.
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
     "signal is received while in a call dummy is on.*" \
     "turn on unwind on signal"
 
 # Check to see if new behaviour interferes with
 # normal signal handling in inferior function calls.
 gdb_test "p exceptions.raise_signal(1)" \
-    "To change this behavior use \"set unwindonsignal off\".*" \
-    "check for unwindonsignal off message"
+    "To change this behavior use \"set unwind-on-signal off\".*" \
+    "check for unwind-on-signal off message"
 
 # And reverse - turn off again.
-gdb_test_no_output "set unwindonsignal off"
+gdb_test_no_output "set unwind-on-signal off"
 
 # Check that it is actually turned off.
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
     "signal is received while in a call dummy is off.*" \
     "turn off unwind on signal"
 
 # Check to see if new behaviour interferes with
 # normal signal handling in inferior function calls.
 gdb_test "p exceptions.raise_signal(1)" \
-    "To change this behavior use \"set unwindonsignal on\".*" \
-    "check for unwindonsignal on message"
+    "To change this behavior use \"set unwind-on-signal on\".*" \
+    "check for unwind-on-signal on message"
diff --git a/gdb/testsuite/gdb.fortran/function-calls.exp b/gdb/testsuite/gdb.fortran/function-calls.exp
index f9a1efc241f..c4d1f232576 100644
--- a/gdb/testsuite/gdb.fortran/function-calls.exp
+++ b/gdb/testsuite/gdb.fortran/function-calls.exp
@@ -44,7 +44,7 @@ if {![runto [gdb_get_line_number "post_init"]]} {
 }
 
 # Use inspired by gdb.base/callfuncs.exp.
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 
 # Baseline: function and subroutine call with no arguments.
 gdb_test "p no_arg()" " = .TRUE."
diff --git a/gdb/testsuite/gdb.mi/mi-syn-frame.exp b/gdb/testsuite/gdb.mi/mi-syn-frame.exp
index 5b3e60f4f34..f026746931d 100644
--- a/gdb/testsuite/gdb.mi/mi-syn-frame.exp
+++ b/gdb/testsuite/gdb.mi/mi-syn-frame.exp
@@ -97,7 +97,7 @@ mi_gdb_test "409-stack-list-frames 0 0" \
 # 
 
 mi_gdb_test "410-data-evaluate-expression bar()" \
-  ".*410\\^error,msg=\"The program being debugged was signaled while in a function called from GDB.\\\\nGDB remains in the frame where the signal was received.\\\\nTo change this behavior use \\\\\"set unwindonsignal on\\\\\".\\\\nEvaluation of the expression containing the function\\\\n\\(bar\\) will be abandoned.\\\\nWhen the function is done executing, GDB will silently stop.\"" \
+  ".*410\\^error,msg=\"The program being debugged was signaled while in a function called from GDB.\\\\nGDB remains in the frame where the signal was received.\\\\nTo change this behavior use \\\\\"set unwind-on-signal on\\\\\".\\\\nEvaluation of the expression containing the function\\\\n\\(bar\\) will be abandoned.\\\\nWhen the function is done executing, GDB will silently stop.\"" \
   "call inferior function which raises exception"
 
 mi_gdb_test "411-stack-list-frames" "411\\^done,stack=\\\[frame=\{level=\"0\",addr=\"$hex\",func=\"bar\",file=\".*mi-syn-frame.c\",fullname=\"${fullname_syntax}${srcfile}\",line=\"$decimal\",arch=\"$any\"},frame=\{level=\"1\",addr=\"$hex\",func=\"<function called from gdb>\"\},frame=\{level=\"2\",addr=\"$hex\",func=\"main\",file=\".*mi-syn-frame.c\",fullname=\"${fullname_syntax}${srcfile}\",line=\"$decimal\",arch=\"$any\"}.*\\\]" "backtrace from inferior function at exception"
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
index 37e1b64d9a4..bb4402c0926 100644
--- a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
@@ -173,7 +173,7 @@ proc_with_prefix run_bp_cond_segfaults { target_async target_non_stop } {
 	     "Error in testing condition for breakpoint ${bp_1_num}:" \
 	     "The program being debugged was signaled while in a function called from GDB\\." \
 	     "GDB remains in the frame where the signal was received\\." \
-	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "To change this behavior use \"set unwind-on-signal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(function_that_segfaults\\) will be abandoned\\." \
 	     "When the function is done executing, GDB will silently stop\\."]
diff --git a/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp b/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp
index b3e3288ba69..636e6539bda 100644
--- a/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp
+++ b/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp
@@ -13,7 +13,7 @@
 # You should have received a copy of the GNU General Public License
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-# Test use of unwindonsignal when a hand function call that gets interrupted
+# Test use of unwind-on-signal when a hand function call that gets interrupted
 # by a signal in another thread.
 
 set NR_THREADS 4
@@ -52,12 +52,12 @@ gdb_test "continue" \
 # We want the main thread (hand_call_with_signal) and
 # thread 1 (sigabrt_handler) to both run.
 
-# Do turn on unwindonsignal.
+# Do turn on unwind-on-signal.
 # We want to test gdb handling of the current thread changing when
 # unwindonsignal is in effect.
-gdb_test_no_output "set unwindonsignal on" \
+gdb_test_no_output "set unwind-on-signal on" \
 	"setting unwindonsignal"
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
 	"Unwinding of stack .* is on." \
 	"showing unwindonsignal"
 
-- 
2.25.4


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

* Re: [PATCHv2 01/13] gdb/doc: extended documentation for inferior function calls
  2023-01-18 17:20     ` Eli Zaretskii
@ 2023-03-16 17:15       ` Andrew Burgess
  0 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-03-16 17:15 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: gdb-patches

Eli Zaretskii <eliz@gnu.org> writes:

>> Cc: Andrew Burgess <aburgess@redhat.com>
>> Date: Wed, 18 Jan 2023 16:17:57 +0000
>> From: Andrew Burgess via Gdb-patches <gdb-patches@sourceware.org>
>> 
>> I noticed that the documentation for inferior function calls doesn't
>> say much about what happens if/when an inferior function call is
>> interrupted, i.e. it doesn't describe what the dummy frame looks like
>> on the stack, or how GDB behaves when the inferior is continued and
>> reaches the dummy frame.
>> 
>> This commit aims to add some of this missing information.
>
> Thanks.
>
>> +If a called function is interrupted for any reason, and the stack is
>> +not unwound (due to @code{set unwind-on-terminating-exception on} or
>> +@code{set unwindonsignal on}),
>
> Please add here a cross-reference to here these settings are described
> in the manual.
>
> Otherwise, this is OK.

I made this fix and pushed this patch.

Thanks,
Andrew


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

* [PATCHv5 00/11] Infcalls from B/P conditions in multi-threaded inferiors
  2023-02-28 16:42     ` [PATCHv4 00/12] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                         ` (11 preceding siblings ...)
  2023-02-28 16:42       ` [PATCHv4 12/12] gdb: rename unwindonsignal to unwind-on-signal Andrew Burgess
@ 2023-03-16 17:36       ` Andrew Burgess
  2023-03-16 17:36         ` [PATCHv5 01/11] gdb: include breakpoint number in testing condition error message Andrew Burgess
                           ` (11 more replies)
  12 siblings, 12 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-03-16 17:36 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

I'm thinking that I might merge the first 5 patches in this series
some time next week.  These are all the smaller, more obvious fixes.

This might make the rest of the series a little easier to review.

In v5:

  - Rebased to current HEAD of master, minor merge conflict resolved.
    No other code or documentation changes.

  - First patch, which was pure documentation, has now been merged.

  - All other documentation changes have been reviewed and approved.

In v4:

  - I believe all the docs changes have been reviewed and approved by Eli,

  - Rebased onto current master,

  - Dropped patch #2 from the V3 series,

  - I have addressed all the issues Baris pointed out, including the
    fixes for the patch #9 ('gdb: add timeouts for inferior function
    calls'), which I forgot to do in V3.

In v3:

  - Updates for review feedback, biggest changes in #10 and #11, but
    minor changes to most patches.

In V2:

  - Rebased onto something closer to HEAD of master,

  - Patches #1, #2, #12, and #13 are new in this series,

  - Patches #3 to #9, and #11 are unchanged since their V1 iteration,

  - Patches #10 has changed slightly in implementation since v1, and
    the docs have been significantly updated.

---

Andrew Burgess (11):
  gdb: include breakpoint number in testing condition error message
  gdbserver: allows agent_mem_read to return an error code
  gdbserver: allow agent expressions to fail with invalid memory access
  gdb: avoid repeated signal reporting during failed conditional
    breakpoint
  gdb: don't always print breakpoint location after failed condition
    check
  Revert "gdb: remove unnecessary parameter wait_ptid from
    do_target_wait"
  gdb: fix b/p conditions with infcalls in multi-threaded inferiors
  gdb: add timeouts for inferior function calls
  gdb/remote: avoid SIGINT after calling remote_target::stop
  gdb: introduce unwind-on-timeout setting
  gdb: rename unwindonsignal to unwind-on-signal

 gdb/NEWS                                      |  38 +++
 gdb/breakpoint.c                              |  17 +-
 gdb/doc/gdb.texinfo                           | 105 +++++-
 gdb/gdbthread.h                               |   3 +
 gdb/infcall.c                                 | 305 +++++++++++++++++-
 gdb/infrun.c                                  |  70 +++-
 gdb/infrun.h                                  |   3 +-
 gdb/remote.c                                  |  10 +
 gdb/testsuite/gdb.base/bp-cond-failure.c      |  30 ++
 gdb/testsuite/gdb.base/bp-cond-failure.exp    | 104 ++++++
 gdb/testsuite/gdb.base/callfuncs.exp          |   4 +-
 .../gdb.base/catch-signal-siginfo-cond.exp    |   2 +-
 gdb/testsuite/gdb.base/gnu-ifunc.exp          |   2 +-
 gdb/testsuite/gdb.base/help.exp               |   2 +-
 gdb/testsuite/gdb.base/infcall-failure.c      |  48 +++
 gdb/testsuite/gdb.base/infcall-failure.exp    | 183 +++++++++++
 gdb/testsuite/gdb.base/infcall-timeout.c      |  36 +++
 gdb/testsuite/gdb.base/infcall-timeout.exp    |  98 ++++++
 gdb/testsuite/gdb.base/unwindonsignal.exp     |  36 ++-
 gdb/testsuite/gdb.compile/compile-cplus.exp   |   2 +-
 gdb/testsuite/gdb.compile/compile.exp         |   2 +-
 gdb/testsuite/gdb.cp/gdb2495.exp              |  16 +-
 gdb/testsuite/gdb.fortran/function-calls.exp  |   2 +-
 gdb/testsuite/gdb.mi/mi-syn-frame.exp         |   2 +-
 .../gdb.python/py-finish-breakpoint.exp       |   2 +-
 .../infcall-from-bp-cond-other-thread-event.c | 135 ++++++++
 ...nfcall-from-bp-cond-other-thread-event.exp | 174 ++++++++++
 .../gdb.threads/infcall-from-bp-cond-simple.c |  89 +++++
 .../infcall-from-bp-cond-simple.exp           | 235 ++++++++++++++
 .../gdb.threads/infcall-from-bp-cond-single.c | 139 ++++++++
 .../infcall-from-bp-cond-single.exp           | 117 +++++++
 .../infcall-from-bp-cond-timeout.c            | 169 ++++++++++
 .../infcall-from-bp-cond-timeout.exp          | 174 ++++++++++
 .../gdb.threads/thread-unwindonsignal.exp     |   8 +-
 gdbserver/ax.cc                               |  12 +-
 gdbserver/ax.h                                |   3 +-
 gdbserver/tracepoint.cc                       |  11 +-
 gdbserver/tracepoint.h                        |   9 +-
 38 files changed, 2313 insertions(+), 84 deletions(-)
 create mode 100644 gdb/testsuite/gdb.base/bp-cond-failure.c
 create mode 100644 gdb/testsuite/gdb.base/bp-cond-failure.exp
 create mode 100644 gdb/testsuite/gdb.base/infcall-failure.c
 create mode 100644 gdb/testsuite/gdb.base/infcall-failure.exp
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.c
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp


base-commit: eef174f6a97e3f52a84e4c94a4c710b2e7082176
-- 
2.25.4


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

* [PATCHv5 01/11] gdb: include breakpoint number in testing condition error message
  2023-03-16 17:36       ` [PATCHv5 00/11] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
@ 2023-03-16 17:36         ` Andrew Burgess
  2023-04-03 13:50           ` Andrew Burgess
  2023-07-07 12:08           ` Pedro Alves
  2023-03-16 17:36         ` [PATCHv5 02/11] gdbserver: allows agent_mem_read to return an error code Andrew Burgess
                           ` (10 subsequent siblings)
  11 siblings, 2 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-03-16 17:36 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

When GDB fails to test the condition of a conditional breakpoint, for
whatever reason, the error message looks like this:

  (gdb) break foo if (*(int *) 0) == 1
  Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
  (gdb) r
  Starting program: /tmp/bpcond
  Error in testing breakpoint condition:
  Cannot access memory at address 0x0

  Breakpoint 1, foo () at bpcond.c:11
  11	  int a = 32;
  (gdb)

The line I'm interested in for this commit is this one:

  Error in testing breakpoint condition:

In the case above we can figure out that the problematic breakpoint
was #1 because in the final line of the message GDB reports the stop a
breakpoint #1.

However, in the next few patches I plan to change this.  In some cases
I don't think it makes sense for GDB to report the stop as being at
breakpoint #1, consider this case:

  (gdb) list some_func
  1	int
  2	some_func ()
  3	{
  4	  int *p = 0;
  5	  return *p;
  6	}
  7
  8	void
  9	foo ()
  10	{
  (gdb) break foo if (some_func ())
  Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
  (gdb) r
  Starting program: /tmp/bpcond

  Program received signal SIGSEGV, Segmentation fault.
  0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  Error in testing breakpoint condition:
  The program being debugged was signaled while in a function called from GDB.
  GDB remains in the frame where the signal was received.
  To change this behavior use "set unwindonsignal on".
  Evaluation of the expression containing the function
  (some_func) will be abandoned.
  When the function is done executing, GDB will silently stop.

  Program received signal SIGSEGV, Segmentation fault.

  Breakpoint 1, 0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  (gdb)

Notice that, the final lines of output report the stop as being at
breakpoint #1, even though we are actually located within some_func.

I find this behaviour confusing, and propose that this should be
changed.  However, if I make that change then every reference to
breakpoint #1 will be lost from the error message.

So, in this commit, in preparation for the later commits, I propose to
change the 'Error in testing breakpoint condition:' line to this:

  Error in testing condition for breakpoint NUMBER:

where NUMBER will be filled in as appropriate.  Here's the first
example with the updated error:

  (gdb) break foo if (*(int *) 0) == 0
  Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
  (gdb) r
  Starting program: /tmp/bpcond
  Error in testing condition for breakpoint 1:
  Cannot access memory at address 0x0

  Breakpoint 1, foo () at bpcond.c:11
  11	  int a = 32;
  (gdb)

The breakpoint number does now appear twice in the output, but I don't
see that as a negative.

This commit just changes the one line of the error, and updates the
few tests that either included the old error in comments, or actually
checked for the error in the expected output.

As the only test that checked the line I modified is a Python test,
I've added a new test that doesn't rely on Python that checks the
error message in detail.

While working on the new test, I spotted that it would fail when run
with native-gdbserver and native-extended-gdbserver target boards.
This turns out to be due to a gdbserver bug.  To avoid cluttering this
commit I've added a work around to the new test script so that the
test passes for the remote boards, in the next few commits I will fix
gdbserver, and update the test script to remove the work around.
---
 gdb/breakpoint.c                              |   3 +-
 gdb/testsuite/gdb.base/bp-cond-failure.c      |  30 +++++
 gdb/testsuite/gdb.base/bp-cond-failure.exp    | 112 ++++++++++++++++++
 .../gdb.base/catch-signal-siginfo-cond.exp    |   2 +-
 gdb/testsuite/gdb.base/gnu-ifunc.exp          |   2 +-
 .../gdb.python/py-finish-breakpoint.exp       |   2 +-
 6 files changed, 147 insertions(+), 4 deletions(-)
 create mode 100644 gdb/testsuite/gdb.base/bp-cond-failure.c
 create mode 100644 gdb/testsuite/gdb.base/bp-cond-failure.exp

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index abee22cd162..dcd42e6b2e2 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -5543,7 +5543,8 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
 	  catch (const gdb_exception_error &ex)
 	    {
 	      exception_fprintf (gdb_stderr, ex,
-				 "Error in testing breakpoint condition:\n");
+				 "Error in testing condition for breakpoint %d:\n",
+				 b->number);
 	    }
 	}
       else
diff --git a/gdb/testsuite/gdb.base/bp-cond-failure.c b/gdb/testsuite/gdb.base/bp-cond-failure.c
new file mode 100644
index 00000000000..2a9974b47ce
--- /dev/null
+++ b/gdb/testsuite/gdb.base/bp-cond-failure.c
@@ -0,0 +1,30 @@
+/* Copyright 2022-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/>.  */
+
+int
+foo ()
+{
+  return 0;	/* Breakpoint here.  */
+}
+
+int
+main ()
+{
+  int res = foo ();
+
+  return res;
+}
diff --git a/gdb/testsuite/gdb.base/bp-cond-failure.exp b/gdb/testsuite/gdb.base/bp-cond-failure.exp
new file mode 100644
index 00000000000..b528ccce4ad
--- /dev/null
+++ b/gdb/testsuite/gdb.base/bp-cond-failure.exp
@@ -0,0 +1,112 @@
+# Copyright 2022-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/>.
+
+# Check the format of the error message given when a breakpoint
+# condition fails.
+#
+# In this case the breakpoint condition does not make use of inferior
+# function calls, instead, the expression used for the breakpoint
+# condition will throw an error when evaluated.
+#
+# We check that the correct breakpoint number appears in the error
+# message, and that the error is reported at the correct source
+# location.
+
+standard_testfile
+
+if { [prepare_for_testing "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug}] == -1 } {
+    return
+}
+
+# Run to main so that we connect to the target if using 'target
+# remote'.  This means that the is_address_zero_readable, and the
+# 'show breakpoint condition-evaluation' checks below will be
+# performed with the remote connection in place.
+if { ![runto_main] } {
+    return -1
+}
+
+# This test relies on reading address zero triggering a SIGSEGV.
+if { [is_address_zero_readable] } {
+    return
+}
+
+# Where the breakpoint will be placed.
+set bp_line [gdb_get_line_number "Breakpoint here"]
+
+proc run_test { cond_eval } {
+    clean_restart ${::binfile}
+
+    if { ![runto_main] } {
+	return -1
+    }
+
+    if { $cond_eval ne "auto" } {
+	gdb_test_no_output "set breakpoint condition-evaluation ${cond_eval}"
+    }
+
+    # Setup the conditional breakpoint and record its number.
+    gdb_breakpoint "${::srcfile}:${::bp_line} if (*(int *) 0) == 0"
+    set bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*"]
+
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     "Error in testing condition for breakpoint ${bp_num}:" \
+	     "Cannot access memory at address 0x0" \
+	     "" \
+	     "Breakpoint ${bp_num}, foo \\(\\) at \[^\r\n\]+:${::bp_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Breakpoint here\[^\r\n\]+"]
+}
+
+# If we're using a remote target then conditions could be evaulated
+# locally on the host, or on the remote target.  Otherwise, conditions
+# are always evaluated locally.
+#
+# Using "auto" will select the target if the target supports condition
+# evaluation, otherwise, the local host will be used.
+#
+# So, we always include "auto", but then we look at the output of
+# 'show breakpoint condition-evaluation', if this tells us that "auto"
+# is using the target, then we specifically add "host" to the list of
+# modes to check.
+
+set cond_eval_modes { "auto" }
+
+gdb_test_multiple "show breakpoint condition-evaluation" "" {
+    -re -wrap "Breakpoint condition evaluation mode is auto \\(currently target\\)\\." {
+
+	## NOTE: Instead of testing with "auto" and "host" in this
+	## case we only test with "host".  This is because a GDB bug
+	## prevents the "auto" (a.k.a. target) mode from working.
+	##
+	## Don't worry, this will be fixed in a later commit, and this
+	## comment will be removed at that time.
+	##
+	## lappend cond_eval_modes "host"
+
+	set cond_eval_modes { "host" }
+	pass $gdb_test_name
+    }
+
+    -re -wrap "Breakpoint condition evaluation mode is auto \\(currently host\\)\\." {
+	pass $gdb_test_name
+    }
+}
+
+foreach_with_prefix cond_eval $cond_eval_modes {
+    run_test $cond_eval
+}
diff --git a/gdb/testsuite/gdb.base/catch-signal-siginfo-cond.exp b/gdb/testsuite/gdb.base/catch-signal-siginfo-cond.exp
index 7a9452f2d55..86c322372c2 100644
--- a/gdb/testsuite/gdb.base/catch-signal-siginfo-cond.exp
+++ b/gdb/testsuite/gdb.base/catch-signal-siginfo-cond.exp
@@ -18,7 +18,7 @@
 #
 # (gdb) continue
 # Continuing.
-# Error in testing breakpoint condition:
+# Error in testing condition for breakpoint NUM:
 # Selected thread is running.
 #
 # Catchpoint 3 (signal SIGUSR1), 0x0000003615e35877 in __GI_raise (sig=10) at raise.c:56
diff --git a/gdb/testsuite/gdb.base/gnu-ifunc.exp b/gdb/testsuite/gdb.base/gnu-ifunc.exp
index 0a435806409..22462bea233 100644
--- a/gdb/testsuite/gdb.base/gnu-ifunc.exp
+++ b/gdb/testsuite/gdb.base/gnu-ifunc.exp
@@ -281,7 +281,7 @@ proc misc_tests {resolver_attr resolver_debug final_debug} {
 
     # Also test a former patch regression:
     # Continuing.
-    # Error in testing breakpoint condition:
+    # Error in testing condition for breakpoint NUM:
     # Attempt to take address of value not located in memory.
     #
     # Breakpoint 2, main () at ./gdb.base/gnu-ifunc.c:33
diff --git a/gdb/testsuite/gdb.python/py-finish-breakpoint.exp b/gdb/testsuite/gdb.python/py-finish-breakpoint.exp
index b6bd7a63c8f..e5a46874afd 100644
--- a/gdb/testsuite/gdb.python/py-finish-breakpoint.exp
+++ b/gdb/testsuite/gdb.python/py-finish-breakpoint.exp
@@ -188,7 +188,7 @@ with_test_prefix "finish in normal frame" {
     gdb_test "python TestBreakpoint()" "TestBreakpoint init" "set BP in condition"
 
     gdb_test "continue" \
-	"test don't stop: 1.*test don't stop: 2.*test stop.*Error in testing breakpoint condition.*The program being debugged stopped while in a function called from GDB.*" \
+	"test don't stop: 1.*test don't stop: 2.*test stop.*Error in testing condition for breakpoint ${::decimal}.*The program being debugged stopped while in a function called from GDB.*" \
 	"stop in condition function"
 
     gdb_test "continue" "Continuing.*" "finish condition evaluation"
-- 
2.25.4


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

* [PATCHv5 02/11] gdbserver: allows agent_mem_read to return an error code
  2023-03-16 17:36       ` [PATCHv5 00/11] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
  2023-03-16 17:36         ` [PATCHv5 01/11] gdb: include breakpoint number in testing condition error message Andrew Burgess
@ 2023-03-16 17:36         ` Andrew Burgess
  2023-04-03 13:50           ` Andrew Burgess
  2023-03-16 17:36         ` [PATCHv5 03/11] gdbserver: allow agent expressions to fail with invalid memory access Andrew Burgess
                           ` (9 subsequent siblings)
  11 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2023-03-16 17:36 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Currently the gdbserver function agent_mem_read ignores any errors
from calling read_inferior_memory.  This means that if there is an
attempt to access invalid memory then this will appear to succeed.

In this patch I update agent_mem_read so that if read_inferior_memory
fails, agent_mem_read will return an error code.

However, none of the callers of agent_mem_read actually check the
return value, so this commit will have no effect on anything.  In the
next commit I will update the users of agent_mem_read to check for the
error code.

I've also updated the header comments on agent_mem_read to better
reflect what the function does, and its possible return values.
---
 gdbserver/tracepoint.cc | 11 ++++-------
 gdbserver/tracepoint.h  |  9 +++++++--
 2 files changed, 11 insertions(+), 9 deletions(-)

diff --git a/gdbserver/tracepoint.cc b/gdbserver/tracepoint.cc
index 3f60989e4c7..125a384ffb3 100644
--- a/gdbserver/tracepoint.cc
+++ b/gdbserver/tracepoint.cc
@@ -4914,8 +4914,7 @@ condition_true_at_tracepoint (struct tracepoint_hit_ctx *ctx,
   return (value ? 1 : 0);
 }
 
-/* Do memory copies for bytecodes.  */
-/* Do the recording of memory blocks for actions and bytecodes.  */
+/* See tracepoint.h.  */
 
 int
 agent_mem_read (struct eval_agent_expr_context *ctx,
@@ -4927,10 +4926,7 @@ agent_mem_read (struct eval_agent_expr_context *ctx,
 
   /* If a 'to' buffer is specified, use it.  */
   if (to != NULL)
-    {
-      read_inferior_memory (from, to, len);
-      return 0;
-    }
+    return read_inferior_memory (from, to, len);
 
   /* Otherwise, create a new memory block in the trace buffer.  */
   while (remaining > 0)
@@ -4951,7 +4947,8 @@ agent_mem_read (struct eval_agent_expr_context *ctx,
       memcpy (mspace, &blocklen, sizeof (blocklen));
       mspace += sizeof (blocklen);
       /* Record the memory block proper.  */
-      read_inferior_memory (from, mspace, blocklen);
+      if (read_inferior_memory (from, mspace, blocklen) != 0)
+	return 1;
       trace_debug ("%d bytes recorded", blocklen);
       remaining -= blocklen;
       from += blocklen;
diff --git a/gdbserver/tracepoint.h b/gdbserver/tracepoint.h
index 060d44d0033..1f40d7b5177 100644
--- a/gdbserver/tracepoint.h
+++ b/gdbserver/tracepoint.h
@@ -161,8 +161,13 @@ void gdb_agent_about_to_close (int pid);
 struct traceframe;
 struct eval_agent_expr_context;
 
-/* Do memory copies for bytecodes.  */
-/* Do the recording of memory blocks for actions and bytecodes.  */
+/* When TO is not NULL, do memory copies for bytecodes, read LEN bytes
+   starting at address FROM, and place the result in the buffer TO.
+   Return 0 on success, otherwise a non-zero error code.
+
+   When TO is NULL, do the recording of memory blocks for actions and
+   bytecodes into a new traceframe block.  Return 0 on success, otherwise,
+   return 1 if there is an error.  */
 
 int agent_mem_read (struct eval_agent_expr_context *ctx,
 		    unsigned char *to, CORE_ADDR from,
-- 
2.25.4


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

* [PATCHv5 03/11] gdbserver: allow agent expressions to fail with invalid memory access
  2023-03-16 17:36       ` [PATCHv5 00/11] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
  2023-03-16 17:36         ` [PATCHv5 01/11] gdb: include breakpoint number in testing condition error message Andrew Burgess
  2023-03-16 17:36         ` [PATCHv5 02/11] gdbserver: allows agent_mem_read to return an error code Andrew Burgess
@ 2023-03-16 17:36         ` Andrew Burgess
  2023-04-03 13:50           ` Andrew Burgess
  2023-07-07 12:25           ` Pedro Alves
  2023-03-16 17:36         ` [PATCHv5 04/11] gdb: avoid repeated signal reporting during failed conditional breakpoint Andrew Burgess
                           ` (8 subsequent siblings)
  11 siblings, 2 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-03-16 17:36 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

This commit extends gdbserver to take account of a failed memory
access from agent_mem_read, and to return a new eval_result_type
expr_eval_invalid_memory_access.

I have only updated the agent_mem_read calls related directly to
reading memory, I have not updated any of the calls related to
tracepoint data collection.  This is just because I'm not familiar
with that area of gdb/gdbserver, and I don't want to break anything,
so leaving the existing behaviour untouched seems like the safest
approach.

I've then updated gdb.base/bp-cond-failure.exp to test evaluating the
breakpoints on the target, and have also extended the test so that it
checks for different sizes of memory access.
---
 gdb/testsuite/gdb.base/bp-cond-failure.exp | 22 +++++++---------------
 gdbserver/ax.cc                            | 12 ++++++++----
 gdbserver/ax.h                             |  3 ++-
 3 files changed, 17 insertions(+), 20 deletions(-)

diff --git a/gdb/testsuite/gdb.base/bp-cond-failure.exp b/gdb/testsuite/gdb.base/bp-cond-failure.exp
index b528ccce4ad..cb572203772 100644
--- a/gdb/testsuite/gdb.base/bp-cond-failure.exp
+++ b/gdb/testsuite/gdb.base/bp-cond-failure.exp
@@ -47,7 +47,7 @@ if { [is_address_zero_readable] } {
 # Where the breakpoint will be placed.
 set bp_line [gdb_get_line_number "Breakpoint here"]
 
-proc run_test { cond_eval } {
+proc run_test { cond_eval access_type } {
     clean_restart ${::binfile}
 
     if { ![runto_main] } {
@@ -59,7 +59,7 @@ proc run_test { cond_eval } {
     }
 
     # Setup the conditional breakpoint and record its number.
-    gdb_breakpoint "${::srcfile}:${::bp_line} if (*(int *) 0) == 0"
+    gdb_breakpoint "${::srcfile}:${::bp_line} if (*(${access_type} *) 0) == 0"
     set bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*"]
 
     gdb_test "continue" \
@@ -88,17 +88,7 @@ set cond_eval_modes { "auto" }
 
 gdb_test_multiple "show breakpoint condition-evaluation" "" {
     -re -wrap "Breakpoint condition evaluation mode is auto \\(currently target\\)\\." {
-
-	## NOTE: Instead of testing with "auto" and "host" in this
-	## case we only test with "host".  This is because a GDB bug
-	## prevents the "auto" (a.k.a. target) mode from working.
-	##
-	## Don't worry, this will be fixed in a later commit, and this
-	## comment will be removed at that time.
-	##
-	## lappend cond_eval_modes "host"
-
-	set cond_eval_modes { "host" }
+	lappend cond_eval_modes "host"
 	pass $gdb_test_name
     }
 
@@ -107,6 +97,8 @@ gdb_test_multiple "show breakpoint condition-evaluation" "" {
     }
 }
 
-foreach_with_prefix cond_eval $cond_eval_modes {
-    run_test $cond_eval
+foreach_with_prefix access_type { "char" "short" "int" "long long" } {
+    foreach_with_prefix cond_eval $cond_eval_modes {
+	run_test $cond_eval $access_type
+    }
 }
diff --git a/gdbserver/ax.cc b/gdbserver/ax.cc
index 38ebfbbd750..fba5b4ad0fc 100644
--- a/gdbserver/ax.cc
+++ b/gdbserver/ax.cc
@@ -1112,22 +1112,26 @@ gdb_eval_agent_expr (struct eval_agent_expr_context *ctx,
 	  break;
 
 	case gdb_agent_op_ref8:
-	  agent_mem_read (ctx, cnv.u8.bytes, (CORE_ADDR) top, 1);
+	  if (agent_mem_read (ctx, cnv.u8.bytes, (CORE_ADDR) top, 1) != 0)
+	    return expr_eval_invalid_memory_access;
 	  top = cnv.u8.val;
 	  break;
 
 	case gdb_agent_op_ref16:
-	  agent_mem_read (ctx, cnv.u16.bytes, (CORE_ADDR) top, 2);
+	  if (agent_mem_read (ctx, cnv.u16.bytes, (CORE_ADDR) top, 2) != 0)
+	    return expr_eval_invalid_memory_access;
 	  top = cnv.u16.val;
 	  break;
 
 	case gdb_agent_op_ref32:
-	  agent_mem_read (ctx, cnv.u32.bytes, (CORE_ADDR) top, 4);
+	  if (agent_mem_read (ctx, cnv.u32.bytes, (CORE_ADDR) top, 4) != 0)
+	    return expr_eval_invalid_memory_access;
 	  top = cnv.u32.val;
 	  break;
 
 	case gdb_agent_op_ref64:
-	  agent_mem_read (ctx, cnv.u64.bytes, (CORE_ADDR) top, 8);
+	  if (agent_mem_read (ctx, cnv.u64.bytes, (CORE_ADDR) top, 8) != 0)
+	    return expr_eval_invalid_memory_access;
 	  top = cnv.u64.val;
 	  break;
 
diff --git a/gdbserver/ax.h b/gdbserver/ax.h
index 8e64a7a593e..c98e36a83c6 100644
--- a/gdbserver/ax.h
+++ b/gdbserver/ax.h
@@ -41,7 +41,8 @@ enum eval_result_type
     expr_eval_unhandled_opcode,
     expr_eval_unrecognized_opcode,
     expr_eval_divide_by_zero,
-    expr_eval_invalid_goto
+    expr_eval_invalid_goto,
+    expr_eval_invalid_memory_access
   };
 
 struct agent_expr
-- 
2.25.4


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

* [PATCHv5 04/11] gdb: avoid repeated signal reporting during failed conditional breakpoint
  2023-03-16 17:36       ` [PATCHv5 00/11] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                           ` (2 preceding siblings ...)
  2023-03-16 17:36         ` [PATCHv5 03/11] gdbserver: allow agent expressions to fail with invalid memory access Andrew Burgess
@ 2023-03-16 17:36         ` Andrew Burgess
  2023-04-03 13:50           ` Andrew Burgess
  2023-03-16 17:37         ` [PATCHv5 05/11] gdb: don't always print breakpoint location after failed condition check Andrew Burgess
                           ` (7 subsequent siblings)
  11 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2023-03-16 17:36 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Consider the following case:

  (gdb) list some_func
  1	int
  2	some_func ()
  3	{
  4	  int *p = 0;
  5	  return *p;
  6	}
  7
  8	void
  9	foo ()
  10	{
  (gdb) break foo if (some_func ())
  Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
  (gdb) r
  Starting program: /tmp/bpcond

  Program received signal SIGSEGV, Segmentation fault.
  0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  Error in testing breakpoint condition:
  The program being debugged was signaled while in a function called from GDB.
  GDB remains in the frame where the signal was received.
  To change this behavior use "set unwindonsignal on".
  Evaluation of the expression containing the function
  (some_func) will be abandoned.
  When the function is done executing, GDB will silently stop.

  Program received signal SIGSEGV, Segmentation fault.

  Breakpoint 1, 0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  (gdb)

Notice that this line:

  Program received signal SIGSEGV, Segmentation fault.

Appears twice in the output.  The first time is followed by the
current location.  The second time is a little odd, why do we print
that?

Printing that line is controlled, in part, by a global variable,
stopped_by_random_signal.  This variable is reset to zero in
handle_signal_stop, and is set if/when GDB figures out that the
inferior stopped due to some random signal.

The problem is, in our case, GDB first stops at the breakpoint for
foo, and enters handle_signal_stop and the stopped_by_random_signal
global is reset to 0.

Later within handle_signal_stop GDB calls bpstat_stop_status, it is
within this function (via bpstat_check_breakpoint_conditions) that the
breakpoint condition is checked, and, we end up calling the inferior
function (some_func in our example above).

In our case above the thread performing the inferior function call
segfaults in some_func.  GDB catches the SIGSEGV and handles the stop,
this causes us to reenter handle_signal_stop.  The global variable
stopped_by_random_signal is updated, this time it is set to true
because the thread stopped due to SIGSEGV.  As a result of this we
print the first instance of the line (as seen above in the example).

Finally we unwind GDB's call stack, the inferior function call is
complete, and we return to the original handle_signal_stop.  However,
the stopped_by_random_signal global is still carrying the value as
computed for the inferior function call's stop, which is why we now
print a second instance of the line, as seen in the example.

To prevent this, I propose adding a scoped_restore before we start an
inferior function call.  This will save and restore the global
stopped_by_random_signal value.

With this done, the output from our example is now this:

 (gdb) list some_func
  1	int
  2	some_func ()
  3	{
  4	  int *p = 0;
  5	  return *p;
  6	}
  7
  8	void
  9	foo ()
  10	{
  (gdb) break foo if (some_func ())
  Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
  (gdb) r
  Starting program: /tmp/bpcond

  Program received signal SIGSEGV, Segmentation fault.
  0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  Error in testing condition for breakpoint 1:
  The program being debugged stopped while in a function called from GDB.
  Evaluation of the expression containing the function
  (some_func) will be abandoned.
  When the function is done executing, GDB will silently stop.

  Breakpoint 1, 0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  (gdb)

We now only see the 'Program received signal SIGSEGV, ...' line once,
which I think makes more sense.

Finally, I'm aware that the last few lines, that report the stop as
being at 'Breakpoint 1', when this is not where the thread is actually
located anymore, is not great.  I'll address that in the next commit.
---
 gdb/infcall.c                              |   9 +
 gdb/testsuite/gdb.base/infcall-failure.c   |  48 ++++++
 gdb/testsuite/gdb.base/infcall-failure.exp | 185 +++++++++++++++++++++
 3 files changed, 242 insertions(+)
 create mode 100644 gdb/testsuite/gdb.base/infcall-failure.c
 create mode 100644 gdb/testsuite/gdb.base/infcall-failure.exp

diff --git a/gdb/infcall.c b/gdb/infcall.c
index 9ed17bf4f8b..e6cc6ed1a21 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -1293,6 +1293,15 @@ call_function_by_hand_dummy (struct value *function,
   /* Register a clean-up for unwind_on_terminating_exception_breakpoint.  */
   SCOPE_EXIT { delete_std_terminate_breakpoint (); };
 
+  /* The stopped_by_random_signal variable is global.  If we are here
+     as part of a breakpoint condition check then the global will have
+     already been setup as part of the original breakpoint stop.  By
+     making the inferior call the global will be changed when GDB
+     handles the stop after the inferior call.  Avoid confusion by
+     restoring the current value after the inferior call.  */
+  scoped_restore restore_stopped_by_random_signal
+    = make_scoped_restore (&stopped_by_random_signal, 0);
+
   /* - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP -
      If you're looking to implement asynchronous dummy-frames, then
      just below is the place to chop this function in two..  */
diff --git a/gdb/testsuite/gdb.base/infcall-failure.c b/gdb/testsuite/gdb.base/infcall-failure.c
new file mode 100644
index 00000000000..fae012b2cda
--- /dev/null
+++ b/gdb/testsuite/gdb.base/infcall-failure.c
@@ -0,0 +1,48 @@
+/* Copyright 2022-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/>.  */
+
+/* A function that segfaults (assuming that reads of address zero are
+   prohibited), this is used from within a breakpoint condition.  */
+int
+func_segfault ()
+{
+  volatile int *p = 0;
+  return *p;	/* Segfault here.  */
+}
+
+/* A function in which we will place a breakpoint.  This function is itself
+   then used from within a breakpoint condition.  */
+int
+func_bp ()
+{
+  int res = 0;	/* Second breakpoint.  */
+  return res;
+}
+
+int
+foo ()
+{
+  return 0;	/* First breakpoint.  */
+}
+
+int
+main ()
+{
+  int res = foo ();
+
+  return res;
+}
diff --git a/gdb/testsuite/gdb.base/infcall-failure.exp b/gdb/testsuite/gdb.base/infcall-failure.exp
new file mode 100644
index 00000000000..214a64f8de3
--- /dev/null
+++ b/gdb/testsuite/gdb.base/infcall-failure.exp
@@ -0,0 +1,185 @@
+# Copyright 2022-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/>.
+
+# Some simple tests of inferior function calls from breakpoint
+# conditions, in a single-threaded inferior.
+#
+# Test what happens when the inferior function (from a breakpoint
+# condition) either hits a nested breakpoint, or segfaults.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug}] == -1 } {
+    return
+}
+
+set bp_1_line [gdb_get_line_number "First breakpoint"]
+set bp_2_line [gdb_get_line_number "Second breakpoint"]
+set segv_line [gdb_get_line_number "Segfault here"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto
+# main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if { ![runto_main] } {
+	return -1
+    }
+
+    return 0
+}
+
+# Start GDB according to ASYNC_P and NON_STOP_P, then setup a
+# conditional breakpoint.  The breakpoint condition includes an
+# inferior function call that will itself hit a breakpoint.  Check how
+# GDB reports this to the user.
+proc_with_prefix run_cond_hits_breakpoint_test { async_p non_stop_p } {
+    if { [start_gdb_and_runto_main $async_p $non_stop_p] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint and record its number.
+    gdb_breakpoint "${::srcfile}:${::bp_1_line} if (func_bp ())"
+    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		     "get number of first breakpoint"]
+
+    # Setup a breakpoint inside func_bp.
+    gdb_breakpoint "${::srcfile}:${::bp_2_line}"
+    set bp_2_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		     "get number of second breakpoint"]
+
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     "" \
+	     "Breakpoint ${bp_2_num}, func_bp \\(\\) at \[^\r\n\]+:${::bp_2_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Second breakpoint\[^\r\n\]+" \
+	     "Error in testing condition for breakpoint ${bp_1_num}:" \
+	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(func_bp\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\." \
+	     "" \
+	     "Breakpoint ${bp_1_num}, \[^\r\n\]+" \
+	     "${::decimal}\\s+\[^\r\n\]+Second breakpoint\[^\r\n\]+"]
+}
+
+# Start GDB according to ASYNC_P and NON_STOP_P, then call an inferior
+# function.  The inferior function being called will itself have a
+# breakpoint within it.  Check how GDB reports this to the user.
+proc_with_prefix run_call_hits_breakpoint_test { async_p non_stop_p } {
+    if { [start_gdb_and_runto_main $async_p $non_stop_p] == -1 } {
+	return
+    }
+
+    # Setup a breakpoint inside func_bp.
+    gdb_breakpoint "${::srcfile}:${::bp_2_line}"
+    set bp_2_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of second breakpoint"]
+
+
+    gdb_test "call func_bp ()" \
+	[multi_line \
+	     "" \
+	     "Breakpoint ${bp_2_num}, func_bp \\(\\) at \[^\r\n\]+:${::bp_2_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Second breakpoint\[^\r\n\]+" \
+	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(func_bp\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+}
+
+# Start GDB according to ASYNC_P and NON_STOP_P, then setup a
+# conditional breakpoint.  The breakpoint condition includes an
+# inferior function call that segfaults.  Check how GDB reports this
+# to the user.
+proc_with_prefix run_cond_hits_segfault_test { async_p non_stop_p } {
+    if { [start_gdb_and_runto_main $async_p $non_stop_p] == -1 } {
+	return
+    }
+
+    # This test relies on the inferior segfaulting when trying to
+    # access address zero.
+    if { [is_address_zero_readable] } {
+	unsupported "address zero is readable"
+	return
+    }
+
+    # Setup the conditional breakpoint and record its number.
+    gdb_breakpoint "${::srcfile}:${::bp_1_line} if (func_segfault ())"
+    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		     "get number of first breakpoint"]
+
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     "" \
+	     "Program received signal SIGSEGV, Segmentation fault\\." \
+	     "${::hex} in func_segfault \\(\\) at \[^\r\n\]+:${::segv_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
+	     "Error in testing condition for breakpoint ${bp_1_num}:" \
+	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(func_segfault\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\." \
+	     "" \
+	     "Breakpoint ${bp_1_num}, \[^\r\n\]+" \
+	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"]
+}
+
+# Start GDB according to ASYNC_P and NON_STOP_P, then call an inferior
+# function.  The inferior function will segfault.  Check how GDB
+# reports this to the user.
+proc_with_prefix run_call_hits_segfault_test { async_p non_stop_p } {
+    if { [start_gdb_and_runto_main $async_p $non_stop_p] == -1 } {
+	return
+    }
+
+    # This test relies on the inferior segfaulting when trying to
+    # access address zero.
+    if { [is_address_zero_readable] } {
+	unsupported "address zero is readable"
+	return
+    }
+
+    gdb_test "call func_segfault ()" \
+	[multi_line \
+	     "" \
+	     "Program received signal SIGSEGV, Segmentation fault\\." \
+	     "${::hex} in func_segfault \\(\\) at \[^\r\n\]+:${::segv_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
+	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(func_segfault\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	run_cond_hits_breakpoint_test $target_async $target_non_stop
+	run_call_hits_breakpoint_test $target_async $target_non_stop
+
+	run_cond_hits_segfault_test $target_async $target_non_stop
+	run_call_hits_segfault_test $target_async $target_non_stop
+    }
+}
-- 
2.25.4


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

* [PATCHv5 05/11] gdb: don't always print breakpoint location after failed condition check
  2023-03-16 17:36       ` [PATCHv5 00/11] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                           ` (3 preceding siblings ...)
  2023-03-16 17:36         ` [PATCHv5 04/11] gdb: avoid repeated signal reporting during failed conditional breakpoint Andrew Burgess
@ 2023-03-16 17:37         ` Andrew Burgess
  2023-04-03 13:51           ` Andrew Burgess
  2023-07-07 15:20           ` Pedro Alves
  2023-03-16 17:37         ` [PATCHv5 06/11] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
                           ` (6 subsequent siblings)
  11 siblings, 2 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-03-16 17:37 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Consider the following session:

  (gdb) list some_func
  1	int
  2	some_func ()
  3	{
  4	  int *p = 0;
  5	  return *p;
  6	}
  7
  8	void
  9	foo ()
  10	{
  (gdb) break foo if (some_func ())
  Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
  (gdb) r
  Starting program: /tmp/bpcond

  Program received signal SIGSEGV, Segmentation fault.
  0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  Error in testing condition for breakpoint 1:
  The program being debugged stopped while in a function called from GDB.
  Evaluation of the expression containing the function
  (some_func) will be abandoned.
  When the function is done executing, GDB will silently stop.

  Breakpoint 1, 0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  (gdb)

What happens here is the breakpoint condition includes a call to an
inferior function, and the inferior function segfaults.  We can see
that GDB reports the segfault, and then gives an error message that
indicates that an inferior function call was interrupted.

After this GDB appears to report that it is stopped at Breakpoint 1,
inside some_func.

I find this second stop report a little confusing.  While it is true
that GDB stopped as a result of hitting breakpoint 1, I think the
message GDB currently prints might give the impression that GDB is
actually stopped at a location of breakpoint 1, which is not the case.

Also, I find the second stop message draws attention away from
the "Program received signal SIGSEGV, Segmentation fault" stop
message, and this second stop might be thought of as replacing in
someway the earlier message.

In short, I think things would be clearer if the second stop message
were not reported at all, so the output should, I think, look like
this:

  (gdb) list some_func
  1	int
  2	some_func ()
  3	{
  4	  int *p = 0;
  5	  return *p;
  6	}
  7
  8	void
  9	foo ()
  10	{
  (gdb) break foo if (some_func ())
  Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
  (gdb) r
  Starting program: /tmp/bpcond

  Program received signal SIGSEGV, Segmentation fault.
  0x0000000000401116 in some_func () at bpcond.c:5
  5	  return *p;
  Error in testing condition for breakpoint 1:
  The program being debugged stopped while in a function called from GDB.
  Evaluation of the expression containing the function
  (some_func) will be abandoned.
  When the function is done executing, GDB will silently stop.
  (gdb)

The user can still find the number of the breakpoint that triggered
the initial stop in this line:

  Error in testing condition for breakpoint 1:

But there's now only one stop reason reported, the SIGSEGV, which I
think is much clearer.

To achieve this change I set the bpstat::print field when:

  (a) a breakpoint condition evaluation failed, and

  (b) the $pc of the thread changed during condition evaluation.

I've updated the existing tests that checked the error message printed
when a breakpoint condition evaluation failed.
---
 gdb/breakpoint.c                           | 12 ++++++++++++
 gdb/testsuite/gdb.base/infcall-failure.exp | 18 ++++++++----------
 2 files changed, 20 insertions(+), 10 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index dcd42e6b2e2..445b46a706a 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -5534,6 +5534,7 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
 	  else
 	    within_current_scope = false;
 	}
+      CORE_ADDR pc_before_check = get_frame_pc (get_selected_frame (nullptr));
       if (within_current_scope)
 	{
 	  try
@@ -5545,6 +5546,17 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
 	      exception_fprintf (gdb_stderr, ex,
 				 "Error in testing condition for breakpoint %d:\n",
 				 b->number);
+
+	      /* If the pc value changed as a result of evaluating the
+		 condition then we probably stopped within an inferior
+		 function call due to some unexpected stop, e.g. the thread
+		 hit another breakpoint, or the thread received an
+		 unexpected signal.  In this case we don't want to also
+		 print the information about this breakpoint.  */
+	      CORE_ADDR pc_after_check
+		= get_frame_pc (get_selected_frame (nullptr));
+	      if (pc_before_check != pc_after_check)
+		bs->print = 0;
 	    }
 	}
       else
diff --git a/gdb/testsuite/gdb.base/infcall-failure.exp b/gdb/testsuite/gdb.base/infcall-failure.exp
index 214a64f8de3..5ad179a089d 100644
--- a/gdb/testsuite/gdb.base/infcall-failure.exp
+++ b/gdb/testsuite/gdb.base/infcall-failure.exp
@@ -78,10 +78,7 @@ proc_with_prefix run_cond_hits_breakpoint_test { async_p non_stop_p } {
 	     "The program being debugged stopped while in a function called from GDB\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(func_bp\\) will be abandoned\\." \
-	     "When the function is done executing, GDB will silently stop\\." \
-	     "" \
-	     "Breakpoint ${bp_1_num}, \[^\r\n\]+" \
-	     "${::decimal}\\s+\[^\r\n\]+Second breakpoint\[^\r\n\]+"]
+	     "When the function is done executing, GDB will silently stop\\."]
 }
 
 # Start GDB according to ASYNC_P and NON_STOP_P, then call an inferior
@@ -138,13 +135,12 @@ proc_with_prefix run_cond_hits_segfault_test { async_p non_stop_p } {
 	     "${::hex} in func_segfault \\(\\) at \[^\r\n\]+:${::segv_line}" \
 	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
 	     "Error in testing condition for breakpoint ${bp_1_num}:" \
-	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "The program being debugged was signaled while in a function called from GDB\\." \
+	     "GDB remains in the frame where the signal was received\\." \
+	     "To change this behavior use \"set unwindonsignal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(func_segfault\\) will be abandoned\\." \
-	     "When the function is done executing, GDB will silently stop\\." \
-	     "" \
-	     "Breakpoint ${bp_1_num}, \[^\r\n\]+" \
-	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"]
+	     "When the function is done executing, GDB will silently stop\\."]
 }
 
 # Start GDB according to ASYNC_P and NON_STOP_P, then call an inferior
@@ -168,7 +164,9 @@ proc_with_prefix run_call_hits_segfault_test { async_p non_stop_p } {
 	     "Program received signal SIGSEGV, Segmentation fault\\." \
 	     "${::hex} in func_segfault \\(\\) at \[^\r\n\]+:${::segv_line}" \
 	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
-	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "The program being debugged was signaled while in a function called from GDB\\." \
+	     "GDB remains in the frame where the signal was received\\." \
+	     "To change this behavior use \"set unwindonsignal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(func_segfault\\) will be abandoned\\." \
 	     "When the function is done executing, GDB will silently stop\\."]
-- 
2.25.4


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

* [PATCHv5 06/11] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait"
  2023-03-16 17:36       ` [PATCHv5 00/11] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                           ` (4 preceding siblings ...)
  2023-03-16 17:37         ` [PATCHv5 05/11] gdb: don't always print breakpoint location after failed condition check Andrew Burgess
@ 2023-03-16 17:37         ` Andrew Burgess
  2023-03-16 17:37         ` [PATCHv5 07/11] gdb: fix b/p conditions with infcalls in multi-threaded inferiors Andrew Burgess
                           ` (5 subsequent siblings)
  11 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-03-16 17:37 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

This reverts commit ac0d67ed1dcf470bad6a3bc4800c2ddc9bedecca.

There was nothing wrong with the commit which I'm reverting here, but
it removed some functionality that will be needed for a later commit;
that is, the ability for GDB to ask for events from a specific ptid_t
via the do_target_wait function.

In a follow up commit, this functionality will be used to implement
inferior function calls in multi-threaded inferiors.

This is not a straight revert of the above commit.  Reverting the
above commit replaces a 'nullptr' with 'NULL', I've gone in and
changed that, preserving the 'nullptr'.
---
 gdb/infrun.c | 12 +++++++-----
 1 file changed, 7 insertions(+), 5 deletions(-)

diff --git a/gdb/infrun.c b/gdb/infrun.c
index 33aa0c8794b..9f8c8412183 100644
--- a/gdb/infrun.c
+++ b/gdb/infrun.c
@@ -3830,7 +3830,8 @@ do_target_wait_1 (inferior *inf, ptid_t ptid,
    more events.  Polls for events from all inferiors/targets.  */
 
 static bool
-do_target_wait (execution_control_state *ecs, target_wait_flags options)
+do_target_wait (ptid_t wait_ptid, execution_control_state *ecs,
+		target_wait_flags options)
 {
   int num_inferiors = 0;
   int random_selector;
@@ -3840,9 +3841,10 @@ do_target_wait (execution_control_state *ecs, target_wait_flags options)
      polling the rest of the inferior list starting from that one in a
      circular fashion until the whole list is polled once.  */
 
-  auto inferior_matches = [] (inferior *inf)
+  auto inferior_matches = [&wait_ptid] (inferior *inf)
     {
-      return inf->process_target () != nullptr;
+      return (inf->process_target () != nullptr
+	      && ptid_t (inf->pid).matches (wait_ptid));
     };
 
   /* First see how many matching inferiors we have.  */
@@ -3881,7 +3883,7 @@ do_target_wait (execution_control_state *ecs, target_wait_flags options)
 
   auto do_wait = [&] (inferior *inf)
   {
-    ecs->ptid = do_target_wait_1 (inf, minus_one_ptid, &ecs->ws, options);
+    ecs->ptid = do_target_wait_1 (inf, wait_ptid, &ecs->ws, options);
     ecs->target = inf->process_target ();
     return (ecs->ws.kind () != TARGET_WAITKIND_IGNORE);
   };
@@ -4311,7 +4313,7 @@ fetch_inferior_event ()
        the event.  */
     scoped_disable_commit_resumed disable_commit_resumed ("handling event");
 
-    if (!do_target_wait (&ecs, TARGET_WNOHANG))
+    if (!do_target_wait (minus_one_ptid, &ecs, TARGET_WNOHANG))
       {
 	infrun_debug_printf ("do_target_wait returned no event");
 	disable_commit_resumed.reset_and_commit ();
-- 
2.25.4


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

* [PATCHv5 07/11] gdb: fix b/p conditions with infcalls in multi-threaded inferiors
  2023-03-16 17:36       ` [PATCHv5 00/11] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                           ` (5 preceding siblings ...)
  2023-03-16 17:37         ` [PATCHv5 06/11] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
@ 2023-03-16 17:37         ` Andrew Burgess
  2023-03-16 17:37         ` [PATCHv5 08/11] gdb: add timeouts for inferior function calls Andrew Burgess
                           ` (4 subsequent siblings)
  11 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-03-16 17:37 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Natalia Saiapova, Tankut Baris Aktemur

This commit fixes bug PR 28942, that is, creating a conditional
breakpoint in a multi-threaded inferior, where the breakpoint
condition includes an inferior function call.

Currently, when a user tries to create such a breakpoint, then GDB
will fail with:

  (gdb) break infcall-from-bp-cond-single.c:61 if (return_true ())
  Breakpoint 2 at 0x4011fa: file /tmp/build/gdb/testsuite/../../../src/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c, line 61.
  (gdb) continue
  Continuing.
  [New Thread 0x7ffff7c5d700 (LWP 2460150)]
  [New Thread 0x7ffff745c700 (LWP 2460151)]
  [New Thread 0x7ffff6c5b700 (LWP 2460152)]
  [New Thread 0x7ffff645a700 (LWP 2460153)]
  [New Thread 0x7ffff5c59700 (LWP 2460154)]
  Error in testing breakpoint condition:
  Couldn't get registers: No such process.
  An error occurred while in a function called from GDB.
  Evaluation of the expression containing the function
  (return_true) will be abandoned.
  When the function is done executing, GDB will silently stop.
  Selected thread is running.
  (gdb)

Or, in some cases, like this:

  (gdb) break infcall-from-bp-cond-simple.c:56 if (is_matching_tid (arg, 1))
  Breakpoint 2 at 0x401194: file /tmp/build/gdb/testsuite/../../../src/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c, line 56.
  (gdb) continue
  Continuing.
  [New Thread 0x7ffff7c5d700 (LWP 2461106)]
  [New Thread 0x7ffff745c700 (LWP 2461107)]
  ../../src.release/gdb/nat/x86-linux-dregs.c:146: internal-error: x86_linux_update_debug_registers: Assertion `lwp_is_stopped (lwp)' failed.
  A problem internal to GDB has been detected,
  further debugging may prove unreliable.

The precise error depends on the exact thread state; so there's race
conditions depending on which threads have fully started, and which
have not.  But the underlying problem is always the same; when GDB
tries to execute the inferior function call from within the breakpoint
condition, GDB will, incorrectly, try to resume threads that are
already running - GDB doesn't realise that some threads might already
be running.

The solution proposed in this patch requires an additional member
variable thread_info::in_cond_eval.  This flag is set to true (in
breakpoint.c) when GDB is evaluating a breakpoint condition.

In user_visible_resume_ptid (infrun.c), when the in_cond_eval flag is
true, then GDB will only try to resume the current thread, that is,
the thread for which the breakpoint condition is being evaluated.
This solves the problem of GDB trying to resume threads that are
already running.

The next problem is that inferior function calls are assumed to be
synchronous, that is, GDB doesn't expect to start an inferior function
call in thread #1, then receive a stop from thread #2 for some other,
unrelated reason.  To prevent GDB responding to an event from another
thread, we update fetch_inferior_event and do_target_wait in infrun.c,
so that, when an inferior function call (on behalf of a breakpoint
condition) is in progress, we only wait for events from the current
thread (the one evaluating the condition).

In do_target_wait I had to change the inferior_matches lambda
function, which is used to select which inferior to wait on.
Previously the logic was this:

   auto inferior_matches = [&wait_ptid] (inferior *inf)
     {
       return (inf->process_target () != nullptr
               && ptid_t (inf->pid).matches (wait_ptid));
     };

This compares the pid of the inferior against the complete ptid we
want to wait on.  Before this commit wait_ptid was only ever
minus_one_ptid (which is special, and means any process), and so every
inferior would match.

After this commit though wait_ptid might represent a specific thread
in a specific inferior.  If we compare the pid of the inferior to a
specific ptid then these will not match.  The fix is to compare
against the pid extracted from the wait_ptid, not against the complete
wait_ptid itself.

In fetch_inferior_event, after receiving the event, we only want to
stop all the other threads, and call inferior_event_handler with
INF_EXEC_COMPLETE, if we are not evaluating a conditional breakpoint.
If we are, then all the other threads should be left doing whatever
they were before.  The inferior_event_handler call will be performed
once the breakpoint condition has finished being evaluated, and GDB
decides to stop or not.

The final problem that needs solving relates to GDB's commit-resume
mechanism, which allows GDB to collect resume requests into a single
packet in order to reduce traffic to a remote target.

The problem is that the commit-resume mechanism will not send any
resume requests for an inferior if there are already events pending on
the GDB side.

Imagine an inferior with two threads.  Both threads hit a breakpoint,
maybe the same conditional breakpoint.  At this point there are two
pending events, one for each thread.

GDB selects one of the events and spots that this is a conditional
breakpoint, GDB evaluates the condition.

The condition includes an inferior function call, so GDB sets up for
the call and resumes the one thread, the resume request is added to
the commit-resume queue.

When the commit-resume queue is committed GDB sees that there is a
pending event from another thread, and so doesn't send any resume
requests to the actual target, GDB is assuming that when we wait we
will select the event from the other thread.

However, as this is an inferior function call for a condition
evaluation, we will not select the event from the other thread, we
only care about events from the thread that is evaluating the
condition - and the resume for this thread was never sent to the
target.

And so, GDB hangs, waiting for an event from a thread that was never
fully resumed.

To fix this issue I have added the concept of "forcing" the
commit-resume queue.  When enabling commit resume, if the force flag
is true, then any resumes will be committed to the target, even if
there are other threads with pending events.

A note on authorship: this patch was based on some work done by
Natalia Saiapova and Tankut Baris Aktemur from Intel[1].  I have made
some changes to their work in this version.

Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=28942

[1] https://sourceware.org/pipermail/gdb-patches/2020-October/172454.html

Co-authored-by: Natalia Saiapova <natalia.saiapova@intel.com>
Co-authored-by: Tankut Baris Aktemur <tankut.baris.aktemur@intel.com>
---
 gdb/breakpoint.c                              |   2 +
 gdb/gdbthread.h                               |   3 +
 gdb/infcall.c                                 |   6 +
 gdb/infrun.c                                  |  64 +++--
 gdb/infrun.h                                  |   3 +-
 .../infcall-from-bp-cond-other-thread-event.c | 135 ++++++++++
 ...nfcall-from-bp-cond-other-thread-event.exp | 174 +++++++++++++
 .../gdb.threads/infcall-from-bp-cond-simple.c |  89 +++++++
 .../infcall-from-bp-cond-simple.exp           | 235 ++++++++++++++++++
 .../gdb.threads/infcall-from-bp-cond-single.c | 139 +++++++++++
 .../infcall-from-bp-cond-single.exp           | 117 +++++++++
 11 files changed, 952 insertions(+), 15 deletions(-)
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 445b46a706a..70621ead9ef 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -5539,6 +5539,8 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
 	{
 	  try
 	    {
+	      scoped_restore reset_in_cond_eval
+		= make_scoped_restore (&thread->control.in_cond_eval, true);
 	      condition_result = breakpoint_cond_eval (cond);
 	    }
 	  catch (const gdb_exception_error &ex)
diff --git a/gdb/gdbthread.h b/gdb/gdbthread.h
index c0f27a8a66e..736d5d50b5f 100644
--- a/gdb/gdbthread.h
+++ b/gdb/gdbthread.h
@@ -171,6 +171,9 @@ struct thread_control_state
      command.  This is used to decide whether "set scheduler-locking
      step" behaves like "on" or "off".  */
   int stepping_command = 0;
+
+  /* True if the thread is evaluating a BP condition.  */
+  bool in_cond_eval = false;
 };
 
 /* Inferior thread specific part of `struct infcall_suspend_state'.  */
diff --git a/gdb/infcall.c b/gdb/infcall.c
index e6cc6ed1a21..4fb8ab07db0 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -641,6 +641,12 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
 
       proceed (real_pc, GDB_SIGNAL_0);
 
+      /* Enable commit resume, but pass true for the force flag.  This
+	 ensures any thread we set running in proceed will actually be
+	 committed to the target, even if some other thread in the current
+	 target has a pending event.  */
+      scoped_enable_commit_resumed enable ("infcall", true);
+
       infrun_debug_show_threads ("non-exited threads after proceed for inferior-call",
 				 all_non_exited_threads ());
 
diff --git a/gdb/infrun.c b/gdb/infrun.c
index 9f8c8412183..11a340b9a78 100644
--- a/gdb/infrun.c
+++ b/gdb/infrun.c
@@ -2219,6 +2219,14 @@ user_visible_resume_ptid (int step)
 	 mode.  */
       resume_ptid = inferior_ptid;
     }
+  else if (inferior_ptid != null_ptid
+	   && inferior_thread ()->control.in_cond_eval)
+    {
+      /* The inferior thread is evaluating a BP condition.  Other threads
+	 might be stopped or running and we do not want to change their
+	 state, thus, resume only the current thread.  */
+      resume_ptid = inferior_ptid;
+    }
   else if (!sched_multi && target_supports_multi_process ())
     {
       /* Resume all threads of the current process (and none of other
@@ -2953,12 +2961,24 @@ schedlock_applies (struct thread_info *tp)
 					    execution_direction)));
 }
 
-/* Set process_stratum_target::COMMIT_RESUMED_STATE in all target
-   stacks that have threads executing and don't have threads with
-   pending events.  */
+/* When FORCE_P is false, set process_stratum_target::COMMIT_RESUMED_STATE
+   in all target stacks that have threads executing and don't have threads
+   with pending events.
+
+   When FORCE_P is true, set process_stratum_target::COMMIT_RESUMED_STATE
+   in all target stacks that have threads executing regardless of whether
+   there are pending events or not.
+
+    Passing FORCE_P as false makes sense when GDB is going to wait for
+    events from all threads and will therefore spot the pending events.
+    However, if GDB is only going to wait for events from select threads
+    (i.e. when performing an inferior call) then a pending event on some
+    other thread will not be spotted, and if we fail to commit the resume
+    state for the thread performing the inferior call, then the inferior
+    call will never complete (or even start).  */
 
 static void
-maybe_set_commit_resumed_all_targets ()
+maybe_set_commit_resumed_all_targets (bool force_p)
 {
   scoped_restore_current_thread restore_thread;
 
@@ -2987,7 +3007,7 @@ maybe_set_commit_resumed_all_targets ()
 	 status to report, handle it before requiring the target to
 	 commit its resumed threads: handling the status might lead to
 	 resuming more threads.  */
-      if (proc_target->has_resumed_with_pending_wait_status ())
+      if (!force_p && proc_target->has_resumed_with_pending_wait_status ())
 	{
 	  infrun_debug_printf ("not requesting commit-resumed for target %s, a"
 			       " thread has a pending waitstatus",
@@ -2997,7 +3017,7 @@ maybe_set_commit_resumed_all_targets ()
 
       switch_to_inferior_no_thread (inf);
 
-      if (target_has_pending_events ())
+      if (!force_p && target_has_pending_events ())
 	{
 	  infrun_debug_printf ("not requesting commit-resumed for target %s, "
 			       "target has pending events",
@@ -3090,7 +3110,7 @@ scoped_disable_commit_resumed::reset ()
     {
       /* This is the outermost instance, re-enable
 	 COMMIT_RESUMED_STATE on the targets where it's possible.  */
-      maybe_set_commit_resumed_all_targets ();
+      maybe_set_commit_resumed_all_targets (false);
     }
   else
     {
@@ -3123,7 +3143,7 @@ scoped_disable_commit_resumed::reset_and_commit ()
 /* See infrun.h.  */
 
 scoped_enable_commit_resumed::scoped_enable_commit_resumed
-  (const char *reason)
+  (const char *reason, bool force_p)
   : m_reason (reason),
     m_prev_enable_commit_resumed (enable_commit_resumed)
 {
@@ -3135,7 +3155,7 @@ scoped_enable_commit_resumed::scoped_enable_commit_resumed
 
       /* Re-enable COMMIT_RESUMED_STATE on the targets where it's
 	 possible.  */
-      maybe_set_commit_resumed_all_targets ();
+      maybe_set_commit_resumed_all_targets (force_p);
 
       maybe_call_commit_resumed_all_targets ();
     }
@@ -3841,10 +3861,11 @@ do_target_wait (ptid_t wait_ptid, execution_control_state *ecs,
      polling the rest of the inferior list starting from that one in a
      circular fashion until the whole list is polled once.  */
 
-  auto inferior_matches = [&wait_ptid] (inferior *inf)
+  ptid_t wait_ptid_pid {wait_ptid.pid ()};
+  auto inferior_matches = [&wait_ptid_pid] (inferior *inf)
     {
       return (inf->process_target () != nullptr
-	      && ptid_t (inf->pid).matches (wait_ptid));
+	      && ptid_t (inf->pid).matches (wait_ptid_pid));
     };
 
   /* First see how many matching inferiors we have.  */
@@ -4313,7 +4334,17 @@ fetch_inferior_event ()
        the event.  */
     scoped_disable_commit_resumed disable_commit_resumed ("handling event");
 
-    if (!do_target_wait (minus_one_ptid, &ecs, TARGET_WNOHANG))
+    /* Is the current thread performing an inferior function call as part
+       of a breakpoint condition evaluation?  */
+    bool in_cond_eval = (inferior_ptid != null_ptid
+			 && inferior_thread ()->control.in_cond_eval);
+
+    /* If the thread is in the middle of the condition evaluation, wait for
+       an event from the current thread.  Otherwise, wait for an event from
+       any thread.  */
+    ptid_t waiton_ptid = in_cond_eval ? inferior_ptid : minus_one_ptid;
+
+    if (!do_target_wait (waiton_ptid, &ecs, TARGET_WNOHANG))
       {
 	infrun_debug_printf ("do_target_wait returned no event");
 	disable_commit_resumed.reset_and_commit ();
@@ -4365,7 +4396,12 @@ fetch_inferior_event ()
 	    bool should_notify_stop = true;
 	    bool proceeded = false;
 
-	    stop_all_threads_if_all_stop_mode ();
+	    /* If the thread that stopped just completed an inferior
+	       function call as part of a condition evaluation, then we
+	       don't want to stop all the other threads.  */
+	    if (ecs.event_thread == nullptr
+		|| !ecs.event_thread->control.in_cond_eval)
+	      stop_all_threads_if_all_stop_mode ();
 
 	    clean_up_just_stopped_threads_fsms (&ecs);
 
@@ -4380,7 +4416,7 @@ fetch_inferior_event ()
 		  proceeded = normal_stop ();
 	      }
 
-	    if (!proceeded)
+	    if (!proceeded && !in_cond_eval)
 	      {
 		inferior_event_handler (INF_EXEC_COMPLETE);
 		cmd_done = 1;
diff --git a/gdb/infrun.h b/gdb/infrun.h
index 5219063586d..f9d68e3db8b 100644
--- a/gdb/infrun.h
+++ b/gdb/infrun.h
@@ -402,7 +402,8 @@ extern void maybe_call_commit_resumed_all_targets ();
 
 struct scoped_enable_commit_resumed
 {
-  explicit scoped_enable_commit_resumed (const char *reason);
+  explicit scoped_enable_commit_resumed (const char *reason,
+					 bool force_p = false);
   ~scoped_enable_commit_resumed ();
 
   DISABLE_COPY_AND_ASSIGN (scoped_enable_commit_resumed);
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
new file mode 100644
index 00000000000..e2a8ccb4ebe
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
@@ -0,0 +1,135 @@
+/* Copyright 2022-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 <pthread.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <sched.h>
+
+#define NUM_THREADS 2
+
+pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+
+/* Some global variables to poke, just for something to do.  */
+volatile int global_var_0 = 0;
+volatile int global_var_1 = 0;
+
+/* This flag is updated from GDB.  */
+volatile int raise_signal = 0;
+
+/* Implement the breakpoint condition function.  Release the other thread
+   and try to give the other thread a chance to run.  Then return ANSWER.  */
+int
+condition_core_func (int answer)
+{
+  /* This unlock should release the other thread.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  /* And this yield and sleep should (hopefully) give the other thread a
+     chance to run.  This isn't guaranteed of course, but once the other
+     thread does run it should hit a breakpoint, which GDB should
+     (temporarily) ignore, so there's no easy way for us to know the other
+     thread has done what it needs to, thus, yielding and sleeping is the
+     best we can do.  */
+  sched_yield ();
+  sleep (2);
+
+  return answer;
+}
+
+void
+stop_marker ()
+{
+  int a = 100;	/* Final breakpoint here.  */
+}
+
+/* A breakpoint condition function that always returns true.  */
+int
+condition_true_func ()
+{
+  return condition_core_func (1);
+}
+
+/* A breakpoint condition function that always returns false.  */
+int
+condition_false_func ()
+{
+  return condition_core_func (0);
+}
+
+void *
+worker_func (void *arg)
+{
+  volatile int *ptr = 0;
+  int tid = *((int *) arg);
+
+  switch (tid)
+    {
+    case 0:
+      global_var_0 = 11;	/* First thread breakpoint.  */
+      break;
+
+    case 1:
+      if (pthread_mutex_lock (&mutex) != 0)
+	abort ();
+      if (raise_signal)
+	global_var_1 = *ptr;	/* Signal here.  */
+      else
+	global_var_1 = 99;	/* Other thread breakpoint.  */
+      break;
+
+    default:
+      abort ();
+    }
+
+  return NULL;
+}
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+
+  /* Set an alarm, just in case the test deadlocks.  */
+  alarm (300);
+
+  /* We want the mutex to start locked.  */
+  if (pthread_mutex_lock (&mutex) != 0)
+    abort ();
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      void *retval;
+      pthread_join (threads[i], &retval);
+    }
+
+  /* Unlock once we're done, just for cleanliness.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
new file mode 100644
index 00000000000..6d4e1e13ab2
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
@@ -0,0 +1,174 @@
+# Copyright 2022-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/>.
+
+# Test for conditional breakpoints where the breakpoint condition includes
+# an inferior function call.
+#
+# The tests in this script are testing what happens when an event arrives in
+# another thread while GDB is waiting for the inferior function call (in the
+# breakpoint condition) to finish.
+#
+# The expectation is that GDB will queue events for other threads and wait
+# for the inferior function call to complete, if the condition is true, then
+# the conditional breakpoint should be reported first.  The other thread
+# event should of course, not get lost, and should be reported as soon as
+# the user tries to continue the inferior.
+#
+# If the conditional breakpoint ends up not being taken (the condition is
+# false), then the other thread event should be reported immediately.
+#
+# This script tests what happens when the other thread event is (a) the
+# other thread hitting a breakpoint, and (b) the other thread taking a
+# signal (SIGSEGV in this case).
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] == -1 } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "First thread breakpoint"]
+set other_bp_line [gdb_get_line_number "Other thread breakpoint"]
+set final_bp_line [gdb_get_line_number "Final breakpoint here"]
+set signal_line [gdb_get_line_number "Signal here"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if { ![runto_main] } {
+	return -1
+    }
+
+    return 0
+}
+
+# Run a test of GDB's conditional breakpoints, where the conditions include
+# inferior function calls.  While the inferior function call is executing
+# another thread will hit a breakpoint (when OTHER_THREAD_SIGNAL is false),
+# or receive a signal (when OTHER_THREAD_SIGNAL is true).  GDB should report
+# the conditional breakpoint first (if the condition is true), and then
+# report the second thread event once the inferior is continued again.
+#
+# When STOP_AT_COND is true then the conditional breakpoint will have a
+# condition that evaluates to true (and the GDB will stop at the
+# breakpoint), otherwise, the condition will evaluate to false (and GDB will
+# not stop at the breakpoint).
+proc run_condition_test { stop_at_cond other_thread_signal \
+			      target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint.
+    if { $stop_at_cond } {
+	set cond_func "condition_true_func"
+    } else {
+	set cond_func "condition_false_func"
+    }
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (${cond_func} ())"
+    set cond_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			"get number for conditional breakpoint"]
+
+    if { $other_thread_signal } {
+	# Arrange for the other thread to raise a signal while GDB is
+	# evaluating the breakpoint condition.
+	gdb_test_no_output "set raise_signal = 1"
+    } else {
+	# And a breakpoint that will be hit by another thread only once the
+	# breakpoint condition starts to be evaluated.
+	gdb_breakpoint "${::srcfile}:${::other_bp_line}"
+	set other_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			      "get number for other breakpoint"]
+    }
+
+    # A final breakpoint once the test has completed.
+    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
+    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			  "get number for final breakpoint"]
+
+    if { $stop_at_cond } {
+	# Continue.  The first breakpoint we hit should be the conditional
+	# breakpoint.  The other thread will have hit its breakpoint, but
+	# that will have been deferred until the conditional breakpoint is
+	# reported.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${cond_bp_num}, worker_func \[^\r\n\]+:${::cond_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+First thread breakpoint\[^\r\n\]+"] \
+	    "hit the conditional breakpoint"
+    }
+
+    if { $other_thread_signal } {
+	# Now continue again, the other thread will now report that it
+	# received a signal.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" received signal SIGSEGV, Segmentation fault\\." \
+		 "\\\[Switching to Thread \[^\r\n\]+\\\]" \
+		 "${::hex} in worker_func \[^\r\n\]+:${::signal_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Signal here\[^\r\n\]+"] \
+	    "received signal in other thread"
+    } else {
+	# Now continue again, the other thread will now report its
+	# breakpoint.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${other_bp_num}, worker_func \[^\r\n\]+:${::other_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Other thread breakpoint\[^\r\n\]+"] \
+	    "hit the breakpoint in other thread"
+
+	# Run to the stop marker.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${final_bp_num}, stop_marker \[^\r\n\]+:${::final_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Final breakpoint here\[^\r\n\]+"] \
+	    "hit the final breakpoint"
+    }
+
+    gdb_exit
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	foreach_with_prefix other_thread_signal { true false } {
+	    foreach_with_prefix stop_at_cond { true false } {
+		run_condition_test $stop_at_cond $other_thread_signal \
+		    $target_async $target_non_stop
+	    }
+	}
+    }
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
new file mode 100644
index 00000000000..9d746d8be49
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
@@ -0,0 +1,89 @@
+/* Copyright 2022-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 <pthread.h>
+#include <unistd.h>
+
+#define NUM_THREADS 3
+
+int
+is_matching_tid (int *tid_ptr, int tid_value)
+{
+  return *tid_ptr == tid_value;
+}
+
+int
+return_true ()
+{
+  return 1;
+}
+
+int
+return_false ()
+{
+  return 0;
+}
+
+int
+function_that_segfaults ()
+{
+  int *p = 0;
+  *p = 1;	/* Segfault happens here.   */
+}
+
+int
+function_with_breakpoint ()
+{
+  return 1;	/* Nested breakpoint.  */
+}
+
+void *
+worker_func (void *arg)
+{
+  int a = 42;	/* Breakpoint here.  */
+}
+
+void
+stop_marker ()
+{
+  int b = 99;	/* Stop marker.  */
+}
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+
+  alarm (300);
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      void *retval;
+      pthread_join (threads[i], &retval);
+    }
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
new file mode 100644
index 00000000000..37e1b64d9a4
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
@@ -0,0 +1,235 @@
+# Copyright 2022-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/>.
+
+# Some simple tests of inferior function calls from breakpoint
+# conditions, in multi-threaded inferiors.
+#
+# This test sets up a multi-threaded inferior, and places a breakpoint
+# at a location that many of the threads will reach.  We repeat the
+# test with different conditions, sometimes a single thread should
+# stop at the breakpoint, sometimes multiple threads should stop, and
+# sometime no threads should stop.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] == -1 } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "Breakpoint here"]
+set stop_bp_line [gdb_get_line_number "Stop marker"]
+set nested_bp_line [gdb_get_line_number "Nested breakpoint"]
+set segv_line [gdb_get_line_number "Segfault happens here"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if { ![runto_main] } {
+	return -1
+    }
+
+    return 0
+}
+
+# Run a test of GDB's conditional breakpoints, where the conditions include
+# inferior function calls.
+#
+# CONDITION is the expression to be used as the breakpoint condition.
+#
+# N_EXPECTED_HITS is the number of threads that we expect to stop due to
+# CONDITON.
+#
+# MESSAGE is used as a test name prefix.
+proc run_condition_test { message n_expected_hits condition \
+			      target_async target_non_stop } {
+    with_test_prefix $message {
+
+	if { [start_gdb_and_runto_main $target_async \
+		  $target_non_stop] == -1 } {
+	    return
+	}
+
+	# Use this convenience variable to track how often the
+	# breakpoint condition has been evaluated.  This should be
+	# once per thread.
+	gdb_test "set \$n_cond_eval = 0"
+
+	# Setup the conditional breakpoint.
+	gdb_breakpoint \
+	    "${::srcfile}:${::cond_bp_line} if ((++\$n_cond_eval) && (${condition}))"
+
+	# And a breakpoint that we hit when the test is over, this one is
+	# not conditional.  Only the main thread gets here once all the
+	# other threads have finished.
+	gdb_breakpoint "${::srcfile}:${::stop_bp_line}"
+
+	# The number of times we stop at the conditional breakpoint.
+	set n_hit_condition 0
+
+	# Now keep 'continue'-ing GDB until all the threads have finished
+	# and we reach the stop_marker breakpoint.
+	gdb_test_multiple "continue" "spot all breakpoint hits" {
+	    -re " worker_func \[^\r\n\]+${::srcfile}:${::cond_bp_line}\r\n${::decimal}\\s+\[^\r\n\]+Breakpoint here\[^\r\n\]+\r\n${::gdb_prompt} $" {
+		incr n_hit_condition
+		send_gdb "continue\n"
+		exp_continue
+	    }
+
+	    -re " stop_marker \[^\r\n\]+${::srcfile}:${::stop_bp_line}\r\n${::decimal}\\s+\[^\r\n\]+Stop marker\[^\r\n\]+\r\n${::gdb_prompt} $" {
+		pass $gdb_test_name
+	    }
+	}
+
+	gdb_assert { $n_hit_condition == $n_expected_hits } \
+	    "stopped at breakpoint the expected number of times"
+
+	# Ensure the breakpoint condition was evaluated once per thread.
+	gdb_test "print \$n_cond_eval" "= 3" \
+	    "condition was evaluated in each thread"
+    }
+}
+
+# Check that after handling a conditional breakpoint (where the condition
+# includes an inferior call), it is still possible to kill the running
+# inferior, and then restart the inferior.
+#
+# At once point doing this would result in GDB giving an assertion error.
+proc_with_prefix run_kill_and_restart_test { target_async target_non_stop } {
+    # This test relies on the 'start' command, which is not possible with
+    # the plain 'remote' target.
+    if { [target_info gdb_protocol] == "remote" } {
+	return
+    }
+
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint.
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 1))"
+    gdb_continue_to_breakpoint "worker_func"
+
+    # Now kill the program being debugged.
+    gdb_test "kill" "" "kill process" \
+	"Kill the program being debugged.*y or n. $" "y"
+
+    # Check we can restart the inferior.  At one point this would trigger an
+    # assertion.
+    gdb_test "start" ".*"
+}
+
+# Create a conditional breakpoint which includes a call to a function that
+# segfaults.  Run GDB and check what happens when the inferior segfaults
+# during the inferior call.
+proc_with_prefix run_bp_cond_segfaults { target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # This test relies on the inferior segfaulting when trying to
+    # access address zero.
+    if { [is_address_zero_readable] } {
+	return
+    }
+
+    # Setup the conditional breakpoint, include a call to
+    # 'function_that_segfaults', which triggers the segfault.
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 0) && function_that_segfaults ())"
+    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of conditional breakpoint"]
+
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     ".*" \
+	     "Thread ${::decimal} \"infcall-from-bp\" received signal SIGSEGV, Segmentation fault\\." \
+	     "${::hex} in function_that_segfaults \\(\\) at \[^\r\n\]+:${::segv_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Segfault happens here\[^\r\n\]+" \
+	     "Error in testing condition for breakpoint ${bp_1_num}:" \
+	     "The program being debugged was signaled while in a function called from GDB\\." \
+	     "GDB remains in the frame where the signal was received\\." \
+	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(function_that_segfaults\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+}
+
+# Create a conditional breakpoint which includes a call to a function that
+# itself has a breakpoint set within it.  Run GDB and check what happens
+# when GDB hits the nested breakpoint.
+proc_with_prefix run_bp_cond_hits_breakpoint { target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint, include a call to
+    # 'function_with_breakpoint' in which we will shortly place a
+    # breakpoint.
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 0) && function_with_breakpoint ())"
+    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of conditional breakpoint"]
+
+    gdb_breakpoint "${::srcfile}:${::nested_bp_line}"
+    set bp_2_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of nested breakpoint"]
+
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     ".*" \
+	     "Thread ${::decimal} \"infcall-from-bp\" hit Breakpoint ${bp_2_num}, function_with_breakpoint \\(\\) at \[^\r\n\]+:${::nested_bp_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Nested breakpoint\[^\r\n\]+" \
+	     "Error in testing condition for breakpoint ${bp_1_num}:" \
+	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(function_with_breakpoint\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	run_condition_test "exactly one thread is hit" \
+	    1 "is_matching_tid (arg, 1)" \
+	    $target_async $target_non_stop
+	run_condition_test "exactly two threads are hit" \
+	    2 "(is_matching_tid (arg, 0) || is_matching_tid (arg, 2))" \
+	    $target_async $target_non_stop
+	run_condition_test "all three threads are hit" \
+	    3 "return_true ()" \
+	    $target_async $target_non_stop
+	run_condition_test "no thread is hit" \
+	    0 "return_false ()" \
+	    $target_async $target_non_stop
+
+	run_kill_and_restart_test $target_async $target_non_stop
+	run_bp_cond_segfaults $target_async $target_non_stop
+	run_bp_cond_hits_breakpoint $target_async $target_non_stop
+    }
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
new file mode 100644
index 00000000000..835c72f03cf
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
@@ -0,0 +1,139 @@
+/* Copyright 2022-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 <pthread.h>
+#include <unistd.h>
+#include <semaphore.h>
+#include <stdlib.h>
+
+#define NUM_THREADS 5
+
+/* Semaphores, used to track when threads have started, and to control
+   when the threads finish.  */
+sem_t startup_semaphore;
+sem_t finish_semaphore;
+
+/* Mutex to control when the first worker thread hit a breakpoint
+   location.  */
+pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+
+/* Global variable to poke, just so threads have something to do.  */
+volatile int global_var = 0;
+
+int
+return_true ()
+{
+  return 1;
+}
+
+int
+return_false ()
+{
+  return 0;
+}
+
+void *
+worker_func (void *arg)
+{
+  int tid = *((int *) arg);
+
+  switch (tid)
+    {
+    case 0:
+      /* Wait for MUTEX to become available, then pass through the
+	 conditional breakpoint location.  */
+      if (pthread_mutex_lock (&mutex) != 0)
+	abort ();
+      global_var = 99;	/* Conditional breakpoint here.  */
+      if (pthread_mutex_unlock (&mutex) != 0)
+	abort ();
+      break;
+
+    default:
+      /* Notify the main thread that the thread has started, then wait for
+	 the main thread to tell us to finish.  */
+      sem_post (&startup_semaphore);
+      if (sem_wait (&finish_semaphore) != 0)
+	abort ();
+      break;
+    }
+}
+
+void
+stop_marker ()
+{
+  global_var = 99;	/* Stop marker.  */
+}
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+  void *retval;
+
+  /* An alarm, just in case the thread deadlocks.  */
+  alarm (300);
+
+  /* Semaphore initialization.  */
+  if (sem_init (&startup_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&finish_semaphore, 0, 0) != 0)
+    abort ();
+
+  /* Lock MUTEX, this prevents the first worker thread from rushing ahead.  */
+  if (pthread_mutex_lock (&mutex) != 0)
+    abort ();
+
+  /* Worker thread creation.  */
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  /* Wait for every thread (other than the first) to tell us it has started
+     up.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    {
+      if (sem_wait (&startup_semaphore) != 0)
+	abort ();
+    }
+
+  /* Unlock the first thread so it can proceed.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  /* Wait for the first thread only.  */
+  pthread_join (threads[0], &retval);
+
+  /* Now post FINISH_SEMAPHORE to allow all the other threads to finish.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    sem_post (&finish_semaphore);
+
+  /* Now wait for the remaining threads to complete.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    pthread_join (threads[i], &retval);
+
+  /* Semaphore cleanup.  */
+  sem_destroy (&finish_semaphore);
+  sem_destroy (&startup_semaphore);
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
new file mode 100644
index 00000000000..787dee3aa8e
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
@@ -0,0 +1,117 @@
+# Copyright 2022-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 reprocuces bug gdb/28942, performing an inferior function
+# call from a breakpoint condition in a multi-threaded inferior.
+#
+# The important part of this test is that, when the conditional
+# breakpoint is hit, and the condition (which includes an inferior
+# function call) is evaluated, the other threads are running.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] == -1 } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "Conditional breakpoint here"]
+set final_bp_line [gdb_get_line_number "Stop marker"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if { ![runto_main] } {
+	return -1
+    }
+
+    return 0
+}
+
+# Run a test of GDB's conditional breakpoints, where the conditions include
+# inferior function calls.
+#
+# TARGET_ASYNC and TARGET_NON_STOP are used when starting up GDB.
+#
+# When STOP_AT_COND is true the breakpoint condtion will evaluate to
+# true, and GDB will stop at the breakpoint.  Otherwise, the
+# breakpoint condition will evaluate to false and GDB will not stop at
+# the breakpoint.
+proc run_condition_test { stop_at_cond \
+			      target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint.
+    if { $stop_at_cond } {
+	set cond_func "return_true"
+    } else {
+	set cond_func "return_false"
+    }
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (${cond_func} ())"
+    set cond_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			"get number for conditional breakpoint"]
+
+    # And a breakpoint that we hit when the test is over, this one is
+    # not conditional.
+    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
+    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			  "get number for final breakpoint"]
+
+    if { $stop_at_cond } {
+	# Continue.  The first breakpoint we hit should be the conditional
+	# breakpoint.  The other thread will have hit its breakpoint, but
+	# that will have been deferred until the conditional breakpoint is
+	# reported.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${cond_bp_num}, worker_func \[^\r\n\]+:${::cond_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Conditional breakpoint here\[^\r\n\]+"] \
+	    "hit the conditional breakpoint"
+    }
+
+    # Run to the stop marker.
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     ".*" \
+	     "" \
+	     "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${final_bp_num}, stop_marker \[^\r\n\]+:${::final_bp_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Stop marker\[^\r\n\]+"] \
+	"hit the final breakpoint"
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	foreach_with_prefix stop_at_cond { true false } {
+	    run_condition_test $stop_at_cond \
+		$target_async $target_non_stop
+	}
+    }
+}
-- 
2.25.4


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

* [PATCHv5 08/11] gdb: add timeouts for inferior function calls
  2023-03-16 17:36       ` [PATCHv5 00/11] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                           ` (6 preceding siblings ...)
  2023-03-16 17:37         ` [PATCHv5 07/11] gdb: fix b/p conditions with infcalls in multi-threaded inferiors Andrew Burgess
@ 2023-03-16 17:37         ` Andrew Burgess
  2023-03-16 17:37         ` [PATCHv5 09/11] gdb/remote: avoid SIGINT after calling remote_target::stop Andrew Burgess
                           ` (3 subsequent siblings)
  11 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-03-16 17:37 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Eli already approved the docs part:
  https://sourceware.org/pipermail/gdb-patches/2023-January/196462.html

---

In the previous commits I have been working on improving inferior
function call support.  One thing that worries me about using inferior
function calls from a conditional breakpoint is: what happens if the
inferior function call fails?

If the failure is obvious, e.g. the thread performing the call
crashes, or hits a breakpoint, then this case is already well handled,
and the error is reported to the user.

But what if the thread performing the inferior call just deadlocks?
If the user made the call from a 'print' or 'call' command, then the
user might have some expectation of when the function call should
complete, and, when this time limit is exceeded, the user
will (hopefully) interrupt GDB and regain control of the debug
session.

But, when the inferior function call is from a breakpoint condition it
is much harder to understand that GDB is deadlocked within an inferior
call.  Maybe the breakpoint hasn't been hit yet?  Or maybe the
condition was always false?  Or maybe GDB is deadlocked in an inferior
call?  The only way to know for sure is to periodically interrupt GDB,
check on all the threads, and then continue.

Additionally, the focus of the previous commit was inferior function
calls, from a conditional breakpoint, in a multi-threaded inferior.
This opens up a whole new set of potential failure conditions.  For
example, what if the function called relies on interaction with some
other thread, and the other thread crashes?  Or hits a breakpoint?
Given how inferior function calls work (in a synchronous manner), a
stop event in some other thread is going to be ignored while the
inferior function call is being executed as part of a breakpoint
condition, and this means that GDB could get stuck waiting for the
original condition thread, which will now never complete.

In this commit I propose a solution to this problem.  A timeout.  For
targets that support async-mode we can install an event-loop timer
before starting the inferior function call.  When the timer expires we
will stop the thread performing the inferior function call.  With this
mechanism in place a user can be sure that any inferior call they make
will either complete, or timeout eventually.

Adding a timer like this is obviously a change in behaviour for the
more common 'call' and 'print' uses of inferior function calls, so, in
this patch, I propose having two different timers.  One I call the
'direct-call-timeout', which is used for 'call' and 'print' commands.
This timeout is by default set to unlimited, which, not surprisingly,
means there is no timeout in place.

A second timer, which I've called 'indirect-call-timeout', is used for
inferior function calls from breakpoint conditions.  This timeout has
a default value of 30 seconds.  This is a reasonably long time to
wait, and hopefully should be enough in most cases to allow the
inferior call to complete.  An inferior call that takes more than 30
seconds, which is installed on a breakpoint condition is really going
to slow down the debug session, so hopefully this is not a common use
case.

The user is, of course, free to reduce, or increase the timeout value,
and can always use Ctrl-c to interrupt an inferior function call, but
this timeout will ensure that GDB will stop at some point.

The new commands added by this commit are:

  set direct-call-timeout SECONDS
  show direct-call-timeout
  set indirect-call-timeout SECONDS
  show indirect-call-timeout

These new timeouts do depend on async-mode, so, if async-mode is
disabled (maint set target-async off), or not supported (e.g. target
sim), then the timeout is treated as unlimited (that is, no timeout is
set).

For targets that "fake" non-async mode, e.g. Linux native, where
non-async mode is really just async mode, but then we park the target
in a sissuspend, we could easily fix things so that the timeouts still
work, however, for targets that really are not async aware, like the
simulator, fixing things so that timeouts work correctly would be a
much bigger task - that effort would be better spent just making the
target async-aware.  And so, I'm happy for now that this feature will
only work on async targets.

The two new show commands will display slightly different text if the
current target is a non-async target, which should allow users to
understand what's going on.

There's a somewhat random test adjustment needed in gdb.base/help.exp,
the test uses a regexp with the apropos command, and expects to find a
single result.  Turns out the new settings I added also matched the
regexp, which broke the test.  I've updated the regexp a little to
exclude my new settings.

In infcall.c you'll notice the thread_info::stop_requested flag being
set when a timeout occurs.  This flag setting is not required as part
of this commit, but will be needed in a later commit.  However, it
seemed like setting this flag fitted better with this commit, which is
why the change is added here.
---
 gdb/NEWS                                      |  18 ++
 gdb/doc/gdb.texinfo                           |  66 ++++++
 gdb/infcall.c                                 | 221 +++++++++++++++++-
 gdb/testsuite/gdb.base/help.exp               |   2 +-
 gdb/testsuite/gdb.base/infcall-timeout.c      |  36 +++
 gdb/testsuite/gdb.base/infcall-timeout.exp    |  82 +++++++
 .../infcall-from-bp-cond-timeout.c            | 169 ++++++++++++++
 .../infcall-from-bp-cond-timeout.exp          | 156 +++++++++++++
 8 files changed, 745 insertions(+), 5 deletions(-)
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.c
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp

diff --git a/gdb/NEWS b/gdb/NEWS
index cc262f1f8a6..77d6bde71cd 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -91,6 +91,24 @@ show always-read-ctf
    $2 = 1
    (gdb) break func if $_shell("some command") == 0
 
+set direct-call-timeout SECONDS
+show direct-call-timeout
+set indirect-call-timeout SECONDS
+show indirect-call-timeout
+  These new settings can be used to limit how long GDB will wait for
+  an inferior function call to complete.  The direct timeout is used
+  for inferior function calls from e.g. 'call' and 'print' commands,
+  while the indirect timeout is used for inferior function calls from
+  within a conditional breakpoint expression.
+
+  The default for the direct timeout is unlimited, while the default
+  for the indirect timeout is 30 seconds.
+
+  These timeouts will only have an effect for targets that are
+  operating in async mode.  For non-async targets the timeouts are
+  ignored, GDB will wait indefinitely for an inferior function to
+  complete, unless interrupted by the user using Ctrl-C.
+
 * MI changes
 
 ** mi now reports 'no-history' as a stop reason when hitting the end of the
diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index 6c811b8be2e..694ac720403 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -20879,6 +20879,72 @@
 @code{step}, etc).  In this case, when the inferior finally returns to
 the dummy-frame, @value{GDBN} will once again halt the inferior.
 
+On targets that support asynchronous execution (@pxref{Background
+Execution}) @value{GDBN} can place a timeout on any functions called
+from @value{GDBN}.  If the timeout expires and the function call is
+still ongoing, then @value{GDBN} will interrupt the program.
+
+For targets that don't support asynchronous execution
+(@pxref{Background Execution}) then timeouts for functions called from
+@value{GDBN} are not supported, the timeout settings described below
+will be treated as @code{unlimited}, meaning @value{GDBN} will wait
+indefinitely for function call to complete, unless interrupted by the
+user using @kbd{Ctrl-C}.
+
+@table @code
+@item set direct-call-timeout @var{seconds}
+@kindex set direct-call-timeout
+@cindex timeout for called functions
+Set the timeout used when calling functions in the program to
+@var{seconds}, which should be an integer greater than zero, or the
+special value @code{unlimited}, which indicates no timeout should be
+used.  The default for this setting is @code{unlimited}.
+
+This setting is used when the user calls a function directly from the
+command prompt, for example with a @code{call} or @code{print}
+command.
+
+This setting only works for targets that support asynchronous
+execution (@pxref{Background Execution}), for any other target the
+setting is treated as @code{unlimited}.
+
+@item show direct-call-timeout
+@kindex show direct-call-timeout
+@cindex timeout for called functions
+Show the timeout used when calling functions in the program with a
+@code{call} or @code{print} command.
+@end table
+
+It is also possible to call functions within the program from the
+condition of a conditional breakpoint (@pxref{Conditions, ,Break
+Conditions}).  A different setting controls the timeout used for
+function calls made from a breakpoint condition.
+
+@table @code
+@item set indirect-call-timeout @var{seconds}
+@kindex set indirect-call-timeout
+@cindex timeout for called functions
+Set the timeout used when calling functions in the program from a
+breakpoint or watchpoint condition to @var{seconds}, which should be
+an integer greater than zero, or the special value @code{unlimited},
+which indicates no timeout should be used.  The default for this
+setting is @code{30} seconds.
+
+This setting only works for targets that support asynchronous
+execution (@pxref{Background Execution}), for any other target the
+setting is treated as @code{unlimited}.
+
+If a function called from a breakpoint or watchpoint condition times
+out, then @value{GDBN} will stop at the point where the timeout
+occurred.  The breakpoint condition evaluation will be abandoned.
+
+@item show indirect-call-timeout
+@kindex show indirect-call-timeout
+@cindex timeout for called functions
+Show the timeout used when calling functions in the program from a
+breakpoint or watchpoint condition.
+@end table
+
 @subsection Calling functions with no debug info
 
 @cindex no debug info functions
diff --git a/gdb/infcall.c b/gdb/infcall.c
index 4fb8ab07db0..bb57faf700f 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -95,6 +95,53 @@ show_may_call_functions_p (struct ui_file *file, int from_tty,
 	      value);
 }
 
+/* A timeout (in seconds) for direct inferior calls.  A direct inferior
+   call is one the user triggers from the prompt, e.g. with a 'call' or
+   'print' command.  Compare with the definition of indirect calls below.  */
+
+static unsigned int direct_call_timeout = UINT_MAX;
+
+/* Implement 'show direct-call-timeout'.  */
+
+static void
+show_direct_call_timeout (struct ui_file *file, int from_tty,
+			  struct cmd_list_element *c, const char *value)
+{
+  if (target_has_execution () && !target_can_async_p ())
+    gdb_printf (file, _("Current target does not support async mode, timeout "
+			"for direct inferior calls is \"unlimited\".\n"));
+  else if (direct_call_timeout == UINT_MAX)
+    gdb_printf (file, _("Timeout for direct inferior function calls "
+			"is \"unlimited\".\n"));
+  else
+    gdb_printf (file, _("Timeout for direct inferior function calls "
+			"is \"%s seconds\".\n"), value);
+}
+
+/* A timeout (in seconds) for indirect inferior calls.  An indirect inferior
+   call is one that originates from within GDB, for example, when
+   evaluating an expression for a conditional breakpoint.  Compare with
+   the definition of direct calls above.  */
+
+static unsigned int indirect_call_timeout = 30;
+
+/* Implement 'show indirect-call-timeout'.  */
+
+static void
+show_indirect_call_timeout (struct ui_file *file, int from_tty,
+			  struct cmd_list_element *c, const char *value)
+{
+  if (target_has_execution () && !target_can_async_p ())
+    gdb_printf (file, _("Current target does not support async mode, timeout "
+			"for indirect inferior calls is \"unlimited\".\n"));
+  else if (indirect_call_timeout == UINT_MAX)
+    gdb_printf (file, _("Timeout for indirect inferior function calls "
+			"is \"unlimited\".\n"));
+  else
+    gdb_printf (file, _("Timeout for indirect inferior function calls "
+			"is \"%s seconds\".\n"), value);
+}
+
 /* How you should pass arguments to a function depends on whether it
    was defined in K&R style or prototype style.  If you define a
    function using the K&R syntax that takes a `float' argument, then
@@ -589,6 +636,86 @@ call_thread_fsm::should_notify_stop ()
   return true;
 }
 
+/* A class to control creation of a timer that will interrupt a thread
+   during an inferior call.  */
+struct infcall_timer_controller
+{
+  /* Setup an event-loop timer that will interrupt PTID if the inferior
+     call takes too long.  DIRECT_CALL_P is true when this inferior call is
+     a result of the user using a 'print' or 'call' command, and false when
+     this inferior call is a result of e.g. a conditional breakpoint
+     expression, this is used to select which timeout to use.  */
+  infcall_timer_controller (thread_info *thr, bool direct_call_p)
+    : m_thread (thr)
+  {
+    unsigned int timeout
+      = direct_call_p ? direct_call_timeout : indirect_call_timeout;
+    if (timeout < UINT_MAX && target_can_async_p ())
+      {
+	int ms = timeout * 1000;
+	int id = create_timer (ms, infcall_timer_controller::timed_out, this);
+	m_timer_id.emplace (id);
+	infcall_debug_printf ("Setting up infcall timeout timer for "
+			      "ptid %s: %d milliseconds",
+			      m_thread->ptid.to_string ().c_str (), ms);
+      }
+  }
+
+  /* Destructor.  Ensure that the timer is removed from the event loop.  */
+  ~infcall_timer_controller ()
+  {
+    /* If the timer has already triggered, then it will have already been
+       deleted from the event loop.  If the timer has not triggered, then
+       delete it now.  */
+    if (m_timer_id.has_value () && !m_triggered)
+      delete_timer (*m_timer_id);
+
+    /* Just for clarity, discard the timer id now.  */
+    m_timer_id.reset ();
+  }
+
+  /* Return true if there was a timer in place, and the timer triggered,
+     otherwise, return false.  */
+  bool triggered_p ()
+  {
+    gdb_assert (!m_triggered || m_timer_id.has_value ());
+    return m_triggered;
+  }
+
+private:
+  /* The thread we should interrupt.  */
+  thread_info *m_thread;
+
+  /* Set true when the timer is triggered.  */
+  bool m_triggered = false;
+
+  /* Given a value when a timer is in place.  */
+  gdb::optional<int> m_timer_id;
+
+  /* Callback for the timer, forwards to ::trigger below.  */
+  static void
+  timed_out (gdb_client_data context)
+  {
+    infcall_timer_controller *ctrl
+      = static_cast<infcall_timer_controller *> (context);
+    ctrl->trigger ();
+  }
+
+  /* Called when the timer goes off.  Stop thread m_thread.  */
+  void
+  trigger ()
+  {
+    m_triggered = true;
+
+    scoped_disable_commit_resumed disable_commit_resumed ("infcall timeout");
+
+    infcall_debug_printf ("Stopping thread %s",
+			  m_thread->ptid.to_string ().c_str ());
+    target_stop (m_thread->ptid);
+    m_thread->stop_requested = true;
+  }
+};
+
 /* Subroutine of call_function_by_hand to simplify it.
    Start up the inferior and wait for it to stop.
    Return the exception if there's an error, or an exception with
@@ -599,13 +726,15 @@ call_thread_fsm::should_notify_stop ()
 
 static struct gdb_exception
 run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
-		   struct thread_info *call_thread, CORE_ADDR real_pc)
+		   struct thread_info *call_thread, CORE_ADDR real_pc,
+		   bool *timed_out_p)
 {
   INFCALL_SCOPED_DEBUG_ENTER_EXIT;
 
   struct gdb_exception caught_error;
   ptid_t call_thread_ptid = call_thread->ptid;
   int was_running = call_thread->state == THREAD_RUNNING;
+  *timed_out_p = false;
 
   infcall_debug_printf ("call function at %s in thread %s, was_running = %d",
 			core_addr_to_string (real_pc),
@@ -617,6 +746,16 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
   scoped_restore restore_in_infcall
     = make_scoped_restore (&call_thread->control.in_infcall, 1);
 
+  /* If the thread making the inferior call stops with a time out then the
+     stop_requested flag will be set.  However, we don't want changes to
+     this flag to leak back to our caller, we might be here to handle an
+     inferior call from a breakpoint condition, so leaving this flag set
+     would appear that the breakpoint stop was actually a requested stop,
+     which is not true, and will cause GDB to print extra messages to the
+     output.  */
+  scoped_restore restore_stop_requested
+    = make_scoped_restore (&call_thread->stop_requested, false);
+
   clear_proceed_status (0);
 
   /* Associate the FSM with the thread after clear_proceed_status
@@ -650,11 +789,23 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
       infrun_debug_show_threads ("non-exited threads after proceed for inferior-call",
 				 all_non_exited_threads ());
 
+      /* Setup a timer (if possible, and if the settings allow) to prevent
+	 the inferior call running forever.  */
+      bool direct_call_p = !call_thread->control.in_cond_eval;
+      infcall_timer_controller infcall_timer (call_thread, direct_call_p);
+
       /* Inferior function calls are always synchronous, even if the
 	 target supports asynchronous execution.  */
       wait_sync_command_done ();
 
-      infcall_debug_printf ("inferior call completed successfully");
+      /* If the timer triggered then the inferior call failed.  */
+      if (infcall_timer.triggered_p ())
+	{
+	  infcall_debug_printf ("inferior call timed out");
+	  *timed_out_p = true;
+	}
+      else
+	infcall_debug_printf ("inferior call completed successfully");
     }
   catch (gdb_exception &e)
     {
@@ -1308,6 +1459,10 @@ call_function_by_hand_dummy (struct value *function,
   scoped_restore restore_stopped_by_random_signal
     = make_scoped_restore (&stopped_by_random_signal, 0);
 
+  /* Set to true by the call to run_inferior_call below if the inferior
+     call is artificially interrupted by GDB due to taking too long.  */
+  bool timed_out_p = false;
+
   /* - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP -
      If you're looking to implement asynchronous dummy-frames, then
      just below is the place to chop this function in two..  */
@@ -1334,7 +1489,8 @@ call_function_by_hand_dummy (struct value *function,
 			      struct_addr);
     {
       std::unique_ptr<call_thread_fsm> sm_up (sm);
-      e = run_inferior_call (std::move (sm_up), call_thread.get (), real_pc);
+      e = run_inferior_call (std::move (sm_up), call_thread.get (), real_pc,
+			     &timed_out_p);
     }
 
     if (e.reason < 0)
@@ -1486,7 +1642,10 @@ When the function is done executing, GDB will silently stop."),
       std::string name = get_function_name (funaddr, name_buf,
 					    sizeof (name_buf));
 
-      if (stopped_by_random_signal)
+      /* If the inferior call timed out then it will have been interrupted
+	 by a signal, but we want to report this differently to the user,
+	 which is done later in this function.  */
+      if (stopped_by_random_signal && !timed_out_p)
 	{
 	  /* We stopped inside the FUNCTION because of a random
 	     signal.  Further execution of the FUNCTION is not
@@ -1530,6 +1689,36 @@ GDB remains in the frame where the signal was received.\n\
 To change this behavior use \"set unwindonsignal on\".\n\
 Evaluation of the expression containing the function\n\
 (%s) will be abandoned.\n\
+When the function is done executing, GDB will silently stop."),
+		     name.c_str ());
+	    }
+	}
+
+      if (timed_out_p)
+	{
+	  /* A timeout results in a signal being sent to the inferior.  */
+	  gdb_assert (stopped_by_random_signal);
+
+	  /* Indentation is weird here.  A later patch is going to move the
+	    following block into an if/else, so I'm leaving the indentation
+	    here to minimise the later patch.
+
+	    Also, the error message used below refers to 'set
+	    unwind-on-timeout' which doesn't exist yet.  This will be added
+	    in a later commit, I'm leaving this in for now to minimise the
+	    churn caused by the commit that adds unwind-on-timeout.  */
+	    {
+	      /* The user wants to stay in the frame where we stopped
+		 (default).  Discard inferior status, we're not at the same
+		 point we started at.  */
+	      discard_infcall_control_state (inf_status.release ());
+
+	      error (_("\
+The program being debugged timed out while in a function called from GDB.\n\
+GDB remains in the frame where the timeout occurred.\n\
+To change this behavior use \"set unwind-on-timeout on\".\n\
+Evaluation of the expression containing the function\n\
+(%s) will be abandoned.\n\
 When the function is done executing, GDB will silently stop."),
 		     name.c_str ());
 	    }
@@ -1643,6 +1832,30 @@ The default is to unwind the frame."),
 			   show_unwind_on_terminating_exception_p,
 			   &setlist, &showlist);
 
+  add_setshow_uinteger_cmd ("direct-call-timeout", no_class,
+			    &direct_call_timeout, _("\
+Set the timeout, for direct calls to inferior function calls."), _("\
+Show the timeout, for direct calls to inferior function calls."), _("\
+If running on a target that supports, and is running in, async mode\n\
+then this timeout is used for any inferior function calls triggered\n\
+directly from the prompt, i.e. from a 'call' or 'print' command.  The\n\
+timeout is specified in seconds."),
+			    nullptr,
+			    show_direct_call_timeout,
+			    &setlist, &showlist);
+
+  add_setshow_uinteger_cmd ("indirect-call-timeout", no_class,
+			    &indirect_call_timeout, _("\
+Set the timeout, for indirect calls to inferior function calls."), _("\
+Show the timeout, for indirect calls to inferior function calls."), _("\
+If running on a target that supports, and is running in, async mode\n\
+then this timeout is used for any inferior function calls triggered\n\
+indirectly, i.e. being made as part of a breakpoint, or watchpoint,\n\
+condition expression.  The timeout is specified in seconds."),
+			    nullptr,
+			    show_indirect_call_timeout,
+			    &setlist, &showlist);
+
   add_setshow_boolean_cmd
     ("infcall", class_maintenance, &debug_infcall,
      _("Set inferior call debugging."),
diff --git a/gdb/testsuite/gdb.base/help.exp b/gdb/testsuite/gdb.base/help.exp
index 87919a819ab..504bf90cc15 100644
--- a/gdb/testsuite/gdb.base/help.exp
+++ b/gdb/testsuite/gdb.base/help.exp
@@ -121,7 +121,7 @@ gdb_test "help info bogus-gdb-command" "Undefined info command: \"bogus-gdb-comm
 gdb_test "help gotcha" "Undefined command: \"gotcha\"\.  Try \"help\"\."
 
 # Test apropos regex.
-gdb_test "apropos \\\(print\[\^\[ bsiedf\\\".-\]\\\)" "handle -- Specify how to handle signals\."
+gdb_test "apropos \\\(print\[\^\[ bsiedf\\\"'.-\]\\\)" "handle -- Specify how to handle signals\."
 # Test apropos >1 word string.
 gdb_test "apropos handle signal" "handle -- Specify how to handle signals\."
 # Test apropos apropos.
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.c b/gdb/testsuite/gdb.base/infcall-timeout.c
new file mode 100644
index 00000000000..12774ca2599
--- /dev/null
+++ b/gdb/testsuite/gdb.base/infcall-timeout.c
@@ -0,0 +1,36 @@
+/* Copyright 2022-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 <unistd.h>
+
+/* This function is called from GDB.  */
+int
+function_that_never_returns ()
+{
+  while (1)
+    sleep (1);
+
+  return 0;
+}
+
+int
+main ()
+{
+  alarm (300);
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.exp b/gdb/testsuite/gdb.base/infcall-timeout.exp
new file mode 100644
index 00000000000..5e9cdc2fa0e
--- /dev/null
+++ b/gdb/testsuite/gdb.base/infcall-timeout.exp
@@ -0,0 +1,82 @@
+# Copyright 2022-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/>.
+
+# Test GDB's direct-call-timeout setting, that is, ensure that if an
+# inferior function call, invoked from e.g. a 'print' command, takes
+# too long, then GDB can interrupt it, and return control to the user.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug}] == -1 } {
+    return
+}
+
+# Start GDB according to TARGET_ASYNC and TARGET_NON_STOP, then adjust
+# the direct-call-timeout, and make an inferior function call that
+# will never return.  GDB should eventually timeout and stop the
+# inferior.
+proc_with_prefix run_test { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if {![runto_main]} {
+	fail "run to main"
+	return
+    }
+
+    gdb_test_no_output "set direct-call-timeout 5"
+
+    # When non-stop mode is off we get slightly different output from GDB.
+    if { [gdb_is_remote_or_extended_remote_target] && !$target_non_stop } {
+	set stopped_line_pattern "Program received signal SIGINT, Interrupt\\."
+    } else {
+	set stopped_line_pattern "Program stopped\\."
+    }
+
+    gdb_test "print function_that_never_returns ()" \
+	[multi_line \
+	     $stopped_line_pattern \
+	     ".*" \
+	     "The program being debugged timed out while in a function called from GDB\\." \
+	     "GDB remains in the frame where the timeout occurred\\." \
+	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(function_that_never_returns\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+
+    gdb_test "bt" ".* function_that_never_returns .*<function called from gdb>.*"
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+
+    if { !$target_async } {
+	# GDB can't timeout while waiting for a thread if the target
+	# runs with async-mode turned off; once the target is running
+	# GDB is effectively blocked until the target stops for some
+	# reason.
+	continue
+    }
+
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	run_test $target_async $target_non_stop
+    }
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
new file mode 100644
index 00000000000..4da4245746e
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
@@ -0,0 +1,169 @@
+/* This testcase is part of GDB, the GNU debugger.
+
+   Copyright 2022-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 <stdio.h>
+#include <pthread.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <semaphore.h>
+
+#define NUM_THREADS 5
+
+/* Semaphores, used to track when threads have started, and to control
+   when the threads finish.  */
+sem_t startup_semaphore;
+sem_t finish_semaphore;
+sem_t thread_1_semaphore;
+sem_t thread_2_semaphore;
+
+/* Mutex to control when the first worker thread hit a breakpoint
+   location.  */
+pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+
+/* Global variable to poke, just so threads have something to do.  */
+volatile int global_var = 0;
+
+int
+condition_func ()
+{
+  /* Let thread 2 run.  */
+  if (sem_post (&thread_2_semaphore) != 0)
+    abort ();
+
+  /* Wait for thread 2 to complete its actions.  */
+  if (sem_wait (&thread_1_semaphore) != 0)
+    abort ();
+
+  return 1;
+}
+
+void
+do_segfault ()
+{
+  volatile int *p = 0;
+  *p = 0;	/* Segfault here.  */
+}
+
+void *
+worker_func (void *arg)
+{
+  int tid = *((int *) arg);
+
+  /* Let the main thread know that this worker has started.  */
+  if (sem_post (&startup_semaphore) != 0)
+    abort ();
+
+  switch (tid)
+    {
+    case 0:
+      /* Wait for MUTEX to become available, then pass through the
+	 conditional breakpoint location.  */
+      if (pthread_mutex_lock (&mutex) != 0)
+	abort ();
+      global_var = 99;	/* Conditional breakpoint here.  */
+      if (pthread_mutex_unlock (&mutex) != 0)
+	abort ();
+      break;
+
+    case 1:
+      if (sem_wait (&thread_2_semaphore) != 0)
+	abort ();
+      do_segfault ();
+      if (sem_post (&thread_1_semaphore) != 0)
+	abort ();
+
+      /* Fall through.  */
+    default:
+      /* Wait until we are allowed to finish.  */
+      if (sem_wait (&finish_semaphore) != 0)
+	abort ();
+      break;
+    }
+}
+
+void
+stop_marker ()
+{
+  global_var = 99;	/* Stop marker.  */
+}
+
+/* The main program entry point.  */
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+  void *retval;
+
+  /* An alarm, just in case the thread deadlocks.  */
+  alarm (300);
+
+  /* Semaphore initialization.  */
+  if (sem_init (&startup_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&finish_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&thread_1_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&thread_2_semaphore, 0, 0) != 0)
+    abort ();
+
+  /* Lock MUTEX, this prevents the first worker thread from rushing ahead.  */
+  if (pthread_mutex_lock (&mutex) != 0)
+    abort ();
+
+  /* Worker thread creation.  */
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  /* Wait for every thread to start.  */
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      if (sem_wait (&startup_semaphore) != 0)
+	abort ();
+    }
+
+  /* Unlock the first thread so it can proceed.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  /* Wait for the first thread only.  */
+  pthread_join (threads[0], &retval);
+
+  /* Now post FINISH_SEMAPHORE to allow all the other threads to finish.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    sem_post (&finish_semaphore);
+
+  /* Now wait for the remaining threads to complete.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    pthread_join (threads[i], &retval);
+
+  /* Semaphore cleanup.  */
+  sem_destroy (&finish_semaphore);
+  sem_destroy (&startup_semaphore);
+  sem_destroy (&thread_1_semaphore);
+  sem_destroy (&thread_2_semaphore);
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
new file mode 100644
index 00000000000..4159288a39c
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
@@ -0,0 +1,156 @@
+# Copyright 2022-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 inferior calls executed from a breakpoint condition in
+# a multi-threaded program.
+#
+# This test has the inferior function call timeout, and checks how GDB
+# handles this situation.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "Conditional breakpoint here"]
+set final_bp_line [gdb_get_line_number "Stop marker"]
+set segfault_line [gdb_get_line_number "Segfault here"]
+
+# Setup GDB based on TARGET_ASYNC and TARGET_NON_STOP.  Setup some
+# breakpoints in the inferior, one of which has an inferior call
+# within its condition.
+#
+# Continue GDB, the breakpoint with inferior call will be hit, but the
+# inferior call will never return.  We expect GDB to timeout.
+#
+# The reason that the inferior call never completes is that a second
+# thread, on which the inferior call relies, either hits a breakpoint
+# (when OTHER_THREAD_BP is true), or crashes (when OTHER_THREAD_BP is
+# false).
+proc run_test { target_async target_non_stop other_thread_bp } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if {![runto_main]} {
+	fail "run to main"
+	return
+    }
+
+    # The default timeout for indirect inferior calls (e.g. inferior
+    # calls for conditional breakpoint expressions) is pretty high.
+    # We don't want the test to take too long, so reduce this.
+    #
+    # However, the test relies on a second thread hitting some event
+    # (either a breakpoint or signal) before this timeout expires.
+    #
+    # There is a chance that on a really slow system this might not
+    # happen, in which case the test might fail.
+    #
+    # However, we still allocate 5 seconds, which feels like it should
+    # be enough time in most cases, but maybe we need to do something
+    # smarter here?  Possibly we could have some initial run where the
+    # inferior doesn't timeout, but does perform the same interaction
+    # between threads, we could time that, and use that as the basis
+    # for this timeout.  For now though, we just hope 5 seconds is
+    # enough.
+    gdb_test_no_output "set indirect-call-timeout 5"
+
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (condition_func ())"
+    set bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		    "get number for conditional breakpoint"]
+
+    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
+    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			  "get number for final breakpoint"]
+
+    # The thread performing an inferior call relies on a second
+    # thread.  The second thread will segfault unless it hits a
+    # breakpoint first.  In either case the initial thread will not
+    # complete its inferior call.
+    if { $other_thread_bp } {
+	gdb_breakpoint "${::srcfile}:${::segfault_line}"
+	set segfault_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+				 "get number for segfault breakpoint"]
+    }
+
+    # When non-stop mode is off we get slightly different output from GDB.
+    if { [gdb_is_remote_or_extended_remote_target] && !$target_non_stop} {
+	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" received signal SIGINT, Interrupt\\."
+    } else {
+	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\."
+    }
+
+    gdb_test "continue" \
+	[multi_line \
+	     $stopped_line_pattern \
+	     ".*" \
+	     "Error in testing condition for breakpoint ${bp_num}:" \
+	     "The program being debugged timed out while in a function called from GDB\\." \
+	     "GDB remains in the frame where the timeout occurred\\." \
+	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(condition_func\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."] \
+	"expected timeout waiting for inferior call to complete"
+
+    # Remember that other thread that either crashed (with a segfault)
+    # or hit a breakpoint?  Now that the inferior call has timed out,
+    # if we try to resume then we should see the pending event from
+    # that other thread.
+    if { $other_thread_bp } {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${segfault_bp_num}, do_segfault \[^\r\n\]+:${::segfault_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"] \
+	    "hit the segfault breakpoint"
+    } else {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "Thread ${::decimal} \"infcall-from-bp\" received signal SIGSEGV, Segmentation fault\\." \
+		 "\\\[Switching to Thread \[^\r\n\]+\\\]" \
+		 "${::hex} in do_segfault \\(\\) at \[^\r\n\]+:${::segfault_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"] \
+	    "hit the segfault"
+    }
+}
+
+foreach_with_prefix target_async {"on" "off" } {
+
+    if { !$target_async } {
+	# GDB can't timeout while waiting for a thread if the target
+	# runs with async-mode turned off; once the target is running
+	# GDB is effectively blocked until the target stops for some
+	# reason.
+	continue
+    }
+
+    foreach_with_prefix target_non_stop {"off" "on"} {
+	foreach_with_prefix other_thread_bp { true false } {
+	    run_test $target_async $target_non_stop $other_thread_bp
+	}
+    }
+}
-- 
2.25.4


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

* [PATCHv5 09/11] gdb/remote: avoid SIGINT after calling remote_target::stop
  2023-03-16 17:36       ` [PATCHv5 00/11] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                           ` (7 preceding siblings ...)
  2023-03-16 17:37         ` [PATCHv5 08/11] gdb: add timeouts for inferior function calls Andrew Burgess
@ 2023-03-16 17:37         ` Andrew Burgess
  2023-03-16 17:37         ` [PATCHv5 10/11] gdb: introduce unwind-on-timeout setting Andrew Burgess
                           ` (2 subsequent siblings)
  11 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-03-16 17:37 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Currently, if the remote target is not running in non-stop mode, then,
when GDB calls remote_target::stop, we end up sending an interrupt
packet \x03 to the remote target.

If the user interrupts the inferior from the GDB prompt (e.g. by
typing Ctrl-c), then GDB calls remote_target::interrupt, which also
ends up sending the interrupt packet.

The problem here is that both of these mechanisms end up sending the
interrupt packet, which means, when the target stops with a SIGINT,
and this is reported back to GDB, we have no choice but to report this
to the user as a SIGINT stop event.

Now maybe this is the correct thing to do, after all the target has
been stopped with SIGINT.  However, this leads to an unfortunate
change in behaviour when comparing non-stop vs all-stop mode.

When running in non-stop mode, and remote_target::stop is called, the
target will be stopped with a vCont packet, and this stop is then
reported back to GDB as GDB_SIGNAL_0, this will cause GDB to print a
message like:

  Program stopped.

Or:

  Thread NN "binary name" stopped.

In contrast, when non-stop mode is off, we get messages like:

  Program received SIGINT, Segmentation fault.

Or:

  Thread NN "binary name" received SIGINT, Segmentation fault.

In this commit I propose making use of thread_info::stop_requested
within remote.c to know if the stop was triggered by GDB (and the
SIGINT should be hidden) or if the stop was a user interrupt, and the
SIGINT should be printed.

In remote_target::process_stop_reply if the inferior stopped with
SIGINT and the thread_info::stop_requested flag is set, then we change
the stop signal to GDB_SIGNAL_0.

Two of the tests added in the previous commit exposed this issue.  In
the previous commit the tests looked for either of the above
patterns.  In this commit I've updated these tests to only look for
the "stopped" based messages.

This commit is the reason why the previous commit took care to set the
thread_info::stop_requested flag in infcall.c.
---
 gdb/remote.c                                           | 10 ++++++++++
 gdb/testsuite/gdb.base/infcall-timeout.exp             |  9 +--------
 .../gdb.threads/infcall-from-bp-cond-timeout.exp       |  9 +--------
 3 files changed, 12 insertions(+), 16 deletions(-)

diff --git a/gdb/remote.c b/gdb/remote.c
index 526df313ea7..ea8f103a589 100644
--- a/gdb/remote.c
+++ b/gdb/remote.c
@@ -8275,6 +8275,16 @@ remote_target::process_stop_reply (struct stop_reply *stop_reply,
 	}
       else
 	{
+	  /* If this stop was actually requested by GDB then we can hide
+	     the SIGINT from the user.  */
+	  if (status->kind () == TARGET_WAITKIND_STOPPED
+	      && status->sig () == GDB_SIGNAL_INT)
+	    {
+	      thread_info *thr = find_thread_ptid (this, ptid);
+	      if (thr->stop_requested)
+		status->set_stopped (GDB_SIGNAL_0);
+	    }
+
 	  /* If the target works in all-stop mode, a stop-reply indicates that
 	     all the target's threads stopped.  */
 	  for (thread_info *tp : all_non_exited_threads (this))
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.exp b/gdb/testsuite/gdb.base/infcall-timeout.exp
index 5e9cdc2fa0e..beb488ffd1e 100644
--- a/gdb/testsuite/gdb.base/infcall-timeout.exp
+++ b/gdb/testsuite/gdb.base/infcall-timeout.exp
@@ -45,16 +45,9 @@ proc_with_prefix run_test { target_async target_non_stop } {
 
     gdb_test_no_output "set direct-call-timeout 5"
 
-    # When non-stop mode is off we get slightly different output from GDB.
-    if { [gdb_is_remote_or_extended_remote_target] && !$target_non_stop } {
-	set stopped_line_pattern "Program received signal SIGINT, Interrupt\\."
-    } else {
-	set stopped_line_pattern "Program stopped\\."
-    }
-
     gdb_test "print function_that_never_returns ()" \
 	[multi_line \
-	     $stopped_line_pattern \
+	     "Program stopped\\." \
 	     ".*" \
 	     "The program being debugged timed out while in a function called from GDB\\." \
 	     "GDB remains in the frame where the timeout occurred\\." \
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
index 4159288a39c..74f7def7dce 100644
--- a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
@@ -92,16 +92,9 @@ proc run_test { target_async target_non_stop other_thread_bp } {
 				 "get number for segfault breakpoint"]
     }
 
-    # When non-stop mode is off we get slightly different output from GDB.
-    if { [gdb_is_remote_or_extended_remote_target] && !$target_non_stop} {
-	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" received signal SIGINT, Interrupt\\."
-    } else {
-	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\."
-    }
-
     gdb_test "continue" \
 	[multi_line \
-	     $stopped_line_pattern \
+	     "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\." \
 	     ".*" \
 	     "Error in testing condition for breakpoint ${bp_num}:" \
 	     "The program being debugged timed out while in a function called from GDB\\." \
-- 
2.25.4


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

* [PATCHv5 10/11] gdb: introduce unwind-on-timeout setting
  2023-03-16 17:36       ` [PATCHv5 00/11] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                           ` (8 preceding siblings ...)
  2023-03-16 17:37         ` [PATCHv5 09/11] gdb/remote: avoid SIGINT after calling remote_target::stop Andrew Burgess
@ 2023-03-16 17:37         ` Andrew Burgess
  2023-03-16 17:37         ` [PATCHv5 11/11] gdb: rename unwindonsignal to unwind-on-signal Andrew Burgess
  2023-04-03 14:01         ` [PATCHv6 0/6] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
  11 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-03-16 17:37 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Eli already approved the docs part:
  https://sourceware.org/pipermail/gdb-patches/2023-January/195873.html

---

Now that inferior function calls can timeout (see the recent
introduction of direct-call-timeout and indirect-call-timeout), this
commit adds a new setting unwind-on-timeout.

This new setting is just like the existing unwindonsignal and
unwind-on-terminating-exception, but the new setting will cause GDB to
unwind the stack if an inferior function call times out.

The existing inferior function call timeout tests have been updated to
cover the new setting.
---
 gdb/NEWS                                      |  9 +++
 gdb/doc/gdb.texinfo                           | 25 ++++++--
 gdb/infcall.c                                 | 62 ++++++++++++++++---
 gdb/testsuite/gdb.base/infcall-timeout.exp    | 49 +++++++++++----
 .../infcall-from-bp-cond-timeout.exp          | 55 +++++++++++-----
 5 files changed, 160 insertions(+), 40 deletions(-)

diff --git a/gdb/NEWS b/gdb/NEWS
index 77d6bde71cd..0712a91421a 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -109,6 +109,15 @@ show indirect-call-timeout
   ignored, GDB will wait indefinitely for an inferior function to
   complete, unless interrupted by the user using Ctrl-C.
 
+set unwind-on-timeout on|off
+show unwind-on-timeout
+  These commands control whether GDB should unwind the stack when a
+  timeout occurs during an inferior function call.  The default is
+  off, in which case the inferior will remain in the frame where the
+  timeout occurred.  When on, GDB will unwind the stack removing the
+  dummy frame that was added for the inferior call, and restoring the
+  inferior state to how it was before the inferior call started.
+
 * MI changes
 
 ** mi now reports 'no-history' as a stop reason when hitting the end of the
diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index 694ac720403..d0f4b180e09 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -20824,6 +20824,21 @@
 Show the current setting of stack unwinding in the functions called by
 @value{GDBN}.
 
+@item set unwind-on-timeout
+@kindex set unwind-on-timeout
+@cindex unwind stack in called functions when timing out
+@cindex call dummy stack unwinding on timeout.
+Set unwinding of the stack if a function called from @value{GDBN}
+times out.  If set to @code{off} (the default), @value{GDBN} stops in
+the frame where the timeout occurred.  If set to @code{on},
+@value{GDBN} unwinds the stack it created for the call and restores
+the context to what it was before the call.
+
+@item show unwind-on-timeout
+@kindex show unwind-on-timeout
+Show whether @value{GDBN} will unwind the stack if a function called
+from @value{GDBN} times out.
+
 @item set may-call-functions
 @kindex set may-call-functions
 @cindex disabling calling functions in the program
@@ -20855,11 +20870,11 @@
 
 If a called function is interrupted for any reason, including hitting
 a breakpoint, or triggering a watchpoint, and the stack is not unwound
-due to @code{set unwind-on-terminating-exception on} or @code{set
-unwindonsignal on} (@pxref{stack unwind settings}),
-then the dummy-frame, created by @value{GDBN} to facilitate the call
-to the program function, will be visible in the backtrace, for example
-frame @code{#3} in the following backtrace:
+due to @code{set unwind-on-terminating-exception on}, @code{set
+unwind-on-timeout on}, or @code{set unwindonsignal on} (@pxref{stack
+unwind settings}), then the dummy-frame, created by @value{GDBN} to
+facilitate the call to the program function, will be visible in the
+backtrace, for example frame @code{#3} in the following backtrace:
 
 @smallexample
 (@value{GDBP}) backtrace
diff --git a/gdb/infcall.c b/gdb/infcall.c
index bb57faf700f..1f0fb4f1d59 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -217,6 +217,27 @@ show_unwind_on_terminating_exception_p (struct ui_file *file, int from_tty,
 	      value);
 }
 
+/* This boolean tells GDB what to do if an inferior function, called from
+   GDB, times out.  If true, GDB unwinds the stack and restores the context
+   to what it was before the call.  When false, GDB leaves the thread as it
+   is at the point of the timeout.
+
+   The default is to stop in the frame where the timeout occurred.  */
+
+static bool unwind_on_timeout_p = false;
+
+/* Implement 'show unwind-on-timeout'.  */
+
+static void
+show_unwind_on_timeout_p (struct ui_file *file, int from_tty,
+			  struct cmd_list_element *c, const char *value)
+{
+  gdb_printf (file,
+	      _("Unwinding of stack if a timeout occurs "
+		"while in a call dummy is %s.\n"),
+	      value);
+}
+
 /* Perform the standard coercions that are specified
    for arguments to be passed to C, Ada or Fortran functions.
 
@@ -1699,14 +1720,27 @@ When the function is done executing, GDB will silently stop."),
 	  /* A timeout results in a signal being sent to the inferior.  */
 	  gdb_assert (stopped_by_random_signal);
 
-	  /* Indentation is weird here.  A later patch is going to move the
-	    following block into an if/else, so I'm leaving the indentation
-	    here to minimise the later patch.
+	  if (unwind_on_timeout_p)
+	    {
+	      /* The user wants the context restored.  */
+
+	      /* We must get back to the frame we were before the
+		 dummy call.  */
+	      dummy_frame_pop (dummy_id, call_thread.get ());
 
-	    Also, the error message used below refers to 'set
-	    unwind-on-timeout' which doesn't exist yet.  This will be added
-	    in a later commit, I'm leaving this in for now to minimise the
-	    churn caused by the commit that adds unwind-on-timeout.  */
+	      /* We also need to restore inferior status to that before the
+		 dummy call.  */
+	      restore_infcall_control_state (inf_status.release ());
+
+	      error (_("\
+The program being debugged timed out while in a function called from GDB.\n\
+GDB has restored the context to what it was before the call.\n\
+To change this behavior use \"set unwind-on-timeout off\".\n\
+Evaluation of the expression containing the function\n\
+(%s) will be abandoned."),
+		     name.c_str ());
+	    }
+	  else
 	    {
 	      /* The user wants to stay in the frame where we stopped
 		 (default).  Discard inferior status, we're not at the same
@@ -1832,6 +1866,20 @@ The default is to unwind the frame."),
 			   show_unwind_on_terminating_exception_p,
 			   &setlist, &showlist);
 
+  add_setshow_boolean_cmd ("unwind-on-timeout", no_class,
+			   &unwind_on_timeout_p, _("\
+Set unwinding of stack if a timeout occurs while in a call dummy."), _("\
+Show unwinding of stack if a timeout occurs while in a call dummy."),
+			   _("\
+The unwind on timeout flag lets the user determine what gdb should do if\n\
+gdb times out while in a function called from gdb.  If set, gdb unwinds\n\
+the stack and restores the context to what it was before the call.  If\n\
+unset, gdb leaves the inferior in the frame where the timeout occurred.\n\
+The default is to stop in the frame where the timeout occurred."),
+			   NULL,
+			   show_unwind_on_timeout_p,
+			   &setlist, &showlist);
+
   add_setshow_uinteger_cmd ("direct-call-timeout", no_class,
 			    &direct_call_timeout, _("\
 Set the timeout, for direct calls to inferior function calls."), _("\
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.exp b/gdb/testsuite/gdb.base/infcall-timeout.exp
index beb488ffd1e..d063abc9077 100644
--- a/gdb/testsuite/gdb.base/infcall-timeout.exp
+++ b/gdb/testsuite/gdb.base/infcall-timeout.exp
@@ -28,7 +28,11 @@ if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
 # the direct-call-timeout, and make an inferior function call that
 # will never return.  GDB should eventually timeout and stop the
 # inferior.
-proc_with_prefix run_test { target_async target_non_stop } {
+#
+# When UNWIND is "off" the inferior wil be left in the frame where the
+# timeout occurs, otherwise, when UNWIND is "on", GDB should unwind
+# back to the frame where the inferior call was made.
+proc_with_prefix run_test { target_async target_non_stop unwind } {
     save_vars { ::GDBFLAGS } {
 	append ::GDBFLAGS \
 	    " -ex \"maint set target-non-stop $target_non_stop\""
@@ -44,19 +48,36 @@ proc_with_prefix run_test { target_async target_non_stop } {
     }
 
     gdb_test_no_output "set direct-call-timeout 5"
+    gdb_test_no_output "set unwind-on-timeout $unwind"
+
+    if { $unwind } {
+	gdb_test "print function_that_never_returns ()" \
+	    [multi_line \
+		 "Program stopped\\." \
+		 ".*" \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB has restored the context to what it was before the call\\." \
+		 "To change this behavior use \"set unwind-on-timeout off\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(function_that_never_returns\\) will be abandoned\\."]
 
-    gdb_test "print function_that_never_returns ()" \
-	[multi_line \
-	     "Program stopped\\." \
-	     ".*" \
-	     "The program being debugged timed out while in a function called from GDB\\." \
-	     "GDB remains in the frame where the timeout occurred\\." \
-	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
-	     "Evaluation of the expression containing the function" \
-	     "\\(function_that_never_returns\\) will be abandoned\\." \
-	     "When the function is done executing, GDB will silently stop\\."]
+	gdb_test "bt" \
+	    "#0\\s+main \\(\\).*"
+    } else {
+	gdb_test "print function_that_never_returns ()" \
+	    [multi_line \
+		 "Program stopped\\." \
+		 ".*" \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB remains in the frame where the timeout occurred\\." \
+		 "To change this behavior use \"set unwind-on-timeout on\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(function_that_never_returns\\) will be abandoned\\." \
+		 "When the function is done executing, GDB will silently stop\\."]
 
-    gdb_test "bt" ".* function_that_never_returns .*<function called from gdb>.*"
+	gdb_test "bt" \
+	    ".* function_that_never_returns .*<function called from gdb>.*"
+    }
 }
 
 foreach_with_prefix target_async { "on" "off" } {
@@ -70,6 +91,8 @@ foreach_with_prefix target_async { "on" "off" } {
     }
 
     foreach_with_prefix target_non_stop { "on" "off" } {
-	run_test $target_async $target_non_stop
+	foreach_with_prefix unwind { "on" "off" } {
+	    run_test $target_async $target_non_stop $unwind
+	}
     }
 }
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
index 74f7def7dce..f399b5420a2 100644
--- a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
@@ -41,7 +41,12 @@ set segfault_line [gdb_get_line_number "Segfault here"]
 # thread, on which the inferior call relies, either hits a breakpoint
 # (when OTHER_THREAD_BP is true), or crashes (when OTHER_THREAD_BP is
 # false).
-proc run_test { target_async target_non_stop other_thread_bp } {
+#
+# When UNWIND is "on" GDB will unwind the thread which performed the
+# inferior function call back to the state where the inferior call was
+# made (when the inferior call times out).  Otherwise, when UNWIND is
+# "off", the inferior is left in the frame where the timeout occurred.
+proc run_test { target_async target_non_stop other_thread_bp unwind } {
     save_vars { ::GDBFLAGS } {
 	append ::GDBFLAGS " -ex \"maint set target-non-stop $target_non_stop\""
 	append ::GDBFLAGS " -ex \"maintenance set target-async ${target_async}\""
@@ -72,6 +77,7 @@ proc run_test { target_async target_non_stop other_thread_bp } {
     # for this timeout.  For now though, we just hope 5 seconds is
     # enough.
     gdb_test_no_output "set indirect-call-timeout 5"
+    gdb_test_no_output "set unwind-on-timeout $unwind"
 
     gdb_breakpoint \
 	"${::srcfile}:${::cond_bp_line} if (condition_func ())"
@@ -92,18 +98,35 @@ proc run_test { target_async target_non_stop other_thread_bp } {
 				 "get number for segfault breakpoint"]
     }
 
-    gdb_test "continue" \
-	[multi_line \
-	     "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\." \
-	     ".*" \
-	     "Error in testing condition for breakpoint ${bp_num}:" \
-	     "The program being debugged timed out while in a function called from GDB\\." \
-	     "GDB remains in the frame where the timeout occurred\\." \
-	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
-	     "Evaluation of the expression containing the function" \
-	     "\\(condition_func\\) will be abandoned\\." \
-	     "When the function is done executing, GDB will silently stop\\."] \
-	"expected timeout waiting for inferior call to complete"
+    if { $unwind } {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\." \
+		 ".*" \
+		 "Error in testing condition for breakpoint ${bp_num}:" \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB has restored the context to what it was before the call\\." \
+		 "To change this behavior use \"set unwind-on-timeout off\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(condition_func\\) will be abandoned\\." \
+		 "" \
+		 "Thread ${::decimal}\[^\r\n\]*hit Breakpoint ${bp_num}, \[^\r\n\]+" \
+		 "\[^\r\n\]+ Conditional breakpoint here\\. \[^\r\n\]+"] \
+	    "expected timeout waiting for inferior call to complete"
+    } else {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\." \
+		 ".*" \
+		 "Error in testing condition for breakpoint ${bp_num}:" \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB remains in the frame where the timeout occurred\\." \
+		 "To change this behavior use \"set unwind-on-timeout on\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(condition_func\\) will be abandoned\\." \
+		 "When the function is done executing, GDB will silently stop\\."] \
+	    "expected timeout waiting for inferior call to complete"
+    }
 
     # Remember that other thread that either crashed (with a segfault)
     # or hit a breakpoint?  Now that the inferior call has timed out,
@@ -142,8 +165,10 @@ foreach_with_prefix target_async {"on" "off" } {
     }
 
     foreach_with_prefix target_non_stop {"off" "on"} {
-	foreach_with_prefix other_thread_bp { true false } {
-	    run_test $target_async $target_non_stop $other_thread_bp
+	foreach_with_prefix unwind {"off" "on"} {
+	    foreach_with_prefix other_thread_bp { true false } {
+		run_test $target_async $target_non_stop $other_thread_bp $unwind
+	    }
 	}
     }
 }
-- 
2.25.4


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

* [PATCHv5 11/11] gdb: rename unwindonsignal to unwind-on-signal
  2023-03-16 17:36       ` [PATCHv5 00/11] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                           ` (9 preceding siblings ...)
  2023-03-16 17:37         ` [PATCHv5 10/11] gdb: introduce unwind-on-timeout setting Andrew Burgess
@ 2023-03-16 17:37         ` Andrew Burgess
  2023-04-03 14:01         ` [PATCHv6 0/6] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
  11 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-03-16 17:37 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Eli already approved the docs part:
  https://sourceware.org/pipermail/gdb-patches/2023-January/195874.html

---

We now have unwind-on-timeout and unwind-on-terminating-exception, and
then the odd one out unwindonsignal.

I'm not a great fan of these squashed together command names, so in
this commit I propose renaming this to unwind-on-signal.

Obviously I've added the hidden alias unwindonsignal so any existing
GDB scripts will keep working.

There's one test that I've extended to test the alias works, but in
most of the other test scripts I've changed over to use the new name.

The docs are updated to reference the new name.
---
 gdb/NEWS                                      | 11 ++++++
 gdb/doc/gdb.texinfo                           | 16 ++++++---
 gdb/infcall.c                                 | 21 ++++++-----
 gdb/testsuite/gdb.base/callfuncs.exp          |  4 +--
 gdb/testsuite/gdb.base/infcall-failure.exp    |  4 +--
 gdb/testsuite/gdb.base/unwindonsignal.exp     | 36 +++++++++++++------
 gdb/testsuite/gdb.compile/compile-cplus.exp   |  2 +-
 gdb/testsuite/gdb.compile/compile.exp         |  2 +-
 gdb/testsuite/gdb.cp/gdb2495.exp              | 16 ++++-----
 gdb/testsuite/gdb.fortran/function-calls.exp  |  2 +-
 gdb/testsuite/gdb.mi/mi-syn-frame.exp         |  2 +-
 .../infcall-from-bp-cond-simple.exp           |  2 +-
 .../gdb.threads/thread-unwindonsignal.exp     |  8 ++---
 13 files changed, 83 insertions(+), 43 deletions(-)

diff --git a/gdb/NEWS b/gdb/NEWS
index 0712a91421a..80fa73c5331 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -118,6 +118,17 @@ show unwind-on-timeout
   dummy frame that was added for the inferior call, and restoring the
   inferior state to how it was before the inferior call started.
 
+set unwind-on-signal on|off
+show unwind-on-signal
+  These new commands replaces the existing set/show unwindonsignal.  The
+  old command is maintained as an alias.
+
+* Changed commands
+
+set unwindonsignal on|off
+show unwindonsignal
+  These commands are now aliases for the new set/show unwind-on-signal.
+
 * MI changes
 
 ** mi now reports 'no-history' as a stop reason when hitting the end of the
diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index d0f4b180e09..484a61cb506 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -20778,7 +20778,7 @@
 It is possible for the function you call via the @code{print} or
 @code{call} command to generate a signal (e.g., if there's a bug in
 the function, or if you passed it incorrect arguments).  What happens
-in that case is controlled by the @code{set unwindonsignal} command.
+in that case is controlled by the @code{set unwind-on-signal} command.
 
 Similarly, with a C@t{++} program it is possible for the function you
 call via the @code{print} or @code{call} command to generate an
@@ -20792,7 +20792,8 @@
 
 @anchor{stack unwind settings}
 @table @code
-@item set unwindonsignal
+@item set unwind-on-signal
+@kindex set unwind-on-signal
 @kindex set unwindonsignal
 @cindex unwind stack in called functions
 @cindex call dummy stack unwinding
@@ -20803,11 +20804,18 @@
 default), @value{GDBN} stops in the frame where the signal was
 received.
 
-@item show unwindonsignal
+The command @code{set unwindonsignal} is an alias for this command,
+and is maintained for backward compatibility.
+
+@item show unwind-on-signal
+@kindex show unwind-on-signal
 @kindex show unwindonsignal
 Show the current setting of stack unwinding in the functions called by
 @value{GDBN}.
 
+The command @code{show unwindonsignal} is an alias for this command,
+and is maintained for backward compatibility.
+
 @item set unwind-on-terminating-exception
 @kindex set unwind-on-terminating-exception
 @cindex unwind stack in called functions with unhandled exceptions
@@ -20871,7 +20879,7 @@
 If a called function is interrupted for any reason, including hitting
 a breakpoint, or triggering a watchpoint, and the stack is not unwound
 due to @code{set unwind-on-terminating-exception on}, @code{set
-unwind-on-timeout on}, or @code{set unwindonsignal on} (@pxref{stack
+unwind-on-timeout on}, or @code{set unwind-on-signal on} (@pxref{stack
 unwind settings}), then the dummy-frame, created by @value{GDBN} to
 facilitate the call to the program function, will be visible in the
 backtrace, for example frame @code{#3} in the following backtrace:
diff --git a/gdb/infcall.c b/gdb/infcall.c
index 1f0fb4f1d59..73b19afe613 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -1689,7 +1689,7 @@ When the function is done executing, GDB will silently stop."),
 	      error (_("\
 The program being debugged was signaled while in a function called from GDB.\n\
 GDB has restored the context to what it was before the call.\n\
-To change this behavior use \"set unwindonsignal off\".\n\
+To change this behavior use \"set unwind-on-signal off\".\n\
 Evaluation of the expression containing the function\n\
 (%s) will be abandoned."),
 		     name.c_str ());
@@ -1707,7 +1707,7 @@ Evaluation of the expression containing the function\n\
 	      error (_("\
 The program being debugged was signaled while in a function called from GDB.\n\
 GDB remains in the frame where the signal was received.\n\
-To change this behavior use \"set unwindonsignal on\".\n\
+To change this behavior use \"set unwind-on-signal on\".\n\
 Evaluation of the expression containing the function\n\
 (%s) will be abandoned.\n\
 When the function is done executing, GDB will silently stop."),
@@ -1839,17 +1839,22 @@ The default is to perform the conversion."),
 			   show_coerce_float_to_double_p,
 			   &setlist, &showlist);
 
-  add_setshow_boolean_cmd ("unwindonsignal", no_class,
-			   &unwind_on_signal_p, _("\
+  set_show_commands setshow_unwind_on_signal_cmds
+    = add_setshow_boolean_cmd ("unwind-on-signal", no_class,
+			       &unwind_on_signal_p, _("\
 Set unwinding of stack if a signal is received while in a call dummy."), _("\
 Show unwinding of stack if a signal is received while in a call dummy."), _("\
-The unwindonsignal lets the user determine what gdb should do if a signal\n\
+The unwind-on-signal lets the user determine what gdb should do if a signal\n\
 is received while in a function called from gdb (call dummy).  If set, gdb\n\
 unwinds the stack and restore the context to what as it was before the call.\n\
 The default is to stop in the frame where the signal was received."),
-			   NULL,
-			   show_unwind_on_signal_p,
-			   &setlist, &showlist);
+			       NULL,
+			       show_unwind_on_signal_p,
+			       &setlist, &showlist);
+  add_alias_cmd ("unwindonsignal", setshow_unwind_on_signal_cmds.set,
+		 no_class, 1, &setlist);
+  add_alias_cmd ("unwindonsignal", setshow_unwind_on_signal_cmds.show,
+		 no_class, 1, &showlist);
 
   add_setshow_boolean_cmd ("unwind-on-terminating-exception", no_class,
 			   &unwind_on_terminating_exception_p, _("\
diff --git a/gdb/testsuite/gdb.base/callfuncs.exp b/gdb/testsuite/gdb.base/callfuncs.exp
index 2c797a224a7..d9f63e944bf 100644
--- a/gdb/testsuite/gdb.base/callfuncs.exp
+++ b/gdb/testsuite/gdb.base/callfuncs.exp
@@ -46,7 +46,7 @@ proc do_function_calls {prototypes} {
 
     # If any of these calls segv we don't want to affect subsequent tests.
     # E.g., we want to ensure register values are restored.
-    gdb_test_no_output "set unwindonsignal on"
+    gdb_test_no_output "set unwind-on-signal on"
 
     gdb_test "p t_char_values(0,0)" " = 0"
     gdb_test "p t_char_values('a','b')" " = 1"
@@ -237,7 +237,7 @@ proc do_function_calls {prototypes} {
     	"call inferior func with struct - returns char *"
 
     # Restore default value.
-    gdb_test_no_output "set unwindonsignal off"
+    gdb_test_no_output "set unwind-on-signal off"
 }
 
 # Procedure to get current content of all registers.
diff --git a/gdb/testsuite/gdb.base/infcall-failure.exp b/gdb/testsuite/gdb.base/infcall-failure.exp
index 5ad179a089d..e2e71649dac 100644
--- a/gdb/testsuite/gdb.base/infcall-failure.exp
+++ b/gdb/testsuite/gdb.base/infcall-failure.exp
@@ -137,7 +137,7 @@ proc_with_prefix run_cond_hits_segfault_test { async_p non_stop_p } {
 	     "Error in testing condition for breakpoint ${bp_1_num}:" \
 	     "The program being debugged was signaled while in a function called from GDB\\." \
 	     "GDB remains in the frame where the signal was received\\." \
-	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "To change this behavior use \"set unwind-on-signal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(func_segfault\\) will be abandoned\\." \
 	     "When the function is done executing, GDB will silently stop\\."]
@@ -166,7 +166,7 @@ proc_with_prefix run_call_hits_segfault_test { async_p non_stop_p } {
 	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
 	     "The program being debugged was signaled while in a function called from GDB\\." \
 	     "GDB remains in the frame where the signal was received\\." \
-	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "To change this behavior use \"set unwind-on-signal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(func_segfault\\) will be abandoned\\." \
 	     "When the function is done executing, GDB will silently stop\\."]
diff --git a/gdb/testsuite/gdb.base/unwindonsignal.exp b/gdb/testsuite/gdb.base/unwindonsignal.exp
index 625b0c4db12..9c1b36e95bc 100644
--- a/gdb/testsuite/gdb.base/unwindonsignal.exp
+++ b/gdb/testsuite/gdb.base/unwindonsignal.exp
@@ -34,34 +34,50 @@ gdb_test "break stop_here" "Breakpoint \[0-9\]* at .*"
 gdb_test "continue" "Continuing.*Breakpoint \[0-9\]*, stop_here.*" \
     "continue to breakpoint at stop_here"
 
-# Turn on unwindonsignal.
-gdb_test_no_output "set unwindonsignal on" \
-	"setting unwindonsignal"
+# Turn on unwind-on-signal.
+gdb_test_no_output "set unwind-on-signal on" \
+	"setting unwind-on-signal"
 
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
 	"Unwinding of stack .* is on." \
-	"showing unwindonsignal"
+	"showing unwind-on-signal"
+
+# For backward compatibility we maintain a 'unwindonsignal' alias for
+# 'unwind-on-signal', check it now.
+gdb_test "show unwindonsignal" \
+    "Unwinding of stack .* is on\\." \
+    "showing unwindonsignal alias"
+
+gdb_test_no_output "set unwindonsignal off" \
+    "setting unwindonsignal alias to off"
+
+gdb_test "show unwind-on-signal" \
+    "Unwinding of stack .* is off\\." \
+    "showing unwind-on-signal after setting via alias"
+
+gdb_test_no_output "set unwindonsignal on" \
+    "setting unwindonsignal alias to on"
 
 # Call function (causing the program to get a signal), and see if gdb handles
 # it properly.
 if {[gdb_test "call gen_signal ()"  \
 	 "\[\r\n\]*The program being debugged was signaled.*" \
-	 "unwindonsignal, inferior function call signaled"] != 0} {
+	 "inferior function call signaled"] != 0} {
     return 0
 }
 
 # Verify the stack got unwound.
 gdb_test "bt" \
     "#0 *\[x0-9a-f in\]*stop_here \\(.*\\) at .*#1 *\[x0-9a-f in\]*main \\(.*\\) at .*" \
-	"unwindonsignal, stack unwound"
+	"stack unwound"
 
 # Verify the dummy frame got removed from dummy_frame_stack.
 gdb_test_multiple "maint print dummy-frames" \
-	"unwindonsignal, dummy frame removed" {
+	"unwind-on-signal, dummy frame removed" {
     -re "\[\r\n\]*.*stack=.*code=.*\[\r\n\]+$gdb_prompt $" {
-	fail "unwindonsignal, dummy frame removed"
+	fail $gdb_test_name
     }
     -re "\[\r\n\]+$gdb_prompt $" {
-	pass "unwindonsignal, dummy frame removed"
+	pass $gdb_test_name
     }
 }
diff --git a/gdb/testsuite/gdb.compile/compile-cplus.exp b/gdb/testsuite/gdb.compile/compile-cplus.exp
index 4e887daeb29..22eebb44953 100644
--- a/gdb/testsuite/gdb.compile/compile-cplus.exp
+++ b/gdb/testsuite/gdb.compile/compile-cplus.exp
@@ -129,7 +129,7 @@ gdb_test "return" "\r\n#0  main .*" "return" \
 	 "Make _gdb_expr\\(__gdb_regs\\*\\) return now\\? \\(y or n\\) " "y"
 gdb_test "info sym $infcall_pc" "\r\nNo symbol matches .*" "info sym not found"
 
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 gdb_test "compile code *(volatile int *) 0 = 0;" \
     "The program being debugged was signaled while in a function called from GDB\\.\r\nGDB has restored the context to what it was before the call\\.\r\n.*" \
     "compile code segfault second"
diff --git a/gdb/testsuite/gdb.compile/compile.exp b/gdb/testsuite/gdb.compile/compile.exp
index f3d87cd2605..8822aab2e81 100644
--- a/gdb/testsuite/gdb.compile/compile.exp
+++ b/gdb/testsuite/gdb.compile/compile.exp
@@ -159,7 +159,7 @@ gdb_test "return" "\r\n#0  main .*" "return" \
 	 "Make _gdb_expr return now\\? \\(y or n\\) " "y"
 gdb_test "info sym $infcall_pc" "\r\nNo symbol matches .*" "info sym not found"
 
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 gdb_test "compile code *(volatile int *) 0 = 0;" \
     "The program being debugged was signaled while in a function called from GDB\\.\r\nGDB has restored the context to what it was before the call\\.\r\n.*" \
     "compile code segfault second"
diff --git a/gdb/testsuite/gdb.cp/gdb2495.exp b/gdb/testsuite/gdb.cp/gdb2495.exp
index e3c0cca3175..d7985e5db48 100644
--- a/gdb/testsuite/gdb.cp/gdb2495.exp
+++ b/gdb/testsuite/gdb.cp/gdb2495.exp
@@ -98,29 +98,29 @@ if {![runto_main]} {
 # behaviour; it should not.  Test both on and off states.
 
 # Turn on unwind on signal behaviour.
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 
 # Check that it is turned on.
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
     "signal is received while in a call dummy is on.*" \
     "turn on unwind on signal"
 
 # Check to see if new behaviour interferes with
 # normal signal handling in inferior function calls.
 gdb_test "p exceptions.raise_signal(1)" \
-    "To change this behavior use \"set unwindonsignal off\".*" \
-    "check for unwindonsignal off message"
+    "To change this behavior use \"set unwind-on-signal off\".*" \
+    "check for unwind-on-signal off message"
 
 # And reverse - turn off again.
-gdb_test_no_output "set unwindonsignal off"
+gdb_test_no_output "set unwind-on-signal off"
 
 # Check that it is actually turned off.
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
     "signal is received while in a call dummy is off.*" \
     "turn off unwind on signal"
 
 # Check to see if new behaviour interferes with
 # normal signal handling in inferior function calls.
 gdb_test "p exceptions.raise_signal(1)" \
-    "To change this behavior use \"set unwindonsignal on\".*" \
-    "check for unwindonsignal on message"
+    "To change this behavior use \"set unwind-on-signal on\".*" \
+    "check for unwind-on-signal on message"
diff --git a/gdb/testsuite/gdb.fortran/function-calls.exp b/gdb/testsuite/gdb.fortran/function-calls.exp
index f9a1efc241f..c4d1f232576 100644
--- a/gdb/testsuite/gdb.fortran/function-calls.exp
+++ b/gdb/testsuite/gdb.fortran/function-calls.exp
@@ -44,7 +44,7 @@ if {![runto [gdb_get_line_number "post_init"]]} {
 }
 
 # Use inspired by gdb.base/callfuncs.exp.
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 
 # Baseline: function and subroutine call with no arguments.
 gdb_test "p no_arg()" " = .TRUE."
diff --git a/gdb/testsuite/gdb.mi/mi-syn-frame.exp b/gdb/testsuite/gdb.mi/mi-syn-frame.exp
index 40df312a1cc..1324226412c 100644
--- a/gdb/testsuite/gdb.mi/mi-syn-frame.exp
+++ b/gdb/testsuite/gdb.mi/mi-syn-frame.exp
@@ -94,7 +94,7 @@ mi_gdb_test "409-stack-list-frames 0 0" \
 # 
 
 mi_gdb_test "410-data-evaluate-expression bar()" \
-  ".*410\\^error,msg=\"The program being debugged was signaled while in a function called from GDB.\\\\nGDB remains in the frame where the signal was received.\\\\nTo change this behavior use \\\\\"set unwindonsignal on\\\\\".\\\\nEvaluation of the expression containing the function\\\\n\\(bar\\) will be abandoned.\\\\nWhen the function is done executing, GDB will silently stop.\"" \
+  ".*410\\^error,msg=\"The program being debugged was signaled while in a function called from GDB.\\\\nGDB remains in the frame where the signal was received.\\\\nTo change this behavior use \\\\\"set unwind-on-signal on\\\\\".\\\\nEvaluation of the expression containing the function\\\\n\\(bar\\) will be abandoned.\\\\nWhen the function is done executing, GDB will silently stop.\"" \
   "call inferior function which raises exception"
 
 mi_gdb_test "411-stack-list-frames" "411\\^done,stack=\\\[frame=\{level=\"0\",addr=\"$hex\",func=\"bar\",file=\".*mi-syn-frame.c\",fullname=\"${fullname_syntax}${srcfile}\",line=\"$decimal\",arch=\"$any\"},frame=\{level=\"1\",addr=\"$hex\",func=\"<function called from gdb>\"\},frame=\{level=\"2\",addr=\"$hex\",func=\"main\",file=\".*mi-syn-frame.c\",fullname=\"${fullname_syntax}${srcfile}\",line=\"$decimal\",arch=\"$any\"}.*\\\]" "backtrace from inferior function at exception"
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
index 37e1b64d9a4..bb4402c0926 100644
--- a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
@@ -173,7 +173,7 @@ proc_with_prefix run_bp_cond_segfaults { target_async target_non_stop } {
 	     "Error in testing condition for breakpoint ${bp_1_num}:" \
 	     "The program being debugged was signaled while in a function called from GDB\\." \
 	     "GDB remains in the frame where the signal was received\\." \
-	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "To change this behavior use \"set unwind-on-signal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(function_that_segfaults\\) will be abandoned\\." \
 	     "When the function is done executing, GDB will silently stop\\."]
diff --git a/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp b/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp
index 68a99f66f1c..a9cedc0c466 100644
--- a/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp
+++ b/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp
@@ -13,7 +13,7 @@
 # You should have received a copy of the GNU General Public License
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-# Test use of unwindonsignal when a hand function call that gets interrupted
+# Test use of unwind-on-signal when a hand function call that gets interrupted
 # by a signal in another thread.
 
 set NR_THREADS 4
@@ -49,12 +49,12 @@ gdb_test "continue" \
 # We want the main thread (hand_call_with_signal) and
 # thread 1 (sigabrt_handler) to both run.
 
-# Do turn on unwindonsignal.
+# Do turn on unwind-on-signal.
 # We want to test gdb handling of the current thread changing when
 # unwindonsignal is in effect.
-gdb_test_no_output "set unwindonsignal on" \
+gdb_test_no_output "set unwind-on-signal on" \
 	"setting unwindonsignal"
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
 	"Unwinding of stack .* is on." \
 	"showing unwindonsignal"
 
-- 
2.25.4


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

* Re: [PATCHv5 01/11] gdb: include breakpoint number in testing condition error message
  2023-03-16 17:36         ` [PATCHv5 01/11] gdb: include breakpoint number in testing condition error message Andrew Burgess
@ 2023-04-03 13:50           ` Andrew Burgess
  2023-07-07 12:08           ` Pedro Alves
  1 sibling, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-04-03 13:50 UTC (permalink / raw)
  To: gdb-patches

Andrew Burgess <aburgess@redhat.com> writes:

> When GDB fails to test the condition of a conditional breakpoint, for
> whatever reason, the error message looks like this:
>
>   (gdb) break foo if (*(int *) 0) == 1
>   Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
>   (gdb) r
>   Starting program: /tmp/bpcond
>   Error in testing breakpoint condition:
>   Cannot access memory at address 0x0
>
>   Breakpoint 1, foo () at bpcond.c:11
>   11	  int a = 32;
>   (gdb)
>
> The line I'm interested in for this commit is this one:
>
>   Error in testing breakpoint condition:
>
> In the case above we can figure out that the problematic breakpoint
> was #1 because in the final line of the message GDB reports the stop a
> breakpoint #1.
>
> However, in the next few patches I plan to change this.  In some cases
> I don't think it makes sense for GDB to report the stop as being at
> breakpoint #1, consider this case:
>
>   (gdb) list some_func
>   1	int
>   2	some_func ()
>   3	{
>   4	  int *p = 0;
>   5	  return *p;
>   6	}
>   7
>   8	void
>   9	foo ()
>   10	{
>   (gdb) break foo if (some_func ())
>   Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
>   (gdb) r
>   Starting program: /tmp/bpcond
>
>   Program received signal SIGSEGV, Segmentation fault.
>   0x0000000000401116 in some_func () at bpcond.c:5
>   5	  return *p;
>   Error in testing breakpoint condition:
>   The program being debugged was signaled while in a function called from GDB.
>   GDB remains in the frame where the signal was received.
>   To change this behavior use "set unwindonsignal on".
>   Evaluation of the expression containing the function
>   (some_func) will be abandoned.
>   When the function is done executing, GDB will silently stop.
>
>   Program received signal SIGSEGV, Segmentation fault.
>
>   Breakpoint 1, 0x0000000000401116 in some_func () at bpcond.c:5
>   5	  return *p;
>   (gdb)
>
> Notice that, the final lines of output report the stop as being at
> breakpoint #1, even though we are actually located within some_func.
>
> I find this behaviour confusing, and propose that this should be
> changed.  However, if I make that change then every reference to
> breakpoint #1 will be lost from the error message.
>
> So, in this commit, in preparation for the later commits, I propose to
> change the 'Error in testing breakpoint condition:' line to this:
>
>   Error in testing condition for breakpoint NUMBER:
>
> where NUMBER will be filled in as appropriate.  Here's the first
> example with the updated error:
>
>   (gdb) break foo if (*(int *) 0) == 0
>   Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
>   (gdb) r
>   Starting program: /tmp/bpcond
>   Error in testing condition for breakpoint 1:
>   Cannot access memory at address 0x0
>
>   Breakpoint 1, foo () at bpcond.c:11
>   11	  int a = 32;
>   (gdb)
>
> The breakpoint number does now appear twice in the output, but I don't
> see that as a negative.
>
> This commit just changes the one line of the error, and updates the
> few tests that either included the old error in comments, or actually
> checked for the error in the expected output.
>
> As the only test that checked the line I modified is a Python test,
> I've added a new test that doesn't rely on Python that checks the
> error message in detail.
>
> While working on the new test, I spotted that it would fail when run
> with native-gdbserver and native-extended-gdbserver target boards.
> This turns out to be due to a gdbserver bug.  To avoid cluttering this
> commit I've added a work around to the new test script so that the
> test passes for the remote boards, in the next few commits I will fix
> gdbserver, and update the test script to remove the work around.

I went ahead and pushed this commit.

If there are any problems, please let me know, I'm happy to address any
issues.

Thanks,
Andrew


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

* Re: [PATCHv5 02/11] gdbserver: allows agent_mem_read to return an error code
  2023-03-16 17:36         ` [PATCHv5 02/11] gdbserver: allows agent_mem_read to return an error code Andrew Burgess
@ 2023-04-03 13:50           ` Andrew Burgess
  0 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-04-03 13:50 UTC (permalink / raw)
  To: gdb-patches

Andrew Burgess <aburgess@redhat.com> writes:

> Currently the gdbserver function agent_mem_read ignores any errors
> from calling read_inferior_memory.  This means that if there is an
> attempt to access invalid memory then this will appear to succeed.
>
> In this patch I update agent_mem_read so that if read_inferior_memory
> fails, agent_mem_read will return an error code.
>
> However, none of the callers of agent_mem_read actually check the
> return value, so this commit will have no effect on anything.  In the
> next commit I will update the users of agent_mem_read to check for the
> error code.
>
> I've also updated the header comments on agent_mem_read to better
> reflect what the function does, and its possible return values.

I went ahead and pushed this commit.

If there are any problems, please let me know, I'm happy to address any
issues.

Thanks,
Andrew



> ---
>  gdbserver/tracepoint.cc | 11 ++++-------
>  gdbserver/tracepoint.h  |  9 +++++++--
>  2 files changed, 11 insertions(+), 9 deletions(-)
>
> diff --git a/gdbserver/tracepoint.cc b/gdbserver/tracepoint.cc
> index 3f60989e4c7..125a384ffb3 100644
> --- a/gdbserver/tracepoint.cc
> +++ b/gdbserver/tracepoint.cc
> @@ -4914,8 +4914,7 @@ condition_true_at_tracepoint (struct tracepoint_hit_ctx *ctx,
>    return (value ? 1 : 0);
>  }
>  
> -/* Do memory copies for bytecodes.  */
> -/* Do the recording of memory blocks for actions and bytecodes.  */
> +/* See tracepoint.h.  */
>  
>  int
>  agent_mem_read (struct eval_agent_expr_context *ctx,
> @@ -4927,10 +4926,7 @@ agent_mem_read (struct eval_agent_expr_context *ctx,
>  
>    /* If a 'to' buffer is specified, use it.  */
>    if (to != NULL)
> -    {
> -      read_inferior_memory (from, to, len);
> -      return 0;
> -    }
> +    return read_inferior_memory (from, to, len);
>  
>    /* Otherwise, create a new memory block in the trace buffer.  */
>    while (remaining > 0)
> @@ -4951,7 +4947,8 @@ agent_mem_read (struct eval_agent_expr_context *ctx,
>        memcpy (mspace, &blocklen, sizeof (blocklen));
>        mspace += sizeof (blocklen);
>        /* Record the memory block proper.  */
> -      read_inferior_memory (from, mspace, blocklen);
> +      if (read_inferior_memory (from, mspace, blocklen) != 0)
> +	return 1;
>        trace_debug ("%d bytes recorded", blocklen);
>        remaining -= blocklen;
>        from += blocklen;
> diff --git a/gdbserver/tracepoint.h b/gdbserver/tracepoint.h
> index 060d44d0033..1f40d7b5177 100644
> --- a/gdbserver/tracepoint.h
> +++ b/gdbserver/tracepoint.h
> @@ -161,8 +161,13 @@ void gdb_agent_about_to_close (int pid);
>  struct traceframe;
>  struct eval_agent_expr_context;
>  
> -/* Do memory copies for bytecodes.  */
> -/* Do the recording of memory blocks for actions and bytecodes.  */
> +/* When TO is not NULL, do memory copies for bytecodes, read LEN bytes
> +   starting at address FROM, and place the result in the buffer TO.
> +   Return 0 on success, otherwise a non-zero error code.
> +
> +   When TO is NULL, do the recording of memory blocks for actions and
> +   bytecodes into a new traceframe block.  Return 0 on success, otherwise,
> +   return 1 if there is an error.  */
>  
>  int agent_mem_read (struct eval_agent_expr_context *ctx,
>  		    unsigned char *to, CORE_ADDR from,
> -- 
> 2.25.4


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

* Re: [PATCHv5 03/11] gdbserver: allow agent expressions to fail with invalid memory access
  2023-03-16 17:36         ` [PATCHv5 03/11] gdbserver: allow agent expressions to fail with invalid memory access Andrew Burgess
@ 2023-04-03 13:50           ` Andrew Burgess
  2023-07-07 12:25           ` Pedro Alves
  1 sibling, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-04-03 13:50 UTC (permalink / raw)
  To: gdb-patches

Andrew Burgess <aburgess@redhat.com> writes:

> This commit extends gdbserver to take account of a failed memory
> access from agent_mem_read, and to return a new eval_result_type
> expr_eval_invalid_memory_access.
>
> I have only updated the agent_mem_read calls related directly to
> reading memory, I have not updated any of the calls related to
> tracepoint data collection.  This is just because I'm not familiar
> with that area of gdb/gdbserver, and I don't want to break anything,
> so leaving the existing behaviour untouched seems like the safest
> approach.
>
> I've then updated gdb.base/bp-cond-failure.exp to test evaluating the
> breakpoints on the target, and have also extended the test so that it
> checks for different sizes of memory access.

I went ahead and pushed this commit.

If there are any problems, please let me know, I'm happy to address any
issues.

Thanks,
Andrew


> ---
>  gdb/testsuite/gdb.base/bp-cond-failure.exp | 22 +++++++---------------
>  gdbserver/ax.cc                            | 12 ++++++++----
>  gdbserver/ax.h                             |  3 ++-
>  3 files changed, 17 insertions(+), 20 deletions(-)
>
> diff --git a/gdb/testsuite/gdb.base/bp-cond-failure.exp b/gdb/testsuite/gdb.base/bp-cond-failure.exp
> index b528ccce4ad..cb572203772 100644
> --- a/gdb/testsuite/gdb.base/bp-cond-failure.exp
> +++ b/gdb/testsuite/gdb.base/bp-cond-failure.exp
> @@ -47,7 +47,7 @@ if { [is_address_zero_readable] } {
>  # Where the breakpoint will be placed.
>  set bp_line [gdb_get_line_number "Breakpoint here"]
>  
> -proc run_test { cond_eval } {
> +proc run_test { cond_eval access_type } {
>      clean_restart ${::binfile}
>  
>      if { ![runto_main] } {
> @@ -59,7 +59,7 @@ proc run_test { cond_eval } {
>      }
>  
>      # Setup the conditional breakpoint and record its number.
> -    gdb_breakpoint "${::srcfile}:${::bp_line} if (*(int *) 0) == 0"
> +    gdb_breakpoint "${::srcfile}:${::bp_line} if (*(${access_type} *) 0) == 0"
>      set bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*"]
>  
>      gdb_test "continue" \
> @@ -88,17 +88,7 @@ set cond_eval_modes { "auto" }
>  
>  gdb_test_multiple "show breakpoint condition-evaluation" "" {
>      -re -wrap "Breakpoint condition evaluation mode is auto \\(currently target\\)\\." {
> -
> -	## NOTE: Instead of testing with "auto" and "host" in this
> -	## case we only test with "host".  This is because a GDB bug
> -	## prevents the "auto" (a.k.a. target) mode from working.
> -	##
> -	## Don't worry, this will be fixed in a later commit, and this
> -	## comment will be removed at that time.
> -	##
> -	## lappend cond_eval_modes "host"
> -
> -	set cond_eval_modes { "host" }
> +	lappend cond_eval_modes "host"
>  	pass $gdb_test_name
>      }
>  
> @@ -107,6 +97,8 @@ gdb_test_multiple "show breakpoint condition-evaluation" "" {
>      }
>  }
>  
> -foreach_with_prefix cond_eval $cond_eval_modes {
> -    run_test $cond_eval
> +foreach_with_prefix access_type { "char" "short" "int" "long long" } {
> +    foreach_with_prefix cond_eval $cond_eval_modes {
> +	run_test $cond_eval $access_type
> +    }
>  }
> diff --git a/gdbserver/ax.cc b/gdbserver/ax.cc
> index 38ebfbbd750..fba5b4ad0fc 100644
> --- a/gdbserver/ax.cc
> +++ b/gdbserver/ax.cc
> @@ -1112,22 +1112,26 @@ gdb_eval_agent_expr (struct eval_agent_expr_context *ctx,
>  	  break;
>  
>  	case gdb_agent_op_ref8:
> -	  agent_mem_read (ctx, cnv.u8.bytes, (CORE_ADDR) top, 1);
> +	  if (agent_mem_read (ctx, cnv.u8.bytes, (CORE_ADDR) top, 1) != 0)
> +	    return expr_eval_invalid_memory_access;
>  	  top = cnv.u8.val;
>  	  break;
>  
>  	case gdb_agent_op_ref16:
> -	  agent_mem_read (ctx, cnv.u16.bytes, (CORE_ADDR) top, 2);
> +	  if (agent_mem_read (ctx, cnv.u16.bytes, (CORE_ADDR) top, 2) != 0)
> +	    return expr_eval_invalid_memory_access;
>  	  top = cnv.u16.val;
>  	  break;
>  
>  	case gdb_agent_op_ref32:
> -	  agent_mem_read (ctx, cnv.u32.bytes, (CORE_ADDR) top, 4);
> +	  if (agent_mem_read (ctx, cnv.u32.bytes, (CORE_ADDR) top, 4) != 0)
> +	    return expr_eval_invalid_memory_access;
>  	  top = cnv.u32.val;
>  	  break;
>  
>  	case gdb_agent_op_ref64:
> -	  agent_mem_read (ctx, cnv.u64.bytes, (CORE_ADDR) top, 8);
> +	  if (agent_mem_read (ctx, cnv.u64.bytes, (CORE_ADDR) top, 8) != 0)
> +	    return expr_eval_invalid_memory_access;
>  	  top = cnv.u64.val;
>  	  break;
>  
> diff --git a/gdbserver/ax.h b/gdbserver/ax.h
> index 8e64a7a593e..c98e36a83c6 100644
> --- a/gdbserver/ax.h
> +++ b/gdbserver/ax.h
> @@ -41,7 +41,8 @@ enum eval_result_type
>      expr_eval_unhandled_opcode,
>      expr_eval_unrecognized_opcode,
>      expr_eval_divide_by_zero,
> -    expr_eval_invalid_goto
> +    expr_eval_invalid_goto,
> +    expr_eval_invalid_memory_access
>    };
>  
>  struct agent_expr
> -- 
> 2.25.4


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

* Re: [PATCHv5 04/11] gdb: avoid repeated signal reporting during failed conditional breakpoint
  2023-03-16 17:36         ` [PATCHv5 04/11] gdb: avoid repeated signal reporting during failed conditional breakpoint Andrew Burgess
@ 2023-04-03 13:50           ` Andrew Burgess
  0 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-04-03 13:50 UTC (permalink / raw)
  To: gdb-patches

Andrew Burgess <aburgess@redhat.com> writes:

> Consider the following case:
>
>   (gdb) list some_func
>   1	int
>   2	some_func ()
>   3	{
>   4	  int *p = 0;
>   5	  return *p;
>   6	}
>   7
>   8	void
>   9	foo ()
>   10	{
>   (gdb) break foo if (some_func ())
>   Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
>   (gdb) r
>   Starting program: /tmp/bpcond
>
>   Program received signal SIGSEGV, Segmentation fault.
>   0x0000000000401116 in some_func () at bpcond.c:5
>   5	  return *p;
>   Error in testing breakpoint condition:
>   The program being debugged was signaled while in a function called from GDB.
>   GDB remains in the frame where the signal was received.
>   To change this behavior use "set unwindonsignal on".
>   Evaluation of the expression containing the function
>   (some_func) will be abandoned.
>   When the function is done executing, GDB will silently stop.
>
>   Program received signal SIGSEGV, Segmentation fault.
>
>   Breakpoint 1, 0x0000000000401116 in some_func () at bpcond.c:5
>   5	  return *p;
>   (gdb)
>
> Notice that this line:
>
>   Program received signal SIGSEGV, Segmentation fault.
>
> Appears twice in the output.  The first time is followed by the
> current location.  The second time is a little odd, why do we print
> that?
>
> Printing that line is controlled, in part, by a global variable,
> stopped_by_random_signal.  This variable is reset to zero in
> handle_signal_stop, and is set if/when GDB figures out that the
> inferior stopped due to some random signal.
>
> The problem is, in our case, GDB first stops at the breakpoint for
> foo, and enters handle_signal_stop and the stopped_by_random_signal
> global is reset to 0.
>
> Later within handle_signal_stop GDB calls bpstat_stop_status, it is
> within this function (via bpstat_check_breakpoint_conditions) that the
> breakpoint condition is checked, and, we end up calling the inferior
> function (some_func in our example above).
>
> In our case above the thread performing the inferior function call
> segfaults in some_func.  GDB catches the SIGSEGV and handles the stop,
> this causes us to reenter handle_signal_stop.  The global variable
> stopped_by_random_signal is updated, this time it is set to true
> because the thread stopped due to SIGSEGV.  As a result of this we
> print the first instance of the line (as seen above in the example).
>
> Finally we unwind GDB's call stack, the inferior function call is
> complete, and we return to the original handle_signal_stop.  However,
> the stopped_by_random_signal global is still carrying the value as
> computed for the inferior function call's stop, which is why we now
> print a second instance of the line, as seen in the example.
>
> To prevent this, I propose adding a scoped_restore before we start an
> inferior function call.  This will save and restore the global
> stopped_by_random_signal value.
>
> With this done, the output from our example is now this:
>
>  (gdb) list some_func
>   1	int
>   2	some_func ()
>   3	{
>   4	  int *p = 0;
>   5	  return *p;
>   6	}
>   7
>   8	void
>   9	foo ()
>   10	{
>   (gdb) break foo if (some_func ())
>   Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
>   (gdb) r
>   Starting program: /tmp/bpcond
>
>   Program received signal SIGSEGV, Segmentation fault.
>   0x0000000000401116 in some_func () at bpcond.c:5
>   5	  return *p;
>   Error in testing condition for breakpoint 1:
>   The program being debugged stopped while in a function called from GDB.
>   Evaluation of the expression containing the function
>   (some_func) will be abandoned.
>   When the function is done executing, GDB will silently stop.
>
>   Breakpoint 1, 0x0000000000401116 in some_func () at bpcond.c:5
>   5	  return *p;
>   (gdb)
>
> We now only see the 'Program received signal SIGSEGV, ...' line once,
> which I think makes more sense.
>
> Finally, I'm aware that the last few lines, that report the stop as
> being at 'Breakpoint 1', when this is not where the thread is actually
> located anymore, is not great.  I'll address that in the next commit.

I went ahead and pushed this commit.

If there are any problems, please let me know, I'm happy to address any
issues.

Thanks,
Andrew


> ---
>  gdb/infcall.c                              |   9 +
>  gdb/testsuite/gdb.base/infcall-failure.c   |  48 ++++++
>  gdb/testsuite/gdb.base/infcall-failure.exp | 185 +++++++++++++++++++++
>  3 files changed, 242 insertions(+)
>  create mode 100644 gdb/testsuite/gdb.base/infcall-failure.c
>  create mode 100644 gdb/testsuite/gdb.base/infcall-failure.exp
>
> diff --git a/gdb/infcall.c b/gdb/infcall.c
> index 9ed17bf4f8b..e6cc6ed1a21 100644
> --- a/gdb/infcall.c
> +++ b/gdb/infcall.c
> @@ -1293,6 +1293,15 @@ call_function_by_hand_dummy (struct value *function,
>    /* Register a clean-up for unwind_on_terminating_exception_breakpoint.  */
>    SCOPE_EXIT { delete_std_terminate_breakpoint (); };
>  
> +  /* The stopped_by_random_signal variable is global.  If we are here
> +     as part of a breakpoint condition check then the global will have
> +     already been setup as part of the original breakpoint stop.  By
> +     making the inferior call the global will be changed when GDB
> +     handles the stop after the inferior call.  Avoid confusion by
> +     restoring the current value after the inferior call.  */
> +  scoped_restore restore_stopped_by_random_signal
> +    = make_scoped_restore (&stopped_by_random_signal, 0);
> +
>    /* - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP -
>       If you're looking to implement asynchronous dummy-frames, then
>       just below is the place to chop this function in two..  */
> diff --git a/gdb/testsuite/gdb.base/infcall-failure.c b/gdb/testsuite/gdb.base/infcall-failure.c
> new file mode 100644
> index 00000000000..fae012b2cda
> --- /dev/null
> +++ b/gdb/testsuite/gdb.base/infcall-failure.c
> @@ -0,0 +1,48 @@
> +/* Copyright 2022-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/>.  */
> +
> +/* A function that segfaults (assuming that reads of address zero are
> +   prohibited), this is used from within a breakpoint condition.  */
> +int
> +func_segfault ()
> +{
> +  volatile int *p = 0;
> +  return *p;	/* Segfault here.  */
> +}
> +
> +/* A function in which we will place a breakpoint.  This function is itself
> +   then used from within a breakpoint condition.  */
> +int
> +func_bp ()
> +{
> +  int res = 0;	/* Second breakpoint.  */
> +  return res;
> +}
> +
> +int
> +foo ()
> +{
> +  return 0;	/* First breakpoint.  */
> +}
> +
> +int
> +main ()
> +{
> +  int res = foo ();
> +
> +  return res;
> +}
> diff --git a/gdb/testsuite/gdb.base/infcall-failure.exp b/gdb/testsuite/gdb.base/infcall-failure.exp
> new file mode 100644
> index 00000000000..214a64f8de3
> --- /dev/null
> +++ b/gdb/testsuite/gdb.base/infcall-failure.exp
> @@ -0,0 +1,185 @@
> +# Copyright 2022-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/>.
> +
> +# Some simple tests of inferior function calls from breakpoint
> +# conditions, in a single-threaded inferior.
> +#
> +# Test what happens when the inferior function (from a breakpoint
> +# condition) either hits a nested breakpoint, or segfaults.
> +
> +standard_testfile
> +
> +if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
> +	  {debug}] == -1 } {
> +    return
> +}
> +
> +set bp_1_line [gdb_get_line_number "First breakpoint"]
> +set bp_2_line [gdb_get_line_number "Second breakpoint"]
> +set segv_line [gdb_get_line_number "Segfault here"]
> +
> +# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto
> +# main.
> +proc start_gdb_and_runto_main { target_async target_non_stop } {
> +    save_vars { ::GDBFLAGS } {
> +	append ::GDBFLAGS \
> +	    " -ex \"maint set target-non-stop $target_non_stop\""
> +	append ::GDBFLAGS \
> +	    " -ex \"maintenance set target-async ${target_async}\""
> +
> +	clean_restart ${::binfile}
> +    }
> +
> +    if { ![runto_main] } {
> +	return -1
> +    }
> +
> +    return 0
> +}
> +
> +# Start GDB according to ASYNC_P and NON_STOP_P, then setup a
> +# conditional breakpoint.  The breakpoint condition includes an
> +# inferior function call that will itself hit a breakpoint.  Check how
> +# GDB reports this to the user.
> +proc_with_prefix run_cond_hits_breakpoint_test { async_p non_stop_p } {
> +    if { [start_gdb_and_runto_main $async_p $non_stop_p] == -1 } {
> +	return
> +    }
> +
> +    # Setup the conditional breakpoint and record its number.
> +    gdb_breakpoint "${::srcfile}:${::bp_1_line} if (func_bp ())"
> +    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
> +		     "get number of first breakpoint"]
> +
> +    # Setup a breakpoint inside func_bp.
> +    gdb_breakpoint "${::srcfile}:${::bp_2_line}"
> +    set bp_2_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
> +		     "get number of second breakpoint"]
> +
> +    gdb_test "continue" \
> +	[multi_line \
> +	     "Continuing\\." \
> +	     "" \
> +	     "Breakpoint ${bp_2_num}, func_bp \\(\\) at \[^\r\n\]+:${::bp_2_line}" \
> +	     "${::decimal}\\s+\[^\r\n\]+Second breakpoint\[^\r\n\]+" \
> +	     "Error in testing condition for breakpoint ${bp_1_num}:" \
> +	     "The program being debugged stopped while in a function called from GDB\\." \
> +	     "Evaluation of the expression containing the function" \
> +	     "\\(func_bp\\) will be abandoned\\." \
> +	     "When the function is done executing, GDB will silently stop\\." \
> +	     "" \
> +	     "Breakpoint ${bp_1_num}, \[^\r\n\]+" \
> +	     "${::decimal}\\s+\[^\r\n\]+Second breakpoint\[^\r\n\]+"]
> +}
> +
> +# Start GDB according to ASYNC_P and NON_STOP_P, then call an inferior
> +# function.  The inferior function being called will itself have a
> +# breakpoint within it.  Check how GDB reports this to the user.
> +proc_with_prefix run_call_hits_breakpoint_test { async_p non_stop_p } {
> +    if { [start_gdb_and_runto_main $async_p $non_stop_p] == -1 } {
> +	return
> +    }
> +
> +    # Setup a breakpoint inside func_bp.
> +    gdb_breakpoint "${::srcfile}:${::bp_2_line}"
> +    set bp_2_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
> +		      "get number of second breakpoint"]
> +
> +
> +    gdb_test "call func_bp ()" \
> +	[multi_line \
> +	     "" \
> +	     "Breakpoint ${bp_2_num}, func_bp \\(\\) at \[^\r\n\]+:${::bp_2_line}" \
> +	     "${::decimal}\\s+\[^\r\n\]+Second breakpoint\[^\r\n\]+" \
> +	     "The program being debugged stopped while in a function called from GDB\\." \
> +	     "Evaluation of the expression containing the function" \
> +	     "\\(func_bp\\) will be abandoned\\." \
> +	     "When the function is done executing, GDB will silently stop\\."]
> +}
> +
> +# Start GDB according to ASYNC_P and NON_STOP_P, then setup a
> +# conditional breakpoint.  The breakpoint condition includes an
> +# inferior function call that segfaults.  Check how GDB reports this
> +# to the user.
> +proc_with_prefix run_cond_hits_segfault_test { async_p non_stop_p } {
> +    if { [start_gdb_and_runto_main $async_p $non_stop_p] == -1 } {
> +	return
> +    }
> +
> +    # This test relies on the inferior segfaulting when trying to
> +    # access address zero.
> +    if { [is_address_zero_readable] } {
> +	unsupported "address zero is readable"
> +	return
> +    }
> +
> +    # Setup the conditional breakpoint and record its number.
> +    gdb_breakpoint "${::srcfile}:${::bp_1_line} if (func_segfault ())"
> +    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
> +		     "get number of first breakpoint"]
> +
> +    gdb_test "continue" \
> +	[multi_line \
> +	     "Continuing\\." \
> +	     "" \
> +	     "Program received signal SIGSEGV, Segmentation fault\\." \
> +	     "${::hex} in func_segfault \\(\\) at \[^\r\n\]+:${::segv_line}" \
> +	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
> +	     "Error in testing condition for breakpoint ${bp_1_num}:" \
> +	     "The program being debugged stopped while in a function called from GDB\\." \
> +	     "Evaluation of the expression containing the function" \
> +	     "\\(func_segfault\\) will be abandoned\\." \
> +	     "When the function is done executing, GDB will silently stop\\." \
> +	     "" \
> +	     "Breakpoint ${bp_1_num}, \[^\r\n\]+" \
> +	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"]
> +}
> +
> +# Start GDB according to ASYNC_P and NON_STOP_P, then call an inferior
> +# function.  The inferior function will segfault.  Check how GDB
> +# reports this to the user.
> +proc_with_prefix run_call_hits_segfault_test { async_p non_stop_p } {
> +    if { [start_gdb_and_runto_main $async_p $non_stop_p] == -1 } {
> +	return
> +    }
> +
> +    # This test relies on the inferior segfaulting when trying to
> +    # access address zero.
> +    if { [is_address_zero_readable] } {
> +	unsupported "address zero is readable"
> +	return
> +    }
> +
> +    gdb_test "call func_segfault ()" \
> +	[multi_line \
> +	     "" \
> +	     "Program received signal SIGSEGV, Segmentation fault\\." \
> +	     "${::hex} in func_segfault \\(\\) at \[^\r\n\]+:${::segv_line}" \
> +	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
> +	     "The program being debugged stopped while in a function called from GDB\\." \
> +	     "Evaluation of the expression containing the function" \
> +	     "\\(func_segfault\\) will be abandoned\\." \
> +	     "When the function is done executing, GDB will silently stop\\."]
> +}
> +
> +foreach_with_prefix target_async { "on" "off" } {
> +    foreach_with_prefix target_non_stop { "on" "off" } {
> +	run_cond_hits_breakpoint_test $target_async $target_non_stop
> +	run_call_hits_breakpoint_test $target_async $target_non_stop
> +
> +	run_cond_hits_segfault_test $target_async $target_non_stop
> +	run_call_hits_segfault_test $target_async $target_non_stop
> +    }
> +}
> -- 
> 2.25.4


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

* Re: [PATCHv5 05/11] gdb: don't always print breakpoint location after failed condition check
  2023-03-16 17:37         ` [PATCHv5 05/11] gdb: don't always print breakpoint location after failed condition check Andrew Burgess
@ 2023-04-03 13:51           ` Andrew Burgess
  2023-07-07 15:20           ` Pedro Alves
  1 sibling, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-04-03 13:51 UTC (permalink / raw)
  To: gdb-patches

Andrew Burgess <aburgess@redhat.com> writes:

> Consider the following session:
>
>   (gdb) list some_func
>   1	int
>   2	some_func ()
>   3	{
>   4	  int *p = 0;
>   5	  return *p;
>   6	}
>   7
>   8	void
>   9	foo ()
>   10	{
>   (gdb) break foo if (some_func ())
>   Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
>   (gdb) r
>   Starting program: /tmp/bpcond
>
>   Program received signal SIGSEGV, Segmentation fault.
>   0x0000000000401116 in some_func () at bpcond.c:5
>   5	  return *p;
>   Error in testing condition for breakpoint 1:
>   The program being debugged stopped while in a function called from GDB.
>   Evaluation of the expression containing the function
>   (some_func) will be abandoned.
>   When the function is done executing, GDB will silently stop.
>
>   Breakpoint 1, 0x0000000000401116 in some_func () at bpcond.c:5
>   5	  return *p;
>   (gdb)
>
> What happens here is the breakpoint condition includes a call to an
> inferior function, and the inferior function segfaults.  We can see
> that GDB reports the segfault, and then gives an error message that
> indicates that an inferior function call was interrupted.
>
> After this GDB appears to report that it is stopped at Breakpoint 1,
> inside some_func.
>
> I find this second stop report a little confusing.  While it is true
> that GDB stopped as a result of hitting breakpoint 1, I think the
> message GDB currently prints might give the impression that GDB is
> actually stopped at a location of breakpoint 1, which is not the case.
>
> Also, I find the second stop message draws attention away from
> the "Program received signal SIGSEGV, Segmentation fault" stop
> message, and this second stop might be thought of as replacing in
> someway the earlier message.
>
> In short, I think things would be clearer if the second stop message
> were not reported at all, so the output should, I think, look like
> this:
>
>   (gdb) list some_func
>   1	int
>   2	some_func ()
>   3	{
>   4	  int *p = 0;
>   5	  return *p;
>   6	}
>   7
>   8	void
>   9	foo ()
>   10	{
>   (gdb) break foo if (some_func ())
>   Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
>   (gdb) r
>   Starting program: /tmp/bpcond
>
>   Program received signal SIGSEGV, Segmentation fault.
>   0x0000000000401116 in some_func () at bpcond.c:5
>   5	  return *p;
>   Error in testing condition for breakpoint 1:
>   The program being debugged stopped while in a function called from GDB.
>   Evaluation of the expression containing the function
>   (some_func) will be abandoned.
>   When the function is done executing, GDB will silently stop.
>   (gdb)
>
> The user can still find the number of the breakpoint that triggered
> the initial stop in this line:
>
>   Error in testing condition for breakpoint 1:
>
> But there's now only one stop reason reported, the SIGSEGV, which I
> think is much clearer.
>
> To achieve this change I set the bpstat::print field when:
>
>   (a) a breakpoint condition evaluation failed, and
>
>   (b) the $pc of the thread changed during condition evaluation.
>
> I've updated the existing tests that checked the error message printed
> when a breakpoint condition evaluation failed.

I went ahead and pushed this commit.

If there are any problems, please let me know, I'm happy to address any
issues.

Thanks,
Andrew


> ---
>  gdb/breakpoint.c                           | 12 ++++++++++++
>  gdb/testsuite/gdb.base/infcall-failure.exp | 18 ++++++++----------
>  2 files changed, 20 insertions(+), 10 deletions(-)
>
> diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
> index dcd42e6b2e2..445b46a706a 100644
> --- a/gdb/breakpoint.c
> +++ b/gdb/breakpoint.c
> @@ -5534,6 +5534,7 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
>  	  else
>  	    within_current_scope = false;
>  	}
> +      CORE_ADDR pc_before_check = get_frame_pc (get_selected_frame (nullptr));
>        if (within_current_scope)
>  	{
>  	  try
> @@ -5545,6 +5546,17 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
>  	      exception_fprintf (gdb_stderr, ex,
>  				 "Error in testing condition for breakpoint %d:\n",
>  				 b->number);
> +
> +	      /* If the pc value changed as a result of evaluating the
> +		 condition then we probably stopped within an inferior
> +		 function call due to some unexpected stop, e.g. the thread
> +		 hit another breakpoint, or the thread received an
> +		 unexpected signal.  In this case we don't want to also
> +		 print the information about this breakpoint.  */
> +	      CORE_ADDR pc_after_check
> +		= get_frame_pc (get_selected_frame (nullptr));
> +	      if (pc_before_check != pc_after_check)
> +		bs->print = 0;
>  	    }
>  	}
>        else
> diff --git a/gdb/testsuite/gdb.base/infcall-failure.exp b/gdb/testsuite/gdb.base/infcall-failure.exp
> index 214a64f8de3..5ad179a089d 100644
> --- a/gdb/testsuite/gdb.base/infcall-failure.exp
> +++ b/gdb/testsuite/gdb.base/infcall-failure.exp
> @@ -78,10 +78,7 @@ proc_with_prefix run_cond_hits_breakpoint_test { async_p non_stop_p } {
>  	     "The program being debugged stopped while in a function called from GDB\\." \
>  	     "Evaluation of the expression containing the function" \
>  	     "\\(func_bp\\) will be abandoned\\." \
> -	     "When the function is done executing, GDB will silently stop\\." \
> -	     "" \
> -	     "Breakpoint ${bp_1_num}, \[^\r\n\]+" \
> -	     "${::decimal}\\s+\[^\r\n\]+Second breakpoint\[^\r\n\]+"]
> +	     "When the function is done executing, GDB will silently stop\\."]
>  }
>  
>  # Start GDB according to ASYNC_P and NON_STOP_P, then call an inferior
> @@ -138,13 +135,12 @@ proc_with_prefix run_cond_hits_segfault_test { async_p non_stop_p } {
>  	     "${::hex} in func_segfault \\(\\) at \[^\r\n\]+:${::segv_line}" \
>  	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
>  	     "Error in testing condition for breakpoint ${bp_1_num}:" \
> -	     "The program being debugged stopped while in a function called from GDB\\." \
> +	     "The program being debugged was signaled while in a function called from GDB\\." \
> +	     "GDB remains in the frame where the signal was received\\." \
> +	     "To change this behavior use \"set unwindonsignal on\"\\." \
>  	     "Evaluation of the expression containing the function" \
>  	     "\\(func_segfault\\) will be abandoned\\." \
> -	     "When the function is done executing, GDB will silently stop\\." \
> -	     "" \
> -	     "Breakpoint ${bp_1_num}, \[^\r\n\]+" \
> -	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"]
> +	     "When the function is done executing, GDB will silently stop\\."]
>  }
>  
>  # Start GDB according to ASYNC_P and NON_STOP_P, then call an inferior
> @@ -168,7 +164,9 @@ proc_with_prefix run_call_hits_segfault_test { async_p non_stop_p } {
>  	     "Program received signal SIGSEGV, Segmentation fault\\." \
>  	     "${::hex} in func_segfault \\(\\) at \[^\r\n\]+:${::segv_line}" \
>  	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
> -	     "The program being debugged stopped while in a function called from GDB\\." \
> +	     "The program being debugged was signaled while in a function called from GDB\\." \
> +	     "GDB remains in the frame where the signal was received\\." \
> +	     "To change this behavior use \"set unwindonsignal on\"\\." \
>  	     "Evaluation of the expression containing the function" \
>  	     "\\(func_segfault\\) will be abandoned\\." \
>  	     "When the function is done executing, GDB will silently stop\\."]
> -- 
> 2.25.4


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

* [PATCHv6 0/6] Infcalls from B/P conditions in multi-threaded inferiors
  2023-03-16 17:36       ` [PATCHv5 00/11] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                           ` (10 preceding siblings ...)
  2023-03-16 17:37         ` [PATCHv5 11/11] gdb: rename unwindonsignal to unwind-on-signal Andrew Burgess
@ 2023-04-03 14:01         ` Andrew Burgess
  2023-04-03 14:01           ` [PATCHv6 1/6] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
                             ` (6 more replies)
  11 siblings, 7 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-04-03 14:01 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

In v6:

  - Pushed the 5 initial patches.  These were the smaller fixes, and,
    I felt were pretty obvious fixes.  I'm sure folk will raise
    objections if they disagree.

  - Of the remaining patches, #1 to #5 really needs review before they
    can be merged.  Patch #6 is an obvious cleanup once the first five
    have been merged.

  - I've rebased onto current HEAD of master, there's no significant
    changes.

  - All other documentation changes have been reviewed and approved.

In v5:

  - Rebased to current HEAD of master, minor merge conflict resolved.
    No other code or documentation changes.

  - First patch, which was pure documentation, has now been merged.

  - All other documentation changes have been reviewed and approved.

In v4:

  - I believe all the docs changes have been reviewed and approved by Eli,

  - Rebased onto current master,

  - Dropped patch #2 from the V3 series,

  - I have addressed all the issues Baris pointed out, including the
    fixes for the patch #9 ('gdb: add timeouts for inferior function
    calls'), which I forgot to do in V3.

In v3:

  - Updates for review feedback, biggest changes in #10 and #11, but
    minor changes to most patches.

In V2:

  - Rebased onto something closer to HEAD of master,

  - Patches #1, #2, #12, and #13 are new in this series,

  - Patches #3 to #9, and #11 are unchanged since their V1 iteration,

  - Patches #10 has changed slightly in implementation since v1, and
    the docs have been significantly updated.

---

Andrew Burgess (6):
  Revert "gdb: remove unnecessary parameter wait_ptid from
    do_target_wait"
  gdb: fix b/p conditions with infcalls in multi-threaded inferiors
  gdb: add timeouts for inferior function calls
  gdb/remote: avoid SIGINT after calling remote_target::stop
  gdb: introduce unwind-on-timeout setting
  gdb: rename unwindonsignal to unwind-on-signal

 gdb/NEWS                                      |  38 +++
 gdb/breakpoint.c                              |   2 +
 gdb/doc/gdb.texinfo                           | 105 ++++++-
 gdb/gdbthread.h                               |   3 +
 gdb/infcall.c                                 | 296 +++++++++++++++++-
 gdb/infrun.c                                  |  70 ++++-
 gdb/infrun.h                                  |   3 +-
 gdb/remote.c                                  |  10 +
 gdb/testsuite/gdb.base/callfuncs.exp          |   4 +-
 gdb/testsuite/gdb.base/help.exp               |   2 +-
 gdb/testsuite/gdb.base/infcall-failure.exp    |   4 +-
 gdb/testsuite/gdb.base/infcall-timeout.c      |  36 +++
 gdb/testsuite/gdb.base/infcall-timeout.exp    |  98 ++++++
 gdb/testsuite/gdb.base/unwindonsignal.exp     |  36 ++-
 gdb/testsuite/gdb.compile/compile-cplus.exp   |   2 +-
 gdb/testsuite/gdb.compile/compile.exp         |   2 +-
 gdb/testsuite/gdb.cp/gdb2495.exp              |  16 +-
 gdb/testsuite/gdb.fortran/function-calls.exp  |   2 +-
 gdb/testsuite/gdb.mi/mi-syn-frame.exp         |   2 +-
 .../infcall-from-bp-cond-other-thread-event.c | 135 ++++++++
 ...nfcall-from-bp-cond-other-thread-event.exp | 174 ++++++++++
 .../gdb.threads/infcall-from-bp-cond-simple.c |  89 ++++++
 .../infcall-from-bp-cond-simple.exp           | 235 ++++++++++++++
 .../gdb.threads/infcall-from-bp-cond-single.c | 139 ++++++++
 .../infcall-from-bp-cond-single.exp           | 117 +++++++
 .../infcall-from-bp-cond-timeout.c            | 169 ++++++++++
 .../infcall-from-bp-cond-timeout.exp          | 174 ++++++++++
 .../gdb.threads/thread-unwindonsignal.exp     |   8 +-
 28 files changed, 1903 insertions(+), 68 deletions(-)
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.c
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp


base-commit: 2e411b8c68eb2b035b31d5b00d940d4be1a0928b
-- 
2.25.4


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

* [PATCHv6 1/6] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait"
  2023-04-03 14:01         ` [PATCHv6 0/6] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
@ 2023-04-03 14:01           ` Andrew Burgess
  2023-04-03 14:01           ` [PATCHv6 2/6] gdb: fix b/p conditions with infcalls in multi-threaded inferiors Andrew Burgess
                             ` (5 subsequent siblings)
  6 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-04-03 14:01 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

This reverts commit ac0d67ed1dcf470bad6a3bc4800c2ddc9bedecca.

There was nothing wrong with the commit which I'm reverting here, but
it removed some functionality that will be needed for a later commit;
that is, the ability for GDB to ask for events from a specific ptid_t
via the do_target_wait function.

In a follow up commit, this functionality will be used to implement
inferior function calls in multi-threaded inferiors.

This is not a straight revert of the above commit.  Reverting the
above commit replaces a 'nullptr' with 'NULL', I've gone in and
changed that, preserving the 'nullptr'.
---
 gdb/infrun.c | 12 +++++++-----
 1 file changed, 7 insertions(+), 5 deletions(-)

diff --git a/gdb/infrun.c b/gdb/infrun.c
index 8a8439f6da5..b7047ae4c69 100644
--- a/gdb/infrun.c
+++ b/gdb/infrun.c
@@ -3863,7 +3863,8 @@ do_target_wait_1 (inferior *inf, ptid_t ptid,
    more events.  Polls for events from all inferiors/targets.  */
 
 static bool
-do_target_wait (execution_control_state *ecs, target_wait_flags options)
+do_target_wait (ptid_t wait_ptid, execution_control_state *ecs,
+		target_wait_flags options)
 {
   int num_inferiors = 0;
   int random_selector;
@@ -3873,9 +3874,10 @@ do_target_wait (execution_control_state *ecs, target_wait_flags options)
      polling the rest of the inferior list starting from that one in a
      circular fashion until the whole list is polled once.  */
 
-  auto inferior_matches = [] (inferior *inf)
+  auto inferior_matches = [&wait_ptid] (inferior *inf)
     {
-      return inf->process_target () != nullptr;
+      return (inf->process_target () != nullptr
+	      && ptid_t (inf->pid).matches (wait_ptid));
     };
 
   /* First see how many matching inferiors we have.  */
@@ -3914,7 +3916,7 @@ do_target_wait (execution_control_state *ecs, target_wait_flags options)
 
   auto do_wait = [&] (inferior *inf)
   {
-    ecs->ptid = do_target_wait_1 (inf, minus_one_ptid, &ecs->ws, options);
+    ecs->ptid = do_target_wait_1 (inf, wait_ptid, &ecs->ws, options);
     ecs->target = inf->process_target ();
     return (ecs->ws.kind () != TARGET_WAITKIND_IGNORE);
   };
@@ -4344,7 +4346,7 @@ fetch_inferior_event ()
        the event.  */
     scoped_disable_commit_resumed disable_commit_resumed ("handling event");
 
-    if (!do_target_wait (&ecs, TARGET_WNOHANG))
+    if (!do_target_wait (minus_one_ptid, &ecs, TARGET_WNOHANG))
       {
 	infrun_debug_printf ("do_target_wait returned no event");
 	disable_commit_resumed.reset_and_commit ();
-- 
2.25.4


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

* [PATCHv6 2/6] gdb: fix b/p conditions with infcalls in multi-threaded inferiors
  2023-04-03 14:01         ` [PATCHv6 0/6] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
  2023-04-03 14:01           ` [PATCHv6 1/6] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
@ 2023-04-03 14:01           ` Andrew Burgess
  2023-04-03 14:01           ` [PATCHv6 3/6] gdb: add timeouts for inferior function calls Andrew Burgess
                             ` (4 subsequent siblings)
  6 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-04-03 14:01 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Natalia Saiapova, Tankut Baris Aktemur

This commit fixes bug PR 28942, that is, creating a conditional
breakpoint in a multi-threaded inferior, where the breakpoint
condition includes an inferior function call.

Currently, when a user tries to create such a breakpoint, then GDB
will fail with:

  (gdb) break infcall-from-bp-cond-single.c:61 if (return_true ())
  Breakpoint 2 at 0x4011fa: file /tmp/build/gdb/testsuite/../../../src/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c, line 61.
  (gdb) continue
  Continuing.
  [New Thread 0x7ffff7c5d700 (LWP 2460150)]
  [New Thread 0x7ffff745c700 (LWP 2460151)]
  [New Thread 0x7ffff6c5b700 (LWP 2460152)]
  [New Thread 0x7ffff645a700 (LWP 2460153)]
  [New Thread 0x7ffff5c59700 (LWP 2460154)]
  Error in testing breakpoint condition:
  Couldn't get registers: No such process.
  An error occurred while in a function called from GDB.
  Evaluation of the expression containing the function
  (return_true) will be abandoned.
  When the function is done executing, GDB will silently stop.
  Selected thread is running.
  (gdb)

Or, in some cases, like this:

  (gdb) break infcall-from-bp-cond-simple.c:56 if (is_matching_tid (arg, 1))
  Breakpoint 2 at 0x401194: file /tmp/build/gdb/testsuite/../../../src/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c, line 56.
  (gdb) continue
  Continuing.
  [New Thread 0x7ffff7c5d700 (LWP 2461106)]
  [New Thread 0x7ffff745c700 (LWP 2461107)]
  ../../src.release/gdb/nat/x86-linux-dregs.c:146: internal-error: x86_linux_update_debug_registers: Assertion `lwp_is_stopped (lwp)' failed.
  A problem internal to GDB has been detected,
  further debugging may prove unreliable.

The precise error depends on the exact thread state; so there's race
conditions depending on which threads have fully started, and which
have not.  But the underlying problem is always the same; when GDB
tries to execute the inferior function call from within the breakpoint
condition, GDB will, incorrectly, try to resume threads that are
already running - GDB doesn't realise that some threads might already
be running.

The solution proposed in this patch requires an additional member
variable thread_info::in_cond_eval.  This flag is set to true (in
breakpoint.c) when GDB is evaluating a breakpoint condition.

In user_visible_resume_ptid (infrun.c), when the in_cond_eval flag is
true, then GDB will only try to resume the current thread, that is,
the thread for which the breakpoint condition is being evaluated.
This solves the problem of GDB trying to resume threads that are
already running.

The next problem is that inferior function calls are assumed to be
synchronous, that is, GDB doesn't expect to start an inferior function
call in thread #1, then receive a stop from thread #2 for some other,
unrelated reason.  To prevent GDB responding to an event from another
thread, we update fetch_inferior_event and do_target_wait in infrun.c,
so that, when an inferior function call (on behalf of a breakpoint
condition) is in progress, we only wait for events from the current
thread (the one evaluating the condition).

In do_target_wait I had to change the inferior_matches lambda
function, which is used to select which inferior to wait on.
Previously the logic was this:

   auto inferior_matches = [&wait_ptid] (inferior *inf)
     {
       return (inf->process_target () != nullptr
               && ptid_t (inf->pid).matches (wait_ptid));
     };

This compares the pid of the inferior against the complete ptid we
want to wait on.  Before this commit wait_ptid was only ever
minus_one_ptid (which is special, and means any process), and so every
inferior would match.

After this commit though wait_ptid might represent a specific thread
in a specific inferior.  If we compare the pid of the inferior to a
specific ptid then these will not match.  The fix is to compare
against the pid extracted from the wait_ptid, not against the complete
wait_ptid itself.

In fetch_inferior_event, after receiving the event, we only want to
stop all the other threads, and call inferior_event_handler with
INF_EXEC_COMPLETE, if we are not evaluating a conditional breakpoint.
If we are, then all the other threads should be left doing whatever
they were before.  The inferior_event_handler call will be performed
once the breakpoint condition has finished being evaluated, and GDB
decides to stop or not.

The final problem that needs solving relates to GDB's commit-resume
mechanism, which allows GDB to collect resume requests into a single
packet in order to reduce traffic to a remote target.

The problem is that the commit-resume mechanism will not send any
resume requests for an inferior if there are already events pending on
the GDB side.

Imagine an inferior with two threads.  Both threads hit a breakpoint,
maybe the same conditional breakpoint.  At this point there are two
pending events, one for each thread.

GDB selects one of the events and spots that this is a conditional
breakpoint, GDB evaluates the condition.

The condition includes an inferior function call, so GDB sets up for
the call and resumes the one thread, the resume request is added to
the commit-resume queue.

When the commit-resume queue is committed GDB sees that there is a
pending event from another thread, and so doesn't send any resume
requests to the actual target, GDB is assuming that when we wait we
will select the event from the other thread.

However, as this is an inferior function call for a condition
evaluation, we will not select the event from the other thread, we
only care about events from the thread that is evaluating the
condition - and the resume for this thread was never sent to the
target.

And so, GDB hangs, waiting for an event from a thread that was never
fully resumed.

To fix this issue I have added the concept of "forcing" the
commit-resume queue.  When enabling commit resume, if the force flag
is true, then any resumes will be committed to the target, even if
there are other threads with pending events.

A note on authorship: this patch was based on some work done by
Natalia Saiapova and Tankut Baris Aktemur from Intel[1].  I have made
some changes to their work in this version.

Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=28942

[1] https://sourceware.org/pipermail/gdb-patches/2020-October/172454.html

Co-authored-by: Natalia Saiapova <natalia.saiapova@intel.com>
Co-authored-by: Tankut Baris Aktemur <tankut.baris.aktemur@intel.com>
---
 gdb/breakpoint.c                              |   2 +
 gdb/gdbthread.h                               |   3 +
 gdb/infcall.c                                 |   6 +
 gdb/infrun.c                                  |  64 +++--
 gdb/infrun.h                                  |   3 +-
 .../infcall-from-bp-cond-other-thread-event.c | 135 ++++++++++
 ...nfcall-from-bp-cond-other-thread-event.exp | 174 +++++++++++++
 .../gdb.threads/infcall-from-bp-cond-simple.c |  89 +++++++
 .../infcall-from-bp-cond-simple.exp           | 235 ++++++++++++++++++
 .../gdb.threads/infcall-from-bp-cond-single.c | 139 +++++++++++
 .../infcall-from-bp-cond-single.exp           | 117 +++++++++
 11 files changed, 952 insertions(+), 15 deletions(-)
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index ebe97940f54..e159a4b6ed5 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -5539,6 +5539,8 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
 	{
 	  try
 	    {
+	      scoped_restore reset_in_cond_eval
+		= make_scoped_restore (&thread->control.in_cond_eval, true);
 	      condition_result = breakpoint_cond_eval (cond);
 	    }
 	  catch (const gdb_exception_error &ex)
diff --git a/gdb/gdbthread.h b/gdb/gdbthread.h
index 848daa94410..455eeb8193d 100644
--- a/gdb/gdbthread.h
+++ b/gdb/gdbthread.h
@@ -171,6 +171,9 @@ struct thread_control_state
      command.  This is used to decide whether "set scheduler-locking
      step" behaves like "on" or "off".  */
   int stepping_command = 0;
+
+  /* True if the thread is evaluating a BP condition.  */
+  bool in_cond_eval = false;
 };
 
 /* Inferior thread specific part of `struct infcall_suspend_state'.  */
diff --git a/gdb/infcall.c b/gdb/infcall.c
index e6cc6ed1a21..4fb8ab07db0 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -641,6 +641,12 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
 
       proceed (real_pc, GDB_SIGNAL_0);
 
+      /* Enable commit resume, but pass true for the force flag.  This
+	 ensures any thread we set running in proceed will actually be
+	 committed to the target, even if some other thread in the current
+	 target has a pending event.  */
+      scoped_enable_commit_resumed enable ("infcall", true);
+
       infrun_debug_show_threads ("non-exited threads after proceed for inferior-call",
 				 all_non_exited_threads ());
 
diff --git a/gdb/infrun.c b/gdb/infrun.c
index b7047ae4c69..49eb1a2d128 100644
--- a/gdb/infrun.c
+++ b/gdb/infrun.c
@@ -2269,6 +2269,14 @@ user_visible_resume_ptid (int step)
 	 mode.  */
       resume_ptid = inferior_ptid;
     }
+  else if (inferior_ptid != null_ptid
+	   && inferior_thread ()->control.in_cond_eval)
+    {
+      /* The inferior thread is evaluating a BP condition.  Other threads
+	 might be stopped or running and we do not want to change their
+	 state, thus, resume only the current thread.  */
+      resume_ptid = inferior_ptid;
+    }
   else if (!sched_multi && target_supports_multi_process ())
     {
       /* Resume all threads of the current process (and none of other
@@ -2986,12 +2994,24 @@ schedlock_applies (struct thread_info *tp)
 					    execution_direction)));
 }
 
-/* Set process_stratum_target::COMMIT_RESUMED_STATE in all target
-   stacks that have threads executing and don't have threads with
-   pending events.  */
+/* When FORCE_P is false, set process_stratum_target::COMMIT_RESUMED_STATE
+   in all target stacks that have threads executing and don't have threads
+   with pending events.
+
+   When FORCE_P is true, set process_stratum_target::COMMIT_RESUMED_STATE
+   in all target stacks that have threads executing regardless of whether
+   there are pending events or not.
+
+    Passing FORCE_P as false makes sense when GDB is going to wait for
+    events from all threads and will therefore spot the pending events.
+    However, if GDB is only going to wait for events from select threads
+    (i.e. when performing an inferior call) then a pending event on some
+    other thread will not be spotted, and if we fail to commit the resume
+    state for the thread performing the inferior call, then the inferior
+    call will never complete (or even start).  */
 
 static void
-maybe_set_commit_resumed_all_targets ()
+maybe_set_commit_resumed_all_targets (bool force_p)
 {
   scoped_restore_current_thread restore_thread;
 
@@ -3020,7 +3040,7 @@ maybe_set_commit_resumed_all_targets ()
 	 status to report, handle it before requiring the target to
 	 commit its resumed threads: handling the status might lead to
 	 resuming more threads.  */
-      if (proc_target->has_resumed_with_pending_wait_status ())
+      if (!force_p && proc_target->has_resumed_with_pending_wait_status ())
 	{
 	  infrun_debug_printf ("not requesting commit-resumed for target %s, a"
 			       " thread has a pending waitstatus",
@@ -3030,7 +3050,7 @@ maybe_set_commit_resumed_all_targets ()
 
       switch_to_inferior_no_thread (inf);
 
-      if (target_has_pending_events ())
+      if (!force_p && target_has_pending_events ())
 	{
 	  infrun_debug_printf ("not requesting commit-resumed for target %s, "
 			       "target has pending events",
@@ -3123,7 +3143,7 @@ scoped_disable_commit_resumed::reset ()
     {
       /* This is the outermost instance, re-enable
 	 COMMIT_RESUMED_STATE on the targets where it's possible.  */
-      maybe_set_commit_resumed_all_targets ();
+      maybe_set_commit_resumed_all_targets (false);
     }
   else
     {
@@ -3156,7 +3176,7 @@ scoped_disable_commit_resumed::reset_and_commit ()
 /* See infrun.h.  */
 
 scoped_enable_commit_resumed::scoped_enable_commit_resumed
-  (const char *reason)
+  (const char *reason, bool force_p)
   : m_reason (reason),
     m_prev_enable_commit_resumed (enable_commit_resumed)
 {
@@ -3168,7 +3188,7 @@ scoped_enable_commit_resumed::scoped_enable_commit_resumed
 
       /* Re-enable COMMIT_RESUMED_STATE on the targets where it's
 	 possible.  */
-      maybe_set_commit_resumed_all_targets ();
+      maybe_set_commit_resumed_all_targets (force_p);
 
       maybe_call_commit_resumed_all_targets ();
     }
@@ -3874,10 +3894,11 @@ do_target_wait (ptid_t wait_ptid, execution_control_state *ecs,
      polling the rest of the inferior list starting from that one in a
      circular fashion until the whole list is polled once.  */
 
-  auto inferior_matches = [&wait_ptid] (inferior *inf)
+  ptid_t wait_ptid_pid {wait_ptid.pid ()};
+  auto inferior_matches = [&wait_ptid_pid] (inferior *inf)
     {
       return (inf->process_target () != nullptr
-	      && ptid_t (inf->pid).matches (wait_ptid));
+	      && ptid_t (inf->pid).matches (wait_ptid_pid));
     };
 
   /* First see how many matching inferiors we have.  */
@@ -4346,7 +4367,17 @@ fetch_inferior_event ()
        the event.  */
     scoped_disable_commit_resumed disable_commit_resumed ("handling event");
 
-    if (!do_target_wait (minus_one_ptid, &ecs, TARGET_WNOHANG))
+    /* Is the current thread performing an inferior function call as part
+       of a breakpoint condition evaluation?  */
+    bool in_cond_eval = (inferior_ptid != null_ptid
+			 && inferior_thread ()->control.in_cond_eval);
+
+    /* If the thread is in the middle of the condition evaluation, wait for
+       an event from the current thread.  Otherwise, wait for an event from
+       any thread.  */
+    ptid_t waiton_ptid = in_cond_eval ? inferior_ptid : minus_one_ptid;
+
+    if (!do_target_wait (waiton_ptid, &ecs, TARGET_WNOHANG))
       {
 	infrun_debug_printf ("do_target_wait returned no event");
 	disable_commit_resumed.reset_and_commit ();
@@ -4398,7 +4429,12 @@ fetch_inferior_event ()
 	    bool should_notify_stop = true;
 	    bool proceeded = false;
 
-	    stop_all_threads_if_all_stop_mode ();
+	    /* If the thread that stopped just completed an inferior
+	       function call as part of a condition evaluation, then we
+	       don't want to stop all the other threads.  */
+	    if (ecs.event_thread == nullptr
+		|| !ecs.event_thread->control.in_cond_eval)
+	      stop_all_threads_if_all_stop_mode ();
 
 	    clean_up_just_stopped_threads_fsms (&ecs);
 
@@ -4413,7 +4449,7 @@ fetch_inferior_event ()
 		  proceeded = normal_stop ();
 	      }
 
-	    if (!proceeded)
+	    if (!proceeded && !in_cond_eval)
 	      {
 		inferior_event_handler (INF_EXEC_COMPLETE);
 		cmd_done = 1;
diff --git a/gdb/infrun.h b/gdb/infrun.h
index 9b3c8962939..d5952e194d7 100644
--- a/gdb/infrun.h
+++ b/gdb/infrun.h
@@ -399,7 +399,8 @@ extern void maybe_call_commit_resumed_all_targets ();
 
 struct scoped_enable_commit_resumed
 {
-  explicit scoped_enable_commit_resumed (const char *reason);
+  explicit scoped_enable_commit_resumed (const char *reason,
+					 bool force_p = false);
   ~scoped_enable_commit_resumed ();
 
   DISABLE_COPY_AND_ASSIGN (scoped_enable_commit_resumed);
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
new file mode 100644
index 00000000000..e2a8ccb4ebe
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
@@ -0,0 +1,135 @@
+/* Copyright 2022-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 <pthread.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <sched.h>
+
+#define NUM_THREADS 2
+
+pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+
+/* Some global variables to poke, just for something to do.  */
+volatile int global_var_0 = 0;
+volatile int global_var_1 = 0;
+
+/* This flag is updated from GDB.  */
+volatile int raise_signal = 0;
+
+/* Implement the breakpoint condition function.  Release the other thread
+   and try to give the other thread a chance to run.  Then return ANSWER.  */
+int
+condition_core_func (int answer)
+{
+  /* This unlock should release the other thread.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  /* And this yield and sleep should (hopefully) give the other thread a
+     chance to run.  This isn't guaranteed of course, but once the other
+     thread does run it should hit a breakpoint, which GDB should
+     (temporarily) ignore, so there's no easy way for us to know the other
+     thread has done what it needs to, thus, yielding and sleeping is the
+     best we can do.  */
+  sched_yield ();
+  sleep (2);
+
+  return answer;
+}
+
+void
+stop_marker ()
+{
+  int a = 100;	/* Final breakpoint here.  */
+}
+
+/* A breakpoint condition function that always returns true.  */
+int
+condition_true_func ()
+{
+  return condition_core_func (1);
+}
+
+/* A breakpoint condition function that always returns false.  */
+int
+condition_false_func ()
+{
+  return condition_core_func (0);
+}
+
+void *
+worker_func (void *arg)
+{
+  volatile int *ptr = 0;
+  int tid = *((int *) arg);
+
+  switch (tid)
+    {
+    case 0:
+      global_var_0 = 11;	/* First thread breakpoint.  */
+      break;
+
+    case 1:
+      if (pthread_mutex_lock (&mutex) != 0)
+	abort ();
+      if (raise_signal)
+	global_var_1 = *ptr;	/* Signal here.  */
+      else
+	global_var_1 = 99;	/* Other thread breakpoint.  */
+      break;
+
+    default:
+      abort ();
+    }
+
+  return NULL;
+}
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+
+  /* Set an alarm, just in case the test deadlocks.  */
+  alarm (300);
+
+  /* We want the mutex to start locked.  */
+  if (pthread_mutex_lock (&mutex) != 0)
+    abort ();
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      void *retval;
+      pthread_join (threads[i], &retval);
+    }
+
+  /* Unlock once we're done, just for cleanliness.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
new file mode 100644
index 00000000000..6d4e1e13ab2
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
@@ -0,0 +1,174 @@
+# Copyright 2022-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/>.
+
+# Test for conditional breakpoints where the breakpoint condition includes
+# an inferior function call.
+#
+# The tests in this script are testing what happens when an event arrives in
+# another thread while GDB is waiting for the inferior function call (in the
+# breakpoint condition) to finish.
+#
+# The expectation is that GDB will queue events for other threads and wait
+# for the inferior function call to complete, if the condition is true, then
+# the conditional breakpoint should be reported first.  The other thread
+# event should of course, not get lost, and should be reported as soon as
+# the user tries to continue the inferior.
+#
+# If the conditional breakpoint ends up not being taken (the condition is
+# false), then the other thread event should be reported immediately.
+#
+# This script tests what happens when the other thread event is (a) the
+# other thread hitting a breakpoint, and (b) the other thread taking a
+# signal (SIGSEGV in this case).
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] == -1 } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "First thread breakpoint"]
+set other_bp_line [gdb_get_line_number "Other thread breakpoint"]
+set final_bp_line [gdb_get_line_number "Final breakpoint here"]
+set signal_line [gdb_get_line_number "Signal here"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if { ![runto_main] } {
+	return -1
+    }
+
+    return 0
+}
+
+# Run a test of GDB's conditional breakpoints, where the conditions include
+# inferior function calls.  While the inferior function call is executing
+# another thread will hit a breakpoint (when OTHER_THREAD_SIGNAL is false),
+# or receive a signal (when OTHER_THREAD_SIGNAL is true).  GDB should report
+# the conditional breakpoint first (if the condition is true), and then
+# report the second thread event once the inferior is continued again.
+#
+# When STOP_AT_COND is true then the conditional breakpoint will have a
+# condition that evaluates to true (and the GDB will stop at the
+# breakpoint), otherwise, the condition will evaluate to false (and GDB will
+# not stop at the breakpoint).
+proc run_condition_test { stop_at_cond other_thread_signal \
+			      target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint.
+    if { $stop_at_cond } {
+	set cond_func "condition_true_func"
+    } else {
+	set cond_func "condition_false_func"
+    }
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (${cond_func} ())"
+    set cond_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			"get number for conditional breakpoint"]
+
+    if { $other_thread_signal } {
+	# Arrange for the other thread to raise a signal while GDB is
+	# evaluating the breakpoint condition.
+	gdb_test_no_output "set raise_signal = 1"
+    } else {
+	# And a breakpoint that will be hit by another thread only once the
+	# breakpoint condition starts to be evaluated.
+	gdb_breakpoint "${::srcfile}:${::other_bp_line}"
+	set other_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			      "get number for other breakpoint"]
+    }
+
+    # A final breakpoint once the test has completed.
+    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
+    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			  "get number for final breakpoint"]
+
+    if { $stop_at_cond } {
+	# Continue.  The first breakpoint we hit should be the conditional
+	# breakpoint.  The other thread will have hit its breakpoint, but
+	# that will have been deferred until the conditional breakpoint is
+	# reported.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${cond_bp_num}, worker_func \[^\r\n\]+:${::cond_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+First thread breakpoint\[^\r\n\]+"] \
+	    "hit the conditional breakpoint"
+    }
+
+    if { $other_thread_signal } {
+	# Now continue again, the other thread will now report that it
+	# received a signal.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" received signal SIGSEGV, Segmentation fault\\." \
+		 "\\\[Switching to Thread \[^\r\n\]+\\\]" \
+		 "${::hex} in worker_func \[^\r\n\]+:${::signal_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Signal here\[^\r\n\]+"] \
+	    "received signal in other thread"
+    } else {
+	# Now continue again, the other thread will now report its
+	# breakpoint.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${other_bp_num}, worker_func \[^\r\n\]+:${::other_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Other thread breakpoint\[^\r\n\]+"] \
+	    "hit the breakpoint in other thread"
+
+	# Run to the stop marker.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${final_bp_num}, stop_marker \[^\r\n\]+:${::final_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Final breakpoint here\[^\r\n\]+"] \
+	    "hit the final breakpoint"
+    }
+
+    gdb_exit
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	foreach_with_prefix other_thread_signal { true false } {
+	    foreach_with_prefix stop_at_cond { true false } {
+		run_condition_test $stop_at_cond $other_thread_signal \
+		    $target_async $target_non_stop
+	    }
+	}
+    }
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
new file mode 100644
index 00000000000..9d746d8be49
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
@@ -0,0 +1,89 @@
+/* Copyright 2022-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 <pthread.h>
+#include <unistd.h>
+
+#define NUM_THREADS 3
+
+int
+is_matching_tid (int *tid_ptr, int tid_value)
+{
+  return *tid_ptr == tid_value;
+}
+
+int
+return_true ()
+{
+  return 1;
+}
+
+int
+return_false ()
+{
+  return 0;
+}
+
+int
+function_that_segfaults ()
+{
+  int *p = 0;
+  *p = 1;	/* Segfault happens here.   */
+}
+
+int
+function_with_breakpoint ()
+{
+  return 1;	/* Nested breakpoint.  */
+}
+
+void *
+worker_func (void *arg)
+{
+  int a = 42;	/* Breakpoint here.  */
+}
+
+void
+stop_marker ()
+{
+  int b = 99;	/* Stop marker.  */
+}
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+
+  alarm (300);
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      void *retval;
+      pthread_join (threads[i], &retval);
+    }
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
new file mode 100644
index 00000000000..37e1b64d9a4
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
@@ -0,0 +1,235 @@
+# Copyright 2022-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/>.
+
+# Some simple tests of inferior function calls from breakpoint
+# conditions, in multi-threaded inferiors.
+#
+# This test sets up a multi-threaded inferior, and places a breakpoint
+# at a location that many of the threads will reach.  We repeat the
+# test with different conditions, sometimes a single thread should
+# stop at the breakpoint, sometimes multiple threads should stop, and
+# sometime no threads should stop.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] == -1 } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "Breakpoint here"]
+set stop_bp_line [gdb_get_line_number "Stop marker"]
+set nested_bp_line [gdb_get_line_number "Nested breakpoint"]
+set segv_line [gdb_get_line_number "Segfault happens here"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if { ![runto_main] } {
+	return -1
+    }
+
+    return 0
+}
+
+# Run a test of GDB's conditional breakpoints, where the conditions include
+# inferior function calls.
+#
+# CONDITION is the expression to be used as the breakpoint condition.
+#
+# N_EXPECTED_HITS is the number of threads that we expect to stop due to
+# CONDITON.
+#
+# MESSAGE is used as a test name prefix.
+proc run_condition_test { message n_expected_hits condition \
+			      target_async target_non_stop } {
+    with_test_prefix $message {
+
+	if { [start_gdb_and_runto_main $target_async \
+		  $target_non_stop] == -1 } {
+	    return
+	}
+
+	# Use this convenience variable to track how often the
+	# breakpoint condition has been evaluated.  This should be
+	# once per thread.
+	gdb_test "set \$n_cond_eval = 0"
+
+	# Setup the conditional breakpoint.
+	gdb_breakpoint \
+	    "${::srcfile}:${::cond_bp_line} if ((++\$n_cond_eval) && (${condition}))"
+
+	# And a breakpoint that we hit when the test is over, this one is
+	# not conditional.  Only the main thread gets here once all the
+	# other threads have finished.
+	gdb_breakpoint "${::srcfile}:${::stop_bp_line}"
+
+	# The number of times we stop at the conditional breakpoint.
+	set n_hit_condition 0
+
+	# Now keep 'continue'-ing GDB until all the threads have finished
+	# and we reach the stop_marker breakpoint.
+	gdb_test_multiple "continue" "spot all breakpoint hits" {
+	    -re " worker_func \[^\r\n\]+${::srcfile}:${::cond_bp_line}\r\n${::decimal}\\s+\[^\r\n\]+Breakpoint here\[^\r\n\]+\r\n${::gdb_prompt} $" {
+		incr n_hit_condition
+		send_gdb "continue\n"
+		exp_continue
+	    }
+
+	    -re " stop_marker \[^\r\n\]+${::srcfile}:${::stop_bp_line}\r\n${::decimal}\\s+\[^\r\n\]+Stop marker\[^\r\n\]+\r\n${::gdb_prompt} $" {
+		pass $gdb_test_name
+	    }
+	}
+
+	gdb_assert { $n_hit_condition == $n_expected_hits } \
+	    "stopped at breakpoint the expected number of times"
+
+	# Ensure the breakpoint condition was evaluated once per thread.
+	gdb_test "print \$n_cond_eval" "= 3" \
+	    "condition was evaluated in each thread"
+    }
+}
+
+# Check that after handling a conditional breakpoint (where the condition
+# includes an inferior call), it is still possible to kill the running
+# inferior, and then restart the inferior.
+#
+# At once point doing this would result in GDB giving an assertion error.
+proc_with_prefix run_kill_and_restart_test { target_async target_non_stop } {
+    # This test relies on the 'start' command, which is not possible with
+    # the plain 'remote' target.
+    if { [target_info gdb_protocol] == "remote" } {
+	return
+    }
+
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint.
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 1))"
+    gdb_continue_to_breakpoint "worker_func"
+
+    # Now kill the program being debugged.
+    gdb_test "kill" "" "kill process" \
+	"Kill the program being debugged.*y or n. $" "y"
+
+    # Check we can restart the inferior.  At one point this would trigger an
+    # assertion.
+    gdb_test "start" ".*"
+}
+
+# Create a conditional breakpoint which includes a call to a function that
+# segfaults.  Run GDB and check what happens when the inferior segfaults
+# during the inferior call.
+proc_with_prefix run_bp_cond_segfaults { target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # This test relies on the inferior segfaulting when trying to
+    # access address zero.
+    if { [is_address_zero_readable] } {
+	return
+    }
+
+    # Setup the conditional breakpoint, include a call to
+    # 'function_that_segfaults', which triggers the segfault.
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 0) && function_that_segfaults ())"
+    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of conditional breakpoint"]
+
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     ".*" \
+	     "Thread ${::decimal} \"infcall-from-bp\" received signal SIGSEGV, Segmentation fault\\." \
+	     "${::hex} in function_that_segfaults \\(\\) at \[^\r\n\]+:${::segv_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Segfault happens here\[^\r\n\]+" \
+	     "Error in testing condition for breakpoint ${bp_1_num}:" \
+	     "The program being debugged was signaled while in a function called from GDB\\." \
+	     "GDB remains in the frame where the signal was received\\." \
+	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(function_that_segfaults\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+}
+
+# Create a conditional breakpoint which includes a call to a function that
+# itself has a breakpoint set within it.  Run GDB and check what happens
+# when GDB hits the nested breakpoint.
+proc_with_prefix run_bp_cond_hits_breakpoint { target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint, include a call to
+    # 'function_with_breakpoint' in which we will shortly place a
+    # breakpoint.
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 0) && function_with_breakpoint ())"
+    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of conditional breakpoint"]
+
+    gdb_breakpoint "${::srcfile}:${::nested_bp_line}"
+    set bp_2_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of nested breakpoint"]
+
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     ".*" \
+	     "Thread ${::decimal} \"infcall-from-bp\" hit Breakpoint ${bp_2_num}, function_with_breakpoint \\(\\) at \[^\r\n\]+:${::nested_bp_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Nested breakpoint\[^\r\n\]+" \
+	     "Error in testing condition for breakpoint ${bp_1_num}:" \
+	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(function_with_breakpoint\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	run_condition_test "exactly one thread is hit" \
+	    1 "is_matching_tid (arg, 1)" \
+	    $target_async $target_non_stop
+	run_condition_test "exactly two threads are hit" \
+	    2 "(is_matching_tid (arg, 0) || is_matching_tid (arg, 2))" \
+	    $target_async $target_non_stop
+	run_condition_test "all three threads are hit" \
+	    3 "return_true ()" \
+	    $target_async $target_non_stop
+	run_condition_test "no thread is hit" \
+	    0 "return_false ()" \
+	    $target_async $target_non_stop
+
+	run_kill_and_restart_test $target_async $target_non_stop
+	run_bp_cond_segfaults $target_async $target_non_stop
+	run_bp_cond_hits_breakpoint $target_async $target_non_stop
+    }
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
new file mode 100644
index 00000000000..835c72f03cf
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
@@ -0,0 +1,139 @@
+/* Copyright 2022-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 <pthread.h>
+#include <unistd.h>
+#include <semaphore.h>
+#include <stdlib.h>
+
+#define NUM_THREADS 5
+
+/* Semaphores, used to track when threads have started, and to control
+   when the threads finish.  */
+sem_t startup_semaphore;
+sem_t finish_semaphore;
+
+/* Mutex to control when the first worker thread hit a breakpoint
+   location.  */
+pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+
+/* Global variable to poke, just so threads have something to do.  */
+volatile int global_var = 0;
+
+int
+return_true ()
+{
+  return 1;
+}
+
+int
+return_false ()
+{
+  return 0;
+}
+
+void *
+worker_func (void *arg)
+{
+  int tid = *((int *) arg);
+
+  switch (tid)
+    {
+    case 0:
+      /* Wait for MUTEX to become available, then pass through the
+	 conditional breakpoint location.  */
+      if (pthread_mutex_lock (&mutex) != 0)
+	abort ();
+      global_var = 99;	/* Conditional breakpoint here.  */
+      if (pthread_mutex_unlock (&mutex) != 0)
+	abort ();
+      break;
+
+    default:
+      /* Notify the main thread that the thread has started, then wait for
+	 the main thread to tell us to finish.  */
+      sem_post (&startup_semaphore);
+      if (sem_wait (&finish_semaphore) != 0)
+	abort ();
+      break;
+    }
+}
+
+void
+stop_marker ()
+{
+  global_var = 99;	/* Stop marker.  */
+}
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+  void *retval;
+
+  /* An alarm, just in case the thread deadlocks.  */
+  alarm (300);
+
+  /* Semaphore initialization.  */
+  if (sem_init (&startup_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&finish_semaphore, 0, 0) != 0)
+    abort ();
+
+  /* Lock MUTEX, this prevents the first worker thread from rushing ahead.  */
+  if (pthread_mutex_lock (&mutex) != 0)
+    abort ();
+
+  /* Worker thread creation.  */
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  /* Wait for every thread (other than the first) to tell us it has started
+     up.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    {
+      if (sem_wait (&startup_semaphore) != 0)
+	abort ();
+    }
+
+  /* Unlock the first thread so it can proceed.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  /* Wait for the first thread only.  */
+  pthread_join (threads[0], &retval);
+
+  /* Now post FINISH_SEMAPHORE to allow all the other threads to finish.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    sem_post (&finish_semaphore);
+
+  /* Now wait for the remaining threads to complete.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    pthread_join (threads[i], &retval);
+
+  /* Semaphore cleanup.  */
+  sem_destroy (&finish_semaphore);
+  sem_destroy (&startup_semaphore);
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
new file mode 100644
index 00000000000..787dee3aa8e
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
@@ -0,0 +1,117 @@
+# Copyright 2022-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 reprocuces bug gdb/28942, performing an inferior function
+# call from a breakpoint condition in a multi-threaded inferior.
+#
+# The important part of this test is that, when the conditional
+# breakpoint is hit, and the condition (which includes an inferior
+# function call) is evaluated, the other threads are running.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] == -1 } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "Conditional breakpoint here"]
+set final_bp_line [gdb_get_line_number "Stop marker"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if { ![runto_main] } {
+	return -1
+    }
+
+    return 0
+}
+
+# Run a test of GDB's conditional breakpoints, where the conditions include
+# inferior function calls.
+#
+# TARGET_ASYNC and TARGET_NON_STOP are used when starting up GDB.
+#
+# When STOP_AT_COND is true the breakpoint condtion will evaluate to
+# true, and GDB will stop at the breakpoint.  Otherwise, the
+# breakpoint condition will evaluate to false and GDB will not stop at
+# the breakpoint.
+proc run_condition_test { stop_at_cond \
+			      target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint.
+    if { $stop_at_cond } {
+	set cond_func "return_true"
+    } else {
+	set cond_func "return_false"
+    }
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (${cond_func} ())"
+    set cond_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			"get number for conditional breakpoint"]
+
+    # And a breakpoint that we hit when the test is over, this one is
+    # not conditional.
+    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
+    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			  "get number for final breakpoint"]
+
+    if { $stop_at_cond } {
+	# Continue.  The first breakpoint we hit should be the conditional
+	# breakpoint.  The other thread will have hit its breakpoint, but
+	# that will have been deferred until the conditional breakpoint is
+	# reported.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${cond_bp_num}, worker_func \[^\r\n\]+:${::cond_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Conditional breakpoint here\[^\r\n\]+"] \
+	    "hit the conditional breakpoint"
+    }
+
+    # Run to the stop marker.
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     ".*" \
+	     "" \
+	     "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${final_bp_num}, stop_marker \[^\r\n\]+:${::final_bp_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Stop marker\[^\r\n\]+"] \
+	"hit the final breakpoint"
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	foreach_with_prefix stop_at_cond { true false } {
+	    run_condition_test $stop_at_cond \
+		$target_async $target_non_stop
+	}
+    }
+}
-- 
2.25.4


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

* [PATCHv6 3/6] gdb: add timeouts for inferior function calls
  2023-04-03 14:01         ` [PATCHv6 0/6] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
  2023-04-03 14:01           ` [PATCHv6 1/6] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
  2023-04-03 14:01           ` [PATCHv6 2/6] gdb: fix b/p conditions with infcalls in multi-threaded inferiors Andrew Burgess
@ 2023-04-03 14:01           ` Andrew Burgess
  2023-07-11 14:23             ` Pedro Alves
  2023-04-03 14:01           ` [PATCHv6 4/6] gdb/remote: avoid SIGINT after calling remote_target::stop Andrew Burgess
                             ` (3 subsequent siblings)
  6 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2023-04-03 14:01 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Eli already approved the docs part:
  https://sourceware.org/pipermail/gdb-patches/2023-January/196462.html

---

In the previous commits I have been working on improving inferior
function call support.  One thing that worries me about using inferior
function calls from a conditional breakpoint is: what happens if the
inferior function call fails?

If the failure is obvious, e.g. the thread performing the call
crashes, or hits a breakpoint, then this case is already well handled,
and the error is reported to the user.

But what if the thread performing the inferior call just deadlocks?
If the user made the call from a 'print' or 'call' command, then the
user might have some expectation of when the function call should
complete, and, when this time limit is exceeded, the user
will (hopefully) interrupt GDB and regain control of the debug
session.

But, when the inferior function call is from a breakpoint condition it
is much harder to understand that GDB is deadlocked within an inferior
call.  Maybe the breakpoint hasn't been hit yet?  Or maybe the
condition was always false?  Or maybe GDB is deadlocked in an inferior
call?  The only way to know for sure is to periodically interrupt GDB,
check on all the threads, and then continue.

Additionally, the focus of the previous commit was inferior function
calls, from a conditional breakpoint, in a multi-threaded inferior.
This opens up a whole new set of potential failure conditions.  For
example, what if the function called relies on interaction with some
other thread, and the other thread crashes?  Or hits a breakpoint?
Given how inferior function calls work (in a synchronous manner), a
stop event in some other thread is going to be ignored while the
inferior function call is being executed as part of a breakpoint
condition, and this means that GDB could get stuck waiting for the
original condition thread, which will now never complete.

In this commit I propose a solution to this problem.  A timeout.  For
targets that support async-mode we can install an event-loop timer
before starting the inferior function call.  When the timer expires we
will stop the thread performing the inferior function call.  With this
mechanism in place a user can be sure that any inferior call they make
will either complete, or timeout eventually.

Adding a timer like this is obviously a change in behaviour for the
more common 'call' and 'print' uses of inferior function calls, so, in
this patch, I propose having two different timers.  One I call the
'direct-call-timeout', which is used for 'call' and 'print' commands.
This timeout is by default set to unlimited, which, not surprisingly,
means there is no timeout in place.

A second timer, which I've called 'indirect-call-timeout', is used for
inferior function calls from breakpoint conditions.  This timeout has
a default value of 30 seconds.  This is a reasonably long time to
wait, and hopefully should be enough in most cases to allow the
inferior call to complete.  An inferior call that takes more than 30
seconds, which is installed on a breakpoint condition is really going
to slow down the debug session, so hopefully this is not a common use
case.

The user is, of course, free to reduce, or increase the timeout value,
and can always use Ctrl-c to interrupt an inferior function call, but
this timeout will ensure that GDB will stop at some point.

The new commands added by this commit are:

  set direct-call-timeout SECONDS
  show direct-call-timeout
  set indirect-call-timeout SECONDS
  show indirect-call-timeout

These new timeouts do depend on async-mode, so, if async-mode is
disabled (maint set target-async off), or not supported (e.g. target
sim), then the timeout is treated as unlimited (that is, no timeout is
set).

For targets that "fake" non-async mode, e.g. Linux native, where
non-async mode is really just async mode, but then we park the target
in a sissuspend, we could easily fix things so that the timeouts still
work, however, for targets that really are not async aware, like the
simulator, fixing things so that timeouts work correctly would be a
much bigger task - that effort would be better spent just making the
target async-aware.  And so, I'm happy for now that this feature will
only work on async targets.

The two new show commands will display slightly different text if the
current target is a non-async target, which should allow users to
understand what's going on.

There's a somewhat random test adjustment needed in gdb.base/help.exp,
the test uses a regexp with the apropos command, and expects to find a
single result.  Turns out the new settings I added also matched the
regexp, which broke the test.  I've updated the regexp a little to
exclude my new settings.

In infcall.c you'll notice the thread_info::stop_requested flag being
set when a timeout occurs.  This flag setting is not required as part
of this commit, but will be needed in a later commit.  However, it
seemed like setting this flag fitted better with this commit, which is
why the change is added here.
---
 gdb/NEWS                                      |  18 ++
 gdb/doc/gdb.texinfo                           |  66 ++++++
 gdb/infcall.c                                 | 221 +++++++++++++++++-
 gdb/testsuite/gdb.base/help.exp               |   2 +-
 gdb/testsuite/gdb.base/infcall-timeout.c      |  36 +++
 gdb/testsuite/gdb.base/infcall-timeout.exp    |  82 +++++++
 .../infcall-from-bp-cond-timeout.c            | 169 ++++++++++++++
 .../infcall-from-bp-cond-timeout.exp          | 156 +++++++++++++
 8 files changed, 745 insertions(+), 5 deletions(-)
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.c
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp

diff --git a/gdb/NEWS b/gdb/NEWS
index 10a1a70fa52..70987994e7b 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -96,6 +96,24 @@ info main
    $2 = 1
    (gdb) break func if $_shell("some command") == 0
 
+set direct-call-timeout SECONDS
+show direct-call-timeout
+set indirect-call-timeout SECONDS
+show indirect-call-timeout
+  These new settings can be used to limit how long GDB will wait for
+  an inferior function call to complete.  The direct timeout is used
+  for inferior function calls from e.g. 'call' and 'print' commands,
+  while the indirect timeout is used for inferior function calls from
+  within a conditional breakpoint expression.
+
+  The default for the direct timeout is unlimited, while the default
+  for the indirect timeout is 30 seconds.
+
+  These timeouts will only have an effect for targets that are
+  operating in async mode.  For non-async targets the timeouts are
+  ignored, GDB will wait indefinitely for an inferior function to
+  complete, unless interrupted by the user using Ctrl-C.
+
 * MI changes
 
 ** mi now reports 'no-history' as a stop reason when hitting the end of the
diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index fe76e5e0a0e..46f17798510 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -20885,6 +20885,72 @@
 @code{step}, etc).  In this case, when the inferior finally returns to
 the dummy-frame, @value{GDBN} will once again halt the inferior.
 
+On targets that support asynchronous execution (@pxref{Background
+Execution}) @value{GDBN} can place a timeout on any functions called
+from @value{GDBN}.  If the timeout expires and the function call is
+still ongoing, then @value{GDBN} will interrupt the program.
+
+For targets that don't support asynchronous execution
+(@pxref{Background Execution}) then timeouts for functions called from
+@value{GDBN} are not supported, the timeout settings described below
+will be treated as @code{unlimited}, meaning @value{GDBN} will wait
+indefinitely for function call to complete, unless interrupted by the
+user using @kbd{Ctrl-C}.
+
+@table @code
+@item set direct-call-timeout @var{seconds}
+@kindex set direct-call-timeout
+@cindex timeout for called functions
+Set the timeout used when calling functions in the program to
+@var{seconds}, which should be an integer greater than zero, or the
+special value @code{unlimited}, which indicates no timeout should be
+used.  The default for this setting is @code{unlimited}.
+
+This setting is used when the user calls a function directly from the
+command prompt, for example with a @code{call} or @code{print}
+command.
+
+This setting only works for targets that support asynchronous
+execution (@pxref{Background Execution}), for any other target the
+setting is treated as @code{unlimited}.
+
+@item show direct-call-timeout
+@kindex show direct-call-timeout
+@cindex timeout for called functions
+Show the timeout used when calling functions in the program with a
+@code{call} or @code{print} command.
+@end table
+
+It is also possible to call functions within the program from the
+condition of a conditional breakpoint (@pxref{Conditions, ,Break
+Conditions}).  A different setting controls the timeout used for
+function calls made from a breakpoint condition.
+
+@table @code
+@item set indirect-call-timeout @var{seconds}
+@kindex set indirect-call-timeout
+@cindex timeout for called functions
+Set the timeout used when calling functions in the program from a
+breakpoint or watchpoint condition to @var{seconds}, which should be
+an integer greater than zero, or the special value @code{unlimited},
+which indicates no timeout should be used.  The default for this
+setting is @code{30} seconds.
+
+This setting only works for targets that support asynchronous
+execution (@pxref{Background Execution}), for any other target the
+setting is treated as @code{unlimited}.
+
+If a function called from a breakpoint or watchpoint condition times
+out, then @value{GDBN} will stop at the point where the timeout
+occurred.  The breakpoint condition evaluation will be abandoned.
+
+@item show indirect-call-timeout
+@kindex show indirect-call-timeout
+@cindex timeout for called functions
+Show the timeout used when calling functions in the program from a
+breakpoint or watchpoint condition.
+@end table
+
 @subsection Calling functions with no debug info
 
 @cindex no debug info functions
diff --git a/gdb/infcall.c b/gdb/infcall.c
index 4fb8ab07db0..bb57faf700f 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -95,6 +95,53 @@ show_may_call_functions_p (struct ui_file *file, int from_tty,
 	      value);
 }
 
+/* A timeout (in seconds) for direct inferior calls.  A direct inferior
+   call is one the user triggers from the prompt, e.g. with a 'call' or
+   'print' command.  Compare with the definition of indirect calls below.  */
+
+static unsigned int direct_call_timeout = UINT_MAX;
+
+/* Implement 'show direct-call-timeout'.  */
+
+static void
+show_direct_call_timeout (struct ui_file *file, int from_tty,
+			  struct cmd_list_element *c, const char *value)
+{
+  if (target_has_execution () && !target_can_async_p ())
+    gdb_printf (file, _("Current target does not support async mode, timeout "
+			"for direct inferior calls is \"unlimited\".\n"));
+  else if (direct_call_timeout == UINT_MAX)
+    gdb_printf (file, _("Timeout for direct inferior function calls "
+			"is \"unlimited\".\n"));
+  else
+    gdb_printf (file, _("Timeout for direct inferior function calls "
+			"is \"%s seconds\".\n"), value);
+}
+
+/* A timeout (in seconds) for indirect inferior calls.  An indirect inferior
+   call is one that originates from within GDB, for example, when
+   evaluating an expression for a conditional breakpoint.  Compare with
+   the definition of direct calls above.  */
+
+static unsigned int indirect_call_timeout = 30;
+
+/* Implement 'show indirect-call-timeout'.  */
+
+static void
+show_indirect_call_timeout (struct ui_file *file, int from_tty,
+			  struct cmd_list_element *c, const char *value)
+{
+  if (target_has_execution () && !target_can_async_p ())
+    gdb_printf (file, _("Current target does not support async mode, timeout "
+			"for indirect inferior calls is \"unlimited\".\n"));
+  else if (indirect_call_timeout == UINT_MAX)
+    gdb_printf (file, _("Timeout for indirect inferior function calls "
+			"is \"unlimited\".\n"));
+  else
+    gdb_printf (file, _("Timeout for indirect inferior function calls "
+			"is \"%s seconds\".\n"), value);
+}
+
 /* How you should pass arguments to a function depends on whether it
    was defined in K&R style or prototype style.  If you define a
    function using the K&R syntax that takes a `float' argument, then
@@ -589,6 +636,86 @@ call_thread_fsm::should_notify_stop ()
   return true;
 }
 
+/* A class to control creation of a timer that will interrupt a thread
+   during an inferior call.  */
+struct infcall_timer_controller
+{
+  /* Setup an event-loop timer that will interrupt PTID if the inferior
+     call takes too long.  DIRECT_CALL_P is true when this inferior call is
+     a result of the user using a 'print' or 'call' command, and false when
+     this inferior call is a result of e.g. a conditional breakpoint
+     expression, this is used to select which timeout to use.  */
+  infcall_timer_controller (thread_info *thr, bool direct_call_p)
+    : m_thread (thr)
+  {
+    unsigned int timeout
+      = direct_call_p ? direct_call_timeout : indirect_call_timeout;
+    if (timeout < UINT_MAX && target_can_async_p ())
+      {
+	int ms = timeout * 1000;
+	int id = create_timer (ms, infcall_timer_controller::timed_out, this);
+	m_timer_id.emplace (id);
+	infcall_debug_printf ("Setting up infcall timeout timer for "
+			      "ptid %s: %d milliseconds",
+			      m_thread->ptid.to_string ().c_str (), ms);
+      }
+  }
+
+  /* Destructor.  Ensure that the timer is removed from the event loop.  */
+  ~infcall_timer_controller ()
+  {
+    /* If the timer has already triggered, then it will have already been
+       deleted from the event loop.  If the timer has not triggered, then
+       delete it now.  */
+    if (m_timer_id.has_value () && !m_triggered)
+      delete_timer (*m_timer_id);
+
+    /* Just for clarity, discard the timer id now.  */
+    m_timer_id.reset ();
+  }
+
+  /* Return true if there was a timer in place, and the timer triggered,
+     otherwise, return false.  */
+  bool triggered_p ()
+  {
+    gdb_assert (!m_triggered || m_timer_id.has_value ());
+    return m_triggered;
+  }
+
+private:
+  /* The thread we should interrupt.  */
+  thread_info *m_thread;
+
+  /* Set true when the timer is triggered.  */
+  bool m_triggered = false;
+
+  /* Given a value when a timer is in place.  */
+  gdb::optional<int> m_timer_id;
+
+  /* Callback for the timer, forwards to ::trigger below.  */
+  static void
+  timed_out (gdb_client_data context)
+  {
+    infcall_timer_controller *ctrl
+      = static_cast<infcall_timer_controller *> (context);
+    ctrl->trigger ();
+  }
+
+  /* Called when the timer goes off.  Stop thread m_thread.  */
+  void
+  trigger ()
+  {
+    m_triggered = true;
+
+    scoped_disable_commit_resumed disable_commit_resumed ("infcall timeout");
+
+    infcall_debug_printf ("Stopping thread %s",
+			  m_thread->ptid.to_string ().c_str ());
+    target_stop (m_thread->ptid);
+    m_thread->stop_requested = true;
+  }
+};
+
 /* Subroutine of call_function_by_hand to simplify it.
    Start up the inferior and wait for it to stop.
    Return the exception if there's an error, or an exception with
@@ -599,13 +726,15 @@ call_thread_fsm::should_notify_stop ()
 
 static struct gdb_exception
 run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
-		   struct thread_info *call_thread, CORE_ADDR real_pc)
+		   struct thread_info *call_thread, CORE_ADDR real_pc,
+		   bool *timed_out_p)
 {
   INFCALL_SCOPED_DEBUG_ENTER_EXIT;
 
   struct gdb_exception caught_error;
   ptid_t call_thread_ptid = call_thread->ptid;
   int was_running = call_thread->state == THREAD_RUNNING;
+  *timed_out_p = false;
 
   infcall_debug_printf ("call function at %s in thread %s, was_running = %d",
 			core_addr_to_string (real_pc),
@@ -617,6 +746,16 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
   scoped_restore restore_in_infcall
     = make_scoped_restore (&call_thread->control.in_infcall, 1);
 
+  /* If the thread making the inferior call stops with a time out then the
+     stop_requested flag will be set.  However, we don't want changes to
+     this flag to leak back to our caller, we might be here to handle an
+     inferior call from a breakpoint condition, so leaving this flag set
+     would appear that the breakpoint stop was actually a requested stop,
+     which is not true, and will cause GDB to print extra messages to the
+     output.  */
+  scoped_restore restore_stop_requested
+    = make_scoped_restore (&call_thread->stop_requested, false);
+
   clear_proceed_status (0);
 
   /* Associate the FSM with the thread after clear_proceed_status
@@ -650,11 +789,23 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
       infrun_debug_show_threads ("non-exited threads after proceed for inferior-call",
 				 all_non_exited_threads ());
 
+      /* Setup a timer (if possible, and if the settings allow) to prevent
+	 the inferior call running forever.  */
+      bool direct_call_p = !call_thread->control.in_cond_eval;
+      infcall_timer_controller infcall_timer (call_thread, direct_call_p);
+
       /* Inferior function calls are always synchronous, even if the
 	 target supports asynchronous execution.  */
       wait_sync_command_done ();
 
-      infcall_debug_printf ("inferior call completed successfully");
+      /* If the timer triggered then the inferior call failed.  */
+      if (infcall_timer.triggered_p ())
+	{
+	  infcall_debug_printf ("inferior call timed out");
+	  *timed_out_p = true;
+	}
+      else
+	infcall_debug_printf ("inferior call completed successfully");
     }
   catch (gdb_exception &e)
     {
@@ -1308,6 +1459,10 @@ call_function_by_hand_dummy (struct value *function,
   scoped_restore restore_stopped_by_random_signal
     = make_scoped_restore (&stopped_by_random_signal, 0);
 
+  /* Set to true by the call to run_inferior_call below if the inferior
+     call is artificially interrupted by GDB due to taking too long.  */
+  bool timed_out_p = false;
+
   /* - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP -
      If you're looking to implement asynchronous dummy-frames, then
      just below is the place to chop this function in two..  */
@@ -1334,7 +1489,8 @@ call_function_by_hand_dummy (struct value *function,
 			      struct_addr);
     {
       std::unique_ptr<call_thread_fsm> sm_up (sm);
-      e = run_inferior_call (std::move (sm_up), call_thread.get (), real_pc);
+      e = run_inferior_call (std::move (sm_up), call_thread.get (), real_pc,
+			     &timed_out_p);
     }
 
     if (e.reason < 0)
@@ -1486,7 +1642,10 @@ When the function is done executing, GDB will silently stop."),
       std::string name = get_function_name (funaddr, name_buf,
 					    sizeof (name_buf));
 
-      if (stopped_by_random_signal)
+      /* If the inferior call timed out then it will have been interrupted
+	 by a signal, but we want to report this differently to the user,
+	 which is done later in this function.  */
+      if (stopped_by_random_signal && !timed_out_p)
 	{
 	  /* We stopped inside the FUNCTION because of a random
 	     signal.  Further execution of the FUNCTION is not
@@ -1530,6 +1689,36 @@ GDB remains in the frame where the signal was received.\n\
 To change this behavior use \"set unwindonsignal on\".\n\
 Evaluation of the expression containing the function\n\
 (%s) will be abandoned.\n\
+When the function is done executing, GDB will silently stop."),
+		     name.c_str ());
+	    }
+	}
+
+      if (timed_out_p)
+	{
+	  /* A timeout results in a signal being sent to the inferior.  */
+	  gdb_assert (stopped_by_random_signal);
+
+	  /* Indentation is weird here.  A later patch is going to move the
+	    following block into an if/else, so I'm leaving the indentation
+	    here to minimise the later patch.
+
+	    Also, the error message used below refers to 'set
+	    unwind-on-timeout' which doesn't exist yet.  This will be added
+	    in a later commit, I'm leaving this in for now to minimise the
+	    churn caused by the commit that adds unwind-on-timeout.  */
+	    {
+	      /* The user wants to stay in the frame where we stopped
+		 (default).  Discard inferior status, we're not at the same
+		 point we started at.  */
+	      discard_infcall_control_state (inf_status.release ());
+
+	      error (_("\
+The program being debugged timed out while in a function called from GDB.\n\
+GDB remains in the frame where the timeout occurred.\n\
+To change this behavior use \"set unwind-on-timeout on\".\n\
+Evaluation of the expression containing the function\n\
+(%s) will be abandoned.\n\
 When the function is done executing, GDB will silently stop."),
 		     name.c_str ());
 	    }
@@ -1643,6 +1832,30 @@ The default is to unwind the frame."),
 			   show_unwind_on_terminating_exception_p,
 			   &setlist, &showlist);
 
+  add_setshow_uinteger_cmd ("direct-call-timeout", no_class,
+			    &direct_call_timeout, _("\
+Set the timeout, for direct calls to inferior function calls."), _("\
+Show the timeout, for direct calls to inferior function calls."), _("\
+If running on a target that supports, and is running in, async mode\n\
+then this timeout is used for any inferior function calls triggered\n\
+directly from the prompt, i.e. from a 'call' or 'print' command.  The\n\
+timeout is specified in seconds."),
+			    nullptr,
+			    show_direct_call_timeout,
+			    &setlist, &showlist);
+
+  add_setshow_uinteger_cmd ("indirect-call-timeout", no_class,
+			    &indirect_call_timeout, _("\
+Set the timeout, for indirect calls to inferior function calls."), _("\
+Show the timeout, for indirect calls to inferior function calls."), _("\
+If running on a target that supports, and is running in, async mode\n\
+then this timeout is used for any inferior function calls triggered\n\
+indirectly, i.e. being made as part of a breakpoint, or watchpoint,\n\
+condition expression.  The timeout is specified in seconds."),
+			    nullptr,
+			    show_indirect_call_timeout,
+			    &setlist, &showlist);
+
   add_setshow_boolean_cmd
     ("infcall", class_maintenance, &debug_infcall,
      _("Set inferior call debugging."),
diff --git a/gdb/testsuite/gdb.base/help.exp b/gdb/testsuite/gdb.base/help.exp
index 87919a819ab..504bf90cc15 100644
--- a/gdb/testsuite/gdb.base/help.exp
+++ b/gdb/testsuite/gdb.base/help.exp
@@ -121,7 +121,7 @@ gdb_test "help info bogus-gdb-command" "Undefined info command: \"bogus-gdb-comm
 gdb_test "help gotcha" "Undefined command: \"gotcha\"\.  Try \"help\"\."
 
 # Test apropos regex.
-gdb_test "apropos \\\(print\[\^\[ bsiedf\\\".-\]\\\)" "handle -- Specify how to handle signals\."
+gdb_test "apropos \\\(print\[\^\[ bsiedf\\\"'.-\]\\\)" "handle -- Specify how to handle signals\."
 # Test apropos >1 word string.
 gdb_test "apropos handle signal" "handle -- Specify how to handle signals\."
 # Test apropos apropos.
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.c b/gdb/testsuite/gdb.base/infcall-timeout.c
new file mode 100644
index 00000000000..12774ca2599
--- /dev/null
+++ b/gdb/testsuite/gdb.base/infcall-timeout.c
@@ -0,0 +1,36 @@
+/* Copyright 2022-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 <unistd.h>
+
+/* This function is called from GDB.  */
+int
+function_that_never_returns ()
+{
+  while (1)
+    sleep (1);
+
+  return 0;
+}
+
+int
+main ()
+{
+  alarm (300);
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.exp b/gdb/testsuite/gdb.base/infcall-timeout.exp
new file mode 100644
index 00000000000..5e9cdc2fa0e
--- /dev/null
+++ b/gdb/testsuite/gdb.base/infcall-timeout.exp
@@ -0,0 +1,82 @@
+# Copyright 2022-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/>.
+
+# Test GDB's direct-call-timeout setting, that is, ensure that if an
+# inferior function call, invoked from e.g. a 'print' command, takes
+# too long, then GDB can interrupt it, and return control to the user.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug}] == -1 } {
+    return
+}
+
+# Start GDB according to TARGET_ASYNC and TARGET_NON_STOP, then adjust
+# the direct-call-timeout, and make an inferior function call that
+# will never return.  GDB should eventually timeout and stop the
+# inferior.
+proc_with_prefix run_test { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if {![runto_main]} {
+	fail "run to main"
+	return
+    }
+
+    gdb_test_no_output "set direct-call-timeout 5"
+
+    # When non-stop mode is off we get slightly different output from GDB.
+    if { [gdb_is_remote_or_extended_remote_target] && !$target_non_stop } {
+	set stopped_line_pattern "Program received signal SIGINT, Interrupt\\."
+    } else {
+	set stopped_line_pattern "Program stopped\\."
+    }
+
+    gdb_test "print function_that_never_returns ()" \
+	[multi_line \
+	     $stopped_line_pattern \
+	     ".*" \
+	     "The program being debugged timed out while in a function called from GDB\\." \
+	     "GDB remains in the frame where the timeout occurred\\." \
+	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(function_that_never_returns\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+
+    gdb_test "bt" ".* function_that_never_returns .*<function called from gdb>.*"
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+
+    if { !$target_async } {
+	# GDB can't timeout while waiting for a thread if the target
+	# runs with async-mode turned off; once the target is running
+	# GDB is effectively blocked until the target stops for some
+	# reason.
+	continue
+    }
+
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	run_test $target_async $target_non_stop
+    }
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
new file mode 100644
index 00000000000..4da4245746e
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
@@ -0,0 +1,169 @@
+/* This testcase is part of GDB, the GNU debugger.
+
+   Copyright 2022-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 <stdio.h>
+#include <pthread.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <semaphore.h>
+
+#define NUM_THREADS 5
+
+/* Semaphores, used to track when threads have started, and to control
+   when the threads finish.  */
+sem_t startup_semaphore;
+sem_t finish_semaphore;
+sem_t thread_1_semaphore;
+sem_t thread_2_semaphore;
+
+/* Mutex to control when the first worker thread hit a breakpoint
+   location.  */
+pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+
+/* Global variable to poke, just so threads have something to do.  */
+volatile int global_var = 0;
+
+int
+condition_func ()
+{
+  /* Let thread 2 run.  */
+  if (sem_post (&thread_2_semaphore) != 0)
+    abort ();
+
+  /* Wait for thread 2 to complete its actions.  */
+  if (sem_wait (&thread_1_semaphore) != 0)
+    abort ();
+
+  return 1;
+}
+
+void
+do_segfault ()
+{
+  volatile int *p = 0;
+  *p = 0;	/* Segfault here.  */
+}
+
+void *
+worker_func (void *arg)
+{
+  int tid = *((int *) arg);
+
+  /* Let the main thread know that this worker has started.  */
+  if (sem_post (&startup_semaphore) != 0)
+    abort ();
+
+  switch (tid)
+    {
+    case 0:
+      /* Wait for MUTEX to become available, then pass through the
+	 conditional breakpoint location.  */
+      if (pthread_mutex_lock (&mutex) != 0)
+	abort ();
+      global_var = 99;	/* Conditional breakpoint here.  */
+      if (pthread_mutex_unlock (&mutex) != 0)
+	abort ();
+      break;
+
+    case 1:
+      if (sem_wait (&thread_2_semaphore) != 0)
+	abort ();
+      do_segfault ();
+      if (sem_post (&thread_1_semaphore) != 0)
+	abort ();
+
+      /* Fall through.  */
+    default:
+      /* Wait until we are allowed to finish.  */
+      if (sem_wait (&finish_semaphore) != 0)
+	abort ();
+      break;
+    }
+}
+
+void
+stop_marker ()
+{
+  global_var = 99;	/* Stop marker.  */
+}
+
+/* The main program entry point.  */
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+  void *retval;
+
+  /* An alarm, just in case the thread deadlocks.  */
+  alarm (300);
+
+  /* Semaphore initialization.  */
+  if (sem_init (&startup_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&finish_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&thread_1_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&thread_2_semaphore, 0, 0) != 0)
+    abort ();
+
+  /* Lock MUTEX, this prevents the first worker thread from rushing ahead.  */
+  if (pthread_mutex_lock (&mutex) != 0)
+    abort ();
+
+  /* Worker thread creation.  */
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  /* Wait for every thread to start.  */
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      if (sem_wait (&startup_semaphore) != 0)
+	abort ();
+    }
+
+  /* Unlock the first thread so it can proceed.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  /* Wait for the first thread only.  */
+  pthread_join (threads[0], &retval);
+
+  /* Now post FINISH_SEMAPHORE to allow all the other threads to finish.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    sem_post (&finish_semaphore);
+
+  /* Now wait for the remaining threads to complete.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    pthread_join (threads[i], &retval);
+
+  /* Semaphore cleanup.  */
+  sem_destroy (&finish_semaphore);
+  sem_destroy (&startup_semaphore);
+  sem_destroy (&thread_1_semaphore);
+  sem_destroy (&thread_2_semaphore);
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
new file mode 100644
index 00000000000..4159288a39c
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
@@ -0,0 +1,156 @@
+# Copyright 2022-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 inferior calls executed from a breakpoint condition in
+# a multi-threaded program.
+#
+# This test has the inferior function call timeout, and checks how GDB
+# handles this situation.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "Conditional breakpoint here"]
+set final_bp_line [gdb_get_line_number "Stop marker"]
+set segfault_line [gdb_get_line_number "Segfault here"]
+
+# Setup GDB based on TARGET_ASYNC and TARGET_NON_STOP.  Setup some
+# breakpoints in the inferior, one of which has an inferior call
+# within its condition.
+#
+# Continue GDB, the breakpoint with inferior call will be hit, but the
+# inferior call will never return.  We expect GDB to timeout.
+#
+# The reason that the inferior call never completes is that a second
+# thread, on which the inferior call relies, either hits a breakpoint
+# (when OTHER_THREAD_BP is true), or crashes (when OTHER_THREAD_BP is
+# false).
+proc run_test { target_async target_non_stop other_thread_bp } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if {![runto_main]} {
+	fail "run to main"
+	return
+    }
+
+    # The default timeout for indirect inferior calls (e.g. inferior
+    # calls for conditional breakpoint expressions) is pretty high.
+    # We don't want the test to take too long, so reduce this.
+    #
+    # However, the test relies on a second thread hitting some event
+    # (either a breakpoint or signal) before this timeout expires.
+    #
+    # There is a chance that on a really slow system this might not
+    # happen, in which case the test might fail.
+    #
+    # However, we still allocate 5 seconds, which feels like it should
+    # be enough time in most cases, but maybe we need to do something
+    # smarter here?  Possibly we could have some initial run where the
+    # inferior doesn't timeout, but does perform the same interaction
+    # between threads, we could time that, and use that as the basis
+    # for this timeout.  For now though, we just hope 5 seconds is
+    # enough.
+    gdb_test_no_output "set indirect-call-timeout 5"
+
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (condition_func ())"
+    set bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		    "get number for conditional breakpoint"]
+
+    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
+    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			  "get number for final breakpoint"]
+
+    # The thread performing an inferior call relies on a second
+    # thread.  The second thread will segfault unless it hits a
+    # breakpoint first.  In either case the initial thread will not
+    # complete its inferior call.
+    if { $other_thread_bp } {
+	gdb_breakpoint "${::srcfile}:${::segfault_line}"
+	set segfault_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+				 "get number for segfault breakpoint"]
+    }
+
+    # When non-stop mode is off we get slightly different output from GDB.
+    if { [gdb_is_remote_or_extended_remote_target] && !$target_non_stop} {
+	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" received signal SIGINT, Interrupt\\."
+    } else {
+	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\."
+    }
+
+    gdb_test "continue" \
+	[multi_line \
+	     $stopped_line_pattern \
+	     ".*" \
+	     "Error in testing condition for breakpoint ${bp_num}:" \
+	     "The program being debugged timed out while in a function called from GDB\\." \
+	     "GDB remains in the frame where the timeout occurred\\." \
+	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(condition_func\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."] \
+	"expected timeout waiting for inferior call to complete"
+
+    # Remember that other thread that either crashed (with a segfault)
+    # or hit a breakpoint?  Now that the inferior call has timed out,
+    # if we try to resume then we should see the pending event from
+    # that other thread.
+    if { $other_thread_bp } {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${segfault_bp_num}, do_segfault \[^\r\n\]+:${::segfault_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"] \
+	    "hit the segfault breakpoint"
+    } else {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "Thread ${::decimal} \"infcall-from-bp\" received signal SIGSEGV, Segmentation fault\\." \
+		 "\\\[Switching to Thread \[^\r\n\]+\\\]" \
+		 "${::hex} in do_segfault \\(\\) at \[^\r\n\]+:${::segfault_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"] \
+	    "hit the segfault"
+    }
+}
+
+foreach_with_prefix target_async {"on" "off" } {
+
+    if { !$target_async } {
+	# GDB can't timeout while waiting for a thread if the target
+	# runs with async-mode turned off; once the target is running
+	# GDB is effectively blocked until the target stops for some
+	# reason.
+	continue
+    }
+
+    foreach_with_prefix target_non_stop {"off" "on"} {
+	foreach_with_prefix other_thread_bp { true false } {
+	    run_test $target_async $target_non_stop $other_thread_bp
+	}
+    }
+}
-- 
2.25.4


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

* [PATCHv6 4/6] gdb/remote: avoid SIGINT after calling remote_target::stop
  2023-04-03 14:01         ` [PATCHv6 0/6] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                             ` (2 preceding siblings ...)
  2023-04-03 14:01           ` [PATCHv6 3/6] gdb: add timeouts for inferior function calls Andrew Burgess
@ 2023-04-03 14:01           ` Andrew Burgess
  2023-04-03 14:01           ` [PATCHv6 5/6] gdb: introduce unwind-on-timeout setting Andrew Burgess
                             ` (2 subsequent siblings)
  6 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-04-03 14:01 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Currently, if the remote target is not running in non-stop mode, then,
when GDB calls remote_target::stop, we end up sending an interrupt
packet \x03 to the remote target.

If the user interrupts the inferior from the GDB prompt (e.g. by
typing Ctrl-c), then GDB calls remote_target::interrupt, which also
ends up sending the interrupt packet.

The problem here is that both of these mechanisms end up sending the
interrupt packet, which means, when the target stops with a SIGINT,
and this is reported back to GDB, we have no choice but to report this
to the user as a SIGINT stop event.

Now maybe this is the correct thing to do, after all the target has
been stopped with SIGINT.  However, this leads to an unfortunate
change in behaviour when comparing non-stop vs all-stop mode.

When running in non-stop mode, and remote_target::stop is called, the
target will be stopped with a vCont packet, and this stop is then
reported back to GDB as GDB_SIGNAL_0, this will cause GDB to print a
message like:

  Program stopped.

Or:

  Thread NN "binary name" stopped.

In contrast, when non-stop mode is off, we get messages like:

  Program received SIGINT, Segmentation fault.

Or:

  Thread NN "binary name" received SIGINT, Segmentation fault.

In this commit I propose making use of thread_info::stop_requested
within remote.c to know if the stop was triggered by GDB (and the
SIGINT should be hidden) or if the stop was a user interrupt, and the
SIGINT should be printed.

In remote_target::process_stop_reply if the inferior stopped with
SIGINT and the thread_info::stop_requested flag is set, then we change
the stop signal to GDB_SIGNAL_0.

Two of the tests added in the previous commit exposed this issue.  In
the previous commit the tests looked for either of the above
patterns.  In this commit I've updated these tests to only look for
the "stopped" based messages.

This commit is the reason why the previous commit took care to set the
thread_info::stop_requested flag in infcall.c.
---
 gdb/remote.c                                           | 10 ++++++++++
 gdb/testsuite/gdb.base/infcall-timeout.exp             |  9 +--------
 .../gdb.threads/infcall-from-bp-cond-timeout.exp       |  9 +--------
 3 files changed, 12 insertions(+), 16 deletions(-)

diff --git a/gdb/remote.c b/gdb/remote.c
index 526df313ea7..ea8f103a589 100644
--- a/gdb/remote.c
+++ b/gdb/remote.c
@@ -8275,6 +8275,16 @@ remote_target::process_stop_reply (struct stop_reply *stop_reply,
 	}
       else
 	{
+	  /* If this stop was actually requested by GDB then we can hide
+	     the SIGINT from the user.  */
+	  if (status->kind () == TARGET_WAITKIND_STOPPED
+	      && status->sig () == GDB_SIGNAL_INT)
+	    {
+	      thread_info *thr = find_thread_ptid (this, ptid);
+	      if (thr->stop_requested)
+		status->set_stopped (GDB_SIGNAL_0);
+	    }
+
 	  /* If the target works in all-stop mode, a stop-reply indicates that
 	     all the target's threads stopped.  */
 	  for (thread_info *tp : all_non_exited_threads (this))
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.exp b/gdb/testsuite/gdb.base/infcall-timeout.exp
index 5e9cdc2fa0e..beb488ffd1e 100644
--- a/gdb/testsuite/gdb.base/infcall-timeout.exp
+++ b/gdb/testsuite/gdb.base/infcall-timeout.exp
@@ -45,16 +45,9 @@ proc_with_prefix run_test { target_async target_non_stop } {
 
     gdb_test_no_output "set direct-call-timeout 5"
 
-    # When non-stop mode is off we get slightly different output from GDB.
-    if { [gdb_is_remote_or_extended_remote_target] && !$target_non_stop } {
-	set stopped_line_pattern "Program received signal SIGINT, Interrupt\\."
-    } else {
-	set stopped_line_pattern "Program stopped\\."
-    }
-
     gdb_test "print function_that_never_returns ()" \
 	[multi_line \
-	     $stopped_line_pattern \
+	     "Program stopped\\." \
 	     ".*" \
 	     "The program being debugged timed out while in a function called from GDB\\." \
 	     "GDB remains in the frame where the timeout occurred\\." \
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
index 4159288a39c..74f7def7dce 100644
--- a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
@@ -92,16 +92,9 @@ proc run_test { target_async target_non_stop other_thread_bp } {
 				 "get number for segfault breakpoint"]
     }
 
-    # When non-stop mode is off we get slightly different output from GDB.
-    if { [gdb_is_remote_or_extended_remote_target] && !$target_non_stop} {
-	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" received signal SIGINT, Interrupt\\."
-    } else {
-	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\."
-    }
-
     gdb_test "continue" \
 	[multi_line \
-	     $stopped_line_pattern \
+	     "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\." \
 	     ".*" \
 	     "Error in testing condition for breakpoint ${bp_num}:" \
 	     "The program being debugged timed out while in a function called from GDB\\." \
-- 
2.25.4


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

* [PATCHv6 5/6] gdb: introduce unwind-on-timeout setting
  2023-04-03 14:01         ` [PATCHv6 0/6] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                             ` (3 preceding siblings ...)
  2023-04-03 14:01           ` [PATCHv6 4/6] gdb/remote: avoid SIGINT after calling remote_target::stop Andrew Burgess
@ 2023-04-03 14:01           ` Andrew Burgess
  2023-04-03 14:01           ` [PATCHv6 6/6] gdb: rename unwindonsignal to unwind-on-signal Andrew Burgess
  2023-05-15 19:22           ` [PATCHv7 0/6] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
  6 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-04-03 14:01 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Eli already approved the docs part:
  https://sourceware.org/pipermail/gdb-patches/2023-January/195873.html

---

Now that inferior function calls can timeout (see the recent
introduction of direct-call-timeout and indirect-call-timeout), this
commit adds a new setting unwind-on-timeout.

This new setting is just like the existing unwindonsignal and
unwind-on-terminating-exception, but the new setting will cause GDB to
unwind the stack if an inferior function call times out.

The existing inferior function call timeout tests have been updated to
cover the new setting.
---
 gdb/NEWS                                      |  9 +++
 gdb/doc/gdb.texinfo                           | 25 ++++++--
 gdb/infcall.c                                 | 62 ++++++++++++++++---
 gdb/testsuite/gdb.base/infcall-timeout.exp    | 49 +++++++++++----
 .../infcall-from-bp-cond-timeout.exp          | 55 +++++++++++-----
 5 files changed, 160 insertions(+), 40 deletions(-)

diff --git a/gdb/NEWS b/gdb/NEWS
index 70987994e7b..f3a47091967 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -114,6 +114,15 @@ show indirect-call-timeout
   ignored, GDB will wait indefinitely for an inferior function to
   complete, unless interrupted by the user using Ctrl-C.
 
+set unwind-on-timeout on|off
+show unwind-on-timeout
+  These commands control whether GDB should unwind the stack when a
+  timeout occurs during an inferior function call.  The default is
+  off, in which case the inferior will remain in the frame where the
+  timeout occurred.  When on, GDB will unwind the stack removing the
+  dummy frame that was added for the inferior call, and restoring the
+  inferior state to how it was before the inferior call started.
+
 * MI changes
 
 ** mi now reports 'no-history' as a stop reason when hitting the end of the
diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index 46f17798510..545ea90eb60 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -20830,6 +20830,21 @@
 Show the current setting of stack unwinding in the functions called by
 @value{GDBN}.
 
+@item set unwind-on-timeout
+@kindex set unwind-on-timeout
+@cindex unwind stack in called functions when timing out
+@cindex call dummy stack unwinding on timeout.
+Set unwinding of the stack if a function called from @value{GDBN}
+times out.  If set to @code{off} (the default), @value{GDBN} stops in
+the frame where the timeout occurred.  If set to @code{on},
+@value{GDBN} unwinds the stack it created for the call and restores
+the context to what it was before the call.
+
+@item show unwind-on-timeout
+@kindex show unwind-on-timeout
+Show whether @value{GDBN} will unwind the stack if a function called
+from @value{GDBN} times out.
+
 @item set may-call-functions
 @kindex set may-call-functions
 @cindex disabling calling functions in the program
@@ -20861,11 +20876,11 @@
 
 If a called function is interrupted for any reason, including hitting
 a breakpoint, or triggering a watchpoint, and the stack is not unwound
-due to @code{set unwind-on-terminating-exception on} or @code{set
-unwindonsignal on} (@pxref{stack unwind settings}),
-then the dummy-frame, created by @value{GDBN} to facilitate the call
-to the program function, will be visible in the backtrace, for example
-frame @code{#3} in the following backtrace:
+due to @code{set unwind-on-terminating-exception on}, @code{set
+unwind-on-timeout on}, or @code{set unwindonsignal on} (@pxref{stack
+unwind settings}), then the dummy-frame, created by @value{GDBN} to
+facilitate the call to the program function, will be visible in the
+backtrace, for example frame @code{#3} in the following backtrace:
 
 @smallexample
 (@value{GDBP}) backtrace
diff --git a/gdb/infcall.c b/gdb/infcall.c
index bb57faf700f..1f0fb4f1d59 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -217,6 +217,27 @@ show_unwind_on_terminating_exception_p (struct ui_file *file, int from_tty,
 	      value);
 }
 
+/* This boolean tells GDB what to do if an inferior function, called from
+   GDB, times out.  If true, GDB unwinds the stack and restores the context
+   to what it was before the call.  When false, GDB leaves the thread as it
+   is at the point of the timeout.
+
+   The default is to stop in the frame where the timeout occurred.  */
+
+static bool unwind_on_timeout_p = false;
+
+/* Implement 'show unwind-on-timeout'.  */
+
+static void
+show_unwind_on_timeout_p (struct ui_file *file, int from_tty,
+			  struct cmd_list_element *c, const char *value)
+{
+  gdb_printf (file,
+	      _("Unwinding of stack if a timeout occurs "
+		"while in a call dummy is %s.\n"),
+	      value);
+}
+
 /* Perform the standard coercions that are specified
    for arguments to be passed to C, Ada or Fortran functions.
 
@@ -1699,14 +1720,27 @@ When the function is done executing, GDB will silently stop."),
 	  /* A timeout results in a signal being sent to the inferior.  */
 	  gdb_assert (stopped_by_random_signal);
 
-	  /* Indentation is weird here.  A later patch is going to move the
-	    following block into an if/else, so I'm leaving the indentation
-	    here to minimise the later patch.
+	  if (unwind_on_timeout_p)
+	    {
+	      /* The user wants the context restored.  */
+
+	      /* We must get back to the frame we were before the
+		 dummy call.  */
+	      dummy_frame_pop (dummy_id, call_thread.get ());
 
-	    Also, the error message used below refers to 'set
-	    unwind-on-timeout' which doesn't exist yet.  This will be added
-	    in a later commit, I'm leaving this in for now to minimise the
-	    churn caused by the commit that adds unwind-on-timeout.  */
+	      /* We also need to restore inferior status to that before the
+		 dummy call.  */
+	      restore_infcall_control_state (inf_status.release ());
+
+	      error (_("\
+The program being debugged timed out while in a function called from GDB.\n\
+GDB has restored the context to what it was before the call.\n\
+To change this behavior use \"set unwind-on-timeout off\".\n\
+Evaluation of the expression containing the function\n\
+(%s) will be abandoned."),
+		     name.c_str ());
+	    }
+	  else
 	    {
 	      /* The user wants to stay in the frame where we stopped
 		 (default).  Discard inferior status, we're not at the same
@@ -1832,6 +1866,20 @@ The default is to unwind the frame."),
 			   show_unwind_on_terminating_exception_p,
 			   &setlist, &showlist);
 
+  add_setshow_boolean_cmd ("unwind-on-timeout", no_class,
+			   &unwind_on_timeout_p, _("\
+Set unwinding of stack if a timeout occurs while in a call dummy."), _("\
+Show unwinding of stack if a timeout occurs while in a call dummy."),
+			   _("\
+The unwind on timeout flag lets the user determine what gdb should do if\n\
+gdb times out while in a function called from gdb.  If set, gdb unwinds\n\
+the stack and restores the context to what it was before the call.  If\n\
+unset, gdb leaves the inferior in the frame where the timeout occurred.\n\
+The default is to stop in the frame where the timeout occurred."),
+			   NULL,
+			   show_unwind_on_timeout_p,
+			   &setlist, &showlist);
+
   add_setshow_uinteger_cmd ("direct-call-timeout", no_class,
 			    &direct_call_timeout, _("\
 Set the timeout, for direct calls to inferior function calls."), _("\
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.exp b/gdb/testsuite/gdb.base/infcall-timeout.exp
index beb488ffd1e..d063abc9077 100644
--- a/gdb/testsuite/gdb.base/infcall-timeout.exp
+++ b/gdb/testsuite/gdb.base/infcall-timeout.exp
@@ -28,7 +28,11 @@ if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
 # the direct-call-timeout, and make an inferior function call that
 # will never return.  GDB should eventually timeout and stop the
 # inferior.
-proc_with_prefix run_test { target_async target_non_stop } {
+#
+# When UNWIND is "off" the inferior wil be left in the frame where the
+# timeout occurs, otherwise, when UNWIND is "on", GDB should unwind
+# back to the frame where the inferior call was made.
+proc_with_prefix run_test { target_async target_non_stop unwind } {
     save_vars { ::GDBFLAGS } {
 	append ::GDBFLAGS \
 	    " -ex \"maint set target-non-stop $target_non_stop\""
@@ -44,19 +48,36 @@ proc_with_prefix run_test { target_async target_non_stop } {
     }
 
     gdb_test_no_output "set direct-call-timeout 5"
+    gdb_test_no_output "set unwind-on-timeout $unwind"
+
+    if { $unwind } {
+	gdb_test "print function_that_never_returns ()" \
+	    [multi_line \
+		 "Program stopped\\." \
+		 ".*" \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB has restored the context to what it was before the call\\." \
+		 "To change this behavior use \"set unwind-on-timeout off\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(function_that_never_returns\\) will be abandoned\\."]
 
-    gdb_test "print function_that_never_returns ()" \
-	[multi_line \
-	     "Program stopped\\." \
-	     ".*" \
-	     "The program being debugged timed out while in a function called from GDB\\." \
-	     "GDB remains in the frame where the timeout occurred\\." \
-	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
-	     "Evaluation of the expression containing the function" \
-	     "\\(function_that_never_returns\\) will be abandoned\\." \
-	     "When the function is done executing, GDB will silently stop\\."]
+	gdb_test "bt" \
+	    "#0\\s+main \\(\\).*"
+    } else {
+	gdb_test "print function_that_never_returns ()" \
+	    [multi_line \
+		 "Program stopped\\." \
+		 ".*" \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB remains in the frame where the timeout occurred\\." \
+		 "To change this behavior use \"set unwind-on-timeout on\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(function_that_never_returns\\) will be abandoned\\." \
+		 "When the function is done executing, GDB will silently stop\\."]
 
-    gdb_test "bt" ".* function_that_never_returns .*<function called from gdb>.*"
+	gdb_test "bt" \
+	    ".* function_that_never_returns .*<function called from gdb>.*"
+    }
 }
 
 foreach_with_prefix target_async { "on" "off" } {
@@ -70,6 +91,8 @@ foreach_with_prefix target_async { "on" "off" } {
     }
 
     foreach_with_prefix target_non_stop { "on" "off" } {
-	run_test $target_async $target_non_stop
+	foreach_with_prefix unwind { "on" "off" } {
+	    run_test $target_async $target_non_stop $unwind
+	}
     }
 }
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
index 74f7def7dce..f399b5420a2 100644
--- a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
@@ -41,7 +41,12 @@ set segfault_line [gdb_get_line_number "Segfault here"]
 # thread, on which the inferior call relies, either hits a breakpoint
 # (when OTHER_THREAD_BP is true), or crashes (when OTHER_THREAD_BP is
 # false).
-proc run_test { target_async target_non_stop other_thread_bp } {
+#
+# When UNWIND is "on" GDB will unwind the thread which performed the
+# inferior function call back to the state where the inferior call was
+# made (when the inferior call times out).  Otherwise, when UNWIND is
+# "off", the inferior is left in the frame where the timeout occurred.
+proc run_test { target_async target_non_stop other_thread_bp unwind } {
     save_vars { ::GDBFLAGS } {
 	append ::GDBFLAGS " -ex \"maint set target-non-stop $target_non_stop\""
 	append ::GDBFLAGS " -ex \"maintenance set target-async ${target_async}\""
@@ -72,6 +77,7 @@ proc run_test { target_async target_non_stop other_thread_bp } {
     # for this timeout.  For now though, we just hope 5 seconds is
     # enough.
     gdb_test_no_output "set indirect-call-timeout 5"
+    gdb_test_no_output "set unwind-on-timeout $unwind"
 
     gdb_breakpoint \
 	"${::srcfile}:${::cond_bp_line} if (condition_func ())"
@@ -92,18 +98,35 @@ proc run_test { target_async target_non_stop other_thread_bp } {
 				 "get number for segfault breakpoint"]
     }
 
-    gdb_test "continue" \
-	[multi_line \
-	     "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\." \
-	     ".*" \
-	     "Error in testing condition for breakpoint ${bp_num}:" \
-	     "The program being debugged timed out while in a function called from GDB\\." \
-	     "GDB remains in the frame where the timeout occurred\\." \
-	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
-	     "Evaluation of the expression containing the function" \
-	     "\\(condition_func\\) will be abandoned\\." \
-	     "When the function is done executing, GDB will silently stop\\."] \
-	"expected timeout waiting for inferior call to complete"
+    if { $unwind } {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\." \
+		 ".*" \
+		 "Error in testing condition for breakpoint ${bp_num}:" \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB has restored the context to what it was before the call\\." \
+		 "To change this behavior use \"set unwind-on-timeout off\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(condition_func\\) will be abandoned\\." \
+		 "" \
+		 "Thread ${::decimal}\[^\r\n\]*hit Breakpoint ${bp_num}, \[^\r\n\]+" \
+		 "\[^\r\n\]+ Conditional breakpoint here\\. \[^\r\n\]+"] \
+	    "expected timeout waiting for inferior call to complete"
+    } else {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\." \
+		 ".*" \
+		 "Error in testing condition for breakpoint ${bp_num}:" \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB remains in the frame where the timeout occurred\\." \
+		 "To change this behavior use \"set unwind-on-timeout on\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(condition_func\\) will be abandoned\\." \
+		 "When the function is done executing, GDB will silently stop\\."] \
+	    "expected timeout waiting for inferior call to complete"
+    }
 
     # Remember that other thread that either crashed (with a segfault)
     # or hit a breakpoint?  Now that the inferior call has timed out,
@@ -142,8 +165,10 @@ foreach_with_prefix target_async {"on" "off" } {
     }
 
     foreach_with_prefix target_non_stop {"off" "on"} {
-	foreach_with_prefix other_thread_bp { true false } {
-	    run_test $target_async $target_non_stop $other_thread_bp
+	foreach_with_prefix unwind {"off" "on"} {
+	    foreach_with_prefix other_thread_bp { true false } {
+		run_test $target_async $target_non_stop $other_thread_bp $unwind
+	    }
 	}
     }
 }
-- 
2.25.4


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

* [PATCHv6 6/6] gdb: rename unwindonsignal to unwind-on-signal
  2023-04-03 14:01         ` [PATCHv6 0/6] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                             ` (4 preceding siblings ...)
  2023-04-03 14:01           ` [PATCHv6 5/6] gdb: introduce unwind-on-timeout setting Andrew Burgess
@ 2023-04-03 14:01           ` Andrew Burgess
  2023-05-15 19:22           ` [PATCHv7 0/6] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
  6 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-04-03 14:01 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Eli already approved the docs part:
  https://sourceware.org/pipermail/gdb-patches/2023-January/195874.html

---

We now have unwind-on-timeout and unwind-on-terminating-exception, and
then the odd one out unwindonsignal.

I'm not a great fan of these squashed together command names, so in
this commit I propose renaming this to unwind-on-signal.

Obviously I've added the hidden alias unwindonsignal so any existing
GDB scripts will keep working.

There's one test that I've extended to test the alias works, but in
most of the other test scripts I've changed over to use the new name.

The docs are updated to reference the new name.
---
 gdb/NEWS                                      | 11 ++++++
 gdb/doc/gdb.texinfo                           | 16 ++++++---
 gdb/infcall.c                                 | 21 ++++++-----
 gdb/testsuite/gdb.base/callfuncs.exp          |  4 +--
 gdb/testsuite/gdb.base/infcall-failure.exp    |  4 +--
 gdb/testsuite/gdb.base/unwindonsignal.exp     | 36 +++++++++++++------
 gdb/testsuite/gdb.compile/compile-cplus.exp   |  2 +-
 gdb/testsuite/gdb.compile/compile.exp         |  2 +-
 gdb/testsuite/gdb.cp/gdb2495.exp              | 16 ++++-----
 gdb/testsuite/gdb.fortran/function-calls.exp  |  2 +-
 gdb/testsuite/gdb.mi/mi-syn-frame.exp         |  2 +-
 .../infcall-from-bp-cond-simple.exp           |  2 +-
 .../gdb.threads/thread-unwindonsignal.exp     |  8 ++---
 13 files changed, 83 insertions(+), 43 deletions(-)

diff --git a/gdb/NEWS b/gdb/NEWS
index f3a47091967..2a314017d5b 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -123,6 +123,17 @@ show unwind-on-timeout
   dummy frame that was added for the inferior call, and restoring the
   inferior state to how it was before the inferior call started.
 
+set unwind-on-signal on|off
+show unwind-on-signal
+  These new commands replaces the existing set/show unwindonsignal.  The
+  old command is maintained as an alias.
+
+* Changed commands
+
+set unwindonsignal on|off
+show unwindonsignal
+  These commands are now aliases for the new set/show unwind-on-signal.
+
 * MI changes
 
 ** mi now reports 'no-history' as a stop reason when hitting the end of the
diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index 545ea90eb60..ca29647a378 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -20784,7 +20784,7 @@
 It is possible for the function you call via the @code{print} or
 @code{call} command to generate a signal (e.g., if there's a bug in
 the function, or if you passed it incorrect arguments).  What happens
-in that case is controlled by the @code{set unwindonsignal} command.
+in that case is controlled by the @code{set unwind-on-signal} command.
 
 Similarly, with a C@t{++} program it is possible for the function you
 call via the @code{print} or @code{call} command to generate an
@@ -20798,7 +20798,8 @@
 
 @anchor{stack unwind settings}
 @table @code
-@item set unwindonsignal
+@item set unwind-on-signal
+@kindex set unwind-on-signal
 @kindex set unwindonsignal
 @cindex unwind stack in called functions
 @cindex call dummy stack unwinding
@@ -20809,11 +20810,18 @@
 default), @value{GDBN} stops in the frame where the signal was
 received.
 
-@item show unwindonsignal
+The command @code{set unwindonsignal} is an alias for this command,
+and is maintained for backward compatibility.
+
+@item show unwind-on-signal
+@kindex show unwind-on-signal
 @kindex show unwindonsignal
 Show the current setting of stack unwinding in the functions called by
 @value{GDBN}.
 
+The command @code{show unwindonsignal} is an alias for this command,
+and is maintained for backward compatibility.
+
 @item set unwind-on-terminating-exception
 @kindex set unwind-on-terminating-exception
 @cindex unwind stack in called functions with unhandled exceptions
@@ -20877,7 +20885,7 @@
 If a called function is interrupted for any reason, including hitting
 a breakpoint, or triggering a watchpoint, and the stack is not unwound
 due to @code{set unwind-on-terminating-exception on}, @code{set
-unwind-on-timeout on}, or @code{set unwindonsignal on} (@pxref{stack
+unwind-on-timeout on}, or @code{set unwind-on-signal on} (@pxref{stack
 unwind settings}), then the dummy-frame, created by @value{GDBN} to
 facilitate the call to the program function, will be visible in the
 backtrace, for example frame @code{#3} in the following backtrace:
diff --git a/gdb/infcall.c b/gdb/infcall.c
index 1f0fb4f1d59..73b19afe613 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -1689,7 +1689,7 @@ When the function is done executing, GDB will silently stop."),
 	      error (_("\
 The program being debugged was signaled while in a function called from GDB.\n\
 GDB has restored the context to what it was before the call.\n\
-To change this behavior use \"set unwindonsignal off\".\n\
+To change this behavior use \"set unwind-on-signal off\".\n\
 Evaluation of the expression containing the function\n\
 (%s) will be abandoned."),
 		     name.c_str ());
@@ -1707,7 +1707,7 @@ Evaluation of the expression containing the function\n\
 	      error (_("\
 The program being debugged was signaled while in a function called from GDB.\n\
 GDB remains in the frame where the signal was received.\n\
-To change this behavior use \"set unwindonsignal on\".\n\
+To change this behavior use \"set unwind-on-signal on\".\n\
 Evaluation of the expression containing the function\n\
 (%s) will be abandoned.\n\
 When the function is done executing, GDB will silently stop."),
@@ -1839,17 +1839,22 @@ The default is to perform the conversion."),
 			   show_coerce_float_to_double_p,
 			   &setlist, &showlist);
 
-  add_setshow_boolean_cmd ("unwindonsignal", no_class,
-			   &unwind_on_signal_p, _("\
+  set_show_commands setshow_unwind_on_signal_cmds
+    = add_setshow_boolean_cmd ("unwind-on-signal", no_class,
+			       &unwind_on_signal_p, _("\
 Set unwinding of stack if a signal is received while in a call dummy."), _("\
 Show unwinding of stack if a signal is received while in a call dummy."), _("\
-The unwindonsignal lets the user determine what gdb should do if a signal\n\
+The unwind-on-signal lets the user determine what gdb should do if a signal\n\
 is received while in a function called from gdb (call dummy).  If set, gdb\n\
 unwinds the stack and restore the context to what as it was before the call.\n\
 The default is to stop in the frame where the signal was received."),
-			   NULL,
-			   show_unwind_on_signal_p,
-			   &setlist, &showlist);
+			       NULL,
+			       show_unwind_on_signal_p,
+			       &setlist, &showlist);
+  add_alias_cmd ("unwindonsignal", setshow_unwind_on_signal_cmds.set,
+		 no_class, 1, &setlist);
+  add_alias_cmd ("unwindonsignal", setshow_unwind_on_signal_cmds.show,
+		 no_class, 1, &showlist);
 
   add_setshow_boolean_cmd ("unwind-on-terminating-exception", no_class,
 			   &unwind_on_terminating_exception_p, _("\
diff --git a/gdb/testsuite/gdb.base/callfuncs.exp b/gdb/testsuite/gdb.base/callfuncs.exp
index 2c797a224a7..d9f63e944bf 100644
--- a/gdb/testsuite/gdb.base/callfuncs.exp
+++ b/gdb/testsuite/gdb.base/callfuncs.exp
@@ -46,7 +46,7 @@ proc do_function_calls {prototypes} {
 
     # If any of these calls segv we don't want to affect subsequent tests.
     # E.g., we want to ensure register values are restored.
-    gdb_test_no_output "set unwindonsignal on"
+    gdb_test_no_output "set unwind-on-signal on"
 
     gdb_test "p t_char_values(0,0)" " = 0"
     gdb_test "p t_char_values('a','b')" " = 1"
@@ -237,7 +237,7 @@ proc do_function_calls {prototypes} {
     	"call inferior func with struct - returns char *"
 
     # Restore default value.
-    gdb_test_no_output "set unwindonsignal off"
+    gdb_test_no_output "set unwind-on-signal off"
 }
 
 # Procedure to get current content of all registers.
diff --git a/gdb/testsuite/gdb.base/infcall-failure.exp b/gdb/testsuite/gdb.base/infcall-failure.exp
index 5ad179a089d..e2e71649dac 100644
--- a/gdb/testsuite/gdb.base/infcall-failure.exp
+++ b/gdb/testsuite/gdb.base/infcall-failure.exp
@@ -137,7 +137,7 @@ proc_with_prefix run_cond_hits_segfault_test { async_p non_stop_p } {
 	     "Error in testing condition for breakpoint ${bp_1_num}:" \
 	     "The program being debugged was signaled while in a function called from GDB\\." \
 	     "GDB remains in the frame where the signal was received\\." \
-	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "To change this behavior use \"set unwind-on-signal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(func_segfault\\) will be abandoned\\." \
 	     "When the function is done executing, GDB will silently stop\\."]
@@ -166,7 +166,7 @@ proc_with_prefix run_call_hits_segfault_test { async_p non_stop_p } {
 	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
 	     "The program being debugged was signaled while in a function called from GDB\\." \
 	     "GDB remains in the frame where the signal was received\\." \
-	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "To change this behavior use \"set unwind-on-signal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(func_segfault\\) will be abandoned\\." \
 	     "When the function is done executing, GDB will silently stop\\."]
diff --git a/gdb/testsuite/gdb.base/unwindonsignal.exp b/gdb/testsuite/gdb.base/unwindonsignal.exp
index 625b0c4db12..9c1b36e95bc 100644
--- a/gdb/testsuite/gdb.base/unwindonsignal.exp
+++ b/gdb/testsuite/gdb.base/unwindonsignal.exp
@@ -34,34 +34,50 @@ gdb_test "break stop_here" "Breakpoint \[0-9\]* at .*"
 gdb_test "continue" "Continuing.*Breakpoint \[0-9\]*, stop_here.*" \
     "continue to breakpoint at stop_here"
 
-# Turn on unwindonsignal.
-gdb_test_no_output "set unwindonsignal on" \
-	"setting unwindonsignal"
+# Turn on unwind-on-signal.
+gdb_test_no_output "set unwind-on-signal on" \
+	"setting unwind-on-signal"
 
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
 	"Unwinding of stack .* is on." \
-	"showing unwindonsignal"
+	"showing unwind-on-signal"
+
+# For backward compatibility we maintain a 'unwindonsignal' alias for
+# 'unwind-on-signal', check it now.
+gdb_test "show unwindonsignal" \
+    "Unwinding of stack .* is on\\." \
+    "showing unwindonsignal alias"
+
+gdb_test_no_output "set unwindonsignal off" \
+    "setting unwindonsignal alias to off"
+
+gdb_test "show unwind-on-signal" \
+    "Unwinding of stack .* is off\\." \
+    "showing unwind-on-signal after setting via alias"
+
+gdb_test_no_output "set unwindonsignal on" \
+    "setting unwindonsignal alias to on"
 
 # Call function (causing the program to get a signal), and see if gdb handles
 # it properly.
 if {[gdb_test "call gen_signal ()"  \
 	 "\[\r\n\]*The program being debugged was signaled.*" \
-	 "unwindonsignal, inferior function call signaled"] != 0} {
+	 "inferior function call signaled"] != 0} {
     return 0
 }
 
 # Verify the stack got unwound.
 gdb_test "bt" \
     "#0 *\[x0-9a-f in\]*stop_here \\(.*\\) at .*#1 *\[x0-9a-f in\]*main \\(.*\\) at .*" \
-	"unwindonsignal, stack unwound"
+	"stack unwound"
 
 # Verify the dummy frame got removed from dummy_frame_stack.
 gdb_test_multiple "maint print dummy-frames" \
-	"unwindonsignal, dummy frame removed" {
+	"unwind-on-signal, dummy frame removed" {
     -re "\[\r\n\]*.*stack=.*code=.*\[\r\n\]+$gdb_prompt $" {
-	fail "unwindonsignal, dummy frame removed"
+	fail $gdb_test_name
     }
     -re "\[\r\n\]+$gdb_prompt $" {
-	pass "unwindonsignal, dummy frame removed"
+	pass $gdb_test_name
     }
 }
diff --git a/gdb/testsuite/gdb.compile/compile-cplus.exp b/gdb/testsuite/gdb.compile/compile-cplus.exp
index 4e887daeb29..22eebb44953 100644
--- a/gdb/testsuite/gdb.compile/compile-cplus.exp
+++ b/gdb/testsuite/gdb.compile/compile-cplus.exp
@@ -129,7 +129,7 @@ gdb_test "return" "\r\n#0  main .*" "return" \
 	 "Make _gdb_expr\\(__gdb_regs\\*\\) return now\\? \\(y or n\\) " "y"
 gdb_test "info sym $infcall_pc" "\r\nNo symbol matches .*" "info sym not found"
 
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 gdb_test "compile code *(volatile int *) 0 = 0;" \
     "The program being debugged was signaled while in a function called from GDB\\.\r\nGDB has restored the context to what it was before the call\\.\r\n.*" \
     "compile code segfault second"
diff --git a/gdb/testsuite/gdb.compile/compile.exp b/gdb/testsuite/gdb.compile/compile.exp
index f3d87cd2605..8822aab2e81 100644
--- a/gdb/testsuite/gdb.compile/compile.exp
+++ b/gdb/testsuite/gdb.compile/compile.exp
@@ -159,7 +159,7 @@ gdb_test "return" "\r\n#0  main .*" "return" \
 	 "Make _gdb_expr return now\\? \\(y or n\\) " "y"
 gdb_test "info sym $infcall_pc" "\r\nNo symbol matches .*" "info sym not found"
 
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 gdb_test "compile code *(volatile int *) 0 = 0;" \
     "The program being debugged was signaled while in a function called from GDB\\.\r\nGDB has restored the context to what it was before the call\\.\r\n.*" \
     "compile code segfault second"
diff --git a/gdb/testsuite/gdb.cp/gdb2495.exp b/gdb/testsuite/gdb.cp/gdb2495.exp
index e3c0cca3175..d7985e5db48 100644
--- a/gdb/testsuite/gdb.cp/gdb2495.exp
+++ b/gdb/testsuite/gdb.cp/gdb2495.exp
@@ -98,29 +98,29 @@ if {![runto_main]} {
 # behaviour; it should not.  Test both on and off states.
 
 # Turn on unwind on signal behaviour.
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 
 # Check that it is turned on.
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
     "signal is received while in a call dummy is on.*" \
     "turn on unwind on signal"
 
 # Check to see if new behaviour interferes with
 # normal signal handling in inferior function calls.
 gdb_test "p exceptions.raise_signal(1)" \
-    "To change this behavior use \"set unwindonsignal off\".*" \
-    "check for unwindonsignal off message"
+    "To change this behavior use \"set unwind-on-signal off\".*" \
+    "check for unwind-on-signal off message"
 
 # And reverse - turn off again.
-gdb_test_no_output "set unwindonsignal off"
+gdb_test_no_output "set unwind-on-signal off"
 
 # Check that it is actually turned off.
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
     "signal is received while in a call dummy is off.*" \
     "turn off unwind on signal"
 
 # Check to see if new behaviour interferes with
 # normal signal handling in inferior function calls.
 gdb_test "p exceptions.raise_signal(1)" \
-    "To change this behavior use \"set unwindonsignal on\".*" \
-    "check for unwindonsignal on message"
+    "To change this behavior use \"set unwind-on-signal on\".*" \
+    "check for unwind-on-signal on message"
diff --git a/gdb/testsuite/gdb.fortran/function-calls.exp b/gdb/testsuite/gdb.fortran/function-calls.exp
index f9a1efc241f..c4d1f232576 100644
--- a/gdb/testsuite/gdb.fortran/function-calls.exp
+++ b/gdb/testsuite/gdb.fortran/function-calls.exp
@@ -44,7 +44,7 @@ if {![runto [gdb_get_line_number "post_init"]]} {
 }
 
 # Use inspired by gdb.base/callfuncs.exp.
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 
 # Baseline: function and subroutine call with no arguments.
 gdb_test "p no_arg()" " = .TRUE."
diff --git a/gdb/testsuite/gdb.mi/mi-syn-frame.exp b/gdb/testsuite/gdb.mi/mi-syn-frame.exp
index 40df312a1cc..1324226412c 100644
--- a/gdb/testsuite/gdb.mi/mi-syn-frame.exp
+++ b/gdb/testsuite/gdb.mi/mi-syn-frame.exp
@@ -94,7 +94,7 @@ mi_gdb_test "409-stack-list-frames 0 0" \
 # 
 
 mi_gdb_test "410-data-evaluate-expression bar()" \
-  ".*410\\^error,msg=\"The program being debugged was signaled while in a function called from GDB.\\\\nGDB remains in the frame where the signal was received.\\\\nTo change this behavior use \\\\\"set unwindonsignal on\\\\\".\\\\nEvaluation of the expression containing the function\\\\n\\(bar\\) will be abandoned.\\\\nWhen the function is done executing, GDB will silently stop.\"" \
+  ".*410\\^error,msg=\"The program being debugged was signaled while in a function called from GDB.\\\\nGDB remains in the frame where the signal was received.\\\\nTo change this behavior use \\\\\"set unwind-on-signal on\\\\\".\\\\nEvaluation of the expression containing the function\\\\n\\(bar\\) will be abandoned.\\\\nWhen the function is done executing, GDB will silently stop.\"" \
   "call inferior function which raises exception"
 
 mi_gdb_test "411-stack-list-frames" "411\\^done,stack=\\\[frame=\{level=\"0\",addr=\"$hex\",func=\"bar\",file=\".*mi-syn-frame.c\",fullname=\"${fullname_syntax}${srcfile}\",line=\"$decimal\",arch=\"$any\"},frame=\{level=\"1\",addr=\"$hex\",func=\"<function called from gdb>\"\},frame=\{level=\"2\",addr=\"$hex\",func=\"main\",file=\".*mi-syn-frame.c\",fullname=\"${fullname_syntax}${srcfile}\",line=\"$decimal\",arch=\"$any\"}.*\\\]" "backtrace from inferior function at exception"
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
index 37e1b64d9a4..bb4402c0926 100644
--- a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
@@ -173,7 +173,7 @@ proc_with_prefix run_bp_cond_segfaults { target_async target_non_stop } {
 	     "Error in testing condition for breakpoint ${bp_1_num}:" \
 	     "The program being debugged was signaled while in a function called from GDB\\." \
 	     "GDB remains in the frame where the signal was received\\." \
-	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "To change this behavior use \"set unwind-on-signal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(function_that_segfaults\\) will be abandoned\\." \
 	     "When the function is done executing, GDB will silently stop\\."]
diff --git a/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp b/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp
index 68a99f66f1c..a9cedc0c466 100644
--- a/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp
+++ b/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp
@@ -13,7 +13,7 @@
 # You should have received a copy of the GNU General Public License
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-# Test use of unwindonsignal when a hand function call that gets interrupted
+# Test use of unwind-on-signal when a hand function call that gets interrupted
 # by a signal in another thread.
 
 set NR_THREADS 4
@@ -49,12 +49,12 @@ gdb_test "continue" \
 # We want the main thread (hand_call_with_signal) and
 # thread 1 (sigabrt_handler) to both run.
 
-# Do turn on unwindonsignal.
+# Do turn on unwind-on-signal.
 # We want to test gdb handling of the current thread changing when
 # unwindonsignal is in effect.
-gdb_test_no_output "set unwindonsignal on" \
+gdb_test_no_output "set unwind-on-signal on" \
 	"setting unwindonsignal"
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
 	"Unwinding of stack .* is on." \
 	"showing unwindonsignal"
 
-- 
2.25.4


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

* [PATCHv7 0/6] Infcalls from B/P conditions in multi-threaded inferiors
  2023-04-03 14:01         ` [PATCHv6 0/6] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                             ` (5 preceding siblings ...)
  2023-04-03 14:01           ` [PATCHv6 6/6] gdb: rename unwindonsignal to unwind-on-signal Andrew Burgess
@ 2023-05-15 19:22           ` Andrew Burgess
  2023-05-15 19:22             ` [PATCHv7 1/6] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
                               ` (6 more replies)
  6 siblings, 7 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-05-15 19:22 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

In v7:

  - Rebased onto current upstream/master, fixed use of
    find_thread_ptid which is now a process_stratum_target method,

  - Retested, with no regressions seen.

In v6:

  - Pushed the 5 initial patches.  These were the smaller fixes, and,
    I felt were pretty obvious fixes.  I'm sure folk will raise
    objections if they disagree.

  - Of the remaining patches, #1 to #5 really needs review before they
    can be merged.  Patch #6 is an obvious cleanup once the first five
    have been merged.

  - I've rebased onto current HEAD of master, there's no significant
    changes.

  - All other documentation changes have been reviewed and approved.

In v5:

  - Rebased to current HEAD of master, minor merge conflict resolved.
    No other code or documentation changes.

  - First patch, which was pure documentation, has now been merged.

  - All other documentation changes have been reviewed and approved.

In v4:

  - I believe all the docs changes have been reviewed and approved by Eli,

  - Rebased onto current master,

  - Dropped patch #2 from the V3 series,

  - I have addressed all the issues Baris pointed out, including the
    fixes for the patch #9 ('gdb: add timeouts for inferior function
    calls'), which I forgot to do in V3.

In v3:

  - Updates for review feedback, biggest changes in #10 and #11, but
    minor changes to most patches.

In V2:

  - Rebased onto something closer to HEAD of master,

  - Patches #1, #2, #12, and #13 are new in this series,

  - Patches #3 to #9, and #11 are unchanged since their V1 iteration,

  - Patches #10 has changed slightly in implementation since v1, and
    the docs have been significantly updated.

---

Andrew Burgess (6):
  Revert "gdb: remove unnecessary parameter wait_ptid from
    do_target_wait"
  gdb: fix b/p conditions with infcalls in multi-threaded inferiors
  gdb: add timeouts for inferior function calls
  gdb/remote: avoid SIGINT after calling remote_target::stop
  gdb: introduce unwind-on-timeout setting
  gdb: rename unwindonsignal to unwind-on-signal

 gdb/NEWS                                      |  38 +++
 gdb/breakpoint.c                              |   2 +
 gdb/doc/gdb.texinfo                           | 105 ++++++-
 gdb/gdbthread.h                               |   3 +
 gdb/infcall.c                                 | 296 +++++++++++++++++-
 gdb/infrun.c                                  |  70 ++++-
 gdb/infrun.h                                  |   3 +-
 gdb/remote.c                                  |  10 +
 gdb/testsuite/gdb.base/callfuncs.exp          |   4 +-
 gdb/testsuite/gdb.base/help.exp               |   2 +-
 gdb/testsuite/gdb.base/infcall-failure.exp    |   4 +-
 gdb/testsuite/gdb.base/infcall-timeout.c      |  36 +++
 gdb/testsuite/gdb.base/infcall-timeout.exp    |  98 ++++++
 gdb/testsuite/gdb.base/unwindonsignal.exp     |  36 ++-
 gdb/testsuite/gdb.compile/compile-cplus.exp   |   2 +-
 gdb/testsuite/gdb.compile/compile.exp         |   2 +-
 gdb/testsuite/gdb.cp/gdb2495.exp              |  16 +-
 gdb/testsuite/gdb.fortran/function-calls.exp  |   2 +-
 gdb/testsuite/gdb.mi/mi-syn-frame.exp         |   2 +-
 .../infcall-from-bp-cond-other-thread-event.c | 135 ++++++++
 ...nfcall-from-bp-cond-other-thread-event.exp | 174 ++++++++++
 .../gdb.threads/infcall-from-bp-cond-simple.c |  89 ++++++
 .../infcall-from-bp-cond-simple.exp           | 235 ++++++++++++++
 .../gdb.threads/infcall-from-bp-cond-single.c | 139 ++++++++
 .../infcall-from-bp-cond-single.exp           | 117 +++++++
 .../infcall-from-bp-cond-timeout.c            | 169 ++++++++++
 .../infcall-from-bp-cond-timeout.exp          | 174 ++++++++++
 .../gdb.threads/thread-unwindonsignal.exp     |   8 +-
 28 files changed, 1903 insertions(+), 68 deletions(-)
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.c
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp


base-commit: 6a1cf1bfedbcdb977d9ead3bf6a228360d78cc1b
-- 
2.25.4


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

* [PATCHv7 1/6] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait"
  2023-05-15 19:22           ` [PATCHv7 0/6] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
@ 2023-05-15 19:22             ` Andrew Burgess
  2023-05-16 15:08               ` Aktemur, Tankut Baris
  2023-05-15 19:22             ` [PATCHv7 2/6] gdb: fix b/p conditions with infcalls in multi-threaded inferiors Andrew Burgess
                               ` (5 subsequent siblings)
  6 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2023-05-15 19:22 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

This reverts commit ac0d67ed1dcf470bad6a3bc4800c2ddc9bedecca.

There was nothing wrong with the commit which I'm reverting here, but
it removed some functionality that will be needed for a later commit;
that is, the ability for GDB to ask for events from a specific ptid_t
via the do_target_wait function.

In a follow up commit, this functionality will be used to implement
inferior function calls in multi-threaded inferiors.

This is not a straight revert of the above commit.  Reverting the
above commit replaces a 'nullptr' with 'NULL', I've gone in and
changed that, preserving the 'nullptr'.
---
 gdb/infrun.c | 12 +++++++-----
 1 file changed, 7 insertions(+), 5 deletions(-)

diff --git a/gdb/infrun.c b/gdb/infrun.c
index efe2c00c489..07ef3c7c187 100644
--- a/gdb/infrun.c
+++ b/gdb/infrun.c
@@ -3869,7 +3869,8 @@ do_target_wait_1 (inferior *inf, ptid_t ptid,
    more events.  Polls for events from all inferiors/targets.  */
 
 static bool
-do_target_wait (execution_control_state *ecs, target_wait_flags options)
+do_target_wait (ptid_t wait_ptid, execution_control_state *ecs,
+		target_wait_flags options)
 {
   int num_inferiors = 0;
   int random_selector;
@@ -3879,9 +3880,10 @@ do_target_wait (execution_control_state *ecs, target_wait_flags options)
      polling the rest of the inferior list starting from that one in a
      circular fashion until the whole list is polled once.  */
 
-  auto inferior_matches = [] (inferior *inf)
+  auto inferior_matches = [&wait_ptid] (inferior *inf)
     {
-      return inf->process_target () != nullptr;
+      return (inf->process_target () != nullptr
+	      && ptid_t (inf->pid).matches (wait_ptid));
     };
 
   /* First see how many matching inferiors we have.  */
@@ -3920,7 +3922,7 @@ do_target_wait (execution_control_state *ecs, target_wait_flags options)
 
   auto do_wait = [&] (inferior *inf)
   {
-    ecs->ptid = do_target_wait_1 (inf, minus_one_ptid, &ecs->ws, options);
+    ecs->ptid = do_target_wait_1 (inf, wait_ptid, &ecs->ws, options);
     ecs->target = inf->process_target ();
     return (ecs->ws.kind () != TARGET_WAITKIND_IGNORE);
   };
@@ -4350,7 +4352,7 @@ fetch_inferior_event ()
        the event.  */
     scoped_disable_commit_resumed disable_commit_resumed ("handling event");
 
-    if (!do_target_wait (&ecs, TARGET_WNOHANG))
+    if (!do_target_wait (minus_one_ptid, &ecs, TARGET_WNOHANG))
       {
 	infrun_debug_printf ("do_target_wait returned no event");
 	disable_commit_resumed.reset_and_commit ();
-- 
2.25.4


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

* [PATCHv7 2/6] gdb: fix b/p conditions with infcalls in multi-threaded inferiors
  2023-05-15 19:22           ` [PATCHv7 0/6] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
  2023-05-15 19:22             ` [PATCHv7 1/6] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
@ 2023-05-15 19:22             ` Andrew Burgess
  2023-05-16 15:09               ` Aktemur, Tankut Baris
  2023-05-15 19:22             ` [PATCHv7 3/6] gdb: add timeouts for inferior function calls Andrew Burgess
                               ` (4 subsequent siblings)
  6 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2023-05-15 19:22 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Natalia Saiapova, Tankut Baris Aktemur

This commit fixes bug PR 28942, that is, creating a conditional
breakpoint in a multi-threaded inferior, where the breakpoint
condition includes an inferior function call.

Currently, when a user tries to create such a breakpoint, then GDB
will fail with:

  (gdb) break infcall-from-bp-cond-single.c:61 if (return_true ())
  Breakpoint 2 at 0x4011fa: file /tmp/build/gdb/testsuite/../../../src/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c, line 61.
  (gdb) continue
  Continuing.
  [New Thread 0x7ffff7c5d700 (LWP 2460150)]
  [New Thread 0x7ffff745c700 (LWP 2460151)]
  [New Thread 0x7ffff6c5b700 (LWP 2460152)]
  [New Thread 0x7ffff645a700 (LWP 2460153)]
  [New Thread 0x7ffff5c59700 (LWP 2460154)]
  Error in testing breakpoint condition:
  Couldn't get registers: No such process.
  An error occurred while in a function called from GDB.
  Evaluation of the expression containing the function
  (return_true) will be abandoned.
  When the function is done executing, GDB will silently stop.
  Selected thread is running.
  (gdb)

Or, in some cases, like this:

  (gdb) break infcall-from-bp-cond-simple.c:56 if (is_matching_tid (arg, 1))
  Breakpoint 2 at 0x401194: file /tmp/build/gdb/testsuite/../../../src/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c, line 56.
  (gdb) continue
  Continuing.
  [New Thread 0x7ffff7c5d700 (LWP 2461106)]
  [New Thread 0x7ffff745c700 (LWP 2461107)]
  ../../src.release/gdb/nat/x86-linux-dregs.c:146: internal-error: x86_linux_update_debug_registers: Assertion `lwp_is_stopped (lwp)' failed.
  A problem internal to GDB has been detected,
  further debugging may prove unreliable.

The precise error depends on the exact thread state; so there's race
conditions depending on which threads have fully started, and which
have not.  But the underlying problem is always the same; when GDB
tries to execute the inferior function call from within the breakpoint
condition, GDB will, incorrectly, try to resume threads that are
already running - GDB doesn't realise that some threads might already
be running.

The solution proposed in this patch requires an additional member
variable thread_info::in_cond_eval.  This flag is set to true (in
breakpoint.c) when GDB is evaluating a breakpoint condition.

In user_visible_resume_ptid (infrun.c), when the in_cond_eval flag is
true, then GDB will only try to resume the current thread, that is,
the thread for which the breakpoint condition is being evaluated.
This solves the problem of GDB trying to resume threads that are
already running.

The next problem is that inferior function calls are assumed to be
synchronous, that is, GDB doesn't expect to start an inferior function
call in thread #1, then receive a stop from thread #2 for some other,
unrelated reason.  To prevent GDB responding to an event from another
thread, we update fetch_inferior_event and do_target_wait in infrun.c,
so that, when an inferior function call (on behalf of a breakpoint
condition) is in progress, we only wait for events from the current
thread (the one evaluating the condition).

In do_target_wait I had to change the inferior_matches lambda
function, which is used to select which inferior to wait on.
Previously the logic was this:

   auto inferior_matches = [&wait_ptid] (inferior *inf)
     {
       return (inf->process_target () != nullptr
               && ptid_t (inf->pid).matches (wait_ptid));
     };

This compares the pid of the inferior against the complete ptid we
want to wait on.  Before this commit wait_ptid was only ever
minus_one_ptid (which is special, and means any process), and so every
inferior would match.

After this commit though wait_ptid might represent a specific thread
in a specific inferior.  If we compare the pid of the inferior to a
specific ptid then these will not match.  The fix is to compare
against the pid extracted from the wait_ptid, not against the complete
wait_ptid itself.

In fetch_inferior_event, after receiving the event, we only want to
stop all the other threads, and call inferior_event_handler with
INF_EXEC_COMPLETE, if we are not evaluating a conditional breakpoint.
If we are, then all the other threads should be left doing whatever
they were before.  The inferior_event_handler call will be performed
once the breakpoint condition has finished being evaluated, and GDB
decides to stop or not.

The final problem that needs solving relates to GDB's commit-resume
mechanism, which allows GDB to collect resume requests into a single
packet in order to reduce traffic to a remote target.

The problem is that the commit-resume mechanism will not send any
resume requests for an inferior if there are already events pending on
the GDB side.

Imagine an inferior with two threads.  Both threads hit a breakpoint,
maybe the same conditional breakpoint.  At this point there are two
pending events, one for each thread.

GDB selects one of the events and spots that this is a conditional
breakpoint, GDB evaluates the condition.

The condition includes an inferior function call, so GDB sets up for
the call and resumes the one thread, the resume request is added to
the commit-resume queue.

When the commit-resume queue is committed GDB sees that there is a
pending event from another thread, and so doesn't send any resume
requests to the actual target, GDB is assuming that when we wait we
will select the event from the other thread.

However, as this is an inferior function call for a condition
evaluation, we will not select the event from the other thread, we
only care about events from the thread that is evaluating the
condition - and the resume for this thread was never sent to the
target.

And so, GDB hangs, waiting for an event from a thread that was never
fully resumed.

To fix this issue I have added the concept of "forcing" the
commit-resume queue.  When enabling commit resume, if the force flag
is true, then any resumes will be committed to the target, even if
there are other threads with pending events.

A note on authorship: this patch was based on some work done by
Natalia Saiapova and Tankut Baris Aktemur from Intel[1].  I have made
some changes to their work in this version.

Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=28942

[1] https://sourceware.org/pipermail/gdb-patches/2020-October/172454.html

Co-authored-by: Natalia Saiapova <natalia.saiapova@intel.com>
Co-authored-by: Tankut Baris Aktemur <tankut.baris.aktemur@intel.com>
---
 gdb/breakpoint.c                              |   2 +
 gdb/gdbthread.h                               |   3 +
 gdb/infcall.c                                 |   6 +
 gdb/infrun.c                                  |  64 +++--
 gdb/infrun.h                                  |   3 +-
 .../infcall-from-bp-cond-other-thread-event.c | 135 ++++++++++
 ...nfcall-from-bp-cond-other-thread-event.exp | 174 +++++++++++++
 .../gdb.threads/infcall-from-bp-cond-simple.c |  89 +++++++
 .../infcall-from-bp-cond-simple.exp           | 235 ++++++++++++++++++
 .../gdb.threads/infcall-from-bp-cond-single.c | 139 +++++++++++
 .../infcall-from-bp-cond-single.exp           | 117 +++++++++
 11 files changed, 952 insertions(+), 15 deletions(-)
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index fdb184ae81f..6fceed8f408 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -5548,6 +5548,8 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
 	{
 	  try
 	    {
+	      scoped_restore reset_in_cond_eval
+		= make_scoped_restore (&thread->control.in_cond_eval, true);
 	      condition_result = breakpoint_cond_eval (cond);
 	    }
 	  catch (const gdb_exception_error &ex)
diff --git a/gdb/gdbthread.h b/gdb/gdbthread.h
index 7135515bf45..897752f2691 100644
--- a/gdb/gdbthread.h
+++ b/gdb/gdbthread.h
@@ -171,6 +171,9 @@ struct thread_control_state
      command.  This is used to decide whether "set scheduler-locking
      step" behaves like "on" or "off".  */
   int stepping_command = 0;
+
+  /* True if the thread is evaluating a BP condition.  */
+  bool in_cond_eval = false;
 };
 
 /* Inferior thread specific part of `struct infcall_suspend_state'.  */
diff --git a/gdb/infcall.c b/gdb/infcall.c
index 233ef5f29e9..49c88add394 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -642,6 +642,12 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
 
       proceed (real_pc, GDB_SIGNAL_0);
 
+      /* Enable commit resume, but pass true for the force flag.  This
+	 ensures any thread we set running in proceed will actually be
+	 committed to the target, even if some other thread in the current
+	 target has a pending event.  */
+      scoped_enable_commit_resumed enable ("infcall", true);
+
       infrun_debug_show_threads ("non-exited threads after proceed for inferior-call",
 				 all_non_exited_threads ());
 
diff --git a/gdb/infrun.c b/gdb/infrun.c
index 07ef3c7c187..ea7ab6187ee 100644
--- a/gdb/infrun.c
+++ b/gdb/infrun.c
@@ -2275,6 +2275,14 @@ user_visible_resume_ptid (int step)
 	 mode.  */
       resume_ptid = inferior_ptid;
     }
+  else if (inferior_ptid != null_ptid
+	   && inferior_thread ()->control.in_cond_eval)
+    {
+      /* The inferior thread is evaluating a BP condition.  Other threads
+	 might be stopped or running and we do not want to change their
+	 state, thus, resume only the current thread.  */
+      resume_ptid = inferior_ptid;
+    }
   else if (!sched_multi && target_supports_multi_process ())
     {
       /* Resume all threads of the current process (and none of other
@@ -2992,12 +3000,24 @@ schedlock_applies (struct thread_info *tp)
 					    execution_direction)));
 }
 
-/* Set process_stratum_target::COMMIT_RESUMED_STATE in all target
-   stacks that have threads executing and don't have threads with
-   pending events.  */
+/* When FORCE_P is false, set process_stratum_target::COMMIT_RESUMED_STATE
+   in all target stacks that have threads executing and don't have threads
+   with pending events.
+
+   When FORCE_P is true, set process_stratum_target::COMMIT_RESUMED_STATE
+   in all target stacks that have threads executing regardless of whether
+   there are pending events or not.
+
+    Passing FORCE_P as false makes sense when GDB is going to wait for
+    events from all threads and will therefore spot the pending events.
+    However, if GDB is only going to wait for events from select threads
+    (i.e. when performing an inferior call) then a pending event on some
+    other thread will not be spotted, and if we fail to commit the resume
+    state for the thread performing the inferior call, then the inferior
+    call will never complete (or even start).  */
 
 static void
-maybe_set_commit_resumed_all_targets ()
+maybe_set_commit_resumed_all_targets (bool force_p)
 {
   scoped_restore_current_thread restore_thread;
 
@@ -3026,7 +3046,7 @@ maybe_set_commit_resumed_all_targets ()
 	 status to report, handle it before requiring the target to
 	 commit its resumed threads: handling the status might lead to
 	 resuming more threads.  */
-      if (proc_target->has_resumed_with_pending_wait_status ())
+      if (!force_p && proc_target->has_resumed_with_pending_wait_status ())
 	{
 	  infrun_debug_printf ("not requesting commit-resumed for target %s, a"
 			       " thread has a pending waitstatus",
@@ -3036,7 +3056,7 @@ maybe_set_commit_resumed_all_targets ()
 
       switch_to_inferior_no_thread (inf);
 
-      if (target_has_pending_events ())
+      if (!force_p && target_has_pending_events ())
 	{
 	  infrun_debug_printf ("not requesting commit-resumed for target %s, "
 			       "target has pending events",
@@ -3129,7 +3149,7 @@ scoped_disable_commit_resumed::reset ()
     {
       /* This is the outermost instance, re-enable
 	 COMMIT_RESUMED_STATE on the targets where it's possible.  */
-      maybe_set_commit_resumed_all_targets ();
+      maybe_set_commit_resumed_all_targets (false);
     }
   else
     {
@@ -3162,7 +3182,7 @@ scoped_disable_commit_resumed::reset_and_commit ()
 /* See infrun.h.  */
 
 scoped_enable_commit_resumed::scoped_enable_commit_resumed
-  (const char *reason)
+  (const char *reason, bool force_p)
   : m_reason (reason),
     m_prev_enable_commit_resumed (enable_commit_resumed)
 {
@@ -3174,7 +3194,7 @@ scoped_enable_commit_resumed::scoped_enable_commit_resumed
 
       /* Re-enable COMMIT_RESUMED_STATE on the targets where it's
 	 possible.  */
-      maybe_set_commit_resumed_all_targets ();
+      maybe_set_commit_resumed_all_targets (force_p);
 
       maybe_call_commit_resumed_all_targets ();
     }
@@ -3880,10 +3900,11 @@ do_target_wait (ptid_t wait_ptid, execution_control_state *ecs,
      polling the rest of the inferior list starting from that one in a
      circular fashion until the whole list is polled once.  */
 
-  auto inferior_matches = [&wait_ptid] (inferior *inf)
+  ptid_t wait_ptid_pid {wait_ptid.pid ()};
+  auto inferior_matches = [&wait_ptid_pid] (inferior *inf)
     {
       return (inf->process_target () != nullptr
-	      && ptid_t (inf->pid).matches (wait_ptid));
+	      && ptid_t (inf->pid).matches (wait_ptid_pid));
     };
 
   /* First see how many matching inferiors we have.  */
@@ -4352,7 +4373,17 @@ fetch_inferior_event ()
        the event.  */
     scoped_disable_commit_resumed disable_commit_resumed ("handling event");
 
-    if (!do_target_wait (minus_one_ptid, &ecs, TARGET_WNOHANG))
+    /* Is the current thread performing an inferior function call as part
+       of a breakpoint condition evaluation?  */
+    bool in_cond_eval = (inferior_ptid != null_ptid
+			 && inferior_thread ()->control.in_cond_eval);
+
+    /* If the thread is in the middle of the condition evaluation, wait for
+       an event from the current thread.  Otherwise, wait for an event from
+       any thread.  */
+    ptid_t waiton_ptid = in_cond_eval ? inferior_ptid : minus_one_ptid;
+
+    if (!do_target_wait (waiton_ptid, &ecs, TARGET_WNOHANG))
       {
 	infrun_debug_printf ("do_target_wait returned no event");
 	disable_commit_resumed.reset_and_commit ();
@@ -4408,7 +4439,12 @@ fetch_inferior_event ()
 	    bool should_notify_stop = true;
 	    bool proceeded = false;
 
-	    stop_all_threads_if_all_stop_mode ();
+	    /* If the thread that stopped just completed an inferior
+	       function call as part of a condition evaluation, then we
+	       don't want to stop all the other threads.  */
+	    if (ecs.event_thread == nullptr
+		|| !ecs.event_thread->control.in_cond_eval)
+	      stop_all_threads_if_all_stop_mode ();
 
 	    clean_up_just_stopped_threads_fsms (&ecs);
 
@@ -4423,7 +4459,7 @@ fetch_inferior_event ()
 		  proceeded = normal_stop ();
 	      }
 
-	    if (!proceeded)
+	    if (!proceeded && !in_cond_eval)
 	      {
 		inferior_event_handler (INF_EXEC_COMPLETE);
 		cmd_done = 1;
diff --git a/gdb/infrun.h b/gdb/infrun.h
index 9513bc570e4..1a6743aa45e 100644
--- a/gdb/infrun.h
+++ b/gdb/infrun.h
@@ -395,7 +395,8 @@ extern void maybe_call_commit_resumed_all_targets ();
 
 struct scoped_enable_commit_resumed
 {
-  explicit scoped_enable_commit_resumed (const char *reason);
+  explicit scoped_enable_commit_resumed (const char *reason,
+					 bool force_p = false);
   ~scoped_enable_commit_resumed ();
 
   DISABLE_COPY_AND_ASSIGN (scoped_enable_commit_resumed);
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
new file mode 100644
index 00000000000..e2a8ccb4ebe
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
@@ -0,0 +1,135 @@
+/* Copyright 2022-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 <pthread.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <sched.h>
+
+#define NUM_THREADS 2
+
+pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+
+/* Some global variables to poke, just for something to do.  */
+volatile int global_var_0 = 0;
+volatile int global_var_1 = 0;
+
+/* This flag is updated from GDB.  */
+volatile int raise_signal = 0;
+
+/* Implement the breakpoint condition function.  Release the other thread
+   and try to give the other thread a chance to run.  Then return ANSWER.  */
+int
+condition_core_func (int answer)
+{
+  /* This unlock should release the other thread.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  /* And this yield and sleep should (hopefully) give the other thread a
+     chance to run.  This isn't guaranteed of course, but once the other
+     thread does run it should hit a breakpoint, which GDB should
+     (temporarily) ignore, so there's no easy way for us to know the other
+     thread has done what it needs to, thus, yielding and sleeping is the
+     best we can do.  */
+  sched_yield ();
+  sleep (2);
+
+  return answer;
+}
+
+void
+stop_marker ()
+{
+  int a = 100;	/* Final breakpoint here.  */
+}
+
+/* A breakpoint condition function that always returns true.  */
+int
+condition_true_func ()
+{
+  return condition_core_func (1);
+}
+
+/* A breakpoint condition function that always returns false.  */
+int
+condition_false_func ()
+{
+  return condition_core_func (0);
+}
+
+void *
+worker_func (void *arg)
+{
+  volatile int *ptr = 0;
+  int tid = *((int *) arg);
+
+  switch (tid)
+    {
+    case 0:
+      global_var_0 = 11;	/* First thread breakpoint.  */
+      break;
+
+    case 1:
+      if (pthread_mutex_lock (&mutex) != 0)
+	abort ();
+      if (raise_signal)
+	global_var_1 = *ptr;	/* Signal here.  */
+      else
+	global_var_1 = 99;	/* Other thread breakpoint.  */
+      break;
+
+    default:
+      abort ();
+    }
+
+  return NULL;
+}
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+
+  /* Set an alarm, just in case the test deadlocks.  */
+  alarm (300);
+
+  /* We want the mutex to start locked.  */
+  if (pthread_mutex_lock (&mutex) != 0)
+    abort ();
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      void *retval;
+      pthread_join (threads[i], &retval);
+    }
+
+  /* Unlock once we're done, just for cleanliness.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
new file mode 100644
index 00000000000..6d4e1e13ab2
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
@@ -0,0 +1,174 @@
+# Copyright 2022-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/>.
+
+# Test for conditional breakpoints where the breakpoint condition includes
+# an inferior function call.
+#
+# The tests in this script are testing what happens when an event arrives in
+# another thread while GDB is waiting for the inferior function call (in the
+# breakpoint condition) to finish.
+#
+# The expectation is that GDB will queue events for other threads and wait
+# for the inferior function call to complete, if the condition is true, then
+# the conditional breakpoint should be reported first.  The other thread
+# event should of course, not get lost, and should be reported as soon as
+# the user tries to continue the inferior.
+#
+# If the conditional breakpoint ends up not being taken (the condition is
+# false), then the other thread event should be reported immediately.
+#
+# This script tests what happens when the other thread event is (a) the
+# other thread hitting a breakpoint, and (b) the other thread taking a
+# signal (SIGSEGV in this case).
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] == -1 } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "First thread breakpoint"]
+set other_bp_line [gdb_get_line_number "Other thread breakpoint"]
+set final_bp_line [gdb_get_line_number "Final breakpoint here"]
+set signal_line [gdb_get_line_number "Signal here"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if { ![runto_main] } {
+	return -1
+    }
+
+    return 0
+}
+
+# Run a test of GDB's conditional breakpoints, where the conditions include
+# inferior function calls.  While the inferior function call is executing
+# another thread will hit a breakpoint (when OTHER_THREAD_SIGNAL is false),
+# or receive a signal (when OTHER_THREAD_SIGNAL is true).  GDB should report
+# the conditional breakpoint first (if the condition is true), and then
+# report the second thread event once the inferior is continued again.
+#
+# When STOP_AT_COND is true then the conditional breakpoint will have a
+# condition that evaluates to true (and the GDB will stop at the
+# breakpoint), otherwise, the condition will evaluate to false (and GDB will
+# not stop at the breakpoint).
+proc run_condition_test { stop_at_cond other_thread_signal \
+			      target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint.
+    if { $stop_at_cond } {
+	set cond_func "condition_true_func"
+    } else {
+	set cond_func "condition_false_func"
+    }
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (${cond_func} ())"
+    set cond_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			"get number for conditional breakpoint"]
+
+    if { $other_thread_signal } {
+	# Arrange for the other thread to raise a signal while GDB is
+	# evaluating the breakpoint condition.
+	gdb_test_no_output "set raise_signal = 1"
+    } else {
+	# And a breakpoint that will be hit by another thread only once the
+	# breakpoint condition starts to be evaluated.
+	gdb_breakpoint "${::srcfile}:${::other_bp_line}"
+	set other_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			      "get number for other breakpoint"]
+    }
+
+    # A final breakpoint once the test has completed.
+    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
+    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			  "get number for final breakpoint"]
+
+    if { $stop_at_cond } {
+	# Continue.  The first breakpoint we hit should be the conditional
+	# breakpoint.  The other thread will have hit its breakpoint, but
+	# that will have been deferred until the conditional breakpoint is
+	# reported.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${cond_bp_num}, worker_func \[^\r\n\]+:${::cond_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+First thread breakpoint\[^\r\n\]+"] \
+	    "hit the conditional breakpoint"
+    }
+
+    if { $other_thread_signal } {
+	# Now continue again, the other thread will now report that it
+	# received a signal.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" received signal SIGSEGV, Segmentation fault\\." \
+		 "\\\[Switching to Thread \[^\r\n\]+\\\]" \
+		 "${::hex} in worker_func \[^\r\n\]+:${::signal_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Signal here\[^\r\n\]+"] \
+	    "received signal in other thread"
+    } else {
+	# Now continue again, the other thread will now report its
+	# breakpoint.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${other_bp_num}, worker_func \[^\r\n\]+:${::other_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Other thread breakpoint\[^\r\n\]+"] \
+	    "hit the breakpoint in other thread"
+
+	# Run to the stop marker.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${final_bp_num}, stop_marker \[^\r\n\]+:${::final_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Final breakpoint here\[^\r\n\]+"] \
+	    "hit the final breakpoint"
+    }
+
+    gdb_exit
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	foreach_with_prefix other_thread_signal { true false } {
+	    foreach_with_prefix stop_at_cond { true false } {
+		run_condition_test $stop_at_cond $other_thread_signal \
+		    $target_async $target_non_stop
+	    }
+	}
+    }
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
new file mode 100644
index 00000000000..9d746d8be49
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
@@ -0,0 +1,89 @@
+/* Copyright 2022-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 <pthread.h>
+#include <unistd.h>
+
+#define NUM_THREADS 3
+
+int
+is_matching_tid (int *tid_ptr, int tid_value)
+{
+  return *tid_ptr == tid_value;
+}
+
+int
+return_true ()
+{
+  return 1;
+}
+
+int
+return_false ()
+{
+  return 0;
+}
+
+int
+function_that_segfaults ()
+{
+  int *p = 0;
+  *p = 1;	/* Segfault happens here.   */
+}
+
+int
+function_with_breakpoint ()
+{
+  return 1;	/* Nested breakpoint.  */
+}
+
+void *
+worker_func (void *arg)
+{
+  int a = 42;	/* Breakpoint here.  */
+}
+
+void
+stop_marker ()
+{
+  int b = 99;	/* Stop marker.  */
+}
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+
+  alarm (300);
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      void *retval;
+      pthread_join (threads[i], &retval);
+    }
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
new file mode 100644
index 00000000000..37e1b64d9a4
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
@@ -0,0 +1,235 @@
+# Copyright 2022-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/>.
+
+# Some simple tests of inferior function calls from breakpoint
+# conditions, in multi-threaded inferiors.
+#
+# This test sets up a multi-threaded inferior, and places a breakpoint
+# at a location that many of the threads will reach.  We repeat the
+# test with different conditions, sometimes a single thread should
+# stop at the breakpoint, sometimes multiple threads should stop, and
+# sometime no threads should stop.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] == -1 } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "Breakpoint here"]
+set stop_bp_line [gdb_get_line_number "Stop marker"]
+set nested_bp_line [gdb_get_line_number "Nested breakpoint"]
+set segv_line [gdb_get_line_number "Segfault happens here"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if { ![runto_main] } {
+	return -1
+    }
+
+    return 0
+}
+
+# Run a test of GDB's conditional breakpoints, where the conditions include
+# inferior function calls.
+#
+# CONDITION is the expression to be used as the breakpoint condition.
+#
+# N_EXPECTED_HITS is the number of threads that we expect to stop due to
+# CONDITON.
+#
+# MESSAGE is used as a test name prefix.
+proc run_condition_test { message n_expected_hits condition \
+			      target_async target_non_stop } {
+    with_test_prefix $message {
+
+	if { [start_gdb_and_runto_main $target_async \
+		  $target_non_stop] == -1 } {
+	    return
+	}
+
+	# Use this convenience variable to track how often the
+	# breakpoint condition has been evaluated.  This should be
+	# once per thread.
+	gdb_test "set \$n_cond_eval = 0"
+
+	# Setup the conditional breakpoint.
+	gdb_breakpoint \
+	    "${::srcfile}:${::cond_bp_line} if ((++\$n_cond_eval) && (${condition}))"
+
+	# And a breakpoint that we hit when the test is over, this one is
+	# not conditional.  Only the main thread gets here once all the
+	# other threads have finished.
+	gdb_breakpoint "${::srcfile}:${::stop_bp_line}"
+
+	# The number of times we stop at the conditional breakpoint.
+	set n_hit_condition 0
+
+	# Now keep 'continue'-ing GDB until all the threads have finished
+	# and we reach the stop_marker breakpoint.
+	gdb_test_multiple "continue" "spot all breakpoint hits" {
+	    -re " worker_func \[^\r\n\]+${::srcfile}:${::cond_bp_line}\r\n${::decimal}\\s+\[^\r\n\]+Breakpoint here\[^\r\n\]+\r\n${::gdb_prompt} $" {
+		incr n_hit_condition
+		send_gdb "continue\n"
+		exp_continue
+	    }
+
+	    -re " stop_marker \[^\r\n\]+${::srcfile}:${::stop_bp_line}\r\n${::decimal}\\s+\[^\r\n\]+Stop marker\[^\r\n\]+\r\n${::gdb_prompt} $" {
+		pass $gdb_test_name
+	    }
+	}
+
+	gdb_assert { $n_hit_condition == $n_expected_hits } \
+	    "stopped at breakpoint the expected number of times"
+
+	# Ensure the breakpoint condition was evaluated once per thread.
+	gdb_test "print \$n_cond_eval" "= 3" \
+	    "condition was evaluated in each thread"
+    }
+}
+
+# Check that after handling a conditional breakpoint (where the condition
+# includes an inferior call), it is still possible to kill the running
+# inferior, and then restart the inferior.
+#
+# At once point doing this would result in GDB giving an assertion error.
+proc_with_prefix run_kill_and_restart_test { target_async target_non_stop } {
+    # This test relies on the 'start' command, which is not possible with
+    # the plain 'remote' target.
+    if { [target_info gdb_protocol] == "remote" } {
+	return
+    }
+
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint.
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 1))"
+    gdb_continue_to_breakpoint "worker_func"
+
+    # Now kill the program being debugged.
+    gdb_test "kill" "" "kill process" \
+	"Kill the program being debugged.*y or n. $" "y"
+
+    # Check we can restart the inferior.  At one point this would trigger an
+    # assertion.
+    gdb_test "start" ".*"
+}
+
+# Create a conditional breakpoint which includes a call to a function that
+# segfaults.  Run GDB and check what happens when the inferior segfaults
+# during the inferior call.
+proc_with_prefix run_bp_cond_segfaults { target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # This test relies on the inferior segfaulting when trying to
+    # access address zero.
+    if { [is_address_zero_readable] } {
+	return
+    }
+
+    # Setup the conditional breakpoint, include a call to
+    # 'function_that_segfaults', which triggers the segfault.
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 0) && function_that_segfaults ())"
+    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of conditional breakpoint"]
+
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     ".*" \
+	     "Thread ${::decimal} \"infcall-from-bp\" received signal SIGSEGV, Segmentation fault\\." \
+	     "${::hex} in function_that_segfaults \\(\\) at \[^\r\n\]+:${::segv_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Segfault happens here\[^\r\n\]+" \
+	     "Error in testing condition for breakpoint ${bp_1_num}:" \
+	     "The program being debugged was signaled while in a function called from GDB\\." \
+	     "GDB remains in the frame where the signal was received\\." \
+	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(function_that_segfaults\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+}
+
+# Create a conditional breakpoint which includes a call to a function that
+# itself has a breakpoint set within it.  Run GDB and check what happens
+# when GDB hits the nested breakpoint.
+proc_with_prefix run_bp_cond_hits_breakpoint { target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint, include a call to
+    # 'function_with_breakpoint' in which we will shortly place a
+    # breakpoint.
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 0) && function_with_breakpoint ())"
+    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of conditional breakpoint"]
+
+    gdb_breakpoint "${::srcfile}:${::nested_bp_line}"
+    set bp_2_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of nested breakpoint"]
+
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     ".*" \
+	     "Thread ${::decimal} \"infcall-from-bp\" hit Breakpoint ${bp_2_num}, function_with_breakpoint \\(\\) at \[^\r\n\]+:${::nested_bp_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Nested breakpoint\[^\r\n\]+" \
+	     "Error in testing condition for breakpoint ${bp_1_num}:" \
+	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(function_with_breakpoint\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	run_condition_test "exactly one thread is hit" \
+	    1 "is_matching_tid (arg, 1)" \
+	    $target_async $target_non_stop
+	run_condition_test "exactly two threads are hit" \
+	    2 "(is_matching_tid (arg, 0) || is_matching_tid (arg, 2))" \
+	    $target_async $target_non_stop
+	run_condition_test "all three threads are hit" \
+	    3 "return_true ()" \
+	    $target_async $target_non_stop
+	run_condition_test "no thread is hit" \
+	    0 "return_false ()" \
+	    $target_async $target_non_stop
+
+	run_kill_and_restart_test $target_async $target_non_stop
+	run_bp_cond_segfaults $target_async $target_non_stop
+	run_bp_cond_hits_breakpoint $target_async $target_non_stop
+    }
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
new file mode 100644
index 00000000000..835c72f03cf
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
@@ -0,0 +1,139 @@
+/* Copyright 2022-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 <pthread.h>
+#include <unistd.h>
+#include <semaphore.h>
+#include <stdlib.h>
+
+#define NUM_THREADS 5
+
+/* Semaphores, used to track when threads have started, and to control
+   when the threads finish.  */
+sem_t startup_semaphore;
+sem_t finish_semaphore;
+
+/* Mutex to control when the first worker thread hit a breakpoint
+   location.  */
+pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+
+/* Global variable to poke, just so threads have something to do.  */
+volatile int global_var = 0;
+
+int
+return_true ()
+{
+  return 1;
+}
+
+int
+return_false ()
+{
+  return 0;
+}
+
+void *
+worker_func (void *arg)
+{
+  int tid = *((int *) arg);
+
+  switch (tid)
+    {
+    case 0:
+      /* Wait for MUTEX to become available, then pass through the
+	 conditional breakpoint location.  */
+      if (pthread_mutex_lock (&mutex) != 0)
+	abort ();
+      global_var = 99;	/* Conditional breakpoint here.  */
+      if (pthread_mutex_unlock (&mutex) != 0)
+	abort ();
+      break;
+
+    default:
+      /* Notify the main thread that the thread has started, then wait for
+	 the main thread to tell us to finish.  */
+      sem_post (&startup_semaphore);
+      if (sem_wait (&finish_semaphore) != 0)
+	abort ();
+      break;
+    }
+}
+
+void
+stop_marker ()
+{
+  global_var = 99;	/* Stop marker.  */
+}
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+  void *retval;
+
+  /* An alarm, just in case the thread deadlocks.  */
+  alarm (300);
+
+  /* Semaphore initialization.  */
+  if (sem_init (&startup_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&finish_semaphore, 0, 0) != 0)
+    abort ();
+
+  /* Lock MUTEX, this prevents the first worker thread from rushing ahead.  */
+  if (pthread_mutex_lock (&mutex) != 0)
+    abort ();
+
+  /* Worker thread creation.  */
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  /* Wait for every thread (other than the first) to tell us it has started
+     up.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    {
+      if (sem_wait (&startup_semaphore) != 0)
+	abort ();
+    }
+
+  /* Unlock the first thread so it can proceed.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  /* Wait for the first thread only.  */
+  pthread_join (threads[0], &retval);
+
+  /* Now post FINISH_SEMAPHORE to allow all the other threads to finish.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    sem_post (&finish_semaphore);
+
+  /* Now wait for the remaining threads to complete.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    pthread_join (threads[i], &retval);
+
+  /* Semaphore cleanup.  */
+  sem_destroy (&finish_semaphore);
+  sem_destroy (&startup_semaphore);
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
new file mode 100644
index 00000000000..787dee3aa8e
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
@@ -0,0 +1,117 @@
+# Copyright 2022-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 reprocuces bug gdb/28942, performing an inferior function
+# call from a breakpoint condition in a multi-threaded inferior.
+#
+# The important part of this test is that, when the conditional
+# breakpoint is hit, and the condition (which includes an inferior
+# function call) is evaluated, the other threads are running.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] == -1 } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "Conditional breakpoint here"]
+set final_bp_line [gdb_get_line_number "Stop marker"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if { ![runto_main] } {
+	return -1
+    }
+
+    return 0
+}
+
+# Run a test of GDB's conditional breakpoints, where the conditions include
+# inferior function calls.
+#
+# TARGET_ASYNC and TARGET_NON_STOP are used when starting up GDB.
+#
+# When STOP_AT_COND is true the breakpoint condtion will evaluate to
+# true, and GDB will stop at the breakpoint.  Otherwise, the
+# breakpoint condition will evaluate to false and GDB will not stop at
+# the breakpoint.
+proc run_condition_test { stop_at_cond \
+			      target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint.
+    if { $stop_at_cond } {
+	set cond_func "return_true"
+    } else {
+	set cond_func "return_false"
+    }
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (${cond_func} ())"
+    set cond_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			"get number for conditional breakpoint"]
+
+    # And a breakpoint that we hit when the test is over, this one is
+    # not conditional.
+    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
+    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			  "get number for final breakpoint"]
+
+    if { $stop_at_cond } {
+	# Continue.  The first breakpoint we hit should be the conditional
+	# breakpoint.  The other thread will have hit its breakpoint, but
+	# that will have been deferred until the conditional breakpoint is
+	# reported.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${cond_bp_num}, worker_func \[^\r\n\]+:${::cond_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Conditional breakpoint here\[^\r\n\]+"] \
+	    "hit the conditional breakpoint"
+    }
+
+    # Run to the stop marker.
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     ".*" \
+	     "" \
+	     "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${final_bp_num}, stop_marker \[^\r\n\]+:${::final_bp_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Stop marker\[^\r\n\]+"] \
+	"hit the final breakpoint"
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	foreach_with_prefix stop_at_cond { true false } {
+	    run_condition_test $stop_at_cond \
+		$target_async $target_non_stop
+	}
+    }
+}
-- 
2.25.4


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

* [PATCHv7 3/6] gdb: add timeouts for inferior function calls
  2023-05-15 19:22           ` [PATCHv7 0/6] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
  2023-05-15 19:22             ` [PATCHv7 1/6] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
  2023-05-15 19:22             ` [PATCHv7 2/6] gdb: fix b/p conditions with infcalls in multi-threaded inferiors Andrew Burgess
@ 2023-05-15 19:22             ` Andrew Burgess
  2023-05-16 15:42               ` Aktemur, Tankut Baris
  2023-05-15 19:22             ` [PATCHv7 4/6] gdb/remote: avoid SIGINT after calling remote_target::stop Andrew Burgess
                               ` (3 subsequent siblings)
  6 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2023-05-15 19:22 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Eli already approved the docs part:
  https://sourceware.org/pipermail/gdb-patches/2023-January/196462.html

---

In the previous commits I have been working on improving inferior
function call support.  One thing that worries me about using inferior
function calls from a conditional breakpoint is: what happens if the
inferior function call fails?

If the failure is obvious, e.g. the thread performing the call
crashes, or hits a breakpoint, then this case is already well handled,
and the error is reported to the user.

But what if the thread performing the inferior call just deadlocks?
If the user made the call from a 'print' or 'call' command, then the
user might have some expectation of when the function call should
complete, and, when this time limit is exceeded, the user
will (hopefully) interrupt GDB and regain control of the debug
session.

But, when the inferior function call is from a breakpoint condition it
is much harder to understand that GDB is deadlocked within an inferior
call.  Maybe the breakpoint hasn't been hit yet?  Or maybe the
condition was always false?  Or maybe GDB is deadlocked in an inferior
call?  The only way to know for sure is to periodically interrupt GDB,
check on all the threads, and then continue.

Additionally, the focus of the previous commit was inferior function
calls, from a conditional breakpoint, in a multi-threaded inferior.
This opens up a whole new set of potential failure conditions.  For
example, what if the function called relies on interaction with some
other thread, and the other thread crashes?  Or hits a breakpoint?
Given how inferior function calls work (in a synchronous manner), a
stop event in some other thread is going to be ignored while the
inferior function call is being executed as part of a breakpoint
condition, and this means that GDB could get stuck waiting for the
original condition thread, which will now never complete.

In this commit I propose a solution to this problem.  A timeout.  For
targets that support async-mode we can install an event-loop timer
before starting the inferior function call.  When the timer expires we
will stop the thread performing the inferior function call.  With this
mechanism in place a user can be sure that any inferior call they make
will either complete, or timeout eventually.

Adding a timer like this is obviously a change in behaviour for the
more common 'call' and 'print' uses of inferior function calls, so, in
this patch, I propose having two different timers.  One I call the
'direct-call-timeout', which is used for 'call' and 'print' commands.
This timeout is by default set to unlimited, which, not surprisingly,
means there is no timeout in place.

A second timer, which I've called 'indirect-call-timeout', is used for
inferior function calls from breakpoint conditions.  This timeout has
a default value of 30 seconds.  This is a reasonably long time to
wait, and hopefully should be enough in most cases to allow the
inferior call to complete.  An inferior call that takes more than 30
seconds, which is installed on a breakpoint condition is really going
to slow down the debug session, so hopefully this is not a common use
case.

The user is, of course, free to reduce, or increase the timeout value,
and can always use Ctrl-c to interrupt an inferior function call, but
this timeout will ensure that GDB will stop at some point.

The new commands added by this commit are:

  set direct-call-timeout SECONDS
  show direct-call-timeout
  set indirect-call-timeout SECONDS
  show indirect-call-timeout

These new timeouts do depend on async-mode, so, if async-mode is
disabled (maint set target-async off), or not supported (e.g. target
sim), then the timeout is treated as unlimited (that is, no timeout is
set).

For targets that "fake" non-async mode, e.g. Linux native, where
non-async mode is really just async mode, but then we park the target
in a sissuspend, we could easily fix things so that the timeouts still
work, however, for targets that really are not async aware, like the
simulator, fixing things so that timeouts work correctly would be a
much bigger task - that effort would be better spent just making the
target async-aware.  And so, I'm happy for now that this feature will
only work on async targets.

The two new show commands will display slightly different text if the
current target is a non-async target, which should allow users to
understand what's going on.

There's a somewhat random test adjustment needed in gdb.base/help.exp,
the test uses a regexp with the apropos command, and expects to find a
single result.  Turns out the new settings I added also matched the
regexp, which broke the test.  I've updated the regexp a little to
exclude my new settings.

In infcall.c you'll notice the thread_info::stop_requested flag being
set when a timeout occurs.  This flag setting is not required as part
of this commit, but will be needed in a later commit.  However, it
seemed like setting this flag fitted better with this commit, which is
why the change is added here.
---
 gdb/NEWS                                      |  18 ++
 gdb/doc/gdb.texinfo                           |  66 ++++++
 gdb/infcall.c                                 | 221 +++++++++++++++++-
 gdb/testsuite/gdb.base/help.exp               |   2 +-
 gdb/testsuite/gdb.base/infcall-timeout.c      |  36 +++
 gdb/testsuite/gdb.base/infcall-timeout.exp    |  82 +++++++
 .../infcall-from-bp-cond-timeout.c            | 169 ++++++++++++++
 .../infcall-from-bp-cond-timeout.exp          | 156 +++++++++++++
 8 files changed, 745 insertions(+), 5 deletions(-)
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.c
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp

diff --git a/gdb/NEWS b/gdb/NEWS
index 6aa0d5171f2..216c3a95d09 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -100,6 +100,24 @@ info main
    $2 = 1
    (gdb) break func if $_shell("some command") == 0
 
+set direct-call-timeout SECONDS
+show direct-call-timeout
+set indirect-call-timeout SECONDS
+show indirect-call-timeout
+  These new settings can be used to limit how long GDB will wait for
+  an inferior function call to complete.  The direct timeout is used
+  for inferior function calls from e.g. 'call' and 'print' commands,
+  while the indirect timeout is used for inferior function calls from
+  within a conditional breakpoint expression.
+
+  The default for the direct timeout is unlimited, while the default
+  for the indirect timeout is 30 seconds.
+
+  These timeouts will only have an effect for targets that are
+  operating in async mode.  For non-async targets the timeouts are
+  ignored, GDB will wait indefinitely for an inferior function to
+  complete, unless interrupted by the user using Ctrl-C.
+
 * MI changes
 
 ** mi now reports 'no-history' as a stop reason when hitting the end of the
diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index 531147f6e6b..54668d812cb 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -20903,6 +20903,72 @@
 @code{step}, etc).  In this case, when the inferior finally returns to
 the dummy-frame, @value{GDBN} will once again halt the inferior.
 
+On targets that support asynchronous execution (@pxref{Background
+Execution}) @value{GDBN} can place a timeout on any functions called
+from @value{GDBN}.  If the timeout expires and the function call is
+still ongoing, then @value{GDBN} will interrupt the program.
+
+For targets that don't support asynchronous execution
+(@pxref{Background Execution}) then timeouts for functions called from
+@value{GDBN} are not supported, the timeout settings described below
+will be treated as @code{unlimited}, meaning @value{GDBN} will wait
+indefinitely for function call to complete, unless interrupted by the
+user using @kbd{Ctrl-C}.
+
+@table @code
+@item set direct-call-timeout @var{seconds}
+@kindex set direct-call-timeout
+@cindex timeout for called functions
+Set the timeout used when calling functions in the program to
+@var{seconds}, which should be an integer greater than zero, or the
+special value @code{unlimited}, which indicates no timeout should be
+used.  The default for this setting is @code{unlimited}.
+
+This setting is used when the user calls a function directly from the
+command prompt, for example with a @code{call} or @code{print}
+command.
+
+This setting only works for targets that support asynchronous
+execution (@pxref{Background Execution}), for any other target the
+setting is treated as @code{unlimited}.
+
+@item show direct-call-timeout
+@kindex show direct-call-timeout
+@cindex timeout for called functions
+Show the timeout used when calling functions in the program with a
+@code{call} or @code{print} command.
+@end table
+
+It is also possible to call functions within the program from the
+condition of a conditional breakpoint (@pxref{Conditions, ,Break
+Conditions}).  A different setting controls the timeout used for
+function calls made from a breakpoint condition.
+
+@table @code
+@item set indirect-call-timeout @var{seconds}
+@kindex set indirect-call-timeout
+@cindex timeout for called functions
+Set the timeout used when calling functions in the program from a
+breakpoint or watchpoint condition to @var{seconds}, which should be
+an integer greater than zero, or the special value @code{unlimited},
+which indicates no timeout should be used.  The default for this
+setting is @code{30} seconds.
+
+This setting only works for targets that support asynchronous
+execution (@pxref{Background Execution}), for any other target the
+setting is treated as @code{unlimited}.
+
+If a function called from a breakpoint or watchpoint condition times
+out, then @value{GDBN} will stop at the point where the timeout
+occurred.  The breakpoint condition evaluation will be abandoned.
+
+@item show indirect-call-timeout
+@kindex show indirect-call-timeout
+@cindex timeout for called functions
+Show the timeout used when calling functions in the program from a
+breakpoint or watchpoint condition.
+@end table
+
 @subsection Calling functions with no debug info
 
 @cindex no debug info functions
diff --git a/gdb/infcall.c b/gdb/infcall.c
index 49c88add394..dea7dc83062 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -96,6 +96,53 @@ show_may_call_functions_p (struct ui_file *file, int from_tty,
 	      value);
 }
 
+/* A timeout (in seconds) for direct inferior calls.  A direct inferior
+   call is one the user triggers from the prompt, e.g. with a 'call' or
+   'print' command.  Compare with the definition of indirect calls below.  */
+
+static unsigned int direct_call_timeout = UINT_MAX;
+
+/* Implement 'show direct-call-timeout'.  */
+
+static void
+show_direct_call_timeout (struct ui_file *file, int from_tty,
+			  struct cmd_list_element *c, const char *value)
+{
+  if (target_has_execution () && !target_can_async_p ())
+    gdb_printf (file, _("Current target does not support async mode, timeout "
+			"for direct inferior calls is \"unlimited\".\n"));
+  else if (direct_call_timeout == UINT_MAX)
+    gdb_printf (file, _("Timeout for direct inferior function calls "
+			"is \"unlimited\".\n"));
+  else
+    gdb_printf (file, _("Timeout for direct inferior function calls "
+			"is \"%s seconds\".\n"), value);
+}
+
+/* A timeout (in seconds) for indirect inferior calls.  An indirect inferior
+   call is one that originates from within GDB, for example, when
+   evaluating an expression for a conditional breakpoint.  Compare with
+   the definition of direct calls above.  */
+
+static unsigned int indirect_call_timeout = 30;
+
+/* Implement 'show indirect-call-timeout'.  */
+
+static void
+show_indirect_call_timeout (struct ui_file *file, int from_tty,
+			  struct cmd_list_element *c, const char *value)
+{
+  if (target_has_execution () && !target_can_async_p ())
+    gdb_printf (file, _("Current target does not support async mode, timeout "
+			"for indirect inferior calls is \"unlimited\".\n"));
+  else if (indirect_call_timeout == UINT_MAX)
+    gdb_printf (file, _("Timeout for indirect inferior function calls "
+			"is \"unlimited\".\n"));
+  else
+    gdb_printf (file, _("Timeout for indirect inferior function calls "
+			"is \"%s seconds\".\n"), value);
+}
+
 /* How you should pass arguments to a function depends on whether it
    was defined in K&R style or prototype style.  If you define a
    function using the K&R syntax that takes a `float' argument, then
@@ -590,6 +637,86 @@ call_thread_fsm::should_notify_stop ()
   return true;
 }
 
+/* A class to control creation of a timer that will interrupt a thread
+   during an inferior call.  */
+struct infcall_timer_controller
+{
+  /* Setup an event-loop timer that will interrupt PTID if the inferior
+     call takes too long.  DIRECT_CALL_P is true when this inferior call is
+     a result of the user using a 'print' or 'call' command, and false when
+     this inferior call is a result of e.g. a conditional breakpoint
+     expression, this is used to select which timeout to use.  */
+  infcall_timer_controller (thread_info *thr, bool direct_call_p)
+    : m_thread (thr)
+  {
+    unsigned int timeout
+      = direct_call_p ? direct_call_timeout : indirect_call_timeout;
+    if (timeout < UINT_MAX && target_can_async_p ())
+      {
+	int ms = timeout * 1000;
+	int id = create_timer (ms, infcall_timer_controller::timed_out, this);
+	m_timer_id.emplace (id);
+	infcall_debug_printf ("Setting up infcall timeout timer for "
+			      "ptid %s: %d milliseconds",
+			      m_thread->ptid.to_string ().c_str (), ms);
+      }
+  }
+
+  /* Destructor.  Ensure that the timer is removed from the event loop.  */
+  ~infcall_timer_controller ()
+  {
+    /* If the timer has already triggered, then it will have already been
+       deleted from the event loop.  If the timer has not triggered, then
+       delete it now.  */
+    if (m_timer_id.has_value () && !m_triggered)
+      delete_timer (*m_timer_id);
+
+    /* Just for clarity, discard the timer id now.  */
+    m_timer_id.reset ();
+  }
+
+  /* Return true if there was a timer in place, and the timer triggered,
+     otherwise, return false.  */
+  bool triggered_p ()
+  {
+    gdb_assert (!m_triggered || m_timer_id.has_value ());
+    return m_triggered;
+  }
+
+private:
+  /* The thread we should interrupt.  */
+  thread_info *m_thread;
+
+  /* Set true when the timer is triggered.  */
+  bool m_triggered = false;
+
+  /* Given a value when a timer is in place.  */
+  gdb::optional<int> m_timer_id;
+
+  /* Callback for the timer, forwards to ::trigger below.  */
+  static void
+  timed_out (gdb_client_data context)
+  {
+    infcall_timer_controller *ctrl
+      = static_cast<infcall_timer_controller *> (context);
+    ctrl->trigger ();
+  }
+
+  /* Called when the timer goes off.  Stop thread m_thread.  */
+  void
+  trigger ()
+  {
+    m_triggered = true;
+
+    scoped_disable_commit_resumed disable_commit_resumed ("infcall timeout");
+
+    infcall_debug_printf ("Stopping thread %s",
+			  m_thread->ptid.to_string ().c_str ());
+    target_stop (m_thread->ptid);
+    m_thread->stop_requested = true;
+  }
+};
+
 /* Subroutine of call_function_by_hand to simplify it.
    Start up the inferior and wait for it to stop.
    Return the exception if there's an error, or an exception with
@@ -600,13 +727,15 @@ call_thread_fsm::should_notify_stop ()
 
 static struct gdb_exception
 run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
-		   struct thread_info *call_thread, CORE_ADDR real_pc)
+		   struct thread_info *call_thread, CORE_ADDR real_pc,
+		   bool *timed_out_p)
 {
   INFCALL_SCOPED_DEBUG_ENTER_EXIT;
 
   struct gdb_exception caught_error;
   ptid_t call_thread_ptid = call_thread->ptid;
   int was_running = call_thread->state == THREAD_RUNNING;
+  *timed_out_p = false;
 
   infcall_debug_printf ("call function at %s in thread %s, was_running = %d",
 			core_addr_to_string (real_pc),
@@ -618,6 +747,16 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
   scoped_restore restore_in_infcall
     = make_scoped_restore (&call_thread->control.in_infcall, 1);
 
+  /* If the thread making the inferior call stops with a time out then the
+     stop_requested flag will be set.  However, we don't want changes to
+     this flag to leak back to our caller, we might be here to handle an
+     inferior call from a breakpoint condition, so leaving this flag set
+     would appear that the breakpoint stop was actually a requested stop,
+     which is not true, and will cause GDB to print extra messages to the
+     output.  */
+  scoped_restore restore_stop_requested
+    = make_scoped_restore (&call_thread->stop_requested, false);
+
   clear_proceed_status (0);
 
   /* Associate the FSM with the thread after clear_proceed_status
@@ -651,11 +790,23 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
       infrun_debug_show_threads ("non-exited threads after proceed for inferior-call",
 				 all_non_exited_threads ());
 
+      /* Setup a timer (if possible, and if the settings allow) to prevent
+	 the inferior call running forever.  */
+      bool direct_call_p = !call_thread->control.in_cond_eval;
+      infcall_timer_controller infcall_timer (call_thread, direct_call_p);
+
       /* Inferior function calls are always synchronous, even if the
 	 target supports asynchronous execution.  */
       wait_sync_command_done ();
 
-      infcall_debug_printf ("inferior call completed successfully");
+      /* If the timer triggered then the inferior call failed.  */
+      if (infcall_timer.triggered_p ())
+	{
+	  infcall_debug_printf ("inferior call timed out");
+	  *timed_out_p = true;
+	}
+      else
+	infcall_debug_printf ("inferior call completed successfully");
     }
   catch (gdb_exception &e)
     {
@@ -1309,6 +1460,10 @@ call_function_by_hand_dummy (struct value *function,
   scoped_restore restore_stopped_by_random_signal
     = make_scoped_restore (&stopped_by_random_signal, 0);
 
+  /* Set to true by the call to run_inferior_call below if the inferior
+     call is artificially interrupted by GDB due to taking too long.  */
+  bool timed_out_p = false;
+
   /* - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP -
      If you're looking to implement asynchronous dummy-frames, then
      just below is the place to chop this function in two..  */
@@ -1335,7 +1490,8 @@ call_function_by_hand_dummy (struct value *function,
 			      struct_addr);
     {
       std::unique_ptr<call_thread_fsm> sm_up (sm);
-      e = run_inferior_call (std::move (sm_up), call_thread.get (), real_pc);
+      e = run_inferior_call (std::move (sm_up), call_thread.get (), real_pc,
+			     &timed_out_p);
     }
 
     if (e.reason < 0)
@@ -1487,7 +1643,10 @@ When the function is done executing, GDB will silently stop."),
       std::string name = get_function_name (funaddr, name_buf,
 					    sizeof (name_buf));
 
-      if (stopped_by_random_signal)
+      /* If the inferior call timed out then it will have been interrupted
+	 by a signal, but we want to report this differently to the user,
+	 which is done later in this function.  */
+      if (stopped_by_random_signal && !timed_out_p)
 	{
 	  /* We stopped inside the FUNCTION because of a random
 	     signal.  Further execution of the FUNCTION is not
@@ -1531,6 +1690,36 @@ GDB remains in the frame where the signal was received.\n\
 To change this behavior use \"set unwindonsignal on\".\n\
 Evaluation of the expression containing the function\n\
 (%s) will be abandoned.\n\
+When the function is done executing, GDB will silently stop."),
+		     name.c_str ());
+	    }
+	}
+
+      if (timed_out_p)
+	{
+	  /* A timeout results in a signal being sent to the inferior.  */
+	  gdb_assert (stopped_by_random_signal);
+
+	  /* Indentation is weird here.  A later patch is going to move the
+	    following block into an if/else, so I'm leaving the indentation
+	    here to minimise the later patch.
+
+	    Also, the error message used below refers to 'set
+	    unwind-on-timeout' which doesn't exist yet.  This will be added
+	    in a later commit, I'm leaving this in for now to minimise the
+	    churn caused by the commit that adds unwind-on-timeout.  */
+	    {
+	      /* The user wants to stay in the frame where we stopped
+		 (default).  Discard inferior status, we're not at the same
+		 point we started at.  */
+	      discard_infcall_control_state (inf_status.release ());
+
+	      error (_("\
+The program being debugged timed out while in a function called from GDB.\n\
+GDB remains in the frame where the timeout occurred.\n\
+To change this behavior use \"set unwind-on-timeout on\".\n\
+Evaluation of the expression containing the function\n\
+(%s) will be abandoned.\n\
 When the function is done executing, GDB will silently stop."),
 		     name.c_str ());
 	    }
@@ -1644,6 +1833,30 @@ The default is to unwind the frame."),
 			   show_unwind_on_terminating_exception_p,
 			   &setlist, &showlist);
 
+  add_setshow_uinteger_cmd ("direct-call-timeout", no_class,
+			    &direct_call_timeout, _("\
+Set the timeout, for direct calls to inferior function calls."), _("\
+Show the timeout, for direct calls to inferior function calls."), _("\
+If running on a target that supports, and is running in, async mode\n\
+then this timeout is used for any inferior function calls triggered\n\
+directly from the prompt, i.e. from a 'call' or 'print' command.  The\n\
+timeout is specified in seconds."),
+			    nullptr,
+			    show_direct_call_timeout,
+			    &setlist, &showlist);
+
+  add_setshow_uinteger_cmd ("indirect-call-timeout", no_class,
+			    &indirect_call_timeout, _("\
+Set the timeout, for indirect calls to inferior function calls."), _("\
+Show the timeout, for indirect calls to inferior function calls."), _("\
+If running on a target that supports, and is running in, async mode\n\
+then this timeout is used for any inferior function calls triggered\n\
+indirectly, i.e. being made as part of a breakpoint, or watchpoint,\n\
+condition expression.  The timeout is specified in seconds."),
+			    nullptr,
+			    show_indirect_call_timeout,
+			    &setlist, &showlist);
+
   add_setshow_boolean_cmd
     ("infcall", class_maintenance, &debug_infcall,
      _("Set inferior call debugging."),
diff --git a/gdb/testsuite/gdb.base/help.exp b/gdb/testsuite/gdb.base/help.exp
index 87919a819ab..504bf90cc15 100644
--- a/gdb/testsuite/gdb.base/help.exp
+++ b/gdb/testsuite/gdb.base/help.exp
@@ -121,7 +121,7 @@ gdb_test "help info bogus-gdb-command" "Undefined info command: \"bogus-gdb-comm
 gdb_test "help gotcha" "Undefined command: \"gotcha\"\.  Try \"help\"\."
 
 # Test apropos regex.
-gdb_test "apropos \\\(print\[\^\[ bsiedf\\\".-\]\\\)" "handle -- Specify how to handle signals\."
+gdb_test "apropos \\\(print\[\^\[ bsiedf\\\"'.-\]\\\)" "handle -- Specify how to handle signals\."
 # Test apropos >1 word string.
 gdb_test "apropos handle signal" "handle -- Specify how to handle signals\."
 # Test apropos apropos.
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.c b/gdb/testsuite/gdb.base/infcall-timeout.c
new file mode 100644
index 00000000000..12774ca2599
--- /dev/null
+++ b/gdb/testsuite/gdb.base/infcall-timeout.c
@@ -0,0 +1,36 @@
+/* Copyright 2022-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 <unistd.h>
+
+/* This function is called from GDB.  */
+int
+function_that_never_returns ()
+{
+  while (1)
+    sleep (1);
+
+  return 0;
+}
+
+int
+main ()
+{
+  alarm (300);
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.exp b/gdb/testsuite/gdb.base/infcall-timeout.exp
new file mode 100644
index 00000000000..5e9cdc2fa0e
--- /dev/null
+++ b/gdb/testsuite/gdb.base/infcall-timeout.exp
@@ -0,0 +1,82 @@
+# Copyright 2022-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/>.
+
+# Test GDB's direct-call-timeout setting, that is, ensure that if an
+# inferior function call, invoked from e.g. a 'print' command, takes
+# too long, then GDB can interrupt it, and return control to the user.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug}] == -1 } {
+    return
+}
+
+# Start GDB according to TARGET_ASYNC and TARGET_NON_STOP, then adjust
+# the direct-call-timeout, and make an inferior function call that
+# will never return.  GDB should eventually timeout and stop the
+# inferior.
+proc_with_prefix run_test { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if {![runto_main]} {
+	fail "run to main"
+	return
+    }
+
+    gdb_test_no_output "set direct-call-timeout 5"
+
+    # When non-stop mode is off we get slightly different output from GDB.
+    if { [gdb_is_remote_or_extended_remote_target] && !$target_non_stop } {
+	set stopped_line_pattern "Program received signal SIGINT, Interrupt\\."
+    } else {
+	set stopped_line_pattern "Program stopped\\."
+    }
+
+    gdb_test "print function_that_never_returns ()" \
+	[multi_line \
+	     $stopped_line_pattern \
+	     ".*" \
+	     "The program being debugged timed out while in a function called from GDB\\." \
+	     "GDB remains in the frame where the timeout occurred\\." \
+	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(function_that_never_returns\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+
+    gdb_test "bt" ".* function_that_never_returns .*<function called from gdb>.*"
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+
+    if { !$target_async } {
+	# GDB can't timeout while waiting for a thread if the target
+	# runs with async-mode turned off; once the target is running
+	# GDB is effectively blocked until the target stops for some
+	# reason.
+	continue
+    }
+
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	run_test $target_async $target_non_stop
+    }
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
new file mode 100644
index 00000000000..4da4245746e
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
@@ -0,0 +1,169 @@
+/* This testcase is part of GDB, the GNU debugger.
+
+   Copyright 2022-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 <stdio.h>
+#include <pthread.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <semaphore.h>
+
+#define NUM_THREADS 5
+
+/* Semaphores, used to track when threads have started, and to control
+   when the threads finish.  */
+sem_t startup_semaphore;
+sem_t finish_semaphore;
+sem_t thread_1_semaphore;
+sem_t thread_2_semaphore;
+
+/* Mutex to control when the first worker thread hit a breakpoint
+   location.  */
+pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+
+/* Global variable to poke, just so threads have something to do.  */
+volatile int global_var = 0;
+
+int
+condition_func ()
+{
+  /* Let thread 2 run.  */
+  if (sem_post (&thread_2_semaphore) != 0)
+    abort ();
+
+  /* Wait for thread 2 to complete its actions.  */
+  if (sem_wait (&thread_1_semaphore) != 0)
+    abort ();
+
+  return 1;
+}
+
+void
+do_segfault ()
+{
+  volatile int *p = 0;
+  *p = 0;	/* Segfault here.  */
+}
+
+void *
+worker_func (void *arg)
+{
+  int tid = *((int *) arg);
+
+  /* Let the main thread know that this worker has started.  */
+  if (sem_post (&startup_semaphore) != 0)
+    abort ();
+
+  switch (tid)
+    {
+    case 0:
+      /* Wait for MUTEX to become available, then pass through the
+	 conditional breakpoint location.  */
+      if (pthread_mutex_lock (&mutex) != 0)
+	abort ();
+      global_var = 99;	/* Conditional breakpoint here.  */
+      if (pthread_mutex_unlock (&mutex) != 0)
+	abort ();
+      break;
+
+    case 1:
+      if (sem_wait (&thread_2_semaphore) != 0)
+	abort ();
+      do_segfault ();
+      if (sem_post (&thread_1_semaphore) != 0)
+	abort ();
+
+      /* Fall through.  */
+    default:
+      /* Wait until we are allowed to finish.  */
+      if (sem_wait (&finish_semaphore) != 0)
+	abort ();
+      break;
+    }
+}
+
+void
+stop_marker ()
+{
+  global_var = 99;	/* Stop marker.  */
+}
+
+/* The main program entry point.  */
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+  void *retval;
+
+  /* An alarm, just in case the thread deadlocks.  */
+  alarm (300);
+
+  /* Semaphore initialization.  */
+  if (sem_init (&startup_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&finish_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&thread_1_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&thread_2_semaphore, 0, 0) != 0)
+    abort ();
+
+  /* Lock MUTEX, this prevents the first worker thread from rushing ahead.  */
+  if (pthread_mutex_lock (&mutex) != 0)
+    abort ();
+
+  /* Worker thread creation.  */
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  /* Wait for every thread to start.  */
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      if (sem_wait (&startup_semaphore) != 0)
+	abort ();
+    }
+
+  /* Unlock the first thread so it can proceed.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  /* Wait for the first thread only.  */
+  pthread_join (threads[0], &retval);
+
+  /* Now post FINISH_SEMAPHORE to allow all the other threads to finish.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    sem_post (&finish_semaphore);
+
+  /* Now wait for the remaining threads to complete.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    pthread_join (threads[i], &retval);
+
+  /* Semaphore cleanup.  */
+  sem_destroy (&finish_semaphore);
+  sem_destroy (&startup_semaphore);
+  sem_destroy (&thread_1_semaphore);
+  sem_destroy (&thread_2_semaphore);
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
new file mode 100644
index 00000000000..4159288a39c
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
@@ -0,0 +1,156 @@
+# Copyright 2022-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 inferior calls executed from a breakpoint condition in
+# a multi-threaded program.
+#
+# This test has the inferior function call timeout, and checks how GDB
+# handles this situation.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "Conditional breakpoint here"]
+set final_bp_line [gdb_get_line_number "Stop marker"]
+set segfault_line [gdb_get_line_number "Segfault here"]
+
+# Setup GDB based on TARGET_ASYNC and TARGET_NON_STOP.  Setup some
+# breakpoints in the inferior, one of which has an inferior call
+# within its condition.
+#
+# Continue GDB, the breakpoint with inferior call will be hit, but the
+# inferior call will never return.  We expect GDB to timeout.
+#
+# The reason that the inferior call never completes is that a second
+# thread, on which the inferior call relies, either hits a breakpoint
+# (when OTHER_THREAD_BP is true), or crashes (when OTHER_THREAD_BP is
+# false).
+proc run_test { target_async target_non_stop other_thread_bp } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if {![runto_main]} {
+	fail "run to main"
+	return
+    }
+
+    # The default timeout for indirect inferior calls (e.g. inferior
+    # calls for conditional breakpoint expressions) is pretty high.
+    # We don't want the test to take too long, so reduce this.
+    #
+    # However, the test relies on a second thread hitting some event
+    # (either a breakpoint or signal) before this timeout expires.
+    #
+    # There is a chance that on a really slow system this might not
+    # happen, in which case the test might fail.
+    #
+    # However, we still allocate 5 seconds, which feels like it should
+    # be enough time in most cases, but maybe we need to do something
+    # smarter here?  Possibly we could have some initial run where the
+    # inferior doesn't timeout, but does perform the same interaction
+    # between threads, we could time that, and use that as the basis
+    # for this timeout.  For now though, we just hope 5 seconds is
+    # enough.
+    gdb_test_no_output "set indirect-call-timeout 5"
+
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (condition_func ())"
+    set bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		    "get number for conditional breakpoint"]
+
+    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
+    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			  "get number for final breakpoint"]
+
+    # The thread performing an inferior call relies on a second
+    # thread.  The second thread will segfault unless it hits a
+    # breakpoint first.  In either case the initial thread will not
+    # complete its inferior call.
+    if { $other_thread_bp } {
+	gdb_breakpoint "${::srcfile}:${::segfault_line}"
+	set segfault_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+				 "get number for segfault breakpoint"]
+    }
+
+    # When non-stop mode is off we get slightly different output from GDB.
+    if { [gdb_is_remote_or_extended_remote_target] && !$target_non_stop} {
+	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" received signal SIGINT, Interrupt\\."
+    } else {
+	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\."
+    }
+
+    gdb_test "continue" \
+	[multi_line \
+	     $stopped_line_pattern \
+	     ".*" \
+	     "Error in testing condition for breakpoint ${bp_num}:" \
+	     "The program being debugged timed out while in a function called from GDB\\." \
+	     "GDB remains in the frame where the timeout occurred\\." \
+	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(condition_func\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."] \
+	"expected timeout waiting for inferior call to complete"
+
+    # Remember that other thread that either crashed (with a segfault)
+    # or hit a breakpoint?  Now that the inferior call has timed out,
+    # if we try to resume then we should see the pending event from
+    # that other thread.
+    if { $other_thread_bp } {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${segfault_bp_num}, do_segfault \[^\r\n\]+:${::segfault_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"] \
+	    "hit the segfault breakpoint"
+    } else {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "Thread ${::decimal} \"infcall-from-bp\" received signal SIGSEGV, Segmentation fault\\." \
+		 "\\\[Switching to Thread \[^\r\n\]+\\\]" \
+		 "${::hex} in do_segfault \\(\\) at \[^\r\n\]+:${::segfault_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"] \
+	    "hit the segfault"
+    }
+}
+
+foreach_with_prefix target_async {"on" "off" } {
+
+    if { !$target_async } {
+	# GDB can't timeout while waiting for a thread if the target
+	# runs with async-mode turned off; once the target is running
+	# GDB is effectively blocked until the target stops for some
+	# reason.
+	continue
+    }
+
+    foreach_with_prefix target_non_stop {"off" "on"} {
+	foreach_with_prefix other_thread_bp { true false } {
+	    run_test $target_async $target_non_stop $other_thread_bp
+	}
+    }
+}
-- 
2.25.4


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

* [PATCHv7 4/6] gdb/remote: avoid SIGINT after calling remote_target::stop
  2023-05-15 19:22           ` [PATCHv7 0/6] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                               ` (2 preceding siblings ...)
  2023-05-15 19:22             ` [PATCHv7 3/6] gdb: add timeouts for inferior function calls Andrew Burgess
@ 2023-05-15 19:22             ` Andrew Burgess
  2023-05-16 16:00               ` Aktemur, Tankut Baris
  2023-05-15 19:22             ` [PATCHv7 5/6] gdb: introduce unwind-on-timeout setting Andrew Burgess
                               ` (2 subsequent siblings)
  6 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2023-05-15 19:22 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Currently, if the remote target is not running in non-stop mode, then,
when GDB calls remote_target::stop, we end up sending an interrupt
packet \x03 to the remote target.

If the user interrupts the inferior from the GDB prompt (e.g. by
typing Ctrl-c), then GDB calls remote_target::interrupt, which also
ends up sending the interrupt packet.

The problem here is that both of these mechanisms end up sending the
interrupt packet, which means, when the target stops with a SIGINT,
and this is reported back to GDB, we have no choice but to report this
to the user as a SIGINT stop event.

Now maybe this is the correct thing to do, after all the target has
been stopped with SIGINT.  However, this leads to an unfortunate
change in behaviour when comparing non-stop vs all-stop mode.

When running in non-stop mode, and remote_target::stop is called, the
target will be stopped with a vCont packet, and this stop is then
reported back to GDB as GDB_SIGNAL_0, this will cause GDB to print a
message like:

  Program stopped.

Or:

  Thread NN "binary name" stopped.

In contrast, when non-stop mode is off, we get messages like:

  Program received SIGINT, Segmentation fault.

Or:

  Thread NN "binary name" received SIGINT, Segmentation fault.

In this commit I propose making use of thread_info::stop_requested
within remote.c to know if the stop was triggered by GDB (and the
SIGINT should be hidden) or if the stop was a user interrupt, and the
SIGINT should be printed.

In remote_target::process_stop_reply if the inferior stopped with
SIGINT and the thread_info::stop_requested flag is set, then we change
the stop signal to GDB_SIGNAL_0.

Two of the tests added in the previous commit exposed this issue.  In
the previous commit the tests looked for either of the above
patterns.  In this commit I've updated these tests to only look for
the "stopped" based messages.

This commit is the reason why the previous commit took care to set the
thread_info::stop_requested flag in infcall.c.
---
 gdb/remote.c                                           | 10 ++++++++++
 gdb/testsuite/gdb.base/infcall-timeout.exp             |  9 +--------
 .../gdb.threads/infcall-from-bp-cond-timeout.exp       |  9 +--------
 3 files changed, 12 insertions(+), 16 deletions(-)

diff --git a/gdb/remote.c b/gdb/remote.c
index 8eaa1b2c4d1..c61eeeadc52 100644
--- a/gdb/remote.c
+++ b/gdb/remote.c
@@ -8275,6 +8275,16 @@ remote_target::process_stop_reply (struct stop_reply *stop_reply,
 	}
       else
 	{
+	  /* If this stop was actually requested by GDB then we can hide
+	     the SIGINT from the user.  */
+	  if (status->kind () == TARGET_WAITKIND_STOPPED
+	      && status->sig () == GDB_SIGNAL_INT)
+	    {
+	      thread_info *thr = this->find_thread (ptid);
+	      if (thr->stop_requested)
+		status->set_stopped (GDB_SIGNAL_0);
+	    }
+
 	  /* If the target works in all-stop mode, a stop-reply indicates that
 	     all the target's threads stopped.  */
 	  for (thread_info *tp : all_non_exited_threads (this))
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.exp b/gdb/testsuite/gdb.base/infcall-timeout.exp
index 5e9cdc2fa0e..beb488ffd1e 100644
--- a/gdb/testsuite/gdb.base/infcall-timeout.exp
+++ b/gdb/testsuite/gdb.base/infcall-timeout.exp
@@ -45,16 +45,9 @@ proc_with_prefix run_test { target_async target_non_stop } {
 
     gdb_test_no_output "set direct-call-timeout 5"
 
-    # When non-stop mode is off we get slightly different output from GDB.
-    if { [gdb_is_remote_or_extended_remote_target] && !$target_non_stop } {
-	set stopped_line_pattern "Program received signal SIGINT, Interrupt\\."
-    } else {
-	set stopped_line_pattern "Program stopped\\."
-    }
-
     gdb_test "print function_that_never_returns ()" \
 	[multi_line \
-	     $stopped_line_pattern \
+	     "Program stopped\\." \
 	     ".*" \
 	     "The program being debugged timed out while in a function called from GDB\\." \
 	     "GDB remains in the frame where the timeout occurred\\." \
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
index 4159288a39c..74f7def7dce 100644
--- a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
@@ -92,16 +92,9 @@ proc run_test { target_async target_non_stop other_thread_bp } {
 				 "get number for segfault breakpoint"]
     }
 
-    # When non-stop mode is off we get slightly different output from GDB.
-    if { [gdb_is_remote_or_extended_remote_target] && !$target_non_stop} {
-	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" received signal SIGINT, Interrupt\\."
-    } else {
-	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\."
-    }
-
     gdb_test "continue" \
 	[multi_line \
-	     $stopped_line_pattern \
+	     "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\." \
 	     ".*" \
 	     "Error in testing condition for breakpoint ${bp_num}:" \
 	     "The program being debugged timed out while in a function called from GDB\\." \
-- 
2.25.4


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

* [PATCHv7 5/6] gdb: introduce unwind-on-timeout setting
  2023-05-15 19:22           ` [PATCHv7 0/6] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                               ` (3 preceding siblings ...)
  2023-05-15 19:22             ` [PATCHv7 4/6] gdb/remote: avoid SIGINT after calling remote_target::stop Andrew Burgess
@ 2023-05-15 19:22             ` Andrew Burgess
  2023-05-15 19:22             ` [PATCHv7 6/6] gdb: rename unwindonsignal to unwind-on-signal Andrew Burgess
  2023-06-07 10:01             ` [PATCHv8 0/6] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
  6 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-05-15 19:22 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Eli already approved the docs part:
  https://sourceware.org/pipermail/gdb-patches/2023-January/195873.html

---

Now that inferior function calls can timeout (see the recent
introduction of direct-call-timeout and indirect-call-timeout), this
commit adds a new setting unwind-on-timeout.

This new setting is just like the existing unwindonsignal and
unwind-on-terminating-exception, but the new setting will cause GDB to
unwind the stack if an inferior function call times out.

The existing inferior function call timeout tests have been updated to
cover the new setting.
---
 gdb/NEWS                                      |  9 +++
 gdb/doc/gdb.texinfo                           | 25 ++++++--
 gdb/infcall.c                                 | 62 ++++++++++++++++---
 gdb/testsuite/gdb.base/infcall-timeout.exp    | 49 +++++++++++----
 .../infcall-from-bp-cond-timeout.exp          | 55 +++++++++++-----
 5 files changed, 160 insertions(+), 40 deletions(-)

diff --git a/gdb/NEWS b/gdb/NEWS
index 216c3a95d09..33ba5591fba 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -118,6 +118,15 @@ show indirect-call-timeout
   ignored, GDB will wait indefinitely for an inferior function to
   complete, unless interrupted by the user using Ctrl-C.
 
+set unwind-on-timeout on|off
+show unwind-on-timeout
+  These commands control whether GDB should unwind the stack when a
+  timeout occurs during an inferior function call.  The default is
+  off, in which case the inferior will remain in the frame where the
+  timeout occurred.  When on, GDB will unwind the stack removing the
+  dummy frame that was added for the inferior call, and restoring the
+  inferior state to how it was before the inferior call started.
+
 * MI changes
 
 ** mi now reports 'no-history' as a stop reason when hitting the end of the
diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index 54668d812cb..8fba4286781 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -20848,6 +20848,21 @@
 Show the current setting of stack unwinding in the functions called by
 @value{GDBN}.
 
+@item set unwind-on-timeout
+@kindex set unwind-on-timeout
+@cindex unwind stack in called functions when timing out
+@cindex call dummy stack unwinding on timeout.
+Set unwinding of the stack if a function called from @value{GDBN}
+times out.  If set to @code{off} (the default), @value{GDBN} stops in
+the frame where the timeout occurred.  If set to @code{on},
+@value{GDBN} unwinds the stack it created for the call and restores
+the context to what it was before the call.
+
+@item show unwind-on-timeout
+@kindex show unwind-on-timeout
+Show whether @value{GDBN} will unwind the stack if a function called
+from @value{GDBN} times out.
+
 @item set may-call-functions
 @kindex set may-call-functions
 @cindex disabling calling functions in the program
@@ -20879,11 +20894,11 @@
 
 If a called function is interrupted for any reason, including hitting
 a breakpoint, or triggering a watchpoint, and the stack is not unwound
-due to @code{set unwind-on-terminating-exception on} or @code{set
-unwindonsignal on} (@pxref{stack unwind settings}),
-then the dummy-frame, created by @value{GDBN} to facilitate the call
-to the program function, will be visible in the backtrace, for example
-frame @code{#3} in the following backtrace:
+due to @code{set unwind-on-terminating-exception on}, @code{set
+unwind-on-timeout on}, or @code{set unwindonsignal on} (@pxref{stack
+unwind settings}), then the dummy-frame, created by @value{GDBN} to
+facilitate the call to the program function, will be visible in the
+backtrace, for example frame @code{#3} in the following backtrace:
 
 @smallexample
 (@value{GDBP}) backtrace
diff --git a/gdb/infcall.c b/gdb/infcall.c
index dea7dc83062..886fed22441 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -218,6 +218,27 @@ show_unwind_on_terminating_exception_p (struct ui_file *file, int from_tty,
 	      value);
 }
 
+/* This boolean tells GDB what to do if an inferior function, called from
+   GDB, times out.  If true, GDB unwinds the stack and restores the context
+   to what it was before the call.  When false, GDB leaves the thread as it
+   is at the point of the timeout.
+
+   The default is to stop in the frame where the timeout occurred.  */
+
+static bool unwind_on_timeout_p = false;
+
+/* Implement 'show unwind-on-timeout'.  */
+
+static void
+show_unwind_on_timeout_p (struct ui_file *file, int from_tty,
+			  struct cmd_list_element *c, const char *value)
+{
+  gdb_printf (file,
+	      _("Unwinding of stack if a timeout occurs "
+		"while in a call dummy is %s.\n"),
+	      value);
+}
+
 /* Perform the standard coercions that are specified
    for arguments to be passed to C, Ada or Fortran functions.
 
@@ -1700,14 +1721,27 @@ When the function is done executing, GDB will silently stop."),
 	  /* A timeout results in a signal being sent to the inferior.  */
 	  gdb_assert (stopped_by_random_signal);
 
-	  /* Indentation is weird here.  A later patch is going to move the
-	    following block into an if/else, so I'm leaving the indentation
-	    here to minimise the later patch.
+	  if (unwind_on_timeout_p)
+	    {
+	      /* The user wants the context restored.  */
+
+	      /* We must get back to the frame we were before the
+		 dummy call.  */
+	      dummy_frame_pop (dummy_id, call_thread.get ());
 
-	    Also, the error message used below refers to 'set
-	    unwind-on-timeout' which doesn't exist yet.  This will be added
-	    in a later commit, I'm leaving this in for now to minimise the
-	    churn caused by the commit that adds unwind-on-timeout.  */
+	      /* We also need to restore inferior status to that before the
+		 dummy call.  */
+	      restore_infcall_control_state (inf_status.release ());
+
+	      error (_("\
+The program being debugged timed out while in a function called from GDB.\n\
+GDB has restored the context to what it was before the call.\n\
+To change this behavior use \"set unwind-on-timeout off\".\n\
+Evaluation of the expression containing the function\n\
+(%s) will be abandoned."),
+		     name.c_str ());
+	    }
+	  else
 	    {
 	      /* The user wants to stay in the frame where we stopped
 		 (default).  Discard inferior status, we're not at the same
@@ -1833,6 +1867,20 @@ The default is to unwind the frame."),
 			   show_unwind_on_terminating_exception_p,
 			   &setlist, &showlist);
 
+  add_setshow_boolean_cmd ("unwind-on-timeout", no_class,
+			   &unwind_on_timeout_p, _("\
+Set unwinding of stack if a timeout occurs while in a call dummy."), _("\
+Show unwinding of stack if a timeout occurs while in a call dummy."),
+			   _("\
+The unwind on timeout flag lets the user determine what gdb should do if\n\
+gdb times out while in a function called from gdb.  If set, gdb unwinds\n\
+the stack and restores the context to what it was before the call.  If\n\
+unset, gdb leaves the inferior in the frame where the timeout occurred.\n\
+The default is to stop in the frame where the timeout occurred."),
+			   NULL,
+			   show_unwind_on_timeout_p,
+			   &setlist, &showlist);
+
   add_setshow_uinteger_cmd ("direct-call-timeout", no_class,
 			    &direct_call_timeout, _("\
 Set the timeout, for direct calls to inferior function calls."), _("\
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.exp b/gdb/testsuite/gdb.base/infcall-timeout.exp
index beb488ffd1e..d063abc9077 100644
--- a/gdb/testsuite/gdb.base/infcall-timeout.exp
+++ b/gdb/testsuite/gdb.base/infcall-timeout.exp
@@ -28,7 +28,11 @@ if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
 # the direct-call-timeout, and make an inferior function call that
 # will never return.  GDB should eventually timeout and stop the
 # inferior.
-proc_with_prefix run_test { target_async target_non_stop } {
+#
+# When UNWIND is "off" the inferior wil be left in the frame where the
+# timeout occurs, otherwise, when UNWIND is "on", GDB should unwind
+# back to the frame where the inferior call was made.
+proc_with_prefix run_test { target_async target_non_stop unwind } {
     save_vars { ::GDBFLAGS } {
 	append ::GDBFLAGS \
 	    " -ex \"maint set target-non-stop $target_non_stop\""
@@ -44,19 +48,36 @@ proc_with_prefix run_test { target_async target_non_stop } {
     }
 
     gdb_test_no_output "set direct-call-timeout 5"
+    gdb_test_no_output "set unwind-on-timeout $unwind"
+
+    if { $unwind } {
+	gdb_test "print function_that_never_returns ()" \
+	    [multi_line \
+		 "Program stopped\\." \
+		 ".*" \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB has restored the context to what it was before the call\\." \
+		 "To change this behavior use \"set unwind-on-timeout off\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(function_that_never_returns\\) will be abandoned\\."]
 
-    gdb_test "print function_that_never_returns ()" \
-	[multi_line \
-	     "Program stopped\\." \
-	     ".*" \
-	     "The program being debugged timed out while in a function called from GDB\\." \
-	     "GDB remains in the frame where the timeout occurred\\." \
-	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
-	     "Evaluation of the expression containing the function" \
-	     "\\(function_that_never_returns\\) will be abandoned\\." \
-	     "When the function is done executing, GDB will silently stop\\."]
+	gdb_test "bt" \
+	    "#0\\s+main \\(\\).*"
+    } else {
+	gdb_test "print function_that_never_returns ()" \
+	    [multi_line \
+		 "Program stopped\\." \
+		 ".*" \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB remains in the frame where the timeout occurred\\." \
+		 "To change this behavior use \"set unwind-on-timeout on\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(function_that_never_returns\\) will be abandoned\\." \
+		 "When the function is done executing, GDB will silently stop\\."]
 
-    gdb_test "bt" ".* function_that_never_returns .*<function called from gdb>.*"
+	gdb_test "bt" \
+	    ".* function_that_never_returns .*<function called from gdb>.*"
+    }
 }
 
 foreach_with_prefix target_async { "on" "off" } {
@@ -70,6 +91,8 @@ foreach_with_prefix target_async { "on" "off" } {
     }
 
     foreach_with_prefix target_non_stop { "on" "off" } {
-	run_test $target_async $target_non_stop
+	foreach_with_prefix unwind { "on" "off" } {
+	    run_test $target_async $target_non_stop $unwind
+	}
     }
 }
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
index 74f7def7dce..f399b5420a2 100644
--- a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
@@ -41,7 +41,12 @@ set segfault_line [gdb_get_line_number "Segfault here"]
 # thread, on which the inferior call relies, either hits a breakpoint
 # (when OTHER_THREAD_BP is true), or crashes (when OTHER_THREAD_BP is
 # false).
-proc run_test { target_async target_non_stop other_thread_bp } {
+#
+# When UNWIND is "on" GDB will unwind the thread which performed the
+# inferior function call back to the state where the inferior call was
+# made (when the inferior call times out).  Otherwise, when UNWIND is
+# "off", the inferior is left in the frame where the timeout occurred.
+proc run_test { target_async target_non_stop other_thread_bp unwind } {
     save_vars { ::GDBFLAGS } {
 	append ::GDBFLAGS " -ex \"maint set target-non-stop $target_non_stop\""
 	append ::GDBFLAGS " -ex \"maintenance set target-async ${target_async}\""
@@ -72,6 +77,7 @@ proc run_test { target_async target_non_stop other_thread_bp } {
     # for this timeout.  For now though, we just hope 5 seconds is
     # enough.
     gdb_test_no_output "set indirect-call-timeout 5"
+    gdb_test_no_output "set unwind-on-timeout $unwind"
 
     gdb_breakpoint \
 	"${::srcfile}:${::cond_bp_line} if (condition_func ())"
@@ -92,18 +98,35 @@ proc run_test { target_async target_non_stop other_thread_bp } {
 				 "get number for segfault breakpoint"]
     }
 
-    gdb_test "continue" \
-	[multi_line \
-	     "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\." \
-	     ".*" \
-	     "Error in testing condition for breakpoint ${bp_num}:" \
-	     "The program being debugged timed out while in a function called from GDB\\." \
-	     "GDB remains in the frame where the timeout occurred\\." \
-	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
-	     "Evaluation of the expression containing the function" \
-	     "\\(condition_func\\) will be abandoned\\." \
-	     "When the function is done executing, GDB will silently stop\\."] \
-	"expected timeout waiting for inferior call to complete"
+    if { $unwind } {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\." \
+		 ".*" \
+		 "Error in testing condition for breakpoint ${bp_num}:" \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB has restored the context to what it was before the call\\." \
+		 "To change this behavior use \"set unwind-on-timeout off\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(condition_func\\) will be abandoned\\." \
+		 "" \
+		 "Thread ${::decimal}\[^\r\n\]*hit Breakpoint ${bp_num}, \[^\r\n\]+" \
+		 "\[^\r\n\]+ Conditional breakpoint here\\. \[^\r\n\]+"] \
+	    "expected timeout waiting for inferior call to complete"
+    } else {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\." \
+		 ".*" \
+		 "Error in testing condition for breakpoint ${bp_num}:" \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB remains in the frame where the timeout occurred\\." \
+		 "To change this behavior use \"set unwind-on-timeout on\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(condition_func\\) will be abandoned\\." \
+		 "When the function is done executing, GDB will silently stop\\."] \
+	    "expected timeout waiting for inferior call to complete"
+    }
 
     # Remember that other thread that either crashed (with a segfault)
     # or hit a breakpoint?  Now that the inferior call has timed out,
@@ -142,8 +165,10 @@ foreach_with_prefix target_async {"on" "off" } {
     }
 
     foreach_with_prefix target_non_stop {"off" "on"} {
-	foreach_with_prefix other_thread_bp { true false } {
-	    run_test $target_async $target_non_stop $other_thread_bp
+	foreach_with_prefix unwind {"off" "on"} {
+	    foreach_with_prefix other_thread_bp { true false } {
+		run_test $target_async $target_non_stop $other_thread_bp $unwind
+	    }
 	}
     }
 }
-- 
2.25.4


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

* [PATCHv7 6/6] gdb: rename unwindonsignal to unwind-on-signal
  2023-05-15 19:22           ` [PATCHv7 0/6] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                               ` (4 preceding siblings ...)
  2023-05-15 19:22             ` [PATCHv7 5/6] gdb: introduce unwind-on-timeout setting Andrew Burgess
@ 2023-05-15 19:22             ` Andrew Burgess
  2023-06-07 10:01             ` [PATCHv8 0/6] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
  6 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-05-15 19:22 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Eli already approved the docs part:
  https://sourceware.org/pipermail/gdb-patches/2023-January/195874.html

---

We now have unwind-on-timeout and unwind-on-terminating-exception, and
then the odd one out unwindonsignal.

I'm not a great fan of these squashed together command names, so in
this commit I propose renaming this to unwind-on-signal.

Obviously I've added the hidden alias unwindonsignal so any existing
GDB scripts will keep working.

There's one test that I've extended to test the alias works, but in
most of the other test scripts I've changed over to use the new name.

The docs are updated to reference the new name.
---
 gdb/NEWS                                      | 11 ++++++
 gdb/doc/gdb.texinfo                           | 16 ++++++---
 gdb/infcall.c                                 | 21 ++++++-----
 gdb/testsuite/gdb.base/callfuncs.exp          |  4 +--
 gdb/testsuite/gdb.base/infcall-failure.exp    |  4 +--
 gdb/testsuite/gdb.base/unwindonsignal.exp     | 36 +++++++++++++------
 gdb/testsuite/gdb.compile/compile-cplus.exp   |  2 +-
 gdb/testsuite/gdb.compile/compile.exp         |  2 +-
 gdb/testsuite/gdb.cp/gdb2495.exp              | 16 ++++-----
 gdb/testsuite/gdb.fortran/function-calls.exp  |  2 +-
 gdb/testsuite/gdb.mi/mi-syn-frame.exp         |  2 +-
 .../infcall-from-bp-cond-simple.exp           |  2 +-
 .../gdb.threads/thread-unwindonsignal.exp     |  8 ++---
 13 files changed, 83 insertions(+), 43 deletions(-)

diff --git a/gdb/NEWS b/gdb/NEWS
index 33ba5591fba..9a53c36d460 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -127,6 +127,17 @@ show unwind-on-timeout
   dummy frame that was added for the inferior call, and restoring the
   inferior state to how it was before the inferior call started.
 
+set unwind-on-signal on|off
+show unwind-on-signal
+  These new commands replaces the existing set/show unwindonsignal.  The
+  old command is maintained as an alias.
+
+* Changed commands
+
+set unwindonsignal on|off
+show unwindonsignal
+  These commands are now aliases for the new set/show unwind-on-signal.
+
 * MI changes
 
 ** mi now reports 'no-history' as a stop reason when hitting the end of the
diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index 8fba4286781..2e4181c2e48 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -20802,7 +20802,7 @@
 It is possible for the function you call via the @code{print} or
 @code{call} command to generate a signal (e.g., if there's a bug in
 the function, or if you passed it incorrect arguments).  What happens
-in that case is controlled by the @code{set unwindonsignal} command.
+in that case is controlled by the @code{set unwind-on-signal} command.
 
 Similarly, with a C@t{++} program it is possible for the function you
 call via the @code{print} or @code{call} command to generate an
@@ -20816,7 +20816,8 @@
 
 @anchor{stack unwind settings}
 @table @code
-@item set unwindonsignal
+@item set unwind-on-signal
+@kindex set unwind-on-signal
 @kindex set unwindonsignal
 @cindex unwind stack in called functions
 @cindex call dummy stack unwinding
@@ -20827,11 +20828,18 @@
 default), @value{GDBN} stops in the frame where the signal was
 received.
 
-@item show unwindonsignal
+The command @code{set unwindonsignal} is an alias for this command,
+and is maintained for backward compatibility.
+
+@item show unwind-on-signal
+@kindex show unwind-on-signal
 @kindex show unwindonsignal
 Show the current setting of stack unwinding in the functions called by
 @value{GDBN}.
 
+The command @code{show unwindonsignal} is an alias for this command,
+and is maintained for backward compatibility.
+
 @item set unwind-on-terminating-exception
 @kindex set unwind-on-terminating-exception
 @cindex unwind stack in called functions with unhandled exceptions
@@ -20895,7 +20903,7 @@
 If a called function is interrupted for any reason, including hitting
 a breakpoint, or triggering a watchpoint, and the stack is not unwound
 due to @code{set unwind-on-terminating-exception on}, @code{set
-unwind-on-timeout on}, or @code{set unwindonsignal on} (@pxref{stack
+unwind-on-timeout on}, or @code{set unwind-on-signal on} (@pxref{stack
 unwind settings}), then the dummy-frame, created by @value{GDBN} to
 facilitate the call to the program function, will be visible in the
 backtrace, for example frame @code{#3} in the following backtrace:
diff --git a/gdb/infcall.c b/gdb/infcall.c
index 886fed22441..60e794cb9a8 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -1690,7 +1690,7 @@ When the function is done executing, GDB will silently stop."),
 	      error (_("\
 The program being debugged was signaled while in a function called from GDB.\n\
 GDB has restored the context to what it was before the call.\n\
-To change this behavior use \"set unwindonsignal off\".\n\
+To change this behavior use \"set unwind-on-signal off\".\n\
 Evaluation of the expression containing the function\n\
 (%s) will be abandoned."),
 		     name.c_str ());
@@ -1708,7 +1708,7 @@ Evaluation of the expression containing the function\n\
 	      error (_("\
 The program being debugged was signaled while in a function called from GDB.\n\
 GDB remains in the frame where the signal was received.\n\
-To change this behavior use \"set unwindonsignal on\".\n\
+To change this behavior use \"set unwind-on-signal on\".\n\
 Evaluation of the expression containing the function\n\
 (%s) will be abandoned.\n\
 When the function is done executing, GDB will silently stop."),
@@ -1840,17 +1840,22 @@ The default is to perform the conversion."),
 			   show_coerce_float_to_double_p,
 			   &setlist, &showlist);
 
-  add_setshow_boolean_cmd ("unwindonsignal", no_class,
-			   &unwind_on_signal_p, _("\
+  set_show_commands setshow_unwind_on_signal_cmds
+    = add_setshow_boolean_cmd ("unwind-on-signal", no_class,
+			       &unwind_on_signal_p, _("\
 Set unwinding of stack if a signal is received while in a call dummy."), _("\
 Show unwinding of stack if a signal is received while in a call dummy."), _("\
-The unwindonsignal lets the user determine what gdb should do if a signal\n\
+The unwind-on-signal lets the user determine what gdb should do if a signal\n\
 is received while in a function called from gdb (call dummy).  If set, gdb\n\
 unwinds the stack and restore the context to what as it was before the call.\n\
 The default is to stop in the frame where the signal was received."),
-			   NULL,
-			   show_unwind_on_signal_p,
-			   &setlist, &showlist);
+			       NULL,
+			       show_unwind_on_signal_p,
+			       &setlist, &showlist);
+  add_alias_cmd ("unwindonsignal", setshow_unwind_on_signal_cmds.set,
+		 no_class, 1, &setlist);
+  add_alias_cmd ("unwindonsignal", setshow_unwind_on_signal_cmds.show,
+		 no_class, 1, &showlist);
 
   add_setshow_boolean_cmd ("unwind-on-terminating-exception", no_class,
 			   &unwind_on_terminating_exception_p, _("\
diff --git a/gdb/testsuite/gdb.base/callfuncs.exp b/gdb/testsuite/gdb.base/callfuncs.exp
index 2c797a224a7..d9f63e944bf 100644
--- a/gdb/testsuite/gdb.base/callfuncs.exp
+++ b/gdb/testsuite/gdb.base/callfuncs.exp
@@ -46,7 +46,7 @@ proc do_function_calls {prototypes} {
 
     # If any of these calls segv we don't want to affect subsequent tests.
     # E.g., we want to ensure register values are restored.
-    gdb_test_no_output "set unwindonsignal on"
+    gdb_test_no_output "set unwind-on-signal on"
 
     gdb_test "p t_char_values(0,0)" " = 0"
     gdb_test "p t_char_values('a','b')" " = 1"
@@ -237,7 +237,7 @@ proc do_function_calls {prototypes} {
     	"call inferior func with struct - returns char *"
 
     # Restore default value.
-    gdb_test_no_output "set unwindonsignal off"
+    gdb_test_no_output "set unwind-on-signal off"
 }
 
 # Procedure to get current content of all registers.
diff --git a/gdb/testsuite/gdb.base/infcall-failure.exp b/gdb/testsuite/gdb.base/infcall-failure.exp
index 5ad179a089d..e2e71649dac 100644
--- a/gdb/testsuite/gdb.base/infcall-failure.exp
+++ b/gdb/testsuite/gdb.base/infcall-failure.exp
@@ -137,7 +137,7 @@ proc_with_prefix run_cond_hits_segfault_test { async_p non_stop_p } {
 	     "Error in testing condition for breakpoint ${bp_1_num}:" \
 	     "The program being debugged was signaled while in a function called from GDB\\." \
 	     "GDB remains in the frame where the signal was received\\." \
-	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "To change this behavior use \"set unwind-on-signal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(func_segfault\\) will be abandoned\\." \
 	     "When the function is done executing, GDB will silently stop\\."]
@@ -166,7 +166,7 @@ proc_with_prefix run_call_hits_segfault_test { async_p non_stop_p } {
 	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
 	     "The program being debugged was signaled while in a function called from GDB\\." \
 	     "GDB remains in the frame where the signal was received\\." \
-	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "To change this behavior use \"set unwind-on-signal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(func_segfault\\) will be abandoned\\." \
 	     "When the function is done executing, GDB will silently stop\\."]
diff --git a/gdb/testsuite/gdb.base/unwindonsignal.exp b/gdb/testsuite/gdb.base/unwindonsignal.exp
index 625b0c4db12..9c1b36e95bc 100644
--- a/gdb/testsuite/gdb.base/unwindonsignal.exp
+++ b/gdb/testsuite/gdb.base/unwindonsignal.exp
@@ -34,34 +34,50 @@ gdb_test "break stop_here" "Breakpoint \[0-9\]* at .*"
 gdb_test "continue" "Continuing.*Breakpoint \[0-9\]*, stop_here.*" \
     "continue to breakpoint at stop_here"
 
-# Turn on unwindonsignal.
-gdb_test_no_output "set unwindonsignal on" \
-	"setting unwindonsignal"
+# Turn on unwind-on-signal.
+gdb_test_no_output "set unwind-on-signal on" \
+	"setting unwind-on-signal"
 
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
 	"Unwinding of stack .* is on." \
-	"showing unwindonsignal"
+	"showing unwind-on-signal"
+
+# For backward compatibility we maintain a 'unwindonsignal' alias for
+# 'unwind-on-signal', check it now.
+gdb_test "show unwindonsignal" \
+    "Unwinding of stack .* is on\\." \
+    "showing unwindonsignal alias"
+
+gdb_test_no_output "set unwindonsignal off" \
+    "setting unwindonsignal alias to off"
+
+gdb_test "show unwind-on-signal" \
+    "Unwinding of stack .* is off\\." \
+    "showing unwind-on-signal after setting via alias"
+
+gdb_test_no_output "set unwindonsignal on" \
+    "setting unwindonsignal alias to on"
 
 # Call function (causing the program to get a signal), and see if gdb handles
 # it properly.
 if {[gdb_test "call gen_signal ()"  \
 	 "\[\r\n\]*The program being debugged was signaled.*" \
-	 "unwindonsignal, inferior function call signaled"] != 0} {
+	 "inferior function call signaled"] != 0} {
     return 0
 }
 
 # Verify the stack got unwound.
 gdb_test "bt" \
     "#0 *\[x0-9a-f in\]*stop_here \\(.*\\) at .*#1 *\[x0-9a-f in\]*main \\(.*\\) at .*" \
-	"unwindonsignal, stack unwound"
+	"stack unwound"
 
 # Verify the dummy frame got removed from dummy_frame_stack.
 gdb_test_multiple "maint print dummy-frames" \
-	"unwindonsignal, dummy frame removed" {
+	"unwind-on-signal, dummy frame removed" {
     -re "\[\r\n\]*.*stack=.*code=.*\[\r\n\]+$gdb_prompt $" {
-	fail "unwindonsignal, dummy frame removed"
+	fail $gdb_test_name
     }
     -re "\[\r\n\]+$gdb_prompt $" {
-	pass "unwindonsignal, dummy frame removed"
+	pass $gdb_test_name
     }
 }
diff --git a/gdb/testsuite/gdb.compile/compile-cplus.exp b/gdb/testsuite/gdb.compile/compile-cplus.exp
index 4e887daeb29..22eebb44953 100644
--- a/gdb/testsuite/gdb.compile/compile-cplus.exp
+++ b/gdb/testsuite/gdb.compile/compile-cplus.exp
@@ -129,7 +129,7 @@ gdb_test "return" "\r\n#0  main .*" "return" \
 	 "Make _gdb_expr\\(__gdb_regs\\*\\) return now\\? \\(y or n\\) " "y"
 gdb_test "info sym $infcall_pc" "\r\nNo symbol matches .*" "info sym not found"
 
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 gdb_test "compile code *(volatile int *) 0 = 0;" \
     "The program being debugged was signaled while in a function called from GDB\\.\r\nGDB has restored the context to what it was before the call\\.\r\n.*" \
     "compile code segfault second"
diff --git a/gdb/testsuite/gdb.compile/compile.exp b/gdb/testsuite/gdb.compile/compile.exp
index f3d87cd2605..8822aab2e81 100644
--- a/gdb/testsuite/gdb.compile/compile.exp
+++ b/gdb/testsuite/gdb.compile/compile.exp
@@ -159,7 +159,7 @@ gdb_test "return" "\r\n#0  main .*" "return" \
 	 "Make _gdb_expr return now\\? \\(y or n\\) " "y"
 gdb_test "info sym $infcall_pc" "\r\nNo symbol matches .*" "info sym not found"
 
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 gdb_test "compile code *(volatile int *) 0 = 0;" \
     "The program being debugged was signaled while in a function called from GDB\\.\r\nGDB has restored the context to what it was before the call\\.\r\n.*" \
     "compile code segfault second"
diff --git a/gdb/testsuite/gdb.cp/gdb2495.exp b/gdb/testsuite/gdb.cp/gdb2495.exp
index e3c0cca3175..d7985e5db48 100644
--- a/gdb/testsuite/gdb.cp/gdb2495.exp
+++ b/gdb/testsuite/gdb.cp/gdb2495.exp
@@ -98,29 +98,29 @@ if {![runto_main]} {
 # behaviour; it should not.  Test both on and off states.
 
 # Turn on unwind on signal behaviour.
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 
 # Check that it is turned on.
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
     "signal is received while in a call dummy is on.*" \
     "turn on unwind on signal"
 
 # Check to see if new behaviour interferes with
 # normal signal handling in inferior function calls.
 gdb_test "p exceptions.raise_signal(1)" \
-    "To change this behavior use \"set unwindonsignal off\".*" \
-    "check for unwindonsignal off message"
+    "To change this behavior use \"set unwind-on-signal off\".*" \
+    "check for unwind-on-signal off message"
 
 # And reverse - turn off again.
-gdb_test_no_output "set unwindonsignal off"
+gdb_test_no_output "set unwind-on-signal off"
 
 # Check that it is actually turned off.
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
     "signal is received while in a call dummy is off.*" \
     "turn off unwind on signal"
 
 # Check to see if new behaviour interferes with
 # normal signal handling in inferior function calls.
 gdb_test "p exceptions.raise_signal(1)" \
-    "To change this behavior use \"set unwindonsignal on\".*" \
-    "check for unwindonsignal on message"
+    "To change this behavior use \"set unwind-on-signal on\".*" \
+    "check for unwind-on-signal on message"
diff --git a/gdb/testsuite/gdb.fortran/function-calls.exp b/gdb/testsuite/gdb.fortran/function-calls.exp
index f9a1efc241f..c4d1f232576 100644
--- a/gdb/testsuite/gdb.fortran/function-calls.exp
+++ b/gdb/testsuite/gdb.fortran/function-calls.exp
@@ -44,7 +44,7 @@ if {![runto [gdb_get_line_number "post_init"]]} {
 }
 
 # Use inspired by gdb.base/callfuncs.exp.
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 
 # Baseline: function and subroutine call with no arguments.
 gdb_test "p no_arg()" " = .TRUE."
diff --git a/gdb/testsuite/gdb.mi/mi-syn-frame.exp b/gdb/testsuite/gdb.mi/mi-syn-frame.exp
index 40df312a1cc..1324226412c 100644
--- a/gdb/testsuite/gdb.mi/mi-syn-frame.exp
+++ b/gdb/testsuite/gdb.mi/mi-syn-frame.exp
@@ -94,7 +94,7 @@ mi_gdb_test "409-stack-list-frames 0 0" \
 # 
 
 mi_gdb_test "410-data-evaluate-expression bar()" \
-  ".*410\\^error,msg=\"The program being debugged was signaled while in a function called from GDB.\\\\nGDB remains in the frame where the signal was received.\\\\nTo change this behavior use \\\\\"set unwindonsignal on\\\\\".\\\\nEvaluation of the expression containing the function\\\\n\\(bar\\) will be abandoned.\\\\nWhen the function is done executing, GDB will silently stop.\"" \
+  ".*410\\^error,msg=\"The program being debugged was signaled while in a function called from GDB.\\\\nGDB remains in the frame where the signal was received.\\\\nTo change this behavior use \\\\\"set unwind-on-signal on\\\\\".\\\\nEvaluation of the expression containing the function\\\\n\\(bar\\) will be abandoned.\\\\nWhen the function is done executing, GDB will silently stop.\"" \
   "call inferior function which raises exception"
 
 mi_gdb_test "411-stack-list-frames" "411\\^done,stack=\\\[frame=\{level=\"0\",addr=\"$hex\",func=\"bar\",file=\".*mi-syn-frame.c\",fullname=\"${fullname_syntax}${srcfile}\",line=\"$decimal\",arch=\"$any\"},frame=\{level=\"1\",addr=\"$hex\",func=\"<function called from gdb>\"\},frame=\{level=\"2\",addr=\"$hex\",func=\"main\",file=\".*mi-syn-frame.c\",fullname=\"${fullname_syntax}${srcfile}\",line=\"$decimal\",arch=\"$any\"}.*\\\]" "backtrace from inferior function at exception"
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
index 37e1b64d9a4..bb4402c0926 100644
--- a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
@@ -173,7 +173,7 @@ proc_with_prefix run_bp_cond_segfaults { target_async target_non_stop } {
 	     "Error in testing condition for breakpoint ${bp_1_num}:" \
 	     "The program being debugged was signaled while in a function called from GDB\\." \
 	     "GDB remains in the frame where the signal was received\\." \
-	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "To change this behavior use \"set unwind-on-signal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(function_that_segfaults\\) will be abandoned\\." \
 	     "When the function is done executing, GDB will silently stop\\."]
diff --git a/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp b/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp
index 68a99f66f1c..a9cedc0c466 100644
--- a/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp
+++ b/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp
@@ -13,7 +13,7 @@
 # You should have received a copy of the GNU General Public License
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-# Test use of unwindonsignal when a hand function call that gets interrupted
+# Test use of unwind-on-signal when a hand function call that gets interrupted
 # by a signal in another thread.
 
 set NR_THREADS 4
@@ -49,12 +49,12 @@ gdb_test "continue" \
 # We want the main thread (hand_call_with_signal) and
 # thread 1 (sigabrt_handler) to both run.
 
-# Do turn on unwindonsignal.
+# Do turn on unwind-on-signal.
 # We want to test gdb handling of the current thread changing when
 # unwindonsignal is in effect.
-gdb_test_no_output "set unwindonsignal on" \
+gdb_test_no_output "set unwind-on-signal on" \
 	"setting unwindonsignal"
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
 	"Unwinding of stack .* is on." \
 	"showing unwindonsignal"
 
-- 
2.25.4


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

* RE: [PATCHv7 1/6] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait"
  2023-05-15 19:22             ` [PATCHv7 1/6] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
@ 2023-05-16 15:08               ` Aktemur, Tankut Baris
  0 siblings, 0 replies; 202+ messages in thread
From: Aktemur, Tankut Baris @ 2023-05-16 15:08 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

On Monday, May 15, 2023 9:22 PM, Andrew Burgess wrote:
> This reverts commit ac0d67ed1dcf470bad6a3bc4800c2ddc9bedecca.
> 
> There was nothing wrong with the commit which I'm reverting here, but
> it removed some functionality that will be needed for a later commit;
> that is, the ability for GDB to ask for events from a specific ptid_t
> via the do_target_wait function.
> 
> In a follow up commit, this functionality will be used to implement
> inferior function calls in multi-threaded inferiors.
> 
> This is not a straight revert of the above commit.  Reverting the
> above commit replaces a 'nullptr' with 'NULL', I've gone in and
> changed that, preserving the 'nullptr'.

FWIW, this looks good to me.
Reviewed-By: Tankut Baris Aktemur <tankut.baris.aktemur@intel.com>

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] 202+ messages in thread

* RE: [PATCHv7 2/6] gdb: fix b/p conditions with infcalls in multi-threaded inferiors
  2023-05-15 19:22             ` [PATCHv7 2/6] gdb: fix b/p conditions with infcalls in multi-threaded inferiors Andrew Burgess
@ 2023-05-16 15:09               ` Aktemur, Tankut Baris
  2023-06-05 13:53                 ` Andrew Burgess
  0 siblings, 1 reply; 202+ messages in thread
From: Aktemur, Tankut Baris @ 2023-05-16 15:09 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches; +Cc: Saiapova, Natalia

On Monday, May 15, 2023 9:22 PM, Andrew Burgess wrote:
> This commit fixes bug PR 28942, that is, creating a conditional
> breakpoint in a multi-threaded inferior, where the breakpoint
> condition includes an inferior function call.
> 
> Currently, when a user tries to create such a breakpoint, then GDB
> will fail with:
> 
>   (gdb) break infcall-from-bp-cond-single.c:61 if (return_true ())
>   Breakpoint 2 at 0x4011fa: file
> /tmp/build/gdb/testsuite/../../../src/gdb/testsuite/gdb.threads/infcall-from-bp-cond-
> single.c, line 61.
>   (gdb) continue
>   Continuing.
>   [New Thread 0x7ffff7c5d700 (LWP 2460150)]
>   [New Thread 0x7ffff745c700 (LWP 2460151)]
>   [New Thread 0x7ffff6c5b700 (LWP 2460152)]
>   [New Thread 0x7ffff645a700 (LWP 2460153)]
>   [New Thread 0x7ffff5c59700 (LWP 2460154)]
>   Error in testing breakpoint condition:
>   Couldn't get registers: No such process.
>   An error occurred while in a function called from GDB.
>   Evaluation of the expression containing the function
>   (return_true) will be abandoned.
>   When the function is done executing, GDB will silently stop.
>   Selected thread is running.
>   (gdb)
> 
> Or, in some cases, like this:
> 
>   (gdb) break infcall-from-bp-cond-simple.c:56 if (is_matching_tid (arg, 1))
>   Breakpoint 2 at 0x401194: file
> /tmp/build/gdb/testsuite/../../../src/gdb/testsuite/gdb.threads/infcall-from-bp-cond-
> simple.c, line 56.
>   (gdb) continue
>   Continuing.
>   [New Thread 0x7ffff7c5d700 (LWP 2461106)]
>   [New Thread 0x7ffff745c700 (LWP 2461107)]
>   ../../src.release/gdb/nat/x86-linux-dregs.c:146: internal-error:
> x86_linux_update_debug_registers: Assertion `lwp_is_stopped (lwp)' failed.
>   A problem internal to GDB has been detected,
>   further debugging may prove unreliable.
> 
> The precise error depends on the exact thread state; so there's race
> conditions depending on which threads have fully started, and which
> have not.  But the underlying problem is always the same; when GDB
> tries to execute the inferior function call from within the breakpoint
> condition, GDB will, incorrectly, try to resume threads that are
> already running - GDB doesn't realise that some threads might already
> be running.
> 
> The solution proposed in this patch requires an additional member
> variable thread_info::in_cond_eval.  This flag is set to true (in
> breakpoint.c) when GDB is evaluating a breakpoint condition.
> 
> In user_visible_resume_ptid (infrun.c), when the in_cond_eval flag is
> true, then GDB will only try to resume the current thread, that is,
> the thread for which the breakpoint condition is being evaluated.
> This solves the problem of GDB trying to resume threads that are
> already running.
> 
> The next problem is that inferior function calls are assumed to be
> synchronous, that is, GDB doesn't expect to start an inferior function
> call in thread #1, then receive a stop from thread #2 for some other,
> unrelated reason.  To prevent GDB responding to an event from another
> thread, we update fetch_inferior_event and do_target_wait in infrun.c,
> so that, when an inferior function call (on behalf of a breakpoint
> condition) is in progress, we only wait for events from the current
> thread (the one evaluating the condition).
> 
> In do_target_wait I had to change the inferior_matches lambda
> function, which is used to select which inferior to wait on.
> Previously the logic was this:
> 
>    auto inferior_matches = [&wait_ptid] (inferior *inf)
>      {
>        return (inf->process_target () != nullptr
>                && ptid_t (inf->pid).matches (wait_ptid));
>      };
> 
> This compares the pid of the inferior against the complete ptid we
> want to wait on.  Before this commit wait_ptid was only ever
> minus_one_ptid (which is special, and means any process), and so every
> inferior would match.
> 
> After this commit though wait_ptid might represent a specific thread
> in a specific inferior.  If we compare the pid of the inferior to a
> specific ptid then these will not match.  The fix is to compare
> against the pid extracted from the wait_ptid, not against the complete
> wait_ptid itself.
> 
> In fetch_inferior_event, after receiving the event, we only want to
> stop all the other threads, and call inferior_event_handler with
> INF_EXEC_COMPLETE, if we are not evaluating a conditional breakpoint.
> If we are, then all the other threads should be left doing whatever
> they were before.  The inferior_event_handler call will be performed
> once the breakpoint condition has finished being evaluated, and GDB
> decides to stop or not.
> 
> The final problem that needs solving relates to GDB's commit-resume
> mechanism, which allows GDB to collect resume requests into a single
> packet in order to reduce traffic to a remote target.
> 
> The problem is that the commit-resume mechanism will not send any
> resume requests for an inferior if there are already events pending on
> the GDB side.
> 
> Imagine an inferior with two threads.  Both threads hit a breakpoint,
> maybe the same conditional breakpoint.  At this point there are two
> pending events, one for each thread.
> 
> GDB selects one of the events and spots that this is a conditional
> breakpoint, GDB evaluates the condition.
> 
> The condition includes an inferior function call, so GDB sets up for
> the call and resumes the one thread, the resume request is added to
> the commit-resume queue.
> 
> When the commit-resume queue is committed GDB sees that there is a
> pending event from another thread, and so doesn't send any resume
> requests to the actual target, GDB is assuming that when we wait we
> will select the event from the other thread.
> 
> However, as this is an inferior function call for a condition
> evaluation, we will not select the event from the other thread, we
> only care about events from the thread that is evaluating the
> condition - and the resume for this thread was never sent to the
> target.
> 
> And so, GDB hangs, waiting for an event from a thread that was never
> fully resumed.
> 
> To fix this issue I have added the concept of "forcing" the
> commit-resume queue.  When enabling commit resume, if the force flag
> is true, then any resumes will be committed to the target, even if
> there are other threads with pending events.
> 
> A note on authorship: this patch was based on some work done by
> Natalia Saiapova and Tankut Baris Aktemur from Intel[1].  I have made
> some changes to their work in this version.
> 
> Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=28942
> 
> [1] https://sourceware.org/pipermail/gdb-patches/2020-October/172454.html
> 
> Co-authored-by: Natalia Saiapova <natalia.saiapova@intel.com>
> Co-authored-by: Tankut Baris Aktemur <tankut.baris.aktemur@intel.com>

Thanks again for this.

I have a few minor comments inlined below.  Except those, it looks good to me.
There is already Co-authored-by above, but in case you'd like to also add:
Reviewed-By: Tankut Baris Aktemur <tankut.baris.aktemur@intel.com>

Regards
-Baris


> ---
>  gdb/breakpoint.c                              |   2 +
>  gdb/gdbthread.h                               |   3 +
>  gdb/infcall.c                                 |   6 +
>  gdb/infrun.c                                  |  64 +++--
>  gdb/infrun.h                                  |   3 +-
>  .../infcall-from-bp-cond-other-thread-event.c | 135 ++++++++++
>  ...nfcall-from-bp-cond-other-thread-event.exp | 174 +++++++++++++
>  .../gdb.threads/infcall-from-bp-cond-simple.c |  89 +++++++
>  .../infcall-from-bp-cond-simple.exp           | 235 ++++++++++++++++++
>  .../gdb.threads/infcall-from-bp-cond-single.c | 139 +++++++++++
>  .../infcall-from-bp-cond-single.exp           | 117 +++++++++
>  11 files changed, 952 insertions(+), 15 deletions(-)
>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
> 
> diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
> index fdb184ae81f..6fceed8f408 100644
> --- a/gdb/breakpoint.c
> +++ b/gdb/breakpoint.c
> @@ -5548,6 +5548,8 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
>  	{
>  	  try
>  	    {
> +	      scoped_restore reset_in_cond_eval
> +		= make_scoped_restore (&thread->control.in_cond_eval, true);
>  	      condition_result = breakpoint_cond_eval (cond);
>  	    }
>  	  catch (const gdb_exception_error &ex)
> diff --git a/gdb/gdbthread.h b/gdb/gdbthread.h
> index 7135515bf45..897752f2691 100644
> --- a/gdb/gdbthread.h
> +++ b/gdb/gdbthread.h
> @@ -171,6 +171,9 @@ struct thread_control_state
>       command.  This is used to decide whether "set scheduler-locking
>       step" behaves like "on" or "off".  */
>    int stepping_command = 0;
> +
> +  /* True if the thread is evaluating a BP condition.  */
> +  bool in_cond_eval = false;
>  };
> 
>  /* Inferior thread specific part of `struct infcall_suspend_state'.  */
> diff --git a/gdb/infcall.c b/gdb/infcall.c
> index 233ef5f29e9..49c88add394 100644
> --- a/gdb/infcall.c
> +++ b/gdb/infcall.c
> @@ -642,6 +642,12 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
> 
>        proceed (real_pc, GDB_SIGNAL_0);
> 
> +      /* Enable commit resume, but pass true for the force flag.  This
> +	 ensures any thread we set running in proceed will actually be
> +	 committed to the target, even if some other thread in the current
> +	 target has a pending event.  */
> +      scoped_enable_commit_resumed enable ("infcall", true);
> +
>        infrun_debug_show_threads ("non-exited threads after proceed for inferior-call",
>  				 all_non_exited_threads ());
> 
> diff --git a/gdb/infrun.c b/gdb/infrun.c
> index 07ef3c7c187..ea7ab6187ee 100644
> --- a/gdb/infrun.c
> +++ b/gdb/infrun.c
> @@ -2275,6 +2275,14 @@ user_visible_resume_ptid (int step)
>  	 mode.  */
>        resume_ptid = inferior_ptid;
>      }
> +  else if (inferior_ptid != null_ptid
> +	   && inferior_thread ()->control.in_cond_eval)
> +    {
> +      /* The inferior thread is evaluating a BP condition.  Other threads
> +	 might be stopped or running and we do not want to change their
> +	 state, thus, resume only the current thread.  */
> +      resume_ptid = inferior_ptid;
> +    }
>    else if (!sched_multi && target_supports_multi_process ())
>      {
>        /* Resume all threads of the current process (and none of other
> @@ -2992,12 +3000,24 @@ schedlock_applies (struct thread_info *tp)
>  					    execution_direction)));
>  }
> 
> -/* Set process_stratum_target::COMMIT_RESUMED_STATE in all target
> -   stacks that have threads executing and don't have threads with
> -   pending events.  */
> +/* When FORCE_P is false, set process_stratum_target::COMMIT_RESUMED_STATE
> +   in all target stacks that have threads executing and don't have threads
> +   with pending events.
> +
> +   When FORCE_P is true, set process_stratum_target::COMMIT_RESUMED_STATE
> +   in all target stacks that have threads executing regardless of whether
> +   there are pending events or not.
> +
> +    Passing FORCE_P as false makes sense when GDB is going to wait for
> +    events from all threads and will therefore spot the pending events.
> +    However, if GDB is only going to wait for events from select threads
> +    (i.e. when performing an inferior call) then a pending event on some
> +    other thread will not be spotted, and if we fail to commit the resume
> +    state for the thread performing the inferior call, then the inferior
> +    call will never complete (or even start).  */

There is one extra space of indentation above.  Is that intentional?

>  static void
> -maybe_set_commit_resumed_all_targets ()
> +maybe_set_commit_resumed_all_targets (bool force_p)
>  {
>    scoped_restore_current_thread restore_thread;
> 
> @@ -3026,7 +3046,7 @@ maybe_set_commit_resumed_all_targets ()
>  	 status to report, handle it before requiring the target to
>  	 commit its resumed threads: handling the status might lead to
>  	 resuming more threads.  */
> -      if (proc_target->has_resumed_with_pending_wait_status ())
> +      if (!force_p && proc_target->has_resumed_with_pending_wait_status ())
>  	{
>  	  infrun_debug_printf ("not requesting commit-resumed for target %s, a"
>  			       " thread has a pending waitstatus",
> @@ -3036,7 +3056,7 @@ maybe_set_commit_resumed_all_targets ()
> 
>        switch_to_inferior_no_thread (inf);
> 
> -      if (target_has_pending_events ())
> +      if (!force_p && target_has_pending_events ())
>  	{
>  	  infrun_debug_printf ("not requesting commit-resumed for target %s, "
>  			       "target has pending events",
> @@ -3129,7 +3149,7 @@ scoped_disable_commit_resumed::reset ()
>      {
>        /* This is the outermost instance, re-enable
>  	 COMMIT_RESUMED_STATE on the targets where it's possible.  */
> -      maybe_set_commit_resumed_all_targets ();
> +      maybe_set_commit_resumed_all_targets (false);
>      }
>    else
>      {
> @@ -3162,7 +3182,7 @@ scoped_disable_commit_resumed::reset_and_commit ()
>  /* See infrun.h.  */
> 
>  scoped_enable_commit_resumed::scoped_enable_commit_resumed
> -  (const char *reason)
> +  (const char *reason, bool force_p)
>    : m_reason (reason),
>      m_prev_enable_commit_resumed (enable_commit_resumed)
>  {
> @@ -3174,7 +3194,7 @@ scoped_enable_commit_resumed::scoped_enable_commit_resumed
> 
>        /* Re-enable COMMIT_RESUMED_STATE on the targets where it's
>  	 possible.  */
> -      maybe_set_commit_resumed_all_targets ();
> +      maybe_set_commit_resumed_all_targets (force_p);
> 
>        maybe_call_commit_resumed_all_targets ();
>      }
> @@ -3880,10 +3900,11 @@ do_target_wait (ptid_t wait_ptid, execution_control_state *ecs,
>       polling the rest of the inferior list starting from that one in a
>       circular fashion until the whole list is polled once.  */
> 
> -  auto inferior_matches = [&wait_ptid] (inferior *inf)
> +  ptid_t wait_ptid_pid {wait_ptid.pid ()};
> +  auto inferior_matches = [&wait_ptid_pid] (inferior *inf)
>      {
>        return (inf->process_target () != nullptr
> -	      && ptid_t (inf->pid).matches (wait_ptid));
> +	      && ptid_t (inf->pid).matches (wait_ptid_pid));
>      };
> 
>    /* First see how many matching inferiors we have.  */
> @@ -4352,7 +4373,17 @@ fetch_inferior_event ()
>         the event.  */
>      scoped_disable_commit_resumed disable_commit_resumed ("handling event");
> 
> -    if (!do_target_wait (minus_one_ptid, &ecs, TARGET_WNOHANG))
> +    /* Is the current thread performing an inferior function call as part
> +       of a breakpoint condition evaluation?  */
> +    bool in_cond_eval = (inferior_ptid != null_ptid
> +			 && inferior_thread ()->control.in_cond_eval);
> +
> +    /* If the thread is in the middle of the condition evaluation, wait for
> +       an event from the current thread.  Otherwise, wait for an event from
> +       any thread.  */
> +    ptid_t waiton_ptid = in_cond_eval ? inferior_ptid : minus_one_ptid;
> +
> +    if (!do_target_wait (waiton_ptid, &ecs, TARGET_WNOHANG))
>        {
>  	infrun_debug_printf ("do_target_wait returned no event");
>  	disable_commit_resumed.reset_and_commit ();
> @@ -4408,7 +4439,12 @@ fetch_inferior_event ()
>  	    bool should_notify_stop = true;
>  	    bool proceeded = false;
> 
> -	    stop_all_threads_if_all_stop_mode ();
> +	    /* If the thread that stopped just completed an inferior
> +	       function call as part of a condition evaluation, then we
> +	       don't want to stop all the other threads.  */
> +	    if (ecs.event_thread == nullptr
> +		|| !ecs.event_thread->control.in_cond_eval)
> +	      stop_all_threads_if_all_stop_mode ();
> 
>  	    clean_up_just_stopped_threads_fsms (&ecs);
> 
> @@ -4423,7 +4459,7 @@ fetch_inferior_event ()
>  		  proceeded = normal_stop ();
>  	      }
> 
> -	    if (!proceeded)
> +	    if (!proceeded && !in_cond_eval)
>  	      {
>  		inferior_event_handler (INF_EXEC_COMPLETE);
>  		cmd_done = 1;
> diff --git a/gdb/infrun.h b/gdb/infrun.h
> index 9513bc570e4..1a6743aa45e 100644
> --- a/gdb/infrun.h
> +++ b/gdb/infrun.h
> @@ -395,7 +395,8 @@ extern void maybe_call_commit_resumed_all_targets ();
> 
>  struct scoped_enable_commit_resumed
>  {
> -  explicit scoped_enable_commit_resumed (const char *reason);
> +  explicit scoped_enable_commit_resumed (const char *reason,
> +					 bool force_p = false);
>    ~scoped_enable_commit_resumed ();
> 
>    DISABLE_COPY_AND_ASSIGN (scoped_enable_commit_resumed);
> diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
> b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
> new file mode 100644
> index 00000000000..e2a8ccb4ebe
> --- /dev/null
> +++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
> @@ -0,0 +1,135 @@
> +/* Copyright 2022-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 <pthread.h>
> +#include <unistd.h>
> +#include <stdlib.h>
> +#include <sched.h>
> +
> +#define NUM_THREADS 2
> +
> +pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
> +
> +/* Some global variables to poke, just for something to do.  */
> +volatile int global_var_0 = 0;
> +volatile int global_var_1 = 0;
> +
> +/* This flag is updated from GDB.  */
> +volatile int raise_signal = 0;
> +
> +/* Implement the breakpoint condition function.  Release the other thread
> +   and try to give the other thread a chance to run.  Then return ANSWER.  */
> +int
> +condition_core_func (int answer)
> +{
> +  /* This unlock should release the other thread.  */
> +  if (pthread_mutex_unlock (&mutex) != 0)
> +    abort ();
> +
> +  /* And this yield and sleep should (hopefully) give the other thread a
> +     chance to run.  This isn't guaranteed of course, but once the other
> +     thread does run it should hit a breakpoint, which GDB should
> +     (temporarily) ignore, so there's no easy way for us to know the other
> +     thread has done what it needs to, thus, yielding and sleeping is the
> +     best we can do.  */
> +  sched_yield ();
> +  sleep (2);
> +
> +  return answer;
> +}
> +
> +void
> +stop_marker ()
> +{
> +  int a = 100;	/* Final breakpoint here.  */
> +}
> +
> +/* A breakpoint condition function that always returns true.  */
> +int
> +condition_true_func ()
> +{
> +  return condition_core_func (1);
> +}
> +
> +/* A breakpoint condition function that always returns false.  */
> +int
> +condition_false_func ()
> +{
> +  return condition_core_func (0);
> +}
> +
> +void *
> +worker_func (void *arg)
> +{
> +  volatile int *ptr = 0;
> +  int tid = *((int *) arg);
> +
> +  switch (tid)
> +    {
> +    case 0:
> +      global_var_0 = 11;	/* First thread breakpoint.  */
> +      break;
> +
> +    case 1:
> +      if (pthread_mutex_lock (&mutex) != 0)
> +	abort ();
> +      if (raise_signal)
> +	global_var_1 = *ptr;	/* Signal here.  */
> +      else
> +	global_var_1 = 99;	/* Other thread breakpoint.  */
> +      break;
> +
> +    default:
> +      abort ();
> +    }
> +
> +  return NULL;
> +}
> +
> +int
> +main ()
> +{
> +  pthread_t threads[NUM_THREADS];
> +  int args[NUM_THREADS];
> +
> +  /* Set an alarm, just in case the test deadlocks.  */
> +  alarm (300);
> +
> +  /* We want the mutex to start locked.  */
> +  if (pthread_mutex_lock (&mutex) != 0)
> +    abort ();
> +
> +  for (int i = 0; i < NUM_THREADS; i++)
> +    {
> +      args[i] = i;
> +      pthread_create (&threads[i], NULL, worker_func, &args[i]);
> +    }
> +
> +  for (int i = 0; i < NUM_THREADS; i++)
> +    {
> +      void *retval;
> +      pthread_join (threads[i], &retval);
> +    }
> +
> +  /* Unlock once we're done, just for cleanliness.  */
> +  if (pthread_mutex_unlock (&mutex) != 0)
> +    abort ();
> +
> +  stop_marker ();
> +
> +  return 0;
> +}
> diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
> b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
> new file mode 100644
> index 00000000000..6d4e1e13ab2
> --- /dev/null
> +++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
> @@ -0,0 +1,174 @@
> +# Copyright 2022-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/>.
> +
> +# Test for conditional breakpoints where the breakpoint condition includes
> +# an inferior function call.
> +#
> +# The tests in this script are testing what happens when an event arrives in
> +# another thread while GDB is waiting for the inferior function call (in the
> +# breakpoint condition) to finish.
> +#
> +# The expectation is that GDB will queue events for other threads and wait
> +# for the inferior function call to complete, if the condition is true, then
> +# the conditional breakpoint should be reported first.  The other thread
> +# event should of course, not get lost, and should be reported as soon as
> +# the user tries to continue the inferior.
> +#
> +# If the conditional breakpoint ends up not being taken (the condition is
> +# false), then the other thread event should be reported immediately.
> +#
> +# This script tests what happens when the other thread event is (a) the
> +# other thread hitting a breakpoint, and (b) the other thread taking a
> +# signal (SIGSEGV in this case).
> +
> +standard_testfile
> +
> +if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
> +	  {debug pthreads}] == -1 } {
> +    return
> +}
> +
> +set cond_bp_line [gdb_get_line_number "First thread breakpoint"]
> +set other_bp_line [gdb_get_line_number "Other thread breakpoint"]
> +set final_bp_line [gdb_get_line_number "Final breakpoint here"]
> +set signal_line [gdb_get_line_number "Signal here"]
> +
> +# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
> +proc start_gdb_and_runto_main { target_async target_non_stop } {
> +    save_vars { ::GDBFLAGS } {
> +	append ::GDBFLAGS \
> +	    " -ex \"maint set target-non-stop $target_non_stop\""
> +	append ::GDBFLAGS \
> +	    " -ex \"maintenance set target-async ${target_async}\""
> +
> +	clean_restart ${::binfile}
> +    }
> +
> +    if { ![runto_main] } {
> +	return -1
> +    }
> +
> +    return 0
> +}
> +
> +# Run a test of GDB's conditional breakpoints, where the conditions include
> +# inferior function calls.  While the inferior function call is executing
> +# another thread will hit a breakpoint (when OTHER_THREAD_SIGNAL is false),
> +# or receive a signal (when OTHER_THREAD_SIGNAL is true).  GDB should report
> +# the conditional breakpoint first (if the condition is true), and then
> +# report the second thread event once the inferior is continued again.
> +#
> +# When STOP_AT_COND is true then the conditional breakpoint will have a
> +# condition that evaluates to true (and the GDB will stop at the

Nit: No "the" before "GDB".

> +# breakpoint), otherwise, the condition will evaluate to false (and GDB will
> +# not stop at the breakpoint).
> +proc run_condition_test { stop_at_cond other_thread_signal \
> +			      target_async target_non_stop } {
> +    if { [start_gdb_and_runto_main $target_async \
> +	      $target_non_stop] == -1 } {
> +	return
> +    }
> +
> +    # Setup the conditional breakpoint.
> +    if { $stop_at_cond } {
> +	set cond_func "condition_true_func"
> +    } else {
> +	set cond_func "condition_false_func"
> +    }
> +    gdb_breakpoint \
> +	"${::srcfile}:${::cond_bp_line} if (${cond_func} ())"
> +    set cond_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
> +			"get number for conditional breakpoint"]
> +
> +    if { $other_thread_signal } {
> +	# Arrange for the other thread to raise a signal while GDB is
> +	# evaluating the breakpoint condition.
> +	gdb_test_no_output "set raise_signal = 1"
> +    } else {
> +	# And a breakpoint that will be hit by another thread only once the
> +	# breakpoint condition starts to be evaluated.
> +	gdb_breakpoint "${::srcfile}:${::other_bp_line}"
> +	set other_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
> +			      "get number for other breakpoint"]
> +    }
> +
> +    # A final breakpoint once the test has completed.
> +    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
> +    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
> +			  "get number for final breakpoint"]
> +
> +    if { $stop_at_cond } {
> +	# Continue.  The first breakpoint we hit should be the conditional
> +	# breakpoint.  The other thread will have hit its breakpoint, but
> +	# that will have been deferred until the conditional breakpoint is
> +	# reported.
> +	gdb_test "continue" \
> +	    [multi_line \
> +		 "Continuing\\." \
> +		 ".*" \
> +		 "" \
> +		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${cond_bp_num},
> worker_func \[^\r\n\]+:${::cond_bp_line}" \
> +		 "${::decimal}\\s+\[^\r\n\]+First thread breakpoint\[^\r\n\]+"] \
> +	    "hit the conditional breakpoint"
> +    }
> +
> +    if { $other_thread_signal } {
> +	# Now continue again, the other thread will now report that it
> +	# received a signal.
> +	gdb_test "continue" \
> +	    [multi_line \
> +		 "Continuing\\." \
> +		 ".*" \
> +		 "Thread ${::decimal} \"\[^\"\r\n\]+\" received signal SIGSEGV, Segmentation
> fault\\." \
> +		 "\\\[Switching to Thread \[^\r\n\]+\\\]" \
> +		 "${::hex} in worker_func \[^\r\n\]+:${::signal_line}" \
> +		 "${::decimal}\\s+\[^\r\n\]+Signal here\[^\r\n\]+"] \
> +	    "received signal in other thread"
> +    } else {
> +	# Now continue again, the other thread will now report its
> +	# breakpoint.
> +	gdb_test "continue" \
> +	    [multi_line \
> +		 "Continuing\\." \
> +		 ".*" \
> +		 "" \
> +		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${other_bp_num},
> worker_func \[^\r\n\]+:${::other_bp_line}" \
> +		 "${::decimal}\\s+\[^\r\n\]+Other thread breakpoint\[^\r\n\]+"] \
> +	    "hit the breakpoint in other thread"
> +
> +	# Run to the stop marker.
> +	gdb_test "continue" \
> +	    [multi_line \
> +		 "Continuing\\." \
> +		 ".*" \
> +		 "" \
> +		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${final_bp_num},
> stop_marker \[^\r\n\]+:${::final_bp_line}" \
> +		 "${::decimal}\\s+\[^\r\n\]+Final breakpoint here\[^\r\n\]+"] \
> +	    "hit the final breakpoint"
> +    }
> +
> +    gdb_exit

Is this really necessary?  We do clean_restart at the beginning of a test,
which exits GDB as the first thing.

> +}
> +
> +foreach_with_prefix target_async { "on" "off" } {
> +    foreach_with_prefix target_non_stop { "on" "off" } {
> +	foreach_with_prefix other_thread_signal { true false } {
> +	    foreach_with_prefix stop_at_cond { true false } {
> +		run_condition_test $stop_at_cond $other_thread_signal \
> +		    $target_async $target_non_stop
> +	    }
> +	}
> +    }
> +}
> diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
> b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
> new file mode 100644
> index 00000000000..9d746d8be49
> --- /dev/null
> +++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
> @@ -0,0 +1,89 @@
> +/* Copyright 2022-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 <pthread.h>
> +#include <unistd.h>
> +
> +#define NUM_THREADS 3
> +
> +int
> +is_matching_tid (int *tid_ptr, int tid_value)
> +{
> +  return *tid_ptr == tid_value;
> +}
> +
> +int
> +return_true ()
> +{
> +  return 1;
> +}
> +
> +int
> +return_false ()
> +{
> +  return 0;
> +}
> +
> +int
> +function_that_segfaults ()
> +{
> +  int *p = 0;
> +  *p = 1;	/* Segfault happens here.   */
> +}
> +
> +int
> +function_with_breakpoint ()
> +{
> +  return 1;	/* Nested breakpoint.  */
> +}
> +
> +void *
> +worker_func (void *arg)
> +{
> +  int a = 42;	/* Breakpoint here.  */
> +}
> +
> +void
> +stop_marker ()
> +{
> +  int b = 99;	/* Stop marker.  */
> +}
> +
> +int
> +main ()
> +{
> +  pthread_t threads[NUM_THREADS];
> +  int args[NUM_THREADS];
> +
> +  alarm (300);
> +
> +  for (int i = 0; i < NUM_THREADS; i++)
> +    {
> +      args[i] = i;
> +      pthread_create (&threads[i], NULL, worker_func, &args[i]);
> +    }
> +
> +  for (int i = 0; i < NUM_THREADS; i++)
> +    {
> +      void *retval;
> +      pthread_join (threads[i], &retval);
> +    }
> +
> +  stop_marker ();
> +
> +  return 0;
> +}
> diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
> b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
> new file mode 100644
> index 00000000000..37e1b64d9a4
> --- /dev/null
> +++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
> @@ -0,0 +1,235 @@
> +# Copyright 2022-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/>.
> +
> +# Some simple tests of inferior function calls from breakpoint
> +# conditions, in multi-threaded inferiors.
> +#
> +# This test sets up a multi-threaded inferior, and places a breakpoint
> +# at a location that many of the threads will reach.  We repeat the
> +# test with different conditions, sometimes a single thread should
> +# stop at the breakpoint, sometimes multiple threads should stop, and
> +# sometime no threads should stop.

Typo: sometime -> sometimes

> +
> +standard_testfile
> +
> +if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
> +	  {debug pthreads}] == -1 } {
> +    return
> +}
> +
> +set cond_bp_line [gdb_get_line_number "Breakpoint here"]
> +set stop_bp_line [gdb_get_line_number "Stop marker"]
> +set nested_bp_line [gdb_get_line_number "Nested breakpoint"]
> +set segv_line [gdb_get_line_number "Segfault happens here"]
> +
> +# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
> +proc start_gdb_and_runto_main { target_async target_non_stop } {
> +    save_vars { ::GDBFLAGS } {
> +	append ::GDBFLAGS \
> +	    " -ex \"maint set target-non-stop $target_non_stop\""
> +	append ::GDBFLAGS \
> +	    " -ex \"maintenance set target-async ${target_async}\""
> +
> +	clean_restart ${::binfile}
> +    }
> +
> +    if { ![runto_main] } {
> +	return -1
> +    }
> +
> +    return 0
> +}
> +
> +# Run a test of GDB's conditional breakpoints, where the conditions include
> +# inferior function calls.
> +#
> +# CONDITION is the expression to be used as the breakpoint condition.
> +#
> +# N_EXPECTED_HITS is the number of threads that we expect to stop due to
> +# CONDITON.
> +#
> +# MESSAGE is used as a test name prefix.
> +proc run_condition_test { message n_expected_hits condition \
> +			      target_async target_non_stop } {
> +    with_test_prefix $message {
> +
> +	if { [start_gdb_and_runto_main $target_async \
> +		  $target_non_stop] == -1 } {
> +	    return
> +	}
> +
> +	# Use this convenience variable to track how often the
> +	# breakpoint condition has been evaluated.  This should be
> +	# once per thread.
> +	gdb_test "set \$n_cond_eval = 0"
> +
> +	# Setup the conditional breakpoint.
> +	gdb_breakpoint \
> +	    "${::srcfile}:${::cond_bp_line} if ((++\$n_cond_eval) && (${condition}))"
> +
> +	# And a breakpoint that we hit when the test is over, this one is
> +	# not conditional.  Only the main thread gets here once all the
> +	# other threads have finished.
> +	gdb_breakpoint "${::srcfile}:${::stop_bp_line}"
> +
> +	# The number of times we stop at the conditional breakpoint.
> +	set n_hit_condition 0
> +
> +	# Now keep 'continue'-ing GDB until all the threads have finished
> +	# and we reach the stop_marker breakpoint.
> +	gdb_test_multiple "continue" "spot all breakpoint hits" {
> +	    -re " worker_func
> \[^\r\n\]+${::srcfile}:${::cond_bp_line}\r\n${::decimal}\\s+\[^\r\n\]+Breakpoint
> here\[^\r\n\]+\r\n${::gdb_prompt} $" {
> +		incr n_hit_condition
> +		send_gdb "continue\n"
> +		exp_continue
> +	    }
> +
> +	    -re " stop_marker
> \[^\r\n\]+${::srcfile}:${::stop_bp_line}\r\n${::decimal}\\s+\[^\r\n\]+Stop
> marker\[^\r\n\]+\r\n${::gdb_prompt} $" {
> +		pass $gdb_test_name
> +	    }
> +	}
> +
> +	gdb_assert { $n_hit_condition == $n_expected_hits } \
> +	    "stopped at breakpoint the expected number of times"
> +
> +	# Ensure the breakpoint condition was evaluated once per thread.
> +	gdb_test "print \$n_cond_eval" "= 3" \
> +	    "condition was evaluated in each thread"
> +    }
> +}
> +
> +# Check that after handling a conditional breakpoint (where the condition
> +# includes an inferior call), it is still possible to kill the running
> +# inferior, and then restart the inferior.
> +#
> +# At once point doing this would result in GDB giving an assertion error.
> +proc_with_prefix run_kill_and_restart_test { target_async target_non_stop } {
> +    # This test relies on the 'start' command, which is not possible with
> +    # the plain 'remote' target.
> +    if { [target_info gdb_protocol] == "remote" } {
> +	return
> +    }
> +
> +    if { [start_gdb_and_runto_main $target_async \
> +	      $target_non_stop] == -1 } {
> +	return
> +    }
> +
> +    # Setup the conditional breakpoint.
> +    gdb_breakpoint \
> +	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 1))"
> +    gdb_continue_to_breakpoint "worker_func"
> +
> +    # Now kill the program being debugged.
> +    gdb_test "kill" "" "kill process" \
> +	"Kill the program being debugged.*y or n. $" "y"
> +
> +    # Check we can restart the inferior.  At one point this would trigger an
> +    # assertion.
> +    gdb_test "start" ".*"

I believe using 'gdb_start_cmd' is preferred.

> +}
> +
> +# Create a conditional breakpoint which includes a call to a function that
> +# segfaults.  Run GDB and check what happens when the inferior segfaults
> +# during the inferior call.
> +proc_with_prefix run_bp_cond_segfaults { target_async target_non_stop } {
> +    if { [start_gdb_and_runto_main $target_async \
> +	      $target_non_stop] == -1 } {
> +	return
> +    }
> +
> +    # This test relies on the inferior segfaulting when trying to
> +    # access address zero.
> +    if { [is_address_zero_readable] } {
> +	return
> +    }
> +
> +    # Setup the conditional breakpoint, include a call to
> +    # 'function_that_segfaults', which triggers the segfault.
> +    gdb_breakpoint \
> +	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 0) &&
> function_that_segfaults ())"
> +    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
> +		      "get number of conditional breakpoint"]
> +
> +    gdb_test "continue" \
> +	[multi_line \
> +	     "Continuing\\." \
> +	     ".*" \
> +	     "Thread ${::decimal} \"infcall-from-bp\" received signal SIGSEGV, Segmentation
> fault\\." \
> +	     "${::hex} in function_that_segfaults \\(\\) at \[^\r\n\]+:${::segv_line}" \
> +	     "${::decimal}\\s+\[^\r\n\]+Segfault happens here\[^\r\n\]+" \
> +	     "Error in testing condition for breakpoint ${bp_1_num}:" \
> +	     "The program being debugged was signaled while in a function called from GDB\\."
> \
> +	     "GDB remains in the frame where the signal was received\\." \
> +	     "To change this behavior use \"set unwindonsignal on\"\\." \
> +	     "Evaluation of the expression containing the function" \
> +	     "\\(function_that_segfaults\\) will be abandoned\\." \
> +	     "When the function is done executing, GDB will silently stop\\."]
> +}
> +
> +# Create a conditional breakpoint which includes a call to a function that
> +# itself has a breakpoint set within it.  Run GDB and check what happens
> +# when GDB hits the nested breakpoint.
> +proc_with_prefix run_bp_cond_hits_breakpoint { target_async target_non_stop } {
> +    if { [start_gdb_and_runto_main $target_async \
> +	      $target_non_stop] == -1 } {
> +	return
> +    }
> +
> +    # Setup the conditional breakpoint, include a call to
> +    # 'function_with_breakpoint' in which we will shortly place a
> +    # breakpoint.
> +    gdb_breakpoint \
> +	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 0) &&
> function_with_breakpoint ())"
> +    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
> +		      "get number of conditional breakpoint"]
> +
> +    gdb_breakpoint "${::srcfile}:${::nested_bp_line}"
> +    set bp_2_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
> +		      "get number of nested breakpoint"]
> +
> +    gdb_test "continue" \
> +	[multi_line \
> +	     "Continuing\\." \
> +	     ".*" \
> +	     "Thread ${::decimal} \"infcall-from-bp\" hit Breakpoint ${bp_2_num},
> function_with_breakpoint \\(\\) at \[^\r\n\]+:${::nested_bp_line}" \
> +	     "${::decimal}\\s+\[^\r\n\]+Nested breakpoint\[^\r\n\]+" \
> +	     "Error in testing condition for breakpoint ${bp_1_num}:" \
> +	     "The program being debugged stopped while in a function called from GDB\\." \
> +	     "Evaluation of the expression containing the function" \
> +	     "\\(function_with_breakpoint\\) will be abandoned\\." \
> +	     "When the function is done executing, GDB will silently stop\\."]
> +}
> +
> +foreach_with_prefix target_async { "on" "off" } {
> +    foreach_with_prefix target_non_stop { "on" "off" } {
> +	run_condition_test "exactly one thread is hit" \
> +	    1 "is_matching_tid (arg, 1)" \
> +	    $target_async $target_non_stop
> +	run_condition_test "exactly two threads are hit" \
> +	    2 "(is_matching_tid (arg, 0) || is_matching_tid (arg, 2))" \
> +	    $target_async $target_non_stop
> +	run_condition_test "all three threads are hit" \
> +	    3 "return_true ()" \
> +	    $target_async $target_non_stop
> +	run_condition_test "no thread is hit" \
> +	    0 "return_false ()" \
> +	    $target_async $target_non_stop
> +
> +	run_kill_and_restart_test $target_async $target_non_stop
> +	run_bp_cond_segfaults $target_async $target_non_stop
> +	run_bp_cond_hits_breakpoint $target_async $target_non_stop
> +    }
> +}
> diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
> b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
> new file mode 100644
> index 00000000000..835c72f03cf
> --- /dev/null
> +++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
> @@ -0,0 +1,139 @@
> +/* Copyright 2022-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 <pthread.h>
> +#include <unistd.h>
> +#include <semaphore.h>
> +#include <stdlib.h>
> +
> +#define NUM_THREADS 5
> +
> +/* Semaphores, used to track when threads have started, and to control
> +   when the threads finish.  */
> +sem_t startup_semaphore;
> +sem_t finish_semaphore;
> +
> +/* Mutex to control when the first worker thread hit a breakpoint
> +   location.  */
> +pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
> +
> +/* Global variable to poke, just so threads have something to do.  */
> +volatile int global_var = 0;
> +
> +int
> +return_true ()
> +{
> +  return 1;
> +}
> +
> +int
> +return_false ()
> +{
> +  return 0;
> +}
> +
> +void *
> +worker_func (void *arg)
> +{
> +  int tid = *((int *) arg);
> +
> +  switch (tid)
> +    {
> +    case 0:
> +      /* Wait for MUTEX to become available, then pass through the
> +	 conditional breakpoint location.  */
> +      if (pthread_mutex_lock (&mutex) != 0)
> +	abort ();
> +      global_var = 99;	/* Conditional breakpoint here.  */
> +      if (pthread_mutex_unlock (&mutex) != 0)
> +	abort ();
> +      break;
> +
> +    default:
> +      /* Notify the main thread that the thread has started, then wait for
> +	 the main thread to tell us to finish.  */
> +      sem_post (&startup_semaphore);
> +      if (sem_wait (&finish_semaphore) != 0)
> +	abort ();
> +      break;
> +    }
> +}
> +
> +void
> +stop_marker ()
> +{
> +  global_var = 99;	/* Stop marker.  */
> +}
> +
> +int
> +main ()
> +{
> +  pthread_t threads[NUM_THREADS];
> +  int args[NUM_THREADS];
> +  void *retval;
> +
> +  /* An alarm, just in case the thread deadlocks.  */
> +  alarm (300);
> +
> +  /* Semaphore initialization.  */
> +  if (sem_init (&startup_semaphore, 0, 0) != 0)
> +    abort ();
> +  if (sem_init (&finish_semaphore, 0, 0) != 0)
> +    abort ();
> +
> +  /* Lock MUTEX, this prevents the first worker thread from rushing ahead.  */
> +  if (pthread_mutex_lock (&mutex) != 0)
> +    abort ();
> +
> +  /* Worker thread creation.  */
> +  for (int i = 0; i < NUM_THREADS; i++)
> +    {
> +      args[i] = i;
> +      pthread_create (&threads[i], NULL, worker_func, &args[i]);
> +    }
> +
> +  /* Wait for every thread (other than the first) to tell us it has started
> +     up.  */
> +  for (int i = 1; i < NUM_THREADS; i++)
> +    {
> +      if (sem_wait (&startup_semaphore) != 0)
> +	abort ();
> +    }
> +
> +  /* Unlock the first thread so it can proceed.  */
> +  if (pthread_mutex_unlock (&mutex) != 0)
> +    abort ();
> +
> +  /* Wait for the first thread only.  */
> +  pthread_join (threads[0], &retval);
> +
> +  /* Now post FINISH_SEMAPHORE to allow all the other threads to finish.  */
> +  for (int i = 1; i < NUM_THREADS; i++)
> +    sem_post (&finish_semaphore);
> +
> +  /* Now wait for the remaining threads to complete.  */
> +  for (int i = 1; i < NUM_THREADS; i++)
> +    pthread_join (threads[i], &retval);
> +
> +  /* Semaphore cleanup.  */
> +  sem_destroy (&finish_semaphore);
> +  sem_destroy (&startup_semaphore);
> +
> +  stop_marker ();
> +
> +  return 0;
> +}
> diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
> b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
> new file mode 100644
> index 00000000000..787dee3aa8e
> --- /dev/null
> +++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
> @@ -0,0 +1,117 @@
> +# Copyright 2022-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 reprocuces bug gdb/28942, performing an inferior function
> +# call from a breakpoint condition in a multi-threaded inferior.
> +#
> +# The important part of this test is that, when the conditional
> +# breakpoint is hit, and the condition (which includes an inferior
> +# function call) is evaluated, the other threads are running.
> +
> +standard_testfile
> +
> +if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
> +	  {debug pthreads}] == -1 } {
> +    return
> +}
> +
> +set cond_bp_line [gdb_get_line_number "Conditional breakpoint here"]
> +set final_bp_line [gdb_get_line_number "Stop marker"]
> +
> +# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
> +proc start_gdb_and_runto_main { target_async target_non_stop } {
> +    save_vars { ::GDBFLAGS } {
> +	append ::GDBFLAGS \
> +	    " -ex \"maint set target-non-stop $target_non_stop\""
> +	append ::GDBFLAGS \
> +	    " -ex \"maintenance set target-async ${target_async}\""
> +
> +	clean_restart ${::binfile}
> +    }
> +
> +    if { ![runto_main] } {
> +	return -1
> +    }
> +
> +    return 0
> +}
> +
> +# Run a test of GDB's conditional breakpoints, where the conditions include
> +# inferior function calls.
> +#
> +# TARGET_ASYNC and TARGET_NON_STOP are used when starting up GDB.
> +#
> +# When STOP_AT_COND is true the breakpoint condtion will evaluate to
> +# true, and GDB will stop at the breakpoint.  Otherwise, the
> +# breakpoint condition will evaluate to false and GDB will not stop at
> +# the breakpoint.
> +proc run_condition_test { stop_at_cond \
> +			      target_async target_non_stop } {
> +    if { [start_gdb_and_runto_main $target_async \
> +	      $target_non_stop] == -1 } {
> +	return
> +    }
> +
> +    # Setup the conditional breakpoint.
> +    if { $stop_at_cond } {
> +	set cond_func "return_true"
> +    } else {
> +	set cond_func "return_false"
> +    }
> +    gdb_breakpoint \
> +	"${::srcfile}:${::cond_bp_line} if (${cond_func} ())"
> +    set cond_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
> +			"get number for conditional breakpoint"]
> +
> +    # And a breakpoint that we hit when the test is over, this one is
> +    # not conditional.
> +    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
> +    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
> +			  "get number for final breakpoint"]
> +
> +    if { $stop_at_cond } {
> +	# Continue.  The first breakpoint we hit should be the conditional
> +	# breakpoint.  The other thread will have hit its breakpoint, but
> +	# that will have been deferred until the conditional breakpoint is
> +	# reported.
> +	gdb_test "continue" \
> +	    [multi_line \
> +		 "Continuing\\." \
> +		 ".*" \
> +		 "" \
> +		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${cond_bp_num},
> worker_func \[^\r\n\]+:${::cond_bp_line}" \
> +		 "${::decimal}\\s+\[^\r\n\]+Conditional breakpoint here\[^\r\n\]+"] \
> +	    "hit the conditional breakpoint"
> +    }
> +
> +    # Run to the stop marker.
> +    gdb_test "continue" \
> +	[multi_line \
> +	     "Continuing\\." \
> +	     ".*" \
> +	     "" \
> +	     "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${final_bp_num},
> stop_marker \[^\r\n\]+:${::final_bp_line}" \
> +	     "${::decimal}\\s+\[^\r\n\]+Stop marker\[^\r\n\]+"] \
> +	"hit the final breakpoint"
> +}
> +
> +foreach_with_prefix target_async { "on" "off" } {
> +    foreach_with_prefix target_non_stop { "on" "off" } {
> +	foreach_with_prefix stop_at_cond { true false } {
> +	    run_condition_test $stop_at_cond \
> +		$target_async $target_non_stop
> +	}
> +    }
> +}
> --
> 2.25.4

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] 202+ messages in thread

* RE: [PATCHv7 3/6] gdb: add timeouts for inferior function calls
  2023-05-15 19:22             ` [PATCHv7 3/6] gdb: add timeouts for inferior function calls Andrew Burgess
@ 2023-05-16 15:42               ` Aktemur, Tankut Baris
  2023-06-05 13:54                 ` Andrew Burgess
  0 siblings, 1 reply; 202+ messages in thread
From: Aktemur, Tankut Baris @ 2023-05-16 15:42 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

On Monday, May 15, 2023 9:22 PM, Andrew Burgess wrote:
> Eli already approved the docs part:
>   https://sourceware.org/pipermail/gdb-patches/2023-January/196462.html
> 
> ---
> 
> In the previous commits I have been working on improving inferior
> function call support.  One thing that worries me about using inferior
> function calls from a conditional breakpoint is: what happens if the
> inferior function call fails?
> 
> If the failure is obvious, e.g. the thread performing the call
> crashes, or hits a breakpoint, then this case is already well handled,
> and the error is reported to the user.
> 
> But what if the thread performing the inferior call just deadlocks?
> If the user made the call from a 'print' or 'call' command, then the
> user might have some expectation of when the function call should
> complete, and, when this time limit is exceeded, the user
> will (hopefully) interrupt GDB and regain control of the debug
> session.
> 
> But, when the inferior function call is from a breakpoint condition it
> is much harder to understand that GDB is deadlocked within an inferior
> call.  Maybe the breakpoint hasn't been hit yet?  Or maybe the
> condition was always false?  Or maybe GDB is deadlocked in an inferior
> call?  The only way to know for sure is to periodically interrupt GDB,

Did you mean "interrupt the inferior"?

> check on all the threads, and then continue.
> 
> Additionally, the focus of the previous commit was inferior function
> calls, from a conditional breakpoint, in a multi-threaded inferior.
> This opens up a whole new set of potential failure conditions.  For
> example, what if the function called relies on interaction with some
> other thread, and the other thread crashes?  Or hits a breakpoint?
> Given how inferior function calls work (in a synchronous manner), a
> stop event in some other thread is going to be ignored while the
> inferior function call is being executed as part of a breakpoint
> condition, and this means that GDB could get stuck waiting for the
> original condition thread, which will now never complete.
> 
> In this commit I propose a solution to this problem.  A timeout.  For
> targets that support async-mode we can install an event-loop timer
> before starting the inferior function call.  When the timer expires we
> will stop the thread performing the inferior function call.  With this
> mechanism in place a user can be sure that any inferior call they make
> will either complete, or timeout eventually.
> 
> Adding a timer like this is obviously a change in behaviour for the
> more common 'call' and 'print' uses of inferior function calls, so, in
> this patch, I propose having two different timers.  One I call the
> 'direct-call-timeout', which is used for 'call' and 'print' commands.
> This timeout is by default set to unlimited, which, not surprisingly,
> means there is no timeout in place.
> 
> A second timer, which I've called 'indirect-call-timeout', is used for
> inferior function calls from breakpoint conditions.  This timeout has
> a default value of 30 seconds.  This is a reasonably long time to
> wait, and hopefully should be enough in most cases to allow the
> inferior call to complete.  An inferior call that takes more than 30
> seconds, which is installed on a breakpoint condition is really going
> to slow down the debug session, so hopefully this is not a common use
> case.
> 
> The user is, of course, free to reduce, or increase the timeout value,
> and can always use Ctrl-c to interrupt an inferior function call, but
> this timeout will ensure that GDB will stop at some point.
> 
> The new commands added by this commit are:
> 
>   set direct-call-timeout SECONDS
>   show direct-call-timeout
>   set indirect-call-timeout SECONDS
>   show indirect-call-timeout
> 
> These new timeouts do depend on async-mode, so, if async-mode is
> disabled (maint set target-async off), or not supported (e.g. target
> sim), then the timeout is treated as unlimited (that is, no timeout is
> set).
> 
> For targets that "fake" non-async mode, e.g. Linux native, where
> non-async mode is really just async mode, but then we park the target
> in a sissuspend, we could easily fix things so that the timeouts still
> work, however, for targets that really are not async aware, like the
> simulator, fixing things so that timeouts work correctly would be a
> much bigger task - that effort would be better spent just making the
> target async-aware.  And so, I'm happy for now that this feature will
> only work on async targets.
> 
> The two new show commands will display slightly different text if the
> current target is a non-async target, which should allow users to
> understand what's going on.
> 
> There's a somewhat random test adjustment needed in gdb.base/help.exp,
> the test uses a regexp with the apropos command, and expects to find a
> single result.  Turns out the new settings I added also matched the
> regexp, which broke the test.  I've updated the regexp a little to
> exclude my new settings.
> 
> In infcall.c you'll notice the thread_info::stop_requested flag being
> set when a timeout occurs.  This flag setting is not required as part
> of this commit, but will be needed in a later commit.  However, it
> seemed like setting this flag fitted better with this commit, which is
> why the change is added here.
> ---
>  gdb/NEWS                                      |  18 ++
>  gdb/doc/gdb.texinfo                           |  66 ++++++
>  gdb/infcall.c                                 | 221 +++++++++++++++++-
>  gdb/testsuite/gdb.base/help.exp               |   2 +-
>  gdb/testsuite/gdb.base/infcall-timeout.c      |  36 +++
>  gdb/testsuite/gdb.base/infcall-timeout.exp    |  82 +++++++
>  .../infcall-from-bp-cond-timeout.c            | 169 ++++++++++++++
>  .../infcall-from-bp-cond-timeout.exp          | 156 +++++++++++++
>  8 files changed, 745 insertions(+), 5 deletions(-)
>  create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.c
>  create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.exp
>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
> 
> diff --git a/gdb/NEWS b/gdb/NEWS
> index 6aa0d5171f2..216c3a95d09 100644
> --- a/gdb/NEWS
> +++ b/gdb/NEWS
> @@ -100,6 +100,24 @@ info main
>     $2 = 1
>     (gdb) break func if $_shell("some command") == 0
> 
> +set direct-call-timeout SECONDS
> +show direct-call-timeout
> +set indirect-call-timeout SECONDS
> +show indirect-call-timeout
> +  These new settings can be used to limit how long GDB will wait for
> +  an inferior function call to complete.  The direct timeout is used
> +  for inferior function calls from e.g. 'call' and 'print' commands,
> +  while the indirect timeout is used for inferior function calls from
> +  within a conditional breakpoint expression.
> +
> +  The default for the direct timeout is unlimited, while the default
> +  for the indirect timeout is 30 seconds.
> +
> +  These timeouts will only have an effect for targets that are
> +  operating in async mode.  For non-async targets the timeouts are
> +  ignored, GDB will wait indefinitely for an inferior function to
> +  complete, unless interrupted by the user using Ctrl-C.
> +
>  * MI changes
> 
>  ** mi now reports 'no-history' as a stop reason when hitting the end of the
> diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
> index 531147f6e6b..54668d812cb 100644
> --- a/gdb/doc/gdb.texinfo
> +++ b/gdb/doc/gdb.texinfo
> @@ -20903,6 +20903,72 @@
>  @code{step}, etc).  In this case, when the inferior finally returns to
>  the dummy-frame, @value{GDBN} will once again halt the inferior.
> 
> +On targets that support asynchronous execution (@pxref{Background
> +Execution}) @value{GDBN} can place a timeout on any functions called
> +from @value{GDBN}.  If the timeout expires and the function call is
> +still ongoing, then @value{GDBN} will interrupt the program.
> +
> +For targets that don't support asynchronous execution
> +(@pxref{Background Execution}) then timeouts for functions called from
> +@value{GDBN} are not supported, the timeout settings described below
> +will be treated as @code{unlimited}, meaning @value{GDBN} will wait
> +indefinitely for function call to complete, unless interrupted by the
> +user using @kbd{Ctrl-C}.
> +
> +@table @code
> +@item set direct-call-timeout @var{seconds}
> +@kindex set direct-call-timeout
> +@cindex timeout for called functions
> +Set the timeout used when calling functions in the program to
> +@var{seconds}, which should be an integer greater than zero, or the
> +special value @code{unlimited}, which indicates no timeout should be
> +used.  The default for this setting is @code{unlimited}.
> +
> +This setting is used when the user calls a function directly from the
> +command prompt, for example with a @code{call} or @code{print}
> +command.
> +
> +This setting only works for targets that support asynchronous
> +execution (@pxref{Background Execution}), for any other target the
> +setting is treated as @code{unlimited}.
> +
> +@item show direct-call-timeout
> +@kindex show direct-call-timeout
> +@cindex timeout for called functions
> +Show the timeout used when calling functions in the program with a
> +@code{call} or @code{print} command.
> +@end table
> +
> +It is also possible to call functions within the program from the
> +condition of a conditional breakpoint (@pxref{Conditions, ,Break
> +Conditions}).  A different setting controls the timeout used for
> +function calls made from a breakpoint condition.
> +
> +@table @code
> +@item set indirect-call-timeout @var{seconds}
> +@kindex set indirect-call-timeout
> +@cindex timeout for called functions
> +Set the timeout used when calling functions in the program from a
> +breakpoint or watchpoint condition to @var{seconds}, which should be
> +an integer greater than zero, or the special value @code{unlimited},
> +which indicates no timeout should be used.  The default for this
> +setting is @code{30} seconds.
> +
> +This setting only works for targets that support asynchronous
> +execution (@pxref{Background Execution}), for any other target the
> +setting is treated as @code{unlimited}.
> +
> +If a function called from a breakpoint or watchpoint condition times
> +out, then @value{GDBN} will stop at the point where the timeout
> +occurred.  The breakpoint condition evaluation will be abandoned.
> +
> +@item show indirect-call-timeout
> +@kindex show indirect-call-timeout
> +@cindex timeout for called functions
> +Show the timeout used when calling functions in the program from a
> +breakpoint or watchpoint condition.
> +@end table
> +
>  @subsection Calling functions with no debug info
> 
>  @cindex no debug info functions
> diff --git a/gdb/infcall.c b/gdb/infcall.c
> index 49c88add394..dea7dc83062 100644
> --- a/gdb/infcall.c
> +++ b/gdb/infcall.c
> @@ -96,6 +96,53 @@ show_may_call_functions_p (struct ui_file *file, int from_tty,
>  	      value);
>  }
> 
> +/* A timeout (in seconds) for direct inferior calls.  A direct inferior
> +   call is one the user triggers from the prompt, e.g. with a 'call' or
> +   'print' command.  Compare with the definition of indirect calls below.  */
> +
> +static unsigned int direct_call_timeout = UINT_MAX;
> +
> +/* Implement 'show direct-call-timeout'.  */
> +
> +static void
> +show_direct_call_timeout (struct ui_file *file, int from_tty,
> +			  struct cmd_list_element *c, const char *value)
> +{
> +  if (target_has_execution () && !target_can_async_p ())
> +    gdb_printf (file, _("Current target does not support async mode, timeout "
> +			"for direct inferior calls is \"unlimited\".\n"));
> +  else if (direct_call_timeout == UINT_MAX)
> +    gdb_printf (file, _("Timeout for direct inferior function calls "
> +			"is \"unlimited\".\n"));
> +  else
> +    gdb_printf (file, _("Timeout for direct inferior function calls "
> +			"is \"%s seconds\".\n"), value);
> +}
> +
> +/* A timeout (in seconds) for indirect inferior calls.  An indirect inferior
> +   call is one that originates from within GDB, for example, when
> +   evaluating an expression for a conditional breakpoint.  Compare with
> +   the definition of direct calls above.  */
> +
> +static unsigned int indirect_call_timeout = 30;
> +
> +/* Implement 'show indirect-call-timeout'.  */
> +
> +static void
> +show_indirect_call_timeout (struct ui_file *file, int from_tty,
> +			  struct cmd_list_element *c, const char *value)
> +{
> +  if (target_has_execution () && !target_can_async_p ())
> +    gdb_printf (file, _("Current target does not support async mode, timeout "
> +			"for indirect inferior calls is \"unlimited\".\n"));
> +  else if (indirect_call_timeout == UINT_MAX)
> +    gdb_printf (file, _("Timeout for indirect inferior function calls "
> +			"is \"unlimited\".\n"));
> +  else
> +    gdb_printf (file, _("Timeout for indirect inferior function calls "
> +			"is \"%s seconds\".\n"), value);
> +}
> +
>  /* How you should pass arguments to a function depends on whether it
>     was defined in K&R style or prototype style.  If you define a
>     function using the K&R syntax that takes a `float' argument, then
> @@ -590,6 +637,86 @@ call_thread_fsm::should_notify_stop ()
>    return true;
>  }
> 
> +/* A class to control creation of a timer that will interrupt a thread
> +   during an inferior call.  */
> +struct infcall_timer_controller
> +{
> +  /* Setup an event-loop timer that will interrupt PTID if the inferior
> +     call takes too long.  DIRECT_CALL_P is true when this inferior call is
> +     a result of the user using a 'print' or 'call' command, and false when
> +     this inferior call is a result of e.g. a conditional breakpoint
> +     expression, this is used to select which timeout to use.  */
> +  infcall_timer_controller (thread_info *thr, bool direct_call_p)
> +    : m_thread (thr)
> +  {
> +    unsigned int timeout
> +      = direct_call_p ? direct_call_timeout : indirect_call_timeout;
> +    if (timeout < UINT_MAX && target_can_async_p ())
> +      {
> +	int ms = timeout * 1000;
> +	int id = create_timer (ms, infcall_timer_controller::timed_out, this);
> +	m_timer_id.emplace (id);
> +	infcall_debug_printf ("Setting up infcall timeout timer for "
> +			      "ptid %s: %d milliseconds",
> +			      m_thread->ptid.to_string ().c_str (), ms);
> +      }
> +  }
> +
> +  /* Destructor.  Ensure that the timer is removed from the event loop.  */
> +  ~infcall_timer_controller ()
> +  {
> +    /* If the timer has already triggered, then it will have already been
> +       deleted from the event loop.  If the timer has not triggered, then
> +       delete it now.  */
> +    if (m_timer_id.has_value () && !m_triggered)
> +      delete_timer (*m_timer_id);
> +
> +    /* Just for clarity, discard the timer id now.  */
> +    m_timer_id.reset ();
> +  }
> +
> +  /* Return true if there was a timer in place, and the timer triggered,
> +     otherwise, return false.  */
> +  bool triggered_p ()
> +  {
> +    gdb_assert (!m_triggered || m_timer_id.has_value ());
> +    return m_triggered;
> +  }
> +
> +private:
> +  /* The thread we should interrupt.  */
> +  thread_info *m_thread;
> +
> +  /* Set true when the timer is triggered.  */
> +  bool m_triggered = false;
> +
> +  /* Given a value when a timer is in place.  */
> +  gdb::optional<int> m_timer_id;
> +
> +  /* Callback for the timer, forwards to ::trigger below.  */
> +  static void
> +  timed_out (gdb_client_data context)
> +  {
> +    infcall_timer_controller *ctrl
> +      = static_cast<infcall_timer_controller *> (context);
> +    ctrl->trigger ();
> +  }
> +
> +  /* Called when the timer goes off.  Stop thread m_thread.  */
> +  void
> +  trigger ()
> +  {
> +    m_triggered = true;
> +
> +    scoped_disable_commit_resumed disable_commit_resumed ("infcall timeout");
> +
> +    infcall_debug_printf ("Stopping thread %s",
> +			  m_thread->ptid.to_string ().c_str ());
> +    target_stop (m_thread->ptid);
> +    m_thread->stop_requested = true;
> +  }
> +};
> +
>  /* Subroutine of call_function_by_hand to simplify it.
>     Start up the inferior and wait for it to stop.
>     Return the exception if there's an error, or an exception with
> @@ -600,13 +727,15 @@ call_thread_fsm::should_notify_stop ()
> 
>  static struct gdb_exception
>  run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
> -		   struct thread_info *call_thread, CORE_ADDR real_pc)
> +		   struct thread_info *call_thread, CORE_ADDR real_pc,
> +		   bool *timed_out_p)
>  {
>    INFCALL_SCOPED_DEBUG_ENTER_EXIT;
> 
>    struct gdb_exception caught_error;
>    ptid_t call_thread_ptid = call_thread->ptid;
>    int was_running = call_thread->state == THREAD_RUNNING;
> +  *timed_out_p = false;
> 
>    infcall_debug_printf ("call function at %s in thread %s, was_running = %d",
>  			core_addr_to_string (real_pc),
> @@ -618,6 +747,16 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
>    scoped_restore restore_in_infcall
>      = make_scoped_restore (&call_thread->control.in_infcall, 1);
> 
> +  /* If the thread making the inferior call stops with a time out then the

"time out" -> "timeout"

> +     stop_requested flag will be set.  However, we don't want changes to
> +     this flag to leak back to our caller, we might be here to handle an
> +     inferior call from a breakpoint condition, so leaving this flag set
> +     would appear that the breakpoint stop was actually a requested stop,
> +     which is not true, and will cause GDB to print extra messages to the
> +     output.  */
> +  scoped_restore restore_stop_requested
> +    = make_scoped_restore (&call_thread->stop_requested, false);
> +
>    clear_proceed_status (0);
> 
>    /* Associate the FSM with the thread after clear_proceed_status
> @@ -651,11 +790,23 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
>        infrun_debug_show_threads ("non-exited threads after proceed for inferior-call",
>  				 all_non_exited_threads ());
> 
> +      /* Setup a timer (if possible, and if the settings allow) to prevent
> +	 the inferior call running forever.  */
> +      bool direct_call_p = !call_thread->control.in_cond_eval;
> +      infcall_timer_controller infcall_timer (call_thread, direct_call_p);
> +
>        /* Inferior function calls are always synchronous, even if the
>  	 target supports asynchronous execution.  */
>        wait_sync_command_done ();
> 
> -      infcall_debug_printf ("inferior call completed successfully");
> +      /* If the timer triggered then the inferior call failed.  */
> +      if (infcall_timer.triggered_p ())
> +	{
> +	  infcall_debug_printf ("inferior call timed out");
> +	  *timed_out_p = true;
> +	}
> +      else
> +	infcall_debug_printf ("inferior call completed successfully");
>      }
>    catch (gdb_exception &e)
>      {
> @@ -1309,6 +1460,10 @@ call_function_by_hand_dummy (struct value *function,
>    scoped_restore restore_stopped_by_random_signal
>      = make_scoped_restore (&stopped_by_random_signal, 0);
> 
> +  /* Set to true by the call to run_inferior_call below if the inferior
> +     call is artificially interrupted by GDB due to taking too long.  */
> +  bool timed_out_p = false;
> +
>    /* - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP -
>       If you're looking to implement asynchronous dummy-frames, then
>       just below is the place to chop this function in two..  */
> @@ -1335,7 +1490,8 @@ call_function_by_hand_dummy (struct value *function,
>  			      struct_addr);
>      {
>        std::unique_ptr<call_thread_fsm> sm_up (sm);
> -      e = run_inferior_call (std::move (sm_up), call_thread.get (), real_pc);
> +      e = run_inferior_call (std::move (sm_up), call_thread.get (), real_pc,
> +			     &timed_out_p);
>      }
> 
>      if (e.reason < 0)
> @@ -1487,7 +1643,10 @@ When the function is done executing, GDB will silently stop."),
>        std::string name = get_function_name (funaddr, name_buf,
>  					    sizeof (name_buf));
> 
> -      if (stopped_by_random_signal)
> +      /* If the inferior call timed out then it will have been interrupted
> +	 by a signal, but we want to report this differently to the user,
> +	 which is done later in this function.  */
> +      if (stopped_by_random_signal && !timed_out_p)
>  	{
>  	  /* We stopped inside the FUNCTION because of a random
>  	     signal.  Further execution of the FUNCTION is not
> @@ -1531,6 +1690,36 @@ GDB remains in the frame where the signal was received.\n\
>  To change this behavior use \"set unwindonsignal on\".\n\
>  Evaluation of the expression containing the function\n\
>  (%s) will be abandoned.\n\
> +When the function is done executing, GDB will silently stop."),
> +		     name.c_str ());
> +	    }
> +	}
> +
> +      if (timed_out_p)
> +	{
> +	  /* A timeout results in a signal being sent to the inferior.  */
> +	  gdb_assert (stopped_by_random_signal);
> +
> +	  /* Indentation is weird here.  A later patch is going to move the
> +	    following block into an if/else, so I'm leaving the indentation
> +	    here to minimise the later patch.
> +
> +	    Also, the error message used below refers to 'set
> +	    unwind-on-timeout' which doesn't exist yet.  This will be added
> +	    in a later commit, I'm leaving this in for now to minimise the
> +	    churn caused by the commit that adds unwind-on-timeout.  */
> +	    {
> +	      /* The user wants to stay in the frame where we stopped
> +		 (default).  Discard inferior status, we're not at the same
> +		 point we started at.  */
> +	      discard_infcall_control_state (inf_status.release ());
> +
> +	      error (_("\
> +The program being debugged timed out while in a function called from GDB.\n\
> +GDB remains in the frame where the timeout occurred.\n\
> +To change this behavior use \"set unwind-on-timeout on\".\n\
> +Evaluation of the expression containing the function\n\
> +(%s) will be abandoned.\n\
>  When the function is done executing, GDB will silently stop."),
>  		     name.c_str ());
>  	    }
> @@ -1644,6 +1833,30 @@ The default is to unwind the frame."),
>  			   show_unwind_on_terminating_exception_p,
>  			   &setlist, &showlist);
> 
> +  add_setshow_uinteger_cmd ("direct-call-timeout", no_class,
> +			    &direct_call_timeout, _("\
> +Set the timeout, for direct calls to inferior function calls."), _("\
> +Show the timeout, for direct calls to inferior function calls."), _("\
> +If running on a target that supports, and is running in, async mode\n\
> +then this timeout is used for any inferior function calls triggered\n\
> +directly from the prompt, i.e. from a 'call' or 'print' command.  The\n\
> +timeout is specified in seconds."),
> +			    nullptr,
> +			    show_direct_call_timeout,
> +			    &setlist, &showlist);
> +
> +  add_setshow_uinteger_cmd ("indirect-call-timeout", no_class,
> +			    &indirect_call_timeout, _("\
> +Set the timeout, for indirect calls to inferior function calls."), _("\
> +Show the timeout, for indirect calls to inferior function calls."), _("\
> +If running on a target that supports, and is running in, async mode\n\
> +then this timeout is used for any inferior function calls triggered\n\
> +indirectly, i.e. being made as part of a breakpoint, or watchpoint,\n\
> +condition expression.  The timeout is specified in seconds."),
> +			    nullptr,
> +			    show_indirect_call_timeout,
> +			    &setlist, &showlist);
> +
>    add_setshow_boolean_cmd
>      ("infcall", class_maintenance, &debug_infcall,
>       _("Set inferior call debugging."),
> diff --git a/gdb/testsuite/gdb.base/help.exp b/gdb/testsuite/gdb.base/help.exp
> index 87919a819ab..504bf90cc15 100644
> --- a/gdb/testsuite/gdb.base/help.exp
> +++ b/gdb/testsuite/gdb.base/help.exp
> @@ -121,7 +121,7 @@ gdb_test "help info bogus-gdb-command" "Undefined info command: \"bogus-
> gdb-comm
>  gdb_test "help gotcha" "Undefined command: \"gotcha\"\.  Try \"help\"\."
> 
>  # Test apropos regex.
> -gdb_test "apropos \\\(print\[\^\[ bsiedf\\\".-\]\\\)" "handle -- Specify how to handle
> signals\."
> +gdb_test "apropos \\\(print\[\^\[ bsiedf\\\"'.-\]\\\)" "handle -- Specify how to handle
> signals\."
>  # Test apropos >1 word string.
>  gdb_test "apropos handle signal" "handle -- Specify how to handle signals\."
>  # Test apropos apropos.
> diff --git a/gdb/testsuite/gdb.base/infcall-timeout.c b/gdb/testsuite/gdb.base/infcall-
> timeout.c
> new file mode 100644
> index 00000000000..12774ca2599
> --- /dev/null
> +++ b/gdb/testsuite/gdb.base/infcall-timeout.c
> @@ -0,0 +1,36 @@
> +/* Copyright 2022-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 <unistd.h>
> +
> +/* This function is called from GDB.  */
> +int
> +function_that_never_returns ()
> +{
> +  while (1)
> +    sleep (1);
> +
> +  return 0;
> +}
> +
> +int
> +main ()
> +{
> +  alarm (300);
> +
> +  return 0;
> +}
> diff --git a/gdb/testsuite/gdb.base/infcall-timeout.exp b/gdb/testsuite/gdb.base/infcall-
> timeout.exp
> new file mode 100644
> index 00000000000..5e9cdc2fa0e
> --- /dev/null
> +++ b/gdb/testsuite/gdb.base/infcall-timeout.exp
> @@ -0,0 +1,82 @@
> +# Copyright 2022-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/>.
> +
> +# Test GDB's direct-call-timeout setting, that is, ensure that if an
> +# inferior function call, invoked from e.g. a 'print' command, takes
> +# too long, then GDB can interrupt it, and return control to the user.
> +
> +standard_testfile
> +
> +if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
> +	  {debug}] == -1 } {
> +    return
> +}
> +
> +# Start GDB according to TARGET_ASYNC and TARGET_NON_STOP, then adjust
> +# the direct-call-timeout, and make an inferior function call that
> +# will never return.  GDB should eventually timeout and stop the
> +# inferior.
> +proc_with_prefix run_test { target_async target_non_stop } {
> +    save_vars { ::GDBFLAGS } {
> +	append ::GDBFLAGS \
> +	    " -ex \"maint set target-non-stop $target_non_stop\""
> +	append ::GDBFLAGS \
> +	    " -ex \"maintenance set target-async ${target_async}\""
> +
> +	clean_restart ${::binfile}
> +    }
> +
> +    if {![runto_main]} {
> +	fail "run to main"

runto_main already emits a fail, so no need for this.

> +	return
> +    }
> +
> +    gdb_test_no_output "set direct-call-timeout 5"
> +
> +    # When non-stop mode is off we get slightly different output from GDB.
> +    if { [gdb_is_remote_or_extended_remote_target] && !$target_non_stop } {
> +	set stopped_line_pattern "Program received signal SIGINT, Interrupt\\."
> +    } else {
> +	set stopped_line_pattern "Program stopped\\."
> +    }
> +
> +    gdb_test "print function_that_never_returns ()" \
> +	[multi_line \
> +	     $stopped_line_pattern \
> +	     ".*" \
> +	     "The program being debugged timed out while in a function called from GDB\\." \
> +	     "GDB remains in the frame where the timeout occurred\\." \
> +	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
> +	     "Evaluation of the expression containing the function" \
> +	     "\\(function_that_never_returns\\) will be abandoned\\." \
> +	     "When the function is done executing, GDB will silently stop\\."]
> +
> +    gdb_test "bt" ".* function_that_never_returns .*<function called from gdb>.*"
> +}
> +
> +foreach_with_prefix target_async { "on" "off" } {
> +
> +    if { !$target_async } {
> +	# GDB can't timeout while waiting for a thread if the target
> +	# runs with async-mode turned off; once the target is running
> +	# GDB is effectively blocked until the target stops for some
> +	# reason.
> +	continue
> +    }
> +
> +    foreach_with_prefix target_non_stop { "on" "off" } {
> +	run_test $target_async $target_non_stop
> +    }
> +}
> diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
> b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
> new file mode 100644
> index 00000000000..4da4245746e
> --- /dev/null
> +++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
> @@ -0,0 +1,169 @@
> +/* This testcase is part of GDB, the GNU debugger.
> +
> +   Copyright 2022-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 <stdio.h>
> +#include <pthread.h>
> +#include <unistd.h>
> +#include <stdlib.h>
> +#include <errno.h>
> +#include <semaphore.h>
> +
> +#define NUM_THREADS 5
> +
> +/* Semaphores, used to track when threads have started, and to control
> +   when the threads finish.  */
> +sem_t startup_semaphore;
> +sem_t finish_semaphore;
> +sem_t thread_1_semaphore;
> +sem_t thread_2_semaphore;
> +
> +/* Mutex to control when the first worker thread hit a breakpoint
> +   location.  */
> +pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
> +
> +/* Global variable to poke, just so threads have something to do.  */
> +volatile int global_var = 0;
> +
> +int
> +condition_func ()
> +{
> +  /* Let thread 2 run.  */
> +  if (sem_post (&thread_2_semaphore) != 0)
> +    abort ();
> +
> +  /* Wait for thread 2 to complete its actions.  */
> +  if (sem_wait (&thread_1_semaphore) != 0)
> +    abort ();
> +
> +  return 1;
> +}
> +
> +void
> +do_segfault ()
> +{
> +  volatile int *p = 0;
> +  *p = 0;	/* Segfault here.  */
> +}
> +
> +void *
> +worker_func (void *arg)
> +{
> +  int tid = *((int *) arg);
> +
> +  /* Let the main thread know that this worker has started.  */
> +  if (sem_post (&startup_semaphore) != 0)
> +    abort ();
> +
> +  switch (tid)
> +    {
> +    case 0:
> +      /* Wait for MUTEX to become available, then pass through the
> +	 conditional breakpoint location.  */
> +      if (pthread_mutex_lock (&mutex) != 0)
> +	abort ();
> +      global_var = 99;	/* Conditional breakpoint here.  */
> +      if (pthread_mutex_unlock (&mutex) != 0)
> +	abort ();
> +      break;
> +
> +    case 1:
> +      if (sem_wait (&thread_2_semaphore) != 0)
> +	abort ();
> +      do_segfault ();
> +      if (sem_post (&thread_1_semaphore) != 0)
> +	abort ();
> +
> +      /* Fall through.  */
> +    default:
> +      /* Wait until we are allowed to finish.  */
> +      if (sem_wait (&finish_semaphore) != 0)
> +	abort ();
> +      break;
> +    }
> +}
> +
> +void
> +stop_marker ()
> +{
> +  global_var = 99;	/* Stop marker.  */
> +}
> +
> +/* The main program entry point.  */
> +
> +int
> +main ()
> +{
> +  pthread_t threads[NUM_THREADS];
> +  int args[NUM_THREADS];
> +  void *retval;
> +
> +  /* An alarm, just in case the thread deadlocks.  */
> +  alarm (300);
> +
> +  /* Semaphore initialization.  */
> +  if (sem_init (&startup_semaphore, 0, 0) != 0)
> +    abort ();
> +  if (sem_init (&finish_semaphore, 0, 0) != 0)
> +    abort ();
> +  if (sem_init (&thread_1_semaphore, 0, 0) != 0)
> +    abort ();
> +  if (sem_init (&thread_2_semaphore, 0, 0) != 0)
> +    abort ();
> +
> +  /* Lock MUTEX, this prevents the first worker thread from rushing ahead.  */
> +  if (pthread_mutex_lock (&mutex) != 0)
> +    abort ();
> +
> +  /* Worker thread creation.  */
> +  for (int i = 0; i < NUM_THREADS; i++)
> +    {
> +      args[i] = i;
> +      pthread_create (&threads[i], NULL, worker_func, &args[i]);
> +    }
> +
> +  /* Wait for every thread to start.  */
> +  for (int i = 0; i < NUM_THREADS; i++)
> +    {
> +      if (sem_wait (&startup_semaphore) != 0)
> +	abort ();
> +    }
> +
> +  /* Unlock the first thread so it can proceed.  */
> +  if (pthread_mutex_unlock (&mutex) != 0)
> +    abort ();
> +
> +  /* Wait for the first thread only.  */
> +  pthread_join (threads[0], &retval);
> +
> +  /* Now post FINISH_SEMAPHORE to allow all the other threads to finish.  */
> +  for (int i = 1; i < NUM_THREADS; i++)
> +    sem_post (&finish_semaphore);
> +
> +  /* Now wait for the remaining threads to complete.  */
> +  for (int i = 1; i < NUM_THREADS; i++)
> +    pthread_join (threads[i], &retval);
> +
> +  /* Semaphore cleanup.  */
> +  sem_destroy (&finish_semaphore);
> +  sem_destroy (&startup_semaphore);
> +  sem_destroy (&thread_1_semaphore);
> +  sem_destroy (&thread_2_semaphore);
> +
> +  stop_marker ();
> +
> +  return 0;
> +}
> diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
> b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
> new file mode 100644
> index 00000000000..4159288a39c
> --- /dev/null
> +++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
> @@ -0,0 +1,156 @@
> +# Copyright 2022-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 inferior calls executed from a breakpoint condition in
> +# a multi-threaded program.
> +#
> +# This test has the inferior function call timeout, and checks how GDB
> +# handles this situation.
> +
> +standard_testfile
> +
> +if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
> +	  {debug pthreads}] } {
> +    return
> +}
> +
> +set cond_bp_line [gdb_get_line_number "Conditional breakpoint here"]
> +set final_bp_line [gdb_get_line_number "Stop marker"]
> +set segfault_line [gdb_get_line_number "Segfault here"]
> +
> +# Setup GDB based on TARGET_ASYNC and TARGET_NON_STOP.  Setup some
> +# breakpoints in the inferior, one of which has an inferior call
> +# within its condition.
> +#
> +# Continue GDB, the breakpoint with inferior call will be hit, but the
> +# inferior call will never return.  We expect GDB to timeout.
> +#
> +# The reason that the inferior call never completes is that a second
> +# thread, on which the inferior call relies, either hits a breakpoint
> +# (when OTHER_THREAD_BP is true), or crashes (when OTHER_THREAD_BP is
> +# false).
> +proc run_test { target_async target_non_stop other_thread_bp } {
> +    save_vars { ::GDBFLAGS } {
> +	append ::GDBFLAGS " -ex \"maint set target-non-stop $target_non_stop\""
> +	append ::GDBFLAGS " -ex \"maintenance set target-async ${target_async}\""
> +
> +	clean_restart ${::binfile}
> +    }
> +
> +    if {![runto_main]} {
> +	fail "run to main"

runto_main already emits a fail, so no need for this.

> +	return
> +    }
> +
> +    # The default timeout for indirect inferior calls (e.g. inferior
> +    # calls for conditional breakpoint expressions) is pretty high.
> +    # We don't want the test to take too long, so reduce this.
> +    #
> +    # However, the test relies on a second thread hitting some event
> +    # (either a breakpoint or signal) before this timeout expires.
> +    #
> +    # There is a chance that on a really slow system this might not
> +    # happen, in which case the test might fail.
> +    #
> +    # However, we still allocate 5 seconds, which feels like it should
> +    # be enough time in most cases, but maybe we need to do something
> +    # smarter here?  Possibly we could have some initial run where the
> +    # inferior doesn't timeout, but does perform the same interaction
> +    # between threads, we could time that, and use that as the basis
> +    # for this timeout.  For now though, we just hope 5 seconds is
> +    # enough.
> +    gdb_test_no_output "set indirect-call-timeout 5"
> +
> +    gdb_breakpoint \
> +	"${::srcfile}:${::cond_bp_line} if (condition_func ())"
> +    set bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
> +		    "get number for conditional breakpoint"]
> +
> +    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
> +    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
> +			  "get number for final breakpoint"]
> +
> +    # The thread performing an inferior call relies on a second
> +    # thread.  The second thread will segfault unless it hits a
> +    # breakpoint first.  In either case the initial thread will not
> +    # complete its inferior call.
> +    if { $other_thread_bp } {
> +	gdb_breakpoint "${::srcfile}:${::segfault_line}"
> +	set segfault_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
> +				 "get number for segfault breakpoint"]
> +    }
> +
> +    # When non-stop mode is off we get slightly different output from GDB.
> +    if { [gdb_is_remote_or_extended_remote_target] && !$target_non_stop} {
> +	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" received signal
> SIGINT, Interrupt\\."
> +    } else {
> +	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\."
> +    }
> +
> +    gdb_test "continue" \
> +	[multi_line \
> +	     $stopped_line_pattern \
> +	     ".*" \
> +	     "Error in testing condition for breakpoint ${bp_num}:" \
> +	     "The program being debugged timed out while in a function called from GDB\\." \
> +	     "GDB remains in the frame where the timeout occurred\\." \
> +	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
> +	     "Evaluation of the expression containing the function" \
> +	     "\\(condition_func\\) will be abandoned\\." \
> +	     "When the function is done executing, GDB will silently stop\\."] \
> +	"expected timeout waiting for inferior call to complete"
> +
> +    # Remember that other thread that either crashed (with a segfault)
> +    # or hit a breakpoint?  Now that the inferior call has timed out,
> +    # if we try to resume then we should see the pending event from
> +    # that other thread.
> +    if { $other_thread_bp } {
> +	gdb_test "continue" \
> +	    [multi_line \
> +		 "Continuing\\." \
> +		 ".*" \
> +		 "" \
> +		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${segfault_bp_num},
> do_segfault \[^\r\n\]+:${::segfault_line}" \
> +		 "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"] \
> +	    "hit the segfault breakpoint"
> +    } else {
> +	gdb_test "continue" \
> +	    [multi_line \
> +		 "Continuing\\." \
> +		 ".*" \
> +		 "Thread ${::decimal} \"infcall-from-bp\" received signal SIGSEGV,
> Segmentation fault\\." \
> +		 "\\\[Switching to Thread \[^\r\n\]+\\\]" \
> +		 "${::hex} in do_segfault \\(\\) at \[^\r\n\]+:${::segfault_line}" \
> +		 "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"] \
> +	    "hit the segfault"
> +    }
> +}
> +
> +foreach_with_prefix target_async {"on" "off" } {
> +
> +    if { !$target_async } {
> +	# GDB can't timeout while waiting for a thread if the target
> +	# runs with async-mode turned off; once the target is running
> +	# GDB is effectively blocked until the target stops for some
> +	# reason.
> +	continue
> +    }
> +
> +    foreach_with_prefix target_non_stop {"off" "on"} {
> +	foreach_with_prefix other_thread_bp { true false } {
> +	    run_test $target_async $target_non_stop $other_thread_bp
> +	}
> +    }
> +}
> --
> 2.25.4

Reviewed-By: Tankut Baris Aktemur <tankut.baris.aktemur@intel.com>

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] 202+ messages in thread

* RE: [PATCHv7 4/6] gdb/remote: avoid SIGINT after calling remote_target::stop
  2023-05-15 19:22             ` [PATCHv7 4/6] gdb/remote: avoid SIGINT after calling remote_target::stop Andrew Burgess
@ 2023-05-16 16:00               ` Aktemur, Tankut Baris
  2023-06-05 13:55                 ` Andrew Burgess
  0 siblings, 1 reply; 202+ messages in thread
From: Aktemur, Tankut Baris @ 2023-05-16 16:00 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

On Monday, May 15, 2023 9:22 PM, Andrew Burgess wrote:
> Currently, if the remote target is not running in non-stop mode, then,
> when GDB calls remote_target::stop, we end up sending an interrupt
> packet \x03 to the remote target.
> 
> If the user interrupts the inferior from the GDB prompt (e.g. by
> typing Ctrl-c), then GDB calls remote_target::interrupt, which also
> ends up sending the interrupt packet.
> 
> The problem here is that both of these mechanisms end up sending the
> interrupt packet, which means, when the target stops with a SIGINT,
> and this is reported back to GDB, we have no choice but to report this
> to the user as a SIGINT stop event.
> 
> Now maybe this is the correct thing to do, after all the target has
> been stopped with SIGINT.  However, this leads to an unfortunate
> change in behaviour when comparing non-stop vs all-stop mode.
> 
> When running in non-stop mode, and remote_target::stop is called, the
> target will be stopped with a vCont packet, and this stop is then
> reported back to GDB as GDB_SIGNAL_0, this will cause GDB to print a
> message like:
> 
>   Program stopped.
> 
> Or:
> 
>   Thread NN "binary name" stopped.
> 
> In contrast, when non-stop mode is off, we get messages like:
> 
>   Program received SIGINT, Segmentation fault.
> 
> Or:
> 
>   Thread NN "binary name" received SIGINT, Segmentation fault.
> 
> In this commit I propose making use of thread_info::stop_requested
> within remote.c to know if the stop was triggered by GDB (and the
> SIGINT should be hidden) or if the stop was a user interrupt, and the
> SIGINT should be printed.
> 
> In remote_target::process_stop_reply if the inferior stopped with
> SIGINT and the thread_info::stop_requested flag is set, then we change
> the stop signal to GDB_SIGNAL_0.
> 
> Two of the tests added in the previous commit exposed this issue.  In
> the previous commit the tests looked for either of the above
> patterns.  In this commit I've updated these tests to only look for
> the "stopped" based messages.
> 
> This commit is the reason why the previous commit took care to set the
> thread_info::stop_requested flag in infcall.c.
> ---
>  gdb/remote.c                                           | 10 ++++++++++
>  gdb/testsuite/gdb.base/infcall-timeout.exp             |  9 +--------
>  .../gdb.threads/infcall-from-bp-cond-timeout.exp       |  9 +--------
>  3 files changed, 12 insertions(+), 16 deletions(-)
> 
> diff --git a/gdb/remote.c b/gdb/remote.c
> index 8eaa1b2c4d1..c61eeeadc52 100644
> --- a/gdb/remote.c
> +++ b/gdb/remote.c
> @@ -8275,6 +8275,16 @@ remote_target::process_stop_reply (struct stop_reply *stop_reply,
>  	}
>        else
>  	{
> +	  /* If this stop was actually requested by GDB then we can hide
> +	     the SIGINT from the user.  */
> +	  if (status->kind () == TARGET_WAITKIND_STOPPED
> +	      && status->sig () == GDB_SIGNAL_INT)
> +	    {
> +	      thread_info *thr = this->find_thread (ptid);

A few lines above, there is

      remote_notice_new_inferior (ptid, false);
      remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);

which first does 'target->find_thread (ptid)' to find the thread_info*.
It is unfortunate that we cannot access the thread_info* directly from
remote_thread_info*.  It's not in this patch's scope to add such a backlink.
How about changing 

      remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);

to

      thread_info *thr = this->find_thread (ptid);
      remote_thread_info *remote_thr = get_remote_thread_info (thr);

so that we can reuse 'thr' without having to call 'find_thread'
a second time?

Besides this suggestion, the patch looks fine to me.  FWIW
Reviewed-By: Tankut Baris Aktemur <tankut.baris.aktemur@intel.com>

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] 202+ messages in thread

* RE: [PATCHv7 2/6] gdb: fix b/p conditions with infcalls in multi-threaded inferiors
  2023-05-16 15:09               ` Aktemur, Tankut Baris
@ 2023-06-05 13:53                 ` Andrew Burgess
  0 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-06-05 13:53 UTC (permalink / raw)
  To: Aktemur, Tankut Baris, gdb-patches; +Cc: Saiapova, Natalia

"Aktemur, Tankut Baris" <tankut.baris.aktemur@intel.com> writes:

> On Monday, May 15, 2023 9:22 PM, Andrew Burgess wrote:
>> This commit fixes bug PR 28942, that is, creating a conditional
>> breakpoint in a multi-threaded inferior, where the breakpoint
>> condition includes an inferior function call.
>> 
>> Currently, when a user tries to create such a breakpoint, then GDB
>> will fail with:
>> 
>>   (gdb) break infcall-from-bp-cond-single.c:61 if (return_true ())
>>   Breakpoint 2 at 0x4011fa: file
>> /tmp/build/gdb/testsuite/../../../src/gdb/testsuite/gdb.threads/infcall-from-bp-cond-
>> single.c, line 61.
>>   (gdb) continue
>>   Continuing.
>>   [New Thread 0x7ffff7c5d700 (LWP 2460150)]
>>   [New Thread 0x7ffff745c700 (LWP 2460151)]
>>   [New Thread 0x7ffff6c5b700 (LWP 2460152)]
>>   [New Thread 0x7ffff645a700 (LWP 2460153)]
>>   [New Thread 0x7ffff5c59700 (LWP 2460154)]
>>   Error in testing breakpoint condition:
>>   Couldn't get registers: No such process.
>>   An error occurred while in a function called from GDB.
>>   Evaluation of the expression containing the function
>>   (return_true) will be abandoned.
>>   When the function is done executing, GDB will silently stop.
>>   Selected thread is running.
>>   (gdb)
>> 
>> Or, in some cases, like this:
>> 
>>   (gdb) break infcall-from-bp-cond-simple.c:56 if (is_matching_tid (arg, 1))
>>   Breakpoint 2 at 0x401194: file
>> /tmp/build/gdb/testsuite/../../../src/gdb/testsuite/gdb.threads/infcall-from-bp-cond-
>> simple.c, line 56.
>>   (gdb) continue
>>   Continuing.
>>   [New Thread 0x7ffff7c5d700 (LWP 2461106)]
>>   [New Thread 0x7ffff745c700 (LWP 2461107)]
>>   ../../src.release/gdb/nat/x86-linux-dregs.c:146: internal-error:
>> x86_linux_update_debug_registers: Assertion `lwp_is_stopped (lwp)' failed.
>>   A problem internal to GDB has been detected,
>>   further debugging may prove unreliable.
>> 
>> The precise error depends on the exact thread state; so there's race
>> conditions depending on which threads have fully started, and which
>> have not.  But the underlying problem is always the same; when GDB
>> tries to execute the inferior function call from within the breakpoint
>> condition, GDB will, incorrectly, try to resume threads that are
>> already running - GDB doesn't realise that some threads might already
>> be running.
>> 
>> The solution proposed in this patch requires an additional member
>> variable thread_info::in_cond_eval.  This flag is set to true (in
>> breakpoint.c) when GDB is evaluating a breakpoint condition.
>> 
>> In user_visible_resume_ptid (infrun.c), when the in_cond_eval flag is
>> true, then GDB will only try to resume the current thread, that is,
>> the thread for which the breakpoint condition is being evaluated.
>> This solves the problem of GDB trying to resume threads that are
>> already running.
>> 
>> The next problem is that inferior function calls are assumed to be
>> synchronous, that is, GDB doesn't expect to start an inferior function
>> call in thread #1, then receive a stop from thread #2 for some other,
>> unrelated reason.  To prevent GDB responding to an event from another
>> thread, we update fetch_inferior_event and do_target_wait in infrun.c,
>> so that, when an inferior function call (on behalf of a breakpoint
>> condition) is in progress, we only wait for events from the current
>> thread (the one evaluating the condition).
>> 
>> In do_target_wait I had to change the inferior_matches lambda
>> function, which is used to select which inferior to wait on.
>> Previously the logic was this:
>> 
>>    auto inferior_matches = [&wait_ptid] (inferior *inf)
>>      {
>>        return (inf->process_target () != nullptr
>>                && ptid_t (inf->pid).matches (wait_ptid));
>>      };
>> 
>> This compares the pid of the inferior against the complete ptid we
>> want to wait on.  Before this commit wait_ptid was only ever
>> minus_one_ptid (which is special, and means any process), and so every
>> inferior would match.
>> 
>> After this commit though wait_ptid might represent a specific thread
>> in a specific inferior.  If we compare the pid of the inferior to a
>> specific ptid then these will not match.  The fix is to compare
>> against the pid extracted from the wait_ptid, not against the complete
>> wait_ptid itself.
>> 
>> In fetch_inferior_event, after receiving the event, we only want to
>> stop all the other threads, and call inferior_event_handler with
>> INF_EXEC_COMPLETE, if we are not evaluating a conditional breakpoint.
>> If we are, then all the other threads should be left doing whatever
>> they were before.  The inferior_event_handler call will be performed
>> once the breakpoint condition has finished being evaluated, and GDB
>> decides to stop or not.
>> 
>> The final problem that needs solving relates to GDB's commit-resume
>> mechanism, which allows GDB to collect resume requests into a single
>> packet in order to reduce traffic to a remote target.
>> 
>> The problem is that the commit-resume mechanism will not send any
>> resume requests for an inferior if there are already events pending on
>> the GDB side.
>> 
>> Imagine an inferior with two threads.  Both threads hit a breakpoint,
>> maybe the same conditional breakpoint.  At this point there are two
>> pending events, one for each thread.
>> 
>> GDB selects one of the events and spots that this is a conditional
>> breakpoint, GDB evaluates the condition.
>> 
>> The condition includes an inferior function call, so GDB sets up for
>> the call and resumes the one thread, the resume request is added to
>> the commit-resume queue.
>> 
>> When the commit-resume queue is committed GDB sees that there is a
>> pending event from another thread, and so doesn't send any resume
>> requests to the actual target, GDB is assuming that when we wait we
>> will select the event from the other thread.
>> 
>> However, as this is an inferior function call for a condition
>> evaluation, we will not select the event from the other thread, we
>> only care about events from the thread that is evaluating the
>> condition - and the resume for this thread was never sent to the
>> target.
>> 
>> And so, GDB hangs, waiting for an event from a thread that was never
>> fully resumed.
>> 
>> To fix this issue I have added the concept of "forcing" the
>> commit-resume queue.  When enabling commit resume, if the force flag
>> is true, then any resumes will be committed to the target, even if
>> there are other threads with pending events.
>> 
>> A note on authorship: this patch was based on some work done by
>> Natalia Saiapova and Tankut Baris Aktemur from Intel[1].  I have made
>> some changes to their work in this version.
>> 
>> Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=28942
>> 
>> [1] https://sourceware.org/pipermail/gdb-patches/2020-October/172454.html
>> 
>> Co-authored-by: Natalia Saiapova <natalia.saiapova@intel.com>
>> Co-authored-by: Tankut Baris Aktemur <tankut.baris.aktemur@intel.com>
>
> Thanks again for this.
>
> I have a few minor comments inlined below.  Except those, it looks good to me.
> There is already Co-authored-by above, but in case you'd like to also add:
> Reviewed-By: Tankut Baris Aktemur <tankut.baris.aktemur@intel.com>

I fixed this issues you highlighted and added your reviewed-by tag.

Thanks,
Andrew

>
> Regards
> -Baris
>
>
>> ---
>>  gdb/breakpoint.c                              |   2 +
>>  gdb/gdbthread.h                               |   3 +
>>  gdb/infcall.c                                 |   6 +
>>  gdb/infrun.c                                  |  64 +++--
>>  gdb/infrun.h                                  |   3 +-
>>  .../infcall-from-bp-cond-other-thread-event.c | 135 ++++++++++
>>  ...nfcall-from-bp-cond-other-thread-event.exp | 174 +++++++++++++
>>  .../gdb.threads/infcall-from-bp-cond-simple.c |  89 +++++++
>>  .../infcall-from-bp-cond-simple.exp           | 235 ++++++++++++++++++
>>  .../gdb.threads/infcall-from-bp-cond-single.c | 139 +++++++++++
>>  .../infcall-from-bp-cond-single.exp           | 117 +++++++++
>>  11 files changed, 952 insertions(+), 15 deletions(-)
>>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
>>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
>>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
>>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
>>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
>>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
>> 
>> diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
>> index fdb184ae81f..6fceed8f408 100644
>> --- a/gdb/breakpoint.c
>> +++ b/gdb/breakpoint.c
>> @@ -5548,6 +5548,8 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
>>  	{
>>  	  try
>>  	    {
>> +	      scoped_restore reset_in_cond_eval
>> +		= make_scoped_restore (&thread->control.in_cond_eval, true);
>>  	      condition_result = breakpoint_cond_eval (cond);
>>  	    }
>>  	  catch (const gdb_exception_error &ex)
>> diff --git a/gdb/gdbthread.h b/gdb/gdbthread.h
>> index 7135515bf45..897752f2691 100644
>> --- a/gdb/gdbthread.h
>> +++ b/gdb/gdbthread.h
>> @@ -171,6 +171,9 @@ struct thread_control_state
>>       command.  This is used to decide whether "set scheduler-locking
>>       step" behaves like "on" or "off".  */
>>    int stepping_command = 0;
>> +
>> +  /* True if the thread is evaluating a BP condition.  */
>> +  bool in_cond_eval = false;
>>  };
>> 
>>  /* Inferior thread specific part of `struct infcall_suspend_state'.  */
>> diff --git a/gdb/infcall.c b/gdb/infcall.c
>> index 233ef5f29e9..49c88add394 100644
>> --- a/gdb/infcall.c
>> +++ b/gdb/infcall.c
>> @@ -642,6 +642,12 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
>> 
>>        proceed (real_pc, GDB_SIGNAL_0);
>> 
>> +      /* Enable commit resume, but pass true for the force flag.  This
>> +	 ensures any thread we set running in proceed will actually be
>> +	 committed to the target, even if some other thread in the current
>> +	 target has a pending event.  */
>> +      scoped_enable_commit_resumed enable ("infcall", true);
>> +
>>        infrun_debug_show_threads ("non-exited threads after proceed for inferior-call",
>>  				 all_non_exited_threads ());
>> 
>> diff --git a/gdb/infrun.c b/gdb/infrun.c
>> index 07ef3c7c187..ea7ab6187ee 100644
>> --- a/gdb/infrun.c
>> +++ b/gdb/infrun.c
>> @@ -2275,6 +2275,14 @@ user_visible_resume_ptid (int step)
>>  	 mode.  */
>>        resume_ptid = inferior_ptid;
>>      }
>> +  else if (inferior_ptid != null_ptid
>> +	   && inferior_thread ()->control.in_cond_eval)
>> +    {
>> +      /* The inferior thread is evaluating a BP condition.  Other threads
>> +	 might be stopped or running and we do not want to change their
>> +	 state, thus, resume only the current thread.  */
>> +      resume_ptid = inferior_ptid;
>> +    }
>>    else if (!sched_multi && target_supports_multi_process ())
>>      {
>>        /* Resume all threads of the current process (and none of other
>> @@ -2992,12 +3000,24 @@ schedlock_applies (struct thread_info *tp)
>>  					    execution_direction)));
>>  }
>> 
>> -/* Set process_stratum_target::COMMIT_RESUMED_STATE in all target
>> -   stacks that have threads executing and don't have threads with
>> -   pending events.  */
>> +/* When FORCE_P is false, set process_stratum_target::COMMIT_RESUMED_STATE
>> +   in all target stacks that have threads executing and don't have threads
>> +   with pending events.
>> +
>> +   When FORCE_P is true, set process_stratum_target::COMMIT_RESUMED_STATE
>> +   in all target stacks that have threads executing regardless of whether
>> +   there are pending events or not.
>> +
>> +    Passing FORCE_P as false makes sense when GDB is going to wait for
>> +    events from all threads and will therefore spot the pending events.
>> +    However, if GDB is only going to wait for events from select threads
>> +    (i.e. when performing an inferior call) then a pending event on some
>> +    other thread will not be spotted, and if we fail to commit the resume
>> +    state for the thread performing the inferior call, then the inferior
>> +    call will never complete (or even start).  */
>
> There is one extra space of indentation above.  Is that intentional?
>
>>  static void
>> -maybe_set_commit_resumed_all_targets ()
>> +maybe_set_commit_resumed_all_targets (bool force_p)
>>  {
>>    scoped_restore_current_thread restore_thread;
>> 
>> @@ -3026,7 +3046,7 @@ maybe_set_commit_resumed_all_targets ()
>>  	 status to report, handle it before requiring the target to
>>  	 commit its resumed threads: handling the status might lead to
>>  	 resuming more threads.  */
>> -      if (proc_target->has_resumed_with_pending_wait_status ())
>> +      if (!force_p && proc_target->has_resumed_with_pending_wait_status ())
>>  	{
>>  	  infrun_debug_printf ("not requesting commit-resumed for target %s, a"
>>  			       " thread has a pending waitstatus",
>> @@ -3036,7 +3056,7 @@ maybe_set_commit_resumed_all_targets ()
>> 
>>        switch_to_inferior_no_thread (inf);
>> 
>> -      if (target_has_pending_events ())
>> +      if (!force_p && target_has_pending_events ())
>>  	{
>>  	  infrun_debug_printf ("not requesting commit-resumed for target %s, "
>>  			       "target has pending events",
>> @@ -3129,7 +3149,7 @@ scoped_disable_commit_resumed::reset ()
>>      {
>>        /* This is the outermost instance, re-enable
>>  	 COMMIT_RESUMED_STATE on the targets where it's possible.  */
>> -      maybe_set_commit_resumed_all_targets ();
>> +      maybe_set_commit_resumed_all_targets (false);
>>      }
>>    else
>>      {
>> @@ -3162,7 +3182,7 @@ scoped_disable_commit_resumed::reset_and_commit ()
>>  /* See infrun.h.  */
>> 
>>  scoped_enable_commit_resumed::scoped_enable_commit_resumed
>> -  (const char *reason)
>> +  (const char *reason, bool force_p)
>>    : m_reason (reason),
>>      m_prev_enable_commit_resumed (enable_commit_resumed)
>>  {
>> @@ -3174,7 +3194,7 @@ scoped_enable_commit_resumed::scoped_enable_commit_resumed
>> 
>>        /* Re-enable COMMIT_RESUMED_STATE on the targets where it's
>>  	 possible.  */
>> -      maybe_set_commit_resumed_all_targets ();
>> +      maybe_set_commit_resumed_all_targets (force_p);
>> 
>>        maybe_call_commit_resumed_all_targets ();
>>      }
>> @@ -3880,10 +3900,11 @@ do_target_wait (ptid_t wait_ptid, execution_control_state *ecs,
>>       polling the rest of the inferior list starting from that one in a
>>       circular fashion until the whole list is polled once.  */
>> 
>> -  auto inferior_matches = [&wait_ptid] (inferior *inf)
>> +  ptid_t wait_ptid_pid {wait_ptid.pid ()};
>> +  auto inferior_matches = [&wait_ptid_pid] (inferior *inf)
>>      {
>>        return (inf->process_target () != nullptr
>> -	      && ptid_t (inf->pid).matches (wait_ptid));
>> +	      && ptid_t (inf->pid).matches (wait_ptid_pid));
>>      };
>> 
>>    /* First see how many matching inferiors we have.  */
>> @@ -4352,7 +4373,17 @@ fetch_inferior_event ()
>>         the event.  */
>>      scoped_disable_commit_resumed disable_commit_resumed ("handling event");
>> 
>> -    if (!do_target_wait (minus_one_ptid, &ecs, TARGET_WNOHANG))
>> +    /* Is the current thread performing an inferior function call as part
>> +       of a breakpoint condition evaluation?  */
>> +    bool in_cond_eval = (inferior_ptid != null_ptid
>> +			 && inferior_thread ()->control.in_cond_eval);
>> +
>> +    /* If the thread is in the middle of the condition evaluation, wait for
>> +       an event from the current thread.  Otherwise, wait for an event from
>> +       any thread.  */
>> +    ptid_t waiton_ptid = in_cond_eval ? inferior_ptid : minus_one_ptid;
>> +
>> +    if (!do_target_wait (waiton_ptid, &ecs, TARGET_WNOHANG))
>>        {
>>  	infrun_debug_printf ("do_target_wait returned no event");
>>  	disable_commit_resumed.reset_and_commit ();
>> @@ -4408,7 +4439,12 @@ fetch_inferior_event ()
>>  	    bool should_notify_stop = true;
>>  	    bool proceeded = false;
>> 
>> -	    stop_all_threads_if_all_stop_mode ();
>> +	    /* If the thread that stopped just completed an inferior
>> +	       function call as part of a condition evaluation, then we
>> +	       don't want to stop all the other threads.  */
>> +	    if (ecs.event_thread == nullptr
>> +		|| !ecs.event_thread->control.in_cond_eval)
>> +	      stop_all_threads_if_all_stop_mode ();
>> 
>>  	    clean_up_just_stopped_threads_fsms (&ecs);
>> 
>> @@ -4423,7 +4459,7 @@ fetch_inferior_event ()
>>  		  proceeded = normal_stop ();
>>  	      }
>> 
>> -	    if (!proceeded)
>> +	    if (!proceeded && !in_cond_eval)
>>  	      {
>>  		inferior_event_handler (INF_EXEC_COMPLETE);
>>  		cmd_done = 1;
>> diff --git a/gdb/infrun.h b/gdb/infrun.h
>> index 9513bc570e4..1a6743aa45e 100644
>> --- a/gdb/infrun.h
>> +++ b/gdb/infrun.h
>> @@ -395,7 +395,8 @@ extern void maybe_call_commit_resumed_all_targets ();
>> 
>>  struct scoped_enable_commit_resumed
>>  {
>> -  explicit scoped_enable_commit_resumed (const char *reason);
>> +  explicit scoped_enable_commit_resumed (const char *reason,
>> +					 bool force_p = false);
>>    ~scoped_enable_commit_resumed ();
>> 
>>    DISABLE_COPY_AND_ASSIGN (scoped_enable_commit_resumed);
>> diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
>> b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
>> new file mode 100644
>> index 00000000000..e2a8ccb4ebe
>> --- /dev/null
>> +++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
>> @@ -0,0 +1,135 @@
>> +/* Copyright 2022-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 <pthread.h>
>> +#include <unistd.h>
>> +#include <stdlib.h>
>> +#include <sched.h>
>> +
>> +#define NUM_THREADS 2
>> +
>> +pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
>> +
>> +/* Some global variables to poke, just for something to do.  */
>> +volatile int global_var_0 = 0;
>> +volatile int global_var_1 = 0;
>> +
>> +/* This flag is updated from GDB.  */
>> +volatile int raise_signal = 0;
>> +
>> +/* Implement the breakpoint condition function.  Release the other thread
>> +   and try to give the other thread a chance to run.  Then return ANSWER.  */
>> +int
>> +condition_core_func (int answer)
>> +{
>> +  /* This unlock should release the other thread.  */
>> +  if (pthread_mutex_unlock (&mutex) != 0)
>> +    abort ();
>> +
>> +  /* And this yield and sleep should (hopefully) give the other thread a
>> +     chance to run.  This isn't guaranteed of course, but once the other
>> +     thread does run it should hit a breakpoint, which GDB should
>> +     (temporarily) ignore, so there's no easy way for us to know the other
>> +     thread has done what it needs to, thus, yielding and sleeping is the
>> +     best we can do.  */
>> +  sched_yield ();
>> +  sleep (2);
>> +
>> +  return answer;
>> +}
>> +
>> +void
>> +stop_marker ()
>> +{
>> +  int a = 100;	/* Final breakpoint here.  */
>> +}
>> +
>> +/* A breakpoint condition function that always returns true.  */
>> +int
>> +condition_true_func ()
>> +{
>> +  return condition_core_func (1);
>> +}
>> +
>> +/* A breakpoint condition function that always returns false.  */
>> +int
>> +condition_false_func ()
>> +{
>> +  return condition_core_func (0);
>> +}
>> +
>> +void *
>> +worker_func (void *arg)
>> +{
>> +  volatile int *ptr = 0;
>> +  int tid = *((int *) arg);
>> +
>> +  switch (tid)
>> +    {
>> +    case 0:
>> +      global_var_0 = 11;	/* First thread breakpoint.  */
>> +      break;
>> +
>> +    case 1:
>> +      if (pthread_mutex_lock (&mutex) != 0)
>> +	abort ();
>> +      if (raise_signal)
>> +	global_var_1 = *ptr;	/* Signal here.  */
>> +      else
>> +	global_var_1 = 99;	/* Other thread breakpoint.  */
>> +      break;
>> +
>> +    default:
>> +      abort ();
>> +    }
>> +
>> +  return NULL;
>> +}
>> +
>> +int
>> +main ()
>> +{
>> +  pthread_t threads[NUM_THREADS];
>> +  int args[NUM_THREADS];
>> +
>> +  /* Set an alarm, just in case the test deadlocks.  */
>> +  alarm (300);
>> +
>> +  /* We want the mutex to start locked.  */
>> +  if (pthread_mutex_lock (&mutex) != 0)
>> +    abort ();
>> +
>> +  for (int i = 0; i < NUM_THREADS; i++)
>> +    {
>> +      args[i] = i;
>> +      pthread_create (&threads[i], NULL, worker_func, &args[i]);
>> +    }
>> +
>> +  for (int i = 0; i < NUM_THREADS; i++)
>> +    {
>> +      void *retval;
>> +      pthread_join (threads[i], &retval);
>> +    }
>> +
>> +  /* Unlock once we're done, just for cleanliness.  */
>> +  if (pthread_mutex_unlock (&mutex) != 0)
>> +    abort ();
>> +
>> +  stop_marker ();
>> +
>> +  return 0;
>> +}
>> diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
>> b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
>> new file mode 100644
>> index 00000000000..6d4e1e13ab2
>> --- /dev/null
>> +++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
>> @@ -0,0 +1,174 @@
>> +# Copyright 2022-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/>.
>> +
>> +# Test for conditional breakpoints where the breakpoint condition includes
>> +# an inferior function call.
>> +#
>> +# The tests in this script are testing what happens when an event arrives in
>> +# another thread while GDB is waiting for the inferior function call (in the
>> +# breakpoint condition) to finish.
>> +#
>> +# The expectation is that GDB will queue events for other threads and wait
>> +# for the inferior function call to complete, if the condition is true, then
>> +# the conditional breakpoint should be reported first.  The other thread
>> +# event should of course, not get lost, and should be reported as soon as
>> +# the user tries to continue the inferior.
>> +#
>> +# If the conditional breakpoint ends up not being taken (the condition is
>> +# false), then the other thread event should be reported immediately.
>> +#
>> +# This script tests what happens when the other thread event is (a) the
>> +# other thread hitting a breakpoint, and (b) the other thread taking a
>> +# signal (SIGSEGV in this case).
>> +
>> +standard_testfile
>> +
>> +if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
>> +	  {debug pthreads}] == -1 } {
>> +    return
>> +}
>> +
>> +set cond_bp_line [gdb_get_line_number "First thread breakpoint"]
>> +set other_bp_line [gdb_get_line_number "Other thread breakpoint"]
>> +set final_bp_line [gdb_get_line_number "Final breakpoint here"]
>> +set signal_line [gdb_get_line_number "Signal here"]
>> +
>> +# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
>> +proc start_gdb_and_runto_main { target_async target_non_stop } {
>> +    save_vars { ::GDBFLAGS } {
>> +	append ::GDBFLAGS \
>> +	    " -ex \"maint set target-non-stop $target_non_stop\""
>> +	append ::GDBFLAGS \
>> +	    " -ex \"maintenance set target-async ${target_async}\""
>> +
>> +	clean_restart ${::binfile}
>> +    }
>> +
>> +    if { ![runto_main] } {
>> +	return -1
>> +    }
>> +
>> +    return 0
>> +}
>> +
>> +# Run a test of GDB's conditional breakpoints, where the conditions include
>> +# inferior function calls.  While the inferior function call is executing
>> +# another thread will hit a breakpoint (when OTHER_THREAD_SIGNAL is false),
>> +# or receive a signal (when OTHER_THREAD_SIGNAL is true).  GDB should report
>> +# the conditional breakpoint first (if the condition is true), and then
>> +# report the second thread event once the inferior is continued again.
>> +#
>> +# When STOP_AT_COND is true then the conditional breakpoint will have a
>> +# condition that evaluates to true (and the GDB will stop at the
>
> Nit: No "the" before "GDB".
>
>> +# breakpoint), otherwise, the condition will evaluate to false (and GDB will
>> +# not stop at the breakpoint).
>> +proc run_condition_test { stop_at_cond other_thread_signal \
>> +			      target_async target_non_stop } {
>> +    if { [start_gdb_and_runto_main $target_async \
>> +	      $target_non_stop] == -1 } {
>> +	return
>> +    }
>> +
>> +    # Setup the conditional breakpoint.
>> +    if { $stop_at_cond } {
>> +	set cond_func "condition_true_func"
>> +    } else {
>> +	set cond_func "condition_false_func"
>> +    }
>> +    gdb_breakpoint \
>> +	"${::srcfile}:${::cond_bp_line} if (${cond_func} ())"
>> +    set cond_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
>> +			"get number for conditional breakpoint"]
>> +
>> +    if { $other_thread_signal } {
>> +	# Arrange for the other thread to raise a signal while GDB is
>> +	# evaluating the breakpoint condition.
>> +	gdb_test_no_output "set raise_signal = 1"
>> +    } else {
>> +	# And a breakpoint that will be hit by another thread only once the
>> +	# breakpoint condition starts to be evaluated.
>> +	gdb_breakpoint "${::srcfile}:${::other_bp_line}"
>> +	set other_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
>> +			      "get number for other breakpoint"]
>> +    }
>> +
>> +    # A final breakpoint once the test has completed.
>> +    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
>> +    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
>> +			  "get number for final breakpoint"]
>> +
>> +    if { $stop_at_cond } {
>> +	# Continue.  The first breakpoint we hit should be the conditional
>> +	# breakpoint.  The other thread will have hit its breakpoint, but
>> +	# that will have been deferred until the conditional breakpoint is
>> +	# reported.
>> +	gdb_test "continue" \
>> +	    [multi_line \
>> +		 "Continuing\\." \
>> +		 ".*" \
>> +		 "" \
>> +		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${cond_bp_num},
>> worker_func \[^\r\n\]+:${::cond_bp_line}" \
>> +		 "${::decimal}\\s+\[^\r\n\]+First thread breakpoint\[^\r\n\]+"] \
>> +	    "hit the conditional breakpoint"
>> +    }
>> +
>> +    if { $other_thread_signal } {
>> +	# Now continue again, the other thread will now report that it
>> +	# received a signal.
>> +	gdb_test "continue" \
>> +	    [multi_line \
>> +		 "Continuing\\." \
>> +		 ".*" \
>> +		 "Thread ${::decimal} \"\[^\"\r\n\]+\" received signal SIGSEGV, Segmentation
>> fault\\." \
>> +		 "\\\[Switching to Thread \[^\r\n\]+\\\]" \
>> +		 "${::hex} in worker_func \[^\r\n\]+:${::signal_line}" \
>> +		 "${::decimal}\\s+\[^\r\n\]+Signal here\[^\r\n\]+"] \
>> +	    "received signal in other thread"
>> +    } else {
>> +	# Now continue again, the other thread will now report its
>> +	# breakpoint.
>> +	gdb_test "continue" \
>> +	    [multi_line \
>> +		 "Continuing\\." \
>> +		 ".*" \
>> +		 "" \
>> +		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${other_bp_num},
>> worker_func \[^\r\n\]+:${::other_bp_line}" \
>> +		 "${::decimal}\\s+\[^\r\n\]+Other thread breakpoint\[^\r\n\]+"] \
>> +	    "hit the breakpoint in other thread"
>> +
>> +	# Run to the stop marker.
>> +	gdb_test "continue" \
>> +	    [multi_line \
>> +		 "Continuing\\." \
>> +		 ".*" \
>> +		 "" \
>> +		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${final_bp_num},
>> stop_marker \[^\r\n\]+:${::final_bp_line}" \
>> +		 "${::decimal}\\s+\[^\r\n\]+Final breakpoint here\[^\r\n\]+"] \
>> +	    "hit the final breakpoint"
>> +    }
>> +
>> +    gdb_exit
>
> Is this really necessary?  We do clean_restart at the beginning of a test,
> which exits GDB as the first thing.
>
>> +}
>> +
>> +foreach_with_prefix target_async { "on" "off" } {
>> +    foreach_with_prefix target_non_stop { "on" "off" } {
>> +	foreach_with_prefix other_thread_signal { true false } {
>> +	    foreach_with_prefix stop_at_cond { true false } {
>> +		run_condition_test $stop_at_cond $other_thread_signal \
>> +		    $target_async $target_non_stop
>> +	    }
>> +	}
>> +    }
>> +}
>> diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
>> b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
>> new file mode 100644
>> index 00000000000..9d746d8be49
>> --- /dev/null
>> +++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
>> @@ -0,0 +1,89 @@
>> +/* Copyright 2022-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 <pthread.h>
>> +#include <unistd.h>
>> +
>> +#define NUM_THREADS 3
>> +
>> +int
>> +is_matching_tid (int *tid_ptr, int tid_value)
>> +{
>> +  return *tid_ptr == tid_value;
>> +}
>> +
>> +int
>> +return_true ()
>> +{
>> +  return 1;
>> +}
>> +
>> +int
>> +return_false ()
>> +{
>> +  return 0;
>> +}
>> +
>> +int
>> +function_that_segfaults ()
>> +{
>> +  int *p = 0;
>> +  *p = 1;	/* Segfault happens here.   */
>> +}
>> +
>> +int
>> +function_with_breakpoint ()
>> +{
>> +  return 1;	/* Nested breakpoint.  */
>> +}
>> +
>> +void *
>> +worker_func (void *arg)
>> +{
>> +  int a = 42;	/* Breakpoint here.  */
>> +}
>> +
>> +void
>> +stop_marker ()
>> +{
>> +  int b = 99;	/* Stop marker.  */
>> +}
>> +
>> +int
>> +main ()
>> +{
>> +  pthread_t threads[NUM_THREADS];
>> +  int args[NUM_THREADS];
>> +
>> +  alarm (300);
>> +
>> +  for (int i = 0; i < NUM_THREADS; i++)
>> +    {
>> +      args[i] = i;
>> +      pthread_create (&threads[i], NULL, worker_func, &args[i]);
>> +    }
>> +
>> +  for (int i = 0; i < NUM_THREADS; i++)
>> +    {
>> +      void *retval;
>> +      pthread_join (threads[i], &retval);
>> +    }
>> +
>> +  stop_marker ();
>> +
>> +  return 0;
>> +}
>> diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
>> b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
>> new file mode 100644
>> index 00000000000..37e1b64d9a4
>> --- /dev/null
>> +++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
>> @@ -0,0 +1,235 @@
>> +# Copyright 2022-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/>.
>> +
>> +# Some simple tests of inferior function calls from breakpoint
>> +# conditions, in multi-threaded inferiors.
>> +#
>> +# This test sets up a multi-threaded inferior, and places a breakpoint
>> +# at a location that many of the threads will reach.  We repeat the
>> +# test with different conditions, sometimes a single thread should
>> +# stop at the breakpoint, sometimes multiple threads should stop, and
>> +# sometime no threads should stop.
>
> Typo: sometime -> sometimes
>
>> +
>> +standard_testfile
>> +
>> +if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
>> +	  {debug pthreads}] == -1 } {
>> +    return
>> +}
>> +
>> +set cond_bp_line [gdb_get_line_number "Breakpoint here"]
>> +set stop_bp_line [gdb_get_line_number "Stop marker"]
>> +set nested_bp_line [gdb_get_line_number "Nested breakpoint"]
>> +set segv_line [gdb_get_line_number "Segfault happens here"]
>> +
>> +# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
>> +proc start_gdb_and_runto_main { target_async target_non_stop } {
>> +    save_vars { ::GDBFLAGS } {
>> +	append ::GDBFLAGS \
>> +	    " -ex \"maint set target-non-stop $target_non_stop\""
>> +	append ::GDBFLAGS \
>> +	    " -ex \"maintenance set target-async ${target_async}\""
>> +
>> +	clean_restart ${::binfile}
>> +    }
>> +
>> +    if { ![runto_main] } {
>> +	return -1
>> +    }
>> +
>> +    return 0
>> +}
>> +
>> +# Run a test of GDB's conditional breakpoints, where the conditions include
>> +# inferior function calls.
>> +#
>> +# CONDITION is the expression to be used as the breakpoint condition.
>> +#
>> +# N_EXPECTED_HITS is the number of threads that we expect to stop due to
>> +# CONDITON.
>> +#
>> +# MESSAGE is used as a test name prefix.
>> +proc run_condition_test { message n_expected_hits condition \
>> +			      target_async target_non_stop } {
>> +    with_test_prefix $message {
>> +
>> +	if { [start_gdb_and_runto_main $target_async \
>> +		  $target_non_stop] == -1 } {
>> +	    return
>> +	}
>> +
>> +	# Use this convenience variable to track how often the
>> +	# breakpoint condition has been evaluated.  This should be
>> +	# once per thread.
>> +	gdb_test "set \$n_cond_eval = 0"
>> +
>> +	# Setup the conditional breakpoint.
>> +	gdb_breakpoint \
>> +	    "${::srcfile}:${::cond_bp_line} if ((++\$n_cond_eval) && (${condition}))"
>> +
>> +	# And a breakpoint that we hit when the test is over, this one is
>> +	# not conditional.  Only the main thread gets here once all the
>> +	# other threads have finished.
>> +	gdb_breakpoint "${::srcfile}:${::stop_bp_line}"
>> +
>> +	# The number of times we stop at the conditional breakpoint.
>> +	set n_hit_condition 0
>> +
>> +	# Now keep 'continue'-ing GDB until all the threads have finished
>> +	# and we reach the stop_marker breakpoint.
>> +	gdb_test_multiple "continue" "spot all breakpoint hits" {
>> +	    -re " worker_func
>> \[^\r\n\]+${::srcfile}:${::cond_bp_line}\r\n${::decimal}\\s+\[^\r\n\]+Breakpoint
>> here\[^\r\n\]+\r\n${::gdb_prompt} $" {
>> +		incr n_hit_condition
>> +		send_gdb "continue\n"
>> +		exp_continue
>> +	    }
>> +
>> +	    -re " stop_marker
>> \[^\r\n\]+${::srcfile}:${::stop_bp_line}\r\n${::decimal}\\s+\[^\r\n\]+Stop
>> marker\[^\r\n\]+\r\n${::gdb_prompt} $" {
>> +		pass $gdb_test_name
>> +	    }
>> +	}
>> +
>> +	gdb_assert { $n_hit_condition == $n_expected_hits } \
>> +	    "stopped at breakpoint the expected number of times"
>> +
>> +	# Ensure the breakpoint condition was evaluated once per thread.
>> +	gdb_test "print \$n_cond_eval" "= 3" \
>> +	    "condition was evaluated in each thread"
>> +    }
>> +}
>> +
>> +# Check that after handling a conditional breakpoint (where the condition
>> +# includes an inferior call), it is still possible to kill the running
>> +# inferior, and then restart the inferior.
>> +#
>> +# At once point doing this would result in GDB giving an assertion error.
>> +proc_with_prefix run_kill_and_restart_test { target_async target_non_stop } {
>> +    # This test relies on the 'start' command, which is not possible with
>> +    # the plain 'remote' target.
>> +    if { [target_info gdb_protocol] == "remote" } {
>> +	return
>> +    }
>> +
>> +    if { [start_gdb_and_runto_main $target_async \
>> +	      $target_non_stop] == -1 } {
>> +	return
>> +    }
>> +
>> +    # Setup the conditional breakpoint.
>> +    gdb_breakpoint \
>> +	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 1))"
>> +    gdb_continue_to_breakpoint "worker_func"
>> +
>> +    # Now kill the program being debugged.
>> +    gdb_test "kill" "" "kill process" \
>> +	"Kill the program being debugged.*y or n. $" "y"
>> +
>> +    # Check we can restart the inferior.  At one point this would trigger an
>> +    # assertion.
>> +    gdb_test "start" ".*"
>
> I believe using 'gdb_start_cmd' is preferred.
>
>> +}
>> +
>> +# Create a conditional breakpoint which includes a call to a function that
>> +# segfaults.  Run GDB and check what happens when the inferior segfaults
>> +# during the inferior call.
>> +proc_with_prefix run_bp_cond_segfaults { target_async target_non_stop } {
>> +    if { [start_gdb_and_runto_main $target_async \
>> +	      $target_non_stop] == -1 } {
>> +	return
>> +    }
>> +
>> +    # This test relies on the inferior segfaulting when trying to
>> +    # access address zero.
>> +    if { [is_address_zero_readable] } {
>> +	return
>> +    }
>> +
>> +    # Setup the conditional breakpoint, include a call to
>> +    # 'function_that_segfaults', which triggers the segfault.
>> +    gdb_breakpoint \
>> +	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 0) &&
>> function_that_segfaults ())"
>> +    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
>> +		      "get number of conditional breakpoint"]
>> +
>> +    gdb_test "continue" \
>> +	[multi_line \
>> +	     "Continuing\\." \
>> +	     ".*" \
>> +	     "Thread ${::decimal} \"infcall-from-bp\" received signal SIGSEGV, Segmentation
>> fault\\." \
>> +	     "${::hex} in function_that_segfaults \\(\\) at \[^\r\n\]+:${::segv_line}" \
>> +	     "${::decimal}\\s+\[^\r\n\]+Segfault happens here\[^\r\n\]+" \
>> +	     "Error in testing condition for breakpoint ${bp_1_num}:" \
>> +	     "The program being debugged was signaled while in a function called from GDB\\."
>> \
>> +	     "GDB remains in the frame where the signal was received\\." \
>> +	     "To change this behavior use \"set unwindonsignal on\"\\." \
>> +	     "Evaluation of the expression containing the function" \
>> +	     "\\(function_that_segfaults\\) will be abandoned\\." \
>> +	     "When the function is done executing, GDB will silently stop\\."]
>> +}
>> +
>> +# Create a conditional breakpoint which includes a call to a function that
>> +# itself has a breakpoint set within it.  Run GDB and check what happens
>> +# when GDB hits the nested breakpoint.
>> +proc_with_prefix run_bp_cond_hits_breakpoint { target_async target_non_stop } {
>> +    if { [start_gdb_and_runto_main $target_async \
>> +	      $target_non_stop] == -1 } {
>> +	return
>> +    }
>> +
>> +    # Setup the conditional breakpoint, include a call to
>> +    # 'function_with_breakpoint' in which we will shortly place a
>> +    # breakpoint.
>> +    gdb_breakpoint \
>> +	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 0) &&
>> function_with_breakpoint ())"
>> +    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
>> +		      "get number of conditional breakpoint"]
>> +
>> +    gdb_breakpoint "${::srcfile}:${::nested_bp_line}"
>> +    set bp_2_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
>> +		      "get number of nested breakpoint"]
>> +
>> +    gdb_test "continue" \
>> +	[multi_line \
>> +	     "Continuing\\." \
>> +	     ".*" \
>> +	     "Thread ${::decimal} \"infcall-from-bp\" hit Breakpoint ${bp_2_num},
>> function_with_breakpoint \\(\\) at \[^\r\n\]+:${::nested_bp_line}" \
>> +	     "${::decimal}\\s+\[^\r\n\]+Nested breakpoint\[^\r\n\]+" \
>> +	     "Error in testing condition for breakpoint ${bp_1_num}:" \
>> +	     "The program being debugged stopped while in a function called from GDB\\." \
>> +	     "Evaluation of the expression containing the function" \
>> +	     "\\(function_with_breakpoint\\) will be abandoned\\." \
>> +	     "When the function is done executing, GDB will silently stop\\."]
>> +}
>> +
>> +foreach_with_prefix target_async { "on" "off" } {
>> +    foreach_with_prefix target_non_stop { "on" "off" } {
>> +	run_condition_test "exactly one thread is hit" \
>> +	    1 "is_matching_tid (arg, 1)" \
>> +	    $target_async $target_non_stop
>> +	run_condition_test "exactly two threads are hit" \
>> +	    2 "(is_matching_tid (arg, 0) || is_matching_tid (arg, 2))" \
>> +	    $target_async $target_non_stop
>> +	run_condition_test "all three threads are hit" \
>> +	    3 "return_true ()" \
>> +	    $target_async $target_non_stop
>> +	run_condition_test "no thread is hit" \
>> +	    0 "return_false ()" \
>> +	    $target_async $target_non_stop
>> +
>> +	run_kill_and_restart_test $target_async $target_non_stop
>> +	run_bp_cond_segfaults $target_async $target_non_stop
>> +	run_bp_cond_hits_breakpoint $target_async $target_non_stop
>> +    }
>> +}
>> diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
>> b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
>> new file mode 100644
>> index 00000000000..835c72f03cf
>> --- /dev/null
>> +++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
>> @@ -0,0 +1,139 @@
>> +/* Copyright 2022-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 <pthread.h>
>> +#include <unistd.h>
>> +#include <semaphore.h>
>> +#include <stdlib.h>
>> +
>> +#define NUM_THREADS 5
>> +
>> +/* Semaphores, used to track when threads have started, and to control
>> +   when the threads finish.  */
>> +sem_t startup_semaphore;
>> +sem_t finish_semaphore;
>> +
>> +/* Mutex to control when the first worker thread hit a breakpoint
>> +   location.  */
>> +pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
>> +
>> +/* Global variable to poke, just so threads have something to do.  */
>> +volatile int global_var = 0;
>> +
>> +int
>> +return_true ()
>> +{
>> +  return 1;
>> +}
>> +
>> +int
>> +return_false ()
>> +{
>> +  return 0;
>> +}
>> +
>> +void *
>> +worker_func (void *arg)
>> +{
>> +  int tid = *((int *) arg);
>> +
>> +  switch (tid)
>> +    {
>> +    case 0:
>> +      /* Wait for MUTEX to become available, then pass through the
>> +	 conditional breakpoint location.  */
>> +      if (pthread_mutex_lock (&mutex) != 0)
>> +	abort ();
>> +      global_var = 99;	/* Conditional breakpoint here.  */
>> +      if (pthread_mutex_unlock (&mutex) != 0)
>> +	abort ();
>> +      break;
>> +
>> +    default:
>> +      /* Notify the main thread that the thread has started, then wait for
>> +	 the main thread to tell us to finish.  */
>> +      sem_post (&startup_semaphore);
>> +      if (sem_wait (&finish_semaphore) != 0)
>> +	abort ();
>> +      break;
>> +    }
>> +}
>> +
>> +void
>> +stop_marker ()
>> +{
>> +  global_var = 99;	/* Stop marker.  */
>> +}
>> +
>> +int
>> +main ()
>> +{
>> +  pthread_t threads[NUM_THREADS];
>> +  int args[NUM_THREADS];
>> +  void *retval;
>> +
>> +  /* An alarm, just in case the thread deadlocks.  */
>> +  alarm (300);
>> +
>> +  /* Semaphore initialization.  */
>> +  if (sem_init (&startup_semaphore, 0, 0) != 0)
>> +    abort ();
>> +  if (sem_init (&finish_semaphore, 0, 0) != 0)
>> +    abort ();
>> +
>> +  /* Lock MUTEX, this prevents the first worker thread from rushing ahead.  */
>> +  if (pthread_mutex_lock (&mutex) != 0)
>> +    abort ();
>> +
>> +  /* Worker thread creation.  */
>> +  for (int i = 0; i < NUM_THREADS; i++)
>> +    {
>> +      args[i] = i;
>> +      pthread_create (&threads[i], NULL, worker_func, &args[i]);
>> +    }
>> +
>> +  /* Wait for every thread (other than the first) to tell us it has started
>> +     up.  */
>> +  for (int i = 1; i < NUM_THREADS; i++)
>> +    {
>> +      if (sem_wait (&startup_semaphore) != 0)
>> +	abort ();
>> +    }
>> +
>> +  /* Unlock the first thread so it can proceed.  */
>> +  if (pthread_mutex_unlock (&mutex) != 0)
>> +    abort ();
>> +
>> +  /* Wait for the first thread only.  */
>> +  pthread_join (threads[0], &retval);
>> +
>> +  /* Now post FINISH_SEMAPHORE to allow all the other threads to finish.  */
>> +  for (int i = 1; i < NUM_THREADS; i++)
>> +    sem_post (&finish_semaphore);
>> +
>> +  /* Now wait for the remaining threads to complete.  */
>> +  for (int i = 1; i < NUM_THREADS; i++)
>> +    pthread_join (threads[i], &retval);
>> +
>> +  /* Semaphore cleanup.  */
>> +  sem_destroy (&finish_semaphore);
>> +  sem_destroy (&startup_semaphore);
>> +
>> +  stop_marker ();
>> +
>> +  return 0;
>> +}
>> diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
>> b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
>> new file mode 100644
>> index 00000000000..787dee3aa8e
>> --- /dev/null
>> +++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
>> @@ -0,0 +1,117 @@
>> +# Copyright 2022-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 reprocuces bug gdb/28942, performing an inferior function
>> +# call from a breakpoint condition in a multi-threaded inferior.
>> +#
>> +# The important part of this test is that, when the conditional
>> +# breakpoint is hit, and the condition (which includes an inferior
>> +# function call) is evaluated, the other threads are running.
>> +
>> +standard_testfile
>> +
>> +if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
>> +	  {debug pthreads}] == -1 } {
>> +    return
>> +}
>> +
>> +set cond_bp_line [gdb_get_line_number "Conditional breakpoint here"]
>> +set final_bp_line [gdb_get_line_number "Stop marker"]
>> +
>> +# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
>> +proc start_gdb_and_runto_main { target_async target_non_stop } {
>> +    save_vars { ::GDBFLAGS } {
>> +	append ::GDBFLAGS \
>> +	    " -ex \"maint set target-non-stop $target_non_stop\""
>> +	append ::GDBFLAGS \
>> +	    " -ex \"maintenance set target-async ${target_async}\""
>> +
>> +	clean_restart ${::binfile}
>> +    }
>> +
>> +    if { ![runto_main] } {
>> +	return -1
>> +    }
>> +
>> +    return 0
>> +}
>> +
>> +# Run a test of GDB's conditional breakpoints, where the conditions include
>> +# inferior function calls.
>> +#
>> +# TARGET_ASYNC and TARGET_NON_STOP are used when starting up GDB.
>> +#
>> +# When STOP_AT_COND is true the breakpoint condtion will evaluate to
>> +# true, and GDB will stop at the breakpoint.  Otherwise, the
>> +# breakpoint condition will evaluate to false and GDB will not stop at
>> +# the breakpoint.
>> +proc run_condition_test { stop_at_cond \
>> +			      target_async target_non_stop } {
>> +    if { [start_gdb_and_runto_main $target_async \
>> +	      $target_non_stop] == -1 } {
>> +	return
>> +    }
>> +
>> +    # Setup the conditional breakpoint.
>> +    if { $stop_at_cond } {
>> +	set cond_func "return_true"
>> +    } else {
>> +	set cond_func "return_false"
>> +    }
>> +    gdb_breakpoint \
>> +	"${::srcfile}:${::cond_bp_line} if (${cond_func} ())"
>> +    set cond_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
>> +			"get number for conditional breakpoint"]
>> +
>> +    # And a breakpoint that we hit when the test is over, this one is
>> +    # not conditional.
>> +    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
>> +    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
>> +			  "get number for final breakpoint"]
>> +
>> +    if { $stop_at_cond } {
>> +	# Continue.  The first breakpoint we hit should be the conditional
>> +	# breakpoint.  The other thread will have hit its breakpoint, but
>> +	# that will have been deferred until the conditional breakpoint is
>> +	# reported.
>> +	gdb_test "continue" \
>> +	    [multi_line \
>> +		 "Continuing\\." \
>> +		 ".*" \
>> +		 "" \
>> +		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${cond_bp_num},
>> worker_func \[^\r\n\]+:${::cond_bp_line}" \
>> +		 "${::decimal}\\s+\[^\r\n\]+Conditional breakpoint here\[^\r\n\]+"] \
>> +	    "hit the conditional breakpoint"
>> +    }
>> +
>> +    # Run to the stop marker.
>> +    gdb_test "continue" \
>> +	[multi_line \
>> +	     "Continuing\\." \
>> +	     ".*" \
>> +	     "" \
>> +	     "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${final_bp_num},
>> stop_marker \[^\r\n\]+:${::final_bp_line}" \
>> +	     "${::decimal}\\s+\[^\r\n\]+Stop marker\[^\r\n\]+"] \
>> +	"hit the final breakpoint"
>> +}
>> +
>> +foreach_with_prefix target_async { "on" "off" } {
>> +    foreach_with_prefix target_non_stop { "on" "off" } {
>> +	foreach_with_prefix stop_at_cond { true false } {
>> +	    run_condition_test $stop_at_cond \
>> +		$target_async $target_non_stop
>> +	}
>> +    }
>> +}
>> --
>> 2.25.4
>
> 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] 202+ messages in thread

* RE: [PATCHv7 3/6] gdb: add timeouts for inferior function calls
  2023-05-16 15:42               ` Aktemur, Tankut Baris
@ 2023-06-05 13:54                 ` Andrew Burgess
  0 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-06-05 13:54 UTC (permalink / raw)
  To: Aktemur, Tankut Baris, gdb-patches

"Aktemur, Tankut Baris" <tankut.baris.aktemur@intel.com> writes:

> On Monday, May 15, 2023 9:22 PM, Andrew Burgess wrote:
>> Eli already approved the docs part:
>>   https://sourceware.org/pipermail/gdb-patches/2023-January/196462.html
>> 
>> ---
>> 
>> In the previous commits I have been working on improving inferior
>> function call support.  One thing that worries me about using inferior
>> function calls from a conditional breakpoint is: what happens if the
>> inferior function call fails?
>> 
>> If the failure is obvious, e.g. the thread performing the call
>> crashes, or hits a breakpoint, then this case is already well handled,
>> and the error is reported to the user.
>> 
>> But what if the thread performing the inferior call just deadlocks?
>> If the user made the call from a 'print' or 'call' command, then the
>> user might have some expectation of when the function call should
>> complete, and, when this time limit is exceeded, the user
>> will (hopefully) interrupt GDB and regain control of the debug
>> session.
>> 
>> But, when the inferior function call is from a breakpoint condition it
>> is much harder to understand that GDB is deadlocked within an inferior
>> call.  Maybe the breakpoint hasn't been hit yet?  Or maybe the
>> condition was always false?  Or maybe GDB is deadlocked in an inferior
>> call?  The only way to know for sure is to periodically interrupt GDB,
>
> Did you mean "interrupt the inferior"?

Yes, that makes more sense.  I think I was trying to say interrupt the
inferior via GDB, but I think mentioning GDB here is not helpful.

I've added your reviewed-by tag.

Thanks,
Andrew

>
>> check on all the threads, and then continue.
>> 
>> Additionally, the focus of the previous commit was inferior function
>> calls, from a conditional breakpoint, in a multi-threaded inferior.
>> This opens up a whole new set of potential failure conditions.  For
>> example, what if the function called relies on interaction with some
>> other thread, and the other thread crashes?  Or hits a breakpoint?
>> Given how inferior function calls work (in a synchronous manner), a
>> stop event in some other thread is going to be ignored while the
>> inferior function call is being executed as part of a breakpoint
>> condition, and this means that GDB could get stuck waiting for the
>> original condition thread, which will now never complete.
>> 
>> In this commit I propose a solution to this problem.  A timeout.  For
>> targets that support async-mode we can install an event-loop timer
>> before starting the inferior function call.  When the timer expires we
>> will stop the thread performing the inferior function call.  With this
>> mechanism in place a user can be sure that any inferior call they make
>> will either complete, or timeout eventually.
>> 
>> Adding a timer like this is obviously a change in behaviour for the
>> more common 'call' and 'print' uses of inferior function calls, so, in
>> this patch, I propose having two different timers.  One I call the
>> 'direct-call-timeout', which is used for 'call' and 'print' commands.
>> This timeout is by default set to unlimited, which, not surprisingly,
>> means there is no timeout in place.
>> 
>> A second timer, which I've called 'indirect-call-timeout', is used for
>> inferior function calls from breakpoint conditions.  This timeout has
>> a default value of 30 seconds.  This is a reasonably long time to
>> wait, and hopefully should be enough in most cases to allow the
>> inferior call to complete.  An inferior call that takes more than 30
>> seconds, which is installed on a breakpoint condition is really going
>> to slow down the debug session, so hopefully this is not a common use
>> case.
>> 
>> The user is, of course, free to reduce, or increase the timeout value,
>> and can always use Ctrl-c to interrupt an inferior function call, but
>> this timeout will ensure that GDB will stop at some point.
>> 
>> The new commands added by this commit are:
>> 
>>   set direct-call-timeout SECONDS
>>   show direct-call-timeout
>>   set indirect-call-timeout SECONDS
>>   show indirect-call-timeout
>> 
>> These new timeouts do depend on async-mode, so, if async-mode is
>> disabled (maint set target-async off), or not supported (e.g. target
>> sim), then the timeout is treated as unlimited (that is, no timeout is
>> set).
>> 
>> For targets that "fake" non-async mode, e.g. Linux native, where
>> non-async mode is really just async mode, but then we park the target
>> in a sissuspend, we could easily fix things so that the timeouts still
>> work, however, for targets that really are not async aware, like the
>> simulator, fixing things so that timeouts work correctly would be a
>> much bigger task - that effort would be better spent just making the
>> target async-aware.  And so, I'm happy for now that this feature will
>> only work on async targets.
>> 
>> The two new show commands will display slightly different text if the
>> current target is a non-async target, which should allow users to
>> understand what's going on.
>> 
>> There's a somewhat random test adjustment needed in gdb.base/help.exp,
>> the test uses a regexp with the apropos command, and expects to find a
>> single result.  Turns out the new settings I added also matched the
>> regexp, which broke the test.  I've updated the regexp a little to
>> exclude my new settings.
>> 
>> In infcall.c you'll notice the thread_info::stop_requested flag being
>> set when a timeout occurs.  This flag setting is not required as part
>> of this commit, but will be needed in a later commit.  However, it
>> seemed like setting this flag fitted better with this commit, which is
>> why the change is added here.
>> ---
>>  gdb/NEWS                                      |  18 ++
>>  gdb/doc/gdb.texinfo                           |  66 ++++++
>>  gdb/infcall.c                                 | 221 +++++++++++++++++-
>>  gdb/testsuite/gdb.base/help.exp               |   2 +-
>>  gdb/testsuite/gdb.base/infcall-timeout.c      |  36 +++
>>  gdb/testsuite/gdb.base/infcall-timeout.exp    |  82 +++++++
>>  .../infcall-from-bp-cond-timeout.c            | 169 ++++++++++++++
>>  .../infcall-from-bp-cond-timeout.exp          | 156 +++++++++++++
>>  8 files changed, 745 insertions(+), 5 deletions(-)
>>  create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.c
>>  create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.exp
>>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
>>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
>> 
>> diff --git a/gdb/NEWS b/gdb/NEWS
>> index 6aa0d5171f2..216c3a95d09 100644
>> --- a/gdb/NEWS
>> +++ b/gdb/NEWS
>> @@ -100,6 +100,24 @@ info main
>>     $2 = 1
>>     (gdb) break func if $_shell("some command") == 0
>> 
>> +set direct-call-timeout SECONDS
>> +show direct-call-timeout
>> +set indirect-call-timeout SECONDS
>> +show indirect-call-timeout
>> +  These new settings can be used to limit how long GDB will wait for
>> +  an inferior function call to complete.  The direct timeout is used
>> +  for inferior function calls from e.g. 'call' and 'print' commands,
>> +  while the indirect timeout is used for inferior function calls from
>> +  within a conditional breakpoint expression.
>> +
>> +  The default for the direct timeout is unlimited, while the default
>> +  for the indirect timeout is 30 seconds.
>> +
>> +  These timeouts will only have an effect for targets that are
>> +  operating in async mode.  For non-async targets the timeouts are
>> +  ignored, GDB will wait indefinitely for an inferior function to
>> +  complete, unless interrupted by the user using Ctrl-C.
>> +
>>  * MI changes
>> 
>>  ** mi now reports 'no-history' as a stop reason when hitting the end of the
>> diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
>> index 531147f6e6b..54668d812cb 100644
>> --- a/gdb/doc/gdb.texinfo
>> +++ b/gdb/doc/gdb.texinfo
>> @@ -20903,6 +20903,72 @@
>>  @code{step}, etc).  In this case, when the inferior finally returns to
>>  the dummy-frame, @value{GDBN} will once again halt the inferior.
>> 
>> +On targets that support asynchronous execution (@pxref{Background
>> +Execution}) @value{GDBN} can place a timeout on any functions called
>> +from @value{GDBN}.  If the timeout expires and the function call is
>> +still ongoing, then @value{GDBN} will interrupt the program.
>> +
>> +For targets that don't support asynchronous execution
>> +(@pxref{Background Execution}) then timeouts for functions called from
>> +@value{GDBN} are not supported, the timeout settings described below
>> +will be treated as @code{unlimited}, meaning @value{GDBN} will wait
>> +indefinitely for function call to complete, unless interrupted by the
>> +user using @kbd{Ctrl-C}.
>> +
>> +@table @code
>> +@item set direct-call-timeout @var{seconds}
>> +@kindex set direct-call-timeout
>> +@cindex timeout for called functions
>> +Set the timeout used when calling functions in the program to
>> +@var{seconds}, which should be an integer greater than zero, or the
>> +special value @code{unlimited}, which indicates no timeout should be
>> +used.  The default for this setting is @code{unlimited}.
>> +
>> +This setting is used when the user calls a function directly from the
>> +command prompt, for example with a @code{call} or @code{print}
>> +command.
>> +
>> +This setting only works for targets that support asynchronous
>> +execution (@pxref{Background Execution}), for any other target the
>> +setting is treated as @code{unlimited}.
>> +
>> +@item show direct-call-timeout
>> +@kindex show direct-call-timeout
>> +@cindex timeout for called functions
>> +Show the timeout used when calling functions in the program with a
>> +@code{call} or @code{print} command.
>> +@end table
>> +
>> +It is also possible to call functions within the program from the
>> +condition of a conditional breakpoint (@pxref{Conditions, ,Break
>> +Conditions}).  A different setting controls the timeout used for
>> +function calls made from a breakpoint condition.
>> +
>> +@table @code
>> +@item set indirect-call-timeout @var{seconds}
>> +@kindex set indirect-call-timeout
>> +@cindex timeout for called functions
>> +Set the timeout used when calling functions in the program from a
>> +breakpoint or watchpoint condition to @var{seconds}, which should be
>> +an integer greater than zero, or the special value @code{unlimited},
>> +which indicates no timeout should be used.  The default for this
>> +setting is @code{30} seconds.
>> +
>> +This setting only works for targets that support asynchronous
>> +execution (@pxref{Background Execution}), for any other target the
>> +setting is treated as @code{unlimited}.
>> +
>> +If a function called from a breakpoint or watchpoint condition times
>> +out, then @value{GDBN} will stop at the point where the timeout
>> +occurred.  The breakpoint condition evaluation will be abandoned.
>> +
>> +@item show indirect-call-timeout
>> +@kindex show indirect-call-timeout
>> +@cindex timeout for called functions
>> +Show the timeout used when calling functions in the program from a
>> +breakpoint or watchpoint condition.
>> +@end table
>> +
>>  @subsection Calling functions with no debug info
>> 
>>  @cindex no debug info functions
>> diff --git a/gdb/infcall.c b/gdb/infcall.c
>> index 49c88add394..dea7dc83062 100644
>> --- a/gdb/infcall.c
>> +++ b/gdb/infcall.c
>> @@ -96,6 +96,53 @@ show_may_call_functions_p (struct ui_file *file, int from_tty,
>>  	      value);
>>  }
>> 
>> +/* A timeout (in seconds) for direct inferior calls.  A direct inferior
>> +   call is one the user triggers from the prompt, e.g. with a 'call' or
>> +   'print' command.  Compare with the definition of indirect calls below.  */
>> +
>> +static unsigned int direct_call_timeout = UINT_MAX;
>> +
>> +/* Implement 'show direct-call-timeout'.  */
>> +
>> +static void
>> +show_direct_call_timeout (struct ui_file *file, int from_tty,
>> +			  struct cmd_list_element *c, const char *value)
>> +{
>> +  if (target_has_execution () && !target_can_async_p ())
>> +    gdb_printf (file, _("Current target does not support async mode, timeout "
>> +			"for direct inferior calls is \"unlimited\".\n"));
>> +  else if (direct_call_timeout == UINT_MAX)
>> +    gdb_printf (file, _("Timeout for direct inferior function calls "
>> +			"is \"unlimited\".\n"));
>> +  else
>> +    gdb_printf (file, _("Timeout for direct inferior function calls "
>> +			"is \"%s seconds\".\n"), value);
>> +}
>> +
>> +/* A timeout (in seconds) for indirect inferior calls.  An indirect inferior
>> +   call is one that originates from within GDB, for example, when
>> +   evaluating an expression for a conditional breakpoint.  Compare with
>> +   the definition of direct calls above.  */
>> +
>> +static unsigned int indirect_call_timeout = 30;
>> +
>> +/* Implement 'show indirect-call-timeout'.  */
>> +
>> +static void
>> +show_indirect_call_timeout (struct ui_file *file, int from_tty,
>> +			  struct cmd_list_element *c, const char *value)
>> +{
>> +  if (target_has_execution () && !target_can_async_p ())
>> +    gdb_printf (file, _("Current target does not support async mode, timeout "
>> +			"for indirect inferior calls is \"unlimited\".\n"));
>> +  else if (indirect_call_timeout == UINT_MAX)
>> +    gdb_printf (file, _("Timeout for indirect inferior function calls "
>> +			"is \"unlimited\".\n"));
>> +  else
>> +    gdb_printf (file, _("Timeout for indirect inferior function calls "
>> +			"is \"%s seconds\".\n"), value);
>> +}
>> +
>>  /* How you should pass arguments to a function depends on whether it
>>     was defined in K&R style or prototype style.  If you define a
>>     function using the K&R syntax that takes a `float' argument, then
>> @@ -590,6 +637,86 @@ call_thread_fsm::should_notify_stop ()
>>    return true;
>>  }
>> 
>> +/* A class to control creation of a timer that will interrupt a thread
>> +   during an inferior call.  */
>> +struct infcall_timer_controller
>> +{
>> +  /* Setup an event-loop timer that will interrupt PTID if the inferior
>> +     call takes too long.  DIRECT_CALL_P is true when this inferior call is
>> +     a result of the user using a 'print' or 'call' command, and false when
>> +     this inferior call is a result of e.g. a conditional breakpoint
>> +     expression, this is used to select which timeout to use.  */
>> +  infcall_timer_controller (thread_info *thr, bool direct_call_p)
>> +    : m_thread (thr)
>> +  {
>> +    unsigned int timeout
>> +      = direct_call_p ? direct_call_timeout : indirect_call_timeout;
>> +    if (timeout < UINT_MAX && target_can_async_p ())
>> +      {
>> +	int ms = timeout * 1000;
>> +	int id = create_timer (ms, infcall_timer_controller::timed_out, this);
>> +	m_timer_id.emplace (id);
>> +	infcall_debug_printf ("Setting up infcall timeout timer for "
>> +			      "ptid %s: %d milliseconds",
>> +			      m_thread->ptid.to_string ().c_str (), ms);
>> +      }
>> +  }
>> +
>> +  /* Destructor.  Ensure that the timer is removed from the event loop.  */
>> +  ~infcall_timer_controller ()
>> +  {
>> +    /* If the timer has already triggered, then it will have already been
>> +       deleted from the event loop.  If the timer has not triggered, then
>> +       delete it now.  */
>> +    if (m_timer_id.has_value () && !m_triggered)
>> +      delete_timer (*m_timer_id);
>> +
>> +    /* Just for clarity, discard the timer id now.  */
>> +    m_timer_id.reset ();
>> +  }
>> +
>> +  /* Return true if there was a timer in place, and the timer triggered,
>> +     otherwise, return false.  */
>> +  bool triggered_p ()
>> +  {
>> +    gdb_assert (!m_triggered || m_timer_id.has_value ());
>> +    return m_triggered;
>> +  }
>> +
>> +private:
>> +  /* The thread we should interrupt.  */
>> +  thread_info *m_thread;
>> +
>> +  /* Set true when the timer is triggered.  */
>> +  bool m_triggered = false;
>> +
>> +  /* Given a value when a timer is in place.  */
>> +  gdb::optional<int> m_timer_id;
>> +
>> +  /* Callback for the timer, forwards to ::trigger below.  */
>> +  static void
>> +  timed_out (gdb_client_data context)
>> +  {
>> +    infcall_timer_controller *ctrl
>> +      = static_cast<infcall_timer_controller *> (context);
>> +    ctrl->trigger ();
>> +  }
>> +
>> +  /* Called when the timer goes off.  Stop thread m_thread.  */
>> +  void
>> +  trigger ()
>> +  {
>> +    m_triggered = true;
>> +
>> +    scoped_disable_commit_resumed disable_commit_resumed ("infcall timeout");
>> +
>> +    infcall_debug_printf ("Stopping thread %s",
>> +			  m_thread->ptid.to_string ().c_str ());
>> +    target_stop (m_thread->ptid);
>> +    m_thread->stop_requested = true;
>> +  }
>> +};
>> +
>>  /* Subroutine of call_function_by_hand to simplify it.
>>     Start up the inferior and wait for it to stop.
>>     Return the exception if there's an error, or an exception with
>> @@ -600,13 +727,15 @@ call_thread_fsm::should_notify_stop ()
>> 
>>  static struct gdb_exception
>>  run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
>> -		   struct thread_info *call_thread, CORE_ADDR real_pc)
>> +		   struct thread_info *call_thread, CORE_ADDR real_pc,
>> +		   bool *timed_out_p)
>>  {
>>    INFCALL_SCOPED_DEBUG_ENTER_EXIT;
>> 
>>    struct gdb_exception caught_error;
>>    ptid_t call_thread_ptid = call_thread->ptid;
>>    int was_running = call_thread->state == THREAD_RUNNING;
>> +  *timed_out_p = false;
>> 
>>    infcall_debug_printf ("call function at %s in thread %s, was_running = %d",
>>  			core_addr_to_string (real_pc),
>> @@ -618,6 +747,16 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
>>    scoped_restore restore_in_infcall
>>      = make_scoped_restore (&call_thread->control.in_infcall, 1);
>> 
>> +  /* If the thread making the inferior call stops with a time out then the
>
> "time out" -> "timeout"
>
>> +     stop_requested flag will be set.  However, we don't want changes to
>> +     this flag to leak back to our caller, we might be here to handle an
>> +     inferior call from a breakpoint condition, so leaving this flag set
>> +     would appear that the breakpoint stop was actually a requested stop,
>> +     which is not true, and will cause GDB to print extra messages to the
>> +     output.  */
>> +  scoped_restore restore_stop_requested
>> +    = make_scoped_restore (&call_thread->stop_requested, false);
>> +
>>    clear_proceed_status (0);
>> 
>>    /* Associate the FSM with the thread after clear_proceed_status
>> @@ -651,11 +790,23 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
>>        infrun_debug_show_threads ("non-exited threads after proceed for inferior-call",
>>  				 all_non_exited_threads ());
>> 
>> +      /* Setup a timer (if possible, and if the settings allow) to prevent
>> +	 the inferior call running forever.  */
>> +      bool direct_call_p = !call_thread->control.in_cond_eval;
>> +      infcall_timer_controller infcall_timer (call_thread, direct_call_p);
>> +
>>        /* Inferior function calls are always synchronous, even if the
>>  	 target supports asynchronous execution.  */
>>        wait_sync_command_done ();
>> 
>> -      infcall_debug_printf ("inferior call completed successfully");
>> +      /* If the timer triggered then the inferior call failed.  */
>> +      if (infcall_timer.triggered_p ())
>> +	{
>> +	  infcall_debug_printf ("inferior call timed out");
>> +	  *timed_out_p = true;
>> +	}
>> +      else
>> +	infcall_debug_printf ("inferior call completed successfully");
>>      }
>>    catch (gdb_exception &e)
>>      {
>> @@ -1309,6 +1460,10 @@ call_function_by_hand_dummy (struct value *function,
>>    scoped_restore restore_stopped_by_random_signal
>>      = make_scoped_restore (&stopped_by_random_signal, 0);
>> 
>> +  /* Set to true by the call to run_inferior_call below if the inferior
>> +     call is artificially interrupted by GDB due to taking too long.  */
>> +  bool timed_out_p = false;
>> +
>>    /* - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP -
>>       If you're looking to implement asynchronous dummy-frames, then
>>       just below is the place to chop this function in two..  */
>> @@ -1335,7 +1490,8 @@ call_function_by_hand_dummy (struct value *function,
>>  			      struct_addr);
>>      {
>>        std::unique_ptr<call_thread_fsm> sm_up (sm);
>> -      e = run_inferior_call (std::move (sm_up), call_thread.get (), real_pc);
>> +      e = run_inferior_call (std::move (sm_up), call_thread.get (), real_pc,
>> +			     &timed_out_p);
>>      }
>> 
>>      if (e.reason < 0)
>> @@ -1487,7 +1643,10 @@ When the function is done executing, GDB will silently stop."),
>>        std::string name = get_function_name (funaddr, name_buf,
>>  					    sizeof (name_buf));
>> 
>> -      if (stopped_by_random_signal)
>> +      /* If the inferior call timed out then it will have been interrupted
>> +	 by a signal, but we want to report this differently to the user,
>> +	 which is done later in this function.  */
>> +      if (stopped_by_random_signal && !timed_out_p)
>>  	{
>>  	  /* We stopped inside the FUNCTION because of a random
>>  	     signal.  Further execution of the FUNCTION is not
>> @@ -1531,6 +1690,36 @@ GDB remains in the frame where the signal was received.\n\
>>  To change this behavior use \"set unwindonsignal on\".\n\
>>  Evaluation of the expression containing the function\n\
>>  (%s) will be abandoned.\n\
>> +When the function is done executing, GDB will silently stop."),
>> +		     name.c_str ());
>> +	    }
>> +	}
>> +
>> +      if (timed_out_p)
>> +	{
>> +	  /* A timeout results in a signal being sent to the inferior.  */
>> +	  gdb_assert (stopped_by_random_signal);
>> +
>> +	  /* Indentation is weird here.  A later patch is going to move the
>> +	    following block into an if/else, so I'm leaving the indentation
>> +	    here to minimise the later patch.
>> +
>> +	    Also, the error message used below refers to 'set
>> +	    unwind-on-timeout' which doesn't exist yet.  This will be added
>> +	    in a later commit, I'm leaving this in for now to minimise the
>> +	    churn caused by the commit that adds unwind-on-timeout.  */
>> +	    {
>> +	      /* The user wants to stay in the frame where we stopped
>> +		 (default).  Discard inferior status, we're not at the same
>> +		 point we started at.  */
>> +	      discard_infcall_control_state (inf_status.release ());
>> +
>> +	      error (_("\
>> +The program being debugged timed out while in a function called from GDB.\n\
>> +GDB remains in the frame where the timeout occurred.\n\
>> +To change this behavior use \"set unwind-on-timeout on\".\n\
>> +Evaluation of the expression containing the function\n\
>> +(%s) will be abandoned.\n\
>>  When the function is done executing, GDB will silently stop."),
>>  		     name.c_str ());
>>  	    }
>> @@ -1644,6 +1833,30 @@ The default is to unwind the frame."),
>>  			   show_unwind_on_terminating_exception_p,
>>  			   &setlist, &showlist);
>> 
>> +  add_setshow_uinteger_cmd ("direct-call-timeout", no_class,
>> +			    &direct_call_timeout, _("\
>> +Set the timeout, for direct calls to inferior function calls."), _("\
>> +Show the timeout, for direct calls to inferior function calls."), _("\
>> +If running on a target that supports, and is running in, async mode\n\
>> +then this timeout is used for any inferior function calls triggered\n\
>> +directly from the prompt, i.e. from a 'call' or 'print' command.  The\n\
>> +timeout is specified in seconds."),
>> +			    nullptr,
>> +			    show_direct_call_timeout,
>> +			    &setlist, &showlist);
>> +
>> +  add_setshow_uinteger_cmd ("indirect-call-timeout", no_class,
>> +			    &indirect_call_timeout, _("\
>> +Set the timeout, for indirect calls to inferior function calls."), _("\
>> +Show the timeout, for indirect calls to inferior function calls."), _("\
>> +If running on a target that supports, and is running in, async mode\n\
>> +then this timeout is used for any inferior function calls triggered\n\
>> +indirectly, i.e. being made as part of a breakpoint, or watchpoint,\n\
>> +condition expression.  The timeout is specified in seconds."),
>> +			    nullptr,
>> +			    show_indirect_call_timeout,
>> +			    &setlist, &showlist);
>> +
>>    add_setshow_boolean_cmd
>>      ("infcall", class_maintenance, &debug_infcall,
>>       _("Set inferior call debugging."),
>> diff --git a/gdb/testsuite/gdb.base/help.exp b/gdb/testsuite/gdb.base/help.exp
>> index 87919a819ab..504bf90cc15 100644
>> --- a/gdb/testsuite/gdb.base/help.exp
>> +++ b/gdb/testsuite/gdb.base/help.exp
>> @@ -121,7 +121,7 @@ gdb_test "help info bogus-gdb-command" "Undefined info command: \"bogus-
>> gdb-comm
>>  gdb_test "help gotcha" "Undefined command: \"gotcha\"\.  Try \"help\"\."
>> 
>>  # Test apropos regex.
>> -gdb_test "apropos \\\(print\[\^\[ bsiedf\\\".-\]\\\)" "handle -- Specify how to handle
>> signals\."
>> +gdb_test "apropos \\\(print\[\^\[ bsiedf\\\"'.-\]\\\)" "handle -- Specify how to handle
>> signals\."
>>  # Test apropos >1 word string.
>>  gdb_test "apropos handle signal" "handle -- Specify how to handle signals\."
>>  # Test apropos apropos.
>> diff --git a/gdb/testsuite/gdb.base/infcall-timeout.c b/gdb/testsuite/gdb.base/infcall-
>> timeout.c
>> new file mode 100644
>> index 00000000000..12774ca2599
>> --- /dev/null
>> +++ b/gdb/testsuite/gdb.base/infcall-timeout.c
>> @@ -0,0 +1,36 @@
>> +/* Copyright 2022-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 <unistd.h>
>> +
>> +/* This function is called from GDB.  */
>> +int
>> +function_that_never_returns ()
>> +{
>> +  while (1)
>> +    sleep (1);
>> +
>> +  return 0;
>> +}
>> +
>> +int
>> +main ()
>> +{
>> +  alarm (300);
>> +
>> +  return 0;
>> +}
>> diff --git a/gdb/testsuite/gdb.base/infcall-timeout.exp b/gdb/testsuite/gdb.base/infcall-
>> timeout.exp
>> new file mode 100644
>> index 00000000000..5e9cdc2fa0e
>> --- /dev/null
>> +++ b/gdb/testsuite/gdb.base/infcall-timeout.exp
>> @@ -0,0 +1,82 @@
>> +# Copyright 2022-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/>.
>> +
>> +# Test GDB's direct-call-timeout setting, that is, ensure that if an
>> +# inferior function call, invoked from e.g. a 'print' command, takes
>> +# too long, then GDB can interrupt it, and return control to the user.
>> +
>> +standard_testfile
>> +
>> +if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
>> +	  {debug}] == -1 } {
>> +    return
>> +}
>> +
>> +# Start GDB according to TARGET_ASYNC and TARGET_NON_STOP, then adjust
>> +# the direct-call-timeout, and make an inferior function call that
>> +# will never return.  GDB should eventually timeout and stop the
>> +# inferior.
>> +proc_with_prefix run_test { target_async target_non_stop } {
>> +    save_vars { ::GDBFLAGS } {
>> +	append ::GDBFLAGS \
>> +	    " -ex \"maint set target-non-stop $target_non_stop\""
>> +	append ::GDBFLAGS \
>> +	    " -ex \"maintenance set target-async ${target_async}\""
>> +
>> +	clean_restart ${::binfile}
>> +    }
>> +
>> +    if {![runto_main]} {
>> +	fail "run to main"
>
> runto_main already emits a fail, so no need for this.
>
>> +	return
>> +    }
>> +
>> +    gdb_test_no_output "set direct-call-timeout 5"
>> +
>> +    # When non-stop mode is off we get slightly different output from GDB.
>> +    if { [gdb_is_remote_or_extended_remote_target] && !$target_non_stop } {
>> +	set stopped_line_pattern "Program received signal SIGINT, Interrupt\\."
>> +    } else {
>> +	set stopped_line_pattern "Program stopped\\."
>> +    }
>> +
>> +    gdb_test "print function_that_never_returns ()" \
>> +	[multi_line \
>> +	     $stopped_line_pattern \
>> +	     ".*" \
>> +	     "The program being debugged timed out while in a function called from GDB\\." \
>> +	     "GDB remains in the frame where the timeout occurred\\." \
>> +	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
>> +	     "Evaluation of the expression containing the function" \
>> +	     "\\(function_that_never_returns\\) will be abandoned\\." \
>> +	     "When the function is done executing, GDB will silently stop\\."]
>> +
>> +    gdb_test "bt" ".* function_that_never_returns .*<function called from gdb>.*"
>> +}
>> +
>> +foreach_with_prefix target_async { "on" "off" } {
>> +
>> +    if { !$target_async } {
>> +	# GDB can't timeout while waiting for a thread if the target
>> +	# runs with async-mode turned off; once the target is running
>> +	# GDB is effectively blocked until the target stops for some
>> +	# reason.
>> +	continue
>> +    }
>> +
>> +    foreach_with_prefix target_non_stop { "on" "off" } {
>> +	run_test $target_async $target_non_stop
>> +    }
>> +}
>> diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
>> b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
>> new file mode 100644
>> index 00000000000..4da4245746e
>> --- /dev/null
>> +++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
>> @@ -0,0 +1,169 @@
>> +/* This testcase is part of GDB, the GNU debugger.
>> +
>> +   Copyright 2022-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 <stdio.h>
>> +#include <pthread.h>
>> +#include <unistd.h>
>> +#include <stdlib.h>
>> +#include <errno.h>
>> +#include <semaphore.h>
>> +
>> +#define NUM_THREADS 5
>> +
>> +/* Semaphores, used to track when threads have started, and to control
>> +   when the threads finish.  */
>> +sem_t startup_semaphore;
>> +sem_t finish_semaphore;
>> +sem_t thread_1_semaphore;
>> +sem_t thread_2_semaphore;
>> +
>> +/* Mutex to control when the first worker thread hit a breakpoint
>> +   location.  */
>> +pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
>> +
>> +/* Global variable to poke, just so threads have something to do.  */
>> +volatile int global_var = 0;
>> +
>> +int
>> +condition_func ()
>> +{
>> +  /* Let thread 2 run.  */
>> +  if (sem_post (&thread_2_semaphore) != 0)
>> +    abort ();
>> +
>> +  /* Wait for thread 2 to complete its actions.  */
>> +  if (sem_wait (&thread_1_semaphore) != 0)
>> +    abort ();
>> +
>> +  return 1;
>> +}
>> +
>> +void
>> +do_segfault ()
>> +{
>> +  volatile int *p = 0;
>> +  *p = 0;	/* Segfault here.  */
>> +}
>> +
>> +void *
>> +worker_func (void *arg)
>> +{
>> +  int tid = *((int *) arg);
>> +
>> +  /* Let the main thread know that this worker has started.  */
>> +  if (sem_post (&startup_semaphore) != 0)
>> +    abort ();
>> +
>> +  switch (tid)
>> +    {
>> +    case 0:
>> +      /* Wait for MUTEX to become available, then pass through the
>> +	 conditional breakpoint location.  */
>> +      if (pthread_mutex_lock (&mutex) != 0)
>> +	abort ();
>> +      global_var = 99;	/* Conditional breakpoint here.  */
>> +      if (pthread_mutex_unlock (&mutex) != 0)
>> +	abort ();
>> +      break;
>> +
>> +    case 1:
>> +      if (sem_wait (&thread_2_semaphore) != 0)
>> +	abort ();
>> +      do_segfault ();
>> +      if (sem_post (&thread_1_semaphore) != 0)
>> +	abort ();
>> +
>> +      /* Fall through.  */
>> +    default:
>> +      /* Wait until we are allowed to finish.  */
>> +      if (sem_wait (&finish_semaphore) != 0)
>> +	abort ();
>> +      break;
>> +    }
>> +}
>> +
>> +void
>> +stop_marker ()
>> +{
>> +  global_var = 99;	/* Stop marker.  */
>> +}
>> +
>> +/* The main program entry point.  */
>> +
>> +int
>> +main ()
>> +{
>> +  pthread_t threads[NUM_THREADS];
>> +  int args[NUM_THREADS];
>> +  void *retval;
>> +
>> +  /* An alarm, just in case the thread deadlocks.  */
>> +  alarm (300);
>> +
>> +  /* Semaphore initialization.  */
>> +  if (sem_init (&startup_semaphore, 0, 0) != 0)
>> +    abort ();
>> +  if (sem_init (&finish_semaphore, 0, 0) != 0)
>> +    abort ();
>> +  if (sem_init (&thread_1_semaphore, 0, 0) != 0)
>> +    abort ();
>> +  if (sem_init (&thread_2_semaphore, 0, 0) != 0)
>> +    abort ();
>> +
>> +  /* Lock MUTEX, this prevents the first worker thread from rushing ahead.  */
>> +  if (pthread_mutex_lock (&mutex) != 0)
>> +    abort ();
>> +
>> +  /* Worker thread creation.  */
>> +  for (int i = 0; i < NUM_THREADS; i++)
>> +    {
>> +      args[i] = i;
>> +      pthread_create (&threads[i], NULL, worker_func, &args[i]);
>> +    }
>> +
>> +  /* Wait for every thread to start.  */
>> +  for (int i = 0; i < NUM_THREADS; i++)
>> +    {
>> +      if (sem_wait (&startup_semaphore) != 0)
>> +	abort ();
>> +    }
>> +
>> +  /* Unlock the first thread so it can proceed.  */
>> +  if (pthread_mutex_unlock (&mutex) != 0)
>> +    abort ();
>> +
>> +  /* Wait for the first thread only.  */
>> +  pthread_join (threads[0], &retval);
>> +
>> +  /* Now post FINISH_SEMAPHORE to allow all the other threads to finish.  */
>> +  for (int i = 1; i < NUM_THREADS; i++)
>> +    sem_post (&finish_semaphore);
>> +
>> +  /* Now wait for the remaining threads to complete.  */
>> +  for (int i = 1; i < NUM_THREADS; i++)
>> +    pthread_join (threads[i], &retval);
>> +
>> +  /* Semaphore cleanup.  */
>> +  sem_destroy (&finish_semaphore);
>> +  sem_destroy (&startup_semaphore);
>> +  sem_destroy (&thread_1_semaphore);
>> +  sem_destroy (&thread_2_semaphore);
>> +
>> +  stop_marker ();
>> +
>> +  return 0;
>> +}
>> diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
>> b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
>> new file mode 100644
>> index 00000000000..4159288a39c
>> --- /dev/null
>> +++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
>> @@ -0,0 +1,156 @@
>> +# Copyright 2022-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 inferior calls executed from a breakpoint condition in
>> +# a multi-threaded program.
>> +#
>> +# This test has the inferior function call timeout, and checks how GDB
>> +# handles this situation.
>> +
>> +standard_testfile
>> +
>> +if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
>> +	  {debug pthreads}] } {
>> +    return
>> +}
>> +
>> +set cond_bp_line [gdb_get_line_number "Conditional breakpoint here"]
>> +set final_bp_line [gdb_get_line_number "Stop marker"]
>> +set segfault_line [gdb_get_line_number "Segfault here"]
>> +
>> +# Setup GDB based on TARGET_ASYNC and TARGET_NON_STOP.  Setup some
>> +# breakpoints in the inferior, one of which has an inferior call
>> +# within its condition.
>> +#
>> +# Continue GDB, the breakpoint with inferior call will be hit, but the
>> +# inferior call will never return.  We expect GDB to timeout.
>> +#
>> +# The reason that the inferior call never completes is that a second
>> +# thread, on which the inferior call relies, either hits a breakpoint
>> +# (when OTHER_THREAD_BP is true), or crashes (when OTHER_THREAD_BP is
>> +# false).
>> +proc run_test { target_async target_non_stop other_thread_bp } {
>> +    save_vars { ::GDBFLAGS } {
>> +	append ::GDBFLAGS " -ex \"maint set target-non-stop $target_non_stop\""
>> +	append ::GDBFLAGS " -ex \"maintenance set target-async ${target_async}\""
>> +
>> +	clean_restart ${::binfile}
>> +    }
>> +
>> +    if {![runto_main]} {
>> +	fail "run to main"
>
> runto_main already emits a fail, so no need for this.
>
>> +	return
>> +    }
>> +
>> +    # The default timeout for indirect inferior calls (e.g. inferior
>> +    # calls for conditional breakpoint expressions) is pretty high.
>> +    # We don't want the test to take too long, so reduce this.
>> +    #
>> +    # However, the test relies on a second thread hitting some event
>> +    # (either a breakpoint or signal) before this timeout expires.
>> +    #
>> +    # There is a chance that on a really slow system this might not
>> +    # happen, in which case the test might fail.
>> +    #
>> +    # However, we still allocate 5 seconds, which feels like it should
>> +    # be enough time in most cases, but maybe we need to do something
>> +    # smarter here?  Possibly we could have some initial run where the
>> +    # inferior doesn't timeout, but does perform the same interaction
>> +    # between threads, we could time that, and use that as the basis
>> +    # for this timeout.  For now though, we just hope 5 seconds is
>> +    # enough.
>> +    gdb_test_no_output "set indirect-call-timeout 5"
>> +
>> +    gdb_breakpoint \
>> +	"${::srcfile}:${::cond_bp_line} if (condition_func ())"
>> +    set bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
>> +		    "get number for conditional breakpoint"]
>> +
>> +    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
>> +    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
>> +			  "get number for final breakpoint"]
>> +
>> +    # The thread performing an inferior call relies on a second
>> +    # thread.  The second thread will segfault unless it hits a
>> +    # breakpoint first.  In either case the initial thread will not
>> +    # complete its inferior call.
>> +    if { $other_thread_bp } {
>> +	gdb_breakpoint "${::srcfile}:${::segfault_line}"
>> +	set segfault_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
>> +				 "get number for segfault breakpoint"]
>> +    }
>> +
>> +    # When non-stop mode is off we get slightly different output from GDB.
>> +    if { [gdb_is_remote_or_extended_remote_target] && !$target_non_stop} {
>> +	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" received signal
>> SIGINT, Interrupt\\."
>> +    } else {
>> +	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\."
>> +    }
>> +
>> +    gdb_test "continue" \
>> +	[multi_line \
>> +	     $stopped_line_pattern \
>> +	     ".*" \
>> +	     "Error in testing condition for breakpoint ${bp_num}:" \
>> +	     "The program being debugged timed out while in a function called from GDB\\." \
>> +	     "GDB remains in the frame where the timeout occurred\\." \
>> +	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
>> +	     "Evaluation of the expression containing the function" \
>> +	     "\\(condition_func\\) will be abandoned\\." \
>> +	     "When the function is done executing, GDB will silently stop\\."] \
>> +	"expected timeout waiting for inferior call to complete"
>> +
>> +    # Remember that other thread that either crashed (with a segfault)
>> +    # or hit a breakpoint?  Now that the inferior call has timed out,
>> +    # if we try to resume then we should see the pending event from
>> +    # that other thread.
>> +    if { $other_thread_bp } {
>> +	gdb_test "continue" \
>> +	    [multi_line \
>> +		 "Continuing\\." \
>> +		 ".*" \
>> +		 "" \
>> +		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${segfault_bp_num},
>> do_segfault \[^\r\n\]+:${::segfault_line}" \
>> +		 "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"] \
>> +	    "hit the segfault breakpoint"
>> +    } else {
>> +	gdb_test "continue" \
>> +	    [multi_line \
>> +		 "Continuing\\." \
>> +		 ".*" \
>> +		 "Thread ${::decimal} \"infcall-from-bp\" received signal SIGSEGV,
>> Segmentation fault\\." \
>> +		 "\\\[Switching to Thread \[^\r\n\]+\\\]" \
>> +		 "${::hex} in do_segfault \\(\\) at \[^\r\n\]+:${::segfault_line}" \
>> +		 "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"] \
>> +	    "hit the segfault"
>> +    }
>> +}
>> +
>> +foreach_with_prefix target_async {"on" "off" } {
>> +
>> +    if { !$target_async } {
>> +	# GDB can't timeout while waiting for a thread if the target
>> +	# runs with async-mode turned off; once the target is running
>> +	# GDB is effectively blocked until the target stops for some
>> +	# reason.
>> +	continue
>> +    }
>> +
>> +    foreach_with_prefix target_non_stop {"off" "on"} {
>> +	foreach_with_prefix other_thread_bp { true false } {
>> +	    run_test $target_async $target_non_stop $other_thread_bp
>> +	}
>> +    }
>> +}
>> --
>> 2.25.4
>
> Reviewed-By: Tankut Baris Aktemur <tankut.baris.aktemur@intel.com>
>
> 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] 202+ messages in thread

* RE: [PATCHv7 4/6] gdb/remote: avoid SIGINT after calling remote_target::stop
  2023-05-16 16:00               ` Aktemur, Tankut Baris
@ 2023-06-05 13:55                 ` Andrew Burgess
  0 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-06-05 13:55 UTC (permalink / raw)
  To: Aktemur, Tankut Baris, gdb-patches

"Aktemur, Tankut Baris" <tankut.baris.aktemur@intel.com> writes:

> On Monday, May 15, 2023 9:22 PM, Andrew Burgess wrote:
>> Currently, if the remote target is not running in non-stop mode, then,
>> when GDB calls remote_target::stop, we end up sending an interrupt
>> packet \x03 to the remote target.
>> 
>> If the user interrupts the inferior from the GDB prompt (e.g. by
>> typing Ctrl-c), then GDB calls remote_target::interrupt, which also
>> ends up sending the interrupt packet.
>> 
>> The problem here is that both of these mechanisms end up sending the
>> interrupt packet, which means, when the target stops with a SIGINT,
>> and this is reported back to GDB, we have no choice but to report this
>> to the user as a SIGINT stop event.
>> 
>> Now maybe this is the correct thing to do, after all the target has
>> been stopped with SIGINT.  However, this leads to an unfortunate
>> change in behaviour when comparing non-stop vs all-stop mode.
>> 
>> When running in non-stop mode, and remote_target::stop is called, the
>> target will be stopped with a vCont packet, and this stop is then
>> reported back to GDB as GDB_SIGNAL_0, this will cause GDB to print a
>> message like:
>> 
>>   Program stopped.
>> 
>> Or:
>> 
>>   Thread NN "binary name" stopped.
>> 
>> In contrast, when non-stop mode is off, we get messages like:
>> 
>>   Program received SIGINT, Segmentation fault.
>> 
>> Or:
>> 
>>   Thread NN "binary name" received SIGINT, Segmentation fault.
>> 
>> In this commit I propose making use of thread_info::stop_requested
>> within remote.c to know if the stop was triggered by GDB (and the
>> SIGINT should be hidden) or if the stop was a user interrupt, and the
>> SIGINT should be printed.
>> 
>> In remote_target::process_stop_reply if the inferior stopped with
>> SIGINT and the thread_info::stop_requested flag is set, then we change
>> the stop signal to GDB_SIGNAL_0.
>> 
>> Two of the tests added in the previous commit exposed this issue.  In
>> the previous commit the tests looked for either of the above
>> patterns.  In this commit I've updated these tests to only look for
>> the "stopped" based messages.
>> 
>> This commit is the reason why the previous commit took care to set the
>> thread_info::stop_requested flag in infcall.c.
>> ---
>>  gdb/remote.c                                           | 10 ++++++++++
>>  gdb/testsuite/gdb.base/infcall-timeout.exp             |  9 +--------
>>  .../gdb.threads/infcall-from-bp-cond-timeout.exp       |  9 +--------
>>  3 files changed, 12 insertions(+), 16 deletions(-)
>> 
>> diff --git a/gdb/remote.c b/gdb/remote.c
>> index 8eaa1b2c4d1..c61eeeadc52 100644
>> --- a/gdb/remote.c
>> +++ b/gdb/remote.c
>> @@ -8275,6 +8275,16 @@ remote_target::process_stop_reply (struct stop_reply *stop_reply,
>>  	}
>>        else
>>  	{
>> +	  /* If this stop was actually requested by GDB then we can hide
>> +	     the SIGINT from the user.  */
>> +	  if (status->kind () == TARGET_WAITKIND_STOPPED
>> +	      && status->sig () == GDB_SIGNAL_INT)
>> +	    {
>> +	      thread_info *thr = this->find_thread (ptid);
>
> A few lines above, there is
>
>       remote_notice_new_inferior (ptid, false);
>       remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
>
> which first does 'target->find_thread (ptid)' to find the thread_info*.
> It is unfortunate that we cannot access the thread_info* directly from
> remote_thread_info*.  It's not in this patch's scope to add such a backlink.
> How about changing 
>
>       remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
>
> to
>
>       thread_info *thr = this->find_thread (ptid);
>       remote_thread_info *remote_thr = get_remote_thread_info (thr);
>
> so that we can reuse 'thr' without having to call 'find_thread'
> a second time?

Great idea.  I've reworked things as you suggest.  This now means one of
the get_remote_thread_info overloads can be deleted too, which I've done.

>
> Besides this suggestion, the patch looks fine to me.  FWIW
> Reviewed-By: Tankut Baris Aktemur <tankut.baris.aktemur@intel.com>

I added your reviewed-by tag.

Thanks,
Andrew

>
> 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] 202+ messages in thread

* [PATCHv8 0/6] Infcalls from B/P conditions in multi-threaded inferiors
  2023-05-15 19:22           ` [PATCHv7 0/6] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                               ` (5 preceding siblings ...)
  2023-05-15 19:22             ` [PATCHv7 6/6] gdb: rename unwindonsignal to unwind-on-signal Andrew Burgess
@ 2023-06-07 10:01             ` Andrew Burgess
  2023-06-07 10:01               ` [PATCHv8 1/6] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
                                 ` (7 more replies)
  6 siblings, 8 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-06-07 10:01 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

In v8:

  - Rebased onto current upstream/master and retested.

  - Addressed feedback from Baris on patches 1, 2, 3, & 4.  This was
    mostly minor stuff, comment typos and some improvements to the
    testsuite.  There was one real (but minor) GDB change in patch 4.

In v7:

  - Rebased onto current upstream/master, fixed use of
    find_thread_ptid which is now a process_stratum_target method,

  - Retested, with no regressions seen.

In v6:

  - Pushed the 5 initial patches.  These were the smaller fixes, and,
    I felt were pretty obvious fixes.  I'm sure folk will raise
    objections if they disagree.

  - Of the remaining patches, #1 to #5 really needs review before they
    can be merged.  Patch #6 is an obvious cleanup once the first five
    have been merged.

  - I've rebased onto current HEAD of master, there's no significant
    changes.

  - All other documentation changes have been reviewed and approved.

In v5:

  - Rebased to current HEAD of master, minor merge conflict resolved.
    No other code or documentation changes.

  - First patch, which was pure documentation, has now been merged.

  - All other documentation changes have been reviewed and approved.

In v4:

  - I believe all the docs changes have been reviewed and approved by Eli,

  - Rebased onto current master,

  - Dropped patch #2 from the V3 series,

  - I have addressed all the issues Baris pointed out, including the
    fixes for the patch #9 ('gdb: add timeouts for inferior function
    calls'), which I forgot to do in V3.

In v3:

  - Updates for review feedback, biggest changes in #10 and #11, but
    minor changes to most patches.

In V2:

  - Rebased onto something closer to HEAD of master,

  - Patches #1, #2, #12, and #13 are new in this series,

  - Patches #3 to #9, and #11 are unchanged since their V1 iteration,

  - Patches #10 has changed slightly in implementation since v1, and
    the docs have been significantly updated.

---

Andrew Burgess (6):
  Revert "gdb: remove unnecessary parameter wait_ptid from
    do_target_wait"
  gdb: fix b/p conditions with infcalls in multi-threaded inferiors
  gdb: add timeouts for inferior function calls
  gdb/remote: avoid SIGINT after calling remote_target::stop
  gdb: introduce unwind-on-timeout setting
  gdb: rename unwindonsignal to unwind-on-signal

 gdb/NEWS                                      |  38 +++
 gdb/breakpoint.c                              |   2 +
 gdb/doc/gdb.texinfo                           | 105 ++++++-
 gdb/gdbthread.h                               |   3 +
 gdb/infcall.c                                 | 296 +++++++++++++++++-
 gdb/infrun.c                                  |  70 ++++-
 gdb/infrun.h                                  |   3 +-
 gdb/remote.c                                  |  23 +-
 gdb/testsuite/gdb.base/callfuncs.exp          |   4 +-
 gdb/testsuite/gdb.base/help.exp               |   2 +-
 gdb/testsuite/gdb.base/infcall-failure.exp    |   4 +-
 gdb/testsuite/gdb.base/infcall-timeout.c      |  36 +++
 gdb/testsuite/gdb.base/infcall-timeout.exp    |  97 ++++++
 gdb/testsuite/gdb.base/unwindonsignal.exp     |  36 ++-
 gdb/testsuite/gdb.compile/compile-cplus.exp   |   2 +-
 gdb/testsuite/gdb.compile/compile.exp         |   2 +-
 gdb/testsuite/gdb.cp/gdb2495.exp              |  16 +-
 gdb/testsuite/gdb.fortran/function-calls.exp  |   2 +-
 gdb/testsuite/gdb.mi/mi-syn-frame.exp         |   2 +-
 .../infcall-from-bp-cond-other-thread-event.c | 135 ++++++++
 ...nfcall-from-bp-cond-other-thread-event.exp | 174 ++++++++++
 .../gdb.threads/infcall-from-bp-cond-simple.c |  89 ++++++
 .../infcall-from-bp-cond-simple.exp           | 235 ++++++++++++++
 .../gdb.threads/infcall-from-bp-cond-single.c | 139 ++++++++
 .../infcall-from-bp-cond-single.exp           | 117 +++++++
 .../infcall-from-bp-cond-timeout.c            | 169 ++++++++++
 .../infcall-from-bp-cond-timeout.exp          | 173 ++++++++++
 .../gdb.threads/thread-unwindonsignal.exp     |   8 +-
 28 files changed, 1902 insertions(+), 80 deletions(-)
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.c
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp


base-commit: baab375361c365afee2577c94cbbd3fdd443d6da
-- 
2.25.4


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

* [PATCHv8 1/6] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait"
  2023-06-07 10:01             ` [PATCHv8 0/6] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
@ 2023-06-07 10:01               ` Andrew Burgess
  2023-06-07 10:01               ` [PATCHv8 2/6] gdb: fix b/p conditions with infcalls in multi-threaded inferiors Andrew Burgess
                                 ` (6 subsequent siblings)
  7 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-06-07 10:01 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Tankut Baris Aktemur

This reverts commit ac0d67ed1dcf470bad6a3bc4800c2ddc9bedecca.

There was nothing wrong with the commit which I'm reverting here, but
it removed some functionality that will be needed for a later commit;
that is, the ability for GDB to ask for events from a specific ptid_t
via the do_target_wait function.

In a follow up commit, this functionality will be used to implement
inferior function calls in multi-threaded inferiors.

This is not a straight revert of the above commit.  Reverting the
above commit replaces a 'nullptr' with 'NULL', I've gone in and
changed that, preserving the 'nullptr'.

Reviewed-By: Tankut Baris Aktemur <tankut.baris.aktemur@intel.com>
---
 gdb/infrun.c | 12 +++++++-----
 1 file changed, 7 insertions(+), 5 deletions(-)

diff --git a/gdb/infrun.c b/gdb/infrun.c
index 58da1cef29e..db8b918986c 100644
--- a/gdb/infrun.c
+++ b/gdb/infrun.c
@@ -3881,7 +3881,8 @@ do_target_wait_1 (inferior *inf, ptid_t ptid,
    more events.  Polls for events from all inferiors/targets.  */
 
 static bool
-do_target_wait (execution_control_state *ecs, target_wait_flags options)
+do_target_wait (ptid_t wait_ptid, execution_control_state *ecs,
+		target_wait_flags options)
 {
   int num_inferiors = 0;
   int random_selector;
@@ -3891,9 +3892,10 @@ do_target_wait (execution_control_state *ecs, target_wait_flags options)
      polling the rest of the inferior list starting from that one in a
      circular fashion until the whole list is polled once.  */
 
-  auto inferior_matches = [] (inferior *inf)
+  auto inferior_matches = [&wait_ptid] (inferior *inf)
     {
-      return inf->process_target () != nullptr;
+      return (inf->process_target () != nullptr
+	      && ptid_t (inf->pid).matches (wait_ptid));
     };
 
   /* First see how many matching inferiors we have.  */
@@ -3932,7 +3934,7 @@ do_target_wait (execution_control_state *ecs, target_wait_flags options)
 
   auto do_wait = [&] (inferior *inf)
   {
-    ecs->ptid = do_target_wait_1 (inf, minus_one_ptid, &ecs->ws, options);
+    ecs->ptid = do_target_wait_1 (inf, wait_ptid, &ecs->ws, options);
     ecs->target = inf->process_target ();
     return (ecs->ws.kind () != TARGET_WAITKIND_IGNORE);
   };
@@ -4362,7 +4364,7 @@ fetch_inferior_event ()
        the event.  */
     scoped_disable_commit_resumed disable_commit_resumed ("handling event");
 
-    if (!do_target_wait (&ecs, TARGET_WNOHANG))
+    if (!do_target_wait (minus_one_ptid, &ecs, TARGET_WNOHANG))
       {
 	infrun_debug_printf ("do_target_wait returned no event");
 	disable_commit_resumed.reset_and_commit ();
-- 
2.25.4


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

* [PATCHv8 2/6] gdb: fix b/p conditions with infcalls in multi-threaded inferiors
  2023-06-07 10:01             ` [PATCHv8 0/6] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
  2023-06-07 10:01               ` [PATCHv8 1/6] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
@ 2023-06-07 10:01               ` Andrew Burgess
  2023-06-07 10:01               ` [PATCHv8 3/6] gdb: add timeouts for inferior function calls Andrew Burgess
                                 ` (5 subsequent siblings)
  7 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-06-07 10:01 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Natalia Saiapova, Tankut Baris Aktemur

This commit fixes bug PR 28942, that is, creating a conditional
breakpoint in a multi-threaded inferior, where the breakpoint
condition includes an inferior function call.

Currently, when a user tries to create such a breakpoint, then GDB
will fail with:

  (gdb) break infcall-from-bp-cond-single.c:61 if (return_true ())
  Breakpoint 2 at 0x4011fa: file /tmp/build/gdb/testsuite/../../../src/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c, line 61.
  (gdb) continue
  Continuing.
  [New Thread 0x7ffff7c5d700 (LWP 2460150)]
  [New Thread 0x7ffff745c700 (LWP 2460151)]
  [New Thread 0x7ffff6c5b700 (LWP 2460152)]
  [New Thread 0x7ffff645a700 (LWP 2460153)]
  [New Thread 0x7ffff5c59700 (LWP 2460154)]
  Error in testing breakpoint condition:
  Couldn't get registers: No such process.
  An error occurred while in a function called from GDB.
  Evaluation of the expression containing the function
  (return_true) will be abandoned.
  When the function is done executing, GDB will silently stop.
  Selected thread is running.
  (gdb)

Or, in some cases, like this:

  (gdb) break infcall-from-bp-cond-simple.c:56 if (is_matching_tid (arg, 1))
  Breakpoint 2 at 0x401194: file /tmp/build/gdb/testsuite/../../../src/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c, line 56.
  (gdb) continue
  Continuing.
  [New Thread 0x7ffff7c5d700 (LWP 2461106)]
  [New Thread 0x7ffff745c700 (LWP 2461107)]
  ../../src.release/gdb/nat/x86-linux-dregs.c:146: internal-error: x86_linux_update_debug_registers: Assertion `lwp_is_stopped (lwp)' failed.
  A problem internal to GDB has been detected,
  further debugging may prove unreliable.

The precise error depends on the exact thread state; so there's race
conditions depending on which threads have fully started, and which
have not.  But the underlying problem is always the same; when GDB
tries to execute the inferior function call from within the breakpoint
condition, GDB will, incorrectly, try to resume threads that are
already running - GDB doesn't realise that some threads might already
be running.

The solution proposed in this patch requires an additional member
variable thread_info::in_cond_eval.  This flag is set to true (in
breakpoint.c) when GDB is evaluating a breakpoint condition.

In user_visible_resume_ptid (infrun.c), when the in_cond_eval flag is
true, then GDB will only try to resume the current thread, that is,
the thread for which the breakpoint condition is being evaluated.
This solves the problem of GDB trying to resume threads that are
already running.

The next problem is that inferior function calls are assumed to be
synchronous, that is, GDB doesn't expect to start an inferior function
call in thread #1, then receive a stop from thread #2 for some other,
unrelated reason.  To prevent GDB responding to an event from another
thread, we update fetch_inferior_event and do_target_wait in infrun.c,
so that, when an inferior function call (on behalf of a breakpoint
condition) is in progress, we only wait for events from the current
thread (the one evaluating the condition).

In do_target_wait I had to change the inferior_matches lambda
function, which is used to select which inferior to wait on.
Previously the logic was this:

   auto inferior_matches = [&wait_ptid] (inferior *inf)
     {
       return (inf->process_target () != nullptr
               && ptid_t (inf->pid).matches (wait_ptid));
     };

This compares the pid of the inferior against the complete ptid we
want to wait on.  Before this commit wait_ptid was only ever
minus_one_ptid (which is special, and means any process), and so every
inferior would match.

After this commit though wait_ptid might represent a specific thread
in a specific inferior.  If we compare the pid of the inferior to a
specific ptid then these will not match.  The fix is to compare
against the pid extracted from the wait_ptid, not against the complete
wait_ptid itself.

In fetch_inferior_event, after receiving the event, we only want to
stop all the other threads, and call inferior_event_handler with
INF_EXEC_COMPLETE, if we are not evaluating a conditional breakpoint.
If we are, then all the other threads should be left doing whatever
they were before.  The inferior_event_handler call will be performed
once the breakpoint condition has finished being evaluated, and GDB
decides to stop or not.

The final problem that needs solving relates to GDB's commit-resume
mechanism, which allows GDB to collect resume requests into a single
packet in order to reduce traffic to a remote target.

The problem is that the commit-resume mechanism will not send any
resume requests for an inferior if there are already events pending on
the GDB side.

Imagine an inferior with two threads.  Both threads hit a breakpoint,
maybe the same conditional breakpoint.  At this point there are two
pending events, one for each thread.

GDB selects one of the events and spots that this is a conditional
breakpoint, GDB evaluates the condition.

The condition includes an inferior function call, so GDB sets up for
the call and resumes the one thread, the resume request is added to
the commit-resume queue.

When the commit-resume queue is committed GDB sees that there is a
pending event from another thread, and so doesn't send any resume
requests to the actual target, GDB is assuming that when we wait we
will select the event from the other thread.

However, as this is an inferior function call for a condition
evaluation, we will not select the event from the other thread, we
only care about events from the thread that is evaluating the
condition - and the resume for this thread was never sent to the
target.

And so, GDB hangs, waiting for an event from a thread that was never
fully resumed.

To fix this issue I have added the concept of "forcing" the
commit-resume queue.  When enabling commit resume, if the force flag
is true, then any resumes will be committed to the target, even if
there are other threads with pending events.

A note on authorship: this patch was based on some work done by
Natalia Saiapova and Tankut Baris Aktemur from Intel[1].  I have made
some changes to their work in this version.

Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=28942

[1] https://sourceware.org/pipermail/gdb-patches/2020-October/172454.html

Co-authored-by: Natalia Saiapova <natalia.saiapova@intel.com>
Co-authored-by: Tankut Baris Aktemur <tankut.baris.aktemur@intel.com>
Reviewed-By: Tankut Baris Aktemur <tankut.baris.aktemur@intel.com>
---
 gdb/breakpoint.c                              |   2 +
 gdb/gdbthread.h                               |   3 +
 gdb/infcall.c                                 |   6 +
 gdb/infrun.c                                  |  64 +++--
 gdb/infrun.h                                  |   3 +-
 .../infcall-from-bp-cond-other-thread-event.c | 135 ++++++++++
 ...nfcall-from-bp-cond-other-thread-event.exp | 174 +++++++++++++
 .../gdb.threads/infcall-from-bp-cond-simple.c |  89 +++++++
 .../infcall-from-bp-cond-simple.exp           | 235 ++++++++++++++++++
 .../gdb.threads/infcall-from-bp-cond-single.c | 139 +++++++++++
 .../infcall-from-bp-cond-single.exp           | 117 +++++++++
 11 files changed, 952 insertions(+), 15 deletions(-)
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index da6c8de9d14..592aa29d949 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -5540,6 +5540,8 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
 	{
 	  try
 	    {
+	      scoped_restore reset_in_cond_eval
+		= make_scoped_restore (&thread->control.in_cond_eval, true);
 	      condition_result = breakpoint_cond_eval (cond);
 	    }
 	  catch (const gdb_exception_error &ex)
diff --git a/gdb/gdbthread.h b/gdb/gdbthread.h
index 7135515bf45..897752f2691 100644
--- a/gdb/gdbthread.h
+++ b/gdb/gdbthread.h
@@ -171,6 +171,9 @@ struct thread_control_state
      command.  This is used to decide whether "set scheduler-locking
      step" behaves like "on" or "off".  */
   int stepping_command = 0;
+
+  /* True if the thread is evaluating a BP condition.  */
+  bool in_cond_eval = false;
 };
 
 /* Inferior thread specific part of `struct infcall_suspend_state'.  */
diff --git a/gdb/infcall.c b/gdb/infcall.c
index ddf325a62a5..b055fbfbd64 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -642,6 +642,12 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
 
       proceed (real_pc, GDB_SIGNAL_0);
 
+      /* Enable commit resume, but pass true for the force flag.  This
+	 ensures any thread we set running in proceed will actually be
+	 committed to the target, even if some other thread in the current
+	 target has a pending event.  */
+      scoped_enable_commit_resumed enable ("infcall", true);
+
       infrun_debug_show_threads ("non-exited threads after proceed for inferior-call",
 				 all_non_exited_threads ());
 
diff --git a/gdb/infrun.c b/gdb/infrun.c
index db8b918986c..d2c17433104 100644
--- a/gdb/infrun.c
+++ b/gdb/infrun.c
@@ -2276,6 +2276,14 @@ user_visible_resume_ptid (int step)
 	 mode.  */
       resume_ptid = inferior_ptid;
     }
+  else if (inferior_ptid != null_ptid
+	   && inferior_thread ()->control.in_cond_eval)
+    {
+      /* The inferior thread is evaluating a BP condition.  Other threads
+	 might be stopped or running and we do not want to change their
+	 state, thus, resume only the current thread.  */
+      resume_ptid = inferior_ptid;
+    }
   else if (!sched_multi && target_supports_multi_process ())
     {
       /* Resume all threads of the current process (and none of other
@@ -3004,12 +3012,24 @@ schedlock_applies (struct thread_info *tp)
 					    execution_direction)));
 }
 
-/* Set process_stratum_target::COMMIT_RESUMED_STATE in all target
-   stacks that have threads executing and don't have threads with
-   pending events.  */
+/* When FORCE_P is false, set process_stratum_target::COMMIT_RESUMED_STATE
+   in all target stacks that have threads executing and don't have threads
+   with pending events.
+
+   When FORCE_P is true, set process_stratum_target::COMMIT_RESUMED_STATE
+   in all target stacks that have threads executing regardless of whether
+   there are pending events or not.
+
+   Passing FORCE_P as false makes sense when GDB is going to wait for
+   events from all threads and will therefore spot the pending events.
+   However, if GDB is only going to wait for events from select threads
+   (i.e. when performing an inferior call) then a pending event on some
+   other thread will not be spotted, and if we fail to commit the resume
+   state for the thread performing the inferior call, then the inferior
+   call will never complete (or even start).  */
 
 static void
-maybe_set_commit_resumed_all_targets ()
+maybe_set_commit_resumed_all_targets (bool force_p)
 {
   scoped_restore_current_thread restore_thread;
 
@@ -3038,7 +3058,7 @@ maybe_set_commit_resumed_all_targets ()
 	 status to report, handle it before requiring the target to
 	 commit its resumed threads: handling the status might lead to
 	 resuming more threads.  */
-      if (proc_target->has_resumed_with_pending_wait_status ())
+      if (!force_p && proc_target->has_resumed_with_pending_wait_status ())
 	{
 	  infrun_debug_printf ("not requesting commit-resumed for target %s, a"
 			       " thread has a pending waitstatus",
@@ -3048,7 +3068,7 @@ maybe_set_commit_resumed_all_targets ()
 
       switch_to_inferior_no_thread (inf);
 
-      if (target_has_pending_events ())
+      if (!force_p && target_has_pending_events ())
 	{
 	  infrun_debug_printf ("not requesting commit-resumed for target %s, "
 			       "target has pending events",
@@ -3141,7 +3161,7 @@ scoped_disable_commit_resumed::reset ()
     {
       /* This is the outermost instance, re-enable
 	 COMMIT_RESUMED_STATE on the targets where it's possible.  */
-      maybe_set_commit_resumed_all_targets ();
+      maybe_set_commit_resumed_all_targets (false);
     }
   else
     {
@@ -3174,7 +3194,7 @@ scoped_disable_commit_resumed::reset_and_commit ()
 /* See infrun.h.  */
 
 scoped_enable_commit_resumed::scoped_enable_commit_resumed
-  (const char *reason)
+  (const char *reason, bool force_p)
   : m_reason (reason),
     m_prev_enable_commit_resumed (enable_commit_resumed)
 {
@@ -3186,7 +3206,7 @@ scoped_enable_commit_resumed::scoped_enable_commit_resumed
 
       /* Re-enable COMMIT_RESUMED_STATE on the targets where it's
 	 possible.  */
-      maybe_set_commit_resumed_all_targets ();
+      maybe_set_commit_resumed_all_targets (force_p);
 
       maybe_call_commit_resumed_all_targets ();
     }
@@ -3892,10 +3912,11 @@ do_target_wait (ptid_t wait_ptid, execution_control_state *ecs,
      polling the rest of the inferior list starting from that one in a
      circular fashion until the whole list is polled once.  */
 
-  auto inferior_matches = [&wait_ptid] (inferior *inf)
+  ptid_t wait_ptid_pid {wait_ptid.pid ()};
+  auto inferior_matches = [&wait_ptid_pid] (inferior *inf)
     {
       return (inf->process_target () != nullptr
-	      && ptid_t (inf->pid).matches (wait_ptid));
+	      && ptid_t (inf->pid).matches (wait_ptid_pid));
     };
 
   /* First see how many matching inferiors we have.  */
@@ -4364,7 +4385,17 @@ fetch_inferior_event ()
        the event.  */
     scoped_disable_commit_resumed disable_commit_resumed ("handling event");
 
-    if (!do_target_wait (minus_one_ptid, &ecs, TARGET_WNOHANG))
+    /* Is the current thread performing an inferior function call as part
+       of a breakpoint condition evaluation?  */
+    bool in_cond_eval = (inferior_ptid != null_ptid
+			 && inferior_thread ()->control.in_cond_eval);
+
+    /* If the thread is in the middle of the condition evaluation, wait for
+       an event from the current thread.  Otherwise, wait for an event from
+       any thread.  */
+    ptid_t waiton_ptid = in_cond_eval ? inferior_ptid : minus_one_ptid;
+
+    if (!do_target_wait (waiton_ptid, &ecs, TARGET_WNOHANG))
       {
 	infrun_debug_printf ("do_target_wait returned no event");
 	disable_commit_resumed.reset_and_commit ();
@@ -4420,7 +4451,12 @@ fetch_inferior_event ()
 	    bool should_notify_stop = true;
 	    bool proceeded = false;
 
-	    stop_all_threads_if_all_stop_mode ();
+	    /* If the thread that stopped just completed an inferior
+	       function call as part of a condition evaluation, then we
+	       don't want to stop all the other threads.  */
+	    if (ecs.event_thread == nullptr
+		|| !ecs.event_thread->control.in_cond_eval)
+	      stop_all_threads_if_all_stop_mode ();
 
 	    clean_up_just_stopped_threads_fsms (&ecs);
 
@@ -4435,7 +4471,7 @@ fetch_inferior_event ()
 		  proceeded = normal_stop ();
 	      }
 
-	    if (!proceeded)
+	    if (!proceeded && !in_cond_eval)
 	      {
 		inferior_event_handler (INF_EXEC_COMPLETE);
 		cmd_done = 1;
diff --git a/gdb/infrun.h b/gdb/infrun.h
index a343d27f72d..d8db153ecc6 100644
--- a/gdb/infrun.h
+++ b/gdb/infrun.h
@@ -406,7 +406,8 @@ extern void maybe_call_commit_resumed_all_targets ();
 
 struct scoped_enable_commit_resumed
 {
-  explicit scoped_enable_commit_resumed (const char *reason);
+  explicit scoped_enable_commit_resumed (const char *reason,
+					 bool force_p = false);
   ~scoped_enable_commit_resumed ();
 
   DISABLE_COPY_AND_ASSIGN (scoped_enable_commit_resumed);
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
new file mode 100644
index 00000000000..e2a8ccb4ebe
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
@@ -0,0 +1,135 @@
+/* Copyright 2022-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 <pthread.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <sched.h>
+
+#define NUM_THREADS 2
+
+pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+
+/* Some global variables to poke, just for something to do.  */
+volatile int global_var_0 = 0;
+volatile int global_var_1 = 0;
+
+/* This flag is updated from GDB.  */
+volatile int raise_signal = 0;
+
+/* Implement the breakpoint condition function.  Release the other thread
+   and try to give the other thread a chance to run.  Then return ANSWER.  */
+int
+condition_core_func (int answer)
+{
+  /* This unlock should release the other thread.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  /* And this yield and sleep should (hopefully) give the other thread a
+     chance to run.  This isn't guaranteed of course, but once the other
+     thread does run it should hit a breakpoint, which GDB should
+     (temporarily) ignore, so there's no easy way for us to know the other
+     thread has done what it needs to, thus, yielding and sleeping is the
+     best we can do.  */
+  sched_yield ();
+  sleep (2);
+
+  return answer;
+}
+
+void
+stop_marker ()
+{
+  int a = 100;	/* Final breakpoint here.  */
+}
+
+/* A breakpoint condition function that always returns true.  */
+int
+condition_true_func ()
+{
+  return condition_core_func (1);
+}
+
+/* A breakpoint condition function that always returns false.  */
+int
+condition_false_func ()
+{
+  return condition_core_func (0);
+}
+
+void *
+worker_func (void *arg)
+{
+  volatile int *ptr = 0;
+  int tid = *((int *) arg);
+
+  switch (tid)
+    {
+    case 0:
+      global_var_0 = 11;	/* First thread breakpoint.  */
+      break;
+
+    case 1:
+      if (pthread_mutex_lock (&mutex) != 0)
+	abort ();
+      if (raise_signal)
+	global_var_1 = *ptr;	/* Signal here.  */
+      else
+	global_var_1 = 99;	/* Other thread breakpoint.  */
+      break;
+
+    default:
+      abort ();
+    }
+
+  return NULL;
+}
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+
+  /* Set an alarm, just in case the test deadlocks.  */
+  alarm (300);
+
+  /* We want the mutex to start locked.  */
+  if (pthread_mutex_lock (&mutex) != 0)
+    abort ();
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      void *retval;
+      pthread_join (threads[i], &retval);
+    }
+
+  /* Unlock once we're done, just for cleanliness.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
new file mode 100644
index 00000000000..1453575e4ad
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
@@ -0,0 +1,174 @@
+# Copyright 2022-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/>.
+
+# Test for conditional breakpoints where the breakpoint condition includes
+# an inferior function call.
+#
+# The tests in this script are testing what happens when an event arrives in
+# another thread while GDB is waiting for the inferior function call (in the
+# breakpoint condition) to finish.
+#
+# The expectation is that GDB will queue events for other threads and wait
+# for the inferior function call to complete, if the condition is true, then
+# the conditional breakpoint should be reported first.  The other thread
+# event should of course, not get lost, and should be reported as soon as
+# the user tries to continue the inferior.
+#
+# If the conditional breakpoint ends up not being taken (the condition is
+# false), then the other thread event should be reported immediately.
+#
+# This script tests what happens when the other thread event is (a) the
+# other thread hitting a breakpoint, and (b) the other thread taking a
+# signal (SIGSEGV in this case).
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] == -1 } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "First thread breakpoint"]
+set other_bp_line [gdb_get_line_number "Other thread breakpoint"]
+set final_bp_line [gdb_get_line_number "Final breakpoint here"]
+set signal_line [gdb_get_line_number "Signal here"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if { ![runto_main] } {
+	return -1
+    }
+
+    return 0
+}
+
+# Run a test of GDB's conditional breakpoints, where the conditions include
+# inferior function calls.  While the inferior function call is executing
+# another thread will hit a breakpoint (when OTHER_THREAD_SIGNAL is false),
+# or receive a signal (when OTHER_THREAD_SIGNAL is true).  GDB should report
+# the conditional breakpoint first (if the condition is true), and then
+# report the second thread event once the inferior is continued again.
+#
+# When STOP_AT_COND is true then the conditional breakpoint will have a
+# condition that evaluates to true (and GDB will stop at the breakpoint),
+# otherwise, the condition will evaluate to false (and GDB will not stop at
+# the breakpoint).
+proc run_condition_test { stop_at_cond other_thread_signal \
+			      target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint.
+    if { $stop_at_cond } {
+	set cond_func "condition_true_func"
+    } else {
+	set cond_func "condition_false_func"
+    }
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (${cond_func} ())"
+    set cond_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			"get number for conditional breakpoint"]
+
+    if { $other_thread_signal } {
+	# Arrange for the other thread to raise a signal while GDB is
+	# evaluating the breakpoint condition.
+	gdb_test_no_output "set raise_signal = 1"
+    } else {
+	# And a breakpoint that will be hit by another thread only once the
+	# breakpoint condition starts to be evaluated.
+	gdb_breakpoint "${::srcfile}:${::other_bp_line}"
+	set other_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			      "get number for other breakpoint"]
+    }
+
+    # A final breakpoint once the test has completed.
+    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
+    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			  "get number for final breakpoint"]
+
+    if { $stop_at_cond } {
+	# Continue.  The first breakpoint we hit should be the conditional
+	# breakpoint.  The other thread will have hit its breakpoint, but
+	# that will have been deferred until the conditional breakpoint is
+	# reported.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${cond_bp_num}, worker_func \[^\r\n\]+:${::cond_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+First thread breakpoint\[^\r\n\]+"] \
+	    "hit the conditional breakpoint"
+    }
+
+    if { $other_thread_signal } {
+	# Now continue again, the other thread will now report that it
+	# received a signal.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" received signal SIGSEGV, Segmentation fault\\." \
+		 "\\\[Switching to Thread \[^\r\n\]+\\\]" \
+		 "${::hex} in worker_func \[^\r\n\]+:${::signal_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Signal here\[^\r\n\]+"] \
+	    "received signal in other thread"
+    } else {
+	# Now continue again, the other thread will now report its
+	# breakpoint.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${other_bp_num}, worker_func \[^\r\n\]+:${::other_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Other thread breakpoint\[^\r\n\]+"] \
+	    "hit the breakpoint in other thread"
+
+	# Run to the stop marker.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${final_bp_num}, stop_marker \[^\r\n\]+:${::final_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Final breakpoint here\[^\r\n\]+"] \
+	    "hit the final breakpoint"
+    }
+
+    gdb_exit
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	foreach_with_prefix other_thread_signal { true false } {
+	    foreach_with_prefix stop_at_cond { true false } {
+		run_condition_test $stop_at_cond $other_thread_signal \
+		    $target_async $target_non_stop
+	    }
+	}
+    }
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
new file mode 100644
index 00000000000..9d746d8be49
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
@@ -0,0 +1,89 @@
+/* Copyright 2022-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 <pthread.h>
+#include <unistd.h>
+
+#define NUM_THREADS 3
+
+int
+is_matching_tid (int *tid_ptr, int tid_value)
+{
+  return *tid_ptr == tid_value;
+}
+
+int
+return_true ()
+{
+  return 1;
+}
+
+int
+return_false ()
+{
+  return 0;
+}
+
+int
+function_that_segfaults ()
+{
+  int *p = 0;
+  *p = 1;	/* Segfault happens here.   */
+}
+
+int
+function_with_breakpoint ()
+{
+  return 1;	/* Nested breakpoint.  */
+}
+
+void *
+worker_func (void *arg)
+{
+  int a = 42;	/* Breakpoint here.  */
+}
+
+void
+stop_marker ()
+{
+  int b = 99;	/* Stop marker.  */
+}
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+
+  alarm (300);
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      void *retval;
+      pthread_join (threads[i], &retval);
+    }
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
new file mode 100644
index 00000000000..c46f8cdb981
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
@@ -0,0 +1,235 @@
+# Copyright 2022-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/>.
+
+# Some simple tests of inferior function calls from breakpoint
+# conditions, in multi-threaded inferiors.
+#
+# This test sets up a multi-threaded inferior, and places a breakpoint
+# at a location that many of the threads will reach.  We repeat the
+# test with different conditions, sometimes a single thread should
+# stop at the breakpoint, sometimes multiple threads should stop, and
+# sometimes no threads should stop.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] == -1 } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "Breakpoint here"]
+set stop_bp_line [gdb_get_line_number "Stop marker"]
+set nested_bp_line [gdb_get_line_number "Nested breakpoint"]
+set segv_line [gdb_get_line_number "Segfault happens here"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if { ![runto_main] } {
+	return -1
+    }
+
+    return 0
+}
+
+# Run a test of GDB's conditional breakpoints, where the conditions include
+# inferior function calls.
+#
+# CONDITION is the expression to be used as the breakpoint condition.
+#
+# N_EXPECTED_HITS is the number of threads that we expect to stop due to
+# CONDITON.
+#
+# MESSAGE is used as a test name prefix.
+proc run_condition_test { message n_expected_hits condition \
+			      target_async target_non_stop } {
+    with_test_prefix $message {
+
+	if { [start_gdb_and_runto_main $target_async \
+		  $target_non_stop] == -1 } {
+	    return
+	}
+
+	# Use this convenience variable to track how often the
+	# breakpoint condition has been evaluated.  This should be
+	# once per thread.
+	gdb_test "set \$n_cond_eval = 0"
+
+	# Setup the conditional breakpoint.
+	gdb_breakpoint \
+	    "${::srcfile}:${::cond_bp_line} if ((++\$n_cond_eval) && (${condition}))"
+
+	# And a breakpoint that we hit when the test is over, this one is
+	# not conditional.  Only the main thread gets here once all the
+	# other threads have finished.
+	gdb_breakpoint "${::srcfile}:${::stop_bp_line}"
+
+	# The number of times we stop at the conditional breakpoint.
+	set n_hit_condition 0
+
+	# Now keep 'continue'-ing GDB until all the threads have finished
+	# and we reach the stop_marker breakpoint.
+	gdb_test_multiple "continue" "spot all breakpoint hits" {
+	    -re " worker_func \[^\r\n\]+${::srcfile}:${::cond_bp_line}\r\n${::decimal}\\s+\[^\r\n\]+Breakpoint here\[^\r\n\]+\r\n${::gdb_prompt} $" {
+		incr n_hit_condition
+		send_gdb "continue\n"
+		exp_continue
+	    }
+
+	    -re " stop_marker \[^\r\n\]+${::srcfile}:${::stop_bp_line}\r\n${::decimal}\\s+\[^\r\n\]+Stop marker\[^\r\n\]+\r\n${::gdb_prompt} $" {
+		pass $gdb_test_name
+	    }
+	}
+
+	gdb_assert { $n_hit_condition == $n_expected_hits } \
+	    "stopped at breakpoint the expected number of times"
+
+	# Ensure the breakpoint condition was evaluated once per thread.
+	gdb_test "print \$n_cond_eval" "= 3" \
+	    "condition was evaluated in each thread"
+    }
+}
+
+# Check that after handling a conditional breakpoint (where the condition
+# includes an inferior call), it is still possible to kill the running
+# inferior, and then restart the inferior.
+#
+# At once point doing this would result in GDB giving an assertion error.
+proc_with_prefix run_kill_and_restart_test { target_async target_non_stop } {
+    # This test relies on the 'start' command, which is not possible with
+    # the plain 'remote' target.
+    if { [target_info gdb_protocol] == "remote" } {
+	return
+    }
+
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint.
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 1))"
+    gdb_continue_to_breakpoint "worker_func"
+
+    # Now kill the program being debugged.
+    gdb_test "kill" "" "kill process" \
+	"Kill the program being debugged.*y or n. $" "y"
+
+    # Check we can restart the inferior.  At one point this would trigger an
+    # assertion.
+    gdb_start_cmd
+}
+
+# Create a conditional breakpoint which includes a call to a function that
+# segfaults.  Run GDB and check what happens when the inferior segfaults
+# during the inferior call.
+proc_with_prefix run_bp_cond_segfaults { target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # This test relies on the inferior segfaulting when trying to
+    # access address zero.
+    if { [is_address_zero_readable] } {
+	return
+    }
+
+    # Setup the conditional breakpoint, include a call to
+    # 'function_that_segfaults', which triggers the segfault.
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 0) && function_that_segfaults ())"
+    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of conditional breakpoint"]
+
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     ".*" \
+	     "Thread ${::decimal} \"infcall-from-bp\" received signal SIGSEGV, Segmentation fault\\." \
+	     "${::hex} in function_that_segfaults \\(\\) at \[^\r\n\]+:${::segv_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Segfault happens here\[^\r\n\]+" \
+	     "Error in testing condition for breakpoint ${bp_1_num}:" \
+	     "The program being debugged was signaled while in a function called from GDB\\." \
+	     "GDB remains in the frame where the signal was received\\." \
+	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(function_that_segfaults\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+}
+
+# Create a conditional breakpoint which includes a call to a function that
+# itself has a breakpoint set within it.  Run GDB and check what happens
+# when GDB hits the nested breakpoint.
+proc_with_prefix run_bp_cond_hits_breakpoint { target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint, include a call to
+    # 'function_with_breakpoint' in which we will shortly place a
+    # breakpoint.
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 0) && function_with_breakpoint ())"
+    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of conditional breakpoint"]
+
+    gdb_breakpoint "${::srcfile}:${::nested_bp_line}"
+    set bp_2_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of nested breakpoint"]
+
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     ".*" \
+	     "Thread ${::decimal} \"infcall-from-bp\" hit Breakpoint ${bp_2_num}, function_with_breakpoint \\(\\) at \[^\r\n\]+:${::nested_bp_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Nested breakpoint\[^\r\n\]+" \
+	     "Error in testing condition for breakpoint ${bp_1_num}:" \
+	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(function_with_breakpoint\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	run_condition_test "exactly one thread is hit" \
+	    1 "is_matching_tid (arg, 1)" \
+	    $target_async $target_non_stop
+	run_condition_test "exactly two threads are hit" \
+	    2 "(is_matching_tid (arg, 0) || is_matching_tid (arg, 2))" \
+	    $target_async $target_non_stop
+	run_condition_test "all three threads are hit" \
+	    3 "return_true ()" \
+	    $target_async $target_non_stop
+	run_condition_test "no thread is hit" \
+	    0 "return_false ()" \
+	    $target_async $target_non_stop
+
+	run_kill_and_restart_test $target_async $target_non_stop
+	run_bp_cond_segfaults $target_async $target_non_stop
+	run_bp_cond_hits_breakpoint $target_async $target_non_stop
+    }
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
new file mode 100644
index 00000000000..835c72f03cf
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
@@ -0,0 +1,139 @@
+/* Copyright 2022-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 <pthread.h>
+#include <unistd.h>
+#include <semaphore.h>
+#include <stdlib.h>
+
+#define NUM_THREADS 5
+
+/* Semaphores, used to track when threads have started, and to control
+   when the threads finish.  */
+sem_t startup_semaphore;
+sem_t finish_semaphore;
+
+/* Mutex to control when the first worker thread hit a breakpoint
+   location.  */
+pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+
+/* Global variable to poke, just so threads have something to do.  */
+volatile int global_var = 0;
+
+int
+return_true ()
+{
+  return 1;
+}
+
+int
+return_false ()
+{
+  return 0;
+}
+
+void *
+worker_func (void *arg)
+{
+  int tid = *((int *) arg);
+
+  switch (tid)
+    {
+    case 0:
+      /* Wait for MUTEX to become available, then pass through the
+	 conditional breakpoint location.  */
+      if (pthread_mutex_lock (&mutex) != 0)
+	abort ();
+      global_var = 99;	/* Conditional breakpoint here.  */
+      if (pthread_mutex_unlock (&mutex) != 0)
+	abort ();
+      break;
+
+    default:
+      /* Notify the main thread that the thread has started, then wait for
+	 the main thread to tell us to finish.  */
+      sem_post (&startup_semaphore);
+      if (sem_wait (&finish_semaphore) != 0)
+	abort ();
+      break;
+    }
+}
+
+void
+stop_marker ()
+{
+  global_var = 99;	/* Stop marker.  */
+}
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+  void *retval;
+
+  /* An alarm, just in case the thread deadlocks.  */
+  alarm (300);
+
+  /* Semaphore initialization.  */
+  if (sem_init (&startup_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&finish_semaphore, 0, 0) != 0)
+    abort ();
+
+  /* Lock MUTEX, this prevents the first worker thread from rushing ahead.  */
+  if (pthread_mutex_lock (&mutex) != 0)
+    abort ();
+
+  /* Worker thread creation.  */
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  /* Wait for every thread (other than the first) to tell us it has started
+     up.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    {
+      if (sem_wait (&startup_semaphore) != 0)
+	abort ();
+    }
+
+  /* Unlock the first thread so it can proceed.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  /* Wait for the first thread only.  */
+  pthread_join (threads[0], &retval);
+
+  /* Now post FINISH_SEMAPHORE to allow all the other threads to finish.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    sem_post (&finish_semaphore);
+
+  /* Now wait for the remaining threads to complete.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    pthread_join (threads[i], &retval);
+
+  /* Semaphore cleanup.  */
+  sem_destroy (&finish_semaphore);
+  sem_destroy (&startup_semaphore);
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
new file mode 100644
index 00000000000..787dee3aa8e
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
@@ -0,0 +1,117 @@
+# Copyright 2022-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 reprocuces bug gdb/28942, performing an inferior function
+# call from a breakpoint condition in a multi-threaded inferior.
+#
+# The important part of this test is that, when the conditional
+# breakpoint is hit, and the condition (which includes an inferior
+# function call) is evaluated, the other threads are running.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] == -1 } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "Conditional breakpoint here"]
+set final_bp_line [gdb_get_line_number "Stop marker"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if { ![runto_main] } {
+	return -1
+    }
+
+    return 0
+}
+
+# Run a test of GDB's conditional breakpoints, where the conditions include
+# inferior function calls.
+#
+# TARGET_ASYNC and TARGET_NON_STOP are used when starting up GDB.
+#
+# When STOP_AT_COND is true the breakpoint condtion will evaluate to
+# true, and GDB will stop at the breakpoint.  Otherwise, the
+# breakpoint condition will evaluate to false and GDB will not stop at
+# the breakpoint.
+proc run_condition_test { stop_at_cond \
+			      target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint.
+    if { $stop_at_cond } {
+	set cond_func "return_true"
+    } else {
+	set cond_func "return_false"
+    }
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (${cond_func} ())"
+    set cond_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			"get number for conditional breakpoint"]
+
+    # And a breakpoint that we hit when the test is over, this one is
+    # not conditional.
+    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
+    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			  "get number for final breakpoint"]
+
+    if { $stop_at_cond } {
+	# Continue.  The first breakpoint we hit should be the conditional
+	# breakpoint.  The other thread will have hit its breakpoint, but
+	# that will have been deferred until the conditional breakpoint is
+	# reported.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${cond_bp_num}, worker_func \[^\r\n\]+:${::cond_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Conditional breakpoint here\[^\r\n\]+"] \
+	    "hit the conditional breakpoint"
+    }
+
+    # Run to the stop marker.
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     ".*" \
+	     "" \
+	     "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${final_bp_num}, stop_marker \[^\r\n\]+:${::final_bp_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Stop marker\[^\r\n\]+"] \
+	"hit the final breakpoint"
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	foreach_with_prefix stop_at_cond { true false } {
+	    run_condition_test $stop_at_cond \
+		$target_async $target_non_stop
+	}
+    }
+}
-- 
2.25.4


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

* [PATCHv8 3/6] gdb: add timeouts for inferior function calls
  2023-06-07 10:01             ` [PATCHv8 0/6] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
  2023-06-07 10:01               ` [PATCHv8 1/6] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
  2023-06-07 10:01               ` [PATCHv8 2/6] gdb: fix b/p conditions with infcalls in multi-threaded inferiors Andrew Burgess
@ 2023-06-07 10:01               ` Andrew Burgess
  2023-06-07 10:01               ` [PATCHv8 4/6] gdb/remote: avoid SIGINT after calling remote_target::stop Andrew Burgess
                                 ` (4 subsequent siblings)
  7 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-06-07 10:01 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Tankut Baris Aktemur

In the previous commits I have been working on improving inferior
function call support.  One thing that worries me about using inferior
function calls from a conditional breakpoint is: what happens if the
inferior function call fails?

If the failure is obvious, e.g. the thread performing the call
crashes, or hits a breakpoint, then this case is already well handled,
and the error is reported to the user.

But what if the thread performing the inferior call just deadlocks?
If the user made the call from a 'print' or 'call' command, then the
user might have some expectation of when the function call should
complete, and, when this time limit is exceeded, the user
will (hopefully) interrupt GDB and regain control of the debug
session.

But, when the inferior function call is from a breakpoint condition it
is much harder to understand that GDB is deadlocked within an inferior
call.  Maybe the breakpoint hasn't been hit yet?  Or maybe the
condition was always false?  Or maybe GDB is deadlocked in an inferior
call?  The only way to know for sure is for the user to periodically
interrupt the inferior, check on the state of all the threads, and
then continue.

Additionally, the focus of the previous commit was inferior function
calls, from a conditional breakpoint, in a multi-threaded inferior.
This opens up a whole new set of potential failure conditions.  For
example, what if the function called relies on interaction with some
other thread, and the other thread crashes?  Or hits a breakpoint?
Given how inferior function calls work (in a synchronous manner), a
stop event in some other thread is going to be ignored while the
inferior function call is being executed as part of a breakpoint
condition, and this means that GDB could get stuck waiting for the
original condition thread, which will now never complete.

In this commit I propose a solution to this problem.  A timeout.  For
targets that support async-mode we can install an event-loop timer
before starting the inferior function call.  When the timer expires we
will stop the thread performing the inferior function call.  With this
mechanism in place a user can be sure that any inferior call they make
will either complete, or timeout eventually.

Adding a timer like this is obviously a change in behaviour for the
more common 'call' and 'print' uses of inferior function calls, so, in
this patch, I propose having two different timers.  One I call the
'direct-call-timeout', which is used for 'call' and 'print' commands.
This timeout is by default set to unlimited, which, not surprisingly,
means there is no timeout in place.

A second timer, which I've called 'indirect-call-timeout', is used for
inferior function calls from breakpoint conditions.  This timeout has
a default value of 30 seconds.  This is a reasonably long time to
wait, and hopefully should be enough in most cases to allow the
inferior call to complete.  An inferior call that takes more than 30
seconds, which is installed on a breakpoint condition is really going
to slow down the debug session, so hopefully this is not a common use
case.

The user is, of course, free to reduce, or increase the timeout value,
and can always use Ctrl-c to interrupt an inferior function call, but
this timeout will ensure that GDB will stop at some point.

The new commands added by this commit are:

  set direct-call-timeout SECONDS
  show direct-call-timeout
  set indirect-call-timeout SECONDS
  show indirect-call-timeout

These new timeouts do depend on async-mode, so, if async-mode is
disabled (maint set target-async off), or not supported (e.g. target
sim), then the timeout is treated as unlimited (that is, no timeout is
set).

For targets that "fake" non-async mode, e.g. Linux native, where
non-async mode is really just async mode, but then we park the target
in a sissuspend, we could easily fix things so that the timeouts still
work, however, for targets that really are not async aware, like the
simulator, fixing things so that timeouts work correctly would be a
much bigger task - that effort would be better spent just making the
target async-aware.  And so, I'm happy for now that this feature will
only work on async targets.

The two new show commands will display slightly different text if the
current target is a non-async target, which should allow users to
understand what's going on.

There's a somewhat random test adjustment needed in gdb.base/help.exp,
the test uses a regexp with the apropos command, and expects to find a
single result.  Turns out the new settings I added also matched the
regexp, which broke the test.  I've updated the regexp a little to
exclude my new settings.

In infcall.c you'll notice the thread_info::stop_requested flag being
set when a timeout occurs.  This flag setting is not required as part
of this commit, but will be needed in a later commit.  However, it
seemed like setting this flag fitted better with this commit, which is
why the change is added here.

Reviewed-By: Tankut Baris Aktemur <tankut.baris.aktemur@intel.com>
---
 gdb/NEWS                                      |  18 ++
 gdb/doc/gdb.texinfo                           |  66 ++++++
 gdb/infcall.c                                 | 221 +++++++++++++++++-
 gdb/testsuite/gdb.base/help.exp               |   2 +-
 gdb/testsuite/gdb.base/infcall-timeout.c      |  36 +++
 gdb/testsuite/gdb.base/infcall-timeout.exp    |  83 +++++++
 .../infcall-from-bp-cond-timeout.c            | 169 ++++++++++++++
 .../infcall-from-bp-cond-timeout.exp          | 157 +++++++++++++
 8 files changed, 747 insertions(+), 5 deletions(-)
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.c
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp

diff --git a/gdb/NEWS b/gdb/NEWS
index 649a3a9824a..4ddc0a047f0 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -111,6 +111,24 @@ info main
    $2 = 1
    (gdb) break func if $_shell("some command") == 0
 
+set direct-call-timeout SECONDS
+show direct-call-timeout
+set indirect-call-timeout SECONDS
+show indirect-call-timeout
+  These new settings can be used to limit how long GDB will wait for
+  an inferior function call to complete.  The direct timeout is used
+  for inferior function calls from e.g. 'call' and 'print' commands,
+  while the indirect timeout is used for inferior function calls from
+  within a conditional breakpoint expression.
+
+  The default for the direct timeout is unlimited, while the default
+  for the indirect timeout is 30 seconds.
+
+  These timeouts will only have an effect for targets that are
+  operating in async mode.  For non-async targets the timeouts are
+  ignored, GDB will wait indefinitely for an inferior function to
+  complete, unless interrupted by the user using Ctrl-C.
+
 * MI changes
 
 ** mi now reports 'no-history' as a stop reason when hitting the end of the
diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index 40d1f244417..f27ec719d11 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -20920,6 +20920,72 @@
 @code{step}, etc).  In this case, when the inferior finally returns to
 the dummy-frame, @value{GDBN} will once again halt the inferior.
 
+On targets that support asynchronous execution (@pxref{Background
+Execution}) @value{GDBN} can place a timeout on any functions called
+from @value{GDBN}.  If the timeout expires and the function call is
+still ongoing, then @value{GDBN} will interrupt the program.
+
+For targets that don't support asynchronous execution
+(@pxref{Background Execution}) then timeouts for functions called from
+@value{GDBN} are not supported, the timeout settings described below
+will be treated as @code{unlimited}, meaning @value{GDBN} will wait
+indefinitely for function call to complete, unless interrupted by the
+user using @kbd{Ctrl-C}.
+
+@table @code
+@item set direct-call-timeout @var{seconds}
+@kindex set direct-call-timeout
+@cindex timeout for called functions
+Set the timeout used when calling functions in the program to
+@var{seconds}, which should be an integer greater than zero, or the
+special value @code{unlimited}, which indicates no timeout should be
+used.  The default for this setting is @code{unlimited}.
+
+This setting is used when the user calls a function directly from the
+command prompt, for example with a @code{call} or @code{print}
+command.
+
+This setting only works for targets that support asynchronous
+execution (@pxref{Background Execution}), for any other target the
+setting is treated as @code{unlimited}.
+
+@item show direct-call-timeout
+@kindex show direct-call-timeout
+@cindex timeout for called functions
+Show the timeout used when calling functions in the program with a
+@code{call} or @code{print} command.
+@end table
+
+It is also possible to call functions within the program from the
+condition of a conditional breakpoint (@pxref{Conditions, ,Break
+Conditions}).  A different setting controls the timeout used for
+function calls made from a breakpoint condition.
+
+@table @code
+@item set indirect-call-timeout @var{seconds}
+@kindex set indirect-call-timeout
+@cindex timeout for called functions
+Set the timeout used when calling functions in the program from a
+breakpoint or watchpoint condition to @var{seconds}, which should be
+an integer greater than zero, or the special value @code{unlimited},
+which indicates no timeout should be used.  The default for this
+setting is @code{30} seconds.
+
+This setting only works for targets that support asynchronous
+execution (@pxref{Background Execution}), for any other target the
+setting is treated as @code{unlimited}.
+
+If a function called from a breakpoint or watchpoint condition times
+out, then @value{GDBN} will stop at the point where the timeout
+occurred.  The breakpoint condition evaluation will be abandoned.
+
+@item show indirect-call-timeout
+@kindex show indirect-call-timeout
+@cindex timeout for called functions
+Show the timeout used when calling functions in the program from a
+breakpoint or watchpoint condition.
+@end table
+
 @subsection Calling functions with no debug info
 
 @cindex no debug info functions
diff --git a/gdb/infcall.c b/gdb/infcall.c
index b055fbfbd64..162659ca8e6 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -96,6 +96,53 @@ show_may_call_functions_p (struct ui_file *file, int from_tty,
 	      value);
 }
 
+/* A timeout (in seconds) for direct inferior calls.  A direct inferior
+   call is one the user triggers from the prompt, e.g. with a 'call' or
+   'print' command.  Compare with the definition of indirect calls below.  */
+
+static unsigned int direct_call_timeout = UINT_MAX;
+
+/* Implement 'show direct-call-timeout'.  */
+
+static void
+show_direct_call_timeout (struct ui_file *file, int from_tty,
+			  struct cmd_list_element *c, const char *value)
+{
+  if (target_has_execution () && !target_can_async_p ())
+    gdb_printf (file, _("Current target does not support async mode, timeout "
+			"for direct inferior calls is \"unlimited\".\n"));
+  else if (direct_call_timeout == UINT_MAX)
+    gdb_printf (file, _("Timeout for direct inferior function calls "
+			"is \"unlimited\".\n"));
+  else
+    gdb_printf (file, _("Timeout for direct inferior function calls "
+			"is \"%s seconds\".\n"), value);
+}
+
+/* A timeout (in seconds) for indirect inferior calls.  An indirect inferior
+   call is one that originates from within GDB, for example, when
+   evaluating an expression for a conditional breakpoint.  Compare with
+   the definition of direct calls above.  */
+
+static unsigned int indirect_call_timeout = 30;
+
+/* Implement 'show indirect-call-timeout'.  */
+
+static void
+show_indirect_call_timeout (struct ui_file *file, int from_tty,
+			  struct cmd_list_element *c, const char *value)
+{
+  if (target_has_execution () && !target_can_async_p ())
+    gdb_printf (file, _("Current target does not support async mode, timeout "
+			"for indirect inferior calls is \"unlimited\".\n"));
+  else if (indirect_call_timeout == UINT_MAX)
+    gdb_printf (file, _("Timeout for indirect inferior function calls "
+			"is \"unlimited\".\n"));
+  else
+    gdb_printf (file, _("Timeout for indirect inferior function calls "
+			"is \"%s seconds\".\n"), value);
+}
+
 /* How you should pass arguments to a function depends on whether it
    was defined in K&R style or prototype style.  If you define a
    function using the K&R syntax that takes a `float' argument, then
@@ -590,6 +637,86 @@ call_thread_fsm::should_notify_stop ()
   return true;
 }
 
+/* A class to control creation of a timer that will interrupt a thread
+   during an inferior call.  */
+struct infcall_timer_controller
+{
+  /* Setup an event-loop timer that will interrupt PTID if the inferior
+     call takes too long.  DIRECT_CALL_P is true when this inferior call is
+     a result of the user using a 'print' or 'call' command, and false when
+     this inferior call is a result of e.g. a conditional breakpoint
+     expression, this is used to select which timeout to use.  */
+  infcall_timer_controller (thread_info *thr, bool direct_call_p)
+    : m_thread (thr)
+  {
+    unsigned int timeout
+      = direct_call_p ? direct_call_timeout : indirect_call_timeout;
+    if (timeout < UINT_MAX && target_can_async_p ())
+      {
+	int ms = timeout * 1000;
+	int id = create_timer (ms, infcall_timer_controller::timed_out, this);
+	m_timer_id.emplace (id);
+	infcall_debug_printf ("Setting up infcall timeout timer for "
+			      "ptid %s: %d milliseconds",
+			      m_thread->ptid.to_string ().c_str (), ms);
+      }
+  }
+
+  /* Destructor.  Ensure that the timer is removed from the event loop.  */
+  ~infcall_timer_controller ()
+  {
+    /* If the timer has already triggered, then it will have already been
+       deleted from the event loop.  If the timer has not triggered, then
+       delete it now.  */
+    if (m_timer_id.has_value () && !m_triggered)
+      delete_timer (*m_timer_id);
+
+    /* Just for clarity, discard the timer id now.  */
+    m_timer_id.reset ();
+  }
+
+  /* Return true if there was a timer in place, and the timer triggered,
+     otherwise, return false.  */
+  bool triggered_p ()
+  {
+    gdb_assert (!m_triggered || m_timer_id.has_value ());
+    return m_triggered;
+  }
+
+private:
+  /* The thread we should interrupt.  */
+  thread_info *m_thread;
+
+  /* Set true when the timer is triggered.  */
+  bool m_triggered = false;
+
+  /* Given a value when a timer is in place.  */
+  gdb::optional<int> m_timer_id;
+
+  /* Callback for the timer, forwards to ::trigger below.  */
+  static void
+  timed_out (gdb_client_data context)
+  {
+    infcall_timer_controller *ctrl
+      = static_cast<infcall_timer_controller *> (context);
+    ctrl->trigger ();
+  }
+
+  /* Called when the timer goes off.  Stop thread m_thread.  */
+  void
+  trigger ()
+  {
+    m_triggered = true;
+
+    scoped_disable_commit_resumed disable_commit_resumed ("infcall timeout");
+
+    infcall_debug_printf ("Stopping thread %s",
+			  m_thread->ptid.to_string ().c_str ());
+    target_stop (m_thread->ptid);
+    m_thread->stop_requested = true;
+  }
+};
+
 /* Subroutine of call_function_by_hand to simplify it.
    Start up the inferior and wait for it to stop.
    Return the exception if there's an error, or an exception with
@@ -600,13 +727,15 @@ call_thread_fsm::should_notify_stop ()
 
 static struct gdb_exception
 run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
-		   struct thread_info *call_thread, CORE_ADDR real_pc)
+		   struct thread_info *call_thread, CORE_ADDR real_pc,
+		   bool *timed_out_p)
 {
   INFCALL_SCOPED_DEBUG_ENTER_EXIT;
 
   struct gdb_exception caught_error;
   ptid_t call_thread_ptid = call_thread->ptid;
   int was_running = call_thread->state == THREAD_RUNNING;
+  *timed_out_p = false;
 
   infcall_debug_printf ("call function at %s in thread %s, was_running = %d",
 			core_addr_to_string (real_pc),
@@ -618,6 +747,16 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
   scoped_restore restore_in_infcall
     = make_scoped_restore (&call_thread->control.in_infcall, 1);
 
+  /* If the thread making the inferior call stops with a timeout then the
+     stop_requested flag will be set.  However, we don't want changes to
+     this flag to leak back to our caller, we might be here to handle an
+     inferior call from a breakpoint condition, so leaving this flag set
+     would appear that the breakpoint stop was actually a requested stop,
+     which is not true, and will cause GDB to print extra messages to the
+     output.  */
+  scoped_restore restore_stop_requested
+    = make_scoped_restore (&call_thread->stop_requested, false);
+
   clear_proceed_status (0);
 
   /* Associate the FSM with the thread after clear_proceed_status
@@ -651,11 +790,23 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
       infrun_debug_show_threads ("non-exited threads after proceed for inferior-call",
 				 all_non_exited_threads ());
 
+      /* Setup a timer (if possible, and if the settings allow) to prevent
+	 the inferior call running forever.  */
+      bool direct_call_p = !call_thread->control.in_cond_eval;
+      infcall_timer_controller infcall_timer (call_thread, direct_call_p);
+
       /* Inferior function calls are always synchronous, even if the
 	 target supports asynchronous execution.  */
       wait_sync_command_done ();
 
-      infcall_debug_printf ("inferior call completed successfully");
+      /* If the timer triggered then the inferior call failed.  */
+      if (infcall_timer.triggered_p ())
+	{
+	  infcall_debug_printf ("inferior call timed out");
+	  *timed_out_p = true;
+	}
+      else
+	infcall_debug_printf ("inferior call completed successfully");
     }
   catch (gdb_exception &e)
     {
@@ -1309,6 +1460,10 @@ call_function_by_hand_dummy (struct value *function,
   scoped_restore restore_stopped_by_random_signal
     = make_scoped_restore (&stopped_by_random_signal, 0);
 
+  /* Set to true by the call to run_inferior_call below if the inferior
+     call is artificially interrupted by GDB due to taking too long.  */
+  bool timed_out_p = false;
+
   /* - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP -
      If you're looking to implement asynchronous dummy-frames, then
      just below is the place to chop this function in two..  */
@@ -1335,7 +1490,8 @@ call_function_by_hand_dummy (struct value *function,
 			      struct_addr);
     {
       std::unique_ptr<call_thread_fsm> sm_up (sm);
-      e = run_inferior_call (std::move (sm_up), call_thread.get (), real_pc);
+      e = run_inferior_call (std::move (sm_up), call_thread.get (), real_pc,
+			     &timed_out_p);
     }
 
     if (e.reason < 0)
@@ -1487,7 +1643,10 @@ When the function is done executing, GDB will silently stop."),
       std::string name = get_function_name (funaddr, name_buf,
 					    sizeof (name_buf));
 
-      if (stopped_by_random_signal)
+      /* If the inferior call timed out then it will have been interrupted
+	 by a signal, but we want to report this differently to the user,
+	 which is done later in this function.  */
+      if (stopped_by_random_signal && !timed_out_p)
 	{
 	  /* We stopped inside the FUNCTION because of a random
 	     signal.  Further execution of the FUNCTION is not
@@ -1531,6 +1690,36 @@ GDB remains in the frame where the signal was received.\n\
 To change this behavior use \"set unwindonsignal on\".\n\
 Evaluation of the expression containing the function\n\
 (%s) will be abandoned.\n\
+When the function is done executing, GDB will silently stop."),
+		     name.c_str ());
+	    }
+	}
+
+      if (timed_out_p)
+	{
+	  /* A timeout results in a signal being sent to the inferior.  */
+	  gdb_assert (stopped_by_random_signal);
+
+	  /* Indentation is weird here.  A later patch is going to move the
+	    following block into an if/else, so I'm leaving the indentation
+	    here to minimise the later patch.
+
+	    Also, the error message used below refers to 'set
+	    unwind-on-timeout' which doesn't exist yet.  This will be added
+	    in a later commit, I'm leaving this in for now to minimise the
+	    churn caused by the commit that adds unwind-on-timeout.  */
+	    {
+	      /* The user wants to stay in the frame where we stopped
+		 (default).  Discard inferior status, we're not at the same
+		 point we started at.  */
+	      discard_infcall_control_state (inf_status.release ());
+
+	      error (_("\
+The program being debugged timed out while in a function called from GDB.\n\
+GDB remains in the frame where the timeout occurred.\n\
+To change this behavior use \"set unwind-on-timeout on\".\n\
+Evaluation of the expression containing the function\n\
+(%s) will be abandoned.\n\
 When the function is done executing, GDB will silently stop."),
 		     name.c_str ());
 	    }
@@ -1644,6 +1833,30 @@ The default is to unwind the frame."),
 			   show_unwind_on_terminating_exception_p,
 			   &setlist, &showlist);
 
+  add_setshow_uinteger_cmd ("direct-call-timeout", no_class,
+			    &direct_call_timeout, _("\
+Set the timeout, for direct calls to inferior function calls."), _("\
+Show the timeout, for direct calls to inferior function calls."), _("\
+If running on a target that supports, and is running in, async mode\n\
+then this timeout is used for any inferior function calls triggered\n\
+directly from the prompt, i.e. from a 'call' or 'print' command.  The\n\
+timeout is specified in seconds."),
+			    nullptr,
+			    show_direct_call_timeout,
+			    &setlist, &showlist);
+
+  add_setshow_uinteger_cmd ("indirect-call-timeout", no_class,
+			    &indirect_call_timeout, _("\
+Set the timeout, for indirect calls to inferior function calls."), _("\
+Show the timeout, for indirect calls to inferior function calls."), _("\
+If running on a target that supports, and is running in, async mode\n\
+then this timeout is used for any inferior function calls triggered\n\
+indirectly, i.e. being made as part of a breakpoint, or watchpoint,\n\
+condition expression.  The timeout is specified in seconds."),
+			    nullptr,
+			    show_indirect_call_timeout,
+			    &setlist, &showlist);
+
   add_setshow_boolean_cmd
     ("infcall", class_maintenance, &debug_infcall,
      _("Set inferior call debugging."),
diff --git a/gdb/testsuite/gdb.base/help.exp b/gdb/testsuite/gdb.base/help.exp
index 87919a819ab..504bf90cc15 100644
--- a/gdb/testsuite/gdb.base/help.exp
+++ b/gdb/testsuite/gdb.base/help.exp
@@ -121,7 +121,7 @@ gdb_test "help info bogus-gdb-command" "Undefined info command: \"bogus-gdb-comm
 gdb_test "help gotcha" "Undefined command: \"gotcha\"\.  Try \"help\"\."
 
 # Test apropos regex.
-gdb_test "apropos \\\(print\[\^\[ bsiedf\\\".-\]\\\)" "handle -- Specify how to handle signals\."
+gdb_test "apropos \\\(print\[\^\[ bsiedf\\\"'.-\]\\\)" "handle -- Specify how to handle signals\."
 # Test apropos >1 word string.
 gdb_test "apropos handle signal" "handle -- Specify how to handle signals\."
 # Test apropos apropos.
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.c b/gdb/testsuite/gdb.base/infcall-timeout.c
new file mode 100644
index 00000000000..12774ca2599
--- /dev/null
+++ b/gdb/testsuite/gdb.base/infcall-timeout.c
@@ -0,0 +1,36 @@
+/* Copyright 2022-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 <unistd.h>
+
+/* This function is called from GDB.  */
+int
+function_that_never_returns ()
+{
+  while (1)
+    sleep (1);
+
+  return 0;
+}
+
+int
+main ()
+{
+  alarm (300);
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.exp b/gdb/testsuite/gdb.base/infcall-timeout.exp
new file mode 100644
index 00000000000..729d8d8734a
--- /dev/null
+++ b/gdb/testsuite/gdb.base/infcall-timeout.exp
@@ -0,0 +1,83 @@
+# Copyright 2022-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/>.
+
+# Test GDB's direct-call-timeout setting, that is, ensure that if an
+# inferior function call, invoked from e.g. a 'print' command, takes
+# too long, then GDB can interrupt it, and return control to the user.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug}] == -1 } {
+    return
+}
+
+# Start GDB according to TARGET_ASYNC and TARGET_NON_STOP, then adjust
+# the direct-call-timeout, and make an inferior function call that
+# will never return.  GDB should eventually timeout and stop the
+# inferior.
+proc_with_prefix run_test { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if {![runto_main]} {
+	return
+    }
+
+    gdb_test_no_output "set direct-call-timeout 5"
+
+    # When non-stop mode is off we get slightly different output from GDB.
+    if { ([target_info gdb_protocol] == "remote"
+	  || [target_info gdb_protocol] == "extended-remote")
+	 && !$target_non_stop } {
+	set stopped_line_pattern "Program received signal SIGINT, Interrupt\\."
+    } else {
+	set stopped_line_pattern "Program stopped\\."
+    }
+
+    gdb_test "print function_that_never_returns ()" \
+	[multi_line \
+	     $stopped_line_pattern \
+	     ".*" \
+	     "The program being debugged timed out while in a function called from GDB\\." \
+	     "GDB remains in the frame where the timeout occurred\\." \
+	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(function_that_never_returns\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+
+    gdb_test "bt" ".* function_that_never_returns .*<function called from gdb>.*"
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+
+    if { !$target_async } {
+	# GDB can't timeout while waiting for a thread if the target
+	# runs with async-mode turned off; once the target is running
+	# GDB is effectively blocked until the target stops for some
+	# reason.
+	continue
+    }
+
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	run_test $target_async $target_non_stop
+    }
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
new file mode 100644
index 00000000000..4da4245746e
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
@@ -0,0 +1,169 @@
+/* This testcase is part of GDB, the GNU debugger.
+
+   Copyright 2022-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 <stdio.h>
+#include <pthread.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <semaphore.h>
+
+#define NUM_THREADS 5
+
+/* Semaphores, used to track when threads have started, and to control
+   when the threads finish.  */
+sem_t startup_semaphore;
+sem_t finish_semaphore;
+sem_t thread_1_semaphore;
+sem_t thread_2_semaphore;
+
+/* Mutex to control when the first worker thread hit a breakpoint
+   location.  */
+pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+
+/* Global variable to poke, just so threads have something to do.  */
+volatile int global_var = 0;
+
+int
+condition_func ()
+{
+  /* Let thread 2 run.  */
+  if (sem_post (&thread_2_semaphore) != 0)
+    abort ();
+
+  /* Wait for thread 2 to complete its actions.  */
+  if (sem_wait (&thread_1_semaphore) != 0)
+    abort ();
+
+  return 1;
+}
+
+void
+do_segfault ()
+{
+  volatile int *p = 0;
+  *p = 0;	/* Segfault here.  */
+}
+
+void *
+worker_func (void *arg)
+{
+  int tid = *((int *) arg);
+
+  /* Let the main thread know that this worker has started.  */
+  if (sem_post (&startup_semaphore) != 0)
+    abort ();
+
+  switch (tid)
+    {
+    case 0:
+      /* Wait for MUTEX to become available, then pass through the
+	 conditional breakpoint location.  */
+      if (pthread_mutex_lock (&mutex) != 0)
+	abort ();
+      global_var = 99;	/* Conditional breakpoint here.  */
+      if (pthread_mutex_unlock (&mutex) != 0)
+	abort ();
+      break;
+
+    case 1:
+      if (sem_wait (&thread_2_semaphore) != 0)
+	abort ();
+      do_segfault ();
+      if (sem_post (&thread_1_semaphore) != 0)
+	abort ();
+
+      /* Fall through.  */
+    default:
+      /* Wait until we are allowed to finish.  */
+      if (sem_wait (&finish_semaphore) != 0)
+	abort ();
+      break;
+    }
+}
+
+void
+stop_marker ()
+{
+  global_var = 99;	/* Stop marker.  */
+}
+
+/* The main program entry point.  */
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+  void *retval;
+
+  /* An alarm, just in case the thread deadlocks.  */
+  alarm (300);
+
+  /* Semaphore initialization.  */
+  if (sem_init (&startup_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&finish_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&thread_1_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&thread_2_semaphore, 0, 0) != 0)
+    abort ();
+
+  /* Lock MUTEX, this prevents the first worker thread from rushing ahead.  */
+  if (pthread_mutex_lock (&mutex) != 0)
+    abort ();
+
+  /* Worker thread creation.  */
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  /* Wait for every thread to start.  */
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      if (sem_wait (&startup_semaphore) != 0)
+	abort ();
+    }
+
+  /* Unlock the first thread so it can proceed.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  /* Wait for the first thread only.  */
+  pthread_join (threads[0], &retval);
+
+  /* Now post FINISH_SEMAPHORE to allow all the other threads to finish.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    sem_post (&finish_semaphore);
+
+  /* Now wait for the remaining threads to complete.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    pthread_join (threads[i], &retval);
+
+  /* Semaphore cleanup.  */
+  sem_destroy (&finish_semaphore);
+  sem_destroy (&startup_semaphore);
+  sem_destroy (&thread_1_semaphore);
+  sem_destroy (&thread_2_semaphore);
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
new file mode 100644
index 00000000000..3e74958589c
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
@@ -0,0 +1,157 @@
+# Copyright 2022-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 inferior calls executed from a breakpoint condition in
+# a multi-threaded program.
+#
+# This test has the inferior function call timeout, and checks how GDB
+# handles this situation.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "Conditional breakpoint here"]
+set final_bp_line [gdb_get_line_number "Stop marker"]
+set segfault_line [gdb_get_line_number "Segfault here"]
+
+# Setup GDB based on TARGET_ASYNC and TARGET_NON_STOP.  Setup some
+# breakpoints in the inferior, one of which has an inferior call
+# within its condition.
+#
+# Continue GDB, the breakpoint with inferior call will be hit, but the
+# inferior call will never return.  We expect GDB to timeout.
+#
+# The reason that the inferior call never completes is that a second
+# thread, on which the inferior call relies, either hits a breakpoint
+# (when OTHER_THREAD_BP is true), or crashes (when OTHER_THREAD_BP is
+# false).
+proc run_test { target_async target_non_stop other_thread_bp } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if {![runto_main]} {
+	return
+    }
+
+    # The default timeout for indirect inferior calls (e.g. inferior
+    # calls for conditional breakpoint expressions) is pretty high.
+    # We don't want the test to take too long, so reduce this.
+    #
+    # However, the test relies on a second thread hitting some event
+    # (either a breakpoint or signal) before this timeout expires.
+    #
+    # There is a chance that on a really slow system this might not
+    # happen, in which case the test might fail.
+    #
+    # However, we still allocate 5 seconds, which feels like it should
+    # be enough time in most cases, but maybe we need to do something
+    # smarter here?  Possibly we could have some initial run where the
+    # inferior doesn't timeout, but does perform the same interaction
+    # between threads, we could time that, and use that as the basis
+    # for this timeout.  For now though, we just hope 5 seconds is
+    # enough.
+    gdb_test_no_output "set indirect-call-timeout 5"
+
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (condition_func ())"
+    set bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		    "get number for conditional breakpoint"]
+
+    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
+    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			  "get number for final breakpoint"]
+
+    # The thread performing an inferior call relies on a second
+    # thread.  The second thread will segfault unless it hits a
+    # breakpoint first.  In either case the initial thread will not
+    # complete its inferior call.
+    if { $other_thread_bp } {
+	gdb_breakpoint "${::srcfile}:${::segfault_line}"
+	set segfault_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+				 "get number for segfault breakpoint"]
+    }
+
+    # When non-stop mode is off we get slightly different output from GDB.
+    if { ([target_info gdb_protocol] == "remote"
+	  || [target_info gdb_protocol] == "extended-remote")
+	 && !$target_non_stop} {
+	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" received signal SIGINT, Interrupt\\."
+    } else {
+	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\."
+    }
+
+    gdb_test "continue" \
+	[multi_line \
+	     $stopped_line_pattern \
+	     ".*" \
+	     "Error in testing condition for breakpoint ${bp_num}:" \
+	     "The program being debugged timed out while in a function called from GDB\\." \
+	     "GDB remains in the frame where the timeout occurred\\." \
+	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(condition_func\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."] \
+	"expected timeout waiting for inferior call to complete"
+
+    # Remember that other thread that either crashed (with a segfault)
+    # or hit a breakpoint?  Now that the inferior call has timed out,
+    # if we try to resume then we should see the pending event from
+    # that other thread.
+    if { $other_thread_bp } {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${segfault_bp_num}, do_segfault \[^\r\n\]+:${::segfault_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"] \
+	    "hit the segfault breakpoint"
+    } else {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "Thread ${::decimal} \"infcall-from-bp\" received signal SIGSEGV, Segmentation fault\\." \
+		 "\\\[Switching to Thread \[^\r\n\]+\\\]" \
+		 "${::hex} in do_segfault \\(\\) at \[^\r\n\]+:${::segfault_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"] \
+	    "hit the segfault"
+    }
+}
+
+foreach_with_prefix target_async {"on" "off" } {
+
+    if { !$target_async } {
+	# GDB can't timeout while waiting for a thread if the target
+	# runs with async-mode turned off; once the target is running
+	# GDB is effectively blocked until the target stops for some
+	# reason.
+	continue
+    }
+
+    foreach_with_prefix target_non_stop {"off" "on"} {
+	foreach_with_prefix other_thread_bp { true false } {
+	    run_test $target_async $target_non_stop $other_thread_bp
+	}
+    }
+}
-- 
2.25.4


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

* [PATCHv8 4/6] gdb/remote: avoid SIGINT after calling remote_target::stop
  2023-06-07 10:01             ` [PATCHv8 0/6] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                                 ` (2 preceding siblings ...)
  2023-06-07 10:01               ` [PATCHv8 3/6] gdb: add timeouts for inferior function calls Andrew Burgess
@ 2023-06-07 10:01               ` Andrew Burgess
  2023-07-07 17:18                 ` Pedro Alves
  2023-06-07 10:01               ` [PATCHv8 5/6] gdb: introduce unwind-on-timeout setting Andrew Burgess
                                 ` (3 subsequent siblings)
  7 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2023-06-07 10:01 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Currently, if the remote target is not running in non-stop mode, then,
when GDB calls remote_target::stop, we end up sending an interrupt
packet \x03 to the remote target.

If the user interrupts the inferior from the GDB prompt (e.g. by
typing Ctrl-c), then GDB calls remote_target::interrupt, which also
ends up sending the interrupt packet.

The problem here is that both of these mechanisms end up sending the
interrupt packet, which means, when the target stops with a SIGINT,
and this is reported back to GDB, we have no choice but to report this
to the user as a SIGINT stop event.

Now maybe this is the correct thing to do, after all the target has
been stopped with SIGINT.  However, this leads to an unfortunate
change in behaviour when comparing non-stop vs all-stop mode.

When running in non-stop mode, and remote_target::stop is called, the
target will be stopped with a vCont packet, and this stop is then
reported back to GDB as GDB_SIGNAL_0, this will cause GDB to print a
message like:

  Program stopped.

Or:

  Thread NN "binary name" stopped.

In contrast, when non-stop mode is off, we get messages like:

  Program received SIGINT, Segmentation fault.

Or:

  Thread NN "binary name" received SIGINT, Segmentation fault.

In this commit I propose making use of thread_info::stop_requested
within remote.c to know if the stop was triggered by GDB (and the
SIGINT should be hidden) or if the stop was a user interrupt, and the
SIGINT should be printed.

In remote_target::process_stop_reply if the inferior stopped with
SIGINT and the thread_info::stop_requested flag is set, then we change
the stop signal to GDB_SIGNAL_0.

Two of the tests added in the previous commit exposed this issue.  In
the previous commit the tests looked for either of the above
patterns.  In this commit I've updated these tests to only look for
the "stopped" based messages.

This commit is the reason why the previous commit took care to set the
thread_info::stop_requested flag in infcall.c.

Due to the changes to how get_remote_thread_info is now called in
remote.c, one of the overloads of get_remote_thread_info is no longer
used and can be deleted.
---
 gdb/remote.c                                  | 23 +++++++++----------
 gdb/testsuite/gdb.base/infcall-timeout.exp    | 11 +--------
 .../infcall-from-bp-cond-timeout.exp          | 11 +--------
 3 files changed, 13 insertions(+), 32 deletions(-)

diff --git a/gdb/remote.c b/gdb/remote.c
index 02ff3a12bdb..d50802bc4a0 100644
--- a/gdb/remote.c
+++ b/gdb/remote.c
@@ -2729,8 +2729,6 @@ remote_target::remote_add_inferior (bool fake_pid_p, int pid, int attached,
 }
 
 static remote_thread_info *get_remote_thread_info (thread_info *thread);
-static remote_thread_info *get_remote_thread_info (remote_target *target,
-						   ptid_t ptid);
 
 /* Add thread PTID to GDB's thread list.  Tag it as executing/running
    according to EXECUTING and RUNNING respectively.  If SILENT_P (or the
@@ -2870,15 +2868,6 @@ get_remote_thread_info (thread_info *thread)
   return gdb::checked_static_cast<remote_thread_info *> (thread->priv.get ());
 }
 
-/* Return PTID's private thread data, creating it if necessary.  */
-
-static remote_thread_info *
-get_remote_thread_info (remote_target *target, ptid_t ptid)
-{
-  thread_info *thr = target->find_thread (ptid);
-  return get_remote_thread_info (thr);
-}
-
 /* Call this function as a result of
    1) A halt indication (T packet) containing a thread id
    2) A direct query of currthread
@@ -8263,7 +8252,8 @@ remote_target::process_stop_reply (struct stop_reply *stop_reply,
 	}
 
       remote_notice_new_inferior (ptid, false);
-      remote_thread_info *remote_thr = get_remote_thread_info (this, ptid);
+      thread_info *tinfo = this->find_thread (ptid);
+      remote_thread_info *remote_thr = get_remote_thread_info (tinfo);
       remote_thr->core = stop_reply->core;
       remote_thr->stop_reason = stop_reply->stop_reason;
       remote_thr->watch_data_address = stop_reply->watch_data_address;
@@ -8276,6 +8266,15 @@ remote_target::process_stop_reply (struct stop_reply *stop_reply,
 	}
       else
 	{
+	  /* If this stop was actually requested by GDB then we can hide
+	     the SIGINT from the user.  */
+	  if (status->kind () == TARGET_WAITKIND_STOPPED
+	      && status->sig () == GDB_SIGNAL_INT)
+	    {
+	      if (tinfo->stop_requested)
+		status->set_stopped (GDB_SIGNAL_0);
+	    }
+
 	  /* If the target works in all-stop mode, a stop-reply indicates that
 	     all the target's threads stopped.  */
 	  for (thread_info *tp : all_non_exited_threads (this))
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.exp b/gdb/testsuite/gdb.base/infcall-timeout.exp
index 729d8d8734a..2af598e044d 100644
--- a/gdb/testsuite/gdb.base/infcall-timeout.exp
+++ b/gdb/testsuite/gdb.base/infcall-timeout.exp
@@ -44,18 +44,9 @@ proc_with_prefix run_test { target_async target_non_stop } {
 
     gdb_test_no_output "set direct-call-timeout 5"
 
-    # When non-stop mode is off we get slightly different output from GDB.
-    if { ([target_info gdb_protocol] == "remote"
-	  || [target_info gdb_protocol] == "extended-remote")
-	 && !$target_non_stop } {
-	set stopped_line_pattern "Program received signal SIGINT, Interrupt\\."
-    } else {
-	set stopped_line_pattern "Program stopped\\."
-    }
-
     gdb_test "print function_that_never_returns ()" \
 	[multi_line \
-	     $stopped_line_pattern \
+	     "Program stopped\\." \
 	     ".*" \
 	     "The program being debugged timed out while in a function called from GDB\\." \
 	     "GDB remains in the frame where the timeout occurred\\." \
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
index 3e74958589c..a94c6a58192 100644
--- a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
@@ -91,18 +91,9 @@ proc run_test { target_async target_non_stop other_thread_bp } {
 				 "get number for segfault breakpoint"]
     }
 
-    # When non-stop mode is off we get slightly different output from GDB.
-    if { ([target_info gdb_protocol] == "remote"
-	  || [target_info gdb_protocol] == "extended-remote")
-	 && !$target_non_stop} {
-	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" received signal SIGINT, Interrupt\\."
-    } else {
-	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\."
-    }
-
     gdb_test "continue" \
 	[multi_line \
-	     $stopped_line_pattern \
+	     "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\." \
 	     ".*" \
 	     "Error in testing condition for breakpoint ${bp_num}:" \
 	     "The program being debugged timed out while in a function called from GDB\\." \
-- 
2.25.4


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

* [PATCHv8 5/6] gdb: introduce unwind-on-timeout setting
  2023-06-07 10:01             ` [PATCHv8 0/6] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                                 ` (3 preceding siblings ...)
  2023-06-07 10:01               ` [PATCHv8 4/6] gdb/remote: avoid SIGINT after calling remote_target::stop Andrew Burgess
@ 2023-06-07 10:01               ` Andrew Burgess
  2023-06-07 10:01               ` [PATCHv8 6/6] gdb: rename unwindonsignal to unwind-on-signal Andrew Burgess
                                 ` (2 subsequent siblings)
  7 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-06-07 10:01 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

Now that inferior function calls can timeout (see the recent
introduction of direct-call-timeout and indirect-call-timeout), this
commit adds a new setting unwind-on-timeout.

This new setting is just like the existing unwindonsignal and
unwind-on-terminating-exception, but the new setting will cause GDB to
unwind the stack if an inferior function call times out.

The existing inferior function call timeout tests have been updated to
cover the new setting.
---
 gdb/NEWS                                      |  9 +++
 gdb/doc/gdb.texinfo                           | 25 ++++++--
 gdb/infcall.c                                 | 62 ++++++++++++++++---
 gdb/testsuite/gdb.base/infcall-timeout.exp    | 49 +++++++++++----
 .../infcall-from-bp-cond-timeout.exp          | 55 +++++++++++-----
 5 files changed, 160 insertions(+), 40 deletions(-)

diff --git a/gdb/NEWS b/gdb/NEWS
index 4ddc0a047f0..81eb270c5ae 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -129,6 +129,15 @@ show indirect-call-timeout
   ignored, GDB will wait indefinitely for an inferior function to
   complete, unless interrupted by the user using Ctrl-C.
 
+set unwind-on-timeout on|off
+show unwind-on-timeout
+  These commands control whether GDB should unwind the stack when a
+  timeout occurs during an inferior function call.  The default is
+  off, in which case the inferior will remain in the frame where the
+  timeout occurred.  When on, GDB will unwind the stack removing the
+  dummy frame that was added for the inferior call, and restoring the
+  inferior state to how it was before the inferior call started.
+
 * MI changes
 
 ** mi now reports 'no-history' as a stop reason when hitting the end of the
diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index f27ec719d11..4f2062ff7e2 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -20865,6 +20865,21 @@
 Show the current setting of stack unwinding in the functions called by
 @value{GDBN}.
 
+@item set unwind-on-timeout
+@kindex set unwind-on-timeout
+@cindex unwind stack in called functions when timing out
+@cindex call dummy stack unwinding on timeout.
+Set unwinding of the stack if a function called from @value{GDBN}
+times out.  If set to @code{off} (the default), @value{GDBN} stops in
+the frame where the timeout occurred.  If set to @code{on},
+@value{GDBN} unwinds the stack it created for the call and restores
+the context to what it was before the call.
+
+@item show unwind-on-timeout
+@kindex show unwind-on-timeout
+Show whether @value{GDBN} will unwind the stack if a function called
+from @value{GDBN} times out.
+
 @item set may-call-functions
 @kindex set may-call-functions
 @cindex disabling calling functions in the program
@@ -20896,11 +20911,11 @@
 
 If a called function is interrupted for any reason, including hitting
 a breakpoint, or triggering a watchpoint, and the stack is not unwound
-due to @code{set unwind-on-terminating-exception on} or @code{set
-unwindonsignal on} (@pxref{stack unwind settings}),
-then the dummy-frame, created by @value{GDBN} to facilitate the call
-to the program function, will be visible in the backtrace, for example
-frame @code{#3} in the following backtrace:
+due to @code{set unwind-on-terminating-exception on}, @code{set
+unwind-on-timeout on}, or @code{set unwindonsignal on} (@pxref{stack
+unwind settings}), then the dummy-frame, created by @value{GDBN} to
+facilitate the call to the program function, will be visible in the
+backtrace, for example frame @code{#3} in the following backtrace:
 
 @smallexample
 (@value{GDBP}) backtrace
diff --git a/gdb/infcall.c b/gdb/infcall.c
index 162659ca8e6..526be837248 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -218,6 +218,27 @@ show_unwind_on_terminating_exception_p (struct ui_file *file, int from_tty,
 	      value);
 }
 
+/* This boolean tells GDB what to do if an inferior function, called from
+   GDB, times out.  If true, GDB unwinds the stack and restores the context
+   to what it was before the call.  When false, GDB leaves the thread as it
+   is at the point of the timeout.
+
+   The default is to stop in the frame where the timeout occurred.  */
+
+static bool unwind_on_timeout_p = false;
+
+/* Implement 'show unwind-on-timeout'.  */
+
+static void
+show_unwind_on_timeout_p (struct ui_file *file, int from_tty,
+			  struct cmd_list_element *c, const char *value)
+{
+  gdb_printf (file,
+	      _("Unwinding of stack if a timeout occurs "
+		"while in a call dummy is %s.\n"),
+	      value);
+}
+
 /* Perform the standard coercions that are specified
    for arguments to be passed to C, Ada or Fortran functions.
 
@@ -1700,14 +1721,27 @@ When the function is done executing, GDB will silently stop."),
 	  /* A timeout results in a signal being sent to the inferior.  */
 	  gdb_assert (stopped_by_random_signal);
 
-	  /* Indentation is weird here.  A later patch is going to move the
-	    following block into an if/else, so I'm leaving the indentation
-	    here to minimise the later patch.
+	  if (unwind_on_timeout_p)
+	    {
+	      /* The user wants the context restored.  */
+
+	      /* We must get back to the frame we were before the
+		 dummy call.  */
+	      dummy_frame_pop (dummy_id, call_thread.get ());
 
-	    Also, the error message used below refers to 'set
-	    unwind-on-timeout' which doesn't exist yet.  This will be added
-	    in a later commit, I'm leaving this in for now to minimise the
-	    churn caused by the commit that adds unwind-on-timeout.  */
+	      /* We also need to restore inferior status to that before the
+		 dummy call.  */
+	      restore_infcall_control_state (inf_status.release ());
+
+	      error (_("\
+The program being debugged timed out while in a function called from GDB.\n\
+GDB has restored the context to what it was before the call.\n\
+To change this behavior use \"set unwind-on-timeout off\".\n\
+Evaluation of the expression containing the function\n\
+(%s) will be abandoned."),
+		     name.c_str ());
+	    }
+	  else
 	    {
 	      /* The user wants to stay in the frame where we stopped
 		 (default).  Discard inferior status, we're not at the same
@@ -1833,6 +1867,20 @@ The default is to unwind the frame."),
 			   show_unwind_on_terminating_exception_p,
 			   &setlist, &showlist);
 
+  add_setshow_boolean_cmd ("unwind-on-timeout", no_class,
+			   &unwind_on_timeout_p, _("\
+Set unwinding of stack if a timeout occurs while in a call dummy."), _("\
+Show unwinding of stack if a timeout occurs while in a call dummy."),
+			   _("\
+The unwind on timeout flag lets the user determine what gdb should do if\n\
+gdb times out while in a function called from gdb.  If set, gdb unwinds\n\
+the stack and restores the context to what it was before the call.  If\n\
+unset, gdb leaves the inferior in the frame where the timeout occurred.\n\
+The default is to stop in the frame where the timeout occurred."),
+			   NULL,
+			   show_unwind_on_timeout_p,
+			   &setlist, &showlist);
+
   add_setshow_uinteger_cmd ("direct-call-timeout", no_class,
 			    &direct_call_timeout, _("\
 Set the timeout, for direct calls to inferior function calls."), _("\
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.exp b/gdb/testsuite/gdb.base/infcall-timeout.exp
index 2af598e044d..1f47d143699 100644
--- a/gdb/testsuite/gdb.base/infcall-timeout.exp
+++ b/gdb/testsuite/gdb.base/infcall-timeout.exp
@@ -28,7 +28,11 @@ if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
 # the direct-call-timeout, and make an inferior function call that
 # will never return.  GDB should eventually timeout and stop the
 # inferior.
-proc_with_prefix run_test { target_async target_non_stop } {
+#
+# When UNWIND is "off" the inferior wil be left in the frame where the
+# timeout occurs, otherwise, when UNWIND is "on", GDB should unwind
+# back to the frame where the inferior call was made.
+proc_with_prefix run_test { target_async target_non_stop unwind } {
     save_vars { ::GDBFLAGS } {
 	append ::GDBFLAGS \
 	    " -ex \"maint set target-non-stop $target_non_stop\""
@@ -43,19 +47,36 @@ proc_with_prefix run_test { target_async target_non_stop } {
     }
 
     gdb_test_no_output "set direct-call-timeout 5"
+    gdb_test_no_output "set unwind-on-timeout $unwind"
+
+    if { $unwind } {
+	gdb_test "print function_that_never_returns ()" \
+	    [multi_line \
+		 "Program stopped\\." \
+		 ".*" \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB has restored the context to what it was before the call\\." \
+		 "To change this behavior use \"set unwind-on-timeout off\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(function_that_never_returns\\) will be abandoned\\."]
 
-    gdb_test "print function_that_never_returns ()" \
-	[multi_line \
-	     "Program stopped\\." \
-	     ".*" \
-	     "The program being debugged timed out while in a function called from GDB\\." \
-	     "GDB remains in the frame where the timeout occurred\\." \
-	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
-	     "Evaluation of the expression containing the function" \
-	     "\\(function_that_never_returns\\) will be abandoned\\." \
-	     "When the function is done executing, GDB will silently stop\\."]
+	gdb_test "bt" \
+	    "#0\\s+main \\(\\).*"
+    } else {
+	gdb_test "print function_that_never_returns ()" \
+	    [multi_line \
+		 "Program stopped\\." \
+		 ".*" \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB remains in the frame where the timeout occurred\\." \
+		 "To change this behavior use \"set unwind-on-timeout on\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(function_that_never_returns\\) will be abandoned\\." \
+		 "When the function is done executing, GDB will silently stop\\."]
 
-    gdb_test "bt" ".* function_that_never_returns .*<function called from gdb>.*"
+	gdb_test "bt" \
+	    ".* function_that_never_returns .*<function called from gdb>.*"
+    }
 }
 
 foreach_with_prefix target_async { "on" "off" } {
@@ -69,6 +90,8 @@ foreach_with_prefix target_async { "on" "off" } {
     }
 
     foreach_with_prefix target_non_stop { "on" "off" } {
-	run_test $target_async $target_non_stop
+	foreach_with_prefix unwind { "on" "off" } {
+	    run_test $target_async $target_non_stop $unwind
+	}
     }
 }
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
index a94c6a58192..fedcad3d6c0 100644
--- a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
@@ -41,7 +41,12 @@ set segfault_line [gdb_get_line_number "Segfault here"]
 # thread, on which the inferior call relies, either hits a breakpoint
 # (when OTHER_THREAD_BP is true), or crashes (when OTHER_THREAD_BP is
 # false).
-proc run_test { target_async target_non_stop other_thread_bp } {
+#
+# When UNWIND is "on" GDB will unwind the thread which performed the
+# inferior function call back to the state where the inferior call was
+# made (when the inferior call times out).  Otherwise, when UNWIND is
+# "off", the inferior is left in the frame where the timeout occurred.
+proc run_test { target_async target_non_stop other_thread_bp unwind } {
     save_vars { ::GDBFLAGS } {
 	append ::GDBFLAGS " -ex \"maint set target-non-stop $target_non_stop\""
 	append ::GDBFLAGS " -ex \"maintenance set target-async ${target_async}\""
@@ -71,6 +76,7 @@ proc run_test { target_async target_non_stop other_thread_bp } {
     # for this timeout.  For now though, we just hope 5 seconds is
     # enough.
     gdb_test_no_output "set indirect-call-timeout 5"
+    gdb_test_no_output "set unwind-on-timeout $unwind"
 
     gdb_breakpoint \
 	"${::srcfile}:${::cond_bp_line} if (condition_func ())"
@@ -91,18 +97,35 @@ proc run_test { target_async target_non_stop other_thread_bp } {
 				 "get number for segfault breakpoint"]
     }
 
-    gdb_test "continue" \
-	[multi_line \
-	     "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\." \
-	     ".*" \
-	     "Error in testing condition for breakpoint ${bp_num}:" \
-	     "The program being debugged timed out while in a function called from GDB\\." \
-	     "GDB remains in the frame where the timeout occurred\\." \
-	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
-	     "Evaluation of the expression containing the function" \
-	     "\\(condition_func\\) will be abandoned\\." \
-	     "When the function is done executing, GDB will silently stop\\."] \
-	"expected timeout waiting for inferior call to complete"
+    if { $unwind } {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\." \
+		 ".*" \
+		 "Error in testing condition for breakpoint ${bp_num}:" \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB has restored the context to what it was before the call\\." \
+		 "To change this behavior use \"set unwind-on-timeout off\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(condition_func\\) will be abandoned\\." \
+		 "" \
+		 "Thread ${::decimal}\[^\r\n\]*hit Breakpoint ${bp_num}, \[^\r\n\]+" \
+		 "\[^\r\n\]+ Conditional breakpoint here\\. \[^\r\n\]+"] \
+	    "expected timeout waiting for inferior call to complete"
+    } else {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\." \
+		 ".*" \
+		 "Error in testing condition for breakpoint ${bp_num}:" \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB remains in the frame where the timeout occurred\\." \
+		 "To change this behavior use \"set unwind-on-timeout on\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(condition_func\\) will be abandoned\\." \
+		 "When the function is done executing, GDB will silently stop\\."] \
+	    "expected timeout waiting for inferior call to complete"
+    }
 
     # Remember that other thread that either crashed (with a segfault)
     # or hit a breakpoint?  Now that the inferior call has timed out,
@@ -141,8 +164,10 @@ foreach_with_prefix target_async {"on" "off" } {
     }
 
     foreach_with_prefix target_non_stop {"off" "on"} {
-	foreach_with_prefix other_thread_bp { true false } {
-	    run_test $target_async $target_non_stop $other_thread_bp
+	foreach_with_prefix unwind {"off" "on"} {
+	    foreach_with_prefix other_thread_bp { true false } {
+		run_test $target_async $target_non_stop $other_thread_bp $unwind
+	    }
 	}
     }
 }
-- 
2.25.4


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

* [PATCHv8 6/6] gdb: rename unwindonsignal to unwind-on-signal
  2023-06-07 10:01             ` [PATCHv8 0/6] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                                 ` (4 preceding siblings ...)
  2023-06-07 10:01               ` [PATCHv8 5/6] gdb: introduce unwind-on-timeout setting Andrew Burgess
@ 2023-06-07 10:01               ` Andrew Burgess
  2023-06-07 12:41                 ` Eli Zaretskii
  2023-07-04 11:20               ` [PATCHv8 0/6] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
  2023-12-02 10:52               ` [PATCHv9 0/5] " Andrew Burgess
  7 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2023-06-07 10:01 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

We now have unwind-on-timeout and unwind-on-terminating-exception, and
then the odd one out unwindonsignal.

I'm not a great fan of these squashed together command names, so in
this commit I propose renaming this to unwind-on-signal.

Obviously I've added the hidden alias unwindonsignal so any existing
GDB scripts will keep working.

There's one test that I've extended to test the alias works, but in
most of the other test scripts I've changed over to use the new name.

The docs are updated to reference the new name.
---
 gdb/NEWS                                      | 11 ++++++
 gdb/doc/gdb.texinfo                           | 16 ++++++---
 gdb/infcall.c                                 | 21 ++++++-----
 gdb/testsuite/gdb.base/callfuncs.exp          |  4 +--
 gdb/testsuite/gdb.base/infcall-failure.exp    |  4 +--
 gdb/testsuite/gdb.base/unwindonsignal.exp     | 36 +++++++++++++------
 gdb/testsuite/gdb.compile/compile-cplus.exp   |  2 +-
 gdb/testsuite/gdb.compile/compile.exp         |  2 +-
 gdb/testsuite/gdb.cp/gdb2495.exp              | 16 ++++-----
 gdb/testsuite/gdb.fortran/function-calls.exp  |  2 +-
 gdb/testsuite/gdb.mi/mi-syn-frame.exp         |  2 +-
 .../infcall-from-bp-cond-simple.exp           |  2 +-
 .../gdb.threads/thread-unwindonsignal.exp     |  8 ++---
 13 files changed, 83 insertions(+), 43 deletions(-)

diff --git a/gdb/NEWS b/gdb/NEWS
index 81eb270c5ae..c41ff0aad19 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -138,6 +138,17 @@ show unwind-on-timeout
   dummy frame that was added for the inferior call, and restoring the
   inferior state to how it was before the inferior call started.
 
+set unwind-on-signal on|off
+show unwind-on-signal
+  These new commands replaces the existing set/show unwindonsignal.  The
+  old command is maintained as an alias.
+
+* Changed commands
+
+set unwindonsignal on|off
+show unwindonsignal
+  These commands are now aliases for the new set/show unwind-on-signal.
+
 * MI changes
 
 ** mi now reports 'no-history' as a stop reason when hitting the end of the
diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index 4f2062ff7e2..7e00d88a83c 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -20819,7 +20819,7 @@
 It is possible for the function you call via the @code{print} or
 @code{call} command to generate a signal (e.g., if there's a bug in
 the function, or if you passed it incorrect arguments).  What happens
-in that case is controlled by the @code{set unwindonsignal} command.
+in that case is controlled by the @code{set unwind-on-signal} command.
 
 Similarly, with a C@t{++} program it is possible for the function you
 call via the @code{print} or @code{call} command to generate an
@@ -20833,7 +20833,8 @@
 
 @anchor{stack unwind settings}
 @table @code
-@item set unwindonsignal
+@item set unwind-on-signal
+@kindex set unwind-on-signal
 @kindex set unwindonsignal
 @cindex unwind stack in called functions
 @cindex call dummy stack unwinding
@@ -20844,11 +20845,18 @@
 default), @value{GDBN} stops in the frame where the signal was
 received.
 
-@item show unwindonsignal
+The command @code{set unwindonsignal} is an alias for this command,
+and is maintained for backward compatibility.
+
+@item show unwind-on-signal
+@kindex show unwind-on-signal
 @kindex show unwindonsignal
 Show the current setting of stack unwinding in the functions called by
 @value{GDBN}.
 
+The command @code{show unwindonsignal} is an alias for this command,
+and is maintained for backward compatibility.
+
 @item set unwind-on-terminating-exception
 @kindex set unwind-on-terminating-exception
 @cindex unwind stack in called functions with unhandled exceptions
@@ -20912,7 +20920,7 @@
 If a called function is interrupted for any reason, including hitting
 a breakpoint, or triggering a watchpoint, and the stack is not unwound
 due to @code{set unwind-on-terminating-exception on}, @code{set
-unwind-on-timeout on}, or @code{set unwindonsignal on} (@pxref{stack
+unwind-on-timeout on}, or @code{set unwind-on-signal on} (@pxref{stack
 unwind settings}), then the dummy-frame, created by @value{GDBN} to
 facilitate the call to the program function, will be visible in the
 backtrace, for example frame @code{#3} in the following backtrace:
diff --git a/gdb/infcall.c b/gdb/infcall.c
index 526be837248..0a800994e4d 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -1690,7 +1690,7 @@ When the function is done executing, GDB will silently stop."),
 	      error (_("\
 The program being debugged was signaled while in a function called from GDB.\n\
 GDB has restored the context to what it was before the call.\n\
-To change this behavior use \"set unwindonsignal off\".\n\
+To change this behavior use \"set unwind-on-signal off\".\n\
 Evaluation of the expression containing the function\n\
 (%s) will be abandoned."),
 		     name.c_str ());
@@ -1708,7 +1708,7 @@ Evaluation of the expression containing the function\n\
 	      error (_("\
 The program being debugged was signaled while in a function called from GDB.\n\
 GDB remains in the frame where the signal was received.\n\
-To change this behavior use \"set unwindonsignal on\".\n\
+To change this behavior use \"set unwind-on-signal on\".\n\
 Evaluation of the expression containing the function\n\
 (%s) will be abandoned.\n\
 When the function is done executing, GDB will silently stop."),
@@ -1840,17 +1840,22 @@ The default is to perform the conversion."),
 			   show_coerce_float_to_double_p,
 			   &setlist, &showlist);
 
-  add_setshow_boolean_cmd ("unwindonsignal", no_class,
-			   &unwind_on_signal_p, _("\
+  set_show_commands setshow_unwind_on_signal_cmds
+    = add_setshow_boolean_cmd ("unwind-on-signal", no_class,
+			       &unwind_on_signal_p, _("\
 Set unwinding of stack if a signal is received while in a call dummy."), _("\
 Show unwinding of stack if a signal is received while in a call dummy."), _("\
-The unwindonsignal lets the user determine what gdb should do if a signal\n\
+The unwind-on-signal lets the user determine what gdb should do if a signal\n\
 is received while in a function called from gdb (call dummy).  If set, gdb\n\
 unwinds the stack and restore the context to what as it was before the call.\n\
 The default is to stop in the frame where the signal was received."),
-			   NULL,
-			   show_unwind_on_signal_p,
-			   &setlist, &showlist);
+			       NULL,
+			       show_unwind_on_signal_p,
+			       &setlist, &showlist);
+  add_alias_cmd ("unwindonsignal", setshow_unwind_on_signal_cmds.set,
+		 no_class, 1, &setlist);
+  add_alias_cmd ("unwindonsignal", setshow_unwind_on_signal_cmds.show,
+		 no_class, 1, &showlist);
 
   add_setshow_boolean_cmd ("unwind-on-terminating-exception", no_class,
 			   &unwind_on_terminating_exception_p, _("\
diff --git a/gdb/testsuite/gdb.base/callfuncs.exp b/gdb/testsuite/gdb.base/callfuncs.exp
index 2c797a224a7..d9f63e944bf 100644
--- a/gdb/testsuite/gdb.base/callfuncs.exp
+++ b/gdb/testsuite/gdb.base/callfuncs.exp
@@ -46,7 +46,7 @@ proc do_function_calls {prototypes} {
 
     # If any of these calls segv we don't want to affect subsequent tests.
     # E.g., we want to ensure register values are restored.
-    gdb_test_no_output "set unwindonsignal on"
+    gdb_test_no_output "set unwind-on-signal on"
 
     gdb_test "p t_char_values(0,0)" " = 0"
     gdb_test "p t_char_values('a','b')" " = 1"
@@ -237,7 +237,7 @@ proc do_function_calls {prototypes} {
     	"call inferior func with struct - returns char *"
 
     # Restore default value.
-    gdb_test_no_output "set unwindonsignal off"
+    gdb_test_no_output "set unwind-on-signal off"
 }
 
 # Procedure to get current content of all registers.
diff --git a/gdb/testsuite/gdb.base/infcall-failure.exp b/gdb/testsuite/gdb.base/infcall-failure.exp
index 5ad179a089d..e2e71649dac 100644
--- a/gdb/testsuite/gdb.base/infcall-failure.exp
+++ b/gdb/testsuite/gdb.base/infcall-failure.exp
@@ -137,7 +137,7 @@ proc_with_prefix run_cond_hits_segfault_test { async_p non_stop_p } {
 	     "Error in testing condition for breakpoint ${bp_1_num}:" \
 	     "The program being debugged was signaled while in a function called from GDB\\." \
 	     "GDB remains in the frame where the signal was received\\." \
-	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "To change this behavior use \"set unwind-on-signal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(func_segfault\\) will be abandoned\\." \
 	     "When the function is done executing, GDB will silently stop\\."]
@@ -166,7 +166,7 @@ proc_with_prefix run_call_hits_segfault_test { async_p non_stop_p } {
 	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
 	     "The program being debugged was signaled while in a function called from GDB\\." \
 	     "GDB remains in the frame where the signal was received\\." \
-	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "To change this behavior use \"set unwind-on-signal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(func_segfault\\) will be abandoned\\." \
 	     "When the function is done executing, GDB will silently stop\\."]
diff --git a/gdb/testsuite/gdb.base/unwindonsignal.exp b/gdb/testsuite/gdb.base/unwindonsignal.exp
index 625b0c4db12..9c1b36e95bc 100644
--- a/gdb/testsuite/gdb.base/unwindonsignal.exp
+++ b/gdb/testsuite/gdb.base/unwindonsignal.exp
@@ -34,34 +34,50 @@ gdb_test "break stop_here" "Breakpoint \[0-9\]* at .*"
 gdb_test "continue" "Continuing.*Breakpoint \[0-9\]*, stop_here.*" \
     "continue to breakpoint at stop_here"
 
-# Turn on unwindonsignal.
-gdb_test_no_output "set unwindonsignal on" \
-	"setting unwindonsignal"
+# Turn on unwind-on-signal.
+gdb_test_no_output "set unwind-on-signal on" \
+	"setting unwind-on-signal"
 
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
 	"Unwinding of stack .* is on." \
-	"showing unwindonsignal"
+	"showing unwind-on-signal"
+
+# For backward compatibility we maintain a 'unwindonsignal' alias for
+# 'unwind-on-signal', check it now.
+gdb_test "show unwindonsignal" \
+    "Unwinding of stack .* is on\\." \
+    "showing unwindonsignal alias"
+
+gdb_test_no_output "set unwindonsignal off" \
+    "setting unwindonsignal alias to off"
+
+gdb_test "show unwind-on-signal" \
+    "Unwinding of stack .* is off\\." \
+    "showing unwind-on-signal after setting via alias"
+
+gdb_test_no_output "set unwindonsignal on" \
+    "setting unwindonsignal alias to on"
 
 # Call function (causing the program to get a signal), and see if gdb handles
 # it properly.
 if {[gdb_test "call gen_signal ()"  \
 	 "\[\r\n\]*The program being debugged was signaled.*" \
-	 "unwindonsignal, inferior function call signaled"] != 0} {
+	 "inferior function call signaled"] != 0} {
     return 0
 }
 
 # Verify the stack got unwound.
 gdb_test "bt" \
     "#0 *\[x0-9a-f in\]*stop_here \\(.*\\) at .*#1 *\[x0-9a-f in\]*main \\(.*\\) at .*" \
-	"unwindonsignal, stack unwound"
+	"stack unwound"
 
 # Verify the dummy frame got removed from dummy_frame_stack.
 gdb_test_multiple "maint print dummy-frames" \
-	"unwindonsignal, dummy frame removed" {
+	"unwind-on-signal, dummy frame removed" {
     -re "\[\r\n\]*.*stack=.*code=.*\[\r\n\]+$gdb_prompt $" {
-	fail "unwindonsignal, dummy frame removed"
+	fail $gdb_test_name
     }
     -re "\[\r\n\]+$gdb_prompt $" {
-	pass "unwindonsignal, dummy frame removed"
+	pass $gdb_test_name
     }
 }
diff --git a/gdb/testsuite/gdb.compile/compile-cplus.exp b/gdb/testsuite/gdb.compile/compile-cplus.exp
index 4e887daeb29..22eebb44953 100644
--- a/gdb/testsuite/gdb.compile/compile-cplus.exp
+++ b/gdb/testsuite/gdb.compile/compile-cplus.exp
@@ -129,7 +129,7 @@ gdb_test "return" "\r\n#0  main .*" "return" \
 	 "Make _gdb_expr\\(__gdb_regs\\*\\) return now\\? \\(y or n\\) " "y"
 gdb_test "info sym $infcall_pc" "\r\nNo symbol matches .*" "info sym not found"
 
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 gdb_test "compile code *(volatile int *) 0 = 0;" \
     "The program being debugged was signaled while in a function called from GDB\\.\r\nGDB has restored the context to what it was before the call\\.\r\n.*" \
     "compile code segfault second"
diff --git a/gdb/testsuite/gdb.compile/compile.exp b/gdb/testsuite/gdb.compile/compile.exp
index f3d87cd2605..8822aab2e81 100644
--- a/gdb/testsuite/gdb.compile/compile.exp
+++ b/gdb/testsuite/gdb.compile/compile.exp
@@ -159,7 +159,7 @@ gdb_test "return" "\r\n#0  main .*" "return" \
 	 "Make _gdb_expr return now\\? \\(y or n\\) " "y"
 gdb_test "info sym $infcall_pc" "\r\nNo symbol matches .*" "info sym not found"
 
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 gdb_test "compile code *(volatile int *) 0 = 0;" \
     "The program being debugged was signaled while in a function called from GDB\\.\r\nGDB has restored the context to what it was before the call\\.\r\n.*" \
     "compile code segfault second"
diff --git a/gdb/testsuite/gdb.cp/gdb2495.exp b/gdb/testsuite/gdb.cp/gdb2495.exp
index e3c0cca3175..d7985e5db48 100644
--- a/gdb/testsuite/gdb.cp/gdb2495.exp
+++ b/gdb/testsuite/gdb.cp/gdb2495.exp
@@ -98,29 +98,29 @@ if {![runto_main]} {
 # behaviour; it should not.  Test both on and off states.
 
 # Turn on unwind on signal behaviour.
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 
 # Check that it is turned on.
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
     "signal is received while in a call dummy is on.*" \
     "turn on unwind on signal"
 
 # Check to see if new behaviour interferes with
 # normal signal handling in inferior function calls.
 gdb_test "p exceptions.raise_signal(1)" \
-    "To change this behavior use \"set unwindonsignal off\".*" \
-    "check for unwindonsignal off message"
+    "To change this behavior use \"set unwind-on-signal off\".*" \
+    "check for unwind-on-signal off message"
 
 # And reverse - turn off again.
-gdb_test_no_output "set unwindonsignal off"
+gdb_test_no_output "set unwind-on-signal off"
 
 # Check that it is actually turned off.
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
     "signal is received while in a call dummy is off.*" \
     "turn off unwind on signal"
 
 # Check to see if new behaviour interferes with
 # normal signal handling in inferior function calls.
 gdb_test "p exceptions.raise_signal(1)" \
-    "To change this behavior use \"set unwindonsignal on\".*" \
-    "check for unwindonsignal on message"
+    "To change this behavior use \"set unwind-on-signal on\".*" \
+    "check for unwind-on-signal on message"
diff --git a/gdb/testsuite/gdb.fortran/function-calls.exp b/gdb/testsuite/gdb.fortran/function-calls.exp
index f9a1efc241f..c4d1f232576 100644
--- a/gdb/testsuite/gdb.fortran/function-calls.exp
+++ b/gdb/testsuite/gdb.fortran/function-calls.exp
@@ -44,7 +44,7 @@ if {![runto [gdb_get_line_number "post_init"]]} {
 }
 
 # Use inspired by gdb.base/callfuncs.exp.
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 
 # Baseline: function and subroutine call with no arguments.
 gdb_test "p no_arg()" " = .TRUE."
diff --git a/gdb/testsuite/gdb.mi/mi-syn-frame.exp b/gdb/testsuite/gdb.mi/mi-syn-frame.exp
index 40df312a1cc..1324226412c 100644
--- a/gdb/testsuite/gdb.mi/mi-syn-frame.exp
+++ b/gdb/testsuite/gdb.mi/mi-syn-frame.exp
@@ -94,7 +94,7 @@ mi_gdb_test "409-stack-list-frames 0 0" \
 # 
 
 mi_gdb_test "410-data-evaluate-expression bar()" \
-  ".*410\\^error,msg=\"The program being debugged was signaled while in a function called from GDB.\\\\nGDB remains in the frame where the signal was received.\\\\nTo change this behavior use \\\\\"set unwindonsignal on\\\\\".\\\\nEvaluation of the expression containing the function\\\\n\\(bar\\) will be abandoned.\\\\nWhen the function is done executing, GDB will silently stop.\"" \
+  ".*410\\^error,msg=\"The program being debugged was signaled while in a function called from GDB.\\\\nGDB remains in the frame where the signal was received.\\\\nTo change this behavior use \\\\\"set unwind-on-signal on\\\\\".\\\\nEvaluation of the expression containing the function\\\\n\\(bar\\) will be abandoned.\\\\nWhen the function is done executing, GDB will silently stop.\"" \
   "call inferior function which raises exception"
 
 mi_gdb_test "411-stack-list-frames" "411\\^done,stack=\\\[frame=\{level=\"0\",addr=\"$hex\",func=\"bar\",file=\".*mi-syn-frame.c\",fullname=\"${fullname_syntax}${srcfile}\",line=\"$decimal\",arch=\"$any\"},frame=\{level=\"1\",addr=\"$hex\",func=\"<function called from gdb>\"\},frame=\{level=\"2\",addr=\"$hex\",func=\"main\",file=\".*mi-syn-frame.c\",fullname=\"${fullname_syntax}${srcfile}\",line=\"$decimal\",arch=\"$any\"}.*\\\]" "backtrace from inferior function at exception"
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
index c46f8cdb981..26ce59d6335 100644
--- a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
@@ -173,7 +173,7 @@ proc_with_prefix run_bp_cond_segfaults { target_async target_non_stop } {
 	     "Error in testing condition for breakpoint ${bp_1_num}:" \
 	     "The program being debugged was signaled while in a function called from GDB\\." \
 	     "GDB remains in the frame where the signal was received\\." \
-	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "To change this behavior use \"set unwind-on-signal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(function_that_segfaults\\) will be abandoned\\." \
 	     "When the function is done executing, GDB will silently stop\\."]
diff --git a/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp b/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp
index 68a99f66f1c..a9cedc0c466 100644
--- a/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp
+++ b/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp
@@ -13,7 +13,7 @@
 # You should have received a copy of the GNU General Public License
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-# Test use of unwindonsignal when a hand function call that gets interrupted
+# Test use of unwind-on-signal when a hand function call that gets interrupted
 # by a signal in another thread.
 
 set NR_THREADS 4
@@ -49,12 +49,12 @@ gdb_test "continue" \
 # We want the main thread (hand_call_with_signal) and
 # thread 1 (sigabrt_handler) to both run.
 
-# Do turn on unwindonsignal.
+# Do turn on unwind-on-signal.
 # We want to test gdb handling of the current thread changing when
 # unwindonsignal is in effect.
-gdb_test_no_output "set unwindonsignal on" \
+gdb_test_no_output "set unwind-on-signal on" \
 	"setting unwindonsignal"
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
 	"Unwinding of stack .* is on." \
 	"showing unwindonsignal"
 
-- 
2.25.4


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

* Re: [PATCHv8 6/6] gdb: rename unwindonsignal to unwind-on-signal
  2023-06-07 10:01               ` [PATCHv8 6/6] gdb: rename unwindonsignal to unwind-on-signal Andrew Burgess
@ 2023-06-07 12:41                 ` Eli Zaretskii
  2023-06-07 14:29                   ` Andrew Burgess
  0 siblings, 1 reply; 202+ messages in thread
From: Eli Zaretskii @ 2023-06-07 12:41 UTC (permalink / raw)
  To: Andrew Burgess; +Cc: gdb-patches

> Cc: Andrew Burgess <aburgess@redhat.com>
> Date: Wed,  7 Jun 2023 11:01:18 +0100
> From: Andrew Burgess via Gdb-patches <gdb-patches@sourceware.org>
> 
> We now have unwind-on-timeout and unwind-on-terminating-exception, and
> then the odd one out unwindonsignal.
> 
> I'm not a great fan of these squashed together command names, so in
> this commit I propose renaming this to unwind-on-signal.
> 
> Obviously I've added the hidden alias unwindonsignal so any existing
> GDB scripts will keep working.
> 
> There's one test that I've extended to test the alias works, but in
> most of the other test scripts I've changed over to use the new name.
> 
> The docs are updated to reference the new name.

If the only changes in the documentation are mechanical renaming, can
I blindly approve the documentation part?  Or would you prefer a real
review?

Thanks.

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

* Re: [PATCHv8 6/6] gdb: rename unwindonsignal to unwind-on-signal
  2023-06-07 12:41                 ` Eli Zaretskii
@ 2023-06-07 14:29                   ` Andrew Burgess
  2023-06-07 15:31                     ` Eli Zaretskii
  0 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2023-06-07 14:29 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: gdb-patches

Eli Zaretskii <eliz@gnu.org> writes:

>> Cc: Andrew Burgess <aburgess@redhat.com>
>> Date: Wed,  7 Jun 2023 11:01:18 +0100
>> From: Andrew Burgess via Gdb-patches <gdb-patches@sourceware.org>
>> 
>> We now have unwind-on-timeout and unwind-on-terminating-exception, and
>> then the odd one out unwindonsignal.
>> 
>> I'm not a great fan of these squashed together command names, so in
>> this commit I propose renaming this to unwind-on-signal.
>> 
>> Obviously I've added the hidden alias unwindonsignal so any existing
>> GDB scripts will keep working.
>> 
>> There's one test that I've extended to test the alias works, but in
>> most of the other test scripts I've changed over to use the new name.
>> 
>> The docs are updated to reference the new name.
>
> If the only changes in the documentation are mechanical renaming, can
> I blindly approve the documentation part?  Or would you prefer a real
> review?

Eli,

Apologies, I forgot to add text to these emails to indicate that you
have already approved all of the doc changes:

[6/6] https://sourceware.org/pipermail/gdb-patches/2023-January/195874.html
[5/6] https://sourceware.org/pipermail/gdb-patches/2023-January/195873.html
[3/6] https://sourceware.org/pipermail/gdb-patches/2023-January/196462.html

Sorry for wasting your time here.  I'm going to go though and add your
reviewed-by tag to each commit message now.  I should have done this
much sooner.

Thanks,
Andrew


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

* Re: [PATCHv8 6/6] gdb: rename unwindonsignal to unwind-on-signal
  2023-06-07 14:29                   ` Andrew Burgess
@ 2023-06-07 15:31                     ` Eli Zaretskii
  0 siblings, 0 replies; 202+ messages in thread
From: Eli Zaretskii @ 2023-06-07 15:31 UTC (permalink / raw)
  To: Andrew Burgess; +Cc: gdb-patches

> From: Andrew Burgess <aburgess@redhat.com>
> Cc: gdb-patches@sourceware.org
> Date: Wed, 07 Jun 2023 15:29:58 +0100
> 
> Eli Zaretskii <eliz@gnu.org> writes:
> 
> > If the only changes in the documentation are mechanical renaming, can
> > I blindly approve the documentation part?  Or would you prefer a real
> > review?
> 
> Eli,
> 
> Apologies, I forgot to add text to these emails to indicate that you
> have already approved all of the doc changes:
> 
> [6/6] https://sourceware.org/pipermail/gdb-patches/2023-January/195874.html
> [5/6] https://sourceware.org/pipermail/gdb-patches/2023-January/195873.html
> [3/6] https://sourceware.org/pipermail/gdb-patches/2023-January/196462.html

OK, great.

> Sorry for wasting your time here.

You didn't waste any of my time, I asked before investing any effort
in a review.  No sweat, really.

> I'm going to go though and add your reviewed-by tag to each commit
> message now.  I should have done this much sooner.

Thanks.

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

* Re: [PATCHv8 0/6] Infcalls from B/P conditions in multi-threaded inferiors
  2023-06-07 10:01             ` [PATCHv8 0/6] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                                 ` (5 preceding siblings ...)
  2023-06-07 10:01               ` [PATCHv8 6/6] gdb: rename unwindonsignal to unwind-on-signal Andrew Burgess
@ 2023-07-04 11:20               ` Andrew Burgess
  2023-12-02 10:52               ` [PATCHv9 0/5] " Andrew Burgess
  7 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-07-04 11:20 UTC (permalink / raw)
  To: gdb-patches

Andrew Burgess <aburgess@redhat.com> writes:

I'm thinking about merging this series possibly later this week, or
early next.  I didn't get this on the list early enough for GDB 13, and
I'd like to see this land for GDB 14.

If there are any objections then, of course, I'll hold off merging this.

Thanks,
Andrew

> In v8:
>
>   - Rebased onto current upstream/master and retested.
>
>   - Addressed feedback from Baris on patches 1, 2, 3, & 4.  This was
>     mostly minor stuff, comment typos and some improvements to the
>     testsuite.  There was one real (but minor) GDB change in patch 4.
>
> In v7:
>
>   - Rebased onto current upstream/master, fixed use of
>     find_thread_ptid which is now a process_stratum_target method,
>
>   - Retested, with no regressions seen.
>
> In v6:
>
>   - Pushed the 5 initial patches.  These were the smaller fixes, and,
>     I felt were pretty obvious fixes.  I'm sure folk will raise
>     objections if they disagree.
>
>   - Of the remaining patches, #1 to #5 really needs review before they
>     can be merged.  Patch #6 is an obvious cleanup once the first five
>     have been merged.
>
>   - I've rebased onto current HEAD of master, there's no significant
>     changes.
>
>   - All other documentation changes have been reviewed and approved.
>
> In v5:
>
>   - Rebased to current HEAD of master, minor merge conflict resolved.
>     No other code or documentation changes.
>
>   - First patch, which was pure documentation, has now been merged.
>
>   - All other documentation changes have been reviewed and approved.
>
> In v4:
>
>   - I believe all the docs changes have been reviewed and approved by Eli,
>
>   - Rebased onto current master,
>
>   - Dropped patch #2 from the V3 series,
>
>   - I have addressed all the issues Baris pointed out, including the
>     fixes for the patch #9 ('gdb: add timeouts for inferior function
>     calls'), which I forgot to do in V3.
>
> In v3:
>
>   - Updates for review feedback, biggest changes in #10 and #11, but
>     minor changes to most patches.
>
> In V2:
>
>   - Rebased onto something closer to HEAD of master,
>
>   - Patches #1, #2, #12, and #13 are new in this series,
>
>   - Patches #3 to #9, and #11 are unchanged since their V1 iteration,
>
>   - Patches #10 has changed slightly in implementation since v1, and
>     the docs have been significantly updated.
>
> ---
>
> Andrew Burgess (6):
>   Revert "gdb: remove unnecessary parameter wait_ptid from
>     do_target_wait"
>   gdb: fix b/p conditions with infcalls in multi-threaded inferiors
>   gdb: add timeouts for inferior function calls
>   gdb/remote: avoid SIGINT after calling remote_target::stop
>   gdb: introduce unwind-on-timeout setting
>   gdb: rename unwindonsignal to unwind-on-signal
>
>  gdb/NEWS                                      |  38 +++
>  gdb/breakpoint.c                              |   2 +
>  gdb/doc/gdb.texinfo                           | 105 ++++++-
>  gdb/gdbthread.h                               |   3 +
>  gdb/infcall.c                                 | 296 +++++++++++++++++-
>  gdb/infrun.c                                  |  70 ++++-
>  gdb/infrun.h                                  |   3 +-
>  gdb/remote.c                                  |  23 +-
>  gdb/testsuite/gdb.base/callfuncs.exp          |   4 +-
>  gdb/testsuite/gdb.base/help.exp               |   2 +-
>  gdb/testsuite/gdb.base/infcall-failure.exp    |   4 +-
>  gdb/testsuite/gdb.base/infcall-timeout.c      |  36 +++
>  gdb/testsuite/gdb.base/infcall-timeout.exp    |  97 ++++++
>  gdb/testsuite/gdb.base/unwindonsignal.exp     |  36 ++-
>  gdb/testsuite/gdb.compile/compile-cplus.exp   |   2 +-
>  gdb/testsuite/gdb.compile/compile.exp         |   2 +-
>  gdb/testsuite/gdb.cp/gdb2495.exp              |  16 +-
>  gdb/testsuite/gdb.fortran/function-calls.exp  |   2 +-
>  gdb/testsuite/gdb.mi/mi-syn-frame.exp         |   2 +-
>  .../infcall-from-bp-cond-other-thread-event.c | 135 ++++++++
>  ...nfcall-from-bp-cond-other-thread-event.exp | 174 ++++++++++
>  .../gdb.threads/infcall-from-bp-cond-simple.c |  89 ++++++
>  .../infcall-from-bp-cond-simple.exp           | 235 ++++++++++++++
>  .../gdb.threads/infcall-from-bp-cond-single.c | 139 ++++++++
>  .../infcall-from-bp-cond-single.exp           | 117 +++++++
>  .../infcall-from-bp-cond-timeout.c            | 169 ++++++++++
>  .../infcall-from-bp-cond-timeout.exp          | 173 ++++++++++
>  .../gdb.threads/thread-unwindonsignal.exp     |   8 +-
>  28 files changed, 1902 insertions(+), 80 deletions(-)
>  create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.c
>  create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.exp
>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
>
>
> base-commit: baab375361c365afee2577c94cbbd3fdd443d6da
> -- 
> 2.25.4


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

* Re: [PATCHv5 01/11] gdb: include breakpoint number in testing condition error message
  2023-03-16 17:36         ` [PATCHv5 01/11] gdb: include breakpoint number in testing condition error message Andrew Burgess
  2023-04-03 13:50           ` Andrew Burgess
@ 2023-07-07 12:08           ` Pedro Alves
  2023-07-07 15:43             ` Andrew Burgess
  1 sibling, 1 reply; 202+ messages in thread
From: Pedro Alves @ 2023-07-07 12:08 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

Hi,

On 2023-03-16 17:36, Andrew Burgess via Gdb-patches wrote:

> So, in this commit, in preparation for the later commits, I propose to
> change the 'Error in testing breakpoint condition:' line to this:
> 
>   Error in testing condition for breakpoint NUMBER:
> 
> where NUMBER will be filled in as appropriate.  Here's the first
> example with the updated error:
> 
>   (gdb) break foo if (*(int *) 0) == 0
>   Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
>   (gdb) r
>   Starting program: /tmp/bpcond
>   Error in testing condition for breakpoint 1:
>   Cannot access memory at address 0x0
> 
>   Breakpoint 1, foo () at bpcond.c:11
>   11	  int a = 32;
>   (gdb)
> 

Reading this, I was thinking that we should print the breakpoint location number
as well.  We do print it when presenting breakpoint stops nowadays, like:

 (top-gdb) b printf
 Breakpoint 3 at 0xee680 (2 locations)
 (top-gdb) r
 ...
 Breakpoint 3.1, ui_file::printf ...
 ...

Did you consider that and decided against?  I didn't find any mention of it in previous
discussions.


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

* Re: [PATCHv5 03/11] gdbserver: allow agent expressions to fail with invalid memory access
  2023-03-16 17:36         ` [PATCHv5 03/11] gdbserver: allow agent expressions to fail with invalid memory access Andrew Burgess
  2023-04-03 13:50           ` Andrew Burgess
@ 2023-07-07 12:25           ` Pedro Alves
  2023-07-07 16:28             ` Andrew Burgess
  1 sibling, 1 reply; 202+ messages in thread
From: Pedro Alves @ 2023-07-07 12:25 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

On 2023-03-16 17:36, Andrew Burgess via Gdb-patches wrote:
> This commit extends gdbserver to take account of a failed memory
> access from agent_mem_read, and to return a new eval_result_type
> expr_eval_invalid_memory_access.
> 
> I have only updated the agent_mem_read calls related directly to
> reading memory, I have not updated any of the calls related to
> tracepoint data collection.  This is just because I'm not familiar
> with that area of gdb/gdbserver, and I don't want to break anything,
> so leaving the existing behaviour untouched seems like the safest
> approach.

I think this should update the gdbserver/tracepoint.cc:eval_result_names array at least,
though.  Otherwise I think a memory error during collection is going to trigger undefined
behavior, crash if we're lucky.


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

* Re: [PATCHv5 05/11] gdb: don't always print breakpoint location after failed condition check
  2023-03-16 17:37         ` [PATCHv5 05/11] gdb: don't always print breakpoint location after failed condition check Andrew Burgess
  2023-04-03 13:51           ` Andrew Burgess
@ 2023-07-07 15:20           ` Pedro Alves
  2023-07-07 15:24             ` Pedro Alves
  1 sibling, 1 reply; 202+ messages in thread
From: Pedro Alves @ 2023-07-07 15:20 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

Hi!

On 2023-03-16 17:37, Andrew Burgess via Gdb-patches wrote:

> The user can still find the number of the breakpoint that triggered
> the initial stop in this line:
> 
>   Error in testing condition for breakpoint 1:
> 
> But there's now only one stop reason reported, the SIGSEGV, which I
> think is much clearer.

That's reasonable.

> @@ -5545,6 +5546,17 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
>  	      exception_fprintf (gdb_stderr, ex,
>  				 "Error in testing condition for breakpoint %d:\n",
>  				 b->number);
> +
> +	      /* If the pc value changed as a result of evaluating the
> +		 condition then we probably stopped within an inferior
> +		 function call due to some unexpected stop, e.g. the thread
> +		 hit another breakpoint, or the thread received an
> +		 unexpected signal.  In this case we don't want to also
> +		 print the information about this breakpoint.  */
> +	      CORE_ADDR pc_after_check
> +		= get_frame_pc (get_selected_frame (nullptr));
> +	      if (pc_before_check != pc_after_check)
> +		bs->print = 0;


Not a great fan of this PC heuristic, though.  We can reuse the logic stop_id logic used by normal_stop
to detect whether a hook-stop changed the execution context.  See patch below.  It passes the
whole testsuite cleanly for me (on native, that's all I tested).  Note, it adds
thread_state to struct stop_context, because in run_inferior_call, the thread for which we are
saving the context for is THREAD_RUNNING.  In this particular scenario, probably only comparing
the last stop_id would suffice, but, it doesn't hurt to compare the whole context.  It can
actually be a bit better, in case e.g., the exception was due to the remote target connection
dropping, in which case the current get_selected_frame call would throw, while with this
approach, we'll just detect that the context changed.  (haven't actually tried that scenario,
just going by inspection.)

The other thing that I think we could/should do better is best seen with MI:

Before your change, we had:

 *stopped,reason="breakpoint-hit",disp="keep",bkptno="3",frame={addr="0x0000555555555149",func="func_bp",args=[],file="gdb.base/infcall-failure.c",fullname="gdb.base/infcall-failure.c",line="32",arch="i386:x86-64"},thread-id="1",stopped-threads="all",core="2"
 &"Error in testing condition for breakpoint 2:\n"
 &"The program being debugged stopped while in a function called from GDB.\n"
 &"Evaluation of the expression containing the function\n"
 &"(func_bp) will be abandoned.\n"
 &"When the function is done executing, GDB will silently stop.\n"
 =breakpoint-modified,bkpt={number="2",type="breakpoint",disp="keep",enabled="y",addr="0x000055555555515d",func="foo",file="gdb.base/infcall-failure.c",fullname="gdb.base/infcall-failure.c",line="39",thread-groups=["i1"],cond="(func_bp ())",times="1",original-location="infcall-failure.c:39"}
 ~"\n"
 ~"Breakpoint 2, func_bp () at gdb.base/infcall-failure.c:32\n"
 ~"32\t  int res = 0;\t/* Second breakpoint.  */\n"
 *stopped,reason="breakpoint-hit",disp="keep",bkptno="2",frame={addr="0x0000555555555149",func="func_bp",args=[],file="gdb.base/infcall-failure.c",fullname="gdb.base/infcall-failure.c",line="32",arch="i386:x86-64"},thread-id="1",stopped-threads="all",core="2"
 (gdb) 

Note the last *stopped for the breakpoint we tried to evaluate the condition.

While in current master (with your patch merged), we have:

 *stopped,reason="breakpoint-hit",disp="keep",bkptno="3",frame={addr="0x0000555555555149",func="func_bp",args=[],file="gdb.base/infcall-failure.c",fullname="gdb.base/infcall-failure.c",line="32",arch="i386:x86-64"},thread-id="1",stopped-threads="all",core="1"
 &"Error in testing condition for breakpoint 2:\n"
 &"The program being debugged stopped while in a function called from GDB.\n"
 &"Evaluation of the expression containing the function\n"
 &"(func_bp) will be abandoned.\n"
 &"When the function is done executing, GDB will silently stop.\n"
 =breakpoint-modified,bkpt={number="2",type="breakpoint",disp="keep",enabled="y",addr="0x000055555555515d",func="foo",file="gdb.base/infcall-failure.c",fullname="gdb.base/infcall-failure.c",line="39",thread-groups=["i1"],cond="(func_bp ())",times="1",original-location="infcall-failure.c:39"}
 *stopped                                 <<<<<<<<<<<<< here
 (gdb) 

Note the "*stopped" without any context in the "<<<< here" line.

I'd think the second *stopped shouldn't even be there at all, following the
logic used to remove the stop from the CLI.

Maybe we should try moving or copying this "don't report this stop" logic to
fetch_inferior_event, to avoid calling the second normal_stop at all.
I gave it a quick try, but what I tried without thinking much about it
just hung GDB.  I didn't dig too much as I want to move on to review the rest
of your series.

From e8584146cfbb372214097a519c5a2738a72fbb4d Mon Sep 17 00:00:00 2001
From: Pedro Alves <pedro@palves.net>
Date: Fri, 7 Jul 2023 14:21:18 +0100
Subject: [PATCH] stop_context/stop_id instead of PC

Change-Id: I3e70c3fdb95b9bc4996f6c0c18431a3df48cc3a6
---
 gdb/breakpoint.c | 18 ++++++++----------
 gdb/infrun.c     | 30 ++++--------------------------
 gdb/infrun.h     | 27 +++++++++++++++++++++++++++
 3 files changed, 39 insertions(+), 36 deletions(-)

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index da6c8de9d14..f791a74a246 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -5535,9 +5535,11 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
 	  else
 	    within_current_scope = false;
 	}
-      CORE_ADDR pc_before_check = get_frame_pc (get_selected_frame (nullptr));
+
       if (within_current_scope)
 	{
+	  stop_context saved_context;
+
 	  try
 	    {
 	      condition_result = breakpoint_cond_eval (cond);
@@ -5548,15 +5550,11 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
 				 "Error in testing condition for breakpoint %d:\n",
 				 b->number);
 
-	      /* If the pc value changed as a result of evaluating the
-		 condition then we probably stopped within an inferior
-		 function call due to some unexpected stop, e.g. the thread
-		 hit another breakpoint, or the thread received an
-		 unexpected signal.  In this case we don't want to also
-		 print the information about this breakpoint.  */
-	      CORE_ADDR pc_after_check
-		= get_frame_pc (get_selected_frame (nullptr));
-	      if (pc_before_check != pc_after_check)
+	      /* If we stopped within an inferior function call,
+		 e.g. the thread hit another breakpoint, or the thread
+		 received an unexpected signal, don't print the
+		 information about this breakpoint.  */
+	      if (saved_context.changed ())
 		bs->print = 0;
 	    }
 	}
diff --git a/gdb/infrun.c b/gdb/infrun.c
index 58da1cef29e..3dd24fccf6e 100644
--- a/gdb/infrun.c
+++ b/gdb/infrun.c
@@ -8755,31 +8755,6 @@ maybe_remove_breakpoints (void)
     }
 }
 
-/* The execution context that just caused a normal stop.  */
-
-struct stop_context
-{
-  stop_context ();
-
-  DISABLE_COPY_AND_ASSIGN (stop_context);
-
-  bool changed () const;
-
-  /* The stop ID.  */
-  ULONGEST stop_id;
-
-  /* The event PTID.  */
-
-  ptid_t ptid;
-
-  /* If stopp for a thread event, this is the thread that caused the
-     stop.  */
-  thread_info_ref thread;
-
-  /* The inferior that caused the stop.  */
-  int inf_num;
-};
-
 /* Initializes a new stop context.  If stopped for a thread event, this
    takes a strong reference to the thread.  */
 
@@ -8794,7 +8769,10 @@ stop_context::stop_context ()
       /* Take a strong reference so that the thread can't be deleted
 	 yet.  */
       thread = thread_info_ref::new_reference (inferior_thread ());
+      thread_state = thread->state;
     }
+  else
+    thread_state = THREAD_EXITED;
 }
 
 /* Return true if the current context no longer matches the saved stop
@@ -8807,7 +8785,7 @@ stop_context::changed () const
     return true;
   if (inf_num != current_inferior ()->num)
     return true;
-  if (thread != nullptr && thread->state != THREAD_STOPPED)
+  if (thread != nullptr && thread->state != thread_state)
     return true;
   if (get_stop_id () != stop_id)
     return true;
diff --git a/gdb/infrun.h b/gdb/infrun.h
index a343d27f72d..b5bd00f5561 100644
--- a/gdb/infrun.h
+++ b/gdb/infrun.h
@@ -416,5 +416,32 @@ struct scoped_enable_commit_resumed
   bool m_prev_enable_commit_resumed;
 };
 
+/* The execution context that just caused a normal stop.  */
+
+struct stop_context
+{
+  stop_context ();
+
+  DISABLE_COPY_AND_ASSIGN (stop_context);
+
+  bool changed () const;
+
+  /* The stop ID.  */
+  ULONGEST stop_id;
+
+  /* The event PTID.  */
+  ptid_t ptid;
+
+  /* If stopped for a thread event, this is the thread that caused the
+     stop.  */
+  thread_info_ref thread;
+
+  /* If stopped for a thread event, this is the state of the thread
+     that caused the stop.  */
+  enum thread_state thread_state;
+
+  /* The inferior that caused the stop.  */
+  int inf_num;
+};
 
 #endif /* INFRUN_H */

base-commit: c0c3bb70f2f13e07295041cdf24a4d2997fe99a4
-- 
2.34.1



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

* Re: [PATCHv5 05/11] gdb: don't always print breakpoint location after failed condition check
  2023-07-07 15:20           ` Pedro Alves
@ 2023-07-07 15:24             ` Pedro Alves
  2023-07-07 21:18               ` Andrew Burgess
  0 siblings, 1 reply; 202+ messages in thread
From: Pedro Alves @ 2023-07-07 15:24 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

On 2023-07-07 16:20, Pedro Alves wrote:
> I'd think the second *stopped shouldn't even be there at all, following the
> logic used to remove the stop from the CLI.
> 
> Maybe we should try moving or copying this "don't report this stop" logic to
> fetch_inferior_event, to avoid calling the second normal_stop at all.
> I gave it a quick try, but what I tried without thinking much about it
> just hung GDB.  I didn't dig too much as I want to move on to review the rest
> of your series.

Here's the totally broken naive patch I tried.

From e1fde974fa58351de9f6dc0661162d77fc8be078 Mon Sep 17 00:00:00 2001
From: Pedro Alves <pedro@palves.net>
Date: Fri, 7 Jul 2023 16:10:29 +0100
Subject: [PATCH] mi

Change-Id: Ie49a36dc67b9584c40daabfffae1f87f6dd98c5c
---
 gdb/infrun.c | 11 +++++++----
 1 file changed, 7 insertions(+), 4 deletions(-)

diff --git a/gdb/infrun.c b/gdb/infrun.c
index 3dd24fccf6e..ab1fd13abe0 100644
--- a/gdb/infrun.c
+++ b/gdb/infrun.c
@@ -4395,6 +4395,8 @@ fetch_inferior_event ()
     auto defer_delete_threads
       = make_scope_exit (delete_just_stopped_threads_infrun_breakpoints);
 
+    stop_context saved_context;
+
     /* Now figure out what to do with the result of the result.  */
     handle_inferior_event (&ecs);
 
@@ -4415,16 +4417,17 @@ fetch_inferior_event ()
 	  }
 	else
 	  {
-	    bool should_notify_stop = true;
 	    bool proceeded = false;
 
 	    stop_all_threads_if_all_stop_mode ();
 
 	    clean_up_just_stopped_threads_fsms (&ecs);
 
-	    if (thr != nullptr && thr->thread_fsm () != nullptr)
-	      should_notify_stop
-	       = thr->thread_fsm ()->should_notify_stop ();
+	    bool should_notify_stop
+		= (!saved_context.changed ()
+		   && thr != nullptr
+		   && thr->thread_fsm () != nullptr
+		   && thr->thread_fsm ()->should_notify_stop ());
 
 	    if (should_notify_stop)
 	      {

base-commit: c0c3bb70f2f13e07295041cdf24a4d2997fe99a4
prerequisite-patch-id: c39ea2983f5abc3fac4664e7ea78420409d3df86
-- 
2.34.1


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

* Re: [PATCHv5 01/11] gdb: include breakpoint number in testing condition error message
  2023-07-07 12:08           ` Pedro Alves
@ 2023-07-07 15:43             ` Andrew Burgess
  2023-07-07 16:19               ` Pedro Alves
  0 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2023-07-07 15:43 UTC (permalink / raw)
  To: Pedro Alves, gdb-patches

Pedro Alves <pedro@palves.net> writes:

> Hi,
>
> On 2023-03-16 17:36, Andrew Burgess via Gdb-patches wrote:
>
>> So, in this commit, in preparation for the later commits, I propose to
>> change the 'Error in testing breakpoint condition:' line to this:
>> 
>>   Error in testing condition for breakpoint NUMBER:
>> 
>> where NUMBER will be filled in as appropriate.  Here's the first
>> example with the updated error:
>> 
>>   (gdb) break foo if (*(int *) 0) == 0
>>   Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
>>   (gdb) r
>>   Starting program: /tmp/bpcond
>>   Error in testing condition for breakpoint 1:
>>   Cannot access memory at address 0x0
>> 
>>   Breakpoint 1, foo () at bpcond.c:11
>>   11	  int a = 32;
>>   (gdb)
>> 
>
> Reading this, I was thinking that we should print the breakpoint location number
> as well.  We do print it when presenting breakpoint stops nowadays, like:
>
>  (top-gdb) b printf
>  Breakpoint 3 at 0xee680 (2 locations)
>  (top-gdb) r
>  ...
>  Breakpoint 3.1, ui_file::printf ...
>  ...
>
> Did you consider that and decided against?  I didn't find any mention of it in previous
> discussions.

No, this was just an oversight, and would I think be a great
improvement.

The patch below implements this idea.  Let me know what you think.

Thanks,
Andrew

---

commit ead767dcb1f5023ed1ce98001672a63cc3737bdb
Author: Andrew Burgess <aburgess@redhat.com>
Date:   Fri Jul 7 16:36:26 2023 +0100

    gdb: include location number in breakpoint error message
    
    This commit improves the output of this previous commit:
    
      commit 2dc3457a454a35d0617dc1f9cc1db77468471f95
      Date:   Fri Oct 14 13:22:55 2022 +0100
    
          gdb: include breakpoint number in testing condition error message
    
    The earlier commit extended the error message:
    
      Error in testing breakpoint condition:
    
    to include the breakpoint number, e.g.:
    
      Error in testing breakpoint condition 3:
    
    This commit extends takes this further, and includes the location
    number if the breakpoint has multiple locations, so we might now see:
    
      Error in testing breakpoint condition 3.2:
    
    Just as with how GDB reports a normal breakpoint stop, if a breakpoint
    only has a single location then the location number is not included,
    this keeps things nice and consistent.
    
    I've extended one of the tests to cover the new functionality.

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index da6c8de9d14..d898167b7e1 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -5544,9 +5544,17 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
 	    }
 	  catch (const gdb_exception_error &ex)
 	    {
-	      exception_fprintf (gdb_stderr, ex,
-				 "Error in testing condition for breakpoint %d:\n",
-				 b->number);
+	      int locno = bpstat_locno (bs);
+	      if (locno != 0)
+		exception_fprintf
+		  (gdb_stderr, ex,
+		   "Error in testing condition for breakpoint %d.%d:\n",
+		   b->number, locno);
+	      else
+		exception_fprintf
+		  (gdb_stderr, ex,
+		   "Error in testing condition for breakpoint %d:\n",
+		   b->number);
 
 	      /* If the pc value changed as a result of evaluating the
 		 condition then we probably stopped within an inferior
diff --git a/gdb/testsuite/gdb.base/bp-cond-failure.c b/gdb/testsuite/gdb.base/bp-cond-failure.c
index 2a9974b47ce..8c226edd8b4 100644
--- a/gdb/testsuite/gdb.base/bp-cond-failure.c
+++ b/gdb/testsuite/gdb.base/bp-cond-failure.c
@@ -15,16 +15,26 @@
    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
+static inline int __attribute__((__always_inline__))
 foo ()
 {
-  return 0;	/* Breakpoint here.  */
+  return 0;	/* Multi-location breakpoint here.  */
+}
+
+static int __attribute__((noinline))
+bar ()
+{
+  int res = foo ();	/* Single-location breakpoint here.  */
+
+  return res;
 }
 
 int
 main ()
 {
-  int res = foo ();
+  int res = bar ();
+
+  res = foo ();
 
   return res;
 }
diff --git a/gdb/testsuite/gdb.base/bp-cond-failure.exp b/gdb/testsuite/gdb.base/bp-cond-failure.exp
index cb572203772..bc7d8d13b9f 100644
--- a/gdb/testsuite/gdb.base/bp-cond-failure.exp
+++ b/gdb/testsuite/gdb.base/bp-cond-failure.exp
@@ -44,10 +44,7 @@ if { [is_address_zero_readable] } {
     return
 }
 
-# Where the breakpoint will be placed.
-set bp_line [gdb_get_line_number "Breakpoint here"]
-
-proc run_test { cond_eval access_type } {
+proc run_test { cond_eval access_type lineno nloc } {
     clean_restart ${::binfile}
 
     if { ![runto_main] } {
@@ -59,17 +56,23 @@ proc run_test { cond_eval access_type } {
     }
 
     # Setup the conditional breakpoint and record its number.
-    gdb_breakpoint "${::srcfile}:${::bp_line} if (*(${access_type} *) 0) == 0"
+    gdb_breakpoint "${::srcfile}:${lineno} if (*(${access_type} *) 0) == 0"
     set bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*"]
 
+    if { $nloc > 1 } {
+	set bp_num_pattern "${bp_num}.1"
+    } else {
+	set bp_num_pattern "${bp_num}"
+    }
+
     gdb_test "continue" \
 	[multi_line \
 	     "Continuing\\." \
-	     "Error in testing condition for breakpoint ${bp_num}:" \
+	     "Error in testing condition for breakpoint ${bp_num_pattern}:" \
 	     "Cannot access memory at address 0x0" \
 	     "" \
-	     "Breakpoint ${bp_num}, foo \\(\\) at \[^\r\n\]+:${::bp_line}" \
-	     "${::decimal}\\s+\[^\r\n\]+Breakpoint here\[^\r\n\]+"]
+	     "Breakpoint ${bp_num_pattern}, \(foo\|bar\) \\(\\) at \[^\r\n\]+:${lineno}" \
+	     "${::decimal}\\s+\[^\r\n\]+ breakpoint here\\. \[^\r\n\]+"]
 }
 
 # If we're using a remote target then conditions could be evaulated
@@ -97,8 +100,19 @@ gdb_test_multiple "show breakpoint condition-evaluation" "" {
     }
 }
 
+# Where the breakpoint will be placed.
+set bp_line_multi_loc [gdb_get_line_number "Multi-location breakpoint here"]
+set bp_line_single_loc [gdb_get_line_number "Single-location breakpoint here"]
+
+
+
 foreach_with_prefix access_type { "char" "short" "int" "long long" } {
     foreach_with_prefix cond_eval $cond_eval_modes {
-	run_test $cond_eval $access_type
+	with_test_prefix "multi-loc" {
+	    run_test $cond_eval $access_type $bp_line_multi_loc 2
+	}
+	with_test_prefix "single-loc" {
+	    run_test $cond_eval $access_type $bp_line_single_loc 1
+	}
     }
 }


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

* Re: [PATCHv5 01/11] gdb: include breakpoint number in testing condition error message
  2023-07-07 15:43             ` Andrew Burgess
@ 2023-07-07 16:19               ` Pedro Alves
  2023-07-10 10:30                 ` Andrew Burgess
  0 siblings, 1 reply; 202+ messages in thread
From: Pedro Alves @ 2023-07-07 16:19 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

On 2023-07-07 16:43, Andrew Burgess wrote:
> Pedro Alves <pedro@palves.net> writes:

>> Reading this, I was thinking that we should print the breakpoint location number
>> as well.  We do print it when presenting breakpoint stops nowadays, like:
>>
>>  (top-gdb) b printf
>>  Breakpoint 3 at 0xee680 (2 locations)
>>  (top-gdb) r
>>  ...
>>  Breakpoint 3.1, ui_file::printf ...
>>  ...
>>
>> Did you consider that and decided against?  I didn't find any mention of it in previous
>> discussions.
> 
> No, this was just an oversight, and would I think be a great
> improvement.
> 
> The patch below implements this idea.  Let me know what you think.

Looks good, thanks!

Approved-By: Pedro Alves <pedro@palves.net>

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

* Re: [PATCHv5 03/11] gdbserver: allow agent expressions to fail with invalid memory access
  2023-07-07 12:25           ` Pedro Alves
@ 2023-07-07 16:28             ` Andrew Burgess
  2023-07-07 17:26               ` Pedro Alves
  0 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2023-07-07 16:28 UTC (permalink / raw)
  To: Pedro Alves, gdb-patches

Pedro Alves <pedro@palves.net> writes:

> On 2023-03-16 17:36, Andrew Burgess via Gdb-patches wrote:
>> This commit extends gdbserver to take account of a failed memory
>> access from agent_mem_read, and to return a new eval_result_type
>> expr_eval_invalid_memory_access.
>> 
>> I have only updated the agent_mem_read calls related directly to
>> reading memory, I have not updated any of the calls related to
>> tracepoint data collection.  This is just because I'm not familiar
>> with that area of gdb/gdbserver, and I don't want to break anything,
>> so leaving the existing behaviour untouched seems like the safest
>> approach.
>
> I think this should update the gdbserver/tracepoint.cc:eval_result_names array at least,
> though.  Otherwise I think a memory error during collection is going to trigger undefined
> behavior, crash if we're lucky.

Good spot.

What are your thoughts on the patch below that should address this
issue?

Thanks,
Andrew

---

commit 35e78a7699618f0bb1c111cdc54d9f9bcb0171c9
Author: Andrew Burgess <aburgess@redhat.com>
Date:   Fri Jul 7 17:18:46 2023 +0100

    gdbserver: handle all eval_result_type values in tracepoint.cc
    
    It was pointed out[1] that after this commit:
    
      commit 3812b38d8de5804ad3eadd6c7a5d532402ddabab
      Date:   Thu Oct 20 11:14:33 2022 +0100
    
          gdbserver: allow agent expressions to fail with invalid memory access
    
    Now that agent expressions might fail with the error
    expr_eval_invalid_memory_access, we might overflow the
    eval_result_names array in tracepoint.cc.  This is because the
    eval_result_names array does not include a string for either
    expr_eval_invalid_goto or expr_eval_invalid_memory_access.
    
    I don't know if having expr_eval_invalid_goto missing is also a
    problem, but it feels like eval_result_names should just include a
    string for every possible error.
    
    I could just add two more strings into the array, but I figured that,
    if I convert eval_result_names into a function containing a switch
    then I can make use of DIAGNOSTIC_ERROR_SWITCH to have the compiler
    ensure that we always cover every possible error code.
    
    I know (from the comments) that tracepoint.cc is built both into
    gdbserver, and into a shared library that the inferior might load (for
    fast tracepoint support), so I did consider whether this change could
    break the API of that shared library.  However, eval_result_names is a
    static array, so I don't believe that this is part of the external
    API, as such, converting this array into a static function shouldn't
    impact any users.
    
    [1] https://inbox.sourceware.org/gdb-patches/01059f8a-0e59-55b5-f530-190c26df5ba3@palves.net/

diff --git a/gdbserver/tracepoint.cc b/gdbserver/tracepoint.cc
index 1f31e0cc05f..879ad734b66 100644
--- a/gdbserver/tracepoint.cc
+++ b/gdbserver/tracepoint.cc
@@ -857,17 +857,43 @@ EXTERN_C_POP
 
 static struct tracepoint *last_tracepoint;
 
-static const char * const eval_result_names[] =
-  {
-    "terror:in the attic",  /* this should never be reported */
-    "terror:empty expression",
-    "terror:empty stack",
-    "terror:stack overflow",
-    "terror:stack underflow",
-    "terror:unhandled opcode",
-    "terror:unrecognized opcode",
-    "terror:divide by zero"
-  };
+/* Return a string representing the error in ERR.  This should not be
+   called when ERR is expr_eval_no_error.  */
+
+static const char * const
+eval_result_error_name (enum eval_result_type err)
+{
+  gdb_assert (err != expr_eval_no_error);
+
+DIAGNOSTIC_PUSH
+DIAGNOSTIC_ERROR_SWITCH
+  switch (err)
+    {
+    case expr_eval_no_error:
+      break;
+    case expr_eval_empty_expression:
+      return "terror:empty expression";
+    case expr_eval_empty_stack:
+      return "terror:empty stack";
+    case expr_eval_stack_overflow:
+      return "terror:stack overflow";
+    case expr_eval_stack_underflow:
+      return "terror:stack underflow";
+    case expr_eval_unhandled_opcode:
+      return "terror:unhandled opcode";
+    case expr_eval_unrecognized_opcode:
+      return "terror:unrecognized opcode";
+    case expr_eval_divide_by_zero:
+      return "terror:divide by zero";
+    case expr_eval_invalid_goto:
+      return "terror:invalid goto";
+    case expr_eval_invalid_memory_access:
+      return "terror:invalid memory access";
+    }
+DIAGNOSTIC_POP
+
+  gdb_assert_not_reached ("invalid error type");
+}
 
 #endif
 
@@ -3447,7 +3473,8 @@ stop_tracing (void)
   else if (expr_eval_result != expr_eval_no_error)
     {
       trace_debug ("Stopping the trace because of an expression eval error");
-      tracing_stop_reason = eval_result_names[expr_eval_result];
+      tracing_stop_reason
+	= eval_result_error_name ((enum eval_result_type) expr_eval_result);
       tracing_stop_tpnum = error_tracepoint->number;
     }
 #ifndef IN_PROCESS_AGENT


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

* Re: [PATCHv8 4/6] gdb/remote: avoid SIGINT after calling remote_target::stop
  2023-06-07 10:01               ` [PATCHv8 4/6] gdb/remote: avoid SIGINT after calling remote_target::stop Andrew Burgess
@ 2023-07-07 17:18                 ` Pedro Alves
  2023-07-10 20:04                   ` Andrew Burgess
  0 siblings, 1 reply; 202+ messages in thread
From: Pedro Alves @ 2023-07-07 17:18 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

(I'll go back to reviewing the other patches in the series, but I wanted to
reply to this one immediately.)

I think this patch is just incorrect, design wise, and we should not merge it.

There is absolutely no connection between any selected thread in GDB to the
thread that eventually reports the SIGINT, because the \x03 packet carries no
thread context.  So GDB could ask for target_stop({pid=123, lwpid=999}), and
if we end up sending \x03, the thread that gets the SIGINT could be
say, {pid=123, lwpid=123}, or even {pid=666, lwpid=666}.

On Windows, both GenerateConsoleCtrlEvent and DebugBreakProcess (the functions
used by win32_process_target::request_interrupt()) inject a new thread
in the inferior and has _thread_ thread report the event.  So the thread that
reports the interrupt is completely unknown to GDB at the time the \x03 is sent.

Also, there's even no guarantee that you'll get a SIGINT instead of some
other signal.  On Windows, DebugBreakProcess results in SIGTRAP.

We should just not assume that target_stop with an all-stop backend is able
to stop a specific thread.

Pedro Alves


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

* Re: [PATCHv5 03/11] gdbserver: allow agent expressions to fail with invalid memory access
  2023-07-07 16:28             ` Andrew Burgess
@ 2023-07-07 17:26               ` Pedro Alves
  2023-07-07 21:19                 ` Andrew Burgess
  2023-07-10 10:32                 ` Andrew Burgess
  0 siblings, 2 replies; 202+ messages in thread
From: Pedro Alves @ 2023-07-07 17:26 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

On 2023-07-07 17:28, Andrew Burgess wrote:
> Pedro Alves <pedro@palves.net> writes:
> 
>> On 2023-03-16 17:36, Andrew Burgess via Gdb-patches wrote:
>>> This commit extends gdbserver to take account of a failed memory
>>> access from agent_mem_read, and to return a new eval_result_type
>>> expr_eval_invalid_memory_access.
>>>
>>> I have only updated the agent_mem_read calls related directly to
>>> reading memory, I have not updated any of the calls related to
>>> tracepoint data collection.  This is just because I'm not familiar
>>> with that area of gdb/gdbserver, and I don't want to break anything,
>>> so leaving the existing behaviour untouched seems like the safest
>>> approach.
>>
>> I think this should update the gdbserver/tracepoint.cc:eval_result_names array at least,
>> though.  Otherwise I think a memory error during collection is going to trigger undefined
>> behavior, crash if we're lucky.
> 
> Good spot.
> 
> What are your thoughts on the patch below that should address this
> issue?

Hmm.  If we're changing how the array is built completely, you could go a step
further and convert to a .def file (like e.g., gdb/unwind_stop_reasons.def) that is
included by both ax.h and tracepoint.cc.  That would keep the enum names and their
string representations in the same place.  It would also dispense with the
diagnostics pragmas, as the problem scenario goes away by design.

Pedro Alves

> 
> Thanks,
> Andrew
> 
> ---
> 
> commit 35e78a7699618f0bb1c111cdc54d9f9bcb0171c9
> Author: Andrew Burgess <aburgess@redhat.com>
> Date:   Fri Jul 7 17:18:46 2023 +0100
> 
>     gdbserver: handle all eval_result_type values in tracepoint.cc
>     
>     It was pointed out[1] that after this commit:
>     
>       commit 3812b38d8de5804ad3eadd6c7a5d532402ddabab
>       Date:   Thu Oct 20 11:14:33 2022 +0100
>     
>           gdbserver: allow agent expressions to fail with invalid memory access
>     
>     Now that agent expressions might fail with the error
>     expr_eval_invalid_memory_access, we might overflow the
>     eval_result_names array in tracepoint.cc.  This is because the
>     eval_result_names array does not include a string for either
>     expr_eval_invalid_goto or expr_eval_invalid_memory_access.
>     
>     I don't know if having expr_eval_invalid_goto missing is also a
>     problem, but it feels like eval_result_names should just include a
>     string for every possible error.
>     
>     I could just add two more strings into the array, but I figured that,
>     if I convert eval_result_names into a function containing a switch
>     then I can make use of DIAGNOSTIC_ERROR_SWITCH to have the compiler
>     ensure that we always cover every possible error code.
>     
>     I know (from the comments) that tracepoint.cc is built both into
>     gdbserver, and into a shared library that the inferior might load (for
>     fast tracepoint support), so I did consider whether this change could
>     break the API of that shared library.  However, eval_result_names is a
>     static array, so I don't believe that this is part of the external
>     API, as such, converting this array into a static function shouldn't
>     impact any users.
>     
>     [1] https://inbox.sourceware.org/gdb-patches/01059f8a-0e59-55b5-f530-190c26df5ba3@palves.net/
> 
> diff --git a/gdbserver/tracepoint.cc b/gdbserver/tracepoint.cc
> index 1f31e0cc05f..879ad734b66 100644
> --- a/gdbserver/tracepoint.cc
> +++ b/gdbserver/tracepoint.cc
> @@ -857,17 +857,43 @@ EXTERN_C_POP
>  
>  static struct tracepoint *last_tracepoint;
>  
> -static const char * const eval_result_names[] =
> -  {
> -    "terror:in the attic",  /* this should never be reported */
> -    "terror:empty expression",
> -    "terror:empty stack",
> -    "terror:stack overflow",
> -    "terror:stack underflow",
> -    "terror:unhandled opcode",
> -    "terror:unrecognized opcode",
> -    "terror:divide by zero"
> -  };
> +/* Return a string representing the error in ERR.  This should not be
> +   called when ERR is expr_eval_no_error.  */
> +
> +static const char * const
> +eval_result_error_name (enum eval_result_type err)
> +{
> +  gdb_assert (err != expr_eval_no_error);
> +
> +DIAGNOSTIC_PUSH
> +DIAGNOSTIC_ERROR_SWITCH
> +  switch (err)
> +    {
> +    case expr_eval_no_error:
> +      break;
> +    case expr_eval_empty_expression:
> +      return "terror:empty expression";
> +    case expr_eval_empty_stack:
> +      return "terror:empty stack";
> +    case expr_eval_stack_overflow:
> +      return "terror:stack overflow";
> +    case expr_eval_stack_underflow:
> +      return "terror:stack underflow";
> +    case expr_eval_unhandled_opcode:
> +      return "terror:unhandled opcode";
> +    case expr_eval_unrecognized_opcode:
> +      return "terror:unrecognized opcode";
> +    case expr_eval_divide_by_zero:
> +      return "terror:divide by zero";
> +    case expr_eval_invalid_goto:
> +      return "terror:invalid goto";
> +    case expr_eval_invalid_memory_access:
> +      return "terror:invalid memory access";
> +    }
> +DIAGNOSTIC_POP
> +
> +  gdb_assert_not_reached ("invalid error type");
> +}
>  
>  #endif
>  
> @@ -3447,7 +3473,8 @@ stop_tracing (void)
>    else if (expr_eval_result != expr_eval_no_error)
>      {
>        trace_debug ("Stopping the trace because of an expression eval error");
> -      tracing_stop_reason = eval_result_names[expr_eval_result];
> +      tracing_stop_reason
> +	= eval_result_error_name ((enum eval_result_type) expr_eval_result);
>        tracing_stop_tpnum = error_tracepoint->number;
>      }
>  #ifndef IN_PROCESS_AGENT
> 

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

* Re: [PATCHv5 05/11] gdb: don't always print breakpoint location after failed condition check
  2023-07-07 15:24             ` Pedro Alves
@ 2023-07-07 21:18               ` Andrew Burgess
  2023-07-11 12:06                 ` Pedro Alves
  0 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2023-07-07 21:18 UTC (permalink / raw)
  To: Pedro Alves, gdb-patches

Pedro Alves <pedro@palves.net> writes:

> On 2023-07-07 16:20, Pedro Alves wrote:
>> I'd think the second *stopped shouldn't even be there at all, following the
>> logic used to remove the stop from the CLI.
>> 
>> Maybe we should try moving or copying this "don't report this stop" logic to
>> fetch_inferior_event, to avoid calling the second normal_stop at all.
>> I gave it a quick try, but what I tried without thinking much about it
>> just hung GDB.  I didn't dig too much as I want to move on to review the rest
>> of your series.
>
> Here's the totally broken naive patch I tried.
>
> From e1fde974fa58351de9f6dc0661162d77fc8be078 Mon Sep 17 00:00:00 2001
> From: Pedro Alves <pedro@palves.net>
> Date: Fri, 7 Jul 2023 16:10:29 +0100
> Subject: [PATCH] mi
>
> Change-Id: Ie49a36dc67b9584c40daabfffae1f87f6dd98c5c
> ---
>  gdb/infrun.c | 11 +++++++----
>  1 file changed, 7 insertions(+), 4 deletions(-)
>
> diff --git a/gdb/infrun.c b/gdb/infrun.c
> index 3dd24fccf6e..ab1fd13abe0 100644
> --- a/gdb/infrun.c
> +++ b/gdb/infrun.c
> @@ -4395,6 +4395,8 @@ fetch_inferior_event ()
>      auto defer_delete_threads
>        = make_scope_exit (delete_just_stopped_threads_infrun_breakpoints);
>  
> +    stop_context saved_context;
> +
>      /* Now figure out what to do with the result of the result.  */
>      handle_inferior_event (&ecs);
>  
> @@ -4415,16 +4417,17 @@ fetch_inferior_event ()
>  	  }
>  	else
>  	  {
> -	    bool should_notify_stop = true;
>  	    bool proceeded = false;
>  
>  	    stop_all_threads_if_all_stop_mode ();
>  
>  	    clean_up_just_stopped_threads_fsms (&ecs);
>  
> -	    if (thr != nullptr && thr->thread_fsm () != nullptr)
> -	      should_notify_stop
> -	       = thr->thread_fsm ()->should_notify_stop ();
> +	    bool should_notify_stop
> +		= (!saved_context.changed ()
> +		   && thr != nullptr
> +		   && thr->thread_fsm () != nullptr
> +		   && thr->thread_fsm ()->should_notify_stop ());

So, I got this working, as in, not locking up GDB.  The problem was that
thr->thread_fsm() is often nullptr, so we end up never calling
normal_stop.

However, I don't think this is going to work out.  There's a couple of
problems.

First, at the point fetch_inferior_event is called, there is no thread
selected, so the ptid and thread captured in saved_context are always
null_ptid and nullptr respectively.  By the time we call
saved_context.changed() we do have a thread selected, so the context
appears to have always changed.

However, I figured I could work around this be replacing the full
stop_context with a simple 'int stop_id = get_stop_id ();', I figured
this might be enough, this will tell me if GDB has notified the user of
a stop somewhere within the handle_inferior_event code.

This works fine in the sense that I do now correctly spot that the user
has been notified of a stop and don't call normal_stop again...

... but as a consequence, GDB now doesn't realise that is has stopped,
and doesn't display a prompt back to the user.

I'm going to have to leave this for the weekend now, but will continue
looking at this next week.  I've included my WIP hack below.

Would be interested on whether you see any problems with just using
get_stop_id() to determine if the user has already seen a stop or not? 

Thanks,
Andrew

>  
>  	    if (should_notify_stop)
>  	      {
>
> base-commit: c0c3bb70f2f13e07295041cdf24a4d2997fe99a4
> prerequisite-patch-id: c39ea2983f5abc3fac4664e7ea78420409d3df86
> -- 
> 2.34.1


---

diff --git a/gdb/infrun.c b/gdb/infrun.c
index 3dd24fccf6e..83c5c6c51d6 100644
--- a/gdb/infrun.c
+++ b/gdb/infrun.c
@@ -4395,6 +4395,8 @@ fetch_inferior_event ()
     auto defer_delete_threads
       = make_scope_exit (delete_just_stopped_threads_infrun_breakpoints);
 
+    int stop_id = get_stop_id ();
+
     /* Now figure out what to do with the result of the result.  */
     handle_inferior_event (&ecs);
 
@@ -4415,7 +4420,7 @@ fetch_inferior_event ()
 	  }
 	else
 	  {
-	    bool should_notify_stop = true;
+	    bool should_notify_stop = stop_id == get_stop_id ();
 	    bool proceeded = false;
 
 	    stop_all_threads_if_all_stop_mode ();
@@ -4424,7 +4435,8 @@ fetch_inferior_event ()
 
 	    if (thr != nullptr && thr->thread_fsm () != nullptr)
 	      should_notify_stop
-	       = thr->thread_fsm ()->should_notify_stop ();
+		= (should_notify_stop
+		   && thr->thread_fsm ()->should_notify_stop ());
 
 	    if (should_notify_stop)
 	      {


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

* Re: [PATCHv5 03/11] gdbserver: allow agent expressions to fail with invalid memory access
  2023-07-07 17:26               ` Pedro Alves
@ 2023-07-07 21:19                 ` Andrew Burgess
  2023-07-10 10:32                 ` Andrew Burgess
  1 sibling, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-07-07 21:19 UTC (permalink / raw)
  To: Pedro Alves, gdb-patches

Pedro Alves <pedro@palves.net> writes:

> On 2023-07-07 17:28, Andrew Burgess wrote:
>> Pedro Alves <pedro@palves.net> writes:
>> 
>>> On 2023-03-16 17:36, Andrew Burgess via Gdb-patches wrote:
>>>> This commit extends gdbserver to take account of a failed memory
>>>> access from agent_mem_read, and to return a new eval_result_type
>>>> expr_eval_invalid_memory_access.
>>>>
>>>> I have only updated the agent_mem_read calls related directly to
>>>> reading memory, I have not updated any of the calls related to
>>>> tracepoint data collection.  This is just because I'm not familiar
>>>> with that area of gdb/gdbserver, and I don't want to break anything,
>>>> so leaving the existing behaviour untouched seems like the safest
>>>> approach.
>>>
>>> I think this should update the gdbserver/tracepoint.cc:eval_result_names array at least,
>>> though.  Otherwise I think a memory error during collection is going to trigger undefined
>>> behavior, crash if we're lucky.
>> 
>> Good spot.
>> 
>> What are your thoughts on the patch below that should address this
>> issue?
>
> Hmm.  If we're changing how the array is built completely, you could go a step
> further and convert to a .def file (like e.g., gdb/unwind_stop_reasons.def) that is
> included by both ax.h and tracepoint.cc.  That would keep the enum names and their
> string representations in the same place.  It would also dispense with the
> diagnostics pragmas, as the problem scenario goes away by design.

Will do this next week and repost.

Thanks,
Andrew

>
> Pedro Alves
>
>> 
>> Thanks,
>> Andrew
>> 
>> ---
>> 
>> commit 35e78a7699618f0bb1c111cdc54d9f9bcb0171c9
>> Author: Andrew Burgess <aburgess@redhat.com>
>> Date:   Fri Jul 7 17:18:46 2023 +0100
>> 
>>     gdbserver: handle all eval_result_type values in tracepoint.cc
>>     
>>     It was pointed out[1] that after this commit:
>>     
>>       commit 3812b38d8de5804ad3eadd6c7a5d532402ddabab
>>       Date:   Thu Oct 20 11:14:33 2022 +0100
>>     
>>           gdbserver: allow agent expressions to fail with invalid memory access
>>     
>>     Now that agent expressions might fail with the error
>>     expr_eval_invalid_memory_access, we might overflow the
>>     eval_result_names array in tracepoint.cc.  This is because the
>>     eval_result_names array does not include a string for either
>>     expr_eval_invalid_goto or expr_eval_invalid_memory_access.
>>     
>>     I don't know if having expr_eval_invalid_goto missing is also a
>>     problem, but it feels like eval_result_names should just include a
>>     string for every possible error.
>>     
>>     I could just add two more strings into the array, but I figured that,
>>     if I convert eval_result_names into a function containing a switch
>>     then I can make use of DIAGNOSTIC_ERROR_SWITCH to have the compiler
>>     ensure that we always cover every possible error code.
>>     
>>     I know (from the comments) that tracepoint.cc is built both into
>>     gdbserver, and into a shared library that the inferior might load (for
>>     fast tracepoint support), so I did consider whether this change could
>>     break the API of that shared library.  However, eval_result_names is a
>>     static array, so I don't believe that this is part of the external
>>     API, as such, converting this array into a static function shouldn't
>>     impact any users.
>>     
>>     [1] https://inbox.sourceware.org/gdb-patches/01059f8a-0e59-55b5-f530-190c26df5ba3@palves.net/
>> 
>> diff --git a/gdbserver/tracepoint.cc b/gdbserver/tracepoint.cc
>> index 1f31e0cc05f..879ad734b66 100644
>> --- a/gdbserver/tracepoint.cc
>> +++ b/gdbserver/tracepoint.cc
>> @@ -857,17 +857,43 @@ EXTERN_C_POP
>>  
>>  static struct tracepoint *last_tracepoint;
>>  
>> -static const char * const eval_result_names[] =
>> -  {
>> -    "terror:in the attic",  /* this should never be reported */
>> -    "terror:empty expression",
>> -    "terror:empty stack",
>> -    "terror:stack overflow",
>> -    "terror:stack underflow",
>> -    "terror:unhandled opcode",
>> -    "terror:unrecognized opcode",
>> -    "terror:divide by zero"
>> -  };
>> +/* Return a string representing the error in ERR.  This should not be
>> +   called when ERR is expr_eval_no_error.  */
>> +
>> +static const char * const
>> +eval_result_error_name (enum eval_result_type err)
>> +{
>> +  gdb_assert (err != expr_eval_no_error);
>> +
>> +DIAGNOSTIC_PUSH
>> +DIAGNOSTIC_ERROR_SWITCH
>> +  switch (err)
>> +    {
>> +    case expr_eval_no_error:
>> +      break;
>> +    case expr_eval_empty_expression:
>> +      return "terror:empty expression";
>> +    case expr_eval_empty_stack:
>> +      return "terror:empty stack";
>> +    case expr_eval_stack_overflow:
>> +      return "terror:stack overflow";
>> +    case expr_eval_stack_underflow:
>> +      return "terror:stack underflow";
>> +    case expr_eval_unhandled_opcode:
>> +      return "terror:unhandled opcode";
>> +    case expr_eval_unrecognized_opcode:
>> +      return "terror:unrecognized opcode";
>> +    case expr_eval_divide_by_zero:
>> +      return "terror:divide by zero";
>> +    case expr_eval_invalid_goto:
>> +      return "terror:invalid goto";
>> +    case expr_eval_invalid_memory_access:
>> +      return "terror:invalid memory access";
>> +    }
>> +DIAGNOSTIC_POP
>> +
>> +  gdb_assert_not_reached ("invalid error type");
>> +}
>>  
>>  #endif
>>  
>> @@ -3447,7 +3473,8 @@ stop_tracing (void)
>>    else if (expr_eval_result != expr_eval_no_error)
>>      {
>>        trace_debug ("Stopping the trace because of an expression eval error");
>> -      tracing_stop_reason = eval_result_names[expr_eval_result];
>> +      tracing_stop_reason
>> +	= eval_result_error_name ((enum eval_result_type) expr_eval_result);
>>        tracing_stop_tpnum = error_tracepoint->number;
>>      }
>>  #ifndef IN_PROCESS_AGENT
>> 


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

* Re: [PATCHv5 01/11] gdb: include breakpoint number in testing condition error message
  2023-07-07 16:19               ` Pedro Alves
@ 2023-07-10 10:30                 ` Andrew Burgess
  0 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-07-10 10:30 UTC (permalink / raw)
  To: Pedro Alves, gdb-patches

Pedro Alves <pedro@palves.net> writes:

> On 2023-07-07 16:43, Andrew Burgess wrote:
>> Pedro Alves <pedro@palves.net> writes:
>
>>> Reading this, I was thinking that we should print the breakpoint location number
>>> as well.  We do print it when presenting breakpoint stops nowadays, like:
>>>
>>>  (top-gdb) b printf
>>>  Breakpoint 3 at 0xee680 (2 locations)
>>>  (top-gdb) r
>>>  ...
>>>  Breakpoint 3.1, ui_file::printf ...
>>>  ...
>>>
>>> Did you consider that and decided against?  I didn't find any mention of it in previous
>>> discussions.
>> 
>> No, this was just an oversight, and would I think be a great
>> improvement.
>> 
>> The patch below implements this idea.  Let me know what you think.
>
> Looks good, thanks!
>
> Approved-By: Pedro Alves <pedro@palves.net>

Pushed.

Thanks,
Andrew


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

* Re: [PATCHv5 03/11] gdbserver: allow agent expressions to fail with invalid memory access
  2023-07-07 17:26               ` Pedro Alves
  2023-07-07 21:19                 ` Andrew Burgess
@ 2023-07-10 10:32                 ` Andrew Burgess
  2023-07-10 10:44                   ` Pedro Alves
  1 sibling, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2023-07-10 10:32 UTC (permalink / raw)
  To: Pedro Alves, gdb-patches

Pedro Alves <pedro@palves.net> writes:

> On 2023-07-07 17:28, Andrew Burgess wrote:
>> Pedro Alves <pedro@palves.net> writes:
>> 
>>> On 2023-03-16 17:36, Andrew Burgess via Gdb-patches wrote:
>>>> This commit extends gdbserver to take account of a failed memory
>>>> access from agent_mem_read, and to return a new eval_result_type
>>>> expr_eval_invalid_memory_access.
>>>>
>>>> I have only updated the agent_mem_read calls related directly to
>>>> reading memory, I have not updated any of the calls related to
>>>> tracepoint data collection.  This is just because I'm not familiar
>>>> with that area of gdb/gdbserver, and I don't want to break anything,
>>>> so leaving the existing behaviour untouched seems like the safest
>>>> approach.
>>>
>>> I think this should update the gdbserver/tracepoint.cc:eval_result_names array at least,
>>> though.  Otherwise I think a memory error during collection is going to trigger undefined
>>> behavior, crash if we're lucky.
>> 
>> Good spot.
>> 
>> What are your thoughts on the patch below that should address this
>> issue?
>
> Hmm.  If we're changing how the array is built completely, you could go a step
> further and convert to a .def file (like e.g., gdb/unwind_stop_reasons.def) that is
> included by both ax.h and tracepoint.cc.  That would keep the enum names and their
> string representations in the same place.  It would also dispense with the
> diagnostics pragmas, as the problem scenario goes away by design.

Thanks for the suggestion.  Here's an attempt to switch to a .def file.
Thoughts?

Thanks,
Andrew

---

commit 75a86840a474097a19f4d04c9232981df3bf8066
Author: Andrew Burgess <aburgess@redhat.com>
Date:   Fri Jul 7 17:18:46 2023 +0100

    gdbserver: handle all eval_result_type values in tracepoint.cc
    
    It was pointed out[1] that after this commit:
    
      commit 3812b38d8de5804ad3eadd6c7a5d532402ddabab
      Date:   Thu Oct 20 11:14:33 2022 +0100
    
          gdbserver: allow agent expressions to fail with invalid memory access
    
    Now that agent expressions might fail with the error
    expr_eval_invalid_memory_access, we might overflow the
    eval_result_names array in tracepoint.cc.  This is because the
    eval_result_names array does not include a string for either
    expr_eval_invalid_goto or expr_eval_invalid_memory_access.
    
    I don't know if having expr_eval_invalid_goto missing is also a
    problem, but it feels like eval_result_names should just include a
    string for every possible error.
    
    I could just add two more strings into the array, but I figure that a
    more robust solution will be to move all of the error types, and their
    associated strings, into a new ax-result-types.def file, and to then
    include this file in both ax.h and tracepoint.cc in order to build
    the enum eval_result_type and the eval_result_names string array.
    Doing this means it is impossible to have a missing error string in
    the future.
    
    [1] https://inbox.sourceware.org/gdb-patches/01059f8a-0e59-55b5-f530-190c26df5ba3@palves.net/

diff --git a/gdbserver/ax-result-types.def b/gdbserver/ax-result-types.def
new file mode 100644
index 00000000000..3a832c44be2
--- /dev/null
+++ b/gdbserver/ax-result-types.def
@@ -0,0 +1,44 @@
+/* Agent expression result types.
+
+   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/>.  */
+
+/* The AX_RESULT_TYPE macro is used to define a result type that can be
+   generated by agent expression evaluation.  The first macro argument is
+   tye name of an enum entry, and the second is a string that describes
+   this result type.  */
+
+AX_RESULT_TYPE (expr_eval_no_error,
+		"terror:no error")
+AX_RESULT_TYPE (expr_eval_empty_expression,
+		"terror:empty expression")
+AX_RESULT_TYPE (expr_eval_empty_stack,
+		"terror:empty stack")
+AX_RESULT_TYPE (expr_eval_stack_overflow,
+		"terror:stack overflow")
+AX_RESULT_TYPE (expr_eval_stack_underflow,
+		"terror:stack underflow")
+AX_RESULT_TYPE (expr_eval_unhandled_opcode,
+		"terror:unhandled opcode")
+AX_RESULT_TYPE (expr_eval_unrecognized_opcode,
+		"terror:unrecognized opcode")
+AX_RESULT_TYPE (expr_eval_divide_by_zero,
+		"terror:divide by zero")
+AX_RESULT_TYPE (expr_eval_invalid_goto,
+		"terror:invalid goto")
+AX_RESULT_TYPE (expr_eval_invalid_memory_access,
+		"terror:invalid memory access")
diff --git a/gdbserver/ax.h b/gdbserver/ax.h
index c98e36a83c6..60e307ca42d 100644
--- a/gdbserver/ax.h
+++ b/gdbserver/ax.h
@@ -33,16 +33,9 @@ struct traceframe;
 
 enum eval_result_type
   {
-    expr_eval_no_error,
-    expr_eval_empty_expression,
-    expr_eval_empty_stack,
-    expr_eval_stack_overflow,
-    expr_eval_stack_underflow,
-    expr_eval_unhandled_opcode,
-    expr_eval_unrecognized_opcode,
-    expr_eval_divide_by_zero,
-    expr_eval_invalid_goto,
-    expr_eval_invalid_memory_access
+#define AX_RESULT_TYPE(ENUM,STR) ENUM,
+#include "ax-result-types.def"
+#undef AX_RESULT_TYPE
   };
 
 struct agent_expr
diff --git a/gdbserver/tracepoint.cc b/gdbserver/tracepoint.cc
index 1f31e0cc05f..609d49a87ef 100644
--- a/gdbserver/tracepoint.cc
+++ b/gdbserver/tracepoint.cc
@@ -859,14 +859,9 @@ static struct tracepoint *last_tracepoint;
 
 static const char * const eval_result_names[] =
   {
-    "terror:in the attic",  /* this should never be reported */
-    "terror:empty expression",
-    "terror:empty stack",
-    "terror:stack overflow",
-    "terror:stack underflow",
-    "terror:unhandled opcode",
-    "terror:unrecognized opcode",
-    "terror:divide by zero"
+#define AX_RESULT_TYPE(ENUM,STR) STR,
+#include "ax-result-types.def"
+#undef AX_RESULT_TYPE
   };
 
 #endif


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

* Re: [PATCHv5 03/11] gdbserver: allow agent expressions to fail with invalid memory access
  2023-07-10 10:32                 ` Andrew Burgess
@ 2023-07-10 10:44                   ` Pedro Alves
  2023-07-10 13:44                     ` Andrew Burgess
  0 siblings, 1 reply; 202+ messages in thread
From: Pedro Alves @ 2023-07-10 10:44 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

On 2023-07-10 11:32, Andrew Burgess wrote:

> commit 75a86840a474097a19f4d04c9232981df3bf8066
> Author: Andrew Burgess <aburgess@redhat.com>
> Date:   Fri Jul 7 17:18:46 2023 +0100
> 
>     gdbserver: handle all eval_result_type values in tracepoint.cc

...


> +/* The AX_RESULT_TYPE macro is used to define a result type that can be
> +   generated by agent expression evaluation.  The first macro argument is
> +   tye name of an enum entry, and the second is a string that describes

Typo: "tye" -> "the"

Otherwise,

Approved-By: Pedro Alves <pedro@palves.net>

Thanks!

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

* Re: [PATCHv5 03/11] gdbserver: allow agent expressions to fail with invalid memory access
  2023-07-10 10:44                   ` Pedro Alves
@ 2023-07-10 13:44                     ` Andrew Burgess
  0 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-07-10 13:44 UTC (permalink / raw)
  To: Pedro Alves, gdb-patches

Pedro Alves <pedro@palves.net> writes:

> On 2023-07-10 11:32, Andrew Burgess wrote:
>
>> commit 75a86840a474097a19f4d04c9232981df3bf8066
>> Author: Andrew Burgess <aburgess@redhat.com>
>> Date:   Fri Jul 7 17:18:46 2023 +0100
>> 
>>     gdbserver: handle all eval_result_type values in tracepoint.cc
>
> ...
>
>
>> +/* The AX_RESULT_TYPE macro is used to define a result type that can be
>> +   generated by agent expression evaluation.  The first macro argument is
>> +   tye name of an enum entry, and the second is a string that describes
>
> Typo: "tye" -> "the"

Fixed.

>
> Otherwise,
>
> Approved-By: Pedro Alves <pedro@palves.net>

Pushed.

Thanks,
Andrew


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

* Re: [PATCHv8 4/6] gdb/remote: avoid SIGINT after calling remote_target::stop
  2023-07-07 17:18                 ` Pedro Alves
@ 2023-07-10 20:04                   ` Andrew Burgess
  0 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-07-10 20:04 UTC (permalink / raw)
  To: Pedro Alves, gdb-patches

Pedro Alves <pedro@palves.net> writes:

> (I'll go back to reviewing the other patches in the series, but I wanted to
> reply to this one immediately.)
>
> I think this patch is just incorrect, design wise, and we should not merge it.
>
> There is absolutely no connection between any selected thread in GDB to the
> thread that eventually reports the SIGINT, because the \x03 packet carries no
> thread context.  So GDB could ask for target_stop({pid=123, lwpid=999}), and
> if we end up sending \x03, the thread that gets the SIGINT could be
> say, {pid=123, lwpid=123}, or even {pid=666, lwpid=666}.
>
> On Windows, both GenerateConsoleCtrlEvent and DebugBreakProcess (the functions
> used by win32_process_target::request_interrupt()) inject a new thread
> in the inferior and has _thread_ thread report the event.  So the thread that
> reports the interrupt is completely unknown to GDB at the time the \x03 is sent.
>
> Also, there's even no guarantee that you'll get a SIGINT instead of some
> other signal.  On Windows, DebugBreakProcess results in SIGTRAP.
>
> We should just not assume that target_stop with an all-stop backend is able
> to stop a specific thread.

Thanks for the feedback.

Andrew


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

* Re: [PATCHv5 05/11] gdb: don't always print breakpoint location after failed condition check
  2023-07-07 21:18               ` Andrew Burgess
@ 2023-07-11 12:06                 ` Pedro Alves
  2023-07-14 12:17                   ` Andrew Burgess
  0 siblings, 1 reply; 202+ messages in thread
From: Pedro Alves @ 2023-07-11 12:06 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

On 2023-07-07 22:18, Andrew Burgess wrote:
> Pedro Alves <pedro@palves.net> writes:
> 
>> On 2023-07-07 16:20, Pedro Alves wrote:
>>> I'd think the second *stopped shouldn't even be there at all, following the
>>> logic used to remove the stop from the CLI.
>>>
>>> Maybe we should try moving or copying this "don't report this stop" logic to
>>> fetch_inferior_event, to avoid calling the second normal_stop at all.
>>> I gave it a quick try, but what I tried without thinking much about it
>>> just hung GDB.  I didn't dig too much as I want to move on to review the rest
>>> of your series.
>>
>> Here's the totally broken naive patch I tried.
>>
>> From e1fde974fa58351de9f6dc0661162d77fc8be078 Mon Sep 17 00:00:00 2001
>> From: Pedro Alves <pedro@palves.net>
>> Date: Fri, 7 Jul 2023 16:10:29 +0100
>> Subject: [PATCH] mi
>>
>> Change-Id: Ie49a36dc67b9584c40daabfffae1f87f6dd98c5c
>> ---
>>  gdb/infrun.c | 11 +++++++----
>>  1 file changed, 7 insertions(+), 4 deletions(-)
>>
>> diff --git a/gdb/infrun.c b/gdb/infrun.c
>> index 3dd24fccf6e..ab1fd13abe0 100644
>> --- a/gdb/infrun.c
>> +++ b/gdb/infrun.c
>> @@ -4395,6 +4395,8 @@ fetch_inferior_event ()
>>      auto defer_delete_threads
>>        = make_scope_exit (delete_just_stopped_threads_infrun_breakpoints);
>>  
>> +    stop_context saved_context;
>> +
>>      /* Now figure out what to do with the result of the result.  */
>>      handle_inferior_event (&ecs);
>>  
>> @@ -4415,16 +4417,17 @@ fetch_inferior_event ()
>>  	  }
>>  	else
>>  	  {
>> -	    bool should_notify_stop = true;
>>  	    bool proceeded = false;
>>  
>>  	    stop_all_threads_if_all_stop_mode ();
>>  
>>  	    clean_up_just_stopped_threads_fsms (&ecs);
>>  
>> -	    if (thr != nullptr && thr->thread_fsm () != nullptr)
>> -	      should_notify_stop
>> -	       = thr->thread_fsm ()->should_notify_stop ();
>> +	    bool should_notify_stop
>> +		= (!saved_context.changed ()
>> +		   && thr != nullptr
>> +		   && thr->thread_fsm () != nullptr
>> +		   && thr->thread_fsm ()->should_notify_stop ());
> 
> So, I got this working, as in, not locking up GDB.  The problem was that
> thr->thread_fsm() is often nullptr, so we end up never calling
> normal_stop.
> 
> However, I don't think this is going to work out.  There's a couple of
> problems.
> 
> First, at the point fetch_inferior_event is called, there is no thread
> selected, so the ptid and thread captured in saved_context are always
> null_ptid and nullptr respectively.  By the time we call
> saved_context.changed() we do have a thread selected, so the context
> appears to have always changed.

Yeah.

> However, I figured I could work around this be replacing the full
> stop_context with a simple 'int stop_id = get_stop_id ();', I figured
> this might be enough, this will tell me if GDB has notified the user of
> a stop somewhere within the handle_inferior_event code.
> 
> This works fine in the sense that I do now correctly spot that the user
> has been notified of a stop and don't call normal_stop again...
> 
> ... but as a consequence, GDB now doesn't realise that is has stopped,
> and doesn't display a prompt back to the user.
> 
> I'm going to have to leave this for the weekend now, but will continue
> looking at this next week.  I've included my WIP hack below.
> 
> Would be interested on whether you see any problems with just using
> get_stop_id() to determine if the user has already seen a stop or not? 

I don't see a problem offhand.


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

* Re: [PATCHv6 3/6] gdb: add timeouts for inferior function calls
  2023-04-03 14:01           ` [PATCHv6 3/6] gdb: add timeouts for inferior function calls Andrew Burgess
@ 2023-07-11 14:23             ` Pedro Alves
  2023-07-14 15:20               ` Andrew Burgess
  0 siblings, 1 reply; 202+ messages in thread
From: Pedro Alves @ 2023-07-11 14:23 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

On 2023-04-03 15:01, Andrew Burgess via Gdb-patches wrote:

> diff --git a/gdb/NEWS b/gdb/NEWS
> index 10a1a70fa52..70987994e7b 100644
> --- a/gdb/NEWS
> +++ b/gdb/NEWS
> @@ -96,6 +96,24 @@ info main
>     $2 = 1
>     (gdb) break func if $_shell("some command") == 0
>  
> +set direct-call-timeout SECONDS
> +show direct-call-timeout
> +set indirect-call-timeout SECONDS
> +show indirect-call-timeout
> +  These new settings can be used to limit how long GDB will wait for
> +  an inferior function call to complete.  The direct timeout is used
> +  for inferior function calls from e.g. 'call' and 'print' commands,
> +  while the indirect timeout is used for inferior function calls from
> +  within a conditional breakpoint expression.

What happens with expressions in other commands, basically any command that
accepts an expression?  For example, "x foo()".  Are those direct, or
indirect?  I assume direct?

I wonder whether you have plans/ideas for other kinds of indirect calls.
Just thinking about whether naming the option as something about
"breakpoint-condition" wouldn't be better by being more direct (ah!) and
to the point, while leaving the possibility of other kinds of situations
having different timeouts.  to avoid long command names, we could have
a prefix setting, like:

 set call-timeout direct  # maybe there's a better name for this.
 set call-timeout breakpoint-conditions
 set call-timeout some-other-case

Just some thoughts, by no way am I objecting to what you have.

> +
> +  The default for the direct timeout is unlimited, while the default
> +  for the indirect timeout is 30 seconds.

While working on Windows non-stop support recently, I noticed that
gdb.threads/multiple-successive-infcall.exp has infcalls that would
just hang "forever", the infcall never completed.  The test
enables schedlock, and then calls a function in each thread in the
program [like, (gdb) p get_value()].  The issue turns out to be about
calling a function in a thread that is currently running Windows kernel
code.  On Linux, most system calls are interruptible (EINTR), and
restartable.  When the debugger pauses a thread and the thread is in a
syscall, the syscall is interrupted and restarted later when the thread
is resumed.  On Windows, system calls are NOT interruptible.  The threads
in question in the testcase were stopped inside the syscall done by
ntdll!ZwWaitForMultipleObjects.  In that scenario, you can still pause the
hung thread with Ctrl-C, and you'll see that the (userspace) PC of the thread
in question hasn't changed, it is still pointing to the entry to the
function GDB wants to call -- not surprising since the thread is really
still blocked inside the syscall and never ran any userspace instruction.

This looks like something that Windows GDB users are likely to trip on more
frequently than GNU/Linux users.

So I looked at how Visual Studio (not vscode) handles it, to check how it 
handles this, maybe it just doesn't let you call functions on threads that are
stopped inside a syscall?  Nope.  You guessed it, it handles it with a timeout.
If you add a watch expression (like a gdb "display") involving infcall, and the thread
is in kernel code, VS will still try the call, and then after a few short
seconds (maybe some 5s), it aborts the expression, popping a dialog box informing
you about it.

All that to say that I would think it reasonable to default to a
shorter timeout in GDB too.

Actually, I remembered now that LLDB also has a timeout for infcalls.
On the version I have handy installed, "help expression" talks about
a timeout of "currently .25 seconds", and then retrying with all threads
running, (that's 0.25s, not 25s IIUC, curiously, higher resolution than
second), but I don't know how long that second retry has for timeout,
if it has one.

For breakpoint conditions, I think it may be nice (but not a
requirement of this patch, just an idea) if after some time less than
the whole timeout time, for GDB to print a warning, something like:

 warning: a function call in the condition of breakpoint 2.3 is taking long.

Like, we could print that warning after 1 second, even if the timeout
is set to higher than that.

Anyhow, all that is a lot easier to code than debate and it can always
be done later.

> +
> +  These timeouts will only have an effect for targets that are
> +  operating in async mode.  For non-async targets the timeouts are
> +  ignored, GDB will wait indefinitely for an inferior function to
> +  complete, unless interrupted by the user using Ctrl-C.
> +
>  * MI changes
>  
>  ** mi now reports 'no-history' as a stop reason when hitting the end of the
> diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
> index fe76e5e0a0e..46f17798510 100644
> --- a/gdb/doc/gdb.texinfo
> +++ b/gdb/doc/gdb.texinfo
> @@ -20885,6 +20885,72 @@
>  @code{step}, etc).  In this case, when the inferior finally returns to
>  the dummy-frame, @value{GDBN} will once again halt the inferior.
>  
> +On targets that support asynchronous execution (@pxref{Background
> +Execution}) @value{GDBN} can place a timeout on any functions called
> +from @value{GDBN}.  If the timeout expires and the function call is
> +still ongoing, then @value{GDBN} will interrupt the program.

In the patch introducing "set unwind-on-timeout", I think it would be
good to mention the setting here.  I didn't notice it being added there.
Because, as I read this, I wondered "OK, but what happens after GDB
interrupts the program?  Do we unwind according to set unwind-on-signal?" .

> +
> +For targets that don't support asynchronous execution
> +(@pxref{Background Execution}) then timeouts for functions called from
> +@value{GDBN} are not supported, the timeout settings described below
> +will be treated as @code{unlimited}, meaning @value{GDBN} will wait
> +indefinitely for function call to complete, unless interrupted by the
> +user using @kbd{Ctrl-C}.
> +

...

> diff --git a/gdb/infcall.c b/gdb/infcall.c
> index 4fb8ab07db0..bb57faf700f 100644
> --- a/gdb/infcall.c
> +++ b/gdb/infcall.c
> @@ -95,6 +95,53 @@ show_may_call_functions_p (struct ui_file *file, int from_tty,
>  	      value);
>  }
>  
> +/* A timeout (in seconds) for direct inferior calls.  A direct inferior
> +   call is one the user triggers from the prompt, e.g. with a 'call' or
> +   'print' command.  Compare with the definition of indirect calls below.  */
> +
> +static unsigned int direct_call_timeout = UINT_MAX;
> +
> +/* Implement 'show direct-call-timeout'.  */
> +
> +static void
> +show_direct_call_timeout (struct ui_file *file, int from_tty,
> +			  struct cmd_list_element *c, const char *value)
> +{
> +  if (target_has_execution () && !target_can_async_p ())
> +    gdb_printf (file, _("Current target does not support async mode, timeout "
> +			"for direct inferior calls is \"unlimited\".\n"));
> +  else if (direct_call_timeout == UINT_MAX)
> +    gdb_printf (file, _("Timeout for direct inferior function calls "
> +			"is \"unlimited\".\n"));
> +  else
> +    gdb_printf (file, _("Timeout for direct inferior function calls "
> +			"is \"%s seconds\".\n"), value);
> +}
> +
> +/* A timeout (in seconds) for indirect inferior calls.  An indirect inferior
> +   call is one that originates from within GDB, for example, when
> +   evaluating an expression for a conditional breakpoint.  Compare with
> +   the definition of direct calls above.  */
> +
> +static unsigned int indirect_call_timeout = 30;
> +
> +/* Implement 'show indirect-call-timeout'.  */
> +
> +static void
> +show_indirect_call_timeout (struct ui_file *file, int from_tty,
> +			  struct cmd_list_element *c, const char *value)
> +{
> +  if (target_has_execution () && !target_can_async_p ())
> +    gdb_printf (file, _("Current target does not support async mode, timeout "
> +			"for indirect inferior calls is \"unlimited\".\n"));
> +  else if (indirect_call_timeout == UINT_MAX)
> +    gdb_printf (file, _("Timeout for indirect inferior function calls "
> +			"is \"unlimited\".\n"));
> +  else
> +    gdb_printf (file, _("Timeout for indirect inferior function calls "
> +			"is \"%s seconds\".\n"), value);
> +}
> +
>  /* How you should pass arguments to a function depends on whether it
>     was defined in K&R style or prototype style.  If you define a
>     function using the K&R syntax that takes a `float' argument, then
> @@ -589,6 +636,86 @@ call_thread_fsm::should_notify_stop ()
>    return true;
>  }
>  
> +/* A class to control creation of a timer that will interrupt a thread
> +   during an inferior call.  */
> +struct infcall_timer_controller
> +{
> +  /* Setup an event-loop timer that will interrupt PTID if the inferior
> +     call takes too long.  DIRECT_CALL_P is true when this inferior call is
> +     a result of the user using a 'print' or 'call' command, and false when
> +     this inferior call is a result of e.g. a conditional breakpoint
> +     expression, this is used to select which timeout to use.  */
> +  infcall_timer_controller (thread_info *thr, bool direct_call_p)
> +    : m_thread (thr)
> +  {
> +    unsigned int timeout
> +      = direct_call_p ? direct_call_timeout : indirect_call_timeout;
> +    if (timeout < UINT_MAX && target_can_async_p ())
> +      {
> +	int ms = timeout * 1000;
> +	int id = create_timer (ms, infcall_timer_controller::timed_out, this);
> +	m_timer_id.emplace (id);
> +	infcall_debug_printf ("Setting up infcall timeout timer for "
> +			      "ptid %s: %d milliseconds",
> +			      m_thread->ptid.to_string ().c_str (), ms);
> +      }
> +  }
> +
> +  /* Destructor.  Ensure that the timer is removed from the event loop.  */
> +  ~infcall_timer_controller ()
> +  {
> +    /* If the timer has already triggered, then it will have already been
> +       deleted from the event loop.  If the timer has not triggered, then
> +       delete it now.  */
> +    if (m_timer_id.has_value () && !m_triggered)
> +      delete_timer (*m_timer_id);
> +
> +    /* Just for clarity, discard the timer id now.  */
> +    m_timer_id.reset ();
> +  }
> +
> +  /* Return true if there was a timer in place, and the timer triggered,
> +     otherwise, return false.  */
> +  bool triggered_p ()
> +  {
> +    gdb_assert (!m_triggered || m_timer_id.has_value ());
> +    return m_triggered;
> +  }
> +
> +private:
> +  /* The thread we should interrupt.  */
> +  thread_info *m_thread;
> +
> +  /* Set true when the timer is triggered.  */
> +  bool m_triggered = false;
> +
> +  /* Given a value when a timer is in place.  */
> +  gdb::optional<int> m_timer_id;
> +
> +  /* Callback for the timer, forwards to ::trigger below.  */
> +  static void
> +  timed_out (gdb_client_data context)
> +  {
> +    infcall_timer_controller *ctrl
> +      = static_cast<infcall_timer_controller *> (context);
> +    ctrl->trigger ();
> +  }
> +
> +  /* Called when the timer goes off.  Stop thread m_thread.  */

Uppercase M_THREAD.

> +  void
> +  trigger ()
> +  {
> +    m_triggered = true;
> +
> +    scoped_disable_commit_resumed disable_commit_resumed ("infcall timeout");
> +
> +    infcall_debug_printf ("Stopping thread %s",
> +			  m_thread->ptid.to_string ().c_str ());
> +    target_stop (m_thread->ptid);
> +    m_thread->stop_requested = true;

As per the discussion in the remote patch, I think this will need
to be adjusted.  Maybe something like:

    if (target_is_non_stop_p ())
      {
        target_stop (m_thread->ptid);
        m_thread->stop_requested = true;
      }
    else
      target_interrupt ();

> +  }
> +};
> +
>  /* Subroutine of call_function_by_hand to simplify it.
>     Start up the inferior and wait for it to stop.
>     Return the exception if there's an error, or an exception with
> @@ -599,13 +726,15 @@ call_thread_fsm::should_notify_stop ()
>  
>  static struct gdb_exception
>  run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
> -		   struct thread_info *call_thread, CORE_ADDR real_pc)
> +		   struct thread_info *call_thread, CORE_ADDR real_pc,
> +		   bool *timed_out_p)
>  {
>    INFCALL_SCOPED_DEBUG_ENTER_EXIT;
>  
>    struct gdb_exception caught_error;
>    ptid_t call_thread_ptid = call_thread->ptid;
>    int was_running = call_thread->state == THREAD_RUNNING;
> +  *timed_out_p = false;
>  
>    infcall_debug_printf ("call function at %s in thread %s, was_running = %d",
>  			core_addr_to_string (real_pc),
> @@ -617,6 +746,16 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
>    scoped_restore restore_in_infcall
>      = make_scoped_restore (&call_thread->control.in_infcall, 1);
>  
> +  /* If the thread making the inferior call stops with a time out then the
> +     stop_requested flag will be set.  However, we don't want changes to
> +     this flag to leak back to our caller, we might be here to handle an
> +     inferior call from a breakpoint condition, so leaving this flag set
> +     would appear that the breakpoint stop was actually a requested stop,
> +     which is not true, and will cause GDB to print extra messages to the
> +     output.  */
> +  scoped_restore restore_stop_requested
> +    = make_scoped_restore (&call_thread->stop_requested, false);

I'm confused by this.  If stop_requested was set when the breakpoint was hit,
are we still evaluating the breakpoint condition (and re-resuming the thread
if the condition is false) ?

> +
>    clear_proceed_status (0);
>  

> --- /dev/null
> +++ b/gdb/testsuite/gdb.base/infcall-timeout.c
> @@ -0,0 +1,36 @@
> +/* Copyright 2022-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 <unistd.h>
> +
> +/* This function is called from GDB.  */
> +int
> +function_that_never_returns ()
> +{
> +  while (1)
> +    sleep (1);
> +
> +  return 0;
> +}
> +
> +int
> +main ()
> +{
> +  alarm (300);
> +
> +  return 0;
> +}
> diff --git a/gdb/testsuite/gdb.base/infcall-timeout.exp b/gdb/testsuite/gdb.base/infcall-timeout.exp


...

> +standard_testfile
> +
> +if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
> +	  {debug}] == -1 } {
> +    return
> +}
> +
> +# Start GDB according to TARGET_ASYNC and TARGET_NON_STOP, then adjust
> +# the direct-call-timeout, and make an inferior function call that
> +# will never return.  GDB should eventually timeout and stop the
> +# inferior.
> +proc_with_prefix run_test { target_async target_non_stop } {
> +    save_vars { ::GDBFLAGS } {
> +	append ::GDBFLAGS \
> +	    " -ex \"maint set target-non-stop $target_non_stop\""

It's curious that target-non-stop on|off is tested, but not "set non-stop on".

> +	append ::GDBFLAGS \
> +	    " -ex \"maintenance set target-async ${target_async}\""
> +
> +	clean_restart ${::binfile}
> +    }
> +

...

> diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
> new file mode 100644
> index 00000000000..4159288a39c
> --- /dev/null
> +++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp

...

> +
> +    gdb_breakpoint \
> +	"${::srcfile}:${::cond_bp_line} if (condition_func ())"
> +    set bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
> +		    "get number for conditional breakpoint"]
> +
> +    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
> +    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
> +			  "get number for final breakpoint"]
> +
> +    # The thread performing an inferior call relies on a second
> +    # thread.  The second thread will segfault unless it hits a
> +    # breakpoint first.  In either case the initial thread will not
> +    # complete its inferior call.
> +    if { $other_thread_bp } {
> +	gdb_breakpoint "${::srcfile}:${::segfault_line}"
> +	set segfault_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
> +				 "get number for segfault breakpoint"]
> +    }
> +
> +    # When non-stop mode is off we get slightly different output from GDB.
> +    if { [gdb_is_remote_or_extended_remote_target] && !$target_non_stop} {
> +	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" received signal SIGINT, Interrupt\\."
> +    } else {
> +	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\."
> +    }

Something is going on in this test that when testing against gdbserver with
all-stop, it is always Thread 2 that reports the SIGINT, which is coincidentally
the thread that was hitting the breakpoint and running the infcall, AFAICS.

 continue
 Continuing.
 [New Thread 3506594.3506599]
 [New Thread 3506594.3506600]
 [New Thread 3506594.3506601]
 [New Thread 3506594.3506602]
 [New Thread 3506594.3506603]

 Thread 2 "infcall-from-bp" received signal SIGINT, Interrupt.
__futex_abstimed_wait_common64 (private=<optimized out>, cancel=true, abstime=0x0, op=393, expected=0, futex_word=0x555555558080 <thread_1_semaphore>) at ./nptl/futex-internal.c:57

Why is that?

Normally, it's usually the main thread that manages to dequeue the signal
on the kernel side.  But it can really be any other thread.  Note
linux_process_target::request_interrupt() does:

  /* Send a SIGINT to the process group.  This acts just like the user
     typed a ^C on the controlling terminal.  */
  int res = ::kill (-signal_pid, SIGINT);

If the main thread is ptrace-stopped, then it will be another thread, so
I guess the main thread is stopped?  But where?

My point is that this is showing a weakness in the testcase.  I would
expect that (in all-stop with gdbserver) the SIGINT would be reported
for the main thread, and that would exercise the scenario that the thread
that is running the infcall is not the same as the thread that reports
the interruption signal.  I think that scenario should be exercised if
possible.  But the testcase as written somehow makes them be the same
threads, which might well hide problems with all-stop targets.

I realize that I'm reading the series out of order, and the answer may
be in the previous patch.  I guess I should read that in detail
first.  :-P

Pedro Alves


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

* Re: [PATCHv5 05/11] gdb: don't always print breakpoint location after failed condition check
  2023-07-11 12:06                 ` Pedro Alves
@ 2023-07-14 12:17                   ` Andrew Burgess
  2023-07-17 17:17                     ` Pedro Alves
  0 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2023-07-14 12:17 UTC (permalink / raw)
  To: Pedro Alves, gdb-patches

Pedro Alves <pedro@palves.net> writes:

> On 2023-07-07 22:18, Andrew Burgess wrote:
>> Pedro Alves <pedro@palves.net> writes:
>> 
>>> On 2023-07-07 16:20, Pedro Alves wrote:
>>>> I'd think the second *stopped shouldn't even be there at all, following the
>>>> logic used to remove the stop from the CLI.
>>>>
>>>> Maybe we should try moving or copying this "don't report this stop" logic to
>>>> fetch_inferior_event, to avoid calling the second normal_stop at all.
>>>> I gave it a quick try, but what I tried without thinking much about it
>>>> just hung GDB.  I didn't dig too much as I want to move on to review the rest
>>>> of your series.
>>>
>>> Here's the totally broken naive patch I tried.
>>>
>>> From e1fde974fa58351de9f6dc0661162d77fc8be078 Mon Sep 17 00:00:00 2001
>>> From: Pedro Alves <pedro@palves.net>
>>> Date: Fri, 7 Jul 2023 16:10:29 +0100
>>> Subject: [PATCH] mi
>>>
>>> Change-Id: Ie49a36dc67b9584c40daabfffae1f87f6dd98c5c
>>> ---
>>>  gdb/infrun.c | 11 +++++++----
>>>  1 file changed, 7 insertions(+), 4 deletions(-)
>>>
>>> diff --git a/gdb/infrun.c b/gdb/infrun.c
>>> index 3dd24fccf6e..ab1fd13abe0 100644
>>> --- a/gdb/infrun.c
>>> +++ b/gdb/infrun.c
>>> @@ -4395,6 +4395,8 @@ fetch_inferior_event ()
>>>      auto defer_delete_threads
>>>        = make_scope_exit (delete_just_stopped_threads_infrun_breakpoints);
>>>  
>>> +    stop_context saved_context;
>>> +
>>>      /* Now figure out what to do with the result of the result.  */
>>>      handle_inferior_event (&ecs);
>>>  
>>> @@ -4415,16 +4417,17 @@ fetch_inferior_event ()
>>>  	  }
>>>  	else
>>>  	  {
>>> -	    bool should_notify_stop = true;
>>>  	    bool proceeded = false;
>>>  
>>>  	    stop_all_threads_if_all_stop_mode ();
>>>  
>>>  	    clean_up_just_stopped_threads_fsms (&ecs);
>>>  
>>> -	    if (thr != nullptr && thr->thread_fsm () != nullptr)
>>> -	      should_notify_stop
>>> -	       = thr->thread_fsm ()->should_notify_stop ();
>>> +	    bool should_notify_stop
>>> +		= (!saved_context.changed ()
>>> +		   && thr != nullptr
>>> +		   && thr->thread_fsm () != nullptr
>>> +		   && thr->thread_fsm ()->should_notify_stop ());
>> 
>> So, I got this working, as in, not locking up GDB.  The problem was that
>> thr->thread_fsm() is often nullptr, so we end up never calling
>> normal_stop.
>> 
>> However, I don't think this is going to work out.  There's a couple of
>> problems.
>> 
>> First, at the point fetch_inferior_event is called, there is no thread
>> selected, so the ptid and thread captured in saved_context are always
>> null_ptid and nullptr respectively.  By the time we call
>> saved_context.changed() we do have a thread selected, so the context
>> appears to have always changed.
>
> Yeah.
>
>> However, I figured I could work around this be replacing the full
>> stop_context with a simple 'int stop_id = get_stop_id ();', I figured
>> this might be enough, this will tell me if GDB has notified the user of
>> a stop somewhere within the handle_inferior_event code.
>> 
>> This works fine in the sense that I do now correctly spot that the user
>> has been notified of a stop and don't call normal_stop again...
>> 
>> ... but as a consequence, GDB now doesn't realise that is has stopped,
>> and doesn't display a prompt back to the user.
>> 
>> I'm going to have to leave this for the weekend now, but will continue
>> looking at this next week.  I've included my WIP hack below.
>> 
>> Would be interested on whether you see any problems with just using
>> get_stop_id() to determine if the user has already seen a stop or not? 
>
> I don't see a problem offhand.

Pedro,

It took a little longer than I'd have liked, but I think I have
something which addresses the problems you pointed out.

Let me know what you think.

Thanks,
Andrew

---

commit bd3309a50423114c2cb31241500820efa21d0452
Author: Andrew Burgess <aburgess@redhat.com>
Date:   Wed Jul 12 21:56:50 2023 +0100

    gdb: avoid double stop after failed breakpoint condition check
    
    This commit replaces this earlier commit:
    
      commit 2e411b8c68eb2b035b31d5b00d940d4be1a0928b
      Date:   Fri Oct 14 14:53:15 2022 +0100
    
          gdb: don't always print breakpoint location after failed condition check
    
    and is a result of feedback received here[1].
    
    The original commit addressed a problem where, if a breakpoint
    condition included an inferior function call, and if the inferior
    function call fail, then GDB would announce the stop twice.  Here's an
    example of GDB's output before the above commit that shows the problem
    being addressed:
    
      (gdb) break foo if (some_func ())
      Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
      (gdb) r
      Starting program: /tmp/bpcond
    
      Program received signal SIGSEGV, Segmentation fault.
      0x0000000000401116 in some_func () at bpcond.c:5
      5       return *p;
      Error in testing condition for breakpoint 1:
      The program being debugged stopped while in a function called from GDB.
      Evaluation of the expression containing the function
      (some_func) will be abandoned.
      When the function is done executing, GDB will silently stop.
    
      Breakpoint 1, 0x0000000000401116 in some_func () at bpcond.c:5
      5       return *p;
      (gdb)
    
    The original commit addressed this issue in breakpoint.c, by spotting
    that the $pc had changed while evaluating the breakpoint condition,
    and inferring from this that GDB must have stopped elsewhere.
    
    However, the way in which the original commit suppressed the second
    stop announcement was to set bpstat::print to true -- this tells GDB
    not to print the frame during the stop announcement, and for the CLI
    this is fine, however, it was pointed out that for the MI this still
    isn't really enough.  Below is an example from an MI session after the
    above commit was applied, this shows the problem with the above
    commit:
    
      -break-insert -c "cond_fail()" foo
      ^done,bkpt={number="1",type="breakpoint",disp="keep",enabled="y",addr="0x000000000040111e",func="foo",file="/tmp/mi-condbreak-fail.c",line="30",thread-groups=["i1"],cond="cond_fail()",times="0",original-location="foo"}
      (gdb)
      -exec-run
      =thread-group-started,id="i1",pid="2636270"
      =thread-created,id="1",group-id="i1"
      =library-loaded,id="/lib64/ld-linux-x86-64.so.2",target-name="/lib64/ld-linux-x86-64.so.2",host-name="/lib64/ld-linux-x86-64.so.2",symbols-loaded="0",thread-group="i1",ranges=[{from="0x00007ffff7fd3110",to="0x00007ffff7ff2bb4"}]
      ^running
      *running,thread-id="all"
      (gdb)
      =library-loaded,id="/lib64/libm.so.6",target-name="/lib64/libm.so.6",host-name="/lib64/libm.so.6",symbols-loaded="0",thread-group="i1",ranges=[{from="0x00007ffff7e59390",to="0x00007ffff7ef4f98"}]
      =library-loaded,id="/lib64/libc.so.6",target-name="/lib64/libc.so.6",host-name="/lib64/libc.so.6",symbols-loaded="0",thread-group="i1",ranges=[{from="0x00007ffff7ca66b0",to="0x00007ffff7df3c5f"}]
      ~"\nProgram"
      ~" received signal SIGSEGV, Segmentation fault.\n"
      ~"0x0000000000401116 in cond_fail () at /tmp/mi-condbreak-fail.c:24\n"
      ~"24\t  return *p;\t\t\t/* Crash here.  */\n"
      *stopped,reason="signal-received",signal-name="SIGSEGV",signal-meaning="Segmentation fault",frame={addr="0x0000000000401116",func="cond_fail",args=[],file="/tmp/mi-condbreak-fail.c",fullname="/tmp/mi-condbreak-fail.c",line="24",arch="i386:x86-64"},thread-id="1",stopped-threads="all",core="9"
      &"Error in testing condition for breakpoint 1:\n"
      &"The program being debugged was signaled while in a function called from GDB.\n"
      &"GDB remains in the frame where the signal was received.\n"
      &"To change this behavior use \"set unwindonsignal on\".\n"
      &"Evaluation of the expression containing the function\n"
      &"(cond_fail) will be abandoned.\n"
      &"When the function is done executing, GDB will silently stop.\n"
      =breakpoint-modified,bkpt={number="1",type="breakpoint",disp="keep",enabled="y",addr="0x000000000040111e",func="foo",file="/tmp/mi-condbreak-fail.c",fullname="/tmp/mi-condbreak-fail.c",line="30",thread-groups=["i1"],cond="cond_fail()",times="1",original-location="foo"}
      *stopped
      (gdb)
    
    Notice that we still see two '*stopped' lines, the first includes the
    full frame information, while the second has no frame information,
    this is a result of bpstat::print having been set.  Ideally, the
    second '*stopped' line should not be present.
    
    By setting bpstat::print I was addressing the problem too late, this
    flag really only changes how interp::on_normal_stop prints the stop
    event, and interp::on_normal_stop is called (indirectly) from the
    normal_stop function in infrun.c.  A better solution is to avoid
    calling normal_stop at all for the stops which should not be reported
    to the user, and this is what I do in this commit.
    
    This commit has 3 parts:
    
      1. In breakpoint.c, revert the above commit,
    
      2. In fetch_inferior_event (infrun.c), capture the stop-id before
      calling handle_inferior_event.  If, after calling
      handle_inferior_event, the stop-id has changed, then this indicates
      that somewhere within handle_inferior_event, a stop was announced to
      the user.  If this is the case then GDB should not call normal_stop,
      and we should rely on whoever announced the stop to ensure that we
      are in a PROMPT_NEEDED state, which means the prompt will be
      displayed once fetch_inferior_event returns.  And,
    
      3. In infcall.c, do two things:
    
         (a) In run_inferior_call, after making the inferior call, ensure
         that either async_disable_stdin or async_enable_stdin is called
         to put the prompt state, and stdin handling into the correct
         state based on whether the inferior call completed successfully
         or not, and
    
         (b) In call_thread_fsm::should_stop, call async_enable_stdin
         rather than changing the prompt state directly.  This isn't
         strictly necessary, but helped me understand this code more.
         This async_enable_stdin call is only reached if normal_stop is
         not going to be called, and replaces the async_enable_stdin call
         that exists in normal_stop.  Though we could just adjust the
         prompt state if felt (to me) much easier to understand when I
         could see this call and the corresponding call in normal_stop.
    
    With these changes in place now, when the inferior call (from the
    breakpoint condition) fails, infcall.c leaves the prompt state as
    PROMPT_NEEDED, and leaves stdin registered with the event loop.
    
    Back in fetch_inferior_event GDB notices that the stop-id has changed
    and so avoids calling normal_stop.
    
    And on return from fetch_inferior_event GDB will display the prompt
    and handle input from stdin.
    
    As normal_stop is not called the MI problem is solved, and the test
    added in the earlier mentioned commit still passes just fine, so the
    CLI has not regressed.
    
    [1] https://inbox.sourceware.org/gdb-patches/6fd4aa13-6003-2563-5841-e80d5a55d59e@palves.net/

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index d898167b7e1..93634bd7e51 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -5535,7 +5535,6 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
 	  else
 	    within_current_scope = false;
 	}
-      CORE_ADDR pc_before_check = get_frame_pc (get_selected_frame (nullptr));
       if (within_current_scope)
 	{
 	  try
@@ -5555,17 +5554,6 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
 		  (gdb_stderr, ex,
 		   "Error in testing condition for breakpoint %d:\n",
 		   b->number);
-
-	      /* If the pc value changed as a result of evaluating the
-		 condition then we probably stopped within an inferior
-		 function call due to some unexpected stop, e.g. the thread
-		 hit another breakpoint, or the thread received an
-		 unexpected signal.  In this case we don't want to also
-		 print the information about this breakpoint.  */
-	      CORE_ADDR pc_after_check
-		= get_frame_pc (get_selected_frame (nullptr));
-	      if (pc_before_check != pc_after_check)
-		bs->print = 0;
 	    }
 	}
       else
diff --git a/gdb/infcall.c b/gdb/infcall.c
index ddf325a62a5..0944097e18d 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -564,10 +564,13 @@ call_thread_fsm::should_stop (struct thread_info *thread)
 	 call..  */
       return_value = get_call_return_value (&return_meta_info);
 
-      /* Break out of wait_sync_command_done.  */
+      /* Break out of wait_sync_command_done.  This is similar to the
+	 async_enable_stdin call in normal_stop (which we don't call),
+	 however, in this case we only change the WAITING_UI, this is
+	 enough for wait_sync_command_done.  */
       scoped_restore save_ui = make_scoped_restore (&current_ui, waiting_ui);
-      target_terminal::ours ();
-      waiting_ui->prompt_state = PROMPT_NEEDED;
+      gdb_assert (current_ui->prompt_state == PROMPT_BLOCKED);
+      async_enable_stdin ();
     }
 
   return true;
@@ -661,14 +664,30 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
   infcall_debug_printf ("thread is now: %s",
 			inferior_ptid.to_string ().c_str ());
 
-  /* If GDB has the prompt blocked before, then ensure that it remains
-     so.  normal_stop calls async_enable_stdin, so reset the prompt
-     state again here.  In other cases, stdin will be re-enabled by
-     inferior_event_handler, when an exception is thrown.  */
+  /* After the inferior call async_enable_stdin has been called, either
+     from normal_stop or from call_thread_fsm::should_stop, and the prompt
+     state has been restored by the scoped_restore in the try block above.
+
+     If the inferior call finished successfully then we should disable
+     stdin as we don't know yet whether the inferior will be stopping,
+     calling async_disable_stdin restores things as they were when this
+     function was called.
+
+     If the inferior call didn't complete successfully then normal_stop has
+     already been called, and we know for sure that we are going to present
+     this stop to the user, in this case we call async_enable_stdin, this
+     changes the prompt state to PROMPT_NEEDED.
+
+     If the previous prompt state was PROMPT_NEEDED then, as
+     async_enable_stdin has already been called, nothing additional needs
+     to be done here.  */
   if (current_ui->prompt_state == PROMPT_BLOCKED)
-    current_ui->unregister_file_handler ();
-  else
-    current_ui->register_file_handler ();
+    {
+      if (call_thread->thread_fsm ()->finished_p ())
+	async_disable_stdin ();
+      else
+	async_enable_stdin ();
+    }
 
   /* If the infcall does NOT succeed, normal_stop will have already
      finished the thread states.  However, on success, normal_stop
diff --git a/gdb/infrun.c b/gdb/infrun.c
index 58da1cef29e..95ab7c6f7dc 100644
--- a/gdb/infrun.c
+++ b/gdb/infrun.c
@@ -4395,6 +4395,8 @@ fetch_inferior_event ()
     auto defer_delete_threads
       = make_scope_exit (delete_just_stopped_threads_infrun_breakpoints);
 
+    int stop_id = get_stop_id ();
+
     /* Now figure out what to do with the result of the result.  */
     handle_inferior_event (&ecs);
 
@@ -4422,7 +4424,19 @@ fetch_inferior_event ()
 
 	    clean_up_just_stopped_threads_fsms (&ecs);
 
-	    if (thr != nullptr && thr->thread_fsm () != nullptr)
+	    if (stop_id != get_stop_id ())
+	      {
+		/* If the stop-id has changed then a stop has already been
+		   presented to the user in handle_inferior_event, this is
+		   likely a failed inferior call.  As the stop has already
+		   been announced then we should not notify again.
+
+		   Also, if the prompt state is not PROMPT_NEEDED then GDB
+		   will not be ready for user input after this function.  */
+		should_notify_stop = false;
+		gdb_assert (current_ui->prompt_state == PROMPT_NEEDED);
+	      }
+	    else if (thr != nullptr && thr->thread_fsm () != nullptr)
 	      should_notify_stop
 	       = thr->thread_fsm ()->should_notify_stop ();
 
diff --git a/gdb/testsuite/gdb.mi/mi-condbreak-fail.c b/gdb/testsuite/gdb.mi/mi-condbreak-fail.c
new file mode 100644
index 00000000000..94bd2484934
--- /dev/null
+++ b/gdb/testsuite/gdb.mi/mi-condbreak-fail.c
@@ -0,0 +1,39 @@
+/* Copyright 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/>.  */
+
+volatile int global_counter = 0;
+
+int
+cond_fail ()
+{
+  volatile int *p = 0;
+  return *p;			/* Crash here.  */
+}
+
+int
+foo ()
+{
+  global_counter += 1;		/* Set breakpoint here.  */
+  return 0;
+}
+
+int
+main ()
+{
+  int res = foo ();
+  return res;
+}
diff --git a/gdb/testsuite/gdb.mi/mi-condbreak-fail.exp b/gdb/testsuite/gdb.mi/mi-condbreak-fail.exp
new file mode 100644
index 00000000000..86b1db5a8dd
--- /dev/null
+++ b/gdb/testsuite/gdb.mi/mi-condbreak-fail.exp
@@ -0,0 +1,67 @@
+# Copyright (C) 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/>.
+
+# Check that when GDB fails to evaluate the condition of a conditional
+# breakpoint we only get one *stopped message.
+
+load_lib mi-support.exp
+set MIFLAGS "-i=mi"
+
+standard_testfile
+
+if [build_executable ${testfile}.exp ${binfile} ${srcfile}] {
+    return -1
+}
+
+if {[mi_clean_restart $binfile]} {
+    return
+}
+
+if {[mi_runto_main] == -1} {
+    return
+}
+
+# Create the conditional breakpoint.
+set bp_location [gdb_get_line_number "Set breakpoint here"]
+mi_create_breakpoint "-c \"cond_fail ()\" $srcfile:$bp_location" \
+    "insert conditional breakpoint" \
+    -func foo -file ".*$srcfile" -line "$bp_location" \
+    -cond "cond_fail \\(\\)"
+
+# Number of the previous breakpoint.
+set bpnum [mi_get_valueof "/d" "\$bpnum" "INVALID" \
+	       "get number for breakpoint"]
+
+# The line where we expect the inferior to crash.
+set crash_linenum [gdb_get_line_number "Crash here"]
+
+# Run the inferior and wait for it to stop.
+mi_send_resuming_command "exec-continue" "continue the inferior"
+mi_gdb_test "" \
+    [multi_line \
+	 "~\"\\\\nProgram\"" \
+	 "~\" received signal SIGSEGV, Segmentation fault\\.\\\\n\"" \
+	 "~\"$hex in cond_fail \\(\\) at \[^\r\n\]+\"" \
+	 "~\"${crash_linenum}\\\\t\\s+return \\*p;\[^\r\n\]+\\\\n\"" \
+	 "\\*stopped,reason=\"signal-received\",signal-name=\"SIGSEGV\"\[^\r\n\]+" \
+	 "&\"Error in testing condition for breakpoint $bpnum:\\\\n\"" \
+	 "&\"The program being debugged was signaled while in a function called from GDB\\.\\\\n\"" \
+	 "&\"GDB remains in the frame where the signal was received\\.\\\\n\"" \
+	 "&\"To change this behavior use \\\\\"set unwindonsignal on\\\\\"\\.\\\\n\"" \
+	 "&\"Evaluation of the expression containing the function\\\\n\"" \
+	 "&\"\\(cond_fail\\) will be abandoned\\.\\\\n\"" \
+	 "&\"When the function is done executing, GDB will silently stop\\.\\\\n\"" \
+	 "=breakpoint-modified,bkpt={number=\"$bpnum\",type=\"breakpoint\",.*}"] \
+    "wait for stop"


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

* Re: [PATCHv6 3/6] gdb: add timeouts for inferior function calls
  2023-07-11 14:23             ` Pedro Alves
@ 2023-07-14 15:20               ` Andrew Burgess
  2023-07-14 19:52                 ` Andrew Burgess
  0 siblings, 1 reply; 202+ messages in thread
From: Andrew Burgess @ 2023-07-14 15:20 UTC (permalink / raw)
  To: Pedro Alves, gdb-patches

Pedro Alves <pedro@palves.net> writes:

> On 2023-04-03 15:01, Andrew Burgess via Gdb-patches wrote:
>
>> diff --git a/gdb/NEWS b/gdb/NEWS
>> index 10a1a70fa52..70987994e7b 100644
>> --- a/gdb/NEWS
>> +++ b/gdb/NEWS
>> @@ -96,6 +96,24 @@ info main
>>     $2 = 1
>>     (gdb) break func if $_shell("some command") == 0
>>  
>> +set direct-call-timeout SECONDS
>> +show direct-call-timeout
>> +set indirect-call-timeout SECONDS
>> +show indirect-call-timeout
>> +  These new settings can be used to limit how long GDB will wait for
>> +  an inferior function call to complete.  The direct timeout is used
>> +  for inferior function calls from e.g. 'call' and 'print' commands,
>> +  while the indirect timeout is used for inferior function calls from
>> +  within a conditional breakpoint expression.
>
> What happens with expressions in other commands, basically any command that
> accepts an expression?  For example, "x foo()".  Are those direct, or
> indirect?  I assume direct?

Correct, these would be direct.  I struggled to come up with a good
name, but the basic idea was:

  direct -- user enters a command and as a result GDB performs an
            inferior function call.  The user can only enter the next
            command once the first command (and hence inferior call) has
            completed.

  indirect -- user enters a command that accepts an expression,
              e.g. breakpoint condition, but the expression is only
              evaluated at some future time which is largely outside of
              the users control, e.g. when the inferior hits the
              breakpoint.  The user might not even be aware that the
              inferior call is taking place (as b/p conditions are not
              announced until they complete or timeout).

>
> I wonder whether you have plans/ideas for other kinds of indirect calls.
> Just thinking about whether naming the option as something about
> "breakpoint-condition" wouldn't be better by being more direct (ah!) and
> to the point, while leaving the possibility of other kinds of situations
> having different timeouts.  to avoid long command names, we could have
> a prefix setting, like:

I guess we could, but I'm not sure why a user might want such fine
grained control -- they want to limit how long a breakpoint condition
can take to evaluate, but want a different limit on some-other indirect
case.  This just seems overly complex, surely you'd just pick a timeout
that satisfies your expected worst case and go with that.

To be honest, the reason I initially split direct and indirect is so
that the direct case could be unlimited to match GDB's current
behaviour.  But, now I've written it, I do think there's an argument
that a user might want to allow direct calls to take longer.  In the
direct case the user is (hopefully) aware that an inferior call has
taken place, and can manually interrupt if the call is taking too long,
so I think this split does make sense.

>
>  set call-timeout direct  # maybe there's a better name for this.
>  set call-timeout breakpoint-conditions
>  set call-timeout some-other-case
>
> Just some thoughts, by no way am I objecting to what you have.
>
>> +
>> +  The default for the direct timeout is unlimited, while the default
>> +  for the indirect timeout is 30 seconds.
>
> While working on Windows non-stop support recently, I noticed that
> gdb.threads/multiple-successive-infcall.exp has infcalls that would
> just hang "forever", the infcall never completed.  The test
> enables schedlock, and then calls a function in each thread in the
> program [like, (gdb) p get_value()].  The issue turns out to be about
> calling a function in a thread that is currently running Windows kernel
> code.  On Linux, most system calls are interruptible (EINTR), and
> restartable.  When the debugger pauses a thread and the thread is in a
> syscall, the syscall is interrupted and restarted later when the thread
> is resumed.  On Windows, system calls are NOT interruptible.  The threads
> in question in the testcase were stopped inside the syscall done by
> ntdll!ZwWaitForMultipleObjects.  In that scenario, you can still pause the
> hung thread with Ctrl-C, and you'll see that the (userspace) PC of the thread
> in question hasn't changed, it is still pointing to the entry to the
> function GDB wants to call -- not surprising since the thread is really
> still blocked inside the syscall and never ran any userspace instruction.
>
> This looks like something that Windows GDB users are likely to trip on more
> frequently than GNU/Linux users.
>
> So I looked at how Visual Studio (not vscode) handles it, to check how it 
> handles this, maybe it just doesn't let you call functions on threads that are
> stopped inside a syscall?  Nope.  You guessed it, it handles it with a timeout.
> If you add a watch expression (like a gdb "display") involving infcall, and the thread
> is in kernel code, VS will still try the call, and then after a few short
> seconds (maybe some 5s), it aborts the expression, popping a dialog box informing
> you about it.
>
> All that to say that I would think it reasonable to default to a
> shorter timeout in GDB too.
>
> Actually, I remembered now that LLDB also has a timeout for infcalls.
> On the version I have handy installed, "help expression" talks about
> a timeout of "currently .25 seconds", and then retrying with all threads
> running, (that's 0.25s, not 25s IIUC, curiously, higher resolution than
> second), but I don't know how long that second retry has for timeout,
> if it has one.
>
> For breakpoint conditions, I think it may be nice (but not a
> requirement of this patch, just an idea) if after some time less than
> the whole timeout time, for GDB to print a warning, something like:
>
>  warning: a function call in the condition of breakpoint 2.3 is taking long.
>
> Like, we could print that warning after 1 second, even if the timeout
> is set to higher than that.
>
> Anyhow, all that is a lot easier to code than debate and it can always
> be done later.
>
>> +
>> +  These timeouts will only have an effect for targets that are
>> +  operating in async mode.  For non-async targets the timeouts are
>> +  ignored, GDB will wait indefinitely for an inferior function to
>> +  complete, unless interrupted by the user using Ctrl-C.
>> +
>>  * MI changes
>>  
>>  ** mi now reports 'no-history' as a stop reason when hitting the end of the
>> diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
>> index fe76e5e0a0e..46f17798510 100644
>> --- a/gdb/doc/gdb.texinfo
>> +++ b/gdb/doc/gdb.texinfo
>> @@ -20885,6 +20885,72 @@
>>  @code{step}, etc).  In this case, when the inferior finally returns to
>>  the dummy-frame, @value{GDBN} will once again halt the inferior.
>>  
>> +On targets that support asynchronous execution (@pxref{Background
>> +Execution}) @value{GDBN} can place a timeout on any functions called
>> +from @value{GDBN}.  If the timeout expires and the function call is
>> +still ongoing, then @value{GDBN} will interrupt the program.
>
> In the patch introducing "set unwind-on-timeout", I think it would be
> good to mention the setting here.  I didn't notice it being added there.
> Because, as I read this, I wondered "OK, but what happens after GDB
> interrupts the program?  Do we unwind according to set unwind-on-signal?" .
>
>> +
>> +For targets that don't support asynchronous execution
>> +(@pxref{Background Execution}) then timeouts for functions called from
>> +@value{GDBN} are not supported, the timeout settings described below
>> +will be treated as @code{unlimited}, meaning @value{GDBN} will wait
>> +indefinitely for function call to complete, unless interrupted by the
>> +user using @kbd{Ctrl-C}.
>> +
>
> ...
>
>> diff --git a/gdb/infcall.c b/gdb/infcall.c
>> index 4fb8ab07db0..bb57faf700f 100644
>> --- a/gdb/infcall.c
>> +++ b/gdb/infcall.c
>> @@ -95,6 +95,53 @@ show_may_call_functions_p (struct ui_file *file, int from_tty,
>>  	      value);
>>  }
>>  
>> +/* A timeout (in seconds) for direct inferior calls.  A direct inferior
>> +   call is one the user triggers from the prompt, e.g. with a 'call' or
>> +   'print' command.  Compare with the definition of indirect calls below.  */
>> +
>> +static unsigned int direct_call_timeout = UINT_MAX;
>> +
>> +/* Implement 'show direct-call-timeout'.  */
>> +
>> +static void
>> +show_direct_call_timeout (struct ui_file *file, int from_tty,
>> +			  struct cmd_list_element *c, const char *value)
>> +{
>> +  if (target_has_execution () && !target_can_async_p ())
>> +    gdb_printf (file, _("Current target does not support async mode, timeout "
>> +			"for direct inferior calls is \"unlimited\".\n"));
>> +  else if (direct_call_timeout == UINT_MAX)
>> +    gdb_printf (file, _("Timeout for direct inferior function calls "
>> +			"is \"unlimited\".\n"));
>> +  else
>> +    gdb_printf (file, _("Timeout for direct inferior function calls "
>> +			"is \"%s seconds\".\n"), value);
>> +}
>> +
>> +/* A timeout (in seconds) for indirect inferior calls.  An indirect inferior
>> +   call is one that originates from within GDB, for example, when
>> +   evaluating an expression for a conditional breakpoint.  Compare with
>> +   the definition of direct calls above.  */
>> +
>> +static unsigned int indirect_call_timeout = 30;
>> +
>> +/* Implement 'show indirect-call-timeout'.  */
>> +
>> +static void
>> +show_indirect_call_timeout (struct ui_file *file, int from_tty,
>> +			  struct cmd_list_element *c, const char *value)
>> +{
>> +  if (target_has_execution () && !target_can_async_p ())
>> +    gdb_printf (file, _("Current target does not support async mode, timeout "
>> +			"for indirect inferior calls is \"unlimited\".\n"));
>> +  else if (indirect_call_timeout == UINT_MAX)
>> +    gdb_printf (file, _("Timeout for indirect inferior function calls "
>> +			"is \"unlimited\".\n"));
>> +  else
>> +    gdb_printf (file, _("Timeout for indirect inferior function calls "
>> +			"is \"%s seconds\".\n"), value);
>> +}
>> +
>>  /* How you should pass arguments to a function depends on whether it
>>     was defined in K&R style or prototype style.  If you define a
>>     function using the K&R syntax that takes a `float' argument, then
>> @@ -589,6 +636,86 @@ call_thread_fsm::should_notify_stop ()
>>    return true;
>>  }
>>  
>> +/* A class to control creation of a timer that will interrupt a thread
>> +   during an inferior call.  */
>> +struct infcall_timer_controller
>> +{
>> +  /* Setup an event-loop timer that will interrupt PTID if the inferior
>> +     call takes too long.  DIRECT_CALL_P is true when this inferior call is
>> +     a result of the user using a 'print' or 'call' command, and false when
>> +     this inferior call is a result of e.g. a conditional breakpoint
>> +     expression, this is used to select which timeout to use.  */
>> +  infcall_timer_controller (thread_info *thr, bool direct_call_p)
>> +    : m_thread (thr)
>> +  {
>> +    unsigned int timeout
>> +      = direct_call_p ? direct_call_timeout : indirect_call_timeout;
>> +    if (timeout < UINT_MAX && target_can_async_p ())
>> +      {
>> +	int ms = timeout * 1000;
>> +	int id = create_timer (ms, infcall_timer_controller::timed_out, this);
>> +	m_timer_id.emplace (id);
>> +	infcall_debug_printf ("Setting up infcall timeout timer for "
>> +			      "ptid %s: %d milliseconds",
>> +			      m_thread->ptid.to_string ().c_str (), ms);
>> +      }
>> +  }
>> +
>> +  /* Destructor.  Ensure that the timer is removed from the event loop.  */
>> +  ~infcall_timer_controller ()
>> +  {
>> +    /* If the timer has already triggered, then it will have already been
>> +       deleted from the event loop.  If the timer has not triggered, then
>> +       delete it now.  */
>> +    if (m_timer_id.has_value () && !m_triggered)
>> +      delete_timer (*m_timer_id);
>> +
>> +    /* Just for clarity, discard the timer id now.  */
>> +    m_timer_id.reset ();
>> +  }
>> +
>> +  /* Return true if there was a timer in place, and the timer triggered,
>> +     otherwise, return false.  */
>> +  bool triggered_p ()
>> +  {
>> +    gdb_assert (!m_triggered || m_timer_id.has_value ());
>> +    return m_triggered;
>> +  }
>> +
>> +private:
>> +  /* The thread we should interrupt.  */
>> +  thread_info *m_thread;
>> +
>> +  /* Set true when the timer is triggered.  */
>> +  bool m_triggered = false;
>> +
>> +  /* Given a value when a timer is in place.  */
>> +  gdb::optional<int> m_timer_id;
>> +
>> +  /* Callback for the timer, forwards to ::trigger below.  */
>> +  static void
>> +  timed_out (gdb_client_data context)
>> +  {
>> +    infcall_timer_controller *ctrl
>> +      = static_cast<infcall_timer_controller *> (context);
>> +    ctrl->trigger ();
>> +  }
>> +
>> +  /* Called when the timer goes off.  Stop thread m_thread.  */
>
> Uppercase M_THREAD.

Fixed.

>
>> +  void
>> +  trigger ()
>> +  {
>> +    m_triggered = true;
>> +
>> +    scoped_disable_commit_resumed disable_commit_resumed ("infcall timeout");
>> +
>> +    infcall_debug_printf ("Stopping thread %s",
>> +			  m_thread->ptid.to_string ().c_str ());
>> +    target_stop (m_thread->ptid);
>> +    m_thread->stop_requested = true;
>
> As per the discussion in the remote patch, I think this will need
> to be adjusted.  Maybe something like:
>
>     if (target_is_non_stop_p ())
>       {
>         target_stop (m_thread->ptid);
>         m_thread->stop_requested = true;
>       }
>     else
>       target_interrupt ();

I understand your critique of the 'avoid SIGINT after calling
remote_target::stop' patch, but I don't understand this comment.  What
we want to do is stop the target, not interrupt it, thus, surely, we
should call target_stop.

The fact that we can't target_stop for a !non-stop target is surely
something the target should deal with.  And indeed, if we check out
remote_target::stop we see that for !non-stop target we call
remote_interrupt_as.  In contrast, calling remote_target::interrupt for
a !non-stop target also calls remote_interrupt_as, which I think is very
much the point of your critique, right?

My thinking here is that, if we _did_ come up with some clever way to
support ::stop for a !non-stop target, this code would be added to
remote_target::stop, but _not_ to remote_target::interrupt, so we should
call the function that matches our intention, even if, right now, GDB
can't actually satisfy our needs.

>
>> +  }
>> +};
>> +
>>  /* Subroutine of call_function_by_hand to simplify it.
>>     Start up the inferior and wait for it to stop.
>>     Return the exception if there's an error, or an exception with
>> @@ -599,13 +726,15 @@ call_thread_fsm::should_notify_stop ()
>>  
>>  static struct gdb_exception
>>  run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
>> -		   struct thread_info *call_thread, CORE_ADDR real_pc)
>> +		   struct thread_info *call_thread, CORE_ADDR real_pc,
>> +		   bool *timed_out_p)
>>  {
>>    INFCALL_SCOPED_DEBUG_ENTER_EXIT;
>>  
>>    struct gdb_exception caught_error;
>>    ptid_t call_thread_ptid = call_thread->ptid;
>>    int was_running = call_thread->state == THREAD_RUNNING;
>> +  *timed_out_p = false;
>>  
>>    infcall_debug_printf ("call function at %s in thread %s, was_running = %d",
>>  			core_addr_to_string (real_pc),
>> @@ -617,6 +746,16 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
>>    scoped_restore restore_in_infcall
>>      = make_scoped_restore (&call_thread->control.in_infcall, 1);
>>  
>> +  /* If the thread making the inferior call stops with a time out then the
>> +     stop_requested flag will be set.  However, we don't want changes to
>> +     this flag to leak back to our caller, we might be here to handle an
>> +     inferior call from a breakpoint condition, so leaving this flag set
>> +     would appear that the breakpoint stop was actually a requested stop,
>> +     which is not true, and will cause GDB to print extra messages to the
>> +     output.  */
>> +  scoped_restore restore_stop_requested
>> +    = make_scoped_restore (&call_thread->stop_requested, false);
>
> I'm confused by this.  If stop_requested was set when the breakpoint was hit,
> are we still evaluating the breakpoint condition (and re-resuming the thread
> if the condition is false) ?

I don't really understand your question here, but I don't think that it
matters now.  This stop_requested stuff was only in place to support the
'avoid SIGINT after calling remote_target::stop' patch (the next one),
which I'm going to drop after your feedback.

>
>> +
>>    clear_proceed_status (0);
>>  
>
>> --- /dev/null
>> +++ b/gdb/testsuite/gdb.base/infcall-timeout.c
>> @@ -0,0 +1,36 @@
>> +/* Copyright 2022-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 <unistd.h>
>> +
>> +/* This function is called from GDB.  */
>> +int
>> +function_that_never_returns ()
>> +{
>> +  while (1)
>> +    sleep (1);
>> +
>> +  return 0;
>> +}
>> +
>> +int
>> +main ()
>> +{
>> +  alarm (300);
>> +
>> +  return 0;
>> +}
>> diff --git a/gdb/testsuite/gdb.base/infcall-timeout.exp b/gdb/testsuite/gdb.base/infcall-timeout.exp
>
>
> ...
>
>> +standard_testfile
>> +
>> +if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
>> +	  {debug}] == -1 } {
>> +    return
>> +}
>> +
>> +# Start GDB according to TARGET_ASYNC and TARGET_NON_STOP, then adjust
>> +# the direct-call-timeout, and make an inferior function call that
>> +# will never return.  GDB should eventually timeout and stop the
>> +# inferior.
>> +proc_with_prefix run_test { target_async target_non_stop } {
>> +    save_vars { ::GDBFLAGS } {
>> +	append ::GDBFLAGS \
>> +	    " -ex \"maint set target-non-stop $target_non_stop\""
>
> It's curious that target-non-stop on|off is tested, but not "set non-stop on".

I've extended the tests to cover this case.

>
>> +	append ::GDBFLAGS \
>> +	    " -ex \"maintenance set target-async ${target_async}\""
>> +
>> +	clean_restart ${::binfile}
>> +    }
>> +
>
> ...
>
>> diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
>> new file mode 100644
>> index 00000000000..4159288a39c
>> --- /dev/null
>> +++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
>
> ...
>
>> +
>> +    gdb_breakpoint \
>> +	"${::srcfile}:${::cond_bp_line} if (condition_func ())"
>> +    set bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
>> +		    "get number for conditional breakpoint"]
>> +
>> +    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
>> +    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
>> +			  "get number for final breakpoint"]
>> +
>> +    # The thread performing an inferior call relies on a second
>> +    # thread.  The second thread will segfault unless it hits a
>> +    # breakpoint first.  In either case the initial thread will not
>> +    # complete its inferior call.
>> +    if { $other_thread_bp } {
>> +	gdb_breakpoint "${::srcfile}:${::segfault_line}"
>> +	set segfault_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
>> +				 "get number for segfault breakpoint"]
>> +    }
>> +
>> +    # When non-stop mode is off we get slightly different output from GDB.
>> +    if { [gdb_is_remote_or_extended_remote_target] && !$target_non_stop} {
>> +	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" received signal SIGINT, Interrupt\\."
>> +    } else {
>> +	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\."
>> +    }
>
> Something is going on in this test that when testing against gdbserver with
> all-stop, it is always Thread 2 that reports the SIGINT, which is coincidentally
> the thread that was hitting the breakpoint and running the infcall, AFAICS.
>
>  continue
>  Continuing.
>  [New Thread 3506594.3506599]
>  [New Thread 3506594.3506600]
>  [New Thread 3506594.3506601]
>  [New Thread 3506594.3506602]
>  [New Thread 3506594.3506603]
>
>  Thread 2 "infcall-from-bp" received signal SIGINT, Interrupt.
> __futex_abstimed_wait_common64 (private=<optimized out>, cancel=true, abstime=0x0, op=393, expected=0, futex_word=0x555555558080 <thread_1_semaphore>) at ./nptl/futex-internal.c:57
>
> Why is that?

The answer lies in the 'gdb: fix b/p conditions with infcalls in
multi-threaded inferiors' patch, specifically the change to
user_visible_resume_ptid, which ensures that, when evaluating a B/P
condition, only the thread evaluating the condition is resumed.

The code didn't originate with me[1], but I didn't question it too much
when I incorporated it into this series, and maybe I should have.

I wonder if in all-stop mode we should be resuming all threads when
evaluating the condition?

I'll think about this some more follow up..

[1] https://inbox.sourceware.org/gdb-patches/20201009112719.629-3-natalia.saiapova@intel.com/

Thanks,
Andrew

>
> Normally, it's usually the main thread that manages to dequeue the signal
> on the kernel side.  But it can really be any other thread.  Note
> linux_process_target::request_interrupt() does:
>
>   /* Send a SIGINT to the process group.  This acts just like the user
>      typed a ^C on the controlling terminal.  */
>   int res = ::kill (-signal_pid, SIGINT);
>
> If the main thread is ptrace-stopped, then it will be another thread, so
> I guess the main thread is stopped?  But where?
>
> My point is that this is showing a weakness in the testcase.  I would
> expect that (in all-stop with gdbserver) the SIGINT would be reported
> for the main thread, and that would exercise the scenario that the thread
> that is running the infcall is not the same as the thread that reports
> the interruption signal.  I think that scenario should be exercised if
> possible.  But the testcase as written somehow makes them be the same
> threads, which might well hide problems with all-stop targets.
>
> I realize that I'm reading the series out of order, and the answer may
> be in the previous patch.  I guess I should read that in detail
> first.  :-P
>
> Pedro Alves


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

* Re: [PATCHv6 3/6] gdb: add timeouts for inferior function calls
  2023-07-14 15:20               ` Andrew Burgess
@ 2023-07-14 19:52                 ` Andrew Burgess
  0 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-07-14 19:52 UTC (permalink / raw)
  To: Pedro Alves, gdb-patches

Andrew Burgess <aburgess@redhat.com> writes:

> Pedro Alves <pedro@palves.net> writes:
>
>> On 2023-04-03 15:01, Andrew Burgess via Gdb-patches wrote:
>>
>>> diff --git a/gdb/NEWS b/gdb/NEWS
>>> index 10a1a70fa52..70987994e7b 100644
>>> --- a/gdb/NEWS
>>> +++ b/gdb/NEWS
>>> @@ -96,6 +96,24 @@ info main
>>>     $2 = 1
>>>     (gdb) break func if $_shell("some command") == 0
>>>  
>>> +set direct-call-timeout SECONDS
>>> +show direct-call-timeout
>>> +set indirect-call-timeout SECONDS
>>> +show indirect-call-timeout
>>> +  These new settings can be used to limit how long GDB will wait for
>>> +  an inferior function call to complete.  The direct timeout is used
>>> +  for inferior function calls from e.g. 'call' and 'print' commands,
>>> +  while the indirect timeout is used for inferior function calls from
>>> +  within a conditional breakpoint expression.
>>
>> What happens with expressions in other commands, basically any command that
>> accepts an expression?  For example, "x foo()".  Are those direct, or
>> indirect?  I assume direct?
>
> Correct, these would be direct.  I struggled to come up with a good
> name, but the basic idea was:
>
>   direct -- user enters a command and as a result GDB performs an
>             inferior function call.  The user can only enter the next
>             command once the first command (and hence inferior call) has
>             completed.
>
>   indirect -- user enters a command that accepts an expression,
>               e.g. breakpoint condition, but the expression is only
>               evaluated at some future time which is largely outside of
>               the users control, e.g. when the inferior hits the
>               breakpoint.  The user might not even be aware that the
>               inferior call is taking place (as b/p conditions are not
>               announced until they complete or timeout).
>
>>
>> I wonder whether you have plans/ideas for other kinds of indirect calls.
>> Just thinking about whether naming the option as something about
>> "breakpoint-condition" wouldn't be better by being more direct (ah!) and
>> to the point, while leaving the possibility of other kinds of situations
>> having different timeouts.  to avoid long command names, we could have
>> a prefix setting, like:
>
> I guess we could, but I'm not sure why a user might want such fine
> grained control -- they want to limit how long a breakpoint condition
> can take to evaluate, but want a different limit on some-other indirect
> case.  This just seems overly complex, surely you'd just pick a timeout
> that satisfies your expected worst case and go with that.
>
> To be honest, the reason I initially split direct and indirect is so
> that the direct case could be unlimited to match GDB's current
> behaviour.  But, now I've written it, I do think there's an argument
> that a user might want to allow direct calls to take longer.  In the
> direct case the user is (hopefully) aware that an inferior call has
> taken place, and can manually interrupt if the call is taking too long,
> so I think this split does make sense.
>
>>
>>  set call-timeout direct  # maybe there's a better name for this.
>>  set call-timeout breakpoint-conditions
>>  set call-timeout some-other-case
>>
>> Just some thoughts, by no way am I objecting to what you have.
>>
>>> +
>>> +  The default for the direct timeout is unlimited, while the default
>>> +  for the indirect timeout is 30 seconds.
>>
>> While working on Windows non-stop support recently, I noticed that
>> gdb.threads/multiple-successive-infcall.exp has infcalls that would
>> just hang "forever", the infcall never completed.  The test
>> enables schedlock, and then calls a function in each thread in the
>> program [like, (gdb) p get_value()].  The issue turns out to be about
>> calling a function in a thread that is currently running Windows kernel
>> code.  On Linux, most system calls are interruptible (EINTR), and
>> restartable.  When the debugger pauses a thread and the thread is in a
>> syscall, the syscall is interrupted and restarted later when the thread
>> is resumed.  On Windows, system calls are NOT interruptible.  The threads
>> in question in the testcase were stopped inside the syscall done by
>> ntdll!ZwWaitForMultipleObjects.  In that scenario, you can still pause the
>> hung thread with Ctrl-C, and you'll see that the (userspace) PC of the thread
>> in question hasn't changed, it is still pointing to the entry to the
>> function GDB wants to call -- not surprising since the thread is really
>> still blocked inside the syscall and never ran any userspace instruction.
>>
>> This looks like something that Windows GDB users are likely to trip on more
>> frequently than GNU/Linux users.
>>
>> So I looked at how Visual Studio (not vscode) handles it, to check how it 
>> handles this, maybe it just doesn't let you call functions on threads that are
>> stopped inside a syscall?  Nope.  You guessed it, it handles it with a timeout.
>> If you add a watch expression (like a gdb "display") involving infcall, and the thread
>> is in kernel code, VS will still try the call, and then after a few short
>> seconds (maybe some 5s), it aborts the expression, popping a dialog box informing
>> you about it.
>>
>> All that to say that I would think it reasonable to default to a
>> shorter timeout in GDB too.
>>
>> Actually, I remembered now that LLDB also has a timeout for infcalls.
>> On the version I have handy installed, "help expression" talks about
>> a timeout of "currently .25 seconds", and then retrying with all threads
>> running, (that's 0.25s, not 25s IIUC, curiously, higher resolution than
>> second), but I don't know how long that second retry has for timeout,
>> if it has one.
>>
>> For breakpoint conditions, I think it may be nice (but not a
>> requirement of this patch, just an idea) if after some time less than
>> the whole timeout time, for GDB to print a warning, something like:
>>
>>  warning: a function call in the condition of breakpoint 2.3 is taking long.
>>
>> Like, we could print that warning after 1 second, even if the timeout
>> is set to higher than that.
>>
>> Anyhow, all that is a lot easier to code than debate and it can always
>> be done later.
>>
>>> +
>>> +  These timeouts will only have an effect for targets that are
>>> +  operating in async mode.  For non-async targets the timeouts are
>>> +  ignored, GDB will wait indefinitely for an inferior function to
>>> +  complete, unless interrupted by the user using Ctrl-C.
>>> +
>>>  * MI changes
>>>  
>>>  ** mi now reports 'no-history' as a stop reason when hitting the end of the
>>> diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
>>> index fe76e5e0a0e..46f17798510 100644
>>> --- a/gdb/doc/gdb.texinfo
>>> +++ b/gdb/doc/gdb.texinfo
>>> @@ -20885,6 +20885,72 @@
>>>  @code{step}, etc).  In this case, when the inferior finally returns to
>>>  the dummy-frame, @value{GDBN} will once again halt the inferior.
>>>  
>>> +On targets that support asynchronous execution (@pxref{Background
>>> +Execution}) @value{GDBN} can place a timeout on any functions called
>>> +from @value{GDBN}.  If the timeout expires and the function call is
>>> +still ongoing, then @value{GDBN} will interrupt the program.
>>
>> In the patch introducing "set unwind-on-timeout", I think it would be
>> good to mention the setting here.  I didn't notice it being added there.
>> Because, as I read this, I wondered "OK, but what happens after GDB
>> interrupts the program?  Do we unwind according to set unwind-on-signal?" .
>>
>>> +
>>> +For targets that don't support asynchronous execution
>>> +(@pxref{Background Execution}) then timeouts for functions called from
>>> +@value{GDBN} are not supported, the timeout settings described below
>>> +will be treated as @code{unlimited}, meaning @value{GDBN} will wait
>>> +indefinitely for function call to complete, unless interrupted by the
>>> +user using @kbd{Ctrl-C}.
>>> +
>>
>> ...
>>
>>> diff --git a/gdb/infcall.c b/gdb/infcall.c
>>> index 4fb8ab07db0..bb57faf700f 100644
>>> --- a/gdb/infcall.c
>>> +++ b/gdb/infcall.c
>>> @@ -95,6 +95,53 @@ show_may_call_functions_p (struct ui_file *file, int from_tty,
>>>  	      value);
>>>  }
>>>  
>>> +/* A timeout (in seconds) for direct inferior calls.  A direct inferior
>>> +   call is one the user triggers from the prompt, e.g. with a 'call' or
>>> +   'print' command.  Compare with the definition of indirect calls below.  */
>>> +
>>> +static unsigned int direct_call_timeout = UINT_MAX;
>>> +
>>> +/* Implement 'show direct-call-timeout'.  */
>>> +
>>> +static void
>>> +show_direct_call_timeout (struct ui_file *file, int from_tty,
>>> +			  struct cmd_list_element *c, const char *value)
>>> +{
>>> +  if (target_has_execution () && !target_can_async_p ())
>>> +    gdb_printf (file, _("Current target does not support async mode, timeout "
>>> +			"for direct inferior calls is \"unlimited\".\n"));
>>> +  else if (direct_call_timeout == UINT_MAX)
>>> +    gdb_printf (file, _("Timeout for direct inferior function calls "
>>> +			"is \"unlimited\".\n"));
>>> +  else
>>> +    gdb_printf (file, _("Timeout for direct inferior function calls "
>>> +			"is \"%s seconds\".\n"), value);
>>> +}
>>> +
>>> +/* A timeout (in seconds) for indirect inferior calls.  An indirect inferior
>>> +   call is one that originates from within GDB, for example, when
>>> +   evaluating an expression for a conditional breakpoint.  Compare with
>>> +   the definition of direct calls above.  */
>>> +
>>> +static unsigned int indirect_call_timeout = 30;
>>> +
>>> +/* Implement 'show indirect-call-timeout'.  */
>>> +
>>> +static void
>>> +show_indirect_call_timeout (struct ui_file *file, int from_tty,
>>> +			  struct cmd_list_element *c, const char *value)
>>> +{
>>> +  if (target_has_execution () && !target_can_async_p ())
>>> +    gdb_printf (file, _("Current target does not support async mode, timeout "
>>> +			"for indirect inferior calls is \"unlimited\".\n"));
>>> +  else if (indirect_call_timeout == UINT_MAX)
>>> +    gdb_printf (file, _("Timeout for indirect inferior function calls "
>>> +			"is \"unlimited\".\n"));
>>> +  else
>>> +    gdb_printf (file, _("Timeout for indirect inferior function calls "
>>> +			"is \"%s seconds\".\n"), value);
>>> +}
>>> +
>>>  /* How you should pass arguments to a function depends on whether it
>>>     was defined in K&R style or prototype style.  If you define a
>>>     function using the K&R syntax that takes a `float' argument, then
>>> @@ -589,6 +636,86 @@ call_thread_fsm::should_notify_stop ()
>>>    return true;
>>>  }
>>>  
>>> +/* A class to control creation of a timer that will interrupt a thread
>>> +   during an inferior call.  */
>>> +struct infcall_timer_controller
>>> +{
>>> +  /* Setup an event-loop timer that will interrupt PTID if the inferior
>>> +     call takes too long.  DIRECT_CALL_P is true when this inferior call is
>>> +     a result of the user using a 'print' or 'call' command, and false when
>>> +     this inferior call is a result of e.g. a conditional breakpoint
>>> +     expression, this is used to select which timeout to use.  */
>>> +  infcall_timer_controller (thread_info *thr, bool direct_call_p)
>>> +    : m_thread (thr)
>>> +  {
>>> +    unsigned int timeout
>>> +      = direct_call_p ? direct_call_timeout : indirect_call_timeout;
>>> +    if (timeout < UINT_MAX && target_can_async_p ())
>>> +      {
>>> +	int ms = timeout * 1000;
>>> +	int id = create_timer (ms, infcall_timer_controller::timed_out, this);
>>> +	m_timer_id.emplace (id);
>>> +	infcall_debug_printf ("Setting up infcall timeout timer for "
>>> +			      "ptid %s: %d milliseconds",
>>> +			      m_thread->ptid.to_string ().c_str (), ms);
>>> +      }
>>> +  }
>>> +
>>> +  /* Destructor.  Ensure that the timer is removed from the event loop.  */
>>> +  ~infcall_timer_controller ()
>>> +  {
>>> +    /* If the timer has already triggered, then it will have already been
>>> +       deleted from the event loop.  If the timer has not triggered, then
>>> +       delete it now.  */
>>> +    if (m_timer_id.has_value () && !m_triggered)
>>> +      delete_timer (*m_timer_id);
>>> +
>>> +    /* Just for clarity, discard the timer id now.  */
>>> +    m_timer_id.reset ();
>>> +  }
>>> +
>>> +  /* Return true if there was a timer in place, and the timer triggered,
>>> +     otherwise, return false.  */
>>> +  bool triggered_p ()
>>> +  {
>>> +    gdb_assert (!m_triggered || m_timer_id.has_value ());
>>> +    return m_triggered;
>>> +  }
>>> +
>>> +private:
>>> +  /* The thread we should interrupt.  */
>>> +  thread_info *m_thread;
>>> +
>>> +  /* Set true when the timer is triggered.  */
>>> +  bool m_triggered = false;
>>> +
>>> +  /* Given a value when a timer is in place.  */
>>> +  gdb::optional<int> m_timer_id;
>>> +
>>> +  /* Callback for the timer, forwards to ::trigger below.  */
>>> +  static void
>>> +  timed_out (gdb_client_data context)
>>> +  {
>>> +    infcall_timer_controller *ctrl
>>> +      = static_cast<infcall_timer_controller *> (context);
>>> +    ctrl->trigger ();
>>> +  }
>>> +
>>> +  /* Called when the timer goes off.  Stop thread m_thread.  */
>>
>> Uppercase M_THREAD.
>
> Fixed.
>
>>
>>> +  void
>>> +  trigger ()
>>> +  {
>>> +    m_triggered = true;
>>> +
>>> +    scoped_disable_commit_resumed disable_commit_resumed ("infcall timeout");
>>> +
>>> +    infcall_debug_printf ("Stopping thread %s",
>>> +			  m_thread->ptid.to_string ().c_str ());
>>> +    target_stop (m_thread->ptid);
>>> +    m_thread->stop_requested = true;
>>
>> As per the discussion in the remote patch, I think this will need
>> to be adjusted.  Maybe something like:
>>
>>     if (target_is_non_stop_p ())
>>       {
>>         target_stop (m_thread->ptid);
>>         m_thread->stop_requested = true;
>>       }
>>     else
>>       target_interrupt ();
>
> I understand your critique of the 'avoid SIGINT after calling
> remote_target::stop' patch, but I don't understand this comment.  What
> we want to do is stop the target, not interrupt it, thus, surely, we
> should call target_stop.
>
> The fact that we can't target_stop for a !non-stop target is surely
> something the target should deal with.  And indeed, if we check out
> remote_target::stop we see that for !non-stop target we call
> remote_interrupt_as.  In contrast, calling remote_target::interrupt for
> a !non-stop target also calls remote_interrupt_as, which I think is very
> much the point of your critique, right?
>
> My thinking here is that, if we _did_ come up with some clever way to
> support ::stop for a !non-stop target, this code would be added to
> remote_target::stop, but _not_ to remote_target::interrupt, so we should
> call the function that matches our intention, even if, right now, GDB
> can't actually satisfy our needs.
>
>>
>>> +  }
>>> +};
>>> +
>>>  /* Subroutine of call_function_by_hand to simplify it.
>>>     Start up the inferior and wait for it to stop.
>>>     Return the exception if there's an error, or an exception with
>>> @@ -599,13 +726,15 @@ call_thread_fsm::should_notify_stop ()
>>>  
>>>  static struct gdb_exception
>>>  run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
>>> -		   struct thread_info *call_thread, CORE_ADDR real_pc)
>>> +		   struct thread_info *call_thread, CORE_ADDR real_pc,
>>> +		   bool *timed_out_p)
>>>  {
>>>    INFCALL_SCOPED_DEBUG_ENTER_EXIT;
>>>  
>>>    struct gdb_exception caught_error;
>>>    ptid_t call_thread_ptid = call_thread->ptid;
>>>    int was_running = call_thread->state == THREAD_RUNNING;
>>> +  *timed_out_p = false;
>>>  
>>>    infcall_debug_printf ("call function at %s in thread %s, was_running = %d",
>>>  			core_addr_to_string (real_pc),
>>> @@ -617,6 +746,16 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
>>>    scoped_restore restore_in_infcall
>>>      = make_scoped_restore (&call_thread->control.in_infcall, 1);
>>>  
>>> +  /* If the thread making the inferior call stops with a time out then the
>>> +     stop_requested flag will be set.  However, we don't want changes to
>>> +     this flag to leak back to our caller, we might be here to handle an
>>> +     inferior call from a breakpoint condition, so leaving this flag set
>>> +     would appear that the breakpoint stop was actually a requested stop,
>>> +     which is not true, and will cause GDB to print extra messages to the
>>> +     output.  */
>>> +  scoped_restore restore_stop_requested
>>> +    = make_scoped_restore (&call_thread->stop_requested, false);
>>
>> I'm confused by this.  If stop_requested was set when the breakpoint was hit,
>> are we still evaluating the breakpoint condition (and re-resuming the thread
>> if the condition is false) ?
>
> I don't really understand your question here, but I don't think that it
> matters now.  This stop_requested stuff was only in place to support the
> 'avoid SIGINT after calling remote_target::stop' patch (the next one),
> which I'm going to drop after your feedback.
>
>>
>>> +
>>>    clear_proceed_status (0);
>>>  
>>
>>> --- /dev/null
>>> +++ b/gdb/testsuite/gdb.base/infcall-timeout.c
>>> @@ -0,0 +1,36 @@
>>> +/* Copyright 2022-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 <unistd.h>
>>> +
>>> +/* This function is called from GDB.  */
>>> +int
>>> +function_that_never_returns ()
>>> +{
>>> +  while (1)
>>> +    sleep (1);
>>> +
>>> +  return 0;
>>> +}
>>> +
>>> +int
>>> +main ()
>>> +{
>>> +  alarm (300);
>>> +
>>> +  return 0;
>>> +}
>>> diff --git a/gdb/testsuite/gdb.base/infcall-timeout.exp b/gdb/testsuite/gdb.base/infcall-timeout.exp
>>
>>
>> ...
>>
>>> +standard_testfile
>>> +
>>> +if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
>>> +	  {debug}] == -1 } {
>>> +    return
>>> +}
>>> +
>>> +# Start GDB according to TARGET_ASYNC and TARGET_NON_STOP, then adjust
>>> +# the direct-call-timeout, and make an inferior function call that
>>> +# will never return.  GDB should eventually timeout and stop the
>>> +# inferior.
>>> +proc_with_prefix run_test { target_async target_non_stop } {
>>> +    save_vars { ::GDBFLAGS } {
>>> +	append ::GDBFLAGS \
>>> +	    " -ex \"maint set target-non-stop $target_non_stop\""
>>
>> It's curious that target-non-stop on|off is tested, but not "set non-stop on".
>
> I've extended the tests to cover this case.
>
>>
>>> +	append ::GDBFLAGS \
>>> +	    " -ex \"maintenance set target-async ${target_async}\""
>>> +
>>> +	clean_restart ${::binfile}
>>> +    }
>>> +
>>
>> ...
>>
>>> diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
>>> new file mode 100644
>>> index 00000000000..4159288a39c
>>> --- /dev/null
>>> +++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
>>
>> ...
>>
>>> +
>>> +    gdb_breakpoint \
>>> +	"${::srcfile}:${::cond_bp_line} if (condition_func ())"
>>> +    set bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
>>> +		    "get number for conditional breakpoint"]
>>> +
>>> +    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
>>> +    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
>>> +			  "get number for final breakpoint"]
>>> +
>>> +    # The thread performing an inferior call relies on a second
>>> +    # thread.  The second thread will segfault unless it hits a
>>> +    # breakpoint first.  In either case the initial thread will not
>>> +    # complete its inferior call.
>>> +    if { $other_thread_bp } {
>>> +	gdb_breakpoint "${::srcfile}:${::segfault_line}"
>>> +	set segfault_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
>>> +				 "get number for segfault breakpoint"]
>>> +    }
>>> +
>>> +    # When non-stop mode is off we get slightly different output from GDB.
>>> +    if { [gdb_is_remote_or_extended_remote_target] && !$target_non_stop} {
>>> +	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" received signal SIGINT, Interrupt\\."
>>> +    } else {
>>> +	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\."
>>> +    }
>>
>> Something is going on in this test that when testing against gdbserver with
>> all-stop, it is always Thread 2 that reports the SIGINT, which is coincidentally
>> the thread that was hitting the breakpoint and running the infcall, AFAICS.
>>
>>  continue
>>  Continuing.
>>  [New Thread 3506594.3506599]
>>  [New Thread 3506594.3506600]
>>  [New Thread 3506594.3506601]
>>  [New Thread 3506594.3506602]
>>  [New Thread 3506594.3506603]
>>
>>  Thread 2 "infcall-from-bp" received signal SIGINT, Interrupt.
>> __futex_abstimed_wait_common64 (private=<optimized out>, cancel=true, abstime=0x0, op=393, expected=0, futex_word=0x555555558080 <thread_1_semaphore>) at ./nptl/futex-internal.c:57
>>
>> Why is that?
>
> The answer lies in the 'gdb: fix b/p conditions with infcalls in
> multi-threaded inferiors' patch, specifically the change to
> user_visible_resume_ptid, which ensures that, when evaluating a B/P
> condition, only the thread evaluating the condition is resumed.
>
> The code didn't originate with me[1], but I didn't question it too much
> when I incorporated it into this series, and maybe I should have.
>
> I wonder if in all-stop mode we should be resuming all threads when
> evaluating the condition?
>
> I'll think about this some more follow up..
>
> [1] https://inbox.sourceware.org/gdb-patches/20201009112719.629-3-natalia.saiapova@intel.com/

OK, so the post I linked includes one reason for only resuming the
thread in which the condition is being evaluated, but the more I think
about it, the less I'm sure resuming all threads would make sense.

If we consider an all-stop target (rather than GDB running all-stop on
top of a non-stop target), if all threads resumed then there's a
chance we could hit some event in a thread other than the one executing
the b/p condition.  If this happens then we're going to be in trouble as
all threads would stop, including the b/p thread, and we'd have to
abandon the conditional breakpoint evaluation, which would result in
more b/p conditions being abandoned than necessary.

For an all-stop on non-stop target, maybe the situation isn't so bad?
The post linked above does highlight one problem, that at the point the
b/p condition is evaluated other threads that are stopping might not be
in a state suitable for being resumed, and if two such threads both hit
a conditional breakpoint at the same time I'm really not sure what we'd
do ... resume some threads maybe?

Like I said, the more I consider it, the more it feels like just
resuming the one thread solves a bunch of problems.

What might help, I guess, would be to wrap the condition evaluation into
a thread_fsm and handle the condition evaluation asynchronously, but
that feels like a whole mountain of change -- I'd much rather merge
something like this series and then build from there.

Anyway, hopefully this explains why we're seeing the stop arrive in
thread 2, rather than the main thread.

Would be interested to hear your thoughts,

Thanks,
Andrew


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

* Re: [PATCHv5 05/11] gdb: don't always print breakpoint location after failed condition check
  2023-07-14 12:17                   ` Andrew Burgess
@ 2023-07-17 17:17                     ` Pedro Alves
  2023-08-03 13:57                       ` Andrew Burgess
  0 siblings, 1 reply; 202+ messages in thread
From: Pedro Alves @ 2023-07-17 17:17 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

Hi!

Overall this looks good.  Some nits below.

On 2023-07-14 13:17, Andrew Burgess wrote:

> commit bd3309a50423114c2cb31241500820efa21d0452
> Author: Andrew Burgess <aburgess@redhat.com>
> Date:   Wed Jul 12 21:56:50 2023 +0100
> 
>     gdb: avoid double stop after failed breakpoint condition check
>     
>     This commit replaces this earlier commit:
>     
>       commit 2e411b8c68eb2b035b31d5b00d940d4be1a0928b
>       Date:   Fri Oct 14 14:53:15 2022 +0100
>     
>           gdb: don't always print breakpoint location after failed condition check
>     
>     and is a result of feedback received here[1].
>     
>     The original commit addressed a problem where, if a breakpoint
>     condition included an inferior function call, and if the inferior
>     function call fail, then GDB would announce the stop twice.  Here's an

"fail" -> "failed" or "fails", I guess.

>     example of GDB's output before the above commit that shows the problem
>     being addressed:
>     
>       (gdb) break foo if (some_func ())
>       Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
>       (gdb) r
>       Starting program: /tmp/bpcond
>     
>       Program received signal SIGSEGV, Segmentation fault.
>       0x0000000000401116 in some_func () at bpcond.c:5
>       5       return *p;
>       Error in testing condition for breakpoint 1:
>       The program being debugged stopped while in a function called from GDB.
>       Evaluation of the expression containing the function
>       (some_func) will be abandoned.
>       When the function is done executing, GDB will silently stop.
>     
>       Breakpoint 1, 0x0000000000401116 in some_func () at bpcond.c:5
>       5       return *p;
>       (gdb)
>     
>     The original commit addressed this issue in breakpoint.c, by spotting
>     that the $pc had changed while evaluating the breakpoint condition,
>     and inferring from this that GDB must have stopped elsewhere.
>     
>     However, the way in which the original commit suppressed the second
>     stop announcement was to set bpstat::print to true -- this tells GDB
>     not to print the frame during the stop announcement, and for the CLI
>     this is fine, however, it was pointed out that for the MI this still
>     isn't really enough.  Below is an example from an MI session after the
>     above commit was applied, this shows the problem with the above
>     commit:
>     
>       -break-insert -c "cond_fail()" foo
>       ^done,bkpt={number="1",type="breakpoint",disp="keep",enabled="y",addr="0x000000000040111e",func="foo",file="/tmp/mi-condbreak-fail.c",line="30",thread-groups=["i1"],cond="cond_fail()",times="0",original-location="foo"}
>       (gdb)
>       -exec-run
>       =thread-group-started,id="i1",pid="2636270"
>       =thread-created,id="1",group-id="i1"
>       =library-loaded,id="/lib64/ld-linux-x86-64.so.2",target-name="/lib64/ld-linux-x86-64.so.2",host-name="/lib64/ld-linux-x86-64.so.2",symbols-loaded="0",thread-group="i1",ranges=[{from="0x00007ffff7fd3110",to="0x00007ffff7ff2bb4"}]
>       ^running
>       *running,thread-id="all"
>       (gdb)
>       =library-loaded,id="/lib64/libm.so.6",target-name="/lib64/libm.so.6",host-name="/lib64/libm.so.6",symbols-loaded="0",thread-group="i1",ranges=[{from="0x00007ffff7e59390",to="0x00007ffff7ef4f98"}]
>       =library-loaded,id="/lib64/libc.so.6",target-name="/lib64/libc.so.6",host-name="/lib64/libc.so.6",symbols-loaded="0",thread-group="i1",ranges=[{from="0x00007ffff7ca66b0",to="0x00007ffff7df3c5f"}]
>       ~"\nProgram"
>       ~" received signal SIGSEGV, Segmentation fault.\n"
>       ~"0x0000000000401116 in cond_fail () at /tmp/mi-condbreak-fail.c:24\n"
>       ~"24\t  return *p;\t\t\t/* Crash here.  */\n"
>       *stopped,reason="signal-received",signal-name="SIGSEGV",signal-meaning="Segmentation fault",frame={addr="0x0000000000401116",func="cond_fail",args=[],file="/tmp/mi-condbreak-fail.c",fullname="/tmp/mi-condbreak-fail.c",line="24",arch="i386:x86-64"},thread-id="1",stopped-threads="all",core="9"
>       &"Error in testing condition for breakpoint 1:\n"
>       &"The program being debugged was signaled while in a function called from GDB.\n"
>       &"GDB remains in the frame where the signal was received.\n"
>       &"To change this behavior use \"set unwindonsignal on\".\n"
>       &"Evaluation of the expression containing the function\n"
>       &"(cond_fail) will be abandoned.\n"
>       &"When the function is done executing, GDB will silently stop.\n"
>       =breakpoint-modified,bkpt={number="1",type="breakpoint",disp="keep",enabled="y",addr="0x000000000040111e",func="foo",file="/tmp/mi-condbreak-fail.c",fullname="/tmp/mi-condbreak-fail.c",line="30",thread-groups=["i1"],cond="cond_fail()",times="1",original-location="foo"}
>       *stopped
>       (gdb)
>     
>     Notice that we still see two '*stopped' lines, the first includes the
>     full frame information, while the second has no frame information,
>     this is a result of bpstat::print having been set.  Ideally, the
>     second '*stopped' line should not be present.
>     
>     By setting bpstat::print I was addressing the problem too late, this
>     flag really only changes how interp::on_normal_stop prints the stop
>     event, and interp::on_normal_stop is called (indirectly) from the
>     normal_stop function in infrun.c.  A better solution is to avoid
>     calling normal_stop at all for the stops which should not be reported
>     to the user, and this is what I do in this commit.
>     
>     This commit has 3 parts:
>     
>       1. In breakpoint.c, revert the above commit,
>     
>       2. In fetch_inferior_event (infrun.c), capture the stop-id before
>       calling handle_inferior_event.  If, after calling
>       handle_inferior_event, the stop-id has changed, then this indicates
>       that somewhere within handle_inferior_event, a stop was announced to
>       the user.  If this is the case then GDB should not call normal_stop,
>       and we should rely on whoever announced the stop to ensure that we
>       are in a PROMPT_NEEDED state, which means the prompt will be
>       displayed once fetch_inferior_event returns.  And,
>     
>       3. In infcall.c, do two things:
>     
>          (a) In run_inferior_call, after making the inferior call, ensure
>          that either async_disable_stdin or async_enable_stdin is called
>          to put the prompt state, and stdin handling into the correct
>          state based on whether the inferior call completed successfully
>          or not, and
>     
>          (b) In call_thread_fsm::should_stop, call async_enable_stdin
>          rather than changing the prompt state directly.  This isn't
>          strictly necessary, but helped me understand this code more.
>          This async_enable_stdin call is only reached if normal_stop is
>          not going to be called, and replaces the async_enable_stdin call
>          that exists in normal_stop.  Though we could just adjust the
>          prompt state if felt (to me) much easier to understand when I
>          could see this call and the corresponding call in normal_stop.
>     
>     With these changes in place now, when the inferior call (from the
>     breakpoint condition) fails, infcall.c leaves the prompt state as
>     PROMPT_NEEDED, and leaves stdin registered with the event loop.
>     
>     Back in fetch_inferior_event GDB notices that the stop-id has changed
>     and so avoids calling normal_stop.
>     
>     And on return from fetch_inferior_event GDB will display the prompt
>     and handle input from stdin.
>     
>     As normal_stop is not called the MI problem is solved, and the test
>     added in the earlier mentioned commit still passes just fine, so the
>     CLI has not regressed.
>     
>     [1] https://inbox.sourceware.org/gdb-patches/6fd4aa13-6003-2563-5841-e80d5a55d59e@palves.net/
> 
> diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
> index d898167b7e1..93634bd7e51 100644
> --- a/gdb/breakpoint.c
> +++ b/gdb/breakpoint.c
> @@ -5535,7 +5535,6 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
>  	  else
>  	    within_current_scope = false;
>  	}
> -      CORE_ADDR pc_before_check = get_frame_pc (get_selected_frame (nullptr));
>        if (within_current_scope)
>  	{
>  	  try
> @@ -5555,17 +5554,6 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
>  		  (gdb_stderr, ex,
>  		   "Error in testing condition for breakpoint %d:\n",
>  		   b->number);
> -
> -	      /* If the pc value changed as a result of evaluating the
> -		 condition then we probably stopped within an inferior
> -		 function call due to some unexpected stop, e.g. the thread
> -		 hit another breakpoint, or the thread received an
> -		 unexpected signal.  In this case we don't want to also
> -		 print the information about this breakpoint.  */
> -	      CORE_ADDR pc_after_check
> -		= get_frame_pc (get_selected_frame (nullptr));
> -	      if (pc_before_check != pc_after_check)
> -		bs->print = 0;
>  	    }
>  	}
>        else
> diff --git a/gdb/infcall.c b/gdb/infcall.c
> index ddf325a62a5..0944097e18d 100644
> --- a/gdb/infcall.c
> +++ b/gdb/infcall.c
> @@ -564,10 +564,13 @@ call_thread_fsm::should_stop (struct thread_info *thread)
>  	 call..  */
>        return_value = get_call_return_value (&return_meta_info);
>  
> -      /* Break out of wait_sync_command_done.  */
> +      /* Break out of wait_sync_command_done.  This is similar to the
> +	 async_enable_stdin call in normal_stop (which we don't call),
> +	 however, in this case we only change the WAITING_UI, this is

Full stop after WAITING_UI.

> +	 enough for wait_sync_command_done.  */
>        scoped_restore save_ui = make_scoped_restore (&current_ui, waiting_ui);
> -      target_terminal::ours ();
> -      waiting_ui->prompt_state = PROMPT_NEEDED;
> +      gdb_assert (current_ui->prompt_state == PROMPT_BLOCKED);
> +      async_enable_stdin ();
>      }
>  
>    return true;
> @@ -661,14 +664,30 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
>    infcall_debug_printf ("thread is now: %s",
>  			inferior_ptid.to_string ().c_str ());
>  
> -  /* If GDB has the prompt blocked before, then ensure that it remains
> -     so.  normal_stop calls async_enable_stdin, so reset the prompt
> -     state again here.  In other cases, stdin will be re-enabled by
> -     inferior_event_handler, when an exception is thrown.  */
> +  /* After the inferior call async_enable_stdin has been called, either
> +     from normal_stop or from call_thread_fsm::should_stop, and the prompt
> +     state has been restored by the scoped_restore in the try block above.

It took me several reads to understand this comment.  I kept misreading this
as "After ... async_enable_stdin has been called, then ..."

I think putting a comma here

 /* After the inferior call, async_enable_stdin has been called, either
                          ^^^

would have helped me.  Maybe even say:

   "After the inferior call finishes, ".

?

> +
> +     If the inferior call finished successfully then we should disable
> +     stdin as we don't know yet whether the inferior will be stopping,

The last comma should be a period, IMO.

> +     calling async_disable_stdin restores things as they were when this
> +     function was called.

"restores things as they were" -> "restores things to how they were" ?

> +
> +     If the inferior call didn't complete successfully then normal_stop has

Comma before "then".

> +     already been called, and we know for sure that we are going to present
> +     this stop to the user, in this case we call async_enable_stdin, this

Period after "the user" instead of comma.  Comma after "this case".
Also period after async_enable_stdin; alternatively, say "which" instead of
"this".

> +     changes the prompt state to PROMPT_NEEDED.
> +
> +     If the previous prompt state was PROMPT_NEEDED then, as

I think you mean to put the comma before "then" instead of after?
Or is this "then" refering to some previously-referred-to situation?

> +     async_enable_stdin has already been called, nothing additional needs
> +     to be done here.  */

I found it much easier to understand the whole comment block without applying
my suggestions above locally.  Here is the result for your reference, and to
double check I'm parsing this all correctly:

  /* After the inferior call finished, async_enable_stdin has been
     called, either from normal_stop or from
     call_thread_fsm::should_stop, and the prompt state has been
     restored by the scoped_restore in the try block above.

     If the inferior call finished successfully, then we should
     disable stdin as we don't know yet whether the inferior will be
     stopping.  Calling async_disable_stdin restores things to how
     they were when this function was called.

     If the inferior call didn't complete successfully, then
     normal_stop has already been called, and we know for sure that we
     are going to present this stop to the user.  In this case, we
     call async_enable_stdin.  This changes the prompt state to
     PROMPT_NEEDED.

     If the previous prompt state was PROMPT_NEEDED, then as
     async_enable_stdin has already been called, nothing additional
     needs to be done here.  */


>    if (current_ui->prompt_state == PROMPT_BLOCKED)
> -    current_ui->unregister_file_handler ();
> -  else
> -    current_ui->register_file_handler ();
> +    {
> +      if (call_thread->thread_fsm ()->finished_p ())
> +	async_disable_stdin ();
> +      else
> +	async_enable_stdin ();
> +    }
>  
>    /* If the infcall does NOT succeed, normal_stop will have already
>       finished the thread states.  However, on success, normal_stop
> diff --git a/gdb/infrun.c b/gdb/infrun.c
> index 58da1cef29e..95ab7c6f7dc 100644
> --- a/gdb/infrun.c
> +++ b/gdb/infrun.c
> @@ -4395,6 +4395,8 @@ fetch_inferior_event ()
>      auto defer_delete_threads
>        = make_scope_exit (delete_just_stopped_threads_infrun_breakpoints);
>  
> +    int stop_id = get_stop_id ();
> +
>      /* Now figure out what to do with the result of the result.  */
>      handle_inferior_event (&ecs);
>  
> @@ -4422,7 +4424,19 @@ fetch_inferior_event ()
>  
>  	    clean_up_just_stopped_threads_fsms (&ecs);
>  
> -	    if (thr != nullptr && thr->thread_fsm () != nullptr)
> +	    if (stop_id != get_stop_id ())
> +	      {
> +		/* If the stop-id has changed then a stop has already been
> +		   presented to the user in handle_inferior_event, this is
> +		   likely a failed inferior call.  As the stop has already
> +		   been announced then we should not notify again.
> +
> +		   Also, if the prompt state is not PROMPT_NEEDED then GDB
> +		   will not be ready for user input after this function.  */
> +		should_notify_stop = false;
> +		gdb_assert (current_ui->prompt_state == PROMPT_NEEDED);
> +	      }
> +	    else if (thr != nullptr && thr->thread_fsm () != nullptr)
>  	      should_notify_stop
>  	       = thr->thread_fsm ()->should_notify_stop ();
>  
> diff --git a/gdb/testsuite/gdb.mi/mi-condbreak-fail.c b/gdb/testsuite/gdb.mi/mi-condbreak-fail.c
> new file mode 100644
> index 00000000000..94bd2484934
> --- /dev/null
> +++ b/gdb/testsuite/gdb.mi/mi-condbreak-fail.c
> @@ -0,0 +1,39 @@
> +/* Copyright 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/>.  */
> +
> +volatile int global_counter = 0;
> +
> +int
> +cond_fail ()
> +{
> +  volatile int *p = 0;
> +  return *p;			/* Crash here.  */
> +}
> +
> +int
> +foo ()
> +{
> +  global_counter += 1;		/* Set breakpoint here.  */
> +  return 0;
> +}
> +
> +int
> +main ()
> +{
> +  int res = foo ();
> +  return res;
> +}
> diff --git a/gdb/testsuite/gdb.mi/mi-condbreak-fail.exp b/gdb/testsuite/gdb.mi/mi-condbreak-fail.exp
> new file mode 100644
> index 00000000000..86b1db5a8dd
> --- /dev/null
> +++ b/gdb/testsuite/gdb.mi/mi-condbreak-fail.exp
> @@ -0,0 +1,67 @@
> +# Copyright (C) 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/>.
> +
> +# Check that when GDB fails to evaluate the condition of a conditional
> +# breakpoint we only get one *stopped message.

"message" -> "async record" or "notification".

> +
> +load_lib mi-support.exp
> +set MIFLAGS "-i=mi"
> +
> +standard_testfile
> +
> +if [build_executable ${testfile}.exp ${binfile} ${srcfile}] {
> +    return -1
> +}
> +
> +if {[mi_clean_restart $binfile]} {
> +    return
> +}
> +
> +if {[mi_runto_main] == -1} {
> +    return
> +}
> +
> +# Create the conditional breakpoint.
> +set bp_location [gdb_get_line_number "Set breakpoint here"]
> +mi_create_breakpoint "-c \"cond_fail ()\" $srcfile:$bp_location" \
> +    "insert conditional breakpoint" \
> +    -func foo -file ".*$srcfile" -line "$bp_location" \
> +    -cond "cond_fail \\(\\)"
> +
> +# Number of the previous breakpoint.
> +set bpnum [mi_get_valueof "/d" "\$bpnum" "INVALID" \
> +	       "get number for breakpoint"]
> +
> +# The line where we expect the inferior to crash.
> +set crash_linenum [gdb_get_line_number "Crash here"]
> +
> +# Run the inferior and wait for it to stop.
> +mi_send_resuming_command "exec-continue" "continue the inferior"
> +mi_gdb_test "" \
> +    [multi_line \
> +	 "~\"\\\\nProgram\"" \
> +	 "~\" received signal SIGSEGV, Segmentation fault\\.\\\\n\"" \
> +	 "~\"$hex in cond_fail \\(\\) at \[^\r\n\]+\"" \
> +	 "~\"${crash_linenum}\\\\t\\s+return \\*p;\[^\r\n\]+\\\\n\"" \
> +	 "\\*stopped,reason=\"signal-received\",signal-name=\"SIGSEGV\"\[^\r\n\]+" \
> +	 "&\"Error in testing condition for breakpoint $bpnum:\\\\n\"" \
> +	 "&\"The program being debugged was signaled while in a function called from GDB\\.\\\\n\"" \
> +	 "&\"GDB remains in the frame where the signal was received\\.\\\\n\"" \
> +	 "&\"To change this behavior use \\\\\"set unwindonsignal on\\\\\"\\.\\\\n\"" \
> +	 "&\"Evaluation of the expression containing the function\\\\n\"" \
> +	 "&\"\\(cond_fail\\) will be abandoned\\.\\\\n\"" \
> +	 "&\"When the function is done executing, GDB will silently stop\\.\\\\n\"" \
> +	 "=breakpoint-modified,bkpt={number=\"$bpnum\",type=\"breakpoint\",.*}"] \

I wonder about matching times="1" too, to confirm we're incrementing the hit
count even if the condition fails.

Also, that ".*" in the last line gave me pause.  It makes it so that a future
change that results in an output like:

  =breakpoint-modified,bkpt={number=\"$bpnum\",type=\"breakpoint\", [snip]
  *stopped
  =something-else-that-ends-in-curly-braces,{...}

would still pass.  Maybe use "\[^\r\n\]*" instead.

With the nits fixed, this LGTM.

Thanks!

Pedro Alves


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

* Re: [PATCHv5 05/11] gdb: don't always print breakpoint location after failed condition check
  2023-07-17 17:17                     ` Pedro Alves
@ 2023-08-03 13:57                       ` Andrew Burgess
  0 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-08-03 13:57 UTC (permalink / raw)
  To: Pedro Alves, gdb-patches

Pedro Alves <pedro@palves.net> writes:

> Hi!
>
> Overall this looks good.  Some nits below.
>
> On 2023-07-14 13:17, Andrew Burgess wrote:
>
>> commit bd3309a50423114c2cb31241500820efa21d0452
>> Author: Andrew Burgess <aburgess@redhat.com>
>> Date:   Wed Jul 12 21:56:50 2023 +0100
>> 
>>     gdb: avoid double stop after failed breakpoint condition check
>>     
>>     This commit replaces this earlier commit:
>>     
>>       commit 2e411b8c68eb2b035b31d5b00d940d4be1a0928b
>>       Date:   Fri Oct 14 14:53:15 2022 +0100
>>     
>>           gdb: don't always print breakpoint location after failed condition check
>>     
>>     and is a result of feedback received here[1].
>>     
>>     The original commit addressed a problem where, if a breakpoint
>>     condition included an inferior function call, and if the inferior
>>     function call fail, then GDB would announce the stop twice.  Here's an
>
> "fail" -> "failed" or "fails", I guess.
>
>>     example of GDB's output before the above commit that shows the problem
>>     being addressed:
>>     
>>       (gdb) break foo if (some_func ())
>>       Breakpoint 1 at 0x40111e: file bpcond.c, line 11.
>>       (gdb) r
>>       Starting program: /tmp/bpcond
>>     
>>       Program received signal SIGSEGV, Segmentation fault.
>>       0x0000000000401116 in some_func () at bpcond.c:5
>>       5       return *p;
>>       Error in testing condition for breakpoint 1:
>>       The program being debugged stopped while in a function called from GDB.
>>       Evaluation of the expression containing the function
>>       (some_func) will be abandoned.
>>       When the function is done executing, GDB will silently stop.
>>     
>>       Breakpoint 1, 0x0000000000401116 in some_func () at bpcond.c:5
>>       5       return *p;
>>       (gdb)
>>     
>>     The original commit addressed this issue in breakpoint.c, by spotting
>>     that the $pc had changed while evaluating the breakpoint condition,
>>     and inferring from this that GDB must have stopped elsewhere.
>>     
>>     However, the way in which the original commit suppressed the second
>>     stop announcement was to set bpstat::print to true -- this tells GDB
>>     not to print the frame during the stop announcement, and for the CLI
>>     this is fine, however, it was pointed out that for the MI this still
>>     isn't really enough.  Below is an example from an MI session after the
>>     above commit was applied, this shows the problem with the above
>>     commit:
>>     
>>       -break-insert -c "cond_fail()" foo
>>       ^done,bkpt={number="1",type="breakpoint",disp="keep",enabled="y",addr="0x000000000040111e",func="foo",file="/tmp/mi-condbreak-fail.c",line="30",thread-groups=["i1"],cond="cond_fail()",times="0",original-location="foo"}
>>       (gdb)
>>       -exec-run
>>       =thread-group-started,id="i1",pid="2636270"
>>       =thread-created,id="1",group-id="i1"
>>       =library-loaded,id="/lib64/ld-linux-x86-64.so.2",target-name="/lib64/ld-linux-x86-64.so.2",host-name="/lib64/ld-linux-x86-64.so.2",symbols-loaded="0",thread-group="i1",ranges=[{from="0x00007ffff7fd3110",to="0x00007ffff7ff2bb4"}]
>>       ^running
>>       *running,thread-id="all"
>>       (gdb)
>>       =library-loaded,id="/lib64/libm.so.6",target-name="/lib64/libm.so.6",host-name="/lib64/libm.so.6",symbols-loaded="0",thread-group="i1",ranges=[{from="0x00007ffff7e59390",to="0x00007ffff7ef4f98"}]
>>       =library-loaded,id="/lib64/libc.so.6",target-name="/lib64/libc.so.6",host-name="/lib64/libc.so.6",symbols-loaded="0",thread-group="i1",ranges=[{from="0x00007ffff7ca66b0",to="0x00007ffff7df3c5f"}]
>>       ~"\nProgram"
>>       ~" received signal SIGSEGV, Segmentation fault.\n"
>>       ~"0x0000000000401116 in cond_fail () at /tmp/mi-condbreak-fail.c:24\n"
>>       ~"24\t  return *p;\t\t\t/* Crash here.  */\n"
>>       *stopped,reason="signal-received",signal-name="SIGSEGV",signal-meaning="Segmentation fault",frame={addr="0x0000000000401116",func="cond_fail",args=[],file="/tmp/mi-condbreak-fail.c",fullname="/tmp/mi-condbreak-fail.c",line="24",arch="i386:x86-64"},thread-id="1",stopped-threads="all",core="9"
>>       &"Error in testing condition for breakpoint 1:\n"
>>       &"The program being debugged was signaled while in a function called from GDB.\n"
>>       &"GDB remains in the frame where the signal was received.\n"
>>       &"To change this behavior use \"set unwindonsignal on\".\n"
>>       &"Evaluation of the expression containing the function\n"
>>       &"(cond_fail) will be abandoned.\n"
>>       &"When the function is done executing, GDB will silently stop.\n"
>>       =breakpoint-modified,bkpt={number="1",type="breakpoint",disp="keep",enabled="y",addr="0x000000000040111e",func="foo",file="/tmp/mi-condbreak-fail.c",fullname="/tmp/mi-condbreak-fail.c",line="30",thread-groups=["i1"],cond="cond_fail()",times="1",original-location="foo"}
>>       *stopped
>>       (gdb)
>>     
>>     Notice that we still see two '*stopped' lines, the first includes the
>>     full frame information, while the second has no frame information,
>>     this is a result of bpstat::print having been set.  Ideally, the
>>     second '*stopped' line should not be present.
>>     
>>     By setting bpstat::print I was addressing the problem too late, this
>>     flag really only changes how interp::on_normal_stop prints the stop
>>     event, and interp::on_normal_stop is called (indirectly) from the
>>     normal_stop function in infrun.c.  A better solution is to avoid
>>     calling normal_stop at all for the stops which should not be reported
>>     to the user, and this is what I do in this commit.
>>     
>>     This commit has 3 parts:
>>     
>>       1. In breakpoint.c, revert the above commit,
>>     
>>       2. In fetch_inferior_event (infrun.c), capture the stop-id before
>>       calling handle_inferior_event.  If, after calling
>>       handle_inferior_event, the stop-id has changed, then this indicates
>>       that somewhere within handle_inferior_event, a stop was announced to
>>       the user.  If this is the case then GDB should not call normal_stop,
>>       and we should rely on whoever announced the stop to ensure that we
>>       are in a PROMPT_NEEDED state, which means the prompt will be
>>       displayed once fetch_inferior_event returns.  And,
>>     
>>       3. In infcall.c, do two things:
>>     
>>          (a) In run_inferior_call, after making the inferior call, ensure
>>          that either async_disable_stdin or async_enable_stdin is called
>>          to put the prompt state, and stdin handling into the correct
>>          state based on whether the inferior call completed successfully
>>          or not, and
>>     
>>          (b) In call_thread_fsm::should_stop, call async_enable_stdin
>>          rather than changing the prompt state directly.  This isn't
>>          strictly necessary, but helped me understand this code more.
>>          This async_enable_stdin call is only reached if normal_stop is
>>          not going to be called, and replaces the async_enable_stdin call
>>          that exists in normal_stop.  Though we could just adjust the
>>          prompt state if felt (to me) much easier to understand when I
>>          could see this call and the corresponding call in normal_stop.
>>     
>>     With these changes in place now, when the inferior call (from the
>>     breakpoint condition) fails, infcall.c leaves the prompt state as
>>     PROMPT_NEEDED, and leaves stdin registered with the event loop.
>>     
>>     Back in fetch_inferior_event GDB notices that the stop-id has changed
>>     and so avoids calling normal_stop.
>>     
>>     And on return from fetch_inferior_event GDB will display the prompt
>>     and handle input from stdin.
>>     
>>     As normal_stop is not called the MI problem is solved, and the test
>>     added in the earlier mentioned commit still passes just fine, so the
>>     CLI has not regressed.
>>     
>>     [1] https://inbox.sourceware.org/gdb-patches/6fd4aa13-6003-2563-5841-e80d5a55d59e@palves.net/
>> 
>> diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
>> index d898167b7e1..93634bd7e51 100644
>> --- a/gdb/breakpoint.c
>> +++ b/gdb/breakpoint.c
>> @@ -5535,7 +5535,6 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
>>  	  else
>>  	    within_current_scope = false;
>>  	}
>> -      CORE_ADDR pc_before_check = get_frame_pc (get_selected_frame (nullptr));
>>        if (within_current_scope)
>>  	{
>>  	  try
>> @@ -5555,17 +5554,6 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
>>  		  (gdb_stderr, ex,
>>  		   "Error in testing condition for breakpoint %d:\n",
>>  		   b->number);
>> -
>> -	      /* If the pc value changed as a result of evaluating the
>> -		 condition then we probably stopped within an inferior
>> -		 function call due to some unexpected stop, e.g. the thread
>> -		 hit another breakpoint, or the thread received an
>> -		 unexpected signal.  In this case we don't want to also
>> -		 print the information about this breakpoint.  */
>> -	      CORE_ADDR pc_after_check
>> -		= get_frame_pc (get_selected_frame (nullptr));
>> -	      if (pc_before_check != pc_after_check)
>> -		bs->print = 0;
>>  	    }
>>  	}
>>        else
>> diff --git a/gdb/infcall.c b/gdb/infcall.c
>> index ddf325a62a5..0944097e18d 100644
>> --- a/gdb/infcall.c
>> +++ b/gdb/infcall.c
>> @@ -564,10 +564,13 @@ call_thread_fsm::should_stop (struct thread_info *thread)
>>  	 call..  */
>>        return_value = get_call_return_value (&return_meta_info);
>>  
>> -      /* Break out of wait_sync_command_done.  */
>> +      /* Break out of wait_sync_command_done.  This is similar to the
>> +	 async_enable_stdin call in normal_stop (which we don't call),
>> +	 however, in this case we only change the WAITING_UI, this is
>
> Full stop after WAITING_UI.
>
>> +	 enough for wait_sync_command_done.  */
>>        scoped_restore save_ui = make_scoped_restore (&current_ui, waiting_ui);
>> -      target_terminal::ours ();
>> -      waiting_ui->prompt_state = PROMPT_NEEDED;
>> +      gdb_assert (current_ui->prompt_state == PROMPT_BLOCKED);
>> +      async_enable_stdin ();
>>      }
>>  
>>    return true;
>> @@ -661,14 +664,30 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
>>    infcall_debug_printf ("thread is now: %s",
>>  			inferior_ptid.to_string ().c_str ());
>>  
>> -  /* If GDB has the prompt blocked before, then ensure that it remains
>> -     so.  normal_stop calls async_enable_stdin, so reset the prompt
>> -     state again here.  In other cases, stdin will be re-enabled by
>> -     inferior_event_handler, when an exception is thrown.  */
>> +  /* After the inferior call async_enable_stdin has been called, either
>> +     from normal_stop or from call_thread_fsm::should_stop, and the prompt
>> +     state has been restored by the scoped_restore in the try block above.
>
> It took me several reads to understand this comment.  I kept misreading this
> as "After ... async_enable_stdin has been called, then ..."
>
> I think putting a comma here
>
>  /* After the inferior call, async_enable_stdin has been called, either
>                           ^^^
>
> would have helped me.  Maybe even say:
>
>    "After the inferior call finishes, ".
>
> ?
>
>> +
>> +     If the inferior call finished successfully then we should disable
>> +     stdin as we don't know yet whether the inferior will be stopping,
>
> The last comma should be a period, IMO.
>
>> +     calling async_disable_stdin restores things as they were when this
>> +     function was called.
>
> "restores things as they were" -> "restores things to how they were" ?
>
>> +
>> +     If the inferior call didn't complete successfully then normal_stop has
>
> Comma before "then".
>
>> +     already been called, and we know for sure that we are going to present
>> +     this stop to the user, in this case we call async_enable_stdin, this
>
> Period after "the user" instead of comma.  Comma after "this case".
> Also period after async_enable_stdin; alternatively, say "which" instead of
> "this".
>
>> +     changes the prompt state to PROMPT_NEEDED.
>> +
>> +     If the previous prompt state was PROMPT_NEEDED then, as
>
> I think you mean to put the comma before "then" instead of after?
> Or is this "then" refering to some previously-referred-to situation?
>
>> +     async_enable_stdin has already been called, nothing additional needs
>> +     to be done here.  */
>
> I found it much easier to understand the whole comment block without applying
> my suggestions above locally.  Here is the result for your reference, and to
> double check I'm parsing this all correctly:
>
>   /* After the inferior call finished, async_enable_stdin has been
>      called, either from normal_stop or from
>      call_thread_fsm::should_stop, and the prompt state has been
>      restored by the scoped_restore in the try block above.
>
>      If the inferior call finished successfully, then we should
>      disable stdin as we don't know yet whether the inferior will be
>      stopping.  Calling async_disable_stdin restores things to how
>      they were when this function was called.
>
>      If the inferior call didn't complete successfully, then
>      normal_stop has already been called, and we know for sure that we
>      are going to present this stop to the user.  In this case, we
>      call async_enable_stdin.  This changes the prompt state to
>      PROMPT_NEEDED.
>
>      If the previous prompt state was PROMPT_NEEDED, then as
>      async_enable_stdin has already been called, nothing additional
>      needs to be done here.  */
>
>
>>    if (current_ui->prompt_state == PROMPT_BLOCKED)
>> -    current_ui->unregister_file_handler ();
>> -  else
>> -    current_ui->register_file_handler ();
>> +    {
>> +      if (call_thread->thread_fsm ()->finished_p ())
>> +	async_disable_stdin ();
>> +      else
>> +	async_enable_stdin ();
>> +    }
>>  
>>    /* If the infcall does NOT succeed, normal_stop will have already
>>       finished the thread states.  However, on success, normal_stop
>> diff --git a/gdb/infrun.c b/gdb/infrun.c
>> index 58da1cef29e..95ab7c6f7dc 100644
>> --- a/gdb/infrun.c
>> +++ b/gdb/infrun.c
>> @@ -4395,6 +4395,8 @@ fetch_inferior_event ()
>>      auto defer_delete_threads
>>        = make_scope_exit (delete_just_stopped_threads_infrun_breakpoints);
>>  
>> +    int stop_id = get_stop_id ();
>> +
>>      /* Now figure out what to do with the result of the result.  */
>>      handle_inferior_event (&ecs);
>>  
>> @@ -4422,7 +4424,19 @@ fetch_inferior_event ()
>>  
>>  	    clean_up_just_stopped_threads_fsms (&ecs);
>>  
>> -	    if (thr != nullptr && thr->thread_fsm () != nullptr)
>> +	    if (stop_id != get_stop_id ())
>> +	      {
>> +		/* If the stop-id has changed then a stop has already been
>> +		   presented to the user in handle_inferior_event, this is
>> +		   likely a failed inferior call.  As the stop has already
>> +		   been announced then we should not notify again.
>> +
>> +		   Also, if the prompt state is not PROMPT_NEEDED then GDB
>> +		   will not be ready for user input after this function.  */
>> +		should_notify_stop = false;
>> +		gdb_assert (current_ui->prompt_state == PROMPT_NEEDED);
>> +	      }
>> +	    else if (thr != nullptr && thr->thread_fsm () != nullptr)
>>  	      should_notify_stop
>>  	       = thr->thread_fsm ()->should_notify_stop ();
>>  
>> diff --git a/gdb/testsuite/gdb.mi/mi-condbreak-fail.c b/gdb/testsuite/gdb.mi/mi-condbreak-fail.c
>> new file mode 100644
>> index 00000000000..94bd2484934
>> --- /dev/null
>> +++ b/gdb/testsuite/gdb.mi/mi-condbreak-fail.c
>> @@ -0,0 +1,39 @@
>> +/* Copyright 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/>.  */
>> +
>> +volatile int global_counter = 0;
>> +
>> +int
>> +cond_fail ()
>> +{
>> +  volatile int *p = 0;
>> +  return *p;			/* Crash here.  */
>> +}
>> +
>> +int
>> +foo ()
>> +{
>> +  global_counter += 1;		/* Set breakpoint here.  */
>> +  return 0;
>> +}
>> +
>> +int
>> +main ()
>> +{
>> +  int res = foo ();
>> +  return res;
>> +}
>> diff --git a/gdb/testsuite/gdb.mi/mi-condbreak-fail.exp b/gdb/testsuite/gdb.mi/mi-condbreak-fail.exp
>> new file mode 100644
>> index 00000000000..86b1db5a8dd
>> --- /dev/null
>> +++ b/gdb/testsuite/gdb.mi/mi-condbreak-fail.exp
>> @@ -0,0 +1,67 @@
>> +# Copyright (C) 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/>.
>> +
>> +# Check that when GDB fails to evaluate the condition of a conditional
>> +# breakpoint we only get one *stopped message.
>
> "message" -> "async record" or "notification".
>
>> +
>> +load_lib mi-support.exp
>> +set MIFLAGS "-i=mi"
>> +
>> +standard_testfile
>> +
>> +if [build_executable ${testfile}.exp ${binfile} ${srcfile}] {
>> +    return -1
>> +}
>> +
>> +if {[mi_clean_restart $binfile]} {
>> +    return
>> +}
>> +
>> +if {[mi_runto_main] == -1} {
>> +    return
>> +}
>> +
>> +# Create the conditional breakpoint.
>> +set bp_location [gdb_get_line_number "Set breakpoint here"]
>> +mi_create_breakpoint "-c \"cond_fail ()\" $srcfile:$bp_location" \
>> +    "insert conditional breakpoint" \
>> +    -func foo -file ".*$srcfile" -line "$bp_location" \
>> +    -cond "cond_fail \\(\\)"
>> +
>> +# Number of the previous breakpoint.
>> +set bpnum [mi_get_valueof "/d" "\$bpnum" "INVALID" \
>> +	       "get number for breakpoint"]
>> +
>> +# The line where we expect the inferior to crash.
>> +set crash_linenum [gdb_get_line_number "Crash here"]
>> +
>> +# Run the inferior and wait for it to stop.
>> +mi_send_resuming_command "exec-continue" "continue the inferior"
>> +mi_gdb_test "" \
>> +    [multi_line \
>> +	 "~\"\\\\nProgram\"" \
>> +	 "~\" received signal SIGSEGV, Segmentation fault\\.\\\\n\"" \
>> +	 "~\"$hex in cond_fail \\(\\) at \[^\r\n\]+\"" \
>> +	 "~\"${crash_linenum}\\\\t\\s+return \\*p;\[^\r\n\]+\\\\n\"" \
>> +	 "\\*stopped,reason=\"signal-received\",signal-name=\"SIGSEGV\"\[^\r\n\]+" \
>> +	 "&\"Error in testing condition for breakpoint $bpnum:\\\\n\"" \
>> +	 "&\"The program being debugged was signaled while in a function called from GDB\\.\\\\n\"" \
>> +	 "&\"GDB remains in the frame where the signal was received\\.\\\\n\"" \
>> +	 "&\"To change this behavior use \\\\\"set unwindonsignal on\\\\\"\\.\\\\n\"" \
>> +	 "&\"Evaluation of the expression containing the function\\\\n\"" \
>> +	 "&\"\\(cond_fail\\) will be abandoned\\.\\\\n\"" \
>> +	 "&\"When the function is done executing, GDB will silently stop\\.\\\\n\"" \
>> +	 "=breakpoint-modified,bkpt={number=\"$bpnum\",type=\"breakpoint\",.*}"] \
>
> I wonder about matching times="1" too, to confirm we're incrementing the hit
> count even if the condition fails.
>
> Also, that ".*" in the last line gave me pause.  It makes it so that a future
> change that results in an output like:
>
>   =breakpoint-modified,bkpt={number=\"$bpnum\",type=\"breakpoint\", [snip]
>   *stopped
>   =something-else-that-ends-in-curly-braces,{...}
>
> would still pass.  Maybe use "\[^\r\n\]*" instead.
>
> With the nits fixed, this LGTM.

I made the fixes you suggested and pushed this patch.

Thanks,
Andrew


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

* [PATCHv9 0/5] Infcalls from B/P conditions in multi-threaded inferiors
  2023-06-07 10:01             ` [PATCHv8 0/6] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                                 ` (6 preceding siblings ...)
  2023-07-04 11:20               ` [PATCHv8 0/6] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
@ 2023-12-02 10:52               ` Andrew Burgess
  2023-12-02 10:52                 ` [PATCHv9 1/5] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
                                   ` (5 more replies)
  7 siblings, 6 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-12-02 10:52 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

In v9:

  - Dropped previous patch #4 (gdb/remote: avoid SIGINT after calling
    remote_target::stop) after feedback from Pedro.  This patch wasn't
    essential for this series, instead I've just updated some of the
    tests to expect different output from remote targets.

  - Updated to more recent master, and applied a small fix due to the
    recent C++17 changes, nothing huge.

  - Retested on unix, native-gdbserver, and native-extended-gdbserver
    boards.

In v8:

  - Rebased onto current upstream/master and retested.

  - Addressed feedback from Baris on patches 1, 2, 3, & 4.  This was
    mostly minor stuff, comment typos and some improvements to the
    testsuite.  There was one real (but minor) GDB change in patch 4.

In v7:

  - Rebased onto current upstream/master, fixed use of
    find_thread_ptid which is now a process_stratum_target method,

  - Retested, with no regressions seen.

In v6:

  - Pushed the 5 initial patches.  These were the smaller fixes, and,
    I felt were pretty obvious fixes.  I'm sure folk will raise
    objections if they disagree.

  - Of the remaining patches, #1 to #5 really needs review before they
    can be merged.  Patch #6 is an obvious cleanup once the first five
    have been merged.

  - I've rebased onto current HEAD of master, there's no significant
    changes.

  - All other documentation changes have been reviewed and approved.

In v5:

  - Rebased to current HEAD of master, minor merge conflict resolved.
    No other code or documentation changes.

  - First patch, which was pure documentation, has now been merged.

  - All other documentation changes have been reviewed and approved.

In v4:

  - I believe all the docs changes have been reviewed and approved by Eli,

  - Rebased onto current master,

  - Dropped patch #2 from the V3 series,

  - I have addressed all the issues Baris pointed out, including the
    fixes for the patch #9 ('gdb: add timeouts for inferior function
    calls'), which I forgot to do in V3.

In v3:

  - Updates for review feedback, biggest changes in #10 and #11, but
    minor changes to most patches.

In V2:

  - Rebased onto something closer to HEAD of master,

  - Patches #1, #2, #12, and #13 are new in this series,

  - Patches #3 to #9, and #11 are unchanged since their V1 iteration,

  - Patches #10 has changed slightly in implementation since v1, and
    the docs have been significantly updated.

---

Andrew Burgess (5):
  Revert "gdb: remove unnecessary parameter wait_ptid from
    do_target_wait"
  gdb: fix b/p conditions with infcalls in multi-threaded inferiors
  gdb: add timeouts for inferior function calls
  gdb: introduce unwind-on-timeout setting
  gdb: rename unwindonsignal to unwind-on-signal

 gdb/NEWS                                      |  36 +++
 gdb/breakpoint.c                              |   2 +
 gdb/doc/gdb.texinfo                           | 111 ++++++-
 gdb/gdbthread.h                               |   3 +
 gdb/infcall.c                                 | 301 +++++++++++++++++-
 gdb/infrun.c                                  |  70 +++-
 gdb/infrun.h                                  |   3 +-
 gdb/testsuite/gdb.base/callfuncs.exp          |   4 +-
 gdb/testsuite/gdb.base/help.exp               |   2 +-
 gdb/testsuite/gdb.base/infcall-failure.exp    |   4 +-
 gdb/testsuite/gdb.base/infcall-timeout.c      |  36 +++
 gdb/testsuite/gdb.base/infcall-timeout.exp    | 115 +++++++
 gdb/testsuite/gdb.base/unwindonsignal.exp     |  36 ++-
 gdb/testsuite/gdb.compile/compile-cplus.exp   |   6 +-
 gdb/testsuite/gdb.compile/compile.exp         |   6 +-
 gdb/testsuite/gdb.cp/gdb2495.exp              |  16 +-
 gdb/testsuite/gdb.fortran/function-calls.exp  |   2 +-
 gdb/testsuite/gdb.mi/mi-condbreak-fail.exp    |   6 +-
 gdb/testsuite/gdb.mi/mi-condbreak-throw.exp   |   2 +-
 gdb/testsuite/gdb.mi/mi-syn-frame.exp         |   2 +-
 .../infcall-from-bp-cond-other-thread-event.c | 135 ++++++++
 ...nfcall-from-bp-cond-other-thread-event.exp | 174 ++++++++++
 .../gdb.threads/infcall-from-bp-cond-simple.c |  89 ++++++
 .../infcall-from-bp-cond-simple.exp           | 235 ++++++++++++++
 .../gdb.threads/infcall-from-bp-cond-single.c | 139 ++++++++
 .../infcall-from-bp-cond-single.exp           | 117 +++++++
 .../infcall-from-bp-cond-timeout.c            | 169 ++++++++++
 .../infcall-from-bp-cond-timeout.exp          | 191 +++++++++++
 .../gdb.threads/thread-unwindonsignal.exp     |   8 +-
 29 files changed, 1943 insertions(+), 77 deletions(-)
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.c
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp


base-commit: a393b155174d20d3d120b5012b87c5438ab9e3d4
-- 
2.25.4


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

* [PATCHv9 1/5] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait"
  2023-12-02 10:52               ` [PATCHv9 0/5] " Andrew Burgess
@ 2023-12-02 10:52                 ` Andrew Burgess
  2023-12-02 10:52                 ` [PATCHv9 2/5] gdb: fix b/p conditions with infcalls in multi-threaded inferiors Andrew Burgess
                                   ` (4 subsequent siblings)
  5 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-12-02 10:52 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Tankut Baris Aktemur

This reverts commit ac0d67ed1dcf470bad6a3bc4800c2ddc9bedecca.

There was nothing wrong with the commit which I'm reverting here, but
it removed some functionality that will be needed for a later commit;
that is, the ability for GDB to ask for events from a specific ptid_t
via the do_target_wait function.

In a follow up commit, this functionality will be used to implement
inferior function calls in multi-threaded inferiors.

This is not a straight revert of the above commit.  Reverting the
above commit replaces a 'nullptr' with 'NULL', I've gone in and
changed that, preserving the 'nullptr'.

Reviewed-By: Tankut Baris Aktemur <tankut.baris.aktemur@intel.com>
---
 gdb/infrun.c | 12 +++++++-----
 1 file changed, 7 insertions(+), 5 deletions(-)

diff --git a/gdb/infrun.c b/gdb/infrun.c
index 45c1b4a79bb..8ef22c6453a 100644
--- a/gdb/infrun.c
+++ b/gdb/infrun.c
@@ -4118,7 +4118,8 @@ do_target_wait_1 (inferior *inf, ptid_t ptid,
    more events.  Polls for events from all inferiors/targets.  */
 
 static bool
-do_target_wait (execution_control_state *ecs, target_wait_flags options)
+do_target_wait (ptid_t wait_ptid, execution_control_state *ecs,
+		target_wait_flags options)
 {
   int num_inferiors = 0;
   int random_selector;
@@ -4128,9 +4129,10 @@ do_target_wait (execution_control_state *ecs, target_wait_flags options)
      polling the rest of the inferior list starting from that one in a
      circular fashion until the whole list is polled once.  */
 
-  auto inferior_matches = [] (inferior *inf)
+  auto inferior_matches = [&wait_ptid] (inferior *inf)
     {
-      return inf->process_target () != nullptr;
+      return (inf->process_target () != nullptr
+	      && ptid_t (inf->pid).matches (wait_ptid));
     };
 
   /* First see how many matching inferiors we have.  */
@@ -4169,7 +4171,7 @@ do_target_wait (execution_control_state *ecs, target_wait_flags options)
 
   auto do_wait = [&] (inferior *inf)
   {
-    ecs->ptid = do_target_wait_1 (inf, minus_one_ptid, &ecs->ws, options);
+    ecs->ptid = do_target_wait_1 (inf, wait_ptid, &ecs->ws, options);
     ecs->target = inf->process_target ();
     return (ecs->ws.kind () != TARGET_WAITKIND_IGNORE);
   };
@@ -4619,7 +4621,7 @@ fetch_inferior_event ()
        the event.  */
     scoped_disable_commit_resumed disable_commit_resumed ("handling event");
 
-    if (!do_target_wait (&ecs, TARGET_WNOHANG))
+    if (!do_target_wait (minus_one_ptid, &ecs, TARGET_WNOHANG))
       {
 	infrun_debug_printf ("do_target_wait returned no event");
 	disable_commit_resumed.reset_and_commit ();
-- 
2.25.4


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

* [PATCHv9 2/5] gdb: fix b/p conditions with infcalls in multi-threaded inferiors
  2023-12-02 10:52               ` [PATCHv9 0/5] " Andrew Burgess
  2023-12-02 10:52                 ` [PATCHv9 1/5] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
@ 2023-12-02 10:52                 ` Andrew Burgess
  2023-12-02 10:52                 ` [PATCHv9 3/5] gdb: add timeouts for inferior function calls Andrew Burgess
                                   ` (3 subsequent siblings)
  5 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-12-02 10:52 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Natalia Saiapova, Tankut Baris Aktemur

This commit fixes bug PR 28942, that is, creating a conditional
breakpoint in a multi-threaded inferior, where the breakpoint
condition includes an inferior function call.

Currently, when a user tries to create such a breakpoint, then GDB
will fail with:

  (gdb) break infcall-from-bp-cond-single.c:61 if (return_true ())
  Breakpoint 2 at 0x4011fa: file /tmp/build/gdb/testsuite/../../../src/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c, line 61.
  (gdb) continue
  Continuing.
  [New Thread 0x7ffff7c5d700 (LWP 2460150)]
  [New Thread 0x7ffff745c700 (LWP 2460151)]
  [New Thread 0x7ffff6c5b700 (LWP 2460152)]
  [New Thread 0x7ffff645a700 (LWP 2460153)]
  [New Thread 0x7ffff5c59700 (LWP 2460154)]
  Error in testing breakpoint condition:
  Couldn't get registers: No such process.
  An error occurred while in a function called from GDB.
  Evaluation of the expression containing the function
  (return_true) will be abandoned.
  When the function is done executing, GDB will silently stop.
  Selected thread is running.
  (gdb)

Or, in some cases, like this:

  (gdb) break infcall-from-bp-cond-simple.c:56 if (is_matching_tid (arg, 1))
  Breakpoint 2 at 0x401194: file /tmp/build/gdb/testsuite/../../../src/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c, line 56.
  (gdb) continue
  Continuing.
  [New Thread 0x7ffff7c5d700 (LWP 2461106)]
  [New Thread 0x7ffff745c700 (LWP 2461107)]
  ../../src.release/gdb/nat/x86-linux-dregs.c:146: internal-error: x86_linux_update_debug_registers: Assertion `lwp_is_stopped (lwp)' failed.
  A problem internal to GDB has been detected,
  further debugging may prove unreliable.

The precise error depends on the exact thread state; so there's race
conditions depending on which threads have fully started, and which
have not.  But the underlying problem is always the same; when GDB
tries to execute the inferior function call from within the breakpoint
condition, GDB will, incorrectly, try to resume threads that are
already running - GDB doesn't realise that some threads might already
be running.

The solution proposed in this patch requires an additional member
variable thread_info::in_cond_eval.  This flag is set to true (in
breakpoint.c) when GDB is evaluating a breakpoint condition.

In user_visible_resume_ptid (infrun.c), when the in_cond_eval flag is
true, then GDB will only try to resume the current thread, that is,
the thread for which the breakpoint condition is being evaluated.
This solves the problem of GDB trying to resume threads that are
already running.

The next problem is that inferior function calls are assumed to be
synchronous, that is, GDB doesn't expect to start an inferior function
call in thread #1, then receive a stop from thread #2 for some other,
unrelated reason.  To prevent GDB responding to an event from another
thread, we update fetch_inferior_event and do_target_wait in infrun.c,
so that, when an inferior function call (on behalf of a breakpoint
condition) is in progress, we only wait for events from the current
thread (the one evaluating the condition).

In do_target_wait I had to change the inferior_matches lambda
function, which is used to select which inferior to wait on.
Previously the logic was this:

   auto inferior_matches = [&wait_ptid] (inferior *inf)
     {
       return (inf->process_target () != nullptr
               && ptid_t (inf->pid).matches (wait_ptid));
     };

This compares the pid of the inferior against the complete ptid we
want to wait on.  Before this commit wait_ptid was only ever
minus_one_ptid (which is special, and means any process), and so every
inferior would match.

After this commit though wait_ptid might represent a specific thread
in a specific inferior.  If we compare the pid of the inferior to a
specific ptid then these will not match.  The fix is to compare
against the pid extracted from the wait_ptid, not against the complete
wait_ptid itself.

In fetch_inferior_event, after receiving the event, we only want to
stop all the other threads, and call inferior_event_handler with
INF_EXEC_COMPLETE, if we are not evaluating a conditional breakpoint.
If we are, then all the other threads should be left doing whatever
they were before.  The inferior_event_handler call will be performed
once the breakpoint condition has finished being evaluated, and GDB
decides to stop or not.

The final problem that needs solving relates to GDB's commit-resume
mechanism, which allows GDB to collect resume requests into a single
packet in order to reduce traffic to a remote target.

The problem is that the commit-resume mechanism will not send any
resume requests for an inferior if there are already events pending on
the GDB side.

Imagine an inferior with two threads.  Both threads hit a breakpoint,
maybe the same conditional breakpoint.  At this point there are two
pending events, one for each thread.

GDB selects one of the events and spots that this is a conditional
breakpoint, GDB evaluates the condition.

The condition includes an inferior function call, so GDB sets up for
the call and resumes the one thread, the resume request is added to
the commit-resume queue.

When the commit-resume queue is committed GDB sees that there is a
pending event from another thread, and so doesn't send any resume
requests to the actual target, GDB is assuming that when we wait we
will select the event from the other thread.

However, as this is an inferior function call for a condition
evaluation, we will not select the event from the other thread, we
only care about events from the thread that is evaluating the
condition - and the resume for this thread was never sent to the
target.

And so, GDB hangs, waiting for an event from a thread that was never
fully resumed.

To fix this issue I have added the concept of "forcing" the
commit-resume queue.  When enabling commit resume, if the force flag
is true, then any resumes will be committed to the target, even if
there are other threads with pending events.

A note on authorship: this patch was based on some work done by
Natalia Saiapova and Tankut Baris Aktemur from Intel[1].  I have made
some changes to their work in this version.

Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=28942

[1] https://sourceware.org/pipermail/gdb-patches/2020-October/172454.html

Co-authored-by: Natalia Saiapova <natalia.saiapova@intel.com>
Co-authored-by: Tankut Baris Aktemur <tankut.baris.aktemur@intel.com>
Reviewed-By: Tankut Baris Aktemur <tankut.baris.aktemur@intel.com>
---
 gdb/breakpoint.c                              |   2 +
 gdb/gdbthread.h                               |   3 +
 gdb/infcall.c                                 |   6 +
 gdb/infrun.c                                  |  64 +++--
 gdb/infrun.h                                  |   3 +-
 .../infcall-from-bp-cond-other-thread-event.c | 135 ++++++++++
 ...nfcall-from-bp-cond-other-thread-event.exp | 174 +++++++++++++
 .../gdb.threads/infcall-from-bp-cond-simple.c |  89 +++++++
 .../infcall-from-bp-cond-simple.exp           | 235 ++++++++++++++++++
 .../gdb.threads/infcall-from-bp-cond-single.c | 139 +++++++++++
 .../infcall-from-bp-cond-single.exp           | 117 +++++++++
 11 files changed, 952 insertions(+), 15 deletions(-)
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 699919e32b3..252bc72e011 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -5675,6 +5675,8 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
 	{
 	  try
 	    {
+	      scoped_restore reset_in_cond_eval
+		= make_scoped_restore (&thread->control.in_cond_eval, true);
 	      condition_result = breakpoint_cond_eval (cond);
 	    }
 	  catch (const gdb_exception_error &ex)
diff --git a/gdb/gdbthread.h b/gdb/gdbthread.h
index b2c6baf4432..1bd6a8f508c 100644
--- a/gdb/gdbthread.h
+++ b/gdb/gdbthread.h
@@ -172,6 +172,9 @@ struct thread_control_state
      command.  This is used to decide whether "set scheduler-locking
      step" behaves like "on" or "off".  */
   int stepping_command = 0;
+
+  /* True if the thread is evaluating a BP condition.  */
+  bool in_cond_eval = false;
 };
 
 /* Inferior thread specific part of `struct infcall_suspend_state'.  */
diff --git a/gdb/infcall.c b/gdb/infcall.c
index 8252feea074..935a555e817 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -672,6 +672,12 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
 
       proceed (real_pc, GDB_SIGNAL_0);
 
+      /* Enable commit resume, but pass true for the force flag.  This
+	 ensures any thread we set running in proceed will actually be
+	 committed to the target, even if some other thread in the current
+	 target has a pending event.  */
+      scoped_enable_commit_resumed enable ("infcall", true);
+
       infrun_debug_show_threads ("non-exited threads after proceed for inferior-call",
 				 all_non_exited_threads ());
 
diff --git a/gdb/infrun.c b/gdb/infrun.c
index 8ef22c6453a..ae99fe17b0c 100644
--- a/gdb/infrun.c
+++ b/gdb/infrun.c
@@ -2399,6 +2399,14 @@ user_visible_resume_ptid (int step)
 	 mode.  */
       resume_ptid = inferior_ptid;
     }
+  else if (inferior_ptid != null_ptid
+	   && inferior_thread ()->control.in_cond_eval)
+    {
+      /* The inferior thread is evaluating a BP condition.  Other threads
+	 might be stopped or running and we do not want to change their
+	 state, thus, resume only the current thread.  */
+      resume_ptid = inferior_ptid;
+    }
   else if (!sched_multi && target_supports_multi_process ())
     {
       /* Resume all threads of the current process (and none of other
@@ -3194,12 +3202,24 @@ schedlock_applies (struct thread_info *tp)
 					    execution_direction)));
 }
 
-/* Set process_stratum_target::COMMIT_RESUMED_STATE in all target
-   stacks that have threads executing and don't have threads with
-   pending events.  */
+/* When FORCE_P is false, set process_stratum_target::COMMIT_RESUMED_STATE
+   in all target stacks that have threads executing and don't have threads
+   with pending events.
+
+   When FORCE_P is true, set process_stratum_target::COMMIT_RESUMED_STATE
+   in all target stacks that have threads executing regardless of whether
+   there are pending events or not.
+
+   Passing FORCE_P as false makes sense when GDB is going to wait for
+   events from all threads and will therefore spot the pending events.
+   However, if GDB is only going to wait for events from select threads
+   (i.e. when performing an inferior call) then a pending event on some
+   other thread will not be spotted, and if we fail to commit the resume
+   state for the thread performing the inferior call, then the inferior
+   call will never complete (or even start).  */
 
 static void
-maybe_set_commit_resumed_all_targets ()
+maybe_set_commit_resumed_all_targets (bool force_p)
 {
   scoped_restore_current_thread restore_thread;
 
@@ -3228,7 +3248,7 @@ maybe_set_commit_resumed_all_targets ()
 	 status to report, handle it before requiring the target to
 	 commit its resumed threads: handling the status might lead to
 	 resuming more threads.  */
-      if (proc_target->has_resumed_with_pending_wait_status ())
+      if (!force_p && proc_target->has_resumed_with_pending_wait_status ())
 	{
 	  infrun_debug_printf ("not requesting commit-resumed for target %s, a"
 			       " thread has a pending waitstatus",
@@ -3238,7 +3258,7 @@ maybe_set_commit_resumed_all_targets ()
 
       switch_to_inferior_no_thread (inf);
 
-      if (target_has_pending_events ())
+      if (!force_p && target_has_pending_events ())
 	{
 	  infrun_debug_printf ("not requesting commit-resumed for target %s, "
 			       "target has pending events",
@@ -3331,7 +3351,7 @@ scoped_disable_commit_resumed::reset ()
     {
       /* This is the outermost instance, re-enable
 	 COMMIT_RESUMED_STATE on the targets where it's possible.  */
-      maybe_set_commit_resumed_all_targets ();
+      maybe_set_commit_resumed_all_targets (false);
     }
   else
     {
@@ -3364,7 +3384,7 @@ scoped_disable_commit_resumed::reset_and_commit ()
 /* See infrun.h.  */
 
 scoped_enable_commit_resumed::scoped_enable_commit_resumed
-  (const char *reason)
+  (const char *reason, bool force_p)
   : m_reason (reason),
     m_prev_enable_commit_resumed (enable_commit_resumed)
 {
@@ -3376,7 +3396,7 @@ scoped_enable_commit_resumed::scoped_enable_commit_resumed
 
       /* Re-enable COMMIT_RESUMED_STATE on the targets where it's
 	 possible.  */
-      maybe_set_commit_resumed_all_targets ();
+      maybe_set_commit_resumed_all_targets (force_p);
 
       maybe_call_commit_resumed_all_targets ();
     }
@@ -4129,10 +4149,11 @@ do_target_wait (ptid_t wait_ptid, execution_control_state *ecs,
      polling the rest of the inferior list starting from that one in a
      circular fashion until the whole list is polled once.  */
 
-  auto inferior_matches = [&wait_ptid] (inferior *inf)
+  ptid_t wait_ptid_pid {wait_ptid.pid ()};
+  auto inferior_matches = [&wait_ptid_pid] (inferior *inf)
     {
       return (inf->process_target () != nullptr
-	      && ptid_t (inf->pid).matches (wait_ptid));
+	      && ptid_t (inf->pid).matches (wait_ptid_pid));
     };
 
   /* First see how many matching inferiors we have.  */
@@ -4621,7 +4642,17 @@ fetch_inferior_event ()
        the event.  */
     scoped_disable_commit_resumed disable_commit_resumed ("handling event");
 
-    if (!do_target_wait (minus_one_ptid, &ecs, TARGET_WNOHANG))
+    /* Is the current thread performing an inferior function call as part
+       of a breakpoint condition evaluation?  */
+    bool in_cond_eval = (inferior_ptid != null_ptid
+			 && inferior_thread ()->control.in_cond_eval);
+
+    /* If the thread is in the middle of the condition evaluation, wait for
+       an event from the current thread.  Otherwise, wait for an event from
+       any thread.  */
+    ptid_t waiton_ptid = in_cond_eval ? inferior_ptid : minus_one_ptid;
+
+    if (!do_target_wait (waiton_ptid, &ecs, TARGET_WNOHANG))
       {
 	infrun_debug_printf ("do_target_wait returned no event");
 	disable_commit_resumed.reset_and_commit ();
@@ -4679,7 +4710,12 @@ fetch_inferior_event ()
 	    bool should_notify_stop = true;
 	    bool proceeded = false;
 
-	    stop_all_threads_if_all_stop_mode ();
+	    /* If the thread that stopped just completed an inferior
+	       function call as part of a condition evaluation, then we
+	       don't want to stop all the other threads.  */
+	    if (ecs.event_thread == nullptr
+		|| !ecs.event_thread->control.in_cond_eval)
+	      stop_all_threads_if_all_stop_mode ();
 
 	    clean_up_just_stopped_threads_fsms (&ecs);
 
@@ -4706,7 +4742,7 @@ fetch_inferior_event ()
 		  proceeded = normal_stop ();
 	      }
 
-	    if (!proceeded)
+	    if (!proceeded && !in_cond_eval)
 	      {
 		inferior_event_handler (INF_EXEC_COMPLETE);
 		cmd_done = 1;
diff --git a/gdb/infrun.h b/gdb/infrun.h
index a343d27f72d..d8db153ecc6 100644
--- a/gdb/infrun.h
+++ b/gdb/infrun.h
@@ -406,7 +406,8 @@ extern void maybe_call_commit_resumed_all_targets ();
 
 struct scoped_enable_commit_resumed
 {
-  explicit scoped_enable_commit_resumed (const char *reason);
+  explicit scoped_enable_commit_resumed (const char *reason,
+					 bool force_p = false);
   ~scoped_enable_commit_resumed ();
 
   DISABLE_COPY_AND_ASSIGN (scoped_enable_commit_resumed);
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
new file mode 100644
index 00000000000..e2a8ccb4ebe
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
@@ -0,0 +1,135 @@
+/* Copyright 2022-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 <pthread.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <sched.h>
+
+#define NUM_THREADS 2
+
+pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+
+/* Some global variables to poke, just for something to do.  */
+volatile int global_var_0 = 0;
+volatile int global_var_1 = 0;
+
+/* This flag is updated from GDB.  */
+volatile int raise_signal = 0;
+
+/* Implement the breakpoint condition function.  Release the other thread
+   and try to give the other thread a chance to run.  Then return ANSWER.  */
+int
+condition_core_func (int answer)
+{
+  /* This unlock should release the other thread.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  /* And this yield and sleep should (hopefully) give the other thread a
+     chance to run.  This isn't guaranteed of course, but once the other
+     thread does run it should hit a breakpoint, which GDB should
+     (temporarily) ignore, so there's no easy way for us to know the other
+     thread has done what it needs to, thus, yielding and sleeping is the
+     best we can do.  */
+  sched_yield ();
+  sleep (2);
+
+  return answer;
+}
+
+void
+stop_marker ()
+{
+  int a = 100;	/* Final breakpoint here.  */
+}
+
+/* A breakpoint condition function that always returns true.  */
+int
+condition_true_func ()
+{
+  return condition_core_func (1);
+}
+
+/* A breakpoint condition function that always returns false.  */
+int
+condition_false_func ()
+{
+  return condition_core_func (0);
+}
+
+void *
+worker_func (void *arg)
+{
+  volatile int *ptr = 0;
+  int tid = *((int *) arg);
+
+  switch (tid)
+    {
+    case 0:
+      global_var_0 = 11;	/* First thread breakpoint.  */
+      break;
+
+    case 1:
+      if (pthread_mutex_lock (&mutex) != 0)
+	abort ();
+      if (raise_signal)
+	global_var_1 = *ptr;	/* Signal here.  */
+      else
+	global_var_1 = 99;	/* Other thread breakpoint.  */
+      break;
+
+    default:
+      abort ();
+    }
+
+  return NULL;
+}
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+
+  /* Set an alarm, just in case the test deadlocks.  */
+  alarm (300);
+
+  /* We want the mutex to start locked.  */
+  if (pthread_mutex_lock (&mutex) != 0)
+    abort ();
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      void *retval;
+      pthread_join (threads[i], &retval);
+    }
+
+  /* Unlock once we're done, just for cleanliness.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
new file mode 100644
index 00000000000..1453575e4ad
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
@@ -0,0 +1,174 @@
+# Copyright 2022-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/>.
+
+# Test for conditional breakpoints where the breakpoint condition includes
+# an inferior function call.
+#
+# The tests in this script are testing what happens when an event arrives in
+# another thread while GDB is waiting for the inferior function call (in the
+# breakpoint condition) to finish.
+#
+# The expectation is that GDB will queue events for other threads and wait
+# for the inferior function call to complete, if the condition is true, then
+# the conditional breakpoint should be reported first.  The other thread
+# event should of course, not get lost, and should be reported as soon as
+# the user tries to continue the inferior.
+#
+# If the conditional breakpoint ends up not being taken (the condition is
+# false), then the other thread event should be reported immediately.
+#
+# This script tests what happens when the other thread event is (a) the
+# other thread hitting a breakpoint, and (b) the other thread taking a
+# signal (SIGSEGV in this case).
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] == -1 } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "First thread breakpoint"]
+set other_bp_line [gdb_get_line_number "Other thread breakpoint"]
+set final_bp_line [gdb_get_line_number "Final breakpoint here"]
+set signal_line [gdb_get_line_number "Signal here"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if { ![runto_main] } {
+	return -1
+    }
+
+    return 0
+}
+
+# Run a test of GDB's conditional breakpoints, where the conditions include
+# inferior function calls.  While the inferior function call is executing
+# another thread will hit a breakpoint (when OTHER_THREAD_SIGNAL is false),
+# or receive a signal (when OTHER_THREAD_SIGNAL is true).  GDB should report
+# the conditional breakpoint first (if the condition is true), and then
+# report the second thread event once the inferior is continued again.
+#
+# When STOP_AT_COND is true then the conditional breakpoint will have a
+# condition that evaluates to true (and GDB will stop at the breakpoint),
+# otherwise, the condition will evaluate to false (and GDB will not stop at
+# the breakpoint).
+proc run_condition_test { stop_at_cond other_thread_signal \
+			      target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint.
+    if { $stop_at_cond } {
+	set cond_func "condition_true_func"
+    } else {
+	set cond_func "condition_false_func"
+    }
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (${cond_func} ())"
+    set cond_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			"get number for conditional breakpoint"]
+
+    if { $other_thread_signal } {
+	# Arrange for the other thread to raise a signal while GDB is
+	# evaluating the breakpoint condition.
+	gdb_test_no_output "set raise_signal = 1"
+    } else {
+	# And a breakpoint that will be hit by another thread only once the
+	# breakpoint condition starts to be evaluated.
+	gdb_breakpoint "${::srcfile}:${::other_bp_line}"
+	set other_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			      "get number for other breakpoint"]
+    }
+
+    # A final breakpoint once the test has completed.
+    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
+    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			  "get number for final breakpoint"]
+
+    if { $stop_at_cond } {
+	# Continue.  The first breakpoint we hit should be the conditional
+	# breakpoint.  The other thread will have hit its breakpoint, but
+	# that will have been deferred until the conditional breakpoint is
+	# reported.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${cond_bp_num}, worker_func \[^\r\n\]+:${::cond_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+First thread breakpoint\[^\r\n\]+"] \
+	    "hit the conditional breakpoint"
+    }
+
+    if { $other_thread_signal } {
+	# Now continue again, the other thread will now report that it
+	# received a signal.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" received signal SIGSEGV, Segmentation fault\\." \
+		 "\\\[Switching to Thread \[^\r\n\]+\\\]" \
+		 "${::hex} in worker_func \[^\r\n\]+:${::signal_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Signal here\[^\r\n\]+"] \
+	    "received signal in other thread"
+    } else {
+	# Now continue again, the other thread will now report its
+	# breakpoint.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${other_bp_num}, worker_func \[^\r\n\]+:${::other_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Other thread breakpoint\[^\r\n\]+"] \
+	    "hit the breakpoint in other thread"
+
+	# Run to the stop marker.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${final_bp_num}, stop_marker \[^\r\n\]+:${::final_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Final breakpoint here\[^\r\n\]+"] \
+	    "hit the final breakpoint"
+    }
+
+    gdb_exit
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	foreach_with_prefix other_thread_signal { true false } {
+	    foreach_with_prefix stop_at_cond { true false } {
+		run_condition_test $stop_at_cond $other_thread_signal \
+		    $target_async $target_non_stop
+	    }
+	}
+    }
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
new file mode 100644
index 00000000000..9d746d8be49
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
@@ -0,0 +1,89 @@
+/* Copyright 2022-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 <pthread.h>
+#include <unistd.h>
+
+#define NUM_THREADS 3
+
+int
+is_matching_tid (int *tid_ptr, int tid_value)
+{
+  return *tid_ptr == tid_value;
+}
+
+int
+return_true ()
+{
+  return 1;
+}
+
+int
+return_false ()
+{
+  return 0;
+}
+
+int
+function_that_segfaults ()
+{
+  int *p = 0;
+  *p = 1;	/* Segfault happens here.   */
+}
+
+int
+function_with_breakpoint ()
+{
+  return 1;	/* Nested breakpoint.  */
+}
+
+void *
+worker_func (void *arg)
+{
+  int a = 42;	/* Breakpoint here.  */
+}
+
+void
+stop_marker ()
+{
+  int b = 99;	/* Stop marker.  */
+}
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+
+  alarm (300);
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      void *retval;
+      pthread_join (threads[i], &retval);
+    }
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
new file mode 100644
index 00000000000..c46f8cdb981
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
@@ -0,0 +1,235 @@
+# Copyright 2022-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/>.
+
+# Some simple tests of inferior function calls from breakpoint
+# conditions, in multi-threaded inferiors.
+#
+# This test sets up a multi-threaded inferior, and places a breakpoint
+# at a location that many of the threads will reach.  We repeat the
+# test with different conditions, sometimes a single thread should
+# stop at the breakpoint, sometimes multiple threads should stop, and
+# sometimes no threads should stop.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] == -1 } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "Breakpoint here"]
+set stop_bp_line [gdb_get_line_number "Stop marker"]
+set nested_bp_line [gdb_get_line_number "Nested breakpoint"]
+set segv_line [gdb_get_line_number "Segfault happens here"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if { ![runto_main] } {
+	return -1
+    }
+
+    return 0
+}
+
+# Run a test of GDB's conditional breakpoints, where the conditions include
+# inferior function calls.
+#
+# CONDITION is the expression to be used as the breakpoint condition.
+#
+# N_EXPECTED_HITS is the number of threads that we expect to stop due to
+# CONDITON.
+#
+# MESSAGE is used as a test name prefix.
+proc run_condition_test { message n_expected_hits condition \
+			      target_async target_non_stop } {
+    with_test_prefix $message {
+
+	if { [start_gdb_and_runto_main $target_async \
+		  $target_non_stop] == -1 } {
+	    return
+	}
+
+	# Use this convenience variable to track how often the
+	# breakpoint condition has been evaluated.  This should be
+	# once per thread.
+	gdb_test "set \$n_cond_eval = 0"
+
+	# Setup the conditional breakpoint.
+	gdb_breakpoint \
+	    "${::srcfile}:${::cond_bp_line} if ((++\$n_cond_eval) && (${condition}))"
+
+	# And a breakpoint that we hit when the test is over, this one is
+	# not conditional.  Only the main thread gets here once all the
+	# other threads have finished.
+	gdb_breakpoint "${::srcfile}:${::stop_bp_line}"
+
+	# The number of times we stop at the conditional breakpoint.
+	set n_hit_condition 0
+
+	# Now keep 'continue'-ing GDB until all the threads have finished
+	# and we reach the stop_marker breakpoint.
+	gdb_test_multiple "continue" "spot all breakpoint hits" {
+	    -re " worker_func \[^\r\n\]+${::srcfile}:${::cond_bp_line}\r\n${::decimal}\\s+\[^\r\n\]+Breakpoint here\[^\r\n\]+\r\n${::gdb_prompt} $" {
+		incr n_hit_condition
+		send_gdb "continue\n"
+		exp_continue
+	    }
+
+	    -re " stop_marker \[^\r\n\]+${::srcfile}:${::stop_bp_line}\r\n${::decimal}\\s+\[^\r\n\]+Stop marker\[^\r\n\]+\r\n${::gdb_prompt} $" {
+		pass $gdb_test_name
+	    }
+	}
+
+	gdb_assert { $n_hit_condition == $n_expected_hits } \
+	    "stopped at breakpoint the expected number of times"
+
+	# Ensure the breakpoint condition was evaluated once per thread.
+	gdb_test "print \$n_cond_eval" "= 3" \
+	    "condition was evaluated in each thread"
+    }
+}
+
+# Check that after handling a conditional breakpoint (where the condition
+# includes an inferior call), it is still possible to kill the running
+# inferior, and then restart the inferior.
+#
+# At once point doing this would result in GDB giving an assertion error.
+proc_with_prefix run_kill_and_restart_test { target_async target_non_stop } {
+    # This test relies on the 'start' command, which is not possible with
+    # the plain 'remote' target.
+    if { [target_info gdb_protocol] == "remote" } {
+	return
+    }
+
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint.
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 1))"
+    gdb_continue_to_breakpoint "worker_func"
+
+    # Now kill the program being debugged.
+    gdb_test "kill" "" "kill process" \
+	"Kill the program being debugged.*y or n. $" "y"
+
+    # Check we can restart the inferior.  At one point this would trigger an
+    # assertion.
+    gdb_start_cmd
+}
+
+# Create a conditional breakpoint which includes a call to a function that
+# segfaults.  Run GDB and check what happens when the inferior segfaults
+# during the inferior call.
+proc_with_prefix run_bp_cond_segfaults { target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # This test relies on the inferior segfaulting when trying to
+    # access address zero.
+    if { [is_address_zero_readable] } {
+	return
+    }
+
+    # Setup the conditional breakpoint, include a call to
+    # 'function_that_segfaults', which triggers the segfault.
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 0) && function_that_segfaults ())"
+    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of conditional breakpoint"]
+
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     ".*" \
+	     "Thread ${::decimal} \"infcall-from-bp\" received signal SIGSEGV, Segmentation fault\\." \
+	     "${::hex} in function_that_segfaults \\(\\) at \[^\r\n\]+:${::segv_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Segfault happens here\[^\r\n\]+" \
+	     "Error in testing condition for breakpoint ${bp_1_num}:" \
+	     "The program being debugged was signaled while in a function called from GDB\\." \
+	     "GDB remains in the frame where the signal was received\\." \
+	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(function_that_segfaults\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+}
+
+# Create a conditional breakpoint which includes a call to a function that
+# itself has a breakpoint set within it.  Run GDB and check what happens
+# when GDB hits the nested breakpoint.
+proc_with_prefix run_bp_cond_hits_breakpoint { target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint, include a call to
+    # 'function_with_breakpoint' in which we will shortly place a
+    # breakpoint.
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 0) && function_with_breakpoint ())"
+    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of conditional breakpoint"]
+
+    gdb_breakpoint "${::srcfile}:${::nested_bp_line}"
+    set bp_2_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of nested breakpoint"]
+
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     ".*" \
+	     "Thread ${::decimal} \"infcall-from-bp\" hit Breakpoint ${bp_2_num}, function_with_breakpoint \\(\\) at \[^\r\n\]+:${::nested_bp_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Nested breakpoint\[^\r\n\]+" \
+	     "Error in testing condition for breakpoint ${bp_1_num}:" \
+	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(function_with_breakpoint\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	run_condition_test "exactly one thread is hit" \
+	    1 "is_matching_tid (arg, 1)" \
+	    $target_async $target_non_stop
+	run_condition_test "exactly two threads are hit" \
+	    2 "(is_matching_tid (arg, 0) || is_matching_tid (arg, 2))" \
+	    $target_async $target_non_stop
+	run_condition_test "all three threads are hit" \
+	    3 "return_true ()" \
+	    $target_async $target_non_stop
+	run_condition_test "no thread is hit" \
+	    0 "return_false ()" \
+	    $target_async $target_non_stop
+
+	run_kill_and_restart_test $target_async $target_non_stop
+	run_bp_cond_segfaults $target_async $target_non_stop
+	run_bp_cond_hits_breakpoint $target_async $target_non_stop
+    }
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
new file mode 100644
index 00000000000..835c72f03cf
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
@@ -0,0 +1,139 @@
+/* Copyright 2022-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 <pthread.h>
+#include <unistd.h>
+#include <semaphore.h>
+#include <stdlib.h>
+
+#define NUM_THREADS 5
+
+/* Semaphores, used to track when threads have started, and to control
+   when the threads finish.  */
+sem_t startup_semaphore;
+sem_t finish_semaphore;
+
+/* Mutex to control when the first worker thread hit a breakpoint
+   location.  */
+pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+
+/* Global variable to poke, just so threads have something to do.  */
+volatile int global_var = 0;
+
+int
+return_true ()
+{
+  return 1;
+}
+
+int
+return_false ()
+{
+  return 0;
+}
+
+void *
+worker_func (void *arg)
+{
+  int tid = *((int *) arg);
+
+  switch (tid)
+    {
+    case 0:
+      /* Wait for MUTEX to become available, then pass through the
+	 conditional breakpoint location.  */
+      if (pthread_mutex_lock (&mutex) != 0)
+	abort ();
+      global_var = 99;	/* Conditional breakpoint here.  */
+      if (pthread_mutex_unlock (&mutex) != 0)
+	abort ();
+      break;
+
+    default:
+      /* Notify the main thread that the thread has started, then wait for
+	 the main thread to tell us to finish.  */
+      sem_post (&startup_semaphore);
+      if (sem_wait (&finish_semaphore) != 0)
+	abort ();
+      break;
+    }
+}
+
+void
+stop_marker ()
+{
+  global_var = 99;	/* Stop marker.  */
+}
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+  void *retval;
+
+  /* An alarm, just in case the thread deadlocks.  */
+  alarm (300);
+
+  /* Semaphore initialization.  */
+  if (sem_init (&startup_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&finish_semaphore, 0, 0) != 0)
+    abort ();
+
+  /* Lock MUTEX, this prevents the first worker thread from rushing ahead.  */
+  if (pthread_mutex_lock (&mutex) != 0)
+    abort ();
+
+  /* Worker thread creation.  */
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  /* Wait for every thread (other than the first) to tell us it has started
+     up.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    {
+      if (sem_wait (&startup_semaphore) != 0)
+	abort ();
+    }
+
+  /* Unlock the first thread so it can proceed.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  /* Wait for the first thread only.  */
+  pthread_join (threads[0], &retval);
+
+  /* Now post FINISH_SEMAPHORE to allow all the other threads to finish.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    sem_post (&finish_semaphore);
+
+  /* Now wait for the remaining threads to complete.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    pthread_join (threads[i], &retval);
+
+  /* Semaphore cleanup.  */
+  sem_destroy (&finish_semaphore);
+  sem_destroy (&startup_semaphore);
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
new file mode 100644
index 00000000000..787dee3aa8e
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
@@ -0,0 +1,117 @@
+# Copyright 2022-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 reprocuces bug gdb/28942, performing an inferior function
+# call from a breakpoint condition in a multi-threaded inferior.
+#
+# The important part of this test is that, when the conditional
+# breakpoint is hit, and the condition (which includes an inferior
+# function call) is evaluated, the other threads are running.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] == -1 } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "Conditional breakpoint here"]
+set final_bp_line [gdb_get_line_number "Stop marker"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if { ![runto_main] } {
+	return -1
+    }
+
+    return 0
+}
+
+# Run a test of GDB's conditional breakpoints, where the conditions include
+# inferior function calls.
+#
+# TARGET_ASYNC and TARGET_NON_STOP are used when starting up GDB.
+#
+# When STOP_AT_COND is true the breakpoint condtion will evaluate to
+# true, and GDB will stop at the breakpoint.  Otherwise, the
+# breakpoint condition will evaluate to false and GDB will not stop at
+# the breakpoint.
+proc run_condition_test { stop_at_cond \
+			      target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint.
+    if { $stop_at_cond } {
+	set cond_func "return_true"
+    } else {
+	set cond_func "return_false"
+    }
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (${cond_func} ())"
+    set cond_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			"get number for conditional breakpoint"]
+
+    # And a breakpoint that we hit when the test is over, this one is
+    # not conditional.
+    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
+    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			  "get number for final breakpoint"]
+
+    if { $stop_at_cond } {
+	# Continue.  The first breakpoint we hit should be the conditional
+	# breakpoint.  The other thread will have hit its breakpoint, but
+	# that will have been deferred until the conditional breakpoint is
+	# reported.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${cond_bp_num}, worker_func \[^\r\n\]+:${::cond_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Conditional breakpoint here\[^\r\n\]+"] \
+	    "hit the conditional breakpoint"
+    }
+
+    # Run to the stop marker.
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     ".*" \
+	     "" \
+	     "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${final_bp_num}, stop_marker \[^\r\n\]+:${::final_bp_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Stop marker\[^\r\n\]+"] \
+	"hit the final breakpoint"
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	foreach_with_prefix stop_at_cond { true false } {
+	    run_condition_test $stop_at_cond \
+		$target_async $target_non_stop
+	}
+    }
+}
-- 
2.25.4


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

* [PATCHv9 3/5] gdb: add timeouts for inferior function calls
  2023-12-02 10:52               ` [PATCHv9 0/5] " Andrew Burgess
  2023-12-02 10:52                 ` [PATCHv9 1/5] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
  2023-12-02 10:52                 ` [PATCHv9 2/5] gdb: fix b/p conditions with infcalls in multi-threaded inferiors Andrew Burgess
@ 2023-12-02 10:52                 ` Andrew Burgess
  2023-12-02 10:52                 ` [PATCHv9 4/5] gdb: introduce unwind-on-timeout setting Andrew Burgess
                                   ` (2 subsequent siblings)
  5 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-12-02 10:52 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Tankut Baris Aktemur, Eli Zaretskii

Eli has already approved the NEWS/doc changes in this file.

---

In the previous commits I have been working on improving inferior
function call support.  One thing that worries me about using inferior
function calls from a conditional breakpoint is: what happens if the
inferior function call fails?

If the failure is obvious, e.g. the thread performing the call
crashes, or hits a breakpoint, then this case is already well handled,
and the error is reported to the user.

But what if the thread performing the inferior call just deadlocks?
If the user made the call from a 'print' or 'call' command, then the
user might have some expectation of when the function call should
complete, and, when this time limit is exceeded, the user
will (hopefully) interrupt GDB and regain control of the debug
session.

But, when the inferior function call is from a breakpoint condition it
is much harder to understand that GDB is deadlocked within an inferior
call.  Maybe the breakpoint hasn't been hit yet?  Or maybe the
condition was always false?  Or maybe GDB is deadlocked in an inferior
call?  The only way to know for sure is for the user to periodically
interrupt the inferior, check on the state of all the threads, and
then continue.

Additionally, the focus of the previous commit was inferior function
calls, from a conditional breakpoint, in a multi-threaded inferior.
This opens up a whole new set of potential failure conditions.  For
example, what if the function called relies on interaction with some
other thread, and the other thread crashes?  Or hits a breakpoint?
Given how inferior function calls work (in a synchronous manner), a
stop event in some other thread is going to be ignored while the
inferior function call is being executed as part of a breakpoint
condition, and this means that GDB could get stuck waiting for the
original condition thread, which will now never complete.

In this commit I propose a solution to this problem.  A timeout.  For
targets that support async-mode we can install an event-loop timer
before starting the inferior function call.  When the timer expires we
will stop the thread performing the inferior function call.  With this
mechanism in place a user can be sure that any inferior call they make
will either complete, or timeout eventually.

Adding a timer like this is obviously a change in behaviour for the
more common 'call' and 'print' uses of inferior function calls, so, in
this patch, I propose having two different timers.  One I call the
'direct-call-timeout', which is used for 'call' and 'print' commands.
This timeout is by default set to unlimited, which, not surprisingly,
means there is no timeout in place.

A second timer, which I've called 'indirect-call-timeout', is used for
inferior function calls from breakpoint conditions.  This timeout has
a default value of 30 seconds.  This is a reasonably long time to
wait, and hopefully should be enough in most cases to allow the
inferior call to complete.  An inferior call that takes more than 30
seconds, which is installed on a breakpoint condition is really going
to slow down the debug session, so hopefully this is not a common use
case.

The user is, of course, free to reduce, or increase the timeout value,
and can always use Ctrl-c to interrupt an inferior function call, but
this timeout will ensure that GDB will stop at some point.

The new commands added by this commit are:

  set direct-call-timeout SECONDS
  show direct-call-timeout
  set indirect-call-timeout SECONDS
  show indirect-call-timeout

These new timeouts do depend on async-mode, so, if async-mode is
disabled (maint set target-async off), or not supported (e.g. target
sim), then the timeout is treated as unlimited (that is, no timeout is
set).

For targets that "fake" non-async mode, e.g. Linux native, where
non-async mode is really just async mode, but then we park the target
in a sissuspend, we could easily fix things so that the timeouts still
work, however, for targets that really are not async aware, like the
simulator, fixing things so that timeouts work correctly would be a
much bigger task - that effort would be better spent just making the
target async-aware.  And so, I'm happy for now that this feature will
only work on async targets.

The two new show commands will display slightly different text if the
current target is a non-async target, which should allow users to
understand what's going on.

There's a somewhat random test adjustment needed in gdb.base/help.exp,
the test uses a regexp with the apropos command, and expects to find a
single result.  Turns out the new settings I added also matched the
regexp, which broke the test.  I've updated the regexp a little to
exclude my new settings.

Reviewed-By: Tankut Baris Aktemur <tankut.baris.aktemur@intel.com>
Reviewed-By: Eli Zaretskii <eliz@gnu.org>
---
 gdb/NEWS                                      |  18 ++
 gdb/doc/gdb.texinfo                           |  66 ++++++
 gdb/infcall.c                                 | 210 +++++++++++++++++-
 gdb/testsuite/gdb.base/help.exp               |   2 +-
 gdb/testsuite/gdb.base/infcall-timeout.c      |  36 +++
 gdb/testsuite/gdb.base/infcall-timeout.exp    |  94 ++++++++
 .../infcall-from-bp-cond-timeout.c            | 169 ++++++++++++++
 .../infcall-from-bp-cond-timeout.exp          | 166 ++++++++++++++
 8 files changed, 756 insertions(+), 5 deletions(-)
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.c
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp

diff --git a/gdb/NEWS b/gdb/NEWS
index 1073e38dfc6..3500acd42b6 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -38,6 +38,24 @@ set remote thread-options-packet
 show remote thread-options-packet
   Set/show the use of the thread options packet.
 
+set direct-call-timeout SECONDS
+show direct-call-timeout
+set indirect-call-timeout SECONDS
+show indirect-call-timeout
+  These new settings can be used to limit how long GDB will wait for
+  an inferior function call to complete.  The direct timeout is used
+  for inferior function calls from e.g. 'call' and 'print' commands,
+  while the indirect timeout is used for inferior function calls from
+  within a conditional breakpoint expression.
+
+  The default for the direct timeout is unlimited, while the default
+  for the indirect timeout is 30 seconds.
+
+  These timeouts will only have an effect for targets that are
+  operating in async mode.  For non-async targets the timeouts are
+  ignored, GDB will wait indefinitely for an inferior function to
+  complete, unless interrupted by the user using Ctrl-C.
+
 * Python API
 
   ** New function gdb.notify_mi(NAME, DATA), that emits custom
diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index e4c00143fd1..5725aeb0713 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -20997,6 +20997,72 @@
 @code{step}, etc).  In this case, when the inferior finally returns to
 the dummy-frame, @value{GDBN} will once again halt the inferior.
 
+On targets that support asynchronous execution (@pxref{Background
+Execution}) @value{GDBN} can place a timeout on any functions called
+from @value{GDBN}.  If the timeout expires and the function call is
+still ongoing, then @value{GDBN} will interrupt the program.
+
+For targets that don't support asynchronous execution
+(@pxref{Background Execution}) then timeouts for functions called from
+@value{GDBN} are not supported, the timeout settings described below
+will be treated as @code{unlimited}, meaning @value{GDBN} will wait
+indefinitely for function call to complete, unless interrupted by the
+user using @kbd{Ctrl-C}.
+
+@table @code
+@item set direct-call-timeout @var{seconds}
+@kindex set direct-call-timeout
+@cindex timeout for called functions
+Set the timeout used when calling functions in the program to
+@var{seconds}, which should be an integer greater than zero, or the
+special value @code{unlimited}, which indicates no timeout should be
+used.  The default for this setting is @code{unlimited}.
+
+This setting is used when the user calls a function directly from the
+command prompt, for example with a @code{call} or @code{print}
+command.
+
+This setting only works for targets that support asynchronous
+execution (@pxref{Background Execution}), for any other target the
+setting is treated as @code{unlimited}.
+
+@item show direct-call-timeout
+@kindex show direct-call-timeout
+@cindex timeout for called functions
+Show the timeout used when calling functions in the program with a
+@code{call} or @code{print} command.
+@end table
+
+It is also possible to call functions within the program from the
+condition of a conditional breakpoint (@pxref{Conditions, ,Break
+Conditions}).  A different setting controls the timeout used for
+function calls made from a breakpoint condition.
+
+@table @code
+@item set indirect-call-timeout @var{seconds}
+@kindex set indirect-call-timeout
+@cindex timeout for called functions
+Set the timeout used when calling functions in the program from a
+breakpoint or watchpoint condition to @var{seconds}, which should be
+an integer greater than zero, or the special value @code{unlimited},
+which indicates no timeout should be used.  The default for this
+setting is @code{30} seconds.
+
+This setting only works for targets that support asynchronous
+execution (@pxref{Background Execution}), for any other target the
+setting is treated as @code{unlimited}.
+
+If a function called from a breakpoint or watchpoint condition times
+out, then @value{GDBN} will stop at the point where the timeout
+occurred.  The breakpoint condition evaluation will be abandoned.
+
+@item show indirect-call-timeout
+@kindex show indirect-call-timeout
+@cindex timeout for called functions
+Show the timeout used when calling functions in the program from a
+breakpoint or watchpoint condition.
+@end table
+
 @subsection Calling functions with no debug info
 
 @cindex no debug info functions
diff --git a/gdb/infcall.c b/gdb/infcall.c
index 935a555e817..a295b1e7090 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -96,6 +96,53 @@ show_may_call_functions_p (struct ui_file *file, int from_tty,
 	      value);
 }
 
+/* A timeout (in seconds) for direct inferior calls.  A direct inferior
+   call is one the user triggers from the prompt, e.g. with a 'call' or
+   'print' command.  Compare with the definition of indirect calls below.  */
+
+static unsigned int direct_call_timeout = UINT_MAX;
+
+/* Implement 'show direct-call-timeout'.  */
+
+static void
+show_direct_call_timeout (struct ui_file *file, int from_tty,
+			  struct cmd_list_element *c, const char *value)
+{
+  if (target_has_execution () && !target_can_async_p ())
+    gdb_printf (file, _("Current target does not support async mode, timeout "
+			"for direct inferior calls is \"unlimited\".\n"));
+  else if (direct_call_timeout == UINT_MAX)
+    gdb_printf (file, _("Timeout for direct inferior function calls "
+			"is \"unlimited\".\n"));
+  else
+    gdb_printf (file, _("Timeout for direct inferior function calls "
+			"is \"%s seconds\".\n"), value);
+}
+
+/* A timeout (in seconds) for indirect inferior calls.  An indirect inferior
+   call is one that originates from within GDB, for example, when
+   evaluating an expression for a conditional breakpoint.  Compare with
+   the definition of direct calls above.  */
+
+static unsigned int indirect_call_timeout = 30;
+
+/* Implement 'show indirect-call-timeout'.  */
+
+static void
+show_indirect_call_timeout (struct ui_file *file, int from_tty,
+			  struct cmd_list_element *c, const char *value)
+{
+  if (target_has_execution () && !target_can_async_p ())
+    gdb_printf (file, _("Current target does not support async mode, timeout "
+			"for indirect inferior calls is \"unlimited\".\n"));
+  else if (indirect_call_timeout == UINT_MAX)
+    gdb_printf (file, _("Timeout for indirect inferior function calls "
+			"is \"unlimited\".\n"));
+  else
+    gdb_printf (file, _("Timeout for indirect inferior function calls "
+			"is \"%s seconds\".\n"), value);
+}
+
 /* How you should pass arguments to a function depends on whether it
    was defined in K&R style or prototype style.  If you define a
    function using the K&R syntax that takes a `float' argument, then
@@ -620,6 +667,85 @@ call_thread_fsm::should_notify_stop ()
   return true;
 }
 
+/* A class to control creation of a timer that will interrupt a thread
+   during an inferior call.  */
+struct infcall_timer_controller
+{
+  /* Setup an event-loop timer that will interrupt PTID if the inferior
+     call takes too long.  DIRECT_CALL_P is true when this inferior call is
+     a result of the user using a 'print' or 'call' command, and false when
+     this inferior call is a result of e.g. a conditional breakpoint
+     expression, this is used to select which timeout to use.  */
+  infcall_timer_controller (thread_info *thr, bool direct_call_p)
+    : m_thread (thr)
+  {
+    unsigned int timeout
+      = direct_call_p ? direct_call_timeout : indirect_call_timeout;
+    if (timeout < UINT_MAX && target_can_async_p ())
+      {
+	int ms = timeout * 1000;
+	int id = create_timer (ms, infcall_timer_controller::timed_out, this);
+	m_timer_id.emplace (id);
+	infcall_debug_printf ("Setting up infcall timeout timer for "
+			      "ptid %s: %d milliseconds",
+			      m_thread->ptid.to_string ().c_str (), ms);
+      }
+  }
+
+  /* Destructor.  Ensure that the timer is removed from the event loop.  */
+  ~infcall_timer_controller ()
+  {
+    /* If the timer has already triggered, then it will have already been
+       deleted from the event loop.  If the timer has not triggered, then
+       delete it now.  */
+    if (m_timer_id.has_value () && !m_triggered)
+      delete_timer (*m_timer_id);
+
+    /* Just for clarity, discard the timer id now.  */
+    m_timer_id.reset ();
+  }
+
+  /* Return true if there was a timer in place, and the timer triggered,
+     otherwise, return false.  */
+  bool triggered_p ()
+  {
+    gdb_assert (!m_triggered || m_timer_id.has_value ());
+    return m_triggered;
+  }
+
+private:
+  /* The thread we should interrupt.  */
+  thread_info *m_thread;
+
+  /* Set true when the timer is triggered.  */
+  bool m_triggered = false;
+
+  /* Given a value when a timer is in place.  */
+  std::optional<int> m_timer_id;
+
+  /* Callback for the timer, forwards to ::trigger below.  */
+  static void
+  timed_out (gdb_client_data context)
+  {
+    infcall_timer_controller *ctrl
+      = static_cast<infcall_timer_controller *> (context);
+    ctrl->trigger ();
+  }
+
+  /* Called when the timer goes off.  Stop thread M_THREAD.  */
+  void
+  trigger ()
+  {
+    m_triggered = true;
+
+    scoped_disable_commit_resumed disable_commit_resumed ("infcall timeout");
+
+    infcall_debug_printf ("Stopping thread %s",
+			  m_thread->ptid.to_string ().c_str ());
+    target_stop (m_thread->ptid);
+  }
+};
+
 /* Subroutine of call_function_by_hand to simplify it.
    Start up the inferior and wait for it to stop.
    Return the exception if there's an error, or an exception with
@@ -630,13 +756,15 @@ call_thread_fsm::should_notify_stop ()
 
 static struct gdb_exception
 run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
-		   struct thread_info *call_thread, CORE_ADDR real_pc)
+		   struct thread_info *call_thread, CORE_ADDR real_pc,
+		   bool *timed_out_p)
 {
   INFCALL_SCOPED_DEBUG_ENTER_EXIT;
 
   struct gdb_exception caught_error;
   ptid_t call_thread_ptid = call_thread->ptid;
   int was_running = call_thread->state == THREAD_RUNNING;
+  *timed_out_p = false;
 
   infcall_debug_printf ("call function at %s in thread %s, was_running = %d",
 			core_addr_to_string (real_pc),
@@ -681,11 +809,23 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
       infrun_debug_show_threads ("non-exited threads after proceed for inferior-call",
 				 all_non_exited_threads ());
 
+      /* Setup a timer (if possible, and if the settings allow) to prevent
+	 the inferior call running forever.  */
+      bool direct_call_p = !call_thread->control.in_cond_eval;
+      infcall_timer_controller infcall_timer (call_thread, direct_call_p);
+
       /* Inferior function calls are always synchronous, even if the
 	 target supports asynchronous execution.  */
       wait_sync_command_done ();
 
-      infcall_debug_printf ("inferior call completed successfully");
+      /* If the timer triggered then the inferior call failed.  */
+      if (infcall_timer.triggered_p ())
+	{
+	  infcall_debug_printf ("inferior call timed out");
+	  *timed_out_p = true;
+	}
+      else
+	infcall_debug_printf ("inferior call completed successfully");
     }
   catch (gdb_exception &e)
     {
@@ -1358,6 +1498,10 @@ call_function_by_hand_dummy (struct value *function,
   scoped_restore restore_stopped_by_random_signal
     = make_scoped_restore (&stopped_by_random_signal, 0);
 
+  /* Set to true by the call to run_inferior_call below if the inferior
+     call is artificially interrupted by GDB due to taking too long.  */
+  bool timed_out_p = false;
+
   /* - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP -
      If you're looking to implement asynchronous dummy-frames, then
      just below is the place to chop this function in two..  */
@@ -1384,7 +1528,8 @@ call_function_by_hand_dummy (struct value *function,
 			      struct_addr);
     {
       std::unique_ptr<call_thread_fsm> sm_up (sm);
-      e = run_inferior_call (std::move (sm_up), call_thread.get (), real_pc);
+      e = run_inferior_call (std::move (sm_up), call_thread.get (), real_pc,
+			     &timed_out_p);
     }
 
     if (e.reason < 0)
@@ -1543,7 +1688,10 @@ When the function is done executing, GDB will silently stop."),
       std::string name = get_function_name (funaddr, name_buf,
 					    sizeof (name_buf));
 
-      if (stopped_by_random_signal)
+      /* If the inferior call timed out then it will have been interrupted
+	 by a signal, but we want to report this differently to the user,
+	 which is done later in this function.  */
+      if (stopped_by_random_signal && !timed_out_p)
 	{
 	  /* We stopped inside the FUNCTION because of a random
 	     signal.  Further execution of the FUNCTION is not
@@ -1594,6 +1742,36 @@ GDB remains in the frame where the signal was received.\n\
 To change this behavior use \"set unwindonsignal on\".\n\
 Evaluation of the expression containing the function\n\
 (%s) will be abandoned.\n\
+When the function is done executing, GDB will silently stop."),
+		     name.c_str ());
+	    }
+	}
+
+      if (timed_out_p)
+	{
+	  /* A timeout results in a signal being sent to the inferior.  */
+	  gdb_assert (stopped_by_random_signal);
+
+	  /* Indentation is weird here.  A later patch is going to move the
+	    following block into an if/else, so I'm leaving the indentation
+	    here to minimise the later patch.
+
+	    Also, the error message used below refers to 'set
+	    unwind-on-timeout' which doesn't exist yet.  This will be added
+	    in a later commit, I'm leaving this in for now to minimise the
+	    churn caused by the commit that adds unwind-on-timeout.  */
+	    {
+	      /* The user wants to stay in the frame where we stopped
+		 (default).  Discard inferior status, we're not at the same
+		 point we started at.  */
+	      discard_infcall_control_state (inf_status.release ());
+
+	      error (_("\
+The program being debugged timed out while in a function called from GDB.\n\
+GDB remains in the frame where the timeout occurred.\n\
+To change this behavior use \"set unwind-on-timeout on\".\n\
+Evaluation of the expression containing the function\n\
+(%s) will be abandoned.\n\
 When the function is done executing, GDB will silently stop."),
 		     name.c_str ());
 	    }
@@ -1707,6 +1885,30 @@ The default is to unwind the frame."),
 			   show_unwind_on_terminating_exception_p,
 			   &setlist, &showlist);
 
+  add_setshow_uinteger_cmd ("direct-call-timeout", no_class,
+			    &direct_call_timeout, _("\
+Set the timeout, for direct calls to inferior function calls."), _("\
+Show the timeout, for direct calls to inferior function calls."), _("\
+If running on a target that supports, and is running in, async mode\n\
+then this timeout is used for any inferior function calls triggered\n\
+directly from the prompt, i.e. from a 'call' or 'print' command.  The\n\
+timeout is specified in seconds."),
+			    nullptr,
+			    show_direct_call_timeout,
+			    &setlist, &showlist);
+
+  add_setshow_uinteger_cmd ("indirect-call-timeout", no_class,
+			    &indirect_call_timeout, _("\
+Set the timeout, for indirect calls to inferior function calls."), _("\
+Show the timeout, for indirect calls to inferior function calls."), _("\
+If running on a target that supports, and is running in, async mode\n\
+then this timeout is used for any inferior function calls triggered\n\
+indirectly, i.e. being made as part of a breakpoint, or watchpoint,\n\
+condition expression.  The timeout is specified in seconds."),
+			    nullptr,
+			    show_indirect_call_timeout,
+			    &setlist, &showlist);
+
   add_setshow_boolean_cmd
     ("infcall", class_maintenance, &debug_infcall,
      _("Set inferior call debugging."),
diff --git a/gdb/testsuite/gdb.base/help.exp b/gdb/testsuite/gdb.base/help.exp
index 87919a819ab..504bf90cc15 100644
--- a/gdb/testsuite/gdb.base/help.exp
+++ b/gdb/testsuite/gdb.base/help.exp
@@ -121,7 +121,7 @@ gdb_test "help info bogus-gdb-command" "Undefined info command: \"bogus-gdb-comm
 gdb_test "help gotcha" "Undefined command: \"gotcha\"\.  Try \"help\"\."
 
 # Test apropos regex.
-gdb_test "apropos \\\(print\[\^\[ bsiedf\\\".-\]\\\)" "handle -- Specify how to handle signals\."
+gdb_test "apropos \\\(print\[\^\[ bsiedf\\\"'.-\]\\\)" "handle -- Specify how to handle signals\."
 # Test apropos >1 word string.
 gdb_test "apropos handle signal" "handle -- Specify how to handle signals\."
 # Test apropos apropos.
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.c b/gdb/testsuite/gdb.base/infcall-timeout.c
new file mode 100644
index 00000000000..12774ca2599
--- /dev/null
+++ b/gdb/testsuite/gdb.base/infcall-timeout.c
@@ -0,0 +1,36 @@
+/* Copyright 2022-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 <unistd.h>
+
+/* This function is called from GDB.  */
+int
+function_that_never_returns ()
+{
+  while (1)
+    sleep (1);
+
+  return 0;
+}
+
+int
+main ()
+{
+  alarm (300);
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.exp b/gdb/testsuite/gdb.base/infcall-timeout.exp
new file mode 100644
index 00000000000..c6bf8f8ec2d
--- /dev/null
+++ b/gdb/testsuite/gdb.base/infcall-timeout.exp
@@ -0,0 +1,94 @@
+# Copyright 2022-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/>.
+
+# Test GDB's direct-call-timeout setting, that is, ensure that if an
+# inferior function call, invoked from e.g. a 'print' command, takes
+# too long, then GDB can interrupt it, and return control to the user.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug}] == -1 } {
+    return
+}
+
+# Start GDB according to TARGET_ASYNC, TARGET_NON_STOP, and NON_STOP,
+# then adjust the direct-call-timeout, and make an inferior function
+# call that will never return.  GDB should eventually timeout and stop
+# the inferior.
+proc run_test { target_async target_non_stop non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"set non-stop $non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if {![runto_main]} {
+	return
+    }
+
+    gdb_test_no_output "set direct-call-timeout 5"
+
+    # When non-stop mode is off we get slightly different output from GDB.
+    if { ([target_info gdb_protocol] == "remote"
+	  || [target_info gdb_protocol] == "extended-remote")
+	 && !$target_non_stop } {
+	set stopped_line_pattern "Program received signal SIGINT, Interrupt\\."
+    } else {
+	set stopped_line_pattern "Program stopped\\."
+    }
+
+    gdb_test "print function_that_never_returns ()" \
+	[multi_line \
+	     $stopped_line_pattern \
+	     ".*" \
+	     "The program being debugged timed out while in a function called from GDB\\." \
+	     "GDB remains in the frame where the timeout occurred\\." \
+	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(function_that_never_returns\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+
+    gdb_test "bt" ".* function_that_never_returns .*<function called from gdb>.*"
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+
+    if { !$target_async } {
+	# GDB can't timeout while waiting for a thread if the target
+	# runs with async-mode turned off; once the target is running
+	# GDB is effectively blocked until the target stops for some
+	# reason.
+	continue
+    }
+
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	foreach_with_prefix non_stop { "on" "off" } {
+	    if { $non_stop && !$target_non_stop } {
+		# It doesn't make sense to operate GDB in non-stop
+		# mode when the target has (in theory) non-stop mode
+		# disabled.
+		continue
+	    }
+
+	    run_test $target_async $target_non_stop $non_stop
+	}
+    }
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
new file mode 100644
index 00000000000..4da4245746e
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
@@ -0,0 +1,169 @@
+/* This testcase is part of GDB, the GNU debugger.
+
+   Copyright 2022-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 <stdio.h>
+#include <pthread.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <semaphore.h>
+
+#define NUM_THREADS 5
+
+/* Semaphores, used to track when threads have started, and to control
+   when the threads finish.  */
+sem_t startup_semaphore;
+sem_t finish_semaphore;
+sem_t thread_1_semaphore;
+sem_t thread_2_semaphore;
+
+/* Mutex to control when the first worker thread hit a breakpoint
+   location.  */
+pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+
+/* Global variable to poke, just so threads have something to do.  */
+volatile int global_var = 0;
+
+int
+condition_func ()
+{
+  /* Let thread 2 run.  */
+  if (sem_post (&thread_2_semaphore) != 0)
+    abort ();
+
+  /* Wait for thread 2 to complete its actions.  */
+  if (sem_wait (&thread_1_semaphore) != 0)
+    abort ();
+
+  return 1;
+}
+
+void
+do_segfault ()
+{
+  volatile int *p = 0;
+  *p = 0;	/* Segfault here.  */
+}
+
+void *
+worker_func (void *arg)
+{
+  int tid = *((int *) arg);
+
+  /* Let the main thread know that this worker has started.  */
+  if (sem_post (&startup_semaphore) != 0)
+    abort ();
+
+  switch (tid)
+    {
+    case 0:
+      /* Wait for MUTEX to become available, then pass through the
+	 conditional breakpoint location.  */
+      if (pthread_mutex_lock (&mutex) != 0)
+	abort ();
+      global_var = 99;	/* Conditional breakpoint here.  */
+      if (pthread_mutex_unlock (&mutex) != 0)
+	abort ();
+      break;
+
+    case 1:
+      if (sem_wait (&thread_2_semaphore) != 0)
+	abort ();
+      do_segfault ();
+      if (sem_post (&thread_1_semaphore) != 0)
+	abort ();
+
+      /* Fall through.  */
+    default:
+      /* Wait until we are allowed to finish.  */
+      if (sem_wait (&finish_semaphore) != 0)
+	abort ();
+      break;
+    }
+}
+
+void
+stop_marker ()
+{
+  global_var = 99;	/* Stop marker.  */
+}
+
+/* The main program entry point.  */
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+  void *retval;
+
+  /* An alarm, just in case the thread deadlocks.  */
+  alarm (300);
+
+  /* Semaphore initialization.  */
+  if (sem_init (&startup_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&finish_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&thread_1_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&thread_2_semaphore, 0, 0) != 0)
+    abort ();
+
+  /* Lock MUTEX, this prevents the first worker thread from rushing ahead.  */
+  if (pthread_mutex_lock (&mutex) != 0)
+    abort ();
+
+  /* Worker thread creation.  */
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  /* Wait for every thread to start.  */
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      if (sem_wait (&startup_semaphore) != 0)
+	abort ();
+    }
+
+  /* Unlock the first thread so it can proceed.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  /* Wait for the first thread only.  */
+  pthread_join (threads[0], &retval);
+
+  /* Now post FINISH_SEMAPHORE to allow all the other threads to finish.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    sem_post (&finish_semaphore);
+
+  /* Now wait for the remaining threads to complete.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    pthread_join (threads[i], &retval);
+
+  /* Semaphore cleanup.  */
+  sem_destroy (&finish_semaphore);
+  sem_destroy (&startup_semaphore);
+  sem_destroy (&thread_1_semaphore);
+  sem_destroy (&thread_2_semaphore);
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
new file mode 100644
index 00000000000..7bb6b4db813
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
@@ -0,0 +1,166 @@
+# Copyright 2022-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 inferior calls executed from a breakpoint condition in
+# a multi-threaded program.
+#
+# This test has the inferior function call timeout, and checks how GDB
+# handles this situation.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "Conditional breakpoint here"]
+set final_bp_line [gdb_get_line_number "Stop marker"]
+set segfault_line [gdb_get_line_number "Segfault here"]
+
+# Setup GDB based on TARGET_ASYNC, TARGET_NON_STOP, and NON_STOP.
+# Setup some breakpoints in the inferior, one of which has an inferior
+# call within its condition.
+#
+# Continue GDB, the breakpoint with inferior call will be hit, but the
+# inferior call will never return.  We expect GDB to timeout.
+#
+# The reason that the inferior call never completes is that a second
+# thread, on which the inferior call relies, either hits a breakpoint
+# (when OTHER_THREAD_BP is true), or crashes (when OTHER_THREAD_BP is
+# false).
+proc run_test { target_async target_non_stop non_stop other_thread_bp } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS " -ex \"maint non-stop $non_stop\""
+	append ::GDBFLAGS " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if {![runto_main]} {
+	return
+    }
+
+    # The default timeout for indirect inferior calls (e.g. inferior
+    # calls for conditional breakpoint expressions) is pretty high.
+    # We don't want the test to take too long, so reduce this.
+    #
+    # However, the test relies on a second thread hitting some event
+    # (either a breakpoint or signal) before this timeout expires.
+    #
+    # There is a chance that on a really slow system this might not
+    # happen, in which case the test might fail.
+    #
+    # However, we still allocate 5 seconds, which feels like it should
+    # be enough time in most cases, but maybe we need to do something
+    # smarter here?  Possibly we could have some initial run where the
+    # inferior doesn't timeout, but does perform the same interaction
+    # between threads, we could time that, and use that as the basis
+    # for this timeout.  For now though, we just hope 5 seconds is
+    # enough.
+    gdb_test_no_output "set indirect-call-timeout 5"
+
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (condition_func ())"
+    set bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		    "get number for conditional breakpoint"]
+
+    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
+    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			  "get number for final breakpoint"]
+
+    # The thread performing an inferior call relies on a second
+    # thread.  The second thread will segfault unless it hits a
+    # breakpoint first.  In either case the initial thread will not
+    # complete its inferior call.
+    if { $other_thread_bp } {
+	gdb_breakpoint "${::srcfile}:${::segfault_line}"
+	set segfault_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+				 "get number for segfault breakpoint"]
+    }
+
+    # When non-stop mode is off we get slightly different output from GDB.
+    if { ([target_info gdb_protocol] == "remote"
+	  || [target_info gdb_protocol] == "extended-remote")
+	 && !$target_non_stop} {
+	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" received signal SIGINT, Interrupt\\."
+    } else {
+	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\."
+    }
+
+    gdb_test "continue" \
+	[multi_line \
+	     $stopped_line_pattern \
+	     ".*" \
+	     "Error in testing condition for breakpoint ${bp_num}:" \
+	     "The program being debugged timed out while in a function called from GDB\\." \
+	     "GDB remains in the frame where the timeout occurred\\." \
+	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(condition_func\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."] \
+	"expected timeout waiting for inferior call to complete"
+
+    # Remember that other thread that either crashed (with a segfault)
+    # or hit a breakpoint?  Now that the inferior call has timed out,
+    # if we try to resume then we should see the pending event from
+    # that other thread.
+    if { $other_thread_bp } {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${segfault_bp_num}, do_segfault \[^\r\n\]+:${::segfault_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"] \
+	    "hit the segfault breakpoint"
+    } else {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "Thread ${::decimal} \"infcall-from-bp\" received signal SIGSEGV, Segmentation fault\\." \
+		 "\\\[Switching to Thread \[^\r\n\]+\\\]" \
+		 "${::hex} in do_segfault \\(\\) at \[^\r\n\]+:${::segfault_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"] \
+	    "hit the segfault"
+    }
+}
+
+foreach_with_prefix target_async {"on" "off" } {
+
+    if { !$target_async } {
+	# GDB can't timeout while waiting for a thread if the target
+	# runs with async-mode turned off; once the target is running
+	# GDB is effectively blocked until the target stops for some
+	# reason.
+	continue
+    }
+
+    foreach_with_prefix target_non_stop {"off" "on"} {
+	foreach_with_prefix non_stop {"off" "on"} {
+	    if { $non_stop && !$target_non_stop } {
+		# It doesn't make sense to operate GDB in non-stop
+		# mode when the target has (in theory) non-stop mode
+		# disabled.
+		continue
+	    }
+	    foreach_with_prefix other_thread_bp { true false } {
+		run_test $target_async $target_non_stop $non_stop $other_thread_bp
+	    }
+	}
+    }
+}
-- 
2.25.4


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

* [PATCHv9 4/5] gdb: introduce unwind-on-timeout setting
  2023-12-02 10:52               ` [PATCHv9 0/5] " Andrew Burgess
                                   ` (2 preceding siblings ...)
  2023-12-02 10:52                 ` [PATCHv9 3/5] gdb: add timeouts for inferior function calls Andrew Burgess
@ 2023-12-02 10:52                 ` Andrew Burgess
  2023-12-02 10:52                 ` [PATCHv9 5/5] gdb: rename unwindonsignal to unwind-on-signal Andrew Burgess
  2024-01-02 15:57                 ` [PATCHv10 0/5] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
  5 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-12-02 10:52 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Eli Zaretskii

Eli has already approved the NEWS/doc changes in this file.

---

Now that inferior function calls can timeout (see the recent
introduction of direct-call-timeout and indirect-call-timeout), this
commit adds a new setting unwind-on-timeout.

This new setting is just like the existing unwindonsignal and
unwind-on-terminating-exception, but the new setting will cause GDB to
unwind the stack if an inferior function call times out.

The existing inferior function call timeout tests have been updated to
cover the new setting.

Reviewed-By: Eli Zaretskii <eliz@gnu.org>
---
 gdb/NEWS                                      |  9 +++
 gdb/doc/gdb.texinfo                           | 31 ++++++--
 gdb/infcall.c                                 | 78 +++++++++++++++++--
 gdb/testsuite/gdb.base/infcall-timeout.exp    | 63 ++++++++++-----
 .../infcall-from-bp-cond-timeout.exp          | 69 ++++++++++------
 5 files changed, 194 insertions(+), 56 deletions(-)

diff --git a/gdb/NEWS b/gdb/NEWS
index 3500acd42b6..b5ac1b848d6 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -56,6 +56,15 @@ show indirect-call-timeout
   ignored, GDB will wait indefinitely for an inferior function to
   complete, unless interrupted by the user using Ctrl-C.
 
+set unwind-on-timeout on|off
+show unwind-on-timeout
+  These commands control whether GDB should unwind the stack when a
+  timeout occurs during an inferior function call.  The default is
+  off, in which case the inferior will remain in the frame where the
+  timeout occurred.  When on, GDB will unwind the stack removing the
+  dummy frame that was added for the inferior call, and restoring the
+  inferior state to how it was before the inferior call started.
+
 * Python API
 
   ** New function gdb.notify_mi(NAME, DATA), that emits custom
diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index 5725aeb0713..9ba9e898977 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -20942,6 +20942,22 @@
 Show the current setting of stack unwinding in the functions called by
 @value{GDBN}.
 
+@anchor{set unwind-on-timeout}
+@item set unwind-on-timeout
+@kindex set unwind-on-timeout
+@cindex unwind stack in called functions when timing out
+@cindex call dummy stack unwinding on timeout.
+Set unwinding of the stack if a function called from @value{GDBN}
+times out.  If set to @code{off} (the default), @value{GDBN} stops in
+the frame where the timeout occurred.  If set to @code{on},
+@value{GDBN} unwinds the stack it created for the call and restores
+the context to what it was before the call.
+
+@item show unwind-on-timeout
+@kindex show unwind-on-timeout
+Show whether @value{GDBN} will unwind the stack if a function called
+from @value{GDBN} times out.
+
 @item set may-call-functions
 @kindex set may-call-functions
 @cindex disabling calling functions in the program
@@ -20973,11 +20989,11 @@
 
 If a called function is interrupted for any reason, including hitting
 a breakpoint, or triggering a watchpoint, and the stack is not unwound
-due to @code{set unwind-on-terminating-exception on} or @code{set
-unwindonsignal on} (@pxref{stack unwind settings}),
-then the dummy-frame, created by @value{GDBN} to facilitate the call
-to the program function, will be visible in the backtrace, for example
-frame @code{#3} in the following backtrace:
+due to @code{set unwind-on-terminating-exception on}, @code{set
+unwind-on-timeout on}, or @code{set unwindonsignal on} (@pxref{stack
+unwind settings}), then the dummy-frame, created by @value{GDBN} to
+facilitate the call to the program function, will be visible in the
+backtrace, for example frame @code{#3} in the following backtrace:
 
 @smallexample
 (@value{GDBP}) backtrace
@@ -21002,6 +21018,11 @@
 from @value{GDBN}.  If the timeout expires and the function call is
 still ongoing, then @value{GDBN} will interrupt the program.
 
+If a function called from @value{GDBN} is interrupted by a timeout,
+then by default the inferior is left in the frame where the timeout
+occurred, this behaviour can be adjusted with @samp{set
+unwind-on-timeout} (@pxref{set unwind-on-timeout}).
+
 For targets that don't support asynchronous execution
 (@pxref{Background Execution}) then timeouts for functions called from
 @value{GDBN} are not supported, the timeout settings described below
diff --git a/gdb/infcall.c b/gdb/infcall.c
index a295b1e7090..84c6bf2cdd2 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -218,6 +218,27 @@ show_unwind_on_terminating_exception_p (struct ui_file *file, int from_tty,
 	      value);
 }
 
+/* This boolean tells GDB what to do if an inferior function, called from
+   GDB, times out.  If true, GDB unwinds the stack and restores the context
+   to what it was before the call.  When false, GDB leaves the thread as it
+   is at the point of the timeout.
+
+   The default is to stop in the frame where the timeout occurred.  */
+
+static bool unwind_on_timeout_p = false;
+
+/* Implement 'show unwind-on-timeout'.  */
+
+static void
+show_unwind_on_timeout_p (struct ui_file *file, int from_tty,
+			  struct cmd_list_element *c, const char *value)
+{
+  gdb_printf (file,
+	      _("Unwinding of stack if a timeout occurs "
+		"while in a call dummy is %s.\n"),
+	      value);
+}
+
 /* Perform the standard coercions that are specified
    for arguments to be passed to C, Ada or Fortran functions.
 
@@ -574,6 +595,16 @@ struct call_thread_fsm : public thread_fsm
   bool should_stop (struct thread_info *thread) override;
 
   bool should_notify_stop () override;
+
+  /* Record that this thread timed out while performing an infcall.  */
+  void timed_out ()
+  {
+    m_timed_out = true;
+  }
+
+private:
+  /* Set true if the thread timed out while performing an infcall.  */
+  bool m_timed_out = false;
 };
 
 /* Allocate a new call_thread_fsm object.  */
@@ -649,7 +680,8 @@ call_thread_fsm::should_notify_stop ()
 
   infcall_debug_printf ("inferior call didn't complete fully");
 
-  if (stopped_by_random_signal && unwind_on_signal_p)
+  if ((stopped_by_random_signal && unwind_on_signal_p)
+      || (m_timed_out && unwind_on_timeout_p))
     {
       infcall_debug_printf ("unwind-on-signal is on, don't notify");
       return false;
@@ -742,6 +774,9 @@ struct infcall_timer_controller
 
     infcall_debug_printf ("Stopping thread %s",
 			  m_thread->ptid.to_string ().c_str ());
+    call_thread_fsm *fsm
+      = gdb::checked_static_cast<call_thread_fsm *> (m_thread->thread_fsm ());
+    fsm->timed_out ();
     target_stop (m_thread->ptid);
   }
 };
@@ -1752,14 +1787,27 @@ When the function is done executing, GDB will silently stop."),
 	  /* A timeout results in a signal being sent to the inferior.  */
 	  gdb_assert (stopped_by_random_signal);
 
-	  /* Indentation is weird here.  A later patch is going to move the
-	    following block into an if/else, so I'm leaving the indentation
-	    here to minimise the later patch.
+	  if (unwind_on_timeout_p)
+	    {
+	      /* The user wants the context restored.  */
+
+	      /* We must get back to the frame we were before the
+		 dummy call.  */
+	      dummy_frame_pop (dummy_id, call_thread.get ());
 
-	    Also, the error message used below refers to 'set
-	    unwind-on-timeout' which doesn't exist yet.  This will be added
-	    in a later commit, I'm leaving this in for now to minimise the
-	    churn caused by the commit that adds unwind-on-timeout.  */
+	      /* We also need to restore inferior status to that before the
+		 dummy call.  */
+	      restore_infcall_control_state (inf_status.release ());
+
+	      error (_("\
+The program being debugged timed out while in a function called from GDB.\n\
+GDB has restored the context to what it was before the call.\n\
+To change this behavior use \"set unwind-on-timeout off\".\n\
+Evaluation of the expression containing the function\n\
+(%s) will be abandoned."),
+		     name.c_str ());
+	    }
+	  else
 	    {
 	      /* The user wants to stay in the frame where we stopped
 		 (default).  Discard inferior status, we're not at the same
@@ -1885,6 +1933,20 @@ The default is to unwind the frame."),
 			   show_unwind_on_terminating_exception_p,
 			   &setlist, &showlist);
 
+  add_setshow_boolean_cmd ("unwind-on-timeout", no_class,
+			   &unwind_on_timeout_p, _("\
+Set unwinding of stack if a timeout occurs while in a call dummy."), _("\
+Show unwinding of stack if a timeout occurs while in a call dummy."),
+			   _("\
+The unwind on timeout flag lets the user determine what gdb should do if\n\
+gdb times out while in a function called from gdb.  If set, gdb unwinds\n\
+the stack and restores the context to what it was before the call.  If\n\
+unset, gdb leaves the inferior in the frame where the timeout occurred.\n\
+The default is to stop in the frame where the timeout occurred."),
+			   NULL,
+			   show_unwind_on_timeout_p,
+			   &setlist, &showlist);
+
   add_setshow_uinteger_cmd ("direct-call-timeout", no_class,
 			    &direct_call_timeout, _("\
 Set the timeout, for direct calls to inferior function calls."), _("\
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.exp b/gdb/testsuite/gdb.base/infcall-timeout.exp
index c6bf8f8ec2d..cfb9a907633 100644
--- a/gdb/testsuite/gdb.base/infcall-timeout.exp
+++ b/gdb/testsuite/gdb.base/infcall-timeout.exp
@@ -28,7 +28,11 @@ if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
 # then adjust the direct-call-timeout, and make an inferior function
 # call that will never return.  GDB should eventually timeout and stop
 # the inferior.
-proc run_test { target_async target_non_stop non_stop } {
+#
+# When UNWIND is "off" the inferior wil be left in the frame where the
+# timeout occurs, otherwise, when UNWIND is "on", GDB should unwind
+# back to the frame where the inferior call was made.
+proc run_test { target_async target_non_stop non_stop unwind } {
     save_vars { ::GDBFLAGS } {
 	append ::GDBFLAGS \
 	    " -ex \"maint set target-non-stop $target_non_stop\""
@@ -45,28 +49,43 @@ proc run_test { target_async target_non_stop non_stop } {
     }
 
     gdb_test_no_output "set direct-call-timeout 5"
+    gdb_test_no_output "set unwind-on-timeout $unwind"
+
+    if { $unwind } {
+	gdb_test "print function_that_never_returns ()" \
+	    [multi_line \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB has restored the context to what it was before the call\\." \
+		 "To change this behavior use \"set unwind-on-timeout off\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(function_that_never_returns\\) will be abandoned\\."]
 
-    # When non-stop mode is off we get slightly different output from GDB.
-    if { ([target_info gdb_protocol] == "remote"
-	  || [target_info gdb_protocol] == "extended-remote")
-	 && !$target_non_stop } {
-	set stopped_line_pattern "Program received signal SIGINT, Interrupt\\."
+	gdb_test "bt" \
+	    "#0\\s+main \\(\\).*"
     } else {
-	set stopped_line_pattern "Program stopped\\."
-    }
+	# When non-stop mode is off we get slightly different output from GDB.
+	if { ([target_info gdb_protocol] == "remote"
+	      || [target_info gdb_protocol] == "extended-remote")
+	     && !$target_non_stop } {
+	    set stopped_line_pattern "Program received signal SIGINT, Interrupt\\."
+	} else {
+	    set stopped_line_pattern "Program stopped\\."
+	}
 
-    gdb_test "print function_that_never_returns ()" \
-	[multi_line \
-	     $stopped_line_pattern \
-	     ".*" \
-	     "The program being debugged timed out while in a function called from GDB\\." \
-	     "GDB remains in the frame where the timeout occurred\\." \
-	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
-	     "Evaluation of the expression containing the function" \
-	     "\\(function_that_never_returns\\) will be abandoned\\." \
-	     "When the function is done executing, GDB will silently stop\\."]
-
-    gdb_test "bt" ".* function_that_never_returns .*<function called from gdb>.*"
+	gdb_test "print function_that_never_returns ()" \
+	    [multi_line \
+		 $stopped_line_pattern \
+		 ".*" \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB remains in the frame where the timeout occurred\\." \
+		 "To change this behavior use \"set unwind-on-timeout on\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(function_that_never_returns\\) will be abandoned\\." \
+		 "When the function is done executing, GDB will silently stop\\."]
+
+	gdb_test "bt" \
+	    ".* function_that_never_returns .*<function called from gdb>.*"
+    }
 }
 
 foreach_with_prefix target_async { "on" "off" } {
@@ -88,7 +107,9 @@ foreach_with_prefix target_async { "on" "off" } {
 		continue
 	    }
 
-	    run_test $target_async $target_non_stop $non_stop
+	    foreach_with_prefix unwind { "on" "off" } {
+		run_test $target_async $target_non_stop $non_stop $unwind
+	    }
 	}
     }
 }
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
index 7bb6b4db813..f3168b89231 100644
--- a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
@@ -41,7 +41,12 @@ set segfault_line [gdb_get_line_number "Segfault here"]
 # thread, on which the inferior call relies, either hits a breakpoint
 # (when OTHER_THREAD_BP is true), or crashes (when OTHER_THREAD_BP is
 # false).
-proc run_test { target_async target_non_stop non_stop other_thread_bp } {
+#
+# When UNWIND is "on" GDB will unwind the thread which performed the
+# inferior function call back to the state where the inferior call was
+# made (when the inferior call times out).  Otherwise, when UNWIND is
+# "off", the inferior is left in the frame where the timeout occurred.
+proc run_test { target_async target_non_stop non_stop other_thread_bp unwind } {
     save_vars { ::GDBFLAGS } {
 	append ::GDBFLAGS " -ex \"maint set target-non-stop $target_non_stop\""
 	append ::GDBFLAGS " -ex \"maint non-stop $non_stop\""
@@ -72,6 +77,7 @@ proc run_test { target_async target_non_stop non_stop other_thread_bp } {
     # for this timeout.  For now though, we just hope 5 seconds is
     # enough.
     gdb_test_no_output "set indirect-call-timeout 5"
+    gdb_test_no_output "set unwind-on-timeout $unwind"
 
     gdb_breakpoint \
 	"${::srcfile}:${::cond_bp_line} if (condition_func ())"
@@ -92,27 +98,43 @@ proc run_test { target_async target_non_stop non_stop other_thread_bp } {
 				 "get number for segfault breakpoint"]
     }
 
-    # When non-stop mode is off we get slightly different output from GDB.
-    if { ([target_info gdb_protocol] == "remote"
-	  || [target_info gdb_protocol] == "extended-remote")
-	 && !$target_non_stop} {
-	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" received signal SIGINT, Interrupt\\."
+    if { $unwind } {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Error in testing condition for breakpoint ${bp_num}:" \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB has restored the context to what it was before the call\\." \
+		 "To change this behavior use \"set unwind-on-timeout off\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(condition_func\\) will be abandoned\\." \
+		 "" \
+		 "Thread ${::decimal}\[^\r\n\]*hit Breakpoint ${bp_num}, \[^\r\n\]+" \
+		 "\[^\r\n\]+ Conditional breakpoint here\\. \[^\r\n\]+"] \
+	    "expected timeout waiting for inferior call to complete"
     } else {
-	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\."
-    }
+	# When non-stop mode is off we get slightly different output from GDB.
+	if { ([target_info gdb_protocol] == "remote"
+	      || [target_info gdb_protocol] == "extended-remote")
+	     && !$target_non_stop} {
+	    set stopped_line_pattern \
+		"Thread ${::decimal} \"\[^\r\n\"\]+\" received signal SIGINT, Interrupt\\."
+	} else {
+	    set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\."
+	}
 
-    gdb_test "continue" \
-	[multi_line \
-	     $stopped_line_pattern \
-	     ".*" \
-	     "Error in testing condition for breakpoint ${bp_num}:" \
-	     "The program being debugged timed out while in a function called from GDB\\." \
-	     "GDB remains in the frame where the timeout occurred\\." \
-	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
-	     "Evaluation of the expression containing the function" \
-	     "\\(condition_func\\) will be abandoned\\." \
-	     "When the function is done executing, GDB will silently stop\\."] \
-	"expected timeout waiting for inferior call to complete"
+	gdb_test "continue" \
+	    [multi_line \
+		 "$stopped_line_pattern" \
+		 ".*" \
+		 "Error in testing condition for breakpoint ${bp_num}:" \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB remains in the frame where the timeout occurred\\." \
+		 "To change this behavior use \"set unwind-on-timeout on\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(condition_func\\) will be abandoned\\." \
+		 "When the function is done executing, GDB will silently stop\\."] \
+	    "expected timeout waiting for inferior call to complete"
+    }
 
     # Remember that other thread that either crashed (with a segfault)
     # or hit a breakpoint?  Now that the inferior call has timed out,
@@ -158,8 +180,11 @@ foreach_with_prefix target_async {"on" "off" } {
 		# disabled.
 		continue
 	    }
-	    foreach_with_prefix other_thread_bp { true false } {
-		run_test $target_async $target_non_stop $non_stop $other_thread_bp
+	    foreach_with_prefix unwind {"off" "on"} {
+		foreach_with_prefix other_thread_bp { true false } {
+		    run_test $target_async $target_non_stop $non_stop \
+			$other_thread_bp $unwind
+		}
 	    }
 	}
     }
-- 
2.25.4


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

* [PATCHv9 5/5] gdb: rename unwindonsignal to unwind-on-signal
  2023-12-02 10:52               ` [PATCHv9 0/5] " Andrew Burgess
                                   ` (3 preceding siblings ...)
  2023-12-02 10:52                 ` [PATCHv9 4/5] gdb: introduce unwind-on-timeout setting Andrew Burgess
@ 2023-12-02 10:52                 ` Andrew Burgess
  2024-01-02 15:57                 ` [PATCHv10 0/5] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
  5 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2023-12-02 10:52 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Eli Zaretskii

Eli has already approved the NEWS/doc changes in this file.

---

We now have unwind-on-timeout and unwind-on-terminating-exception, and
then the odd one out unwindonsignal.

I'm not a great fan of these squashed together command names, so in
this commit I propose renaming this to unwind-on-signal.

Obviously I've added the hidden alias unwindonsignal so any existing
GDB scripts will keep working.

There's one test that I've extended to test the alias works, but in
most of the other test scripts I've changed over to use the new name.

The docs are updated to reference the new name.

Reviewed-By: Eli Zaretskii <eliz@gnu.org>
---
 gdb/NEWS                                      |  9 +++++
 gdb/doc/gdb.texinfo                           | 16 ++++++---
 gdb/infcall.c                                 | 21 ++++++-----
 gdb/testsuite/gdb.base/callfuncs.exp          |  4 +--
 gdb/testsuite/gdb.base/infcall-failure.exp    |  4 +--
 gdb/testsuite/gdb.base/unwindonsignal.exp     | 36 +++++++++++++------
 gdb/testsuite/gdb.compile/compile-cplus.exp   |  6 ++--
 gdb/testsuite/gdb.compile/compile.exp         |  6 ++--
 gdb/testsuite/gdb.cp/gdb2495.exp              | 16 ++++-----
 gdb/testsuite/gdb.fortran/function-calls.exp  |  2 +-
 gdb/testsuite/gdb.mi/mi-condbreak-fail.exp    |  6 ++--
 gdb/testsuite/gdb.mi/mi-condbreak-throw.exp   |  2 +-
 gdb/testsuite/gdb.mi/mi-syn-frame.exp         |  2 +-
 .../infcall-from-bp-cond-simple.exp           |  2 +-
 .../gdb.threads/thread-unwindonsignal.exp     |  8 ++---
 15 files changed, 89 insertions(+), 51 deletions(-)

diff --git a/gdb/NEWS b/gdb/NEWS
index b5ac1b848d6..592984f21e8 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -16,6 +16,10 @@ disassemble
   command will now give an error.  Previously the 'b' flag would
   always override the 'r' flag.
 
+set unwindonsignal on|off
+show unwindonsignal
+  These commands are now aliases for the new set/show unwind-on-signal.
+
 * New commands
 
 info missing-debug-handler
@@ -65,6 +69,11 @@ show unwind-on-timeout
   dummy frame that was added for the inferior call, and restoring the
   inferior state to how it was before the inferior call started.
 
+set unwind-on-signal on|off
+show unwind-on-signal
+  These new commands replaces the existing set/show unwindonsignal.  The
+  old command is maintained as an alias.
+
 * Python API
 
   ** New function gdb.notify_mi(NAME, DATA), that emits custom
diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index 9ba9e898977..3c254b259dd 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -20896,7 +20896,7 @@
 It is possible for the function you call via the @code{print} or
 @code{call} command to generate a signal (e.g., if there's a bug in
 the function, or if you passed it incorrect arguments).  What happens
-in that case is controlled by the @code{set unwindonsignal} command.
+in that case is controlled by the @code{set unwind-on-signal} command.
 
 Similarly, with a C@t{++} program it is possible for the function you
 call via the @code{print} or @code{call} command to generate an
@@ -20910,7 +20910,8 @@
 
 @anchor{stack unwind settings}
 @table @code
-@item set unwindonsignal
+@item set unwind-on-signal
+@kindex set unwind-on-signal
 @kindex set unwindonsignal
 @cindex unwind stack in called functions
 @cindex call dummy stack unwinding
@@ -20921,11 +20922,18 @@
 default), @value{GDBN} stops in the frame where the signal was
 received.
 
-@item show unwindonsignal
+The command @code{set unwindonsignal} is an alias for this command,
+and is maintained for backward compatibility.
+
+@item show unwind-on-signal
+@kindex show unwind-on-signal
 @kindex show unwindonsignal
 Show the current setting of stack unwinding in the functions called by
 @value{GDBN}.
 
+The command @code{show unwindonsignal} is an alias for this command,
+and is maintained for backward compatibility.
+
 @item set unwind-on-terminating-exception
 @kindex set unwind-on-terminating-exception
 @cindex unwind stack in called functions with unhandled exceptions
@@ -20990,7 +20998,7 @@
 If a called function is interrupted for any reason, including hitting
 a breakpoint, or triggering a watchpoint, and the stack is not unwound
 due to @code{set unwind-on-terminating-exception on}, @code{set
-unwind-on-timeout on}, or @code{set unwindonsignal on} (@pxref{stack
+unwind-on-timeout on}, or @code{set unwind-on-signal on} (@pxref{stack
 unwind settings}), then the dummy-frame, created by @value{GDBN} to
 facilitate the call to the program function, will be visible in the
 backtrace, for example frame @code{#3} in the following backtrace:
diff --git a/gdb/infcall.c b/gdb/infcall.c
index 84c6bf2cdd2..bf17a1a21d6 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -1755,7 +1755,7 @@ When the function is done executing, GDB will silently stop."),
 The program being debugged received signal %s, %s\n\
 while in a function called from GDB.  GDB has restored the context\n\
 to what it was before the call.  To change this behavior use\n\
-\"set unwindonsignal off\".  Evaluation of the expression containing\n\
+\"set unwind-on-signal off\".  Evaluation of the expression containing\n\
 the function (%s) will be abandoned."),
 		     gdb_signal_to_name (stop_signal),
 		     gdb_signal_to_string (stop_signal),
@@ -1774,7 +1774,7 @@ the function (%s) will be abandoned."),
 	      error (_("\
 The program being debugged was signaled while in a function called from GDB.\n\
 GDB remains in the frame where the signal was received.\n\
-To change this behavior use \"set unwindonsignal on\".\n\
+To change this behavior use \"set unwind-on-signal on\".\n\
 Evaluation of the expression containing the function\n\
 (%s) will be abandoned.\n\
 When the function is done executing, GDB will silently stop."),
@@ -1906,17 +1906,22 @@ The default is to perform the conversion."),
 			   show_coerce_float_to_double_p,
 			   &setlist, &showlist);
 
-  add_setshow_boolean_cmd ("unwindonsignal", no_class,
-			   &unwind_on_signal_p, _("\
+  set_show_commands setshow_unwind_on_signal_cmds
+    = add_setshow_boolean_cmd ("unwind-on-signal", no_class,
+			       &unwind_on_signal_p, _("\
 Set unwinding of stack if a signal is received while in a call dummy."), _("\
 Show unwinding of stack if a signal is received while in a call dummy."), _("\
-The unwindonsignal lets the user determine what gdb should do if a signal\n\
+The unwind-on-signal lets the user determine what gdb should do if a signal\n\
 is received while in a function called from gdb (call dummy).  If set, gdb\n\
 unwinds the stack and restore the context to what as it was before the call.\n\
 The default is to stop in the frame where the signal was received."),
-			   NULL,
-			   show_unwind_on_signal_p,
-			   &setlist, &showlist);
+			       NULL,
+			       show_unwind_on_signal_p,
+			       &setlist, &showlist);
+  add_alias_cmd ("unwindonsignal", setshow_unwind_on_signal_cmds.set,
+		 no_class, 1, &setlist);
+  add_alias_cmd ("unwindonsignal", setshow_unwind_on_signal_cmds.show,
+		 no_class, 1, &showlist);
 
   add_setshow_boolean_cmd ("unwind-on-terminating-exception", no_class,
 			   &unwind_on_terminating_exception_p, _("\
diff --git a/gdb/testsuite/gdb.base/callfuncs.exp b/gdb/testsuite/gdb.base/callfuncs.exp
index 2c797a224a7..d9f63e944bf 100644
--- a/gdb/testsuite/gdb.base/callfuncs.exp
+++ b/gdb/testsuite/gdb.base/callfuncs.exp
@@ -46,7 +46,7 @@ proc do_function_calls {prototypes} {
 
     # If any of these calls segv we don't want to affect subsequent tests.
     # E.g., we want to ensure register values are restored.
-    gdb_test_no_output "set unwindonsignal on"
+    gdb_test_no_output "set unwind-on-signal on"
 
     gdb_test "p t_char_values(0,0)" " = 0"
     gdb_test "p t_char_values('a','b')" " = 1"
@@ -237,7 +237,7 @@ proc do_function_calls {prototypes} {
     	"call inferior func with struct - returns char *"
 
     # Restore default value.
-    gdb_test_no_output "set unwindonsignal off"
+    gdb_test_no_output "set unwind-on-signal off"
 }
 
 # Procedure to get current content of all registers.
diff --git a/gdb/testsuite/gdb.base/infcall-failure.exp b/gdb/testsuite/gdb.base/infcall-failure.exp
index 5ad179a089d..e2e71649dac 100644
--- a/gdb/testsuite/gdb.base/infcall-failure.exp
+++ b/gdb/testsuite/gdb.base/infcall-failure.exp
@@ -137,7 +137,7 @@ proc_with_prefix run_cond_hits_segfault_test { async_p non_stop_p } {
 	     "Error in testing condition for breakpoint ${bp_1_num}:" \
 	     "The program being debugged was signaled while in a function called from GDB\\." \
 	     "GDB remains in the frame where the signal was received\\." \
-	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "To change this behavior use \"set unwind-on-signal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(func_segfault\\) will be abandoned\\." \
 	     "When the function is done executing, GDB will silently stop\\."]
@@ -166,7 +166,7 @@ proc_with_prefix run_call_hits_segfault_test { async_p non_stop_p } {
 	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
 	     "The program being debugged was signaled while in a function called from GDB\\." \
 	     "GDB remains in the frame where the signal was received\\." \
-	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "To change this behavior use \"set unwind-on-signal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(func_segfault\\) will be abandoned\\." \
 	     "When the function is done executing, GDB will silently stop\\."]
diff --git a/gdb/testsuite/gdb.base/unwindonsignal.exp b/gdb/testsuite/gdb.base/unwindonsignal.exp
index 5c2243236ba..bf876fb42ba 100644
--- a/gdb/testsuite/gdb.base/unwindonsignal.exp
+++ b/gdb/testsuite/gdb.base/unwindonsignal.exp
@@ -34,13 +34,29 @@ gdb_test "break stop_here" "Breakpoint \[0-9\]* at .*"
 gdb_test "continue" "Continuing.*Breakpoint \[0-9\]*, stop_here.*" \
     "continue to breakpoint at stop_here"
 
-# Turn on unwindonsignal.
-gdb_test_no_output "set unwindonsignal on" \
-	"setting unwindonsignal"
+# Turn on unwind-on-signal.
+gdb_test_no_output "set unwind-on-signal on" \
+	"setting unwind-on-signal"
 
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
 	"Unwinding of stack .* is on." \
-	"showing unwindonsignal"
+	"showing unwind-on-signal"
+
+# For backward compatibility we maintain a 'unwindonsignal' alias for
+# 'unwind-on-signal', check it now.
+gdb_test "show unwindonsignal" \
+    "Unwinding of stack .* is on\\." \
+    "showing unwindonsignal alias"
+
+gdb_test_no_output "set unwindonsignal off" \
+    "setting unwindonsignal alias to off"
+
+gdb_test "show unwind-on-signal" \
+    "Unwinding of stack .* is off\\." \
+    "showing unwind-on-signal after setting via alias"
+
+gdb_test_no_output "set unwindonsignal on" \
+    "setting unwindonsignal alias to on"
 
 # Call function (causing the program to get a signal), and see if gdb handles
 # it properly.
@@ -49,7 +65,7 @@ if {[gdb_test "call gen_signal ()"  \
 	      "The program being debugged received signal SIGABRT, Aborted" \
 	      "while in a function called from GDB\\.  GDB has restored the context" \
 	      "to what it was before the call\\.  To change this behavior use" \
-	      "\"set unwindonsignal off\"\\.  Evaluation of the expression containing" \
+	      "\"set unwind-on-signal off\"\\.  Evaluation of the expression containing" \
 	      "the function \\(gen_signal\\) will be abandoned\\."] \
 	 "unwindonsignal, inferior function call signaled"] != 0} {
     return 0
@@ -58,15 +74,15 @@ if {[gdb_test "call gen_signal ()"  \
 # Verify the stack got unwound.
 gdb_test "bt" \
     "#0 *\[x0-9a-f in\]*stop_here \\(.*\\) at .*#1 *\[x0-9a-f in\]*main \\(.*\\) at .*" \
-	"unwindonsignal, stack unwound"
+	"stack unwound"
 
 # Verify the dummy frame got removed from dummy_frame_stack.
 gdb_test_multiple "maint print dummy-frames" \
-	"unwindonsignal, dummy frame removed" {
+	"unwind-on-signal, dummy frame removed" {
     -re "\[\r\n\]*.*stack=.*code=.*\[\r\n\]+$gdb_prompt $" {
-	fail "unwindonsignal, dummy frame removed"
+	fail $gdb_test_name
     }
     -re "\[\r\n\]+$gdb_prompt $" {
-	pass "unwindonsignal, dummy frame removed"
+	pass $gdb_test_name
     }
 }
diff --git a/gdb/testsuite/gdb.compile/compile-cplus.exp b/gdb/testsuite/gdb.compile/compile-cplus.exp
index 48fb75c3d78..c938c60ee98 100644
--- a/gdb/testsuite/gdb.compile/compile-cplus.exp
+++ b/gdb/testsuite/gdb.compile/compile-cplus.exp
@@ -131,13 +131,13 @@ gdb_test "return" "\r\n#0  main .*" "return" \
 	 "Make _gdb_expr\\(__gdb_regs\\*\\) return now\\? \\(y or n\\) " "y"
 gdb_test "info sym $infcall_pc" "\r\nNo symbol matches .*" "info sym not found"
 
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 gdb_test "compile code *(volatile int *) 0 = 0;" \
     [multi_line \
 	 "The program being debugged received signal SIGSEGV, Segmentation fault" \
 	 "while in a function called from GDB\\.  GDB has restored the context" \
 	 "to what it was before the call\\.  To change this behavior use" \
-	 "\"set unwindonsignal off\"\\.  Evaluation of the expression containing" \
+	 "\"set unwind-on-signal off\"\\.  Evaluation of the expression containing" \
 	 "the function \\(_gdb_expr\\(__gdb_regs\\*\\)\\) will be abandoned\\."] \
     "compile code segfault second"
 
@@ -313,7 +313,7 @@ gdb_test "compile code static const int readonly = 1; *(int *) &readonly = 2;" \
 	 "The program being debugged received signal SIGSEGV, Segmentation fault" \
 	 "while in a function called from GDB\\.  GDB has restored the context" \
 	 "to what it was before the call\\.  To change this behavior use" \
-	 "\"set unwindonsignal off\"\\.  Evaluation of the expression containing" \
+	 "\"set unwind-on-signal off\"\\.  Evaluation of the expression containing" \
 	 "the function \\(_gdb_expr\\(__gdb_regs\\*\\)\\) will be abandoned\\."]
 gdb_test_no_output "set debug compile off"
 
diff --git a/gdb/testsuite/gdb.compile/compile.exp b/gdb/testsuite/gdb.compile/compile.exp
index 86521e99dac..cd409f5a48a 100644
--- a/gdb/testsuite/gdb.compile/compile.exp
+++ b/gdb/testsuite/gdb.compile/compile.exp
@@ -157,13 +157,13 @@ gdb_test "return" "\r\n#0  main .*" "return" \
 	 "Make _gdb_expr return now\\? \\(y or n\\) " "y"
 gdb_test "info sym $infcall_pc" "\r\nNo symbol matches .*" "info sym not found"
 
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 gdb_test "compile code *(volatile int *) 0 = 0;" \
     [multi_line \
 	 "The program being debugged received signal SIGSEGV, Segmentation fault" \
 	 "while in a function called from GDB\\.  GDB has restored the context" \
 	 "to what it was before the call\\.  To change this behavior use" \
-	 "\"set unwindonsignal off\"\\.  Evaluation of the expression containing" \
+	 "\"set unwind-on-signal off\"\\.  Evaluation of the expression containing" \
 	 "the function \\(_gdb_expr\\) will be abandoned\\."] \
     "compile code segfault second"
 
@@ -321,7 +321,7 @@ gdb_test "compile code static const int readonly = 1; *(int *) &readonly = 2;" \
 	 "The program being debugged received signal SIGSEGV, Segmentation fault" \
 	 "while in a function called from GDB\\.  GDB has restored the context" \
 	 "to what it was before the call\\.  To change this behavior use" \
-	 "\"set unwindonsignal off\"\\.  Evaluation of the expression containing" \
+	 "\"set unwind-on-signal off\"\\.  Evaluation of the expression containing" \
 	 "the function \\(_gdb_expr\\) will be abandoned\\."]
 gdb_test_no_output "set debug compile off"
 
diff --git a/gdb/testsuite/gdb.cp/gdb2495.exp b/gdb/testsuite/gdb.cp/gdb2495.exp
index 93b046ad3a6..b888924ec63 100644
--- a/gdb/testsuite/gdb.cp/gdb2495.exp
+++ b/gdb/testsuite/gdb.cp/gdb2495.exp
@@ -98,10 +98,10 @@ if {![runto_main]} {
 # behaviour; it should not.  Test both on and off states.
 
 # Turn on unwind on signal behaviour.
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 
 # Check that it is turned on.
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
     "signal is received while in a call dummy is on.*" \
     "turn on unwind on signal"
 
@@ -112,20 +112,20 @@ gdb_test "p exceptions.raise_signal(1)" \
 	 "The program being debugged received signal SIGABRT, Aborted" \
 	 "while in a function called from GDB\\.  GDB has restored the context" \
 	 "to what it was before the call\\.  To change this behavior use" \
-	 "\"set unwindonsignal off\"\\.  Evaluation of the expression containing" \
+	 "\"set unwind-on-signal off\"\\.  Evaluation of the expression containing" \
 	 "the function \\(SimpleException::raise_signal\\(int\\)\\) will be abandoned\\."]\
-    "check for unwindonsignal off message"
+    "check for unwind-on-signal off message"
 
 # And reverse - turn off again.
-gdb_test_no_output "set unwindonsignal off"
+gdb_test_no_output "set unwind-on-signal off"
 
 # Check that it is actually turned off.
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
     "signal is received while in a call dummy is off.*" \
     "turn off unwind on signal"
 
 # Check to see if new behaviour interferes with
 # normal signal handling in inferior function calls.
 gdb_test "p exceptions.raise_signal(1)" \
-    "To change this behavior use \"set unwindonsignal on\".*" \
-    "check for unwindonsignal on message"
+    "To change this behavior use \"set unwind-on-signal on\".*" \
+    "check for unwind-on-signal on message"
diff --git a/gdb/testsuite/gdb.fortran/function-calls.exp b/gdb/testsuite/gdb.fortran/function-calls.exp
index 646fbb06435..27dd68d8cd9 100644
--- a/gdb/testsuite/gdb.fortran/function-calls.exp
+++ b/gdb/testsuite/gdb.fortran/function-calls.exp
@@ -44,7 +44,7 @@ if {![runto [gdb_get_line_number "post_init"]]} {
 }
 
 # Use inspired by gdb.base/callfuncs.exp.
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 
 # Baseline: function and subroutine call with no arguments.
 gdb_test "p no_arg()" " = .TRUE."
diff --git a/gdb/testsuite/gdb.mi/mi-condbreak-fail.exp b/gdb/testsuite/gdb.mi/mi-condbreak-fail.exp
index 3ccca4c2e9b..d91bef420af 100644
--- a/gdb/testsuite/gdb.mi/mi-condbreak-fail.exp
+++ b/gdb/testsuite/gdb.mi/mi-condbreak-fail.exp
@@ -43,7 +43,7 @@ proc run_test { unwind_on_signal } {
 	return
     }
 
-    mi_gdb_test "-gdb-set unwindonsignal ${unwind_on_signal}" {\^done} \
+    mi_gdb_test "-gdb-set unwind-on-signal ${unwind_on_signal}" {\^done} \
 	"set unwind-on-signal"
 
     # Create the conditional breakpoint.
@@ -70,7 +70,7 @@ proc run_test { unwind_on_signal } {
 		 "&\"The program being debugged received signal SIGSEGV, Segmentation fault\\\\n\"" \
 		 "&\"while in a function called from GDB\\.  GDB has restored the context\\\\n\"" \
 		 "&\"to what it was before the call\\.  To change this behavior use\\\\n\"" \
-		 "&\"\\\\\"set unwindonsignal off\\\\\"\\.  Evaluation of the expression containing\\\\n\"" \
+		 "&\"\\\\\"set unwind-on-signal off\\\\\"\\.  Evaluation of the expression containing\\\\n\"" \
 		 "&\"the function \\(cond_fail\\) will be abandoned\\.\\\\n\"" \
 		 "=breakpoint-modified,bkpt={number=\"$bpnum\",type=\"breakpoint\",\[^\r\n\]+times=\"1\",\[^\r\n\]+}" \
 		 "~\"\\\\n\"" \
@@ -92,7 +92,7 @@ proc run_test { unwind_on_signal } {
 		 "&\"Error in testing condition for breakpoint $bpnum:\\\\n\"" \
 		 "&\"The program being debugged was signaled while in a function called from GDB\\.\\\\n\"" \
 		 "&\"GDB remains in the frame where the signal was received\\.\\\\n\"" \
-		 "&\"To change this behavior use \\\\\"set unwindonsignal on\\\\\"\\.\\\\n\"" \
+		 "&\"To change this behavior use \\\\\"set unwind-on-signal on\\\\\"\\.\\\\n\"" \
 		 "&\"Evaluation of the expression containing the function\\\\n\"" \
 		 "&\"\\(cond_fail\\) will be abandoned\\.\\\\n\"" \
 		 "&\"When the function is done executing, GDB will silently stop\\.\\\\n\"" \
diff --git a/gdb/testsuite/gdb.mi/mi-condbreak-throw.exp b/gdb/testsuite/gdb.mi/mi-condbreak-throw.exp
index 7f291244e53..437825eea47 100644
--- a/gdb/testsuite/gdb.mi/mi-condbreak-throw.exp
+++ b/gdb/testsuite/gdb.mi/mi-condbreak-throw.exp
@@ -103,7 +103,7 @@ proc run_test { unwind_on_exception } {
 		 "&\"Error in testing condition for breakpoint $bpnum:\\\\n\"" \
 		 "&\"The program being debugged was signaled while in a function called from GDB\\.\\\\n\"" \
 		 "&\"GDB remains in the frame where the signal was received\\.\\\\n\"" \
-		 "&\"To change this behavior use \\\\\"set unwindonsignal on\\\\\"\\.\\\\n\"" \
+		 "&\"To change this behavior use \\\\\"set unwind-on-signal on\\\\\"\\.\\\\n\"" \
 		 "&\"Evaluation of the expression containing the function\\\\n\"" \
 		 "&\"\\(cond_throw\\(\\)\\) will be abandoned\\.\\\\n\"" \
 		 "&\"When the function is done executing, GDB will silently stop\\.\\\\n\"" \
diff --git a/gdb/testsuite/gdb.mi/mi-syn-frame.exp b/gdb/testsuite/gdb.mi/mi-syn-frame.exp
index 40df312a1cc..1324226412c 100644
--- a/gdb/testsuite/gdb.mi/mi-syn-frame.exp
+++ b/gdb/testsuite/gdb.mi/mi-syn-frame.exp
@@ -94,7 +94,7 @@ mi_gdb_test "409-stack-list-frames 0 0" \
 # 
 
 mi_gdb_test "410-data-evaluate-expression bar()" \
-  ".*410\\^error,msg=\"The program being debugged was signaled while in a function called from GDB.\\\\nGDB remains in the frame where the signal was received.\\\\nTo change this behavior use \\\\\"set unwindonsignal on\\\\\".\\\\nEvaluation of the expression containing the function\\\\n\\(bar\\) will be abandoned.\\\\nWhen the function is done executing, GDB will silently stop.\"" \
+  ".*410\\^error,msg=\"The program being debugged was signaled while in a function called from GDB.\\\\nGDB remains in the frame where the signal was received.\\\\nTo change this behavior use \\\\\"set unwind-on-signal on\\\\\".\\\\nEvaluation of the expression containing the function\\\\n\\(bar\\) will be abandoned.\\\\nWhen the function is done executing, GDB will silently stop.\"" \
   "call inferior function which raises exception"
 
 mi_gdb_test "411-stack-list-frames" "411\\^done,stack=\\\[frame=\{level=\"0\",addr=\"$hex\",func=\"bar\",file=\".*mi-syn-frame.c\",fullname=\"${fullname_syntax}${srcfile}\",line=\"$decimal\",arch=\"$any\"},frame=\{level=\"1\",addr=\"$hex\",func=\"<function called from gdb>\"\},frame=\{level=\"2\",addr=\"$hex\",func=\"main\",file=\".*mi-syn-frame.c\",fullname=\"${fullname_syntax}${srcfile}\",line=\"$decimal\",arch=\"$any\"}.*\\\]" "backtrace from inferior function at exception"
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
index c46f8cdb981..26ce59d6335 100644
--- a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
@@ -173,7 +173,7 @@ proc_with_prefix run_bp_cond_segfaults { target_async target_non_stop } {
 	     "Error in testing condition for breakpoint ${bp_1_num}:" \
 	     "The program being debugged was signaled while in a function called from GDB\\." \
 	     "GDB remains in the frame where the signal was received\\." \
-	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "To change this behavior use \"set unwind-on-signal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(function_that_segfaults\\) will be abandoned\\." \
 	     "When the function is done executing, GDB will silently stop\\."]
diff --git a/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp b/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp
index 68a99f66f1c..a9cedc0c466 100644
--- a/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp
+++ b/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp
@@ -13,7 +13,7 @@
 # You should have received a copy of the GNU General Public License
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-# Test use of unwindonsignal when a hand function call that gets interrupted
+# Test use of unwind-on-signal when a hand function call that gets interrupted
 # by a signal in another thread.
 
 set NR_THREADS 4
@@ -49,12 +49,12 @@ gdb_test "continue" \
 # We want the main thread (hand_call_with_signal) and
 # thread 1 (sigabrt_handler) to both run.
 
-# Do turn on unwindonsignal.
+# Do turn on unwind-on-signal.
 # We want to test gdb handling of the current thread changing when
 # unwindonsignal is in effect.
-gdb_test_no_output "set unwindonsignal on" \
+gdb_test_no_output "set unwind-on-signal on" \
 	"setting unwindonsignal"
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
 	"Unwinding of stack .* is on." \
 	"showing unwindonsignal"
 
-- 
2.25.4


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

* [PATCHv10 0/5] Infcalls from B/P conditions in multi-threaded inferiors
  2023-12-02 10:52               ` [PATCHv9 0/5] " Andrew Burgess
                                   ` (4 preceding siblings ...)
  2023-12-02 10:52                 ` [PATCHv9 5/5] gdb: rename unwindonsignal to unwind-on-signal Andrew Burgess
@ 2024-01-02 15:57                 ` Andrew Burgess
  2024-01-02 15:57                   ` [PATCHv10 1/5] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
                                     ` (5 more replies)
  5 siblings, 6 replies; 202+ messages in thread
From: Andrew Burgess @ 2024-01-02 15:57 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

In v10:

  - Rebased onto current upstream/master, I've updated the copyright
    dates from 2023 to 2024.

  - No merge conflicts (other than NEWS) and no build problems.

In v9:

  - Dropped previous patch #4 (gdb/remote: avoid SIGINT after calling
    remote_target::stop) after feedback from Pedro.  This patch wasn't
    essential for this series, instead I've just updated some of the
    tests to expect different output from remote targets.

  - Updated to more recent master, and applied a small fix due to the
    recent C++17 changes, nothing huge.

  - Retested on unix, native-gdbserver, and native-extended-gdbserver
    boards.

In v8:

  - Rebased onto current upstream/master and retested.

  - Addressed feedback from Baris on patches 1, 2, 3, & 4.  This was
    mostly minor stuff, comment typos and some improvements to the
    testsuite.  There was one real (but minor) GDB change in patch 4.

In v7:

  - Rebased onto current upstream/master, fixed use of
    find_thread_ptid which is now a process_stratum_target method,

  - Retested, with no regressions seen.

In v6:

  - Pushed the 5 initial patches.  These were the smaller fixes, and,
    I felt were pretty obvious fixes.  I'm sure folk will raise
    objections if they disagree.

  - Of the remaining patches, #1 to #5 really needs review before they
    can be merged.  Patch #6 is an obvious cleanup once the first five
    have been merged.

  - I've rebased onto current HEAD of master, there's no significant
    changes.

  - All other documentation changes have been reviewed and approved.

In v5:

  - Rebased to current HEAD of master, minor merge conflict resolved.
    No other code or documentation changes.

  - First patch, which was pure documentation, has now been merged.

  - All other documentation changes have been reviewed and approved.

In v4:

  - I believe all the docs changes have been reviewed and approved by Eli,

  - Rebased onto current master,

  - Dropped patch #2 from the V3 series,

  - I have addressed all the issues Baris pointed out, including the
    fixes for the patch #9 ('gdb: add timeouts for inferior function
    calls'), which I forgot to do in V3.

In v3:

  - Updates for review feedback, biggest changes in #10 and #11, but
    minor changes to most patches.

In V2:

  - Rebased onto something closer to HEAD of master,

  - Patches #1, #2, #12, and #13 are new in this series,

  - Patches #3 to #9, and #11 are unchanged since their V1 iteration,

  - Patches #10 has changed slightly in implementation since v1, and
    the docs have been significantly updated.

---

Andrew Burgess (5):
  Revert "gdb: remove unnecessary parameter wait_ptid from
    do_target_wait"
  gdb: fix b/p conditions with infcalls in multi-threaded inferiors
  gdb: add timeouts for inferior function calls
  gdb: introduce unwind-on-timeout setting
  gdb: rename unwindonsignal to unwind-on-signal

 gdb/NEWS                                      |  36 +++
 gdb/breakpoint.c                              |   2 +
 gdb/doc/gdb.texinfo                           | 111 ++++++-
 gdb/gdbthread.h                               |   3 +
 gdb/infcall.c                                 | 301 +++++++++++++++++-
 gdb/infrun.c                                  |  70 +++-
 gdb/infrun.h                                  |   3 +-
 gdb/testsuite/gdb.base/callfuncs.exp          |   4 +-
 gdb/testsuite/gdb.base/help.exp               |   2 +-
 gdb/testsuite/gdb.base/infcall-failure.exp    |   4 +-
 gdb/testsuite/gdb.base/infcall-timeout.c      |  36 +++
 gdb/testsuite/gdb.base/infcall-timeout.exp    | 115 +++++++
 gdb/testsuite/gdb.base/unwindonsignal.exp     |  36 ++-
 gdb/testsuite/gdb.compile/compile-cplus.exp   |   6 +-
 gdb/testsuite/gdb.compile/compile.exp         |   6 +-
 gdb/testsuite/gdb.cp/gdb2495.exp              |  16 +-
 gdb/testsuite/gdb.fortran/function-calls.exp  |   2 +-
 gdb/testsuite/gdb.mi/mi-condbreak-fail.exp    |   6 +-
 gdb/testsuite/gdb.mi/mi-condbreak-throw.exp   |   2 +-
 gdb/testsuite/gdb.mi/mi-syn-frame.exp         |   2 +-
 .../infcall-from-bp-cond-other-thread-event.c | 135 ++++++++
 ...nfcall-from-bp-cond-other-thread-event.exp | 174 ++++++++++
 .../gdb.threads/infcall-from-bp-cond-simple.c |  89 ++++++
 .../infcall-from-bp-cond-simple.exp           | 235 ++++++++++++++
 .../gdb.threads/infcall-from-bp-cond-single.c | 139 ++++++++
 .../infcall-from-bp-cond-single.exp           | 117 +++++++
 .../infcall-from-bp-cond-timeout.c            | 169 ++++++++++
 .../infcall-from-bp-cond-timeout.exp          | 191 +++++++++++
 .../gdb.threads/thread-unwindonsignal.exp     |   8 +-
 29 files changed, 1943 insertions(+), 77 deletions(-)
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.c
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp


base-commit: 528b729be1a293a21f44149351f3eba5b4e2d870
-- 
2.25.4


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

* [PATCHv10 1/5] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait"
  2024-01-02 15:57                 ` [PATCHv10 0/5] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
@ 2024-01-02 15:57                   ` Andrew Burgess
  2024-01-02 15:57                   ` [PATCHv10 2/5] gdb: fix b/p conditions with infcalls in multi-threaded inferiors Andrew Burgess
                                     ` (4 subsequent siblings)
  5 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2024-01-02 15:57 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Tankut Baris Aktemur

This reverts commit ac0d67ed1dcf470bad6a3bc4800c2ddc9bedecca.

There was nothing wrong with the commit which I'm reverting here, but
it removed some functionality that will be needed for a later commit;
that is, the ability for GDB to ask for events from a specific ptid_t
via the do_target_wait function.

In a follow up commit, this functionality will be used to implement
inferior function calls in multi-threaded inferiors.

This is not a straight revert of the above commit.  Reverting the
above commit replaces a 'nullptr' with 'NULL', I've gone in and
changed that, preserving the 'nullptr'.

Reviewed-By: Tankut Baris Aktemur <tankut.baris.aktemur@intel.com>
---
 gdb/infrun.c | 12 +++++++-----
 1 file changed, 7 insertions(+), 5 deletions(-)

diff --git a/gdb/infrun.c b/gdb/infrun.c
index 1d863896c40..e04612f1a0f 100644
--- a/gdb/infrun.c
+++ b/gdb/infrun.c
@@ -4123,7 +4123,8 @@ do_target_wait_1 (inferior *inf, ptid_t ptid,
    more events.  Polls for events from all inferiors/targets.  */
 
 static bool
-do_target_wait (execution_control_state *ecs, target_wait_flags options)
+do_target_wait (ptid_t wait_ptid, execution_control_state *ecs,
+		target_wait_flags options)
 {
   int num_inferiors = 0;
   int random_selector;
@@ -4133,9 +4134,10 @@ do_target_wait (execution_control_state *ecs, target_wait_flags options)
      polling the rest of the inferior list starting from that one in a
      circular fashion until the whole list is polled once.  */
 
-  auto inferior_matches = [] (inferior *inf)
+  auto inferior_matches = [&wait_ptid] (inferior *inf)
     {
-      return inf->process_target () != nullptr;
+      return (inf->process_target () != nullptr
+	      && ptid_t (inf->pid).matches (wait_ptid));
     };
 
   /* First see how many matching inferiors we have.  */
@@ -4174,7 +4176,7 @@ do_target_wait (execution_control_state *ecs, target_wait_flags options)
 
   auto do_wait = [&] (inferior *inf)
   {
-    ecs->ptid = do_target_wait_1 (inf, minus_one_ptid, &ecs->ws, options);
+    ecs->ptid = do_target_wait_1 (inf, wait_ptid, &ecs->ws, options);
     ecs->target = inf->process_target ();
     return (ecs->ws.kind () != TARGET_WAITKIND_IGNORE);
   };
@@ -4624,7 +4626,7 @@ fetch_inferior_event ()
        the event.  */
     scoped_disable_commit_resumed disable_commit_resumed ("handling event");
 
-    if (!do_target_wait (&ecs, TARGET_WNOHANG))
+    if (!do_target_wait (minus_one_ptid, &ecs, TARGET_WNOHANG))
       {
 	infrun_debug_printf ("do_target_wait returned no event");
 	disable_commit_resumed.reset_and_commit ();
-- 
2.25.4


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

* [PATCHv10 2/5] gdb: fix b/p conditions with infcalls in multi-threaded inferiors
  2024-01-02 15:57                 ` [PATCHv10 0/5] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
  2024-01-02 15:57                   ` [PATCHv10 1/5] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
@ 2024-01-02 15:57                   ` Andrew Burgess
  2024-01-02 15:57                   ` [PATCHv10 3/5] gdb: add timeouts for inferior function calls Andrew Burgess
                                     ` (3 subsequent siblings)
  5 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2024-01-02 15:57 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Natalia Saiapova, Tankut Baris Aktemur

This commit fixes bug PR 28942, that is, creating a conditional
breakpoint in a multi-threaded inferior, where the breakpoint
condition includes an inferior function call.

Currently, when a user tries to create such a breakpoint, then GDB
will fail with:

  (gdb) break infcall-from-bp-cond-single.c:61 if (return_true ())
  Breakpoint 2 at 0x4011fa: file /tmp/build/gdb/testsuite/../../../src/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c, line 61.
  (gdb) continue
  Continuing.
  [New Thread 0x7ffff7c5d700 (LWP 2460150)]
  [New Thread 0x7ffff745c700 (LWP 2460151)]
  [New Thread 0x7ffff6c5b700 (LWP 2460152)]
  [New Thread 0x7ffff645a700 (LWP 2460153)]
  [New Thread 0x7ffff5c59700 (LWP 2460154)]
  Error in testing breakpoint condition:
  Couldn't get registers: No such process.
  An error occurred while in a function called from GDB.
  Evaluation of the expression containing the function
  (return_true) will be abandoned.
  When the function is done executing, GDB will silently stop.
  Selected thread is running.
  (gdb)

Or, in some cases, like this:

  (gdb) break infcall-from-bp-cond-simple.c:56 if (is_matching_tid (arg, 1))
  Breakpoint 2 at 0x401194: file /tmp/build/gdb/testsuite/../../../src/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c, line 56.
  (gdb) continue
  Continuing.
  [New Thread 0x7ffff7c5d700 (LWP 2461106)]
  [New Thread 0x7ffff745c700 (LWP 2461107)]
  ../../src.release/gdb/nat/x86-linux-dregs.c:146: internal-error: x86_linux_update_debug_registers: Assertion `lwp_is_stopped (lwp)' failed.
  A problem internal to GDB has been detected,
  further debugging may prove unreliable.

The precise error depends on the exact thread state; so there's race
conditions depending on which threads have fully started, and which
have not.  But the underlying problem is always the same; when GDB
tries to execute the inferior function call from within the breakpoint
condition, GDB will, incorrectly, try to resume threads that are
already running - GDB doesn't realise that some threads might already
be running.

The solution proposed in this patch requires an additional member
variable thread_info::in_cond_eval.  This flag is set to true (in
breakpoint.c) when GDB is evaluating a breakpoint condition.

In user_visible_resume_ptid (infrun.c), when the in_cond_eval flag is
true, then GDB will only try to resume the current thread, that is,
the thread for which the breakpoint condition is being evaluated.
This solves the problem of GDB trying to resume threads that are
already running.

The next problem is that inferior function calls are assumed to be
synchronous, that is, GDB doesn't expect to start an inferior function
call in thread #1, then receive a stop from thread #2 for some other,
unrelated reason.  To prevent GDB responding to an event from another
thread, we update fetch_inferior_event and do_target_wait in infrun.c,
so that, when an inferior function call (on behalf of a breakpoint
condition) is in progress, we only wait for events from the current
thread (the one evaluating the condition).

In do_target_wait I had to change the inferior_matches lambda
function, which is used to select which inferior to wait on.
Previously the logic was this:

   auto inferior_matches = [&wait_ptid] (inferior *inf)
     {
       return (inf->process_target () != nullptr
               && ptid_t (inf->pid).matches (wait_ptid));
     };

This compares the pid of the inferior against the complete ptid we
want to wait on.  Before this commit wait_ptid was only ever
minus_one_ptid (which is special, and means any process), and so every
inferior would match.

After this commit though wait_ptid might represent a specific thread
in a specific inferior.  If we compare the pid of the inferior to a
specific ptid then these will not match.  The fix is to compare
against the pid extracted from the wait_ptid, not against the complete
wait_ptid itself.

In fetch_inferior_event, after receiving the event, we only want to
stop all the other threads, and call inferior_event_handler with
INF_EXEC_COMPLETE, if we are not evaluating a conditional breakpoint.
If we are, then all the other threads should be left doing whatever
they were before.  The inferior_event_handler call will be performed
once the breakpoint condition has finished being evaluated, and GDB
decides to stop or not.

The final problem that needs solving relates to GDB's commit-resume
mechanism, which allows GDB to collect resume requests into a single
packet in order to reduce traffic to a remote target.

The problem is that the commit-resume mechanism will not send any
resume requests for an inferior if there are already events pending on
the GDB side.

Imagine an inferior with two threads.  Both threads hit a breakpoint,
maybe the same conditional breakpoint.  At this point there are two
pending events, one for each thread.

GDB selects one of the events and spots that this is a conditional
breakpoint, GDB evaluates the condition.

The condition includes an inferior function call, so GDB sets up for
the call and resumes the one thread, the resume request is added to
the commit-resume queue.

When the commit-resume queue is committed GDB sees that there is a
pending event from another thread, and so doesn't send any resume
requests to the actual target, GDB is assuming that when we wait we
will select the event from the other thread.

However, as this is an inferior function call for a condition
evaluation, we will not select the event from the other thread, we
only care about events from the thread that is evaluating the
condition - and the resume for this thread was never sent to the
target.

And so, GDB hangs, waiting for an event from a thread that was never
fully resumed.

To fix this issue I have added the concept of "forcing" the
commit-resume queue.  When enabling commit resume, if the force flag
is true, then any resumes will be committed to the target, even if
there are other threads with pending events.

A note on authorship: this patch was based on some work done by
Natalia Saiapova and Tankut Baris Aktemur from Intel[1].  I have made
some changes to their work in this version.

Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=28942

[1] https://sourceware.org/pipermail/gdb-patches/2020-October/172454.html

Co-authored-by: Natalia Saiapova <natalia.saiapova@intel.com>
Co-authored-by: Tankut Baris Aktemur <tankut.baris.aktemur@intel.com>
Reviewed-By: Tankut Baris Aktemur <tankut.baris.aktemur@intel.com>
---
 gdb/breakpoint.c                              |   2 +
 gdb/gdbthread.h                               |   3 +
 gdb/infcall.c                                 |   6 +
 gdb/infrun.c                                  |  64 +++--
 gdb/infrun.h                                  |   3 +-
 .../infcall-from-bp-cond-other-thread-event.c | 135 ++++++++++
 ...nfcall-from-bp-cond-other-thread-event.exp | 174 +++++++++++++
 .../gdb.threads/infcall-from-bp-cond-simple.c |  89 +++++++
 .../infcall-from-bp-cond-simple.exp           | 235 ++++++++++++++++++
 .../gdb.threads/infcall-from-bp-cond-single.c | 139 +++++++++++
 .../infcall-from-bp-cond-single.exp           | 117 +++++++++
 11 files changed, 952 insertions(+), 15 deletions(-)
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index bd7f74671ce..687802be527 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -5675,6 +5675,8 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
 	{
 	  try
 	    {
+	      scoped_restore reset_in_cond_eval
+		= make_scoped_restore (&thread->control.in_cond_eval, true);
 	      condition_result = breakpoint_cond_eval (cond);
 	    }
 	  catch (const gdb_exception_error &ex)
diff --git a/gdb/gdbthread.h b/gdb/gdbthread.h
index b2c6baf4432..1bd6a8f508c 100644
--- a/gdb/gdbthread.h
+++ b/gdb/gdbthread.h
@@ -172,6 +172,9 @@ struct thread_control_state
      command.  This is used to decide whether "set scheduler-locking
      step" behaves like "on" or "off".  */
   int stepping_command = 0;
+
+  /* True if the thread is evaluating a BP condition.  */
+  bool in_cond_eval = false;
 };
 
 /* Inferior thread specific part of `struct infcall_suspend_state'.  */
diff --git a/gdb/infcall.c b/gdb/infcall.c
index 8252feea074..935a555e817 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -672,6 +672,12 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
 
       proceed (real_pc, GDB_SIGNAL_0);
 
+      /* Enable commit resume, but pass true for the force flag.  This
+	 ensures any thread we set running in proceed will actually be
+	 committed to the target, even if some other thread in the current
+	 target has a pending event.  */
+      scoped_enable_commit_resumed enable ("infcall", true);
+
       infrun_debug_show_threads ("non-exited threads after proceed for inferior-call",
 				 all_non_exited_threads ());
 
diff --git a/gdb/infrun.c b/gdb/infrun.c
index e04612f1a0f..1f7e013fe12 100644
--- a/gdb/infrun.c
+++ b/gdb/infrun.c
@@ -2404,6 +2404,14 @@ user_visible_resume_ptid (int step)
 	 mode.  */
       resume_ptid = inferior_ptid;
     }
+  else if (inferior_ptid != null_ptid
+	   && inferior_thread ()->control.in_cond_eval)
+    {
+      /* The inferior thread is evaluating a BP condition.  Other threads
+	 might be stopped or running and we do not want to change their
+	 state, thus, resume only the current thread.  */
+      resume_ptid = inferior_ptid;
+    }
   else if (!sched_multi && target_supports_multi_process ())
     {
       /* Resume all threads of the current process (and none of other
@@ -3199,12 +3207,24 @@ schedlock_applies (struct thread_info *tp)
 					    execution_direction)));
 }
 
-/* Set process_stratum_target::COMMIT_RESUMED_STATE in all target
-   stacks that have threads executing and don't have threads with
-   pending events.  */
+/* When FORCE_P is false, set process_stratum_target::COMMIT_RESUMED_STATE
+   in all target stacks that have threads executing and don't have threads
+   with pending events.
+
+   When FORCE_P is true, set process_stratum_target::COMMIT_RESUMED_STATE
+   in all target stacks that have threads executing regardless of whether
+   there are pending events or not.
+
+   Passing FORCE_P as false makes sense when GDB is going to wait for
+   events from all threads and will therefore spot the pending events.
+   However, if GDB is only going to wait for events from select threads
+   (i.e. when performing an inferior call) then a pending event on some
+   other thread will not be spotted, and if we fail to commit the resume
+   state for the thread performing the inferior call, then the inferior
+   call will never complete (or even start).  */
 
 static void
-maybe_set_commit_resumed_all_targets ()
+maybe_set_commit_resumed_all_targets (bool force_p)
 {
   scoped_restore_current_thread restore_thread;
 
@@ -3233,7 +3253,7 @@ maybe_set_commit_resumed_all_targets ()
 	 status to report, handle it before requiring the target to
 	 commit its resumed threads: handling the status might lead to
 	 resuming more threads.  */
-      if (proc_target->has_resumed_with_pending_wait_status ())
+      if (!force_p && proc_target->has_resumed_with_pending_wait_status ())
 	{
 	  infrun_debug_printf ("not requesting commit-resumed for target %s, a"
 			       " thread has a pending waitstatus",
@@ -3243,7 +3263,7 @@ maybe_set_commit_resumed_all_targets ()
 
       switch_to_inferior_no_thread (inf);
 
-      if (target_has_pending_events ())
+      if (!force_p && target_has_pending_events ())
 	{
 	  infrun_debug_printf ("not requesting commit-resumed for target %s, "
 			       "target has pending events",
@@ -3336,7 +3356,7 @@ scoped_disable_commit_resumed::reset ()
     {
       /* This is the outermost instance, re-enable
 	 COMMIT_RESUMED_STATE on the targets where it's possible.  */
-      maybe_set_commit_resumed_all_targets ();
+      maybe_set_commit_resumed_all_targets (false);
     }
   else
     {
@@ -3369,7 +3389,7 @@ scoped_disable_commit_resumed::reset_and_commit ()
 /* See infrun.h.  */
 
 scoped_enable_commit_resumed::scoped_enable_commit_resumed
-  (const char *reason)
+  (const char *reason, bool force_p)
   : m_reason (reason),
     m_prev_enable_commit_resumed (enable_commit_resumed)
 {
@@ -3381,7 +3401,7 @@ scoped_enable_commit_resumed::scoped_enable_commit_resumed
 
       /* Re-enable COMMIT_RESUMED_STATE on the targets where it's
 	 possible.  */
-      maybe_set_commit_resumed_all_targets ();
+      maybe_set_commit_resumed_all_targets (force_p);
 
       maybe_call_commit_resumed_all_targets ();
     }
@@ -4134,10 +4154,11 @@ do_target_wait (ptid_t wait_ptid, execution_control_state *ecs,
      polling the rest of the inferior list starting from that one in a
      circular fashion until the whole list is polled once.  */
 
-  auto inferior_matches = [&wait_ptid] (inferior *inf)
+  ptid_t wait_ptid_pid {wait_ptid.pid ()};
+  auto inferior_matches = [&wait_ptid_pid] (inferior *inf)
     {
       return (inf->process_target () != nullptr
-	      && ptid_t (inf->pid).matches (wait_ptid));
+	      && ptid_t (inf->pid).matches (wait_ptid_pid));
     };
 
   /* First see how many matching inferiors we have.  */
@@ -4626,7 +4647,17 @@ fetch_inferior_event ()
        the event.  */
     scoped_disable_commit_resumed disable_commit_resumed ("handling event");
 
-    if (!do_target_wait (minus_one_ptid, &ecs, TARGET_WNOHANG))
+    /* Is the current thread performing an inferior function call as part
+       of a breakpoint condition evaluation?  */
+    bool in_cond_eval = (inferior_ptid != null_ptid
+			 && inferior_thread ()->control.in_cond_eval);
+
+    /* If the thread is in the middle of the condition evaluation, wait for
+       an event from the current thread.  Otherwise, wait for an event from
+       any thread.  */
+    ptid_t waiton_ptid = in_cond_eval ? inferior_ptid : minus_one_ptid;
+
+    if (!do_target_wait (waiton_ptid, &ecs, TARGET_WNOHANG))
       {
 	infrun_debug_printf ("do_target_wait returned no event");
 	disable_commit_resumed.reset_and_commit ();
@@ -4684,7 +4715,12 @@ fetch_inferior_event ()
 	    bool should_notify_stop = true;
 	    bool proceeded = false;
 
-	    stop_all_threads_if_all_stop_mode ();
+	    /* If the thread that stopped just completed an inferior
+	       function call as part of a condition evaluation, then we
+	       don't want to stop all the other threads.  */
+	    if (ecs.event_thread == nullptr
+		|| !ecs.event_thread->control.in_cond_eval)
+	      stop_all_threads_if_all_stop_mode ();
 
 	    clean_up_just_stopped_threads_fsms (&ecs);
 
@@ -4711,7 +4747,7 @@ fetch_inferior_event ()
 		  proceeded = normal_stop ();
 	      }
 
-	    if (!proceeded)
+	    if (!proceeded && !in_cond_eval)
 	      {
 		inferior_event_handler (INF_EXEC_COMPLETE);
 		cmd_done = 1;
diff --git a/gdb/infrun.h b/gdb/infrun.h
index a343d27f72d..d8db153ecc6 100644
--- a/gdb/infrun.h
+++ b/gdb/infrun.h
@@ -406,7 +406,8 @@ extern void maybe_call_commit_resumed_all_targets ();
 
 struct scoped_enable_commit_resumed
 {
-  explicit scoped_enable_commit_resumed (const char *reason);
+  explicit scoped_enable_commit_resumed (const char *reason,
+					 bool force_p = false);
   ~scoped_enable_commit_resumed ();
 
   DISABLE_COPY_AND_ASSIGN (scoped_enable_commit_resumed);
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
new file mode 100644
index 00000000000..38a5bc284df
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
@@ -0,0 +1,135 @@
+/* Copyright 2022-2024 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 <pthread.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <sched.h>
+
+#define NUM_THREADS 2
+
+pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+
+/* Some global variables to poke, just for something to do.  */
+volatile int global_var_0 = 0;
+volatile int global_var_1 = 0;
+
+/* This flag is updated from GDB.  */
+volatile int raise_signal = 0;
+
+/* Implement the breakpoint condition function.  Release the other thread
+   and try to give the other thread a chance to run.  Then return ANSWER.  */
+int
+condition_core_func (int answer)
+{
+  /* This unlock should release the other thread.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  /* And this yield and sleep should (hopefully) give the other thread a
+     chance to run.  This isn't guaranteed of course, but once the other
+     thread does run it should hit a breakpoint, which GDB should
+     (temporarily) ignore, so there's no easy way for us to know the other
+     thread has done what it needs to, thus, yielding and sleeping is the
+     best we can do.  */
+  sched_yield ();
+  sleep (2);
+
+  return answer;
+}
+
+void
+stop_marker ()
+{
+  int a = 100;	/* Final breakpoint here.  */
+}
+
+/* A breakpoint condition function that always returns true.  */
+int
+condition_true_func ()
+{
+  return condition_core_func (1);
+}
+
+/* A breakpoint condition function that always returns false.  */
+int
+condition_false_func ()
+{
+  return condition_core_func (0);
+}
+
+void *
+worker_func (void *arg)
+{
+  volatile int *ptr = 0;
+  int tid = *((int *) arg);
+
+  switch (tid)
+    {
+    case 0:
+      global_var_0 = 11;	/* First thread breakpoint.  */
+      break;
+
+    case 1:
+      if (pthread_mutex_lock (&mutex) != 0)
+	abort ();
+      if (raise_signal)
+	global_var_1 = *ptr;	/* Signal here.  */
+      else
+	global_var_1 = 99;	/* Other thread breakpoint.  */
+      break;
+
+    default:
+      abort ();
+    }
+
+  return NULL;
+}
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+
+  /* Set an alarm, just in case the test deadlocks.  */
+  alarm (300);
+
+  /* We want the mutex to start locked.  */
+  if (pthread_mutex_lock (&mutex) != 0)
+    abort ();
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      void *retval;
+      pthread_join (threads[i], &retval);
+    }
+
+  /* Unlock once we're done, just for cleanliness.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
new file mode 100644
index 00000000000..b5c0d84afbf
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
@@ -0,0 +1,174 @@
+# Copyright 2022-2024 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/>.
+
+# Test for conditional breakpoints where the breakpoint condition includes
+# an inferior function call.
+#
+# The tests in this script are testing what happens when an event arrives in
+# another thread while GDB is waiting for the inferior function call (in the
+# breakpoint condition) to finish.
+#
+# The expectation is that GDB will queue events for other threads and wait
+# for the inferior function call to complete, if the condition is true, then
+# the conditional breakpoint should be reported first.  The other thread
+# event should of course, not get lost, and should be reported as soon as
+# the user tries to continue the inferior.
+#
+# If the conditional breakpoint ends up not being taken (the condition is
+# false), then the other thread event should be reported immediately.
+#
+# This script tests what happens when the other thread event is (a) the
+# other thread hitting a breakpoint, and (b) the other thread taking a
+# signal (SIGSEGV in this case).
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] == -1 } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "First thread breakpoint"]
+set other_bp_line [gdb_get_line_number "Other thread breakpoint"]
+set final_bp_line [gdb_get_line_number "Final breakpoint here"]
+set signal_line [gdb_get_line_number "Signal here"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if { ![runto_main] } {
+	return -1
+    }
+
+    return 0
+}
+
+# Run a test of GDB's conditional breakpoints, where the conditions include
+# inferior function calls.  While the inferior function call is executing
+# another thread will hit a breakpoint (when OTHER_THREAD_SIGNAL is false),
+# or receive a signal (when OTHER_THREAD_SIGNAL is true).  GDB should report
+# the conditional breakpoint first (if the condition is true), and then
+# report the second thread event once the inferior is continued again.
+#
+# When STOP_AT_COND is true then the conditional breakpoint will have a
+# condition that evaluates to true (and GDB will stop at the breakpoint),
+# otherwise, the condition will evaluate to false (and GDB will not stop at
+# the breakpoint).
+proc run_condition_test { stop_at_cond other_thread_signal \
+			      target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint.
+    if { $stop_at_cond } {
+	set cond_func "condition_true_func"
+    } else {
+	set cond_func "condition_false_func"
+    }
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (${cond_func} ())"
+    set cond_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			"get number for conditional breakpoint"]
+
+    if { $other_thread_signal } {
+	# Arrange for the other thread to raise a signal while GDB is
+	# evaluating the breakpoint condition.
+	gdb_test_no_output "set raise_signal = 1"
+    } else {
+	# And a breakpoint that will be hit by another thread only once the
+	# breakpoint condition starts to be evaluated.
+	gdb_breakpoint "${::srcfile}:${::other_bp_line}"
+	set other_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			      "get number for other breakpoint"]
+    }
+
+    # A final breakpoint once the test has completed.
+    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
+    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			  "get number for final breakpoint"]
+
+    if { $stop_at_cond } {
+	# Continue.  The first breakpoint we hit should be the conditional
+	# breakpoint.  The other thread will have hit its breakpoint, but
+	# that will have been deferred until the conditional breakpoint is
+	# reported.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${cond_bp_num}, worker_func \[^\r\n\]+:${::cond_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+First thread breakpoint\[^\r\n\]+"] \
+	    "hit the conditional breakpoint"
+    }
+
+    if { $other_thread_signal } {
+	# Now continue again, the other thread will now report that it
+	# received a signal.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" received signal SIGSEGV, Segmentation fault\\." \
+		 "\\\[Switching to Thread \[^\r\n\]+\\\]" \
+		 "${::hex} in worker_func \[^\r\n\]+:${::signal_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Signal here\[^\r\n\]+"] \
+	    "received signal in other thread"
+    } else {
+	# Now continue again, the other thread will now report its
+	# breakpoint.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${other_bp_num}, worker_func \[^\r\n\]+:${::other_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Other thread breakpoint\[^\r\n\]+"] \
+	    "hit the breakpoint in other thread"
+
+	# Run to the stop marker.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${final_bp_num}, stop_marker \[^\r\n\]+:${::final_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Final breakpoint here\[^\r\n\]+"] \
+	    "hit the final breakpoint"
+    }
+
+    gdb_exit
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	foreach_with_prefix other_thread_signal { true false } {
+	    foreach_with_prefix stop_at_cond { true false } {
+		run_condition_test $stop_at_cond $other_thread_signal \
+		    $target_async $target_non_stop
+	    }
+	}
+    }
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
new file mode 100644
index 00000000000..2e23f1229c5
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
@@ -0,0 +1,89 @@
+/* Copyright 2022-2024 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 <pthread.h>
+#include <unistd.h>
+
+#define NUM_THREADS 3
+
+int
+is_matching_tid (int *tid_ptr, int tid_value)
+{
+  return *tid_ptr == tid_value;
+}
+
+int
+return_true ()
+{
+  return 1;
+}
+
+int
+return_false ()
+{
+  return 0;
+}
+
+int
+function_that_segfaults ()
+{
+  int *p = 0;
+  *p = 1;	/* Segfault happens here.   */
+}
+
+int
+function_with_breakpoint ()
+{
+  return 1;	/* Nested breakpoint.  */
+}
+
+void *
+worker_func (void *arg)
+{
+  int a = 42;	/* Breakpoint here.  */
+}
+
+void
+stop_marker ()
+{
+  int b = 99;	/* Stop marker.  */
+}
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+
+  alarm (300);
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      void *retval;
+      pthread_join (threads[i], &retval);
+    }
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
new file mode 100644
index 00000000000..d6069ebaa58
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
@@ -0,0 +1,235 @@
+# Copyright 2022-2024 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/>.
+
+# Some simple tests of inferior function calls from breakpoint
+# conditions, in multi-threaded inferiors.
+#
+# This test sets up a multi-threaded inferior, and places a breakpoint
+# at a location that many of the threads will reach.  We repeat the
+# test with different conditions, sometimes a single thread should
+# stop at the breakpoint, sometimes multiple threads should stop, and
+# sometimes no threads should stop.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] == -1 } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "Breakpoint here"]
+set stop_bp_line [gdb_get_line_number "Stop marker"]
+set nested_bp_line [gdb_get_line_number "Nested breakpoint"]
+set segv_line [gdb_get_line_number "Segfault happens here"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if { ![runto_main] } {
+	return -1
+    }
+
+    return 0
+}
+
+# Run a test of GDB's conditional breakpoints, where the conditions include
+# inferior function calls.
+#
+# CONDITION is the expression to be used as the breakpoint condition.
+#
+# N_EXPECTED_HITS is the number of threads that we expect to stop due to
+# CONDITON.
+#
+# MESSAGE is used as a test name prefix.
+proc run_condition_test { message n_expected_hits condition \
+			      target_async target_non_stop } {
+    with_test_prefix $message {
+
+	if { [start_gdb_and_runto_main $target_async \
+		  $target_non_stop] == -1 } {
+	    return
+	}
+
+	# Use this convenience variable to track how often the
+	# breakpoint condition has been evaluated.  This should be
+	# once per thread.
+	gdb_test "set \$n_cond_eval = 0"
+
+	# Setup the conditional breakpoint.
+	gdb_breakpoint \
+	    "${::srcfile}:${::cond_bp_line} if ((++\$n_cond_eval) && (${condition}))"
+
+	# And a breakpoint that we hit when the test is over, this one is
+	# not conditional.  Only the main thread gets here once all the
+	# other threads have finished.
+	gdb_breakpoint "${::srcfile}:${::stop_bp_line}"
+
+	# The number of times we stop at the conditional breakpoint.
+	set n_hit_condition 0
+
+	# Now keep 'continue'-ing GDB until all the threads have finished
+	# and we reach the stop_marker breakpoint.
+	gdb_test_multiple "continue" "spot all breakpoint hits" {
+	    -re " worker_func \[^\r\n\]+${::srcfile}:${::cond_bp_line}\r\n${::decimal}\\s+\[^\r\n\]+Breakpoint here\[^\r\n\]+\r\n${::gdb_prompt} $" {
+		incr n_hit_condition
+		send_gdb "continue\n"
+		exp_continue
+	    }
+
+	    -re " stop_marker \[^\r\n\]+${::srcfile}:${::stop_bp_line}\r\n${::decimal}\\s+\[^\r\n\]+Stop marker\[^\r\n\]+\r\n${::gdb_prompt} $" {
+		pass $gdb_test_name
+	    }
+	}
+
+	gdb_assert { $n_hit_condition == $n_expected_hits } \
+	    "stopped at breakpoint the expected number of times"
+
+	# Ensure the breakpoint condition was evaluated once per thread.
+	gdb_test "print \$n_cond_eval" "= 3" \
+	    "condition was evaluated in each thread"
+    }
+}
+
+# Check that after handling a conditional breakpoint (where the condition
+# includes an inferior call), it is still possible to kill the running
+# inferior, and then restart the inferior.
+#
+# At once point doing this would result in GDB giving an assertion error.
+proc_with_prefix run_kill_and_restart_test { target_async target_non_stop } {
+    # This test relies on the 'start' command, which is not possible with
+    # the plain 'remote' target.
+    if { [target_info gdb_protocol] == "remote" } {
+	return
+    }
+
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint.
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 1))"
+    gdb_continue_to_breakpoint "worker_func"
+
+    # Now kill the program being debugged.
+    gdb_test "kill" "" "kill process" \
+	"Kill the program being debugged.*y or n. $" "y"
+
+    # Check we can restart the inferior.  At one point this would trigger an
+    # assertion.
+    gdb_start_cmd
+}
+
+# Create a conditional breakpoint which includes a call to a function that
+# segfaults.  Run GDB and check what happens when the inferior segfaults
+# during the inferior call.
+proc_with_prefix run_bp_cond_segfaults { target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # This test relies on the inferior segfaulting when trying to
+    # access address zero.
+    if { [is_address_zero_readable] } {
+	return
+    }
+
+    # Setup the conditional breakpoint, include a call to
+    # 'function_that_segfaults', which triggers the segfault.
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 0) && function_that_segfaults ())"
+    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of conditional breakpoint"]
+
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     ".*" \
+	     "Thread ${::decimal} \"infcall-from-bp\" received signal SIGSEGV, Segmentation fault\\." \
+	     "${::hex} in function_that_segfaults \\(\\) at \[^\r\n\]+:${::segv_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Segfault happens here\[^\r\n\]+" \
+	     "Error in testing condition for breakpoint ${bp_1_num}:" \
+	     "The program being debugged was signaled while in a function called from GDB\\." \
+	     "GDB remains in the frame where the signal was received\\." \
+	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(function_that_segfaults\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+}
+
+# Create a conditional breakpoint which includes a call to a function that
+# itself has a breakpoint set within it.  Run GDB and check what happens
+# when GDB hits the nested breakpoint.
+proc_with_prefix run_bp_cond_hits_breakpoint { target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint, include a call to
+    # 'function_with_breakpoint' in which we will shortly place a
+    # breakpoint.
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 0) && function_with_breakpoint ())"
+    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of conditional breakpoint"]
+
+    gdb_breakpoint "${::srcfile}:${::nested_bp_line}"
+    set bp_2_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of nested breakpoint"]
+
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     ".*" \
+	     "Thread ${::decimal} \"infcall-from-bp\" hit Breakpoint ${bp_2_num}, function_with_breakpoint \\(\\) at \[^\r\n\]+:${::nested_bp_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Nested breakpoint\[^\r\n\]+" \
+	     "Error in testing condition for breakpoint ${bp_1_num}:" \
+	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(function_with_breakpoint\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	run_condition_test "exactly one thread is hit" \
+	    1 "is_matching_tid (arg, 1)" \
+	    $target_async $target_non_stop
+	run_condition_test "exactly two threads are hit" \
+	    2 "(is_matching_tid (arg, 0) || is_matching_tid (arg, 2))" \
+	    $target_async $target_non_stop
+	run_condition_test "all three threads are hit" \
+	    3 "return_true ()" \
+	    $target_async $target_non_stop
+	run_condition_test "no thread is hit" \
+	    0 "return_false ()" \
+	    $target_async $target_non_stop
+
+	run_kill_and_restart_test $target_async $target_non_stop
+	run_bp_cond_segfaults $target_async $target_non_stop
+	run_bp_cond_hits_breakpoint $target_async $target_non_stop
+    }
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
new file mode 100644
index 00000000000..0b045f86fad
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
@@ -0,0 +1,139 @@
+/* Copyright 2022-2024 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 <pthread.h>
+#include <unistd.h>
+#include <semaphore.h>
+#include <stdlib.h>
+
+#define NUM_THREADS 5
+
+/* Semaphores, used to track when threads have started, and to control
+   when the threads finish.  */
+sem_t startup_semaphore;
+sem_t finish_semaphore;
+
+/* Mutex to control when the first worker thread hit a breakpoint
+   location.  */
+pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+
+/* Global variable to poke, just so threads have something to do.  */
+volatile int global_var = 0;
+
+int
+return_true ()
+{
+  return 1;
+}
+
+int
+return_false ()
+{
+  return 0;
+}
+
+void *
+worker_func (void *arg)
+{
+  int tid = *((int *) arg);
+
+  switch (tid)
+    {
+    case 0:
+      /* Wait for MUTEX to become available, then pass through the
+	 conditional breakpoint location.  */
+      if (pthread_mutex_lock (&mutex) != 0)
+	abort ();
+      global_var = 99;	/* Conditional breakpoint here.  */
+      if (pthread_mutex_unlock (&mutex) != 0)
+	abort ();
+      break;
+
+    default:
+      /* Notify the main thread that the thread has started, then wait for
+	 the main thread to tell us to finish.  */
+      sem_post (&startup_semaphore);
+      if (sem_wait (&finish_semaphore) != 0)
+	abort ();
+      break;
+    }
+}
+
+void
+stop_marker ()
+{
+  global_var = 99;	/* Stop marker.  */
+}
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+  void *retval;
+
+  /* An alarm, just in case the thread deadlocks.  */
+  alarm (300);
+
+  /* Semaphore initialization.  */
+  if (sem_init (&startup_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&finish_semaphore, 0, 0) != 0)
+    abort ();
+
+  /* Lock MUTEX, this prevents the first worker thread from rushing ahead.  */
+  if (pthread_mutex_lock (&mutex) != 0)
+    abort ();
+
+  /* Worker thread creation.  */
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  /* Wait for every thread (other than the first) to tell us it has started
+     up.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    {
+      if (sem_wait (&startup_semaphore) != 0)
+	abort ();
+    }
+
+  /* Unlock the first thread so it can proceed.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  /* Wait for the first thread only.  */
+  pthread_join (threads[0], &retval);
+
+  /* Now post FINISH_SEMAPHORE to allow all the other threads to finish.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    sem_post (&finish_semaphore);
+
+  /* Now wait for the remaining threads to complete.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    pthread_join (threads[i], &retval);
+
+  /* Semaphore cleanup.  */
+  sem_destroy (&finish_semaphore);
+  sem_destroy (&startup_semaphore);
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
new file mode 100644
index 00000000000..2c3623ec3a5
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
@@ -0,0 +1,117 @@
+# Copyright 2022-2024 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 reprocuces bug gdb/28942, performing an inferior function
+# call from a breakpoint condition in a multi-threaded inferior.
+#
+# The important part of this test is that, when the conditional
+# breakpoint is hit, and the condition (which includes an inferior
+# function call) is evaluated, the other threads are running.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] == -1 } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "Conditional breakpoint here"]
+set final_bp_line [gdb_get_line_number "Stop marker"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if { ![runto_main] } {
+	return -1
+    }
+
+    return 0
+}
+
+# Run a test of GDB's conditional breakpoints, where the conditions include
+# inferior function calls.
+#
+# TARGET_ASYNC and TARGET_NON_STOP are used when starting up GDB.
+#
+# When STOP_AT_COND is true the breakpoint condtion will evaluate to
+# true, and GDB will stop at the breakpoint.  Otherwise, the
+# breakpoint condition will evaluate to false and GDB will not stop at
+# the breakpoint.
+proc run_condition_test { stop_at_cond \
+			      target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint.
+    if { $stop_at_cond } {
+	set cond_func "return_true"
+    } else {
+	set cond_func "return_false"
+    }
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (${cond_func} ())"
+    set cond_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			"get number for conditional breakpoint"]
+
+    # And a breakpoint that we hit when the test is over, this one is
+    # not conditional.
+    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
+    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			  "get number for final breakpoint"]
+
+    if { $stop_at_cond } {
+	# Continue.  The first breakpoint we hit should be the conditional
+	# breakpoint.  The other thread will have hit its breakpoint, but
+	# that will have been deferred until the conditional breakpoint is
+	# reported.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${cond_bp_num}, worker_func \[^\r\n\]+:${::cond_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Conditional breakpoint here\[^\r\n\]+"] \
+	    "hit the conditional breakpoint"
+    }
+
+    # Run to the stop marker.
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     ".*" \
+	     "" \
+	     "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${final_bp_num}, stop_marker \[^\r\n\]+:${::final_bp_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Stop marker\[^\r\n\]+"] \
+	"hit the final breakpoint"
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	foreach_with_prefix stop_at_cond { true false } {
+	    run_condition_test $stop_at_cond \
+		$target_async $target_non_stop
+	}
+    }
+}
-- 
2.25.4


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

* [PATCHv10 3/5] gdb: add timeouts for inferior function calls
  2024-01-02 15:57                 ` [PATCHv10 0/5] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
  2024-01-02 15:57                   ` [PATCHv10 1/5] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
  2024-01-02 15:57                   ` [PATCHv10 2/5] gdb: fix b/p conditions with infcalls in multi-threaded inferiors Andrew Burgess
@ 2024-01-02 15:57                   ` Andrew Burgess
  2024-01-02 15:57                   ` [PATCHv10 4/5] gdb: introduce unwind-on-timeout setting Andrew Burgess
                                     ` (2 subsequent siblings)
  5 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2024-01-02 15:57 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Tankut Baris Aktemur, Eli Zaretskii

Eli has already approved the NEWS/doc changes in this file.

---

In the previous commits I have been working on improving inferior
function call support.  One thing that worries me about using inferior
function calls from a conditional breakpoint is: what happens if the
inferior function call fails?

If the failure is obvious, e.g. the thread performing the call
crashes, or hits a breakpoint, then this case is already well handled,
and the error is reported to the user.

But what if the thread performing the inferior call just deadlocks?
If the user made the call from a 'print' or 'call' command, then the
user might have some expectation of when the function call should
complete, and, when this time limit is exceeded, the user
will (hopefully) interrupt GDB and regain control of the debug
session.

But, when the inferior function call is from a breakpoint condition it
is much harder to understand that GDB is deadlocked within an inferior
call.  Maybe the breakpoint hasn't been hit yet?  Or maybe the
condition was always false?  Or maybe GDB is deadlocked in an inferior
call?  The only way to know for sure is for the user to periodically
interrupt the inferior, check on the state of all the threads, and
then continue.

Additionally, the focus of the previous commit was inferior function
calls, from a conditional breakpoint, in a multi-threaded inferior.
This opens up a whole new set of potential failure conditions.  For
example, what if the function called relies on interaction with some
other thread, and the other thread crashes?  Or hits a breakpoint?
Given how inferior function calls work (in a synchronous manner), a
stop event in some other thread is going to be ignored while the
inferior function call is being executed as part of a breakpoint
condition, and this means that GDB could get stuck waiting for the
original condition thread, which will now never complete.

In this commit I propose a solution to this problem.  A timeout.  For
targets that support async-mode we can install an event-loop timer
before starting the inferior function call.  When the timer expires we
will stop the thread performing the inferior function call.  With this
mechanism in place a user can be sure that any inferior call they make
will either complete, or timeout eventually.

Adding a timer like this is obviously a change in behaviour for the
more common 'call' and 'print' uses of inferior function calls, so, in
this patch, I propose having two different timers.  One I call the
'direct-call-timeout', which is used for 'call' and 'print' commands.
This timeout is by default set to unlimited, which, not surprisingly,
means there is no timeout in place.

A second timer, which I've called 'indirect-call-timeout', is used for
inferior function calls from breakpoint conditions.  This timeout has
a default value of 30 seconds.  This is a reasonably long time to
wait, and hopefully should be enough in most cases to allow the
inferior call to complete.  An inferior call that takes more than 30
seconds, which is installed on a breakpoint condition is really going
to slow down the debug session, so hopefully this is not a common use
case.

The user is, of course, free to reduce, or increase the timeout value,
and can always use Ctrl-c to interrupt an inferior function call, but
this timeout will ensure that GDB will stop at some point.

The new commands added by this commit are:

  set direct-call-timeout SECONDS
  show direct-call-timeout
  set indirect-call-timeout SECONDS
  show indirect-call-timeout

These new timeouts do depend on async-mode, so, if async-mode is
disabled (maint set target-async off), or not supported (e.g. target
sim), then the timeout is treated as unlimited (that is, no timeout is
set).

For targets that "fake" non-async mode, e.g. Linux native, where
non-async mode is really just async mode, but then we park the target
in a sissuspend, we could easily fix things so that the timeouts still
work, however, for targets that really are not async aware, like the
simulator, fixing things so that timeouts work correctly would be a
much bigger task - that effort would be better spent just making the
target async-aware.  And so, I'm happy for now that this feature will
only work on async targets.

The two new show commands will display slightly different text if the
current target is a non-async target, which should allow users to
understand what's going on.

There's a somewhat random test adjustment needed in gdb.base/help.exp,
the test uses a regexp with the apropos command, and expects to find a
single result.  Turns out the new settings I added also matched the
regexp, which broke the test.  I've updated the regexp a little to
exclude my new settings.

Reviewed-By: Tankut Baris Aktemur <tankut.baris.aktemur@intel.com>
Reviewed-By: Eli Zaretskii <eliz@gnu.org>
---
 gdb/NEWS                                      |  18 ++
 gdb/doc/gdb.texinfo                           |  66 ++++++
 gdb/infcall.c                                 | 210 +++++++++++++++++-
 gdb/testsuite/gdb.base/help.exp               |   2 +-
 gdb/testsuite/gdb.base/infcall-timeout.c      |  36 +++
 gdb/testsuite/gdb.base/infcall-timeout.exp    |  94 ++++++++
 .../infcall-from-bp-cond-timeout.c            | 169 ++++++++++++++
 .../infcall-from-bp-cond-timeout.exp          | 166 ++++++++++++++
 8 files changed, 756 insertions(+), 5 deletions(-)
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.c
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp

diff --git a/gdb/NEWS b/gdb/NEWS
index 11cd6c0663e..694189910dc 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -43,6 +43,24 @@ set remote thread-options-packet
 show remote thread-options-packet
   Set/show the use of the thread options packet.
 
+set direct-call-timeout SECONDS
+show direct-call-timeout
+set indirect-call-timeout SECONDS
+show indirect-call-timeout
+  These new settings can be used to limit how long GDB will wait for
+  an inferior function call to complete.  The direct timeout is used
+  for inferior function calls from e.g. 'call' and 'print' commands,
+  while the indirect timeout is used for inferior function calls from
+  within a conditional breakpoint expression.
+
+  The default for the direct timeout is unlimited, while the default
+  for the indirect timeout is 30 seconds.
+
+  These timeouts will only have an effect for targets that are
+  operating in async mode.  For non-async targets the timeouts are
+  ignored, GDB will wait indefinitely for an inferior function to
+  complete, unless interrupted by the user using Ctrl-C.
+
 * New features in the GDB remote stub, GDBserver
 
   ** The --remote-debug and --event-loop-debug command line options
diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index 4ada257d256..9e4fdc8a2cd 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -20999,6 +20999,72 @@
 @code{step}, etc).  In this case, when the inferior finally returns to
 the dummy-frame, @value{GDBN} will once again halt the inferior.
 
+On targets that support asynchronous execution (@pxref{Background
+Execution}) @value{GDBN} can place a timeout on any functions called
+from @value{GDBN}.  If the timeout expires and the function call is
+still ongoing, then @value{GDBN} will interrupt the program.
+
+For targets that don't support asynchronous execution
+(@pxref{Background Execution}) then timeouts for functions called from
+@value{GDBN} are not supported, the timeout settings described below
+will be treated as @code{unlimited}, meaning @value{GDBN} will wait
+indefinitely for function call to complete, unless interrupted by the
+user using @kbd{Ctrl-C}.
+
+@table @code
+@item set direct-call-timeout @var{seconds}
+@kindex set direct-call-timeout
+@cindex timeout for called functions
+Set the timeout used when calling functions in the program to
+@var{seconds}, which should be an integer greater than zero, or the
+special value @code{unlimited}, which indicates no timeout should be
+used.  The default for this setting is @code{unlimited}.
+
+This setting is used when the user calls a function directly from the
+command prompt, for example with a @code{call} or @code{print}
+command.
+
+This setting only works for targets that support asynchronous
+execution (@pxref{Background Execution}), for any other target the
+setting is treated as @code{unlimited}.
+
+@item show direct-call-timeout
+@kindex show direct-call-timeout
+@cindex timeout for called functions
+Show the timeout used when calling functions in the program with a
+@code{call} or @code{print} command.
+@end table
+
+It is also possible to call functions within the program from the
+condition of a conditional breakpoint (@pxref{Conditions, ,Break
+Conditions}).  A different setting controls the timeout used for
+function calls made from a breakpoint condition.
+
+@table @code
+@item set indirect-call-timeout @var{seconds}
+@kindex set indirect-call-timeout
+@cindex timeout for called functions
+Set the timeout used when calling functions in the program from a
+breakpoint or watchpoint condition to @var{seconds}, which should be
+an integer greater than zero, or the special value @code{unlimited},
+which indicates no timeout should be used.  The default for this
+setting is @code{30} seconds.
+
+This setting only works for targets that support asynchronous
+execution (@pxref{Background Execution}), for any other target the
+setting is treated as @code{unlimited}.
+
+If a function called from a breakpoint or watchpoint condition times
+out, then @value{GDBN} will stop at the point where the timeout
+occurred.  The breakpoint condition evaluation will be abandoned.
+
+@item show indirect-call-timeout
+@kindex show indirect-call-timeout
+@cindex timeout for called functions
+Show the timeout used when calling functions in the program from a
+breakpoint or watchpoint condition.
+@end table
+
 @subsection Calling functions with no debug info
 
 @cindex no debug info functions
diff --git a/gdb/infcall.c b/gdb/infcall.c
index 935a555e817..a295b1e7090 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -96,6 +96,53 @@ show_may_call_functions_p (struct ui_file *file, int from_tty,
 	      value);
 }
 
+/* A timeout (in seconds) for direct inferior calls.  A direct inferior
+   call is one the user triggers from the prompt, e.g. with a 'call' or
+   'print' command.  Compare with the definition of indirect calls below.  */
+
+static unsigned int direct_call_timeout = UINT_MAX;
+
+/* Implement 'show direct-call-timeout'.  */
+
+static void
+show_direct_call_timeout (struct ui_file *file, int from_tty,
+			  struct cmd_list_element *c, const char *value)
+{
+  if (target_has_execution () && !target_can_async_p ())
+    gdb_printf (file, _("Current target does not support async mode, timeout "
+			"for direct inferior calls is \"unlimited\".\n"));
+  else if (direct_call_timeout == UINT_MAX)
+    gdb_printf (file, _("Timeout for direct inferior function calls "
+			"is \"unlimited\".\n"));
+  else
+    gdb_printf (file, _("Timeout for direct inferior function calls "
+			"is \"%s seconds\".\n"), value);
+}
+
+/* A timeout (in seconds) for indirect inferior calls.  An indirect inferior
+   call is one that originates from within GDB, for example, when
+   evaluating an expression for a conditional breakpoint.  Compare with
+   the definition of direct calls above.  */
+
+static unsigned int indirect_call_timeout = 30;
+
+/* Implement 'show indirect-call-timeout'.  */
+
+static void
+show_indirect_call_timeout (struct ui_file *file, int from_tty,
+			  struct cmd_list_element *c, const char *value)
+{
+  if (target_has_execution () && !target_can_async_p ())
+    gdb_printf (file, _("Current target does not support async mode, timeout "
+			"for indirect inferior calls is \"unlimited\".\n"));
+  else if (indirect_call_timeout == UINT_MAX)
+    gdb_printf (file, _("Timeout for indirect inferior function calls "
+			"is \"unlimited\".\n"));
+  else
+    gdb_printf (file, _("Timeout for indirect inferior function calls "
+			"is \"%s seconds\".\n"), value);
+}
+
 /* How you should pass arguments to a function depends on whether it
    was defined in K&R style or prototype style.  If you define a
    function using the K&R syntax that takes a `float' argument, then
@@ -620,6 +667,85 @@ call_thread_fsm::should_notify_stop ()
   return true;
 }
 
+/* A class to control creation of a timer that will interrupt a thread
+   during an inferior call.  */
+struct infcall_timer_controller
+{
+  /* Setup an event-loop timer that will interrupt PTID if the inferior
+     call takes too long.  DIRECT_CALL_P is true when this inferior call is
+     a result of the user using a 'print' or 'call' command, and false when
+     this inferior call is a result of e.g. a conditional breakpoint
+     expression, this is used to select which timeout to use.  */
+  infcall_timer_controller (thread_info *thr, bool direct_call_p)
+    : m_thread (thr)
+  {
+    unsigned int timeout
+      = direct_call_p ? direct_call_timeout : indirect_call_timeout;
+    if (timeout < UINT_MAX && target_can_async_p ())
+      {
+	int ms = timeout * 1000;
+	int id = create_timer (ms, infcall_timer_controller::timed_out, this);
+	m_timer_id.emplace (id);
+	infcall_debug_printf ("Setting up infcall timeout timer for "
+			      "ptid %s: %d milliseconds",
+			      m_thread->ptid.to_string ().c_str (), ms);
+      }
+  }
+
+  /* Destructor.  Ensure that the timer is removed from the event loop.  */
+  ~infcall_timer_controller ()
+  {
+    /* If the timer has already triggered, then it will have already been
+       deleted from the event loop.  If the timer has not triggered, then
+       delete it now.  */
+    if (m_timer_id.has_value () && !m_triggered)
+      delete_timer (*m_timer_id);
+
+    /* Just for clarity, discard the timer id now.  */
+    m_timer_id.reset ();
+  }
+
+  /* Return true if there was a timer in place, and the timer triggered,
+     otherwise, return false.  */
+  bool triggered_p ()
+  {
+    gdb_assert (!m_triggered || m_timer_id.has_value ());
+    return m_triggered;
+  }
+
+private:
+  /* The thread we should interrupt.  */
+  thread_info *m_thread;
+
+  /* Set true when the timer is triggered.  */
+  bool m_triggered = false;
+
+  /* Given a value when a timer is in place.  */
+  std::optional<int> m_timer_id;
+
+  /* Callback for the timer, forwards to ::trigger below.  */
+  static void
+  timed_out (gdb_client_data context)
+  {
+    infcall_timer_controller *ctrl
+      = static_cast<infcall_timer_controller *> (context);
+    ctrl->trigger ();
+  }
+
+  /* Called when the timer goes off.  Stop thread M_THREAD.  */
+  void
+  trigger ()
+  {
+    m_triggered = true;
+
+    scoped_disable_commit_resumed disable_commit_resumed ("infcall timeout");
+
+    infcall_debug_printf ("Stopping thread %s",
+			  m_thread->ptid.to_string ().c_str ());
+    target_stop (m_thread->ptid);
+  }
+};
+
 /* Subroutine of call_function_by_hand to simplify it.
    Start up the inferior and wait for it to stop.
    Return the exception if there's an error, or an exception with
@@ -630,13 +756,15 @@ call_thread_fsm::should_notify_stop ()
 
 static struct gdb_exception
 run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
-		   struct thread_info *call_thread, CORE_ADDR real_pc)
+		   struct thread_info *call_thread, CORE_ADDR real_pc,
+		   bool *timed_out_p)
 {
   INFCALL_SCOPED_DEBUG_ENTER_EXIT;
 
   struct gdb_exception caught_error;
   ptid_t call_thread_ptid = call_thread->ptid;
   int was_running = call_thread->state == THREAD_RUNNING;
+  *timed_out_p = false;
 
   infcall_debug_printf ("call function at %s in thread %s, was_running = %d",
 			core_addr_to_string (real_pc),
@@ -681,11 +809,23 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
       infrun_debug_show_threads ("non-exited threads after proceed for inferior-call",
 				 all_non_exited_threads ());
 
+      /* Setup a timer (if possible, and if the settings allow) to prevent
+	 the inferior call running forever.  */
+      bool direct_call_p = !call_thread->control.in_cond_eval;
+      infcall_timer_controller infcall_timer (call_thread, direct_call_p);
+
       /* Inferior function calls are always synchronous, even if the
 	 target supports asynchronous execution.  */
       wait_sync_command_done ();
 
-      infcall_debug_printf ("inferior call completed successfully");
+      /* If the timer triggered then the inferior call failed.  */
+      if (infcall_timer.triggered_p ())
+	{
+	  infcall_debug_printf ("inferior call timed out");
+	  *timed_out_p = true;
+	}
+      else
+	infcall_debug_printf ("inferior call completed successfully");
     }
   catch (gdb_exception &e)
     {
@@ -1358,6 +1498,10 @@ call_function_by_hand_dummy (struct value *function,
   scoped_restore restore_stopped_by_random_signal
     = make_scoped_restore (&stopped_by_random_signal, 0);
 
+  /* Set to true by the call to run_inferior_call below if the inferior
+     call is artificially interrupted by GDB due to taking too long.  */
+  bool timed_out_p = false;
+
   /* - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP -
      If you're looking to implement asynchronous dummy-frames, then
      just below is the place to chop this function in two..  */
@@ -1384,7 +1528,8 @@ call_function_by_hand_dummy (struct value *function,
 			      struct_addr);
     {
       std::unique_ptr<call_thread_fsm> sm_up (sm);
-      e = run_inferior_call (std::move (sm_up), call_thread.get (), real_pc);
+      e = run_inferior_call (std::move (sm_up), call_thread.get (), real_pc,
+			     &timed_out_p);
     }
 
     if (e.reason < 0)
@@ -1543,7 +1688,10 @@ When the function is done executing, GDB will silently stop."),
       std::string name = get_function_name (funaddr, name_buf,
 					    sizeof (name_buf));
 
-      if (stopped_by_random_signal)
+      /* If the inferior call timed out then it will have been interrupted
+	 by a signal, but we want to report this differently to the user,
+	 which is done later in this function.  */
+      if (stopped_by_random_signal && !timed_out_p)
 	{
 	  /* We stopped inside the FUNCTION because of a random
 	     signal.  Further execution of the FUNCTION is not
@@ -1594,6 +1742,36 @@ GDB remains in the frame where the signal was received.\n\
 To change this behavior use \"set unwindonsignal on\".\n\
 Evaluation of the expression containing the function\n\
 (%s) will be abandoned.\n\
+When the function is done executing, GDB will silently stop."),
+		     name.c_str ());
+	    }
+	}
+
+      if (timed_out_p)
+	{
+	  /* A timeout results in a signal being sent to the inferior.  */
+	  gdb_assert (stopped_by_random_signal);
+
+	  /* Indentation is weird here.  A later patch is going to move the
+	    following block into an if/else, so I'm leaving the indentation
+	    here to minimise the later patch.
+
+	    Also, the error message used below refers to 'set
+	    unwind-on-timeout' which doesn't exist yet.  This will be added
+	    in a later commit, I'm leaving this in for now to minimise the
+	    churn caused by the commit that adds unwind-on-timeout.  */
+	    {
+	      /* The user wants to stay in the frame where we stopped
+		 (default).  Discard inferior status, we're not at the same
+		 point we started at.  */
+	      discard_infcall_control_state (inf_status.release ());
+
+	      error (_("\
+The program being debugged timed out while in a function called from GDB.\n\
+GDB remains in the frame where the timeout occurred.\n\
+To change this behavior use \"set unwind-on-timeout on\".\n\
+Evaluation of the expression containing the function\n\
+(%s) will be abandoned.\n\
 When the function is done executing, GDB will silently stop."),
 		     name.c_str ());
 	    }
@@ -1707,6 +1885,30 @@ The default is to unwind the frame."),
 			   show_unwind_on_terminating_exception_p,
 			   &setlist, &showlist);
 
+  add_setshow_uinteger_cmd ("direct-call-timeout", no_class,
+			    &direct_call_timeout, _("\
+Set the timeout, for direct calls to inferior function calls."), _("\
+Show the timeout, for direct calls to inferior function calls."), _("\
+If running on a target that supports, and is running in, async mode\n\
+then this timeout is used for any inferior function calls triggered\n\
+directly from the prompt, i.e. from a 'call' or 'print' command.  The\n\
+timeout is specified in seconds."),
+			    nullptr,
+			    show_direct_call_timeout,
+			    &setlist, &showlist);
+
+  add_setshow_uinteger_cmd ("indirect-call-timeout", no_class,
+			    &indirect_call_timeout, _("\
+Set the timeout, for indirect calls to inferior function calls."), _("\
+Show the timeout, for indirect calls to inferior function calls."), _("\
+If running on a target that supports, and is running in, async mode\n\
+then this timeout is used for any inferior function calls triggered\n\
+indirectly, i.e. being made as part of a breakpoint, or watchpoint,\n\
+condition expression.  The timeout is specified in seconds."),
+			    nullptr,
+			    show_indirect_call_timeout,
+			    &setlist, &showlist);
+
   add_setshow_boolean_cmd
     ("infcall", class_maintenance, &debug_infcall,
      _("Set inferior call debugging."),
diff --git a/gdb/testsuite/gdb.base/help.exp b/gdb/testsuite/gdb.base/help.exp
index 87919a819ab..504bf90cc15 100644
--- a/gdb/testsuite/gdb.base/help.exp
+++ b/gdb/testsuite/gdb.base/help.exp
@@ -121,7 +121,7 @@ gdb_test "help info bogus-gdb-command" "Undefined info command: \"bogus-gdb-comm
 gdb_test "help gotcha" "Undefined command: \"gotcha\"\.  Try \"help\"\."
 
 # Test apropos regex.
-gdb_test "apropos \\\(print\[\^\[ bsiedf\\\".-\]\\\)" "handle -- Specify how to handle signals\."
+gdb_test "apropos \\\(print\[\^\[ bsiedf\\\"'.-\]\\\)" "handle -- Specify how to handle signals\."
 # Test apropos >1 word string.
 gdb_test "apropos handle signal" "handle -- Specify how to handle signals\."
 # Test apropos apropos.
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.c b/gdb/testsuite/gdb.base/infcall-timeout.c
new file mode 100644
index 00000000000..61f64c53129
--- /dev/null
+++ b/gdb/testsuite/gdb.base/infcall-timeout.c
@@ -0,0 +1,36 @@
+/* Copyright 2022-2024 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 <unistd.h>
+
+/* This function is called from GDB.  */
+int
+function_that_never_returns ()
+{
+  while (1)
+    sleep (1);
+
+  return 0;
+}
+
+int
+main ()
+{
+  alarm (300);
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.exp b/gdb/testsuite/gdb.base/infcall-timeout.exp
new file mode 100644
index 00000000000..e6a03b2ac6b
--- /dev/null
+++ b/gdb/testsuite/gdb.base/infcall-timeout.exp
@@ -0,0 +1,94 @@
+# Copyright 2022-2024 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/>.
+
+# Test GDB's direct-call-timeout setting, that is, ensure that if an
+# inferior function call, invoked from e.g. a 'print' command, takes
+# too long, then GDB can interrupt it, and return control to the user.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug}] == -1 } {
+    return
+}
+
+# Start GDB according to TARGET_ASYNC, TARGET_NON_STOP, and NON_STOP,
+# then adjust the direct-call-timeout, and make an inferior function
+# call that will never return.  GDB should eventually timeout and stop
+# the inferior.
+proc run_test { target_async target_non_stop non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"set non-stop $non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if {![runto_main]} {
+	return
+    }
+
+    gdb_test_no_output "set direct-call-timeout 5"
+
+    # When non-stop mode is off we get slightly different output from GDB.
+    if { ([target_info gdb_protocol] == "remote"
+	  || [target_info gdb_protocol] == "extended-remote")
+	 && !$target_non_stop } {
+	set stopped_line_pattern "Program received signal SIGINT, Interrupt\\."
+    } else {
+	set stopped_line_pattern "Program stopped\\."
+    }
+
+    gdb_test "print function_that_never_returns ()" \
+	[multi_line \
+	     $stopped_line_pattern \
+	     ".*" \
+	     "The program being debugged timed out while in a function called from GDB\\." \
+	     "GDB remains in the frame where the timeout occurred\\." \
+	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(function_that_never_returns\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+
+    gdb_test "bt" ".* function_that_never_returns .*<function called from gdb>.*"
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+
+    if { !$target_async } {
+	# GDB can't timeout while waiting for a thread if the target
+	# runs with async-mode turned off; once the target is running
+	# GDB is effectively blocked until the target stops for some
+	# reason.
+	continue
+    }
+
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	foreach_with_prefix non_stop { "on" "off" } {
+	    if { $non_stop && !$target_non_stop } {
+		# It doesn't make sense to operate GDB in non-stop
+		# mode when the target has (in theory) non-stop mode
+		# disabled.
+		continue
+	    }
+
+	    run_test $target_async $target_non_stop $non_stop
+	}
+    }
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
new file mode 100644
index 00000000000..415eaea8ccb
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
@@ -0,0 +1,169 @@
+/* This testcase is part of GDB, the GNU debugger.
+
+   Copyright 2022-2024 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 <stdio.h>
+#include <pthread.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <semaphore.h>
+
+#define NUM_THREADS 5
+
+/* Semaphores, used to track when threads have started, and to control
+   when the threads finish.  */
+sem_t startup_semaphore;
+sem_t finish_semaphore;
+sem_t thread_1_semaphore;
+sem_t thread_2_semaphore;
+
+/* Mutex to control when the first worker thread hit a breakpoint
+   location.  */
+pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+
+/* Global variable to poke, just so threads have something to do.  */
+volatile int global_var = 0;
+
+int
+condition_func ()
+{
+  /* Let thread 2 run.  */
+  if (sem_post (&thread_2_semaphore) != 0)
+    abort ();
+
+  /* Wait for thread 2 to complete its actions.  */
+  if (sem_wait (&thread_1_semaphore) != 0)
+    abort ();
+
+  return 1;
+}
+
+void
+do_segfault ()
+{
+  volatile int *p = 0;
+  *p = 0;	/* Segfault here.  */
+}
+
+void *
+worker_func (void *arg)
+{
+  int tid = *((int *) arg);
+
+  /* Let the main thread know that this worker has started.  */
+  if (sem_post (&startup_semaphore) != 0)
+    abort ();
+
+  switch (tid)
+    {
+    case 0:
+      /* Wait for MUTEX to become available, then pass through the
+	 conditional breakpoint location.  */
+      if (pthread_mutex_lock (&mutex) != 0)
+	abort ();
+      global_var = 99;	/* Conditional breakpoint here.  */
+      if (pthread_mutex_unlock (&mutex) != 0)
+	abort ();
+      break;
+
+    case 1:
+      if (sem_wait (&thread_2_semaphore) != 0)
+	abort ();
+      do_segfault ();
+      if (sem_post (&thread_1_semaphore) != 0)
+	abort ();
+
+      /* Fall through.  */
+    default:
+      /* Wait until we are allowed to finish.  */
+      if (sem_wait (&finish_semaphore) != 0)
+	abort ();
+      break;
+    }
+}
+
+void
+stop_marker ()
+{
+  global_var = 99;	/* Stop marker.  */
+}
+
+/* The main program entry point.  */
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+  void *retval;
+
+  /* An alarm, just in case the thread deadlocks.  */
+  alarm (300);
+
+  /* Semaphore initialization.  */
+  if (sem_init (&startup_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&finish_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&thread_1_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&thread_2_semaphore, 0, 0) != 0)
+    abort ();
+
+  /* Lock MUTEX, this prevents the first worker thread from rushing ahead.  */
+  if (pthread_mutex_lock (&mutex) != 0)
+    abort ();
+
+  /* Worker thread creation.  */
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  /* Wait for every thread to start.  */
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      if (sem_wait (&startup_semaphore) != 0)
+	abort ();
+    }
+
+  /* Unlock the first thread so it can proceed.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  /* Wait for the first thread only.  */
+  pthread_join (threads[0], &retval);
+
+  /* Now post FINISH_SEMAPHORE to allow all the other threads to finish.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    sem_post (&finish_semaphore);
+
+  /* Now wait for the remaining threads to complete.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    pthread_join (threads[i], &retval);
+
+  /* Semaphore cleanup.  */
+  sem_destroy (&finish_semaphore);
+  sem_destroy (&startup_semaphore);
+  sem_destroy (&thread_1_semaphore);
+  sem_destroy (&thread_2_semaphore);
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
new file mode 100644
index 00000000000..67dabce66ee
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
@@ -0,0 +1,166 @@
+# Copyright 2022-2024 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 inferior calls executed from a breakpoint condition in
+# a multi-threaded program.
+#
+# This test has the inferior function call timeout, and checks how GDB
+# handles this situation.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "Conditional breakpoint here"]
+set final_bp_line [gdb_get_line_number "Stop marker"]
+set segfault_line [gdb_get_line_number "Segfault here"]
+
+# Setup GDB based on TARGET_ASYNC, TARGET_NON_STOP, and NON_STOP.
+# Setup some breakpoints in the inferior, one of which has an inferior
+# call within its condition.
+#
+# Continue GDB, the breakpoint with inferior call will be hit, but the
+# inferior call will never return.  We expect GDB to timeout.
+#
+# The reason that the inferior call never completes is that a second
+# thread, on which the inferior call relies, either hits a breakpoint
+# (when OTHER_THREAD_BP is true), or crashes (when OTHER_THREAD_BP is
+# false).
+proc run_test { target_async target_non_stop non_stop other_thread_bp } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS " -ex \"maint non-stop $non_stop\""
+	append ::GDBFLAGS " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if {![runto_main]} {
+	return
+    }
+
+    # The default timeout for indirect inferior calls (e.g. inferior
+    # calls for conditional breakpoint expressions) is pretty high.
+    # We don't want the test to take too long, so reduce this.
+    #
+    # However, the test relies on a second thread hitting some event
+    # (either a breakpoint or signal) before this timeout expires.
+    #
+    # There is a chance that on a really slow system this might not
+    # happen, in which case the test might fail.
+    #
+    # However, we still allocate 5 seconds, which feels like it should
+    # be enough time in most cases, but maybe we need to do something
+    # smarter here?  Possibly we could have some initial run where the
+    # inferior doesn't timeout, but does perform the same interaction
+    # between threads, we could time that, and use that as the basis
+    # for this timeout.  For now though, we just hope 5 seconds is
+    # enough.
+    gdb_test_no_output "set indirect-call-timeout 5"
+
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (condition_func ())"
+    set bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		    "get number for conditional breakpoint"]
+
+    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
+    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			  "get number for final breakpoint"]
+
+    # The thread performing an inferior call relies on a second
+    # thread.  The second thread will segfault unless it hits a
+    # breakpoint first.  In either case the initial thread will not
+    # complete its inferior call.
+    if { $other_thread_bp } {
+	gdb_breakpoint "${::srcfile}:${::segfault_line}"
+	set segfault_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+				 "get number for segfault breakpoint"]
+    }
+
+    # When non-stop mode is off we get slightly different output from GDB.
+    if { ([target_info gdb_protocol] == "remote"
+	  || [target_info gdb_protocol] == "extended-remote")
+	 && !$target_non_stop} {
+	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" received signal SIGINT, Interrupt\\."
+    } else {
+	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\."
+    }
+
+    gdb_test "continue" \
+	[multi_line \
+	     $stopped_line_pattern \
+	     ".*" \
+	     "Error in testing condition for breakpoint ${bp_num}:" \
+	     "The program being debugged timed out while in a function called from GDB\\." \
+	     "GDB remains in the frame where the timeout occurred\\." \
+	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(condition_func\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."] \
+	"expected timeout waiting for inferior call to complete"
+
+    # Remember that other thread that either crashed (with a segfault)
+    # or hit a breakpoint?  Now that the inferior call has timed out,
+    # if we try to resume then we should see the pending event from
+    # that other thread.
+    if { $other_thread_bp } {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${segfault_bp_num}, do_segfault \[^\r\n\]+:${::segfault_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"] \
+	    "hit the segfault breakpoint"
+    } else {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "Thread ${::decimal} \"infcall-from-bp\" received signal SIGSEGV, Segmentation fault\\." \
+		 "\\\[Switching to Thread \[^\r\n\]+\\\]" \
+		 "${::hex} in do_segfault \\(\\) at \[^\r\n\]+:${::segfault_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"] \
+	    "hit the segfault"
+    }
+}
+
+foreach_with_prefix target_async {"on" "off" } {
+
+    if { !$target_async } {
+	# GDB can't timeout while waiting for a thread if the target
+	# runs with async-mode turned off; once the target is running
+	# GDB is effectively blocked until the target stops for some
+	# reason.
+	continue
+    }
+
+    foreach_with_prefix target_non_stop {"off" "on"} {
+	foreach_with_prefix non_stop {"off" "on"} {
+	    if { $non_stop && !$target_non_stop } {
+		# It doesn't make sense to operate GDB in non-stop
+		# mode when the target has (in theory) non-stop mode
+		# disabled.
+		continue
+	    }
+	    foreach_with_prefix other_thread_bp { true false } {
+		run_test $target_async $target_non_stop $non_stop $other_thread_bp
+	    }
+	}
+    }
+}
-- 
2.25.4


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

* [PATCHv10 4/5] gdb: introduce unwind-on-timeout setting
  2024-01-02 15:57                 ` [PATCHv10 0/5] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                                     ` (2 preceding siblings ...)
  2024-01-02 15:57                   ` [PATCHv10 3/5] gdb: add timeouts for inferior function calls Andrew Burgess
@ 2024-01-02 15:57                   ` Andrew Burgess
  2024-01-02 15:57                   ` [PATCHv10 5/5] gdb: rename unwindonsignal to unwind-on-signal Andrew Burgess
  2024-03-05 15:40                   ` [PATCHv11 0/5] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
  5 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2024-01-02 15:57 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Eli Zaretskii

Eli has already approved the NEWS/doc changes in this file.

---

Now that inferior function calls can timeout (see the recent
introduction of direct-call-timeout and indirect-call-timeout), this
commit adds a new setting unwind-on-timeout.

This new setting is just like the existing unwindonsignal and
unwind-on-terminating-exception, but the new setting will cause GDB to
unwind the stack if an inferior function call times out.

The existing inferior function call timeout tests have been updated to
cover the new setting.

Reviewed-By: Eli Zaretskii <eliz@gnu.org>
---
 gdb/NEWS                                      |  9 +++
 gdb/doc/gdb.texinfo                           | 31 ++++++--
 gdb/infcall.c                                 | 78 +++++++++++++++++--
 gdb/testsuite/gdb.base/infcall-timeout.exp    | 63 ++++++++++-----
 .../infcall-from-bp-cond-timeout.exp          | 69 ++++++++++------
 5 files changed, 194 insertions(+), 56 deletions(-)

diff --git a/gdb/NEWS b/gdb/NEWS
index 694189910dc..4ba8f62a8b3 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -61,6 +61,15 @@ show indirect-call-timeout
   ignored, GDB will wait indefinitely for an inferior function to
   complete, unless interrupted by the user using Ctrl-C.
 
+set unwind-on-timeout on|off
+show unwind-on-timeout
+  These commands control whether GDB should unwind the stack when a
+  timeout occurs during an inferior function call.  The default is
+  off, in which case the inferior will remain in the frame where the
+  timeout occurred.  When on, GDB will unwind the stack removing the
+  dummy frame that was added for the inferior call, and restoring the
+  inferior state to how it was before the inferior call started.
+
 * New features in the GDB remote stub, GDBserver
 
   ** The --remote-debug and --event-loop-debug command line options
diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index 9e4fdc8a2cd..6f847295e28 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -20944,6 +20944,22 @@
 Show the current setting of stack unwinding in the functions called by
 @value{GDBN}.
 
+@anchor{set unwind-on-timeout}
+@item set unwind-on-timeout
+@kindex set unwind-on-timeout
+@cindex unwind stack in called functions when timing out
+@cindex call dummy stack unwinding on timeout.
+Set unwinding of the stack if a function called from @value{GDBN}
+times out.  If set to @code{off} (the default), @value{GDBN} stops in
+the frame where the timeout occurred.  If set to @code{on},
+@value{GDBN} unwinds the stack it created for the call and restores
+the context to what it was before the call.
+
+@item show unwind-on-timeout
+@kindex show unwind-on-timeout
+Show whether @value{GDBN} will unwind the stack if a function called
+from @value{GDBN} times out.
+
 @item set may-call-functions
 @kindex set may-call-functions
 @cindex disabling calling functions in the program
@@ -20975,11 +20991,11 @@
 
 If a called function is interrupted for any reason, including hitting
 a breakpoint, or triggering a watchpoint, and the stack is not unwound
-due to @code{set unwind-on-terminating-exception on} or @code{set
-unwindonsignal on} (@pxref{stack unwind settings}),
-then the dummy-frame, created by @value{GDBN} to facilitate the call
-to the program function, will be visible in the backtrace, for example
-frame @code{#3} in the following backtrace:
+due to @code{set unwind-on-terminating-exception on}, @code{set
+unwind-on-timeout on}, or @code{set unwindonsignal on} (@pxref{stack
+unwind settings}), then the dummy-frame, created by @value{GDBN} to
+facilitate the call to the program function, will be visible in the
+backtrace, for example frame @code{#3} in the following backtrace:
 
 @smallexample
 (@value{GDBP}) backtrace
@@ -21004,6 +21020,11 @@
 from @value{GDBN}.  If the timeout expires and the function call is
 still ongoing, then @value{GDBN} will interrupt the program.
 
+If a function called from @value{GDBN} is interrupted by a timeout,
+then by default the inferior is left in the frame where the timeout
+occurred, this behaviour can be adjusted with @samp{set
+unwind-on-timeout} (@pxref{set unwind-on-timeout}).
+
 For targets that don't support asynchronous execution
 (@pxref{Background Execution}) then timeouts for functions called from
 @value{GDBN} are not supported, the timeout settings described below
diff --git a/gdb/infcall.c b/gdb/infcall.c
index a295b1e7090..84c6bf2cdd2 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -218,6 +218,27 @@ show_unwind_on_terminating_exception_p (struct ui_file *file, int from_tty,
 	      value);
 }
 
+/* This boolean tells GDB what to do if an inferior function, called from
+   GDB, times out.  If true, GDB unwinds the stack and restores the context
+   to what it was before the call.  When false, GDB leaves the thread as it
+   is at the point of the timeout.
+
+   The default is to stop in the frame where the timeout occurred.  */
+
+static bool unwind_on_timeout_p = false;
+
+/* Implement 'show unwind-on-timeout'.  */
+
+static void
+show_unwind_on_timeout_p (struct ui_file *file, int from_tty,
+			  struct cmd_list_element *c, const char *value)
+{
+  gdb_printf (file,
+	      _("Unwinding of stack if a timeout occurs "
+		"while in a call dummy is %s.\n"),
+	      value);
+}
+
 /* Perform the standard coercions that are specified
    for arguments to be passed to C, Ada or Fortran functions.
 
@@ -574,6 +595,16 @@ struct call_thread_fsm : public thread_fsm
   bool should_stop (struct thread_info *thread) override;
 
   bool should_notify_stop () override;
+
+  /* Record that this thread timed out while performing an infcall.  */
+  void timed_out ()
+  {
+    m_timed_out = true;
+  }
+
+private:
+  /* Set true if the thread timed out while performing an infcall.  */
+  bool m_timed_out = false;
 };
 
 /* Allocate a new call_thread_fsm object.  */
@@ -649,7 +680,8 @@ call_thread_fsm::should_notify_stop ()
 
   infcall_debug_printf ("inferior call didn't complete fully");
 
-  if (stopped_by_random_signal && unwind_on_signal_p)
+  if ((stopped_by_random_signal && unwind_on_signal_p)
+      || (m_timed_out && unwind_on_timeout_p))
     {
       infcall_debug_printf ("unwind-on-signal is on, don't notify");
       return false;
@@ -742,6 +774,9 @@ struct infcall_timer_controller
 
     infcall_debug_printf ("Stopping thread %s",
 			  m_thread->ptid.to_string ().c_str ());
+    call_thread_fsm *fsm
+      = gdb::checked_static_cast<call_thread_fsm *> (m_thread->thread_fsm ());
+    fsm->timed_out ();
     target_stop (m_thread->ptid);
   }
 };
@@ -1752,14 +1787,27 @@ When the function is done executing, GDB will silently stop."),
 	  /* A timeout results in a signal being sent to the inferior.  */
 	  gdb_assert (stopped_by_random_signal);
 
-	  /* Indentation is weird here.  A later patch is going to move the
-	    following block into an if/else, so I'm leaving the indentation
-	    here to minimise the later patch.
+	  if (unwind_on_timeout_p)
+	    {
+	      /* The user wants the context restored.  */
+
+	      /* We must get back to the frame we were before the
+		 dummy call.  */
+	      dummy_frame_pop (dummy_id, call_thread.get ());
 
-	    Also, the error message used below refers to 'set
-	    unwind-on-timeout' which doesn't exist yet.  This will be added
-	    in a later commit, I'm leaving this in for now to minimise the
-	    churn caused by the commit that adds unwind-on-timeout.  */
+	      /* We also need to restore inferior status to that before the
+		 dummy call.  */
+	      restore_infcall_control_state (inf_status.release ());
+
+	      error (_("\
+The program being debugged timed out while in a function called from GDB.\n\
+GDB has restored the context to what it was before the call.\n\
+To change this behavior use \"set unwind-on-timeout off\".\n\
+Evaluation of the expression containing the function\n\
+(%s) will be abandoned."),
+		     name.c_str ());
+	    }
+	  else
 	    {
 	      /* The user wants to stay in the frame where we stopped
 		 (default).  Discard inferior status, we're not at the same
@@ -1885,6 +1933,20 @@ The default is to unwind the frame."),
 			   show_unwind_on_terminating_exception_p,
 			   &setlist, &showlist);
 
+  add_setshow_boolean_cmd ("unwind-on-timeout", no_class,
+			   &unwind_on_timeout_p, _("\
+Set unwinding of stack if a timeout occurs while in a call dummy."), _("\
+Show unwinding of stack if a timeout occurs while in a call dummy."),
+			   _("\
+The unwind on timeout flag lets the user determine what gdb should do if\n\
+gdb times out while in a function called from gdb.  If set, gdb unwinds\n\
+the stack and restores the context to what it was before the call.  If\n\
+unset, gdb leaves the inferior in the frame where the timeout occurred.\n\
+The default is to stop in the frame where the timeout occurred."),
+			   NULL,
+			   show_unwind_on_timeout_p,
+			   &setlist, &showlist);
+
   add_setshow_uinteger_cmd ("direct-call-timeout", no_class,
 			    &direct_call_timeout, _("\
 Set the timeout, for direct calls to inferior function calls."), _("\
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.exp b/gdb/testsuite/gdb.base/infcall-timeout.exp
index e6a03b2ac6b..ad4dbe3b415 100644
--- a/gdb/testsuite/gdb.base/infcall-timeout.exp
+++ b/gdb/testsuite/gdb.base/infcall-timeout.exp
@@ -28,7 +28,11 @@ if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
 # then adjust the direct-call-timeout, and make an inferior function
 # call that will never return.  GDB should eventually timeout and stop
 # the inferior.
-proc run_test { target_async target_non_stop non_stop } {
+#
+# When UNWIND is "off" the inferior wil be left in the frame where the
+# timeout occurs, otherwise, when UNWIND is "on", GDB should unwind
+# back to the frame where the inferior call was made.
+proc run_test { target_async target_non_stop non_stop unwind } {
     save_vars { ::GDBFLAGS } {
 	append ::GDBFLAGS \
 	    " -ex \"maint set target-non-stop $target_non_stop\""
@@ -45,28 +49,43 @@ proc run_test { target_async target_non_stop non_stop } {
     }
 
     gdb_test_no_output "set direct-call-timeout 5"
+    gdb_test_no_output "set unwind-on-timeout $unwind"
+
+    if { $unwind } {
+	gdb_test "print function_that_never_returns ()" \
+	    [multi_line \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB has restored the context to what it was before the call\\." \
+		 "To change this behavior use \"set unwind-on-timeout off\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(function_that_never_returns\\) will be abandoned\\."]
 
-    # When non-stop mode is off we get slightly different output from GDB.
-    if { ([target_info gdb_protocol] == "remote"
-	  || [target_info gdb_protocol] == "extended-remote")
-	 && !$target_non_stop } {
-	set stopped_line_pattern "Program received signal SIGINT, Interrupt\\."
+	gdb_test "bt" \
+	    "#0\\s+main \\(\\).*"
     } else {
-	set stopped_line_pattern "Program stopped\\."
-    }
+	# When non-stop mode is off we get slightly different output from GDB.
+	if { ([target_info gdb_protocol] == "remote"
+	      || [target_info gdb_protocol] == "extended-remote")
+	     && !$target_non_stop } {
+	    set stopped_line_pattern "Program received signal SIGINT, Interrupt\\."
+	} else {
+	    set stopped_line_pattern "Program stopped\\."
+	}
 
-    gdb_test "print function_that_never_returns ()" \
-	[multi_line \
-	     $stopped_line_pattern \
-	     ".*" \
-	     "The program being debugged timed out while in a function called from GDB\\." \
-	     "GDB remains in the frame where the timeout occurred\\." \
-	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
-	     "Evaluation of the expression containing the function" \
-	     "\\(function_that_never_returns\\) will be abandoned\\." \
-	     "When the function is done executing, GDB will silently stop\\."]
-
-    gdb_test "bt" ".* function_that_never_returns .*<function called from gdb>.*"
+	gdb_test "print function_that_never_returns ()" \
+	    [multi_line \
+		 $stopped_line_pattern \
+		 ".*" \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB remains in the frame where the timeout occurred\\." \
+		 "To change this behavior use \"set unwind-on-timeout on\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(function_that_never_returns\\) will be abandoned\\." \
+		 "When the function is done executing, GDB will silently stop\\."]
+
+	gdb_test "bt" \
+	    ".* function_that_never_returns .*<function called from gdb>.*"
+    }
 }
 
 foreach_with_prefix target_async { "on" "off" } {
@@ -88,7 +107,9 @@ foreach_with_prefix target_async { "on" "off" } {
 		continue
 	    }
 
-	    run_test $target_async $target_non_stop $non_stop
+	    foreach_with_prefix unwind { "on" "off" } {
+		run_test $target_async $target_non_stop $non_stop $unwind
+	    }
 	}
     }
 }
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
index 67dabce66ee..8f17f13d97a 100644
--- a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
@@ -41,7 +41,12 @@ set segfault_line [gdb_get_line_number "Segfault here"]
 # thread, on which the inferior call relies, either hits a breakpoint
 # (when OTHER_THREAD_BP is true), or crashes (when OTHER_THREAD_BP is
 # false).
-proc run_test { target_async target_non_stop non_stop other_thread_bp } {
+#
+# When UNWIND is "on" GDB will unwind the thread which performed the
+# inferior function call back to the state where the inferior call was
+# made (when the inferior call times out).  Otherwise, when UNWIND is
+# "off", the inferior is left in the frame where the timeout occurred.
+proc run_test { target_async target_non_stop non_stop other_thread_bp unwind } {
     save_vars { ::GDBFLAGS } {
 	append ::GDBFLAGS " -ex \"maint set target-non-stop $target_non_stop\""
 	append ::GDBFLAGS " -ex \"maint non-stop $non_stop\""
@@ -72,6 +77,7 @@ proc run_test { target_async target_non_stop non_stop other_thread_bp } {
     # for this timeout.  For now though, we just hope 5 seconds is
     # enough.
     gdb_test_no_output "set indirect-call-timeout 5"
+    gdb_test_no_output "set unwind-on-timeout $unwind"
 
     gdb_breakpoint \
 	"${::srcfile}:${::cond_bp_line} if (condition_func ())"
@@ -92,27 +98,43 @@ proc run_test { target_async target_non_stop non_stop other_thread_bp } {
 				 "get number for segfault breakpoint"]
     }
 
-    # When non-stop mode is off we get slightly different output from GDB.
-    if { ([target_info gdb_protocol] == "remote"
-	  || [target_info gdb_protocol] == "extended-remote")
-	 && !$target_non_stop} {
-	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" received signal SIGINT, Interrupt\\."
+    if { $unwind } {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Error in testing condition for breakpoint ${bp_num}:" \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB has restored the context to what it was before the call\\." \
+		 "To change this behavior use \"set unwind-on-timeout off\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(condition_func\\) will be abandoned\\." \
+		 "" \
+		 "Thread ${::decimal}\[^\r\n\]*hit Breakpoint ${bp_num}, \[^\r\n\]+" \
+		 "\[^\r\n\]+ Conditional breakpoint here\\. \[^\r\n\]+"] \
+	    "expected timeout waiting for inferior call to complete"
     } else {
-	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\."
-    }
+	# When non-stop mode is off we get slightly different output from GDB.
+	if { ([target_info gdb_protocol] == "remote"
+	      || [target_info gdb_protocol] == "extended-remote")
+	     && !$target_non_stop} {
+	    set stopped_line_pattern \
+		"Thread ${::decimal} \"\[^\r\n\"\]+\" received signal SIGINT, Interrupt\\."
+	} else {
+	    set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\."
+	}
 
-    gdb_test "continue" \
-	[multi_line \
-	     $stopped_line_pattern \
-	     ".*" \
-	     "Error in testing condition for breakpoint ${bp_num}:" \
-	     "The program being debugged timed out while in a function called from GDB\\." \
-	     "GDB remains in the frame where the timeout occurred\\." \
-	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
-	     "Evaluation of the expression containing the function" \
-	     "\\(condition_func\\) will be abandoned\\." \
-	     "When the function is done executing, GDB will silently stop\\."] \
-	"expected timeout waiting for inferior call to complete"
+	gdb_test "continue" \
+	    [multi_line \
+		 "$stopped_line_pattern" \
+		 ".*" \
+		 "Error in testing condition for breakpoint ${bp_num}:" \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB remains in the frame where the timeout occurred\\." \
+		 "To change this behavior use \"set unwind-on-timeout on\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(condition_func\\) will be abandoned\\." \
+		 "When the function is done executing, GDB will silently stop\\."] \
+	    "expected timeout waiting for inferior call to complete"
+    }
 
     # Remember that other thread that either crashed (with a segfault)
     # or hit a breakpoint?  Now that the inferior call has timed out,
@@ -158,8 +180,11 @@ foreach_with_prefix target_async {"on" "off" } {
 		# disabled.
 		continue
 	    }
-	    foreach_with_prefix other_thread_bp { true false } {
-		run_test $target_async $target_non_stop $non_stop $other_thread_bp
+	    foreach_with_prefix unwind {"off" "on"} {
+		foreach_with_prefix other_thread_bp { true false } {
+		    run_test $target_async $target_non_stop $non_stop \
+			$other_thread_bp $unwind
+		}
 	    }
 	}
     }
-- 
2.25.4


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

* [PATCHv10 5/5] gdb: rename unwindonsignal to unwind-on-signal
  2024-01-02 15:57                 ` [PATCHv10 0/5] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                                     ` (3 preceding siblings ...)
  2024-01-02 15:57                   ` [PATCHv10 4/5] gdb: introduce unwind-on-timeout setting Andrew Burgess
@ 2024-01-02 15:57                   ` Andrew Burgess
  2024-03-05 15:40                   ` [PATCHv11 0/5] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
  5 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2024-01-02 15:57 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Eli Zaretskii

Eli has already approved the NEWS/doc changes in this file.

---

We now have unwind-on-timeout and unwind-on-terminating-exception, and
then the odd one out unwindonsignal.

I'm not a great fan of these squashed together command names, so in
this commit I propose renaming this to unwind-on-signal.

Obviously I've added the hidden alias unwindonsignal so any existing
GDB scripts will keep working.

There's one test that I've extended to test the alias works, but in
most of the other test scripts I've changed over to use the new name.

The docs are updated to reference the new name.

Reviewed-By: Eli Zaretskii <eliz@gnu.org>
---
 gdb/NEWS                                      |  9 +++++
 gdb/doc/gdb.texinfo                           | 16 ++++++---
 gdb/infcall.c                                 | 21 ++++++-----
 gdb/testsuite/gdb.base/callfuncs.exp          |  4 +--
 gdb/testsuite/gdb.base/infcall-failure.exp    |  4 +--
 gdb/testsuite/gdb.base/unwindonsignal.exp     | 36 +++++++++++++------
 gdb/testsuite/gdb.compile/compile-cplus.exp   |  6 ++--
 gdb/testsuite/gdb.compile/compile.exp         |  6 ++--
 gdb/testsuite/gdb.cp/gdb2495.exp              | 16 ++++-----
 gdb/testsuite/gdb.fortran/function-calls.exp  |  2 +-
 gdb/testsuite/gdb.mi/mi-condbreak-fail.exp    |  6 ++--
 gdb/testsuite/gdb.mi/mi-condbreak-throw.exp   |  2 +-
 gdb/testsuite/gdb.mi/mi-syn-frame.exp         |  2 +-
 .../infcall-from-bp-cond-simple.exp           |  2 +-
 .../gdb.threads/thread-unwindonsignal.exp     |  8 ++---
 15 files changed, 89 insertions(+), 51 deletions(-)

diff --git a/gdb/NEWS b/gdb/NEWS
index 4ba8f62a8b3..dda757a8ceb 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -21,6 +21,10 @@ maintenance info line-table
   if the line is considered the start of the epilgoue, and thus a point at
   which the frame can be considered destroyed.
 
+set unwindonsignal on|off
+show unwindonsignal
+  These commands are now aliases for the new set/show unwind-on-signal.
+
 * New commands
 
 info missing-debug-handler
@@ -70,6 +74,11 @@ show unwind-on-timeout
   dummy frame that was added for the inferior call, and restoring the
   inferior state to how it was before the inferior call started.
 
+set unwind-on-signal on|off
+show unwind-on-signal
+  These new commands replaces the existing set/show unwindonsignal.  The
+  old command is maintained as an alias.
+
 * New features in the GDB remote stub, GDBserver
 
   ** The --remote-debug and --event-loop-debug command line options
diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index 6f847295e28..6b4126b8f1a 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -20898,7 +20898,7 @@
 It is possible for the function you call via the @code{print} or
 @code{call} command to generate a signal (e.g., if there's a bug in
 the function, or if you passed it incorrect arguments).  What happens
-in that case is controlled by the @code{set unwindonsignal} command.
+in that case is controlled by the @code{set unwind-on-signal} command.
 
 Similarly, with a C@t{++} program it is possible for the function you
 call via the @code{print} or @code{call} command to generate an
@@ -20912,7 +20912,8 @@
 
 @anchor{stack unwind settings}
 @table @code
-@item set unwindonsignal
+@item set unwind-on-signal
+@kindex set unwind-on-signal
 @kindex set unwindonsignal
 @cindex unwind stack in called functions
 @cindex call dummy stack unwinding
@@ -20923,11 +20924,18 @@
 default), @value{GDBN} stops in the frame where the signal was
 received.
 
-@item show unwindonsignal
+The command @code{set unwindonsignal} is an alias for this command,
+and is maintained for backward compatibility.
+
+@item show unwind-on-signal
+@kindex show unwind-on-signal
 @kindex show unwindonsignal
 Show the current setting of stack unwinding in the functions called by
 @value{GDBN}.
 
+The command @code{show unwindonsignal} is an alias for this command,
+and is maintained for backward compatibility.
+
 @item set unwind-on-terminating-exception
 @kindex set unwind-on-terminating-exception
 @cindex unwind stack in called functions with unhandled exceptions
@@ -20992,7 +21000,7 @@
 If a called function is interrupted for any reason, including hitting
 a breakpoint, or triggering a watchpoint, and the stack is not unwound
 due to @code{set unwind-on-terminating-exception on}, @code{set
-unwind-on-timeout on}, or @code{set unwindonsignal on} (@pxref{stack
+unwind-on-timeout on}, or @code{set unwind-on-signal on} (@pxref{stack
 unwind settings}), then the dummy-frame, created by @value{GDBN} to
 facilitate the call to the program function, will be visible in the
 backtrace, for example frame @code{#3} in the following backtrace:
diff --git a/gdb/infcall.c b/gdb/infcall.c
index 84c6bf2cdd2..bf17a1a21d6 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -1755,7 +1755,7 @@ When the function is done executing, GDB will silently stop."),
 The program being debugged received signal %s, %s\n\
 while in a function called from GDB.  GDB has restored the context\n\
 to what it was before the call.  To change this behavior use\n\
-\"set unwindonsignal off\".  Evaluation of the expression containing\n\
+\"set unwind-on-signal off\".  Evaluation of the expression containing\n\
 the function (%s) will be abandoned."),
 		     gdb_signal_to_name (stop_signal),
 		     gdb_signal_to_string (stop_signal),
@@ -1774,7 +1774,7 @@ the function (%s) will be abandoned."),
 	      error (_("\
 The program being debugged was signaled while in a function called from GDB.\n\
 GDB remains in the frame where the signal was received.\n\
-To change this behavior use \"set unwindonsignal on\".\n\
+To change this behavior use \"set unwind-on-signal on\".\n\
 Evaluation of the expression containing the function\n\
 (%s) will be abandoned.\n\
 When the function is done executing, GDB will silently stop."),
@@ -1906,17 +1906,22 @@ The default is to perform the conversion."),
 			   show_coerce_float_to_double_p,
 			   &setlist, &showlist);
 
-  add_setshow_boolean_cmd ("unwindonsignal", no_class,
-			   &unwind_on_signal_p, _("\
+  set_show_commands setshow_unwind_on_signal_cmds
+    = add_setshow_boolean_cmd ("unwind-on-signal", no_class,
+			       &unwind_on_signal_p, _("\
 Set unwinding of stack if a signal is received while in a call dummy."), _("\
 Show unwinding of stack if a signal is received while in a call dummy."), _("\
-The unwindonsignal lets the user determine what gdb should do if a signal\n\
+The unwind-on-signal lets the user determine what gdb should do if a signal\n\
 is received while in a function called from gdb (call dummy).  If set, gdb\n\
 unwinds the stack and restore the context to what as it was before the call.\n\
 The default is to stop in the frame where the signal was received."),
-			   NULL,
-			   show_unwind_on_signal_p,
-			   &setlist, &showlist);
+			       NULL,
+			       show_unwind_on_signal_p,
+			       &setlist, &showlist);
+  add_alias_cmd ("unwindonsignal", setshow_unwind_on_signal_cmds.set,
+		 no_class, 1, &setlist);
+  add_alias_cmd ("unwindonsignal", setshow_unwind_on_signal_cmds.show,
+		 no_class, 1, &showlist);
 
   add_setshow_boolean_cmd ("unwind-on-terminating-exception", no_class,
 			   &unwind_on_terminating_exception_p, _("\
diff --git a/gdb/testsuite/gdb.base/callfuncs.exp b/gdb/testsuite/gdb.base/callfuncs.exp
index 2c797a224a7..d9f63e944bf 100644
--- a/gdb/testsuite/gdb.base/callfuncs.exp
+++ b/gdb/testsuite/gdb.base/callfuncs.exp
@@ -46,7 +46,7 @@ proc do_function_calls {prototypes} {
 
     # If any of these calls segv we don't want to affect subsequent tests.
     # E.g., we want to ensure register values are restored.
-    gdb_test_no_output "set unwindonsignal on"
+    gdb_test_no_output "set unwind-on-signal on"
 
     gdb_test "p t_char_values(0,0)" " = 0"
     gdb_test "p t_char_values('a','b')" " = 1"
@@ -237,7 +237,7 @@ proc do_function_calls {prototypes} {
     	"call inferior func with struct - returns char *"
 
     # Restore default value.
-    gdb_test_no_output "set unwindonsignal off"
+    gdb_test_no_output "set unwind-on-signal off"
 }
 
 # Procedure to get current content of all registers.
diff --git a/gdb/testsuite/gdb.base/infcall-failure.exp b/gdb/testsuite/gdb.base/infcall-failure.exp
index 5ad179a089d..e2e71649dac 100644
--- a/gdb/testsuite/gdb.base/infcall-failure.exp
+++ b/gdb/testsuite/gdb.base/infcall-failure.exp
@@ -137,7 +137,7 @@ proc_with_prefix run_cond_hits_segfault_test { async_p non_stop_p } {
 	     "Error in testing condition for breakpoint ${bp_1_num}:" \
 	     "The program being debugged was signaled while in a function called from GDB\\." \
 	     "GDB remains in the frame where the signal was received\\." \
-	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "To change this behavior use \"set unwind-on-signal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(func_segfault\\) will be abandoned\\." \
 	     "When the function is done executing, GDB will silently stop\\."]
@@ -166,7 +166,7 @@ proc_with_prefix run_call_hits_segfault_test { async_p non_stop_p } {
 	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
 	     "The program being debugged was signaled while in a function called from GDB\\." \
 	     "GDB remains in the frame where the signal was received\\." \
-	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "To change this behavior use \"set unwind-on-signal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(func_segfault\\) will be abandoned\\." \
 	     "When the function is done executing, GDB will silently stop\\."]
diff --git a/gdb/testsuite/gdb.base/unwindonsignal.exp b/gdb/testsuite/gdb.base/unwindonsignal.exp
index 5c2243236ba..bf876fb42ba 100644
--- a/gdb/testsuite/gdb.base/unwindonsignal.exp
+++ b/gdb/testsuite/gdb.base/unwindonsignal.exp
@@ -34,13 +34,29 @@ gdb_test "break stop_here" "Breakpoint \[0-9\]* at .*"
 gdb_test "continue" "Continuing.*Breakpoint \[0-9\]*, stop_here.*" \
     "continue to breakpoint at stop_here"
 
-# Turn on unwindonsignal.
-gdb_test_no_output "set unwindonsignal on" \
-	"setting unwindonsignal"
+# Turn on unwind-on-signal.
+gdb_test_no_output "set unwind-on-signal on" \
+	"setting unwind-on-signal"
 
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
 	"Unwinding of stack .* is on." \
-	"showing unwindonsignal"
+	"showing unwind-on-signal"
+
+# For backward compatibility we maintain a 'unwindonsignal' alias for
+# 'unwind-on-signal', check it now.
+gdb_test "show unwindonsignal" \
+    "Unwinding of stack .* is on\\." \
+    "showing unwindonsignal alias"
+
+gdb_test_no_output "set unwindonsignal off" \
+    "setting unwindonsignal alias to off"
+
+gdb_test "show unwind-on-signal" \
+    "Unwinding of stack .* is off\\." \
+    "showing unwind-on-signal after setting via alias"
+
+gdb_test_no_output "set unwindonsignal on" \
+    "setting unwindonsignal alias to on"
 
 # Call function (causing the program to get a signal), and see if gdb handles
 # it properly.
@@ -49,7 +65,7 @@ if {[gdb_test "call gen_signal ()"  \
 	      "The program being debugged received signal SIGABRT, Aborted" \
 	      "while in a function called from GDB\\.  GDB has restored the context" \
 	      "to what it was before the call\\.  To change this behavior use" \
-	      "\"set unwindonsignal off\"\\.  Evaluation of the expression containing" \
+	      "\"set unwind-on-signal off\"\\.  Evaluation of the expression containing" \
 	      "the function \\(gen_signal\\) will be abandoned\\."] \
 	 "unwindonsignal, inferior function call signaled"] != 0} {
     return 0
@@ -58,15 +74,15 @@ if {[gdb_test "call gen_signal ()"  \
 # Verify the stack got unwound.
 gdb_test "bt" \
     "#0 *\[x0-9a-f in\]*stop_here \\(.*\\) at .*#1 *\[x0-9a-f in\]*main \\(.*\\) at .*" \
-	"unwindonsignal, stack unwound"
+	"stack unwound"
 
 # Verify the dummy frame got removed from dummy_frame_stack.
 gdb_test_multiple "maint print dummy-frames" \
-	"unwindonsignal, dummy frame removed" {
+	"unwind-on-signal, dummy frame removed" {
     -re "\[\r\n\]*.*stack=.*code=.*\[\r\n\]+$gdb_prompt $" {
-	fail "unwindonsignal, dummy frame removed"
+	fail $gdb_test_name
     }
     -re "\[\r\n\]+$gdb_prompt $" {
-	pass "unwindonsignal, dummy frame removed"
+	pass $gdb_test_name
     }
 }
diff --git a/gdb/testsuite/gdb.compile/compile-cplus.exp b/gdb/testsuite/gdb.compile/compile-cplus.exp
index 48fb75c3d78..c938c60ee98 100644
--- a/gdb/testsuite/gdb.compile/compile-cplus.exp
+++ b/gdb/testsuite/gdb.compile/compile-cplus.exp
@@ -131,13 +131,13 @@ gdb_test "return" "\r\n#0  main .*" "return" \
 	 "Make _gdb_expr\\(__gdb_regs\\*\\) return now\\? \\(y or n\\) " "y"
 gdb_test "info sym $infcall_pc" "\r\nNo symbol matches .*" "info sym not found"
 
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 gdb_test "compile code *(volatile int *) 0 = 0;" \
     [multi_line \
 	 "The program being debugged received signal SIGSEGV, Segmentation fault" \
 	 "while in a function called from GDB\\.  GDB has restored the context" \
 	 "to what it was before the call\\.  To change this behavior use" \
-	 "\"set unwindonsignal off\"\\.  Evaluation of the expression containing" \
+	 "\"set unwind-on-signal off\"\\.  Evaluation of the expression containing" \
 	 "the function \\(_gdb_expr\\(__gdb_regs\\*\\)\\) will be abandoned\\."] \
     "compile code segfault second"
 
@@ -313,7 +313,7 @@ gdb_test "compile code static const int readonly = 1; *(int *) &readonly = 2;" \
 	 "The program being debugged received signal SIGSEGV, Segmentation fault" \
 	 "while in a function called from GDB\\.  GDB has restored the context" \
 	 "to what it was before the call\\.  To change this behavior use" \
-	 "\"set unwindonsignal off\"\\.  Evaluation of the expression containing" \
+	 "\"set unwind-on-signal off\"\\.  Evaluation of the expression containing" \
 	 "the function \\(_gdb_expr\\(__gdb_regs\\*\\)\\) will be abandoned\\."]
 gdb_test_no_output "set debug compile off"
 
diff --git a/gdb/testsuite/gdb.compile/compile.exp b/gdb/testsuite/gdb.compile/compile.exp
index 86521e99dac..cd409f5a48a 100644
--- a/gdb/testsuite/gdb.compile/compile.exp
+++ b/gdb/testsuite/gdb.compile/compile.exp
@@ -157,13 +157,13 @@ gdb_test "return" "\r\n#0  main .*" "return" \
 	 "Make _gdb_expr return now\\? \\(y or n\\) " "y"
 gdb_test "info sym $infcall_pc" "\r\nNo symbol matches .*" "info sym not found"
 
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 gdb_test "compile code *(volatile int *) 0 = 0;" \
     [multi_line \
 	 "The program being debugged received signal SIGSEGV, Segmentation fault" \
 	 "while in a function called from GDB\\.  GDB has restored the context" \
 	 "to what it was before the call\\.  To change this behavior use" \
-	 "\"set unwindonsignal off\"\\.  Evaluation of the expression containing" \
+	 "\"set unwind-on-signal off\"\\.  Evaluation of the expression containing" \
 	 "the function \\(_gdb_expr\\) will be abandoned\\."] \
     "compile code segfault second"
 
@@ -321,7 +321,7 @@ gdb_test "compile code static const int readonly = 1; *(int *) &readonly = 2;" \
 	 "The program being debugged received signal SIGSEGV, Segmentation fault" \
 	 "while in a function called from GDB\\.  GDB has restored the context" \
 	 "to what it was before the call\\.  To change this behavior use" \
-	 "\"set unwindonsignal off\"\\.  Evaluation of the expression containing" \
+	 "\"set unwind-on-signal off\"\\.  Evaluation of the expression containing" \
 	 "the function \\(_gdb_expr\\) will be abandoned\\."]
 gdb_test_no_output "set debug compile off"
 
diff --git a/gdb/testsuite/gdb.cp/gdb2495.exp b/gdb/testsuite/gdb.cp/gdb2495.exp
index 93b046ad3a6..b888924ec63 100644
--- a/gdb/testsuite/gdb.cp/gdb2495.exp
+++ b/gdb/testsuite/gdb.cp/gdb2495.exp
@@ -98,10 +98,10 @@ if {![runto_main]} {
 # behaviour; it should not.  Test both on and off states.
 
 # Turn on unwind on signal behaviour.
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 
 # Check that it is turned on.
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
     "signal is received while in a call dummy is on.*" \
     "turn on unwind on signal"
 
@@ -112,20 +112,20 @@ gdb_test "p exceptions.raise_signal(1)" \
 	 "The program being debugged received signal SIGABRT, Aborted" \
 	 "while in a function called from GDB\\.  GDB has restored the context" \
 	 "to what it was before the call\\.  To change this behavior use" \
-	 "\"set unwindonsignal off\"\\.  Evaluation of the expression containing" \
+	 "\"set unwind-on-signal off\"\\.  Evaluation of the expression containing" \
 	 "the function \\(SimpleException::raise_signal\\(int\\)\\) will be abandoned\\."]\
-    "check for unwindonsignal off message"
+    "check for unwind-on-signal off message"
 
 # And reverse - turn off again.
-gdb_test_no_output "set unwindonsignal off"
+gdb_test_no_output "set unwind-on-signal off"
 
 # Check that it is actually turned off.
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
     "signal is received while in a call dummy is off.*" \
     "turn off unwind on signal"
 
 # Check to see if new behaviour interferes with
 # normal signal handling in inferior function calls.
 gdb_test "p exceptions.raise_signal(1)" \
-    "To change this behavior use \"set unwindonsignal on\".*" \
-    "check for unwindonsignal on message"
+    "To change this behavior use \"set unwind-on-signal on\".*" \
+    "check for unwind-on-signal on message"
diff --git a/gdb/testsuite/gdb.fortran/function-calls.exp b/gdb/testsuite/gdb.fortran/function-calls.exp
index 646fbb06435..27dd68d8cd9 100644
--- a/gdb/testsuite/gdb.fortran/function-calls.exp
+++ b/gdb/testsuite/gdb.fortran/function-calls.exp
@@ -44,7 +44,7 @@ if {![runto [gdb_get_line_number "post_init"]]} {
 }
 
 # Use inspired by gdb.base/callfuncs.exp.
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 
 # Baseline: function and subroutine call with no arguments.
 gdb_test "p no_arg()" " = .TRUE."
diff --git a/gdb/testsuite/gdb.mi/mi-condbreak-fail.exp b/gdb/testsuite/gdb.mi/mi-condbreak-fail.exp
index 3ccca4c2e9b..d91bef420af 100644
--- a/gdb/testsuite/gdb.mi/mi-condbreak-fail.exp
+++ b/gdb/testsuite/gdb.mi/mi-condbreak-fail.exp
@@ -43,7 +43,7 @@ proc run_test { unwind_on_signal } {
 	return
     }
 
-    mi_gdb_test "-gdb-set unwindonsignal ${unwind_on_signal}" {\^done} \
+    mi_gdb_test "-gdb-set unwind-on-signal ${unwind_on_signal}" {\^done} \
 	"set unwind-on-signal"
 
     # Create the conditional breakpoint.
@@ -70,7 +70,7 @@ proc run_test { unwind_on_signal } {
 		 "&\"The program being debugged received signal SIGSEGV, Segmentation fault\\\\n\"" \
 		 "&\"while in a function called from GDB\\.  GDB has restored the context\\\\n\"" \
 		 "&\"to what it was before the call\\.  To change this behavior use\\\\n\"" \
-		 "&\"\\\\\"set unwindonsignal off\\\\\"\\.  Evaluation of the expression containing\\\\n\"" \
+		 "&\"\\\\\"set unwind-on-signal off\\\\\"\\.  Evaluation of the expression containing\\\\n\"" \
 		 "&\"the function \\(cond_fail\\) will be abandoned\\.\\\\n\"" \
 		 "=breakpoint-modified,bkpt={number=\"$bpnum\",type=\"breakpoint\",\[^\r\n\]+times=\"1\",\[^\r\n\]+}" \
 		 "~\"\\\\n\"" \
@@ -92,7 +92,7 @@ proc run_test { unwind_on_signal } {
 		 "&\"Error in testing condition for breakpoint $bpnum:\\\\n\"" \
 		 "&\"The program being debugged was signaled while in a function called from GDB\\.\\\\n\"" \
 		 "&\"GDB remains in the frame where the signal was received\\.\\\\n\"" \
-		 "&\"To change this behavior use \\\\\"set unwindonsignal on\\\\\"\\.\\\\n\"" \
+		 "&\"To change this behavior use \\\\\"set unwind-on-signal on\\\\\"\\.\\\\n\"" \
 		 "&\"Evaluation of the expression containing the function\\\\n\"" \
 		 "&\"\\(cond_fail\\) will be abandoned\\.\\\\n\"" \
 		 "&\"When the function is done executing, GDB will silently stop\\.\\\\n\"" \
diff --git a/gdb/testsuite/gdb.mi/mi-condbreak-throw.exp b/gdb/testsuite/gdb.mi/mi-condbreak-throw.exp
index 7f291244e53..437825eea47 100644
--- a/gdb/testsuite/gdb.mi/mi-condbreak-throw.exp
+++ b/gdb/testsuite/gdb.mi/mi-condbreak-throw.exp
@@ -103,7 +103,7 @@ proc run_test { unwind_on_exception } {
 		 "&\"Error in testing condition for breakpoint $bpnum:\\\\n\"" \
 		 "&\"The program being debugged was signaled while in a function called from GDB\\.\\\\n\"" \
 		 "&\"GDB remains in the frame where the signal was received\\.\\\\n\"" \
-		 "&\"To change this behavior use \\\\\"set unwindonsignal on\\\\\"\\.\\\\n\"" \
+		 "&\"To change this behavior use \\\\\"set unwind-on-signal on\\\\\"\\.\\\\n\"" \
 		 "&\"Evaluation of the expression containing the function\\\\n\"" \
 		 "&\"\\(cond_throw\\(\\)\\) will be abandoned\\.\\\\n\"" \
 		 "&\"When the function is done executing, GDB will silently stop\\.\\\\n\"" \
diff --git a/gdb/testsuite/gdb.mi/mi-syn-frame.exp b/gdb/testsuite/gdb.mi/mi-syn-frame.exp
index 40df312a1cc..1324226412c 100644
--- a/gdb/testsuite/gdb.mi/mi-syn-frame.exp
+++ b/gdb/testsuite/gdb.mi/mi-syn-frame.exp
@@ -94,7 +94,7 @@ mi_gdb_test "409-stack-list-frames 0 0" \
 # 
 
 mi_gdb_test "410-data-evaluate-expression bar()" \
-  ".*410\\^error,msg=\"The program being debugged was signaled while in a function called from GDB.\\\\nGDB remains in the frame where the signal was received.\\\\nTo change this behavior use \\\\\"set unwindonsignal on\\\\\".\\\\nEvaluation of the expression containing the function\\\\n\\(bar\\) will be abandoned.\\\\nWhen the function is done executing, GDB will silently stop.\"" \
+  ".*410\\^error,msg=\"The program being debugged was signaled while in a function called from GDB.\\\\nGDB remains in the frame where the signal was received.\\\\nTo change this behavior use \\\\\"set unwind-on-signal on\\\\\".\\\\nEvaluation of the expression containing the function\\\\n\\(bar\\) will be abandoned.\\\\nWhen the function is done executing, GDB will silently stop.\"" \
   "call inferior function which raises exception"
 
 mi_gdb_test "411-stack-list-frames" "411\\^done,stack=\\\[frame=\{level=\"0\",addr=\"$hex\",func=\"bar\",file=\".*mi-syn-frame.c\",fullname=\"${fullname_syntax}${srcfile}\",line=\"$decimal\",arch=\"$any\"},frame=\{level=\"1\",addr=\"$hex\",func=\"<function called from gdb>\"\},frame=\{level=\"2\",addr=\"$hex\",func=\"main\",file=\".*mi-syn-frame.c\",fullname=\"${fullname_syntax}${srcfile}\",line=\"$decimal\",arch=\"$any\"}.*\\\]" "backtrace from inferior function at exception"
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
index d6069ebaa58..c9508c9d67e 100644
--- a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
@@ -173,7 +173,7 @@ proc_with_prefix run_bp_cond_segfaults { target_async target_non_stop } {
 	     "Error in testing condition for breakpoint ${bp_1_num}:" \
 	     "The program being debugged was signaled while in a function called from GDB\\." \
 	     "GDB remains in the frame where the signal was received\\." \
-	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "To change this behavior use \"set unwind-on-signal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(function_that_segfaults\\) will be abandoned\\." \
 	     "When the function is done executing, GDB will silently stop\\."]
diff --git a/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp b/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp
index 68a99f66f1c..a9cedc0c466 100644
--- a/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp
+++ b/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp
@@ -13,7 +13,7 @@
 # You should have received a copy of the GNU General Public License
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-# Test use of unwindonsignal when a hand function call that gets interrupted
+# Test use of unwind-on-signal when a hand function call that gets interrupted
 # by a signal in another thread.
 
 set NR_THREADS 4
@@ -49,12 +49,12 @@ gdb_test "continue" \
 # We want the main thread (hand_call_with_signal) and
 # thread 1 (sigabrt_handler) to both run.
 
-# Do turn on unwindonsignal.
+# Do turn on unwind-on-signal.
 # We want to test gdb handling of the current thread changing when
 # unwindonsignal is in effect.
-gdb_test_no_output "set unwindonsignal on" \
+gdb_test_no_output "set unwind-on-signal on" \
 	"setting unwindonsignal"
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
 	"Unwinding of stack .* is on." \
 	"showing unwindonsignal"
 
-- 
2.25.4


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

* [PATCHv11 0/5] Infcalls from B/P conditions in multi-threaded inferiors
  2024-01-02 15:57                 ` [PATCHv10 0/5] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                                     ` (4 preceding siblings ...)
  2024-01-02 15:57                   ` [PATCHv10 5/5] gdb: rename unwindonsignal to unwind-on-signal Andrew Burgess
@ 2024-03-05 15:40                   ` Andrew Burgess
  2024-03-05 15:40                     ` [PATCHv11 1/5] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
                                       ` (7 more replies)
  5 siblings, 8 replies; 202+ messages in thread
From: Andrew Burgess @ 2024-03-05 15:40 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess

In v11:

  - Rebased onto current upstream/master, only merge conflict was in
    NEWS file.  Retested with no regressions.

In v10:

  - Rebased onto current upstream/master, I've updated the copyright
    dates from 2023 to 2024.

  - No merge conflicts (other than NEWS) and no build problems.

In v9:

  - Dropped previous patch #4 (gdb/remote: avoid SIGINT after calling
    remote_target::stop) after feedback from Pedro.  This patch wasn't
    essential for this series, instead I've just updated some of the
    tests to expect different output from remote targets.

  - Updated to more recent master, and applied a small fix due to the
    recent C++17 changes, nothing huge.

  - Retested on unix, native-gdbserver, and native-extended-gdbserver
    boards.

In v8:

  - Rebased onto current upstream/master and retested.

  - Addressed feedback from Baris on patches 1, 2, 3, & 4.  This was
    mostly minor stuff, comment typos and some improvements to the
    testsuite.  There was one real (but minor) GDB change in patch 4.

In v7:

  - Rebased onto current upstream/master, fixed use of
    find_thread_ptid which is now a process_stratum_target method,

  - Retested, with no regressions seen.

In v6:

  - Pushed the 5 initial patches.  These were the smaller fixes, and,
    I felt were pretty obvious fixes.  I'm sure folk will raise
    objections if they disagree.

  - Of the remaining patches, #1 to #5 really needs review before they
    can be merged.  Patch #6 is an obvious cleanup once the first five
    have been merged.

  - I've rebased onto current HEAD of master, there's no significant
    changes.

  - All other documentation changes have been reviewed and approved.

In v5:

  - Rebased to current HEAD of master, minor merge conflict resolved.
    No other code or documentation changes.

  - First patch, which was pure documentation, has now been merged.

  - All other documentation changes have been reviewed and approved.

In v4:

  - I believe all the docs changes have been reviewed and approved by Eli,

  - Rebased onto current master,

  - Dropped patch #2 from the V3 series,

  - I have addressed all the issues Baris pointed out, including the
    fixes for the patch #9 ('gdb: add timeouts for inferior function
    calls'), which I forgot to do in V3.

In v3:

  - Updates for review feedback, biggest changes in #10 and #11, but
    minor changes to most patches.

In V2:

  - Rebased onto something closer to HEAD of master,

  - Patches #1, #2, #12, and #13 are new in this series,

  - Patches #3 to #9, and #11 are unchanged since their V1 iteration,

  - Patches #10 has changed slightly in implementation since v1, and
    the docs have been significantly updated.

---

Andrew Burgess (5):
  Revert "gdb: remove unnecessary parameter wait_ptid from
    do_target_wait"
  gdb: fix b/p conditions with infcalls in multi-threaded inferiors
  gdb: add timeouts for inferior function calls
  gdb: introduce unwind-on-timeout setting
  gdb: rename unwindonsignal to unwind-on-signal

 gdb/NEWS                                      |  36 +++
 gdb/breakpoint.c                              |   2 +
 gdb/doc/gdb.texinfo                           | 111 ++++++-
 gdb/gdbthread.h                               |   3 +
 gdb/infcall.c                                 | 301 +++++++++++++++++-
 gdb/infrun.c                                  |  70 +++-
 gdb/infrun.h                                  |   3 +-
 gdb/testsuite/gdb.base/callfuncs.exp          |   4 +-
 gdb/testsuite/gdb.base/help.exp               |   2 +-
 gdb/testsuite/gdb.base/infcall-failure.exp    |   4 +-
 gdb/testsuite/gdb.base/infcall-timeout.c      |  36 +++
 gdb/testsuite/gdb.base/infcall-timeout.exp    | 115 +++++++
 gdb/testsuite/gdb.base/unwindonsignal.exp     |  36 ++-
 gdb/testsuite/gdb.compile/compile-cplus.exp   |   6 +-
 gdb/testsuite/gdb.compile/compile.exp         |   6 +-
 gdb/testsuite/gdb.cp/gdb2495.exp              |  16 +-
 gdb/testsuite/gdb.fortran/function-calls.exp  |   2 +-
 gdb/testsuite/gdb.mi/mi-condbreak-fail.exp    |   6 +-
 gdb/testsuite/gdb.mi/mi-condbreak-throw.exp   |   2 +-
 gdb/testsuite/gdb.mi/mi-syn-frame.exp         |   2 +-
 .../infcall-from-bp-cond-other-thread-event.c | 135 ++++++++
 ...nfcall-from-bp-cond-other-thread-event.exp | 174 ++++++++++
 .../gdb.threads/infcall-from-bp-cond-simple.c |  89 ++++++
 .../infcall-from-bp-cond-simple.exp           | 235 ++++++++++++++
 .../gdb.threads/infcall-from-bp-cond-single.c | 139 ++++++++
 .../infcall-from-bp-cond-single.exp           | 117 +++++++
 .../infcall-from-bp-cond-timeout.c            | 169 ++++++++++
 .../infcall-from-bp-cond-timeout.exp          | 191 +++++++++++
 .../gdb.threads/thread-unwindonsignal.exp     |   8 +-
 29 files changed, 1943 insertions(+), 77 deletions(-)
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.c
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp


base-commit: a7ea089b0bccb6379e079e2ab764c2012d94b472
-- 
2.25.4


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

* [PATCHv11 1/5] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait"
  2024-03-05 15:40                   ` [PATCHv11 0/5] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
@ 2024-03-05 15:40                     ` Andrew Burgess
  2024-03-05 15:40                     ` [PATCHv11 2/5] gdb: fix b/p conditions with infcalls in multi-threaded inferiors Andrew Burgess
                                       ` (6 subsequent siblings)
  7 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2024-03-05 15:40 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Tankut Baris Aktemur

This reverts commit ac0d67ed1dcf470bad6a3bc4800c2ddc9bedecca.

There was nothing wrong with the commit which I'm reverting here, but
it removed some functionality that will be needed for a later commit;
that is, the ability for GDB to ask for events from a specific ptid_t
via the do_target_wait function.

In a follow up commit, this functionality will be used to implement
inferior function calls in multi-threaded inferiors.

This is not a straight revert of the above commit.  Reverting the
above commit replaces a 'nullptr' with 'NULL', I've gone in and
changed that, preserving the 'nullptr'.

Reviewed-By: Tankut Baris Aktemur <tankut.baris.aktemur@intel.com>
---
 gdb/infrun.c | 12 +++++++-----
 1 file changed, 7 insertions(+), 5 deletions(-)

diff --git a/gdb/infrun.c b/gdb/infrun.c
index bbb98f6dcdb..e0e0ba35a68 100644
--- a/gdb/infrun.c
+++ b/gdb/infrun.c
@@ -4125,7 +4125,8 @@ do_target_wait_1 (inferior *inf, ptid_t ptid,
    more events.  Polls for events from all inferiors/targets.  */
 
 static bool
-do_target_wait (execution_control_state *ecs, target_wait_flags options)
+do_target_wait (ptid_t wait_ptid, execution_control_state *ecs,
+		target_wait_flags options)
 {
   int num_inferiors = 0;
   int random_selector;
@@ -4135,9 +4136,10 @@ do_target_wait (execution_control_state *ecs, target_wait_flags options)
      polling the rest of the inferior list starting from that one in a
      circular fashion until the whole list is polled once.  */
 
-  auto inferior_matches = [] (inferior *inf)
+  auto inferior_matches = [&wait_ptid] (inferior *inf)
     {
-      return inf->process_target () != nullptr;
+      return (inf->process_target () != nullptr
+	      && ptid_t (inf->pid).matches (wait_ptid));
     };
 
   /* First see how many matching inferiors we have.  */
@@ -4176,7 +4178,7 @@ do_target_wait (execution_control_state *ecs, target_wait_flags options)
 
   auto do_wait = [&] (inferior *inf)
   {
-    ecs->ptid = do_target_wait_1 (inf, minus_one_ptid, &ecs->ws, options);
+    ecs->ptid = do_target_wait_1 (inf, wait_ptid, &ecs->ws, options);
     ecs->target = inf->process_target ();
     return (ecs->ws.kind () != TARGET_WAITKIND_IGNORE);
   };
@@ -4626,7 +4628,7 @@ fetch_inferior_event ()
        the event.  */
     scoped_disable_commit_resumed disable_commit_resumed ("handling event");
 
-    if (!do_target_wait (&ecs, TARGET_WNOHANG))
+    if (!do_target_wait (minus_one_ptid, &ecs, TARGET_WNOHANG))
       {
 	infrun_debug_printf ("do_target_wait returned no event");
 	disable_commit_resumed.reset_and_commit ();
-- 
2.25.4


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

* [PATCHv11 2/5] gdb: fix b/p conditions with infcalls in multi-threaded inferiors
  2024-03-05 15:40                   ` [PATCHv11 0/5] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
  2024-03-05 15:40                     ` [PATCHv11 1/5] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
@ 2024-03-05 15:40                     ` Andrew Burgess
  2024-03-05 15:40                     ` [PATCHv11 3/5] gdb: add timeouts for inferior function calls Andrew Burgess
                                       ` (5 subsequent siblings)
  7 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2024-03-05 15:40 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Natalia Saiapova, Tankut Baris Aktemur

This commit fixes bug PR 28942, that is, creating a conditional
breakpoint in a multi-threaded inferior, where the breakpoint
condition includes an inferior function call.

Currently, when a user tries to create such a breakpoint, then GDB
will fail with:

  (gdb) break infcall-from-bp-cond-single.c:61 if (return_true ())
  Breakpoint 2 at 0x4011fa: file /tmp/build/gdb/testsuite/../../../src/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c, line 61.
  (gdb) continue
  Continuing.
  [New Thread 0x7ffff7c5d700 (LWP 2460150)]
  [New Thread 0x7ffff745c700 (LWP 2460151)]
  [New Thread 0x7ffff6c5b700 (LWP 2460152)]
  [New Thread 0x7ffff645a700 (LWP 2460153)]
  [New Thread 0x7ffff5c59700 (LWP 2460154)]
  Error in testing breakpoint condition:
  Couldn't get registers: No such process.
  An error occurred while in a function called from GDB.
  Evaluation of the expression containing the function
  (return_true) will be abandoned.
  When the function is done executing, GDB will silently stop.
  Selected thread is running.
  (gdb)

Or, in some cases, like this:

  (gdb) break infcall-from-bp-cond-simple.c:56 if (is_matching_tid (arg, 1))
  Breakpoint 2 at 0x401194: file /tmp/build/gdb/testsuite/../../../src/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c, line 56.
  (gdb) continue
  Continuing.
  [New Thread 0x7ffff7c5d700 (LWP 2461106)]
  [New Thread 0x7ffff745c700 (LWP 2461107)]
  ../../src.release/gdb/nat/x86-linux-dregs.c:146: internal-error: x86_linux_update_debug_registers: Assertion `lwp_is_stopped (lwp)' failed.
  A problem internal to GDB has been detected,
  further debugging may prove unreliable.

The precise error depends on the exact thread state; so there's race
conditions depending on which threads have fully started, and which
have not.  But the underlying problem is always the same; when GDB
tries to execute the inferior function call from within the breakpoint
condition, GDB will, incorrectly, try to resume threads that are
already running - GDB doesn't realise that some threads might already
be running.

The solution proposed in this patch requires an additional member
variable thread_info::in_cond_eval.  This flag is set to true (in
breakpoint.c) when GDB is evaluating a breakpoint condition.

In user_visible_resume_ptid (infrun.c), when the in_cond_eval flag is
true, then GDB will only try to resume the current thread, that is,
the thread for which the breakpoint condition is being evaluated.
This solves the problem of GDB trying to resume threads that are
already running.

The next problem is that inferior function calls are assumed to be
synchronous, that is, GDB doesn't expect to start an inferior function
call in thread #1, then receive a stop from thread #2 for some other,
unrelated reason.  To prevent GDB responding to an event from another
thread, we update fetch_inferior_event and do_target_wait in infrun.c,
so that, when an inferior function call (on behalf of a breakpoint
condition) is in progress, we only wait for events from the current
thread (the one evaluating the condition).

In do_target_wait I had to change the inferior_matches lambda
function, which is used to select which inferior to wait on.
Previously the logic was this:

   auto inferior_matches = [&wait_ptid] (inferior *inf)
     {
       return (inf->process_target () != nullptr
               && ptid_t (inf->pid).matches (wait_ptid));
     };

This compares the pid of the inferior against the complete ptid we
want to wait on.  Before this commit wait_ptid was only ever
minus_one_ptid (which is special, and means any process), and so every
inferior would match.

After this commit though wait_ptid might represent a specific thread
in a specific inferior.  If we compare the pid of the inferior to a
specific ptid then these will not match.  The fix is to compare
against the pid extracted from the wait_ptid, not against the complete
wait_ptid itself.

In fetch_inferior_event, after receiving the event, we only want to
stop all the other threads, and call inferior_event_handler with
INF_EXEC_COMPLETE, if we are not evaluating a conditional breakpoint.
If we are, then all the other threads should be left doing whatever
they were before.  The inferior_event_handler call will be performed
once the breakpoint condition has finished being evaluated, and GDB
decides to stop or not.

The final problem that needs solving relates to GDB's commit-resume
mechanism, which allows GDB to collect resume requests into a single
packet in order to reduce traffic to a remote target.

The problem is that the commit-resume mechanism will not send any
resume requests for an inferior if there are already events pending on
the GDB side.

Imagine an inferior with two threads.  Both threads hit a breakpoint,
maybe the same conditional breakpoint.  At this point there are two
pending events, one for each thread.

GDB selects one of the events and spots that this is a conditional
breakpoint, GDB evaluates the condition.

The condition includes an inferior function call, so GDB sets up for
the call and resumes the one thread, the resume request is added to
the commit-resume queue.

When the commit-resume queue is committed GDB sees that there is a
pending event from another thread, and so doesn't send any resume
requests to the actual target, GDB is assuming that when we wait we
will select the event from the other thread.

However, as this is an inferior function call for a condition
evaluation, we will not select the event from the other thread, we
only care about events from the thread that is evaluating the
condition - and the resume for this thread was never sent to the
target.

And so, GDB hangs, waiting for an event from a thread that was never
fully resumed.

To fix this issue I have added the concept of "forcing" the
commit-resume queue.  When enabling commit resume, if the force flag
is true, then any resumes will be committed to the target, even if
there are other threads with pending events.

A note on authorship: this patch was based on some work done by
Natalia Saiapova and Tankut Baris Aktemur from Intel[1].  I have made
some changes to their work in this version.

Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=28942

[1] https://sourceware.org/pipermail/gdb-patches/2020-October/172454.html

Co-authored-by: Natalia Saiapova <natalia.saiapova@intel.com>
Co-authored-by: Tankut Baris Aktemur <tankut.baris.aktemur@intel.com>
Reviewed-By: Tankut Baris Aktemur <tankut.baris.aktemur@intel.com>
---
 gdb/breakpoint.c                              |   2 +
 gdb/gdbthread.h                               |   3 +
 gdb/infcall.c                                 |   6 +
 gdb/infrun.c                                  |  64 +++--
 gdb/infrun.h                                  |   3 +-
 .../infcall-from-bp-cond-other-thread-event.c | 135 ++++++++++
 ...nfcall-from-bp-cond-other-thread-event.exp | 174 +++++++++++++
 .../gdb.threads/infcall-from-bp-cond-simple.c |  89 +++++++
 .../infcall-from-bp-cond-simple.exp           | 235 ++++++++++++++++++
 .../gdb.threads/infcall-from-bp-cond-single.c | 139 +++++++++++
 .../infcall-from-bp-cond-single.exp           | 117 +++++++++
 11 files changed, 952 insertions(+), 15 deletions(-)
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp

diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index 102bd7fad41..39c13107ba2 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -5665,6 +5665,8 @@ bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
 	{
 	  try
 	    {
+	      scoped_restore reset_in_cond_eval
+		= make_scoped_restore (&thread->control.in_cond_eval, true);
 	      condition_result = breakpoint_cond_eval (cond);
 	    }
 	  catch (const gdb_exception_error &ex)
diff --git a/gdb/gdbthread.h b/gdb/gdbthread.h
index 11c553a99ca..73f6895fe46 100644
--- a/gdb/gdbthread.h
+++ b/gdb/gdbthread.h
@@ -173,6 +173,9 @@ struct thread_control_state
      command.  This is used to decide whether "set scheduler-locking
      step" behaves like "on" or "off".  */
   int stepping_command = 0;
+
+  /* True if the thread is evaluating a BP condition.  */
+  bool in_cond_eval = false;
 };
 
 /* Inferior thread specific part of `struct infcall_suspend_state'.  */
diff --git a/gdb/infcall.c b/gdb/infcall.c
index 145ce25b0d1..bfcac20e3f5 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -672,6 +672,12 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
 
       proceed (real_pc, GDB_SIGNAL_0);
 
+      /* Enable commit resume, but pass true for the force flag.  This
+	 ensures any thread we set running in proceed will actually be
+	 committed to the target, even if some other thread in the current
+	 target has a pending event.  */
+      scoped_enable_commit_resumed enable ("infcall", true);
+
       infrun_debug_show_threads ("non-exited threads after proceed for inferior-call",
 				 all_non_exited_threads ());
 
diff --git a/gdb/infrun.c b/gdb/infrun.c
index e0e0ba35a68..b06972bb968 100644
--- a/gdb/infrun.c
+++ b/gdb/infrun.c
@@ -2406,6 +2406,14 @@ user_visible_resume_ptid (int step)
 	 mode.  */
       resume_ptid = inferior_ptid;
     }
+  else if (inferior_ptid != null_ptid
+	   && inferior_thread ()->control.in_cond_eval)
+    {
+      /* The inferior thread is evaluating a BP condition.  Other threads
+	 might be stopped or running and we do not want to change their
+	 state, thus, resume only the current thread.  */
+      resume_ptid = inferior_ptid;
+    }
   else if (!sched_multi && target_supports_multi_process ())
     {
       /* Resume all threads of the current process (and none of other
@@ -3201,12 +3209,24 @@ schedlock_applies (struct thread_info *tp)
 					    execution_direction)));
 }
 
-/* Set process_stratum_target::COMMIT_RESUMED_STATE in all target
-   stacks that have threads executing and don't have threads with
-   pending events.  */
+/* When FORCE_P is false, set process_stratum_target::COMMIT_RESUMED_STATE
+   in all target stacks that have threads executing and don't have threads
+   with pending events.
+
+   When FORCE_P is true, set process_stratum_target::COMMIT_RESUMED_STATE
+   in all target stacks that have threads executing regardless of whether
+   there are pending events or not.
+
+   Passing FORCE_P as false makes sense when GDB is going to wait for
+   events from all threads and will therefore spot the pending events.
+   However, if GDB is only going to wait for events from select threads
+   (i.e. when performing an inferior call) then a pending event on some
+   other thread will not be spotted, and if we fail to commit the resume
+   state for the thread performing the inferior call, then the inferior
+   call will never complete (or even start).  */
 
 static void
-maybe_set_commit_resumed_all_targets ()
+maybe_set_commit_resumed_all_targets (bool force_p)
 {
   scoped_restore_current_thread restore_thread;
 
@@ -3235,7 +3255,7 @@ maybe_set_commit_resumed_all_targets ()
 	 status to report, handle it before requiring the target to
 	 commit its resumed threads: handling the status might lead to
 	 resuming more threads.  */
-      if (proc_target->has_resumed_with_pending_wait_status ())
+      if (!force_p && proc_target->has_resumed_with_pending_wait_status ())
 	{
 	  infrun_debug_printf ("not requesting commit-resumed for target %s, a"
 			       " thread has a pending waitstatus",
@@ -3245,7 +3265,7 @@ maybe_set_commit_resumed_all_targets ()
 
       switch_to_inferior_no_thread (inf);
 
-      if (target_has_pending_events ())
+      if (!force_p && target_has_pending_events ())
 	{
 	  infrun_debug_printf ("not requesting commit-resumed for target %s, "
 			       "target has pending events",
@@ -3338,7 +3358,7 @@ scoped_disable_commit_resumed::reset ()
     {
       /* This is the outermost instance, re-enable
 	 COMMIT_RESUMED_STATE on the targets where it's possible.  */
-      maybe_set_commit_resumed_all_targets ();
+      maybe_set_commit_resumed_all_targets (false);
     }
   else
     {
@@ -3371,7 +3391,7 @@ scoped_disable_commit_resumed::reset_and_commit ()
 /* See infrun.h.  */
 
 scoped_enable_commit_resumed::scoped_enable_commit_resumed
-  (const char *reason)
+  (const char *reason, bool force_p)
   : m_reason (reason),
     m_prev_enable_commit_resumed (enable_commit_resumed)
 {
@@ -3383,7 +3403,7 @@ scoped_enable_commit_resumed::scoped_enable_commit_resumed
 
       /* Re-enable COMMIT_RESUMED_STATE on the targets where it's
 	 possible.  */
-      maybe_set_commit_resumed_all_targets ();
+      maybe_set_commit_resumed_all_targets (force_p);
 
       maybe_call_commit_resumed_all_targets ();
     }
@@ -4136,10 +4156,11 @@ do_target_wait (ptid_t wait_ptid, execution_control_state *ecs,
      polling the rest of the inferior list starting from that one in a
      circular fashion until the whole list is polled once.  */
 
-  auto inferior_matches = [&wait_ptid] (inferior *inf)
+  ptid_t wait_ptid_pid {wait_ptid.pid ()};
+  auto inferior_matches = [&wait_ptid_pid] (inferior *inf)
     {
       return (inf->process_target () != nullptr
-	      && ptid_t (inf->pid).matches (wait_ptid));
+	      && ptid_t (inf->pid).matches (wait_ptid_pid));
     };
 
   /* First see how many matching inferiors we have.  */
@@ -4628,7 +4649,17 @@ fetch_inferior_event ()
        the event.  */
     scoped_disable_commit_resumed disable_commit_resumed ("handling event");
 
-    if (!do_target_wait (minus_one_ptid, &ecs, TARGET_WNOHANG))
+    /* Is the current thread performing an inferior function call as part
+       of a breakpoint condition evaluation?  */
+    bool in_cond_eval = (inferior_ptid != null_ptid
+			 && inferior_thread ()->control.in_cond_eval);
+
+    /* If the thread is in the middle of the condition evaluation, wait for
+       an event from the current thread.  Otherwise, wait for an event from
+       any thread.  */
+    ptid_t waiton_ptid = in_cond_eval ? inferior_ptid : minus_one_ptid;
+
+    if (!do_target_wait (waiton_ptid, &ecs, TARGET_WNOHANG))
       {
 	infrun_debug_printf ("do_target_wait returned no event");
 	disable_commit_resumed.reset_and_commit ();
@@ -4686,7 +4717,12 @@ fetch_inferior_event ()
 	    bool should_notify_stop = true;
 	    bool proceeded = false;
 
-	    stop_all_threads_if_all_stop_mode ();
+	    /* If the thread that stopped just completed an inferior
+	       function call as part of a condition evaluation, then we
+	       don't want to stop all the other threads.  */
+	    if (ecs.event_thread == nullptr
+		|| !ecs.event_thread->control.in_cond_eval)
+	      stop_all_threads_if_all_stop_mode ();
 
 	    clean_up_just_stopped_threads_fsms (&ecs);
 
@@ -4713,7 +4749,7 @@ fetch_inferior_event ()
 		  proceeded = normal_stop ();
 	      }
 
-	    if (!proceeded)
+	    if (!proceeded && !in_cond_eval)
 	      {
 		inferior_event_handler (INF_EXEC_COMPLETE);
 		cmd_done = 1;
diff --git a/gdb/infrun.h b/gdb/infrun.h
index 6339fd997e1..5f83ca2b4c3 100644
--- a/gdb/infrun.h
+++ b/gdb/infrun.h
@@ -406,7 +406,8 @@ extern void maybe_call_commit_resumed_all_targets ();
 
 struct scoped_enable_commit_resumed
 {
-  explicit scoped_enable_commit_resumed (const char *reason);
+  explicit scoped_enable_commit_resumed (const char *reason,
+					 bool force_p = false);
   ~scoped_enable_commit_resumed ();
 
   DISABLE_COPY_AND_ASSIGN (scoped_enable_commit_resumed);
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
new file mode 100644
index 00000000000..38a5bc284df
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
@@ -0,0 +1,135 @@
+/* Copyright 2022-2024 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 <pthread.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <sched.h>
+
+#define NUM_THREADS 2
+
+pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+
+/* Some global variables to poke, just for something to do.  */
+volatile int global_var_0 = 0;
+volatile int global_var_1 = 0;
+
+/* This flag is updated from GDB.  */
+volatile int raise_signal = 0;
+
+/* Implement the breakpoint condition function.  Release the other thread
+   and try to give the other thread a chance to run.  Then return ANSWER.  */
+int
+condition_core_func (int answer)
+{
+  /* This unlock should release the other thread.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  /* And this yield and sleep should (hopefully) give the other thread a
+     chance to run.  This isn't guaranteed of course, but once the other
+     thread does run it should hit a breakpoint, which GDB should
+     (temporarily) ignore, so there's no easy way for us to know the other
+     thread has done what it needs to, thus, yielding and sleeping is the
+     best we can do.  */
+  sched_yield ();
+  sleep (2);
+
+  return answer;
+}
+
+void
+stop_marker ()
+{
+  int a = 100;	/* Final breakpoint here.  */
+}
+
+/* A breakpoint condition function that always returns true.  */
+int
+condition_true_func ()
+{
+  return condition_core_func (1);
+}
+
+/* A breakpoint condition function that always returns false.  */
+int
+condition_false_func ()
+{
+  return condition_core_func (0);
+}
+
+void *
+worker_func (void *arg)
+{
+  volatile int *ptr = 0;
+  int tid = *((int *) arg);
+
+  switch (tid)
+    {
+    case 0:
+      global_var_0 = 11;	/* First thread breakpoint.  */
+      break;
+
+    case 1:
+      if (pthread_mutex_lock (&mutex) != 0)
+	abort ();
+      if (raise_signal)
+	global_var_1 = *ptr;	/* Signal here.  */
+      else
+	global_var_1 = 99;	/* Other thread breakpoint.  */
+      break;
+
+    default:
+      abort ();
+    }
+
+  return NULL;
+}
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+
+  /* Set an alarm, just in case the test deadlocks.  */
+  alarm (300);
+
+  /* We want the mutex to start locked.  */
+  if (pthread_mutex_lock (&mutex) != 0)
+    abort ();
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      void *retval;
+      pthread_join (threads[i], &retval);
+    }
+
+  /* Unlock once we're done, just for cleanliness.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
new file mode 100644
index 00000000000..b5c0d84afbf
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
@@ -0,0 +1,174 @@
+# Copyright 2022-2024 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/>.
+
+# Test for conditional breakpoints where the breakpoint condition includes
+# an inferior function call.
+#
+# The tests in this script are testing what happens when an event arrives in
+# another thread while GDB is waiting for the inferior function call (in the
+# breakpoint condition) to finish.
+#
+# The expectation is that GDB will queue events for other threads and wait
+# for the inferior function call to complete, if the condition is true, then
+# the conditional breakpoint should be reported first.  The other thread
+# event should of course, not get lost, and should be reported as soon as
+# the user tries to continue the inferior.
+#
+# If the conditional breakpoint ends up not being taken (the condition is
+# false), then the other thread event should be reported immediately.
+#
+# This script tests what happens when the other thread event is (a) the
+# other thread hitting a breakpoint, and (b) the other thread taking a
+# signal (SIGSEGV in this case).
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] == -1 } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "First thread breakpoint"]
+set other_bp_line [gdb_get_line_number "Other thread breakpoint"]
+set final_bp_line [gdb_get_line_number "Final breakpoint here"]
+set signal_line [gdb_get_line_number "Signal here"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if { ![runto_main] } {
+	return -1
+    }
+
+    return 0
+}
+
+# Run a test of GDB's conditional breakpoints, where the conditions include
+# inferior function calls.  While the inferior function call is executing
+# another thread will hit a breakpoint (when OTHER_THREAD_SIGNAL is false),
+# or receive a signal (when OTHER_THREAD_SIGNAL is true).  GDB should report
+# the conditional breakpoint first (if the condition is true), and then
+# report the second thread event once the inferior is continued again.
+#
+# When STOP_AT_COND is true then the conditional breakpoint will have a
+# condition that evaluates to true (and GDB will stop at the breakpoint),
+# otherwise, the condition will evaluate to false (and GDB will not stop at
+# the breakpoint).
+proc run_condition_test { stop_at_cond other_thread_signal \
+			      target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint.
+    if { $stop_at_cond } {
+	set cond_func "condition_true_func"
+    } else {
+	set cond_func "condition_false_func"
+    }
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (${cond_func} ())"
+    set cond_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			"get number for conditional breakpoint"]
+
+    if { $other_thread_signal } {
+	# Arrange for the other thread to raise a signal while GDB is
+	# evaluating the breakpoint condition.
+	gdb_test_no_output "set raise_signal = 1"
+    } else {
+	# And a breakpoint that will be hit by another thread only once the
+	# breakpoint condition starts to be evaluated.
+	gdb_breakpoint "${::srcfile}:${::other_bp_line}"
+	set other_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			      "get number for other breakpoint"]
+    }
+
+    # A final breakpoint once the test has completed.
+    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
+    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			  "get number for final breakpoint"]
+
+    if { $stop_at_cond } {
+	# Continue.  The first breakpoint we hit should be the conditional
+	# breakpoint.  The other thread will have hit its breakpoint, but
+	# that will have been deferred until the conditional breakpoint is
+	# reported.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${cond_bp_num}, worker_func \[^\r\n\]+:${::cond_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+First thread breakpoint\[^\r\n\]+"] \
+	    "hit the conditional breakpoint"
+    }
+
+    if { $other_thread_signal } {
+	# Now continue again, the other thread will now report that it
+	# received a signal.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" received signal SIGSEGV, Segmentation fault\\." \
+		 "\\\[Switching to Thread \[^\r\n\]+\\\]" \
+		 "${::hex} in worker_func \[^\r\n\]+:${::signal_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Signal here\[^\r\n\]+"] \
+	    "received signal in other thread"
+    } else {
+	# Now continue again, the other thread will now report its
+	# breakpoint.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${other_bp_num}, worker_func \[^\r\n\]+:${::other_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Other thread breakpoint\[^\r\n\]+"] \
+	    "hit the breakpoint in other thread"
+
+	# Run to the stop marker.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${final_bp_num}, stop_marker \[^\r\n\]+:${::final_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Final breakpoint here\[^\r\n\]+"] \
+	    "hit the final breakpoint"
+    }
+
+    gdb_exit
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	foreach_with_prefix other_thread_signal { true false } {
+	    foreach_with_prefix stop_at_cond { true false } {
+		run_condition_test $stop_at_cond $other_thread_signal \
+		    $target_async $target_non_stop
+	    }
+	}
+    }
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
new file mode 100644
index 00000000000..2e23f1229c5
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
@@ -0,0 +1,89 @@
+/* Copyright 2022-2024 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 <pthread.h>
+#include <unistd.h>
+
+#define NUM_THREADS 3
+
+int
+is_matching_tid (int *tid_ptr, int tid_value)
+{
+  return *tid_ptr == tid_value;
+}
+
+int
+return_true ()
+{
+  return 1;
+}
+
+int
+return_false ()
+{
+  return 0;
+}
+
+int
+function_that_segfaults ()
+{
+  int *p = 0;
+  *p = 1;	/* Segfault happens here.   */
+}
+
+int
+function_with_breakpoint ()
+{
+  return 1;	/* Nested breakpoint.  */
+}
+
+void *
+worker_func (void *arg)
+{
+  int a = 42;	/* Breakpoint here.  */
+}
+
+void
+stop_marker ()
+{
+  int b = 99;	/* Stop marker.  */
+}
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+
+  alarm (300);
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      void *retval;
+      pthread_join (threads[i], &retval);
+    }
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
new file mode 100644
index 00000000000..d6069ebaa58
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
@@ -0,0 +1,235 @@
+# Copyright 2022-2024 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/>.
+
+# Some simple tests of inferior function calls from breakpoint
+# conditions, in multi-threaded inferiors.
+#
+# This test sets up a multi-threaded inferior, and places a breakpoint
+# at a location that many of the threads will reach.  We repeat the
+# test with different conditions, sometimes a single thread should
+# stop at the breakpoint, sometimes multiple threads should stop, and
+# sometimes no threads should stop.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] == -1 } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "Breakpoint here"]
+set stop_bp_line [gdb_get_line_number "Stop marker"]
+set nested_bp_line [gdb_get_line_number "Nested breakpoint"]
+set segv_line [gdb_get_line_number "Segfault happens here"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if { ![runto_main] } {
+	return -1
+    }
+
+    return 0
+}
+
+# Run a test of GDB's conditional breakpoints, where the conditions include
+# inferior function calls.
+#
+# CONDITION is the expression to be used as the breakpoint condition.
+#
+# N_EXPECTED_HITS is the number of threads that we expect to stop due to
+# CONDITON.
+#
+# MESSAGE is used as a test name prefix.
+proc run_condition_test { message n_expected_hits condition \
+			      target_async target_non_stop } {
+    with_test_prefix $message {
+
+	if { [start_gdb_and_runto_main $target_async \
+		  $target_non_stop] == -1 } {
+	    return
+	}
+
+	# Use this convenience variable to track how often the
+	# breakpoint condition has been evaluated.  This should be
+	# once per thread.
+	gdb_test "set \$n_cond_eval = 0"
+
+	# Setup the conditional breakpoint.
+	gdb_breakpoint \
+	    "${::srcfile}:${::cond_bp_line} if ((++\$n_cond_eval) && (${condition}))"
+
+	# And a breakpoint that we hit when the test is over, this one is
+	# not conditional.  Only the main thread gets here once all the
+	# other threads have finished.
+	gdb_breakpoint "${::srcfile}:${::stop_bp_line}"
+
+	# The number of times we stop at the conditional breakpoint.
+	set n_hit_condition 0
+
+	# Now keep 'continue'-ing GDB until all the threads have finished
+	# and we reach the stop_marker breakpoint.
+	gdb_test_multiple "continue" "spot all breakpoint hits" {
+	    -re " worker_func \[^\r\n\]+${::srcfile}:${::cond_bp_line}\r\n${::decimal}\\s+\[^\r\n\]+Breakpoint here\[^\r\n\]+\r\n${::gdb_prompt} $" {
+		incr n_hit_condition
+		send_gdb "continue\n"
+		exp_continue
+	    }
+
+	    -re " stop_marker \[^\r\n\]+${::srcfile}:${::stop_bp_line}\r\n${::decimal}\\s+\[^\r\n\]+Stop marker\[^\r\n\]+\r\n${::gdb_prompt} $" {
+		pass $gdb_test_name
+	    }
+	}
+
+	gdb_assert { $n_hit_condition == $n_expected_hits } \
+	    "stopped at breakpoint the expected number of times"
+
+	# Ensure the breakpoint condition was evaluated once per thread.
+	gdb_test "print \$n_cond_eval" "= 3" \
+	    "condition was evaluated in each thread"
+    }
+}
+
+# Check that after handling a conditional breakpoint (where the condition
+# includes an inferior call), it is still possible to kill the running
+# inferior, and then restart the inferior.
+#
+# At once point doing this would result in GDB giving an assertion error.
+proc_with_prefix run_kill_and_restart_test { target_async target_non_stop } {
+    # This test relies on the 'start' command, which is not possible with
+    # the plain 'remote' target.
+    if { [target_info gdb_protocol] == "remote" } {
+	return
+    }
+
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint.
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 1))"
+    gdb_continue_to_breakpoint "worker_func"
+
+    # Now kill the program being debugged.
+    gdb_test "kill" "" "kill process" \
+	"Kill the program being debugged.*y or n. $" "y"
+
+    # Check we can restart the inferior.  At one point this would trigger an
+    # assertion.
+    gdb_start_cmd
+}
+
+# Create a conditional breakpoint which includes a call to a function that
+# segfaults.  Run GDB and check what happens when the inferior segfaults
+# during the inferior call.
+proc_with_prefix run_bp_cond_segfaults { target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # This test relies on the inferior segfaulting when trying to
+    # access address zero.
+    if { [is_address_zero_readable] } {
+	return
+    }
+
+    # Setup the conditional breakpoint, include a call to
+    # 'function_that_segfaults', which triggers the segfault.
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 0) && function_that_segfaults ())"
+    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of conditional breakpoint"]
+
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     ".*" \
+	     "Thread ${::decimal} \"infcall-from-bp\" received signal SIGSEGV, Segmentation fault\\." \
+	     "${::hex} in function_that_segfaults \\(\\) at \[^\r\n\]+:${::segv_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Segfault happens here\[^\r\n\]+" \
+	     "Error in testing condition for breakpoint ${bp_1_num}:" \
+	     "The program being debugged was signaled while in a function called from GDB\\." \
+	     "GDB remains in the frame where the signal was received\\." \
+	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(function_that_segfaults\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+}
+
+# Create a conditional breakpoint which includes a call to a function that
+# itself has a breakpoint set within it.  Run GDB and check what happens
+# when GDB hits the nested breakpoint.
+proc_with_prefix run_bp_cond_hits_breakpoint { target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint, include a call to
+    # 'function_with_breakpoint' in which we will shortly place a
+    # breakpoint.
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (is_matching_tid (arg, 0) && function_with_breakpoint ())"
+    set bp_1_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of conditional breakpoint"]
+
+    gdb_breakpoint "${::srcfile}:${::nested_bp_line}"
+    set bp_2_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		      "get number of nested breakpoint"]
+
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     ".*" \
+	     "Thread ${::decimal} \"infcall-from-bp\" hit Breakpoint ${bp_2_num}, function_with_breakpoint \\(\\) at \[^\r\n\]+:${::nested_bp_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Nested breakpoint\[^\r\n\]+" \
+	     "Error in testing condition for breakpoint ${bp_1_num}:" \
+	     "The program being debugged stopped while in a function called from GDB\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(function_with_breakpoint\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	run_condition_test "exactly one thread is hit" \
+	    1 "is_matching_tid (arg, 1)" \
+	    $target_async $target_non_stop
+	run_condition_test "exactly two threads are hit" \
+	    2 "(is_matching_tid (arg, 0) || is_matching_tid (arg, 2))" \
+	    $target_async $target_non_stop
+	run_condition_test "all three threads are hit" \
+	    3 "return_true ()" \
+	    $target_async $target_non_stop
+	run_condition_test "no thread is hit" \
+	    0 "return_false ()" \
+	    $target_async $target_non_stop
+
+	run_kill_and_restart_test $target_async $target_non_stop
+	run_bp_cond_segfaults $target_async $target_non_stop
+	run_bp_cond_hits_breakpoint $target_async $target_non_stop
+    }
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
new file mode 100644
index 00000000000..0b045f86fad
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
@@ -0,0 +1,139 @@
+/* Copyright 2022-2024 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 <pthread.h>
+#include <unistd.h>
+#include <semaphore.h>
+#include <stdlib.h>
+
+#define NUM_THREADS 5
+
+/* Semaphores, used to track when threads have started, and to control
+   when the threads finish.  */
+sem_t startup_semaphore;
+sem_t finish_semaphore;
+
+/* Mutex to control when the first worker thread hit a breakpoint
+   location.  */
+pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+
+/* Global variable to poke, just so threads have something to do.  */
+volatile int global_var = 0;
+
+int
+return_true ()
+{
+  return 1;
+}
+
+int
+return_false ()
+{
+  return 0;
+}
+
+void *
+worker_func (void *arg)
+{
+  int tid = *((int *) arg);
+
+  switch (tid)
+    {
+    case 0:
+      /* Wait for MUTEX to become available, then pass through the
+	 conditional breakpoint location.  */
+      if (pthread_mutex_lock (&mutex) != 0)
+	abort ();
+      global_var = 99;	/* Conditional breakpoint here.  */
+      if (pthread_mutex_unlock (&mutex) != 0)
+	abort ();
+      break;
+
+    default:
+      /* Notify the main thread that the thread has started, then wait for
+	 the main thread to tell us to finish.  */
+      sem_post (&startup_semaphore);
+      if (sem_wait (&finish_semaphore) != 0)
+	abort ();
+      break;
+    }
+}
+
+void
+stop_marker ()
+{
+  global_var = 99;	/* Stop marker.  */
+}
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+  void *retval;
+
+  /* An alarm, just in case the thread deadlocks.  */
+  alarm (300);
+
+  /* Semaphore initialization.  */
+  if (sem_init (&startup_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&finish_semaphore, 0, 0) != 0)
+    abort ();
+
+  /* Lock MUTEX, this prevents the first worker thread from rushing ahead.  */
+  if (pthread_mutex_lock (&mutex) != 0)
+    abort ();
+
+  /* Worker thread creation.  */
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  /* Wait for every thread (other than the first) to tell us it has started
+     up.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    {
+      if (sem_wait (&startup_semaphore) != 0)
+	abort ();
+    }
+
+  /* Unlock the first thread so it can proceed.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  /* Wait for the first thread only.  */
+  pthread_join (threads[0], &retval);
+
+  /* Now post FINISH_SEMAPHORE to allow all the other threads to finish.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    sem_post (&finish_semaphore);
+
+  /* Now wait for the remaining threads to complete.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    pthread_join (threads[i], &retval);
+
+  /* Semaphore cleanup.  */
+  sem_destroy (&finish_semaphore);
+  sem_destroy (&startup_semaphore);
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
new file mode 100644
index 00000000000..2c3623ec3a5
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
@@ -0,0 +1,117 @@
+# Copyright 2022-2024 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 reprocuces bug gdb/28942, performing an inferior function
+# call from a breakpoint condition in a multi-threaded inferior.
+#
+# The important part of this test is that, when the conditional
+# breakpoint is hit, and the condition (which includes an inferior
+# function call) is evaluated, the other threads are running.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] == -1 } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "Conditional breakpoint here"]
+set final_bp_line [gdb_get_line_number "Stop marker"]
+
+# Start GDB based on TARGET_ASYNC and TARGET_NON_STOP, and then runto main.
+proc start_gdb_and_runto_main { target_async target_non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if { ![runto_main] } {
+	return -1
+    }
+
+    return 0
+}
+
+# Run a test of GDB's conditional breakpoints, where the conditions include
+# inferior function calls.
+#
+# TARGET_ASYNC and TARGET_NON_STOP are used when starting up GDB.
+#
+# When STOP_AT_COND is true the breakpoint condtion will evaluate to
+# true, and GDB will stop at the breakpoint.  Otherwise, the
+# breakpoint condition will evaluate to false and GDB will not stop at
+# the breakpoint.
+proc run_condition_test { stop_at_cond \
+			      target_async target_non_stop } {
+    if { [start_gdb_and_runto_main $target_async \
+	      $target_non_stop] == -1 } {
+	return
+    }
+
+    # Setup the conditional breakpoint.
+    if { $stop_at_cond } {
+	set cond_func "return_true"
+    } else {
+	set cond_func "return_false"
+    }
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (${cond_func} ())"
+    set cond_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			"get number for conditional breakpoint"]
+
+    # And a breakpoint that we hit when the test is over, this one is
+    # not conditional.
+    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
+    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			  "get number for final breakpoint"]
+
+    if { $stop_at_cond } {
+	# Continue.  The first breakpoint we hit should be the conditional
+	# breakpoint.  The other thread will have hit its breakpoint, but
+	# that will have been deferred until the conditional breakpoint is
+	# reported.
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${cond_bp_num}, worker_func \[^\r\n\]+:${::cond_bp_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Conditional breakpoint here\[^\r\n\]+"] \
+	    "hit the conditional breakpoint"
+    }
+
+    # Run to the stop marker.
+    gdb_test "continue" \
+	[multi_line \
+	     "Continuing\\." \
+	     ".*" \
+	     "" \
+	     "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${final_bp_num}, stop_marker \[^\r\n\]+:${::final_bp_line}" \
+	     "${::decimal}\\s+\[^\r\n\]+Stop marker\[^\r\n\]+"] \
+	"hit the final breakpoint"
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	foreach_with_prefix stop_at_cond { true false } {
+	    run_condition_test $stop_at_cond \
+		$target_async $target_non_stop
+	}
+    }
+}
-- 
2.25.4


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

* [PATCHv11 3/5] gdb: add timeouts for inferior function calls
  2024-03-05 15:40                   ` [PATCHv11 0/5] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
  2024-03-05 15:40                     ` [PATCHv11 1/5] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
  2024-03-05 15:40                     ` [PATCHv11 2/5] gdb: fix b/p conditions with infcalls in multi-threaded inferiors Andrew Burgess
@ 2024-03-05 15:40                     ` Andrew Burgess
  2024-03-05 15:40                     ` [PATCHv11 4/5] gdb: introduce unwind-on-timeout setting Andrew Burgess
                                       ` (4 subsequent siblings)
  7 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2024-03-05 15:40 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Tankut Baris Aktemur, Eli Zaretskii

In the previous commits I have been working on improving inferior
function call support.  One thing that worries me about using inferior
function calls from a conditional breakpoint is: what happens if the
inferior function call fails?

If the failure is obvious, e.g. the thread performing the call
crashes, or hits a breakpoint, then this case is already well handled,
and the error is reported to the user.

But what if the thread performing the inferior call just deadlocks?
If the user made the call from a 'print' or 'call' command, then the
user might have some expectation of when the function call should
complete, and, when this time limit is exceeded, the user
will (hopefully) interrupt GDB and regain control of the debug
session.

But, when the inferior function call is from a breakpoint condition it
is much harder to understand that GDB is deadlocked within an inferior
call.  Maybe the breakpoint hasn't been hit yet?  Or maybe the
condition was always false?  Or maybe GDB is deadlocked in an inferior
call?  The only way to know for sure is for the user to periodically
interrupt the inferior, check on the state of all the threads, and
then continue.

Additionally, the focus of the previous commit was inferior function
calls, from a conditional breakpoint, in a multi-threaded inferior.
This opens up a whole new set of potential failure conditions.  For
example, what if the function called relies on interaction with some
other thread, and the other thread crashes?  Or hits a breakpoint?
Given how inferior function calls work (in a synchronous manner), a
stop event in some other thread is going to be ignored while the
inferior function call is being executed as part of a breakpoint
condition, and this means that GDB could get stuck waiting for the
original condition thread, which will now never complete.

In this commit I propose a solution to this problem.  A timeout.  For
targets that support async-mode we can install an event-loop timer
before starting the inferior function call.  When the timer expires we
will stop the thread performing the inferior function call.  With this
mechanism in place a user can be sure that any inferior call they make
will either complete, or timeout eventually.

Adding a timer like this is obviously a change in behaviour for the
more common 'call' and 'print' uses of inferior function calls, so, in
this patch, I propose having two different timers.  One I call the
'direct-call-timeout', which is used for 'call' and 'print' commands.
This timeout is by default set to unlimited, which, not surprisingly,
means there is no timeout in place.

A second timer, which I've called 'indirect-call-timeout', is used for
inferior function calls from breakpoint conditions.  This timeout has
a default value of 30 seconds.  This is a reasonably long time to
wait, and hopefully should be enough in most cases to allow the
inferior call to complete.  An inferior call that takes more than 30
seconds, which is installed on a breakpoint condition is really going
to slow down the debug session, so hopefully this is not a common use
case.

The user is, of course, free to reduce, or increase the timeout value,
and can always use Ctrl-c to interrupt an inferior function call, but
this timeout will ensure that GDB will stop at some point.

The new commands added by this commit are:

  set direct-call-timeout SECONDS
  show direct-call-timeout
  set indirect-call-timeout SECONDS
  show indirect-call-timeout

These new timeouts do depend on async-mode, so, if async-mode is
disabled (maint set target-async off), or not supported (e.g. target
sim), then the timeout is treated as unlimited (that is, no timeout is
set).

For targets that "fake" non-async mode, e.g. Linux native, where
non-async mode is really just async mode, but then we park the target
in a sissuspend, we could easily fix things so that the timeouts still
work, however, for targets that really are not async aware, like the
simulator, fixing things so that timeouts work correctly would be a
much bigger task - that effort would be better spent just making the
target async-aware.  And so, I'm happy for now that this feature will
only work on async targets.

The two new show commands will display slightly different text if the
current target is a non-async target, which should allow users to
understand what's going on.

There's a somewhat random test adjustment needed in gdb.base/help.exp,
the test uses a regexp with the apropos command, and expects to find a
single result.  Turns out the new settings I added also matched the
regexp, which broke the test.  I've updated the regexp a little to
exclude my new settings.

Reviewed-By: Tankut Baris Aktemur <tankut.baris.aktemur@intel.com>
Reviewed-By: Eli Zaretskii <eliz@gnu.org>
---
 gdb/NEWS                                      |  18 ++
 gdb/doc/gdb.texinfo                           |  66 ++++++
 gdb/infcall.c                                 | 210 +++++++++++++++++-
 gdb/testsuite/gdb.base/help.exp               |   2 +-
 gdb/testsuite/gdb.base/infcall-timeout.c      |  36 +++
 gdb/testsuite/gdb.base/infcall-timeout.exp    |  94 ++++++++
 .../infcall-from-bp-cond-timeout.c            | 169 ++++++++++++++
 .../infcall-from-bp-cond-timeout.exp          | 166 ++++++++++++++
 8 files changed, 756 insertions(+), 5 deletions(-)
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.c
 create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.exp
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
 create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp

diff --git a/gdb/NEWS b/gdb/NEWS
index 2638b3e0d9c..b98822f28b1 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -47,6 +47,24 @@ set remote thread-options-packet
 show remote thread-options-packet
   Set/show the use of the thread options packet.
 
+set direct-call-timeout SECONDS
+show direct-call-timeout
+set indirect-call-timeout SECONDS
+show indirect-call-timeout
+  These new settings can be used to limit how long GDB will wait for
+  an inferior function call to complete.  The direct timeout is used
+  for inferior function calls from e.g. 'call' and 'print' commands,
+  while the indirect timeout is used for inferior function calls from
+  within a conditional breakpoint expression.
+
+  The default for the direct timeout is unlimited, while the default
+  for the indirect timeout is 30 seconds.
+
+  These timeouts will only have an effect for targets that are
+  operating in async mode.  For non-async targets the timeouts are
+  ignored, GDB will wait indefinitely for an inferior function to
+  complete, unless interrupted by the user using Ctrl-C.
+
 * New features in the GDB remote stub, GDBserver
 
   ** The --remote-debug and --event-loop-debug command line options
diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index 34cd567f811..6b98a960442 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -21001,6 +21001,72 @@
 @code{step}, etc).  In this case, when the inferior finally returns to
 the dummy-frame, @value{GDBN} will once again halt the inferior.
 
+On targets that support asynchronous execution (@pxref{Background
+Execution}) @value{GDBN} can place a timeout on any functions called
+from @value{GDBN}.  If the timeout expires and the function call is
+still ongoing, then @value{GDBN} will interrupt the program.
+
+For targets that don't support asynchronous execution
+(@pxref{Background Execution}) then timeouts for functions called from
+@value{GDBN} are not supported, the timeout settings described below
+will be treated as @code{unlimited}, meaning @value{GDBN} will wait
+indefinitely for function call to complete, unless interrupted by the
+user using @kbd{Ctrl-C}.
+
+@table @code
+@item set direct-call-timeout @var{seconds}
+@kindex set direct-call-timeout
+@cindex timeout for called functions
+Set the timeout used when calling functions in the program to
+@var{seconds}, which should be an integer greater than zero, or the
+special value @code{unlimited}, which indicates no timeout should be
+used.  The default for this setting is @code{unlimited}.
+
+This setting is used when the user calls a function directly from the
+command prompt, for example with a @code{call} or @code{print}
+command.
+
+This setting only works for targets that support asynchronous
+execution (@pxref{Background Execution}), for any other target the
+setting is treated as @code{unlimited}.
+
+@item show direct-call-timeout
+@kindex show direct-call-timeout
+@cindex timeout for called functions
+Show the timeout used when calling functions in the program with a
+@code{call} or @code{print} command.
+@end table
+
+It is also possible to call functions within the program from the
+condition of a conditional breakpoint (@pxref{Conditions, ,Break
+Conditions}).  A different setting controls the timeout used for
+function calls made from a breakpoint condition.
+
+@table @code
+@item set indirect-call-timeout @var{seconds}
+@kindex set indirect-call-timeout
+@cindex timeout for called functions
+Set the timeout used when calling functions in the program from a
+breakpoint or watchpoint condition to @var{seconds}, which should be
+an integer greater than zero, or the special value @code{unlimited},
+which indicates no timeout should be used.  The default for this
+setting is @code{30} seconds.
+
+This setting only works for targets that support asynchronous
+execution (@pxref{Background Execution}), for any other target the
+setting is treated as @code{unlimited}.
+
+If a function called from a breakpoint or watchpoint condition times
+out, then @value{GDBN} will stop at the point where the timeout
+occurred.  The breakpoint condition evaluation will be abandoned.
+
+@item show indirect-call-timeout
+@kindex show indirect-call-timeout
+@cindex timeout for called functions
+Show the timeout used when calling functions in the program from a
+breakpoint or watchpoint condition.
+@end table
+
 @subsection Calling functions with no debug info
 
 @cindex no debug info functions
diff --git a/gdb/infcall.c b/gdb/infcall.c
index bfcac20e3f5..7dc1324023f 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -96,6 +96,53 @@ show_may_call_functions_p (struct ui_file *file, int from_tty,
 	      value);
 }
 
+/* A timeout (in seconds) for direct inferior calls.  A direct inferior
+   call is one the user triggers from the prompt, e.g. with a 'call' or
+   'print' command.  Compare with the definition of indirect calls below.  */
+
+static unsigned int direct_call_timeout = UINT_MAX;
+
+/* Implement 'show direct-call-timeout'.  */
+
+static void
+show_direct_call_timeout (struct ui_file *file, int from_tty,
+			  struct cmd_list_element *c, const char *value)
+{
+  if (target_has_execution () && !target_can_async_p ())
+    gdb_printf (file, _("Current target does not support async mode, timeout "
+			"for direct inferior calls is \"unlimited\".\n"));
+  else if (direct_call_timeout == UINT_MAX)
+    gdb_printf (file, _("Timeout for direct inferior function calls "
+			"is \"unlimited\".\n"));
+  else
+    gdb_printf (file, _("Timeout for direct inferior function calls "
+			"is \"%s seconds\".\n"), value);
+}
+
+/* A timeout (in seconds) for indirect inferior calls.  An indirect inferior
+   call is one that originates from within GDB, for example, when
+   evaluating an expression for a conditional breakpoint.  Compare with
+   the definition of direct calls above.  */
+
+static unsigned int indirect_call_timeout = 30;
+
+/* Implement 'show indirect-call-timeout'.  */
+
+static void
+show_indirect_call_timeout (struct ui_file *file, int from_tty,
+			  struct cmd_list_element *c, const char *value)
+{
+  if (target_has_execution () && !target_can_async_p ())
+    gdb_printf (file, _("Current target does not support async mode, timeout "
+			"for indirect inferior calls is \"unlimited\".\n"));
+  else if (indirect_call_timeout == UINT_MAX)
+    gdb_printf (file, _("Timeout for indirect inferior function calls "
+			"is \"unlimited\".\n"));
+  else
+    gdb_printf (file, _("Timeout for indirect inferior function calls "
+			"is \"%s seconds\".\n"), value);
+}
+
 /* How you should pass arguments to a function depends on whether it
    was defined in K&R style or prototype style.  If you define a
    function using the K&R syntax that takes a `float' argument, then
@@ -620,6 +667,85 @@ call_thread_fsm::should_notify_stop ()
   return true;
 }
 
+/* A class to control creation of a timer that will interrupt a thread
+   during an inferior call.  */
+struct infcall_timer_controller
+{
+  /* Setup an event-loop timer that will interrupt PTID if the inferior
+     call takes too long.  DIRECT_CALL_P is true when this inferior call is
+     a result of the user using a 'print' or 'call' command, and false when
+     this inferior call is a result of e.g. a conditional breakpoint
+     expression, this is used to select which timeout to use.  */
+  infcall_timer_controller (thread_info *thr, bool direct_call_p)
+    : m_thread (thr)
+  {
+    unsigned int timeout
+      = direct_call_p ? direct_call_timeout : indirect_call_timeout;
+    if (timeout < UINT_MAX && target_can_async_p ())
+      {
+	int ms = timeout * 1000;
+	int id = create_timer (ms, infcall_timer_controller::timed_out, this);
+	m_timer_id.emplace (id);
+	infcall_debug_printf ("Setting up infcall timeout timer for "
+			      "ptid %s: %d milliseconds",
+			      m_thread->ptid.to_string ().c_str (), ms);
+      }
+  }
+
+  /* Destructor.  Ensure that the timer is removed from the event loop.  */
+  ~infcall_timer_controller ()
+  {
+    /* If the timer has already triggered, then it will have already been
+       deleted from the event loop.  If the timer has not triggered, then
+       delete it now.  */
+    if (m_timer_id.has_value () && !m_triggered)
+      delete_timer (*m_timer_id);
+
+    /* Just for clarity, discard the timer id now.  */
+    m_timer_id.reset ();
+  }
+
+  /* Return true if there was a timer in place, and the timer triggered,
+     otherwise, return false.  */
+  bool triggered_p ()
+  {
+    gdb_assert (!m_triggered || m_timer_id.has_value ());
+    return m_triggered;
+  }
+
+private:
+  /* The thread we should interrupt.  */
+  thread_info *m_thread;
+
+  /* Set true when the timer is triggered.  */
+  bool m_triggered = false;
+
+  /* Given a value when a timer is in place.  */
+  std::optional<int> m_timer_id;
+
+  /* Callback for the timer, forwards to ::trigger below.  */
+  static void
+  timed_out (gdb_client_data context)
+  {
+    infcall_timer_controller *ctrl
+      = static_cast<infcall_timer_controller *> (context);
+    ctrl->trigger ();
+  }
+
+  /* Called when the timer goes off.  Stop thread M_THREAD.  */
+  void
+  trigger ()
+  {
+    m_triggered = true;
+
+    scoped_disable_commit_resumed disable_commit_resumed ("infcall timeout");
+
+    infcall_debug_printf ("Stopping thread %s",
+			  m_thread->ptid.to_string ().c_str ());
+    target_stop (m_thread->ptid);
+  }
+};
+
 /* Subroutine of call_function_by_hand to simplify it.
    Start up the inferior and wait for it to stop.
    Return the exception if there's an error, or an exception with
@@ -630,13 +756,15 @@ call_thread_fsm::should_notify_stop ()
 
 static struct gdb_exception
 run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
-		   struct thread_info *call_thread, CORE_ADDR real_pc)
+		   struct thread_info *call_thread, CORE_ADDR real_pc,
+		   bool *timed_out_p)
 {
   INFCALL_SCOPED_DEBUG_ENTER_EXIT;
 
   struct gdb_exception caught_error;
   ptid_t call_thread_ptid = call_thread->ptid;
   int was_running = call_thread->state == THREAD_RUNNING;
+  *timed_out_p = false;
 
   infcall_debug_printf ("call function at %s in thread %s, was_running = %d",
 			core_addr_to_string (real_pc),
@@ -681,11 +809,23 @@ run_inferior_call (std::unique_ptr<call_thread_fsm> sm,
       infrun_debug_show_threads ("non-exited threads after proceed for inferior-call",
 				 all_non_exited_threads ());
 
+      /* Setup a timer (if possible, and if the settings allow) to prevent
+	 the inferior call running forever.  */
+      bool direct_call_p = !call_thread->control.in_cond_eval;
+      infcall_timer_controller infcall_timer (call_thread, direct_call_p);
+
       /* Inferior function calls are always synchronous, even if the
 	 target supports asynchronous execution.  */
       wait_sync_command_done ();
 
-      infcall_debug_printf ("inferior call completed successfully");
+      /* If the timer triggered then the inferior call failed.  */
+      if (infcall_timer.triggered_p ())
+	{
+	  infcall_debug_printf ("inferior call timed out");
+	  *timed_out_p = true;
+	}
+      else
+	infcall_debug_printf ("inferior call completed successfully");
     }
   catch (gdb_exception &e)
     {
@@ -1355,6 +1495,10 @@ call_function_by_hand_dummy (struct value *function,
   scoped_restore restore_stopped_by_random_signal
     = make_scoped_restore (&stopped_by_random_signal, 0);
 
+  /* Set to true by the call to run_inferior_call below if the inferior
+     call is artificially interrupted by GDB due to taking too long.  */
+  bool timed_out_p = false;
+
   /* - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP - SNIP -
      If you're looking to implement asynchronous dummy-frames, then
      just below is the place to chop this function in two..  */
@@ -1381,7 +1525,8 @@ call_function_by_hand_dummy (struct value *function,
 			      struct_addr);
     {
       std::unique_ptr<call_thread_fsm> sm_up (sm);
-      e = run_inferior_call (std::move (sm_up), call_thread.get (), real_pc);
+      e = run_inferior_call (std::move (sm_up), call_thread.get (), real_pc,
+			     &timed_out_p);
     }
 
     if (e.reason < 0)
@@ -1540,7 +1685,10 @@ When the function is done executing, GDB will silently stop."),
       std::string name = get_function_name (funaddr, name_buf,
 					    sizeof (name_buf));
 
-      if (stopped_by_random_signal)
+      /* If the inferior call timed out then it will have been interrupted
+	 by a signal, but we want to report this differently to the user,
+	 which is done later in this function.  */
+      if (stopped_by_random_signal && !timed_out_p)
 	{
 	  /* We stopped inside the FUNCTION because of a random
 	     signal.  Further execution of the FUNCTION is not
@@ -1591,6 +1739,36 @@ GDB remains in the frame where the signal was received.\n\
 To change this behavior use \"set unwindonsignal on\".\n\
 Evaluation of the expression containing the function\n\
 (%s) will be abandoned.\n\
+When the function is done executing, GDB will silently stop."),
+		     name.c_str ());
+	    }
+	}
+
+      if (timed_out_p)
+	{
+	  /* A timeout results in a signal being sent to the inferior.  */
+	  gdb_assert (stopped_by_random_signal);
+
+	  /* Indentation is weird here.  A later patch is going to move the
+	    following block into an if/else, so I'm leaving the indentation
+	    here to minimise the later patch.
+
+	    Also, the error message used below refers to 'set
+	    unwind-on-timeout' which doesn't exist yet.  This will be added
+	    in a later commit, I'm leaving this in for now to minimise the
+	    churn caused by the commit that adds unwind-on-timeout.  */
+	    {
+	      /* The user wants to stay in the frame where we stopped
+		 (default).  Discard inferior status, we're not at the same
+		 point we started at.  */
+	      discard_infcall_control_state (inf_status.release ());
+
+	      error (_("\
+The program being debugged timed out while in a function called from GDB.\n\
+GDB remains in the frame where the timeout occurred.\n\
+To change this behavior use \"set unwind-on-timeout on\".\n\
+Evaluation of the expression containing the function\n\
+(%s) will be abandoned.\n\
 When the function is done executing, GDB will silently stop."),
 		     name.c_str ());
 	    }
@@ -1704,6 +1882,30 @@ The default is to unwind the frame."),
 			   show_unwind_on_terminating_exception_p,
 			   &setlist, &showlist);
 
+  add_setshow_uinteger_cmd ("direct-call-timeout", no_class,
+			    &direct_call_timeout, _("\
+Set the timeout, for direct calls to inferior function calls."), _("\
+Show the timeout, for direct calls to inferior function calls."), _("\
+If running on a target that supports, and is running in, async mode\n\
+then this timeout is used for any inferior function calls triggered\n\
+directly from the prompt, i.e. from a 'call' or 'print' command.  The\n\
+timeout is specified in seconds."),
+			    nullptr,
+			    show_direct_call_timeout,
+			    &setlist, &showlist);
+
+  add_setshow_uinteger_cmd ("indirect-call-timeout", no_class,
+			    &indirect_call_timeout, _("\
+Set the timeout, for indirect calls to inferior function calls."), _("\
+Show the timeout, for indirect calls to inferior function calls."), _("\
+If running on a target that supports, and is running in, async mode\n\
+then this timeout is used for any inferior function calls triggered\n\
+indirectly, i.e. being made as part of a breakpoint, or watchpoint,\n\
+condition expression.  The timeout is specified in seconds."),
+			    nullptr,
+			    show_indirect_call_timeout,
+			    &setlist, &showlist);
+
   add_setshow_boolean_cmd
     ("infcall", class_maintenance, &debug_infcall,
      _("Set inferior call debugging."),
diff --git a/gdb/testsuite/gdb.base/help.exp b/gdb/testsuite/gdb.base/help.exp
index 5ea5c79d3ec..056e352f99f 100644
--- a/gdb/testsuite/gdb.base/help.exp
+++ b/gdb/testsuite/gdb.base/help.exp
@@ -122,7 +122,7 @@ gdb_test "help info bogus-gdb-command" "Undefined info command: \"bogus-gdb-comm
 gdb_test "help gotcha" "Undefined command: \"gotcha\"\.  Try \"help\"\."
 
 # Test apropos regex.
-gdb_test "apropos \\\(print\[\^\[ bsiedf\\\".-\]\\\)" "handle -- Specify how to handle signals\."
+gdb_test "apropos \\\(print\[\^\[ bsiedf\\\"'.-\]\\\)" "handle -- Specify how to handle signals\."
 # Test apropos >1 word string.
 gdb_test "apropos handle signal" "handle -- Specify how to handle signals\."
 # Test apropos apropos.
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.c b/gdb/testsuite/gdb.base/infcall-timeout.c
new file mode 100644
index 00000000000..61f64c53129
--- /dev/null
+++ b/gdb/testsuite/gdb.base/infcall-timeout.c
@@ -0,0 +1,36 @@
+/* Copyright 2022-2024 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 <unistd.h>
+
+/* This function is called from GDB.  */
+int
+function_that_never_returns ()
+{
+  while (1)
+    sleep (1);
+
+  return 0;
+}
+
+int
+main ()
+{
+  alarm (300);
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.exp b/gdb/testsuite/gdb.base/infcall-timeout.exp
new file mode 100644
index 00000000000..e6a03b2ac6b
--- /dev/null
+++ b/gdb/testsuite/gdb.base/infcall-timeout.exp
@@ -0,0 +1,94 @@
+# Copyright 2022-2024 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/>.
+
+# Test GDB's direct-call-timeout setting, that is, ensure that if an
+# inferior function call, invoked from e.g. a 'print' command, takes
+# too long, then GDB can interrupt it, and return control to the user.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug}] == -1 } {
+    return
+}
+
+# Start GDB according to TARGET_ASYNC, TARGET_NON_STOP, and NON_STOP,
+# then adjust the direct-call-timeout, and make an inferior function
+# call that will never return.  GDB should eventually timeout and stop
+# the inferior.
+proc run_test { target_async target_non_stop non_stop } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS \
+	    " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"set non-stop $non_stop\""
+	append ::GDBFLAGS \
+	    " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if {![runto_main]} {
+	return
+    }
+
+    gdb_test_no_output "set direct-call-timeout 5"
+
+    # When non-stop mode is off we get slightly different output from GDB.
+    if { ([target_info gdb_protocol] == "remote"
+	  || [target_info gdb_protocol] == "extended-remote")
+	 && !$target_non_stop } {
+	set stopped_line_pattern "Program received signal SIGINT, Interrupt\\."
+    } else {
+	set stopped_line_pattern "Program stopped\\."
+    }
+
+    gdb_test "print function_that_never_returns ()" \
+	[multi_line \
+	     $stopped_line_pattern \
+	     ".*" \
+	     "The program being debugged timed out while in a function called from GDB\\." \
+	     "GDB remains in the frame where the timeout occurred\\." \
+	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(function_that_never_returns\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."]
+
+    gdb_test "bt" ".* function_that_never_returns .*<function called from gdb>.*"
+}
+
+foreach_with_prefix target_async { "on" "off" } {
+
+    if { !$target_async } {
+	# GDB can't timeout while waiting for a thread if the target
+	# runs with async-mode turned off; once the target is running
+	# GDB is effectively blocked until the target stops for some
+	# reason.
+	continue
+    }
+
+    foreach_with_prefix target_non_stop { "on" "off" } {
+	foreach_with_prefix non_stop { "on" "off" } {
+	    if { $non_stop && !$target_non_stop } {
+		# It doesn't make sense to operate GDB in non-stop
+		# mode when the target has (in theory) non-stop mode
+		# disabled.
+		continue
+	    }
+
+	    run_test $target_async $target_non_stop $non_stop
+	}
+    }
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
new file mode 100644
index 00000000000..415eaea8ccb
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
@@ -0,0 +1,169 @@
+/* This testcase is part of GDB, the GNU debugger.
+
+   Copyright 2022-2024 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 <stdio.h>
+#include <pthread.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <semaphore.h>
+
+#define NUM_THREADS 5
+
+/* Semaphores, used to track when threads have started, and to control
+   when the threads finish.  */
+sem_t startup_semaphore;
+sem_t finish_semaphore;
+sem_t thread_1_semaphore;
+sem_t thread_2_semaphore;
+
+/* Mutex to control when the first worker thread hit a breakpoint
+   location.  */
+pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+
+/* Global variable to poke, just so threads have something to do.  */
+volatile int global_var = 0;
+
+int
+condition_func ()
+{
+  /* Let thread 2 run.  */
+  if (sem_post (&thread_2_semaphore) != 0)
+    abort ();
+
+  /* Wait for thread 2 to complete its actions.  */
+  if (sem_wait (&thread_1_semaphore) != 0)
+    abort ();
+
+  return 1;
+}
+
+void
+do_segfault ()
+{
+  volatile int *p = 0;
+  *p = 0;	/* Segfault here.  */
+}
+
+void *
+worker_func (void *arg)
+{
+  int tid = *((int *) arg);
+
+  /* Let the main thread know that this worker has started.  */
+  if (sem_post (&startup_semaphore) != 0)
+    abort ();
+
+  switch (tid)
+    {
+    case 0:
+      /* Wait for MUTEX to become available, then pass through the
+	 conditional breakpoint location.  */
+      if (pthread_mutex_lock (&mutex) != 0)
+	abort ();
+      global_var = 99;	/* Conditional breakpoint here.  */
+      if (pthread_mutex_unlock (&mutex) != 0)
+	abort ();
+      break;
+
+    case 1:
+      if (sem_wait (&thread_2_semaphore) != 0)
+	abort ();
+      do_segfault ();
+      if (sem_post (&thread_1_semaphore) != 0)
+	abort ();
+
+      /* Fall through.  */
+    default:
+      /* Wait until we are allowed to finish.  */
+      if (sem_wait (&finish_semaphore) != 0)
+	abort ();
+      break;
+    }
+}
+
+void
+stop_marker ()
+{
+  global_var = 99;	/* Stop marker.  */
+}
+
+/* The main program entry point.  */
+
+int
+main ()
+{
+  pthread_t threads[NUM_THREADS];
+  int args[NUM_THREADS];
+  void *retval;
+
+  /* An alarm, just in case the thread deadlocks.  */
+  alarm (300);
+
+  /* Semaphore initialization.  */
+  if (sem_init (&startup_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&finish_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&thread_1_semaphore, 0, 0) != 0)
+    abort ();
+  if (sem_init (&thread_2_semaphore, 0, 0) != 0)
+    abort ();
+
+  /* Lock MUTEX, this prevents the first worker thread from rushing ahead.  */
+  if (pthread_mutex_lock (&mutex) != 0)
+    abort ();
+
+  /* Worker thread creation.  */
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      args[i] = i;
+      pthread_create (&threads[i], NULL, worker_func, &args[i]);
+    }
+
+  /* Wait for every thread to start.  */
+  for (int i = 0; i < NUM_THREADS; i++)
+    {
+      if (sem_wait (&startup_semaphore) != 0)
+	abort ();
+    }
+
+  /* Unlock the first thread so it can proceed.  */
+  if (pthread_mutex_unlock (&mutex) != 0)
+    abort ();
+
+  /* Wait for the first thread only.  */
+  pthread_join (threads[0], &retval);
+
+  /* Now post FINISH_SEMAPHORE to allow all the other threads to finish.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    sem_post (&finish_semaphore);
+
+  /* Now wait for the remaining threads to complete.  */
+  for (int i = 1; i < NUM_THREADS; i++)
+    pthread_join (threads[i], &retval);
+
+  /* Semaphore cleanup.  */
+  sem_destroy (&finish_semaphore);
+  sem_destroy (&startup_semaphore);
+  sem_destroy (&thread_1_semaphore);
+  sem_destroy (&thread_2_semaphore);
+
+  stop_marker ();
+
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
new file mode 100644
index 00000000000..67dabce66ee
--- /dev/null
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
@@ -0,0 +1,166 @@
+# Copyright 2022-2024 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 inferior calls executed from a breakpoint condition in
+# a multi-threaded program.
+#
+# This test has the inferior function call timeout, and checks how GDB
+# handles this situation.
+
+standard_testfile
+
+if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
+	  {debug pthreads}] } {
+    return
+}
+
+set cond_bp_line [gdb_get_line_number "Conditional breakpoint here"]
+set final_bp_line [gdb_get_line_number "Stop marker"]
+set segfault_line [gdb_get_line_number "Segfault here"]
+
+# Setup GDB based on TARGET_ASYNC, TARGET_NON_STOP, and NON_STOP.
+# Setup some breakpoints in the inferior, one of which has an inferior
+# call within its condition.
+#
+# Continue GDB, the breakpoint with inferior call will be hit, but the
+# inferior call will never return.  We expect GDB to timeout.
+#
+# The reason that the inferior call never completes is that a second
+# thread, on which the inferior call relies, either hits a breakpoint
+# (when OTHER_THREAD_BP is true), or crashes (when OTHER_THREAD_BP is
+# false).
+proc run_test { target_async target_non_stop non_stop other_thread_bp } {
+    save_vars { ::GDBFLAGS } {
+	append ::GDBFLAGS " -ex \"maint set target-non-stop $target_non_stop\""
+	append ::GDBFLAGS " -ex \"maint non-stop $non_stop\""
+	append ::GDBFLAGS " -ex \"maintenance set target-async ${target_async}\""
+
+	clean_restart ${::binfile}
+    }
+
+    if {![runto_main]} {
+	return
+    }
+
+    # The default timeout for indirect inferior calls (e.g. inferior
+    # calls for conditional breakpoint expressions) is pretty high.
+    # We don't want the test to take too long, so reduce this.
+    #
+    # However, the test relies on a second thread hitting some event
+    # (either a breakpoint or signal) before this timeout expires.
+    #
+    # There is a chance that on a really slow system this might not
+    # happen, in which case the test might fail.
+    #
+    # However, we still allocate 5 seconds, which feels like it should
+    # be enough time in most cases, but maybe we need to do something
+    # smarter here?  Possibly we could have some initial run where the
+    # inferior doesn't timeout, but does perform the same interaction
+    # between threads, we could time that, and use that as the basis
+    # for this timeout.  For now though, we just hope 5 seconds is
+    # enough.
+    gdb_test_no_output "set indirect-call-timeout 5"
+
+    gdb_breakpoint \
+	"${::srcfile}:${::cond_bp_line} if (condition_func ())"
+    set bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+		    "get number for conditional breakpoint"]
+
+    gdb_breakpoint "${::srcfile}:${::final_bp_line}"
+    set final_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+			  "get number for final breakpoint"]
+
+    # The thread performing an inferior call relies on a second
+    # thread.  The second thread will segfault unless it hits a
+    # breakpoint first.  In either case the initial thread will not
+    # complete its inferior call.
+    if { $other_thread_bp } {
+	gdb_breakpoint "${::srcfile}:${::segfault_line}"
+	set segfault_bp_num [get_integer_valueof "\$bpnum" "*UNKNOWN*" \
+				 "get number for segfault breakpoint"]
+    }
+
+    # When non-stop mode is off we get slightly different output from GDB.
+    if { ([target_info gdb_protocol] == "remote"
+	  || [target_info gdb_protocol] == "extended-remote")
+	 && !$target_non_stop} {
+	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" received signal SIGINT, Interrupt\\."
+    } else {
+	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\."
+    }
+
+    gdb_test "continue" \
+	[multi_line \
+	     $stopped_line_pattern \
+	     ".*" \
+	     "Error in testing condition for breakpoint ${bp_num}:" \
+	     "The program being debugged timed out while in a function called from GDB\\." \
+	     "GDB remains in the frame where the timeout occurred\\." \
+	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
+	     "Evaluation of the expression containing the function" \
+	     "\\(condition_func\\) will be abandoned\\." \
+	     "When the function is done executing, GDB will silently stop\\."] \
+	"expected timeout waiting for inferior call to complete"
+
+    # Remember that other thread that either crashed (with a segfault)
+    # or hit a breakpoint?  Now that the inferior call has timed out,
+    # if we try to resume then we should see the pending event from
+    # that other thread.
+    if { $other_thread_bp } {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "" \
+		 "Thread ${::decimal} \"\[^\"\r\n\]+\" hit Breakpoint ${segfault_bp_num}, do_segfault \[^\r\n\]+:${::segfault_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"] \
+	    "hit the segfault breakpoint"
+    } else {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Continuing\\." \
+		 ".*" \
+		 "Thread ${::decimal} \"infcall-from-bp\" received signal SIGSEGV, Segmentation fault\\." \
+		 "\\\[Switching to Thread \[^\r\n\]+\\\]" \
+		 "${::hex} in do_segfault \\(\\) at \[^\r\n\]+:${::segfault_line}" \
+		 "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+"] \
+	    "hit the segfault"
+    }
+}
+
+foreach_with_prefix target_async {"on" "off" } {
+
+    if { !$target_async } {
+	# GDB can't timeout while waiting for a thread if the target
+	# runs with async-mode turned off; once the target is running
+	# GDB is effectively blocked until the target stops for some
+	# reason.
+	continue
+    }
+
+    foreach_with_prefix target_non_stop {"off" "on"} {
+	foreach_with_prefix non_stop {"off" "on"} {
+	    if { $non_stop && !$target_non_stop } {
+		# It doesn't make sense to operate GDB in non-stop
+		# mode when the target has (in theory) non-stop mode
+		# disabled.
+		continue
+	    }
+	    foreach_with_prefix other_thread_bp { true false } {
+		run_test $target_async $target_non_stop $non_stop $other_thread_bp
+	    }
+	}
+    }
+}
-- 
2.25.4


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

* [PATCHv11 4/5] gdb: introduce unwind-on-timeout setting
  2024-03-05 15:40                   ` [PATCHv11 0/5] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                                       ` (2 preceding siblings ...)
  2024-03-05 15:40                     ` [PATCHv11 3/5] gdb: add timeouts for inferior function calls Andrew Burgess
@ 2024-03-05 15:40                     ` Andrew Burgess
  2024-03-05 15:40                     ` [PATCHv11 5/5] gdb: rename unwindonsignal to unwind-on-signal Andrew Burgess
                                       ` (3 subsequent siblings)
  7 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2024-03-05 15:40 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Eli Zaretskii

Now that inferior function calls can timeout (see the recent
introduction of direct-call-timeout and indirect-call-timeout), this
commit adds a new setting unwind-on-timeout.

This new setting is just like the existing unwindonsignal and
unwind-on-terminating-exception, but the new setting will cause GDB to
unwind the stack if an inferior function call times out.

The existing inferior function call timeout tests have been updated to
cover the new setting.

Reviewed-By: Eli Zaretskii <eliz@gnu.org>
---
 gdb/NEWS                                      |  9 +++
 gdb/doc/gdb.texinfo                           | 31 ++++++--
 gdb/infcall.c                                 | 78 +++++++++++++++++--
 gdb/testsuite/gdb.base/infcall-timeout.exp    | 63 ++++++++++-----
 .../infcall-from-bp-cond-timeout.exp          | 69 ++++++++++------
 5 files changed, 194 insertions(+), 56 deletions(-)

diff --git a/gdb/NEWS b/gdb/NEWS
index b98822f28b1..d6139ed5001 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -65,6 +65,15 @@ show indirect-call-timeout
   ignored, GDB will wait indefinitely for an inferior function to
   complete, unless interrupted by the user using Ctrl-C.
 
+set unwind-on-timeout on|off
+show unwind-on-timeout
+  These commands control whether GDB should unwind the stack when a
+  timeout occurs during an inferior function call.  The default is
+  off, in which case the inferior will remain in the frame where the
+  timeout occurred.  When on, GDB will unwind the stack removing the
+  dummy frame that was added for the inferior call, and restoring the
+  inferior state to how it was before the inferior call started.
+
 * New features in the GDB remote stub, GDBserver
 
   ** The --remote-debug and --event-loop-debug command line options
diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index 6b98a960442..0c53f1254f1 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -20946,6 +20946,22 @@
 Show the current setting of stack unwinding in the functions called by
 @value{GDBN}.
 
+@anchor{set unwind-on-timeout}
+@item set unwind-on-timeout
+@kindex set unwind-on-timeout
+@cindex unwind stack in called functions when timing out
+@cindex call dummy stack unwinding on timeout.
+Set unwinding of the stack if a function called from @value{GDBN}
+times out.  If set to @code{off} (the default), @value{GDBN} stops in
+the frame where the timeout occurred.  If set to @code{on},
+@value{GDBN} unwinds the stack it created for the call and restores
+the context to what it was before the call.
+
+@item show unwind-on-timeout
+@kindex show unwind-on-timeout
+Show whether @value{GDBN} will unwind the stack if a function called
+from @value{GDBN} times out.
+
 @item set may-call-functions
 @kindex set may-call-functions
 @cindex disabling calling functions in the program
@@ -20977,11 +20993,11 @@
 
 If a called function is interrupted for any reason, including hitting
 a breakpoint, or triggering a watchpoint, and the stack is not unwound
-due to @code{set unwind-on-terminating-exception on} or @code{set
-unwindonsignal on} (@pxref{stack unwind settings}),
-then the dummy-frame, created by @value{GDBN} to facilitate the call
-to the program function, will be visible in the backtrace, for example
-frame @code{#3} in the following backtrace:
+due to @code{set unwind-on-terminating-exception on}, @code{set
+unwind-on-timeout on}, or @code{set unwindonsignal on} (@pxref{stack
+unwind settings}), then the dummy-frame, created by @value{GDBN} to
+facilitate the call to the program function, will be visible in the
+backtrace, for example frame @code{#3} in the following backtrace:
 
 @smallexample
 (@value{GDBP}) backtrace
@@ -21006,6 +21022,11 @@
 from @value{GDBN}.  If the timeout expires and the function call is
 still ongoing, then @value{GDBN} will interrupt the program.
 
+If a function called from @value{GDBN} is interrupted by a timeout,
+then by default the inferior is left in the frame where the timeout
+occurred, this behaviour can be adjusted with @samp{set
+unwind-on-timeout} (@pxref{set unwind-on-timeout}).
+
 For targets that don't support asynchronous execution
 (@pxref{Background Execution}) then timeouts for functions called from
 @value{GDBN} are not supported, the timeout settings described below
diff --git a/gdb/infcall.c b/gdb/infcall.c
index 7dc1324023f..bbe906420d1 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -218,6 +218,27 @@ show_unwind_on_terminating_exception_p (struct ui_file *file, int from_tty,
 	      value);
 }
 
+/* This boolean tells GDB what to do if an inferior function, called from
+   GDB, times out.  If true, GDB unwinds the stack and restores the context
+   to what it was before the call.  When false, GDB leaves the thread as it
+   is at the point of the timeout.
+
+   The default is to stop in the frame where the timeout occurred.  */
+
+static bool unwind_on_timeout_p = false;
+
+/* Implement 'show unwind-on-timeout'.  */
+
+static void
+show_unwind_on_timeout_p (struct ui_file *file, int from_tty,
+			  struct cmd_list_element *c, const char *value)
+{
+  gdb_printf (file,
+	      _("Unwinding of stack if a timeout occurs "
+		"while in a call dummy is %s.\n"),
+	      value);
+}
+
 /* Perform the standard coercions that are specified
    for arguments to be passed to C, Ada or Fortran functions.
 
@@ -574,6 +595,16 @@ struct call_thread_fsm : public thread_fsm
   bool should_stop (struct thread_info *thread) override;
 
   bool should_notify_stop () override;
+
+  /* Record that this thread timed out while performing an infcall.  */
+  void timed_out ()
+  {
+    m_timed_out = true;
+  }
+
+private:
+  /* Set true if the thread timed out while performing an infcall.  */
+  bool m_timed_out = false;
 };
 
 /* Allocate a new call_thread_fsm object.  */
@@ -649,7 +680,8 @@ call_thread_fsm::should_notify_stop ()
 
   infcall_debug_printf ("inferior call didn't complete fully");
 
-  if (stopped_by_random_signal && unwind_on_signal_p)
+  if ((stopped_by_random_signal && unwind_on_signal_p)
+      || (m_timed_out && unwind_on_timeout_p))
     {
       infcall_debug_printf ("unwind-on-signal is on, don't notify");
       return false;
@@ -742,6 +774,9 @@ struct infcall_timer_controller
 
     infcall_debug_printf ("Stopping thread %s",
 			  m_thread->ptid.to_string ().c_str ());
+    call_thread_fsm *fsm
+      = gdb::checked_static_cast<call_thread_fsm *> (m_thread->thread_fsm ());
+    fsm->timed_out ();
     target_stop (m_thread->ptid);
   }
 };
@@ -1749,14 +1784,27 @@ When the function is done executing, GDB will silently stop."),
 	  /* A timeout results in a signal being sent to the inferior.  */
 	  gdb_assert (stopped_by_random_signal);
 
-	  /* Indentation is weird here.  A later patch is going to move the
-	    following block into an if/else, so I'm leaving the indentation
-	    here to minimise the later patch.
+	  if (unwind_on_timeout_p)
+	    {
+	      /* The user wants the context restored.  */
+
+	      /* We must get back to the frame we were before the
+		 dummy call.  */
+	      dummy_frame_pop (dummy_id, call_thread.get ());
 
-	    Also, the error message used below refers to 'set
-	    unwind-on-timeout' which doesn't exist yet.  This will be added
-	    in a later commit, I'm leaving this in for now to minimise the
-	    churn caused by the commit that adds unwind-on-timeout.  */
+	      /* We also need to restore inferior status to that before the
+		 dummy call.  */
+	      restore_infcall_control_state (inf_status.release ());
+
+	      error (_("\
+The program being debugged timed out while in a function called from GDB.\n\
+GDB has restored the context to what it was before the call.\n\
+To change this behavior use \"set unwind-on-timeout off\".\n\
+Evaluation of the expression containing the function\n\
+(%s) will be abandoned."),
+		     name.c_str ());
+	    }
+	  else
 	    {
 	      /* The user wants to stay in the frame where we stopped
 		 (default).  Discard inferior status, we're not at the same
@@ -1882,6 +1930,20 @@ The default is to unwind the frame."),
 			   show_unwind_on_terminating_exception_p,
 			   &setlist, &showlist);
 
+  add_setshow_boolean_cmd ("unwind-on-timeout", no_class,
+			   &unwind_on_timeout_p, _("\
+Set unwinding of stack if a timeout occurs while in a call dummy."), _("\
+Show unwinding of stack if a timeout occurs while in a call dummy."),
+			   _("\
+The unwind on timeout flag lets the user determine what gdb should do if\n\
+gdb times out while in a function called from gdb.  If set, gdb unwinds\n\
+the stack and restores the context to what it was before the call.  If\n\
+unset, gdb leaves the inferior in the frame where the timeout occurred.\n\
+The default is to stop in the frame where the timeout occurred."),
+			   NULL,
+			   show_unwind_on_timeout_p,
+			   &setlist, &showlist);
+
   add_setshow_uinteger_cmd ("direct-call-timeout", no_class,
 			    &direct_call_timeout, _("\
 Set the timeout, for direct calls to inferior function calls."), _("\
diff --git a/gdb/testsuite/gdb.base/infcall-timeout.exp b/gdb/testsuite/gdb.base/infcall-timeout.exp
index e6a03b2ac6b..ad4dbe3b415 100644
--- a/gdb/testsuite/gdb.base/infcall-timeout.exp
+++ b/gdb/testsuite/gdb.base/infcall-timeout.exp
@@ -28,7 +28,11 @@ if { [build_executable "failed to prepare" ${binfile} "${srcfile}" \
 # then adjust the direct-call-timeout, and make an inferior function
 # call that will never return.  GDB should eventually timeout and stop
 # the inferior.
-proc run_test { target_async target_non_stop non_stop } {
+#
+# When UNWIND is "off" the inferior wil be left in the frame where the
+# timeout occurs, otherwise, when UNWIND is "on", GDB should unwind
+# back to the frame where the inferior call was made.
+proc run_test { target_async target_non_stop non_stop unwind } {
     save_vars { ::GDBFLAGS } {
 	append ::GDBFLAGS \
 	    " -ex \"maint set target-non-stop $target_non_stop\""
@@ -45,28 +49,43 @@ proc run_test { target_async target_non_stop non_stop } {
     }
 
     gdb_test_no_output "set direct-call-timeout 5"
+    gdb_test_no_output "set unwind-on-timeout $unwind"
+
+    if { $unwind } {
+	gdb_test "print function_that_never_returns ()" \
+	    [multi_line \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB has restored the context to what it was before the call\\." \
+		 "To change this behavior use \"set unwind-on-timeout off\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(function_that_never_returns\\) will be abandoned\\."]
 
-    # When non-stop mode is off we get slightly different output from GDB.
-    if { ([target_info gdb_protocol] == "remote"
-	  || [target_info gdb_protocol] == "extended-remote")
-	 && !$target_non_stop } {
-	set stopped_line_pattern "Program received signal SIGINT, Interrupt\\."
+	gdb_test "bt" \
+	    "#0\\s+main \\(\\).*"
     } else {
-	set stopped_line_pattern "Program stopped\\."
-    }
+	# When non-stop mode is off we get slightly different output from GDB.
+	if { ([target_info gdb_protocol] == "remote"
+	      || [target_info gdb_protocol] == "extended-remote")
+	     && !$target_non_stop } {
+	    set stopped_line_pattern "Program received signal SIGINT, Interrupt\\."
+	} else {
+	    set stopped_line_pattern "Program stopped\\."
+	}
 
-    gdb_test "print function_that_never_returns ()" \
-	[multi_line \
-	     $stopped_line_pattern \
-	     ".*" \
-	     "The program being debugged timed out while in a function called from GDB\\." \
-	     "GDB remains in the frame where the timeout occurred\\." \
-	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
-	     "Evaluation of the expression containing the function" \
-	     "\\(function_that_never_returns\\) will be abandoned\\." \
-	     "When the function is done executing, GDB will silently stop\\."]
-
-    gdb_test "bt" ".* function_that_never_returns .*<function called from gdb>.*"
+	gdb_test "print function_that_never_returns ()" \
+	    [multi_line \
+		 $stopped_line_pattern \
+		 ".*" \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB remains in the frame where the timeout occurred\\." \
+		 "To change this behavior use \"set unwind-on-timeout on\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(function_that_never_returns\\) will be abandoned\\." \
+		 "When the function is done executing, GDB will silently stop\\."]
+
+	gdb_test "bt" \
+	    ".* function_that_never_returns .*<function called from gdb>.*"
+    }
 }
 
 foreach_with_prefix target_async { "on" "off" } {
@@ -88,7 +107,9 @@ foreach_with_prefix target_async { "on" "off" } {
 		continue
 	    }
 
-	    run_test $target_async $target_non_stop $non_stop
+	    foreach_with_prefix unwind { "on" "off" } {
+		run_test $target_async $target_non_stop $non_stop $unwind
+	    }
 	}
     }
 }
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
index 67dabce66ee..8f17f13d97a 100644
--- a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
@@ -41,7 +41,12 @@ set segfault_line [gdb_get_line_number "Segfault here"]
 # thread, on which the inferior call relies, either hits a breakpoint
 # (when OTHER_THREAD_BP is true), or crashes (when OTHER_THREAD_BP is
 # false).
-proc run_test { target_async target_non_stop non_stop other_thread_bp } {
+#
+# When UNWIND is "on" GDB will unwind the thread which performed the
+# inferior function call back to the state where the inferior call was
+# made (when the inferior call times out).  Otherwise, when UNWIND is
+# "off", the inferior is left in the frame where the timeout occurred.
+proc run_test { target_async target_non_stop non_stop other_thread_bp unwind } {
     save_vars { ::GDBFLAGS } {
 	append ::GDBFLAGS " -ex \"maint set target-non-stop $target_non_stop\""
 	append ::GDBFLAGS " -ex \"maint non-stop $non_stop\""
@@ -72,6 +77,7 @@ proc run_test { target_async target_non_stop non_stop other_thread_bp } {
     # for this timeout.  For now though, we just hope 5 seconds is
     # enough.
     gdb_test_no_output "set indirect-call-timeout 5"
+    gdb_test_no_output "set unwind-on-timeout $unwind"
 
     gdb_breakpoint \
 	"${::srcfile}:${::cond_bp_line} if (condition_func ())"
@@ -92,27 +98,43 @@ proc run_test { target_async target_non_stop non_stop other_thread_bp } {
 				 "get number for segfault breakpoint"]
     }
 
-    # When non-stop mode is off we get slightly different output from GDB.
-    if { ([target_info gdb_protocol] == "remote"
-	  || [target_info gdb_protocol] == "extended-remote")
-	 && !$target_non_stop} {
-	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" received signal SIGINT, Interrupt\\."
+    if { $unwind } {
+	gdb_test "continue" \
+	    [multi_line \
+		 "Error in testing condition for breakpoint ${bp_num}:" \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB has restored the context to what it was before the call\\." \
+		 "To change this behavior use \"set unwind-on-timeout off\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(condition_func\\) will be abandoned\\." \
+		 "" \
+		 "Thread ${::decimal}\[^\r\n\]*hit Breakpoint ${bp_num}, \[^\r\n\]+" \
+		 "\[^\r\n\]+ Conditional breakpoint here\\. \[^\r\n\]+"] \
+	    "expected timeout waiting for inferior call to complete"
     } else {
-	set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\."
-    }
+	# When non-stop mode is off we get slightly different output from GDB.
+	if { ([target_info gdb_protocol] == "remote"
+	      || [target_info gdb_protocol] == "extended-remote")
+	     && !$target_non_stop} {
+	    set stopped_line_pattern \
+		"Thread ${::decimal} \"\[^\r\n\"\]+\" received signal SIGINT, Interrupt\\."
+	} else {
+	    set stopped_line_pattern "Thread ${::decimal} \"\[^\r\n\"\]+\" stopped\\."
+	}
 
-    gdb_test "continue" \
-	[multi_line \
-	     $stopped_line_pattern \
-	     ".*" \
-	     "Error in testing condition for breakpoint ${bp_num}:" \
-	     "The program being debugged timed out while in a function called from GDB\\." \
-	     "GDB remains in the frame where the timeout occurred\\." \
-	     "To change this behavior use \"set unwind-on-timeout on\"\\." \
-	     "Evaluation of the expression containing the function" \
-	     "\\(condition_func\\) will be abandoned\\." \
-	     "When the function is done executing, GDB will silently stop\\."] \
-	"expected timeout waiting for inferior call to complete"
+	gdb_test "continue" \
+	    [multi_line \
+		 "$stopped_line_pattern" \
+		 ".*" \
+		 "Error in testing condition for breakpoint ${bp_num}:" \
+		 "The program being debugged timed out while in a function called from GDB\\." \
+		 "GDB remains in the frame where the timeout occurred\\." \
+		 "To change this behavior use \"set unwind-on-timeout on\"\\." \
+		 "Evaluation of the expression containing the function" \
+		 "\\(condition_func\\) will be abandoned\\." \
+		 "When the function is done executing, GDB will silently stop\\."] \
+	    "expected timeout waiting for inferior call to complete"
+    }
 
     # Remember that other thread that either crashed (with a segfault)
     # or hit a breakpoint?  Now that the inferior call has timed out,
@@ -158,8 +180,11 @@ foreach_with_prefix target_async {"on" "off" } {
 		# disabled.
 		continue
 	    }
-	    foreach_with_prefix other_thread_bp { true false } {
-		run_test $target_async $target_non_stop $non_stop $other_thread_bp
+	    foreach_with_prefix unwind {"off" "on"} {
+		foreach_with_prefix other_thread_bp { true false } {
+		    run_test $target_async $target_non_stop $non_stop \
+			$other_thread_bp $unwind
+		}
 	    }
 	}
     }
-- 
2.25.4


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

* [PATCHv11 5/5] gdb: rename unwindonsignal to unwind-on-signal
  2024-03-05 15:40                   ` [PATCHv11 0/5] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                                       ` (3 preceding siblings ...)
  2024-03-05 15:40                     ` [PATCHv11 4/5] gdb: introduce unwind-on-timeout setting Andrew Burgess
@ 2024-03-05 15:40                     ` Andrew Burgess
  2024-03-14 16:08                     ` [PATCHv11 0/5] Infcalls from B/P conditions in multi-threaded inferiors Keith Seitz
                                       ` (2 subsequent siblings)
  7 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2024-03-05 15:40 UTC (permalink / raw)
  To: gdb-patches; +Cc: Andrew Burgess, Eli Zaretskii

We now have unwind-on-timeout and unwind-on-terminating-exception, and
then the odd one out unwindonsignal.

I'm not a great fan of these squashed together command names, so in
this commit I propose renaming this to unwind-on-signal.

Obviously I've added the hidden alias unwindonsignal so any existing
GDB scripts will keep working.

There's one test that I've extended to test the alias works, but in
most of the other test scripts I've changed over to use the new name.

The docs are updated to reference the new name.

Reviewed-By: Eli Zaretskii <eliz@gnu.org>
---
 gdb/NEWS                                      |  9 +++++
 gdb/doc/gdb.texinfo                           | 16 ++++++---
 gdb/infcall.c                                 | 21 ++++++-----
 gdb/testsuite/gdb.base/callfuncs.exp          |  4 +--
 gdb/testsuite/gdb.base/infcall-failure.exp    |  4 +--
 gdb/testsuite/gdb.base/unwindonsignal.exp     | 36 +++++++++++++------
 gdb/testsuite/gdb.compile/compile-cplus.exp   |  6 ++--
 gdb/testsuite/gdb.compile/compile.exp         |  6 ++--
 gdb/testsuite/gdb.cp/gdb2495.exp              | 16 ++++-----
 gdb/testsuite/gdb.fortran/function-calls.exp  |  2 +-
 gdb/testsuite/gdb.mi/mi-condbreak-fail.exp    |  6 ++--
 gdb/testsuite/gdb.mi/mi-condbreak-throw.exp   |  2 +-
 gdb/testsuite/gdb.mi/mi-syn-frame.exp         |  2 +-
 .../infcall-from-bp-cond-simple.exp           |  2 +-
 .../gdb.threads/thread-unwindonsignal.exp     |  8 ++---
 15 files changed, 89 insertions(+), 51 deletions(-)

diff --git a/gdb/NEWS b/gdb/NEWS
index d6139ed5001..bf2d40e57a6 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -25,6 +25,10 @@ maintenance info line-table
   if the line is considered the start of the epilgoue, and thus a point at
   which the frame can be considered destroyed.
 
+set unwindonsignal on|off
+show unwindonsignal
+  These commands are now aliases for the new set/show unwind-on-signal.
+
 * New commands
 
 info missing-debug-handler
@@ -74,6 +78,11 @@ show unwind-on-timeout
   dummy frame that was added for the inferior call, and restoring the
   inferior state to how it was before the inferior call started.
 
+set unwind-on-signal on|off
+show unwind-on-signal
+  These new commands replaces the existing set/show unwindonsignal.  The
+  old command is maintained as an alias.
+
 * New features in the GDB remote stub, GDBserver
 
   ** The --remote-debug and --event-loop-debug command line options
diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index 0c53f1254f1..fe2cf73d509 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -20900,7 +20900,7 @@
 It is possible for the function you call via the @code{print} or
 @code{call} command to generate a signal (e.g., if there's a bug in
 the function, or if you passed it incorrect arguments).  What happens
-in that case is controlled by the @code{set unwindonsignal} command.
+in that case is controlled by the @code{set unwind-on-signal} command.
 
 Similarly, with a C@t{++} program it is possible for the function you
 call via the @code{print} or @code{call} command to generate an
@@ -20914,7 +20914,8 @@
 
 @anchor{stack unwind settings}
 @table @code
-@item set unwindonsignal
+@item set unwind-on-signal
+@kindex set unwind-on-signal
 @kindex set unwindonsignal
 @cindex unwind stack in called functions
 @cindex call dummy stack unwinding
@@ -20925,11 +20926,18 @@
 default), @value{GDBN} stops in the frame where the signal was
 received.
 
-@item show unwindonsignal
+The command @code{set unwindonsignal} is an alias for this command,
+and is maintained for backward compatibility.
+
+@item show unwind-on-signal
+@kindex show unwind-on-signal
 @kindex show unwindonsignal
 Show the current setting of stack unwinding in the functions called by
 @value{GDBN}.
 
+The command @code{show unwindonsignal} is an alias for this command,
+and is maintained for backward compatibility.
+
 @item set unwind-on-terminating-exception
 @kindex set unwind-on-terminating-exception
 @cindex unwind stack in called functions with unhandled exceptions
@@ -20994,7 +21002,7 @@
 If a called function is interrupted for any reason, including hitting
 a breakpoint, or triggering a watchpoint, and the stack is not unwound
 due to @code{set unwind-on-terminating-exception on}, @code{set
-unwind-on-timeout on}, or @code{set unwindonsignal on} (@pxref{stack
+unwind-on-timeout on}, or @code{set unwind-on-signal on} (@pxref{stack
 unwind settings}), then the dummy-frame, created by @value{GDBN} to
 facilitate the call to the program function, will be visible in the
 backtrace, for example frame @code{#3} in the following backtrace:
diff --git a/gdb/infcall.c b/gdb/infcall.c
index bbe906420d1..c9267e7a129 100644
--- a/gdb/infcall.c
+++ b/gdb/infcall.c
@@ -1752,7 +1752,7 @@ When the function is done executing, GDB will silently stop."),
 The program being debugged received signal %s, %s\n\
 while in a function called from GDB.  GDB has restored the context\n\
 to what it was before the call.  To change this behavior use\n\
-\"set unwindonsignal off\".  Evaluation of the expression containing\n\
+\"set unwind-on-signal off\".  Evaluation of the expression containing\n\
 the function (%s) will be abandoned."),
 		     gdb_signal_to_name (stop_signal),
 		     gdb_signal_to_string (stop_signal),
@@ -1771,7 +1771,7 @@ the function (%s) will be abandoned."),
 	      error (_("\
 The program being debugged was signaled while in a function called from GDB.\n\
 GDB remains in the frame where the signal was received.\n\
-To change this behavior use \"set unwindonsignal on\".\n\
+To change this behavior use \"set unwind-on-signal on\".\n\
 Evaluation of the expression containing the function\n\
 (%s) will be abandoned.\n\
 When the function is done executing, GDB will silently stop."),
@@ -1903,17 +1903,22 @@ The default is to perform the conversion."),
 			   show_coerce_float_to_double_p,
 			   &setlist, &showlist);
 
-  add_setshow_boolean_cmd ("unwindonsignal", no_class,
-			   &unwind_on_signal_p, _("\
+  set_show_commands setshow_unwind_on_signal_cmds
+    = add_setshow_boolean_cmd ("unwind-on-signal", no_class,
+			       &unwind_on_signal_p, _("\
 Set unwinding of stack if a signal is received while in a call dummy."), _("\
 Show unwinding of stack if a signal is received while in a call dummy."), _("\
-The unwindonsignal lets the user determine what gdb should do if a signal\n\
+The unwind-on-signal lets the user determine what gdb should do if a signal\n\
 is received while in a function called from gdb (call dummy).  If set, gdb\n\
 unwinds the stack and restore the context to what as it was before the call.\n\
 The default is to stop in the frame where the signal was received."),
-			   NULL,
-			   show_unwind_on_signal_p,
-			   &setlist, &showlist);
+			       NULL,
+			       show_unwind_on_signal_p,
+			       &setlist, &showlist);
+  add_alias_cmd ("unwindonsignal", setshow_unwind_on_signal_cmds.set,
+		 no_class, 1, &setlist);
+  add_alias_cmd ("unwindonsignal", setshow_unwind_on_signal_cmds.show,
+		 no_class, 1, &showlist);
 
   add_setshow_boolean_cmd ("unwind-on-terminating-exception", no_class,
 			   &unwind_on_terminating_exception_p, _("\
diff --git a/gdb/testsuite/gdb.base/callfuncs.exp b/gdb/testsuite/gdb.base/callfuncs.exp
index 603bbfe0aa8..494b6dfa96f 100644
--- a/gdb/testsuite/gdb.base/callfuncs.exp
+++ b/gdb/testsuite/gdb.base/callfuncs.exp
@@ -46,7 +46,7 @@ proc do_function_calls {prototypes} {
 
     # If any of these calls segv we don't want to affect subsequent tests.
     # E.g., we want to ensure register values are restored.
-    gdb_test_no_output "set unwindonsignal on"
+    gdb_test_no_output "set unwind-on-signal on"
 
     gdb_test "p t_char_values(0,0)" " = 0"
     gdb_test "p t_char_values('a','b')" " = 1"
@@ -237,7 +237,7 @@ proc do_function_calls {prototypes} {
     	"call inferior func with struct - returns char *"
 
     # Restore default value.
-    gdb_test_no_output "set unwindonsignal off"
+    gdb_test_no_output "set unwind-on-signal off"
 }
 
 # Procedure to get current content of all registers.
diff --git a/gdb/testsuite/gdb.base/infcall-failure.exp b/gdb/testsuite/gdb.base/infcall-failure.exp
index 89ddfb81546..8d08555682a 100644
--- a/gdb/testsuite/gdb.base/infcall-failure.exp
+++ b/gdb/testsuite/gdb.base/infcall-failure.exp
@@ -137,7 +137,7 @@ proc_with_prefix run_cond_hits_segfault_test { async_p non_stop_p } {
 	     "Error in testing condition for breakpoint ${bp_1_num}:" \
 	     "The program being debugged was signaled while in a function called from GDB\\." \
 	     "GDB remains in the frame where the signal was received\\." \
-	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "To change this behavior use \"set unwind-on-signal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(func_segfault\\) will be abandoned\\." \
 	     "When the function is done executing, GDB will silently stop\\."]
@@ -166,7 +166,7 @@ proc_with_prefix run_call_hits_segfault_test { async_p non_stop_p } {
 	     "${::decimal}\\s+\[^\r\n\]+Segfault here\[^\r\n\]+" \
 	     "The program being debugged was signaled while in a function called from GDB\\." \
 	     "GDB remains in the frame where the signal was received\\." \
-	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "To change this behavior use \"set unwind-on-signal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(func_segfault\\) will be abandoned\\." \
 	     "When the function is done executing, GDB will silently stop\\."]
diff --git a/gdb/testsuite/gdb.base/unwindonsignal.exp b/gdb/testsuite/gdb.base/unwindonsignal.exp
index 7e8de6bee77..31793556c2c 100644
--- a/gdb/testsuite/gdb.base/unwindonsignal.exp
+++ b/gdb/testsuite/gdb.base/unwindonsignal.exp
@@ -34,13 +34,29 @@ gdb_test "break stop_here" "Breakpoint \[0-9\]* at .*"
 gdb_test "continue" "Continuing.*Breakpoint \[0-9\]*, stop_here.*" \
     "continue to breakpoint at stop_here"
 
-# Turn on unwindonsignal.
-gdb_test_no_output "set unwindonsignal on" \
-	"setting unwindonsignal"
+# Turn on unwind-on-signal.
+gdb_test_no_output "set unwind-on-signal on" \
+	"setting unwind-on-signal"
 
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
 	"Unwinding of stack .* is on." \
-	"showing unwindonsignal"
+	"showing unwind-on-signal"
+
+# For backward compatibility we maintain a 'unwindonsignal' alias for
+# 'unwind-on-signal', check it now.
+gdb_test "show unwindonsignal" \
+    "Unwinding of stack .* is on\\." \
+    "showing unwindonsignal alias"
+
+gdb_test_no_output "set unwindonsignal off" \
+    "setting unwindonsignal alias to off"
+
+gdb_test "show unwind-on-signal" \
+    "Unwinding of stack .* is off\\." \
+    "showing unwind-on-signal after setting via alias"
+
+gdb_test_no_output "set unwindonsignal on" \
+    "setting unwindonsignal alias to on"
 
 # Call function (causing the program to get a signal), and see if gdb handles
 # it properly.
@@ -49,7 +65,7 @@ if {[gdb_test "call gen_signal ()"  \
 	      "The program being debugged received signal SIGABRT, Aborted" \
 	      "while in a function called from GDB\\.  GDB has restored the context" \
 	      "to what it was before the call\\.  To change this behavior use" \
-	      "\"set unwindonsignal off\"\\.  Evaluation of the expression containing" \
+	      "\"set unwind-on-signal off\"\\.  Evaluation of the expression containing" \
 	      "the function \\(gen_signal\\) will be abandoned\\."] \
 	 "unwindonsignal, inferior function call signaled"] != 0} {
     return 0
@@ -58,15 +74,15 @@ if {[gdb_test "call gen_signal ()"  \
 # Verify the stack got unwound.
 gdb_test "bt" \
     "#0 *\[x0-9a-f in\]*stop_here \\(.*\\) at .*#1 *\[x0-9a-f in\]*main \\(.*\\) at .*" \
-	"unwindonsignal, stack unwound"
+	"stack unwound"
 
 # Verify the dummy frame got removed from dummy_frame_stack.
 gdb_test_multiple "maint print dummy-frames" \
-	"unwindonsignal, dummy frame removed" {
+	"unwind-on-signal, dummy frame removed" {
     -re "\[\r\n\]*.*stack=.*code=.*\[\r\n\]+$gdb_prompt $" {
-	fail "unwindonsignal, dummy frame removed"
+	fail $gdb_test_name
     }
     -re "\[\r\n\]+$gdb_prompt $" {
-	pass "unwindonsignal, dummy frame removed"
+	pass $gdb_test_name
     }
 }
diff --git a/gdb/testsuite/gdb.compile/compile-cplus.exp b/gdb/testsuite/gdb.compile/compile-cplus.exp
index 40191a08b1a..711f299574d 100644
--- a/gdb/testsuite/gdb.compile/compile-cplus.exp
+++ b/gdb/testsuite/gdb.compile/compile-cplus.exp
@@ -131,13 +131,13 @@ gdb_test "return" "\r\n#0  main .*" "return" \
 	 "Make _gdb_expr\\(__gdb_regs\\*\\) return now\\? \\(y or n\\) " "y"
 gdb_test "info sym $infcall_pc" "\r\nNo symbol matches .*" "info sym not found"
 
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 gdb_test "compile code *(volatile int *) 0 = 0;" \
     [multi_line \
 	 "The program being debugged received signal SIGSEGV, Segmentation fault" \
 	 "while in a function called from GDB\\.  GDB has restored the context" \
 	 "to what it was before the call\\.  To change this behavior use" \
-	 "\"set unwindonsignal off\"\\.  Evaluation of the expression containing" \
+	 "\"set unwind-on-signal off\"\\.  Evaluation of the expression containing" \
 	 "the function \\(_gdb_expr\\(__gdb_regs\\*\\)\\) will be abandoned\\."] \
     "compile code segfault second"
 
@@ -313,7 +313,7 @@ gdb_test "compile code static const int readonly = 1; *(int *) &readonly = 2;" \
 	 "The program being debugged received signal SIGSEGV, Segmentation fault" \
 	 "while in a function called from GDB\\.  GDB has restored the context" \
 	 "to what it was before the call\\.  To change this behavior use" \
-	 "\"set unwindonsignal off\"\\.  Evaluation of the expression containing" \
+	 "\"set unwind-on-signal off\"\\.  Evaluation of the expression containing" \
 	 "the function \\(_gdb_expr\\(__gdb_regs\\*\\)\\) will be abandoned\\."]
 gdb_test_no_output "set debug compile off"
 
diff --git a/gdb/testsuite/gdb.compile/compile.exp b/gdb/testsuite/gdb.compile/compile.exp
index fed7b04a4c3..528ae247637 100644
--- a/gdb/testsuite/gdb.compile/compile.exp
+++ b/gdb/testsuite/gdb.compile/compile.exp
@@ -157,13 +157,13 @@ gdb_test "return" "\r\n#0  main .*" "return" \
 	 "Make _gdb_expr return now\\? \\(y or n\\) " "y"
 gdb_test "info sym $infcall_pc" "\r\nNo symbol matches .*" "info sym not found"
 
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 gdb_test "compile code *(volatile int *) 0 = 0;" \
     [multi_line \
 	 "The program being debugged received signal SIGSEGV, Segmentation fault" \
 	 "while in a function called from GDB\\.  GDB has restored the context" \
 	 "to what it was before the call\\.  To change this behavior use" \
-	 "\"set unwindonsignal off\"\\.  Evaluation of the expression containing" \
+	 "\"set unwind-on-signal off\"\\.  Evaluation of the expression containing" \
 	 "the function \\(_gdb_expr\\) will be abandoned\\."] \
     "compile code segfault second"
 
@@ -321,7 +321,7 @@ gdb_test "compile code static const int readonly = 1; *(int *) &readonly = 2;" \
 	 "The program being debugged received signal SIGSEGV, Segmentation fault" \
 	 "while in a function called from GDB\\.  GDB has restored the context" \
 	 "to what it was before the call\\.  To change this behavior use" \
-	 "\"set unwindonsignal off\"\\.  Evaluation of the expression containing" \
+	 "\"set unwind-on-signal off\"\\.  Evaluation of the expression containing" \
 	 "the function \\(_gdb_expr\\) will be abandoned\\."]
 gdb_test_no_output "set debug compile off"
 
diff --git a/gdb/testsuite/gdb.cp/gdb2495.exp b/gdb/testsuite/gdb.cp/gdb2495.exp
index 1b3168ee963..7fbadb2c4f1 100644
--- a/gdb/testsuite/gdb.cp/gdb2495.exp
+++ b/gdb/testsuite/gdb.cp/gdb2495.exp
@@ -98,10 +98,10 @@ if {![runto_main]} {
 # behaviour; it should not.  Test both on and off states.
 
 # Turn on unwind on signal behaviour.
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 
 # Check that it is turned on.
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
     "signal is received while in a call dummy is on.*" \
     "turn on unwind on signal"
 
@@ -112,20 +112,20 @@ gdb_test "p exceptions.raise_signal(1)" \
 	 "The program being debugged received signal SIGABRT, Aborted" \
 	 "while in a function called from GDB\\.  GDB has restored the context" \
 	 "to what it was before the call\\.  To change this behavior use" \
-	 "\"set unwindonsignal off\"\\.  Evaluation of the expression containing" \
+	 "\"set unwind-on-signal off\"\\.  Evaluation of the expression containing" \
 	 "the function \\(SimpleException::raise_signal\\(int\\)\\) will be abandoned\\."]\
-    "check for unwindonsignal off message"
+    "check for unwind-on-signal off message"
 
 # And reverse - turn off again.
-gdb_test_no_output "set unwindonsignal off"
+gdb_test_no_output "set unwind-on-signal off"
 
 # Check that it is actually turned off.
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
     "signal is received while in a call dummy is off.*" \
     "turn off unwind on signal"
 
 # Check to see if new behaviour interferes with
 # normal signal handling in inferior function calls.
 gdb_test "p exceptions.raise_signal(1)" \
-    "To change this behavior use \"set unwindonsignal on\".*" \
-    "check for unwindonsignal on message"
+    "To change this behavior use \"set unwind-on-signal on\".*" \
+    "check for unwind-on-signal on message"
diff --git a/gdb/testsuite/gdb.fortran/function-calls.exp b/gdb/testsuite/gdb.fortran/function-calls.exp
index 3e698a55e9e..e0b35d697ad 100644
--- a/gdb/testsuite/gdb.fortran/function-calls.exp
+++ b/gdb/testsuite/gdb.fortran/function-calls.exp
@@ -44,7 +44,7 @@ if {![runto [gdb_get_line_number "post_init"]]} {
 }
 
 # Use inspired by gdb.base/callfuncs.exp.
-gdb_test_no_output "set unwindonsignal on"
+gdb_test_no_output "set unwind-on-signal on"
 
 # Baseline: function and subroutine call with no arguments.
 gdb_test "p no_arg()" " = .TRUE."
diff --git a/gdb/testsuite/gdb.mi/mi-condbreak-fail.exp b/gdb/testsuite/gdb.mi/mi-condbreak-fail.exp
index f84f874593d..fdcfa9bb40c 100644
--- a/gdb/testsuite/gdb.mi/mi-condbreak-fail.exp
+++ b/gdb/testsuite/gdb.mi/mi-condbreak-fail.exp
@@ -43,7 +43,7 @@ proc run_test { unwind_on_signal } {
 	return
     }
 
-    mi_gdb_test "-gdb-set unwindonsignal ${unwind_on_signal}" {\^done} \
+    mi_gdb_test "-gdb-set unwind-on-signal ${unwind_on_signal}" {\^done} \
 	"set unwind-on-signal"
 
     # Create the conditional breakpoint.
@@ -70,7 +70,7 @@ proc run_test { unwind_on_signal } {
 		 "&\"The program being debugged received signal SIGSEGV, Segmentation fault\\\\n\"" \
 		 "&\"while in a function called from GDB\\.  GDB has restored the context\\\\n\"" \
 		 "&\"to what it was before the call\\.  To change this behavior use\\\\n\"" \
-		 "&\"\\\\\"set unwindonsignal off\\\\\"\\.  Evaluation of the expression containing\\\\n\"" \
+		 "&\"\\\\\"set unwind-on-signal off\\\\\"\\.  Evaluation of the expression containing\\\\n\"" \
 		 "&\"the function \\(cond_fail\\) will be abandoned\\.\\\\n\"" \
 		 "=breakpoint-modified,bkpt={number=\"$bpnum\",type=\"breakpoint\",\[^\r\n\]+times=\"1\",\[^\r\n\]+}" \
 		 "~\"\\\\n\"" \
@@ -92,7 +92,7 @@ proc run_test { unwind_on_signal } {
 		 "&\"Error in testing condition for breakpoint $bpnum:\\\\n\"" \
 		 "&\"The program being debugged was signaled while in a function called from GDB\\.\\\\n\"" \
 		 "&\"GDB remains in the frame where the signal was received\\.\\\\n\"" \
-		 "&\"To change this behavior use \\\\\"set unwindonsignal on\\\\\"\\.\\\\n\"" \
+		 "&\"To change this behavior use \\\\\"set unwind-on-signal on\\\\\"\\.\\\\n\"" \
 		 "&\"Evaluation of the expression containing the function\\\\n\"" \
 		 "&\"\\(cond_fail\\) will be abandoned\\.\\\\n\"" \
 		 "&\"When the function is done executing, GDB will silently stop\\.\\\\n\"" \
diff --git a/gdb/testsuite/gdb.mi/mi-condbreak-throw.exp b/gdb/testsuite/gdb.mi/mi-condbreak-throw.exp
index 4f4e3c1f37b..e35ad8f9999 100644
--- a/gdb/testsuite/gdb.mi/mi-condbreak-throw.exp
+++ b/gdb/testsuite/gdb.mi/mi-condbreak-throw.exp
@@ -103,7 +103,7 @@ proc run_test { unwind_on_exception } {
 		 "&\"Error in testing condition for breakpoint $bpnum:\\\\n\"" \
 		 "&\"The program being debugged was signaled while in a function called from GDB\\.\\\\n\"" \
 		 "&\"GDB remains in the frame where the signal was received\\.\\\\n\"" \
-		 "&\"To change this behavior use \\\\\"set unwindonsignal on\\\\\"\\.\\\\n\"" \
+		 "&\"To change this behavior use \\\\\"set unwind-on-signal on\\\\\"\\.\\\\n\"" \
 		 "&\"Evaluation of the expression containing the function\\\\n\"" \
 		 "&\"\\(cond_throw\\(\\)\\) will be abandoned\\.\\\\n\"" \
 		 "&\"When the function is done executing, GDB will silently stop\\.\\\\n\"" \
diff --git a/gdb/testsuite/gdb.mi/mi-syn-frame.exp b/gdb/testsuite/gdb.mi/mi-syn-frame.exp
index 4e4a72225a8..b059d126968 100644
--- a/gdb/testsuite/gdb.mi/mi-syn-frame.exp
+++ b/gdb/testsuite/gdb.mi/mi-syn-frame.exp
@@ -94,7 +94,7 @@ mi_gdb_test "409-stack-list-frames 0 0" \
 # 
 
 mi_gdb_test "410-data-evaluate-expression bar()" \
-  ".*410\\^error,msg=\"The program being debugged was signaled while in a function called from GDB.\\\\nGDB remains in the frame where the signal was received.\\\\nTo change this behavior use \\\\\"set unwindonsignal on\\\\\".\\\\nEvaluation of the expression containing the function\\\\n\\(bar\\) will be abandoned.\\\\nWhen the function is done executing, GDB will silently stop.\"" \
+  ".*410\\^error,msg=\"The program being debugged was signaled while in a function called from GDB.\\\\nGDB remains in the frame where the signal was received.\\\\nTo change this behavior use \\\\\"set unwind-on-signal on\\\\\".\\\\nEvaluation of the expression containing the function\\\\n\\(bar\\) will be abandoned.\\\\nWhen the function is done executing, GDB will silently stop.\"" \
   "call inferior function which raises exception"
 
 mi_gdb_test "411-stack-list-frames" "411\\^done,stack=\\\[frame=\{level=\"0\",addr=\"$hex\",func=\"bar\",file=\".*mi-syn-frame.c\",fullname=\"${fullname_syntax}${srcfile}\",line=\"$decimal\",arch=\"$any\"},frame=\{level=\"1\",addr=\"$hex\",func=\"<function called from gdb>\"\},frame=\{level=\"2\",addr=\"$hex\",func=\"main\",file=\".*mi-syn-frame.c\",fullname=\"${fullname_syntax}${srcfile}\",line=\"$decimal\",arch=\"$any\"}.*\\\]" "backtrace from inferior function at exception"
diff --git a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
index d6069ebaa58..c9508c9d67e 100644
--- a/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
+++ b/gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
@@ -173,7 +173,7 @@ proc_with_prefix run_bp_cond_segfaults { target_async target_non_stop } {
 	     "Error in testing condition for breakpoint ${bp_1_num}:" \
 	     "The program being debugged was signaled while in a function called from GDB\\." \
 	     "GDB remains in the frame where the signal was received\\." \
-	     "To change this behavior use \"set unwindonsignal on\"\\." \
+	     "To change this behavior use \"set unwind-on-signal on\"\\." \
 	     "Evaluation of the expression containing the function" \
 	     "\\(function_that_segfaults\\) will be abandoned\\." \
 	     "When the function is done executing, GDB will silently stop\\."]
diff --git a/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp b/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp
index 4beefd8c9c8..11d9fb2d6d4 100644
--- a/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp
+++ b/gdb/testsuite/gdb.threads/thread-unwindonsignal.exp
@@ -13,7 +13,7 @@
 # You should have received a copy of the GNU General Public License
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-# Test use of unwindonsignal when a hand function call that gets interrupted
+# Test use of unwind-on-signal when a hand function call that gets interrupted
 # by a signal in another thread.
 
 set NR_THREADS 4
@@ -49,12 +49,12 @@ gdb_test "continue" \
 # We want the main thread (hand_call_with_signal) and
 # thread 1 (sigabrt_handler) to both run.
 
-# Do turn on unwindonsignal.
+# Do turn on unwind-on-signal.
 # We want to test gdb handling of the current thread changing when
 # unwindonsignal is in effect.
-gdb_test_no_output "set unwindonsignal on" \
+gdb_test_no_output "set unwind-on-signal on" \
 	"setting unwindonsignal"
-gdb_test "show unwindonsignal" \
+gdb_test "show unwind-on-signal" \
 	"Unwinding of stack .* is on." \
 	"showing unwindonsignal"
 
-- 
2.25.4


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

* Re: [PATCHv11 0/5] Infcalls from B/P conditions in multi-threaded inferiors
  2024-03-05 15:40                   ` [PATCHv11 0/5] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                                       ` (4 preceding siblings ...)
  2024-03-05 15:40                     ` [PATCHv11 5/5] gdb: rename unwindonsignal to unwind-on-signal Andrew Burgess
@ 2024-03-14 16:08                     ` Keith Seitz
  2024-03-15 13:26                     ` Luis Machado
  2024-03-25 17:47                     ` Andrew Burgess
  7 siblings, 0 replies; 202+ messages in thread
From: Keith Seitz @ 2024-03-14 16:08 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

On 3/5/24 07:40, Andrew Burgess wrote:
> In v11:
> 
>    - Rebased onto current upstream/master, only merge conflict was in
>      NEWS file.  Retested with no regressions.
> 

I have lightly perused this series and run tests on an internal infra,
covering all supported Fedora 38 architectures. Having found no issues
or regressions, I think it would be great to see this series released 
with GDB 15.

Keith


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

* Re: [PATCHv11 0/5] Infcalls from B/P conditions in multi-threaded inferiors
  2024-03-05 15:40                   ` [PATCHv11 0/5] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                                       ` (5 preceding siblings ...)
  2024-03-14 16:08                     ` [PATCHv11 0/5] Infcalls from B/P conditions in multi-threaded inferiors Keith Seitz
@ 2024-03-15 13:26                     ` Luis Machado
  2024-03-25 17:47                     ` Andrew Burgess
  7 siblings, 0 replies; 202+ messages in thread
From: Luis Machado @ 2024-03-15 13:26 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

On 3/5/24 15:40, Andrew Burgess wrote:
> In v11:
> 
>   - Rebased onto current upstream/master, only merge conflict was in
>     NEWS file.  Retested with no regressions.
> 
> In v10:
> 
>   - Rebased onto current upstream/master, I've updated the copyright
>     dates from 2023 to 2024.
> 
>   - No merge conflicts (other than NEWS) and no build problems.
> 
> In v9:
> 
>   - Dropped previous patch #4 (gdb/remote: avoid SIGINT after calling
>     remote_target::stop) after feedback from Pedro.  This patch wasn't
>     essential for this series, instead I've just updated some of the
>     tests to expect different output from remote targets.
> 
>   - Updated to more recent master, and applied a small fix due to the
>     recent C++17 changes, nothing huge.
> 
>   - Retested on unix, native-gdbserver, and native-extended-gdbserver
>     boards.
> 
> In v8:
> 
>   - Rebased onto current upstream/master and retested.
> 
>   - Addressed feedback from Baris on patches 1, 2, 3, & 4.  This was
>     mostly minor stuff, comment typos and some improvements to the
>     testsuite.  There was one real (but minor) GDB change in patch 4.
> 
> In v7:
> 
>   - Rebased onto current upstream/master, fixed use of
>     find_thread_ptid which is now a process_stratum_target method,
> 
>   - Retested, with no regressions seen.
> 
> In v6:
> 
>   - Pushed the 5 initial patches.  These were the smaller fixes, and,
>     I felt were pretty obvious fixes.  I'm sure folk will raise
>     objections if they disagree.
> 
>   - Of the remaining patches, #1 to #5 really needs review before they
>     can be merged.  Patch #6 is an obvious cleanup once the first five
>     have been merged.
> 
>   - I've rebased onto current HEAD of master, there's no significant
>     changes.
> 
>   - All other documentation changes have been reviewed and approved.
> 
> In v5:
> 
>   - Rebased to current HEAD of master, minor merge conflict resolved.
>     No other code or documentation changes.
> 
>   - First patch, which was pure documentation, has now been merged.
> 
>   - All other documentation changes have been reviewed and approved.
> 
> In v4:
> 
>   - I believe all the docs changes have been reviewed and approved by Eli,
> 
>   - Rebased onto current master,
> 
>   - Dropped patch #2 from the V3 series,
> 
>   - I have addressed all the issues Baris pointed out, including the
>     fixes for the patch #9 ('gdb: add timeouts for inferior function
>     calls'), which I forgot to do in V3.
> 
> In v3:
> 
>   - Updates for review feedback, biggest changes in #10 and #11, but
>     minor changes to most patches.
> 
> In V2:
> 
>   - Rebased onto something closer to HEAD of master,
> 
>   - Patches #1, #2, #12, and #13 are new in this series,
> 
>   - Patches #3 to #9, and #11 are unchanged since their V1 iteration,
> 
>   - Patches #10 has changed slightly in implementation since v1, and
>     the docs have been significantly updated.
> 
> ---
> 
> Andrew Burgess (5):
>   Revert "gdb: remove unnecessary parameter wait_ptid from
>     do_target_wait"
>   gdb: fix b/p conditions with infcalls in multi-threaded inferiors
>   gdb: add timeouts for inferior function calls
>   gdb: introduce unwind-on-timeout setting
>   gdb: rename unwindonsignal to unwind-on-signal
> 
>  gdb/NEWS                                      |  36 +++
>  gdb/breakpoint.c                              |   2 +
>  gdb/doc/gdb.texinfo                           | 111 ++++++-
>  gdb/gdbthread.h                               |   3 +
>  gdb/infcall.c                                 | 301 +++++++++++++++++-
>  gdb/infrun.c                                  |  70 +++-
>  gdb/infrun.h                                  |   3 +-
>  gdb/testsuite/gdb.base/callfuncs.exp          |   4 +-
>  gdb/testsuite/gdb.base/help.exp               |   2 +-
>  gdb/testsuite/gdb.base/infcall-failure.exp    |   4 +-
>  gdb/testsuite/gdb.base/infcall-timeout.c      |  36 +++
>  gdb/testsuite/gdb.base/infcall-timeout.exp    | 115 +++++++
>  gdb/testsuite/gdb.base/unwindonsignal.exp     |  36 ++-
>  gdb/testsuite/gdb.compile/compile-cplus.exp   |   6 +-
>  gdb/testsuite/gdb.compile/compile.exp         |   6 +-
>  gdb/testsuite/gdb.cp/gdb2495.exp              |  16 +-
>  gdb/testsuite/gdb.fortran/function-calls.exp  |   2 +-
>  gdb/testsuite/gdb.mi/mi-condbreak-fail.exp    |   6 +-
>  gdb/testsuite/gdb.mi/mi-condbreak-throw.exp   |   2 +-
>  gdb/testsuite/gdb.mi/mi-syn-frame.exp         |   2 +-
>  .../infcall-from-bp-cond-other-thread-event.c | 135 ++++++++
>  ...nfcall-from-bp-cond-other-thread-event.exp | 174 ++++++++++
>  .../gdb.threads/infcall-from-bp-cond-simple.c |  89 ++++++
>  .../infcall-from-bp-cond-simple.exp           | 235 ++++++++++++++
>  .../gdb.threads/infcall-from-bp-cond-single.c | 139 ++++++++
>  .../infcall-from-bp-cond-single.exp           | 117 +++++++
>  .../infcall-from-bp-cond-timeout.c            | 169 ++++++++++
>  .../infcall-from-bp-cond-timeout.exp          | 191 +++++++++++
>  .../gdb.threads/thread-unwindonsignal.exp     |   8 +-
>  29 files changed, 1943 insertions(+), 77 deletions(-)
>  create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.c
>  create mode 100644 gdb/testsuite/gdb.base/infcall-timeout.exp
>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.c
>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-other-thread-event.exp
>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.c
>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-simple.exp
>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.c
>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-single.exp
>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.c
>  create mode 100644 gdb/testsuite/gdb.threads/infcall-from-bp-cond-timeout.exp
> 
> 
> base-commit: a7ea089b0bccb6379e079e2ab764c2012d94b472

Just a heads-up I tested this on aarch64-linux and observed no regressions.

Tested-By: Luis Machado <luis.machado@arm.com>

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

* Re: [PATCHv4 01/12] gdb/doc: extended documentation for inferior function calls
  2023-02-28 16:42       ` [PATCHv4 01/12] gdb/doc: extended documentation for inferior function calls Andrew Burgess
@ 2024-03-21  9:03         ` Tom de Vries
  2024-03-21  9:11           ` Tom de Vries
  0 siblings, 1 reply; 202+ messages in thread
From: Tom de Vries @ 2024-03-21  9:03 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

On 2/28/23 17:42, Andrew Burgess via Gdb-patches wrote:
> +If a called function is interrupted for any reason, including hitting
> +a breakpoint, or triggering a watchpoint, and the stack is not unwound

Hi Andrew,

I read this bit and went investigating why a watchpoint didn't trigger 
during a called function (PR31485), and found that in fact we explicitly 
disable watchpoints during a called function.

I suppose we should either drop mentioning the watchpoint here, or 
perhaps better, mention that they are disabled.

And perhaps eventually, allow watchpoints to be triggered.

Thanks,
- Tom

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

* Re: [PATCHv4 01/12] gdb/doc: extended documentation for inferior function calls
  2024-03-21  9:03         ` Tom de Vries
@ 2024-03-21  9:11           ` Tom de Vries
  0 siblings, 0 replies; 202+ messages in thread
From: Tom de Vries @ 2024-03-21  9:11 UTC (permalink / raw)
  To: Andrew Burgess, gdb-patches

On 3/21/24 10:03, Tom de Vries wrote:
> On 2/28/23 17:42, Andrew Burgess via Gdb-patches wrote:
>> +If a called function is interrupted for any reason, including hitting
>> +a breakpoint, or triggering a watchpoint, and the stack is not unwound
> 
> Hi Andrew,
> 
> I read this bit and went investigating why a watchpoint didn't trigger 
> during a called function (PR31485), and found that in fact we explicitly 
> disable watchpoints during a called function.
> 
> I suppose we should either drop mentioning the watchpoint here, or 
> perhaps better, mention that they are disabled.
> 

Ah, I found that the behaviour is documented at the watchpoints side ( 
https://sourceware.org/gdb/current/onlinedocs/gdb.html/Set-Watchpoints.html 
):
...
If you call a function interactively using print or call, any 
watchpoints you have set will be inactive until GDB reaches another kind 
of breakpoint or the call completes.
...

Thanks,
- Tom

> And perhaps eventually, allow watchpoints to be triggered.
> 
> Thanks,
> - Tom


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

* Re: [PATCHv11 0/5] Infcalls from B/P conditions in multi-threaded inferiors
  2024-03-05 15:40                   ` [PATCHv11 0/5] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
                                       ` (6 preceding siblings ...)
  2024-03-15 13:26                     ` Luis Machado
@ 2024-03-25 17:47                     ` Andrew Burgess
  7 siblings, 0 replies; 202+ messages in thread
From: Andrew Burgess @ 2024-03-25 17:47 UTC (permalink / raw)
  To: gdb-patches

Andrew Burgess <aburgess@redhat.com> writes:

> In v11:
>
>   - Rebased onto current upstream/master, only merge conflict was in
>     NEWS file.  Retested with no regressions.

After the independent testing from Keith and Luis, I've gone ahead and
pushed this commit.

If there is any feedback post commit, just let me know, I'm happy to do
any additional work needed.

Thanks,
Andrew


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

end of thread, other threads:[~2024-03-25 17:47 UTC | newest]

Thread overview: 202+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2022-10-21  8:43 [PATCH 00/12] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
2022-10-21  8:43 ` [PATCH 01/12] gdb: int to bool conversion for normal_stop Andrew Burgess
2022-11-04 12:20   ` Lancelot SIX
2023-01-13 16:35     ` Andrew Burgess
2022-10-21  8:43 ` [PATCH 02/12] gdb/infrun: add debug print in print_signal_received_reason Andrew Burgess
2023-01-13 16:38   ` Andrew Burgess
2022-10-21  8:43 ` [PATCH 03/12] gdb: include breakpoint number in testing condition error message Andrew Burgess
2022-10-21  8:43 ` [PATCH 04/12] gdbserver: add comments to read_inferior_memory function Andrew Burgess
2023-01-13 16:42   ` Andrew Burgess
2022-10-21  8:43 ` [PATCH 05/12] gdbserver: allows agent_mem_read to return an error code Andrew Burgess
2022-10-21  8:43 ` [PATCH 06/12] gdbserver: allow agent expressions to fail with invalid memory access Andrew Burgess
2022-10-21  8:43 ` [PATCH 07/12] gdb: avoid repeated signal reporting during failed conditional breakpoint Andrew Burgess
2022-10-21  8:43 ` [PATCH 08/12] gdb: don't always print breakpoint location after failed condition check Andrew Burgess
2022-10-21  8:43 ` [PATCH 09/12] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
2022-10-21  8:43 ` [PATCH 10/12] gdb: fix b/p conditions with infcalls in multi-threaded inferiors Andrew Burgess
2022-10-21  8:43 ` [PATCH 11/12] gdb: add timeouts for inferior function calls Andrew Burgess
2022-10-21 11:08   ` Eli Zaretskii
2023-01-14 11:00     ` Andrew Burgess
2023-01-14 11:48       ` Eli Zaretskii
2023-01-16 17:22         ` Andrew Burgess
2023-01-16 17:27           ` Eli Zaretskii
2022-11-04 23:17   ` Lancelot SIX
2023-01-13 16:49     ` Andrew Burgess
2023-01-16  9:44       ` Lancelot SIX
2022-10-21  8:43 ` [PATCH 12/12] gdb/remote: avoid SIGINT after calling remote_target::stop Andrew Burgess
2023-01-18 16:17 ` [PATCHv2 00/13] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
2023-01-18 16:17   ` [PATCHv2 01/13] gdb/doc: extended documentation for inferior function calls Andrew Burgess
2023-01-18 17:20     ` Eli Zaretskii
2023-03-16 17:15       ` Andrew Burgess
2023-01-19  9:00     ` Aktemur, Tankut Baris
2023-01-18 16:17   ` [PATCHv2 02/13] gdb/doc: extend the documentation for conditional breakpoints Andrew Burgess
2023-01-18 17:22     ` Eli Zaretskii
2023-01-19  9:04     ` Aktemur, Tankut Baris
2023-01-19 10:07       ` Eli Zaretskii
2023-01-18 16:17   ` [PATCHv2 03/13] gdb: include breakpoint number in testing condition error message Andrew Burgess
2023-01-19  9:54     ` Aktemur, Tankut Baris
2023-01-19 10:54     ` Aktemur, Tankut Baris
2023-01-19 11:34       ` Eli Zaretskii
2023-01-20  9:46         ` Aktemur, Tankut Baris
2023-01-25 16:49           ` Andrew Burgess
2023-01-25 17:09             ` Eli Zaretskii
2023-01-18 16:18   ` [PATCHv2 04/13] gdbserver: allows agent_mem_read to return an error code Andrew Burgess
2023-01-19  9:59     ` Aktemur, Tankut Baris
2023-01-18 16:18   ` [PATCHv2 05/13] gdbserver: allow agent expressions to fail with invalid memory access Andrew Burgess
2023-01-19 10:13     ` Aktemur, Tankut Baris
2023-01-18 16:18   ` [PATCHv2 06/13] gdb: avoid repeated signal reporting during failed conditional breakpoint Andrew Burgess
2023-01-19 10:33     ` Aktemur, Tankut Baris
2023-01-18 16:18   ` [PATCHv2 07/13] gdb: don't always print breakpoint location after failed condition check Andrew Burgess
2023-01-19 10:49     ` Aktemur, Tankut Baris
2023-01-18 16:18   ` [PATCHv2 08/13] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
2023-01-19 11:05     ` Aktemur, Tankut Baris
2023-01-18 16:18   ` [PATCHv2 09/13] gdb: fix b/p conditions with infcalls in multi-threaded inferiors Andrew Burgess
2023-01-20  7:13     ` Aktemur, Tankut Baris
2023-01-18 16:18   ` [PATCHv2 10/13] gdb: add timeouts for inferior function calls Andrew Burgess
2023-01-18 17:30     ` Eli Zaretskii
2023-01-20  8:50     ` Aktemur, Tankut Baris
2023-01-18 16:18   ` [PATCHv2 11/13] gdb/remote: avoid SIGINT after calling remote_target::stop Andrew Burgess
2023-01-20  9:14     ` Aktemur, Tankut Baris
2023-01-18 16:18   ` [PATCHv2 12/13] gdb: introduce unwind-on-timeout setting Andrew Burgess
2023-01-18 17:33     ` Eli Zaretskii
2023-01-20  9:26     ` Aktemur, Tankut Baris
2023-01-18 16:18   ` [PATCHv2 13/13] gdb: rename unwindonsignal to unwind-on-signal Andrew Burgess
2023-01-18 17:35     ` Eli Zaretskii
2023-01-20  9:34   ` [PATCHv2 00/13] Infcalls from B/P conditions in multi-threaded inferiors Aktemur, Tankut Baris
2023-01-25 15:53     ` Andrew Burgess
2023-02-16 11:09       ` Aktemur, Tankut Baris
2023-01-31 17:27   ` [PATCHv3 " Andrew Burgess
2023-01-31 17:27     ` [PATCHv3 01/13] gdb/doc: extended documentation for inferior function calls Andrew Burgess
2023-01-31 17:27     ` [PATCHv3 02/13] gdb/doc: extend the documentation for conditional breakpoints Andrew Burgess
2023-01-31 18:07       ` Eli Zaretskii
2023-02-01 17:47         ` Andrew Burgess
2023-02-01 18:25           ` Eli Zaretskii
2023-02-02 13:34             ` Andrew Burgess
2023-01-31 17:27     ` [PATCHv3 03/13] gdb: include breakpoint number in testing condition error message Andrew Burgess
2023-02-16 10:15       ` Aktemur, Tankut Baris
2023-01-31 17:27     ` [PATCHv3 04/13] gdbserver: allows agent_mem_read to return an error code Andrew Burgess
2023-01-31 17:27     ` [PATCHv3 05/13] gdbserver: allow agent expressions to fail with invalid memory access Andrew Burgess
2023-02-16 10:29       ` Aktemur, Tankut Baris
2023-01-31 17:27     ` [PATCHv3 06/13] gdb: avoid repeated signal reporting during failed conditional breakpoint Andrew Burgess
2023-01-31 17:27     ` [PATCHv3 07/13] gdb: don't always print breakpoint location after failed condition check Andrew Burgess
2023-01-31 17:27     ` [PATCHv3 08/13] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
2023-01-31 17:27     ` [PATCHv3 09/13] gdb: fix b/p conditions with infcalls in multi-threaded inferiors Andrew Burgess
2023-02-16 10:47       ` Aktemur, Tankut Baris
2023-01-31 17:27     ` [PATCHv3 10/13] gdb: add timeouts for inferior function calls Andrew Burgess
2023-01-31 18:11       ` Eli Zaretskii
2023-02-01 17:50         ` Andrew Burgess
2023-02-01 18:29           ` Eli Zaretskii
2023-02-16 10:53       ` Aktemur, Tankut Baris
2023-01-31 17:27     ` [PATCHv3 11/13] gdb/remote: avoid SIGINT after calling remote_target::stop Andrew Burgess
2023-01-31 17:27     ` [PATCHv3 12/13] gdb: introduce unwind-on-timeout setting Andrew Burgess
2023-01-31 18:09       ` Eli Zaretskii
2023-02-16 11:01       ` Aktemur, Tankut Baris
2023-01-31 17:27     ` [PATCHv3 13/13] gdb: rename unwindonsignal to unwind-on-signal Andrew Burgess
2023-01-31 18:12       ` Eli Zaretskii
2023-02-28 16:42     ` [PATCHv4 00/12] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
2023-02-28 16:42       ` [PATCHv4 01/12] gdb/doc: extended documentation for inferior function calls Andrew Burgess
2024-03-21  9:03         ` Tom de Vries
2024-03-21  9:11           ` Tom de Vries
2023-02-28 16:42       ` [PATCHv4 02/12] gdb: include breakpoint number in testing condition error message Andrew Burgess
2023-02-28 16:42       ` [PATCHv4 03/12] gdbserver: allows agent_mem_read to return an error code Andrew Burgess
2023-02-28 16:42       ` [PATCHv4 04/12] gdbserver: allow agent expressions to fail with invalid memory access Andrew Burgess
2023-02-28 16:42       ` [PATCHv4 05/12] gdb: avoid repeated signal reporting during failed conditional breakpoint Andrew Burgess
2023-02-28 16:42       ` [PATCHv4 06/12] gdb: don't always print breakpoint location after failed condition check Andrew Burgess
2023-02-28 16:42       ` [PATCHv4 07/12] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
2023-02-28 16:42       ` [PATCHv4 08/12] gdb: fix b/p conditions with infcalls in multi-threaded inferiors Andrew Burgess
2023-02-28 16:42       ` [PATCHv4 09/12] gdb: add timeouts for inferior function calls Andrew Burgess
2023-02-28 16:42       ` [PATCHv4 10/12] gdb/remote: avoid SIGINT after calling remote_target::stop Andrew Burgess
2023-02-28 16:42       ` [PATCHv4 11/12] gdb: introduce unwind-on-timeout setting Andrew Burgess
2023-02-28 16:42       ` [PATCHv4 12/12] gdb: rename unwindonsignal to unwind-on-signal Andrew Burgess
2023-03-16 17:36       ` [PATCHv5 00/11] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
2023-03-16 17:36         ` [PATCHv5 01/11] gdb: include breakpoint number in testing condition error message Andrew Burgess
2023-04-03 13:50           ` Andrew Burgess
2023-07-07 12:08           ` Pedro Alves
2023-07-07 15:43             ` Andrew Burgess
2023-07-07 16:19               ` Pedro Alves
2023-07-10 10:30                 ` Andrew Burgess
2023-03-16 17:36         ` [PATCHv5 02/11] gdbserver: allows agent_mem_read to return an error code Andrew Burgess
2023-04-03 13:50           ` Andrew Burgess
2023-03-16 17:36         ` [PATCHv5 03/11] gdbserver: allow agent expressions to fail with invalid memory access Andrew Burgess
2023-04-03 13:50           ` Andrew Burgess
2023-07-07 12:25           ` Pedro Alves
2023-07-07 16:28             ` Andrew Burgess
2023-07-07 17:26               ` Pedro Alves
2023-07-07 21:19                 ` Andrew Burgess
2023-07-10 10:32                 ` Andrew Burgess
2023-07-10 10:44                   ` Pedro Alves
2023-07-10 13:44                     ` Andrew Burgess
2023-03-16 17:36         ` [PATCHv5 04/11] gdb: avoid repeated signal reporting during failed conditional breakpoint Andrew Burgess
2023-04-03 13:50           ` Andrew Burgess
2023-03-16 17:37         ` [PATCHv5 05/11] gdb: don't always print breakpoint location after failed condition check Andrew Burgess
2023-04-03 13:51           ` Andrew Burgess
2023-07-07 15:20           ` Pedro Alves
2023-07-07 15:24             ` Pedro Alves
2023-07-07 21:18               ` Andrew Burgess
2023-07-11 12:06                 ` Pedro Alves
2023-07-14 12:17                   ` Andrew Burgess
2023-07-17 17:17                     ` Pedro Alves
2023-08-03 13:57                       ` Andrew Burgess
2023-03-16 17:37         ` [PATCHv5 06/11] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
2023-03-16 17:37         ` [PATCHv5 07/11] gdb: fix b/p conditions with infcalls in multi-threaded inferiors Andrew Burgess
2023-03-16 17:37         ` [PATCHv5 08/11] gdb: add timeouts for inferior function calls Andrew Burgess
2023-03-16 17:37         ` [PATCHv5 09/11] gdb/remote: avoid SIGINT after calling remote_target::stop Andrew Burgess
2023-03-16 17:37         ` [PATCHv5 10/11] gdb: introduce unwind-on-timeout setting Andrew Burgess
2023-03-16 17:37         ` [PATCHv5 11/11] gdb: rename unwindonsignal to unwind-on-signal Andrew Burgess
2023-04-03 14:01         ` [PATCHv6 0/6] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
2023-04-03 14:01           ` [PATCHv6 1/6] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
2023-04-03 14:01           ` [PATCHv6 2/6] gdb: fix b/p conditions with infcalls in multi-threaded inferiors Andrew Burgess
2023-04-03 14:01           ` [PATCHv6 3/6] gdb: add timeouts for inferior function calls Andrew Burgess
2023-07-11 14:23             ` Pedro Alves
2023-07-14 15:20               ` Andrew Burgess
2023-07-14 19:52                 ` Andrew Burgess
2023-04-03 14:01           ` [PATCHv6 4/6] gdb/remote: avoid SIGINT after calling remote_target::stop Andrew Burgess
2023-04-03 14:01           ` [PATCHv6 5/6] gdb: introduce unwind-on-timeout setting Andrew Burgess
2023-04-03 14:01           ` [PATCHv6 6/6] gdb: rename unwindonsignal to unwind-on-signal Andrew Burgess
2023-05-15 19:22           ` [PATCHv7 0/6] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
2023-05-15 19:22             ` [PATCHv7 1/6] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
2023-05-16 15:08               ` Aktemur, Tankut Baris
2023-05-15 19:22             ` [PATCHv7 2/6] gdb: fix b/p conditions with infcalls in multi-threaded inferiors Andrew Burgess
2023-05-16 15:09               ` Aktemur, Tankut Baris
2023-06-05 13:53                 ` Andrew Burgess
2023-05-15 19:22             ` [PATCHv7 3/6] gdb: add timeouts for inferior function calls Andrew Burgess
2023-05-16 15:42               ` Aktemur, Tankut Baris
2023-06-05 13:54                 ` Andrew Burgess
2023-05-15 19:22             ` [PATCHv7 4/6] gdb/remote: avoid SIGINT after calling remote_target::stop Andrew Burgess
2023-05-16 16:00               ` Aktemur, Tankut Baris
2023-06-05 13:55                 ` Andrew Burgess
2023-05-15 19:22             ` [PATCHv7 5/6] gdb: introduce unwind-on-timeout setting Andrew Burgess
2023-05-15 19:22             ` [PATCHv7 6/6] gdb: rename unwindonsignal to unwind-on-signal Andrew Burgess
2023-06-07 10:01             ` [PATCHv8 0/6] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
2023-06-07 10:01               ` [PATCHv8 1/6] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
2023-06-07 10:01               ` [PATCHv8 2/6] gdb: fix b/p conditions with infcalls in multi-threaded inferiors Andrew Burgess
2023-06-07 10:01               ` [PATCHv8 3/6] gdb: add timeouts for inferior function calls Andrew Burgess
2023-06-07 10:01               ` [PATCHv8 4/6] gdb/remote: avoid SIGINT after calling remote_target::stop Andrew Burgess
2023-07-07 17:18                 ` Pedro Alves
2023-07-10 20:04                   ` Andrew Burgess
2023-06-07 10:01               ` [PATCHv8 5/6] gdb: introduce unwind-on-timeout setting Andrew Burgess
2023-06-07 10:01               ` [PATCHv8 6/6] gdb: rename unwindonsignal to unwind-on-signal Andrew Burgess
2023-06-07 12:41                 ` Eli Zaretskii
2023-06-07 14:29                   ` Andrew Burgess
2023-06-07 15:31                     ` Eli Zaretskii
2023-07-04 11:20               ` [PATCHv8 0/6] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
2023-12-02 10:52               ` [PATCHv9 0/5] " Andrew Burgess
2023-12-02 10:52                 ` [PATCHv9 1/5] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
2023-12-02 10:52                 ` [PATCHv9 2/5] gdb: fix b/p conditions with infcalls in multi-threaded inferiors Andrew Burgess
2023-12-02 10:52                 ` [PATCHv9 3/5] gdb: add timeouts for inferior function calls Andrew Burgess
2023-12-02 10:52                 ` [PATCHv9 4/5] gdb: introduce unwind-on-timeout setting Andrew Burgess
2023-12-02 10:52                 ` [PATCHv9 5/5] gdb: rename unwindonsignal to unwind-on-signal Andrew Burgess
2024-01-02 15:57                 ` [PATCHv10 0/5] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
2024-01-02 15:57                   ` [PATCHv10 1/5] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
2024-01-02 15:57                   ` [PATCHv10 2/5] gdb: fix b/p conditions with infcalls in multi-threaded inferiors Andrew Burgess
2024-01-02 15:57                   ` [PATCHv10 3/5] gdb: add timeouts for inferior function calls Andrew Burgess
2024-01-02 15:57                   ` [PATCHv10 4/5] gdb: introduce unwind-on-timeout setting Andrew Burgess
2024-01-02 15:57                   ` [PATCHv10 5/5] gdb: rename unwindonsignal to unwind-on-signal Andrew Burgess
2024-03-05 15:40                   ` [PATCHv11 0/5] Infcalls from B/P conditions in multi-threaded inferiors Andrew Burgess
2024-03-05 15:40                     ` [PATCHv11 1/5] Revert "gdb: remove unnecessary parameter wait_ptid from do_target_wait" Andrew Burgess
2024-03-05 15:40                     ` [PATCHv11 2/5] gdb: fix b/p conditions with infcalls in multi-threaded inferiors Andrew Burgess
2024-03-05 15:40                     ` [PATCHv11 3/5] gdb: add timeouts for inferior function calls Andrew Burgess
2024-03-05 15:40                     ` [PATCHv11 4/5] gdb: introduce unwind-on-timeout setting Andrew Burgess
2024-03-05 15:40                     ` [PATCHv11 5/5] gdb: rename unwindonsignal to unwind-on-signal Andrew Burgess
2024-03-14 16:08                     ` [PATCHv11 0/5] Infcalls from B/P conditions in multi-threaded inferiors Keith Seitz
2024-03-15 13:26                     ` Luis Machado
2024-03-25 17:47                     ` 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).