binutils-gdb/gdb/regcache.c
Pedro Alves 5b6d1e4fa4 Multi-target support
This commit adds multi-target support to GDB.  What this means is that
with this commit, GDB can now be connected to different targets at the
same time.  E.g., you can debug a live native process and a core dump
at the same time, connect to multiple gdbservers, etc.

Actually, the word "target" is overloaded in gdb.  We already have a
target stack, with pushes several target_ops instances on top of one
another.  We also have "info target" already, which means something
completely different to what this patch does.

So from here on, I'll be using the "target connections" term, to mean
an open process_stratum target, pushed on a target stack.  This patch
makes gdb have multiple target stacks, and multiple process_stratum
targets open simultaneously.  The user-visible changes / commands will
also use this terminology, but of course it's all open to debate.

User-interface-wise, not that much changes.  The main difference is
that each inferior may have its own target connection.

A target connection (e.g., a target extended-remote connection) may
support debugging multiple processes, just as before.

Say you're debugging against gdbserver in extended-remote mode, and
you do "add-inferior" to prepare to spawn a new process, like:

 (gdb) target extended-remote :9999
 ...
 (gdb) start
 ...
 (gdb) add-inferior
 Added inferior 2
 (gdb) inferior 2
 [Switching to inferior 2 [<null>] (<noexec>)]
 (gdb) file a.out
 ...
 (gdb) start
 ...

At this point, you have two inferiors connected to the same gdbserver.

With this commit, GDB will maintain a target stack per inferior,
instead of a global target stack.

To preserve the behavior above, by default, "add-inferior" makes the
new inferior inherit a copy of the target stack of the current
inferior.  Same across a fork - the child inherits a copy of the
target stack of the parent.  While the target stacks are copied, the
targets themselves are not.  Instead, target_ops is made a
refcounted_object, which means that target_ops instances are
refcounted, which each inferior counting for a reference.

What if you want to create an inferior and connect it to some _other_
target?  For that, this commit introduces a new "add-inferior
-no-connection" option that makes the new inferior not share the
current inferior's target.  So you could do:

 (gdb) target extended-remote :9999
 Remote debugging using :9999
 ...
 (gdb) add-inferior -no-connection
 [New inferior 2]
 Added inferior 2
 (gdb) inferior 2
 [Switching to inferior 2 [<null>] (<noexec>)]
 (gdb) info inferiors
   Num  Description       Executable
   1    process 18401     target:/home/pedro/tmp/main
 * 2    <null>
 (gdb) tar extended-remote :10000
 Remote debugging using :10000
 ...
 (gdb) info inferiors
   Num  Description       Executable
   1    process 18401     target:/home/pedro/tmp/main
 * 2    process 18450     target:/home/pedro/tmp/main
 (gdb)

A following patch will extended "info inferiors" to include a column
indicating which connection an inferior is bound to, along with a
couple other UI tweaks.

Other than that, debugging is the same as before.  Users interact with
inferiors and threads as before.  The only difference is that
inferiors may be bound to processes running in different machines.

That's pretty much all there is to it in terms of noticeable UI
changes.

On to implementation.

Since we can be connected to different systems at the same time, a
ptid_t is no longer a unique identifier.  Instead a thread can be
identified by a pair of ptid_t and 'process_stratum_target *', the
later being the instance of the process_stratum target that owns the
process/thread.  Note that process_stratum_target inherits from
target_ops, and all process_stratum targets inherit from
process_stratum_target.  In earlier patches, many places in gdb were
converted to refer to threads by thread_info pointer instead of
ptid_t, but there are still places in gdb where we start with a
pid/tid and need to find the corresponding inferior or thread_info
objects.  So you'll see in the patch many places adding a
process_stratum_target parameter to functions that used to take only a
ptid_t.

Since each inferior has its own target stack now, we can always find
the process_stratum target for an inferior.  That is done via a
inf->process_target() convenience method.

Since each inferior has its own target stack, we need to handle the
"beneath" calls when servicing target calls.  The solution I settled
with is just to make sure to switch the current inferior to the
inferior you want before making a target call.  Not relying on global
context is just not feasible in current GDB.  Fortunately, there
aren't that many places that need to do that, because generally most
code that calls target methods already has the current context
pointing to the right inferior/thread.  Note, to emphasize -- there's
no method to "switch to this target stack".  Instead, you switch the
current inferior, and that implicitly switches the target stack.

In some spots, we need to iterate over all inferiors so that we reach
all target stacks.

Native targets are still singletons.  There's always only a single
instance of such targets.

Remote targets however, we'll have one instance per remote connection.

The exec target is still a singleton.  There's only one instance.  I
did not see the point of instanciating more than one exec_target
object.

After vfork, we need to make sure to push the exec target on the new
inferior.  See exec_on_vfork.

For type safety, functions that need a {target, ptid} pair to identify
a thread, take a process_stratum_target pointer for target parameter
instead of target_ops *.  Some shared code in gdb/nat/ also need to
gain a target pointer parameter.  This poses an issue, since gdbserver
doesn't have process_stratum_target, only target_ops.  To fix this,
this commit renames gdbserver's target_ops to process_stratum_target.
I think this makes sense.  There's no concept of target stack in
gdbserver, and gdbserver's target_ops really implements a
process_stratum-like target.

The thread and inferior iterator functions also gain
process_stratum_target parameters.  These are used to be able to
iterate over threads and inferiors of a given target.  Following usual
conventions, if the target pointer is null, then we iterate over
threads and inferiors of all targets.

I tried converting "add-inferior" to the gdb::option framework, as a
preparatory patch, but that stumbled on the fact that gdb::option does
not support file options yet, for "add-inferior -exec".  I have a WIP
patchset that adds that, but it's not a trivial patch, mainly due to
need to integrate readline's filename completion, so I deferred that
to some other time.

In infrun.c/infcmd.c, the main change is that we need to poll events
out of all targets.  See do_target_wait.  Right after collecting an
event, we switch the current inferior to an inferior bound to the
target that reported the event, so that target methods can be used
while handling the event.  This makes most of the code transparent to
multi-targets.  See fetch_inferior_event.

infrun.c:stop_all_threads is interesting -- in this function we need
to stop all threads of all targets.  What the function does is send an
asynchronous stop request to all threads, and then synchronously waits
for events, with target_wait, rinse repeat, until all it finds are
stopped threads.  Now that we have multiple targets, it's not
efficient to synchronously block in target_wait waiting for events out
of one target.  Instead, we implement a mini event loop, with
interruptible_select, select'ing on one file descriptor per target.
For this to work, we need to be able to ask the target for a waitable
file descriptor.  Such file descriptors already exist, they are the
descriptors registered in the main event loop with add_file_handler,
inside the target_async implementations.  This commit adds a new
target_async_wait_fd target method that just returns the file
descriptor in question.  See wait_one / stop_all_threads in infrun.c.

The 'threads_executing' global is made a per-target variable.  Since
it is only relevant to process_stratum_target targets, this is where
it is put, instead of in target_ops.

You'll notice that remote.c includes some FIXME notes.  These refer to
the fact that the global arrays that hold data for the remote packets
supported are still globals.  For example, if we connect to two
different servers/stubs, then each might support different remote
protocol features.  They might even be different architectures, like
e.g., one ARM baremetal stub, and a x86 gdbserver, to debug a
host/controller scenario as a single program.  That isn't going to
work correctly today, because of said globals.  I'm leaving fixing
that for another pass, since it does not appear to be trivial, and I'd
rather land the base work first.  It's already useful to be able to
debug multiple instances of the same server (e.g., a distributed
cluster, where you have full control over the servers installed), so I
think as is it's already reasonable incremental progress.

Current limitations:

 - You can only resume more that one target at the same time if all
   targets support asynchronous debugging, and support non-stop mode.
   It should be possible to support mixed all-stop + non-stop
   backends, but that is left for another time.  This means that
   currently in order to do multi-target with gdbserver you need to
   issue "maint set target-non-stop on".  I would like to make that
   mode be the default, but we're not there yet.  Note that I'm
   talking about how the target backend works, only.  User-visible
   all-stop mode works just fine.

 - As explained above, connecting to different remote servers at the
   same time is likely to produce bad results if they don't support the
   exact set of RSP features.

FreeBSD updates courtesy of John Baldwin.

