binutils-gdb/gdb/python/py-inferior.c
Pedro Alves 00431a78b2 Use thread_info and inferior pointers more throughout
This is more preparation bits for multi-target support.

In a multi-target scenario, we need to address the case of different
processes/threads running on different targets that happen to have the
same PID/PTID.  E.g., we can have both process 123 in target 1, and
process 123 in target 2, while they're in reality different processes
running on different machines.  Or maybe we've loaded multiple
instances of the same core file.  Etc.

To address this, in my WIP multi-target branch, threads and processes
are uniquely identified by the (process_stratum target_ops *, ptid_t)
and (process_stratum target_ops *, pid) tuples respectively.  I.e.,
each process_stratum instance has its own thread/process number space.

As you can imagine, that requires passing around target_ops * pointers
in a number of functions where we're currently passing only a ptid_t
or an int.  E.g., when we look up a thread_info object by ptid_t in
find_thread_ptid, the ptid_t alone isn't sufficient.

In many cases though, we already have the thread_info or inferior
pointer handy, but we "lose" it somewhere along the call stack, only
to look it up again by ptid_t/pid.  Since thread_info or inferior
objects know their parent target, if we pass around thread_info or
inferior pointers when possible, we avoid having to add extra
target_ops parameters to many functions, and also, we eliminate a
number of by ptid_t/int lookups.

So that's what this patch does.  In a bit more detail:

- Changes a number of functions and methods to take a thread_info or
  inferior pointer instead of a ptid_t or int parameter.

- Changes a number of structure fields from ptid_t/int to inferior or
  thread_info pointers.

- Uses the inferior_thread() function whenever possible instead of
  inferior_ptid.

- Uses thread_info pointers directly when possible instead of the
  is_running/is_stopped etc. routines that require a lookup.

- A number of functions are eliminated along the way, such as:

  int valid_gdb_inferior_id (int num);
  int pid_to_gdb_inferior_id (int pid);
  int gdb_inferior_id_to_pid (int num);
  int in_inferior_list (int pid);

- A few structures and places hold a thread_info pointer across
  inferior execution, so now they take a strong reference to the
  (refcounted) thread_info object to avoid the thread_info pointer
  getting stale.  This is done in enable_thread_stack_temporaries and
  in the infcall.c code.

- Related, there's a spot in infcall.c where using a RAII object to
  handle the refcount would be handy, so a gdb::ref_ptr specialization
  for thread_info is added (thread_info_ref, in gdbthread.h), along
  with a gdb_ref_ptr policy that works for all refcounted_object types
  (in common/refcounted-object.h).

