This is the mail archive of the gdb-patches@sourceware.org mailing list for the GDB project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: [PATCH 3/3] Per-inferior thread list, thread ranges/iterators, down with ALL_THREADS, etc.


On 10/01/2018 06:11 PM, Tom Tromey wrote:

> Pedro> init_wait_for_inferior is currently responsible for discarding skipped
> Pedro> inline frames, which had to be moved elsewhere.
> 
> Note that ASAN pointed out a use-after-free bug in
> clear_inline_frame_state.  It can be called sometimes after the
> thread_info has been deleted, so:
> 
>     return pid == state.thread->inf->pid;
> 
> ... references freed memory.
> 
> I wonder if your patch fixes this.  If not, maybe I have a patch on my
> asan branch (or maybe that was one of the ones I had to rewrite, I can't
> recall at the moment).

Interesting.  Sounds like it might, but I can't tell for sure,
since there's still a call to clear_inline_frame_state with a wildcard
ptid in target_resume.

I ran the gdb.op/inline-frame binary under gdb under valgrind manually
("run" to inline frame, do "info frame", and then "kill"), and that didn't
reveal anything, but then again it also didn't reveal anything without
the patch.

> 
> Pedro>	* inline-frame.c (clear_inline_frame_state(thread_info*)): New
> Pedro>	overload.
> Pedro>	* inline-frame.h (clear_inline_frame_state(thread_info*)): New
> Pedro>	overload.
> 
> I didn't see these in the patch.

Whoops, that was something I realized wasn't needed in this patch yet,
so I removed it and changed the patch to call the existing 
clear_inline_frame_state(ptid_t) overload instead, but forgot to
update the ChangeLog entry.

> 
> Pedro> +/* Filter for filtered_iterator.  Filters out exited inferiors.  */
> Pedro> +
> Pedro> +struct exited_inferior_filter
> Pedro> +{
> Pedro> +  bool operator() (inferior *inf)
> Pedro> +  {
> Pedro> +    return (inf->pid != 0);
> 
> Nit: the parens.  There were some other instances of this.  Maybe we
> don't care.

I've fixed them all, like so:

diff --git i/gdb/common/filtered-iterator.h w/gdb/common/filtered-iterator.h
index 4bfb123170..fe1c20b2e5 100644
--- i/gdb/common/filtered-iterator.h
+++ w/gdb/common/filtered-iterator.h
@@ -64,10 +64,10 @@ public:
   }
 
   bool operator== (const self_type &other) const
-  { return (*m_it == *other.m_it); }
+  { return *m_it == *other.m_it; }
 
   bool operator!= (const self_type &other) const
-  { return (*m_it != *other.m_it); }
+  { return *m_it != *other.m_it; }
 
 private:
 
diff --git i/gdb/common/safe-iterator.h w/gdb/common/safe-iterator.h
index a3d64c0d9f..4210766fde 100644
--- i/gdb/common/safe-iterator.h
+++ w/gdb/common/safe-iterator.h
@@ -74,10 +74,10 @@ public:
   }
 
   bool operator== (const self_type &other) const
-  { return (m_it == other.m_it); }
+  { return m_it == other.m_it; }
 
   bool operator!= (const self_type &other) const
-  { return (m_it != other.m_it); }
+  { return m_it != other.m_it; }
 
 private:
   /* The current element.  */
diff --git i/gdb/inferior-iter.h w/gdb/inferior-iter.h
index e416cc97f2..b5bdf51493 100644
--- i/gdb/inferior-iter.h
+++ w/gdb/inferior-iter.h
@@ -67,7 +67,7 @@ struct exited_inferior_filter
 {
   bool operator() (inferior *inf)
   {
-    return (inf->pid != 0);
+    return inf->pid != 0;
   }
 };
 
diff --git i/gdb/thread-iter.h w/gdb/thread-iter.h
index 967844b64e..3cc185e4b0 100644
--- i/gdb/thread-iter.h
+++ w/gdb/thread-iter.h
@@ -56,7 +56,7 @@ public:
   thread_info *operator* () const { return m_thr; }
 
   bool operator!= (const inf_threads_iterator &other) const
-  { return (m_thr != other.m_thr); }
+  { return m_thr != other.m_thr; }
 
 private:
   /* The currently-iterated thread.  NULL if we reached the end of the
@@ -117,10 +117,10 @@ public:
   }
 
   bool operator== (const all_threads_iterator &other) const
-  { return (m_thr == other.m_thr); }
+  { return m_thr == other.m_thr; }
 
   bool operator!= (const all_threads_iterator &other) const
-  { return (m_thr != other.m_thr); }
+  { return m_thr != other.m_thr; }
 
 private:
   /* Advance to the next thread.  */
@@ -165,10 +165,10 @@ public:
   }
 
   bool operator== (const all_matching_threads_iterator &other) const
-  { return (m_thr == other.m_thr); }
+  { return m_thr == other.m_thr; }
 
   bool operator!= (const all_matching_threads_iterator &other) const
-  { return (m_thr != other.m_thr); }
+  { return m_thr != other.m_thr; }
 
 private:
   /* Advance to next thread, skipping filtered threads.  */
@@ -195,7 +195,7 @@ struct non_exited_thread_filter
 {
   bool operator() (struct thread_info *thr) const
   {
-    return (thr->state != THREAD_EXITED);
+    return thr->state != THREAD_EXITED;
   }
 };
 
diff --git i/gdb/thread.c w/gdb/thread.c
index 156a65a1b9..48d605e612 100644
--- i/gdb/thread.c
+++ w/gdb/thread.c
@@ -359,7 +359,7 @@ thread_info::deletable () const
 {
   /* If this is the current thread, or there's code out there that
      relies on it existing (refcount > 0) we can't delete yet.  */
-  return (refcount () == 0 && ptid != inferior_ptid);
+  return refcount () == 0 && ptid != inferior_ptid;
 }
 
 /* Add TP to the end of the step-over chain LIST_P.  */



> 
> Pedro> +  /* Returns a range adapter covering the inferior's non-exited
> Pedro> +     threads.  Used like this:
> Pedro> +
> Pedro> +       for (thread_info *thr : inf->non_exited_threads ())
> Pedro> +	 [...]
> Pedro> +  */
> Pedro> +  inf_non_exited_threads_range non_exited_threads ()
> Pedro> +  { return inf_non_exited_threads_range (this->thread_list); }
> Pedro> +
> Pedro> +  inline safe_inf_threads_range threads_safe ()
> Pedro> +  { return safe_inf_threads_range (this->thread_list); }
> 
> Nit: threads_safe should have an intro comment.
> 

Whoops.  Added this now:

+  /* Like inferior::threads(), but returns a range adapter that can be
+     used with range-for, safely.  I.e., it is safe to delete the
+     currently-iterated thread, like this:
+
+     for (thread_info *t : inf->threads_safe ())
+       if (some_condition ())
+         delete f;
+  */


> Pedro> +#include "inferior-iter.h"
> 
> I've been using "common/..." but it seems to vary in gdb.

Indeed.  I've added the "common/" prefix to the 
filtered-iterator.h and safe-iterator.h inclusions.
(inferior-iter.h is in gdb/.)

Here's the resulting patch.

>From 99ef2b61a762a6d87e892219cf695b54e310779e Mon Sep 17 00:00:00 2001
From: Pedro Alves <palves@redhat.com>
Date: Mon, 1 Oct 2018 11:15:00 +0100
Subject: [PATCH] Per-inferior thread list, thread ranges/iterators, down with
 ALL_THREADS, etc.

As preparation for multi-target, this patch makes each inferior have
its own thread list.

This isn't absolutely necessary for multi-target, but simplifies
things.  It originally stemmed from the desire to eliminate the
init_thread_list calls sprinkled around, plus it makes it more
efficient to iterate over threads of a given inferior (no need to
always iterate over threads of all inferiors).

We still need to iterate over threads of all inferiors in a number of
places, which means we'd need adjust the ALL_THREADS /
ALL_NON_EXITED_THREADS macros.  However, naively tweaking those macros
to have an extra for loop, like:

     #define ALL_THREADS (thr, inf) \
       for (inf = inferior_list; inf; inf = inf->next) \
	 for (thr = inf->thread_list; thr; thr = thr->next)

causes problems with code that does "break" or "continue" within the
ALL_THREADS loop body.  Plus, we need to declare the extra "inf" local
variable in order to pass it as temporary variable to ALL_THREADS
(etc.)

It gets even trickier when we consider extending the macros to filter
out threads matching a ptid_t and a target.  The macros become tricker
to read/write.  Been there.

An alternative (which was my next attempt), is to replace the
ALL_THREADS etc. iteration style with for_each_all_threads,
for_each_non_exited_threads, etc. functions which would take a
callback as parameter, which would usually be passed a lambda.
However, I did not find that satisfactory at all, because the
resulting code ends up a little less natural / more noisy to read,
write and debug/step-through (due to use of lambdas), and in many
places where we use "continue;" to skip to the next thread now need to
use "return;".  (I ran into hard to debug bugs caused by a
continue/return confusion.)

I.e., before:

    ALL_NON_EXITED_THREADS (tp)
      {
	if (tp->not_what_I_want)
	  continue;
	// do something
      }

would turn into:

    for_each_non_exited_thread ([&] (thread_info *tp)
      {
	if (tp->not_what_I_want)
	  return;
	// do something
      });

Lastly, the solution I settled with was to replace the ALL_THREADS /
ALL_NON_EXITED_THREADS / ALL_INFERIORS macros with (C++20-like) ranges
and iterators, such that you can instead naturaly iterate over
threads/inferiors using range-for, like e.g,.:

   // all threads, including THREAD_EXITED threads.
   for (thread_info *tp : all_threads ())
     { .... }

   // all non-exited threads.
   for (thread_info *tp : all_non_exited_threads ())
     { .... }

   // all non-exited threads of INF inferior.
   for (thread_info *tp : inf->non_exited_threads ())
     { .... }

The all_non_exited_threads() function takes an optional filter ptid_t as
parameter, which is quite convenient when we need to iterate over
threads matching that filter.  See e.g., how the
set_executing/set_stop_requested/finish_thread_state etc. functions in
thread.c end up being simplified.

Most of the patch thus is about adding the infrustructure for allowing
the above.  Later on when we get to actual multi-target, these
functions/ranges/iterators will gain a "target_ops *" parameter so
that e.g., we can iterate over all threads of a given target that
match a given filter ptid_t.

The only entry points users needs to be aware of are the
all_threads/all_non_exited_threads etc. functions seen above.  Thus,
those functions are declared in gdbthread.h/inferior.h.  The actual
iterators/ranges are mainly "internals" and thus are put out of view
in the new thread-iter.h/thread-iter.c/inferior-iter.h files.  That
keeps the gdbthread.h/inferior.h headers quite a bit more readable.

A common/safe-iterator.h header is added which adds a template that
can be used to build "safe" iterators, which are forward iterators
that can be used to replace the ALL_THREADS_SAFE macro and other
instances of the same idiom in future.

There's a little bit of shuffling of code between
gdbthread.h/thread.c/inferior.h in the patch.  That is necessary in
order to avoid circular dependencies between the
gdbthread.h/inferior.h headers.

As for the init_thread_list calls sprinkled around, they're all
eliminated by this patch, and a new, central call is added to
inferior_appeared.  Note how also related to that, there's a call to
init_wait_for_inferior in remote.c that is eliminated.
init_wait_for_inferior is currently responsible for discarding skipped
inline frames, which had to be moved elsewhere.  Given that nowadays
we always have a thread even for single-threaded processes, the
natural place is to delete a frame's inline frame info when we delete
the thread.  I.e., from clear_thread_inferior_resources.

gdb/ChangeLog:
yyyy-mm-dd  Pedro Alves  <palves@redhat.com>

	* Makefile.in (COMMON_SFILES): Add thread-iter.c.
	* breakpoint.c (breakpoints_should_be_inserted_now): Replace
	ALL_NON_EXITED_THREADS with all_non_exited_threads.
	(print_one_breakpoint_location): Replace ALL_INFERIORS with
	all_inferiors.
	* btrace.c (btrace_free_objfile): Replace ALL_NON_EXITED_THREADS
	with all_non_exited_threads.
	* common/filtered-iterator.h: New.
	* common/safe-iterator.h: New.
	* corelow.c (core_target_open): Don't call init_thread_list here.
	* darwin-nat.c (thread_info_from_private_thread_info): Replace
	ALL_THREADS with all_threads.
	* fbsd-nat.c (fbsd_nat_target::resume): Replace
	ALL_NON_EXITED_THREADS with inf->non_exited_threads.
	* fbsd-tdep.c (fbsd_make_corefile_notes): Replace
	ALL_NON_EXITED_THREADS with inf->non_exited_threads.
	* fork-child.c (postfork_hook): Don't call init_thread_list here.
	* gdbarch-selftests.c (register_to_value_test): Adjust.
	* gdbthread.h: Don't include "inferior.h" here.
	(struct inferior): Forward declare.
	(enum step_over_calls_kind): Moved here from inferior.h.
	(thread_info::deletable): Definition moved to thread.c.
	(find_thread_ptid (inferior *, ptid_t)): Declare.
	(ALL_THREADS, ALL_THREADS_BY_INFERIOR, ALL_THREADS_SAFE): Delete.
	Include "thread-iter.h".
	(all_threads, all_non_exited_threads, all_threads_safe): New.
	(any_thread_p): Declare.
	(thread_list): Delete.
	* infcmd.c (signal_command): Replace ALL_NON_EXITED_THREADS with
	all_non_exited_threads.
	(proceed_after_attach_callback): Delete.
	(proceed_after_attach): Take an inferior pointer instead of an
	integer PID.  Adjust to use range-for.
	(attach_post_wait): Pass down inferior pointer instead of pid.
	Use range-for instead of ALL_NON_EXITED_THREADS.
	(detach_command): Remove init_thread_list call.
	* inferior-iter.h: New.
	* inferior.c (struct delete_thread_of_inferior_arg): Delete.
	(delete_thread_of_inferior): Delete.
	(delete_inferior, exit_inferior_1): Use range-for with
	inf->threads_safe() instead of iterate_over_threads.
	(inferior_appeared): Call init_thread_list here.
	(discard_all_inferiors): Use all_non_exited_inferiors.
	(find_inferior_id, find_inferior_pid): Use all_inferiors.
	(iterate_over_inferiors): Use all_inferiors_safe.
	(have_inferiors, number_of_live_inferiors): Use
	all_non_exited_inferiors.
	(number_of_inferiors): Use all_inferiors and std::distance.
	(print_inferior): Use all_inferiors.
	* inferior.h: Include gdbthread.h.
	(enum step_over_calls_kind): Moved to gdbthread.h.
	(struct inferior) <thread_list>: New field.
	<threads, non_exited_threads, threads_safe>: New methods.
	(ALL_INFERIORS): Delete.
	Include "inferior-iter.h".
	(ALL_NON_EXITED_INFERIORS): Delete.
	(all_inferiors_safe, all_inferiors, all_non_exited_inferiors): New
	functions.
	* inflow.c (child_interrupt, child_pass_ctrlc): Replace
	ALL_NON_EXITED_THREADS with all_non_exited_threads.
	* infrun.c (follow_exec): Use all_threads_safe.
	(clear_proceed_status, proceed): Use all_non_exited_threads.
	(init_wait_for_inferior): Don't clear inline frame state here.
	(infrun_thread_stop_requested, for_each_just_stopped_thread): Use
	all_threads instead of ALL_NON_EXITED_THREADS.
	(random_pending_event_thread): Use all_non_exited_threads instead
	of ALL_NON_EXITED_THREADS.  Use a lambda for repeated code.
	(clean_up_just_stopped_threads_fsms): Use all_non_exited_threads
	instead of ALL_NON_EXITED_THREADS.
	(handle_no_resumed): Use all_non_exited_threads instead of
	ALL_NON_EXITED_THREADS.  Use all_inferiors instead of
	ALL_INFERIORS.
	(restart_threads, switch_back_to_stepped_thread): Use
	all_non_exited_threads instead of ALL_NON_EXITED_THREADS.
	* linux-nat.c (check_zombie_leaders): Replace ALL_INFERIORS with
	all_inferiors.
	(kill_unfollowed_fork_children): Use inf->non_exited_threads
	instead of ALL_NON_EXITED_THREADS.
	* linux-tdep.c (linux_make_corefile_notes): Use
	inf->non_exited_threads instead of ALL_NON_EXITED_THREADS.
	* linux-thread-db.c (thread_db_target::update_thread_list):
	Replace ALL_INFERIORS with all_inferiors.
	(thread_db_target::thread_handle_to_thread_info): Use
	inf->non_exited_threads instead of ALL_NON_EXITED_THREADS.
	* mi/mi-interp.c (multiple_inferiors_p): New.
	(mi_on_resume_1): Simplify using all_non_exited_threads and
	multiple_inferiors_p.
	* mi/mi-main.c (mi_cmd_thread_list_ids): Use all_non_exited_threads
	instead of ALL_NON_EXITED_THREADS.
	* nto-procfs.c (nto_procfs_target::open): Don't call
	init_thread_list here.
	* record-btrace.c (record_btrace_target_open)
	(record_btrace_target::stop_recording)
	(record_btrace_target::close)
	(record_btrace_target::record_is_replaying)
	(record_btrace_target::resume, record_btrace_target::wait)
	(record_btrace_target::record_stop_replaying): Use
	all_non_exited_threads instead of ALL_NON_EXITED_THREADS.
	* record-full.c (record_full_wait_1): Use all_non_exited_threads
	instead of ALL_NON_EXITED_THREADS.
	* regcache.c (cooked_read_test): Remove reference to global
	thread_list.
	* remote-sim.c (gdbsim_target::create_inferior): Don't call
	init_thread_list here.
	* remote.c (remote_target::update_thread_list): Use
	all_threads_safe instead of ALL_NON_EXITED_THREADS.
	(remote_target::process_initial_stop_replies): Replace
	ALL_INFERIORS with all_non_exited_inferiors and use
	all_non_exited_threads instead of ALL_NON_EXITED_THREADS.
	(remote_target::open_1): Don't call init_thread_list here.
	(remote_target::append_pending_thread_resumptions)
	(remote_target::remote_resume_with_hc): Use all_non_exited_threads
	instead of ALL_NON_EXITED_THREADS.
	(remote_target::commit_resume)
	(remote_target::remove_new_fork_children): Replace ALL_INFERIORS
	with all_non_exited_inferiors and use all_non_exited_threads
	instead of ALL_NON_EXITED_THREADS.
	(remote_target::kill_new_fork_children): Use
	all_non_exited_threads instead of ALL_NON_EXITED_THREADS.  Remove
	init_thread_list and init_wait_for_inferior calls.
	(remote_target::remote_btrace_maybe_reopen)
	(remote_target::thread_handle_to_thread_info): Use
	all_non_exited_threads instead of ALL_NON_EXITED_THREADS.
	* target.c (target_terminal::restore_inferior)
	(target_terminal_is_ours_kind): Replace ALL_INFERIORS with
	all_non_exited_inferiors.
	* thread-iter.c: New file.
	* thread-iter.h: New file.
	* thread.c: Include "inline-frame.h".
	(thread_list): Delete.
	(clear_thread_inferior_resources): Call clear_inline_frame_state.
	(init_thread_list): Use all_threads_safe instead of
	ALL_THREADS_SAFE.  Adjust to per-inferior thread lists.
	(new_thread): Adjust to per-inferior thread lists.
	(add_thread_silent): Pass inferior to find_thread_ptid.
	(thread_info::deletable): New, moved from the header.
	(delete_thread_1): Adjust to per-inferior thread lists.
	(find_thread_global_id): Use inf->threads().
	(find_thread_ptid): Use find_inferior_ptid and pass inferior to
	find_thread_ptid.
	(find_thread_ptid(inferior*, ptid_t)): New overload.
	(iterate_over_threads): Use all_threads_safe.
	(any_thread_p): New.
	(thread_count): Use all_threads and std::distance.
	(live_threads_count): Use all_non_exited_threads and
	std::distance.
	(valid_global_thread_id): Use all_threads.
	(in_thread_list): Use find_thread_ptid.
	(first_thread_of_inferior): Adjust to per-inferior thread lists.
	(any_thread_of_inferior, any_live_thread_of_inferior): Use
	inf->non_exited_threads().
	(prune_threads, delete_exited_threads): Use all_threads_safe.
	(thread_change_ptid): Pass inferior pointer to find_thread_ptid.
	(set_resumed, set_running): Use all_non_exited_threads.
	(is_thread_state, is_stopped, is_exited, is_running)
	(is_executing): Delete.
	(set_executing, set_stop_requested, finish_thread_state): Use
	all_non_exited_threads.
	(print_thread_info_1): Use all_inferiors and all_threads.
	(thread_apply_all_command): Use all_non_exited_threads.
	(thread_find_command): Use all_threads.
	(update_threads_executing): Use all_non_exited_threads.
	* tid-parse.c (parse_thread_id): Use inf->threads.
	* x86-bsd-nat.c (x86bsd_dr_set): Use inf->non_exited_threads ().
