+/* The thread that was current before prepare_to_access_memory was
+ called. done_accessing_memory uses this to restore the previous
+ selected thread. */
+static ptid_t prev_general_thread;
+
+/* See target.h. */
+
+int
+prepare_to_access_memory (void)
+{
+ client_state &cs = get_client_state ();
+
+ /* The first thread found. */
+ struct thread_info *first = NULL;
+ /* The first stopped thread found. */
+ struct thread_info *stopped = NULL;
+ /* The current general thread, if found. */
+ struct thread_info *current = NULL;
+
+ /* Save the general thread value, since prepare_to_access_memory could change
+ it. */
+ prev_general_thread = cs.general_thread;
+
+ if (the_target->prepare_to_access_memory != NULL)
+ {
+ int res;
+
+ res = the_target->prepare_to_access_memory ();
+ if (res != 0)
+ return res;
+ }
+
+ for_each_thread (prev_general_thread.pid (), [&] (thread_info *thread)
+ {
+ if (mythread_alive (thread->id))
+ {
+ if (stopped == NULL && the_target->thread_stopped != NULL
+ && thread_stopped (thread))
+ stopped = thread;
+
+ if (first == NULL)
+ first = thread;
+
+ if (current == NULL && prev_general_thread == thread->id)
+ current = thread;
+ }
+ });
+
+ /* The thread we end up choosing. */
+ struct thread_info *thread;
+
+ /* Prefer a stopped thread. If none is found, try the current
+ thread. Otherwise, take the first thread in the process. If
+ none is found, undo the effects of
+ target->prepare_to_access_memory() and return error. */
+ if (stopped != NULL)
+ thread = stopped;
+ else if (current != NULL)
+ thread = current;
+ else if (first != NULL)
+ thread = first;
+ else
+ {
+ done_accessing_memory ();
+ return 1;
+ }
+
+ current_thread = thread;
+ cs.general_thread = ptid_of (thread);
+
+ return 0;
+}
+
+/* See target.h. */
+
+void
+done_accessing_memory (void)
+{
+ client_state &cs = get_client_state ();
+
+ if (the_target->done_accessing_memory != NULL)
+ the_target->done_accessing_memory ();
+
+ /* Restore the previous selected thread. */
+ cs.general_thread = prev_general_thread;
+ switch_to_thread (cs.general_thread);
+}
+