gdb/ChangeLog:
2018-06-21  Pedro Alves  <palves@redhat.com>

	* ada-lang.h (ada_get_task_number): Take a thread_info pointer
	instead of a ptid_t.  All callers adjusted.
	* ada-tasks.c (ada_get_task_number): Likewise.  All callers
	adjusted.
	(print_ada_task_info, display_current_task_id, task_command_1):
	Adjust.
	* breakpoint.c (watchpoint_in_thread_scope): Adjust to use
	inferior_thread.
	(breakpoint_kind): Adjust.
	(remove_breakpoints_pid): Rename to ...
	(remove_breakpoints_inf): ... this.  Adjust to take an inferior
	pointer.  All callers adjusted.
	(bpstat_clear_actions): Use inferior_thread.
	(get_bpstat_thread): New.
	(bpstat_do_actions): Use it.
	(bpstat_check_breakpoint_conditions, bpstat_stop_status): Adjust
	to take a thread_info pointer.  All callers adjusted.
	(set_longjmp_breakpoint_for_call_dummy, set_momentary_breakpoint)
	(breakpoint_re_set_thread): Use inferior_thread.
	* breakpoint.h (struct inferior): Forward declare.
	(bpstat_stop_status): Update.
	(remove_breakpoints_pid): Delete.
	(remove_breakpoints_inf): New.
	* bsd-uthread.c (bsd_uthread_target::wait)
	(bsd_uthread_target::update_thread_list): Use find_thread_ptid.
	* btrace.c (btrace_add_pc, btrace_enable, btrace_fetch)
	(maint_btrace_packet_history_cmd)
	(maint_btrace_clear_packet_history_cmd): Adjust.
	(maint_btrace_clear_cmd, maint_info_btrace_cmd): Adjust to use
	inferior_thread.
	* cli/cli-interp.c: Include "inferior.h".
	* common/refcounted-object.h (struct
	refcounted_object_ref_policy): New.
	* compile/compile-object-load.c: Include gdbthread.h.
	(store_regs): Use inferior_thread.
	* corelow.c (core_target::close): Use current_inferior.
	(core_target_open): Adjust to use first_thread_of_inferior and use
	the current inferior.
	* ctf.c (ctf_target::close): Adjust to use current_inferior.
	* dummy-frame.c (dummy_frame_id) <ptid>: Delete, replaced by ...
	<thread>: ... this new field.  All references adjusted.
	(dummy_frame_pop, dummy_frame_discard, register_dummy_frame_dtor):
	Take a thread_info pointer instead of a ptid_t.
	* dummy-frame.h (dummy_frame_push, dummy_frame_pop)
	(dummy_frame_discard, register_dummy_frame_dtor): Take a
	thread_info pointer instead of a ptid_t.
	* elfread.c: Include "inferior.h".
	(elf_gnu_ifunc_resolver_stop, elf_gnu_ifunc_resolver_return_stop):
	Use inferior_thread.
	* eval.c (evaluate_subexp): Likewise.
	* frame.c (frame_pop, has_stack_frames, find_frame_sal): Use
	inferior_thread.
	* gdb_proc_service.h (struct thread_info): Forward declare.
	(struct ps_prochandle) <ptid>: Delete, replaced by ...
	<thread>: ... this new field.  All references adjusted.
	* gdbarch.h, gdbarch.c: Regenerate.
	* gdbarch.sh (get_syscall_number): Replace 'ptid' parameter with a
	'thread' parameter.  All implementations and callers adjusted.
	* gdbthread.h (thread_info) <set_running>: New method.
	(delete_thread, delete_thread_silent): Take a thread_info pointer
	instead of a ptid.
	(global_thread_id_to_ptid, ptid_to_global_thread_id): Delete.
	(first_thread_of_process): Delete, replaced by ...
	(first_thread_of_inferior): ... this new function.  All callers
	adjusted.
	(any_live_thread_of_process): Delete, replaced by ...
	(any_live_thread_of_inferior): ... this new function.  All callers
	adjusted.
	(switch_to_thread, switch_to_no_thread): Declare.
	(is_executing): Delete.
	(enable_thread_stack_temporaries): Update comment.
	<enable_thread_stack_temporaries>: Take a thread_info pointer
	instead of a ptid_t.  Incref the thread.
	<~enable_thread_stack_temporaries>: Decref the thread.
	<m_ptid>: Delete
	<m_thr>: New.
	(thread_stack_temporaries_enabled_p, push_thread_stack_temporary)
	(get_last_thread_stack_temporary)
	(value_in_thread_stack_temporaries, can_access_registers_thread):
	Take a thread_info pointer instead of a ptid_t.  All callers
	adjusted.
	* infcall.c (get_call_return_value): Use inferior_thread.
	(run_inferior_call): Work with thread pointers instead of ptid_t.
	(call_function_by_hand_dummy): Work with thread pointers instead
	of ptid_t.  Use thread_info_ref.
	* infcmd.c (proceed_thread_callback): Access thread's state
	directly.
	(ensure_valid_thread, ensure_not_running): Use inferior_thread,
	access thread's state directly.
	(continue_command): Use inferior_thread.
	(info_program_command): Use find_thread_ptid and access thread
	state directly.
	(proceed_after_attach_callback): Use thread state directly.
	(notice_new_inferior): Take a thread_info pointer instead of a
	ptid_t.  All callers adjusted.
	(exit_inferior): Take an inferior pointer instead of a pid.  All
	callers adjusted.
	(exit_inferior_silent): New.
	(detach_inferior): Delete.
	(valid_gdb_inferior_id, pid_to_gdb_inferior_id)
	(gdb_inferior_id_to_pid, in_inferior_list): Delete.
	(detach_inferior_command, kill_inferior_command): Use
	find_inferior_id instead of valid_gdb_inferior_id and
	gdb_inferior_id_to_pid.
	(inferior_command): Use inferior and thread pointers.
	* inferior.h (struct thread_info): Forward declare.
	(notice_new_inferior): Take a thread_info pointer instead of a
	ptid_t.  All callers adjusted.
	(detach_inferior): Delete declaration.
	(exit_inferior, exit_inferior_silent): Take an inferior pointer
	instead of a pid.  All callers adjusted.
	(gdb_inferior_id_to_pid, pid_to_gdb_inferior_id, in_inferior_list)
	(valid_gdb_inferior_id): Delete.
	* infrun.c (follow_fork_inferior, proceed_after_vfork_done)
	(handle_vfork_child_exec_or_exit, follow_exec): Adjust.
	(struct displaced_step_inferior_state) <pid>: Delete, replaced by
	...
	<inf>: ... this new field.
	<step_ptid>: Delete, replaced by ...
	<step_thread>: ... this new field.
	(get_displaced_stepping_state): Take an inferior pointer instead
	of a pid.  All callers adjusted.
	(displaced_step_in_progress_any_inferior): Adjust.
	(displaced_step_in_progress_thread): Take a thread pointer instead
	of a ptid_t.  All callers adjusted.
	(displaced_step_in_progress, add_displaced_stepping_state): Take
	an inferior pointer instead of a pid.  All callers adjusted.
	(get_displaced_step_closure_by_addr): Adjust.
	(remove_displaced_stepping_state): Take an inferior pointer
	instead of a pid.  All callers adjusted.
	(displaced_step_prepare_throw, displaced_step_prepare)
	(displaced_step_fixup): Take a thread pointer instead of a ptid_t.
	All callers adjusted.
	(start_step_over): Adjust.
	(infrun_thread_ptid_changed): Remove bit updating ptids in the
	displaced step queue.
	(do_target_resume): Adjust.
	(fetch_inferior_event): Use inferior_thread.
	(context_switch, get_inferior_stop_soon): Take an
	execution_control_state pointer instead of a ptid_t.  All callers
	adjusted.
	(switch_to_thread_cleanup): Delete.
	(stop_all_threads): Use scoped_restore_current_thread.
	* inline-frame.c: Include "gdbthread.h".
	(inline_state) <inline_state>: Take a thread pointer instead of a
	ptid_t.  All callers adjusted.
	<ptid>: Delete, replaced by ...
	<thread>: ... this new field.
	(find_inline_frame_state): Take a thread pointer instead of a
	ptid_t.  All callers adjusted.
	(skip_inline_frames, step_into_inline_frame)
	(inline_skipped_frames, inline_skipped_symbol): Take a thread
	pointer instead of a ptid_t.  All callers adjusted.
	* inline-frame.h (skip_inline_frames, step_into_inline_frame)
	(inline_skipped_frames, inline_skipped_symbol): Likewise.
	* linux-fork.c (delete_checkpoint_command): Adjust to use thread
	pointers directly.
	* linux-nat.c (get_detach_signal): Likewise.
	* linux-thread-db.c (thread_from_lwp): New 'stopped' parameter.
	(thread_db_notice_clone): Adjust.
	(thread_db_find_new_threads_silently)
	(thread_db_find_new_threads_2, thread_db_find_new_threads_1): Take
	a thread pointer instead of a ptid_t.  All callers adjusted.
	* mi/mi-cmd-var.c: Include "inferior.h".
	(mi_cmd_var_update_iter): Update to use thread pointers.
	* mi/mi-interp.c (mi_new_thread): Update to use the thread's
	inferior directly.
	(mi_output_running_pid, mi_inferior_count): Delete, bits factored
	out to ...
	(mi_output_running): ... this new function.
	(mi_on_resume_1): Adjust to use it.
	(mi_user_selected_context_changed): Adjust to use inferior_thread.
	* mi/mi-main.c (proceed_thread): Adjust to use thread pointers
	directly.
	(interrupt_thread_callback): : Adjust to use thread and inferior
	pointers.
	* proc-service.c: Include "gdbthread.h".
	(ps_pglobal_lookup): Adjust to use the thread's inferior directly.
	* progspace-and-thread.c: Include "inferior.h".
	* progspace.c: Include "inferior.h".
	* python/py-exitedevent.c (create_exited_event_object): Adjust to
	hold a reference to an inferior_object.
	* python/py-finishbreakpoint.c (bpfinishpy_init): Adjust to use
	inferior_thread.
	* python/py-inferior.c (struct inferior_object): Give the type a
	tag name instead of a typedef.
	(python_on_normal_stop): No need to check if the current thread is
	listed.
	(inferior_to_inferior_object): Change return type to
	inferior_object.  All callers adjusted.
	(find_thread_object): Delete, bits factored out to ...
	(thread_to_thread_object): ... this new function.
	* python/py-infthread.c (create_thread_object): Use
	inferior_to_inferior_object.
	(thpy_is_stopped): Use thread pointer directly.
	(gdbpy_selected_thread): Use inferior_thread.
	* python/py-record-btrace.c (btpy_list_object) <ptid>: Delete
	field, replaced with ...
	<thread>: ... this new field.  All users adjusted.
	(btpy_insn_or_gap_new): Drop const.
	(btpy_list_new): Take a thread pointer instead of a ptid_t.  All
	callers adjusted.
	* python/py-record.c: Include "gdbthread.h".
	(recpy_insn_new, recpy_func_new): Take a thread pointer instead of
	a ptid_t.  All callers adjusted.
	(gdbpy_current_recording): Use inferior_thread.
	* python/py-record.h (recpy_record_object) <ptid>: Delete
	field, replaced with ...
	<thread>: ... this new field.  All users adjusted.
	(recpy_element_object) <ptid>: Delete
	field, replaced with ...
	<thread>: ... this new field.  All users adjusted.
	(recpy_insn_new, recpy_func_new): Take a thread pointer instead of
	a ptid_t.  All callers adjusted.
	* python/py-threadevent.c: Include "gdbthread.h".
	(get_event_thread): Use thread_to_thread_object.
	* python/python-internal.h (struct inferior_object): Forward
	declare.
	(find_thread_object, find_inferior_object): Delete declarations.
	(thread_to_thread_object, inferior_to_inferior_object): New
	declarations.
	* record-btrace.c: Include "inferior.h".
	(require_btrace_thread): Use inferior_thread.
	(record_btrace_frame_sniffer)
	(record_btrace_tailcall_frame_sniffer): Use inferior_thread.
	(get_thread_current_frame): Use scoped_restore_current_thread and
	switch_to_thread.
	(get_thread_current_frame): Use thread pointer directly.
	(record_btrace_replay_at_breakpoint): Use thread's inferior
	pointer directly.
	* record-full.c: Include "inferior.h".
	* regcache.c: Include "gdbthread.h".
	(get_thread_arch_regcache): Use the inferior's address space
	directly.
	(get_thread_regcache, registers_changed_thread): New.
	* regcache.h (get_thread_regcache(thread_info *thread)): New
	overload.
	(registers_changed_thread): New.
	(remote_target) <remote_detach_1>: Swap order of parameters.
	(remote_add_thread): <remote_add_thread>: Return the new thread.
	(get_remote_thread_info(ptid_t)): New overload.
	(remote_target::remote_notice_new_inferior): Use thread pointers
	directly.
	(remote_target::process_initial_stop_replies): Use
	thread_info::set_running.
	(remote_target::remote_detach_1, remote_target::detach)
	(extended_remote_target::detach): Adjust.
	* stack.c (frame_show_address): Use inferior_thread.
	* target-debug.h (target_debug_print_thread_info_pp): New.
	* target-delegates.c: Regenerate.
	* target.c (default_thread_address_space): Delete.
	(memory_xfer_partial_1): Use current_inferior.
	(target_detach): Use current_inferior.
	(target_thread_address_space): Delete.
	(generic_mourn_inferior): Use current_inferior.
	* target.h (struct target_ops) <thread_address_space>: Delete.
	(target_thread_address_space): Delete.
	* thread.c (init_thread_list): Use ALL_THREADS_SAFE.  Use thread
	pointers directly.
	(delete_thread_1, delete_thread, delete_thread_silent): Take a
	thread pointer instead of a ptid_t.  Adjust all callers.
	(ptid_to_global_thread_id, global_thread_id_to_ptid): Delete.
	(first_thread_of_process): Delete, replaced by ...
	(first_thread_of_inferior): ... this new function.  All callers
	adjusted.
	(any_thread_of_process): Rename to ...
	(any_thread_of_inferior): ... this, and take an inferior pointer.
	(any_live_thread_of_process): Rename to ...
	(any_live_thread_of_inferior): ... this, and take an inferior
	pointer.
	(thread_stack_temporaries_enabled_p, push_thread_stack_temporary)
	(value_in_thread_stack_temporaries)
	(get_last_thread_stack_temporary): Take a thread pointer instead
	of a ptid_t.  Adjust all callers.
	(thread_info::set_running): New.
	(validate_registers_access): Use inferior_thread.
	(can_access_registers_ptid): Rename to ...
	(can_access_registers_thread): ... this, and take a thread
	pointer.
	(print_thread_info_1): Adjust to compare thread pointers instead
	of ptids.
	(switch_to_no_thread, switch_to_thread): Make extern.
	(scoped_restore_current_thread::~scoped_restore_current_thread):
	Use m_thread pointer directly.
	(scoped_restore_current_thread::scoped_restore_current_thread):
	Use inferior_thread.
	(thread_command): Use thread pointer directly.
	(thread_num_make_value_helper): Use inferior_thread.
	* top.c (execute_command): Use inferior_thread.
	* tui/tui-interp.c: Include "inferior.h".
	* varobj.c (varobj_create): Use inferior_thread.
	(value_of_root_1): Use find_thread_global_id instead of
	global_thread_id_to_ptid.