---
 gdb/Makefile.in                |   1 +
 gdb/breakpoint.c               |   7 +-
 gdb/btrace.c                   |   4 +-
 gdb/common/filtered-iterator.h |  87 +++++++++++
 gdb/common/safe-iterator.h     |  93 +++++++++++
 gdb/corelow.c                  |   6 -
 gdb/darwin-nat.c               |  10 +-
 gdb/fbsd-nat.c                 |  21 +--
 gdb/fbsd-tdep.c                |   6 +-
 gdb/fork-child.c               |   7 +-
 gdb/gdbarch-selftests.c        |   2 +-
 gdb/gdbthread.h                |  94 +++++++----
 gdb/infcmd.c                   |  69 +++-----
 gdb/inferior-iter.h            | 117 ++++++++++++++
 gdb/inferior.c                 | 129 +++++----------
 gdb/inferior.h                 |  91 ++++++++---
 gdb/inflow.c                   |   6 +-
 gdb/infrun.c                   | 181 +++++++++------------
 gdb/linux-nat.c                |  43 +++--
 gdb/linux-tdep.c               |   6 +-
 gdb/linux-thread-db.c          |   8 +-
 gdb/mi/mi-interp.c             |  60 +++----
 gdb/mi/mi-main.c               |   5 +-
 gdb/nto-procfs.c               |   2 -
 gdb/record-btrace.c            |  72 +++------
 gdb/record-full.c              |   4 +-
 gdb/regcache.c                 |   3 -
 gdb/remote-sim.c               |   3 -
 gdb/remote.c                   |  75 +++------
 gdb/target.c                   |   8 +-
 gdb/thread-iter.c              | 101 ++++++++++++
 gdb/thread-iter.h              | 311 ++++++++++++++++++++++++++++++++++++
 gdb/thread.c                   | 346 ++++++++++++-----------------------------
 gdb/tid-parse.c                |  12 +-
 gdb/x86-bsd-nat.c              |  14 +-
 35 files changed, 1211 insertions(+), 793 deletions(-)
 create mode 100644 gdb/common/filtered-iterator.h
 create mode 100644 gdb/common/safe-iterator.h
 create mode 100644 gdb/inferior-iter.h
 create mode 100644 gdb/thread-iter.c
 create mode 100644 gdb/thread-iter.h

diff --git a/gdb/Makefile.in b/gdb/Makefile.in
index f856c32383..e17e97ddea 100644
--- a/gdb/Makefile.in
+++ b/gdb/Makefile.in
@@ -1105,6 +1105,7 @@ COMMON_SFILES = \
 	target-descriptions.c \
 	target-memory.c \
 	thread.c \
+	thread-iter.c \
 	thread-fsm.c \
 	tid-parse.c \
 	top.c \
