gdb/python/py-inferior.c - gdb

Global variables defined

Data types defined

Functions defined

Macros defined

Source code

  1. /* Python interface to inferiors.

  2.    Copyright (C) 2009-2015 Free Software Foundation, Inc.

  3.    This file is part of GDB.

  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 3 of the License, or
  7.    (at your option) any later version.

  8.    This program is distributed in the hope that it will be useful,
  9.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  10.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  11.    GNU General Public License for more details.

  12.    You should have received a copy of the GNU General Public License
  13.    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

  14. #include "defs.h"
  15. #include "gdbcore.h"
  16. #include "gdbthread.h"
  17. #include "inferior.h"
  18. #include "objfiles.h"
  19. #include "observer.h"
  20. #include "python-internal.h"
  21. #include "arch-utils.h"
  22. #include "language.h"
  23. #include "gdb_signals.h"
  24. #include "py-event.h"
  25. #include "py-stopevent.h"

  26. struct threadlist_entry {
  27.   thread_object *thread_obj;
  28.   struct threadlist_entry *next;
  29. };

  30. typedef struct
  31. {
  32.   PyObject_HEAD

  33.   /* The inferior we represent.  */
  34.   struct inferior *inferior;

  35.   /* thread_object instances under this inferior.  This list owns a
  36.      reference to each object it contains.  */
  37.   struct threadlist_entry *threads;

  38.   /* Number of threads in the list.  */
  39.   int nthreads;
  40. } inferior_object;

  41. static PyTypeObject inferior_object_type
  42.     CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("inferior_object");

  43. static const struct inferior_data *infpy_inf_data_key;

  44. typedef struct {
  45.   PyObject_HEAD
  46.   void *buffer;

  47.   /* These are kept just for mbpy_str.  */
  48.   CORE_ADDR addr;
  49.   CORE_ADDR length;
  50. } membuf_object;

  51. static PyTypeObject membuf_object_type
  52.     CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("membuf_object");

  53. /* Require that INFERIOR be a valid inferior ID.  */
  54. #define INFPY_REQUIRE_VALID(Inferior)                                \
  55.   do {                                                                \
  56.     if (!Inferior->inferior)                                        \
  57.       {                                                                \
  58.         PyErr_SetString (PyExc_RuntimeError,                        \
  59.                          _("Inferior no longer exists."));        \
  60.         return NULL;                                                \
  61.       }                                                                \
  62.   } while (0)

  63. static void
  64. python_on_normal_stop (struct bpstats *bs, int print_frame)
  65. {
  66.   struct cleanup *cleanup;
  67.   enum gdb_signal stop_signal;

  68.   if (!gdb_python_initialized)
  69.     return;

  70.   if (!find_thread_ptid (inferior_ptid))
  71.       return;

  72.   stop_signal = inferior_thread ()->suspend.stop_signal;

  73.   cleanup = ensure_python_env (get_current_arch (), current_language);

  74.   if (emit_stop_event (bs, stop_signal) < 0)
  75.     gdbpy_print_stack ();

  76.   do_cleanups (cleanup);
  77. }

  78. static void
  79. python_on_resume (ptid_t ptid)
  80. {
  81.   struct cleanup *cleanup;

  82.   if (!gdb_python_initialized)
  83.     return;

  84.   cleanup = ensure_python_env (target_gdbarch (), current_language);

  85.   if (emit_continue_event (ptid) < 0)
  86.     gdbpy_print_stack ();

  87.   do_cleanups (cleanup);
  88. }

  89. /* Callback, registered as an observer, that notifies Python listeners
  90.    when an inferior function call is about to be made. */

  91. static void
  92. python_on_inferior_call_pre (ptid_t thread, CORE_ADDR address)
  93. {
  94.   struct cleanup *cleanup;

  95.   cleanup = ensure_python_env (target_gdbarch (), current_language);

  96.   if (emit_inferior_call_event (INFERIOR_CALL_PRE, thread, address) < 0)
  97.     gdbpy_print_stack ();

  98.   do_cleanups (cleanup);
  99. }

  100. /* Callback, registered as an observer, that notifies Python listeners
  101.    when an inferior function call has completed. */

  102. static void
  103. python_on_inferior_call_post (ptid_t thread, CORE_ADDR address)
  104. {
  105.   struct cleanup *cleanup;

  106.   cleanup = ensure_python_env (target_gdbarch (), current_language);

  107.   if (emit_inferior_call_event (INFERIOR_CALL_POST, thread, address) < 0)
  108.     gdbpy_print_stack ();

  109.   do_cleanups (cleanup);
  110. }

  111. /* Callback, registered as an observer, that notifies Python listeners
  112.    when a part of memory has been modified by user action (eg via a
  113.    'set' command). */

  114. static void
  115. python_on_memory_change (struct inferior *inferior, CORE_ADDR addr, ssize_t len, const bfd_byte *data)
  116. {
  117.   struct cleanup *cleanup;

  118.   cleanup = ensure_python_env (target_gdbarch (), current_language);

  119.   if (emit_memory_changed_event (addr, len) < 0)
  120.     gdbpy_print_stack ();

  121.   do_cleanups (cleanup);
  122. }

  123. /* Callback, registered as an observer, that notifies Python listeners
  124.    when a register has been modified by user action (eg via a 'set'
  125.    command). */

  126. static void
  127. python_on_register_change (struct frame_info *frame, int regnum)
  128. {
  129.   struct cleanup *cleanup;

  130.   cleanup = ensure_python_env (target_gdbarch (), current_language);

  131.   if (emit_register_changed_event (frame, regnum) < 0)
  132.     gdbpy_print_stack ();

  133.   do_cleanups (cleanup);
  134. }

  135. static void
  136. python_inferior_exit (struct inferior *inf)
  137. {
  138.   struct cleanup *cleanup;
  139.   const LONGEST *exit_code = NULL;

  140.   if (!gdb_python_initialized)
  141.     return;

  142.   cleanup = ensure_python_env (target_gdbarch (), current_language);

  143.   if (inf->has_exit_code)
  144.     exit_code = &inf->exit_code;

  145.   if (emit_exited_event (exit_code, inf) < 0)
  146.     gdbpy_print_stack ();

  147.   do_cleanups (cleanup);
  148. }

  149. /* Callback used to notify Python listeners about new objfiles loaded in the
  150.    inferior.  OBJFILE may be NULL which means that the objfile list has been
  151.    cleared (emptied).  */

  152. static void
  153. python_new_objfile (struct objfile *objfile)
  154. {
  155.   struct cleanup *cleanup;

  156.   if (!gdb_python_initialized)
  157.     return;

  158.   cleanup = ensure_python_env (objfile != NULL
  159.                                ? get_objfile_arch (objfile)
  160.                                : target_gdbarch (),
  161.                                current_language);

  162.   if (objfile == NULL)
  163.     {
  164.       if (emit_clear_objfiles_event () < 0)
  165.         gdbpy_print_stack ();
  166.     }
  167.   else
  168.     {
  169.       if (emit_new_objfile_event (objfile) < 0)
  170.         gdbpy_print_stack ();
  171.     }

  172.   do_cleanups (cleanup);
  173. }

  174. /* Return a reference to the Python object of type Inferior
  175.    representing INFERIOR.  If the object has already been created,
  176.    return it and increment the reference count,  otherwise, create it.
  177.    Return NULL on failure.  */
  178. PyObject *
  179. inferior_to_inferior_object (struct inferior *inferior)
  180. {
  181.   inferior_object *inf_obj;

  182.   inf_obj = inferior_data (inferior, infpy_inf_data_key);
  183.   if (!inf_obj)
  184.     {
  185.       inf_obj = PyObject_New (inferior_object, &inferior_object_type);
  186.       if (!inf_obj)
  187.           return NULL;

  188.       inf_obj->inferior = inferior;
  189.       inf_obj->threads = NULL;
  190.       inf_obj->nthreads = 0;

  191.       set_inferior_data (inferior, infpy_inf_data_key, inf_obj);

  192.     }
  193.   else
  194.     Py_INCREF ((PyObject *)inf_obj);

  195.   return (PyObject *) inf_obj;
  196. }

  197. /* Finds the Python Inferior object for the given PID.  Returns a
  198.    reference, or NULL if PID does not match any inferior object. */

  199. PyObject *
  200. find_inferior_object (int pid)
  201. {
  202.   struct inferior *inf = find_inferior_pid (pid);

  203.   if (inf)
  204.     return inferior_to_inferior_object (inf);

  205.   return NULL;
  206. }

  207. thread_object *
  208. find_thread_object (ptid_t ptid)
  209. {
  210.   int pid;
  211.   struct threadlist_entry *thread;
  212.   PyObject *inf_obj;
  213.   thread_object *found = NULL;

  214.   pid = ptid_get_pid (ptid);
  215.   if (pid == 0)
  216.     return NULL;

  217.   inf_obj = find_inferior_object (pid);

  218.   if (! inf_obj)
  219.     return NULL;

  220.   for (thread = ((inferior_object *)inf_obj)->threads; thread;
  221.        thread = thread->next)
  222.     if (ptid_equal (thread->thread_obj->thread->ptid, ptid))
  223.       {
  224.         found = thread->thread_obj;
  225.         break;
  226.       }

  227.   Py_DECREF (inf_obj);

  228.   if (found)
  229.     return found;

  230.   return NULL;
  231. }

  232. static void
  233. add_thread_object (struct thread_info *tp)
  234. {
  235.   struct cleanup *cleanup;
  236.   thread_object *thread_obj;
  237.   inferior_object *inf_obj;
  238.   struct threadlist_entry *entry;

  239.   if (!gdb_python_initialized)
  240.     return;

  241.   cleanup = ensure_python_env (python_gdbarch, python_language);

  242.   thread_obj = create_thread_object (tp);
  243.   if (!thread_obj)
  244.     {
  245.       gdbpy_print_stack ();
  246.       do_cleanups (cleanup);
  247.       return;
  248.     }

  249.   inf_obj = (inferior_object *) thread_obj->inf_obj;

  250.   entry = xmalloc (sizeof (struct threadlist_entry));
  251.   entry->thread_obj = thread_obj;
  252.   entry->next = inf_obj->threads;

  253.   inf_obj->threads = entry;
  254.   inf_obj->nthreads++;

  255.   do_cleanups (cleanup);
  256. }

  257. static void
  258. delete_thread_object (struct thread_info *tp, int ignore)
  259. {
  260.   struct cleanup *cleanup;
  261.   inferior_object *inf_obj;
  262.   struct threadlist_entry **entry, *tmp;

  263.   if (!gdb_python_initialized)
  264.     return;

  265.   cleanup = ensure_python_env (python_gdbarch, python_language);

  266.   inf_obj
  267.     = (inferior_object *) find_inferior_object (ptid_get_pid (tp->ptid));
  268.   if (!inf_obj)
  269.     {
  270.       do_cleanups (cleanup);
  271.       return;
  272.     }

  273.   /* Find thread entry in its inferior's thread_list.  */
  274.   for (entry = &inf_obj->threads; *entry != NULL; entry =
  275.          &(*entry)->next)
  276.     if ((*entry)->thread_obj->thread == tp)
  277.       break;

  278.   if (!*entry)
  279.     {
  280.       Py_DECREF (inf_obj);
  281.       do_cleanups (cleanup);
  282.       return;
  283.     }

  284.   tmp = *entry;
  285.   tmp->thread_obj->thread = NULL;

  286.   *entry = (*entry)->next;
  287.   inf_obj->nthreads--;

  288.   Py_DECREF (tmp->thread_obj);
  289.   Py_DECREF (inf_obj);
  290.   xfree (tmp);

  291.   do_cleanups (cleanup);
  292. }

  293. static PyObject *
  294. infpy_threads (PyObject *self, PyObject *args)
  295. {
  296.   int i;
  297.   struct threadlist_entry *entry;
  298.   inferior_object *inf_obj = (inferior_object *) self;
  299.   PyObject *tuple;
  300.   volatile struct gdb_exception except;

  301.   INFPY_REQUIRE_VALID (inf_obj);

  302.   TRY_CATCH (except, RETURN_MASK_ALL)
  303.     update_thread_list ();
  304.   GDB_PY_HANDLE_EXCEPTION (except);

  305.   tuple = PyTuple_New (inf_obj->nthreads);
  306.   if (!tuple)
  307.     return NULL;

  308.   for (i = 0, entry = inf_obj->threads; i < inf_obj->nthreads;
  309.        i++, entry = entry->next)
  310.     {
  311.       Py_INCREF (entry->thread_obj);
  312.       PyTuple_SET_ITEM (tuple, i, (PyObject *) entry->thread_obj);
  313.     }

  314.   return tuple;
  315. }

  316. static PyObject *
  317. infpy_get_num (PyObject *self, void *closure)
  318. {
  319.   inferior_object *inf = (inferior_object *) self;

  320.   INFPY_REQUIRE_VALID (inf);

  321.   return PyLong_FromLong (inf->inferior->num);
  322. }

  323. static PyObject *
  324. infpy_get_pid (PyObject *self, void *closure)
  325. {
  326.   inferior_object *inf = (inferior_object *) self;

  327.   INFPY_REQUIRE_VALID (inf);

  328.   return PyLong_FromLong (inf->inferior->pid);
  329. }

  330. static PyObject *
  331. infpy_get_was_attached (PyObject *self, void *closure)
  332. {
  333.   inferior_object *inf = (inferior_object *) self;

  334.   INFPY_REQUIRE_VALID (inf);
  335.   if (inf->inferior->attach_flag)
  336.     Py_RETURN_TRUE;
  337.   Py_RETURN_FALSE;
  338. }

  339. static int
  340. build_inferior_list (struct inferior *inf, void *arg)
  341. {
  342.   PyObject *list = arg;
  343.   PyObject *inferior = inferior_to_inferior_object (inf);
  344.   int success = 0;

  345.   if (! inferior)
  346.     return 0;

  347.   success = PyList_Append (list, inferior);
  348.   Py_DECREF (inferior);

  349.   if (success)
  350.     return 1;

  351.   return 0;
  352. }

  353. /* Implementation of gdb.inferiors () -> (gdb.Inferior, ...).
  354.    Returns a tuple of all inferiors.  */
  355. PyObject *
  356. gdbpy_inferiors (PyObject *unused, PyObject *unused2)
  357. {
  358.   PyObject *list, *tuple;

  359.   list = PyList_New (0);
  360.   if (!list)
  361.     return NULL;

  362.   if (iterate_over_inferiors (build_inferior_list, list))
  363.     {
  364.       Py_DECREF (list);
  365.       return NULL;
  366.     }

  367.   tuple = PyList_AsTuple (list);
  368.   Py_DECREF (list);

  369.   return tuple;
  370. }

  371. /* Membuf and memory manipulation.  */

  372. /* Implementation of Inferior.read_memory (address, length).
  373.    Returns a Python buffer object with LENGTH bytes of the inferior's
  374.    memory at ADDRESS.  Both arguments are integers.  Returns NULL on error,
  375.    with a python exception set.  */
  376. static PyObject *
  377. infpy_read_memory (PyObject *self, PyObject *args, PyObject *kw)
  378. {
  379.   CORE_ADDR addr, length;
  380.   void *buffer = NULL;
  381.   membuf_object *membuf_obj;
  382.   PyObject *addr_obj, *length_obj, *result;
  383.   volatile struct gdb_exception except;
  384.   static char *keywords[] = { "address", "length", NULL };

  385.   if (! PyArg_ParseTupleAndKeywords (args, kw, "OO", keywords,
  386.                                      &addr_obj, &length_obj))
  387.     return NULL;

  388.   if (get_addr_from_python (addr_obj, &addr) < 0
  389.       || get_addr_from_python (length_obj, &length) < 0)
  390.     return NULL;

  391.   TRY_CATCH (except, RETURN_MASK_ALL)
  392.     {
  393.       buffer = xmalloc (length);

  394.       read_memory (addr, buffer, length);
  395.     }
  396.   if (except.reason < 0)
  397.     {
  398.       xfree (buffer);
  399.       GDB_PY_HANDLE_EXCEPTION (except);
  400.     }

  401.   membuf_obj = PyObject_New (membuf_object, &membuf_object_type);
  402.   if (membuf_obj == NULL)
  403.     {
  404.       xfree (buffer);
  405.       return NULL;
  406.     }

  407.   membuf_obj->buffer = buffer;
  408.   membuf_obj->addr = addr;
  409.   membuf_obj->length = length;

  410. #ifdef IS_PY3K
  411.   result = PyMemoryView_FromObject ((PyObject *) membuf_obj);
  412. #else
  413.   result = PyBuffer_FromReadWriteObject ((PyObject *) membuf_obj, 0,
  414.                                          Py_END_OF_BUFFER);
  415. #endif
  416.   Py_DECREF (membuf_obj);

  417.   return result;
  418. }

  419. /* Implementation of Inferior.write_memory (address, buffer [, length]).
  420.    Writes the contents of BUFFER (a Python object supporting the read
  421.    buffer protocol) at ADDRESS in the inferior's memory.  Write LENGTH
  422.    bytes from BUFFER, or its entire contents if the argument is not
  423.    provided.  The function returns nothing.  Returns NULL on error, with
  424.    a python exception set.  */
  425. static PyObject *
  426. infpy_write_memory (PyObject *self, PyObject *args, PyObject *kw)
  427. {
  428.   Py_ssize_t buf_len;
  429.   const char *buffer;
  430.   CORE_ADDR addr, length;
  431.   PyObject *addr_obj, *length_obj = NULL;
  432.   volatile struct gdb_exception except;
  433.   static char *keywords[] = { "address", "buffer", "length", NULL };
  434. #ifdef IS_PY3K
  435.   Py_buffer pybuf;

  436.   if (! PyArg_ParseTupleAndKeywords (args, kw, "Os*|O", keywords,
  437.                                      &addr_obj, &pybuf,
  438.                                      &length_obj))
  439.     return NULL;

  440.   buffer = pybuf.buf;
  441.   buf_len = pybuf.len;
  442. #else
  443.   if (! PyArg_ParseTupleAndKeywords (args, kw, "Os#|O", keywords,
  444.                                      &addr_obj, &buffer, &buf_len,
  445.                                      &length_obj))
  446.     return NULL;
  447. #endif

  448.   if (get_addr_from_python (addr_obj, &addr) < 0)
  449.     goto fail;

  450.   if (!length_obj)
  451.     length = buf_len;
  452.   else if (get_addr_from_python (length_obj, &length) < 0)
  453.     goto fail;

  454.   TRY_CATCH (except, RETURN_MASK_ALL)
  455.     {
  456.       write_memory_with_notification (addr, (gdb_byte *) buffer, length);
  457.     }
  458. #ifdef IS_PY3K
  459.   PyBuffer_Release (&pybuf);
  460. #endif
  461.   GDB_PY_HANDLE_EXCEPTION (except);

  462.   Py_RETURN_NONE;

  463. fail:
  464. #ifdef IS_PY3K
  465.   PyBuffer_Release (&pybuf);
  466. #endif
  467.   return NULL;
  468. }

  469. /* Destructor of Membuf objects.  */
  470. static void
  471. mbpy_dealloc (PyObject *self)
  472. {
  473.   xfree (((membuf_object *) self)->buffer);
  474.   Py_TYPE (self)->tp_free (self);
  475. }

  476. /* Return a description of the Membuf object.  */
  477. static PyObject *
  478. mbpy_str (PyObject *self)
  479. {
  480.   membuf_object *membuf_obj = (membuf_object *) self;

  481.   return PyString_FromFormat (_("Memory buffer for address %s, \
  482. which is %s bytes long."),
  483.                               paddress (python_gdbarch, membuf_obj->addr),
  484.                               pulongest (membuf_obj->length));
  485. }

  486. #ifdef IS_PY3K

  487. static int
  488. get_buffer (PyObject *self, Py_buffer *buf, int flags)
  489. {
  490.   membuf_object *membuf_obj = (membuf_object *) self;
  491.   int ret;

  492.   ret = PyBuffer_FillInfo (buf, self, membuf_obj->buffer,
  493.                            membuf_obj->length, 0,
  494.                            PyBUF_CONTIG);
  495.   buf->format = "c";

  496.   return ret;
  497. }

  498. #else

  499. static Py_ssize_t
  500. get_read_buffer (PyObject *self, Py_ssize_t segment, void **ptrptr)
  501. {
  502.   membuf_object *membuf_obj = (membuf_object *) self;

  503.   if (segment)
  504.     {
  505.       PyErr_SetString (PyExc_SystemError,
  506.                        _("The memory buffer supports only one segment."));
  507.       return -1;
  508.     }

  509.   *ptrptr = membuf_obj->buffer;

  510.   return membuf_obj->length;
  511. }

  512. static Py_ssize_t
  513. get_write_buffer (PyObject *self, Py_ssize_t segment, void **ptrptr)
  514. {
  515.   return get_read_buffer (self, segment, ptrptr);
  516. }

  517. static Py_ssize_t
  518. get_seg_count (PyObject *self, Py_ssize_t *lenp)
  519. {
  520.   if (lenp)
  521.     *lenp = ((membuf_object *) self)->length;

  522.   return 1;
  523. }

  524. static Py_ssize_t
  525. get_char_buffer (PyObject *self, Py_ssize_t segment, char **ptrptr)
  526. {
  527.   void *ptr = NULL;
  528.   Py_ssize_t ret;

  529.   ret = get_read_buffer (self, segment, &ptr);
  530.   *ptrptr = (char *) ptr;

  531.   return ret;
  532. }

  533. #endif        /* IS_PY3K */

  534. /* Implementation of
  535.    gdb.search_memory (address, length, pattern).  ADDRESS is the
  536.    address to start the search.  LENGTH specifies the scope of the
  537.    search from ADDRESS.  PATTERN is the pattern to search for (and
  538.    must be a Python object supporting the buffer protocol).
  539.    Returns a Python Long object holding the address where the pattern
  540.    was located, or if the pattern was not found, returns None.  Returns NULL
  541.    on error, with a python exception set.  */
  542. static PyObject *
  543. infpy_search_memory (PyObject *self, PyObject *args, PyObject *kw)
  544. {
  545.   CORE_ADDR start_addr, length;
  546.   static char *keywords[] = { "address", "length", "pattern", NULL };
  547.   PyObject *start_addr_obj, *length_obj;
  548.   volatile struct gdb_exception except;
  549.   Py_ssize_t pattern_size;
  550.   const void *buffer;
  551.   CORE_ADDR found_addr;
  552.   int found = 0;
  553. #ifdef IS_PY3K
  554.   Py_buffer pybuf;

  555.   if (! PyArg_ParseTupleAndKeywords (args, kw, "OOs*", keywords,
  556.                                      &start_addr_obj, &length_obj,
  557.                                      &pybuf))
  558.     return NULL;

  559.   buffer = pybuf.buf;
  560.   pattern_size = pybuf.len;
  561. #else
  562.   PyObject *pattern;

  563.   if (! PyArg_ParseTupleAndKeywords (args, kw, "OOO", keywords,
  564.                                       &start_addr_obj, &length_obj,
  565.                                      &pattern))
  566.      return NULL;

  567.   if (!PyObject_CheckReadBuffer (pattern))
  568.     {
  569.       PyErr_SetString (PyExc_RuntimeError,
  570.                        _("The pattern is not a Python buffer."));

  571.       return NULL;
  572.     }

  573.   if (PyObject_AsReadBuffer (pattern, &buffer, &pattern_size) == -1)
  574.     return NULL;
  575. #endif

  576.   if (get_addr_from_python (start_addr_obj, &start_addr) < 0)
  577.     goto fail;

  578.   if (get_addr_from_python (length_obj, &length) < 0)
  579.     goto fail;

  580.   if (!length)
  581.     {
  582.       PyErr_SetString (PyExc_ValueError,
  583.                        _("Search range is empty."));
  584.       goto fail;
  585.     }
  586.   /* Watch for overflows.  */
  587.   else if (length > CORE_ADDR_MAX
  588.            || (start_addr + length - 1) < start_addr)
  589.     {
  590.       PyErr_SetString (PyExc_ValueError,
  591.                        _("The search range is too large."));
  592.       goto fail;
  593.     }

  594.   TRY_CATCH (except, RETURN_MASK_ALL)
  595.     {
  596.       found = target_search_memory (start_addr, length,
  597.                                     buffer, pattern_size,
  598.                                     &found_addr);
  599.     }
  600. #ifdef IS_PY3K
  601.   PyBuffer_Release (&pybuf);
  602. #endif
  603.   GDB_PY_HANDLE_EXCEPTION (except);

  604.   if (found)
  605.     return PyLong_FromLong (found_addr);
  606.   else
  607.     Py_RETURN_NONE;

  608. fail:
  609. #ifdef IS_PY3K
  610.   PyBuffer_Release (&pybuf);
  611. #endif
  612.   return NULL;
  613. }

  614. /* Implementation of gdb.Inferior.is_valid (self) -> Boolean.
  615.    Returns True if this inferior object still exists in GDB.  */

  616. static PyObject *
  617. infpy_is_valid (PyObject *self, PyObject *args)
  618. {
  619.   inferior_object *inf = (inferior_object *) self;

  620.   if (! inf->inferior)
  621.     Py_RETURN_FALSE;

  622.   Py_RETURN_TRUE;
  623. }

  624. static void
  625. infpy_dealloc (PyObject *obj)
  626. {
  627.   inferior_object *inf_obj = (inferior_object *) obj;
  628.   struct inferior *inf = inf_obj->inferior;

  629.   if (! inf)
  630.     return;

  631.   set_inferior_data (inf, infpy_inf_data_key, NULL);
  632. }

  633. /* Clear the INFERIOR pointer in an Inferior object and clear the
  634.    thread list.  */
  635. static void
  636. py_free_inferior (struct inferior *inf, void *datum)
  637. {

  638.   struct cleanup *cleanup;
  639.   inferior_object *inf_obj = datum;
  640.   struct threadlist_entry *th_entry, *th_tmp;

  641.   if (!gdb_python_initialized)
  642.     return;

  643.   cleanup = ensure_python_env (python_gdbarch, python_language);

  644.   inf_obj->inferior = NULL;

  645.   /* Deallocate threads list.  */
  646.   for (th_entry = inf_obj->threads; th_entry != NULL;)
  647.     {
  648.       Py_DECREF (th_entry->thread_obj);

  649.       th_tmp = th_entry;
  650.       th_entry = th_entry->next;
  651.       xfree (th_tmp);
  652.     }

  653.   inf_obj->nthreads = 0;

  654.   Py_DECREF ((PyObject *) inf_obj);
  655.   do_cleanups (cleanup);
  656. }

  657. /* Implementation of gdb.selected_inferior() -> gdb.Inferior.
  658.    Returns the current inferior object.  */

  659. PyObject *
  660. gdbpy_selected_inferior (PyObject *self, PyObject *args)
  661. {
  662.   return inferior_to_inferior_object (current_inferior ());
  663. }

  664. int
  665. gdbpy_initialize_inferior (void)
  666. {
  667.   if (PyType_Ready (&inferior_object_type) < 0)
  668.     return -1;

  669.   if (gdb_pymodule_addobject (gdb_module, "Inferior",
  670.                               (PyObject *) &inferior_object_type) < 0)
  671.     return -1;

  672.   infpy_inf_data_key =
  673.     register_inferior_data_with_cleanup (NULL, py_free_inferior);

  674.   observer_attach_new_thread (add_thread_object);
  675.   observer_attach_thread_exit (delete_thread_object);
  676.   observer_attach_normal_stop (python_on_normal_stop);
  677.   observer_attach_target_resumed (python_on_resume);
  678.   observer_attach_inferior_call_pre (python_on_inferior_call_pre);
  679.   observer_attach_inferior_call_post (python_on_inferior_call_post);
  680.   observer_attach_memory_changed (python_on_memory_change);
  681.   observer_attach_register_changed (python_on_register_change);
  682.   observer_attach_inferior_exit (python_inferior_exit);
  683.   observer_attach_new_objfile (python_new_objfile);

  684.   membuf_object_type.tp_new = PyType_GenericNew;
  685.   if (PyType_Ready (&membuf_object_type) < 0)
  686.     return -1;

  687.   return gdb_pymodule_addobject (gdb_module, "Membuf", (PyObject *)
  688.                                  &membuf_object_type);
  689. }

  690. static PyGetSetDef inferior_object_getset[] =
  691. {
  692.   { "num", infpy_get_num, NULL, "ID of inferior, as assigned by GDB.", NULL },
  693.   { "pid", infpy_get_pid, NULL, "PID of inferior, as assigned by the OS.",
  694.     NULL },
  695.   { "was_attached", infpy_get_was_attached, NULL,
  696.     "True if the inferior was created using 'attach'.", NULL },
  697.   { NULL }
  698. };

  699. static PyMethodDef inferior_object_methods[] =
  700. {
  701.   { "is_valid", infpy_is_valid, METH_NOARGS,
  702.     "is_valid () -> Boolean.\n\
  703. Return true if this inferior is valid, false if not." },
  704.   { "threads", infpy_threads, METH_NOARGS,
  705.     "Return all the threads of this inferior." },
  706.   { "read_memory", (PyCFunction) infpy_read_memory,
  707.     METH_VARARGS | METH_KEYWORDS,
  708.     "read_memory (address, length) -> buffer\n\
  709. Return a buffer object for reading from the inferior's memory." },
  710.   { "write_memory", (PyCFunction) infpy_write_memory,
  711.     METH_VARARGS | METH_KEYWORDS,
  712.     "write_memory (address, buffer [, length])\n\
  713. Write the given buffer object to the inferior's memory." },
  714.   { "search_memory", (PyCFunction) infpy_search_memory,
  715.     METH_VARARGS | METH_KEYWORDS,
  716.     "search_memory (address, length, pattern) -> long\n\
  717. Return a long with the address of a match, or None." },
  718.   { NULL }
  719. };

  720. static PyTypeObject inferior_object_type =
  721. {
  722.   PyVarObject_HEAD_INIT (NULL, 0)
  723.   "gdb.Inferior",                  /* tp_name */
  724.   sizeof (inferior_object),          /* tp_basicsize */
  725.   0,                                  /* tp_itemsize */
  726.   infpy_dealloc,                  /* tp_dealloc */
  727.   0,                                  /* tp_print */
  728.   0,                                  /* tp_getattr */
  729.   0,                                  /* tp_setattr */
  730.   0,                                  /* tp_compare */
  731.   0,                                  /* tp_repr */
  732.   0,                                  /* tp_as_number */
  733.   0,                                  /* tp_as_sequence */
  734.   0,                                  /* tp_as_mapping */
  735.   0,                                  /* tp_hash  */
  736.   0,                                  /* tp_call */
  737.   0,                                  /* tp_str */
  738.   0,                                  /* tp_getattro */
  739.   0,                                  /* tp_setattro */
  740.   0,                                  /* tp_as_buffer */
  741.   Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_ITER/* tp_flags */
  742.   "GDB inferior object",          /* tp_doc */
  743.   0,                                  /* tp_traverse */
  744.   0,                                  /* tp_clear */
  745.   0,                                  /* tp_richcompare */
  746.   0,                                  /* tp_weaklistoffset */
  747.   0,                                  /* tp_iter */
  748.   0,                                  /* tp_iternext */
  749.   inferior_object_methods,          /* tp_methods */
  750.   0,                                  /* tp_members */
  751.   inferior_object_getset,          /* tp_getset */
  752.   0,                                  /* tp_base */
  753.   0,                                  /* tp_dict */
  754.   0,                                  /* tp_descr_get */
  755.   0,                                  /* tp_descr_set */
  756.   0,                                  /* tp_dictoffset */
  757.   0,                                  /* tp_init */
  758.   0                                  /* tp_alloc */
  759. };

  760. #ifdef IS_PY3K

  761. static PyBufferProcs buffer_procs =
  762. {
  763.   get_buffer
  764. };

  765. #else

  766. /* Python doesn't provide a decent way to get compatibility here.  */
  767. #if HAVE_LIBPYTHON2_4
  768. #define CHARBUFFERPROC_NAME getcharbufferproc
  769. #else
  770. #define CHARBUFFERPROC_NAME charbufferproc
  771. #endif

  772. static PyBufferProcs buffer_procs = {
  773.   get_read_buffer,
  774.   get_write_buffer,
  775.   get_seg_count,
  776.   /* The cast here works around a difference between Python 2.4 and
  777.      Python 2.5.  */
  778.   (CHARBUFFERPROC_NAME) get_char_buffer
  779. };
  780. #endif        /* IS_PY3K */

  781. static PyTypeObject membuf_object_type = {
  782.   PyVarObject_HEAD_INIT (NULL, 0)
  783.   "gdb.Membuf",                          /*tp_name*/
  784.   sizeof (membuf_object),          /*tp_basicsize*/
  785.   0,                                  /*tp_itemsize*/
  786.   mbpy_dealloc,                          /*tp_dealloc*/
  787.   0,                                  /*tp_print*/
  788.   0,                                  /*tp_getattr*/
  789.   0,                                  /*tp_setattr*/
  790.   0,                                  /*tp_compare*/
  791.   0,                                  /*tp_repr*/
  792.   0,                                  /*tp_as_number*/
  793.   0,                                  /*tp_as_sequence*/
  794.   0,                                  /*tp_as_mapping*/
  795.   0,                                  /*tp_hash */
  796.   0,                                  /*tp_call*/
  797.   mbpy_str,                          /*tp_str*/
  798.   0,                                  /*tp_getattro*/
  799.   0,                                  /*tp_setattro*/
  800.   &buffer_procs,                  /*tp_as_buffer*/
  801.   Py_TPFLAGS_DEFAULT,                  /*tp_flags*/
  802.   "GDB memory buffer object",           /*tp_doc*/
  803.   0,                                  /* tp_traverse */
  804.   0,                                  /* tp_clear */
  805.   0,                                  /* tp_richcompare */
  806.   0,                                  /* tp_weaklistoffset */
  807.   0,                                  /* tp_iter */
  808.   0,                                  /* tp_iternext */
  809.   0,                                  /* tp_methods */
  810.   0,                                  /* tp_members */
  811.   0,                                  /* tp_getset */
  812.   0,                                  /* tp_base */
  813.   0,                                  /* tp_dict */
  814.   0,                                  /* tp_descr_get */
  815.   0,                                  /* tp_descr_set */
  816.   0,                                  /* tp_dictoffset */
  817.   0,                                  /* tp_init */
  818.   0,                                  /* tp_alloc */
  819. };