2018-06-21 17:09:31 +01:00

1089 lines
27 KiB
C

/* Python interface to inferiors.
Copyright (C) 2009-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 "gdbcore.h"
#include "gdbthread.h"
#include "inferior.h"
#include "objfiles.h"
#include "observable.h"
#include "python-internal.h"
#include "arch-utils.h"
#include "language.h"
#include "gdb_signals.h"
#include "py-event.h"
#include "py-stopevent.h"
struct threadlist_entry {
thread_object *thread_obj;
struct threadlist_entry *next;
};
struct inferior_object
{
PyObject_HEAD
/* The inferior we represent. */
struct inferior *inferior;
/* thread_object instances under this inferior. This list owns a
reference to each object it contains. */
struct threadlist_entry *threads;
/* Number of threads in the list. */
int nthreads;
};
extern PyTypeObject inferior_object_type
CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("inferior_object");
static const struct inferior_data *infpy_inf_data_key;
typedef struct {
PyObject_HEAD
void *buffer;
/* These are kept just for mbpy_str. */
CORE_ADDR addr;
CORE_ADDR length;
} membuf_object;
extern PyTypeObject membuf_object_type
CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("membuf_object");
/* Require that INFERIOR be a valid inferior ID. */
#define INFPY_REQUIRE_VALID(Inferior) \
do { \
if (!Inferior->inferior) \
{ \
PyErr_SetString (PyExc_RuntimeError, \
_("Inferior no longer exists.")); \
return NULL; \
} \
} while (0)
static void
python_on_normal_stop (struct bpstats *bs, int print_frame)
{
enum gdb_signal stop_signal;
if (!gdb_python_initialized)
return;
if (!find_thread_ptid (inferior_ptid))
return;
stop_signal = inferior_thread ()->suspend.stop_signal;
gdbpy_enter enter_py (get_current_arch (), current_language);
if (emit_stop_event (bs, stop_signal) < 0)
gdbpy_print_stack ();
}
static void
python_on_resume (ptid_t ptid)
{
if (!gdb_python_initialized)
return;
gdbpy_enter enter_py (target_gdbarch (), current_language);
if (emit_continue_event (ptid) < 0)
gdbpy_print_stack ();
}
/* Callback, registered as an observer, that notifies Python listeners
when an inferior function call is about to be made. */
static void
python_on_inferior_call_pre (ptid_t thread, CORE_ADDR address)
{
gdbpy_enter enter_py (target_gdbarch (), current_language);
if (emit_inferior_call_event (INFERIOR_CALL_PRE, thread, address) < 0)
gdbpy_print_stack ();
}
/* Callback, registered as an observer, that notifies Python listeners
when an inferior function call has completed. */
static void
python_on_inferior_call_post (ptid_t thread, CORE_ADDR address)
{
gdbpy_enter enter_py (target_gdbarch (), current_language);
if (emit_inferior_call_event (INFERIOR_CALL_POST, thread, address) < 0)
gdbpy_print_stack ();
}
/* Callback, registered as an observer, that notifies Python listeners
when a part of memory has been modified by user action (eg via a
'set' command). */
static void
python_on_memory_change (struct inferior *inferior, CORE_ADDR addr, ssize_t len, const bfd_byte *data)
{
gdbpy_enter enter_py (target_gdbarch (), current_language);
if (emit_memory_changed_event (addr, len) < 0)
gdbpy_print_stack ();
}
/* Callback, registered as an observer, that notifies Python listeners
when a register has been modified by user action (eg via a 'set'
command). */
static void
python_on_register_change (struct frame_info *frame, int regnum)
{
gdbpy_enter enter_py (target_gdbarch (), current_language);
if (emit_register_changed_event (frame, regnum) < 0)
gdbpy_print_stack ();
}
static void
python_inferior_exit (struct inferior *inf)
{
const LONGEST *exit_code = NULL;
if (!gdb_python_initialized)
return;
gdbpy_enter enter_py (target_gdbarch (), current_language);
if (inf->has_exit_code)
exit_code = &inf->exit_code;
if (emit_exited_event (exit_code, inf) < 0)
gdbpy_print_stack ();
}
/* Callback used to notify Python listeners about new objfiles loaded in the
inferior. OBJFILE may be NULL which means that the objfile list has been
cleared (emptied). */
static void
python_new_objfile (struct objfile *objfile)
{
if (!gdb_python_initialized)
return;
gdbpy_enter enter_py (objfile != NULL
? get_objfile_arch (objfile)
: target_gdbarch (),
current_language);
if (objfile == NULL)
{
if (emit_clear_objfiles_event () < 0)
gdbpy_print_stack ();
}
else
{
if (emit_new_objfile_event (objfile) < 0)
gdbpy_print_stack ();
}
}
/* Return a reference to the Python object of type Inferior
representing INFERIOR. If the object has already been created,
return it and increment the reference count, otherwise, create it.
Return NULL on failure. */
inferior_object *
inferior_to_inferior_object (struct inferior *inferior)
{
inferior_object *inf_obj;
inf_obj = (inferior_object *) inferior_data (inferior, infpy_inf_data_key);
if (!inf_obj)
{
inf_obj = PyObject_New (inferior_object, &inferior_object_type);
if (!inf_obj)
return NULL;
inf_obj->inferior = inferior;
inf_obj->threads = NULL;
inf_obj->nthreads = 0;
/* PyObject_New initializes the new object with a refcount of 1. This
counts for the reference we are keeping in the inferior data. */
set_inferior_data (inferior, infpy_inf_data_key, inf_obj);
}
/* We are returning a new reference. */
Py_INCREF ((PyObject *)inf_obj);
return inf_obj;
}
/* Called when a new inferior is created. Notifies any Python event
listeners. */
static void
python_new_inferior (struct inferior *inf)
{
if (!gdb_python_initialized)
return;
gdbpy_enter enter_py (python_gdbarch, python_language);
if (evregpy_no_listeners_p (gdb_py_events.new_inferior))
return;
gdbpy_ref<inferior_object> inf_obj (inferior_to_inferior_object (inf));
if (inf_obj == NULL)
{
gdbpy_print_stack ();
return;
}
gdbpy_ref<> event (create_event_object (&new_inferior_event_object_type));
if (event == NULL
|| evpy_add_attribute (event.get (), "inferior",
(PyObject *) inf_obj.get ()) < 0
|| evpy_emit_event (event.get (), gdb_py_events.new_inferior) < 0)
gdbpy_print_stack ();
}
/* Called when an inferior is removed. Notifies any Python event
listeners. */
static void
python_inferior_deleted (struct inferior *inf)
{
if (!gdb_python_initialized)
return;
gdbpy_enter enter_py (python_gdbarch, python_language);
if (evregpy_no_listeners_p (gdb_py_events.inferior_deleted))
return;
gdbpy_ref<inferior_object> inf_obj (inferior_to_inferior_object (inf));
if (inf_obj == NULL)
{
gdbpy_print_stack ();
return;
}
gdbpy_ref<> event (create_event_object (&inferior_deleted_event_object_type));
if (event == NULL
|| evpy_add_attribute (event.get (), "inferior",
(PyObject *) inf_obj.get ()) < 0
|| evpy_emit_event (event.get (), gdb_py_events.inferior_deleted) < 0)
gdbpy_print_stack ();
}
/* Finds the Python Inferior object for the given PID. Returns a
reference, or NULL if PID does not match any inferior object. */
PyObject *
find_inferior_object (int pid)
{
struct inferior *inf = find_inferior_pid (pid);
if (inf)
return (PyObject *) inferior_to_inferior_object (inf);
return NULL;
}
thread_object *
thread_to_thread_object (thread_info *thr)
{
gdbpy_ref<inferior_object> inf_obj (inferior_to_inferior_object (thr->inf));
if (inf_obj == NULL)
return NULL;
for (threadlist_entry *thread = inf_obj->threads;
thread != NULL;
thread = thread->next)
if (thread->thread_obj->thread == thr)
return thread->thread_obj;
return NULL;
}
static void
add_thread_object (struct thread_info *tp)
{
thread_object *thread_obj;
inferior_object *inf_obj;
struct threadlist_entry *entry;
if (!gdb_python_initialized)
return;
gdbpy_enter enter_py (python_gdbarch, python_language);
thread_obj = create_thread_object (tp);
if (!thread_obj)
{
gdbpy_print_stack ();
return;
}
inf_obj = (inferior_object *) thread_obj->inf_obj;
entry = XNEW (struct threadlist_entry);
entry->thread_obj = thread_obj;
entry->next = inf_obj->threads;
inf_obj->threads = entry;
inf_obj->nthreads++;
if (evregpy_no_listeners_p (gdb_py_events.new_thread))
return;
gdbpy_ref<> event (create_thread_event_object (&new_thread_event_object_type,
(PyObject *) thread_obj));
if (event == NULL
|| evpy_emit_event (event.get (), gdb_py_events.new_thread) < 0)
gdbpy_print_stack ();
}
static void
delete_thread_object (struct thread_info *tp, int ignore)
{
struct threadlist_entry **entry, *tmp;
if (!gdb_python_initialized)
return;
gdbpy_enter enter_py (python_gdbarch, python_language);
gdbpy_ref<inferior_object> inf_obj
((inferior_object *) inferior_to_inferior_object (tp->inf));
if (inf_obj == NULL)
return;
/* Find thread entry in its inferior's thread_list. */
for (entry = &inf_obj->threads; *entry != NULL; entry =
&(*entry)->next)
if ((*entry)->thread_obj->thread == tp)
break;
if (!*entry)
return;
tmp = *entry;
tmp->thread_obj->thread = NULL;
*entry = (*entry)->next;
inf_obj->nthreads--;
Py_DECREF (tmp->thread_obj);
xfree (tmp);
}
static PyObject *
infpy_threads (PyObject *self, PyObject *args)
{
int i;
struct threadlist_entry *entry;
inferior_object *inf_obj = (inferior_object *) self;
PyObject *tuple;
INFPY_REQUIRE_VALID (inf_obj);
TRY
{
update_thread_list ();
}
CATCH (except, RETURN_MASK_ALL)
{
GDB_PY_HANDLE_EXCEPTION (except);
}
END_CATCH
tuple = PyTuple_New (inf_obj->nthreads);
if (!tuple)
return NULL;
for (i = 0, entry = inf_obj->threads; i < inf_obj->nthreads;
i++, entry = entry->next)
{
Py_INCREF (entry->thread_obj);
PyTuple_SET_ITEM (tuple, i, (PyObject *) entry->thread_obj);
}
return tuple;
}
static PyObject *
infpy_get_num (PyObject *self, void *closure)
{
inferior_object *inf = (inferior_object *) self;
INFPY_REQUIRE_VALID (inf);
return PyLong_FromLong (inf->inferior->num);
}
static PyObject *
infpy_get_pid (PyObject *self, void *closure)
{
inferior_object *inf = (inferior_object *) self;
INFPY_REQUIRE_VALID (inf);
return PyLong_FromLong (inf->inferior->pid);
}
static PyObject *
infpy_get_was_attached (PyObject *self, void *closure)
{
inferior_object *inf = (inferior_object *) self;
INFPY_REQUIRE_VALID (inf);
if (inf->inferior->attach_flag)
Py_RETURN_TRUE;
Py_RETURN_FALSE;
}
static int
build_inferior_list (struct inferior *inf, void *arg)
{
PyObject *list = (PyObject *) arg;
gdbpy_ref<inferior_object> inferior (inferior_to_inferior_object (inf));
if (inferior == NULL)
return 0;
return PyList_Append (list, (PyObject *) inferior.get ()) ? 1 : 0;
}
/* Implementation of gdb.inferiors () -> (gdb.Inferior, ...).
Returns a tuple of all inferiors. */
PyObject *
gdbpy_inferiors (PyObject *unused, PyObject *unused2)
{
gdbpy_ref<> list (PyList_New (0));
if (list == NULL)
return NULL;
if (iterate_over_inferiors (build_inferior_list, list.get ()))
return NULL;
return PyList_AsTuple (list.get ());
}
/* Membuf and memory manipulation. */
/* Implementation of Inferior.read_memory (address, length).
Returns a Python buffer object with LENGTH bytes of the inferior's
memory at ADDRESS. Both arguments are integers. Returns NULL on error,
with a python exception set. */
static PyObject *
infpy_read_memory (PyObject *self, PyObject *args, PyObject *kw)
{
CORE_ADDR addr, length;
gdb_byte *buffer = NULL;
PyObject *addr_obj, *length_obj, *result;
static const char *keywords[] = { "address", "length", NULL };
if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "OO", keywords,
&addr_obj, &length_obj))
return NULL;
if (get_addr_from_python (addr_obj, &addr) < 0
|| get_addr_from_python (length_obj, &length) < 0)
return NULL;
TRY
{
buffer = (gdb_byte *) xmalloc (length);
read_memory (addr, buffer, length);
}
CATCH (except, RETURN_MASK_ALL)
{
xfree (buffer);
GDB_PY_HANDLE_EXCEPTION (except);
}
END_CATCH
gdbpy_ref<membuf_object> membuf_obj (PyObject_New (membuf_object,
&membuf_object_type));
if (membuf_obj == NULL)
{
xfree (buffer);
return NULL;
}
membuf_obj->buffer = buffer;
membuf_obj->addr = addr;
membuf_obj->length = length;
#ifdef IS_PY3K
result = PyMemoryView_FromObject ((PyObject *) membuf_obj.get ());
#else
result = PyBuffer_FromReadWriteObject ((PyObject *) membuf_obj.get (), 0,
Py_END_OF_BUFFER);
#endif
return result;
}
/* Implementation of Inferior.write_memory (address, buffer [, length]).
Writes the contents of BUFFER (a Python object supporting the read
buffer protocol) at ADDRESS in the inferior's memory. Write LENGTH
bytes from BUFFER, or its entire contents if the argument is not
provided. The function returns nothing. Returns NULL on error, with
a python exception set. */
static PyObject *
infpy_write_memory (PyObject *self, PyObject *args, PyObject *kw)
{
struct gdb_exception except = exception_none;
Py_ssize_t buf_len;
const gdb_byte *buffer;
CORE_ADDR addr, length;
PyObject *addr_obj, *length_obj = NULL;
static const char *keywords[] = { "address", "buffer", "length", NULL };
#ifdef IS_PY3K
Py_buffer pybuf;
if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "Os*|O", keywords,
&addr_obj, &pybuf, &length_obj))
return NULL;
buffer = (const gdb_byte *) pybuf.buf;
buf_len = pybuf.len;
#else
if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "Os#|O", keywords,
&addr_obj, &buffer, &buf_len,
&length_obj))
return NULL;
buffer = (const gdb_byte *) buffer;
#endif
if (get_addr_from_python (addr_obj, &addr) < 0)
goto fail;
if (!length_obj)
length = buf_len;
else if (get_addr_from_python (length_obj, &length) < 0)
goto fail;
TRY
{
write_memory_with_notification (addr, buffer, length);
}
CATCH (ex, RETURN_MASK_ALL)
{
except = ex;
}
END_CATCH
#ifdef IS_PY3K
PyBuffer_Release (&pybuf);
#endif
GDB_PY_HANDLE_EXCEPTION (except);
Py_RETURN_NONE;
fail:
#ifdef IS_PY3K
PyBuffer_Release (&pybuf);
#endif
return NULL;
}
/* Destructor of Membuf objects. */
static void
mbpy_dealloc (PyObject *self)
{
xfree (((membuf_object *) self)->buffer);
Py_TYPE (self)->tp_free (self);
}
/* Return a description of the Membuf object. */
static PyObject *
mbpy_str (PyObject *self)
{
membuf_object *membuf_obj = (membuf_object *) self;
return PyString_FromFormat (_("Memory buffer for address %s, \
which is %s bytes long."),
paddress (python_gdbarch, membuf_obj->addr),
pulongest (membuf_obj->length));
}
#ifdef IS_PY3K
static int
get_buffer (PyObject *self, Py_buffer *buf, int flags)
{
membuf_object *membuf_obj = (membuf_object *) self;
int ret;
ret = PyBuffer_FillInfo (buf, self, membuf_obj->buffer,
membuf_obj->length, 0,
PyBUF_CONTIG);
/* Despite the documentation saying this field is a "const char *",
in Python 3.4 at least, it's really a "char *". */
buf->format = (char *) "c";
return ret;
}
#else
static Py_ssize_t
get_read_buffer (PyObject *self, Py_ssize_t segment, void **ptrptr)
{
membuf_object *membuf_obj = (membuf_object *) self;
if (segment)
{
PyErr_SetString (PyExc_SystemError,
_("The memory buffer supports only one segment."));
return -1;
}
*ptrptr = membuf_obj->buffer;
return membuf_obj->length;
}
static Py_ssize_t
get_write_buffer (PyObject *self, Py_ssize_t segment, void **ptrptr)
{
return get_read_buffer (self, segment, ptrptr);
}
static Py_ssize_t
get_seg_count (PyObject *self, Py_ssize_t *lenp)
{
if (lenp)
*lenp = ((membuf_object *) self)->length;
return 1;
}
static Py_ssize_t
get_char_buffer (PyObject *self, Py_ssize_t segment, char **ptrptr)
{
void *ptr = NULL;
Py_ssize_t ret;
ret = get_read_buffer (self, segment, &ptr);
*ptrptr = (char *) ptr;
return ret;
}
#endif /* IS_PY3K */
/* Implementation of
gdb.search_memory (address, length, pattern). ADDRESS is the
address to start the search. LENGTH specifies the scope of the
search from ADDRESS. PATTERN is the pattern to search for (and
must be a Python object supporting the buffer protocol).
Returns a Python Long object holding the address where the pattern
was located, or if the pattern was not found, returns None. Returns NULL
on error, with a python exception set. */
static PyObject *
infpy_search_memory (PyObject *self, PyObject *args, PyObject *kw)
{
struct gdb_exception except = exception_none;
CORE_ADDR start_addr, length;
static const char *keywords[] = { "address", "length", "pattern", NULL };
PyObject *start_addr_obj, *length_obj;
Py_ssize_t pattern_size;
const gdb_byte *buffer;
CORE_ADDR found_addr;
int found = 0;
#ifdef IS_PY3K
Py_buffer pybuf;
if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "OOs*", keywords,
&start_addr_obj, &length_obj,
&pybuf))
return NULL;
buffer = (const gdb_byte *) pybuf.buf;
pattern_size = pybuf.len;
#else
PyObject *pattern;
const void *vbuffer;
if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "OOO", keywords,
&start_addr_obj, &length_obj,
&pattern))
return NULL;
if (!PyObject_CheckReadBuffer (pattern))
{
PyErr_SetString (PyExc_RuntimeError,
_("The pattern is not a Python buffer."));
return NULL;
}
if (PyObject_AsReadBuffer (pattern, &vbuffer, &pattern_size) == -1)
return NULL;
buffer = (const gdb_byte *) vbuffer;
#endif
if (get_addr_from_python (start_addr_obj, &start_addr) < 0)
goto fail;
if (get_addr_from_python (length_obj, &length) < 0)
goto fail;
if (!length)
{
PyErr_SetString (PyExc_ValueError,
_("Search range is empty."));
goto fail;
}
/* Watch for overflows. */
else if (length > CORE_ADDR_MAX
|| (start_addr + length - 1) < start_addr)
{
PyErr_SetString (PyExc_ValueError,
_("The search range is too large."));
goto fail;
}
TRY
{
found = target_search_memory (start_addr, length,
buffer, pattern_size,
&found_addr);
}
CATCH (ex, RETURN_MASK_ALL)
{
except = ex;
}
END_CATCH
#ifdef IS_PY3K
PyBuffer_Release (&pybuf);
#endif
GDB_PY_HANDLE_EXCEPTION (except);
if (found)
return PyLong_FromLong (found_addr);
else
Py_RETURN_NONE;
fail:
#ifdef IS_PY3K
PyBuffer_Release (&pybuf);
#endif
return NULL;
}
/* Implementation of gdb.Inferior.is_valid (self) -> Boolean.
Returns True if this inferior object still exists in GDB. */
static PyObject *
infpy_is_valid (PyObject *self, PyObject *args)
{
inferior_object *inf = (inferior_object *) self;
if (! inf->inferior)
Py_RETURN_FALSE;
Py_RETURN_TRUE;
}
/* Implementation of gdb.Inferior.thread_from_thread_handle (self, handle)
-> gdb.InferiorThread. */
PyObject *
infpy_thread_from_thread_handle (PyObject *self, PyObject *args, PyObject *kw)
{
PyObject *handle_obj, *result;
inferior_object *inf_obj = (inferior_object *) self;
static const char *keywords[] = { "thread_handle", NULL };
INFPY_REQUIRE_VALID (inf_obj);
if (! gdb_PyArg_ParseTupleAndKeywords (args, kw, "O", keywords, &handle_obj))
return NULL;
result = Py_None;
if (!gdbpy_is_value_object (handle_obj))
{
PyErr_SetString (PyExc_TypeError,
_("Argument 'handle_obj' must be a thread handle object."));
return NULL;
}
else
{
TRY
{
struct thread_info *thread_info;
struct value *val = value_object_to_value (handle_obj);
thread_info = find_thread_by_handle (val, inf_obj->inferior);
if (thread_info != NULL)
{
result = (PyObject *) thread_to_thread_object (thread_info);
if (result != NULL)
Py_INCREF (result);
}
}
CATCH (except, RETURN_MASK_ALL)
{
GDB_PY_HANDLE_EXCEPTION (except);
}
END_CATCH
}
return result;
}
static void
infpy_dealloc (PyObject *obj)
{
inferior_object *inf_obj = (inferior_object *) obj;
struct inferior *inf = inf_obj->inferior;
if (! inf)
return;
set_inferior_data (inf, infpy_inf_data_key, NULL);
}
/* Clear the INFERIOR pointer in an Inferior object and clear the
thread list. */
static void
py_free_inferior (struct inferior *inf, void *datum)
{
gdbpy_ref<inferior_object> inf_obj ((inferior_object *) datum);
struct threadlist_entry *th_entry, *th_tmp;
if (!gdb_python_initialized)
return;
gdbpy_enter enter_py (python_gdbarch, python_language);
inf_obj->inferior = NULL;
/* Deallocate threads list. */
for (th_entry = inf_obj->threads; th_entry != NULL;)
{
Py_DECREF (th_entry->thread_obj);
th_tmp = th_entry;
th_entry = th_entry->next;
xfree (th_tmp);
}
inf_obj->nthreads = 0;
}
/* Implementation of gdb.selected_inferior() -> gdb.Inferior.
Returns the current inferior object. */
PyObject *
gdbpy_selected_inferior (PyObject *self, PyObject *args)
{
return (PyObject *) inferior_to_inferior_object (current_inferior ());
}
int
gdbpy_initialize_inferior (void)
{
if (PyType_Ready (&inferior_object_type) < 0)
return -1;
if (gdb_pymodule_addobject (gdb_module, "Inferior",
(PyObject *) &inferior_object_type) < 0)
return -1;
infpy_inf_data_key =
register_inferior_data_with_cleanup (NULL, py_free_inferior);
gdb::observers::new_thread.attach (add_thread_object);
gdb::observers::thread_exit.attach (delete_thread_object);
gdb::observers::normal_stop.attach (python_on_normal_stop);
gdb::observers::target_resumed.attach (python_on_resume);
gdb::observers::inferior_call_pre.attach (python_on_inferior_call_pre);
gdb::observers::inferior_call_post.attach (python_on_inferior_call_post);
gdb::observers::memory_changed.attach (python_on_memory_change);
gdb::observers::register_changed.attach (python_on_register_change);
gdb::observers::inferior_exit.attach (python_inferior_exit);
gdb::observers::new_objfile.attach (python_new_objfile);
gdb::observers::inferior_added.attach (python_new_inferior);
gdb::observers::inferior_removed.attach (python_inferior_deleted);
membuf_object_type.tp_new = PyType_GenericNew;
if (PyType_Ready (&membuf_object_type) < 0)
return -1;
return gdb_pymodule_addobject (gdb_module, "Membuf", (PyObject *)
&membuf_object_type);
}
static gdb_PyGetSetDef inferior_object_getset[] =
{
{ "num", infpy_get_num, NULL, "ID of inferior, as assigned by GDB.", NULL },
{ "pid", infpy_get_pid, NULL, "PID of inferior, as assigned by the OS.",
NULL },
{ "was_attached", infpy_get_was_attached, NULL,
"True if the inferior was created using 'attach'.", NULL },
{ NULL }
};
static PyMethodDef inferior_object_methods[] =
{
{ "is_valid", infpy_is_valid, METH_NOARGS,
"is_valid () -> Boolean.\n\
Return true if this inferior is valid, false if not." },
{ "threads", infpy_threads, METH_NOARGS,
"Return all the threads of this inferior." },
{ "read_memory", (PyCFunction) infpy_read_memory,
METH_VARARGS | METH_KEYWORDS,
"read_memory (address, length) -> buffer\n\
Return a buffer object for reading from the inferior's memory." },
{ "write_memory", (PyCFunction) infpy_write_memory,
METH_VARARGS | METH_KEYWORDS,
"write_memory (address, buffer [, length])\n\
Write the given buffer object to the inferior's memory." },
{ "search_memory", (PyCFunction) infpy_search_memory,
METH_VARARGS | METH_KEYWORDS,
"search_memory (address, length, pattern) -> long\n\
Return a long with the address of a match, or None." },
{ "thread_from_thread_handle", (PyCFunction) infpy_thread_from_thread_handle,
METH_VARARGS | METH_KEYWORDS,
"thread_from_thread_handle (handle) -> gdb.InferiorThread.\n\
Return thread object corresponding to thread handle." },
{ NULL }
};
PyTypeObject inferior_object_type =
{
PyVarObject_HEAD_INIT (NULL, 0)
"gdb.Inferior", /* tp_name */
sizeof (inferior_object), /* tp_basicsize */
0, /* tp_itemsize */
infpy_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_ITER, /* tp_flags */
"GDB inferior object", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
inferior_object_methods, /* tp_methods */
0, /* tp_members */
inferior_object_getset, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0 /* tp_alloc */
};
#ifdef IS_PY3K
static PyBufferProcs buffer_procs =
{
get_buffer
};
#else
/* Python doesn't provide a decent way to get compatibility here. */
#if HAVE_LIBPYTHON2_4
#define CHARBUFFERPROC_NAME getcharbufferproc
#else
#define CHARBUFFERPROC_NAME charbufferproc
#endif
static PyBufferProcs buffer_procs = {
get_read_buffer,
get_write_buffer,
get_seg_count,
/* The cast here works around a difference between Python 2.4 and
Python 2.5. */
(CHARBUFFERPROC_NAME) get_char_buffer
};
#endif /* IS_PY3K */
PyTypeObject membuf_object_type = {
PyVarObject_HEAD_INIT (NULL, 0)
"gdb.Membuf", /*tp_name*/
sizeof (membuf_object), /*tp_basicsize*/
0, /*tp_itemsize*/
mbpy_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
mbpy_str, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
&buffer_procs, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT, /*tp_flags*/
"GDB memory buffer object", /*tp_doc*/
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
};