diff --git a/gdb/breakpoint.c b/gdb/breakpoint.c
index eb408d7547..0b5f9867c4 100644
--- a/gdb/breakpoint.c
+++ b/gdb/breakpoint.c
@@ -400,8 +400,6 @@ breakpoints_should_be_inserted_now (void)
     }
   else if (target_has_execution)
     {
-      struct thread_info *tp;
-
       if (always_inserted_mode)
 	{
 	  /* The user wants breakpoints inserted even if all threads
@@ -414,7 +412,7 @@ breakpoints_should_be_inserted_now (void)
 
       /* Don't remove breakpoints yet if, even though all threads are
 	 stopped, we still have events to process.  */
-      ALL_NON_EXITED_THREADS (tp)
+      for (thread_info *tp : all_non_exited_threads ())
 	if (tp->resumed
 	    && tp->suspend.waitstatus_pending_p)
 	  return 1;
@@ -6156,11 +6154,10 @@ print_one_breakpoint_location (struct breakpoint *b,
 
   if (loc != NULL && !header_of_multiple)
     {
-      struct inferior *inf;
       std::vector<int> inf_nums;
       int mi_only = 1;
 
-      ALL_INFERIORS (inf)
+      for (inferior *inf : all_inferiors ())
 	{
 	  if (inf->pspace == loc->pspace)
 	    inf_nums.push_back (inf->num);
diff --git a/gdb/btrace.c b/gdb/btrace.c
index e25f047ce2..3e660c4760 100644
--- a/gdb/btrace.c
+++ b/gdb/btrace.c
@@ -1989,11 +1989,9 @@ btrace_clear (struct thread_info *tp)
 void
 btrace_free_objfile (struct objfile *objfile)
 {
-  struct thread_info *tp;
-
   DEBUG ("free objfile");
 
-  ALL_NON_EXITED_THREADS (tp)
+  for (thread_info *tp : all_non_exited_threads ())
     btrace_clear (tp);
 }
 
diff --git a/gdb/common/filtered-iterator.h b/gdb/common/filtered-iterator.h
new file mode 100644
index 0000000000..fe1c20b2e5
--- /dev/null
+++ b/gdb/common/filtered-iterator.h
@@ -0,0 +1,87 @@
+/* A forward filtered iterator for GDB, the GNU debugger.
+   Copyright (C) 2018 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/>.  */
+
+#ifndef FILTERED_ITERATOR_H
+#define FILTERED_ITERATOR_H
+
+/* A filtered iterator.  This wraps BaseIterator and automatically
+   skips elements that FilterFunc filters out.  Requires that
+   default-constructing a BaseIterator creates a valid one-past-end
+   iterator.  */
+
+template<typename BaseIterator, typename FilterFunc>
+class filtered_iterator
+{
+public:
+  typedef filtered_iterator self_type;
+  typedef typename BaseIterator::value_type value_type;
+  typedef typename BaseIterator::reference reference;
+  typedef typename BaseIterator::pointer pointer;
+  typedef typename BaseIterator::iterator_category iterator_category;
+  typedef typename BaseIterator::difference_type difference_type;
+
+  /* Construct by forwarding all arguments to the underlying
+     iterator.  */
+  template<typename... Args>
+  explicit filtered_iterator (Args &&...args)
+    : m_it (std::forward<Args> (args)...)
+  { skip_filtered (); }
+
+  /* Create a one-past-end iterator.  */
+  filtered_iterator () = default;
+
+  /* Need these as the variadic constructor would be a better match
+     otherwise.  */
+  filtered_iterator (filtered_iterator &) = default;
+  filtered_iterator (const filtered_iterator &) = default;
+  filtered_iterator (filtered_iterator &&) = default;
+  filtered_iterator (const filtered_iterator &&other)
+    : filtered_iterator (static_cast<const filtered_iterator &> (other))
+  {}
+
+  value_type operator* () const { return *m_it; }
+
+  self_type &operator++ ()
+  {
+    ++m_it;
+    skip_filtered ();
+    return *this;
+  }
+
+  bool operator== (const self_type &other) const
+  { return *m_it == *other.m_it; }
+
+  bool operator!= (const self_type &other) const
+  { return *m_it != *other.m_it; }
+
+private:
+
+  void skip_filtered ()
+  {
+    for (; m_it != m_end; ++m_it)
+      if (m_filter (*m_it))
+	break;
+  }
+
+private:
+  FilterFunc m_filter {};
+  BaseIterator m_it {};
+  BaseIterator m_end {};
+};
+
+#endif /* FILTERED_ITERATOR_H */
diff --git a/gdb/common/safe-iterator.h b/gdb/common/safe-iterator.h
new file mode 100644
index 0000000000..4210766fde
--- /dev/null
+++ b/gdb/common/safe-iterator.h
@@ -0,0 +1,93 @@
+/* A safe iterator for GDB, the GNU debugger.
+   Copyright (C) 2018 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/>.  */
+
+#ifndef SAFE_ITERATOR_H
+#define SAFE_ITERATOR_H
+
+/* A forward iterator that wraps Iterator, such that when iterating
+   with iterator IT, it is possible to delete *IT without invalidating
+   IT.  Suitably wrapped in a range type and used with range-for, this
+   allow convenient patterns like this:
+
+     // range_safe() returns a range type whose begin()/end() methods
+     // return safe iterators.
+     for (foo *f : range_safe ())
+       {
+	 if (f->should_delete ())
+	   {
+	     // The ++it operation implicitly done by the range-for is
+	     // still OK after this.
+	     delete f;
+	   }
+       }
+*/
+
+template<typename Iterator>
+class basic_safe_iterator
+{
+public:
+  typedef basic_safe_iterator self_type;
+  typedef typename Iterator::value_type value_type;
+  typedef typename Iterator::reference reference;
+  typedef typename Iterator::pointer pointer;
+  typedef typename Iterator::iterator_category iterator_category;
+  typedef typename Iterator::difference_type difference_type;
+
+  /* Construct by forwarding all arguments to the underlying
+     iterator.  */
+  template<typename... Args>
+  explicit basic_safe_iterator (Args &&...args)
+    : m_it (std::forward<Args> (args)...),
+      m_next (m_it)
+  {
+    if (m_it != m_end)
+      ++m_next;
+  }
+
+  /* Create a one-past-end iterator.  */
+  basic_safe_iterator ()
+  {}
+
+  value_type operator* () const { return *m_it; }
+
+  self_type &operator++ ()
+  {
+    m_it = m_next;
+    if (m_it != m_end)
+      ++m_next;
+    return *this;
+  }
+
+  bool operator== (const self_type &other) const
+  { return m_it == other.m_it; }
+
+  bool operator!= (const self_type &other) const
+  { return m_it != other.m_it; }
+
+private:
+  /* The current element.  */
+  Iterator m_it {};
+
+  /* The next element.  Always one element ahead of M_IT.  */
+  Iterator m_next {};
+
+  /* A one-past-end iterator.  */
+  Iterator m_end {};
+};
+
+#endif /* SAFE_ITERATOR_H */
diff --git a/gdb/corelow.c b/gdb/corelow.c
index 8e9ac9a328..72f2807640 100644
--- a/gdb/corelow.c
+++ b/gdb/corelow.c
@@ -421,12 +421,6 @@ core_target_open (const char *arg, int from_tty)
   push_target (target);
   target_holder.release ();
 
-  /* Do this before acknowledging the inferior, so if
-     post_create_inferior throws (can happen easilly if you're loading
-     a core file with the wrong exec), we aren't left with threads
-     from the previous inferior.  */
-  init_thread_list ();
-
   inferior_ptid = null_ptid;
 
   /* Need to flush the register cache (and the frame cache) from a
diff --git a/gdb/darwin-nat.c b/gdb/darwin-nat.c
index ecc7635d04..fe9e0ad5fd 100644
--- a/gdb/darwin-nat.c
+++ b/gdb/darwin-nat.c
@@ -1698,19 +1698,15 @@ darwin_attach_pid (struct inferior *inf)
 static struct thread_info *
 thread_info_from_private_thread_info (darwin_thread_info *pti)
 {
-  struct thread_info *it;
-
-  ALL_THREADS (it)
+  for (struct thread_info *it : all_threads ())
     {
       darwin_thread_info *iter_pti = get_darwin_thread_info (it);
 
       if (iter_pti->gdb_port == pti->gdb_port)
-	break;
+	return it;
     }
 
-  gdb_assert (it != NULL);
-
-  return it;
+  gdb_assert_not_reached ("did not find gdb thread for darwin thread");
 }
 
 static void
diff --git a/gdb/fbsd-nat.c b/gdb/fbsd-nat.c
index 24e40e2406..f35fd39ac6 100644
--- a/gdb/fbsd-nat.c
+++ b/gdb/fbsd-nat.c
@@ -1189,13 +1189,11 @@ fbsd_nat_target::resume (ptid_t ptid, int step, enum gdb_signal signo)
   if (ptid.lwp_p ())
     {
       /* If ptid is a specific LWP, suspend all other LWPs in the process.  */
-      struct thread_info *tp;
-      int request;
+      inferior *inf = find_inferior_ptid (ptid);
 
-      ALL_NON_EXITED_THREADS (tp)
+      for (thread_info *tp : inf->non_exited_threads ())
         {
-	  if (tp->ptid.pid () != ptid.pid ())
-	    continue;
+	  int request;
 
 	  if (tp->ptid.lwp () == ptid.lwp ())
 	    request = PT_RESUME;
@@ -1210,16 +1208,9 @@ fbsd_nat_target::resume (ptid_t ptid, int step, enum gdb_signal signo)
     {
       /* If ptid is a wildcard, resume all matching threads (they won't run
 	 until the process is continued however).  */
-      struct thread_info *tp;
-
-      ALL_NON_EXITED_THREADS (tp)
-        {
-	  if (!tp->ptid.matches (ptid))
-	    continue;
-
-	  if (ptrace (PT_RESUME, tp->ptid.lwp (), NULL, 0) == -1)
-	    perror_with_name (("ptrace"));
-	}
+      for (thread_info *tp : all_non_exited_threads (ptid))
+	if (ptrace (PT_RESUME, tp->ptid.lwp (), NULL, 0) == -1)
+	  perror_with_name (("ptrace"));
       ptid = inferior_ptid;
     }
 
diff --git a/gdb/fbsd-tdep.c b/gdb/fbsd-tdep.c
index 070d448b4e..7a5ec7f156 100644
--- a/gdb/fbsd-tdep.c
+++ b/gdb/fbsd-tdep.c
@@ -653,7 +653,7 @@ fbsd_make_corefile_notes (struct gdbarch *gdbarch, bfd *obfd, int *note_size)
   struct fbsd_corefile_thread_data thread_args;
   char *note_data = NULL;
   Elf_Internal_Ehdr *i_ehdrp;
-  struct thread_info *curr_thr, *signalled_thr, *thr;
+  struct thread_info *curr_thr, *signalled_thr;
 
   /* Put a "FreeBSD" label in the ELF header.  */
   i_ehdrp = elf_elfheader (obfd);
@@ -706,12 +706,10 @@ fbsd_make_corefile_notes (struct gdbarch *gdbarch, bfd *obfd, int *note_size)
   thread_args.stop_signal = signalled_thr->suspend.stop_signal;
 
   fbsd_corefile_thread (signalled_thr, &thread_args);
-  ALL_NON_EXITED_THREADS (thr)
+  for (thread_info *thr : current_inferior ()->non_exited_threads ())
     {
       if (thr == signalled_thr)
 	continue;
-      if (thr->ptid.pid () != inferior_ptid.pid ())
-	continue;
 
       fbsd_corefile_thread (thr, &thread_args);
     }
diff --git a/gdb/fork-child.c b/gdb/fork-child.c
index 1de96b6685..17427408f8 100644
--- a/gdb/fork-child.c
+++ b/gdb/fork-child.c
@@ -78,12 +78,7 @@ prefork_hook (const char *args)
 void
 postfork_hook (pid_t pid)
 {
-  struct inferior *inf;
-
-  if (!have_inferiors ())
-    init_thread_list ();
-
-  inf = current_inferior ();
+  inferior *inf = current_inferior ();
 
   inferior_appeared (inf, pid);
 
diff --git a/gdb/gdbarch-selftests.c b/gdb/gdbarch-selftests.c
index 73a31244b4..98bd5c32f7 100644
--- a/gdb/gdbarch-selftests.c
+++ b/gdb/gdbarch-selftests.c
@@ -86,7 +86,7 @@ register_to_value_test (struct gdbarch *gdbarch)
   thread_info mock_thread (&mock_inferior, mock_ptid);
 
   scoped_restore restore_thread_list
-    = make_scoped_restore (&thread_list, &mock_thread);
+    = make_scoped_restore (&mock_inferior.thread_list, &mock_thread);
 
   /* Add the mock inferior to the inferior list so that look ups by
      target+ptid can find it.  */
diff --git a/gdb/gdbthread.h b/gdb/gdbthread.h
index 2738e44da9..94fc1b7472 100644
--- a/gdb/gdbthread.h
+++ b/gdb/gdbthread.h
@@ -26,7 +26,6 @@ struct symtab;
 #include "breakpoint.h"
 #include "frame.h"
 #include "ui-out.h"
-#include "inferior.h"
 #include "btrace.h"
 #include "common/vec.h"
 #include "target/waitstatus.h"
@@ -34,6 +33,8 @@ struct symtab;
 #include "common/refcounted-object.h"
 #include "common-gdbthread.h"
 
+struct inferior;
+
 /* Frontend view of the thread state.  Possible extensions: stepping,
    finishing, until(ling),...  */
 enum thread_state
@@ -43,6 +44,17 @@ enum thread_state
   THREAD_EXITED,
 };
 
+/* STEP_OVER_ALL means step over all subroutine calls.
+   STEP_OVER_UNDEBUGGABLE means step over calls to undebuggable functions.
+   STEP_OVER_NONE means don't step over any subroutine calls.  */
+
+enum step_over_calls_kind
+  {
+    STEP_OVER_NONE,
+    STEP_OVER_ALL,
+    STEP_OVER_UNDEBUGGABLE
+  };
+
 /* Inferior thread specific part of `struct infcall_control_state'.
 
    Inferior process counterpart is `struct inferior_control_state'.  */
@@ -213,12 +225,7 @@ public:
   explicit thread_info (inferior *inf, ptid_t ptid);
   ~thread_info ();
 
-  bool deletable () const
-  {
-    /* If this is the current thread, or there's code out there that
-       relies on it existing (refcount > 0) we can't delete yet.  */
-    return (refcount () == 0 && ptid != inferior_ptid);
-  }
+  bool deletable () const;
 
   /* Mark this thread as running and notify observers.  */
   void set_running (bool running);
@@ -449,6 +456,10 @@ extern int valid_global_thread_id (int global_id);
 /* Search function to lookup a thread by 'pid'.  */
 extern struct thread_info *find_thread_ptid (ptid_t ptid);
 
+/* Search function to lookup a thread by 'ptid'.  Only searches in
+   threads of INF.  */
+extern struct thread_info *find_thread_ptid (inferior *inf, ptid_t ptid);
+
 /* Find thread by GDB global thread ID.  */
 struct thread_info *find_thread_global_id (int global_id);
 
@@ -475,32 +486,61 @@ void thread_change_ptid (ptid_t old_ptid, ptid_t new_ptid);
 typedef int (*thread_callback_func) (struct thread_info *, void *);
 extern struct thread_info *iterate_over_threads (thread_callback_func, void *);
 
-/* Traverse all threads.  */
-#define ALL_THREADS(T)				\
-  for (T = thread_list; T; T = T->next)		\
+/* Pull in the internals of the inferiors/threads ranges and
+   iterators.  Must be done after struct thread_info is defined.  */
+#include "thread-iter.h"
+
+/* Return a range that can be used to walk over all threads of all
+   inferiors, with range-for.  Used like this:
+
+       for (thread_info *thr : all_threads ())
+	 { .... }
+*/
+inline all_threads_range
+all_threads ()
+{
+  return {};
+}
+
+/* Likewise, but accept a filter PTID.  */
 
-/* Traverse over all threads, sorted by inferior.  */
-#define ALL_THREADS_BY_INFERIOR(inf, tp) \
-  ALL_INFERIORS (inf) \
-    ALL_THREADS (tp) \
-      if (inf == tp->inf)
+inline all_matching_threads_range
+all_threads (ptid_t filter_ptid)
+{
+  return all_matching_threads_range (filter_ptid);
+}
 
-/* Traverse all threads, except those that have THREAD_EXITED
-   state.  */
+/* Return a range that can be used to walk over all non-exited threads
+   of all inferiors, with range-for.  FILTER_PTID can be used to
+   filter out thread that don't match.  */
+
+inline all_non_exited_threads_range
+all_non_exited_threads (ptid_t filter_ptid = minus_one_ptid)
+{
+  return all_non_exited_threads_range (filter_ptid);
+}
 
-#define ALL_NON_EXITED_THREADS(T)				\
-  for (T = thread_list; T; T = T->next) \
-    if ((T)->state != THREAD_EXITED)
+/* Return a range that can be used to walk over all threads of all
+   inferiors, with range-for, safely.  I.e., it is safe to delete the
+   currently-iterated thread.  When combined with range-for, this
+   allow convenient patterns like this:
 
-/* Traverse all threads, including those that have THREAD_EXITED
-   state.  Allows deleting the currently iterated thread.  */
-#define ALL_THREADS_SAFE(T, TMP)	\
-  for ((T) = thread_list;			\
-       (T) != NULL ? ((TMP) = (T)->next, 1): 0;	\
-       (T) = (TMP))
+     for (thread_info *t : all_threads_safe ())
+       if (some_condition ())
+	 delete f;
+*/
+
+inline all_threads_safe_range
+all_threads_safe ()
+{
+  return all_threads_safe_range ();
+}
 
 extern int thread_count (void);
 
+/* Return true if we have any thread in any inferior.  */
+extern bool any_thread_p ();
+
 /* Switch context to thread THR.  Also sets the STOP_PC global.  */
 extern void switch_to_thread (struct thread_info *thr);
 
@@ -748,6 +788,4 @@ extern void print_selected_thread_frame (struct ui_out *uiout,
    alive anymore.  */
 extern void thread_select (const char *tidstr, class thread_info *thr);
 
-extern struct thread_info *thread_list;
-
 #endif /* GDBTHREAD_H */
diff --git a/gdb/infcmd.c b/gdb/infcmd.c
index da0cb340ac..f5690ee52f 100644
--- a/gdb/infcmd.c
+++ b/gdb/infcmd.c
@@ -1339,20 +1339,16 @@ signal_command (const char *signum_exp, int from_tty)
      of the wrong thread.  */
   if (!non_stop)
     {
-      struct thread_info *tp;
-      ptid_t resume_ptid;
       int must_confirm = 0;
 
       /* This indicates what will be resumed.  Either a single thread,
 	 a whole process, or all threads of all processes.  */
-      resume_ptid = user_visible_resume_ptid (0);
+      ptid_t resume_ptid = user_visible_resume_ptid (0);
 
-      ALL_NON_EXITED_THREADS (tp)
+      for (thread_info *tp : all_non_exited_threads (resume_ptid))
 	{
 	  if (tp->ptid == inferior_ptid)
 	    continue;
-	  if (!tp->ptid.matches (resume_ptid))
-	    continue;
 
 	  if (tp->suspend.stop_signal != GDB_SIGNAL_0
 	      && signal_pass_state (tp->suspend.stop_signal))
@@ -2626,34 +2622,13 @@ kill_command (const char *arg, int from_tty)
   bfd_cache_close_all ();
 }
 
-/* Used in `attach&' command.  ARG is a point to an integer
-   representing a process id.  Proceed threads of this process iff
+/* Used in `attach&' command.  Proceed threads of inferior INF iff
    they stopped due to debugger request, and when they did, they
-   reported a clean stop (GDB_SIGNAL_0).  Do not proceed threads
-   that have been explicitly been told to stop.  */
-
-static int
-proceed_after_attach_callback (struct thread_info *thread,
-			       void *arg)
-{
-  int pid = * (int *) arg;
-
-  if (thread->ptid.pid () == pid
-      && thread->state != THREAD_EXITED
-      && !thread->executing
-      && !thread->stop_requested
-      && thread->suspend.stop_signal == GDB_SIGNAL_0)
-    {
-      switch_to_thread (thread);
-      clear_proceed_status (0);
-      proceed ((CORE_ADDR) -1, GDB_SIGNAL_DEFAULT);
-    }
-
-  return 0;
-}
+   reported a clean stop (GDB_SIGNAL_0).  Do not proceed threads that
+   have been explicitly been told to stop.  */
 
 static void
-proceed_after_attach (int pid)
+proceed_after_attach (inferior *inf)
 {
   /* Don't error out if the current thread is running, because
      there may be other stopped threads.  */
@@ -2661,7 +2636,15 @@ proceed_after_attach (int pid)
   /* Backup current thread and selected frame.  */
   scoped_restore_current_thread restore_thread;
 
-  iterate_over_threads (proceed_after_attach_callback, &pid);
+  for (thread_info *thread : inf->non_exited_threads ())
+    if (!thread->executing
+	&& !thread->stop_requested
+	&& thread->suspend.stop_signal == GDB_SIGNAL_0)
+      {
+	switch_to_thread (thread);
+	clear_proceed_status (0);
+	proceed ((CORE_ADDR) -1, GDB_SIGNAL_DEFAULT);
+      }
 }
 
 /* See inferior.h.  */
@@ -2728,7 +2711,7 @@ attach_post_wait (const char *args, int from_tty, enum attach_post_wait_mode mod
 	 already running threads.  If a thread has been stopped with a
 	 signal, leave it be.  */
       if (non_stop)
-	proceed_after_attach (inferior->pid);
+	proceed_after_attach (inferior);
       else
 	{
 	  if (inferior_thread ()->suspend.stop_signal == GDB_SIGNAL_0)
@@ -2754,9 +2737,7 @@ attach_post_wait (const char *args, int from_tty, enum attach_post_wait_mode mod
 	target_stop (ptid_t (inferior->pid));
       else if (target_is_non_stop_p ())
 	{
-	  struct thread_info *thread;
 	  struct thread_info *lowest = inferior_thread ();
-	  int pid = current_inferior ()->pid;
 
 	  stop_all_threads ();
 
@@ -2764,15 +2745,10 @@ attach_post_wait (const char *args, int from_tty, enum attach_post_wait_mode mod
 	     stop.  For consistency, always select the thread with
 	     lowest GDB number, which should be the main thread, if it
 	     still exists.  */
-	  ALL_NON_EXITED_THREADS (thread)
-	    {
-	      if (thread->ptid.pid () == pid)
-		{
-		  if (thread->inf->num < lowest->inf->num
-		      || thread->per_inf_num < lowest->per_inf_num)
-		    lowest = thread;
-		}
-	    }
+	  for (thread_info *thread : current_inferior ()->non_exited_threads ())
+	    if (thread->inf->num < lowest->inf->num
+		|| thread->per_inf_num < lowest->per_inf_num)
+	      lowest = thread;
 
 	  switch_to_thread (lowest);
 	}
@@ -3020,11 +2996,6 @@ detach_command (const char *args, int from_tty)
   if (!gdbarch_has_global_solist (target_gdbarch ()))
     no_shared_libraries (NULL, from_tty);
 
-  /* If we still have inferiors to debug, then don't mess with their
-     threads.  */
-  if (!have_inferiors ())
-    init_thread_list ();
-
   if (deprecated_detach_hook)
     deprecated_detach_hook ();
 }
diff --git a/gdb/inferior-iter.h b/gdb/inferior-iter.h
new file mode 100644
index 0000000000..2993c3eaf2
--- /dev/null
+++ b/gdb/inferior-iter.h
@@ -0,0 +1,117 @@
+/* Inferior iterators and ranges for GDB, the GNU debugger.
+
+   Copyright (C) 2018 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/>.  */
+
+#ifndef INFERIOR_ITER_H
+#define INFERIOR_ITER_H
+
+#include "common/filtered-iterator.h"
+#include "common/safe-iterator.h"
+
+/* A forward iterator that iterates over all inferiors.  */
+
+class all_inferiors_iterator
+{
+public:
+  typedef all_inferiors_iterator self_type;
+  typedef struct inferior *value_type;
+  typedef struct inferior *&reference;
+  typedef struct inferior **pointer;
+  typedef std::forward_iterator_tag iterator_category;
+  typedef int difference_type;
+
+  /* Create an iterator pointing at HEAD.  */
+  explicit all_inferiors_iterator (inferior *head)
+    : m_inf (head)
+  {}
+
+  /* Create a one-past-end iterator.  */
+  all_inferiors_iterator ()
+    : m_inf (nullptr)
+  {}
+
+  all_inferiors_iterator &operator++ ()
+  {
+    m_inf = m_inf->next;
+    return *this;
+  }
+
+  inferior *operator* () const
+  { return m_inf; }
+
+  bool operator!= (const all_inferiors_iterator &other) const
+  { return m_inf != other.m_inf; }
+
+private:
+  inferior *m_inf;
+};
+
+/* Filter for filtered_iterator.  Filters out exited inferiors.  */
+
+struct exited_inferior_filter
+{
+  bool operator() (inferior *inf)
+  {
+    return inf->pid != 0;
+  }
+};
+
+/* Iterate over all non-exited inferiors.  */
+
+using all_non_exited_inferiors_iterator
+  = filtered_iterator<all_inferiors_iterator, exited_inferior_filter>;
+
+/* A range adapter that makes it possible to iterate over all
+   inferiors with range-for.  */
+struct all_inferiors_range
+{
+  all_inferiors_iterator begin () const
+  { return all_inferiors_iterator (inferior_list); }
+  all_inferiors_iterator end () const
+  { return all_inferiors_iterator (); }
+};
+
+/* Iterate over all inferiors, safely.  */
+
+using all_inferiors_safe_iterator
+  = basic_safe_iterator<all_inferiors_iterator>;
+
+/* A range adapter that makes it possible to iterate over all
+   inferiors with range-for "safely".  I.e., it is safe to delete the
+   currently-iterated inferior.  */
+
+struct all_inferiors_safe_range
+{
+  all_inferiors_safe_iterator begin () const
+  { return all_inferiors_safe_iterator (inferior_list); }
+  all_inferiors_safe_iterator end () const
+  { return all_inferiors_safe_iterator (); }
+};
+
+/* A range adapter that makes it possible to iterate over all
+   non-exited inferiors with range-for.  */
+
+struct all_non_exited_inferiors_range
+{
+  all_non_exited_inferiors_iterator begin () const
+  { return all_non_exited_inferiors_iterator (inferior_list); }
+  all_non_exited_inferiors_iterator end () const
+  { return all_non_exited_inferiors_iterator (); }
+};
+
+#endif /* !defined (INFERIOR_ITER_H) */
diff --git a/gdb/inferior.c b/gdb/inferior.c
index 394386a4b7..af65aa5ce7 100644
--- a/gdb/inferior.c
+++ b/gdb/inferior.c
@@ -134,34 +134,10 @@ add_inferior (int pid)
   return inf;
 }
 
-struct delete_thread_of_inferior_arg
-{
-  int pid;
-  int silent;
-};
-
-static int
-delete_thread_of_inferior (struct thread_info *tp, void *data)
-{
-  struct delete_thread_of_inferior_arg *arg
-    = (struct delete_thread_of_inferior_arg *) data;
-
-  if (tp->ptid.pid () == arg->pid)
-    {
-      if (arg->silent)
-	delete_thread_silent (tp);
-      else
-	delete_thread (tp);
-    }
-
-  return 0;
-}
-
 void
 delete_inferior (struct inferior *todel)
 {
   struct inferior *inf, *infprev;
-  struct delete_thread_of_inferior_arg arg;
 
   infprev = NULL;
 
@@ -172,10 +148,8 @@ delete_inferior (struct inferior *todel)
   if (!inf)
     return;
 
-  arg.pid = inf->pid;
-  arg.silent = 1;
-
-  iterate_over_threads (delete_thread_of_inferior, &arg);
+  for (thread_info *tp : inf->threads_safe ())
+    delete_thread_silent (tp);
 
   if (infprev)
     infprev->next = inf->next;
@@ -198,7 +172,6 @@ static void
 exit_inferior_1 (struct inferior *inftoex, int silent)
 {
   struct inferior *inf;
-  struct delete_thread_of_inferior_arg arg;
 
   for (inf = inferior_list; inf; inf = inf->next)
     if (inf == inftoex)
@@ -207,10 +180,13 @@ exit_inferior_1 (struct inferior *inftoex, int silent)
   if (!inf)
     return;
 
-  arg.pid = inf->pid;
-  arg.silent = silent;
-
-  iterate_over_threads (delete_thread_of_inferior, &arg);
+  for (thread_info *tp : inf->threads_safe ())
+    {
+      if (silent)
+	delete_thread_silent (tp);
+      else
+	delete_thread (tp);
+    }
 
   gdb::observers::inferior_exit.notify (inf);
 
@@ -273,6 +249,11 @@ detach_inferior (inferior *inf)
 void
 inferior_appeared (struct inferior *inf, int pid)
 {
+  /* If this is the first inferior with threads, reset the global
+     thread id.  */
+  if (!any_thread_p ())
+    init_thread_list ();
+
   inf->pid = pid;
   inf->has_exit_code = 0;
   inf->exit_code = 0;
@@ -283,21 +264,14 @@ inferior_appeared (struct inferior *inf, int pid)
 void
 discard_all_inferiors (void)
 {
-  struct inferior *inf;
-
-  for (inf = inferior_list; inf; inf = inf->next)
-    {
-      if (inf->pid != 0)
-	exit_inferior_silent (inf);
-    }
+  for (inferior *inf : all_non_exited_inferiors ())
+    exit_inferior_silent (inf);
 }
 
 struct inferior *
 find_inferior_id (int num)
 {
-  struct inferior *inf;
-
-  for (inf = inferior_list; inf; inf = inf->next)
+  for (inferior *inf : all_inferiors ())
     if (inf->num == num)
       return inf;
 
@@ -307,14 +281,12 @@ find_inferior_id (int num)
 struct inferior *
 find_inferior_pid (int pid)
 {
-  struct inferior *inf;
-
   /* Looking for inferior pid == 0 is always wrong, and indicative of
      a bug somewhere else.  There may be more than one with pid == 0,
      for instance.  */
   gdb_assert (pid != 0);
 
-  for (inf = inferior_list; inf; inf = inf->next)
+  for (inferior *inf : all_inferiors ())
     if (inf->pid == pid)
       return inf;
 
@@ -339,11 +311,9 @@ find_inferior_for_program_space (struct program_space *pspace)
   if (inf->pspace == pspace)
     return inf;
 
-  for (inf = inferior_list; inf != NULL; inf = inf->next)
-    {
-      if (inf->pspace == pspace)
-	return inf;
-    }
+  for (inferior *inf : all_inferiors ())
+    if (inf->pspace == pspace)
+      return inf;
 
   return NULL;
 }
@@ -352,14 +322,9 @@ struct inferior *
 iterate_over_inferiors (int (*callback) (struct inferior *, void *),
 			void *data)
 {
-  struct inferior *inf, *infnext;
-
-  for (inf = inferior_list; inf; inf = infnext)
-    {
-      infnext = inf->next;
-      if ((*callback) (inf, data))
-	return inf;
-    }
+  for (inferior *inf : all_inferiors_safe ())
+    if ((*callback) (inf, data))
+      return inf;
 
   return NULL;
 }
@@ -367,11 +332,8 @@ iterate_over_inferiors (int (*callback) (struct inferior *, void *),
 int
 have_inferiors (void)
 {
-  struct inferior *inf;
-
-  for (inf = inferior_list; inf; inf = inf->next)
-    if (inf->pid != 0)
-      return 1;
+  for (inferior *inf ATTRIBUTE_UNUSED : all_non_exited_inferiors ())
+    return 1;
 
   return 0;
 }
@@ -383,24 +345,17 @@ have_inferiors (void)
 int
 number_of_live_inferiors (void)
 {
-  struct inferior *inf;
   int num_inf = 0;
 
-  for (inf = inferior_list; inf; inf = inf->next)
-    if (inf->pid != 0)
-      {
-	struct thread_info *tp;
-
-	ALL_NON_EXITED_THREADS (tp)
-	 if (tp && tp->ptid.pid () == inf->pid)
-	   if (target_has_execution_1 (tp->ptid))
-	     {
-	       /* Found a live thread in this inferior, go to the next
-		  inferior.  */
-	       ++num_inf;
-	       break;
-	     }
-      }
+  for (inferior *inf : all_non_exited_inferiors ())
+    if (target_has_execution_1 (ptid_t (inf->pid)))
+      for (thread_info *tp ATTRIBUTE_UNUSED : inf->non_exited_threads ())
+	{
+	  /* Found a live thread in this inferior, go to the next
+	     inferior.  */
+	  ++num_inf;
+	  break;
+	}
 
   return num_inf;
 }
@@ -445,13 +400,8 @@ prune_inferiors (void)
 int
 number_of_inferiors (void)
 {
-  struct inferior *inf;
-  int count = 0;
-
-  for (inf = inferior_list; inf != NULL; inf = inf->next)
-    count++;
-
-  return count;
+  auto rng = all_inferiors ();
+  return std::distance (rng.begin (), rng.end ());
 }
 
 /* Converts an inferior process id to a string.  Like
@@ -491,11 +441,10 @@ print_selected_inferior (struct ui_out *uiout)
 static void
 print_inferior (struct ui_out *uiout, const char *requested_inferiors)
 {
-  struct inferior *inf;
   int inf_count = 0;
 
   /* Compute number of inferiors we will print.  */
-  for (inf = inferior_list; inf; inf = inf->next)
+  for (inferior *inf : all_inferiors ())
     {
       if (!number_is_in_list (requested_inferiors, inf->num))
 	continue;
@@ -516,7 +465,7 @@ print_inferior (struct ui_out *uiout, const char *requested_inferiors)
   uiout->table_header (17, ui_left, "exec", "Executable");
 
   uiout->table_body ();
-  for (inf = inferior_list; inf; inf = inf->next)
+  for (inferior *inf : all_inferiors ())
     {
       if (!number_is_in_list (requested_inferiors, inf->num))
 	continue;
diff --git a/gdb/inferior.h b/gdb/inferior.h
index af5e920196..33c2eac9d3 100644
--- a/gdb/inferior.h
+++ b/gdb/inferior.h
@@ -53,6 +53,7 @@ struct thread_info;
 #include "common/refcounted-object.h"
 
 #include "common-inferior.h"
+#include "gdbthread.h"
 
 struct infcall_suspend_state;
 struct infcall_control_state;
@@ -245,17 +246,6 @@ extern int stopped_by_random_signal;
    `set print inferior-events'.  */
 extern int print_inferior_events;
 
-/* STEP_OVER_ALL means step over all subroutine calls.
-   STEP_OVER_UNDEBUGGABLE means step over calls to undebuggable functions.
-   STEP_OVER_NONE means don't step over any subroutine calls.  */
-
-enum step_over_calls_kind
-  {
-    STEP_OVER_NONE,
-    STEP_OVER_ALL,
-    STEP_OVER_UNDEBUGGABLE
-  };
-
 /* Anything but NO_STOP_QUIETLY means we expect a trap and the caller
    will handle it themselves.  STOP_QUIETLY is used when running in
    the shell before the child program has been exec'd and when running
@@ -360,6 +350,38 @@ public:
   /* Pointer to next inferior in singly-linked list of inferiors.  */
   struct inferior *next = NULL;
 
+  /* This inferior's thread list.  */
+  thread_info *thread_list = nullptr;
+
+  /* Returns a range adapter covering the inferior's threads,
+     including exited threads.  Used like this:
+
+       for (thread_info *thr : inf->threads ())
+	 { .... }
+  */
+  inf_threads_range threads ()
+  { return inf_threads_range (this->thread_list); }
+
+  /* Returns a range adapter covering the inferior's non-exited
+     threads.  Used like this:
+
+       for (thread_info *thr : inf->non_exited_threads ())
+	 { .... }
+  */
+  inf_non_exited_threads_range non_exited_threads ()
+  { return inf_non_exited_threads_range (this->thread_list); }
+
+  /* Like inferior::threads(), but returns a range adapter that can be
+     used with range-for, safely.  I.e., it is safe to delete the
+     currently-iterated thread, like this:
+
+     for (thread_info *t : inf->threads_safe ())
+       if (some_condition ())
+	 delete f;
+  */
+  inline safe_inf_threads_range threads_safe ()
+  { return safe_inf_threads_range (this->thread_list); }
+
   /* Convenient handle (GDB inferior id).  Unique across all
      inferiors.  */
   int num = 0;
@@ -575,16 +597,49 @@ private:
 
 /* Traverse all inferiors.  */
 
-#define ALL_INFERIORS(I) \
-  for ((I) = inferior_list; (I); (I) = (I)->next)
+extern struct inferior *inferior_list;
 
-/* Traverse all non-exited inferiors.  */
+/* Pull in the internals of the inferiors ranges and iterators.  Must
+   be done after struct inferior is defined.  */
+#include "inferior-iter.h"
 
-#define ALL_NON_EXITED_INFERIORS(I) \
-  ALL_INFERIORS (I)		    \
-    if ((I)->pid != 0)
+/* Return a range that can be used to walk over all inferiors
+   inferiors, with range-for, safely.  I.e., it is safe to delete the
+   currently-iterated inferior.  When combined with range-for, this
+   allow convenient patterns like this:
 
-extern struct inferior *inferior_list;
+     for (inferior *inf : all_inferiors_safe ())
+       if (some_condition ())
+	 delete inf;
+*/
+
+inline all_inferiors_safe_range
+all_inferiors_safe ()
+{
+  return {};
+}
+
+/* Returns a range representing all inferiors, suitable to use with
+   range-for, like this:
+
+   for (inferior *inf : all_inferiors ())
+     [...]
+*/
+
+inline all_inferiors_range
+all_inferiors ()
+{
+  return {};
+}
+
+/* Return a range that can be used to walk over all inferiors with PID
+   not zero, with range-for.  */
+
+inline all_non_exited_inferiors_range
+all_non_exited_inferiors ()
+{
+  return {};
+}
 
 /* Prune away automatically added inferiors that aren't required
    anymore.  */
diff --git a/gdb/inflow.c b/gdb/inflow.c
index caff646207..64e8ad686a 100644
--- a/gdb/inflow.c
+++ b/gdb/inflow.c
@@ -546,9 +546,8 @@ void
 child_interrupt (struct target_ops *self)
 {
   /* Interrupt the first inferior that has a resumed thread.  */
-  thread_info *thr;
   thread_info *resumed = NULL;
-  ALL_NON_EXITED_THREADS (thr)
+  for (thread_info *thr : all_non_exited_threads ())
     {
       if (thr->executing)
 	{
@@ -605,8 +604,7 @@ child_pass_ctrlc (struct target_ops *self)
 
   /* Otherwise, pass the Ctrl-C to the first inferior that was resumed
      in the foreground.  */
-  inferior *inf;
-  ALL_INFERIORS (inf)
+  for (inferior *inf : all_inferiors ())
     {
       if (inf->terminal_state != target_terminal_state::is_ours)
 	{
diff --git a/gdb/infrun.c b/gdb/infrun.c
index 3ddb231ffe..e0b11d5b86 100644
--- a/gdb/infrun.c
+++ b/gdb/infrun.c
@@ -1082,7 +1082,6 @@ show_follow_exec_mode_string (struct ui_file *file, int from_tty,
 static void
 follow_exec (ptid_t ptid, char *exec_file_target)
 {
-  struct thread_info *th, *tmp;
   struct inferior *inf = current_inferior ();
   int pid = ptid.pid ();
   ptid_t process_ptid;
@@ -1129,7 +1128,7 @@ follow_exec (ptid_t ptid, char *exec_file_target)
      them.  Deleting them now rather than at the next user-visible
      stop provides a nicer sequence of events for user and MI
      notifications.  */
-  ALL_THREADS_SAFE (th, tmp)
+  for (thread_info *th : all_threads_safe ())
     if (th->ptid.pid () == pid && th->ptid != ptid)
       delete_thread (th);
 
@@ -1137,7 +1136,7 @@ follow_exec (ptid_t ptid, char *exec_file_target)
      leader/event thread.  E.g., if there was any step-resume
      breakpoint or similar, it's gone now.  We cannot truly
      step-to-next statement through an exec().  */
-  th = inferior_thread ();
+  thread_info *th = inferior_thread ();
   th->control.step_resume_breakpoint = NULL;
   th->control.exception_resume_breakpoint = NULL;
   th->control.single_step_breakpoints = NULL;
@@ -2862,21 +2861,14 @@ clear_proceed_status (int step)
 				     execution_direction))
     target_record_stop_replaying ();
 
-  if (!non_stop)
+  if (!non_stop && inferior_ptid != null_ptid)
     {
-      struct thread_info *tp;
-      ptid_t resume_ptid;
-
-      resume_ptid = user_visible_resume_ptid (step);
+      ptid_t resume_ptid = user_visible_resume_ptid (step);
 
       /* In all-stop mode, delete the per-thread status of all threads
 	 we're about to resume, implicitly and explicitly.  */
-      ALL_NON_EXITED_THREADS (tp)
-        {
-	  if (!tp->ptid.matches (resume_ptid))
-	    continue;
-	  clear_proceed_status_thread (tp);
-	}
+      for (thread_info *tp : all_non_exited_threads (resume_ptid))
+	clear_proceed_status_thread (tp);
     }
 
   if (inferior_ptid != null_ptid)
@@ -3079,17 +3071,13 @@ proceed (CORE_ADDR addr, enum gdb_signal siggnal)
     {
       struct thread_info *current = tp;
 
-      ALL_NON_EXITED_THREADS (tp)
-        {
+      for (thread_info *tp : all_non_exited_threads (resume_ptid))
+	{
 	  /* Ignore the current thread here.  It's handled
 	     afterwards.  */
 	  if (tp == current)
 	    continue;
 
-	  /* Ignore threads of processes we're not resuming.  */
-	  if (!tp->ptid.matches (resume_ptid))
-	    continue;
-
 	  if (!thread_still_needs_step_over (tp))
 	    continue;
 
@@ -3138,12 +3126,8 @@ proceed (CORE_ADDR addr, enum gdb_signal siggnal)
       {
 	/* In all-stop, but the target is always in non-stop mode.
 	   Start all other threads that are implicitly resumed too.  */
-	ALL_NON_EXITED_THREADS (tp)
+      for (thread_info *tp : all_non_exited_threads (resume_ptid))
         {
-	  /* Ignore threads of processes we're not resuming.  */
-	  if (!tp->ptid.matches (resume_ptid))
-	    continue;
-
 	  if (tp->resumed)
 	    {
 	      if (debug_infrun)
@@ -3246,9 +3230,6 @@ init_wait_for_inferior (void)
   target_last_wait_ptid = minus_one_ptid;
 
   previous_inferior_ptid = inferior_ptid;
-
-  /* Discard any skipped inlined frames.  */
-  clear_inline_frame_state (minus_one_ptid);
 }
 
 
@@ -3276,53 +3257,50 @@ static int switch_back_to_stepped_thread (struct execution_control_state *ecs);
 static void
 infrun_thread_stop_requested (ptid_t ptid)
 {
-  struct thread_info *tp;
-
   /* PTID was requested to stop.  If the thread was already stopped,
      but the user/frontend doesn't know about that yet (e.g., the
      thread had been temporarily paused for some step-over), set up
      for reporting the stop now.  */
-  ALL_NON_EXITED_THREADS (tp)
-    if (tp->ptid.matches (ptid))
-      {
-	if (tp->state != THREAD_RUNNING)
-	  continue;
-	if (tp->executing)
-	  continue;
+  for (thread_info *tp : all_threads (ptid))
+    {
+      if (tp->state != THREAD_RUNNING)
+	continue;
+      if (tp->executing)
+	continue;
 
-	/* Remove matching threads from the step-over queue, so
-	   start_step_over doesn't try to resume them
-	   automatically.  */
-	if (thread_is_in_step_over_chain (tp))
-	  thread_step_over_chain_remove (tp);
-
-	/* If the thread is stopped, but the user/frontend doesn't
-	   know about that yet, queue a pending event, as if the
-	   thread had just stopped now.  Unless the thread already had
-	   a pending event.  */
-	if (!tp->suspend.waitstatus_pending_p)
-	  {
-	    tp->suspend.waitstatus_pending_p = 1;
-	    tp->suspend.waitstatus.kind = TARGET_WAITKIND_STOPPED;
-	    tp->suspend.waitstatus.value.sig = GDB_SIGNAL_0;
-	  }
+      /* Remove matching threads from the step-over queue, so
+	 start_step_over doesn't try to resume them
+	 automatically.  */
+      if (thread_is_in_step_over_chain (tp))
+	thread_step_over_chain_remove (tp);
 
-	/* Clear the inline-frame state, since we're re-processing the
-	   stop.  */
-	clear_inline_frame_state (tp->ptid);
+      /* If the thread is stopped, but the user/frontend doesn't
+	 know about that yet, queue a pending event, as if the
+	 thread had just stopped now.  Unless the thread already had
+	 a pending event.  */
+      if (!tp->suspend.waitstatus_pending_p)
+	{
+	  tp->suspend.waitstatus_pending_p = 1;
+	  tp->suspend.waitstatus.kind = TARGET_WAITKIND_STOPPED;
+	  tp->suspend.waitstatus.value.sig = GDB_SIGNAL_0;
+	}
 
-	/* If this thread was paused because some other thread was
-	   doing an inline-step over, let that finish first.  Once
-	   that happens, we'll restart all threads and consume pending
-	   stop events then.  */
-	if (step_over_info_valid_p ())
-	  continue;
+      /* Clear the inline-frame state, since we're re-processing the
+	 stop.  */
+      clear_inline_frame_state (tp->ptid);
 
-	/* Otherwise we can process the (new) pending event now.  Set
-	   it so this pending event is considered by
-	   do_target_wait.  */
-	tp->resumed = 1;
-      }
+      /* If this thread was paused because some other thread was
+	 doing an inline-step over, let that finish first.  Once
+	 that happens, we'll restart all threads and consume pending
+	 stop events then.  */
+      if (step_over_info_valid_p ())
+	continue;
+
+      /* Otherwise we can process the (new) pending event now.  Set
+	 it so this pending event is considered by
+	 do_target_wait.  */
+      tp->resumed = 1;
+    }
 }
 
 static void
@@ -3363,13 +3341,9 @@ for_each_just_stopped_thread (for_each_just_stopped_thread_callback_func func)
     }
   else
     {
-      struct thread_info *tp;
-
       /* In all-stop mode, all threads have stopped.  */
-      ALL_NON_EXITED_THREADS (tp)
-        {
-	  func (tp);
-	}
+      for (thread_info *tp : all_non_exited_threads ())
+	func (tp);
     }
 }
 
@@ -3438,24 +3412,26 @@ print_target_wait_results (ptid_t waiton_ptid, ptid_t result_ptid,
 static struct thread_info *
 random_pending_event_thread (ptid_t waiton_ptid)
 {
-  struct thread_info *event_tp;
   int num_events = 0;
-  int random_selector;
+
+  auto has_event = [] (thread_info *tp)
+    {
+      return (tp->resumed
+	      && tp->suspend.waitstatus_pending_p);
+    };
 
   /* First see how many events we have.  Count only resumed threads
      that have an event pending.  */
-  ALL_NON_EXITED_THREADS (event_tp)
-    if (event_tp->ptid.matches (waiton_ptid)
-	&& event_tp->resumed
-	&& event_tp->suspend.waitstatus_pending_p)
+  for (thread_info *tp : all_non_exited_threads (waiton_ptid))
+    if (has_event (tp))
       num_events++;
 
   if (num_events == 0)
     return NULL;
 
   /* Now randomly pick a thread out of those that have had events.  */
-  random_selector = (int)
-    ((num_events * (double) rand ()) / (RAND_MAX + 1.0));
+  int random_selector = (int) ((num_events * (double) rand ())
+			       / (RAND_MAX + 1.0));
 
   if (debug_infrun && num_events > 1)
     fprintf_unfiltered (gdb_stdlog,
@@ -3463,14 +3439,12 @@ random_pending_event_thread (ptid_t waiton_ptid)
 			num_events, random_selector);
 
   /* Select the Nth thread that has had an event.  */
-  ALL_NON_EXITED_THREADS (event_tp)
-    if (event_tp->ptid.matches (waiton_ptid)
-	&& event_tp->resumed
-	&& event_tp->suspend.waitstatus_pending_p)
+  for (thread_info *tp : all_non_exited_threads (waiton_ptid))
+    if (has_event (tp))
       if (random_selector-- == 0)
-	break;
+	return tp;
 
-  return event_tp;
+  gdb_assert_not_reached ("event thread not found");
 }
 
 /* Wrapper for target_wait that first checks whether threads have
@@ -3766,14 +3740,14 @@ reinstall_readline_callback_handler_cleanup (void *arg)
 static void
 clean_up_just_stopped_threads_fsms (struct execution_control_state *ecs)
 {
-  struct thread_info *thr = ecs->event_thread;
-
-  if (thr != NULL && thr->thread_fsm != NULL)
-    thread_fsm_clean_up (thr->thread_fsm, thr);
+  if (ecs->event_thread != NULL
+      && ecs->event_thread->thread_fsm != NULL)
+    thread_fsm_clean_up (ecs->event_thread->thread_fsm,
+			 ecs->event_thread);
 
   if (!non_stop)
     {
-      ALL_NON_EXITED_THREADS (thr)
+      for (thread_info *thr : all_non_exited_threads ())
         {
 	  if (thr->thread_fsm == NULL)
 	    continue;
@@ -4472,13 +4446,12 @@ stop_all_threads (void)
 	  ptid_t event_ptid;
 	  struct target_waitstatus ws;
 	  int need_wait = 0;
-	  struct thread_info *t;
 
 	  update_thread_list ();
 
 	  /* Go through all threads looking for threads that we need
 	     to tell the target to stop.  */
-	  ALL_NON_EXITED_THREADS (t)
+	  for (thread_info *t : all_non_exited_threads ())
 	    {
 	      if (t->executing)
 		{
@@ -4550,9 +4523,7 @@ stop_all_threads (void)
 	    }
 	  else
 	    {
-	      inferior *inf;
-
-	      t = find_thread_ptid (event_ptid);
+	      thread_info *t = find_thread_ptid (event_ptid);
 	      if (t == NULL)
 		t = add_thread (event_ptid);
 
@@ -4563,7 +4534,7 @@ stop_all_threads (void)
 
 	      /* This may be the first time we see the inferior report
 		 a stop.  */
-	      inf = find_inferior_ptid (event_ptid);
+	      inferior *inf = find_inferior_ptid (event_ptid);
 	      if (inf->needs_setup)
 		{
 		  switch_to_thread_no_regs (t);
@@ -4653,9 +4624,6 @@ stop_all_threads (void)
 static int
 handle_no_resumed (struct execution_control_state *ecs)
 {
-  struct inferior *inf;
-  struct thread_info *thread;
-
   if (target_can_async_p ())
     {
       struct ui *ui;
@@ -4718,7 +4686,7 @@ handle_no_resumed (struct execution_control_state *ecs)
      the synchronous command show "no unwaited-for " to the user.  */
   update_thread_list ();
 
-  ALL_NON_EXITED_THREADS (thread)
+  for (thread_info *thread : all_non_exited_threads ())
     {
       if (thread->executing
 	  || thread->suspend.waitstatus_pending_p)
@@ -4738,7 +4706,7 @@ handle_no_resumed (struct execution_control_state *ecs)
      process exited meanwhile (thus updating the thread list results
      in an empty thread list).  In this case we know we'll be getting
      a process exit event shortly.  */
-  ALL_INFERIORS (inf)
+  for (inferior *inf : all_inferiors ())
     {
       if (inf->pid == 0)
 	continue;
@@ -5394,12 +5362,10 @@ handle_inferior_event (struct execution_control_state *ecs)
 static void
 restart_threads (struct thread_info *event_thread)
 {
-  struct thread_info *tp;
-
   /* In case the instruction just stepped spawned a new thread.  */
   update_thread_list ();
 
-  ALL_NON_EXITED_THREADS (tp)
+  for (thread_info *tp : all_non_exited_threads ())
     {
       if (tp == event_thread)
 	{
@@ -7007,7 +6973,6 @@ switch_back_to_stepped_thread (struct execution_control_state *ecs)
 {
   if (!target_is_non_stop_p ())
     {
-      struct thread_info *tp;
       struct thread_info *stepping_thread;
 
       /* If any thread is blocked on some internal breakpoint, and we
@@ -7094,7 +7059,7 @@ switch_back_to_stepped_thread (struct execution_control_state *ecs)
       /* Look for the stepping/nexting thread.  */
       stepping_thread = NULL;
 
-      ALL_NON_EXITED_THREADS (tp)
+      for (thread_info *tp : all_non_exited_threads ())
         {
 	  /* Ignore threads of processes the caller is not
 	     resuming.  */
diff --git a/gdb/linux-nat.c b/gdb/linux-nat.c
index 64015e7520..786213df6e 100644
--- a/gdb/linux-nat.c
+++ b/gdb/linux-nat.c
@@ -3171,9 +3171,7 @@ linux_nat_filter_event (int lwpid, int status)
 static void
 check_zombie_leaders (void)
 {
-  struct inferior *inf;
-
-  ALL_INFERIORS (inf)
+  for (inferior *inf : all_inferiors ())
     {
       struct lwp_info *leader_lp;
 
@@ -3678,28 +3676,25 @@ kill_wait_callback (struct lwp_info *lp, void *data)
 static void
 kill_unfollowed_fork_children (struct inferior *inf)
 {
-  struct thread_info *thread;
+  for (thread_info *thread : inf->non_exited_threads ())
+    {
+      struct target_waitstatus *ws = &thread->pending_follow;
 
-  ALL_NON_EXITED_THREADS (thread)
-    if (thread->inf == inf)
-      {
-	struct target_waitstatus *ws = &thread->pending_follow;
-
-	if (ws->kind == TARGET_WAITKIND_FORKED
-	    || ws->kind == TARGET_WAITKIND_VFORKED)
-	  {
-	    ptid_t child_ptid = ws->value.related_pid;
-	    int child_pid = child_ptid.pid ();
-	    int child_lwp = child_ptid.lwp ();
-
-	    kill_one_lwp (child_lwp);
-	    kill_wait_one_lwp (child_lwp);
-
-	    /* Let the arch-specific native code know this process is
-	       gone.  */
-	    linux_target->low_forget_process (child_pid);
-	  }
-      }
+      if (ws->kind == TARGET_WAITKIND_FORKED
+	  || ws->kind == TARGET_WAITKIND_VFORKED)
+	{
+	  ptid_t child_ptid = ws->value.related_pid;
+	  int child_pid = child_ptid.pid ();
+	  int child_lwp = child_ptid.lwp ();
+
+	  kill_one_lwp (child_lwp);
+	  kill_wait_one_lwp (child_lwp);
+
+	  /* Let the arch-specific native code know this process is
+	     gone.  */
+	  linux_target->low_forget_process (child_pid);
+	}
+    }
 }
 
 void
diff --git a/gdb/linux-tdep.c b/gdb/linux-tdep.c
index 5bfd7ed92f..306ed545b6 100644
--- a/gdb/linux-tdep.c
+++ b/gdb/linux-tdep.c
@@ -1910,7 +1910,7 @@ linux_make_corefile_notes (struct gdbarch *gdbarch, bfd *obfd, int *note_size)
   struct linux_corefile_thread_data thread_args;
   struct elf_internal_linux_prpsinfo prpsinfo;
   char *note_data = NULL;
-  struct thread_info *curr_thr, *signalled_thr, *thr;
+  struct thread_info *curr_thr, *signalled_thr;
 
   if (! gdbarch_iterate_over_regset_sections_p (gdbarch))
     return NULL;
@@ -1959,12 +1959,10 @@ linux_make_corefile_notes (struct gdbarch *gdbarch, bfd *obfd, int *note_size)
   thread_args.stop_signal = signalled_thr->suspend.stop_signal;
 
   linux_corefile_thread (signalled_thr, &thread_args);
-  ALL_NON_EXITED_THREADS (thr)
+  for (thread_info *thr : current_inferior ()->non_exited_threads ())
     {
       if (thr == signalled_thr)
 	continue;
-      if (thr->ptid.pid () != inferior_ptid.pid ())
-	continue;
 
       linux_corefile_thread (thr, &thread_args);
     }
diff --git a/gdb/linux-thread-db.c b/gdb/linux-thread-db.c
index ad193d64b2..74acec2629 100644
--- a/gdb/linux-thread-db.c
+++ b/gdb/linux-thread-db.c
@@ -1587,11 +1587,10 @@ void
 thread_db_target::update_thread_list ()
 {
   struct thread_db_info *info;
-  struct inferior *inf;
 
   prune_threads ();
 
-  ALL_INFERIORS (inf)
+  for (inferior *inf : all_inferiors ())
     {
       struct thread_info *thread;
 
@@ -1671,7 +1670,6 @@ thread_db_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
 						int handle_len,
 						inferior *inf)
 {
-  struct thread_info *tp;
   thread_t handle_tid;
 
   /* Thread handle sizes must match in order to proceed.  We don't use an
@@ -1684,11 +1682,11 @@ thread_db_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
 
   handle_tid = * (const thread_t *) thread_handle;
 
-  ALL_NON_EXITED_THREADS (tp)
+  for (thread_info *tp : inf->non_exited_threads ())
     {
       thread_db_thread_info *priv = get_thread_db_thread_info (tp);
 
-      if (tp->inf == inf && priv != NULL && handle_tid == priv->tid)
+      if (priv != NULL && handle_tid == priv->tid)
         return tp;
     }
 
diff --git a/gdb/mi/mi-interp.c b/gdb/mi/mi-interp.c
index e055dce59e..9a317bc0ec 100644
--- a/gdb/mi/mi-interp.c
+++ b/gdb/mi/mi-interp.c
@@ -951,6 +951,24 @@ mi_output_running (struct thread_info *thread)
     }
 }
 
+/* Return true if there are multiple inferiors loaded.  This is used
+   for backwards compatibility -- if there's only one inferior, output
+   "all", otherwise, output each resumed thread individually.  */
+
+static bool
+multiple_inferiors_p ()
+{
+  int count = 0;
+  for (inferior *inf ATTRIBUTE_UNUSED : all_non_exited_inferiors ())
+    {
+      count++;
+      if (count > 1)
+	return true;
+    }
+
+  return false;
+}
+
 static void
 mi_on_resume_1 (struct mi_interp *mi, ptid_t ptid)
 {
@@ -968,43 +986,15 @@ mi_on_resume_1 (struct mi_interp *mi, ptid_t ptid)
 			  current_token ? current_token : "");
     }
 
-  if (ptid.pid () == -1)
+  /* Backwards compatibility.  If doing a wildcard resume and there's
+     only one inferior, output "all", otherwise, output each resumed
+     thread individually.  */
+  if ((ptid == minus_one_ptid || ptid.is_pid ())
+      && !multiple_inferiors_p ())
     fprintf_unfiltered (mi->raw_stdout, "*running,thread-id=\"all\"\n");
-  else if (ptid.is_pid ())
-    {
-      int count = 0;
-      inferior *inf;
-
-      /* Backwards compatibility.  If there's only one inferior,
-	 output "all", otherwise, output each resumed thread
-	 individually.  */
-      ALL_INFERIORS (inf)
-	if (inf->pid != 0)
-	  {
-	    count++;
-	    if (count > 1)
-	      break;
-	  }
-
-      if (count == 1)
-	fprintf_unfiltered (mi->raw_stdout, "*running,thread-id=\"all\"\n");
-      else
-	{
-	  thread_info *tp;
-	  inferior *curinf = current_inferior ();
-
-	  ALL_NON_EXITED_THREADS (tp)
-	    if (tp->inf == curinf)
-	      mi_output_running (tp);
-	}
-    }
   else
-    {
-      thread_info *ti = find_thread_ptid (ptid);
-
-      gdb_assert (ti);
-      mi_output_running (ti);
-    }
+    for (thread_info *tp : all_non_exited_threads (ptid))
+      mi_output_running (tp);
 
   if (!running_result_record_printed && mi_proceeded)
     {
diff --git a/gdb/mi/mi-main.c b/gdb/mi/mi-main.c
index 1e31040d1e..7ed73ee20a 100644
--- a/gdb/mi/mi-main.c
+++ b/gdb/mi/mi-main.c
@@ -587,8 +587,7 @@ mi_cmd_thread_list_ids (const char *command, char **argv, int argc)
   {
     ui_out_emit_tuple tuple_emitter (current_uiout, "thread-ids");
 
-    struct thread_info *tp;
-    ALL_NON_EXITED_THREADS (tp)
+    for (thread_info *tp : all_non_exited_threads ())
       {
 	if (tp->ptid == inferior_ptid)
 	  current_thread = tp->global_num;
@@ -1995,7 +1994,7 @@ mi_execute_command (const char *cmd, int from_tty)
 	  top_level_interpreter ()->interp_ui_out ()->is_mi_like_p ()
 	  /* Don't try report anything if there are no threads --
 	     the program is dead.  */
-	  && thread_count () != 0
+	  && any_thread_p ()
 	  /* If the command already reports the thread change, no need to do it
 	     again.  */
 	  && !command_notifies_uscc_observer (command.get ()))
diff --git a/gdb/nto-procfs.c b/gdb/nto-procfs.c
index ed2ef37471..742222b695 100644
--- a/gdb/nto-procfs.c
+++ b/gdb/nto-procfs.c
@@ -214,8 +214,6 @@ nto_procfs_target::open (const char *arg, int from_tty)
   nto_procfs_node = ND_LOCAL_NODE;
   nodestr = (arg != NULL) ? xstrdup (arg) : NULL;
 
-  init_thread_list ();
-
   if (nodestr)
     {
       nto_procfs_node = netmgr_strtond (nodestr, &endstr);
diff --git a/gdb/record-btrace.c b/gdb/record-btrace.c
index 8f1346e52e..4fe9f1d256 100644
--- a/gdb/record-btrace.c
+++ b/gdb/record-btrace.c
@@ -379,7 +379,6 @@ record_btrace_target_open (const char *args, int from_tty)
   /* If we fail to enable btrace for one thread, disable it for the threads for
      which it was successfully enabled.  */
   scoped_btrace_disable btrace_disable;
-  struct thread_info *tp;
 
   DEBUG ("open");
 
@@ -388,7 +387,7 @@ record_btrace_target_open (const char *args, int from_tty)
   if (!target_has_execution)
     error (_("The program is not being run."));
 
-  ALL_NON_EXITED_THREADS (tp)
+  for (thread_info *tp : all_non_exited_threads ())
     if (args == NULL || *args == 0 || number_is_in_list (args, tp->global_num))
       {
 	btrace_enable (tp, &record_btrace_conf);
@@ -406,13 +405,11 @@ record_btrace_target_open (const char *args, int from_tty)
 void
 record_btrace_target::stop_recording ()
 {
-  struct thread_info *tp;
-
   DEBUG ("stop recording");
 
   record_btrace_auto_disable ();
 
-  ALL_NON_EXITED_THREADS (tp)
+  for (thread_info *tp : all_non_exited_threads ())
     if (tp->btrace.target != NULL)
       btrace_disable (tp);
 }
@@ -437,8 +434,6 @@ record_btrace_target::disconnect (const char *args,
 void
 record_btrace_target::close ()
 {
-  struct thread_info *tp;
-
   if (record_btrace_async_inferior_event_handler != NULL)
     delete_async_event_handler (&record_btrace_async_inferior_event_handler);
 
@@ -448,7 +443,7 @@ record_btrace_target::close ()
 
   /* We should have already stopped recording.
      Tear down btrace in case we have not.  */
-  ALL_NON_EXITED_THREADS (tp)
+  for (thread_info *tp : all_non_exited_threads ())
     btrace_teardown (tp);
 }
 
@@ -1398,10 +1393,8 @@ record_btrace_target::record_method (ptid_t ptid)
 bool
 record_btrace_target::record_is_replaying (ptid_t ptid)
 {
-  struct thread_info *tp;
-
-  ALL_NON_EXITED_THREADS (tp)
-    if (tp->ptid.matches (ptid) && btrace_is_replaying (tp))
+  for (thread_info *tp : all_non_exited_threads (ptid))
+    if (btrace_is_replaying (tp))
       return true;
 
   return false;
@@ -2132,7 +2125,6 @@ record_btrace_stop_replaying_at_end (struct thread_info *tp)
 void
 record_btrace_target::resume (ptid_t ptid, int step, enum gdb_signal signal)
 {
-  struct thread_info *tp;
   enum btrace_thread_flag flag, cflag;
 
   DEBUG ("resume %s: %s%s", target_pid_to_str (ptid),
@@ -2177,20 +2169,18 @@ record_btrace_target::resume (ptid_t ptid, int step, enum gdb_signal signal)
     {
       gdb_assert (inferior_ptid.matches (ptid));
 
-      ALL_NON_EXITED_THREADS (tp)
-	if (tp->ptid.matches (ptid))
-	  {
-	    if (tp->ptid.matches (inferior_ptid))
-	      record_btrace_resume_thread (tp, flag);
-	    else
-	      record_btrace_resume_thread (tp, cflag);
-	  }
+      for (thread_info *tp : all_non_exited_threads (ptid))
+	{
+	  if (tp->ptid.matches (inferior_ptid))
+	    record_btrace_resume_thread (tp, flag);
+	  else
+	    record_btrace_resume_thread (tp, cflag);
+	}
     }
   else
     {
-      ALL_NON_EXITED_THREADS (tp)
-	if (tp->ptid.matches (ptid))
-	  record_btrace_resume_thread (tp, flag);
+      for (thread_info *tp : all_non_exited_threads (ptid))
+	record_btrace_resume_thread (tp, flag);
     }
 
   /* Async support.  */
@@ -2547,16 +2537,9 @@ record_btrace_target::wait (ptid_t ptid, struct target_waitstatus *status,
     }
 
   /* Keep a work list of moving threads.  */
-  {
-    thread_info *tp;
-
-    ALL_NON_EXITED_THREADS (tp)
-      {
-	if (tp->ptid.matches (ptid)
-	    && ((tp->btrace.flags & (BTHR_MOVE | BTHR_STOP)) != 0))
-	  moving.push_back (tp);
-      }
-  }
+  for (thread_info *tp : all_non_exited_threads (ptid))
+    if ((tp->btrace.flags & (BTHR_MOVE | BTHR_STOP)) != 0)
+      moving.push_back (tp);
 
   if (moving.empty ())
     {
@@ -2637,9 +2620,7 @@ record_btrace_target::wait (ptid_t ptid, struct target_waitstatus *status,
   /* Stop all other threads. */
   if (!target_is_non_stop_p ())
     {
-      thread_info *tp;
-
-      ALL_NON_EXITED_THREADS (tp)
+      for (thread_info *tp : all_non_exited_threads ())
 	record_btrace_cancel_resume (tp);
     }
 
@@ -2676,14 +2657,11 @@ record_btrace_target::stop (ptid_t ptid)
     }
   else
     {
-      struct thread_info *tp;
-
-      ALL_NON_EXITED_THREADS (tp)
-       if (tp->ptid.matches (ptid))
-         {
-           tp->btrace.flags &= ~BTHR_MOVE;
-           tp->btrace.flags |= BTHR_STOP;
-         }
+      for (thread_info *tp : all_non_exited_threads (ptid))
+	{
+	  tp->btrace.flags &= ~BTHR_MOVE;
+	  tp->btrace.flags |= BTHR_STOP;
+	}
     }
  }
 
@@ -2876,9 +2854,7 @@ record_btrace_target::goto_record (ULONGEST insn)
 void
 record_btrace_target::record_stop_replaying ()
 {
-  struct thread_info *tp;
-
-  ALL_NON_EXITED_THREADS (tp)
+  for (thread_info *tp : all_non_exited_threads ())
     record_btrace_stop_replaying (tp);
 }
 
diff --git a/gdb/record-full.c b/gdb/record-full.c
index 4d8988db2a..dbaa8c3d40 100644
--- a/gdb/record-full.c
+++ b/gdb/record-full.c
@@ -1201,8 +1201,6 @@ record_full_wait_1 (struct target_ops *ops,
 
 	  while (1)
 	    {
-	      struct thread_info *tp;
-
 	      ret = ops->beneath ()->wait (ptid, status, options);
 	      if (status->kind == TARGET_WAITKIND_IGNORE)
 		{
@@ -1213,7 +1211,7 @@ record_full_wait_1 (struct target_ops *ops,
 		  return ret;
 		}
 
-	      ALL_NON_EXITED_THREADS (tp)
+	      for (thread_info *tp : all_non_exited_threads ())
                 delete_single_step_breakpoints (tp);
 
 	      if (record_full_resume_step)
diff --git a/gdb/regcache.c b/gdb/regcache.c
index f3f845aad6..6ca2920227 100644
--- a/gdb/regcache.c
+++ b/gdb/regcache.c
@@ -1577,9 +1577,6 @@ cooked_read_test (struct gdbarch *gdbarch)
   mock_inferior.aspace = &mock_aspace;
   thread_info mock_thread (&mock_inferior, mock_ptid);
 
-  scoped_restore restore_thread_list
-    = make_scoped_restore (&thread_list, &mock_thread);
-
   /* Add the mock inferior to the inferior list so that look ups by
      target+ptid can find it.  */
   scoped_restore restore_inferior_list
diff --git a/gdb/remote-sim.c b/gdb/remote-sim.c
index d30b38ecb7..63e41458d7 100644
--- a/gdb/remote-sim.c
+++ b/gdb/remote-sim.c
@@ -674,9 +674,6 @@ gdbsim_target::create_inferior (const char *exec_file,
       built_argv.reset (arg_buf);
     }
 
-  if (!have_inferiors ())
-    init_thread_list ();
-
   if (sim_create_inferior (sim_data->gdbsim_desc, exec_bfd,
 			   built_argv.get (), env)
       != SIM_RC_OK)
diff --git a/gdb/remote.c b/gdb/remote.c
index 39b3823ffc..82021bf8be 100644
--- a/gdb/remote.c
+++ b/gdb/remote.c
@@ -3785,8 +3785,6 @@ remote_target::update_thread_list ()
       || remote_get_threads_with_qthreadinfo (&context)
       || remote_get_threads_with_ql (&context))
     {
-      struct thread_info *tp, *tmp;
-
       got_list = 1;
 
       if (context.items.empty ()
@@ -3803,7 +3801,7 @@ remote_target::update_thread_list ()
       /* CONTEXT now holds the current thread list on the remote
 	 target end.  Delete GDB-side threads no longer found on the
 	 target.  */
-      ALL_THREADS_SAFE (tp, tmp)
+      for (thread_info *tp : all_threads_safe ())
 	{
 	  if (!context.contains_thread (tp->ptid))
 	    {
@@ -4385,8 +4383,6 @@ void
 remote_target::process_initial_stop_replies (int from_tty)
 {
   int pending_stop_replies = stop_reply_queue_length ();
-  struct inferior *inf;
-  struct thread_info *thread;
   struct thread_info *selected = NULL;
   struct thread_info *lowest_stopped = NULL;
   struct thread_info *first = NULL;
@@ -4454,16 +4450,13 @@ remote_target::process_initial_stop_replies (int from_tty)
 
   /* "Notice" the new inferiors before anything related to
      registers/memory.  */
-  ALL_INFERIORS (inf)
+  for (inferior *inf : all_non_exited_inferiors ())
     {
-      if (inf->pid == 0)
-	continue;
-
       inf->needs_setup = 1;
 
       if (non_stop)
 	{
-	  thread = any_live_thread_of_inferior (inf);
+	  thread_info *thread = any_live_thread_of_inferior (inf);
 	  notice_new_inferior (thread, thread->state == THREAD_RUNNING,
 			       from_tty);
 	}
@@ -4478,14 +4471,11 @@ remote_target::process_initial_stop_replies (int from_tty)
 
       /* If all threads of an inferior were already stopped, we
 	 haven't setup the inferior yet.  */
-      ALL_INFERIORS (inf)
+      for (inferior *inf : all_non_exited_inferiors ())
 	{
-	  if (inf->pid == 0)
-	    continue;
-
 	  if (inf->needs_setup)
 	    {
-	      thread = any_live_thread_of_inferior (inf);
+	      thread_info *thread = any_live_thread_of_inferior (inf);
 	      switch_to_thread_no_regs (thread);
 	      setup_inferior (0);
 	    }
@@ -4495,7 +4485,7 @@ remote_target::process_initial_stop_replies (int from_tty)
   /* Now go over all threads that are stopped, and print their current
      frame.  If all-stop, then if there's a signalled thread, pick
      that as current.  */
-  ALL_NON_EXITED_THREADS (thread)
+  for (thread_info *thread : all_non_exited_threads ())
     {
       if (first == NULL)
 	first = thread;
@@ -4522,7 +4512,7 @@ remote_target::process_initial_stop_replies (int from_tty)
      others with their status pending.  */
   if (!non_stop)
     {
-      thread = selected;
+      thread_info *thread = selected;
       if (thread == NULL)
 	thread = lowest_stopped;
       if (thread == NULL)
@@ -4532,7 +4522,7 @@ remote_target::process_initial_stop_replies (int from_tty)
     }
 
   /* For "info program".  */
-  thread = inferior_thread ();
+  thread_info *thread = inferior_thread ();
   if (thread->state == THREAD_STOPPED)
     set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
 }
@@ -4731,7 +4721,7 @@ remote_target::start_remote (int from_tty, int extended_p)
 		                    "warning: couldn't determine remote "
 				    "current thread; picking first in list.\n");
 
-	      inferior_ptid = thread_list->ptid;
+	      inferior_ptid = inferior_list->thread_list->ptid;
 	    }
 	}
 
@@ -5613,9 +5603,6 @@ remote_target::open_1 (const char *name, int from_tty, int extended_p)
   /* First delete any symbols previously loaded from shared libraries.  */
   no_shared_libraries (NULL, 0);
 
-  /* Start afresh.  */
-  init_thread_list ();
-
   /* Start the remote connection.  If error() or QUIT, discard this
      target (we'd otherwise be in an inconsistent state) and then
      propogate the error on up the exception chain.  This ensures that
@@ -6113,11 +6100,8 @@ char *
 remote_target::append_pending_thread_resumptions (char *p, char *endp,
 						  ptid_t ptid)
 {
-  struct thread_info *thread;
-
-  ALL_NON_EXITED_THREADS (thread)
-    if (thread->ptid.matches (ptid)
-	&& inferior_ptid != thread->ptid
+  for (thread_info *thread : all_non_exited_threads (ptid))
+    if (inferior_ptid != thread->ptid
 	&& thread->suspend.stop_signal != GDB_SIGNAL_0)
       {
 	p = append_resumption (p, endp, thread->ptid,
@@ -6137,7 +6121,6 @@ remote_target::remote_resume_with_hc (ptid_t ptid, int step,
 				      gdb_signal siggnal)
 {
   struct remote_state *rs = get_remote_state ();
-  struct thread_info *thread;
   char *buf;
 
   rs->last_sent_signal = siggnal;
@@ -6150,7 +6133,7 @@ remote_target::remote_resume_with_hc (ptid_t ptid, int step,
   else
     set_continue_thread (ptid);
 
-  ALL_NON_EXITED_THREADS (thread)
+  for (thread_info *thread : all_non_exited_threads ())
     resume_clear_thread_private_info (thread);
 
   buf = rs->buf;
@@ -6458,8 +6441,6 @@ vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
 void
 remote_target::commit_resume ()
 {
-  struct inferior *inf;
-  struct thread_info *tp;
   int any_process_wildcard;
   int may_global_wildcard_vcont;
 
@@ -6522,7 +6503,7 @@ remote_target::commit_resume ()
   may_global_wildcard_vcont = 1;
 
   /* And assume every process is individually wildcard-able too.  */
-  ALL_NON_EXITED_INFERIORS (inf)
+  for (inferior *inf : all_non_exited_inferiors ())
     {
       remote_inferior *priv = get_remote_inferior (inf);
 
@@ -6533,7 +6514,7 @@ remote_target::commit_resume ()
      disable process and global wildcard resumes appropriately.  */
   check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
 
-  ALL_NON_EXITED_THREADS (tp)
+  for (thread_info *tp : all_non_exited_threads ())
     {
       /* If a thread of a process is not meant to be resumed, then we
 	 can't wildcard that process.  */
@@ -6562,7 +6543,7 @@ remote_target::commit_resume ()
   struct vcont_builder vcont_builder (this);
 
   /* Threads first.  */
-  ALL_NON_EXITED_THREADS (tp)
+  for (thread_info *tp : all_non_exited_threads ())
     {
       remote_thread_info *remote_thr = get_remote_thread_info (tp);
 
@@ -6591,7 +6572,7 @@ remote_target::commit_resume ()
      supposed to be resumed.  */
   any_process_wildcard = 0;
 
-  ALL_NON_EXITED_INFERIORS (inf)
+  for (inferior *inf : all_non_exited_inferiors ())
     {
       if (get_remote_inferior (inf)->may_wildcard_vcont)
 	{
@@ -6612,7 +6593,7 @@ remote_target::commit_resume ()
 	}
       else
 	{
-	  ALL_NON_EXITED_INFERIORS (inf)
+	  for (inferior *inf : all_non_exited_inferiors ())
 	    {
 	      if (get_remote_inferior (inf)->may_wildcard_vcont)
 		{
@@ -7019,13 +7000,12 @@ is_pending_fork_parent_thread (struct thread_info *thread)
 void
 remote_target::remove_new_fork_children (threads_listing_context *context)
 {
-  struct thread_info * thread;
   int pid = -1;
   struct notif_client *notif = &notif_client_stop;
 
   /* For any threads stopped at a fork event, remove the corresponding
      fork child threads from the CONTEXT list.  */
-  ALL_NON_EXITED_THREADS (thread)
+  for (thread_info *thread : all_non_exited_threads ())
     {
       struct target_waitstatus *ws = thread_pending_fork_status (thread);
 
@@ -9717,12 +9697,11 @@ void
 remote_target::kill_new_fork_children (int pid)
 {
   remote_state *rs = get_remote_state ();
-  struct thread_info *thread;
   struct notif_client *notif = &notif_client_stop;
 
   /* Kill the fork child threads of any threads in process PID
      that are stopped at a fork event.  */
-  ALL_NON_EXITED_THREADS (thread)
+  for (thread_info *thread : all_non_exited_threads ())
     {
       struct target_waitstatus *ws = &thread->pending_follow;
 
@@ -10164,15 +10143,6 @@ Remote replied unexpectedly while setting startup-with-shell: %s"),
       extended_remote_restart ();
     }
 
-  if (!have_inferiors ())
-    {
-      /* Clean up from the last time we ran, before we mark the target
-	 running again.  This will mark breakpoints uninserted, and
-	 get_offsets may insert breakpoints.  */
-      init_thread_list ();
-      init_wait_for_inferior ();
-    }
-
   /* vRun's success return is a stop reply.  */
   stop_reply = run_worked ? rs->buf : NULL;
   add_current_inferior_and_thread (stop_reply);
@@ -13781,7 +13751,6 @@ void
 remote_target::remote_btrace_maybe_reopen ()
 {
   struct remote_state *rs = get_remote_state ();
-  struct thread_info *tp;
   int btrace_target_pushed = 0;
 #if !defined (HAVE_LIBIPT)
   int warned = 0;
@@ -13789,7 +13758,7 @@ remote_target::remote_btrace_maybe_reopen ()
 
   scoped_restore_current_thread restore_thread;
 
-  ALL_NON_EXITED_THREADS (tp)
+  for (thread_info *tp : all_non_exited_threads ())
     {
       set_general_thread (tp->ptid);
 
@@ -14073,9 +14042,7 @@ remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
 					     int handle_len,
 					     inferior *inf)
 {
-  struct thread_info *tp;
-
-  ALL_NON_EXITED_THREADS (tp)
+  for (thread_info *tp : all_non_exited_threads ())
     {
       remote_thread_info *priv = get_remote_thread_info (tp);
 
diff --git a/gdb/target.c b/gdb/target.c
index 2d98954b54..27e88fbbd4 100644
--- a/gdb/target.c
+++ b/gdb/target.c
@@ -473,9 +473,8 @@ target_terminal::restore_inferior (void)
 
   {
     scoped_restore_current_inferior restore_inferior;
-    struct inferior *inf;
 
-    ALL_INFERIORS (inf)
+    for (struct inferior *inf : all_inferiors ())
       {
 	if (inf->terminal_state == target_terminal_state::is_ours_for_output)
 	  {
@@ -501,14 +500,13 @@ static void
 target_terminal_is_ours_kind (target_terminal_state desired_state)
 {
   scoped_restore_current_inferior restore_inferior;
-  struct inferior *inf;
 
   /* Must do this in two passes.  First, have all inferiors save the
      current terminal settings.  Then, after all inferiors have add a
      chance to safely save the terminal settings, restore GDB's
      terminal settings.  */
 
-  ALL_INFERIORS (inf)
+  for (inferior *inf : all_inferiors ())
     {
       if (inf->terminal_state == target_terminal_state::is_inferior)
 	{
@@ -517,7 +515,7 @@ target_terminal_is_ours_kind (target_terminal_state desired_state)
 	}
     }
 
-  ALL_INFERIORS (inf)
+  for (inferior *inf : all_inferiors ())
     {
       /* Note we don't check is_inferior here like above because we
 	 need to handle 'is_ours_for_output -> is_ours' too.  Careful
diff --git a/gdb/thread-iter.c b/gdb/thread-iter.c
new file mode 100644
index 0000000000..bfe119a61d
--- /dev/null
+++ b/gdb/thread-iter.c
@@ -0,0 +1,101 @@
+/* Thread iterators and ranges for GDB, the GNU debugger.
+
+   Copyright (C) 2018 Free Software Foundation, Inc.
+
+   This file is part of GDB.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#include "defs.h"
+#include "gdbthread.h"
+#include "inferior.h"
+
+/* See thread-iter.h.  */
+
+all_threads_iterator::all_threads_iterator (begin_t)
+{
+  /* Advance M_INF/M_THR to the first thread's position.  */
+  for (m_inf = inferior_list; m_inf != NULL; m_inf = m_inf->next)
+    if ((m_thr = m_inf->thread_list) != NULL)
+      return;
+}
+
+/* See thread-iter.h.  */
+
+void
+all_threads_iterator::advance ()
+{
+  /* The loop below is written in the natural way as-if we'd always
+     start at the beginning of the inferior list.  This fast forwards
+     the algorithm to the actual current position.  */
+  goto start;
+
+  for (; m_inf != NULL; m_inf = m_inf->next)
+    {
+      m_thr = m_inf->thread_list;
+      while (m_thr != NULL)
+	{
+	  return;
+	start:
+	  m_thr = m_thr->next;
+	}
+    }
+}
+
+/* See thread-iter.h.  */
+
+bool
+all_matching_threads_iterator::m_inf_matches ()
+{
+  return (m_filter_ptid == minus_one_ptid
+	  || m_filter_ptid.pid () == m_inf->pid);
+}
+
+/* See thread-iter.h.  */
+
+all_matching_threads_iterator::all_matching_threads_iterator
+  (ptid_t filter_ptid)
+  : m_filter_ptid (filter_ptid)
+{
+  m_thr = nullptr;
+  for (m_inf = inferior_list; m_inf != NULL; m_inf = m_inf->next)
+    if (m_inf_matches ())
+      for (m_thr = m_inf->thread_list; m_thr != NULL; m_thr = m_thr->next)
+	if (m_thr->ptid.matches (m_filter_ptid))
+	  return;
+}
+
+/* See thread-iter.h.  */
+
+void
+all_matching_threads_iterator::advance ()
+{
+  /* The loop below is written in the natural way as-if we'd always
+     start at the beginning of the inferior list.  This fast forwards
+     the algorithm to the actual current position.  */
+  goto start;
+
+  for (; m_inf != NULL; m_inf = m_inf->next)
+    if (m_inf_matches ())
+      {
+	m_thr = m_inf->thread_list;
+	while (m_thr != NULL)
+	  {
+	    if (m_thr->ptid.matches (m_filter_ptid))
+	      return;
+	  start:
+	    m_thr = m_thr->next;
+	  }
+      }
+}
diff --git a/gdb/thread-iter.h b/gdb/thread-iter.h
new file mode 100644
index 0000000000..446305f052
--- /dev/null
+++ b/gdb/thread-iter.h
@@ -0,0 +1,311 @@
+/* Thread iterators and ranges for GDB, the GNU debugger.
+   Copyright (C) 2018 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/>.  */
+
+#ifndef THREAD_ITER_H
+#define THREAD_ITER_H
+
+#include "common/filtered-iterator.h"
+#include "common/safe-iterator.h"
+
+/* A forward iterator that iterates over a given inferior's
+   threads.  */
+
+class inf_threads_iterator
+{
+public:
+  typedef inf_threads_iterator self_type;
+  typedef struct thread_info *value_type;
+  typedef struct thread_info *&reference;
+  typedef struct thread_info **pointer;
+  typedef std::forward_iterator_tag iterator_category;
+  typedef int difference_type;
+
+  /* Create an iterator pointing at HEAD.  This takes a thread pointer
+     instead of an inferior pointer to avoid circular dependencies
+     between the thread and inferior header files.  */
+  explicit inf_threads_iterator (struct thread_info *head)
+    : m_thr (head)
+  {}
+
+  /* Create a one-past-end iterator.  */
+  inf_threads_iterator ()
+    : m_thr (nullptr)
+  {}
+
+  inf_threads_iterator& operator++ ()
+  {
+    m_thr = m_thr->next;
+    return *this;
+  }
+
+  thread_info *operator* () const { return m_thr; }
+
+  bool operator!= (const inf_threads_iterator &other) const
+  { return m_thr != other.m_thr; }
+
+private:
+  /* The currently-iterated thread.  NULL if we reached the end of the
+     list.  */
+  thread_info *m_thr;
+};
+
+/* A range adapter that makes it possible to iterate over an
+   inferior's thread list with range-for.  */
+template<typename Iterator>
+struct basic_inf_threads_range
+{
+  friend struct inferior;
+private:
+  explicit basic_inf_threads_range (struct thread_info *head)
+    : m_head (head)
+  {}
+
+public:
+  Iterator begin () const { return Iterator (m_head); }
+  Iterator end () const { return Iterator (); }
+
+private:
+  thread_info *m_head;
+};
+
+/* A forward iterator that iterates over all threads of all
+   inferiors.  */
+
+class all_threads_iterator
+{
+public:
+  typedef all_threads_iterator self_type;
+  typedef struct thread_info *value_type;
+  typedef struct thread_info *&reference;
+  typedef struct thread_info **pointer;
+  typedef std::forward_iterator_tag iterator_category;
+  typedef int difference_type;
+
+  /* Tag type.  */
+  struct begin_t {};
+
+  /* Create an iterator that points to the first thread of the first
+     inferior.  */
+  explicit all_threads_iterator (begin_t);
+
+  /* Create a one-past-end iterator.  */
+  all_threads_iterator ()
+    : m_thr (nullptr)
+  {}
+
+  thread_info *operator* () const { return m_thr; }
+
+  all_threads_iterator &operator++ ()
+  {
+    advance ();
+    return *this;
+  }
+
+  bool operator== (const all_threads_iterator &other) const
+  { return m_thr == other.m_thr; }
+
+  bool operator!= (const all_threads_iterator &other) const
+  { return m_thr != other.m_thr; }
+
+private:
+  /* Advance to the next thread.  */
+  void advance ();
+
+private:
+  /* The current inferior and thread.  M_THR is NULL if we reached the
+     end of the threads list of the last inferior.  */
+  inferior *m_inf;
+  thread_info *m_thr;
+};
+
+/* Iterate over all threads that match a given PTID.  */
+
+class all_matching_threads_iterator
+{
+public:
+  typedef all_matching_threads_iterator self_type;
+  typedef struct thread_info *value_type;
+  typedef struct thread_info *&reference;
+  typedef struct thread_info **pointer;
+  typedef std::forward_iterator_tag iterator_category;
+  typedef int difference_type;
+
+  /* Creates an iterator that iterates over all threads that match
+     FILTER_PTID.  */
+  explicit all_matching_threads_iterator (ptid_t filter_ptid);
+
+  /* Create a one-past-end iterator.  */
+  all_matching_threads_iterator ()
+    : m_inf (nullptr),
+      m_thr (nullptr),
+      m_filter_ptid (minus_one_ptid)
+  {}
+
+  thread_info *operator* () const { return m_thr; }
+
+  all_matching_threads_iterator &operator++ ()
+  {
+    advance ();
+    return *this;
+  }
+
+  bool operator== (const all_matching_threads_iterator &other) const
+  { return m_thr == other.m_thr; }
+
+  bool operator!= (const all_matching_threads_iterator &other) const
+  { return m_thr != other.m_thr; }
+
+private:
+  /* Advance to next thread, skipping filtered threads.  */
+  void advance ();
+
+  /* True if M_INF matches the process identified by
+     M_FILTER_PTID.  */
+  bool m_inf_matches ();
+
+private:
+  /* The current inferior.  */
+  inferior *m_inf;
+
+  /* The current thread.  */
+  thread_info *m_thr;
+
+  /* The filter.  */
+  ptid_t m_filter_ptid;
+};
+
+/* Filter for filtered_iterator.  Filters out exited threads.  */
+
+struct non_exited_thread_filter
+{
+  bool operator() (struct thread_info *thr) const
+  {
+    return thr->state != THREAD_EXITED;
+  }
+};
+
+/* Iterate over all non-exited threads that match a given PTID.  */
+
+using all_non_exited_threads_iterator
+  = filtered_iterator<all_matching_threads_iterator, non_exited_thread_filter>;
+
+/* Iterate over all non-exited threads of an inferior.  */
+
+using inf_non_exited_threads_iterator
+  = filtered_iterator<inf_threads_iterator, non_exited_thread_filter>;
+
+/* Iterate over all threads of all inferiors, safely.  */
+
+using all_threads_safe_iterator
+  = basic_safe_iterator<all_threads_iterator>;
+
+/* Iterate over all threads of an inferior, safely.  */
+
+using safe_inf_threads_iterator
+  = basic_safe_iterator<inf_threads_iterator>;
+
+/* A range adapter that makes it possible to iterate over all threads
+   of an inferior with range-for.  */
+
+using inf_threads_range
+  = basic_inf_threads_range<inf_threads_iterator>;
+
+/* A range adapter that makes it possible to iterate over all
+   non-exited threads of an inferior with range-for.  */
+
+using inf_non_exited_threads_range
+  = basic_inf_threads_range<inf_non_exited_threads_iterator>;
+
+/* A range adapter that makes it possible to iterate over all threads
+   of an inferior with range-for, safely.  */
+
+using safe_inf_threads_range
+  = basic_inf_threads_range<safe_inf_threads_iterator>;
+
+/* A range adapter that makes it possible to iterate over all threads
+   of all inferiors with range-for.  */
+
+struct all_threads_range
+{
+  all_threads_iterator begin () const
+  { return all_threads_iterator (all_threads_iterator::begin_t {}); }
+  all_threads_iterator end () const
+  { return all_threads_iterator (); }
+};
+
+/* A range adapter that makes it possible to iterate over all threads
+   with range-for "safely".  I.e., it is safe to delete the
+   currently-iterated thread.  */
+
+struct all_threads_safe_range
+{
+  all_threads_safe_iterator begin () const
+  { return all_threads_safe_iterator (all_threads_iterator::begin_t {}); }
+  all_threads_safe_iterator end () const
+  { return all_threads_safe_iterator (); }
+};
+
+/* A range adapter that makes it possible to iterate over all threads
+   that match a PTID filter with range-for.  */
+
+struct all_matching_threads_range
+{
+public:
+  explicit all_matching_threads_range (ptid_t filter_ptid)
+    : m_filter_ptid (filter_ptid)
+  {}
+  all_matching_threads_range ()
+    : m_filter_ptid (minus_one_ptid)
+  {}
+
+  all_matching_threads_iterator begin () const
+  { return all_matching_threads_iterator (m_filter_ptid); }
+  all_matching_threads_iterator end () const
+  { return all_matching_threads_iterator (); }
+
+private:
+  /* The filter.  */
+  ptid_t m_filter_ptid;
+};
+
+/* A range adapter that makes it possible to iterate over all
+   non-exited threads of all inferiors, with range-for.
+   Threads/inferiors that do not match FILTER_PTID are filtered
+   out.  */
+
+class all_non_exited_threads_range
+{
+public:
+  explicit all_non_exited_threads_range (ptid_t filter_ptid)
+    : m_filter_ptid (filter_ptid)
+  {}
+
+  all_non_exited_threads_range ()
+    : m_filter_ptid (minus_one_ptid)
+  {}
+
+  all_non_exited_threads_iterator begin () const
+  { return all_non_exited_threads_iterator (m_filter_ptid); }
+  all_non_exited_threads_iterator end () const
+  { return all_non_exited_threads_iterator (); }
+
+private:
+  ptid_t m_filter_ptid;
+};
+
+#endif /* THREAD_ITER_H */
diff --git a/gdb/thread.c b/gdb/thread.c
index 5071fdb27f..48d605e612 100644
--- a/gdb/thread.c
+++ b/gdb/thread.c
@@ -45,12 +45,12 @@
 #include "tid-parse.h"
 #include <algorithm>
 #include "common/gdb_optional.h"
+#include "inline-frame.h"
 
 /* Definition of struct thread_info exported to gdbthread.h.  */
 
 /* Prototypes for local functions.  */
 
-struct thread_info *thread_list = NULL;
 static int highest_thread_num;
 
 /* True if any thread is, or may be executing.  We need to track this
@@ -194,6 +194,8 @@ clear_thread_inferior_resources (struct thread_info *tp)
   btrace_teardown (tp);
 
   thread_cancel_execution_command (tp);
+
+  clear_inline_frame_state (tp->ptid);
 }
 
 /* Set the TP's state as exited.  */
@@ -220,20 +222,19 @@ set_thread_exited (thread_info *tp, int silent)
 void
 init_thread_list (void)
 {
-  struct thread_info *tp, *tmp;
-
   highest_thread_num = 0;
 
-  ALL_THREADS_SAFE (tp, tmp)
+  for (thread_info *tp : all_threads_safe ())
     {
+      inferior *inf = tp->inf;
+
       if (tp->deletable ())
 	delete tp;
       else
 	set_thread_exited (tp, 1);
-    }
 
-  thread_list = NULL;
-  threads_executing = 0;
+      inf->thread_list = NULL;
+    }
 }
 
 /* Allocate a new thread of inferior INF with target id PTID and add
@@ -244,13 +245,13 @@ new_thread (struct inferior *inf, ptid_t ptid)
 {
   thread_info *tp = new thread_info (inf, ptid);
 
-  if (thread_list == NULL)
-    thread_list = tp;
+  if (inf->thread_list == NULL)
+    inf->thread_list = tp;
   else
     {
       struct thread_info *last;
 
-      for (last = thread_list; last->next != NULL; last = last->next)
+      for (last = inf->thread_list; last->next != NULL; last = last->next)
 	;
       last->next = tp;
     }
@@ -261,11 +262,10 @@ new_thread (struct inferior *inf, ptid_t ptid)
 struct thread_info *
 add_thread_silent (ptid_t ptid)
 {
-  struct thread_info *tp;
   struct inferior *inf = find_inferior_ptid (ptid);
   gdb_assert (inf != NULL);
 
-  tp = find_thread_ptid (ptid);
+  thread_info *tp = find_thread_ptid (inf, ptid);
   if (tp)
     /* Found an old thread with the same id.  It has to be dead,
        otherwise we wouldn't be adding a new thread with the same id.
@@ -352,6 +352,16 @@ thread_info::~thread_info ()
   xfree (this->name);
 }
 
+/* See gdbthread.h.  */
+
+bool
+thread_info::deletable () const
+{
+  /* If this is the current thread, or there's code out there that
+     relies on it existing (refcount > 0) we can't delete yet.  */
+  return refcount () == 0 && ptid != inferior_ptid;
+}
+
 /* Add TP to the end of the step-over chain LIST_P.  */
 
 static void
@@ -442,7 +452,7 @@ delete_thread_1 (thread_info *thr, bool silent)
 
   tpprev = NULL;
 
-  for (tp = thread_list; tp; tpprev = tp, tp = tp->next)
+  for (tp = thr->inf->thread_list; tp; tpprev = tp, tp = tp->next)
     if (tp == thr)
       break;
 
@@ -460,7 +470,7 @@ delete_thread_1 (thread_info *thr, bool silent)
   if (tpprev)
     tpprev->next = tp->next;
   else
-    thread_list = tp->next;
+    tp->inf->thread_list = tp->next;
 
   delete tp;
 }
@@ -485,9 +495,7 @@ delete_thread_silent (thread_info *thread)
 struct thread_info *
 find_thread_global_id (int global_id)
 {
-  struct thread_info *tp;
-
-  for (tp = thread_list; tp; tp = tp->next)
+  for (thread_info *tp : all_threads ())
     if (tp->global_num == global_id)
       return tp;
 
@@ -497,10 +505,8 @@ find_thread_global_id (int global_id)
 static struct thread_info *
 find_thread_id (struct inferior *inf, int thr_num)
 {
-  struct thread_info *tp;
-
-  for (tp = thread_list; tp; tp = tp->next)
-    if (tp->inf == inf && tp->per_inf_num == thr_num)
+  for (thread_info *tp : inf->threads ())
+    if (tp->per_inf_num == thr_num)
       return tp;
 
   return NULL;
@@ -511,9 +517,18 @@ find_thread_id (struct inferior *inf, int thr_num)
 struct thread_info *
 find_thread_ptid (ptid_t ptid)
 {
-  struct thread_info *tp;
+  inferior *inf = find_inferior_ptid (ptid);
+  if (inf == NULL)
+    return NULL;
+  return find_thread_ptid (inf, ptid);
+}
 
-  for (tp = thread_list; tp; tp = tp->next)
+/* See gdbthread.h.  */
+
+struct thread_info *
+find_thread_ptid (inferior *inf, ptid_t ptid)
+{
+  for (thread_info *tp : inf->threads ())
     if (tp->ptid == ptid)
       return tp;
 
@@ -549,28 +564,28 @@ struct thread_info *
 iterate_over_threads (int (*callback) (struct thread_info *, void *),
 		      void *data)
 {
-  struct thread_info *tp, *next;
-
-  for (tp = thread_list; tp; tp = next)
-    {
-      next = tp->next;
-      if ((*callback) (tp, data))
-	return tp;
-    }
+  for (thread_info *tp : all_threads_safe ())
+    if ((*callback) (tp, data))
+      return tp;
 
   return NULL;
 }
 
+/* See gdbthread.h.  */
+
+bool
+any_thread_p ()
+{
+  for (thread_info *tp ATTRIBUTE_UNUSED : all_threads ())
+    return true;
+  return false;
+}
+
 int
 thread_count (void)
 {
-  int result = 0;
-  struct thread_info *tp;
-
-  for (tp = thread_list; tp; tp = tp->next)
-    ++result;
-
-  return result;
+  auto rng = all_threads ();
+  return std::distance (rng.begin (), rng.end ());
 }
 
 /* Return the number of non-exited threads in the thread list.  */
@@ -578,21 +593,14 @@ thread_count (void)
 static int
 live_threads_count (void)
 {
-  int result = 0;
-  struct thread_info *tp;
-
-  ALL_NON_EXITED_THREADS (tp)
-    ++result;
-
-  return result;
+  auto rng = all_non_exited_threads ();
+  return std::distance (rng.begin (), rng.end ());
 }
 
 int
 valid_global_thread_id (int global_id)
 {
-  struct thread_info *tp;
-
-  for (tp = thread_list; tp; tp = tp->next)
+  for (thread_info *tp : all_threads ())
     if (tp->global_num == global_id)
       return 1;
 
@@ -602,13 +610,7 @@ valid_global_thread_id (int global_id)
 int
 in_thread_list (ptid_t ptid)
 {
-  struct thread_info *tp;
-
-  for (tp = thread_list; tp; tp = tp->next)
-    if (tp->ptid == ptid)
-      return 1;
-
-  return 0;			/* Never heard of 'im.  */
+  return find_thread_ptid (ptid) != nullptr;
 }
 
 /* Finds the first thread of the inferior.  */
@@ -616,30 +618,20 @@ in_thread_list (ptid_t ptid)
 thread_info *
 first_thread_of_inferior (inferior *inf)
 {
-  struct thread_info *tp, *ret = NULL;
-
-  for (tp = thread_list; tp; tp = tp->next)
-    if (tp->inf == inf)
-      if (ret == NULL || tp->global_num < ret->global_num)
-	ret = tp;
-
-  return ret;
+  return inf->thread_list;
 }
 
 thread_info *
 any_thread_of_inferior (inferior *inf)
 {
-  struct thread_info *tp;
-
   gdb_assert (inf->pid != 0);
 
   /* Prefer the current thread.  */
   if (inf == current_inferior ())
     return inferior_thread ();
 
-  ALL_NON_EXITED_THREADS (tp)
-    if (tp->inf == inf)
-      return tp;
+  for (thread_info *tp : inf->non_exited_threads ())
+    return tp;
 
   return NULL;
 }
@@ -648,7 +640,6 @@ thread_info *
 any_live_thread_of_inferior (inferior *inf)
 {
   struct thread_info *curr_tp = NULL;
-  struct thread_info *tp;
   struct thread_info *tp_executing = NULL;
 
   gdb_assert (inf != NULL && inf->pid != 0);
@@ -666,14 +657,13 @@ any_live_thread_of_inferior (inferior *inf)
 	return curr_tp;
     }
 
-  ALL_NON_EXITED_THREADS (tp)
-    if (tp->inf == inf)
-      {
-	if (!tp->executing)
-	  return tp;
+  for (thread_info *tp : inf->non_exited_threads ())
+    {
+      if (!tp->executing)
+	return tp;
 
-	tp_executing = tp;
-      }
+      tp_executing = tp;
+    }
 
   /* If both the current thread and all live threads are executing,
      prefer the current thread.  */
@@ -700,13 +690,9 @@ thread_alive (struct thread_info *tp)
 void
 prune_threads (void)
 {
-  struct thread_info *tp, *tmp;
-
-  ALL_THREADS_SAFE (tp, tmp)
-    {
-      if (!thread_alive (tp))
-	delete_thread (tp);
-    }
+  for (thread_info *tp : all_threads_safe ())
+    if (!thread_alive (tp))
+      delete_thread (tp);
 }
 
 /* See gdbthreads.h.  */
@@ -714,13 +700,9 @@ prune_threads (void)
 void
 delete_exited_threads (void)
 {
-  struct thread_info *tp, *tmp;
-
-  ALL_THREADS_SAFE (tp, tmp)
-    {
-      if (tp->state == THREAD_EXITED)
-	delete_thread (tp);
-    }
+  for (thread_info *tp : all_threads_safe ())
+    if (tp->state == THREAD_EXITED)
+      delete_thread (tp);
 }
 
 /* Return true value if stack temporaies are enabled for the thread
@@ -785,7 +767,7 @@ thread_change_ptid (ptid_t old_ptid, ptid_t new_ptid)
   inf = find_inferior_ptid (old_ptid);
   inf->pid = new_ptid.pid ();
 
-  tp = find_thread_ptid (old_ptid);
+  tp = find_thread_ptid (inf, old_ptid);
   tp->ptid = new_ptid;
 
   gdb::observers::thread_ptid_changed.notify (old_ptid, new_ptid);
@@ -796,21 +778,8 @@ thread_change_ptid (ptid_t old_ptid, ptid_t new_ptid)
 void
 set_resumed (ptid_t ptid, int resumed)
 {
-  struct thread_info *tp;
-  int all = ptid == minus_one_ptid;
-
-  if (all || ptid.is_pid ())
-    {
-      for (tp = thread_list; tp; tp = tp->next)
-	if (all || tp->ptid.pid () == ptid.pid ())
-	  tp->resumed = resumed;
-    }
-  else
-    {
-      tp = find_thread_ptid (ptid);
-      gdb_assert (tp != NULL);
-      tp->resumed = resumed;
-    }
+  for (thread_info *tp : all_non_exited_threads (ptid))
+    tp->resumed = resumed;
 }
 
 /* Helper for set_running, that marks one thread either running or
@@ -849,74 +818,20 @@ thread_info::set_running (bool running)
 void
 set_running (ptid_t ptid, int running)
 {
-  struct thread_info *tp;
-  int all = ptid == minus_one_ptid;
-  int any_started = 0;
+  /* We try not to notify the observer if no thread has actually
+     changed the running state -- merely to reduce the number of
+     messages to the MI frontend.  A frontend is supposed to handle
+     multiple *running notifications just fine.  */
+  bool any_started = false;
 
-  /* We try not to notify the observer if no thread has actually changed
-     the running state -- merely to reduce the number of messages to
-     frontend.  Frontend is supposed to handle multiple *running just fine.  */
-  if (all || ptid.is_pid ())
-    {
-      for (tp = thread_list; tp; tp = tp->next)
-	if (all || tp->ptid.pid () == ptid.pid ())
-	  {
-	    if (tp->state == THREAD_EXITED)
-	      continue;
+  for (thread_info *tp : all_non_exited_threads (ptid))
+    if (set_running_thread (tp, running))
+      any_started = true;
 
-	    if (set_running_thread (tp, running))
-	      any_started = 1;
-	  }
-    }
-  else
-    {
-      tp = find_thread_ptid (ptid);
-      gdb_assert (tp != NULL);
-      gdb_assert (tp->state != THREAD_EXITED);
-      if (set_running_thread (tp, running))
-	any_started = 1;
-    }
   if (any_started)
     gdb::observers::target_resumed.notify (ptid);
 }
 
-static int
-is_thread_state (ptid_t ptid, enum thread_state state)
-{
-  struct thread_info *tp;
-
-  tp = find_thread_ptid (ptid);
-  gdb_assert (tp);
-  return tp->state == state;
-}
-
-int
-is_stopped (ptid_t ptid)
-{
-  return is_thread_state (ptid, THREAD_STOPPED);
-}
-
-int
-is_exited (ptid_t ptid)
-{
-  return is_thread_state (ptid, THREAD_EXITED);
-}
-
-int
-is_running (ptid_t ptid)
-{
-  return is_thread_state (ptid, THREAD_RUNNING);
-}
-
-int
-is_executing (ptid_t ptid)
-{
-  struct thread_info *tp;
-
-  tp = find_thread_ptid (ptid);
-  gdb_assert (tp);
-  return tp->executing;
-}
 
 /* Helper for set_executing.  Set's the thread's 'executing' field
    from EXECUTING, and if EXECUTING is true also clears the thread's
@@ -933,23 +848,10 @@ set_executing_thread (thread_info *thr, bool executing)
 void
 set_executing (ptid_t ptid, int executing)
 {
-  struct thread_info *tp;
-  int all = ptid == minus_one_ptid;
+  for (thread_info *tp : all_non_exited_threads (ptid))
+    set_executing_thread (tp, executing);
 
-  if (all || ptid.is_pid ())
-    {
-      for (tp = thread_list; tp; tp = tp->next)
-	if (all || tp->ptid.pid () == ptid.pid ())
-	  set_executing_thread (tp, executing);
-    }
-  else
-    {
-      tp = find_thread_ptid (ptid);
-      gdb_assert (tp);
-      set_executing_thread (tp, executing);
-    }
-
-  /* It only takes one running thread to spawn more threads.*/
+  /* It only takes one running thread to spawn more threads.  */
   if (executing)
     threads_executing = 1;
   /* Only clear the flag if the caller is telling us everything is
@@ -969,21 +871,8 @@ threads_are_executing (void)
 void
 set_stop_requested (ptid_t ptid, int stop)
 {
-  struct thread_info *tp;
-  int all = ptid == minus_one_ptid;
-
-  if (all || ptid.is_pid ())
-    {
-      for (tp = thread_list; tp; tp = tp->next)
-	if (all || tp->ptid.pid () == ptid.pid ())
-	  tp->stop_requested = stop;
-    }
-  else
-    {
-      tp = find_thread_ptid (ptid);
-      gdb_assert (tp);
-      tp->stop_requested = stop;
-    }
+  for (thread_info *tp : all_non_exited_threads (ptid))
+    tp->stop_requested = stop;
 
   /* Call the stop requested observer so other components of GDB can
      react to this request.  */
@@ -994,35 +883,11 @@ set_stop_requested (ptid_t ptid, int stop)
 void
 finish_thread_state (ptid_t ptid)
 {
-  struct thread_info *tp;
-  int all;
-  int any_started = 0;
+  bool any_started = false;
 
-  all = ptid == minus_one_ptid;
-
-  if (all || ptid.is_pid ())
-    {
-      for (tp = thread_list; tp; tp = tp->next)
-	{
-	  if (tp->state == THREAD_EXITED)
-	    continue;
-	  if (all || ptid.pid () == tp->ptid.pid ())
-	    {
-	      if (set_running_thread (tp, tp->executing))
-		any_started = 1;
-	    }
-	}
-    }
-  else
-    {
-      tp = find_thread_ptid (ptid);
-      gdb_assert (tp);
-      if (tp->state != THREAD_EXITED)
-	{
-	  if (set_running_thread (tp, tp->executing))
-	    any_started = 1;
-	}
-    }
+  for (thread_info *tp : all_non_exited_threads (ptid))
+    if (set_running_thread (tp, tp->executing))
+      any_started = true;
 
   if (any_started)
     gdb::observers::target_resumed.notify (ptid);
@@ -1148,8 +1013,6 @@ print_thread_info_1 (struct ui_out *uiout, const char *requested_threads,
 		     int global_ids, int pid,
 		     int show_global_ids)
 {
-  struct thread_info *tp;
-  struct inferior *inf;
   int default_inf_num = current_inferior ()->num;
 
   update_thread_list ();
@@ -1178,7 +1041,7 @@ print_thread_info_1 (struct ui_out *uiout, const char *requested_threads,
 	   accommodate the largest entry.  */
 	size_t target_id_col_width = 17;
 
-	ALL_THREADS (tp)
+	for (thread_info *tp : all_threads ())
 	  {
 	    if (!should_print_thread (requested_threads, default_inf_num,
 				      global_ids, pid, tp))
@@ -1220,7 +1083,8 @@ print_thread_info_1 (struct ui_out *uiout, const char *requested_threads,
     /* We'll be switching threads temporarily.  */
     scoped_restore_current_thread restore_thread;
 
-    ALL_THREADS_BY_INFERIOR (inf, tp)
+    for (inferior *inf : all_inferiors ())
+      for (thread_info *tp : inf->threads ())
       {
 	int core;
 
@@ -1667,16 +1531,9 @@ thread_apply_all_command (const char *cmd, int from_tty)
       std::vector<thread_info *> thr_list_cpy;
       thr_list_cpy.reserve (tc);
 
-      {
-	thread_info *tp;
-
-	ALL_NON_EXITED_THREADS (tp)
-	  {
-	    thr_list_cpy.push_back (tp);
-	  }
-
-	gdb_assert (thr_list_cpy.size () == tc);
-      }
+      for (thread_info *tp : all_non_exited_threads ())
+	thr_list_cpy.push_back (tp);
+      gdb_assert (thr_list_cpy.size () == tc);
 
       /* Increment the refcounts, and restore them back on scope
 	 exit.  */
@@ -1869,7 +1726,6 @@ thread_name_command (const char *arg, int from_tty)
 static void
 thread_find_command (const char *arg, int from_tty)
 {
-  struct thread_info *tp;
   const char *tmp;
   unsigned long match = 0;
 
@@ -1881,7 +1737,7 @@ thread_find_command (const char *arg, int from_tty)
     error (_("Invalid regexp (%s): %s"), tmp, arg);
 
   update_thread_list ();
-  for (tp = thread_list; tp; tp = tp->next)
+  for (thread_info *tp : all_threads ())
     {
       if (tp->name != NULL && re_exec (tp->name))
 	{
@@ -1993,10 +1849,8 @@ print_selected_thread_frame (struct ui_out *uiout,
 static void
 update_threads_executing (void)
 {
-  struct thread_info *tp;
-
   threads_executing = 0;
-  ALL_NON_EXITED_THREADS (tp)
+  for (thread_info *tp : all_non_exited_threads ())
     {
       if (tp->executing)
 	{
diff --git a/gdb/tid-parse.c b/gdb/tid-parse.c
index 8322e58523..03eb7c4646 100644
--- a/gdb/tid-parse.c
+++ b/gdb/tid-parse.c
@@ -55,7 +55,6 @@ parse_thread_id (const char *tidstr, const char **end)
 {
   const char *number = tidstr;
   const char *dot, *p1;
-  struct thread_info *tp;
   struct inferior *inf;
   int thr_num;
   int explicit_inf_id = 0;
@@ -90,12 +89,13 @@ parse_thread_id (const char *tidstr, const char **end)
   if (thr_num == 0)
     invalid_thread_id_error (number);
 
-  ALL_THREADS (tp)
-    {
-      if (tp->ptid.pid () == inf->pid
-	  && tp->per_inf_num == thr_num)
+  thread_info *tp = nullptr;
+  for (thread_info *it : inf->threads ())
+    if (it->per_inf_num == thr_num)
+      {
+	tp = it;
 	break;
-    }
+      }
 
   if (tp == NULL)
     {
diff --git a/gdb/x86-bsd-nat.c b/gdb/x86-bsd-nat.c
index 542bcd0603..47ebff46c8 100644
--- a/gdb/x86-bsd-nat.c
+++ b/gdb/x86-bsd-nat.c
@@ -67,7 +67,6 @@ x86bsd_dr_get (ptid_t ptid, int regnum)
 static void
 x86bsd_dr_set (int regnum, unsigned long value)
 {
-  struct thread_info *thread;
   struct dbreg dbregs;
 
   if (ptrace (PT_GETDBREGS, get_ptrace_pid (inferior_ptid),
@@ -81,13 +80,12 @@ x86bsd_dr_set (int regnum, unsigned long value)
 
   DBREG_DRX ((&dbregs), regnum) = value;
 
-  ALL_NON_EXITED_THREADS (thread)
-    if (thread->inf == current_inferior ())
-      {
-	if (ptrace (PT_SETDBREGS, get_ptrace_pid (thread->ptid),
-		    (PTRACE_TYPE_ARG3) &dbregs, 0) == -1)
-	  perror_with_name (_("Couldn't write debug registers"));
-      }
+  for (thread_info *thread : current_inferior ()->non_exited_threads ())
+    {
+      if (ptrace (PT_SETDBREGS, get_ptrace_pid (thread->ptid),
+		  (PTRACE_TYPE_ARG3) &dbregs, 0) == -1)
+	perror_with_name (_("Couldn't write debug registers"));
+    }
 }
 
 static void
-- 
2.14.4


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]