gdb/ChangeLog:
2020-01-10  Pedro Alves  <palves@redhat.com>
	    John Baldwin  <jhb@FreeBSD.org>

	* aarch64-linux-nat.c
	(aarch64_linux_nat_target::thread_architecture): Adjust.
	* ada-tasks.c (print_ada_task_info): Adjust find_thread_ptid call.
	(task_command_1): Likewise.
	* aix-thread.c (sync_threadlists, aix_thread_target::resume)
	(aix_thread_target::wait, aix_thread_target::fetch_registers)
	(aix_thread_target::store_registers)
	(aix_thread_target::thread_alive): Adjust.
	* amd64-fbsd-tdep.c: Include "inferior.h".
	(amd64fbsd_get_thread_local_address): Pass down target.
	* amd64-linux-nat.c (ps_get_thread_area): Use ps_prochandle
	thread's gdbarch instead of target_gdbarch.
	* break-catch-sig.c (signal_catchpoint_print_it): Adjust call to
	get_last_target_status.
	* break-catch-syscall.c (print_it_catch_syscall): Likewise.
	* breakpoint.c (breakpoints_should_be_inserted_now): Consider all
	inferiors.
	(update_inserted_breakpoint_locations): Skip if inferiors with no
	execution.
	(update_global_location_list): When handling moribund locations,
	find representative inferior for location's pspace, and use thread
	count of its process_stratum target.
	* bsd-kvm.c (bsd_kvm_target_open): Pass target down.
	* bsd-uthread.c (bsd_uthread_target::wait): Use
	as_process_stratum_target and adjust thread_change_ptid and
	add_thread calls.
	(bsd_uthread_target::update_thread_list): Use
	as_process_stratum_target and adjust find_thread_ptid,
	thread_change_ptid and add_thread calls.
	* btrace.c (maint_btrace_packet_history_cmd): Adjust
	find_thread_ptid call.
	* corelow.c (add_to_thread_list): Adjust add_thread call.
	(core_target_open): Adjust add_thread_silent and thread_count
	calls.
	(core_target::pid_to_str): Adjust find_inferior_ptid call.
	* ctf.c (ctf_target_open): Adjust add_thread_silent call.
	* event-top.c (async_disconnect): Pop targets from all inferiors.
	* exec.c (add_target_sections): Push exec target on all inferiors
	sharing the program space.
	(remove_target_sections): Remove the exec target from all
	inferiors sharing the program space.
	(exec_on_vfork): New.
	* exec.h (exec_on_vfork): Declare.
	* fbsd-nat.c (fbsd_add_threads): Add fbsd_nat_target parameter.
	Pass it down.
	(fbsd_nat_target::update_thread_list): Adjust.
	(fbsd_nat_target::resume): Adjust.
	(fbsd_handle_debug_trap): Add fbsd_nat_target parameter.  Pass it
	down.
	(fbsd_nat_target::wait, fbsd_nat_target::post_attach): Adjust.
	* fbsd-tdep.c (fbsd_corefile_thread): Adjust
	get_thread_arch_regcache call.
	* fork-child.c (gdb_startup_inferior): Pass target down to
	startup_inferior and set_executing.
	* gdbthread.h (struct process_stratum_target): Forward declare.
	(add_thread, add_thread_silent, add_thread_with_info)
	(in_thread_list): Add process_stratum_target parameter.
	(find_thread_ptid(inferior*, ptid_t)): New overload.
	(find_thread_ptid, thread_change_ptid): Add process_stratum_target
	parameter.
	(all_threads()): Delete overload.
	(all_threads, all_non_exited_threads): Add process_stratum_target
	parameter.
	(all_threads_safe): Use brace initialization.
	(thread_count): Add process_stratum_target parameter.
	(set_resumed, set_running, set_stop_requested, set_executing)
	(threads_are_executing, finish_thread_state): Add
	process_stratum_target parameter.
	(switch_to_thread): Use is_current_thread.
	* i386-fbsd-tdep.c: Include "inferior.h".
	(i386fbsd_get_thread_local_address): Pass down target.
	* i386-linux-nat.c (i386_linux_nat_target::low_resume): Adjust.
	* inf-child.c (inf_child_target::maybe_unpush_target): Remove
	have_inferiors check.
	* inf-ptrace.c (inf_ptrace_target::create_inferior)
	(inf_ptrace_target::attach): Adjust.
	* infcall.c (run_inferior_call): Adjust.
	* infcmd.c (run_command_1): Pass target to
	scoped_finish_thread_state.
	(proceed_thread_callback): Skip inferiors with no execution.
	(continue_command): Rename 'all_threads' local to avoid hiding
	'all_threads' function.  Adjust get_last_target_status call.
	(prepare_one_step): Adjust set_running call.
	(signal_command): Use user_visible_resume_target.  Compare thread
	pointers instead of inferior_ptid.
	(info_program_command): Adjust to pass down target.
	(attach_command): Mark target's 'thread_executing' flag.
	(stop_current_target_threads_ns): New, factored out from ...
	(interrupt_target_1): ... this.  Switch inferior before making
	target calls.
	* inferior-iter.h
	(struct all_inferiors_iterator, struct all_inferiors_range)
	(struct all_inferiors_safe_range)
	(struct all_non_exited_inferiors_range): Filter on
	process_stratum_target too.  Remove explicit.
	* inferior.c (inferior::inferior): Push dummy target on target
	stack.
	(find_inferior_pid, find_inferior_ptid, number_of_live_inferiors):
	Add process_stratum_target parameter, and pass it down.
	(have_live_inferiors): Adjust.
	(switch_to_inferior_and_push_target): New.
	(add_inferior_command, clone_inferior_command): Handle
	"-no-connection" parameter.  Use
	switch_to_inferior_and_push_target.
	(_initialize_inferior): Mention "-no-connection" option in
	the help of "add-inferior" and "clone-inferior" commands.
	* inferior.h: Include "process-stratum-target.h".
	(interrupt_target_1): Use bool.
	(struct inferior) <push_target, unpush_target, target_is_pushed,
	find_target_beneath, top_target, process_target, target_at,
	m_stack>: New.
	(discard_all_inferiors): Delete.
	(find_inferior_pid, find_inferior_ptid, number_of_live_inferiors)
	(all_inferiors, all_non_exited_inferiors): Add
	process_stratum_target parameter.
	* infrun.c: Include "gdb_select.h" and <unordered_map>.
	(target_last_proc_target): New global.
	(follow_fork_inferior): Push target on new inferior.  Pass target
	to add_thread_silent.  Call exec_on_vfork.  Handle target's
	reference count.
	(follow_fork): Adjust get_last_target_status call.  Also consider
	target.
	(follow_exec): Push target on new inferior.
	(struct execution_control_state) <target>: New field.
	(user_visible_resume_target): New.
	(do_target_resume): Call target_async.
	(resume_1): Set target's threads_executing flag.  Consider resume
	target.
	(commit_resume_all_targets): New.
	(proceed): Also consider resume target.  Skip threads of inferiors
	with no execution.  Commit resumtion in all targets.
	(start_remote): Pass current inferior to wait_for_inferior.
	(infrun_thread_stop_requested): Consider target as well.  Pass
	thread_info pointer to clear_inline_frame_state instead of ptid.
	(infrun_thread_thread_exit): Consider target as well.
	(random_pending_event_thread): New inferior parameter.  Use it.
	(do_target_wait): Rename to ...
	(do_target_wait_1): ... this.  Add inferior parameter, and pass it
	down.
	(threads_are_resumed_pending_p, do_target_wait): New.
	(prepare_for_detach): Adjust calls.
	(wait_for_inferior): New inferior parameter.  Handle it.  Use
	do_target_wait_1 instead of do_target_wait.
	(fetch_inferior_event): Adjust.  Switch to representative
	inferior.  Pass target down.
	(set_last_target_status): Add process_stratum_target parameter.
	Save target in global.
	(get_last_target_status): Add process_stratum_target parameter and
	handle it.
	(nullify_last_target_wait_ptid): Clear 'target_last_proc_target'.
	(context_switch): Check inferior_ptid == null_ptid before calling
	inferior_thread().
	(get_inferior_stop_soon): Pass down target.
	(wait_one): Rename to ...
	(poll_one_curr_target): ... this.
	(struct wait_one_event): New.
	(wait_one): New.
	(stop_all_threads): Adjust.
	(handle_no_resumed, handle_inferior_event): Adjust to consider the
	event's target.
	(switch_back_to_stepped_thread): Also consider target.
	(print_stop_event): Update.
	(normal_stop): Update.  Also consider the resume target.
	* infrun.h (wait_for_inferior): Remove declaration.
	(user_visible_resume_target): New declaration.
	(get_last_target_status, set_last_target_status): New
	process_stratum_target parameter.
	* inline-frame.c (clear_inline_frame_state(ptid_t)): Add
	process_stratum_target parameter, and use it.
	(clear_inline_frame_state (thread_info*)): New.
	* inline-frame.c (clear_inline_frame_state(ptid_t)): Add
	process_stratum_target parameter.
	(clear_inline_frame_state (thread_info*)): Declare.
	* linux-fork.c (delete_checkpoint_command): Pass target down to
	find_thread_ptid.
	(checkpoint_command): Adjust.
	* linux-nat.c (linux_nat_target::follow_fork): Switch to thread
	instead of just tweaking inferior_ptid.
	(linux_nat_switch_fork): Pass target down to thread_change_ptid.
	(exit_lwp): Pass target down to find_thread_ptid.
	(attach_proc_task_lwp_callback): Pass target down to
	add_thread/set_running/set_executing.
	(linux_nat_target::attach): Pass target down to
	thread_change_ptid.
	(get_detach_signal): Pass target down to find_thread_ptid.
	Consider last target status's target.
	(linux_resume_one_lwp_throw, resume_lwp)
	(linux_handle_syscall_trap, linux_handle_extended_wait, wait_lwp)
	(stop_wait_callback, save_stop_reason, linux_nat_filter_event)
	(linux_nat_wait_1, resume_stopped_resumed_lwps): Pass target down.
	(linux_nat_target::async_wait_fd): New.
	(linux_nat_stop_lwp, linux_nat_target::thread_address_space): Pass
	target down.
	* linux-nat.h (linux_nat_target::async_wait_fd): Declare.
	* linux-tdep.c (get_thread_arch_regcache): Pass target down.
	* linux-thread-db.c (struct thread_db_info::process_target): New
	field.
	(add_thread_db_info): Save target.
	(get_thread_db_info): New process_stratum_target parameter.  Also
	match target.
	(delete_thread_db_info): New process_stratum_target parameter.
	Also match target.
	(thread_from_lwp): Adjust to pass down target.
	(thread_db_notice_clone): Pass down target.
	(check_thread_db_callback): Pass down target.
	(try_thread_db_load_1): Always push the thread_db target.
	(try_thread_db_load, record_thread): Pass target down.
	(thread_db_target::detach): Pass target down.  Always unpush the
	thread_db target.
	(thread_db_target::wait, thread_db_target::mourn_inferior): Pass
	target down.  Always unpush the thread_db target.
	(find_new_threads_callback, thread_db_find_new_threads_2)
	(thread_db_target::update_thread_list): Pass target down.
	(thread_db_target::pid_to_str): Pass current inferior down.
	(thread_db_target::get_thread_local_address): Pass target down.
	(thread_db_target::resume, maintenance_check_libthread_db): Pass
	target down.
	* nto-procfs.c (nto_procfs_target::update_thread_list): Adjust.
	* procfs.c (procfs_target::procfs_init_inferior): Declare.
	(proc_set_current_signal, do_attach, procfs_target::wait): Adjust.
	(procfs_init_inferior): Rename to ...
	(procfs_target::procfs_init_inferior): ... this and adjust.
	(procfs_target::create_inferior, procfs_notice_thread)
	(procfs_do_thread_registers): Adjust.
	* ppc-fbsd-tdep.c: Include "inferior.h".
	(ppcfbsd_get_thread_local_address): Pass down target.
	* proc-service.c (ps_xfer_memory): Switch current inferior and
	program space as well.
	(get_ps_regcache): Pass target down.
	* process-stratum-target.c
	(process_stratum_target::thread_address_space)
	(process_stratum_target::thread_architecture): Pass target down.
	* process-stratum-target.h
	(process_stratum_target::threads_executing): New field.
	(as_process_stratum_target): New.
	* ravenscar-thread.c
	(ravenscar_thread_target::update_inferior_ptid): Pass target down.
	(ravenscar_thread_target::wait, ravenscar_add_thread): Pass target
	down.
	* record-btrace.c (record_btrace_target::info_record): Adjust.
	(record_btrace_target::record_method)
	(record_btrace_target::record_is_replaying)
	(record_btrace_target::fetch_registers)
	(get_thread_current_frame_id, record_btrace_target::resume)
	(record_btrace_target::wait, record_btrace_target::stop): Pass
	target down.
	* record-full.c (record_full_wait_1): Switch to event thread.
	Pass target down.
	* regcache.c (regcache::regcache)
	(get_thread_arch_aspace_regcache, get_thread_arch_regcache): Add
	process_stratum_target parameter and handle it.
	(current_thread_target): New global.
	(get_thread_regcache): Add process_stratum_target parameter and
	handle it.  Switch inferior before calling target method.
	(get_thread_regcache): Pass target down.
	(get_thread_regcache_for_ptid): Pass target down.
	(registers_changed_ptid): Add process_stratum_target parameter and
	handle it.
	(registers_changed_thread, registers_changed): Pass target down.
	(test_get_thread_arch_aspace_regcache): New.
	(current_regcache_test): Define a couple local test_target_ops
	instances and use them for testing.
	(readwrite_regcache): Pass process_stratum_target parameter.
	(cooked_read_test, cooked_write_test): Pass mock_target down.
	* regcache.h (get_thread_regcache, get_thread_arch_regcache)
	(get_thread_arch_aspace_regcache): Add process_stratum_target
	parameter.
	(regcache::target): New method.
	(regcache::regcache, regcache::get_thread_arch_aspace_regcache)
	(regcache::registers_changed_ptid): Add process_stratum_target
	parameter.
	(regcache::m_target): New field.
	(registers_changed_ptid): Add process_stratum_target parameter.
	* remote.c (remote_state::supports_vCont_probed): New field.
	(remote_target::async_wait_fd): New method.
	(remote_unpush_and_throw): Add remote_target parameter.
	(get_current_remote_target): Adjust.
	(remote_target::remote_add_inferior): Push target.
	(remote_target::remote_add_thread)
	(remote_target::remote_notice_new_inferior)
	(get_remote_thread_info): Pass target down.
	(remote_target::update_thread_list): Skip threads of inferiors
	bound to other targets.  (remote_target::close): Don't discard
	inferiors.  (remote_target::add_current_inferior_and_thread)
	(remote_target::process_initial_stop_replies)
	(remote_target::start_remote)
	(remote_target::remote_serial_quit_handler): Pass down target.
	(remote_target::remote_unpush_target): New remote_target
	parameter.  Unpush the target from all inferiors.
	(remote_target::remote_unpush_and_throw): New remote_target
	parameter.  Pass it down.
	(remote_target::open_1): Check whether the current inferior has
	execution instead of checking whether any inferior is live.  Pass
	target down.
	(remote_target::remote_detach_1): Pass down target.  Use
	remote_unpush_target.
	(extended_remote_target::attach): Pass down target.
	(remote_target::remote_vcont_probe): Set supports_vCont_probed.
	(remote_target::append_resumption): Pass down target.
	(remote_target::append_pending_thread_resumptions)
	(remote_target::remote_resume_with_hc, remote_target::resume)
	(remote_target::commit_resume): Pass down target.
	(remote_target::remote_stop_ns): Check supports_vCont_probed.
	(remote_target::interrupt_query)
	(remote_target::remove_new_fork_children)
	(remote_target::check_pending_events_prevent_wildcard_vcont)
	(remote_target::remote_parse_stop_reply)
	(remote_target::process_stop_reply): Pass down target.
	(first_remote_resumed_thread): New remote_target parameter.  Pass
	it down.
	(remote_target::wait_as): Pass down target.
	(unpush_and_perror): New remote_target parameter.  Pass it down.
	(remote_target::readchar, remote_target::remote_serial_write)
	(remote_target::getpkt_or_notif_sane_1)
	(remote_target::kill_new_fork_children, remote_target::kill): Pass
	down target.
	(remote_target::mourn_inferior): Pass down target.  Use
	remote_unpush_target.
	(remote_target::core_of_thread)
	(remote_target::remote_btrace_maybe_reopen): Pass down target.
	(remote_target::pid_to_exec_file)
	(remote_target::thread_handle_to_thread_info): Pass down target.
	(remote_target::async_wait_fd): New.
	* riscv-fbsd-tdep.c: Include "inferior.h".
	(riscv_fbsd_get_thread_local_address): Pass down target.
	* sol2-tdep.c (sol2_core_pid_to_str): Pass down target.
	* sol-thread.c (sol_thread_target::wait, ps_lgetregs, ps_lsetregs)
	(ps_lgetfpregs, ps_lsetfpregs, sol_update_thread_list_callback):
	Adjust.
	* solib-spu.c (spu_skip_standalone_loader): Pass down target.
	* solib-svr4.c (enable_break): Pass down target.
	* spu-multiarch.c (parse_spufs_run): Pass down target.
	* spu-tdep.c (spu2ppu_sniffer): Pass down target.
	* target-delegates.c: Regenerate.
	* target.c (g_target_stack): Delete.
	(current_top_target): Return the current inferior's top target.
	(target_has_execution_1): Refer to the passed-in inferior's top
	target.
	(target_supports_terminal_ours): Check whether the initial
	inferior was already created.
	(decref_target): New.
	(target_stack::push): Incref/decref the target.
	(push_target, push_target, unpush_target): Adjust.
	(target_stack::unpush): Defref target.
	(target_is_pushed): Return bool.  Adjust to refer to the current
	inferior's target stack.
	(dispose_inferior): Delete, and inline parts ...
	(target_preopen): ... here.  Only dispose of the current inferior.
	(target_detach): Hold strong target reference while detaching.
	Pass target down.
	(target_thread_name): Add assertion.
	(target_resume): Pass down target.
	(target_ops::beneath, find_target_at): Adjust to refer to the
	current inferior's target stack.
	(get_dummy_target): New.
	(target_pass_ctrlc): Pass the Ctrl-C to the first inferior that
	has a thread running.
	(initialize_targets): Rename to ...
	(_initialize_target): ... this.
	* target.h: Include "gdbsupport/refcounted-object.h".
	(struct target_ops): Inherit refcounted_object.
	(target_ops::shortname, target_ops::longname): Make const.
	(target_ops::async_wait_fd): New method.
	(decref_target): Declare.
	(struct target_ops_ref_policy): New.
	(target_ops_ref): New typedef.
	(get_dummy_target): Declare function.
	(target_is_pushed): Return bool.
	* thread-iter.c (all_matching_threads_iterator::m_inf_matches)
	(all_matching_threads_iterator::all_matching_threads_iterator):
	Handle filter target.
	* thread-iter.h (struct all_matching_threads_iterator, struct
	all_matching_threads_range, class all_non_exited_threads_range):
	Filter by target too.  Remove explicit.
	* thread.c (threads_executing): Delete.
	(inferior_thread): Pass down current inferior.
	(clear_thread_inferior_resources): Pass down thread pointer
	instead of ptid_t.
	(add_thread_silent, add_thread_with_info, add_thread): Add
	process_stratum_target parameter.  Use it for thread and inferior
	searches.
	(is_current_thread): New.
	(thread_info::deletable): Use it.
	(find_thread_ptid, thread_count, in_thread_list)
	(thread_change_ptid, set_resumed, set_running): New
	process_stratum_target parameter.  Pass it down.
	(set_executing): New process_stratum_target parameter.  Pass it
	down.  Adjust reference to 'threads_executing'.
	(threads_are_executing): New process_stratum_target parameter.
	Adjust reference to 'threads_executing'.
	(set_stop_requested, finish_thread_state): New
	process_stratum_target parameter.  Pass it down.
	(switch_to_thread): Also match inferior.
	(switch_to_thread): New process_stratum_target parameter.  Pass it
	down.
	(update_threads_executing): Reimplement.
	* top.c (quit_force): Pop targets from all inferior.
	(gdb_init): Don't call initialize_targets.
	* windows-nat.c (windows_nat_target) <get_windows_debug_event>:
	Declare.
	(windows_add_thread, windows_delete_thread): Adjust.
	(get_windows_debug_event): Rename to ...
	(windows_nat_target::get_windows_debug_event): ... this.  Adjust.
	* tracefile-tfile.c (tfile_target_open): Pass down target.
	* gdbsupport/common-gdbthread.h (struct process_stratum_target):
	Forward declare.
	(switch_to_thread): Add process_stratum_target parameter.
	* mi/mi-interp.c (mi_on_resume_1): Add process_stratum_target
	parameter.  Use it.
	(mi_on_resume): Pass target down.
	* nat/fork-inferior.c (startup_inferior): Add
	process_stratum_target parameter.  Pass it down.
	* nat/fork-inferior.h (startup_inferior): Add
	process_stratum_target parameter.
	* python/py-threadevent.c (py_get_event_thread): Pass target down.

