[PATCH v2 23/47] gdb, remote: do 'remote_add_inferior' in 'remote_notice_new_inferior' earlier

Tankut Baris Aktemur
2024-12-13T16:24:34Z

In remote_target::remote_notice_new_inferior, we check if the inferior
for the reported ptid exists, and if not, we add that inferior via
'remote_add_inferior'. However, before adding the new inferior, we
may have already added a new thread, because the thread is not found
via 'in_thread_list'. This may bring the odd situation that a new
thread is being added before its inferior exists. Fix this problem by
moving the check and creation of a new inferior to an earlier spot in
the execution flow.

Note that the code has a check for inferior_ptid.is_pid, but this is
not useful to avoid the problem described above because the core
infrun clears inferior_ptid (i.e. sets to null_ptid) before waiting on
targets for stop events.
---
gdb/remote.c | 23 +++++++++++------------
1 file changed, 11 insertions(+), 12 deletions(-)

diff --git a/gdb/remote.c b/gdb/remote.c
index 31e78fc0b93039df7c7fcff583f77495575ec8f6..4dc79daf0a8618c5920dd9461d91273244326336 100644
--- a/gdb/remote.c
+++ b/gdb/remote.c
@@ -2991,6 +2991,17 @@ remote_target::remote_notice_new_inferior (ptid_t currthread, bool executing)
struct inferior *inf = NULL;
int pid = currthread.pid ();

+ /* When connecting to a target remote, or to a target
+ extended-remote which already was debugging an inferior, we
+ may not know about it yet. Add it before adding its child
+ thread, so notifications are emitted in a sensible order. */
+ if (find_inferior_pid (this, pid) == nullptr)
+ {
+ bool fake_pid_p = !m_features.remote_multi_process_p ();
+
+ inf = remote_add_inferior (fake_pid_p, pid, -1, 1);
+ }
+
if (inferior_ptid.is_pid ()
&& pid == inferior_ptid.pid ())
{
@@ -3021,18 +3032,6 @@ remote_target::remote_notice_new_inferior (ptid_t currthread, bool executing)
return;
}

- /* When connecting to a target remote, or to a target
- extended-remote which already was debugging an inferior, we
- may not know about it yet. Add it before adding its child
- thread, so notifications are emitted in a sensible order. */
- if (find_inferior_pid (this, currthread.pid ()) == NULL)
- {
- bool fake_pid_p = !m_features.remote_multi_process_p ();
-
- inf = remote_add_inferior (fake_pid_p,
- currthread.pid (), -1, 1);
- }
-
/* This is really a new thread. Add it. */
thread_info *new_thr
= remote_add_thread (currthread, running, executing, false);