gdb/gdbserver/ChangeLog:
2020-01-10  Pedro Alves  <palves@redhat.com>

	* fork-child.c (post_fork_inferior): Pass target down to
	startup_inferior.
	* inferiors.c (switch_to_thread): Add process_stratum_target
	parameter.
	* lynx-low.c (lynx_target_ops): Now a process_stratum_target.
	* nto-low.c (nto_target_ops): Now a process_stratum_target.
	* linux-low.c (linux_target_ops): Now a process_stratum_target.
	* remote-utils.c (prepare_resume_reply): Pass the target to
	switch_to_thread.
	* target.c (the_target): Now a process_stratum_target.
	(done_accessing_memory): Pass the target to switch_to_thread.
	(set_target_ops): Ajust to use process_stratum_target.
	* target.h (struct target_ops): Rename to ...
	(struct process_stratum_target): ... this.
	(the_target, set_target_ops): Adjust.
	(prepare_to_access_memory): Adjust comment.
	* win32-low.c (child_xfer_memory): Adjust to use
	process_stratum_target.
	(win32_target_ops): Now a process_stratum_target.
2020-01-10 20:06:08 +00:00

1879 lines
51 KiB
C

/* Cache and manage the values of registers for GDB, the GNU debugger.
Copyright (C) 1986-2020 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 "inferior.h"
#include "gdbthread.h"
#include "target.h"
#include "test-target.h"
#include "gdbarch.h"
#include "gdbcmd.h"
#include "regcache.h"
#include "reggroups.h"
#include "observable.h"
#include "regset.h"
#include <forward_list>
/*
* DATA STRUCTURE
*
* Here is the actual register cache.
*/
/* Per-architecture object describing the layout of a register cache.
Computed once when the architecture is created. */
struct gdbarch_data *regcache_descr_handle;
struct regcache_descr
{
/* The architecture this descriptor belongs to. */
struct gdbarch *gdbarch;
/* The raw register cache. Each raw (or hard) register is supplied
by the target interface. The raw cache should not contain
redundant information - if the PC is constructed from two
registers then those registers and not the PC lives in the raw
cache. */
long sizeof_raw_registers;
/* The cooked register space. Each cooked register in the range
[0..NR_RAW_REGISTERS) is direct-mapped onto the corresponding raw
register. The remaining [NR_RAW_REGISTERS
.. NR_COOKED_REGISTERS) (a.k.a. pseudo registers) are mapped onto
both raw registers and memory by the architecture methods
gdbarch_pseudo_register_read and gdbarch_pseudo_register_write. */
int nr_cooked_registers;
long sizeof_cooked_registers;
/* Offset and size (in 8 bit bytes), of each register in the
register cache. All registers (including those in the range
[NR_RAW_REGISTERS .. NR_COOKED_REGISTERS) are given an
offset. */
long *register_offset;
long *sizeof_register;
/* Cached table containing the type of each register. */
struct type **register_type;
};
static void *
init_regcache_descr (struct gdbarch *gdbarch)
{
int i;
struct regcache_descr *descr;
gdb_assert (gdbarch != NULL);
/* Create an initial, zero filled, table. */
descr = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct regcache_descr);
descr->gdbarch = gdbarch;
/* Total size of the register space. The raw registers are mapped
directly onto the raw register cache while the pseudo's are
either mapped onto raw-registers or memory. */
descr->nr_cooked_registers = gdbarch_num_cooked_regs (gdbarch);
/* Fill in a table of register types. */
descr->register_type
= GDBARCH_OBSTACK_CALLOC (gdbarch, descr->nr_cooked_registers,
struct type *);
for (i = 0; i < descr->nr_cooked_registers; i++)
descr->register_type[i] = gdbarch_register_type (gdbarch, i);
/* Construct a strictly RAW register cache. Don't allow pseudo's
into the register cache. */
/* Lay out the register cache.
NOTE: cagney/2002-05-22: Only register_type() is used when
constructing the register cache. It is assumed that the
register's raw size, virtual size and type length are all the
same. */
{
long offset = 0;
descr->sizeof_register
= GDBARCH_OBSTACK_CALLOC (gdbarch, descr->nr_cooked_registers, long);
descr->register_offset
= GDBARCH_OBSTACK_CALLOC (gdbarch, descr->nr_cooked_registers, long);
for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
{
descr->sizeof_register[i] = TYPE_LENGTH (descr->register_type[i]);
descr->register_offset[i] = offset;
offset += descr->sizeof_register[i];
}
/* Set the real size of the raw register cache buffer. */
descr->sizeof_raw_registers = offset;
for (; i < descr->nr_cooked_registers; i++)
{
descr->sizeof_register[i] = TYPE_LENGTH (descr->register_type[i]);
descr->register_offset[i] = offset;
offset += descr->sizeof_register[i];
}
/* Set the real size of the readonly register cache buffer. */
descr->sizeof_cooked_registers = offset;
}
return descr;
}
static struct regcache_descr *
regcache_descr (struct gdbarch *gdbarch)
{
return (struct regcache_descr *) gdbarch_data (gdbarch,
regcache_descr_handle);
}
/* Utility functions returning useful register attributes stored in
the regcache descr. */
struct type *
register_type (struct gdbarch *gdbarch, int regnum)
{
struct regcache_descr *descr = regcache_descr (gdbarch);
gdb_assert (regnum >= 0 && regnum < descr->nr_cooked_registers);
return descr->register_type[regnum];
}
/* Utility functions returning useful register attributes stored in
the regcache descr. */
int
register_size (struct gdbarch *gdbarch, int regnum)
{
struct regcache_descr *descr = regcache_descr (gdbarch);
int size;
gdb_assert (regnum >= 0 && regnum < gdbarch_num_cooked_regs (gdbarch));
size = descr->sizeof_register[regnum];
return size;
}
/* See gdbsupport/common-regcache.h. */
int
regcache_register_size (const struct regcache *regcache, int n)
{
return register_size (regcache->arch (), n);
}
reg_buffer::reg_buffer (gdbarch *gdbarch, bool has_pseudo)
: m_has_pseudo (has_pseudo)
{
gdb_assert (gdbarch != NULL);
m_descr = regcache_descr (gdbarch);
if (has_pseudo)
{
m_registers.reset (new gdb_byte[m_descr->sizeof_cooked_registers] ());
m_register_status.reset
(new register_status[m_descr->nr_cooked_registers] ());
}
else
{
m_registers.reset (new gdb_byte[m_descr->sizeof_raw_registers] ());
m_register_status.reset
(new register_status[gdbarch_num_regs (gdbarch)] ());
}
}
regcache::regcache (process_stratum_target *target, gdbarch *gdbarch,
const address_space *aspace_)
/* The register buffers. A read/write register cache can only hold
[0 .. gdbarch_num_regs). */
: detached_regcache (gdbarch, false), m_aspace (aspace_), m_target (target)
{
m_ptid = minus_one_ptid;
}
readonly_detached_regcache::readonly_detached_regcache (regcache &src)
: readonly_detached_regcache (src.arch (),
[&src] (int regnum, gdb_byte *buf)
{
return src.cooked_read (regnum, buf);
})
{
}
gdbarch *
reg_buffer::arch () const
{
return m_descr->gdbarch;
}
/* Return a pointer to register REGNUM's buffer cache. */
gdb_byte *
reg_buffer::register_buffer (int regnum) const
{
return m_registers.get () + m_descr->register_offset[regnum];
}
void
reg_buffer::save (register_read_ftype cooked_read)
{
struct gdbarch *gdbarch = m_descr->gdbarch;
int regnum;
/* It should have pseudo registers. */
gdb_assert (m_has_pseudo);
/* Clear the dest. */
memset (m_registers.get (), 0, m_descr->sizeof_cooked_registers);
memset (m_register_status.get (), REG_UNKNOWN, m_descr->nr_cooked_registers);
/* Copy over any registers (identified by their membership in the
save_reggroup) and mark them as valid. The full [0 .. gdbarch_num_regs +
gdbarch_num_pseudo_regs) range is checked since some architectures need
to save/restore `cooked' registers that live in memory. */
for (regnum = 0; regnum < m_descr->nr_cooked_registers; regnum++)
{
if (gdbarch_register_reggroup_p (gdbarch, regnum, save_reggroup))
{
gdb_byte *dst_buf = register_buffer (regnum);
enum register_status status = cooked_read (regnum, dst_buf);
gdb_assert (status != REG_UNKNOWN);
if (status != REG_VALID)
memset (dst_buf, 0, register_size (gdbarch, regnum));
m_register_status[regnum] = status;
}
}
}
void
regcache::restore (readonly_detached_regcache *src)
{
struct gdbarch *gdbarch = m_descr->gdbarch;
int regnum;
gdb_assert (src != NULL);
gdb_assert (src->m_has_pseudo);
gdb_assert (gdbarch == src->arch ());
/* Copy over any registers, being careful to only restore those that
were both saved and need to be restored. The full [0 .. gdbarch_num_regs
+ gdbarch_num_pseudo_regs) range is checked since some architectures need
to save/restore `cooked' registers that live in memory. */
for (regnum = 0; regnum < m_descr->nr_cooked_registers; regnum++)
{
if (gdbarch_register_reggroup_p (gdbarch, regnum, restore_reggroup))
{
if (src->m_register_status[regnum] == REG_VALID)
cooked_write (regnum, src->register_buffer (regnum));
}
}
}
/* See gdbsupport/common-regcache.h. */
enum register_status
reg_buffer::get_register_status (int regnum) const
{
assert_regnum (regnum);
return m_register_status[regnum];
}
void
reg_buffer::invalidate (int regnum)
{
assert_regnum (regnum);
m_register_status[regnum] = REG_UNKNOWN;
}
void
reg_buffer::assert_regnum (int regnum) const
{
gdb_assert (regnum >= 0);
if (m_has_pseudo)
gdb_assert (regnum < m_descr->nr_cooked_registers);
else
gdb_assert (regnum < gdbarch_num_regs (arch ()));
}
/* Global structure containing the current regcache. */
/* NOTE: this is a write-through cache. There is no "dirty" bit for
recording if the register values have been changed (eg. by the
user). Therefore all registers must be written back to the
target when appropriate. */
std::forward_list<regcache *> regcache::current_regcache;
struct regcache *
get_thread_arch_aspace_regcache (process_stratum_target *target,
ptid_t ptid, struct gdbarch *gdbarch,
struct address_space *aspace)
{
gdb_assert (target != nullptr);
for (const auto &regcache : regcache::current_regcache)
if (regcache->target () == target
&& regcache->ptid () == ptid
&& regcache->arch () == gdbarch)
return regcache;
regcache *new_regcache = new regcache (target, gdbarch, aspace);
regcache::current_regcache.push_front (new_regcache);
new_regcache->set_ptid (ptid);
return new_regcache;
}
struct regcache *
get_thread_arch_regcache (process_stratum_target *target, ptid_t ptid,
struct gdbarch *gdbarch)
{
scoped_restore_current_inferior restore_current_inferior;
set_current_inferior (find_inferior_ptid (target, ptid));
address_space *aspace = target_thread_address_space (ptid);
return get_thread_arch_aspace_regcache (target, ptid, gdbarch, aspace);
}
static process_stratum_target *current_thread_target;
static ptid_t current_thread_ptid;
static struct gdbarch *current_thread_arch;
struct regcache *
get_thread_regcache (process_stratum_target *target, ptid_t ptid)
{
if (!current_thread_arch
|| target != current_thread_target
|| current_thread_ptid != ptid)
{
gdb_assert (ptid != null_ptid);
current_thread_ptid = ptid;
current_thread_target = target;
scoped_restore_current_inferior restore_current_inferior;
set_current_inferior (find_inferior_ptid (target, ptid));
current_thread_arch = target_thread_architecture (ptid);
}
return get_thread_arch_regcache (target, ptid, current_thread_arch);
}
/* See regcache.h. */
struct regcache *
get_thread_regcache (thread_info *thread)
{
return get_thread_regcache (thread->inf->process_target (),
thread->ptid);
}
struct regcache *
get_current_regcache (void)
{
return get_thread_regcache (inferior_thread ());
}
/* See gdbsupport/common-regcache.h. */
struct regcache *
get_thread_regcache_for_ptid (ptid_t ptid)
{
/* This function doesn't take a process_stratum_target parameter
because it's a gdbsupport/ routine implemented by both gdb and
gdbserver. It always refers to a ptid of the current target. */
process_stratum_target *proc_target = current_inferior ()->process_target ();
return get_thread_regcache (proc_target, ptid);
}
/* Observer for the target_changed event. */
static void
regcache_observer_target_changed (struct target_ops *target)
{
registers_changed ();
}
/* Update global variables old ptids to hold NEW_PTID if they were
holding OLD_PTID. */
void
regcache::regcache_thread_ptid_changed (ptid_t old_ptid, ptid_t new_ptid)
{
for (auto &regcache : regcache::current_regcache)
{
if (regcache->ptid () == old_ptid)
regcache->set_ptid (new_ptid);
}
}
/* Low level examining and depositing of registers.
The caller is responsible for making sure that the inferior is
stopped before calling the fetching routines, or it will get
garbage. (a change from GDB version 3, in which the caller got the
value from the last stop). */
/* REGISTERS_CHANGED ()
Indicate that registers may have changed, so invalidate the cache. */
void
registers_changed_ptid (process_stratum_target *target, ptid_t ptid)
{
for (auto oit = regcache::current_regcache.before_begin (),
it = std::next (oit);
it != regcache::current_regcache.end ();
)
{
struct regcache *regcache = *it;
if ((target == nullptr || regcache->target () == target)
&& regcache->ptid ().matches (ptid))
{
delete regcache;
it = regcache::current_regcache.erase_after (oit);
}
else
oit = it++;
}
if ((target == nullptr || current_thread_target == target)
&& current_thread_ptid.matches (ptid))
{
current_thread_target = NULL;
current_thread_ptid = null_ptid;
current_thread_arch = NULL;
}
if ((target == nullptr || current_inferior ()->process_target () == target)
&& inferior_ptid.matches (ptid))
{
/* We just deleted the regcache of the current thread. Need to
forget about any frames we have cached, too. */
reinit_frame_cache ();
}
}
/* See regcache.h. */
void
registers_changed_thread (thread_info *thread)
{
registers_changed_ptid (thread->inf->process_target (), thread->ptid);
}
void
registers_changed (void)
{
registers_changed_ptid (nullptr, minus_one_ptid);
}
void
regcache::raw_update (int regnum)
{
assert_regnum (regnum);
/* Make certain that the register cache is up-to-date with respect
to the current thread. This switching shouldn't be necessary
only there is still only one target side register cache. Sigh!
On the bright side, at least there is a regcache object. */
if (get_register_status (regnum) == REG_UNKNOWN)
{
target_fetch_registers (this, regnum);
/* A number of targets can't access the whole set of raw
registers (because the debug API provides no means to get at
them). */
if (m_register_status[regnum] == REG_UNKNOWN)
m_register_status[regnum] = REG_UNAVAILABLE;
}
}
enum register_status
readable_regcache::raw_read (int regnum, gdb_byte *buf)
{
gdb_assert (buf != NULL);
raw_update (regnum);
if (m_register_status[regnum] != REG_VALID)
memset (buf, 0, m_descr->sizeof_register[regnum]);
else
memcpy (buf, register_buffer (regnum),
m_descr->sizeof_register[regnum]);
return m_register_status[regnum];
}
enum register_status
regcache_raw_read_signed (struct regcache *regcache, int regnum, LONGEST *val)
{
gdb_assert (regcache != NULL);
return regcache->raw_read (regnum, val);
}
template<typename T, typename>
enum register_status
readable_regcache::raw_read (int regnum, T *val)
{
gdb_byte *buf;
enum register_status status;
assert_regnum (regnum);
buf = (gdb_byte *) alloca (m_descr->sizeof_register[regnum]);
status = raw_read (regnum, buf);
if (status == REG_VALID)
*val = extract_integer<T> (buf,
m_descr->sizeof_register[regnum],
gdbarch_byte_order (m_descr->gdbarch));
else
*val = 0;
return status;
}
enum register_status
regcache_raw_read_unsigned (struct regcache *regcache, int regnum,
ULONGEST *val)
{
gdb_assert (regcache != NULL);
return regcache->raw_read (regnum, val);
}
void
regcache_raw_write_signed (struct regcache *regcache, int regnum, LONGEST val)
{
gdb_assert (regcache != NULL);
regcache->raw_write (regnum, val);
}
template<typename T, typename>
void
regcache::raw_write (int regnum, T val)
{
gdb_byte *buf;
assert_regnum (regnum);
buf = (gdb_byte *) alloca (m_descr->sizeof_register[regnum]);
store_integer (buf, m_descr->sizeof_register[regnum],
gdbarch_byte_order (m_descr->gdbarch), val);
raw_write (regnum, buf);
}
void
regcache_raw_write_unsigned (struct regcache *regcache, int regnum,
ULONGEST val)
{
gdb_assert (regcache != NULL);
regcache->raw_write (regnum, val);
}
LONGEST
regcache_raw_get_signed (struct regcache *regcache, int regnum)
{
LONGEST value;
enum register_status status;
status = regcache_raw_read_signed (regcache, regnum, &value);
if (status == REG_UNAVAILABLE)
throw_error (NOT_AVAILABLE_ERROR,
_("Register %d is not available"), regnum);
return value;
}
enum register_status
readable_regcache::cooked_read (int regnum, gdb_byte *buf)
{
gdb_assert (regnum >= 0);
gdb_assert (regnum < m_descr->nr_cooked_registers);
if (regnum < num_raw_registers ())
return raw_read (regnum, buf);
else if (m_has_pseudo
&& m_register_status[regnum] != REG_UNKNOWN)
{
if (m_register_status[regnum] == REG_VALID)
memcpy (buf, register_buffer (regnum),
m_descr->sizeof_register[regnum]);
else
memset (buf, 0, m_descr->sizeof_register[regnum]);
return m_register_status[regnum];
}
else if (gdbarch_pseudo_register_read_value_p (m_descr->gdbarch))
{
struct value *mark, *computed;
enum register_status result = REG_VALID;
mark = value_mark ();
computed = gdbarch_pseudo_register_read_value (m_descr->gdbarch,
this, regnum);
if (value_entirely_available (computed))
memcpy (buf, value_contents_raw (computed),
m_descr->sizeof_register[regnum]);
else
{
memset (buf, 0, m_descr->sizeof_register[regnum]);
result = REG_UNAVAILABLE;
}
value_free_to_mark (mark);
return result;
}
else
return gdbarch_pseudo_register_read (m_descr->gdbarch, this,
regnum, buf);
}
struct value *
readable_regcache::cooked_read_value (int regnum)
{
gdb_assert (regnum >= 0);
gdb_assert (regnum < m_descr->nr_cooked_registers);
if (regnum < num_raw_registers ()
|| (m_has_pseudo && m_register_status[regnum] != REG_UNKNOWN)
|| !gdbarch_pseudo_register_read_value_p (m_descr->gdbarch))
{
struct value *result;
result = allocate_value (register_type (m_descr->gdbarch, regnum));
VALUE_LVAL (result) = lval_register;
VALUE_REGNUM (result) = regnum;
/* It is more efficient in general to do this delegation in this
direction than in the other one, even though the value-based
API is preferred. */
if (cooked_read (regnum,
value_contents_raw (result)) == REG_UNAVAILABLE)
mark_value_bytes_unavailable (result, 0,
TYPE_LENGTH (value_type (result)));
return result;
}
else
return gdbarch_pseudo_register_read_value (m_descr->gdbarch,
this, regnum);
}
enum register_status
regcache_cooked_read_signed (struct regcache *regcache, int regnum,
LONGEST *val)
{
gdb_assert (regcache != NULL);
return regcache->cooked_read (regnum, val);
}
template<typename T, typename>
enum register_status
readable_regcache::cooked_read (int regnum, T *val)
{
enum register_status status;
gdb_byte *buf;
gdb_assert (regnum >= 0 && regnum < m_descr->nr_cooked_registers);
buf = (gdb_byte *) alloca (m_descr->sizeof_register[regnum]);
status = cooked_read (regnum, buf);
if (status == REG_VALID)
*val = extract_integer<T> (buf, m_descr->sizeof_register[regnum],
gdbarch_byte_order (m_descr->gdbarch));
else
*val = 0;
return status;
}
enum register_status
regcache_cooked_read_unsigned (struct regcache *regcache, int regnum,
ULONGEST *val)
{
gdb_assert (regcache != NULL);
return regcache->cooked_read (regnum, val);
}
void
regcache_cooked_write_signed (struct regcache *regcache, int regnum,
LONGEST val)
{
gdb_assert (regcache != NULL);
regcache->cooked_write (regnum, val);
}
template<typename T, typename>
void
regcache::cooked_write (int regnum, T val)
{
gdb_byte *buf;
gdb_assert (regnum >=0 && regnum < m_descr->nr_cooked_registers);
buf = (gdb_byte *) alloca (m_descr->sizeof_register[regnum]);
store_integer (buf, m_descr->sizeof_register[regnum],
gdbarch_byte_order (m_descr->gdbarch), val);
cooked_write (regnum, buf);
}
void
regcache_cooked_write_unsigned (struct regcache *regcache, int regnum,
ULONGEST val)
{
gdb_assert (regcache != NULL);
regcache->cooked_write (regnum, val);
}
void
regcache::raw_write (int regnum, const gdb_byte *buf)
{
gdb_assert (buf != NULL);
assert_regnum (regnum);
/* On the sparc, writing %g0 is a no-op, so we don't even want to
change the registers array if something writes to this register. */
if (gdbarch_cannot_store_register (arch (), regnum))
return;
/* If we have a valid copy of the register, and new value == old
value, then don't bother doing the actual store. */
if (get_register_status (regnum) == REG_VALID
&& (memcmp (register_buffer (regnum), buf,
m_descr->sizeof_register[regnum]) == 0))
return;
target_prepare_to_store (this);
raw_supply (regnum, buf);
/* Invalidate the register after it is written, in case of a
failure. */
auto invalidator
= make_scope_exit ([&] { this->invalidate (regnum); });
target_store_registers (this, regnum);
/* The target did not throw an error so we can discard invalidating
the register. */
invalidator.release ();
}
void
regcache::cooked_write (int regnum, const gdb_byte *buf)
{
gdb_assert (regnum >= 0);
gdb_assert (regnum < m_descr->nr_cooked_registers);
if (regnum < num_raw_registers ())
raw_write (regnum, buf);
else
gdbarch_pseudo_register_write (m_descr->gdbarch, this,
regnum, buf);
}
/* See regcache.h. */
enum register_status
readable_regcache::read_part (int regnum, int offset, int len,
gdb_byte *out, bool is_raw)
{
int reg_size = register_size (arch (), regnum);
gdb_assert (out != NULL);
gdb_assert (offset >= 0 && offset <= reg_size);
gdb_assert (len >= 0 && offset + len <= reg_size);
if (offset == 0 && len == 0)
{
/* Nothing to do. */
return REG_VALID;
}
if (offset == 0 && len == reg_size)
{
/* Read the full register. */
return (is_raw) ? raw_read (regnum, out) : cooked_read (regnum, out);
}
enum register_status status;
gdb_byte *reg = (gdb_byte *) alloca (reg_size);
/* Read full register to buffer. */
status = (is_raw) ? raw_read (regnum, reg) : cooked_read (regnum, reg);
if (status != REG_VALID)
return status;
/* Copy out. */
memcpy (out, reg + offset, len);
return REG_VALID;
}
/* See regcache.h. */
void
reg_buffer::raw_collect_part (int regnum, int offset, int len,
gdb_byte *out) const
{
int reg_size = register_size (arch (), regnum);
gdb_assert (out != nullptr);
gdb_assert (offset >= 0 && offset <= reg_size);
gdb_assert (len >= 0 && offset + len <= reg_size);
if (offset == 0 && len == 0)
{
/* Nothing to do. */
return;
}
if (offset == 0 && len == reg_size)
{
/* Collect the full register. */
return raw_collect (regnum, out);
}
/* Read to buffer, then write out. */
gdb_byte *reg = (gdb_byte *) alloca (reg_size);
raw_collect (regnum, reg);
memcpy (out, reg + offset, len);
}
/* See regcache.h. */
enum register_status
regcache::write_part (int regnum, int offset, int len,
const gdb_byte *in, bool is_raw)
{
int reg_size = register_size (arch (), regnum);
gdb_assert (in != NULL);
gdb_assert (offset >= 0 && offset <= reg_size);
gdb_assert (len >= 0 && offset + len <= reg_size);
if (offset == 0 && len == 0)
{
/* Nothing to do. */
return REG_VALID;
}
if (offset == 0 && len == reg_size)
{
/* Write the full register. */
(is_raw) ? raw_write (regnum, in) : cooked_write (regnum, in);
return REG_VALID;
}
enum register_status status;
gdb_byte *reg = (gdb_byte *) alloca (reg_size);
/* Read existing register to buffer. */
status = (is_raw) ? raw_read (regnum, reg) : cooked_read (regnum, reg);
if (status != REG_VALID)
return status;
/* Update buffer, then write back to regcache. */
memcpy (reg + offset, in, len);
is_raw ? raw_write (regnum, reg) : cooked_write (regnum, reg);
return REG_VALID;
}
/* See regcache.h. */
void
reg_buffer::raw_supply_part (int regnum, int offset, int len,
const gdb_byte *in)
{
int reg_size = register_size (arch (), regnum);
gdb_assert (in != nullptr);
gdb_assert (offset >= 0 && offset <= reg_size);
gdb_assert (len >= 0 && offset + len <= reg_size);
if (offset == 0 && len == 0)
{
/* Nothing to do. */
return;
}
if (offset == 0 && len == reg_size)
{
/* Supply the full register. */
return raw_supply (regnum, in);
}
gdb_byte *reg = (gdb_byte *) alloca (reg_size);
/* Read existing value to buffer. */
raw_collect (regnum, reg);
/* Write to buffer, then write out. */
memcpy (reg + offset, in, len);
raw_supply (regnum, reg);
}
enum register_status
readable_regcache::raw_read_part (int regnum, int offset, int len,
gdb_byte *buf)
{
assert_regnum (regnum);
return read_part (regnum, offset, len, buf, true);
}
/* See regcache.h. */
void
regcache::raw_write_part (int regnum, int offset, int len,
const gdb_byte *buf)
{
assert_regnum (regnum);
write_part (regnum, offset, len, buf, true);
}
/* See regcache.h. */
enum register_status
readable_regcache::cooked_read_part (int regnum, int offset, int len,
gdb_byte *buf)
{
gdb_assert (regnum >= 0 && regnum < m_descr->nr_cooked_registers);
return read_part (regnum, offset, len, buf, false);
}
/* See regcache.h. */
void
regcache::cooked_write_part (int regnum, int offset, int len,
const gdb_byte *buf)
{
gdb_assert (regnum >= 0 && regnum < m_descr->nr_cooked_registers);
write_part (regnum, offset, len, buf, false);
}
/* See gdbsupport/common-regcache.h. */
void
reg_buffer::raw_supply (int regnum, const void *buf)
{
void *regbuf;
size_t size;
assert_regnum (regnum);
regbuf = register_buffer (regnum);
size = m_descr->sizeof_register[regnum];
if (buf)
{
memcpy (regbuf, buf, size);
m_register_status[regnum] = REG_VALID;
}
else
{
/* This memset not strictly necessary, but better than garbage
in case the register value manages to escape somewhere (due
to a bug, no less). */
memset (regbuf, 0, size);
m_register_status[regnum] = REG_UNAVAILABLE;
}
}
/* See regcache.h. */
void
reg_buffer::raw_supply_integer (int regnum, const gdb_byte *addr,
int addr_len, bool is_signed)
{
enum bfd_endian byte_order = gdbarch_byte_order (m_descr->gdbarch);
gdb_byte *regbuf;
size_t regsize;
assert_regnum (regnum);
regbuf = register_buffer (regnum);
regsize = m_descr->sizeof_register[regnum];
copy_integer_to_size (regbuf, regsize, addr, addr_len, is_signed,
byte_order);
m_register_status[regnum] = REG_VALID;
}
/* See regcache.h. */
void
reg_buffer::raw_supply_zeroed (int regnum)
{
void *regbuf;
size_t size;
assert_regnum (regnum);
regbuf = register_buffer (regnum);
size = m_descr->sizeof_register[regnum];
memset (regbuf, 0, size);
m_register_status[regnum] = REG_VALID;
}
/* See gdbsupport/common-regcache.h. */
void
reg_buffer::raw_collect (int regnum, void *buf) const
{
const void *regbuf;
size_t size;
gdb_assert (buf != NULL);
assert_regnum (regnum);
regbuf = register_buffer (regnum);
size = m_descr->sizeof_register[regnum];
memcpy (buf, regbuf, size);
}
/* See regcache.h. */
void
reg_buffer::raw_collect_integer (int regnum, gdb_byte *addr, int addr_len,
bool is_signed) const
{
enum bfd_endian byte_order = gdbarch_byte_order (m_descr->gdbarch);
const gdb_byte *regbuf;
size_t regsize;
assert_regnum (regnum);
regbuf = register_buffer (regnum);
regsize = m_descr->sizeof_register[regnum];
copy_integer_to_size (addr, addr_len, regbuf, regsize, is_signed,
byte_order);
}
/* See regcache.h. */
void
regcache::transfer_regset_register (struct regcache *out_regcache, int regnum,
const gdb_byte *in_buf, gdb_byte *out_buf,
int slot_size, int offs) const
{
struct gdbarch *gdbarch = arch ();
int reg_size = std::min (register_size (gdbarch, regnum), slot_size);
/* Use part versions and reg_size to prevent possible buffer overflows when
accessing the regcache. */
if (out_buf != nullptr)
{
raw_collect_part (regnum, 0, reg_size, out_buf + offs);
/* Ensure any additional space is cleared. */
if (slot_size > reg_size)
memset (out_buf + offs + reg_size, 0, slot_size - reg_size);
}
else if (in_buf != nullptr)
out_regcache->raw_supply_part (regnum, 0, reg_size, in_buf + offs);
else
{
/* Invalidate the register. */
out_regcache->raw_supply (regnum, nullptr);
}
}
/* See regcache.h. */
void
regcache::transfer_regset (const struct regset *regset,
struct regcache *out_regcache,
int regnum, const gdb_byte *in_buf,
gdb_byte *out_buf, size_t size) const
{
const struct regcache_map_entry *map;
int offs = 0, count;
for (map = (const struct regcache_map_entry *) regset->regmap;
(count = map->count) != 0;
map++)
{
int regno = map->regno;
int slot_size = map->size;
if (slot_size == 0 && regno != REGCACHE_MAP_SKIP)
slot_size = m_descr->sizeof_register[regno];
if (regno == REGCACHE_MAP_SKIP
|| (regnum != -1
&& (regnum < regno || regnum >= regno + count)))
offs += count * slot_size;
else if (regnum == -1)
for (; count--; regno++, offs += slot_size)
{
if (offs + slot_size > size)
break;
transfer_regset_register (out_regcache, regno, in_buf, out_buf,
slot_size, offs);
}
else
{
/* Transfer a single register and return. */
offs += (regnum - regno) * slot_size;
if (offs + slot_size > size)
return;
transfer_regset_register (out_regcache, regnum, in_buf, out_buf,
slot_size, offs);
return;
}
}
}
/* Supply register REGNUM from BUF to REGCACHE, using the register map
in REGSET. If REGNUM is -1, do this for all registers in REGSET.
If BUF is NULL, set the register(s) to "unavailable" status. */
void
regcache_supply_regset (const struct regset *regset,
struct regcache *regcache,
int regnum, const void *buf, size_t size)
{
regcache->supply_regset (regset, regnum, (const gdb_byte *) buf, size);
}
void
regcache::supply_regset (const struct regset *regset,
int regnum, const void *buf, size_t size)
{
transfer_regset (regset, this, regnum, (const gdb_byte *) buf, nullptr, size);
}
/* Collect register REGNUM from REGCACHE to BUF, using the register
map in REGSET. If REGNUM is -1, do this for all registers in
REGSET. */
void
regcache_collect_regset (const struct regset *regset,
const struct regcache *regcache,
int regnum, void *buf, size_t size)
{
regcache->collect_regset (regset, regnum, (gdb_byte *) buf, size);
}
void
regcache::collect_regset (const struct regset *regset,
int regnum, void *buf, size_t size) const
{
transfer_regset (regset, nullptr, regnum, nullptr, (gdb_byte *) buf, size);
}
/* See gdbsupport/common-regcache.h. */
bool
reg_buffer::raw_compare (int regnum, const void *buf, int offset) const
{
gdb_assert (buf != NULL);
assert_regnum (regnum);
const char *regbuf = (const char *) register_buffer (regnum);
size_t size = m_descr->sizeof_register[regnum];
gdb_assert (size >= offset);
return (memcmp (buf, regbuf + offset, size - offset) == 0);
}
/* Special handling for register PC. */
CORE_ADDR
regcache_read_pc (struct regcache *regcache)
{
struct gdbarch *gdbarch = regcache->arch ();
CORE_ADDR pc_val;
if (gdbarch_read_pc_p (gdbarch))
pc_val = gdbarch_read_pc (gdbarch, regcache);
/* Else use per-frame method on get_current_frame. */
else if (gdbarch_pc_regnum (gdbarch) >= 0)
{
ULONGEST raw_val;
if (regcache_cooked_read_unsigned (regcache,
gdbarch_pc_regnum (gdbarch),
&raw_val) == REG_UNAVAILABLE)
throw_error (NOT_AVAILABLE_ERROR, _("PC register is not available"));
pc_val = gdbarch_addr_bits_remove (gdbarch, raw_val);
}
else
internal_error (__FILE__, __LINE__,
_("regcache_read_pc: Unable to find PC"));
return pc_val;
}
void
regcache_write_pc (struct regcache *regcache, CORE_ADDR pc)
{
struct gdbarch *gdbarch = regcache->arch ();
if (gdbarch_write_pc_p (gdbarch))
gdbarch_write_pc (gdbarch, regcache, pc);
else if (gdbarch_pc_regnum (gdbarch) >= 0)
regcache_cooked_write_unsigned (regcache,
gdbarch_pc_regnum (gdbarch), pc);
else
internal_error (__FILE__, __LINE__,
_("regcache_write_pc: Unable to update PC"));
/* Writing the PC (for instance, from "load") invalidates the
current frame. */
reinit_frame_cache ();
}
int
reg_buffer::num_raw_registers () const
{
return gdbarch_num_regs (arch ());
}
void
regcache::debug_print_register (const char *func, int regno)
{
struct gdbarch *gdbarch = arch ();
fprintf_unfiltered (gdb_stdlog, "%s ", func);
if (regno >= 0 && regno < gdbarch_num_regs (gdbarch)
&& gdbarch_register_name (gdbarch, regno) != NULL
&& gdbarch_register_name (gdbarch, regno)[0] != '\0')
fprintf_unfiltered (gdb_stdlog, "(%s)",
gdbarch_register_name (gdbarch, regno));
else
fprintf_unfiltered (gdb_stdlog, "(%d)", regno);
if (regno >= 0 && regno < gdbarch_num_regs (gdbarch))
{
enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
int size = register_size (gdbarch, regno);
gdb_byte *buf = register_buffer (regno);
fprintf_unfiltered (gdb_stdlog, " = ");
for (int i = 0; i < size; i++)
{
fprintf_unfiltered (gdb_stdlog, "%02x", buf[i]);
}
if (size <= sizeof (LONGEST))
{
ULONGEST val = extract_unsigned_integer (buf, size, byte_order);
fprintf_unfiltered (gdb_stdlog, " %s %s",
core_addr_to_string_nz (val), plongest (val));
}
}
fprintf_unfiltered (gdb_stdlog, "\n");
}
static void
reg_flush_command (const char *command, int from_tty)
{
/* Force-flush the register cache. */
registers_changed ();
if (from_tty)
printf_filtered (_("Register cache flushed.\n"));
}
void
register_dump::dump (ui_file *file)
{
auto descr = regcache_descr (m_gdbarch);
int regnum;
int footnote_nr = 0;
int footnote_register_offset = 0;
int footnote_register_type_name_null = 0;
long register_offset = 0;
gdb_assert (descr->nr_cooked_registers
== gdbarch_num_cooked_regs (m_gdbarch));
for (regnum = -1; regnum < descr->nr_cooked_registers; regnum++)
{
/* Name. */
if (regnum < 0)
fprintf_unfiltered (file, " %-10s", "Name");
else
{
const char *p = gdbarch_register_name (m_gdbarch, regnum);
if (p == NULL)
p = "";
else if (p[0] == '\0')
p = "''";
fprintf_unfiltered (file, " %-10s", p);
}
/* Number. */
if (regnum < 0)
fprintf_unfiltered (file, " %4s", "Nr");
else
fprintf_unfiltered (file, " %4d", regnum);
/* Relative number. */
if (regnum < 0)
fprintf_unfiltered (file, " %4s", "Rel");
else if (regnum < gdbarch_num_regs (m_gdbarch))
fprintf_unfiltered (file, " %4d", regnum);
else
fprintf_unfiltered (file, " %4d",
(regnum - gdbarch_num_regs (m_gdbarch)));
/* Offset. */
if (regnum < 0)
fprintf_unfiltered (file, " %6s ", "Offset");
else
{
fprintf_unfiltered (file, " %6ld",
descr->register_offset[regnum]);
if (register_offset != descr->register_offset[regnum]
|| (regnum > 0
&& (descr->register_offset[regnum]
!= (descr->register_offset[regnum - 1]
+ descr->sizeof_register[regnum - 1])))
)
{
if (!footnote_register_offset)
footnote_register_offset = ++footnote_nr;
fprintf_unfiltered (file, "*%d", footnote_register_offset);
}
else
fprintf_unfiltered (file, " ");
register_offset = (descr->register_offset[regnum]
+ descr->sizeof_register[regnum]);
}
/* Size. */
if (regnum < 0)
fprintf_unfiltered (file, " %5s ", "Size");
else
fprintf_unfiltered (file, " %5ld", descr->sizeof_register[regnum]);
/* Type. */
{
const char *t;
std::string name_holder;
if (regnum < 0)
t = "Type";
else
{
static const char blt[] = "builtin_type";
t = TYPE_NAME (register_type (m_gdbarch, regnum));
if (t == NULL)
{
if (!footnote_register_type_name_null)
footnote_register_type_name_null = ++footnote_nr;
name_holder = string_printf ("*%d",
footnote_register_type_name_null);
t = name_holder.c_str ();
}
/* Chop a leading builtin_type. */
if (startswith (t, blt))
t += strlen (blt);
}
fprintf_unfiltered (file, " %-15s", t);
}
/* Leading space always present. */
fprintf_unfiltered (file, " ");
dump_reg (file, regnum);
fprintf_unfiltered (file, "\n");
}
if (footnote_register_offset)
fprintf_unfiltered (file, "*%d: Inconsistent register offsets.\n",
footnote_register_offset);
if (footnote_register_type_name_null)
fprintf_unfiltered (file,
"*%d: Register type's name NULL.\n",
footnote_register_type_name_null);
}
#if GDB_SELF_TEST
#include "gdbsupport/selftest.h"
#include "selftest-arch.h"
#include "target-float.h"
namespace selftests {
class regcache_access : public regcache
{
public:
/* Return the number of elements in current_regcache. */
static size_t
current_regcache_size ()
{
return std::distance (regcache::current_regcache.begin (),
regcache::current_regcache.end ());
}
};
/* Wrapper around get_thread_arch_aspace_regcache that does some self checks. */
static void
test_get_thread_arch_aspace_regcache (process_stratum_target *target,
ptid_t ptid, struct gdbarch *gdbarch,
address_space *aspace)
{
struct regcache *regcache
= get_thread_arch_aspace_regcache (target, ptid, gdbarch, aspace);
SELF_CHECK (regcache != NULL);
SELF_CHECK (regcache->target () == target);
SELF_CHECK (regcache->ptid () == ptid);
SELF_CHECK (regcache->aspace () == aspace);
}
static void
current_regcache_test (void)
{
/* It is empty at the start. */
SELF_CHECK (regcache_access::current_regcache_size () == 0);
ptid_t ptid1 (1), ptid2 (2), ptid3 (3);
test_target_ops test_target1;
test_target_ops test_target2;
/* Get regcache from (target1,ptid1), a new regcache is added to
current_regcache. */
test_get_thread_arch_aspace_regcache (&test_target1, ptid1,
target_gdbarch (),
NULL);
SELF_CHECK (regcache_access::current_regcache_size () == 1);
/* Get regcache from (target1,ptid2), a new regcache is added to
current_regcache. */
test_get_thread_arch_aspace_regcache (&test_target1, ptid2,
target_gdbarch (),
NULL);
SELF_CHECK (regcache_access::current_regcache_size () == 2);
/* Get regcache from (target1,ptid3), a new regcache is added to
current_regcache. */
test_get_thread_arch_aspace_regcache (&test_target1, ptid3,
target_gdbarch (),
NULL);
SELF_CHECK (regcache_access::current_regcache_size () == 3);
/* Get regcache from (target1,ptid2) again, nothing is added to
current_regcache. */
test_get_thread_arch_aspace_regcache (&test_target1, ptid2,
target_gdbarch (),
NULL);
SELF_CHECK (regcache_access::current_regcache_size () == 3);
/* Get regcache from (target2,ptid2), a new regcache is added to
current_regcache, since this time we're using a differen
target. */
test_get_thread_arch_aspace_regcache (&test_target2, ptid2,
target_gdbarch (),
NULL);
SELF_CHECK (regcache_access::current_regcache_size () == 4);
/* Mark that (target1,ptid2) changed. The regcache of (target1,
ptid2) should be removed from current_regcache. */
registers_changed_ptid (&test_target1, ptid2);
SELF_CHECK (regcache_access::current_regcache_size () == 3);
/* Get the regcache from (target2,ptid2) again, confirming the
registers_changed_ptid call above did not delete it. */
test_get_thread_arch_aspace_regcache (&test_target2, ptid2,
target_gdbarch (),
NULL);
SELF_CHECK (regcache_access::current_regcache_size () == 3);
/* Confirm that marking all regcaches of all targets as changed
clears current_regcache. */
registers_changed_ptid (nullptr, minus_one_ptid);
SELF_CHECK (regcache_access::current_regcache_size () == 0);
}
class target_ops_no_register : public test_target_ops
{
public:
target_ops_no_register ()
: test_target_ops {}
{}
void reset ()
{
fetch_registers_called = 0;
store_registers_called = 0;
xfer_partial_called = 0;
}
void fetch_registers (regcache *regs, int regno) override;
void store_registers (regcache *regs, int regno) override;
enum target_xfer_status xfer_partial (enum target_object object,
const char *annex, gdb_byte *readbuf,
const gdb_byte *writebuf,
ULONGEST offset, ULONGEST len,
ULONGEST *xfered_len) override;
unsigned int fetch_registers_called = 0;
unsigned int store_registers_called = 0;
unsigned int xfer_partial_called = 0;
};
void
target_ops_no_register::fetch_registers (regcache *regs, int regno)
{
/* Mark register available. */
regs->raw_supply_zeroed (regno);
this->fetch_registers_called++;
}
void
target_ops_no_register::store_registers (regcache *regs, int regno)
{
this->store_registers_called++;
}
enum target_xfer_status
target_ops_no_register::xfer_partial (enum target_object object,
const char *annex, gdb_byte *readbuf,
const gdb_byte *writebuf,
ULONGEST offset, ULONGEST len,
ULONGEST *xfered_len)
{
this->xfer_partial_called++;
*xfered_len = len;
return TARGET_XFER_OK;
}
class readwrite_regcache : public regcache
{
public:
readwrite_regcache (process_stratum_target *target,
struct gdbarch *gdbarch)
: regcache (target, gdbarch, nullptr)
{}
};
/* Test regcache::cooked_read gets registers from raw registers and
memory instead of target to_{fetch,store}_registers. */
static void
cooked_read_test (struct gdbarch *gdbarch)
{
/* Error out if debugging something, because we're going to push the
test target, which would pop any existing target. */
if (current_top_target ()->stratum () >= process_stratum)
error (_("target already pushed"));
/* Create a mock environment. An inferior with a thread, with a
process_stratum target pushed. */
target_ops_no_register mock_target;
ptid_t mock_ptid (1, 1);
inferior mock_inferior (mock_ptid.pid ());
address_space mock_aspace {};
mock_inferior.gdbarch = gdbarch;
mock_inferior.aspace = &mock_aspace;
thread_info mock_thread (&mock_inferior, mock_ptid);
mock_inferior.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
= make_scoped_restore (&inferior_list);
inferior_list = &mock_inferior;
/* Switch to the mock inferior. */
scoped_restore_current_inferior restore_current_inferior;
set_current_inferior (&mock_inferior);
/* Push the process_stratum target so we can mock accessing
registers. */
push_target (&mock_target);
/* Pop it again on exit (return/exception). */
struct on_exit
{
~on_exit ()
{
pop_all_targets_at_and_above (process_stratum);
}
} pop_targets;
/* Switch to the mock thread. */
scoped_restore restore_inferior_ptid
= make_scoped_restore (&inferior_ptid, mock_ptid);
/* Test that read one raw register from regcache_no_target will go
to the target layer. */
/* Find a raw register which size isn't zero. */
int nonzero_regnum;
for (nonzero_regnum = 0;
nonzero_regnum < gdbarch_num_regs (gdbarch);
nonzero_regnum++)
{
if (register_size (gdbarch, nonzero_regnum) != 0)
break;
}
readwrite_regcache readwrite (&mock_target, gdbarch);
gdb::def_vector<gdb_byte> buf (register_size (gdbarch, nonzero_regnum));
readwrite.raw_read (nonzero_regnum, buf.data ());
/* raw_read calls target_fetch_registers. */
SELF_CHECK (mock_target.fetch_registers_called > 0);
mock_target.reset ();
/* Mark all raw registers valid, so the following raw registers
accesses won't go to target. */
for (auto i = 0; i < gdbarch_num_regs (gdbarch); i++)
readwrite.raw_update (i);
mock_target.reset ();
/* Then, read all raw and pseudo registers, and don't expect calling
to_{fetch,store}_registers. */
for (int regnum = 0; regnum < gdbarch_num_cooked_regs (gdbarch); regnum++)
{
if (register_size (gdbarch, regnum) == 0)
continue;
gdb::def_vector<gdb_byte> inner_buf (register_size (gdbarch, regnum));
SELF_CHECK (REG_VALID == readwrite.cooked_read (regnum,
inner_buf.data ()));
SELF_CHECK (mock_target.fetch_registers_called == 0);
SELF_CHECK (mock_target.store_registers_called == 0);
SELF_CHECK (mock_target.xfer_partial_called == 0);
mock_target.reset ();
}
readonly_detached_regcache readonly (readwrite);
/* GDB may go to target layer to fetch all registers and memory for
readonly regcache. */
mock_target.reset ();
for (int regnum = 0; regnum < gdbarch_num_cooked_regs (gdbarch); regnum++)
{
if (register_size (gdbarch, regnum) == 0)
continue;
gdb::def_vector<gdb_byte> inner_buf (register_size (gdbarch, regnum));
enum register_status status = readonly.cooked_read (regnum,
inner_buf.data ());
if (regnum < gdbarch_num_regs (gdbarch))
{
auto bfd_arch = gdbarch_bfd_arch_info (gdbarch)->arch;
if (bfd_arch == bfd_arch_frv || bfd_arch == bfd_arch_h8300
|| bfd_arch == bfd_arch_m32c || bfd_arch == bfd_arch_sh
|| bfd_arch == bfd_arch_alpha || bfd_arch == bfd_arch_v850
|| bfd_arch == bfd_arch_msp430 || bfd_arch == bfd_arch_mep
|| bfd_arch == bfd_arch_mips || bfd_arch == bfd_arch_v850_rh850
|| bfd_arch == bfd_arch_tic6x || bfd_arch == bfd_arch_mn10300
|| bfd_arch == bfd_arch_rl78 || bfd_arch == bfd_arch_score
|| bfd_arch == bfd_arch_riscv || bfd_arch == bfd_arch_csky)
{
/* Raw registers. If raw registers are not in save_reggroup,
their status are unknown. */
if (gdbarch_register_reggroup_p (gdbarch, regnum, save_reggroup))
SELF_CHECK (status == REG_VALID);
else
SELF_CHECK (status == REG_UNKNOWN);
}
else
SELF_CHECK (status == REG_VALID);
}
else
{
if (gdbarch_register_reggroup_p (gdbarch, regnum, save_reggroup))
SELF_CHECK (status == REG_VALID);
else
{
/* If pseudo registers are not in save_reggroup, some of
them can be computed from saved raw registers, but some
of them are unknown. */
auto bfd_arch = gdbarch_bfd_arch_info (gdbarch)->arch;
if (bfd_arch == bfd_arch_frv
|| bfd_arch == bfd_arch_m32c
|| bfd_arch == bfd_arch_mep
|| bfd_arch == bfd_arch_sh)
SELF_CHECK (status == REG_VALID || status == REG_UNKNOWN);
else if (bfd_arch == bfd_arch_mips
|| bfd_arch == bfd_arch_h8300)
SELF_CHECK (status == REG_UNKNOWN);
else
SELF_CHECK (status == REG_VALID);
}
}
SELF_CHECK (mock_target.fetch_registers_called == 0);
SELF_CHECK (mock_target.store_registers_called == 0);
SELF_CHECK (mock_target.xfer_partial_called == 0);
mock_target.reset ();
}
}
/* Test regcache::cooked_write by writing some expected contents to
registers, and checking that contents read from registers and the
expected contents are the same. */
static void
cooked_write_test (struct gdbarch *gdbarch)
{
/* Error out if debugging something, because we're going to push the
test target, which would pop any existing target. */
if (current_top_target ()->stratum () >= process_stratum)
error (_("target already pushed"));
/* Create a mock environment. A process_stratum target pushed. */
target_ops_no_register mock_target;
/* Push the process_stratum target so we can mock accessing
registers. */
push_target (&mock_target);
/* Pop it again on exit (return/exception). */
struct on_exit
{
~on_exit ()
{
pop_all_targets_at_and_above (process_stratum);
}
} pop_targets;
readwrite_regcache readwrite (&mock_target, gdbarch);
const int num_regs = gdbarch_num_cooked_regs (gdbarch);
for (auto regnum = 0; regnum < num_regs; regnum++)
{
if (register_size (gdbarch, regnum) == 0
|| gdbarch_cannot_store_register (gdbarch, regnum))
continue;
auto bfd_arch = gdbarch_bfd_arch_info (gdbarch)->arch;
if (bfd_arch == bfd_arch_sparc
/* SPARC64_CWP_REGNUM, SPARC64_PSTATE_REGNUM,
SPARC64_ASI_REGNUM and SPARC64_CCR_REGNUM are hard to test. */
&& gdbarch_ptr_bit (gdbarch) == 64
&& (regnum >= gdbarch_num_regs (gdbarch)
&& regnum <= gdbarch_num_regs (gdbarch) + 4))
continue;
std::vector<gdb_byte> expected (register_size (gdbarch, regnum), 0);
std::vector<gdb_byte> buf (register_size (gdbarch, regnum), 0);
const auto type = register_type (gdbarch, regnum);
if (TYPE_CODE (type) == TYPE_CODE_FLT
|| TYPE_CODE (type) == TYPE_CODE_DECFLOAT)
{
/* Generate valid float format. */
target_float_from_string (expected.data (), type, "1.25");
}
else if (TYPE_CODE (type) == TYPE_CODE_INT
|| TYPE_CODE (type) == TYPE_CODE_ARRAY
|| TYPE_CODE (type) == TYPE_CODE_PTR
|| TYPE_CODE (type) == TYPE_CODE_UNION
|| TYPE_CODE (type) == TYPE_CODE_STRUCT)
{
if (bfd_arch == bfd_arch_ia64
|| (regnum >= gdbarch_num_regs (gdbarch)
&& (bfd_arch == bfd_arch_xtensa
|| bfd_arch == bfd_arch_bfin
|| bfd_arch == bfd_arch_m32c
/* m68hc11 pseudo registers are in memory. */
|| bfd_arch == bfd_arch_m68hc11
|| bfd_arch == bfd_arch_m68hc12
|| bfd_arch == bfd_arch_s390))
|| (bfd_arch == bfd_arch_frv
/* FRV pseudo registers except iacc0. */
&& regnum > gdbarch_num_regs (gdbarch)))
{
/* Skip setting the expected values for some architecture
registers. */
}
else if (bfd_arch == bfd_arch_rl78 && regnum == 40)
{
/* RL78_PC_REGNUM */
for (auto j = 0; j < register_size (gdbarch, regnum) - 1; j++)
expected[j] = j;
}
else
{
for (auto j = 0; j < register_size (gdbarch, regnum); j++)
expected[j] = j;
}
}
else if (TYPE_CODE (type) == TYPE_CODE_FLAGS)
{
/* No idea how to test flags. */
continue;
}
else
{
/* If we don't know how to create the expected value for the
this type, make it fail. */
SELF_CHECK (0);
}
readwrite.cooked_write (regnum, expected.data ());
SELF_CHECK (readwrite.cooked_read (regnum, buf.data ()) == REG_VALID);
SELF_CHECK (expected == buf);
}
}
} // namespace selftests
#endif /* GDB_SELF_TEST */
void
_initialize_regcache (void)
{
regcache_descr_handle
= gdbarch_data_register_post_init (init_regcache_descr);
gdb::observers::target_changed.attach (regcache_observer_target_changed);
gdb::observers::thread_ptid_changed.attach
(regcache::regcache_thread_ptid_changed);
add_com ("flushregs", class_maintenance, reg_flush_command,
_("Force gdb to flush its register cache (maintainer command)."));
#if GDB_SELF_TEST
selftests::register_test ("current_regcache", selftests::current_regcache_test);
selftests::register_test_foreach_arch ("regcache::cooked_read_test",
selftests::cooked_read_test);
selftests::register_test_foreach_arch ("regcache::cooked_write_test",
selftests::cooked_write_test);
#endif
}